# Songwhip Feature — Cross-Repo Implementation Agent Guide

**Version 0.1.0**

> **For Claude Code agents:** Follow this guide step-by-step when the skill
> activates. This skill **writes code** across multiple repos but **never pushes
> and never opens PRs**. The user reviews the committed branches and pushes/PRs
> themselves.

---

## Table of Contents

1. [Overview](#1-overview)
2. [Prerequisites](#2-prerequisites)
3. [Workflow](#3-workflow)
4. [Subagent Prompt Template](#4-subagent-prompt-template)
5. [Contract Format](#5-contract-format)
6. [Error Handling](#6-error-handling)
7. [Constraints](#7-constraints)
8. [Output Format](#8-output-format)

---

## 1. Overview

Implement one feature spanning multiple Songwhip services. The change is modeled
as a **dependency DAG of stages**: Stage 1 = upstream / shared packages
(`@theorchard/songwhip-*`), later stages = consumers. Repos within a stage are
independent and run in parallel; stages run in order.

Each repo gets its own git worktree (off the user's local clone) and a focused
subagent. Upstream subagents emit a **contract**; the orchestrator hands that
contract to downstream subagents in the next stage (the change is NOT published,
so downstream codes against the contract). Every subagent commits to a local
`feat/<slug>` branch. Nothing is pushed.

This is the **write** counterpart to the read-only `songwhip-cross-repo` skill.

## 2. Prerequisites

- Local full clones at `<clones-dir>/<repo>` (default `~/Development/Songwhip`).
- `git` (with `git worktree`) and `jq` on PATH.
- `GITHUB_PERSONAL_ACCESS_TOKEN` set if a missing clone must be cloned.

## 3. Workflow

Execute these phases in order.

### Phase 1 — Scope & stage (single approval gate)

1. Determine the affected repos, each repo's **slice**, and the dependency order.
   Reuse the `songwhip-cross-repo` skill for impact analysis and routing. Do NOT
   re-derive this by hand if that skill can produce it.
2. Build a **staged plan**:
   - Stage 1: upstream / shared packages.
   - Stage 2+: consumers, ordered so a repo only starts after every repo it
     depends on has completed.
   - Repos with no inter-dependency share a stage (run in parallel).
3. Choose a feature slug — lowercase kebab-case recommended (the scripts accept
   `^[a-zA-Z0-9._-]+$`), e.g. `add-foo-field`.
4. Present the staged plan to the user and **get approval once**. Example:

   ```
   Feature: <slug>   Branch: feat/<slug>   Base: <default branch>
   Stage 1 (parallel): songwhip-packages
   Stage 2 (parallel): songwhip-api, songwhip-lookup
   Stage 3:            songwhip-web
   Per repo: <one-line slice>
   ```

   This is the only routine approval gate. Stages auto-advance after approval.

### Phase 2 — Setup worktrees

1. Emit: `"Setting up worktrees for [N] repos..."`
2. Run the setup script:
   ```bash
   "${CLAUDE_PLUGIN_ROOT}/skills/songwhip-feature/scripts/setup-worktrees.sh" \
     '["songwhip-packages","songwhip-api","songwhip-web"]' \
     --feature <slug>
   ```
   (Add `--clones-dir <path>` / `--base-branch <name>` if the user specified
   them.)
3. Parse the JSON output. Its shape is:
   ```json
   {"feature":"<slug>","branch":"feat/<slug>","created":N,"reused":N,
    "missing":[...],"failed":[...],
    "repos":{"<repo>":{"status":"created|reused|missing|failed",
                       "path":"<abs worktree path>","branch":"feat/<slug>","sha":"..."}}}
   ```
   Report: `"[created] created, [reused] reused."` **For each repo, record
   `repos.<repo>.path` (its absolute worktree path) and `repos.<repo>.branch`** —
   you pass `path` as the worktree path and `branch` as the branch in that repo's
   Section 4 subagent prompt.
4. If `missing` is non-empty, tell the user which clones are absent and ask
   whether to clone them into the clones dir — the same `<clones-dir>` used in
   step 2 (default `~/Development/Songwhip`) — as a full clone, authenticated
   with `GITHUB_PERSONAL_ACCESS_TOKEN`:
   ```bash
   git clone "https://github.com/theorchard/<repo>.git" "<clones-dir>/<repo>"
   ```
   Then re-run setup for those repos. If the user declines, drop those repos
   from scope and warn that their stage will be incomplete.
5. If `failed` is non-empty, report and continue with the rest (unless every
   repo failed — then stop).

### Phase 3 — Execute stages (auto-advance, pause-on-failure)

For each stage, in order:

1. Emit: `"Stage [i]/[n]: dispatching [repos]..."`
2. Dispatch **one subagent per repo in the stage, in parallel** (multiple Agent
   tool calls in a single message). Build each prompt from Section 4, injecting
   the contracts collected from all prior stages.
3. Collect each subagent's structured result. From repos in earlier stages (any
   repo a later stage depends on), extract the **Contract** block (Section 5) and
   accumulate it for later stages. A repo may legitimately return `Contract:
   none` (e.g. only internal or test changes) — that's fine; there is nothing to
   accumulate for it.
4. **Pause-on-failure:** if any subagent reports a non-empty `Blockers` field or
   fails, do NOT dispatch dependent stages. Let the other repos in the current
   stage finish. Then report the failure and ask the user whether to retry that
   repo (re-dispatch into the same worktree) or stop.
5. When a stage's repos all succeed, auto-advance to the next stage.

### Phase 4 — Report

Present the consolidated report (Section 8): per-repo table, contracts,
known-pending items, and next steps (review → push → PR — done by the user).
Strip the `<clones-dir>/<repo>/.worktrees/<slug>/` prefix from any file paths in
the report — show them repo-relative (e.g. `songwhip-api/src/foo.ts:42`).

### Phase 5 — Cleanup (only when the user asks)

Run the teardown script, passing the repos that were set up in Phase 2 (the
list below is illustrative):
```bash
"${CLAUDE_PLUGIN_ROOT}/skills/songwhip-feature/scripts/teardown-worktrees.sh" \
  '["songwhip-packages","songwhip-api","songwhip-web"]' --feature <slug>
```
(Add `--clones-dir <path>` if a non-default clones dir was used at setup.)
Branches are kept. Dirty worktrees are skipped — report them; never force-remove.

## 4. Subagent Prompt Template

Build each subagent prompt from this template. The subagent must NOT inherit
session history — give it everything it needs explicitly.

```
You are implementing one repo's slice of a cross-repo Songwhip feature.

Feature: <one-paragraph feature description>
Your repo: <repo-name>
Work ONLY in this worktree: <abs worktree path from setup output>
Branch (already checked out in the worktree): feat/<slug>

Your slice:
<specific, self-contained description of what THIS repo must change>

Upstream contracts you must build against (NOT yet published — code to these):
<contracts from prior stages, verbatim; write "none" for Stage 1>

Rules:
- Follow this repo's own conventions (its CLAUDE.md/AGENTS.md, linters, and
  formatters) and use its toolchain (pnpm or yarn — check the repo's lockfile).
- Install dependencies first using this repo's toolchain.
- Use test-driven-development.
- Run this repo's tests AND lint before finishing.
- Commit your work to feat/<slug> with a clear message. Do NOT push.
- Build against the upstream contracts above; do NOT attempt local package
  linking (pnpm/yarn link, file: overrides).
- Do NOT modify any file outside this worktree. Do NOT touch other repos.

Return EXACTLY this structure:
- Summary: <what you changed and why>
- Files changed: <repo-relative paths>
- Tests: <command + pass/fail + counts>
- Lint: <command + pass/fail>
- Commit: <sha + subject>
- Contract: <only if this repo exposes changed shared API — see contract
  format below; otherwise "none">
- Blockers: <anything that prevented completion, or "none">
```

## 5. Contract Format

An upstream subagent that changes shared API returns its `Contract` block in this
shape. The orchestrator passes it verbatim into downstream prompts.

```
## Contract: <repo> (<shared package name if applicable>)
- Changed/added exports: <names>
- Types & signatures: <new or changed type/function signatures>
- Behavioral changes: <semantics downstream must account for>
- Semver impact: major | minor | patch — <reason>
- Consumer migration notes: <how downstream should adapt>
- Publish status: NOT published — downstream codes against this contract; green
  runtime tests downstream may depend on the eventual published version.
```

## 6. Error Handling

| Scenario | Action |
|---|---|
| Local clone missing | Report from setup `missing[]`; ask user to clone or drop the repo from scope. |
| `.worktrees/` not ignored | Setup script appends to `.git/info/exclude` (local). Never edits tracked `.gitignore`. |
| Branch/worktree already exists | Setup reuses it idempotently. |
| Subagent fails / has blockers | Do not advance dependent stages; finish the current stage's other repos; report and offer retry/stop. |
| Worktree dirty at teardown | Reported as `skipped_dirty`; never force-removed. |
| Setup exit 1 (partial) | Continue with successful repos; report failures. |
| Setup exit 2 (fatal) | Report and stop. |
| `git`/`jq` missing | Report; suggest install. |

## 7. Constraints

1. **No push, no PRs.** Never push branches or open pull requests.
2. **Never touch `~/.cache/songwhip-cross-repo/`** — that is the read-only
   analysis skill's cache.
3. **Worktree isolation.** Each subagent works only inside its assigned
   `.worktrees/<slug>/` worktree.
4. **No destructive git on the user's primary working trees.** Only the
   dedicated worktrees and the new `feat/<slug>` branches are written. Never
   `reset --hard` / `checkout` / `clean` the user's main checkout.
5. **Local ignore only.** Worktree-ignore setup uses `.git/info/exclude`, not the
   tracked `.gitignore`.
6. **Contract handoff, no linking.** Downstream builds against the contract; do
   not attempt local package linking.

## 8. Output Format

```
## Feature: <slug>   Branch: feat/<slug>

| Repo | Stage | Files | Tests | Lint | Commit |
|------|-------|-------|-------|------|--------|
| <repo> | 1 | <n> | pass (X/Y) | pass | <sha7> <subject> |

### Contracts
<accumulated contract blocks>

### Known-pending
- <repo>: <e.g. tests awaiting published @theorchard/songwhip-X>

### Next steps (you do these)
1. Review each worktree (.worktrees/<slug>) per repo.
2. Push each feat/<slug> branch.
3. Open PRs and cross-link the related PRs.
```

`Files` is the count of files changed; the full repo-relative paths are in each
subagent's `Files changed` field if you need them.
