backend-implement
Implement the approved backend scope so it satisfies the contract exactly, staying within
that scope — never expand beyond what was approved. The backend owns the contract —
implement it as published; never silently change it.
Isolate first (before any edit)
If your instructions name a branch / ask you to work in a worktree (parallel runs always do),
this is a HARD prerequisite, not a suggestion — a sibling step may be writing the main tree
concurrently:
- Create and enter the worktree:
git worktree add -b <branch> <new-dir> HEAD (or
git worktree add <new-dir> <branch> if it already exists), then work from <new-dir>.
- Verify you are isolated:
git rev-parse --show-toplevel must NOT be the main checkout.
- If a worktree cannot be created (e.g. the repo has no commits), STOP and report it —
never fall back to editing the main working tree.
Before editing
- Read
CLAUDE.md, AGENTS.md, the backend LLD, and the contract — the inputs your
instructions point to.
- Read the task DAG (the tasks.json your instructions point to)
if present; otherwise derive the same ordered slices yourself.
- List the files you intend to change.
- Stop and ask a human before DB migrations, auth/permission, payment logic, prod
config, or dependency upgrades.
Slice fan-out (owned by this skill)
This skill owns fanning the task DAG out into slices — no orchestrator passes slices or
worktrees in.
- Validate first — run
python3 engine/validate_tasks.py <the tasks.json path>;
it must print OK. Never build from an invalid tasks.json — fix or regenerate it first.
- With the Task tool (where the harness provides it): spawn one implementer subagent per
independent slice (
slices[] group), at most 3 concurrent. Each subagent works in its
own git worktree on branch maestro/<slug>/backend-<group_id> — delegate worktree hygiene
to the using-git-worktrees skill when installed. Each subagent gets
its slice's tasks + the context manifest and follows the per-slice discipline below. When
all slices are green, merge the slice branches into the feature branch and resolve any
conflicts (disjoint writes across groups should make these rare).
- Without the Task tool: build the slices yourself, sequentially, in dependency order,
in the current checkout.
Either way, this skill is accountable for every slice building and testing clean — a
subagent's claim is not proof; its slice's tests must pass.
Per slice (subagent or inline):
- Batch-load context once —
cat every path in context_manifest.read_once +
context_manifest.reference in a SINGLE call, delimited by === <path> ===. Do not use
one Read per file. This is how the run stays under ~50 SDK calls.
- Run the slice in order — for each
task_id in the slice's task_ids (already
dependency-ordered), batch-read that task's reads delta, then TDD it (write the failing
test → minimal code → refactor) before moving to the next task.
- Human gates — stop and ask before any task with
needs_human_gate: true.
- Stay in scope — edit only files in the slice's tasks'
writes; commit the slice on
its branch.
If no tasks.json exists (standalone run), author the ordered task list first, then proceed
over its slices as above.
Steps (per task, test-first)
- Write the failing test first from the contract/acceptance criteria (RED).
- Implement the minimum to pass it (GREEN), in dependency order: types/schema →
domain/service → persistence → API/controller.
- Refactor with tests green; remove duplication.
- Add cross-cutting concerns for the slice: validation, error mapping, logging/metrics.
- Run the targeted check, then move to the next task. On failure, invoke
/fix-loop.
- After all tasks, run full
/verify and address the standards checklist.
Standards every backend change must satisfy
- Security — authorize every operation (never trust the client); validate & bound all
input; parameterize queries (no injection); encode output; secrets never in code/logs;
minimize/protect PII; safe deserialization; no SSRF from user-supplied URLs.
- Backward compatibility — additive by default; don't remove/rename/retype fields or
tighten validation without a version + migration; defaults for new fields; old clients keep working.
- Rate limiting & abuse — limits/quotas on new endpoints; cap page size & payload size;
sane timeouts; guard expensive operations; return 429 + retry-after when exceeded.
- Idempotency & retries — mutating/retryable operations honor an idempotency key or are
naturally idempotent; no duplicate side effects on retry.
- Data & migrations — expand → migrate → contract; reversible; index new query paths;
no online long locks / full-table rewrites; backfill existing rows safely.
- Concurrency — transactions where needed; prevent lost updates (optimistic version/ETag);
choose correct isolation; handle races.
- Observability — structured logs (no secrets/PII), metrics on new paths, tracing spans,
and an error taxonomy mapped to the contract's error shape.
- Performance — no N+1 or unbounded queries; bound query cost; cache/pool where the LLD says.
- Error contract — return the contract's error envelope and correct status codes; never
leak internals in messages.
Edge cases to implement and test (not just the happy path)
- Inputs: null / missing / empty / whitespace / max-length / oversized / negative / zero /
boundary numbers / invalid enum / malformed / duplicate / unicode / injection payloads.
- Auth: unauthenticated, expired token, insufficient scope, cross-tenant access attempt.
- Concurrency: two writers on the same entity; retry after timeout; idempotency-key reuse.
- Failure: downstream dependency down/slow; DB error; partial write; timeout → correct fallback.
- Pagination: first/last/empty page, invalid cursor, unstable ordering.
- Rate limit reached; large result sets; time zones / DST / numeric precision & rounding.
External skill (provision — the TDD engine)
If the test-driven-development skill (from the Superpowers pack) is installed, use it to
drive RED → GREEN → REFACTOR. Whatever the engine, ensure the tests it produces cover the
edge cases above and the contract's negative paths — not happy-path only. If it is not
installed, implement then add unit + integration tests to the same bar.
Safety
Never run destructive commands (rm -rf, force-push, DROP/TRUNCATE TABLE) or write
prod config/secrets (.env, keys) — those are human pre-steps. Nothing auto-blocks this;
you are the backstop.
Verification
Invoke /verify (lint, typecheck, unit + integration, migration check, provider-side
contract validation). On failure invoke /fix-loop (one attempt per invocation — the workflow's
max_visits on the fix node, typically 3, bounds the overall loop; delegates to the
systematic-debugging skill when installed).
Definition of done (stop condition)
Tests ran and pass; every slice merged; every standards item addressed or explicitly noted;
edge-case tests exist; changed files summarized; remaining risks listed; contract honored
exactly. Passing checks are the proof — not a message that says "done".
Output contract
Return branch, summary, tests_passed. tests_passed MUST be the literal JSON boolean
true or false (true only if every test actually ran AND passed) — never a count, status
phrase, or other prose. A workflow routes on it, so prose reads as "not passing".
1---2name: backend-implement3description: Implement an approved backend scope against the cross-repo contract, test-first, meeting the backend engineering standards (security, backward compatibility, rate limiting, idempotency, migrations, observability, performance). Edits code within the approved scope only. Front door for /backend-implement.4---56# backend-implement78Implement the approved backend scope so it satisfies the contract exactly, staying within9that scope — never expand beyond what was approved. The backend **owns** the contract —10implement it as published; never silently change it.1112## Isolate first (before any edit)13If your instructions name a branch / ask you to work in a worktree (parallel runs always do),14this is a HARD prerequisite, not a suggestion — a sibling step may be writing the main tree15concurrently:161. Create and enter the worktree: `git worktree add -b <branch> <new-dir> HEAD` (or17 `git worktree add <new-dir> <branch>` if it already exists), then work from `<new-dir>`.182. Verify you are isolated: `git rev-parse --show-toplevel` must NOT be the main checkout.193. If a worktree cannot be created (e.g. the repo has no commits), **STOP and report it** —20 never fall back to editing the main working tree.2122## Before editing231. Read `CLAUDE.md`, `AGENTS.md`, the backend LLD, and the contract — the inputs your24 instructions point to.252. Read the task DAG (the tasks.json your instructions point to)26 if present; otherwise derive the same ordered slices yourself.273. List the files you intend to change.284. **Stop and ask a human** before DB migrations, auth/permission, payment logic, prod29 config, or dependency upgrades.3031## Slice fan-out (owned by this skill)32This skill owns fanning the task DAG out into slices — no orchestrator passes slices or33worktrees in.34351. **Validate first** — run `python3 engine/validate_tasks.py <the tasks.json path>`;36 it must print `OK`. Never build from an invalid tasks.json — fix or regenerate it first.372. **With the Task tool** (where the harness provides it): spawn one implementer subagent per38 independent slice (`slices[]` group), **at most 3 concurrent**. Each subagent works in its39 own git worktree on branch `maestro/<slug>/backend-<group_id>` — delegate worktree hygiene40 to the `using-git-worktrees` skill when installed. Each subagent gets41 its slice's tasks + the context manifest and follows the per-slice discipline below. When42 all slices are green, **merge the slice branches into the feature branch** and resolve any43 conflicts (disjoint `writes` across groups should make these rare).443. **Without the Task tool**: build the slices yourself, sequentially, in dependency order,45 in the current checkout.4647Either way, **this skill is accountable for every slice building and testing clean** — a48subagent's claim is not proof; its slice's tests must pass.4950Per slice (subagent or inline):511. **Batch-load context once** — `cat` every path in `context_manifest.read_once` +52 `context_manifest.reference` in a SINGLE call, delimited by `=== <path> ===`. Do not use53 one `Read` per file. This is how the run stays under ~50 SDK calls.542. **Run the slice in order** — for each `task_id` in the slice's `task_ids` (already55 dependency-ordered), batch-read that task's `reads` delta, then TDD it (write the failing56 `test` → minimal code → refactor) before moving to the next task.573. **Human gates** — stop and ask before any task with `needs_human_gate: true`.584. **Stay in scope** — edit only files in the slice's tasks' `writes`; commit the slice on59 its branch.6061If no `tasks.json` exists (standalone run), author the ordered task list first, then proceed62over its slices as above.6364## Steps (per task, test-first)651. **Write the failing test first** from the contract/acceptance criteria (RED).662. **Implement the minimum** to pass it (GREEN), in dependency order: types/schema →67 domain/service → persistence → API/controller.683. **Refactor** with tests green; remove duplication.694. **Add cross-cutting concerns** for the slice: validation, error mapping, logging/metrics.705. **Run the targeted check**, then move to the next task. On failure, invoke `/fix-loop`.716. After all tasks, run full **`/verify`** and address the standards checklist.7273## Standards every backend change must satisfy74- **Security** — authorize every operation (never trust the client); validate & bound all75 input; parameterize queries (no injection); encode output; secrets never in code/logs;76 minimize/protect PII; safe deserialization; no SSRF from user-supplied URLs.77- **Backward compatibility** — additive by default; don't remove/rename/retype fields or78 tighten validation without a version + migration; defaults for new fields; old clients keep working.79- **Rate limiting & abuse** — limits/quotas on new endpoints; cap page size & payload size;80 sane timeouts; guard expensive operations; return 429 + retry-after when exceeded.81- **Idempotency & retries** — mutating/retryable operations honor an idempotency key or are82 naturally idempotent; no duplicate side effects on retry.83- **Data & migrations** — expand → migrate → contract; reversible; index new query paths;84 no online long locks / full-table rewrites; backfill existing rows safely.85- **Concurrency** — transactions where needed; prevent lost updates (optimistic version/ETag);86 choose correct isolation; handle races.87- **Observability** — structured logs (no secrets/PII), metrics on new paths, tracing spans,88 and an error taxonomy mapped to the contract's error shape.89- **Performance** — no N+1 or unbounded queries; bound query cost; cache/pool where the LLD says.90- **Error contract** — return the contract's error envelope and correct status codes; never91 leak internals in messages.9293## Edge cases to implement and test (not just the happy path)94- Inputs: null / missing / empty / whitespace / max-length / oversized / negative / zero /95 boundary numbers / invalid enum / malformed / duplicate / unicode / injection payloads.96- Auth: unauthenticated, expired token, insufficient scope, cross-tenant access attempt.97- Concurrency: two writers on the same entity; retry after timeout; idempotency-key reuse.98- Failure: downstream dependency down/slow; DB error; partial write; timeout → correct fallback.99- Pagination: first/last/empty page, invalid cursor, unstable ordering.100- Rate limit reached; large result sets; time zones / DST / numeric precision & rounding.101102## External skill (provision — the TDD engine)103If the `test-driven-development` skill (from the Superpowers pack) is installed, use it to104drive RED → GREEN → REFACTOR. **Whatever the engine, ensure the tests it produces cover** the105edge cases above and the contract's negative paths — not happy-path only. If it is not106installed, implement then add unit + integration tests to the same bar.107108## Safety109Never run destructive commands (`rm -rf`, force-push, `DROP`/`TRUNCATE TABLE`) or write110prod config/secrets (`.env`, keys) — those are human pre-steps. Nothing auto-blocks this;111you are the backstop.112113## Verification114Invoke `/verify` (lint, typecheck, unit + integration, migration check, provider-side115contract validation). On failure invoke `/fix-loop` (one attempt per invocation — the workflow's116`max_visits` on the fix node, typically 3, bounds the overall loop; delegates to the117`systematic-debugging` skill when installed).118119## Definition of done (stop condition)120Tests ran and pass; every slice merged; every standards item addressed or explicitly noted;121edge-case tests exist; changed files summarized; remaining risks listed; contract honored122exactly. Passing checks are the proof — not a message that says "done".123124## Output contract125Return `branch`, `summary`, `tests_passed`. `tests_passed` MUST be the literal JSON boolean126`true` or `false` (true only if every test actually ran AND passed) — never a count, status127phrase, or other prose. A workflow routes on it, so prose reads as "not passing".