@taskless-app/swarm 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@taskless-app/swarm",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "description": "Local control plane for a fleet of AI coding agents (drones), coordinating through Taskless. The overmind runs the swarm.",
6
6
  "keywords": [
@@ -29,10 +29,11 @@
29
29
  },
30
30
  "files": [
31
31
  "dist",
32
- "docs/HERO.md"
32
+ "docs/HERO.md",
33
+ "roles"
33
34
  ],
34
35
  "dependencies": {
35
- "@hono/node-server": "^2.0.10",
36
+ "@hono/node-server": "^2.0.12",
36
37
  "@modelcontextprotocol/sdk": "^1.29.0",
37
38
  "execa": "^10.0.0",
38
39
  "zod": "3.25.76"
@@ -46,7 +47,7 @@
46
47
  "playwright-core": "1.49.1",
47
48
  "tsup": "^8.5.1",
48
49
  "tsx": "4.19.2",
49
- "typescript": "5.7.3",
50
+ "typescript": "7.0.2",
50
51
  "vitest": "2.1.8",
51
52
  "@taskless/swarm-core": "0.1.0"
52
53
  },
@@ -0,0 +1,31 @@
1
+ # Ролевые каталоги скиллов — то, что едет С РОЕМ
2
+
3
+ Каждый подкаталог — плагин Claude Code (`.claude-plugin/plugin.json` + `skills/`), который
4
+ демон подкладывает дрону флагом `--plugin-dir` по роли прогона (`run.kind`). Резолв — в
5
+ `src/launcher.ts`, `bundledRoleDir()`: относительно МОДУЛЯ, поэтому работает и из
6
+ `src/` в монорепо, и из `dist/` в опубликованном npm-пакете. Каталог попадает в пакет через
7
+ `files: ["dist", "docs/HERO.md", "roles"]`.
8
+
9
+ Сегодня здесь только `drone/`. У `hero/` каталога нет — устав `docs/HERO.md` ни на какой
10
+ скилл не ссылается; появится ролевой скилл для героя — завести той же формой.
11
+
12
+ ## Что сюда можно, а что нельзя (TASWM-315)
13
+
14
+ Признак один: **верно ли это для ЛЮБОГО проекта.**
15
+
16
+ - **Можно:** дисциплина работы дрона — незапушенное умирает с процессом; базовую ветку
17
+ вливать, а не ребейзить запушенную; ждать условие, а не `sleep`; что считать зелёным;
18
+ искать первопричину до фикса.
19
+ - **Нельзя:** как поднять стек, какие порты, какими командами гонять тесты, правила
20
+ вёрстки, «у нас postgres на :5433». Это знания о проекте — им место в `.claude/skills/`
21
+ самого репозитория, и владелец проекта правит их без релиза роя.
22
+
23
+ Причина запрета не вкусовая: после компактизации все скиллы делят **~25k токенов**, и
24
+ каждый скилл здесь тратит их у КАЖДОГО дрона в КАЖДОМ проекте. Набор держим маленьким, и
25
+ скилл обязан себя окупать. Тот же скилл не должен лежать одновременно здесь и в
26
+ `.claude/skills/` репозитория — иначе он доставляется дважды (инвариант закреплён тестом
27
+ `bundledRoleDir` в `src/launcher.test.ts`).
28
+
29
+ Чужие скиллы — только через аудит (trigger phrases, нет сетевого egress, нет рискованных
30
+ bundled-скриптов, совместимая лицензия): чек-лист и история в
31
+ [`../../../.claude/skills/README.md`](../../../.claude/skills/README.md).
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "swarm-drone",
3
+ "description": "Ролевой набор скиллов дрона роя, который едет С РОЕМ, а не с репозиторием: дисциплина, верная для любого проекта (сохраняться часто, вливать базовую ветку не ребейзом, ждать условие вместо sleep, что считать зелёным) плюс vendored systematic-debugging (MIT, superpowers 6.0.3). Подкладывается дрону через --plugin-dir из пакета @taskless-app/swarm, поэтому доступен и в чужом репозитории, где ни одного нашего файла нет. Знания о конкретном проекте (как поднять стек, как гонять тесты, UI-правила) сюда НЕ кладём — им место в .claude/skills/ самого репозитория.",
4
+ "version": "1.0.0",
5
+ "author": {
6
+ "name": "taskless swarm"
7
+ },
8
+ "license": "MIT"
9
+ }
@@ -0,0 +1,61 @@
1
+ ---
2
+ name: swarm-await-process
3
+ description: >-
4
+ Use when you need to wait for something to become ready or finish — a server to
5
+ boot, a port to open, a migration/build/test run to complete, a health check to
6
+ pass — or when tempted to `sleep N`, or to run a long command in the background
7
+ "to wait for it". "жди процесс", "poll for readiness", "condition polling".
8
+ Read this so you wait on a CONDITION (not a fixed sleep) and don't lose work by
9
+ backgrounding long runs.
10
+ license: see LICENSE of @taskless-app/swarm
11
+ metadata:
12
+ area: swarm-role
13
+ audience: swarm-drone
14
+ ---
15
+
16
+ # Wait on a condition, not on a sleep
17
+
18
+ A fixed `sleep 10` is wrong in both directions: too short and it flakes, too long
19
+ and it wastes the whole fleet's time. **Poll the actual condition** with a short
20
+ interval and a hard cap.
21
+
22
+ ## The pattern
23
+
24
+ ```bash
25
+ for i in $(seq 1 60); do
26
+ <check the condition> >/dev/null 2>&1 && { echo ready; break; }
27
+ [ "$i" = 60 ] && { echo "timed out" >&2; exit 1; }
28
+ sleep 1
29
+ done
30
+ ```
31
+
32
+ `<check the condition>` — то, что становится истинным, когда ожидаемое случилось:
33
+ `curl -sf <health-url>`, `pg_isready`, `nc -z localhost <port>`, наличие файла-
34
+ артефакта, `gh pr checks` в терминальном статусе. Хорошие dev-скрипты проекта уже
35
+ делают так — подсмотри у них condition и таймаут, прежде чем изобретать свой.
36
+
37
+ Poll intervals: ~0.5–1s for a local process/port, ~30s+ for a remote API (rate
38
+ limits). Always give the loop a hard ceiling so a stuck process fails loud
39
+ instead of hanging forever. `systematic-debugging` (vendored for drones as
40
+ `swarm-drone:systematic-debugging`) ships a `condition-based-waiting` reference
41
+ with the same principle for async code.
42
+
43
+ ## Headless drones: keep long work BLOCKING (don't background to wait)
44
+
45
+ This is the one that kills drones. Your session ends the moment you stop calling
46
+ tools — a process you launched with `&` / `run_in_background` **will not save you**
47
+ once you go quiet, and its output dies with the session.
48
+
49
+ - Run builds, test suites, and migrations as a **blocking foreground call** and
50
+ read the result. Don't fire-and-forget and "check later".
51
+ - If a run is genuinely long, split the task into parts and
52
+ **commit + push between them** (see [[swarm-save-often]]) — that's your
53
+ checkpoint, not a background process.
54
+ - Never `sleep` in the foreground just to pass time — either you have a condition
55
+ to poll, or you have nothing to wait for.
56
+
57
+ ## Why polling, not sleeping
58
+
59
+ Sleeps encode a guess about timing; conditions encode the truth. Startup time
60
+ varies with cold caches, machine load, and fork contention — a poll adapts, a
61
+ sleep gambles.
@@ -0,0 +1,68 @@
1
+ ---
2
+ name: swarm-merge-main
3
+ description: >-
4
+ ТОЛЬКО ДЛЯ ДРОНА РОЯ с открытым PR: твоя ветка конфликтует с базовой веткой или
5
+ отстала от неё — "merge conflict", "PR out of date with main", "конфликт с main",
6
+ "влить main". Читать ДО любого git merge/rebase на уже запушенной ветке, чтобы не
7
+ переписать историю и не затереть чужую работу.
8
+ license: see LICENSE of @taskless-app/swarm
9
+ metadata:
10
+ area: swarm-role
11
+ audience: swarm-drone
12
+ ---
13
+
14
+ # Integrate the base branch into yours (merge-in), don't rebase
15
+
16
+ Parallel drones share the base branch. When another PR merges and your branch falls
17
+ behind — or the host says your PR conflicts — **merge the base branch INTO your
18
+ branch**. Never rebase or force-push a branch that has an open PR.
19
+
20
+ Базовая ветка — та, в которую открыт (или будет открыт) твой PR: обычно ветка по
21
+ умолчанию (`main`/`master`), но устав мог явно назвать другую. Ниже `<base>` —
22
+ именно она; не подставляй `main` машинально.
23
+
24
+ ## The move
25
+
26
+ ```bash
27
+ git fetch origin
28
+ git merge origin/<base> # from inside your worktree, on your PR branch
29
+ ```
30
+
31
+ - **Clean merge** → `git push` (a normal fast-forwardable push). Done.
32
+ - **Conflicts** → resolve them (below), then:
33
+ ```bash
34
+ git add -A
35
+ git commit --no-edit # finish the merge commit, keep the default message
36
+ git push # normal push — NOT --force / --force-with-lease
37
+ ```
38
+
39
+ ## Resolving conflicts — keep both sides, don't touch the feature
40
+
41
+ The job is to reconcile the merge, not to redesign anything. Most conflicts are
42
+ mechanical:
43
+
44
+ - **Duplicate import / declaration** → keep one copy.
45
+ - **Two independent additions** in the same hunk → keep **both**.
46
+ - Delete nothing beyond the conflict markers; add no new features; do no refactor.
47
+
48
+ If a conflict is a real **logical / product ambiguity** — which of two values or
49
+ behaviours is correct, not just how to stitch text — that's a decision, not
50
+ mechanics. Don't guess: `ask(...)` the operator and wait. (For review-PRs the
51
+ swarm may also spin up a dedicated resolver drone.)
52
+
53
+ After resolving, re-run the project's checks and make sure they're green before
54
+ pushing — рецепт и критерий зелёности у каждого проекта свой, ищи их в скиллах
55
+ репозитория / README (см. [[swarm-verify-green]]). Красное после мержа значит, что
56
+ твоё разрешение конфликта неверно — чини разрешение, а не фичу.
57
+
58
+ ## Never rewrite a shared PR branch
59
+
60
+ `git rebase`, `git push --force`, `git push --force-with-lease` on a PR branch are
61
+ **forbidden** and gated by the swarm — they discard the reviewer's context and
62
+ can lose commits. The only integration path for an open PR is merge-in.
63
+
64
+ ## Prevention beats cure
65
+
66
+ Merge `origin/<base>` into long-running branches **early and often**, especially
67
+ right after another PR lands on files you also touch. A stale branch that sat for
68
+ hours is where the ugly conflicts come from. See also [[swarm-save-often]].
@@ -0,0 +1,68 @@
1
+ ---
2
+ name: swarm-save-often
3
+ description: >-
4
+ ТОЛЬКО ДЛЯ ДРОНА РОЯ, работающего в своём worktree на ветке-слаге: коммить и
5
+ пушить после каждого шага, чекпойнт перед долгим прогоном, слаг задачи и трейлер
6
+ дрона в каждом коммите. "незапушенное умирает с дроном", "checkpoint", "push
7
+ after every step". НЕ для оркестратора и не для обычной сессии — там пуш только
8
+ по просьбе владельца.
9
+ license: see LICENSE of @taskless-app/swarm
10
+ metadata:
11
+ area: swarm-role
12
+ audience: swarm-drone
13
+ ---
14
+
15
+ # Commit and push after every step — unpushed work dies with the drone
16
+
17
+ **Кому это адресовано.** Ты дрон роя: у тебя свой worktree, своя ветка по слагу
18
+ задачи, и тебя могут убить в любой момент. Если ты не дрон, а главная сессия —
19
+ этот скилл не про тебя: там действует обратное правило владельца, пушить только
20
+ когда попросили.
21
+
22
+ A drone can be killed at any moment (process kill, network drop, storm mode,
23
+ respawn). Only what's **pushed to `origin`** survives. Local commits and
24
+ uncommitted edits in the worktree are lost with the process — and a fresh respawn
25
+ starts from the last pushed state, so anything not pushed is redone or gone.
26
+
27
+ ## The rhythm
28
+
29
+ After each meaningful step (a file written, a fix made, a check greened):
30
+
31
+ ```bash
32
+ git add <the files you changed> # not `git add -A` blindly — see below
33
+ git commit -m "<type>(<scope>): <what> (<SLUG>)
34
+
35
+ Drone: <NAME> · run #<id>"
36
+ git push -u origin <your-branch> # branch == task slug
37
+ ```
38
+
39
+ Don't save the whole task for one final commit. Checkpoint often. If you're about
40
+ to start something long (a big build, an e2e run), commit + push **first** — the
41
+ push is your checkpoint, not a background process (see [[swarm-await-process]]).
42
+
43
+ ## Two things every commit needs
44
+
45
+ 1. **The task slug** (`<SLUG>`, e.g. `PRJ-42`) in the message — the tracker links
46
+ tasks to releases by parsing slugs from commits. No slug → the task shows up in
47
+ no release, even if its status changed. **Сначала убедись, что слаг
48
+ существует** (`get_task <SLUG>`): однажды несколько коммитов сослались на номер,
49
+ которого в проекте не было — счётчик стоял ниже, — и деплой зарегистрировался с
50
+ `linkedTasks: 0`.
51
+ 2. **The drone trailer** — a `Drone: <NAME> · run #<id>` line, so runs are greppable.
52
+
53
+ ## Stage deliberately (parallel-agent hygiene)
54
+
55
+ Prefer `git add <paths>` over `git add -A`. Multiple drones and tools can leave
56
+ stray files in a worktree; `-A` sweeps them into your commit. Stage what you
57
+ actually changed.
58
+
59
+ ## If you forgot the slug
60
+
61
+ Don't rewrite history on a pushed branch (see [[swarm-merge-main]]). Add an empty
62
+ marker commit instead:
63
+
64
+ ```bash
65
+ git commit --allow-empty -m "chore: link (<SLUG>)
66
+
67
+ Drone: <NAME> · run #<id>"
68
+ ```
@@ -0,0 +1,66 @@
1
+ ---
2
+ name: swarm-verify-green
3
+ description: >-
4
+ Use right before you claim a task is complete, open a PR, or call done — что
5
+ считать ЗЕЛЁНЫМ и каким доказательством это подтверждать, в любом проекте и на
6
+ любом стеке. "before done", "before PR", "is it finished", "готово?", "claim it
7
+ passes", "verification", "зелёное ли". Read this to know what counts as evidence;
8
+ КАКИЕ команды дают это зелёное в конкретном репозитории — в скиллах самого
9
+ репозитория.
10
+ license: see LICENSE of @taskless-app/swarm
11
+ metadata:
12
+ area: swarm-role
13
+ audience: swarm-drone
14
+ ---
15
+
16
+ # Verify before you say done — evidence, not intent
17
+
18
+ Claiming work is complete without running the check is not efficiency, it's a
19
+ guess. Этот скилл — универсальная половина гейта: он говорит, ЧТО считается
20
+ зелёным. Вторая половина живёт в репозитории проекта (его скиллы / README /
21
+ CONTRIBUTING): КАКИМИ командами это зелёное получить.
22
+
23
+ **Iron rule:** если ты не прогнал проверку в этой сессии, только что — ты не можешь
24
+ утверждать, что она проходит. «Should pass» / «seems fine» / «выглядит правильно» —
25
+ не доказательство.
26
+
27
+ ## Что считается зелёным
28
+
29
+ 1. **Проверка реально ИСПОЛНИЛАСЬ, а не отыгралась из кеша.** Сборочные системы с
30
+ кешем (turbo, nx, gradle, bazel, ccache, CI-кеши) отдают прошлый результат
31
+ мгновенно, если хеш входов не поменялся — и печатают это в выводе (`cache hit`,
32
+ `FULL TURBO`, `up-to-date`, `>>> replayed`). Зелёное из кеша не значит, что твой
33
+ код проверили: перепрогони принудительно (флаг вида `--force`/`--no-cache`) и
34
+ покажи строку, где видно реальный прогон.
35
+ 2. **Ноль упавших, а не «в основном зелёно».** Прочитай ИТОГ, не первые строки; не
36
+ экстраполируй с частичного прогона на весь сьют.
37
+ 3. **Проверка покрывает именно твоё изменение.** Зелёный сьют, который не касается
38
+ твоего кода, ничего о нём не говорит — найди (или прогони) то, что его касается.
39
+ 4. **Изменил видимое поведение — прогони его.** «Компилируется» это не «работает»:
40
+ пройди сценарий на живом приложении (встроенный скилл `/verify`, рецепт запуска —
41
+ в скиллах репозитория). Для UI — скрины mobile + desktop в задачу.
42
+ 5. **Доказательство приложено.** В сдаче — сам вывод (итоговая строка, exit 0,
43
+ наблюдаемое поведение), а не утверждение «проверил».
44
+
45
+ Нечего прогнать (в проекте нет проверок вовсе) — это факт о проекте, а не
46
+ разрешение молча сдать: скажи прямо, чем проверял вместо них. Инфраструктуру
47
+ проекта под гейт роя НЕ достраивай.
48
+
49
+ ## Red flags — stop and go get evidence
50
+
51
+ - «should», «probably», «seems to», «кажется, работает»
52
+ - Радость от готовности РАНЬШЕ прогона («Отлично, починил!») — сначала прогон
53
+ - Собираешься коммитить / пушить / открывать PR / звать `done()` без свежего прогона
54
+ - Веришь отчёту сабагента «успешно» вместо диффа в VCS и своей проверки
55
+ - Кеш-хит принял за прогон (см. пункт 1)
56
+ - Тест красный, и рука тянется подправить тест — это охота за баг-первопричиной,
57
+ а не правка: `swarm-drone:systematic-debugging` (root cause до фикса)
58
+ - Красное списал на «оно и до меня падало» — проверь это на базовой ветке, а не
59
+ предполагай
60
+
61
+ ## Почему это отдельный скилл
62
+
63
+ Универсальный мантра-скилл «всегда проверяй» сам по себе даёт мало — работает
64
+ пара: критерий доказательства (здесь) + конкретные команды проекта (в его
65
+ репозитории). Поэтому эта половина едет С РОЕМ в любой проект, а вторая остаётся у
66
+ владельца репозитория и переживает смену стека.
@@ -0,0 +1,296 @@
1
+ ---
2
+ name: systematic-debugging
3
+ description: Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes
4
+ ---
5
+
6
+ # Systematic Debugging
7
+
8
+ ## Overview
9
+
10
+ Random fixes waste time and create new bugs. Quick patches mask underlying issues.
11
+
12
+ **Core principle:** ALWAYS find root cause before attempting fixes. Symptom fixes are failure.
13
+
14
+ **Violating the letter of this process is violating the spirit of debugging.**
15
+
16
+ ## The Iron Law
17
+
18
+ ```
19
+ NO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST
20
+ ```
21
+
22
+ If you haven't completed Phase 1, you cannot propose fixes.
23
+
24
+ ## When to Use
25
+
26
+ Use for ANY technical issue:
27
+ - Test failures
28
+ - Bugs in production
29
+ - Unexpected behavior
30
+ - Performance problems
31
+ - Build failures
32
+ - Integration issues
33
+
34
+ **Use this ESPECIALLY when:**
35
+ - Under time pressure (emergencies make guessing tempting)
36
+ - "Just one quick fix" seems obvious
37
+ - You've already tried multiple fixes
38
+ - Previous fix didn't work
39
+ - You don't fully understand the issue
40
+
41
+ **Don't skip when:**
42
+ - Issue seems simple (simple bugs have root causes too)
43
+ - You're in a hurry (rushing guarantees rework)
44
+ - Manager wants it fixed NOW (systematic is faster than thrashing)
45
+
46
+ ## The Four Phases
47
+
48
+ You MUST complete each phase before proceeding to the next.
49
+
50
+ ### Phase 1: Root Cause Investigation
51
+
52
+ **BEFORE attempting ANY fix:**
53
+
54
+ 1. **Read Error Messages Carefully**
55
+ - Don't skip past errors or warnings
56
+ - They often contain the exact solution
57
+ - Read stack traces completely
58
+ - Note line numbers, file paths, error codes
59
+
60
+ 2. **Reproduce Consistently**
61
+ - Can you trigger it reliably?
62
+ - What are the exact steps?
63
+ - Does it happen every time?
64
+ - If not reproducible → gather more data, don't guess
65
+
66
+ 3. **Check Recent Changes**
67
+ - What changed that could cause this?
68
+ - Git diff, recent commits
69
+ - New dependencies, config changes
70
+ - Environmental differences
71
+
72
+ 4. **Gather Evidence in Multi-Component Systems**
73
+
74
+ **WHEN system has multiple components (CI → build → signing, API → service → database):**
75
+
76
+ **BEFORE proposing fixes, add diagnostic instrumentation:**
77
+ ```
78
+ For EACH component boundary:
79
+ - Log what data enters component
80
+ - Log what data exits component
81
+ - Verify environment/config propagation
82
+ - Check state at each layer
83
+
84
+ Run once to gather evidence showing WHERE it breaks
85
+ THEN analyze evidence to identify failing component
86
+ THEN investigate that specific component
87
+ ```
88
+
89
+ **Example (multi-layer system):**
90
+ ```bash
91
+ # Layer 1: Workflow
92
+ echo "=== Secrets available in workflow: ==="
93
+ echo "IDENTITY: ${IDENTITY:+SET}${IDENTITY:-UNSET}"
94
+
95
+ # Layer 2: Build script
96
+ echo "=== Env vars in build script: ==="
97
+ env | grep IDENTITY || echo "IDENTITY not in environment"
98
+
99
+ # Layer 3: Signing script
100
+ echo "=== Keychain state: ==="
101
+ security list-keychains
102
+ security find-identity -v
103
+
104
+ # Layer 4: Actual signing
105
+ codesign --sign "$IDENTITY" --verbose=4 "$APP"
106
+ ```
107
+
108
+ **This reveals:** Which layer fails (secrets → workflow ✓, workflow → build ✗)
109
+
110
+ 5. **Trace Data Flow**
111
+
112
+ **WHEN error is deep in call stack:**
113
+
114
+ See `root-cause-tracing.md` in this directory for the complete backward tracing technique.
115
+
116
+ **Quick version:**
117
+ - Where does bad value originate?
118
+ - What called this with bad value?
119
+ - Keep tracing up until you find the source
120
+ - Fix at source, not at symptom
121
+
122
+ ### Phase 2: Pattern Analysis
123
+
124
+ **Find the pattern before fixing:**
125
+
126
+ 1. **Find Working Examples**
127
+ - Locate similar working code in same codebase
128
+ - What works that's similar to what's broken?
129
+
130
+ 2. **Compare Against References**
131
+ - If implementing pattern, read reference implementation COMPLETELY
132
+ - Don't skim - read every line
133
+ - Understand the pattern fully before applying
134
+
135
+ 3. **Identify Differences**
136
+ - What's different between working and broken?
137
+ - List every difference, however small
138
+ - Don't assume "that can't matter"
139
+
140
+ 4. **Understand Dependencies**
141
+ - What other components does this need?
142
+ - What settings, config, environment?
143
+ - What assumptions does it make?
144
+
145
+ ### Phase 3: Hypothesis and Testing
146
+
147
+ **Scientific method:**
148
+
149
+ 1. **Form Single Hypothesis**
150
+ - State clearly: "I think X is the root cause because Y"
151
+ - Write it down
152
+ - Be specific, not vague
153
+
154
+ 2. **Test Minimally**
155
+ - Make the SMALLEST possible change to test hypothesis
156
+ - One variable at a time
157
+ - Don't fix multiple things at once
158
+
159
+ 3. **Verify Before Continuing**
160
+ - Did it work? Yes → Phase 4
161
+ - Didn't work? Form NEW hypothesis
162
+ - DON'T add more fixes on top
163
+
164
+ 4. **When You Don't Know**
165
+ - Say "I don't understand X"
166
+ - Don't pretend to know
167
+ - Ask for help
168
+ - Research more
169
+
170
+ ### Phase 4: Implementation
171
+
172
+ **Fix the root cause, not the symptom:**
173
+
174
+ 1. **Create Failing Test Case**
175
+ - Simplest possible reproduction
176
+ - Automated test if possible
177
+ - One-off test script if no framework
178
+ - MUST have before fixing
179
+ - Write the failing test first, then the fix (TDD)
180
+
181
+ 2. **Implement Single Fix**
182
+ - Address the root cause identified
183
+ - ONE change at a time
184
+ - No "while I'm here" improvements
185
+ - No bundled refactoring
186
+
187
+ 3. **Verify Fix**
188
+ - Test passes now?
189
+ - No other tests broken?
190
+ - Issue actually resolved?
191
+
192
+ 4. **If Fix Doesn't Work**
193
+ - STOP
194
+ - Count: How many fixes have you tried?
195
+ - If < 3: Return to Phase 1, re-analyze with new information
196
+ - **If ≥ 3: STOP and question the architecture (step 5 below)**
197
+ - DON'T attempt Fix #4 without architectural discussion
198
+
199
+ 5. **If 3+ Fixes Failed: Question Architecture**
200
+
201
+ **Pattern indicating architectural problem:**
202
+ - Each fix reveals new shared state/coupling/problem in different place
203
+ - Fixes require "massive refactoring" to implement
204
+ - Each fix creates new symptoms elsewhere
205
+
206
+ **STOP and question fundamentals:**
207
+ - Is this pattern fundamentally sound?
208
+ - Are we "sticking with it through sheer inertia"?
209
+ - Should we refactor architecture vs. continue fixing symptoms?
210
+
211
+ **Discuss with your human partner before attempting more fixes**
212
+
213
+ This is NOT a failed hypothesis - this is a wrong architecture.
214
+
215
+ ## Red Flags - STOP and Follow Process
216
+
217
+ If you catch yourself thinking:
218
+ - "Quick fix for now, investigate later"
219
+ - "Just try changing X and see if it works"
220
+ - "Add multiple changes, run tests"
221
+ - "Skip the test, I'll manually verify"
222
+ - "It's probably X, let me fix that"
223
+ - "I don't fully understand but this might work"
224
+ - "Pattern says X but I'll adapt it differently"
225
+ - "Here are the main problems: [lists fixes without investigation]"
226
+ - Proposing solutions before tracing data flow
227
+ - **"One more fix attempt" (when already tried 2+)**
228
+ - **Each fix reveals new problem in different place**
229
+
230
+ **ALL of these mean: STOP. Return to Phase 1.**
231
+
232
+ **If 3+ fixes failed:** Question the architecture (see Phase 4.5)
233
+
234
+ ## your human partner's Signals You're Doing It Wrong
235
+
236
+ **Watch for these redirections:**
237
+ - "Is that not happening?" - You assumed without verifying
238
+ - "Will it show us...?" - You should have added evidence gathering
239
+ - "Stop guessing" - You're proposing fixes without understanding
240
+ - "Ultra-think this" - Question fundamentals, not just symptoms
241
+ - "We're stuck?" (frustrated) - Your approach isn't working
242
+
243
+ **When you see these:** STOP. Return to Phase 1.
244
+
245
+ ## Common Rationalizations
246
+
247
+ | Excuse | Reality |
248
+ |--------|---------|
249
+ | "Issue is simple, don't need process" | Simple issues have root causes too. Process is fast for simple bugs. |
250
+ | "Emergency, no time for process" | Systematic debugging is FASTER than guess-and-check thrashing. |
251
+ | "Just try this first, then investigate" | First fix sets the pattern. Do it right from the start. |
252
+ | "I'll write test after confirming fix works" | Untested fixes don't stick. Test first proves it. |
253
+ | "Multiple fixes at once saves time" | Can't isolate what worked. Causes new bugs. |
254
+ | "Reference too long, I'll adapt the pattern" | Partial understanding guarantees bugs. Read it completely. |
255
+ | "I see the problem, let me fix it" | Seeing symptoms ≠ understanding root cause. |
256
+ | "One more fix attempt" (after 2+ failures) | 3+ failures = architectural problem. Question pattern, don't fix again. |
257
+
258
+ ## Quick Reference
259
+
260
+ | Phase | Key Activities | Success Criteria |
261
+ |-------|---------------|------------------|
262
+ | **1. Root Cause** | Read errors, reproduce, check changes, gather evidence | Understand WHAT and WHY |
263
+ | **2. Pattern** | Find working examples, compare | Identify differences |
264
+ | **3. Hypothesis** | Form theory, test minimally | Confirmed or new hypothesis |
265
+ | **4. Implementation** | Create test, fix, verify | Bug resolved, tests pass |
266
+
267
+ ## When Process Reveals "No Root Cause"
268
+
269
+ If systematic investigation reveals issue is truly environmental, timing-dependent, or external:
270
+
271
+ 1. You've completed the process
272
+ 2. Document what you investigated
273
+ 3. Implement appropriate handling (retry, timeout, error message)
274
+ 4. Add monitoring/logging for future investigation
275
+
276
+ **But:** 95% of "no root cause" cases are incomplete investigation.
277
+
278
+ ## Supporting Techniques
279
+
280
+ These techniques are part of systematic debugging and available in this directory:
281
+
282
+ - **`root-cause-tracing.md`** - Trace bugs backward through call stack to find original trigger
283
+ - **`defense-in-depth.md`** - Add validation at multiple layers after finding root cause
284
+ - **`condition-based-waiting.md`** - Replace arbitrary timeouts with condition polling
285
+
286
+ **Related skills:**
287
+ - Write the failing test case first, then the fix (Phase 4, Step 1) — TDD
288
+ - **verify-before-done** - Verify fix worked before claiming success
289
+
290
+ ## Real-World Impact
291
+
292
+ From debugging sessions:
293
+ - Systematic approach: 15-30 minutes to fix
294
+ - Random fixes approach: 2-3 hours of thrashing
295
+ - First-time fix rate: 95% vs 40%
296
+ - New bugs introduced: Near zero vs common