# PB Migration Sequencing Pitfalls (Subagent-Driven Development)

## The Problem

When a plan involves creating/updating PocketBase collections AND frontend UI in the same batch, the frontend code inevitably references the new collection name. If the PB migration hasn't been applied yet, the frontend will:
- Type-check fine (no compile-time dependency on PB schema)
- Build fine (no import dependency)
- **Crash at runtime** with "Missing collection" errors

## When This Happens

The standard batch-parallel pattern (`delegate_task` with independent goals) is susceptible because:
1. Subagent A creates `pb_migrations/M25_new_collection.js`
2. Subagent B writes `pb.collection('newCollection').getList(...)` in a UI component
3. Both execute in parallel — neither knows about the other
4. The PB migration still needs to be `docker cp`'d and `migrate up` applied
5. The frontend code is deployed, but the collection doesn't exist in PB yet

## Mitigation Strategy

**For the agent orchestrating the batch:**

- **Deploy PB migrations BEFORE dispatching frontend subagents.** Wrap the sequence as:
  1. Write all PB migration files
  2. Copy to container and `migrate up`
  3. Verify success with `docker exec` / `--dir` check
  4. THEN dispatch frontend subagents

- **If forced to parallelize** (e.g., PB and frontend for different features are interleaved), add a guard in the frontend subagent's context: "The collection [name] already exists in PB — query it directly." Verify the collection exists first with a curl health check before dispatching.

- **For deployment safety**, add a try/catch around PB queries in new frontend code:
  ```typescript
  try {
    const records = await pb.collection('newCollection').getFullList({...});
  } catch (err) {
    console.warn('[newCollection] not available yet');
    return [];
  }
  ```

## Why This Is Tricky

Unlike module imports (which fail at build time), PB collection references are runtime API calls. The JS bundler doesn't know about them. In the SPQ-v2 project:
- All PB queries go through `pb.collection('name').method()`
- The collection name is a runtime string — no compile-time validation
- Missing collections produce a `404` response from PB, which the frontend may or may not handle gracefully
