Skill: brasco05/coding-pipeline (version 1.0.1)

--- name: coding-pipeline description: "Enforces a disciplined 4-phase pipeline for non-trivial coding tasks: Plan (hypothesis) → Code (one fix) → Validate (root cause) → Debug (max 3 tries, escalate). Prevents blind patching, symptom fixes, and retry loops. Activate for any bug fix, feature implementation, refactor, or error investigation that isn't a trivial one-line change." --- # Coding Pipeline A disciplined 4-phase workflow for any non-trivial coding task. Each phase has a clear purpose, explicit exit criteria, and a loop-back rule when things go wrong. The phases exist because AI agents' default failure mode is blind iteration: edit → build → edit → build → give up. This skill forces hypothesis-driven work, one-fix-at-a-time discipline, root-cause verification, and bounded debugging. **This is a rigid skill — follow the phases exactly. Do not skip, merge, or reorder.** ## Core Rule Every non-trivial task — bug fix, feature, refactor — goes through all 4 phases in order: ``` ┌─────────────┐ ┌──────────┐ ┌───────────────┐ ┌─────────────┐ │ 1 PLANNER │───▶│ 2 CODER │───▶│ 3 VALIDATOR │───▶│ 4 DEBUGGER │ │ hypothesis │ │ one fix │ │ build + root │ │ max 3 tries │ └─────────────┘ └────┬─────┘ └───────┬───────┘ └──────┬──────┘ ▲ │ │ │ │ │ unclear cause │ fails │ new hypothesis └────────────────┴──────────────────┴───────────────────┘ loop back to PLANNER ``` Skipping a phase or jumping straight to Phase 2 is the failure mode this skill prevents. ## Quick Reference | Situation | Active Phase | Exit When | |-----------|--------------|-----------| | New task arrives | **Phase 1 Planner** | Hypothesis written, scope defined, success criteria explicit | | Hypothesis validated | **Phase 2 Coder** | One focused change applied, no unrelated edits | | Change applied | **Phase 3 Validator** | Build passes AND root cause verified | | Validator fails | **Phase 4 Debugger** | Either fix found (→ Phase 2) or 3 attempts exhausted (→ escalate) | | Unclear cause mid-fix | **Back to Phase 1** | New hypothesis written | | Fix introduces new error | **Back to Phase 1** | Hypothesis was wrong | ## Phase 1 — Planner **Goal:** Understand the task and formulate an explicit hypothesis *before* any code change. **Required outputs:** 1. **Task breakdown** — what is actually being asked? Break into the smallest independent units. 2. **Hypothesis** — one sentence in the form: *"I believe [symptom] is caused by [cause], because [evidence]."* 3. **Scope** — which files/modules are in-bounds, which are explicitly out-of-bounds 4. **Success criteria** — how Phase 3 will verify this is fixed (not just the symptom gone) **Forbidden in Phase 1:** - Editing any code - Running build or test commands to "see what happens" - Multiple parallel hypotheses — pick one, commit to it - Vague hypotheses ("something with the auth flow") — sharpen until specific **Exit criteria:** Hypothesis is concrete, testable, and you can point to *why* this is the cause — not just *what* looks broken. **Loop-back trigger:** If during Phase 2 or 3 the hypothesis turns out wrong, return here. Do not patch on top of a broken hypothesis. See `references/phase-1-planner.md` for hypothesis patterns and scope breakdown templates. ## Phase 2 — Coder **Goal:** Apply exactly one focused change that tests the hypothesis from Phase 1. **Rules:** 1. **One fix at a time** — one change, one purpose, one file or one tightly-scoped set of files 2. **Full files, not snippets** — deliver complete file contents when showing work 3. **No speculative refactoring** — resist "while I'm in here…"; surgical scope only 4. **If the hypothesis is unclear mid-change → STOP**, return to Phase 1 **Definition of "one fix":** A single logical change that either proves or disproves the hypothesis. Three unrelated improvements = three separate Planner → Coder → Validator cycles. **Exit criteria:** Change is applied, diff contains only the intended work, nothing unrelated. See `references/phase-2-coder.md` for scope discipline and loop-back triggers. ## Phase 3 — Validator **Goal:** Verify the change fixed the *root cause*, not just the symptom. **Checklist (adapt to stack):** 1. **Build check** — compile/transpile succeeds, no new errors 2. **Type check** — no new type errors; any `@ts-ignore` / `type: ignore` needs an explicit written justification comment 3. **Focused test** — run the specific test that proves the hypothesis, not the full suite 4. **Root-cause verification** — the fix addresses the Phase 1 hypothesis, not a side effect 5. **Scope verification** — diff matches what Phase 1 planned; no accidental changes 6. **Regression check** — nothing adjacent broke **The symptom-vs-cause test:** > If I rolled back this change, would the symptom return *because of the same cause*, or because of something else? If you can't answer confidently, the fix is symptomatic. Go back to Phase 1. **Exit criteria:** All checks pass, root cause verified, no regressions. **Failure → Phase 4 Debugger.** See `references/phase-3-validator.md` for stack-agnostic validation patterns. ## Phase 4 — Debugger **Goal:** Bounded debugging with documentation. Escalation over thrashing. **Hard rules:** 1. **Max 3 attempts** — after 3 failed fixes, STOP and escalate to the user 2. **Document every attempt** — what was tried, what happened, why it failed 3. **Never repeat a fix** — if attempt 1 failed, attempt 2 must be *substantively different* 4. **Never "just try again"** — every attempt must be backed by a *new* hypothesis **Attempt log template** (write to `.pipeline-state/attempts-<task>.md` or inline in chat): ```markdown ### Attempt N - **Hypothesis**: What I now believe is wrong - **Change**: What I modified (specific files/lines) - **Result**: What happened (error output, unchanged behavior, new symptom) - **Why it failed**: The actual root cause of this failure - **Next direction**: What to try next OR escalate ``` **After 3 failed attempts:** STOP. Surface to the user with the full attempt log. Do **not** continue with a 4th attempt unless the user explicitly authorizes it. **Recovery trigger:** If during Phase 4 a fundamentally new hypothesis emerges, return to **Phase 1** — not Phase 2. A new hypothesis means a new cycle, not continued debugging. See `references/phase-4-debugger.md` for escalation patterns and worked examples. ## Phase Transition Gates No phase transition is automatic. Each requires explicit criteria: | From | To | Required | |------|-----|----------| | 1 → 2 | Planner → Coder | Hypothesis written + scope defined + success criteria | | 2 → 3 | Coder → Validator | One focused change applied, no unrelated edits | | 3 → Done | Validator passes | Build ✓ + types ✓ + root cause verified + no regressions | | 3 → 4 | Validator → Debugger | Any validation check failed | | 4 → 2 | Debugger → Coder | New hypothesis + change substantively different from previous attempts | | 4 → 1 | Debugger → Planner | Fundamentally new hypothesis (not incremental) | | 4 → STOP | Debugger → Escalate | 3 attempts exhausted | | ANY → 1 | Back to Planner | Hypothesis proven wrong mid-cycle | ## Detection Triggers Activate this pipeline automatically when the task is: - **A bug report** — user says something is broken - **A feature request** — non-trivial new functionality - **A refactor** — touching existing code for non-cosmetic reasons - **An error investigation** — digging into unexpected behavior - **A test failure** — a test that was passing now fails - **A deployment issue** — something that worked in dev fails in prod **Skip the pipeline only for:** - Trivial edits (typo, formatting, one-line config) - Pure documentation changes - Explicitly exploratory work ("just experiment, don't commit") ## Anti-Patterns What this pipeline prevents: 1. **Symptom patching** — fixing what looks wrong without understanding why 2. **Multi-fix chaos** — changing three things at once, unable to tell which one worked 3. **Retry loops** — trying the same fix with minor variations hoping it sticks 4. **Premature coding** — jumping to Phase 2 before Phase 1 is done 5. **Validation skipping** — "it compiles, ship it" without root-cause check 6. **Unbounded debugging** — 8 attempts, no log, no escalation 7. **Speculative refactoring** — "while I'm here, let me also clean up this other file" 8. **Hypothesis drift** — quietly changing the hypothesis mid-fix to match what you just did 9. **Type-ignore laziness** — `@ts-ignore` without a written justification comment 10. **Scope creep** — task was "fix login redirect", PR touches 14 unrelated files See `references/anti-patterns.md` for concrete before/after examples of each. ## Integration with Other Skills This pipeline works well with — but does not replace — the following: - **`systematic-debugging`** — when Phase 4 escalates, hand off to systematic-debugging for the full investigation protocol - **`self-improving-agent`** — after every failed attempt in Phase 4, log to `.learnings/ERRORS.md` so the next task starts with that knowledge - **`root-cause-analysis`** — when Phase 3 root-cause verification is ambiguous, escalate to RCA - **`test-driven-development`** — Phase 1's "success criteria" naturally aligns with TDD's "write the failing test first" See `references/integration.md` for detailed pairing patterns. ## Platform Integration Platform-specific activation and hook configuration lives in `references/`: - **`references/openclaw-integration.md`** — OpenClaw workspace setup, inter-session coordination - **`references/hooks-setup.md`** — Claude Code / Codex hook configuration (`UserPromptSubmit`) - **`references/multi-agent.md`** — Claude Code, Codex CLI, GitHub Copilot activation patterns ## Best Practices 1. **Always start at Phase 1** — no shortcuts, no exceptions for "obvious" fixes 2. **One hypothesis, one fix** — resist bundling 3. **Phase 3 verifies cause, not symptom** — this is the hard check 4. **Phase 4 is bounded** — 3 attempts, then escalate 5. **Document every failed attempt** — pattern recognition matters 6. **Full files, no snippets** — for reviewability 7. **Loop back to Planner on uncertainty** — cheaper than debugging a wrong hypothesis 8. **Escalate fast** — 3 failed attempts is a signal, not a suggestion ## Source This pipeline is based on a production coding standard used in NestJS/Next.js/PHP production systems. It emerged from repeated observation that AI agents, left to their defaults, retry-loop into incoherence on non-trivial work. The 4-phase structure + max-3-attempts rule + mandatory hypothesis is the minimum structure needed to keep agents disciplined.

path: README.md
content: # ⚙️ Coding Pipeline

**Make AI coding agents work like disciplined engineers: plan, change one thing, validate, then debug with a limit.**

Coding Pipeline is a phase-gated workflow for non-trivial coding work. It stops agents from blind-patching, bundling unrelated fixes, and declaring success without proof.

## The 4 Phases

| Phase | Purpose | Required Exit |
|---|---|---|
| 1. Plan | Understand task, risk, hypothesis, success criteria | Written plan + smallest safe scope |
| 2. Code | Apply one focused change | One coherent diff, no surprise scope creep |
| 3. Validate | Prove the change works and root cause is addressed | Test/build/lint/log evidence |
| 4. Debug | If validation fails, investigate with a max of 3 attempts | Fixed or escalated with attempt log |

## Use It For

- Feature implementation
- Non-trivial bug fixes
- Refactors
- Test failures
- Deployment/CI failures
- Any task where “just edit it” is likely to create mess

Skip it only for trivial edits: typo, copy change, one-line config with obvious verification.

## Core Rules

1. **Hypothesis before code** — what should this change prove?
2. **One fix at a time** — unrelated improvements become separate cycles
3. **Validate cause, not vibes** — “it compiles” is not always enough
4. **Max 3 debug attempts** — then escalate with what was tried and what remains unknown
5. **No DONE without evidence** — test, build, lint, logs, screenshot, or named blocker

## Example Agent Output

```text
Phase 1 — Plan
Hypothesis: The checkout 500 is caused by missing null handling in discount lookup.
Smallest change: guard null discount before price calculation.
Validation: unit test for no-discount checkout + npm test checkout.
Risk: low; only checkout pricing path affected.
```

Then code. Then validation. No wandering.

## Pair It With

- **safe-change** before touching shared/high-risk files
- **deep-debugging** when root cause is unclear
- **self-improving-agent** when a failed attempt should become durable learning

---

*by brasco05 · phase-gated coding discipline for OpenClaw, Claude Code, Codex, and similar agents*


path: assets/PHASE-1-planner-template.md
content: # Phase 1 — Planner Template

Copy this into a scratch file, issue, or chat message at the start of any non-trivial task. Fill in every section before touching code.

---

## Task

> <one-sentence description of what is being asked>

## Task Breakdown

- [ ] <smallest independent sub-task>
- [ ] <smallest independent sub-task>
- [ ] <smallest independent sub-task>

## Hypothesis

> *I believe [symptom/requirement] is caused by / will be achieved by [cause/approach], because [evidence].*

**Examples:**

- *I believe the login redirect loops because the middleware reads `session` before next-auth writes the cookie on the `/api/auth/callback` response, because the network tab shows no `Set-Cookie` header on that response.*
- *I believe rate limiting on `/api/chat` is best implemented with a Redis sliding-window counter, because we already use Redis for sessions and in-memory state breaks on multi-instance Railway deployments.*

## Evidence

List concrete observations that support the hypothesis:

- <log output, test failure, code reading, reproduction>
- <log output, test failure, code reading, reproduction>

## Scope

**In-bounds** (files/modules the fix may touch):

- `<path/to/file>`
- `<path/to/file>`

**Out-of-bounds** (files/modules explicitly excluded):

- `<path/to/file>` — reason: <why not>
- any unrelated test file
- any dependency upgrade

## Success Criteria

How Phase 3 will verify this is fixed / complete:

- [ ] <concrete, verifiable outcome>
- [ ] <concrete, verifiable outcome>
- [ ] Build passes
- [ ] Type check passes
- [ ] Specific test: `<test name or command>` passes

---

## Quality Check

Before moving to Phase 2, verify:

- [ ] Hypothesis is **specific** (names exact files/functions/conditions)
- [ ] Hypothesis is **falsifiable** (can be proven wrong by observation)
- [ ] Hypothesis is **evidence-backed** (references something you actually observed)
- [ ] Scope is **explicit** (in-bounds AND out-of-bounds named)
- [ ] Success criteria is **verifiable** (not "it works")

If any box is unchecked, stay in Phase 1.


path: assets/PHASE-2-coder-checklist.md
content: # Phase 2 — Coder Checklist

Use this while applying a change. Tick boxes as you go.

---

## Before You Start Editing

- [ ] Phase 1 is complete (hypothesis + scope + success criteria all written)
- [ ] You can state the **one** change you are about to make in one sentence
- [ ] You know which files will be touched, and they match the Phase 1 scope

## While Editing

- [ ] **One fix at a time** — a single logical change that proves/disproves the hypothesis
- [ ] **Full files** — prepared to show complete file contents, not snippets
- [ ] **No speculative refactors** — resist "while I'm here"
- [ ] **Scope held** — not opening files outside the Phase 1 scope

## Mid-Edit Stop Conditions

STOP editing and return to Phase 1 if you notice:

- [ ] The hypothesis doesn't match what the code actually does
- [ ] You need to edit a file that wasn't in Phase 1 scope
- [ ] The fix requires a deeper architectural change
- [ ] You don't actually understand why the current code looks the way it does

Each of these means Phase 1 was wrong. Cheaper to rewrite the hypothesis than patch through uncertainty.

## Scope Creep Warning Signs

- [ ] Adding imports for libraries Phase 1 didn't plan
- [ ] Modifying tests to make the build pass (instead of making tests pass by fixing code)
- [ ] Running `grep` / `find` to "explore" — that was Phase 1's job
- [ ] Cleaning up unrelated code in the same file
- [ ] Renaming things "while I'm here"

If any of these happen: STOP, revert the creep, return to Phase 1.

## Exit to Phase 3

Before you move to Validator, confirm:

- [ ] Exactly one logical change is applied
- [ ] Diff contains only the intended work
- [ ] No unrelated edits in the diff
- [ ] Full files are available for review
- [ ] You can point at the diff and say which line tests the Phase 1 hypothesis

Otherwise: revert the speculative parts, narrow the diff, try again.


path: assets/PHASE-3-validator-checklist.md
content: # Phase 3 — Validator Checklist

Run through this every time, even when the change feels obviously correct. Skipping steps here is how symptomatic fixes ship.

---

## Build Check

- [ ] Build / compile succeeds without new errors
- [ ] No new warnings that weren't there before

Stack-specific commands:

| Stack | Command |
|-------|---------|
| TypeScript (NestJS, Next.js) | `pnpm build` or `npm run build` |
| TypeScript strict check | `tsc --noEmit` |
| Rust | `cargo build` |
| Go | `go build ./...` |
| Python | `python -m py_compile <file>` |
| PHP | `php -l <file>` |

## Type Check

- [ ] No new type errors
- [ ] Any `@ts-ignore` / `@ts-expect-error` / `type: ignore` has a **written justification comment** explaining why the type system is wrong here

If you can't write the one-sentence justification, fix the types instead of suppressing.

## Focused Test

- [ ] The specific test that proves the Phase 1 hypothesis is run and passes
- [ ] If no test existed yet, a new failing test was written first and now passes

NOT the full test suite — the targeted test that matches Phase 1's success criteria.

## Root-Cause Verification

**The symptom-vs-cause test.** Ask:

> "If I rolled back this change, would the symptom return **because of the same cause** I hypothesized — or because of something else?"

- [ ] You can answer this confidently
- [ ] The answer is "because of the same cause"
- [ ] The fix addresses the hypothesis, not a side effect

If you can't answer confidently → the fix is symptomatic. Return to Phase 1.

## Scope Verification

- [ ] Run `git diff --stat`
- [ ] The changed files match Phase 1's in-bounds list
- [ ] No unexpected files in the diff
- [ ] No files from the out-of-bounds list

If there are unexpected files: either justify each (and update Phase 1 retroactively with a reason) or revert them.

## Regression Check

- [ ] Adjacent tests in the same module still pass
- [ ] Happy path of the affected feature smoke-tested manually
- [ ] No new errors in logs during the smoke test

You don't need to run the full suite (CI does that). You do need to check the immediate neighborhood.

## Completeness Gate

- [ ] Build ✓
- [ ] Types ✓
- [ ] Focused test ✓
- [ ] Root cause verified ✓
- [ ] Scope matches plan ✓
- [ ] No regressions ✓

All six? → **Done.**

Any unchecked? → **Phase 4 Debugger.**

## Common Shortcuts That Fail

- ❌ "Build is green, that's enough" — skipping root-cause verification
- ❌ "Running tests would take forever" — you run the focused test, not the suite
- ❌ "The diff looks fine" — actually run `git diff --stat` and compare against Phase 1
- ❌ "It smoke tests okay" — without also checking root cause
- ❌ "I'll add the type justification later" — no, write it now or fix the types


path: assets/PHASE-4-debugger-log.md
content: # Phase 4 — Debugger Attempt Log

Copy this into `.pipeline-state/attempts-<task>.md` (or inline in chat) when Phase 3 validation has failed. Log every attempt. **Max 3.**

---

## Task

> <one-sentence description>

## Original Phase 1 Hypothesis

> <the hypothesis that was written in Phase 1, verbatim>

---

## Attempt 1

- **Hypothesis**: <what I now believe is wrong — may differ from the original Phase 1 hypothesis>
- **Change**: <specific files and lines modified>
- **Result**: <exact error output, unchanged behavior, or new symptom>
- **Why it failed**: <the actual root cause of this failure>
- **Next direction**: <what to try in attempt 2, OR "escalate">

---

## Attempt 2

- **Hypothesis**: <new hypothesis — substantively different from attempt 1>
- **Change**: <specific files and lines modified — different from attempt 1>
- **Result**: <exact error output, unchanged behavior, or new symptom>
- **Why it failed**: <the actual root cause of this failure>
- **Next direction**: <what to try in attempt 3, OR "escalate">

---

## Attempt 3

- **Hypothesis**: <new hypothesis — substantively different from attempts 1 and 2>
- **Change**: <specific files and lines modified — different from previous attempts>
- **Result**: <exact error output, unchanged behavior, or new symptom>
- **Why it failed**: <the actual root cause of this failure>
- **Next direction**: **ESCALATE** — hand off to user or `systematic-debugging`

---

## Escalation (after 3 failed attempts)

**STOP. Do not start attempt 4 without explicit user authorization.**

### What to Surface

1. **Original Phase 1 hypothesis** (above)
2. **All 3 attempt logs** (above)
3. **What I now believe is true** (based on what failures taught me)
4. **Specific questions for the user** — what info I need to make progress
5. **Optional: handoff to `systematic-debugging`**

### Escalation Message Template

```
Phase 4 exhausted after 3 attempts on <task>.

Original hypothesis: <original>

Attempts:
  1. <one-line summary> — failed because <reason>
  2. <one-line summary> — failed because <reason>
  3. <one-line summary> — failed because <reason>

What I now know:
  - <insight from attempt 1 failure>
  - <insight from attempt 2 failure>
  - <insight from attempt 3 failure>

Questions for you:
  - <specific question I need answered>
  - <specific question I need answered>

Should I hand this off to `systematic-debugging` for a deeper investigation?
```

---

## Recovery Trigger

If during Phase 4 a **fundamentally new hypothesis** emerges — not a refinement, but a different model of what's wrong — return to **Phase 1**, not Phase 2. Start a new cycle. Don't try to patch your way from the old model to the new.

Example:

- Started with: *"Login fails because cookies aren't being set"*
- Attempts 1 + 2 fail
- You realize: *"Actually, the login API isn't being called at all — the fetch URL is wrong"*

That's a completely different model. Return to Phase 1. Write a new hypothesis. Start fresh.

---

## Rules Reminder

1. **Max 3 attempts** — hard cap
2. **Every attempt = new hypothesis** — no repeats, no minor variations
3. **Every attempt documented** — hypothesis / change / result / why it failed
4. **Never "just try again"** — always with a new model
5. **Escalate over thrashing** — the log is the handoff artifact


path: hooks/openclaw/HOOK.md
content: 


path: hooks/openclaw/handler.js
content: 


path: package.json
content: {
  "name": "coding-pipeline",
  "version": "1.0.1",
  "description": "Phase-gated coding workflow for AI agents: plan, make one focused change, validate with evidence, and debug with a hard retry limit.",
  "author": "brasco05",
  "license": "MIT",
  "keywords": [
    "coding-pipeline",
    "disciplined-coding",
    "hypothesis-driven",
    "debugging",
    "root-cause",
    "bug-fixing",
    "phase-gated",
    "claude",
    "codex",
    "openclaw",
    "agent-workflow",
    "verification"
  ]
}


path: references/anti-patterns.md
content: # Anti-Patterns

Concrete before/after examples of the 10 failure modes this pipeline prevents. Each example shows the broken behavior and the disciplined alternative.

## 1. Symptom Patching

**Broken:**

> *User:* "The login redirects in a loop."
> *Agent:* [edits middleware] "I hardcoded the redirect to `/dashboard` when the URL contains `/login`. Should work now."

The symptom is gone, but the cause (session not being read correctly) remains. The bug will resurface the moment anyone changes the middleware order.

**Disciplined:**

> *Phase 1:* "Hypothesis: login redirect loops because middleware reads `session` before next-auth has written the cookie on the callback response. Evidence: network tab shows no cookie on `/api/auth/callback` response."
> *Phase 2:* Edit `middleware.ts` to skip `/api/auth/*` paths.
> *Phase 3:* Verify the callback now sets the cookie, and subsequent requests have a valid session.

## 2. Multi-Fix Chaos

**Broken:**

> *Agent:* "I fixed the auth bug. I also cleaned up the session helper, upgraded `next-auth` to v5, and added logging. 14 files changed."

Now you can't tell which change fixed the bug. If it regresses later, there are 4 candidate causes.

**Disciplined:**

One fix per cycle. The cleanup, upgrade, and logging are three separate tasks. Each gets its own Planner → Coder → Validator pass.

## 3. Retry Loops

**Broken:**

> *Attempt 1:* "Let me add a `try/catch` around the API call."
> *Attempt 2:* "Hmm, that didn't work. Let me add a `try/catch` with a `setTimeout`."
> *Attempt 3:* "Let me wrap it in a `Promise.all` too."
> *Attempt 4:* "Let me also add a retry…"

No hypothesis change, no documentation, no learning.

**Disciplined:**

Each attempt has a new hypothesis backed by evidence from the previous failure. Attempt 3's hypothesis must be substantively different from attempts 1 and 2. After attempt 3, escalate.

## 4. Premature Coding

**Broken:**

> *User:* "Fix the date calculation bug."
> *Agent:* [opens `src/utils/date.ts` and starts editing immediately]

No hypothesis. No scope. No success criteria. Just vibes.

**Disciplined:**

> *Phase 1:* "What date calculation? Show me the failing test. Hypothesis: ISO week function uses `getDay()` returning 0 for Sunday instead of 6 for Sunday. Evidence: failing test case uses a date that is a Sunday."
> *Phase 2:* Narrow edit to the specific line.
> *Phase 3:* Run the failing test; verify it passes; run adjacent date tests to check for regressions.

## 5. Validation Skipping

**Broken:**

> *Agent:* "I fixed it. `pnpm build` succeeded. Done."

Build passing ≠ root cause fixed. The symptom could be hidden by a new bug you just introduced.

**Disciplined:**

Build ✓ is step 1 of Phase 3. Steps 2-6 (types, focused test, root-cause verification, scope check, regression check) are equally required. "It compiles" is never a completion signal.

## 6. Unbounded Debugging

**Broken:**

> *Agent:* [attempt 8] "Still not working. Let me try one more thing…"

No attempt log. No escalation. Context is burned. The human has no idea what's been tried.

**Disciplined:**

Max 3 attempts. Every attempt logged with hypothesis / change / result / why it failed / next direction. At attempt 3 failure, STOP and escalate with the full log.

## 7. Speculative Refactoring

**Broken:**

> *User:* "Fix the failing login test."
> *Agent:* "I fixed the test. I also noticed the auth module had a lot of duplication so I refactored it into a factory pattern. And I renamed some variables for clarity. And I extracted a helper. 600 lines changed."

Now the diff is unreviewable. You can't tell which change fixed the test and which was cosmetic.

**Disciplined:**

Scope in Phase 1 was "fix the failing login test". The refactor wasn't in scope. Log it as a `FEATURE_REQUEST` or TODO for a future separate task. Deliver the narrow fix.

## 8. Hypothesis Drift

**Broken:**

> *Phase 1 hypothesis:* "Redirect loops because the cookie isn't being set."
> *Phase 2:* [edits middleware, not cookie logic]
> *Phase 3:* "Works now. I think the real issue was middleware order, actually."

The hypothesis was retroactively changed to match the fix. This means Phase 1 was skipped in practice.

**Disciplined:**

If the fix didn't test the hypothesis, that's a signal: return to Phase 1, write the *new* hypothesis, start a fresh cycle. Don't rewrite history.

## 9. Type-Ignore Laziness

**Broken:**

```typescript
// @ts-ignore
const user = req.user;
```

No comment. No explanation. The type system was right, and you chose not to listen.

**Disciplined:**

```typescript
// @ts-expect-error — req.user is added by auth middleware at runtime; the Express type definition doesn't include it, but this handler is only reachable after the middleware runs.
const user = req.user;
```

One sentence explaining *why* the type system is wrong here. If you can't write the sentence, fix the types instead of suppressing them.

## 10. Scope Creep

**Broken:**

> *Task:* "Fix login redirect."
> *PR:* 14 files changed. Touches auth, middleware, layout, header component, README, package.json, and three unrelated tests.

Nobody can review this. Nobody knows what the actual fix was.

**Disciplined:**

Phase 1 scope: "in-bounds = `src/middleware.ts`, `src/auth/session.ts`. Out-of-bounds = everything else." Anything outside that list triggers either a hard stop (expand scope with an explicit reason + new Phase 1) or a separate task.

---

## Meta-Pattern

All 10 anti-patterns share a common thread: **the agent skipped or underdid a phase.** The pipeline is designed to be rigid so that the path of least resistance is the correct behavior:

- Phase 1 skipped → symptom patching, premature coding, hypothesis drift
- Phase 2 undisciplined → multi-fix chaos, speculative refactor, scope creep
- Phase 3 skipped → validation skipping, type-ignore laziness
- Phase 4 unbounded → retry loops, unbounded debugging

When in doubt: which phase were you in when the trouble started? Return to it.


path: references/examples.md
content: # Worked Examples

Three complete walkthroughs showing all 4 phases on real scenarios: a bug fix, a feature addition, and a refactor.

---

## Example 1: Bug Fix

**Scenario:** User reports that login from a cold browser session redirects in a loop between `/login` and `/api/auth/callback`.

### Phase 1 — Planner

**Task breakdown:**
- Reproduce in a cold browser session
- Understand which redirect is failing
- Identify what state is expected at each hop

**Hypothesis:**
> *I believe the login redirect loops because the `/api/auth/callback` response is not setting a session cookie, because the middleware is reading the request's session before the callback can write it.*

**Evidence:**
- Network tab shows `Set-Cookie: next-auth.session-token=...` missing on `/api/auth/callback` response
- Middleware logs show `session: null` on the request that follows the callback

**Scope:**
- **In**: `src/middleware.ts`, `src/auth/config.ts`
- **Out**: all route handlers, all UI components, test files other than `auth.e2e.spec.ts`

**Success criteria:**
- `auth.e2e.spec.ts → login redirect` passes
- Fresh browser session reaches `/dashboard` in ≤1 redirect after login
- Network tab shows the session cookie on the callback response

### Phase 2 — Coder

Edit `src/middleware.ts`:
- Add early return for `pathname.startsWith('/api/auth/')` before the session read
- Nothing else

Full file delivered, diff is 6 lines.

### Phase 3 — Validator

1. `pnpm build` ✓
2. `tsc --noEmit` ✓
3. `pnpm test auth.e2e.spec.ts → login redirect` ✓
4. **Root-cause verification**: the middleware no longer blocks the callback; the callback sets the cookie; the subsequent request carries the session. Verified via browser devtools.
5. **Scope verification**: `git diff --stat` shows only `src/middleware.ts` modified ✓
6. **Regression check**: adjacent tests (`auth.unit.spec.ts`, `middleware.spec.ts`) still pass ✓

**Done.** Phase 4 not needed.

---

## Example 2: Feature Addition

**Scenario:** Add rate limiting to the `/api/chat` endpoint — max 20 requests per minute per user.

### Phase 1 — Planner

**Task breakdown:**
- Choose a rate limit mechanism (in-memory vs Redis)
- Implement the limiter
- Wire it into the `/api/chat` handler
- Test both "under limit" and "over limit" cases

**Hypothesis:**

Note: for feature work, the hypothesis is about *how* to implement, not *why* something is broken.

> *The simplest correct approach is a sliding window counter in Redis, keyed by `chat:rate:{userId}`, with a 60-second TTL. Evidence: we already use Redis for sessions, so the infrastructure is in place; in-memory would fail on multi-instance Railway deployments.*

**Scope:**
- **In**: `src/api/chat.ts`, new file `src/lib/rate-limit.ts`, `src/api/chat.test.ts`
- **Out**: other API routes (intentional — do one at a time)

**Success criteria:**
- 20 requests in 60s succeed
- 21st request in 60s returns `429 Too Many Requests`
- Counter resets after 60s
- Redis calls add <10ms to p95 latency (measured locally)

### Phase 2 — Coder

One change:
- Create `src/lib/rate-limit.ts` with sliding window implementation
- Wrap `/api/chat` handler with the limiter

Nothing else — do NOT also refactor the existing handler, do NOT also add limits to other routes, do NOT also update logging.

### Phase 3 — Validator

1. `pnpm build` ✓
2. `tsc --noEmit` ✓
3. Tests:
   - `chat.test.ts → under limit` ✓
   - `chat.test.ts → over limit` ✓
   - `chat.test.ts → resets after window` ✓
4. **Root-cause / feature verification**: local load test with 21 requests in 60s — first 20 return 200, 21st returns 429 ✓
5. **Scope verification**: `git diff --stat` shows `src/api/chat.ts`, `src/lib/rate-limit.ts`, `src/api/chat.test.ts` — matches Phase 1 ✓
6. **Regression**: `/api/*` smoke tests pass ✓

**Done.**

---

## Example 3: Refactor

**Scenario:** A `validateUser()` function is duplicated (with minor variations) in 4 different service files. Consolidate.

### Phase 1 — Planner

**Task breakdown:**
- Identify the 4 call sites
- Find the common core and the variations
- Decide on the consolidated signature
- Migrate call sites one at a time

**Hypothesis:**

> *The 4 copies differ only in whether they throw or return null on invalid input. A single function with a `throwOnInvalid: boolean` option can replace all 4 with identical behavior. Evidence: read the 4 copies side-by-side; the core validation logic is byte-identical except for the error path.*

**Scope:**
- **In**: new file `src/shared/validate-user.ts`, `src/services/auth.service.ts`, `src/services/chat.service.ts`, `src/services/profile.service.ts`, `src/services/admin.service.ts`
- **Out**: any other service file, any test file beyond the 4 affected services

**Success criteria:**
- All 4 services import from `src/shared/validate-user.ts`
- Behavior of each service is unchanged (tests for each still pass)
- `git grep 'function validateUser' | wc -l` returns 1 (the shared one)

### Phase 2 — Coder

**Apply in sub-cycles.** A refactor touching 5 files is not "one fix" — it's 5 coordinated fixes.

Cycle 1:
- Create `src/shared/validate-user.ts`
- Migrate `auth.service.ts` to import from it
- Run `auth.service.test.ts` — passes

Cycle 2:
- Migrate `chat.service.ts`
- Run `chat.service.test.ts`

…and so on for each service.

Each cycle goes through Phase 2 → Phase 3 independently. If cycle 3 breaks, you don't have to re-do cycles 1 and 2.

### Phase 3 — Validator (per cycle)

For each cycle:
1. `tsc --noEmit` ✓
2. Service's own tests pass ✓
3. **Root-cause verification**: the service now uses the shared function; behavior matches the previous inline implementation (diff the outputs on a known input)
4. Scope verification: only the intended service file + the shared file changed in this cycle

### Final Validation

After all 4 sub-cycles:
- `git grep 'function validateUser' | wc -l` → 1 ✓
- Full test suite for affected services passes ✓
- No unrelated behavior changes (diff the API responses for a smoke test)

**Done.**

---

## Takeaways

- **Refactors are multi-cycle**, not one big change
- **Features and bug fixes are single-cycle** when scoped correctly
- **Phase 1 rigor scales down for trivial tasks** but never down to zero — even a typo fix should have an explicit scope ("this file, this line")
- **The pipeline is the cheapest path**, not the slowest — skipping phases wastes more time downstream


path: references/hooks-setup.md
content: # Hook Setup

Configure automatic pipeline reminders via agent hooks. This is **opt-in** — you must explicitly configure hooks in your agent's settings.

## Overview

The pipeline works without hooks — the skill description triggers it. Hooks are for users who want **proactive phase reminders** injected automatically, especially at the start of a task (to nudge toward Phase 1) or after a tool failure (to nudge toward Phase 4's attempt log).

## Claude Code Setup

### Project-Level

Create `.claude/settings.json` in your project root:

```json
{
  "hooks": {
    "UserPromptSubmit": [{
      "matcher": "",
      "hooks": [{
        "type": "command",
        "command": "./skills/coding-pipeline/scripts/activator.sh"
      }]
    }]
  }
}
```

This injects a reminder at the start of every prompt — roughly 60-80 tokens — asking whether the task is non-trivial and nudging toward Phase 1.

### User-Level

If you want the pipeline reminder across all projects, put the same hook in `~/.claude/settings.json`. Use an absolute path for the command:

```json
{
  "hooks": {
    "UserPromptSubmit": [{
      "matcher": "",
      "hooks": [{
        "type": "command",
        "command": "/absolute/path/to/coding-pipeline/scripts/activator.sh"
      }]
    }]
  }
}
```

## Codex CLI Setup

Same pattern, using `.codex/settings.json`:

```json
{
  "hooks": {
    "UserPromptSubmit": [{
      "matcher": "",
      "hooks": [{
        "type": "command",
        "command": "./skills/coding-pipeline/scripts/activator.sh"
      }]
    }]
  }
}
```

Codex supports the same hook events as Claude Code — point both at the same scripts.

## OpenClaw Setup

OpenClaw uses workspace-based injection rather than hooks. Install the skill via ClawdHub:

```bash
clawdhub install coding-pipeline
```

The skill's `SKILL.md` is injected into every session automatically. No hook configuration required. See `references/openclaw-integration.md` for details.

## Hook Script Details

`scripts/activator.sh` is short and side-effect-free. It writes a context block to stdout that the agent consumes:

```
<coding-pipeline-reminder>
If this task is non-trivial (bug, feature, refactor, error investigation):
  1. Start in Phase 1 (Planner) — hypothesis + scope + success criteria
  2. Do NOT skip to Phase 2 (Coder)
  3. Phase 3 (Validator) must verify root cause, not just build success
  4. Phase 4 (Debugger) caps at 3 attempts, then escalates

Trivial tasks (typos, formatting, one-line config) skip the pipeline.
</coding-pipeline-reminder>
```

It takes <10ms to run and adds ~80 tokens per prompt. The overhead is deliberate — a small, consistent nudge is more effective than occasional reminders.

## Disabling

### Claude Code / Codex

Remove the hooks block from `settings.json`.

### OpenClaw

```bash
clawdhub uninstall coding-pipeline
```

Or edit `~/.openclaw/workspace/skills/` to remove the folder.

## Troubleshooting

**Hook not firing:**

- Verify the script is executable: `chmod +x scripts/activator.sh`
- Verify the path in `settings.json` resolves from the working directory where the agent runs
- Check agent logs for hook invocation errors

**Token overhead too high:**

- Reduce the hook trigger — use a `matcher` regex to only fire on certain prompt patterns
- Disable the hook and rely on the skill description for activation instead

**Multiple skills competing:**

- Phase reminders from multiple skills can add up. If you're running `coding-pipeline` + `self-improving-agent` + `systematic-debugging` all with hooks, consider consolidating to one activator that covers all three.


path: references/integration.md
content: # Integration with Other Skills

`coding-pipeline` is deliberately narrow: it enforces the 4-phase structure. It does not replace other specialized skills; it pairs with them. This reference shows how to combine it with the most common companions.

## `systematic-debugging`

**When to hand off:** Phase 4 has escalated (3 attempts exhausted) and the problem is complex enough to warrant structured investigation with parallel hypothesis testing.

**How to hand off:**

1. Complete the Phase 4 attempt log (all 3 attempts documented)
2. Invoke `systematic-debugging` with the attempt log as input
3. `systematic-debugging` picks up where Phase 4 leaves off — its protocol adds deeper instrumentation, hypothesis branching, and parallel sub-agent investigation

**Handoff message template:**

> Phase 4 exhausted after 3 attempts on <task>. Full attempt log in `.pipeline-state/attempts-<task>.md`. Invoking `systematic-debugging` with this log as the "what has been tried" section.

**Why pair them:** `coding-pipeline` enforces discipline on normal work. `systematic-debugging` handles the pathological cases where normal discipline isn't enough. Use the cheap skill first, escalate to the expensive one when the cheap one gives up.

## `self-improving-agent`

**When to log:** After every failed attempt in Phase 4 — immediately, while context is fresh.

**What to log:**

```markdown
## [ERR-YYYYMMDD-XXX] <task-name>

**Logged**: ISO-8601 timestamp
**Priority**: high
**Status**: pending
**Area**: frontend | backend | infra | tests

### Summary
Phase 4 attempt N failed — <one line>.

### Error
<redacted error output — no secrets>

### Context
- Phase 1 hypothesis: <original>
- Attempt N hypothesis: <updated>
- What we learned: <key insight from this failure>

### Suggested Fix
<if identifiable>

### Metadata
- Source: coding-pipeline-phase-4
- Related Files: <path>
- Reproducible: yes | no | unknown
```

**Why pair them:** `coding-pipeline` prevents bad practice; `self-improving-agent` captures learning from the bad-practice-that-happened-anyway. Together they form a loop: attempted failures become logged learnings become promoted rules become permanent improvements.

**Loop pattern:**

```
coding-pipeline Phase 4 fails
        ↓
self-improving-agent logs the attempt
        ↓
recurrence threshold hit (3+ similar failures)
        ↓
promotion to CLAUDE.md / AGENTS.md as a prevention rule
        ↓
future tasks hit the rule in Phase 1 — the mistake is no longer possible
```

## `root-cause-analysis`

**When to hand off:** Phase 3 root-cause verification is ambiguous — you can't confidently answer "if I rolled back this change, would the symptom return because of the same cause?"

**How to hand off:**

1. Pause Phase 3
2. Invoke `root-cause-analysis` with the Phase 1 hypothesis and the Phase 2 change as input
3. Let RCA produce a verified cause chain
4. Return to Phase 3 with the RCA output as evidence

**Why pair them:** `coding-pipeline`'s root-cause check is a go/no-go. `root-cause-analysis` is the full investigation that produces the answer when the check is uncertain.

## `test-driven-development`

**When to pair:** Always, when the task includes "add or modify behavior" (i.e. not a pure refactor).

**How to pair:**

- Phase 1's **success criteria** should be expressed as a **failing test** written first
- Phase 2 is then "make the test pass" — the discipline of TDD enforces the one-fix rule naturally
- Phase 3's **focused test** is the same test from Phase 1, now green

**Why pair them:** TDD and `coding-pipeline` reinforce each other. TDD gives you the test; `coding-pipeline` gives you the framing around it. TDD without phases becomes "make it pass by any means"; phases without TDD become "I think it works, let me check".

## `verification-before-completion`

**When to pair:** Every Phase 3, especially before claiming the task is done.

**How to pair:** `verification-before-completion` requires running verification commands and confirming output before making success claims. This is exactly Phase 3's job, made explicit. The two skills say the same thing from different angles — layer them for rigor.

## General Pairing Philosophy

`coding-pipeline` is the **meta-skill**: it defines when to invoke the others.

- Phase 1 might invoke `brainstorming` (for complex features) or read learnings from `self-improving-agent`
- Phase 2 might invoke `test-driven-development` or `receiving-code-review`
- Phase 3 invokes `verification-before-completion` and possibly `root-cause-analysis`
- Phase 4 invokes `systematic-debugging` on escalation and `self-improving-agent` on every failed attempt

The pipeline is the orchestration layer. The other skills are the tools it reaches for.

## Not a Replacement For

`coding-pipeline` does **not** replace:

- **`brainstorming`** — for upstream design work before a task is even defined
- **`writing-plans`** — for multi-phase implementation planning beyond a single task
- **`executing-plans`** — for running a plan across multiple tasks
- **Platform-specific skills** — stack gotchas, deployment skills, etc.

The pipeline runs **inside** a single task. Upstream (brainstorming, planning) and platform-specific concerns live elsewhere.


path: references/multi-agent.md
content: # Multi-Agent Support

`coding-pipeline` works across different AI coding agents with agent-specific activation. Read the section for the platform you're using.

## Claude Code

**Activation**: Skill description match + optional `UserPromptSubmit` hook
**Setup**: `.claude/settings.json` (see `hooks-setup.md`)
**Detection**: Automatic when a task matches the skill description, reinforced by the optional hook

The skill activates whenever Claude Code sees a task description that matches the frontmatter (bug, feature, refactor, error investigation). The optional hook adds a reminder at every prompt start.

**Recommended Claude Code workflow:**

1. Install: copy the skill folder to `~/.claude/skills/coding-pipeline/`
2. Optional: enable the hook via `~/.claude/settings.json`
3. Start a task — Claude Code should invoke the skill automatically based on the description

## Codex CLI

**Activation**: Skill description match + optional `UserPromptSubmit` hook
**Setup**: `.codex/settings.json` (same shape as Claude Code)
**Detection**: Automatic via the skill description

Codex supports the same hook events and skill loading as Claude Code. Point the same activator script at both.

```json
{
  "hooks": {
    "UserPromptSubmit": [{
      "matcher": "",
      "hooks": [{
        "type": "command",
        "command": "./skills/coding-pipeline/scripts/activator.sh"
      }]
    }]
  }
}
```

## OpenClaw

**Activation**: Workspace injection at session start
**Setup**: See `openclaw-integration.md` for full details
**Detection**: Automatic — the skill content is loaded at workspace start

OpenClaw is the primary home for this skill. Workspace injection means the 4-phase structure is always in context, no hooks required.

## GitHub Copilot

**Activation**: Manual — Copilot has no hook support
**Setup**: Add a reminder block to `.github/copilot-instructions.md`:

```markdown
## Coding Pipeline

For non-trivial tasks (bug fixes, features, refactors, error investigations), follow a 4-phase discipline:

1. **Phase 1 — Planner**: Write a one-sentence hypothesis before touching code. Define scope and success criteria.
2. **Phase 2 — Coder**: Apply exactly one focused change. Full files, no speculative refactors.
3. **Phase 3 — Validator**: Verify root cause, not just symptom. Build check + types + focused test + scope check.
4. **Phase 4 — Debugger**: Max 3 attempts, each with a new hypothesis, all documented. Escalate after 3.

Skip the pipeline only for typos, formatting, and one-line config changes.
```

**Copilot Chat prompts:**

- "Apply the coding-pipeline discipline to this task — start at Phase 1"
- "Write the hypothesis for Phase 1 before suggesting any code"
- "Is this Phase 2 or Phase 3?" (useful mid-task)

**Detection**: Manual — Copilot won't auto-invoke the pipeline. Reference it explicitly in prompts.

## Cursor

**Activation**: Manual — similar to Copilot
**Setup**: Add the 4-phase discipline to `.cursor/rules` or equivalent

Cursor respects project-level rule files; the content should mirror the Copilot section above.

## Agent-Agnostic Guidance

Regardless of platform, apply the pipeline when:

1. **A bug is reported** — don't jump to Phase 2
2. **A feature is requested** — scope and success criteria first
3. **A refactor is planned** — multi-cycle by default
4. **An error is unclear** — Phase 1 forces you to articulate what you don't know
5. **A test is failing** — the failing test is your Phase 3 verification

The 4 phases are text, not tooling. Any agent that reads markdown can follow them.

## Platform Comparison

| Platform | Auto-invocation | Hook support | Token overhead | Best for |
|----------|-----------------|---------------|----------------|----------|
| Claude Code | ✅ (description) | ✅ | ~80/prompt with hook | Single-project discipline |
| Codex CLI | ✅ (description) | ✅ | ~80/prompt with hook | Same as Claude Code |
| OpenClaw | ✅ (injection) | ❌ (not needed) | Baseline injection | Multi-project consistency |
| GitHub Copilot | ❌ (manual) | ❌ | 0 | Teams already using Copilot |
| Cursor | ❌ (manual) | ❌ | 0 | Cursor users who want structure |

## Recommendation

If you use **more than one** of these platforms, install via ClawdHub in OpenClaw (zero overhead, automatic) and configure the hook in Claude Code / Codex. Copilot and Cursor users get the manual version via rule files.


path: references/openclaw-integration.md
content: # OpenClaw Integration

Complete setup for running `coding-pipeline` inside an OpenClaw workspace.

## Overview

OpenClaw uses workspace-based prompt injection — `SKILL.md` content is injected into every session automatically when the skill is installed. Unlike Claude Code, you don't need to configure hooks; the workspace engine handles it.

## Installation

**Via ClawdHub (recommended):**

```bash
clawdhub install coding-pipeline
```

This places the skill at `~/.openclaw/workspace/skills/coding-pipeline/` and registers it in the workspace manifest.

**Manual:**

```bash
mkdir -p ~/.openclaw/workspace/skills/coding-pipeline
cp -r ./coding-pipeline/* ~/.openclaw/workspace/skills/coding-pipeline/
```

Then rebuild the workspace index:

```bash
openclaw workspace reindex
```

## Workspace Structure

After installation:

```
~/.openclaw/workspace/
├── AGENTS.md                 # Multi-agent coordination patterns
├── SOUL.md                   # Behavioral guidelines, personality
├── TOOLS.md                  # Tool capabilities and gotchas
├── MEMORY.md                 # Long-term memory
├── memory/                   # Daily memory files
└── skills/
    └── coding-pipeline/      # This skill
        ├── SKILL.md          # Injected at session start
        ├── references/       # Loaded on demand
        ├── scripts/          # Accessible to the agent
        ├── assets/           # Templates
        └── hooks/openclaw/   # Hook manifest (empty by default)
```

## Promotion Targets

When a learning from `coding-pipeline` Phase 4 failures turns into a durable rule, promote it to the workspace files:

| Target | What Belongs There |
|--------|--------------------|
| `AGENTS.md` | Multi-agent workflows that use the pipeline (e.g. "spawn a phase-tracker sub-agent for long refactors") |
| `SOUL.md` | Behavioral rules like "Never skip Phase 1 even for obvious-looking fixes" |
| `TOOLS.md` | Pipeline-specific tool patterns (e.g. "use phase-check.sh to track state across session pauses") |

Promotion example:

A learning emerges from 3 repeated Phase 4 failures on NestJS DI issues. Promote it to `SOUL.md`:

> **NestJS DI debugging:** Phase 1 hypothesis for any DI error must explicitly name the module boundary where injection fails. Cross-module DI issues are almost always missing `exports:` in the providing module.

Future sessions now get this rule at session start and skip the dead end.

## Inter-Session Coordination

If you run multiple OpenClaw sessions in parallel (e.g. one pairs with Telegram, another does local dev), they share the same `.learnings/` directory. This means Phase 4 failures logged in session A become visible to session B on next task start.

Use `sessions_history` and `sessions_send` to coordinate:

- Session A: exhausts Phase 4, logs to `.learnings/ERRORS.md`
- Session B (invoked later): reads `.learnings/ERRORS.md` at Phase 1, sees the dead ends, starts with a better hypothesis

## Pipeline State Directory

The skill uses `.pipeline-state/` to track phase progression during a task:

```
.pipeline-state/
├── current-phase              # Contains "1" | "2" | "3" | "4"
├── activity.log               # Timestamped phase transitions
└── attempts-<task>.md         # Per-task attempt log (Phase 4)
```

This directory is created on first use by `scripts/phase-check.sh`. Add to `.gitignore` by default — it's local session state, not shared repository content.

```gitignore
.pipeline-state/
```

## Hook Manifest

`hooks/openclaw/HOOK.md` and `hooks/openclaw/handler.js` are present but empty by default. OpenClaw's workspace injection makes hooks unnecessary for this skill — the SKILL.md is already loaded. If you want phase-start reminders beyond the description match, you can populate `handler.js` with a custom hook, but it's not required.

## Comparing with Claude Code

| Aspect | Claude Code | OpenClaw |
|--------|-------------|----------|
| Activation | Hook via `.claude/settings.json` + skill description | Workspace injection at session start |
| Reminder overhead | ~80 tokens per prompt (hook) | 0 tokens per prompt (baseline injection) |
| Cross-session state | Per project | Shared workspace (inter-session messaging) |
| Promotion targets | `CLAUDE.md` | `SOUL.md`, `AGENTS.md`, `TOOLS.md`, `MEMORY.md` |
| Best for | Single-project discipline | Multi-project consistent behavior |

If you use both, install via ClawdHub in OpenClaw and configure the hook in `~/.claude/settings.json` so Claude Code sessions get the reminder too.


path: references/phase-1-planner.md
content: # Phase 1 — Planner

Deep-dive on the Planner phase. Read this when starting any non-trivial task.

## Purpose

Phase 1 exists because **premature coding is the single biggest failure mode of AI agents**. When an agent jumps to Phase 2 without a hypothesis, it ends up:

- Patching symptoms (the bug returns next week)
- Flailing between plausible fixes
- Missing the actual root cause
- Producing unreviewable diffs

The Planner's job is to make you **commit to a hypothesis in writing** before you touch code.

## Required Outputs

### 1. Task Breakdown

Decompose the task into the smallest independent units. Ask:

- What is *actually* being asked — not what you assume
- What is the **one sentence** version of the goal?
- Are there hidden sub-tasks? (auth changes usually drag in token handling, CORS, session state)
- What is explicitly **not** in scope?

### 2. Hypothesis

A hypothesis is a falsifiable claim about the cause. Use this form:

> *"I believe [symptom] is caused by [cause], because [evidence]."*

**Good hypotheses:**

- *"I believe the login redirect loops because the middleware runs before `next-auth` sets its cookie, because the network tab shows no cookie on the `/api/auth/callback` response."*
- *"I believe the vital signs calculation is off by one day because the ISO week function is using `getDay()` (Sunday=0) instead of `getDay()+6 % 7` (Monday=0), because the test fails exactly when the date is a Sunday."*

**Bad hypotheses:**

- *"I think there's something wrong with the auth flow."* → too vague
- *"It's probably a race condition."* → no evidence
- *"Let me just try fixing X and see if it works."* → not a hypothesis, that's Phase 2 without Phase 1

### 3. Scope

Explicitly list:

- **In bounds**: `src/auth/middleware.ts`, `src/auth/session.ts`
- **Out of bounds**: anything in `src/features/`, any test file unrelated to auth, any dependency upgrade

If you find yourself wanting to edit an out-of-bounds file mid-Phase 2, **STOP** — that's scope creep. Either return to Phase 1 to expand scope with a reason, or leave it alone.

### 4. Success Criteria

How will Phase 3 verify this is fixed? Be concrete:

- ✅ "The integration test `auth.e2e.spec.ts → login redirect` passes"
- ✅ "Login from a cold browser session reaches `/dashboard` in ≤1 redirect"
- ❌ "It works" — not verifiable
- ❌ "Users can log in" — not specific enough

## Hypothesis Patterns

Common patterns that produce sharp hypotheses:

| Pattern | Template |
|---------|----------|
| **Timing/ordering** | "X happens before Y, but X depends on Y being complete" |
| **State leakage** | "X is read before it is set in the request lifecycle" |
| **Environment diff** | "Works in dev because X is set via `.env.local`, fails in prod because Railway env vars lack X" |
| **Off-by-one** | "The calculation uses Z index but iterates from Z+1" |
| **Missing invariant** | "The function assumes input is not null, but caller Y passes null" |
| **Contract mismatch** | "API returns snake_case, client expects camelCase" |

## Quality Check

Before exiting Phase 1, your hypothesis must pass:

- [ ] **Specific** — names exact files, functions, conditions
- [ ] **Falsifiable** — can be proven wrong by a concrete observation
- [ ] **Evidence-backed** — references something you actually observed (logs, test output, code reading)
- [ ] **Narrow** — one cause, not "maybe X or Y or Z"
- [ ] **Written down** — not just in your head

If any checkbox is unchecked, the hypothesis isn't ready. Sharpen it.

## Forbidden in Phase 1

- Editing code
- Running `npm install` / `pnpm install` / any setup command
- Running the build "to see"
- Running tests "to see what breaks"
- Multiple parallel hypotheses ("maybe it's A, or B, or C…") — pick one
- Skipping straight to Phase 2 because "it's obvious"

If the fix feels obvious, that's when discipline matters most. *Write the hypothesis anyway*. The 30 seconds of explicit thinking prevents the 30 minutes of retry-loop later.

## Exit Gate to Phase 2

You may proceed to Phase 2 **only when**:

1. ✅ Task is decomposed into independent units
2. ✅ Hypothesis is written, specific, falsifiable, evidence-backed
3. ✅ Scope is explicit (in-bounds + out-of-bounds)
4. ✅ Success criteria is concrete and verifiable

Otherwise: stay in Phase 1.

## Loop-back Triggers

Return to Phase 1 from any later phase when:

- Phase 2: you realize your hypothesis was wrong as soon as you start editing
- Phase 3: validation fails in a way that invalidates the hypothesis
- Phase 4: a fundamentally new hypothesis emerges — don't continue debugging the old one, start a new cycle

Looping back is cheaper than pushing through a wrong hypothesis.


path: references/phase-2-coder.md
content: # Phase 2 — Coder

Deep-dive on the Coder phase. Read this when applying a change from a Phase 1 hypothesis.

## Purpose

Phase 2 is where the hypothesis from Phase 1 gets tested in code. The rule is **one fix, one purpose, one cycle**. The failure mode Phase 2 prevents is the "while I'm here" trap: you open the file to make the intended change, and you see three other things that bother you, and suddenly your diff touches 11 files and nobody can tell which change fixed the bug.

## Rules

### 1. One Fix at a Time

Exactly one logical change per cycle. A "logical change" is a single modification that either **proves or disproves the Phase 1 hypothesis**.

**Counts as one fix:**

- Edit one function in one file
- Add one guard clause where the hypothesis predicts null input
- Rename one variable if the hypothesis says a typo is the cause
- Edit multiple files if they're part of the same logical change (e.g. a type definition + its single consumer)

**Does NOT count as one fix:**

- "Fix the auth bug + clean up the tests + update the README"
- "Fix the calculation + refactor the helper + add logging"
- "Fix the type error + upgrade the dependency + remove the workaround"

Each of those is a separate Plan → Code → Validate cycle.

### 2. Full Files, Not Snippets

When showing your work, deliver complete file contents. Reasons:

- **Reviewability** — snippets hide context, full files don't
- **Confidence** — the reviewer knows nothing unrelated changed
- **Reversibility** — a full file is easy to revert; a snippet requires reconstructing the surrounding context

Exception: file is >500 lines and you only touched a small region — in that case, show the diff *plus* a note about what the surrounding code looks like.

### 3. No Speculative Refactoring

The temptation: *"This function is a bit messy, let me clean it up while I'm in here."*

**Do not.** That is a separate task. Log it as a feature request (`FEATURE_REQUESTS.md` if using `self-improving-agent`) or a TODO, but do not bundle it into the current fix.

Why it matters: speculative refactors change the behavior you're trying to observe in Phase 3. If the bug is fixed but you also moved 40 lines around, you have no way to know if the bug was fixed by your intended change or by the refactor.

### 4. Loop-Back on Uncertainty

If mid-change you realize **any** of:

- The hypothesis doesn't match what you see in the code
- You need to edit a file that wasn't in the Phase 1 scope
- The fix requires a deeper architectural change
- You don't actually understand why the current code looks the way it does

→ **STOP editing**. Return to Phase 1. Write a new hypothesis. Start a new cycle.

Continuing through uncertainty is how retry loops begin.

## Scope Discipline

If you find yourself:

- Opening files not in the Phase 1 scope
- Running `grep` or `find` to "explore" — that was Phase 1's job
- Adding imports for libraries you didn't touch
- Modifying tests to make the build pass rather than asserting the fix works

…you have drifted. Stop, return to Phase 1, expand scope explicitly with a reason, and start over.

## One-Fix Examples

### Example: Bug Fix

**Hypothesis from Phase 1:** *"Login redirect loops because middleware runs before next-auth sets its cookie."*

**Phase 2 (correct):**
- Edit `src/middleware.ts` — add skip condition for `/api/auth/*` routes
- Nothing else

**Phase 2 (wrong):**
- Edit `src/middleware.ts` + clean up unused imports in `src/auth/session.ts` + add missing types in `src/auth/callback.ts` + update the README auth section

### Example: Feature Addition

**Hypothesis from Phase 1:** *"Rate limiting on `/api/chat` will be enforced by sliding window counter in Redis."*

**Phase 2 (correct):**
- Edit `src/api/chat.ts` — wrap handler with rate limit middleware
- Add `src/lib/rate-limit.ts` — the sliding window implementation
- Nothing else

**Phase 2 (wrong):**
- All of the above + refactor the rest of the API routes to "be consistent" + add logging + update dependencies

## Exit Gate to Phase 3

Proceed to Phase 3 **only when**:

1. ✅ Exactly one logical change is applied
2. ✅ Diff is clean — no unrelated edits, no "while I was here"
3. ✅ Full files are available for review
4. ✅ You can point at the diff and say which line tests the Phase 1 hypothesis

Otherwise: revert speculative changes, narrow the diff, try again.

## Common Failures

- **Scope drift** — edit 7 files when Phase 1 planned 2
- **Bundled fixes** — two unrelated changes in one commit
- **Snippet delivery** — showing only the changed lines, hiding context
- **Refactor temptation** — cleaning up while "passing through"
- **Partial edits** — changing a function signature but forgetting one caller
- **Test amendments** — modifying the test to pass instead of making the code pass the test

Each of these invalidates Phase 3 because you can no longer tell what the fix was.


path: references/phase-3-validator.md
content: # Phase 3 — Validator

Deep-dive on the Validator phase. Read this after applying a Phase 2 change.

## Purpose

Phase 3 is the hard check. Its job is to answer **"did this fix the root cause, or just the symptom?"** The failure mode it prevents is "it compiles, ship it" — where an agent runs the build, sees green, and declares victory without verifying that the original cause is actually addressed.

A fix that makes the symptom go away **without addressing the cause** is worse than no fix. It hides the bug and makes it return in a different form.

## Validation Checklist

Adapt to your stack. This is the minimum.

### 1. Build Check

The build/compile succeeds without new errors or warnings.

| Stack | Command |
|-------|---------|
| TypeScript (NestJS, Next.js) | `pnpm build` or `npm run build` |
| TypeScript strict | `tsc --noEmit` |
| Rust | `cargo build` |
| Go | `go build ./...` |
| Python | `python -m py_compile` + import check |
| PHP | `php -l <file>` + manual load |

If a new warning appeared that wasn't there before: investigate. Do not suppress.

### 2. Type Check

No new type errors. Any `@ts-ignore`, `@ts-expect-error`, `// eslint-disable`, `type: ignore`, or equivalent **requires a written justification comment** — one sentence explaining *why* the type system is wrong here.

Unjustified type ignores are a Phase 1 violation: they mean you don't actually understand what the code is doing.

### 3. Focused Test

Run the **specific test** that proves the Phase 1 hypothesis. Not the full suite. The full suite takes longer and obscures which check matters.

If no test exists yet for this hypothesis, write one now — a failing test that exercises the specific cause you hypothesized, then re-run it to confirm the fix made it pass.

### 4. Root-Cause Verification

This is the phase's core job. Ask:

> **"If I rolled back this change, would the symptom return *because of the same cause* I hypothesized — or because of something else?"**

If you can't answer confidently, the fix is symptomatic. Return to Phase 1.

**Examples:**

| Symptom | Symptomatic fix | Root-cause fix |
|---------|-----------------|----------------|
| Login redirect loops | Hardcode `redirect: '/dashboard'` in middleware | Fix the cookie-setting order so middleware can read the session |
| Off-by-one date | Subtract 1 day everywhere | Fix the ISO-week function to use Monday=0 |
| Type error in API call | `as any` cast | Fix the response type definition to match actual API shape |
| Test fails on CI but passes locally | `.skip()` the test | Fix the timezone assumption that only breaks outside Europe |

### 5. Scope Verification

Run `git diff --stat`. The changed files should match what Phase 1 planned. If there are extra files:

- **Expected extras** (imports, type files the hypothesis implied) → fine, note them
- **Unexpected extras** → scope creep. Revert them or explain why they were necessary.

### 6. Regression Check

Did anything adjacent break? Minimum:

- Run tests in the same module (`src/auth/*.test.ts`)
- Smoke-test the happy path of the affected feature manually
- Check for new errors in log output during the smoke test

You don't need to run the whole test suite — that's CI's job. You *do* need to check that nothing in the immediate neighborhood is broken.

## The Symptom-vs-Cause Test in Practice

The most reliable signal that a fix is symptomatic:

- **You can describe what the code now does, but not why the original code was wrong.**

If that's true, you didn't fix the cause. You fixed a coincidence. The bug will come back.

**Good diagnostic questions:**

- "Why was the original code doing X?" — if you don't know, you're patching blind
- "What assumption was being violated?" — name it
- "Why did this work before?" — if it did, something changed; what?
- "Could this same cause produce a different symptom elsewhere?" — if yes, there are related bugs

## Exit Gate to "Done"

The task is complete **only when**:

1. ✅ Build passes, no new errors/warnings
2. ✅ Types pass, no unjustified suppressions
3. ✅ The focused test proves the hypothesis
4. ✅ Root cause is verified — the fix addresses the Phase 1 hypothesis, not a coincidence
5. ✅ Diff matches Phase 1 scope
6. ✅ No regressions in the adjacent area

Otherwise → **Phase 4 Debugger**.

## Common Failures

- **Build green = done** — skipping root-cause verification
- **Unjustified type suppression** — `@ts-ignore` without a comment
- **Symptom tests** — asserting the symptom is gone instead of asserting the cause is addressed
- **Scope creep accepted** — noticing extra files in the diff and shrugging
- **Regression blindness** — not checking adjacent code at all
- **Full-suite churn** — running 2000 tests to feel confident when 3 targeted tests would prove it

Each of these means Phase 3 was skipped, not completed.


path: references/phase-4-debugger.md
content: # Phase 4 — Debugger

Deep-dive on the Debugger phase. Read this when Phase 3 validation has failed.

## Purpose

Phase 4 is **bounded debugging with documentation**. Its job is to keep debugging from turning into thrashing.

The failure mode it prevents: 12 attempts, no log, no escalation, agent gives up with "I can't figure this out" after burning half the context window. The pipeline caps attempts at 3 and requires every attempt to be documented with a hypothesis, a change, a result, and a reason for failure.

## Hard Rules

### 1. Max 3 Attempts

After 3 failed fixes, STOP. Surface the full attempt log to the user. Do not start a 4th attempt unless the user explicitly authorizes it.

Why 3 is the cap:

- 1 attempt: the obvious fix didn't work — probably a wrong hypothesis
- 2 attempts: a new hypothesis, different approach — still not working
- 3 attempts: you've tested two distinct hypotheses, both wrong — you don't understand the system well enough to fix it alone

At attempt 4, the cost of continuing (context burn, further entrenchment in wrong model) exceeds the cost of asking for help.

### 2. Document Every Attempt

Every attempt — even failures — must be logged. Use this template:

```markdown
### Attempt N
- **Hypothesis**: What I believe is wrong now (one sentence)
- **Change**: What I modified (specific files/lines)
- **Result**: What happened — exact error output, unchanged behavior, new symptom
- **Why it failed**: The actual root cause of this failure
- **Next direction**: What to try next OR "escalate"
```

Log location: `.pipeline-state/attempts-<task>.md` if available, otherwise inline in chat.

The log has two purposes:

1. **Prevent repetition** — you can see what you already tried
2. **Enable escalation** — when you hand off to the user or `systematic-debugging`, the log is the handoff artifact

### 3. Never Repeat a Fix

If attempt 1 modified file X by changing Y to Z, attempt 2 cannot modify file X by changing Y to Z'. Every attempt must be **substantively different** — different file, different approach, different hypothesis.

Minor variations of the same fix are not different attempts. They are the same attempt with noise.

### 4. Every Attempt Needs a New Hypothesis

"Let me just try again" is not a hypothesis. Before attempt N+1, answer:

- **Why did attempt N fail?** (the actual root cause of the failure, not just "didn't work")
- **What does that tell me about the system?**
- **What's my new hypothesis for the real cause?**

If you can't answer those three, you're not ready for attempt N+1.

## Attempt Log — Worked Example

```markdown
### Attempt 1
- **Hypothesis**: Login redirect loops because middleware runs before next-auth sets its cookie
- **Change**: src/middleware.ts — added skip condition for /api/auth/* routes
- **Result**: Redirect loop continues, but now /api/auth/callback is reachable (network tab shows 302)
- **Why it failed**: The hypothesis was half-right — middleware DID block the callback, but the real cause is that next-auth is using secure: true cookies in dev, and the dev server is http://
- **Next direction**: Set cookie to secure: process.env.NODE_ENV === 'production' in next-auth config

### Attempt 2
- **Hypothesis**: next-auth cookies are secure: true in dev, blocking the auth cycle on http://
- **Change**: src/auth/next-auth-config.ts — made cookie secure conditional on NODE_ENV
- **Result**: Dev works. But now production shows the same redirect loop again.
- **Why it failed**: Production has its own issue — NEXTAUTH_URL env var is missing on Railway, so next-auth computes the wrong callback URL
- **Next direction**: Add NEXTAUTH_URL=https://caresys-omega.vercel.app to Railway env vars
```

Attempt 3 either succeeds or escalates.

## Escalation — What to Surface

When 3 attempts are exhausted, surface this to the user:

1. **The original Phase 1 hypothesis**
2. **All 3 attempt logs** (verbatim from the template)
3. **What you now believe is true about the system** (based on what you learned from failures)
4. **Specific questions for the user** — what you need to know to make progress
5. **Optional: handoff to `systematic-debugging`** — the full investigation protocol

Example escalation message:

> **Phase 4 exhausted after 3 attempts.**
>
> Original hypothesis: *login redirect loops because middleware runs before next-auth sets its cookie*
>
> **Attempts:**
> 1. [log]
> 2. [log]
> 3. [log]
>
> **What I now know:**
> - Dev works after attempt 2
> - Production NEXTAUTH_URL is set but redirect still loops
> - The Vercel function logs show the callback reaching next-auth, but the session cookie isn't being set on the response
>
> **Questions for you:**
> - Can you share a Vercel function log from a fresh login attempt?
> - Is there a custom `cookies()` config in production that I'm missing?
> - Should I hand this off to `systematic-debugging` for a deeper investigation?

## Recovery Trigger — New Cycle Instead of Continuing

If during Phase 4 a **fundamentally new hypothesis** emerges — not a refinement, but a different model of what's wrong — return to **Phase 1**, not Phase 2. A new hypothesis means a new cycle.

Example:

- Started with: *"Login fails because cookies aren't being set"*
- Attempt 1 + 2 fail
- You realize: *"Actually, the login API isn't being called at all because the fetch URL is wrong"*

That's a completely different model. Return to Phase 1, write a new hypothesis, start fresh. Don't try to patch your way from the old model to the new one.

## Integration with `systematic-debugging`

When Phase 4 escalates, the next step for complex investigations is the `systematic-debugging` skill. Its protocol picks up where Phase 4 leaves off:

- The Phase 4 attempt log becomes the "what has been tried" section
- The systematic-debugging skill adds structured investigation, parallel hypothesis testing via sub-agents, and deeper instrumentation

If `systematic-debugging` is installed, hand off with a message like:

> Invoking systematic-debugging with Phase 4 attempt log as input.

## Integration with `self-improving-agent`

After every failed attempt in Phase 4, log the learning to `.learnings/ERRORS.md`:

```markdown
## [ERR-YYYYMMDD-XXX] <task-name>

**Priority**: high
**Status**: pending

### Summary
Phase 4 attempt N failed — <one line>

### Error
<redacted error output>

### Context
- Phase 1 hypothesis: <original>
- Attempt N hypothesis: <updated>
- What we learned: <key insight>

### Suggested Fix
If identifiable.
```

This way, next time a similar bug appears, the next session starts with that knowledge instead of repeating the dead ends.

## Common Failures

- **No attempt log** — trying fixes without writing down what was tried or why it failed
- **Repeated fixes** — attempt 2 is a minor variation of attempt 1
- **Unbounded debugging** — going past 3 attempts without escalating
- **Silent give-up** — stopping without surfacing the log to the user
- **Missing hypothesis** — "let me just try…" without a new model
- **Patch through failures** — pretending attempt N "kind of worked" and building on top

Each of these makes the handoff to the human useless when it eventually happens.


path: scripts/activator.sh
content: #!/bin/bash
# coding-pipeline Activator Hook
# Triggers on UserPromptSubmit to remind the agent about the 4-phase discipline
# Keep output minimal (~80 tokens) to minimize overhead

set -e

cat << 'EOF'
<coding-pipeline-reminder>
If this task is non-trivial (bug fix, feature, refactor, error investigation):
  1. Phase 1 (Planner) — write hypothesis + scope + success criteria BEFORE code
  2. Phase 2 (Coder) — one focused change, full files, no scope creep
  3. Phase 3 (Validator) — verify root cause, not just build success
  4. Phase 4 (Debugger) — max 3 attempts, each documented, then escalate

Trivial tasks (typos, formatting, one-line config) may skip the pipeline.
Do NOT jump to Phase 2 before Phase 1 is complete.
</coding-pipeline-reminder>
EOF


path: scripts/phase-check.sh
content: #!/bin/bash
# coding-pipeline Phase Tracker
# Tracks current phase state in .pipeline-state/ and appends activity log
# Usage:
#   phase-check.sh get              — print current phase
#   phase-check.sh set <1|2|3|4>    — set current phase and log transition
#   phase-check.sh log <message>    — append a freeform log entry
#   phase-check.sh show             — print full activity log
#   phase-check.sh reset            — clear state (start of new task)

set -e

STATE_DIR=".pipeline-state"
STATE_FILE="${STATE_DIR}/current-phase"
LOG_FILE="${STATE_DIR}/activity.log"

usage() {
    cat << 'EOF'
Usage: phase-check.sh [command] [args]

Commands:
  get              Print current phase (1-4), or "none" if not set
  set <1|2|3|4>    Set the current phase and log the transition
  log <message>    Append a freeform log entry to the activity log
  show             Print the full activity log
  reset            Clear phase state (start of new task)
  -h, --help       Show this help
EOF
}

ensure_state_dir() {
    mkdir -p "$STATE_DIR"
}

timestamp() {
    date -u +"%Y-%m-%dT%H:%M:%SZ"
}

case "${1:-get}" in
    get)
        if [ -f "$STATE_FILE" ]; then
            cat "$STATE_FILE"
        else
            echo "none"
        fi
        ;;

    set)
        if [ -z "${2:-}" ]; then
            echo "Error: set requires a phase number (1-4)" >&2
            usage
            exit 1
        fi
        if ! [[ "$2" =~ ^[1-4]$ ]]; then
            echo "Error: phase must be 1, 2, 3, or 4" >&2
            exit 1
        fi
        ensure_state_dir
        previous="none"
        if [ -f "$STATE_FILE" ]; then
            previous=$(cat "$STATE_FILE")
        fi
        echo "$2" > "$STATE_FILE"
        echo "[$(timestamp)] Phase transition: $previous → $2" >> "$LOG_FILE"
        echo "Phase: $2"
        ;;

    log)
        shift
        if [ -z "${*:-}" ]; then
            echo "Error: log requires a message" >&2
            exit 1
        fi
        ensure_state_dir
        echo "[$(timestamp)] $*" >> "$LOG_FILE"
        ;;

    show)
        if [ -f "$LOG_FILE" ]; then
            cat "$LOG_FILE"
        else
            echo "No activity log yet. Start with 'phase-check.sh set 1'"
        fi
        ;;

    reset)
        if [ -d "$STATE_DIR" ]; then
            rm -f "$STATE_FILE" "$LOG_FILE"
            echo "Pipeline state reset."
        else
            echo "No state to reset."
        fi
        ;;

    -h|--help)
        usage
        exit 0
        ;;

    *)
        echo "Error: unknown command '$1'" >&2
        usage
        exit 1
        ;;
esac


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: clean (LOW)