---
name: gpt-orchestrator
description: Use when coordinating several substantial tasks through ask-gpt or ChatGPT Pro, recovering active conversations after wrapper failures, iterating on partial AI deliverables, or validating and landing multiple generated artifacts without duplicate work.
argument-hint: "<objective|plan-path> [existing conversation IDs]"
---

# GPT Orchestrator

Audience: AI coding agents first.

Run ask-gpt Pro as durable external workers. Keep one producer per task. Trust local evidence, never model narration. Generate concurrently; integrate safely; ship end-to-end.

## Inputs

Accept any combination:

- broad objective;
- plan/spec path;
- task list;
- existing ask-gpt conversation IDs or URLs;
- preserved WIP/worktrees/artifacts.

No task list → derive independent tasks from acceptance boundaries and overlapping-file risk. Record dependencies before dispatch.

## Source of truth

1. Read applicable repository instructions and durable plan index.
2. Run `ask-gpt --help`; current help overrides stale examples here.
3. Create or update one durable plan before dispatch.
4. Maintain one durable ledger. Chat is summary only.
5. NEVER mutate shared/default checkout. Claim isolated worktree before application.

## Durable ledger

Record every task:

| Field | Required value |
|---|---|
| Task | stable ID + slug + acceptance criteria |
| Scope | repositories, paths, plan/spec, dependencies |
| Package | path, SHA-256, included/excluded manifest |
| Dispatch | command owner, timestamp, output/error paths |
| Title | exact first line validated before send |
| Conversation | ID, URL, account, identity evidence |
| State | exact state below |
| Artifact | downloaded paths, hashes, inventory |
| Verification | commands, clean results, findings |
| Integration | base SHA, worktree, commit, landing/deploy receipt |
| Current receipt | latest proved fact; never forecast |
| Next action | executable action or genuine blocker |

Use exactly one state:

1. `QUEUED`
2. `DISPATCHING`
3. `GENERATING`
4. `ARTIFACT_READY`
5. `VALIDATING`
6. `CORRECTION_REQUIRED`
7. `CORRECTING`
8. `APPLYING`
9. `VERIFYING`
10. `LANDED`
11. `DONE`
12. `BLOCKED`
13. `FAILED`
14. `SUPERSEDED`

`DONE` means applied, cleanly tested, landed, deployed/installed/armed when applicable, owner-visible, receipt recorded. Answer returned, ZIP claimed, local commit, or green worktree is NEVER done.

## Decompose and schedule

1. Split by independently verifiable acceptance boundary.
2. Keep cross-cutting contract + consumers in one task unless interface is already pinned.
3. Record expected files and overlap before dispatch.
4. Let independent Pro generations run concurrently.
5. Validate independent artifacts concurrently when worktrees do not overlap.
6. Apply and land overlapping tasks sequentially against refreshed canonical baseline.
7. Assign exactly one writer per worktree.
8. External generation wait MUST NOT idle orchestration. Continue another executable lane; rely on tracked completion notification. NEVER rapid-poll.

## Package contract

Create task-slug package: `<task-slug>-package.zip`. Include only required context:

- `context/TASK.md`: outcome, current state, acceptance criteria, deliverables, prohibited behavior;
- root/project `CLAUDE.md` and mandatory agent/skill rules;
- authoritative plan/spec;
- bounded current source and tests;
- preserved WIP diff/manifest when continuation depends on it.

Before upload:

1. Inventory entries.
2. Verify required files exist.
3. Exclude `.git`, dependencies, caches, generated output, unrelated source, `.env`, credentials, secrets, private conversation indexes/URLs, and logs.
4. Run ZIP CRC check.
5. Record compressed size, entry count, expanded size, and SHA-256.

Oversized context → narrow scope; never drop mandatory rules/specs.

## Conversation title contract

Validate every new/resumed prompt before send. Validation failure MUST block send; fix prompt, validate again, then send. Record exact validated line 1 in ledger `Title` field.

Theme prompts:

1. Line 1 MUST begin exactly `Create <theme-name> WordPress theme` with real theme name substituted.
2. Line 1 MAY append concise outcome language after required prefix.
3. Line 1 MUST NOT begin attachment-reading instructions.
4. Line 1 MUST NOT mention `TASK.md` or `PROMPT.md`.
5. Line 2 onward MUST contain attachment-reading and operational instructions.

TARGET:

```text
Create Acme WordPress theme with accessible editorial layouts
Read attached context/TASK.md and every mandatory rule/spec. Complete task against attached current source…
```

DO NOT — reject before send:

```text
Read TASK.md and PROMPT.md, then create Acme WordPress theme
```

DO NOT — reject before send:

```text
Read attached context/TASK.md and every mandatory rule/spec…
Create Acme WordPress theme
```

Non-theme prompts:

1. Line 1 MUST be concise task-specific outcome: `<verb> <specific system> <specific outcome>`.
2. Line 1 MUST NOT begin attachment-reading instructions or mention `TASK.md`/`PROMPT.md`.
3. Line 2 onward MUST contain attachment-reading and operational instructions.
4. Correction line 1 MUST keep original task identity plus correction scope.

TARGET:

```text
Restore Factory run explorer performance and detail UX
Read attached context/TASK.md and every mandatory rule/spec. Complete task against attached current source…
```

TARGET — correction:

```text
Correct Factory run explorer pagination and cache races
Read attached correction brief. Repair only proven gaps…
```

DO NOT — reject before send:

```text
Read attached context/TASK.md and every mandatory rule/spec…
```

Generic first lines create repeated invisible titles such as “Task execution instructions.”

## Deliverable contract

Every implementation/audit correction prompt MUST require:

1. real downloadable `<task-slug>-files.zip`;
2. fail-closed `apply-and-verify-<task-slug>.sh`;
3. concise `AGENT-INSTRUCTIONS.md`;
4. no inline source dump.

Prose is not artifact evidence. Markdown source is NEVER a fallback: rendered text can lose `#`, `*`, indentation, globs, and newlines. Missing attachment → `CORRECTION_REQUIRED`; resume same conversation and demand real files.

Use short operational prompt; put details in attached `context/TASK.md`:

```text
<Concise task description>
Read attached context/TASK.md and every mandatory rule/spec. Complete task against attached current source. Return real downloadable <slug>-files.zip, fail-closed apply-and-verify-<slug>.sh, and AGENT-INSTRUCTIONS.md. No inline source. Preserve correct WIP; report exact blockers.
```

DO NOT paste long specs into prompt. DO NOT ask for `===FILE===` blocks.

## Send queue — global rate limit

ALL new and resumed prompt sends share one dispatcher. Keep starts 55–75 seconds apart across the whole orchestration, not per task. Downloads/list/search send no prompt and need no spacing.

1. Record `last_prompt_sent_at` and `next_send_not_before` in ledger.
2. Queue new dispatches and corrections together.
3. Start one background dispatcher; never launch independent jitter sleeps per job.
4. After each confirmed send, choose next delay within 55–75 seconds.
5. Wrapper failure does not erase send timestamp or conversation possibility.

Current new-task shape:

```bash
ask-gpt --effort pro -a <task-slug>-package.zip \
  --out <task-dir>/output --json --timeout 7200 \
  "<Concise task description>
Read attached context/TASK.md and every mandatory rule/spec…"
```

Current correction shape:

```bash
ask-gpt --effort pro --resume <conversation-id> \
  -a <task-slug>-correction-context.zip \
  --out <task-dir>/correction-output --json --timeout 7200 \
  "Correct <specific task> <specific proven gap>
Read attached correction brief. Repair only proven gaps. Return replacement real ZIP, apply/test script, and instructions. No inline source."
```

If current `ask-gpt --help` differs, use current syntax and update ledger.

## Dispatch recovery — NEVER duplicate active work

A local nonzero exit, timeout, empty stdout, or missing output file does NOT prove remote failure. NEVER redispatch until remote identity/state is reconciled.

Recover conversation identity in order:

1. parse JSON result and redirected stdout/stderr for `resume: ask-gpt --resume <id>`;
2. use `ask-gpt --list`, `--search`, then `--list-all`/local registry;
3. match account, creation time, title, initial prompt, package/task slug, and conversation URL;
4. inspect supported per-conversation log/state;
5. classify unresolved identity `BLOCKED`, never guess.

`--list-all` writes private conversation metadata. Keep registry output ignored and mode 0600; NEVER package or commit it.

Conversation still generating → leave it alive, record `GENERATING`, continue another lane. Explicit terminal failure with no usable artifact → resume same conversation when possible. Create replacement conversation only after proving original irrecoverable; link old/new IDs and mark old `SUPERSEDED`.

## Retrieve and validate artifacts

Retrieve only after completion:

```bash
ask-gpt --download-attachments <conversation-id> --out <clean-download-dir>
```

`ARTIFACT_READY` requires actual non-empty downloaded bytes. Model text claiming “attached” proves nothing.

Treat archives and scripts as hostile input:

1. Save outside source tree; record filenames, sizes, SHA-256, conversation ID.
2. Verify file type/magic and ZIP CRC.
3. Reject absolute paths, `..`, NUL/control names, duplicate paths, case collisions, symlinks, hardlinks, devices, unexpected binaries, nested archives, and scope escape.
4. Enforce entry-count, per-file, expanded-size, and compression-ratio limits before extraction.
5. Extract into fresh quarantine, never a worktree.
6. Compare archive inventory with promised changed-file scope.
7. Read complete apply/test script before execution. Reject destructive Git, shared-checkout writes, secret access, network/deployment targets outside task contract, or blind copies.
8. Compare every candidate file with current source. Reject stale architecture, placeholders, removed security checks, unrelated changes, generated noise, and duplicated functionality.
9. Record accepted, modified, and rejected files with reasons.

Any failed archive invariant quarantines whole artifact. NEVER salvage “safe-looking” entries from failed validation.

## Preserve, apply, verify

1. Inventory target worktree: committed, staged, dirty, untracked, ignored-important, stash.
2. Preserve relevant state under durable recovery refs/snapshots before mutation.
3. Create or reuse task-owned isolated worktree from current canonical baseline.
4. Apply accepted changes surgically. NEVER unzip/copy whole archive over source.
5. Resolve conflicts from current contracts and tests—not generated file preference.
6. Run deterministic focused regression first.
7. Run repository-native lint/type/build/unit/integration/security/release gates.
8. Address every error, warning, notice, and security-gate line.
9. Verify real installed/deployed entrypoint when task contract requires it.
10. Record exact commands, results, commit, and runtime receipt.

Generated apply script is advisory until reviewed. Local verification owns truth.

## Correction loop

Any wrong, partial, unsafe, stale, non-applying, or test-failing output → `CORRECTION_REQUIRED`.

1. Build bounded correction package containing original task, artifact hashes/inventory, exact current diff, exact failed commands/output, preserved correct files, and required delta.
2. Resume same conversation with `--resume`; NEVER start fresh by default.
3. Keep prompt short; attach evidence.
4. Require replacement real downloadable ZIP/script/instructions.
5. Download into fresh directory; never mix artifact generations.
6. Re-run full validation and verification. No iteration cap while conversation remains productive.
7. Repeated contract violation or irrecoverable thread → prove failure, then supersede explicitly.

For substantial audit/redesign, send evidence back to ask-gpt Pro rather than substituting an untracked local redesign. Deterministic local checks and independent review remain mandatory.

## Landing order

1. Refresh canonical remote immediately before integration.
2. Land clean independent low-conflict tasks first.
3. Rebase/reimplement later artifacts against each newly landed baseline.
4. Land shared contracts before consumers.
5. Land high-overlap/security/migration work sequentially.
6. Use repository landing command; never invent merge/push ceremony.
7. Deploy/install/arm through repository procedure.
8. Verify owner-visible behavior.
9. Mark `DONE`; retire worktree only after preservation and landing proof.

## Owner report

Keep chat ultra-concise. Report ledger summary:

- **Done:** shipped task IDs + commits + deployment receipt.
- **In progress:** active process/conversation and proved state.
- **Deferred:** intentional dependency/order wait.
- **Blocked:** genuine external blocker + unblock condition.
- **Skipped:** duplicate dispatch, unsafe artifact, stale files, or inapplicable gates + reason.

NEVER end with an executable “Next:” action. Execute it now. Name a next action only when a genuine external blocker prevents execution.

## Common failures

| Failure | Required response |
|---|---|
| Wrapper exits nonzero but remote job exists | Recover ID; NEVER redispatch |
| Independent per-job jitter | Replace with one global send queue |
| “ZIP attached” only in prose | Download; absent bytes → same-thread correction |
| Inline source dump | Reject; demand real downloadable ZIP |
| Generic `package.zip` | Rename/rebuild as task-slug package |
| Artifact applies cleanly | Still review scope/current architecture/security |
| Dirty overlapping WIP | Preserve; isolated three-way reconciliation |
| One job generating | Continue another executable lane; no rapid polling |
| Tests pass with warnings | Not clean; resolve every signal |
| Local commit exists | Not done; land/deploy/verify |
| Conversation repeatedly fails | Prove irrecoverable; link replacement; never silently duplicate |

## Red flags

Stop and correct orchestration when reasoning says:

- “The wrapper failed, so send it again.”
- “The answer says the ZIP exists.”
- “Markdown is good enough.”
- “Each job sleeps independently.”
- “Apply all generated files.”
- “The worktree test passed, so done.”
- “Wait for every job before integrating anything.”
- “Start a fresh conversation for the correction.”
- “Ask owner whether to land/deploy.”
