# Orchestration Runbook: Code Review Fixes (Run 2)

Companion to `docs/review-07022026/00-executive-summary.md`. Step-by-step playbook for launching 6 parallel Claude Code agents to fix review findings from the 13K-line codebase audit.

---

## Context

The codebase was audited on 2026-02-07 (see `docs/review-07022026/`). Key numbers:
- **15 critical**, 20 high, 25+ medium, 30+ low findings
- **~2,032 lines of dead code** (~17% of Python codebase)
- **~37% of source code** with zero test coverage
- **No authentication** on any endpoint

This run fixes the findings across 6 parallel tracks, one per review area.

---

## Prerequisites

```bash
# Verify Claude Code is installed
claude --version

# Verify gh CLI is authenticated
gh auth status

# Ensure we're on main and up to date
cd /Users/sagar/work/all-things-quickcall/trace
git checkout main
git pull

# Verify worktrees exist
git worktree list
# Should show 6 review-worktrees/* entries

# Verify CLAUDE.md exists in each worktree
for wt in schemas-and-transforms daemon server-and-db utils-and-cli tests dashboard-and-infra; do
  echo "$wt: $(test -f review-worktrees/$wt/CLAUDE.md && echo 'OK' || echo 'MISSING')"
done

# Install deps in each worktree
for wt in schemas-and-transforms daemon server-and-db utils-and-cli tests dashboard-and-infra; do
  (cd review-worktrees/$wt && uv venv 2>/dev/null; uv pip install -e ".[dev]" 2>/dev/null) &
done
wait
echo "All worktrees ready"

# Create progress log directory
mkdir -p /Users/sagar/work/all-things-quickcall/trace/project_logs/run2
```

### Runtime Environment

- Use `uv run` for all Python commands (e.g., `uv run pytest tests/`)
- `gh` CLI is authenticated on this machine — agents can use it directly
- Each worktree has its own `.venv`

---

## Agents Overview

All 6 agents run in parallel with no cross-dependencies.

| Agent | Worktree | Branch | Issue | Key Fixes |
|-------|----------|--------|-------|-----------|
| 1. Schemas | `review-worktrees/schemas-and-transforms` | `fix/review-schemas-and-transforms` | #55 | Token double-counting, non-deterministic UUIDs, schema/transform mismatch |
| 2. Daemon | `review-worktrees/daemon` | `fix/review-daemon` | #56 | Memory OOM, data loss on push failure, delete dead code, auth headers |
| 3. Server & DB | `review-worktrees/server-and-db` | `fix/review-server-and-db` | #57 | Add auth (email + API key), fix CORS, body size limits, fix upsert SQL |
| 4. Utils & CLI | `review-worktrees/utils-and-cli` | `fix/review-utils-and-cli` | #58 | Delete ~856 lines dead code, fix FD leak, add `qc-traced setup` |
| 5. Tests | `review-worktrees/tests` | `fix/review-tests` | #59 | Fix hardcoded paths, add DB reader tests, add daemon main loop tests |
| 6. Dashboard | `review-worktrees/dashboard-and-infra` | `fix/review-dashboard-and-infra` | #60 | Fix session fetch, fix service files, fix port mismatch, fix deps |

---

## Step 1: Verify Worktrees + Branches

Worktrees were created during the review phase. Verify they're ready:

```bash
cd /Users/sagar/work/all-things-quickcall/trace

git worktree list
# Expected:
# .../trace                                    ee77464 [main]
# .../trace/review-worktrees/schemas-and-transforms  ee77464 [fix/review-schemas-and-transforms]
# .../trace/review-worktrees/daemon                  ee77464 [fix/review-daemon]
# .../trace/review-worktrees/server-and-db           ee77464 [fix/review-server-and-db]
# .../trace/review-worktrees/utils-and-cli           ee77464 [fix/review-utils-and-cli]
# .../trace/review-worktrees/tests                   ee77464 [fix/review-tests]
# .../trace/review-worktrees/dashboard-and-infra     ee77464 [fix/review-dashboard-and-infra]

# Branches already pushed to remote
git branch -r | grep fix/review
```

---

## Step 2: Update CLAUDE.md in Each Worktree

The CLAUDE.md files already contain the review findings. Add operational instructions to each.

### Append to ALL worktree CLAUDE.md files

Run this to append agent instructions to each:

```bash
for wt in schemas-and-transforms daemon server-and-db utils-and-cli tests dashboard-and-infra; do
  cat >> review-worktrees/$wt/CLAUDE.md <<'INSTRUCTIONS'

---

# Agent Instructions

## Your Mission
Fix ALL findings listed above in this review document. Work through them in severity order: Critical first, then High, then Medium. Skip Low-severity items unless they're trivial one-liners.

## Constraints
- Python >= 3.11 (use `X | Y` union syntax, not `Optional[X]`)
- No new dependencies unless absolutely necessary
- Use `uv run` for all commands (e.g., `uv run pytest tests/`, `uv run ruff check`)
- COMMIT after each logical change. Do NOT batch everything into one commit.
- Use conventional commits: `fix:`, `refactor:`, `test:`, `chore:` etc.
- Run `uv run pytest tests/` after each change to ensure nothing breaks.
- Push your branch when all work is done: `git push origin HEAD`

## GitHub Issue Reporting
Use `gh` CLI for issue updates.

### When you START work:
```bash
gh issue comment ISSUE_NUMBER --repo quickcall-dev/trace --body "## Status: In Progress

Starting work on review fixes."
```

### After EACH significant commit:
```bash
gh issue comment ISSUE_NUMBER --repo quickcall-dev/trace --body "## Progress Update

**Fixed:** description
**Commit:** \`$(git rev-parse --short HEAD)\`
**Next:** what's next"
```

### When ALL work is done:
```bash
gh issue comment ISSUE_NUMBER --repo quickcall-dev/trace --body "## Status: Completed

All review findings addressed. Tests passing.
**Commits:**
$(git log --oneline origin/main..HEAD)"
```

## Progress File
Write progress after each major milestone to:
/Users/sagar/work/all-things-quickcall/trace/project_logs/run2/WORKTREE_NAME_progress.json

Format:
```json
{
  "status": "in_progress|completed",
  "current_task": "description",
  "completed_tasks": ["task1", "task2"],
  "errors": [],
  "tests_passing": true
}
```
INSTRUCTIONS
done
```

Then customize the ISSUE_NUMBER and WORKTREE_NAME in each:

```bash
cd /Users/sagar/work/all-things-quickcall/trace

# Agent 1: Schemas
sed -i '' 's/ISSUE_NUMBER/55/g; s/WORKTREE_NAME/schemas-and-transforms/g' review-worktrees/schemas-and-transforms/CLAUDE.md

# Agent 2: Daemon
sed -i '' 's/ISSUE_NUMBER/56/g; s/WORKTREE_NAME/daemon/g' review-worktrees/daemon/CLAUDE.md

# Agent 3: Server & DB
sed -i '' 's/ISSUE_NUMBER/57/g; s/WORKTREE_NAME/server-and-db/g' review-worktrees/server-and-db/CLAUDE.md

# Agent 4: Utils & CLI
sed -i '' 's/ISSUE_NUMBER/58/g; s/WORKTREE_NAME/utils-and-cli/g' review-worktrees/utils-and-cli/CLAUDE.md

# Agent 5: Tests
sed -i '' 's/ISSUE_NUMBER/59/g; s/WORKTREE_NAME/tests/g' review-worktrees/tests/CLAUDE.md

# Agent 6: Dashboard
sed -i '' 's/ISSUE_NUMBER/60/g; s/WORKTREE_NAME/dashboard-and-infra/g' review-worktrees/dashboard-and-infra/CLAUDE.md
```

---

## Step 3: Launch All 6 Agents

All agents are independent — launch them all at once.

### Option A: tmux (recommended)

```bash
# Create session with 6 panes (2x3 grid)
tmux new-session -d -s review -c /Users/sagar/work/all-things-quickcall/trace/review-worktrees/schemas-and-transforms
tmux split-window -h -t review -c /Users/sagar/work/all-things-quickcall/trace/review-worktrees/daemon
tmux split-window -h -t review -c /Users/sagar/work/all-things-quickcall/trace/review-worktrees/server-and-db
tmux select-layout -t review even-horizontal

# Split each pane vertically for the bottom row
tmux select-pane -t review:0.0
tmux split-window -v -t review:0.0 -c /Users/sagar/work/all-things-quickcall/trace/review-worktrees/utils-and-cli
tmux select-pane -t review:0.2
tmux split-window -v -t review:0.2 -c /Users/sagar/work/all-things-quickcall/trace/review-worktrees/tests
tmux select-pane -t review:0.4
tmux split-window -v -t review:0.4 -c /Users/sagar/work/all-things-quickcall/trace/review-worktrees/dashboard-and-infra

# Attach
tmux attach -t review
```

Pane layout:
```
+--------------------+--------------------+--------------------+
|  1. Schemas        |  2. Daemon         |  3. Server & DB    |
|  (fix #55)         |  (fix #56)         |  (fix #57)         |
+--------------------+--------------------+--------------------+
|  4. Utils & CLI    |  5. Tests          |  6. Dashboard      |
|  (fix #58)         |  (fix #59)         |  (fix #60)         |
+--------------------+--------------------+--------------------+
```

In each pane, run:
```bash
claude --dangerously-skip-permissions
```

### Option B: Separate terminals

Open 6 terminal windows and run in each:

```bash
# Terminal 1: Schemas
cd /Users/sagar/work/all-things-quickcall/trace/review-worktrees/schemas-and-transforms
claude --dangerously-skip-permissions

# Terminal 2: Daemon
cd /Users/sagar/work/all-things-quickcall/trace/review-worktrees/daemon
claude --dangerously-skip-permissions

# Terminal 3: Server & DB
cd /Users/sagar/work/all-things-quickcall/trace/review-worktrees/server-and-db
claude --dangerously-skip-permissions

# Terminal 4: Utils & CLI
cd /Users/sagar/work/all-things-quickcall/trace/review-worktrees/utils-and-cli
claude --dangerously-skip-permissions

# Terminal 5: Tests
cd /Users/sagar/work/all-things-quickcall/trace/review-worktrees/tests
claude --dangerously-skip-permissions

# Terminal 6: Dashboard
cd /Users/sagar/work/all-things-quickcall/trace/review-worktrees/dashboard-and-infra
claude --dangerously-skip-permissions
```

---

## Step 4: Monitor All Agents

### Dashboard (single terminal)

```bash
for f in /Users/sagar/work/all-things-quickcall/trace/project_logs/run2/*_progress.json; do
  echo "=== $(basename $f .json | sed 's/_progress//') ==="
  python3 -c "
import json, sys
d = json.load(open('$f'))
print(f\"  Status: {d.get('status', '?')}\")
print(f\"  Task:   {d.get('current_task', '?')}\")
print(f\"  Done:   {len(d.get('completed_tasks', []))} tasks\")
print(f\"  Errors: {len(d.get('errors', []))}\")
print(f\"  Tests:  {'PASS' if d.get('tests_passing') else 'FAIL'}\")
" 2>/dev/null || echo "  (not started)"
  echo
done
```

Save as `scripts/review-status.sh` and run:
```bash
watch -n 15 bash /Users/sagar/work/all-things-quickcall/trace/scripts/review-status.sh
```

### Git activity across worktrees

```bash
for wt in schemas-and-transforms daemon server-and-db utils-and-cli tests dashboard-and-infra; do
  echo "=== $wt ==="
  git -C review-worktrees/$wt log --oneline origin/main..HEAD 2>/dev/null || echo "  (no new commits)"
  echo
done
```

### GitHub issue activity

```bash
for issue in 55 56 57 58 59 60; do
  echo "=== Issue #$issue ==="
  gh issue view $issue --repo quickcall-dev/trace --json title,state --jq '"  " + .title + " [" + .state + "]"'
  gh issue view $issue --repo quickcall-dev/trace --json comments --jq '.comments | length | "  Comments: " + tostring'
  echo
done
```

---

## Step 5: Handle Agent Failures / Restarts

If a Claude Code session dies:

```bash
# 1. Check what the agent accomplished
cd /Users/sagar/work/all-things-quickcall/trace/review-worktrees/<worktree-name>
git log --oneline origin/main..HEAD

# 2. Check progress file
cat /Users/sagar/work/all-things-quickcall/trace/project_logs/run2/<worktree-name>_progress.json

# 3. Restart Claude Code in the same worktree
claude --dangerously-skip-permissions
```

The agent picks up where it left off because:
- Git commits preserve all completed work
- The progress JSON shows what's done vs remaining
- The CLAUDE.md contains the full task specification

### If an agent is stuck / looping

```bash
# Kill the session (Ctrl+C)
cd /Users/sagar/work/all-things-quickcall/trace/review-worktrees/<worktree-name>
git log --oneline -5
git diff HEAD~1

# Optionally revert a bad commit
git revert HEAD

# Add a hint to CLAUDE.md then restart
echo "\n## Hint\nThe previous approach of X didn't work. Try Y instead." >> CLAUDE.md
claude --dangerously-skip-permissions
```

---

## Step 6: Merge All Tracks

Once all 6 agents report `"status": "completed"`:

```bash
cd /Users/sagar/work/all-things-quickcall/trace

# Create integration branch
git checkout main
git pull
git checkout -b fix/review-fixes-integrated

# Merge all 6 branches (order doesn't matter — no cross-deps)
git merge --no-ff fix/review-schemas-and-transforms -m "fix: review findings in schemas and transforms (#55)"
uv run pytest tests/ -x

git merge --no-ff fix/review-daemon -m "fix: review findings in daemon (#56)"
uv run pytest tests/ -x

git merge --no-ff fix/review-server-and-db -m "fix: review findings in server and db (#57)"
uv run pytest tests/ -x

git merge --no-ff fix/review-utils-and-cli -m "fix: review findings in utils and cli (#58)"
uv run pytest tests/ -x

git merge --no-ff fix/review-tests -m "fix: review findings in tests (#59)"
uv run pytest tests/ -x

git merge --no-ff fix/review-dashboard-and-infra -m "fix: review findings in dashboard and infra (#60)"
uv run pytest tests/ -x

# If conflicts arise, resolve manually or launch a Claude session:
# claude --dangerously-skip-permissions
# "Resolve the merge conflicts. Run uv run pytest tests/ to verify."
```

### Integration testing

```bash
# Full test suite
uv run pytest tests/ -v

# Server + dashboard smoke test
docker compose down -v && docker compose up -d
uv run python -m qc_trace.server.app &
sleep 2
curl -s http://localhost:19777/health | python3 -m json.tool

# Verify auth is required (should get 401)
curl -s -o /dev/null -w "%{http_code}" http://localhost:19777/ingest
# Expected: 401

# Verify auth works
curl -s -X POST http://localhost:19777/ingest \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-test-key" \
  -H "X-User-Email: test@example.com" \
  -d '[]'
# Expected: 200

# Kill server
kill %1
```

---

## Step 7: Create PR

```bash
git push -u origin fix/review-fixes-integrated

gh pr create \
  --title "fix: address code review findings from 2026-02-07 audit" \
  --body "$(cat <<'EOF'
## Summary

Addresses all critical and high-severity findings from the full codebase audit (#54).

### Security
- Add API key + email authentication to all endpoints (#57)
- Replace CORS wildcard with dashboard origin (#57)
- Add POST body size limits (#57)

### Data Integrity
- Fix daemon state advancement on push failure (#56)
- Fix token double-counting in Claude Code transform (#55)
- Make Codex message IDs deterministic with uuid5 (#55)
- Fix session upsert missing raw_file_path (#57)

### Dead Code Removal (~1,700 lines)
- Delete `utils/schema_extractor.py` (466 lines) (#58)
- Delete `utils/sqlite.py` (390 lines) (#58)
- Delete `daemon/progress.py` (129 lines) (#56)
- Delete 3 dead cursor_parser functions (112 lines) (#58)
- Remove dead `_make_flush_callback` (#57)

### Performance
- Stream Gemini/Cursor file hashing instead of loading 200MB into memory (#56)
- Fix Codex collector O(n) replay per poll cycle (#56)

### Tests
- Fix hardcoded paths for CI portability (#59)
- Add DB reader tests (#59)
- Add daemon main loop tests (#59)
- Use port 0 in reconcile tests (#59)

### Dashboard & Infra
- Fix SessionDetail to use single-session endpoint (#60)
- Fix service files python path (#60)
- Fix port mismatch (#60)
- Add runtime dependencies to pyproject.toml (#60)

## Sub-Issues
Closes #55, closes #56, closes #57, closes #58, closes #59, closes #60

## Test Plan
- [ ] `uv run pytest tests/` passes (all tests)
- [ ] Unauthenticated requests to /ingest return 401
- [ ] Authenticated requests with X-API-Key + X-User-Email succeed
- [ ] CORS header is dashboard origin, not wildcard
- [ ] `qc-traced setup` prompts for email + API key, stores in ~/.qc-trace/config.json
- [ ] Daemon sends auth headers on push
- [ ] Dead code files are gone (schema_extractor.py, sqlite.py, progress.py)
- [ ] Dashboard SessionDetail loads single session (not all)
- [ ] No hardcoded paths in tests
EOF
)"
```

---

## Step 8: Cleanup

After PR is merged:

```bash
cd /Users/sagar/work/all-things-quickcall/trace

# Kill tmux session
tmux kill-session -t review

# Remove worktrees
for wt in schemas-and-transforms daemon server-and-db utils-and-cli tests dashboard-and-infra; do
  git worktree remove --force review-worktrees/$wt
done
rmdir review-worktrees

# Delete local branches
git branch -D fix/review-schemas-and-transforms fix/review-daemon fix/review-server-and-db \
  fix/review-utils-and-cli fix/review-tests fix/review-dashboard-and-infra \
  fix/review-fixes-integrated

# Delete remote branches
for branch in fix/review-schemas-and-transforms fix/review-daemon fix/review-server-and-db \
  fix/review-utils-and-cli fix/review-tests fix/review-dashboard-and-infra; do
  git push origin --delete $branch
done

# Close epic
gh issue close 54 --repo quickcall-dev/trace --comment "All review findings addressed in PR #XX"
```

---

## Quick Reference: tmux Layout

```
+--------------------+--------------------+--------------------+
|  1. Schemas        |  2. Daemon         |  3. Server & DB    |
|  #55               |  #56               |  #57               |
|  3H, 10M, 12L      |  2C, 4H, 7M       |  3C, 6H, 9M       |
+--------------------+--------------------+--------------------+
|  4. Utils & CLI    |  5. Tests          |  6. Dashboard      |
|  #58               |  #59               |  #60               |
|  2C, 4H, 7M        |  5C, 6H           |  3C, 6H, 9M       |
+--------------------+--------------------+--------------------+
```

---

## Timeline Estimate

```
Phase 1: All 6 agents in parallel         (~45-90 min)
Phase 2: Merge + conflict resolution      (~15-30 min)
Phase 3: Integration testing              (~15 min)
Phase 4: PR + cleanup                     (~10 min)
─────────────────────────────────────────
Total:                                    ~1.5-2.5 hours active
```

All agents can run unattended. Check in periodically via the monitoring dashboard.

---

## Auth Implementation Detail

The auth fix spans 3 agents:

| Component | Agent | What to build |
|-----------|-------|---------------|
| `qc-traced setup` CLI | 4. Utils & CLI (#58) | Prompt for email + API key, store in `~/.qc-trace/config.json` |
| Daemon auth headers | 2. Daemon (#56) | Read config, send `X-API-Key` + `X-User-Email` on `/ingest` POST |
| Server auth middleware | 3. Server & DB (#57) | Validate `X-API-Key` against `QC_TRACE_API_KEYS` env var, reject 401 |

**Decision:** Ask user for email explicitly (not inferred from git config). Manual API key provisioning for now.

**Why ask instead of infer?** Git config is fragile — different emails for work vs personal, config might not be set, would be guessing. Just ask once, store it.

---

## Lessons from Run 1

Applied from the previous orchestration run (`docs/run1-07022026/`):

1. **CLAUDE.md says "COMMIT after each file change"** — prevents lost work
2. **`gh` CLI IS authenticated this time** — agents can use it directly (no MCP workaround needed)
3. **`uv run` for all Python commands** — explicit in CLAUDE.md
4. **Progress JSON files** — enables monitoring without interrupting agents
5. **Worktrees already created and deps installed** — no setup overhead for agents
