# Subagent Prompt Overflow Fallback Protocol

**Purpose:** Define the deterministic recovery workflow when a `Task(subagent_type=...)` invocation returns a "Prompt is too long" error. Eliminates silent ad-hoc inline fallback and preserves an audit trail.

**Reference:** STORY-631 (source incidents), STORY-633 (this protocol).

---

## Trigger

Applies when, after a `Task()` call, the result contains the literal string **"Prompt is too long"** AND `usage.tool_uses` > 0 (the subagent started executing before running out of context). Do NOT retry the same call without trimming, and do NOT silently fall back to inline execution — follow the Recovery Workflow.

---

## Recovery Workflow

Execute Steps 1 → 2 → 3 in order; each step's failure triggers the next. After each step, append one record to the audit log.

### Step 1 — Trim context

Shrink the failed `Task()` prompt, then retry: drop `Read()` of large (>500-line) files not directly referenced; replace full Reads with targeted `Grep(pattern=..., head_limit=50)`; compress constitutional-rules blocks to one-line citations; remove duplicate examples and verbose edge-case descriptions. Success → record `resolution_method="trim_success"`. Continued overflow → Step 2.

### Step 2 — Split delegation

Split the task into N smaller sub-tasks and issue N `Task()` calls (parallel if independent, sequential if ordered), then merge the partial results into the original output contract. Split dimension by subagent type: `test-automator` by Acceptance Criteria; `code-reviewer` by file; `refactoring-specialist` by top-level function/class; `backend-architect`/`frontend-developer` by COMP-NNN component; `framework-analyst` by phase; others by file (clamp N ≤ 10). Success → record `resolution_method="split_success", split_count=N`. Any sub-task overflow → Step 3.

### Step 3 — Inline fallback

The orchestrator executes the task directly with native tools, respecting `test-folder-protection.md`, `spec-file-protection.md`, and the `phase-gate-write.sh` hook. **Hard escalation limits:** >50,000 orchestrator tokens consumed, 2 consecutive inline attempts on the same task, or >10 minutes wall-clock per attempt. On any breach, HALT and escalate to the user via AskUserQuestion. Record `resolution_method="inline_fallback"` — or `"escalated_to_user"` if a limit was breached.

---

## Audit Log Schema

**File:** `tmp/${STORY_ID}/subagent-fallback-log.jsonl` (project-scoped per operational-safety.md Rule 2; if `${STORY_ID}` is unset, `tmp/_framework/subagent-fallback-log.jsonl`). JSON Lines, append-only — one JSON object per line.

Required fields (6): `timestamp` (ISO 8601 UTC), `subagent_type`, `fallback_step_reached` (integer 1/2/3), `original_prompt_length` (character count of the failing prompt, NOT tokens), `tool_uses_before_overflow` (from the Task result usage block), `resolution_method`. Optional: `task_description`, `split_count`, `story_id`, `notes`. `resolution_method` enum: `trim_success`, `split_success`, `inline_fallback`, `escalated_to_user`.

Append with `echo >>` only — POSIX `>>` uses `O_APPEND`, atomic per write and concurrency-safe (`mkdir -p` + `echo >>` are permitted here per the tech-stack.md Bash exception for build infrastructure). `Write()` read-then-append is FORBIDDEN for the log — non-atomic race condition.

---

## Agent References

This protocol applies to all subagents; those with documented overflow history (STORY-631) — `test-automator` (Phase 02, 32 tool_uses), `refactoring-specialist` (Phase 04, 9), `code-reviewer` (Phase 04, 19) — each carry an "Overflow Protocol Reference" subsection in their definition file (`.claude/agents/{name}.md` + `src/` mirror) linking this rule.

---

## Related Rules

- `.claude/rules/workflow/test-folder-protection.md` — Step 3 must not modify test files outside authorized phases
- `.claude/rules/workflow/spec-file-protection.md` — Step 3 must not modify spec files during Phase 04
- `.claude/rules/workflow/operational-safety.md` — Rule 2 governs the `tmp/${STORY_ID}/` audit-log path
- `.claude/rules/workflow/diagnosis-before-fix.md` — audit log records can feed RCA after 3+ failed fallback attempts
- `.claude/hooks/phase-gate-write.sh` — file protection hook that inline fallback must not bypass
