Repository navigation
Description
Problem
Three related problems when agents invoke child sessions for review runs:
1. Model slug stripping
Agents strip @default (and other @suffix version snapshots) from model slugs like google-vertex-anthropic/claude-opus-4-6@default when calling the invoke_agent plugin tool. They misinterpret the @suffix as a variant and either pass it as the separate variant parameter or drop it entirely.
The review-dispatch pipeline itself preserves @default faithfully — profilePair(), mergeOverride(), and serializeDispatchPlan() all pass the model slug through without transformation. The LLM is the weak link: it misreads plan output or strips the suffix when constructing invoke_agent calls.
Evidence
Session log shows:
plan_review_dispatchreturnedmodel: "google-vertex-anthropic/claude-opus-4-6"withvariant: null(agent stripped@default)- Agent passed model without
@default→ all 4invoke_agentcalls failed with "Unexpected server error" - After manual correction to include
@default, retry succeeded on all 4 runs
2. Prompt construction bloat
invoke_agent only accepts prompt as an inline string parameter — there is no file reference option. For review-council runs, the agent builds ~94KB prompt files on disk (diff + sibling evidence + convention packs + review context), then must:
- Read each file into its own context (~94KB per agent)
- Reproduce the content verbatim in each tool call parameter (5 × 94KB = 470KB inline text)
- Stay under its own context window while doing so
This causes analysis paralysis (observed: 3+ minutes of thinking time, multiple compression cycles) and frequently fails when the agent can't fit the prompt content into tool call parameters.
3. Post-dispatch consolidation bloat
After all dispatch runs complete, the agent must manually:
- Track run metadata — generate UUIDs via
uuidgen, guess timestamps, reconstruct usage data - Deduplicate findings — merge by normalized file + root_cause across 5+ runs, apply compound severity
- Compute verdict — apply precedence rules (REQUEST CHANGES > APPROVE WITH ADVISORIES > APPROVE)
- Process lesson proposals — pass full child output text to
prepare_lesson_learning - Build finalization payload — assemble a ~50-field JSON payload for
finalize_review_dispatch
This burns 3+ minutes of thinking time and fails when child outputs are lost to context compression (observed: "recording as informational skips" because agent couldn't access compressed child output for lesson processing).
Root Cause
All three problems stem from the LLM sitting in the data path:
- Model resolution: LLM sits between
plan_review_dispatch(correct slug) andinvoke_agent(needs correct slug), and misinterprets@suffix - Prompt delivery: LLM must read prompt content into context then reproduce it in tool calls, instead of the tool reading from disk directly
- Run tracking: LLM is the only state holder between dispatch runs and finalization — when context compresses, metadata and child outputs are lost
Solution: Option C — Shared Executor + Stateful Dispatch + Deterministic Consolidation
Remove the LLM from the model-resolution, prompt-delivery, and consolidation paths:
- Extract shared session management to a library
- Add
promptFiletoinvoke_agentso it reads prompt content from disk - Create
dispatch_agent_runtool with deterministic model resolution and filesystem-backed state - Create
consolidate_dispatchtool that deduplicates, computes verdict, processes lessons, and builds finalization payload — all deterministically - Register
submit_review_findingsandsubmit_lesson_proposaltools that child agents call to submit structured data via Zod-validated tool calls — no text parsing needed
Architecture
.opencode/lib/
agent-executor.ts <- NEW: shared session management + schemas
reviewer-manifest.ts <- existing (no changes)
review-dispatch-*.ts <- existing (no changes)
.opencode/plugins/
invoke-agent/index.ts <- REFACTORED: delegates to shared executor, adds promptFile
review-dispatch/index.ts <- EXTENDED: dispatch_agent_run, consolidate_dispatch, dispatch_status,
submit_review_findings, submit_lesson_proposal
/tmp/opencode/dispatch-<correlation_id>/ <- Dispatch session state (ephemeral)
plan.json <- written by plan_review_dispatch
run-<agent>.json <- written by dispatch_agent_run (metadata + findings + lesson proposal)
run-<agent>.output.txt <- written by dispatch_agent_run (full child text for reference)
Phase 1: Extract shared executor to .opencode/lib/agent-executor.ts
Move reusable session management from invoke-agent/index.ts to a shared library:
Types that move: ModelIdentity, InvocationTokens, InvocationUsage, InvocationError, InvocationProvenance, InvokeAgentResult
Schemas that move: PromptSchema, PromptFileSchema, TimeoutSchema, MAX_INLINE_PROMPT_BYTES, MAX_PROMPT_FILE_BYTES
Functions that move: errorText(), sanitizeInvocationError(), responseFailure(), directModelIdentity(), reportedModel(), failedResult(), invocationUsage(), responseText(), validateTimeout()
New shared function:
export interface ExecutorDependencies {
readonly client: PluginInput["client"]
readonly sessionID: string
readonly directory: string
readonly parentAbort: AbortSignal
readonly timeoutMilliseconds: number
}
export async function executeAgentSession(
deps: ExecutorDependencies,
agent: string,
promptText: string,
model: ModelIdentity,
variant: string | undefined,
read_only: boolean,
provenance: InvocationProvenance,
): Promise<InvokeAgentResult>This function owns: abort controller setup, child session create, prompt with model/variant, response parsing (text, usage, mismatch check), timeout, cancellation, cleanup.
It does NOT own: input validation, manifest checking, model resolution, host introspection, prompt file reading.
invoke-agent/index.ts re-exports all moved types and sanitizeInvocationError so existing test imports remain stable.
Phase 2: Refactor invoke-agent/index.ts + add promptFile
Two changes:
2a. Shared executor delegation. invokeAgent() shrinks from ~175 lines to ~50 lines. It keeps: input parsing/validation, manifest checking, host model resolution. It delegates session management to executeAgentSession().
2b. promptFile parameter. Add an optional promptFile parameter to the input schema. When provided, the plugin reads the file from disk using deps.readText() and uses its content as the prompt. Mutually exclusive with prompt (exactly one required via .superRefine()).
Phase 3: New dispatch_agent_run tool in review-dispatch plugin
Purpose: Accept agent + prompt/promptFile + tier (or explicit model). Read the review matrix to resolve the exact model slug deterministically. Call executeAgentSession() directly. Persist run metadata and child output to the dispatch session directory. Return the result. No LLM in the model-resolution, prompt-delivery, or state-tracking loop.
Stateful dispatch session (filesystem-backed):
dispatch_agent_run persists each run to disk automatically:
/tmp/opencode/dispatch-<correlation_id>/
run-<agent>.json # { run_id, agent, model, variant, status, started_at,
# finished_at, usage, provenance, findings[], error }
run-<agent>.output.txt # Full child agent text output (for lesson proposals)
The correlation_id comes from the plan (either passed explicitly or generated). Each call writes atomically — survives process restarts. The agent never needs to track run IDs, timestamps, or child output text in its own context.
Structured data via child tool calls:
Instead of parsing JSON from child agent prose, findings and lesson proposals are submitted via Zod-validated tool calls. Two new tools are registered in the review-dispatch plugin and available to all agents (including child Divisor agents in dispatch sessions):
submit_review_findings — Child agent calls this during review to submit structured findings:
const ReviewFindingSchema = z.object({
severity: z.enum(["CRITICAL", "HIGH", "MEDIUM", "LOW"]),
category: z.string().min(1).max(128),
description: z.string().min(1).max(16384),
root_cause: z.string().min(1).max(4096),
file: z.string().max(1024).nullable(),
line: z.number().int().positive().nullable(),
})
// Input: { findings: ReviewFindingSchema[] }
// Output: { status: "ok", count: number }submit_lesson_proposal — Child agent calls this to submit a lesson proposal:
// Input: { information: string, tag: string, category?: string }
// Output: { status: "ok" }In-process handoff mechanism:
Both tools store submitted data in a module-level Map<string, SubmittedData> keyed by context.sessionID. After the child session completes, dispatch_agent_run looks up findings and lesson proposals by the child session ID, includes them in the persisted run-<agent>.json, and cleans up the Map entry.
Child agent workflow:
1. Analyze diff, produce prose review
2. submit_review_findings({ findings: [...] }) ← Zod-validated at call time
3. submit_lesson_proposal({ information, tag }) ← optional, Zod-validated
4. Return prose text
dispatch_agent_run (after child completes):
1. Read findings from Map[childSessionID] ← already validated, no parsing
2. Read lesson proposal from Map[childSessionID] ← already validated
3. Persist both to run-<agent>.json
4. Clean up Map entries
Advantages over JSON text parsing:
- Schema validation at submission time — malformed data is rejected before it's stored
- Agent writes free-form prose review without structuring around JSON blocks
- No regex/JSON.parse error handling needed
- Graceful degradation: if child doesn't call the tool, findings/proposals are empty (same outcome, simpler code)
Phase 4: New consolidate_dispatch tool
Purpose: Read all accumulated run results from the dispatch session directory, deduplicate findings, compute verdict, process lesson proposals, and return a ready-to-submit finalization payload. All deterministic — no LLM judgment.
Input:
const ConsolidateDispatchInputSchema = z.object({
correlation_id: z.string().uuid(),
// Pre-flight coverage from the calling command
coverage: z.object({
checks_passed: z.number().int().min(0),
checks_total: z.number().int().min(0),
preflight_verdict: z.enum(["PASS", "FAIL", "SOFT_GATE", "NOT_RUN"]),
}),
// Sibling evidence for lesson processing (from acquire_sibling_evidence)
sibling_evidence_path: z.string().max(1024).optional(),
// Known dedupe hashes for lesson deduplication
known_dedupe_sha256: z.array(z.string().regex(/^[0-9a-f]{64}$/)).optional(),
})Deterministic algorithms implemented:
-
Finding deduplication — Group by
normalize(file) + root_cause. When multiple runs report the same root cause on the same file, merge into one finding with all contributingrun_ids. -
Compound severity — When 3+ distinct root causes converge on the same defect, escalate one tier. Individual run severities use highest-wins within each deduplicated group.
-
Verdict computation — Precedence: any blocking HIGH or CRITICAL =
REQUEST CHANGES. Any MEDIUM without blocking =APPROVE WITH ADVISORIES. OtherwiseAPPROVE. Failed/cancelled runs don't vote. -
Lesson proposal processing — For each run with a
submit_lesson_proposalentry in the persistedrun-<agent>.json, callprepare_lesson_learningwith the sibling evidence and dedupe hashes. No text extraction needed — proposals are already structured from the tool call. Store results (accepted/rejected/skipped) in the output. -
Finalization payload assembly — Build the complete
finalize_review_dispatchpayload from accumulated plan + run data. Most fields are mechanical echoes of the plan entries and run metadata.
Output:
{
status: "ok",
data: {
verdict: "APPROVE" | "APPROVE WITH ADVISORIES" | "REQUEST CHANGES",
verdict_reason: string,
deduplicated_findings: Finding[],
advisories: Advisory[],
lesson_outcomes: { agent: string, status: "accepted" | "rejected" | "skipped", reason?: string }[],
finalization_payload: object, // Ready to pass to finalize_review_dispatch
}
}Phase 5: New dispatch_status query tool
Purpose: Debugging and observability. Returns the current state of a dispatch session.
Input: { correlation_id: string }
Output: List of completed runs with agent, status, finding count, and timestamps. Shows which runs are pending vs. complete. Helps agents recover from partial failures.
Phase 6: Dual-copy sync
Every change applied to BOTH:
.opencode/lib/and.opencode/plugins/(scaffolded/runtime)internal/scaffold/assets/opencode/lib/andinternal/scaffold/assets/opencode/plugins/(canonical/embedded)
Existing drift detection tests enforce this.
Phase 7: Tests
| Test file | Changes |
|---|---|
invoke-agent.test.ts |
Add promptFile tests: file read, mutual exclusivity validation |
invoke-agent-boundaries.test.ts |
Add boundary: both prompt + promptFile provided, neither provided |
invoke-agent-prompt-file.test.ts |
Dedicated promptFile tests: file read, size limits, error handling |
dispatch-agent-run.test.ts |
Tier resolution, explicit model, promptFile, session lifecycle, filesystem persistence, child tool call handoff |
submit-tools.test.ts |
NEW: submit_review_findings validation, submit_lesson_proposal validation, Map handoff lifecycle |
consolidate-dispatch.test.ts |
NEW: Finding deduplication, compound severity, verdict computation, lesson processing, payload assembly |
dispatch-status.test.ts |
NEW: Session state queries, partial completion, empty session |
plugin-integration.test.ts |
Integration test for dispatch_agent_run + consolidate_dispatch pipeline |
Agent-side: end-to-end workflow
After this ships, the dispatch workflow in command files shrinks from ~3 minutes of manual tracking to:
# Step 4a: Plan
plan_review_dispatch({ mode, discovered_agents, changed_files })
→ returns plan with correlation_id
# Step 4b: Execute each run (in parallel)
dispatch_agent_run({ agent: "divisor-adversary", promptFile: "/tmp/.../prompt.md", tier: "standard" })
dispatch_agent_run({ agent: "divisor-architect", promptFile: "/tmp/.../prompt.md", tier: "standard" })
...
→ each persists run metadata + child output to /tmp/opencode/dispatch-<id>/
# Step 6: Consolidate (one call replaces 3+ minutes of manual work)
consolidate_dispatch({ correlation_id, coverage: { ... } })
→ returns verdict, deduplicated findings, lesson outcomes, finalization payload
# Step 6b: Finalize
finalize_review_dispatch(payload) # payload from consolidate_dispatch output
File Change Summary
| File | Action | Est. Lines |
|---|---|---|
.opencode/lib/agent-executor.ts |
CREATE | ~350 |
internal/scaffold/assets/opencode/lib/agent-executor.ts |
CREATE (canonical) | ~350 |
.opencode/plugins/invoke-agent/index.ts |
EDIT — extract to lib, add promptFile, add re-exports | Net -100 |
internal/.../invoke-agent/index.ts |
EDIT (canonical) | Same |
.opencode/plugins/review-dispatch/index.ts |
EDIT — add 5 tools, capture client, filesystem state, child handoff Map | +550 |
internal/.../review-dispatch/index.ts |
EDIT (canonical) | Same |
.opencode/test/dispatch-agent-run.test.ts |
CREATE | ~450 |
.opencode/test/submit-tools.test.ts |
CREATE | ~200 |
.opencode/test/consolidate-dispatch.test.ts |
CREATE | ~350 |
.opencode/test/dispatch-status.test.ts |
CREATE | ~100 |
.opencode/test/invoke-agent-prompt-file.test.ts |
CREATE | ~220 |
.opencode/test/invoke-agent.test.ts |
EDIT — minor adjustments | +10 |
.opencode/test/plugin-integration.test.ts |
EDIT — add integration tests | +60 |
Open Questions
1. Tool name
dispatch_agent_run is the current working name. Alternatives: run_dispatch_agent, execute_dispatch_run. The name should clearly convey that it reads matrix config and invokes an agent in one deterministic step. Feedback welcome.
2. Tier vs. profile
The review matrix has named profiles (lightweight, standard, heavy). Should the input parameter be called tier (matching the existing TierSchema enum used throughout the codebase) or profile (matching the matrix config structure name profiles)?
3. Manifest validation
Should dispatch_agent_run also validate the agent against the reviewer manifest (.uf/reviewer-capabilities.yaml), as invoke_agent does? Arguments for: defense in depth. Arguments against: the dispatch plan already validated the agent, and skipping it removes a file read.
4. Dispatch advisor skill update
Once this ships, the dispatch-advisor skill (.opencode/skills/dispatch-advisor/SKILL.md) should instruct agents to call dispatch_agent_run instead of invoke_agent for review runs. Should that skill update be included in this change or tracked separately?
5. Backward compatibility
invoke_agent remains fully functional — dispatch_agent_run is additive. The promptFile addition to invoke_agent is also backward-compatible (existing callers that pass prompt inline continue to work unchanged). The new tool is the recommended path for dispatch-driven invocations where deterministic model resolution matters.
6. Child tool availability
submit_review_findings and submit_lesson_proposal are registered as plugin tools in review-dispatch, making them available to all agents including child Divisor agents in dispatch sessions. Should the child agent prompt explicitly instruct agents to call these tools, or should the tool descriptions be sufficient for agents to discover and use them?
7. Map cleanup on failure
If dispatch_agent_run fails after the child agent has already called submit_review_findings, the Map entry must be cleaned up. Should cleanup happen in a finally block (always), or only on success (orphaned entries expire naturally since they're in-process memory)?
Acceptance Criteria
-
agent-executor.tsin.opencode/lib/withexecuteAgentSession()and all moved types/functions/schemas -
invoke-agent/index.tsrefactored to use shared executor; re-exports preserve import compatibility -
invoke_agentacceptspromptFileas alternative to inlineprompt(mutually exclusive, validated via superRefine) -
dispatch_agent_runtool registered in review-dispatch plugin -
dispatch_agent_runreads review matrix and resolves model slug deterministically (including@suffix) -
dispatch_agent_runacceptspromptFilefor disk-based prompt delivery -
dispatch_agent_runpersists run metadata and child output to filesystem (/tmp/opencode/dispatch-<id>/) -
submit_review_findingstool registered in review-dispatch plugin with Zod-validated finding schema -
submit_lesson_proposaltool registered in review-dispatch plugin with Zod-validated proposal schema -
dispatch_agent_runreads findings and lesson proposals from in-process Map after child session completes -
consolidate_dispatchtool deduplicates findings by normalized file + root_cause -
consolidate_dispatchapplies compound severity rules -
consolidate_dispatchcomputes verdict using precedence rules -
consolidate_dispatchprocesses lesson proposals from persisted run data (submitted via tool calls) -
consolidate_dispatchreturns a ready-to-submit finalization payload -
dispatch_statustool returns current session state for debugging - Dual-copy sync maintained (canonical + scaffolded)
- All existing tests pass unchanged
- New tests cover all new tools and paths
-
make plugin-testpasses -
make checkpasses
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsNo status
Activity
jflowers commentedon Oct 7, 2026
Related gap: orchestrator prompt content, not just delivery
While investigating fullsend-ai/agents#1621 (review agent missed that
REVIEW_GIT_FETCH_DEPTHis unreachable in the sandbox), I traced the root cause through two review-council sessions and found a content gap that #680 does not cover.What #680 fixes (delivery mechanism)
@defaultdropped by LLM)What is still missing (prompt content)
The orchestrator (
uf.review-council.md) constructs each child agent prompt from scratch with its own## Instructionssection. It does not incorporate content from.opencode/agents/divisor-*.mdagent definitions. Even thoughinvoke_agentpassesbody.agent = "divisor-fullsend"(which should inject the agent definition as a system prompt), the parent's detailed user prompt overshadows it — the child agent follows the user prompt's instructions exclusively.This means the following content in agent definitions is invisible at runtime:
bash.md,bash-custom.md)Evidence from session traces:
divisor-fullsendagent definition (.opencode/agents/divisor-fullsend.md) contains explicit instructions to load bash packs, run Dewey queries, and verify skill env-var reachabilityProposed fix
When the orchestrator builds each child prompt, it should include the agent definition content. Simplest approach: add an instruction in the child prompt telling the agent to read its own definition file at
.opencode/agents/{agent}.mdas Step 0, similar to how it already instructs readingseverity.mdandAGENTS.md.This is orthogonal to
promptFileanddispatch_agent_run— it is about what goes into the prompt, not how it gets delivered. The fix belongs inuf.review-council.md.feat: add agent definition reinforcement to orchestrator child prompts
fix: resolve dispatch_agent_run sessionID and cancellation misclassif…
feat: add stateful dispatch session with submit tools and consolidation
feat: extract shared agent executor and add dispatch_agent_run tool
fix: resolve dispatch_agent_run sessionID and cancellation misclassif…
feat: add stateful dispatch session with submit tools and consolidation
feat: extract shared agent executor and add dispatch_agent_run tool
fix: resolve dispatch_agent_run sessionID and cancellation misclassif…
feat: add stateful dispatch session with submit tools and consolidation