Hydraia — Agentic Development Pipeline
This skill defines the ONLY approved way to build a feature. Run every phase, in
order, automatically. Never ask the user which model, skill, or reviewer to
use — those decisions are already made here. Never skip a phase. Never pause
for "should I continue?" between phases.
Announce once at the start: "Running the Hydraia pipeline." Then proceed silently
through the phases, narrating at most one short line per phase.
Phase -1 — Intent triage (before everything)
Classify the request into exactly ONE route before any other guard runs.
Explicit commands skip classification and force their route
(/hydraia:feature → feature · /hydraia:story → user story ·
/hydraia:plan → feature, stopping after Phase 3 · /hydraia:review →
review · /hydraia:perf → performance · /hydraia:db → performance,
DB-shaped · /hydraia:architect → greenfield · /hydraia:e2e → E2E suite ·
/hydraia:devops → DevOps config · /hydraia:observability → instrumentation ·
/hydraia:docs → docs sync). Plain-language requests are classified by signals:
| Intent |
Signals |
Route |
| Feature / change |
"add / build / implement / change X" |
Phases 0–6 as written below |
| User story |
"As a … I want … so that …", acceptance-criteria lists, ticket text or a Jira/PDF export |
Run the story-analysis skill FIRST (interactive PO pass → story artifact with numbered ACs), then Phases 0–3 with that artifact as the primary design input; continue into 4–6 only when the entry point runs the full pipeline |
| Bug / unexpected behavior |
"fails / broken / error / regression / used to work" |
systematic-debugging skill first — root cause before any fix. Enter the pipeline only if the fix requires new design/behavior; a surgical fix proceeds under that skill's rules (the spec-drive gate still applies) |
| Performance / DB symptom |
"slow / timeout / high CPU / memory climbing / query takes …" |
Run the performance-tuning skill flow: measured baseline FIRST, dispatch perf-engineer (and db-performance-tuner when the symptom is DB-shaped, per db-optimization), spec carries baseline + numeric target, Phase 6 re-measures against it |
| New app / greenfield |
"from scratch / new app / new service / greenfield" |
Run the greenfield-architect skill: elicitation → architecture proposals (architect + code-architect, microservices only with evidence) → confirmed stack → api-design contract when an API exists → adr records per decision — then Phases 0–6 |
| Review / audit |
"review / audit this branch / this PR" |
Phases 5–6 only |
| Ambiguous |
none of the above clearly |
AskUserQuestion listing the plausible routes — never assume |
Triage is ONE classification step, not a conversation — at most a single
routing question, and only when genuinely ambiguous. Route chosen, proceed
to the start-of-run guards below.
Autonomy tier + cost (after route, before the guards)
Once the route is chosen, estimate a tier from cheap signals and show a cost
estimate. This maps to hydraia's EXISTING controls — it adds no new enforcement axis.
Early-exit (noop) first. If the route's target is empty, do not spin the pipeline:
review / graph: if git diff --name-only against the branch point is empty (or the
named target does not exist), report "nothing to review", drop the run-complete marker
(printf 'brief\n' > <base>/.run-complete), and stop. No Phases 0–6.
perf / db: if the named symptom target is absent or already within a stated
threshold, report and stop.
Tier (feature-shaped routes). Classify from: likely files touched, overlap with the
gate.yaml denylist (risk), new-logic vs mechanical, presence of UI surfaces:
- Tier S (trivial): no new logic, no new file, no risk-path, ≤ ~2 files → propose
quick-mode (the
.quick-approved path) or a Lite review. Minimal ceremony.
- Tier M (standard): default — full pipeline, Full review.
- Tier L (large / risky): many files, risk-path overlap, or a new service → full
pipeline + all gates; the human may raise the agent ceiling.
Cost estimate. Read patterns/cost.yaml for the route × tier and state a one-line
token estimate (e.g. "≈200k tokens, Tier S"). It is a rough anchor, not a promise.
Confirm once. Present the tier + estimate in a single AskUserQuestion,
pre-selecting the review depth for the Phase-3 run-controls picker. The human confirms
with one tap or overrides. Honor autoTier config (off → always Tier M, today's
behavior). A tier NEVER removes the security floor (Phase 5 mandatory reviewers, threat
model) — Tier S only trims optional ceremony, exactly as quick-mode already does.
Start-of-run guards (before Phase 0)
Language gate (first action, before anything else). Call the
AskUserQuestion tool once to ask which language the user wants replies in —
options: English and Español. Use the answer for all user-facing communication
for the rest of the run: narration, the Phase-1 clarifying question, review
findings, and the final summary. If the user dismisses the question, default to the
language they wrote their request in. This choice does NOT change code, commit
messages, spec/plan files, or the credits line — those stay as-is (English,
portable). Ask this exactly once per run; /hydraia:resume inherits the prior
run's choice if the run log records it, otherwise re-asks.
Storage & commit gate (second action, right after the Language gate). Two
AskUserQuestion prompts, asked once per run (like the language gate). Do NOT
recommend an option — the user chooses; these are privacy/workflow decisions, not
quality ones.
- Artifacts location — "Where should Hydraia store its artifacts (specs, plans,
QA, run logs, and pipeline state)?"
In the repo → <repo>/docs/hydraia/ (tracked by git — the default).
Outside the repo → ~/.config/hydraia/artifacts/<repo-slug>/ (on this machine,
never committed, no .gitignore edits). <repo-slug> = repo dir basename + -
- the first 6 hex of a hash of the absolute repo root.
- Auto-commit — "Auto-commit each task as Hydraia goes?"
Yes → commit per task (the default).
No → executors do NOT commit; all changes are left in the working tree for you
to commit as you like.
After the answers: persist both to the GLOBAL config ~/.config/hydraia/config.json
under repos["<absolute repo root>"] — do NOT hand-edit that JSON. Use the
hy_config_set helper in hooks/config.sh, which merges into the file atomically,
preserving every other repo and key:
bash -c '. "$CLAUDE_PLUGIN_ROOT/hooks/config.sh"
hy_config_set "<absolute repo root>" artifactsDir "<docs/hydraia | absolute external path>"
hy_config_set "<absolute repo root>" autoCommit "<true|false>"'
Pass artifactsDir docs/hydraia (or skip it) for in-repo; the absolute external path
otherwise. Then create the external dir (with specs/ plans/ qa/ runs/) if chosen, and
use the resolved absolute base as the artifacts base for the whole run (see
Artifacts base below). If the user dismisses either question, default to in-repo + auto-commit
ON (behavior identical to prior versions). /hydraia:resume inherits both from the
run log if recorded, otherwise re-asks. The hooks read the same choice via
hy_artifacts_dir / hy_repo_config in hooks/config.sh, so the gate, agent caps,
plan-check, and summary all resolve to the same base — in-repo or external.
Commit attribution (hard rule, every commit this pipeline makes). Hydraia commits
carry a clean, conventional message and NOTHING else. NEVER add a Co-Authored-By
trailer for Claude, Hydraia, or any AI; never add a 🤖 Generated with… line; never
add any AI-attribution footer. This overrides any default harness commit-trailer
behavior and applies everywhere a commit is made — executor per-task commits,
qa-automation, spec/plan commits, quick-mode, and any final commit. (The run-summary
credits line is separate and unaffected — it is printed to the user, not written into
git.)
Artifacts base (path resolution). Wherever this skill names a docs/hydraia/<sub>
path (specs, plans, qa, runs, .active-plan, .quick-approved, .run-complete,
.heartbeats, config), that path is
relative to the resolved artifacts base from the Storage gate — docs/hydraia/ in
the repo by default, or the external dir when chosen. Resolve the base once at the
gate and use it for the rest of the run; when dispatching a task to a sub-agent, pass
the absolute base so the executor writes its heartbeat and any artifacts to the right
place. The shown docs/hydraia/... paths below are the default; substitute the
resolved base when the user chose external storage.
Model guard. Check the model this session is running on. If it is NOT Opus 4.8
(e.g. Sonnet 5), print this once, then continue anyway — never block:
⚠️ Hydraia runs best with the main session on Opus 4.8. Opus does the
planning and both review passes, and is smart enough to delegate execution to
Sonnet 5 sub-agents on its own — you don't switch models yourself. Consider
restarting the session on Opus 4.8 for full quality. Continuing anyway.
Two modes: design dialogue, then continuous execution. The pipeline has a
conversational half and an autonomous half, split at the frozen plan.
- Phases 1–3 (think → design → plan) are INTERACTIVE. This is where design
happens, so interaction is expected — not a violation. Run brainstorming as a real
dialogue: ask clarifying questions (one at a time), propose 2–3 approaches with a
recommendation, present the design, and get the user's approval before writing the
spec. Do not compress this into a single question or skip it to "get to the code" —
a design reached without dialogue is the exact failure this pipeline exists to
prevent.
- Phases 4–6 (execute → review → verify) are CONTINUOUS. Once the plan is frozen,
run every remaining phase to completion without pausing. Never insert "should I
continue?" checkpoints between execution phases, never stop with the plan
half-executed. The ONLY permitted stop here is a genuine BLOCKER a sub-agent cannot
resolve — surface it, don't silently spin.
In short: pause to get the design right; never pause once you're building it.
(/hydraia:plan stops at the boundary — after Phase 3 — so you can review before the
autonomous half begins.)
No proportionality escape (non-negotiable). Token cost, change size, or "this
looks trivial / it's just a mirror of existing code" are NEVER reasons for YOU to
skip, compress, or inline a phase on your own. Whether a change is small enough to
skip the ceremony is the human's decision — never yours to make unilaterally. If
you are running the pipeline, run it in full: write the spec, write the plan,
delegate execution, run both review passes, run the real build/tests. A runtime gate
(hooks/gate.sh) enforces this — editing source code before Phase 3 freezes a plan
is blocked — so "compressing the ceremony" does not save effort, it just fails the
gate. The two sanctioned ways to skip are the human bypass and Quick-mode below.
Quick-mode (human-gated shortcut, opt-in per change). When a change is genuinely
trivial you MAY offer to skip the design ceremony — but the human decides, not you.
- Eligibility (ALL must hold, else do NOT offer — run the full pipeline): no new
business logic; no new file; small, localized diff; a mirror of behavior that
already exists and works; and it does NOT touch any security surface
(authN/authZ, PII/financial data, untrusted/external input, secrets). If security
surface is touched, Quick-mode is never eligible — the threat model is not
skippable.
- Ask, honestly. Call
AskUserQuestion once with a neutral pro/con:
"Found a simple, low-risk fix. Skip the spec/plan/double-review ceremony?" —
options Run full pipeline and Quick-mode. State plainly: pro — far fewer
tokens, faster; con — no spec-drive record, no double review. Do not lead with
the token savings or nudge toward skipping.
- On
Run full pipeline (or dismissal): run Phases 0–6 normally. Default to this
whenever unsure.
- On
Quick-mode: write the approval marker with a one-line reason
(printf 'reason\n' > docs/hydraia/.quick-approved), make the edit, then — always,
non-negotiable — run the project's real build/tests and confirm they pass, and
commit with a clear message. Remove the marker afterward
(rm -f docs/hydraia/.quick-approved). Never write this marker without an explicit
human "yes".
Model policy (already decided — do not surface to the user)
- This main session must run on Opus 4.8. It does all analysis, planning,
and both review passes. If the session is not on Opus, tell the user once:
"Hydraia's planning and review run best on Opus 4.8 — switch the session model
to Opus for full quality," then continue regardless.
- Execution runs on Sonnet 5, via the executor subagents (their model is
pinned in their agent definitions). You do not change your own model to execute;
you delegate.
Phase 0 — Context (always first)
Honor the effective config. Read docs/hydraia/config.json (per-repo) and
~/.config/hydraia/config.json (global) if present — the dashboard
(/hydraia:dashboard) writes these. Per-repo overrides global; an env var overrides
both. The hooks already enforce the deterministic toggles (agent caps, spec-drive
mode, telemetry, run summary, codegraph auto). YOU honor the prompt-level ones:
autoInstallDeps (false → skip the install offer below), reviewMode
(single → run only the Superpowers review pass in Phase 5, not both),
selfReviewPasses (Phase 3 plan self-review count), qaFunctional (false → skip
the qa-functional dispatch in Phase 3, drop the AC-coverage freeze check, and skip
qa-automation in Phases 4 and 6), e2eGate (false → skip the Phase 6 E2E gate),
docsSync (false → skip the Phase 6 docs-engineer sync), securityGates (false → the
human disabled threat model / security scans; note it, do not silently assume they
ran), pdfConversion (false → skip markitdown), cavemanInternal,
heartbeatStaleSecs (Phase 4 watchdog: seconds before a commit-less task is deemed
hung, default 300), maxTaskRetries (Phase 4 watchdog: auto re-push attempts before a
stall becomes a blocker, default 2). Defaults apply when a key is absent.
Binding constraints (read first). If docs/hydraia/constraints.md (or the external
artifacts base's constraints.md) exists, read it and treat every rule as BINDING for
this run — it is the repo's own "we don't do it this way" ledger and overrides default
behavior (never the safety gates). The SessionStart hook already injected it as context;
reading it here guarantees the full file is honored even if that injection was truncated.
- Dependency check + one-click install (do this once, silently if all present).
The user should never have to run install commands by hand. Detect what is
available:
command -v codegraph, command -v markitdown, command -v npm,
command -v pip (or pip3).
- The session-start hook already bootstrapped the code graph —
codegraph init the
first time in a project (initialize + index, in the background), or codegraph sync on later sessions. Do not ask the user to sync anything.
- If
codegraph is available, query the code graph to understand existing
structure, call sites, and blast radius before proposing anything — prefer graph
queries over blind file reads to save tokens. If the graph is unavailable
(codegraph not installed, or a first-run index still building), do NOT assume it
or invent results: fall back to targeted, minimal file reads for exactly the code
you need, and suggest /hydraia:doctor once so it is ready next time. codegraph
is an accelerator, never a hard requirement — the pipeline runs without it.
- If the request references a PDF (spec, ticket export, design doc), convert it
with markitdown first (
markitdown <file>), and work from the markdown. Never
dump raw PDF bytes into context.
Phase 1 — Think before coding (mandatory gate)
Apply the karpathy-guidelines skill. Do not write any code yet. Force the
analysis: restate the goal in your own words, list assumptions, name the simplest
approach that could work, and identify what could go wrong. Surgical changes over
broad rewrites. Ask clarifying questions if the goal is ambiguous — you are in the
interactive half of the pipeline (see "Two modes"), so a real back-and-forth here is
correct; the deeper design dialogue continues in Phase 2.
Phase 2 — Design + threat model (Superpowers, this session = Opus 4.8)
Use brainstorming, and run it as a real interactive dialogue (this is the
interactive half — see "Two modes"). Do the actual brainstorming flow: ask clarifying
questions one at a time (purpose, constraints, success criteria), propose 2–3
approaches with trade-offs and your recommendation, then present the design and get
the user's approval. Do NOT jump straight from the prompt to a spec or to code —
design without dialogue is the failure this phase exists to prevent.
This phase produces a written design spec — a real file, not inline reasoning.
Skipping the written spec, or collapsing design into the plan, is a violation of the
pipeline. Be exhaustive; explore alternatives and trade-offs; anchor every decision to
what the code graph showed in Phase 0.
Write the spec to a file (mandatory artifact). Save the design spec to
docs/hydraia/specs/YYYY-MM-DD-<topic>-design.md and commit it. Phase 3 MUST NOT
start until this file exists. The spec MUST contain, at minimum:
- Goal — one or two sentences on what this builds and why.
- Chosen approach + rejected alternatives — the 2–3 approaches considered, their
trade-offs, and why the chosen one won. Not just the winner.
- Code-graph anchors — the existing structure, call sites, and blast radius from
Phase 0 that the design must respect (name the real symbols/files).
- Global constraints — version floors, naming/copy rules, platform limits, and
any acceptance criteria, with exact values.
- Threat model + mitigations — see below; folded in so they become plan tasks.
- UX / visual direction (mandatory when the change creates or touches UI) — the
chosen style, colour palette, type scale, spacing/layout system, key interaction
states, and the accessibility floor, decided HERE via ui-ux-pro-max — not left
to markup-writing time. See the frontend-design rule below.
Design approval (interactive gate, mandatory). Present the design to the user and
get their approval BEFORE writing the spec file — this is brainstorming's HARD-GATE
and it is honored, not skipped. Only pausing to "get to the code faster" defeats the
pipeline. The written spec + the adversarial self-review below are in addition to
the human approval, not a replacement for it. (Note: this human gate lives entirely in
the interactive half; once the plan is frozen and Phase 4 begins, the pipeline runs
autonomously to the end.)
Architecture advice (greenfield / from-scratch work). When the request builds a
new system, service, or module from scratch — not a surgical change to existing
code — first dispatch the architecture agents to propose the shape before the spec:
architect (system design, scalability, trade-offs) and code-architect
(concrete file/interface/data-flow blueprint anchored to existing patterns). If the
work spans multiple services or a monolith split, also use microservices-architect
(bounded contexts, communication patterns, resilience). Fold the chosen architecture
- its rejected alternatives (and why) into the spec. For a FULL greenfield run
(routed by Phase -1 or
/hydraia:architect), the greenfield-architect skill
drives this entire step — elicitation, these same agents, the api-design contract,
and ADRs. Skip this for small changes to existing code — it is for genuinely new
construction.
Design adversarial loop (mandatory, before freezing the spec). After the spec +
threat model are drafted, run ONE adversarial pass against them: take the opposing
view and try to break the design — unstated assumptions, simpler approach ignored,
scalability/failure modes, security holes the threat model missed, spec requirements
that contradict each other. Revise the spec to close every real gap the pass finds.
This is the design-time analogue of the Phase 5 double review: catching a design
flaw here is an order of magnitude cheaper than at review time. One pass only — do
not loop forever.
Threat model (mandatory, before planning): using the code graph's blast
radius, enumerate the attack surface this change introduces or touches —
untrusted inputs, authN/authZ boundaries, PII/financial data handled, external
calls, and secrets. Note the OWASP categories at risk. Bake the mitigations into
the spec so they become plan tasks, not afterthoughts. Catching a design-level
security flaw here is far cheaper than at review time.
Frontend design (HARD GATE when UI is in scope — a precondition for freezing the
spec, not a suggestion): visual quality is decided at design time, not patched on at
markup-writing time — a landing or screen that reads "flat / generic" was already flat
in the spec. This is the ONLY point in the whole pipeline where ui-ux-pro-max runs:
the executor subagents in Phase 4 have no Skill tool and cannot invoke it, so if you do
not run it HERE, nothing downstream will — the front end ships generic. That is the
exact failure this gate exists to stop.
So when this change creates or touches any UI, you (the interactive main thread, which
DOES have the Skill tool) MUST invoke ui-ux-pro-max during design and record its
output in the spec's UX / visual direction section: the chosen style, palette, type
scale, spacing/layout system, key component and interaction states, and the WCAG
accessibility floor — concrete values, not adjectives (exact hex, named font pairing,
spacing scale). Enforcement: the spec MUST NOT be frozen and Phase 3 MUST NOT start
until this section exists and is filled from ui-ux-pro-max output. A spec that reaches
Phase 3 with an empty or hand-waved UX / visual direction section for in-scope UI is a
gate failure — stop and run the skill. Phase 3 inlines this section verbatim into every
UI task and Phase 4 implements it exactly. (Purely back-end / non-visual changes skip
this gate entirely.)
Phase 3 — Plan + self-review loop (the "todo bien hechesito" gate)
Precondition: the Phase 2 spec file must already exist. If it does not, go
back and write it — do not plan without a spec. UI gate: if the change touches
any UI, the spec's UX / visual direction section must already be filled from
ui-ux-pro-max output (see the Phase 2 Frontend-design hard gate). If it is empty or
hand-waved, stop and run ui-ux-pro-max now — do not plan UI tasks against a missing
visual system, because Phase 4 executors cannot recover it (they have no Skill tool).
Use writing-plans to write the implementation plan, saved to
docs/hydraia/plans/YYYY-MM-DD-<feature>.md. Follow the writing-plans structure
in FULL — a thin plan is a failed plan. The plan MUST contain:
- A header: Goal, Architecture (2–3 sentences), Tech Stack, the path of the
Phase 2 spec it derives from, and a Global Constraints block (exact values
copied from the spec).
- A File Structure map: every file to be created or modified and its single
responsibility, before the tasks.
- Right-sized tasks: each task is a coherent, independently shippable unit of
work — not one micro-edit. Consolidate trivially-related edits into one task.
A plan with dozens upon dozens of atomic tasks will fan out into just as many
sub-agents in Phase 4 and multiply token cost; the agent-budget cap
(
HYDRAIA_MAX_AGENTS, default 30) will hard-stop it. Aim well under that
ceiling by design.
- Per-task blocks, each with:
Files: — Create: exact/path, Modify: exact/path:line-range,
Test: exact/path. Exact paths, never "the relevant file".
Interfaces: — Consumes (signatures it uses from earlier tasks) and Produces
(exact function names, parameter and return types later tasks rely on).
- Bite-sized TDD steps (2–5 min each): write failing test → run it, expect
fail → minimal implementation → run, expect pass → commit. With the exact
test command and expected result per step.
Assume the implementer has zero prior context and cannot see the spec or your
session — everything they need is in their task block. Write to the weakest
plausible executor: the plan must be detailed enough that a cheaper or weaker
model (Sonnet 5, Haiku, or an external agent like Codex or Gemini) can implement
each task correctly with no judgment calls left open — exact paths, exact
signatures, exact test commands. If a task would require the executor to infer
intent or make a design decision, it is under-specified — push that decision up
into the plan. This is where token cost is won or lost: a fully-specified task
executes in one shot on a cheap model; an under-specified one forces a re-dispatch
or an Opus rescue, which is the expensive path the plan exists to avoid.
Literal content, never a description of it. A task that creates a file MUST
embed the file's FULL verbatim content in a code block — never "create the file
with the appropriate content". A task that edits a file MUST give the exact
old_string → new_string (or a unique quoted anchor + the exact text to
insert) — never "add error handling here". The executor copies; it does not
compose.
Never point at the spec (or any other document/code) for content the executor
must produce. This is the single most common self-containment failure. A task
that says "implement per spec §3", "follow the skeleton in the design",
"match the existing User validation", or "see the spec for the schema" is NOT
self-contained — the executor may be a context-less cheap model (Gemini Flash,
Codex, Haiku) that CANNOT and WILL NOT open the spec, so it guesses, truncates,
or invents. Inline the actual content into the task, even though it duplicates the
spec. Here DRY yields to self-containment: the spec holds design rationale;
the task holds everything needed to execute, repeated in full. This is exactly why
the plan is a portable hand-off artifact ("execute anywhere" — Codex, Gemini, a
second session): portability only holds if every task carries its own content. A
runtime hook (hooks/plancheck.sh) scans the frozen plan's task bodies for these
reference smells and BLOCKS the gate-arm if it finds any — so a referencing plan
cannot reach execution.
State each task's execution environment — assume nothing from context. A cheap
executor does not know your repo's toolchain. Every task that runs anything gives
the EXACT command (not "run the tests" but pnpm vitest run src/x.test.ts), the
working directory, any dependency/env-var/service precondition, and — if it depends
on an earlier task's output — names that task and the files it must find already
present. Out-of-order or standalone execution must fail loudly, not silently guess.
Verify completeness of large literals, not just existence. A cheap model can
truncate a long verbatim block. For any sizable inlined file, the task's
verification confirms it landed WHOLE — e.g. wc -l file → N or a grep for the
exact last line — not merely that the file exists.
Anchor edits by unique quoted text, never by line number alone. Line numbers
drift as earlier tasks change the file; every Modify must carry a unique text
anchor the executor can match exactly. State this in the task.
Every UI task carries its visual direction inline. A task that creates or
changes UI MUST embed the concrete decisions from the Phase 2 UX / visual
direction section — the exact style, palette values, type scale, spacing,
component/interaction states it must produce, and the WCAG accessibility floor to
verify. The executor implements these values directly and does NOT invoke
ui-ux-pro-max (it has no Skill tool); the inlined direction IS the visual system.
Because Phase 4 runs autonomously on a weak executor, "make it look good" or
"see the spec for styling" is NOT self-contained — the executor cannot open the
spec and will fall back to generic defaults. Inline the values, per the
self-containment rule above. A UI task with no visual direction in its body is
under-specified and produces flat output.
Every task carries a runnable verification with its expected output — not
only TDD steps. Config, docs, and scaffolding tasks each end with an exact
command and the exact output that proves the task landed (e.g.
grep -c X file → 2). A task with no way to self-check is under-specified.
QA cases (parallel, when qaFunctional is on) — ALWAYS a committed document,
NEVER inline. Functional QA is produced as a reviewable artifact, not performed
in your head. While writing the plan, dispatch the qa-functional agent (Sonnet)
with: the spec path, the story artifact path if one exists, and the output path
docs/hydraia/qa/YYYY-MM-DD-<slug>-cases.md. It returns Given/When/Then cases plus
a traceability matrix (AC → Cases → Test ref, refs start as pending) and a GAPS
section. Non-negotiable rules:
- You (the main agent) MUST NOT write the test cases inline or "apply QA
yourself." Dispatch
qa-functional; the value is a durable document the human
can read, review, and upload to the repo — not ephemeral reasoning.
- The document is always produced and committed. Even when the run has no
formal acceptance criteria, instruct
qa-functional to derive implicit ACs from
the spec's behavior so a case doc still results. After it returns, commit the
file (git add docs/hydraia/qa/<file> && git commit) so it lands in the repo.
- Surface every GAP to the human BEFORE freezing the plan — gaps are design
questions, never things to guess around.
- The plan must contain the test tasks that implement these cases (see the Phase 4
QA automation rule). The frozen-plan condition below includes "the QA case doc
exists and is committed."
Self-review the plan (always TWO passes):
- Pass A: critique your own plan hard. The Haiku test — apply it to every
task: could a model with zero context and no permission to make decisions
produce EXACTLY the intended result from this task block alone? If any step
needs the executor to infer, deduce, or invent, the task is under-specified —
reject and push the decision up into the plan. Concretely, reject and revise
if ANY task:
- lacks exact
Files: paths, Interfaces:, or independently testable steps,
or says vaguely "edit the code / update the component";
- describes content instead of embedding it — a create-file task without the
full verbatim file, or an edit task without the exact
old_string→new_string
/ quoted anchor + literal insert;
- references the spec, another document, or other code for content it must
produce — "follow spec §X", "see the design", "as in the spec", "match the
existing X" — instead of inlining that content into the task (the
plancheck.sh hook blocks the gate-arm on these, but catch them here first);
- runs a command without the exact invocation ("run the tests" with no
command/dir), or assumes an earlier task's output without naming it, or
lacks a completeness check on a large inlined literal (existence only, no
line-count / last-line assert);
- anchors an edit to a bare line number instead of a unique quoted string;
- lacks a runnable verification with expected output (not just TDD tasks —
config/docs/scaffolding too);
- contains a placeholder —
TODO, TBD, ..., "similar to Task N",
"add appropriate X", "handle edge cases" — repeat the real content instead;
- references a name (symbol, file, agent, skill) that no earlier task defines
and does not already exist, or uses an inconsistent name/signature across
tasks (
foo() in Task 3 vs fooBar() in Task 7 is a bug).
When qaFunctional is on, also reject if any acceptance criterion lacks BOTH a
QA case (in the qa-functional doc) and an implementing task in the plan. Also
hunt gaps, hidden coupling (check the graph), missing tests, unstated
assumptions, over-broad changes, and drift from the spec. Revise.
- Pass B: run a second full pass regardless — even if Pass A found nothing,
re-audit the whole plan against the same checklist with fresh eyes (Pass A can
miss on the first read, and its own revisions introduce new gaps). Revise again
if it finds anything.
- Both passes always run. Stop after the two even if minor nits remain — do not
loop forever.
The plan is frozen only after the self-review loop converges AND every task has
file-level detail AND — when qaFunctional is on — the QA case doc exists and is
committed AND (when ACs exist) every AC maps to at least one QA case and one plan
task. If it does not, it is not frozen.
Open a run log. Create docs/hydraia/runs/YYYY-MM-DD-HHMM-<feature>.md with
the original request, the plan path, and a phase checklist
(- [ ] Phase 0 … - [ ] Phase 6). Update it at each phase boundary — check
the box as each phase completes — so an interrupted run leaves a durable trail
of where it stopped. /hydraia:resume reads this file.
Arm the spec-drive gate. Only after BOTH the Phase 2 spec file and the frozen
plan exist (and NOT before), write the frozen plan's path into the marker file
docs/hydraia/.active-plan
(e.g. printf '%s\n' "docs/hydraia/plans/<file>.md" > docs/hydraia/.active-plan).
The gate.sh hook blocks all source-code edits until this marker exists — which
is exactly why no code can be written before Phases 2–3 complete. Do not arm the
marker if the spec is missing. (/hydraia:plan stops here and does NOT arm the
marker — planning must never authorize edits.) A second hook
(plancheck.sh) fires on this arm command and scans the plan's task bodies for
reference smells ("follow spec §X", "see the design", etc.); if the plan is not
self-contained it BLOCKS the arm — so a plan that would fail on a cheap executor
cannot reach Phase 4. If it blocks, inline the referenced content and re-arm.
Run-controls picker (LAST interactive step — the human sets the depth before the
autonomous half runs). The autonomous half (Phases 4–6) must not pause, so ask
here, once, via a single AskUserQuestion with these two questions:
(a) Review depth — how much of the Phase 5/6 ceremony to run on this change:
- Full — double review, all matched language reviewers, security gates, QA,
E2E, docs sync. (Default; pick when unsure.)
- Lite — a single review pass, skip the non-core language reviewers and the
docs-sync step; QA and the E2E gate still run per the repo's surface.
- Custom — then a second
AskUserQuestion (multiSelect) over the OPTIONAL
stages only: 2nd review pass, language/framework reviewers,
type-design / performance reviewers, docs sync, extra OWASP pass.
Security floor (never offered as removable): regardless of profile,
security-scan, code-reviewer, silent-failure-hunter, security-reviewer, and
one hydraia-reviewer pass ALWAYS run. The picker cannot switch these off — only
the human's explicit securityGates=false config can, which is a separate act.
(b) Closing summary depth — Brief (compact box) or Detailed (adds what
shipped, per-agent-type counts, main-vs-sub token split, per-model in/out/cache).
Record both answers in the run log and honor them in Phases 5–6. On dismissal,
default to Full + Brief. This is the only question in the autonomous half's
run-up — after it, Phases 4–6 run to completion without pausing.
Phase 4 — Execution (delegated → Sonnet 5)
Use subagent-driven-development. Dispatch a fresh hydraia-executor subagent
per task (these run on Sonnet 5). Give each exactly the context it needs from the
plan and the graph — never your session history. Execute all tasks continuously.
TDD where the plan calls for it. Commit frequently.
Tag each executor dispatch's description with a machine-readable [task:<slug>] marker
(the same <slug> the executor uses for its heartbeat file). The circuit-breaker hook
(hooks/agents.sh) reads this tag to count per-task attempts; without it the breaker
falls back to a description hash and still counts, but the tag makes escalation precise.
Dispatch in bounded waves — never fan out the whole plan at once. Each subagent
loads its own context, so N parallel agents multiply token cost by ~N. Send at most
HYDRAIA_MAX_CONCURRENT (default 6) executors at a time; as they finish, send the
next wave. A whole run is also capped at HYDRAIA_MAX_AGENTS (default 30) total
dispatches. These limits are enforced at runtime by the agent-budget hook
(hooks/agents.sh) — a Task call past the cap is BLOCKED, not throttled silently,
so respect the waves rather than firing 100 tasks and retrying blocked ones. If a
plan truly needs more than the ceiling, that is the human's call to raise
(`export HYDRAIA_MAX_AGENTS=
…(truncated)
1---2name: hydraia3description: Use whenever the user asks to build, add, implement, or change a feature or functionality — or brings a user story or ticket to analyze, reports a bug or unexpected behavior, asks for a branch review, or wants a new app or service designed from scratch. Phase -1 triages the intent and routes it. Runs the complete non-negotiable development pipeline end to end — deep analysis and planning, sub-agent execution, and a double code-review loop — without asking the user which model, skill, or step to use. This is the default way features get built.4---56# Hydraia — Agentic Development Pipeline78This skill defines the ONLY approved way to build a feature. Run every phase, in9order, automatically. **Never ask the user which model, skill, or reviewer to10use — those decisions are already made here.** Never skip a phase. Never pause11for "should I continue?" between phases.1213Announce once at the start: "Running the Hydraia pipeline." Then proceed silently14through the phases, narrating at most one short line per phase.1516## Phase -1 — Intent triage (before everything)1718Classify the request into exactly ONE route before any other guard runs.19Explicit commands skip classification and force their route20(`/hydraia:feature` → feature · `/hydraia:story` → user story ·21`/hydraia:plan` → feature, stopping after Phase 3 · `/hydraia:review` →22review · `/hydraia:perf` → performance · `/hydraia:db` → performance,23DB-shaped · `/hydraia:architect` → greenfield · `/hydraia:e2e` → E2E suite ·24`/hydraia:devops` → DevOps config · `/hydraia:observability` → instrumentation ·25`/hydraia:docs` → docs sync). Plain-language requests are classified by signals:2627| Intent | Signals | Route |28|---|---|---|29| Feature / change | "add / build / implement / change X" | Phases 0–6 as written below |30| User story | "As a … I want … so that …", acceptance-criteria lists, ticket text or a Jira/PDF export | Run the **story-analysis** skill FIRST (interactive PO pass → story artifact with numbered ACs), then Phases 0–3 with that artifact as the primary design input; continue into 4–6 only when the entry point runs the full pipeline |31| Bug / unexpected behavior | "fails / broken / error / regression / used to work" | **systematic-debugging** skill first — root cause before any fix. Enter the pipeline only if the fix requires new design/behavior; a surgical fix proceeds under that skill's rules (the spec-drive gate still applies) |32| Performance / DB symptom | "slow / timeout / high CPU / memory climbing / query takes …" | Run the **performance-tuning** skill flow: measured baseline FIRST, dispatch `perf-engineer` (and `db-performance-tuner` when the symptom is DB-shaped, per **db-optimization**), spec carries baseline + numeric target, Phase 6 re-measures against it |33| New app / greenfield | "from scratch / new app / new service / greenfield" | Run the **greenfield-architect** skill: elicitation → architecture proposals (`architect` + `code-architect`, microservices only with evidence) → confirmed stack → **api-design** contract when an API exists → **adr** records per decision — then Phases 0–6 |34| Review / audit | "review / audit this branch / this PR" | Phases 5–6 only |35| Ambiguous | none of the above clearly | `AskUserQuestion` listing the plausible routes — never assume |3637Triage is ONE classification step, not a conversation — at most a single38routing question, and only when genuinely ambiguous. Route chosen, proceed39to the start-of-run guards below.4041### Autonomy tier + cost (after route, before the guards)4243Once the route is chosen, estimate a **tier** from cheap signals and show a cost44estimate. This maps to hydraia's EXISTING controls — it adds no new enforcement axis.4546**Early-exit (noop) first.** If the route's target is empty, do not spin the pipeline:47- `review` / `graph`: if `git diff --name-only` against the branch point is empty (or the48 named target does not exist), report "nothing to review", drop the run-complete marker49 (`printf 'brief\n' > <base>/.run-complete`), and stop. No Phases 0–6.50- `perf` / `db`: if the named symptom target is absent or already within a stated51 threshold, report and stop.5253**Tier (feature-shaped routes).** Classify from: likely files touched, overlap with the54`gate.yaml` denylist (risk), new-logic vs mechanical, presence of UI surfaces:55- **Tier S (trivial):** no new logic, no new file, no risk-path, ≤ ~2 files → propose56 quick-mode (the `.quick-approved` path) or a Lite review. Minimal ceremony.57- **Tier M (standard):** default — full pipeline, Full review.58- **Tier L (large / risky):** many files, risk-path overlap, or a new service → full59 pipeline + all gates; the human may raise the agent ceiling.6061**Cost estimate.** Read `patterns/cost.yaml` for the route × tier and state a one-line62token estimate (e.g. "≈200k tokens, Tier S"). It is a rough anchor, not a promise.6364**Confirm once.** Present the tier + estimate in a single `AskUserQuestion`,65pre-selecting the review depth for the Phase-3 run-controls picker. The human confirms66with one tap or overrides. Honor `autoTier` config (`off` → always Tier M, today's67behavior). A tier NEVER removes the security floor (Phase 5 mandatory reviewers, threat68model) — Tier S only trims optional ceremony, exactly as quick-mode already does.6970## Start-of-run guards (before Phase 0)7172**Language gate (first action, before anything else).** Call the73`AskUserQuestion` tool once to ask which language the user wants **replies** in —74options: `English` and `Español`. Use the answer for all user-facing communication75for the rest of the run: narration, the Phase-1 clarifying question, review76findings, and the final summary. If the user dismisses the question, default to the77language they wrote their request in. This choice does NOT change code, commit78messages, spec/plan files, or the credits line — those stay as-is (English,79portable). Ask this exactly once per run; `/hydraia:resume` inherits the prior80run's choice if the run log records it, otherwise re-asks.8182**Storage & commit gate (second action, right after the Language gate).** Two83`AskUserQuestion` prompts, asked once per run (like the language gate). Do NOT84recommend an option — the user chooses; these are privacy/workflow decisions, not85quality ones.86871. **Artifacts location** — "Where should Hydraia store its artifacts (specs, plans,88 QA, run logs, and pipeline state)?"89 - `In the repo` → `<repo>/docs/hydraia/` (tracked by git — the default).90 - `Outside the repo` → `~/.config/hydraia/artifacts/<repo-slug>/` (on this machine,91 never committed, no `.gitignore` edits). `<repo-slug>` = repo dir basename + `-`92 + the first 6 hex of a hash of the absolute repo root.932. **Auto-commit** — "Auto-commit each task as Hydraia goes?"94 - `Yes` → commit per task (the default).95 - `No` → executors do NOT commit; all changes are left in the working tree for you96 to commit as you like.9798After the answers: persist both to the GLOBAL config `~/.config/hydraia/config.json`99under `repos["<absolute repo root>"]` — do NOT hand-edit that JSON. Use the100`hy_config_set` helper in `hooks/config.sh`, which merges into the file atomically,101preserving every other repo and key:102103```bash104bash -c '. "$CLAUDE_PLUGIN_ROOT/hooks/config.sh"105hy_config_set "<absolute repo root>" artifactsDir "<docs/hydraia | absolute external path>"106hy_config_set "<absolute repo root>" autoCommit "<true|false>"'107```108109Pass `artifactsDir docs/hydraia` (or skip it) for in-repo; the absolute external path110otherwise. Then create the external dir (with `specs/ plans/ qa/ runs/`) if chosen, and111use the resolved absolute base as **the artifacts base** for the whole run (see112*Artifacts base* below). If the user dismisses either question, default to in-repo + auto-commit113ON (behavior identical to prior versions). `/hydraia:resume` inherits both from the114run log if recorded, otherwise re-asks. The hooks read the same choice via115`hy_artifacts_dir` / `hy_repo_config` in `hooks/config.sh`, so the gate, agent caps,116plan-check, and summary all resolve to the same base — in-repo or external.117118**Commit attribution (hard rule, every commit this pipeline makes).** Hydraia commits119carry a clean, conventional message and NOTHING else. NEVER add a `Co-Authored-By`120trailer for Claude, Hydraia, or any AI; never add a `🤖 Generated with…` line; never121add any AI-attribution footer. This overrides any default harness commit-trailer122behavior and applies everywhere a commit is made — executor per-task commits,123qa-automation, spec/plan commits, quick-mode, and any final commit. (The run-summary124credits line is separate and unaffected — it is printed to the user, not written into125git.)126127**Artifacts base (path resolution).** Wherever this skill names a `docs/hydraia/<sub>`128path (specs, plans, qa, runs, `.active-plan`, `.quick-approved`, `.run-complete`,129`.heartbeats`, config), that path is130relative to the **resolved artifacts base** from the Storage gate — `docs/hydraia/` in131the repo by default, or the external dir when chosen. Resolve the base once at the132gate and use it for the rest of the run; when dispatching a task to a sub-agent, pass133the absolute base so the executor writes its heartbeat and any artifacts to the right134place. The shown `docs/hydraia/...` paths below are the default; substitute the135resolved base when the user chose external storage.136137**Model guard.** Check the model this session is running on. If it is NOT Opus 4.8138(e.g. Sonnet 5), print this once, then continue anyway — never block:139140> ⚠️ Hydraia runs best with the **main session on Opus 4.8**. Opus does the141> planning and both review passes, and is smart enough to delegate execution to142> Sonnet 5 sub-agents on its own — you don't switch models yourself. Consider143> restarting the session on Opus 4.8 for full quality. Continuing anyway.144145**Two modes: design dialogue, then continuous execution.** The pipeline has a146conversational half and an autonomous half, split at the frozen plan.147148- **Phases 1–3 (think → design → plan) are INTERACTIVE.** This is where design149 happens, so interaction is expected — not a violation. Run brainstorming as a real150 dialogue: ask clarifying questions (one at a time), propose 2–3 approaches with a151 recommendation, present the design, and get the user's approval before writing the152 spec. Do not compress this into a single question or skip it to "get to the code" —153 a design reached without dialogue is the exact failure this pipeline exists to154 prevent.155- **Phases 4–6 (execute → review → verify) are CONTINUOUS.** Once the plan is frozen,156 run every remaining phase to completion **without pausing**. Never insert "should I157 continue?" checkpoints between execution phases, never stop with the plan158 half-executed. The ONLY permitted stop here is a genuine BLOCKER a sub-agent cannot159 resolve — surface it, don't silently spin.160161In short: **pause to get the design right; never pause once you're building it.**162(`/hydraia:plan` stops at the boundary — after Phase 3 — so you can review before the163autonomous half begins.)164165**No proportionality escape (non-negotiable).** Token cost, change size, or "this166looks trivial / it's just a mirror of existing code" are NEVER reasons for YOU to167skip, compress, or inline a phase on your own. Whether a change is small enough to168skip the ceremony is the **human's** decision — never yours to make unilaterally. If169you are running the pipeline, run it in full: write the spec, write the plan,170delegate execution, run both review passes, run the real build/tests. A runtime gate171(`hooks/gate.sh`) enforces this — editing source code before Phase 3 freezes a plan172is blocked — so "compressing the ceremony" does not save effort, it just fails the173gate. The two sanctioned ways to skip are the human bypass and Quick-mode below.174175**Quick-mode (human-gated shortcut, opt-in per change).** When a change is genuinely176trivial you MAY *offer* to skip the design ceremony — but the human decides, not you.177178- **Eligibility (ALL must hold, else do NOT offer — run the full pipeline):** no new179 business logic; no new file; small, localized diff; a mirror of behavior that180 already exists and works; and it does **NOT** touch any security surface181 (authN/authZ, PII/financial data, untrusted/external input, secrets). If security182 surface is touched, Quick-mode is never eligible — the threat model is not183 skippable.184- **Ask, honestly.** Call `AskUserQuestion` once with a neutral pro/con:185 *"Found a simple, low-risk fix. Skip the spec/plan/double-review ceremony?"* —186 options `Run full pipeline` and `Quick-mode`. State plainly: **pro** — far fewer187 tokens, faster; **con** — no spec-drive record, no double review. Do not lead with188 the token savings or nudge toward skipping.189- **On `Run full pipeline` (or dismissal):** run Phases 0–6 normally. Default to this190 whenever unsure.191- **On `Quick-mode`:** write the approval marker with a one-line reason192 (`printf 'reason\n' > docs/hydraia/.quick-approved`), make the edit, then — always,193 non-negotiable — **run the project's real build/tests** and confirm they pass, and194 **commit with a clear message**. Remove the marker afterward195 (`rm -f docs/hydraia/.quick-approved`). Never write this marker without an explicit196 human "yes".197198## Model policy (already decided — do not surface to the user)199200- **This main session must run on Opus 4.8.** It does all analysis, planning,201 and both review passes. If the session is not on Opus, tell the user once:202 "Hydraia's planning and review run best on Opus 4.8 — switch the session model203 to Opus for full quality," then continue regardless.204- **Execution runs on Sonnet 5**, via the executor subagents (their model is205 pinned in their agent definitions). You do not change your own model to execute;206 you delegate.207208## Phase 0 — Context (always first)209210**Honor the effective config.** Read `docs/hydraia/config.json` (per-repo) and211`~/.config/hydraia/config.json` (global) if present — the dashboard212(`/hydraia:dashboard`) writes these. Per-repo overrides global; an env var overrides213both. The hooks already enforce the deterministic toggles (agent caps, spec-drive214mode, telemetry, run summary, codegraph auto). YOU honor the prompt-level ones:215`autoInstallDeps` (false → skip the install offer below), `reviewMode`216(`single` → run only the Superpowers review pass in Phase 5, not both),217`selfReviewPasses` (Phase 3 plan self-review count), `qaFunctional` (false → skip218the qa-functional dispatch in Phase 3, drop the AC-coverage freeze check, and skip219qa-automation in Phases 4 and 6), `e2eGate` (false → skip the Phase 6 E2E gate),220`docsSync` (false → skip the Phase 6 docs-engineer sync), `securityGates` (false → the221human disabled threat model / security scans; note it, do not silently assume they222ran), `pdfConversion` (false → skip markitdown), `cavemanInternal`,223`heartbeatStaleSecs` (Phase 4 watchdog: seconds before a commit-less task is deemed224hung, default 300), `maxTaskRetries` (Phase 4 watchdog: auto re-push attempts before a225stall becomes a blocker, default 2). Defaults apply when a key is absent.226227**Binding constraints (read first).** If `docs/hydraia/constraints.md` (or the external228artifacts base's `constraints.md`) exists, read it and treat every rule as BINDING for229this run — it is the repo's own "we don't do it this way" ledger and overrides default230behavior (never the safety gates). The SessionStart hook already injected it as context;231reading it here guarantees the full file is honored even if that injection was truncated.2322330. **Dependency check + one-click install (do this once, silently if all present).**234 The user should never have to run install commands by hand. Detect what is235 available: `command -v codegraph`, `command -v markitdown`, `command -v npm`,236 `command -v pip` (or `pip3`).237 - If **all present** → say nothing, continue.238 - If a **managed** binary is missing but its installer is present (codegraph needs239 `npm`, markitdown needs `pip`), offer to install it **inline, once**, via240 `AskUserQuestion` — e.g. "Hydraia works best with codegraph (fast graph queries)241 and markitdown (PDF→markdown). Install now?" with options *Install now* /242 *Skip this run*. On **Install**, run the bundled installer (single source of243 truth) — resolve its path from the session cache and run it:244 ```245 ROOT="$(cat "${HOME}/.cache/hydraia/plugin-root" 2>/dev/null)"246 [ -n "$ROOT" ] || ROOT="$(ls -d "${HOME}/.claude/plugins/cache/hydraia/hydraia/"*/ 2>/dev/null | sort -V | tail -1)"247 "$ROOT/hooks/doctor.sh" --install --yes248 ```249 The installer is non-interactive and never uses sudo (no hangs). Its **last250 line is machine-readable** — `RESULT codegraph=<state> markitdown=<state>` where251 state is `ok` (usable now), `installed` (present, ready in a NEW session after a252 PATH refresh), or `missing` (failed — the installer printed the exact recovery253 command above it). **Read that line and act on it:**254 - `ok` → use the tool this run.255 - `installed` → tell the user it is ready next session; treat as unavailable for256 THIS run (degrade to file reads / skip PDF conversion). Do NOT re-offer.257 - `missing` → surface the one recovery command the installer printed. Do NOT258 loop or retry the install.259 On **Skip**, continue and do not ask again this run.260 - If an **installer itself** is missing (`npm`/`pip` absent, or `node`/`python3`/261 `git`), these are system runtimes a plugin must not auto-install — run262 `"$ROOT/hooks/doctor.sh" --check` and show the user its per-OS install hints263 (`brew`/`apt`/`dnf`/`winget`), then continue degraded. Never block the pipeline264 on a missing dependency.2651. The session-start hook already bootstrapped the code graph — `codegraph init` the266 first time in a project (initialize + index, in the background), or `codegraph267 sync` on later sessions. Do not ask the user to sync anything.2682. If `codegraph` is available, query the code graph to understand existing269 structure, call sites, and blast radius before proposing anything — prefer graph270 queries over blind file reads to save tokens. If the graph is unavailable271 (codegraph not installed, or a first-run index still building), do NOT assume it272 or invent results: fall back to targeted, minimal file reads for exactly the code273 you need, and suggest `/hydraia:doctor` once so it is ready next time. codegraph274 is an accelerator, never a hard requirement — the pipeline runs without it.2753. If the request references a PDF (spec, ticket export, design doc), convert it276 with markitdown first (`markitdown <file>`), and work from the markdown. Never277 dump raw PDF bytes into context.278279## Phase 1 — Think before coding (mandatory gate)280281Apply the **karpathy-guidelines** skill. Do not write any code yet. Force the282analysis: restate the goal in your own words, list assumptions, name the simplest283approach that could work, and identify what could go wrong. Surgical changes over284broad rewrites. Ask clarifying questions if the goal is ambiguous — you are in the285interactive half of the pipeline (see "Two modes"), so a real back-and-forth here is286correct; the deeper design dialogue continues in Phase 2.287288## Phase 2 — Design + threat model (Superpowers, this session = Opus 4.8)289290Use **brainstorming**, and run it as a **real interactive dialogue** (this is the291interactive half — see "Two modes"). Do the actual brainstorming flow: ask clarifying292questions one at a time (purpose, constraints, success criteria), propose 2–3293approaches with trade-offs and your recommendation, then present the design and get294the user's approval. Do NOT jump straight from the prompt to a spec or to code —295design without dialogue is the failure this phase exists to prevent.296297This phase produces a **written design spec — a real file, not inline reasoning**.298Skipping the written spec, or collapsing design into the plan, is a violation of the299pipeline. Be exhaustive; explore alternatives and trade-offs; anchor every decision to300what the code graph showed in Phase 0.301302**Write the spec to a file (mandatory artifact).** Save the design spec to303`docs/hydraia/specs/YYYY-MM-DD-<topic>-design.md` and commit it. Phase 3 MUST NOT304start until this file exists. The spec MUST contain, at minimum:305306- **Goal** — one or two sentences on what this builds and why.307- **Chosen approach + rejected alternatives** — the 2–3 approaches considered, their308 trade-offs, and why the chosen one won. Not just the winner.309- **Code-graph anchors** — the existing structure, call sites, and blast radius from310 Phase 0 that the design must respect (name the real symbols/files).311- **Global constraints** — version floors, naming/copy rules, platform limits, and312 any acceptance criteria, with exact values.313- **Threat model + mitigations** — see below; folded in so they become plan tasks.314- **UX / visual direction** (mandatory when the change creates or touches UI) — the315 chosen style, colour palette, type scale, spacing/layout system, key interaction316 states, and the accessibility floor, decided HERE via **ui-ux-pro-max** — not left317 to markup-writing time. See the frontend-design rule below.318319**Design approval (interactive gate, mandatory).** Present the design to the user and320get their approval BEFORE writing the spec file — this is `brainstorming`'s HARD-GATE321and it is honored, not skipped. Only pausing to "get to the code faster" defeats the322pipeline. The written spec + the adversarial self-review below are *in addition to*323the human approval, not a replacement for it. (Note: this human gate lives entirely in324the interactive half; once the plan is frozen and Phase 4 begins, the pipeline runs325autonomously to the end.)326327**Architecture advice (greenfield / from-scratch work).** When the request builds a328new system, service, or module from scratch — not a surgical change to existing329code — first dispatch the architecture agents to propose the shape before the spec:330`architect` (system design, scalability, trade-offs) and `code-architect`331(concrete file/interface/data-flow blueprint anchored to existing patterns). If the332work spans multiple services or a monolith split, also use **microservices-architect**333(bounded contexts, communication patterns, resilience). Fold the chosen architecture334+ its rejected alternatives (and why) into the spec. For a FULL greenfield run335(routed by Phase -1 or `/hydraia:architect`), the **greenfield-architect** skill336drives this entire step — elicitation, these same agents, the api-design contract,337and ADRs. Skip this for small changes to existing code — it is for genuinely new338construction.339340**Design adversarial loop (mandatory, before freezing the spec).** After the spec +341threat model are drafted, run ONE adversarial pass against them: take the opposing342view and try to break the design — unstated assumptions, simpler approach ignored,343scalability/failure modes, security holes the threat model missed, spec requirements344that contradict each other. Revise the spec to close every real gap the pass finds.345This is the design-time analogue of the Phase 5 double review: catching a design346flaw here is an order of magnitude cheaper than at review time. One pass only — do347not loop forever.348349**Threat model (mandatory, before planning):** using the code graph's blast350radius, enumerate the attack surface this change introduces or touches —351untrusted inputs, authN/authZ boundaries, PII/financial data handled, external352calls, and secrets. Note the OWASP categories at risk. Bake the mitigations into353the spec so they become plan tasks, not afterthoughts. Catching a design-level354security flaw here is far cheaper than at review time.355356**Frontend design (HARD GATE when UI is in scope — a precondition for freezing the357spec, not a suggestion):** visual quality is decided at design time, not patched on at358markup-writing time — a landing or screen that reads "flat / generic" was already flat359in the spec. This is the ONLY point in the whole pipeline where **ui-ux-pro-max** runs:360the executor subagents in Phase 4 have no Skill tool and cannot invoke it, so if you do361not run it HERE, nothing downstream will — the front end ships generic. That is the362exact failure this gate exists to stop.363364So when this change creates or touches any UI, you (the interactive main thread, which365DOES have the Skill tool) MUST invoke **ui-ux-pro-max** during design and record its366output in the spec's *UX / visual direction* section: the chosen style, palette, type367scale, spacing/layout system, key component and interaction states, and the WCAG368accessibility floor — concrete values, not adjectives (exact hex, named font pairing,369spacing scale). **Enforcement:** the spec MUST NOT be frozen and Phase 3 MUST NOT start370until this section exists and is filled from ui-ux-pro-max output. A spec that reaches371Phase 3 with an empty or hand-waved *UX / visual direction* section for in-scope UI is a372gate failure — stop and run the skill. Phase 3 inlines this section verbatim into every373UI task and Phase 4 implements it exactly. (Purely back-end / non-visual changes skip374this gate entirely.)375376## Phase 3 — Plan + self-review loop (the "todo bien hechesito" gate)3773780. **Precondition:** the Phase 2 spec file must already exist. If it does not, go379 back and write it — do not plan without a spec. **UI gate:** if the change touches380 any UI, the spec's *UX / visual direction* section must already be filled from381 ui-ux-pro-max output (see the Phase 2 Frontend-design hard gate). If it is empty or382 hand-waved, stop and run ui-ux-pro-max now — do not plan UI tasks against a missing383 visual system, because Phase 4 executors cannot recover it (they have no Skill tool).3841. Use **writing-plans** to write the implementation plan, saved to385 `docs/hydraia/plans/YYYY-MM-DD-<feature>.md`. Follow the writing-plans structure386 in FULL — a thin plan is a failed plan. The plan MUST contain:387 - **A header:** Goal, Architecture (2–3 sentences), Tech Stack, the path of the388 Phase 2 spec it derives from, and a **Global Constraints** block (exact values389 copied from the spec).390 - **A File Structure map:** every file to be created or modified and its single391 responsibility, before the tasks.392 - **Right-sized tasks:** each task is a coherent, independently shippable unit of393 work — not one micro-edit. Consolidate trivially-related edits into one task.394 A plan with dozens upon dozens of atomic tasks will fan out into just as many395 sub-agents in Phase 4 and multiply token cost; the agent-budget cap396 (`HYDRAIA_MAX_AGENTS`, default 30) will hard-stop it. Aim well under that397 ceiling by design.398 - **Per-task blocks**, each with:399 - `Files:` — `Create: exact/path`, `Modify: exact/path:line-range`,400 `Test: exact/path`. Exact paths, never "the relevant file".401 - `Interfaces:` — Consumes (signatures it uses from earlier tasks) and Produces402 (exact function names, parameter and return types later tasks rely on).403 - **Bite-sized TDD steps** (2–5 min each): write failing test → run it, expect404 fail → minimal implementation → run, expect pass → commit. With the exact405 test command and expected result per step.406 Assume the implementer has zero prior context and cannot see the spec or your407 session — everything they need is in their task block. **Write to the weakest408 plausible executor:** the plan must be detailed enough that a cheaper or weaker409 model (Sonnet 5, Haiku, or an external agent like Codex or Gemini) can implement410 each task correctly with no judgment calls left open — exact paths, exact411 signatures, exact test commands. If a task would require the executor to infer412 intent or make a design decision, it is under-specified — push that decision up413 into the plan. This is where token cost is won or lost: a fully-specified task414 executes in one shot on a cheap model; an under-specified one forces a re-dispatch415 or an Opus rescue, which is the expensive path the plan exists to avoid.416417 **Literal content, never a description of it.** A task that creates a file MUST418 embed the file's FULL verbatim content in a code block — never "create the file419 with the appropriate content". A task that edits a file MUST give the exact420 `old_string` → `new_string` (or a unique quoted anchor + the exact text to421 insert) — never "add error handling here". The executor copies; it does not422 compose.423424 **Never point at the spec (or any other document/code) for content the executor425 must produce.** This is the single most common self-containment failure. A task426 that says "implement per spec §3", "follow the skeleton in the design",427 "match the existing User validation", or "see the spec for the schema" is NOT428 self-contained — the executor may be a context-less cheap model (Gemini Flash,429 Codex, Haiku) that CANNOT and WILL NOT open the spec, so it guesses, truncates,430 or invents. Inline the actual content into the task, even though it duplicates the431 spec. **Here DRY yields to self-containment:** the spec holds design rationale;432 the task holds everything needed to execute, repeated in full. This is exactly why433 the plan is a portable hand-off artifact ("execute anywhere" — Codex, Gemini, a434 second session): portability only holds if every task carries its own content. A435 runtime hook (`hooks/plancheck.sh`) scans the frozen plan's task bodies for these436 reference smells and BLOCKS the gate-arm if it finds any — so a referencing plan437 cannot reach execution.438439 **State each task's execution environment — assume nothing from context.** A cheap440 executor does not know your repo's toolchain. Every task that runs anything gives441 the EXACT command (not "run the tests" but `pnpm vitest run src/x.test.ts`), the442 working directory, any dependency/env-var/service precondition, and — if it depends443 on an earlier task's output — names that task and the files it must find already444 present. Out-of-order or standalone execution must fail loudly, not silently guess.445446 **Verify completeness of large literals, not just existence.** A cheap model can447 truncate a long verbatim block. For any sizable inlined file, the task's448 verification confirms it landed WHOLE — e.g. `wc -l file → N` or a grep for the449 exact last line — not merely that the file exists.450451 **Anchor edits by unique quoted text, never by line number alone.** Line numbers452 drift as earlier tasks change the file; every `Modify` must carry a unique text453 anchor the executor can match exactly. State this in the task.454455 **Every UI task carries its visual direction inline.** A task that creates or456 changes UI MUST embed the concrete decisions from the Phase 2 *UX / visual457 direction* section — the exact style, palette values, type scale, spacing,458 component/interaction states it must produce, and the WCAG accessibility floor to459 verify. The executor implements these values directly and does NOT invoke460 ui-ux-pro-max (it has no Skill tool); the inlined direction IS the visual system.461 Because Phase 4 runs autonomously on a weak executor, "make it look good" or462 "see the spec for styling" is NOT self-contained — the executor cannot open the463 spec and will fall back to generic defaults. Inline the values, per the464 self-containment rule above. A UI task with no visual direction in its body is465 under-specified and produces flat output.466467 **Every task carries a runnable verification with its expected output** — not468 only TDD steps. Config, docs, and scaffolding tasks each end with an exact469 command and the exact output that proves the task landed (e.g.470 `grep -c X file → 2`). A task with no way to self-check is under-specified.471472 **QA cases (parallel, when `qaFunctional` is on) — ALWAYS a committed document,473 NEVER inline.** Functional QA is produced as a reviewable artifact, not performed474 in your head. While writing the plan, dispatch the `qa-functional` agent (Sonnet)475 with: the spec path, the story artifact path if one exists, and the output path476 `docs/hydraia/qa/YYYY-MM-DD-<slug>-cases.md`. It returns Given/When/Then cases plus477 a traceability matrix (`AC → Cases → Test ref`, refs start as `pending`) and a GAPS478 section. **Non-negotiable rules:**479 - **You (the main agent) MUST NOT write the test cases inline or "apply QA480 yourself."** Dispatch `qa-functional`; the value is a durable document the human481 can read, review, and upload to the repo — not ephemeral reasoning.482 - **The document is always produced and committed.** Even when the run has no483 formal acceptance criteria, instruct `qa-functional` to derive implicit ACs from484 the spec's behavior so a case doc still results. After it returns, **commit the485 file** (`git add docs/hydraia/qa/<file> && git commit`) so it lands in the repo.486 - Surface every GAP to the human BEFORE freezing the plan — gaps are design487 questions, never things to guess around.488 - The plan must contain the test tasks that implement these cases (see the Phase 4489 QA automation rule). The frozen-plan condition below includes "the QA case doc490 exists and is committed."4912. **Self-review the plan (always TWO passes):**492 - Pass A: critique your own plan hard. **The Haiku test — apply it to every493 task:** could a model with zero context and no permission to make decisions494 produce EXACTLY the intended result from this task block alone? If any step495 needs the executor to infer, deduce, or invent, the task is under-specified —496 reject and push the decision up into the plan. Concretely, **reject and revise497 if ANY task:**498 - lacks exact `Files:` paths, `Interfaces:`, or independently testable steps,499 or says vaguely "edit the code / update the component";500 - **describes content instead of embedding it** — a create-file task without the501 full verbatim file, or an edit task without the exact `old_string`→`new_string`502 / quoted anchor + literal insert;503 - **references the spec, another document, or other code for content it must504 produce** — "follow spec §X", "see the design", "as in the spec", "match the505 existing X" — instead of inlining that content into the task (the506 `plancheck.sh` hook blocks the gate-arm on these, but catch them here first);507 - **runs a command without the exact invocation** ("run the tests" with no508 command/dir), or **assumes an earlier task's output without naming it**, or509 **lacks a completeness check on a large inlined literal** (existence only, no510 line-count / last-line assert);511 - **anchors an edit to a bare line number** instead of a unique quoted string;512 - **lacks a runnable verification with expected output** (not just TDD tasks —513 config/docs/scaffolding too);514 - **contains a placeholder** — `TODO`, `TBD`, `...`, "similar to Task N",515 "add appropriate X", "handle edge cases" — repeat the real content instead;516 - **references a name (symbol, file, agent, skill) that no earlier task defines517 and does not already exist**, or uses an inconsistent name/signature across518 tasks (`foo()` in Task 3 vs `fooBar()` in Task 7 is a bug).519 When `qaFunctional` is on, also reject if any acceptance criterion lacks BOTH a520 QA case (in the qa-functional doc) and an implementing task in the plan. Also521 hunt gaps, hidden coupling (check the graph), missing tests, unstated522 assumptions, over-broad changes, and drift from the spec. Revise.523 - Pass B: run a **second full pass regardless** — even if Pass A found nothing,524 re-audit the whole plan against the same checklist with fresh eyes (Pass A can525 miss on the first read, and its own revisions introduce new gaps). Revise again526 if it finds anything.527 - Both passes always run. Stop after the two even if minor nits remain — do not528 loop forever.5293. The plan is frozen only after the self-review loop converges AND every task has530 file-level detail AND — when `qaFunctional` is on — the QA case doc exists and is531 committed AND (when ACs exist) every AC maps to at least one QA case and one plan532 task. If it does not, it is not frozen.5334. **Open a run log.** Create `docs/hydraia/runs/YYYY-MM-DD-HHMM-<feature>.md` with534 the original request, the plan path, and a phase checklist535 (`- [ ] Phase 0` … `- [ ] Phase 6`). Update it at each phase boundary — check536 the box as each phase completes — so an interrupted run leaves a durable trail537 of where it stopped. `/hydraia:resume` reads this file.5385. **Arm the spec-drive gate.** Only after BOTH the Phase 2 spec file and the frozen539 plan exist (and NOT before), write the frozen plan's path into the marker file540 `docs/hydraia/.active-plan`541 (e.g. `printf '%s\n' "docs/hydraia/plans/<file>.md" > docs/hydraia/.active-plan`).542 The `gate.sh` hook blocks all source-code edits until this marker exists — which543 is exactly why no code can be written before Phases 2–3 complete. Do not arm the544 marker if the spec is missing. (`/hydraia:plan` stops here and does NOT arm the545 marker — planning must never authorize edits.) **A second hook546 (`plancheck.sh`) fires on this arm command and scans the plan's task bodies for547 reference smells ("follow spec §X", "see the design", etc.); if the plan is not548 self-contained it BLOCKS the arm — so a plan that would fail on a cheap executor549 cannot reach Phase 4. If it blocks, inline the referenced content and re-arm.**5506. **Run-controls picker (LAST interactive step — the human sets the depth before the551 autonomous half runs).** The autonomous half (Phases 4–6) must not pause, so ask552 here, once, via a single `AskUserQuestion` with these two questions:553554 **(a) Review depth** — how much of the Phase 5/6 ceremony to run on this change:555 - **Full** — double review, all matched language reviewers, security gates, QA,556 E2E, docs sync. (Default; pick when unsure.)557 - **Lite** — a single review pass, skip the non-core language reviewers and the558 docs-sync step; QA and the E2E gate still run per the repo's surface.559 - **Custom** — then a second `AskUserQuestion` (multiSelect) over the OPTIONAL560 stages only: `2nd review pass`, `language/framework reviewers`,561 `type-design / performance reviewers`, `docs sync`, `extra OWASP pass`.562563 **Security floor (never offered as removable):** regardless of profile,564 `security-scan`, `code-reviewer`, `silent-failure-hunter`, `security-reviewer`, and565 one `hydraia-reviewer` pass ALWAYS run. The picker cannot switch these off — only566 the human's explicit `securityGates=false` config can, which is a separate act.567568 **(b) Closing summary depth** — `Brief` (compact box) or `Detailed` (adds what569 shipped, per-agent-type counts, main-vs-sub token split, per-model in/out/cache).570571 Record both answers in the run log and honor them in Phases 5–6. On dismissal,572 default to **Full** + **Brief**. This is the only question in the autonomous half's573 run-up — after it, Phases 4–6 run to completion without pausing.574575## Phase 4 — Execution (delegated → Sonnet 5)576577Use **subagent-driven-development**. Dispatch a fresh `hydraia-executor` subagent578per task (these run on Sonnet 5). Give each exactly the context it needs from the579plan and the graph — never your session history. Execute all tasks continuously.580TDD where the plan calls for it. Commit frequently.581Tag each executor dispatch's description with a machine-readable `[task:<slug>]` marker582(the same `<slug>` the executor uses for its heartbeat file). The circuit-breaker hook583(`hooks/agents.sh`) reads this tag to count per-task attempts; without it the breaker584falls back to a description hash and still counts, but the tag makes escalation precise.585586**Dispatch in bounded waves — never fan out the whole plan at once.** Each subagent587loads its own context, so N parallel agents multiply token cost by ~N. Send at most588`HYDRAIA_MAX_CONCURRENT` (default 6) executors at a time; as they finish, send the589next wave. A whole run is also capped at `HYDRAIA_MAX_AGENTS` (default 30) total590dispatches. These limits are enforced at runtime by the agent-budget hook591(`hooks/agents.sh`) — a `Task` call past the cap is BLOCKED, not throttled silently,592so respect the waves rather than firing 100 tasks and retrying blocked ones. If a593plan truly needs more than the ceiling, that is the human's call to raise594(`export HYDRAIA_MAX_AGENTS=595596…(truncated)