aif-fix
Skill261 starsChanged 2 months agoBSD-3-ClauseView on GitHub
Fix a bug or problem. Supports fix-now or plan-first; no args executes FIX_PLAN.md. When a regression check is needed, reproduce first, then implement and rerun it. Adds logging and suggests extra coverage.
- Reads credentials
5 other projects use a version of this, 4 of them edited.
Adopted by
Most recently taken up by
- ainative-build/skillstheir own version, first seen Nov 1, 2026
- letuhao/lore-weaveedited, first seen Oct 17, 2026
- lee-to/ai-factoryedited, first seen Sep 22, 2026
- maister-dev/maisteredited, first seen May 27, 2026
- hightemp/go_computer_use_mcp_serveredited, first seen Mar 21, 2026
Used with
Projects with it also use aif-distillation and aif-reference.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
maister-devSkillaif-distillation
Distill books, documents, folders, or URLs into compact, practical Agent Skills. Use when source material should become either one reusable skill package or a split set of focused skills, each with a concise SKILL.md plus detailed references and examples.
Also in 3 projects that use this
maister-devSkillaif-reference
Create knowledge references from URLs, documents, or files for use by AI agents. Fetch, process, and store structured references in the configured references directory (default: .ai-factory/references/).
Also in 3 projects that use this
Other versions5 projects use a version of this.
Word for word · 0
None found.
Edited · 4
- lee-to/ai-factory★ 1.2k60% same
- letuhao/lore-weave★ 3588% same
- maister-dev/maister★ 1056% same
- hightemp/go_computer_use_mcp_server★ 227% same
Wrote their own version · 1
- ainative-build/skills★ 10same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository36 other files it gives its agents.
- AGENTS.mdAGENTS.md
- aif-architectureSkill
- aif-archiveSkill
- aif-best-practicesSkill
- aif-build-automationSkill
- aif-ciSkill
- aif-commitSkill
- aif-docsSkill
- aif-evolveSkill
- aif-exploreSkill
- aif-groundedSkill
- aif-implementSkill
- aif-improveSkill
- aif-loopSkill
- aif-planSkill
- aif-qa-checkSkill
- aif-qaSkill
- aif-reviewSkill
- aif-roadmapSkill
- aif-rules-checkSkill
- aif-rulesSkill
- aif-security-checklistSkill
- aif-skill-generatorSkill
- aifSkill
- aif-verifySkill
- golang-code-styleSkill
- golang-concurrencySkill
- golang-contextSkill
- golang-databaseSkill
- golang-design-patternsSkill
- golang-documentationSkill
- golang-error-handlingSkill
- golang-namingSkill
- golang-performanceSkill
- golang-securitySkill
- golang-testingSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
73 rules. 8 are common, 35 are distinctive, and 30 are very specific to this project.
8
Common
Most of the 5 edited versions we read keep these.
35
Distinctive
This author's own choices. Worth a look.
30
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 19
When a bug needs regression coverage, every workflow path (fix-now, plan-first, and existing-plan execution) follows this policy:
- Distinctive: line 25
Only after that, run related existing checks when practical and suggest broader coverage if useful.
- Distinctive: line 29
If no automated/executable check is available, document the narrowest manual/runtime reproduction and why no executable check exists.
- Very specific: line 31
If the pre-fix regression check passes unexpectedly, treat it as a reproduction mismatch: record the command/check, inputs, environment …
- Distinctive: line 33
Do not duplicate or weaken this policy in later workflow sections.
- Very specific: line 51
No interactive questions: Do not use AskUserQuestion.
- Very specific: line 62
CRITICAL: Always pass paused: true with every handoff_sync_status call except done.
- Very specific: line 64
When creating a new FIX_PLAN.md: if there is no existing annotation and no Handoff context, do not add the annotation.
- Very specific: line 68
FIRST: Read .ai-factory/config.yaml if it exists to resolve:
- Very specific: line 74
If config.yaml doesn't exist, use defaults:
- Very specific: line 92
If technical_terms_policy is not one of keep, translate, or mixed, treat it as keep.
- Very specific: line 94
All AskUserQuestion prompts, progress updates, fix summaries, test prompts, and next-step guidance MUST be written in ui_language.
- Common: line 106
Read the resolved fix plan file
- Very specific: line 108
If the parsed source is inside research_bundles_dir, require its sibling INDEX.md to contain <!-- aif:research-mode:ultra --> exactly once …
- Very specific: line 111
If found AND HANDOFF_MODE is NOT 1 (manual session): extract the task ID.
- Very specific: line 112
If found AND HANDOFF_MODE is 1: the Handoff coordinator handles sync — do nothing.
- Common: line 113
If NOT found: no linked Handoff task — skip all MCP sync for the rest of this session.
- Distinctive: line 118
Follow the plan sequentially, but preserve the canonical order: confirm the problem first, implement the fix, then rerun the same …
- Very specific: line 119
After the fix is fully applied and verified in Step 4, delete the resolved fix plan file only when it is the default fix plan path …
- Very specific: line 123
If the fix plan came from a custom paths.fix_plan value, an explicitly supplied custom plan path, or any non-default fix plan location, do …
- Very specific: line 137
THEN: Read .ai-factory/DESCRIPTION.md (use path from config) if it exists to understand:
- Distinctive: line 152
Treat them as project-level overrides for this skill's general instructions
- Very specific: line 153
When a skill-context rule conflicts with a general rule written in this SKILL.md,
- Very specific: line 155
When there is no conflict, apply both: general rules from SKILL.md + project rules from skill-context
- Distinctive: line 156
Do NOT ignore skill-context rules even if they seem to contradict this skill's defaults — they exist because the project's experience …
- Distinctive: line 163
Enforcement: After generating any output artifact, verify it against all skill-context rules.
- Distinctive: line 164
If any rule is violated — fix the output before presenting it to the user.
- Very specific: line 168
If .ai-factory/skill-context/aif-fix/SKILL.md does not exist and the resolved patches dir exists:
- Very specific: line 169
Use Glob to find *.md files in <resolved patches dir>
- Common: line 171
Read those selected patch files only
- Common: line 173
If skill-context exists, do not read all patches by default.
- Very specific: line 211
Handoff sync (manual mode only): If a Handoff task ID is known (from HANDOFF_TASK_ID or an existing annotation) AND HANDOFF_MODE is NOT 1, …
- Common: line 221
After agents return, synthesize findings to:
- Very specific: line 229
Write the fix plan in artifact_language.
- Very specific: line 282
Use the normalization and stdin hashing rules from Step 1.1 when filling SHA256:.
- Very specific: line 296
Handoff sync (manual mode only): If a Handoff task ID is known AND HANDOFF_MODE is NOT 1, call handoff_push_plan with { taskId: <id>, …
- Very specific: line 302
Handoff sync (manual mode, "Fix now" path only): If a Handoff task ID is known AND HANDOFF_MODE is NOT 1, call handoff_sync_status with
- Common: line 334
Fallback: If Task tool is unavailable, investigate directly:
- Common: line 337
Read the code around the issue
- Common: line 339
Check for similar patterns elsewhere
- Distinctive: line 376
If it doesn't work, logs help debug further
- Distinctive: line 381
Check the code compiles/runs
- Distinctive: line 382
If Step 2.5 created, identified, or documented a regression check, rerun or revisit the same check and confirm the fixed behavior
- Distinctive: line 383
Verify the logic is correct
- Distinctive: line 384
Ensure no regressions introduced
- Distinctive: line 385
When practical, run the closest existing related test suite after the regression check passes
- Very specific: line 390
Call handoff_push_plan with { taskId: <id>, planContent: <fix summary or updated plan> }.
- Very specific: line 391
If HANDOFF_SKIP_REVIEW is 1: call handoff_sync_status with { taskId: <id>, newStatus: "done", sourceTimestamp: "<current UTC time in ISO …
- Distinctive: line 437
Create the test file in the appropriate test directory (follow project conventions)
- Distinctive: line 439
Run the test to verify it passes
- Very specific: line 449
Log prefix: Use [FIX] or [FIX:<issue-id>] for easy filtering
- Very specific: line 453
Configurable: Use LOG_LEVEL if available
- Distinctive: line 477
Search for UserProfile component/function
- Distinctive: line 479
Add a regression check for the null user case and confirm it fails
- Distinctive: line 480
Add null check with logging
- Distinctive: line 492
Add or identify an integration regression check for the authenticated user case and confirm it fails
- Distinctive: line 503
Check regex or validation library usage
- Distinctive: line 504
Add a unit regression test for the invalid email case and confirm it fails
- Distinctive: line 506
Add logging for validation failures
- Distinctive: line 511
Check the fix plan first: - Always check the resolved fix plan path before anything else
- Distinctive: line 512
Plan mode = plan only: - When user chooses "Plan first", create the plan and STOP.
- Very specific: line 513
Execute mode = follow the plan: - When the resolved fix plan exists, follow it step by step.
- Distinctive: line 514
NO reports: - Don't create summary documents (patches are learning artifacts, not reports)
- Distinctive: line 515
ALWAYS log: - Every fix must have logging for feedback
- Distinctive: line 516
Regression-first when checks are needed: - When a bug needs regression coverage, follow the Canonical Regression-First Policy before …
- Distinctive: line 520
Minimal changes: - Don't refactor unrelated code
- Distinctive: line 521
One fix at a time: - Don't scope creep
- Distinctive: line 522
Clean up: - Delete the resolved fix plan file after successful fix execution
- Very specific: line 524
Logging scope: - Keep [FIX] logging requirements for fixes.
- Distinctive: line 550
Create directory if it doesn't exist:
- Distinctive: line 556
Create a patch file with the current timestamp as filename.
- Very specific: line 561
Write the patch artifact in artifact_language.
- Distinctive: line 642
This is NOT optional: Every fix generates a patch.
“Common” is measured: kept by at least 6 in 10 of the 5 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Fix - Bug Fix Workflow
Fix a specific bug or problem in the codebase. Supports two modes: immediate fix or plan-first approach. The default workflow is regression-first whenever a regression check is needed: reproduce the problem, confirm the reported behavior, implement the fix, then verify the same check passes.
Workflow
Canonical Regression-First Policy
A regression check is the smallest useful test, command, fixture, API call, browser scenario, script, or documented manual/runtime reproduction that proves the reported bug or validates the expected behavior.
When a bug needs regression coverage, every workflow path (fix-now, plan-first, and existing-plan execution) follows this policy:
- Identify the minimal regression check that should reproduce the issue or encode the expected behavior.
- Execute the check before implementation and confirm it fails or reproduces the reported problem.
- Implement the smallest fix addressing the root cause.
- Re-run the exact same check and confirm it passes.
- Only after that, run related existing checks when practical and suggest broader coverage if useful.
Fallback behavior:
- If no automated/executable check is available, document the narrowest manual/runtime reproduction and why no executable check exists. Treat that documented reproduction as the regression check for Step 4 when it can be rerun.
- If no useful regression check exists at all, record the reason before implementation. In
HANDOFF_MODE=1, continue only when investigation found a plausible root cause that can be fixed safely; otherwise report the task as blocked/unreproducible and stop without changing implementation code. In manual mode, ask whether to proceed with the likely fix, adjust reproduction, or investigate further. - If the pre-fix regression check passes unexpectedly, treat it as a reproduction mismatch: record the command/check, inputs, environment assumptions, and observed result. Then use the same
HANDOFF_MODE=1or manual-mode fallback above.
Do not duplicate or weaken this policy in later workflow sections. Later steps should reference this section and add only local execution details.
Step 0 (pre): Detect Handoff Mode
Determine Handoff mode, task ID, and skip-review flag. If the caller passed HANDOFF_MODE, HANDOFF_TASK_ID, and HANDOFF_SKIP_REVIEW as explicit text in the prompt, use those values. Otherwise, use the Bash tool:
Bash: printenv HANDOFF_MODE || true
Bash: printenv HANDOFF_TASK_ID || true
Bash: printenv HANDOFF_SKIP_REVIEW || trueThen check HANDOFF_MODE:
When HANDOFF_MODE is 1 (autonomous Handoff agent)
The Handoff coordinator already manages status transitions and DB writes directly. Do NOT call MCP tools. Instead:
- No interactive questions: Do not use
AskUserQuestion. If$ARGUMENTScontains--plan-first, use "Plan first" mode. Otherwise default to "Fix now" mode. When a regression check is needed for the bug, include regression-first handling and logging. - Plan annotation (MANDATORY): If
HANDOFF_TASK_IDis non-empty, you MUST insert<!-- handoff:task:<HANDOFF_TASK_ID> -->as the very first line of the fix plan file, before the title. Omitting this annotation when HANDOFF_TASK_ID is set is a bug — verify before completing. This applies to both Step 1.1 (creating new plan) and any plan rewrite.
When HANDOFF_MODE is NOT 1 (manual Claude Code session)
Handoff sync is handled inline — see Step 0.1 (after reading the fix plan file) for the task ID extraction and MCP sync trigger. The sync points are:
- Plan first (Step 1.1):
"planning"→"plan_ready"(after save) - Fix now (Step 2→5):
"implementing"(Step 2 entry) →"done"ifHANDOFF_SKIP_REVIEW=1, else"review"(Step 5) - Execute existing plan (Step 0.1→5):
"implementing"(Step 0.1) →"done"ifHANDOFF_SKIP_REVIEW=1, else"review"(Step 5)
CRITICAL: Always pass paused: true with every handoff_sync_status call except done.
When creating a new FIX_PLAN.md: if there is no existing annotation and no Handoff context, do not add the annotation.
Step 0: Load Config and Resolve Paths
FIRST: Read .ai-factory/config.yaml if it exists to resolve:
- Paths:
paths.description,paths.architecture,paths.rules_file,paths.rules,paths.research,paths.fix_plan, andpaths.patches; deriveresearch_bundles_dir = <parent directory of paths.research>/research/ - Language:
language.uifor prompts and summaries,language.artifactsforFIX_PLAN.mdand patch artifacts, andlanguage.technical_termsfor human-readable technical terminology in artifacts - Rules:
rules.baseplus any namedrules.<area>entries
If config.yaml doesn't exist, use defaults:
- DESCRIPTION.md:
.ai-factory/DESCRIPTION.md - ARCHITECTURE.md:
.ai-factory/ARCHITECTURE.md - RULES.md:
.ai-factory/RULES.md - rules/:
.ai-factory/rules/ - RESEARCH.md:
.ai-factory/RESEARCH.md - FIX_PLAN.md:
.ai-factory/FIX_PLAN.md - patches/:
.ai-factory/patches/ ui_language:enartifact_language:entechnical_terms_policy:keep
Resolved language values:
ui_language = language.ui || "en"artifact_language = language.artifacts || language.ui || "en"technical_terms_policy = language.technical_terms || "keep"
If technical_terms_policy is not one of keep, translate, or mixed, treat it as keep. Legacy values such as english also behave like keep.
All AskUserQuestion prompts, progress updates, fix summaries, test prompts, and next-step guidance MUST be written in ui_language.
Generated FIX_PLAN.md and self-improvement patch files under paths.patches MUST be written in artifact_language.
Templates and examples define structure, not fixed English output. If artifact_language is not en, translate human-readable headings, labels, analysis text, fix checklist entries, risks, prevention notes, and patch prose before saving. Preserve Handoff annotations, markdown structure, checkbox syntax, paths, commands, config keys, code identifiers, package names, API names, raw error messages, code snippets, log prefixes such as [FIX], and patch tags unchanged. Keep ## Research Context, Source:, Active Summary, Updated:, and SHA256: exact because downstream research drift checks parse them as compatibility tokens. Apply technical_terms_policy to other human-readable terminology.
Step 0.1: Check for Existing Fix Plan
BEFORE anything else after config resolution, check the resolved fix plan path (default: .ai-factory/FIX_PLAN.md).
If the file EXISTS:
- Read the resolved fix plan file
- If the fix plan contains
## Research Context, treat its embedded copy as the committed requirements snapshot. Parse the firstSource:/Reference:line with canonical^(?:Source|Reference):\s+\x60([^\x60]+)\x60\s+\(syntax; for older bare-path lines, fall back to^(?:Source|Reference):\s+(.+?)\s+\(. Fall back to configuredpaths.researchonly when neither form identifies a usable path. - If the parsed source is inside
research_bundles_dir, require its siblingINDEX.mdto contain<!-- aif:research-mode:ultra -->exactly once and link thatRESEARCH.mdfrom## Artifact Index; otherwise emitWARN [research-drift]. Valid sibling C4/ADR/dependency artifacts are rationale only. - When
SHA256:is present, extract the current source text strictly between<!-- aif:active-summary:start -->and<!-- aif:active-summary:end -->, remove HTML comment blocks, preserve line order and leading whitespace, trim trailing spaces from every line, use LF endings, and end with one newline. Hash through stdin withshasum -a 256orsha256sum; the digest is authoritative. UseUpdated:only as a legacy fallback whenSHA256:is absent. A missing/invalid source or revision mismatch emitsWARN [research-drift]; execute against the embedded Research Context unless the user explicitly requests a rebase. - Immediately check the first line for
<!-- handoff:task:<uuid> -->:- If found AND
HANDOFF_MODEis NOT1(manual session): extract the task ID. Callhandoff_sync_statuswith{ taskId: <extracted-id>, newStatus: "implementing", sourceTimestamp: "<current UTC time in ISO 8601 format>", direction: "aif_to_handoff", paused: true }. (Status is"implementing"because we are executing an existing plan, not creating one.) - If found AND
HANDOFF_MODEis1: the Handoff coordinator handles sync — do nothing. - If NOT found: no linked Handoff task — skip all MCP sync for the rest of this session.
- If found AND
- Inform the user: "Found existing fix plan. Executing fix based on the plan."
- Skip Step 1 (problem intake/mode choice), but still run Step 0.2 to load context
- Then continue to Step 2: Investigate the Codebase, using the plan as your guide
- Apply the Canonical Regression-First Policy before changing implementation code when a regression check is needed for the bug, even if the existing plan did not include that policy
- Follow the plan sequentially, but preserve the canonical order: confirm the problem first, implement the fix, then rerun the same regression check
- After the fix is fully applied and verified in Step 4, delete the resolved fix plan file only when it is the default fix plan path
.ai-factory/FIX_PLAN.md:rm .ai-factory/FIX_PLAN.md - If the fix plan came from a custom
paths.fix_planvalue, an explicitly supplied custom plan path, or any non-default fix plan location, do not delete it. Leave it in place and mention in the final summary that the custom fix plan was preserved. - Continue to Step 5 (Additional Test Coverage) and Step 6 (Patch)
If the file DOES NOT exist AND $ARGUMENTS is empty:
- Tell the user: "No fix plan found and no problem description provided. Please either provide a bug description (
/aif-fix <description>) or create a fix plan first." - STOP.
If the file DOES NOT exist AND $ARGUMENTS is provided:
- Continue to Step 0.2 below.
Step 0.2: Load Project Context & Past Experience
THEN: Read .ai-factory/DESCRIPTION.md (use path from config) if it exists to understand:
- Tech stack (language, framework, database)
- Project architecture
- Coding conventions
Also read .ai-factory/ARCHITECTURE.md (use path from config), the resolved RULES.md path, and the configured rules hierarchy when present to avoid fixes that violate project structure or local conventions.
Read .ai-factory/skill-context/aif-fix/SKILL.md — MANDATORY if the file exists.
This file contains project-specific rules accumulated by /aif-evolve from patches,
codebase conventions, and tech-stack analysis. These rules are tailored to the current project.
How to apply skill-context rules:
- Treat them as project-level overrides for this skill's general instructions
- When a skill-context rule conflicts with a general rule written in this SKILL.md, the skill-context rule wins (more specific context takes priority — same principle as nested CLAUDE.md files)
- When there is no conflict, apply both: general rules from SKILL.md + project rules from skill-context
- Do NOT ignore skill-context rules even if they seem to contradict this skill's defaults — they exist because the project's experience proved the default insufficient
- CRITICAL: skill-context rules apply to ALL outputs of this skill — including the FIX_PLAN.md template and patch files. The FIX_PLAN.md template in Step 1.1 is a base structure. If a skill-context rule says "steps MUST include X" or "plan MUST have section Y" — you MUST augment the template accordingly. Generating a FIX_PLAN.md or patch that violates skill-context rules is a bug.
Enforcement: After generating any output artifact, verify it against all skill-context rules. If any rule is violated — fix the output before presenting it to the user.
Patch fallback (limited, only when skill-context is missing):
- If
.ai-factory/skill-context/aif-fix/SKILL.mddoes not exist and the resolved patches dir exists:- Use
Globto find*.mdfiles in<resolved patches dir> - Sort patch filenames ascending (lexical), then select the last 10 (or fewer if less exist)
- Read those selected patch files only
- Prioritize recurring Root Cause and Prevention patterns
- Use
- If skill-context exists, do not read all patches by default.
- Optionally inspect a small, targeted subset of recent patches when tags/files clearly match the current bug.
Step 1: Understand the Problem & Choose Mode
From $ARGUMENTS, identify:
- Error message or unexpected behavior
- Where it occurs (file, function, endpoint)
- Steps to reproduce (if provided)
If unclear, ask:
To fix this effectively, I need more context:
1. What is the expected behavior?
2. What actually happens?
3. Can you share the error message/stack trace?
4. When did this start happening?After understanding the problem, ask the user to choose a mode using AskUserQuestion:
Question: "How would you like to proceed with the fix?"
Options:
- Fix now — Investigate and apply the fix immediately
- Plan first — Create a fix plan for review, then fix later
Based on choice:
- "Plan first" → Proceed to Step 1.1: Create Fix Plan
- "Fix now" → Skip Step 1.1, proceed directly to Step 2: Investigate the Codebase
Step 1.1: Create Fix Plan
Handoff sync (manual mode only): If a Handoff task ID is known (from HANDOFF_TASK_ID or an existing annotation) AND HANDOFF_MODE is NOT 1, call handoff_sync_status with { taskId: <id>, newStatus: "planning", sourceTimestamp: "<current UTC time in ISO 8601 format>", direction: "aif_to_handoff", paused: true }.
Investigate the codebase enough to understand the problem and create a plan.
Use the same parallel exploration approach as Step 2 — launch Explore agents to investigate the problem area, related code, and past patterns simultaneously.
If the resolved research path exists, read it before creating the fix plan. Also check direct child bundles under research_bundles_dir, but recognize one as active only when INDEX.md contains <!-- aif:research-mode:ultra --> exactly once, declares Status: active, and links its RESEARCH.md from ## Artifact Index. Select at most one clearly bug-relevant source: explicit concrete path, then exact slug, normalized Topic:, or unique semantic match, then the relevant legacy file; never use recency. When the selected Active Summary influences the planned fix, copy it into ## Research Context and include Source: `<selected research path>` (Active Summary, Updated: <research Updated timestamp>, SHA256: <sha256 of copied Active Summary>). If research is unrelated, omit the section.
When adding ## Research Context to a fix plan, use the same normalization algorithm as the drift check. Calculate the digest without a temporary repository artifact: feed the normalized text through stdin / inline shell input to shasum -a 256; if unavailable, use sha256sum. Use the first output field as SHA256:.
After agents return, synthesize findings to:
- Identify the root cause (or most likely candidates)
- Map affected files and functions
- Assess impact scope
Then create the resolved fix plan file (default: .ai-factory/FIX_PLAN.md).
Write the fix plan in artifact_language. The template below is the required structure only; translate human-readable headings, labels, and prose before saving when artifact_language is not en, while preserving stable technical tokens from Step 0.
Before writing: If HANDOFF_MODE is 1 and HANDOFF_TASK_ID is non-empty, the very first line of the file MUST be <!-- handoff:task:<HANDOFF_TASK_ID> --> followed by a blank line, then the plan content below. If in manual mode and a task ID was extracted from an existing annotation, preserve it.
Structure:
# Fix Plan: [Brief title]
**Problem:** [What's broken — from user's description]
**Created:** YYYY-MM-DD HH:mm
## Analysis
What was found during investigation:
- Root cause (or suspected root cause)
- Affected files and functions
- Impact scope
## Fix Checklist
Checklist entries for implementing the fix:
1. [ ] Apply the Canonical Regression-First Policy: add or identify the minimal regression check, or record why no useful check exists
2. [ ] Run the regression check and confirm it reproduces the reported problem, or record the fallback outcome from the policy
3. [ ] Implement the smallest fix for the root cause
4. [ ] Rerun the same regression check and confirm it passes when a rerunnable check exists
5. [ ] Run the closest related existing checks when practical
## Files to Modify
- `path/to/file.ts` — what changes are needed
- `path/to/another.ts` — what changes are needed
## Risks & Considerations
- Potential side effects
- Things to verify after the fix
- Edge cases to watch for
## Test Coverage
- Minimal regression check to confirm the bug before implementation
- Command/check to run before and after the fix
- Additional edge cases worth covering after the regression check passes
## Research Context (optional)
Include only when this fix plan is based on `RESEARCH.md`.
Source: `<selected research path>` (Active Summary, Updated: YYYY-MM-DD HH:MM, SHA256: <active-summary-sha256>)Use the normalization and stdin hashing rules from Step 1.1 when filling SHA256:.
After creating the plan, output:
## Fix Plan Created ✅
Plan saved to the resolved fix plan path.
Review the plan and when you're ready to execute, run:
/aif-fixHandoff sync (manual mode only): If a Handoff task ID is known AND HANDOFF_MODE is NOT 1, call handoff_push_plan with { taskId: <id>, planContent: <full fix plan text> }, then handoff_sync_status with { taskId: <id>, newStatus: "plan_ready", sourceTimestamp: "<current UTC time in ISO 8601 format>", direction: "aif_to_handoff", paused: true }.
STOP here. Do NOT apply the fix.
Step 2: Investigate the Codebase
Handoff sync (manual mode, "Fix now" path only): If a Handoff task ID is known AND HANDOFF_MODE is NOT 1, call handoff_sync_status with { taskId: <id>, newStatus: "implementing", sourceTimestamp: "<current UTC time in ISO 8601 format>", direction: "aif_to_handoff", paused: true }.
Use Task tool with subagent_type: Explore to investigate the problem in parallel. This keeps the main context clean and allows simultaneous investigation of multiple angles.
Launch 2-3 Explore agents simultaneously:
Agent 1 — Locate the problem area:
Task(subagent_type: Explore, model: sonnet, prompt:
"Find code related to [error location / affected functionality].
Read the relevant functions, trace the data flow.
Thoroughness: medium.")
Agent 2 — Related code & side effects:
Task(subagent_type: Explore, model: sonnet, prompt:
"Find all callers/consumers of [affected function/module].
Identify what else might break or be affected.
Thoroughness: medium.")
Agent 3 — Similar past patterns (if patches exist):
Task(subagent_type: Explore, model: sonnet, prompt:
"Search for similar error patterns or related fixes in the codebase.
Check git log for recent changes to [affected files].
Thoroughness: quick.")After agents return, synthesize findings to identify:
- The root cause (not just symptoms)
- Related code that might be affected
- Existing error handling
Fallback: If Task tool is unavailable, investigate directly:
- Find relevant files using Glob/Grep
- Read the code around the issue
- Trace the data flow
- Check for similar patterns elsewhere
Step 2.5: Capture a Regression Check
Apply the Canonical Regression-First Policy before changing implementation code. Prefer a regression check for behavior bugs, parsing/validation bugs, API/data bugs, crashes, and regressions. If the change is a non-bug cleanup, purely static correction, or investigation-only request, record why the policy does not apply and continue with the normal fix workflow.
Anti-gaming rule: Do not tailor the test to the implementation you plan to write. The test must describe the externally expected behavior or the reported failure condition. If the test passes before any fix, either the reproduction is wrong, the bug is stale, or the environment differs; handle that mismatch through the fallback behavior in the Canonical Regression-First Policy before changing implementation code.
Record the selected regression check, pre-fix result, and any fallback decision in your working notes so Step 4 can rerun or revisit the same check after the fix.
Step 3: Implement the Fix
Apply the fix with logging:
// ✅ REQUIRED: Add logging around the fix
console.log("[FIX] Processing user input", { userId, input });
try {
// The actual fix
const result = fixedLogic(input);
console.log("[FIX] Success", { userId, result });
return result;
} catch (error) {
console.error("[FIX] Error in fixedLogic", {
userId,
input,
error: error.message,
stack: error.stack,
});
throw error;
}Logging is MANDATORY because:
- User needs to verify the fix works
- If it doesn't work, logs help debug further
- Feedback loop: user provides logs → we iterate
Step 4: Verify the Fix
- Check the code compiles/runs
- If Step 2.5 created, identified, or documented a regression check, rerun or revisit the same check and confirm the fixed behavior
- Verify the logic is correct
- Ensure no regressions introduced
- When practical, run the closest existing related test suite after the regression check passes
Step 5: Suggest Additional Test Coverage
Handoff sync (manual mode ONLY — skip entirely when HANDOFF_MODE is 1): If a Handoff task ID is known AND HANDOFF_MODE is NOT 1:
- Call
handoff_push_planwith{ taskId: <id>, planContent: <fix summary or updated plan> }. - If
HANDOFF_SKIP_REVIEWis1: callhandoff_sync_statuswith{ taskId: <id>, newStatus: "done", sourceTimestamp: "<current UTC time in ISO 8601 format>", direction: "aif_to_handoff", paused: false }. - Otherwise: call
handoff_sync_statuswith{ taskId: <id>, newStatus: "review", sourceTimestamp: "<current UTC time in ISO 8601 format>", direction: "aif_to_handoff", paused: true }.
ALWAYS suggest additional test coverage:
The Step 5 and After Fixing output templates define structure only. Render all human-readable text in these user-facing responses in ui_language. Preserve code snippets, commands, file paths, line references, log prefixes such as [FIX], and AskUserQuestion option structure unchanged.
## Fix Applied ✅
The issue was: [brief explanation]
Fixed by: [what was changed]
### Logging Added
The fix includes logging with prefix `[FIX]`.
Please test and share any logs if issues persist.
### Recommended: Add More Test Coverage
If a regression check was created or identified in Step 2.5, this bug is now covered. Consider adding broader coverage to prevent nearby regressions:
\`\`\`typescript
describe('functionName', () => {
it('should handle [the edge case that caused the bug]', () => {
// Arrange
const input = /* the problematic input */;
// Act
const result = functionName(input);
// Assert
expect(result).toBe(/* expected */);
});
});
\`\`\`
AskUserQuestion: Would you like me to create the additional test coverage?
Options:
1. Yes, create the test
2. No, skip for nowHandling the user's response:
- If "Yes, create the test":
- Create the test file in the appropriate test directory (follow project conventions)
- Include the suggested additional test case and related edge cases
- Run the test to verify it passes
- Then proceed to Step 6: Create Self-Improvement Patch
- If "No, skip for now":
- Proceed directly to Step 6: Create Self-Improvement Patch
Logging Requirements
All fixes MUST include logging:
- Log prefix: Use
[FIX]or[FIX:<issue-id>]for easy filtering - Log inputs: What data was being processed
- Log success: Confirm the fix worked
- Log errors: Full context if something fails
- Configurable: Use LOG_LEVEL if available
// Pattern for fixes
const LOG_FIX = process.env.LOG_LEVEL === "debug" || process.env.DEBUG_FIX;
function fixedFunction(input) {
if (LOG_FIX) console.log("[FIX] Input:", input);
// ... fix logic ...
if (LOG_FIX) console.log("[FIX] Output:", result);
return result;
}Examples
Example 1: Null Reference Error
User: /aif-fix TypeError: Cannot read property 'name' of undefined in UserProfile
Actions:
- Search for UserProfile component/function
- Find where
.nameis accessed - Add a regression check for the null user case and confirm it fails
- Add null check with logging
- Rerun the same regression check and confirm it passes
Example 2: API Returns Wrong Data
User: /aif-fix /api/orders returns empty array for authenticated users
Actions:
- Find orders API endpoint
- Trace the query logic
- Find the bug (e.g., wrong filter)
- Add or identify an integration regression check for the authenticated user case and confirm it fails
- Fix with logging
- Rerun the same regression check and confirm it passes
Example 3: Form Validation Not Working
User: /aif-fix email validation accepts invalid emails
Actions:
- Find email validation logic
- Check regex or validation library usage
- Add a unit regression test for the invalid email case and confirm it fails
- Fix the validation
- Add logging for validation failures
- Rerun the same regression test and confirm it passes
Important Rules
- Check the fix plan first - Always check the resolved fix plan path before anything else
- Plan mode = plan only - When user chooses "Plan first", create the plan and STOP. Do NOT fix.
- Execute mode = follow the plan - When the resolved fix plan exists, follow it step by step. Delete it after verified execution only if it is the default
.ai-factory/FIX_PLAN.md; preserve custom/non-default fix plan files. - NO reports - Don't create summary documents (patches are learning artifacts, not reports)
- ALWAYS log - Every fix must have logging for feedback
- Regression-first when checks are needed - When a bug needs regression coverage, follow the Canonical Regression-First Policy before changing implementation code, confirm the problem when reproducible, then verify the same regression check after the fix
- Do not fit tests to implementation - Regression tests encode the reported/expected behavior, not the internal implementation shape
- ALWAYS suggest additional tests - Help prevent nearby regressions beyond the required regression check
- Root cause - Fix the actual problem, not symptoms
- Minimal changes - Don't refactor unrelated code
- One fix at a time - Don't scope creep
- Clean up - Delete the resolved fix plan file after successful fix execution
- Ownership boundary -
/aif-fixownspaths.fix_planandpaths.patches; treat.ai-factory/DESCRIPTION.md, roadmap, rules, and architecture context artifacts as read-only unless the user explicitly requests otherwise - Logging scope - Keep
[FIX]logging requirements for fixes; context-gate outputs in this command should useWARN/ERRORand must not change global logging policy in other skills
After Fixing
Use this output template in Step 5 (before the AskUserQuestion about additional tests):
## Fix Applied ✅
**Issue:** [what was broken]
**Cause:** [why it was broken]
**Fix:** [what was changed]
**Regression check:** [command/check and result, manual/runtime reproduction result, or "not available: <reason>"]
**Files modified:**
- path/to/file.ts (line X)
**Logging added:** Yes, prefix `[FIX]`Step 6: Create Self-Improvement Patch
ALWAYS create a patch after every fix. This builds a knowledge base for future fixes.
Create the patch:
Create directory if it doesn't exist:
mkdir -p <resolved patches dir>- Create a patch file with the current timestamp as filename.
Format:
YYYY-MM-DD-HH.mm.md(e.g.,2026-02-07-14.30.md) - Use this template:
Write the patch artifact in artifact_language. The template below is the required structure only; translate human-readable headings, labels, root-cause text, solution text, and prevention text before saving when artifact_language is not en, while preserving stable technical tokens from Step 0.
# [Brief title describing the fix]
**Date:** YYYY-MM-DD HH:mm
**Files:** list of modified files
**Severity:** low | medium | high | critical
## Problem
What was broken. How it manifested (error message, wrong behavior).
Be specific — include the actual error or symptom.
## Root Cause
WHY the problem occurred. This is the most valuable part.
Not "what was wrong" but "why it was wrong":
- Logic error? Why was the logic incorrect?
- Missing check? Why was it missing?
- Wrong assumption? What was assumed?
- Race condition? What sequence caused it?
## Solution
How the fix was implemented. Key code changes and reasoning.
Include the approach, not just "changed line X".
## Prevention
How to prevent this class of problems in the future:
- What pattern/practice should be followed?
- What should be checked during code review?
- What test would catch this?
## Tags
Space-separated tags for categorization, e.g.:
`#null-check` `#async` `#validation` `#typescript` `#api` `#database`Example patch:
# Null reference in UserProfile when user has no avatar
**Date:** 2026-02-07 14:30
**Files:** src/components/UserProfile.tsx
**Severity:** medium
## Problem
TypeError: Cannot read property 'url' of undefined when rendering
UserProfile for users without an uploaded avatar.
## Root Cause
The `user.avatar` field is optional in the database schema but the
component accessed `user.avatar.url` without a null check. This was
introduced in commit abc123 when avatar display was added — the
developer tested only with users that had avatars.
## Solution
Added optional chaining: `user.avatar?.url` with a fallback to a
default avatar URL. Also added a null check in the Avatar sub-component.
## Prevention
- Always check if database fields marked as `nullable` / `optional`
are handled with null checks in the UI layer
- Add test cases for "empty state" — user with minimal data
- Consider a lint rule for accessing nested optional properties
## Tags
`#null-check` `#react` `#optional-field` `#typescript`This is NOT optional. Every fix generates a patch. The patch is your learning.
Context Cleanup
Suggest the user to free up context space if needed: /clear (full reset) or /compact (compress history).
DO NOT:
- ❌ Apply a fix when user chose "Plan first" - only create the fix plan and stop
- ❌ Skip the fix-plan check at the start
- ❌ Leave the default
.ai-factory/FIX_PLAN.mdafter successful fix execution - ❌ Delete custom/non-default fix plan files after execution
- ❌ Generate reports or summaries (patches are NOT reports — they are learning artifacts)
- ❌ Refactor unrelated code
- ❌ Add features while fixing
- ❌ Skip logging
- ❌ Skip test suggestion
- ❌ Skip patch creation
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

