# Songwhip Cross-Repo Analysis — Agent Guide

**Version 1.1.0**

> **For Claude Code agents:** Follow this guide step-by-step when the skill
> activates. This skill is **read-only** — never modify files in cached repos.

---

## Table of Contents

1. [Overview](#1-overview)
2. [Prerequisites](#2-prerequisites)
3. [Workflow](#3-workflow)
4. [Search Strategies](#4-search-strategies)
5. [Parallel Search](#5-parallel-search)
6. [Error Handling](#6-error-handling)
7. [Constraints](#7-constraints)
8. [Output Format](#8-output-format)

---

## 1. Overview

This skill enables cross-repo analysis across all repositories containing `songwhip` in their name within the `theorchard` GitHub organization. It supports four use cases:

1. **Cross-repo code search** — Find symbols, types, functions across all services
2. **Impact analysis** — Determine which repos are affected by a change
3. **Architecture understanding** — Map dependencies and communication between services
4. **Multi-repo solutioning** — Plan changes that span multiple services

The skill uses the official `github` plugin for repo discovery, a shell script for syncing local shallow clones, and Claude's standard tools (Grep, Glob, Read, Agent) for analysis.

---

## 2. Prerequisites

- **The official `github` plugin** must be installed — it provides the hosted GitHub MCP used for repo discovery. Install with `/plugin install github@claude-plugins-official`.
- **`GITHUB_PERSONAL_ACCESS_TOKEN`** must be set in the environment. The `github` plugin's MCP uses it for discovery, and the sync script uses it to authenticate `git` clones of private repos.
- **git** must be available in PATH.
- **jq** must be installed (used by the sync script for JSON processing).

The sync cache lives at `~/.cache/songwhip-cross-repo/` (outside any repo), so no per-repo `.gitignore` setup is needed.

---

## 3. Workflow

Execute these phases in order on every invocation.

### Phase 1 — Discover Repos

Emit: `"Discovering songwhip repos from GitHub..."`

Use the `github` plugin's repository search tool (`search_repositories`) with:

- `query`: `"org:theorchard songwhip"`
- `perPage`: `100`

This matches all repos in the org containing "songwhip" in their name — including `songwhip-*` prefixed repos as well as repos like `lambda-songwhip`, `frontend-songwhip`, etc.

Extract the list of repo names and default branches from the response. Check the total result count — if results span multiple pages, request the next pages (`page: 2`, `page: 3`, …).

**If the `github` plugin / GitHub MCP is unavailable:** Fall back to the existing cache. Read `~/.cache/songwhip-cross-repo/manifest.json` and use the repo names from there. Warn the user: "The `github` plugin is unavailable. Using cached repo list — it may be incomplete or stale."

### Phase 2 — Sync Repos

Emit: `"Syncing [N] repos..."`

Build a JSON array of repo names from Phase 1 and invoke the sync script:

```bash
"${CLAUDE_PLUGIN_ROOT}/skills/songwhip-cross-repo/scripts/sync-repos.sh" \
  '["songwhip-api","songwhip-web","songwhip-lookup",...]' \
  --org theorchard
```

The script defaults the cache to `~/.cache/songwhip-cross-repo/` and authenticates clones with `GITHUB_PERSONAL_ACCESS_TOKEN` when it is set.

Parse the JSON output. Report the summary to the user:
`"Synced [total] repos. [cloned] cloned, [updated] updated, [unchanged] unchanged."`

If `failed` is non-empty, report: `"Failed to sync: [repo1, repo2]. Continuing without them."`

If `stale` is non-empty, report: `"Stale repos in cache (no longer in GitHub): [repo1]. Consider deleting their cache directories."`

If exit code is 2 (fatal), report the error and stop.

### Phase 3 — Search & Analyze

Now use Claude's standard tools on `~/.cache/songwhip-cross-repo/`:

- **Grep** — `path: "~/.cache/songwhip-cross-repo/"` for text/regex search across all repos
- **Glob** — patterns like `~/.cache/songwhip-cross-repo/*/src/**/*.ts` for file discovery
- **Read** — examine specific files found by Grep/Glob
- **Agent** — dispatch parallel subagents for broad searches (see Section 5)

Emit progress updates between tool calls:

- `"Searching for '[term]' across [N] repos..."`
- `"Found [N] matches in [N] repos. Analyzing..."`

Choose the appropriate search strategy from Section 4 based on the user's question.

### Phase 4 — Report

Present results using the output format in Section 8. Always strip the `~/.cache/songwhip-cross-repo/<repo-name>/` prefix from file paths for readability.

---

## 4. Search Strategies

### 4.1 Cross-Repo Code Search

User asks: "Where is X used across repos?" / "Find all usages of Y"

1. Grep for the symbol/string across `~/.cache/songwhip-cross-repo/`
2. Group results by repo name (extract from path)
3. For each match, classify: **definition**, **usage**, **re-export**, **test**, **config**
4. Sort repos by relevance (definitions first, then usages)

### 4.2 Impact Analysis

User asks: "If I change X, what breaks?" / "What depends on this endpoint?"

1. **Find the definition** — Grep for the target (endpoint path, type name, function name)
2. **Find the shared package** — If the target is in a shared package (`@theorchard/songwhip-*`), find all repos that depend on it by reading `package.json` files:
   ```
   Glob: ~/.cache/songwhip-cross-repo/*/package.json
   ```
   Then grep within those files for the package name.
3. **Find direct usages** — Grep for import statements, API calls, or references
4. **Find test coverage** — Grep for the target in test directories (`test/`, `__tests__/`, `*.test.*`, `*.spec.*`)
5. **Classify each match**: definition, direct usage, transitive usage, test
6. **Report** with change ordering recommendation

### 4.3 Architecture Understanding

User asks: "How do services communicate?" / "What's the dependency graph?"

1. **Read all `package.json` files**:
   ```
   Glob: ~/.cache/songwhip-cross-repo/*/package.json
   ```
2. **Extract `@theorchard/songwhip-*` dependencies** from each
3. **Read all `CLAUDE.md` files** (if they exist):
   ```
   Glob: ~/.cache/songwhip-cross-repo/*/CLAUDE.md
   ```
4. **Build dependency map**: which repos consume which shared packages
5. **Identify communication patterns**: HTTP calls, event publishing, queue messages
6. **Present as a structured dependency graph** (text-based)

### 4.4 Multi-Repo Solutioning

User asks: "What needs to change across services to add X?"

1. Run **Impact Analysis** (4.2) to find all affected repos
2. Run **Architecture Understanding** (4.3) to understand dependencies
3. **Identify change types** per repo: schema/migration, API endpoint, shared type, frontend component, mapper, test
4. **Determine ordering** based on dependency graph (upstream changes first)
5. **Present ordered change plan**:
   ```
   1. songwhip-api — Add migration + update model
   2. @theorchard/songwhip-api (types package) — Update shared types, publish
   3. songwhip-web — Update store + components
   4. songwhip-lookup — Update mapper
   ```

---

## 5. Parallel Search

For broad queries that would be slow sequentially, use the Agent tool to dispatch parallel subagents.

**When to parallelize:**

- Searching 4+ repos for the same pattern
- Running multiple independent search strategies simultaneously

**How to parallelize:**

- Dispatch one Agent subagent per group of 3 repos
- Each subagent uses Grep/Glob/Read on its assigned repos
- Main thread aggregates and deduplicates results

**When NOT to parallelize:**

- Targeted search in fewer than 4 repos
- Sequential analysis where each step depends on the previous

---

## 6. Error Handling

| Scenario                  | Action                                                                                |
| ------------------------- | ------------------------------------------------------------------------------------- |
| `github` plugin unavailable | Use cached manifest repo list, warn user                                            |
| Sync script exit code 1   | Report failed repos, continue with successful ones                                    |
| Sync script exit code 2   | Report fatal error, stop                                                              |
| Script not executable     | Run `chmod +x` on the script, retry once                                              |
| jq not installed          | Report error, suggest `brew install jq`                                               |
| Auth failure on clone     | Confirm `GITHUB_PERSONAL_ACCESS_TOKEN` is set and has repo read scope                 |
| Manifest missing/corrupt  | Script recreates it automatically                                                     |
| Non-shallow repo in cache | Script skips it, reports in `failed`. Suggest user delete the cache dir for that repo |
| No results found          | Report "No matches found across [N] repos" and suggest alternative search terms       |

---

## 7. Constraints

1. **Read-only** — NEVER modify, create, or delete files in `~/.cache/songwhip-cross-repo/`. The cache is for analysis only.
2. **No direct git commands** — Never run `git reset`, `git checkout`, `git clean`, or any destructive git command on cached repos. All git operations go through `sync-repos.sh`.
3. **Path stripping** — Always strip `~/.cache/songwhip-cross-repo/<repo-name>/` from file paths in output. Report paths as `<repo-name>/src/file.ts:42`.
4. **Progress updates** — Emit plain text status between phases. Users should never see long silences during sync or search.
5. **Scope** — This skill handles analysis and search only. Do not use it to propose code changes in other repos, create PRs, or modify deployments.

---

## 8. Output Format

Structure all results by repo with file:line attribution and match classification.

### Code Search Results

```
## Cross-Repo Search: `<search-term>`

Searched [N] repos. Found [M] matches in [K] repos.

### <repo-name> ([count] matches)
- `<path>:<line>` — [classification: definition | usage | re-export | test | config]
- `<path>:<line>` — [classification]

### <repo-name> ([count] matches)
- `<path>:<line>` — [classification]
```

### Impact Analysis Results

```
## Impact Analysis: `<target>`

Defined in: **<repo-name>** (`<path>:<line>`)

### Directly Affected Repos

| Repo | Files | Type |
|------|-------|------|
| <repo> | `<path>:<line>` | usage |
| <repo> | `<path>:<line>` | test |

### Recommended Change Order
1. <repo> — <what to change>
2. <repo> — <what to change>
```

### Architecture Results

```
## Architecture: <topic>

### Dependency Graph
<repo-a> --> @theorchard/songwhip-api --> <repo-b>, <repo-c>
<repo-a> --> @theorchard/songwhip-events --> <repo-d>

### Communication Patterns
- <repo-a> calls <repo-b> via HTTP (REST API)
- <repo-a> publishes events consumed by <repo-c>
```
