Skip to content

feat: extract shared agent executor and add dispatch_agent_run tool - #686

Merged
jflowers merged 12 commits into
unbound-force:mainfrom
jflowers:opsx/shared-agent-executor
Oct 8, 2026
Merged

jflowers merged 12 commits into
unbound-force:mainfrom
jflowers:opsx/shared-agent-executor

Conversation

@jflowers

@jflowers jflowers commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

Summary

Adds deterministic child-agent execution for review workflows. The shared executor centralizes session lifecycle handling, invoke_agent now supports disk-backed prompts, and review-dispatch gains dispatch_agent_run with review-matrix model resolution. This removes large prompt payloads from the parent agent context while preserving existing imports and scaffold parity.

Closes #680

How to Test

  • Run make plugin-test to execute unit, integration, smoke, and coverage tests.
  • Run go test -race -count=1 ./internal/scaffold/... to verify scaffold assets and drift detection.
  • Run make lint to verify Go linting.
  • Run go build ./... to verify the full Go build.
  • Verify invoke_agent accepts exactly one of prompt and promptFile, enforces the 1024-character path and 128 KiB content limits, and sanitizes file-read errors.
  • Verify dispatch_agent_run resolves lightweight, standard, and heavy tiers through the review matrix, supports explicit model bypass, validates reviewer manifest membership, and returns provenance metadata.

How to Demo

  • Start the review-dispatch plugin and inspect the registered dispatch_agent_run tool.
  • Invoke it with an agent, prompt file, and tier; observe that the full model slug, including any suffix such as @default, is resolved from the review matrix.
  • Invoke invoke_agent with promptFile and observe that the file is read at invocation time and delivered to the child session without reproducing the prompt inline.
  • Compare the scaffolded and canonical OpenCode assets through the existing drift detection tests.

Key Files Changed

  • .opencode/lib/agent-executor.ts: New shared child-session lifecycle executor, result types, provenance helpers, timeout, cleanup, and error sanitization.
  • .opencode/plugins/invoke-agent/index.ts: Refactored to use the shared executor and added promptFile support with backward-compatible re-exports.
  • .opencode/plugins/review-dispatch/index.ts: Added dispatch_agent_run, deterministic tier/model resolution, prompt-file support, and client capture.
  • .opencode/test/dispatch-agent-run.test.ts: Coverage for dispatch validation, resolution, provenance, policy loading, and prompt files.
  • .opencode/test/invoke-agent-prompt-file.test.ts: Coverage for prompt-file validation, reads, failures, size limits, and compatibility.
  • internal/scaffold/: Canonical asset copies, ownership classification, and drift detection updates.
  • openspec/changes/shared-agent-executor/: Proposal, design, requirements, tasks, and review markers.
  • .uf/dewey/learnings/: Retrospective learnings from implementation and review.

Known Issues

The following LOW-severity review advisories were acknowledged but not resolved:

  • LOW: .opencode/lib/agent-executor.ts lacks a file-level module comment.
  • LOW: Prompt-file tests couple the fake client response model values to fixture model inputs.

This PR was generated by /uf.finale (AI-assisted).

@jflowers
jflowers requested a review from a team as a code owner October 7, 2026 23:36
@jflowers

jflowers commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

Heads-up: related content gap in orchestrator prompts

Posted a detailed comment on #680 (link) about a gap this PR doesn't currently cover.

TL;DR: promptFile and dispatch_agent_run fix how prompts get delivered and how models get resolved, but the orchestrator (uf.review-council.md) still constructs child prompts that don't include .opencode/agents/divisor-*.md agent definition content. This means Source Documents, Dewey knowledge graph queries, and domain-specific checks defined in agent definitions are invisible to the child agents at runtime.

The fix is in uf.review-council.md — adding an instruction for the child to read its own agent definition file as Step 0. This is orthogonal to what this PR does and could be done as a follow-up, but wanted to flag it since the work is related.

@jflowers jflowers left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR Review: #686 — feat: extract shared agent executor and add dispatch_agent_run tool

Verdict: APPROVE (posted as COMMENT — GitHub prevents approving your own PR)

Five Divisor council members (adversary, architect, curator, guard, testing) unanimously approved with zero findings.

Pre-flight Results

Tool Status
go test PASS (23 packages)
golangci-lint PASS (0 issues)
plugin-test PASS (332 tests, 93.16% coverage)
pipeline tests PASS (91/91)

Summary

Extracts shared agent executor from invoke-agent into .opencode/lib/agent-executor.ts, adds dispatch_agent_run tool to review-dispatch plugin, and introduces promptFile support. Comprehensive test coverage, clean lint, proper OpenSpec artifacts. Closes #680.

This review was generated by /uf.review-pr (AI-assisted).

@jflowers jflowers left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR Review: #686 — feat: extract shared agent executor and add dispatch_agent_run tool

Verdict: APPROVE WITH ADVISORIES

5/5 Divisor agents approved. 3 LOW advisories noted:

Advisories

  1. [LOW] DRY — .opencode/plugins/review-dispatch/index.ts:700
    The promptFile resolution block (~15 lines: read file, check size, handle error, fallback to inline prompt) is structurally identical in both invokeAgent() and dispatchAgentRun(). The different dependency injection shapes (deps.readText vs deps.plannerDependencies.readText) make extraction non-trivial, but this bounded duplication could be addressed in a follow-up.
    Source: divisor-architect

  2. [LOW] dead-code — .opencode/test/consolidate-dispatch.test.ts:218
    Multiple test cases assign const correlationId = await setupDispatchSession(...) but never reference the variable. The setupDispatchSession call is needed for its side effects, but the return value is unused in ~8 of 15 tests. Consider using await setupDispatchSession(...) without the variable binding.
    Source: divisor-architect

  3. [LOW] formatting — .gitignore:75
    Missing trailing newline after the coverage/ entry, violating POSIX text file conventions.
    Source: divisor-architect

Pre-flight

All local checks passed: go vet, golangci-lint, go test (-race -count=1), go build, vitest (332 tests). No CI checks on branch.

Council

Agent Verdict
divisor-adversary APPROVE
divisor-architect APPROVE WITH ADVISORIES
divisor-curator APPROVE
divisor-guard APPROVE
divisor-testing APPROVE

Dispatch: ea0c3a4c-076d-4fdc-b83e-9181e212a58f

This review was generated by /uf.review-pr (AI-assisted).

@jflowers jflowers left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR Review: #686 — APPROVE WITH ADVISORIES

Summary

Clean extraction of shared agent executor from invoke-agent into .opencode/lib/agent-executor.ts with new dispatch_agent_run tool and 4 companion tools. All 333 tests pass, all pre-flight checks pass, and the implementation aligns well with its OpenSpec artifacts. 5/5 review personas approved with advisories.

Advisories (3 MEDIUM, 7 LOW)

MEDIUM

  1. Documentation Completeness — CHANGELOG.md has no entry for this change. Five new tools, shared library extraction, and 4 command updates represent a significant user-facing change (DR-003). (curator, guard)

  2. Intent Drift — Companion tools (consolidate_dispatch, dispatch_status, submit_review_findings, submit_lesson_proposal) are not covered in any spec artifact. Architecturally necessary but undocumented scope expansion. (guard)

  3. Intent Drift — 50 KiB sibling evidence filtering added to all 4 orchestrator commands without spec coverage. (guard)

LOW

  1. Resilience — Module-level Maps (submissionStore, sessionCorrelationMap) grow unboundedly within a plugin session. Acceptable for plugin runtime but worth noting for future server-mode scenarios. review-dispatch/index.ts:550 (adversary, architect)

  2. DRY — promptFile resolution logic duplicated between invokeAgent and dispatchAgentRun. Bounded duplication with different error contexts. (architect)

  3. Formatting — .gitignore missing trailing newline after coverage/ entry. (architect)

  4. Test Isolation — Dead import of withBun/scratchProject from non-existent ./helpers.js in consolidate-dispatch.test.ts:9. (testing)

  5. Test Architecture — withBun/scratchProject helper functions duplicated across 4 test files (pre-existing pattern perpetuated). (testing)

  6. Test Architecture — Unused correlationId assignments in 10 test cases in consolidate-dispatch.test.ts. (testing)

  7. Coverage Strategy — No dedicated unit tests for executeAgentSession() in agent-executor.ts (370 lines). Covered indirectly via caller tests. (testing)

Dispatch

5 runs, 5 success | $0.77 | Artifact: a6035f86-5b9e-40b2-8173-a825cd14862e

This review was generated by /uf.review-pr (AI-assisted).

- Extract reusable session lifecycle to .opencode/lib/agent-executor.ts
  with executeAgentSession(), types, and utility functions
- Add promptFile parameter to invoke_agent for disk-based prompt
  delivery, eliminating ~470KB inline text across review runs
- Add dispatch_agent_run tool to review-dispatch plugin with
  tier-based model resolution via review matrix
- Refactor invoke-agent/index.ts from 519 to 274 lines with
  backward-compatible re-exports
- Dual-copy sync to scaffold assets with drift detection
- OpenSpec artifacts: proposal, design, specs, tasks

Closes unbound-force#680

Assisted-by: gpt-5.6-luna
Generated with AI assistance (gpt-5.6-luna)
All four review-dispatch orchestrators (review-council, review-pr,
triage-issue, address-feedback) now instruct each child agent to read
its own definition file at .opencode/agents/{agent}.md as Step 0
before conducting the review/triage/assessment. This ensures Prior
Learnings queries, Source Documents, and Convention Pack markers
defined in agent definitions are executed rather than overshadowed
by the orchestrator's user prompt.

Addresses the orchestrator prompt content gap identified in issue
but agent-specific knowledge (Dewey queries, severity.md loading,
domain checks) was still invisible at runtime.

Changes:
- Add agent definition reinforcement bullet to mandatory child
  prompt ingredients in all four canonical command files
- Dual-copy sync to scaffolded .opencode/commands/ locations
- Fix TestRunInit_FreshDir file count range [61-64] -> [61-66]
  to accommodate agent-executor.ts scaffold addition
- OpenSpec: new spec orchestrator-context.md, updated design.md
  (D9, R5), updated tasks.md (Section 6, all tasks complete)
- All review commands (council, pr, triage, address-feedback) now
  mandate dispatch_agent_run with promptFile for dispatch-planned
  runs, reserving invoke_agent for ad-hoc calls
- Raise promptFile size limit from 128 KiB to 1 MiB for both
  invoke-agent and review-dispatch plugins
- Add sibling evidence filtering: when evidence prompt exceeds
  50 KiB, filter to file paths relevant to the reviewed change
- Update dispatch-advisor skill with invocation tool guidance
- Update tests and scaffold assets to match
…ication bugs

- dispatch_agent_run: use context.sessionID per-invocation instead of
  empty string captured at plugin init time; fixes BadRequest on child
  session create
- agent-executor: add abort check after session.prompt() so parent
  cancellation is reclassified as cancelled instead of
  child_prompt_failed
- agent-executor: improve responseFailure to detect empty error objects
  and fall through to HTTP status
- invoke-agent/dispatch_agent_run: add @suffix guidance to model
  description
- command files: correct host source wording to reflect standard tier
  default instead of host model replay

Fixes unbound-force#680
Move PromptSchema, PromptFileSchema, TimeoutSchema,
MAX_INLINE_PROMPT_BYTES, and MAX_PROMPT_FILE_BYTES to
agent-executor.ts. Both invoke-agent and review-dispatch
now import from the shared lib.

Fix command_contract_test.go: host source behavior fragments
updated to match the dispatch_agent_run tier-default wording.

Add dispatch_agent_run test coverage for tier_model_unavailable
and invalid timeout paths. Remove unused parseReviewMatrix import.
Add filesystem-backed dispatch sessions, child tool call handoff via
in-process Map, and deterministic post-dispatch consolidation:

- dispatch_agent_run: accepts correlation_id/source/sequence, persists
  run metadata to /tmp/opencode/dispatch-<id>/run-<agent>.json, harvests
  submitted findings and lesson proposals from child sessions
- submit_review_findings: child-facing tool for Zod-validated finding
  submission via module-level Map keyed by child session ID
- submit_lesson_proposal: child-facing tool for lesson proposal
  submission with tag and optional category
- consolidate_dispatch: reads persisted run files, deduplicates findings
  by normalized file + root_cause (keeps highest severity, merges
  run_ids), computes verdict via severity precedence, maps workflow
  result by command type, builds full finalization payload
- dispatch_status: query tool returning run summaries and pending
  submission counts for debugging
- agent-executor: executeAgentSession returns childSessionID for
  submission store harvesting

329 tests pass, 85% branch coverage. Canonical copies synced.

Closes unbound-force#680 phases 3-5
- Replace explicit correlation_id input with session-based lookup via
  sessionCorrelationMap (parent sessionID → auto-generated correlationId)
- dispatch_agent_run always persists run data and returns correlation_id
  and run_id in result (DispatchAgentRunResult)
- consolidate_dispatch and dispatch_status resolve correlation
  automatically from prior dispatch_agent_run calls in the same session
- Remove correlation_id from input schemas of all three tools
- Add earlyExit() helper for consistent ID generation on error paths
- Update tests for session-based correlation behavior
…omputation

- Add optional provenance parameter to consolidate_dispatch; when
  provided, calls finalizeReviewDispatch internally so the agent
  never re-serializes the 30 KB payload by hand.
- Add runVerdict() to compute per-run workflow_verdict from findings
  severity (was hardcoded null, which failed semantic validation for
  successful runs).
- Wire finalizationDependencies into createConsolidateDispatchTool.
- Add two new tests: internal-finalization path and backward-compat
  payload-only path.
consolidate_dispatch now reads command, mode, input_context,
change_profile, plan, and coverage from session-metadata.json
instead of requiring the agent to re-supply them. This eliminates
~35 seconds of manual payload reconstruction per dispatch session.

dispatch_agent_run gains optional session_metadata parameter
persisted on the first call. consolidate_dispatch schema shrinks
to just provenance (optional).
consolidate_dispatch now collects all lesson proposals from
persisted run data and returns them in a top-level proposals
array. The agent can directly call dewey_store_learning for
each proposal instead of struggling to access opaque data.

Proposals are included in both output paths: raw payload (no
provenance) and internal finalization (with provenance).
When no proposals exist, the key is omitted.
Latest review sessions generate 558 KB prompt files (54% of the old
1 MiB cap). Increase to 4 MiB to provide comfortable headroom for
larger diffs and richer evidence context.
@jflowers
jflowers force-pushed the opsx/shared-agent-executor branch from 9f40cbd to 88450a4 Compare October 8, 2026 20:37
@jflowers
jflowers merged commit 8d9057a into unbound-force:main Oct 8, 2026
16 checks passed
@jflowers
jflowers deleted the opsx/shared-agent-executor branch November 15, 2026 21:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Extract shared agent executor to lib and add deterministic dispatch_agent_run tool

1 participant