Skip to content

Extract shared agent executor to lib and add deterministic dispatch_agent_run tool #680

Closed

Description

@jflowers

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_dispatch returned model: "google-vertex-anthropic/claude-opus-4-6" with variant: null (agent stripped @default)
  • Agent passed model without @default → all 4 invoke_agent calls 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:

  1. Read each file into its own context (~94KB per agent)
  2. Reproduce the content verbatim in each tool call parameter (5 × 94KB = 470KB inline text)
  3. 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:

  1. Track run metadata — generate UUIDs via uuidgen, guess timestamps, reconstruct usage data
  2. Deduplicate findings — merge by normalized file + root_cause across 5+ runs, apply compound severity
  3. Compute verdict — apply precedence rules (REQUEST CHANGES > APPROVE WITH ADVISORIES > APPROVE)
  4. Process lesson proposals — pass full child output text to prepare_lesson_learning
  5. 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:

  1. Model resolution: LLM sits between plan_review_dispatch (correct slug) and invoke_agent (needs correct slug), and misinterprets @suffix
  2. Prompt delivery: LLM must read prompt content into context then reproduce it in tool calls, instead of the tool reading from disk directly
  3. 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:

  1. Extract shared session management to a library
  2. Add promptFile to invoke_agent so it reads prompt content from disk
  3. Create dispatch_agent_run tool with deterministic model resolution and filesystem-backed state
  4. Create consolidate_dispatch tool that deduplicates, computes verdict, processes lessons, and builds finalization payload — all deterministically
  5. Register submit_review_findings and submit_lesson_proposal tools 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:

  1. 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 contributing run_ids.

  2. 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.

  3. Verdict computation — Precedence: any blocking HIGH or CRITICAL = REQUEST CHANGES. Any MEDIUM without blocking = APPROVE WITH ADVISORIES. Otherwise APPROVE. Failed/cancelled runs don't vote.

  4. Lesson proposal processing — For each run with a submit_lesson_proposal entry in the persisted run-<agent>.json, call prepare_lesson_learning with 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.

  5. Finalization payload assembly — Build the complete finalize_review_dispatch payload 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/ and internal/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.ts in .opencode/lib/ with executeAgentSession() and all moved types/functions/schemas
  • invoke-agent/index.ts refactored to use shared executor; re-exports preserve import compatibility
  • invoke_agent accepts promptFile as alternative to inline prompt (mutually exclusive, validated via superRefine)
  • dispatch_agent_run tool registered in review-dispatch plugin
  • dispatch_agent_run reads review matrix and resolves model slug deterministically (including @suffix)
  • dispatch_agent_run accepts promptFile for disk-based prompt delivery
  • dispatch_agent_run persists run metadata and child output to filesystem (/tmp/opencode/dispatch-<id>/)
  • submit_review_findings tool registered in review-dispatch plugin with Zod-validated finding schema
  • submit_lesson_proposal tool registered in review-dispatch plugin with Zod-validated proposal schema
  • dispatch_agent_run reads findings and lesson proposals from in-process Map after child session completes
  • consolidate_dispatch tool deduplicates findings by normalized file + root_cause
  • consolidate_dispatch applies compound severity rules
  • consolidate_dispatch computes verdict using precedence rules
  • consolidate_dispatch processes lesson proposals from persisted run data (submitted via tool calls)
  • consolidate_dispatch returns a ready-to-submit finalization payload
  • dispatch_status tool 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-test passes
  • make check passes

Activity

  1. added
    enhancement
    on Oct 6, 2026
  2. jflowers commented on Oct 7, 2026

    @jflowers
    ContributorAuthor

    Related gap: orchestrator prompt content, not just delivery

    While investigating fullsend-ai/agents#1621 (review agent missed that REVIEW_GIT_FETCH_DEPTH is 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)

    • Model slug stripping (@default dropped by LLM)
    • Prompt construction bloat (94KB × 5 inline)

    What is still missing (prompt content)

    The orchestrator (uf.review-council.md) constructs each child agent prompt from scratch with its own ## Instructions section. It does not incorporate content from .opencode/agents/divisor-*.md agent definitions. Even though invoke_agent passes body.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:

    • Source Documents (which packs to load, e.g. bash.md, bash-custom.md)
    • Dewey knowledge graph query instructions (prior learnings)
    • Domain-specific checks (e.g. skill env-var reachability verification)
    • Step 0: Prior Learnings block

    Evidence from session traces:

    1. divisor-fullsend agent definition (.opencode/agents/divisor-fullsend.md) contains explicit instructions to load bash packs, run Dewey queries, and verify skill env-var reachability
    2. The actual child session prompt contained none of these — only what the orchestrator constructed inline
    3. Agent tool calls confirmed: read diff, severity.md, constitution, post-review.sh — zero bash pack reads, zero Dewey queries, zero skill file reads

    Proposed 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}.md as Step 0, similar to how it already instructs reading severity.md and AGENTS.md.

    This is orthogonal to promptFile and dispatch_agent_run — it is about what goes into the prompt, not how it gets delivered. The fix belongs in uf.review-council.md.

  3. added 3 commits that reference this issue on Oct 8, 2026
    2687d13
    09e99af
    3ce2007
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions