Model-agnostic orchestration engine

We are many.
We move as one.

Legion is the model-agnostic execution layer for AI agents. It routes a unit of work to a capable executor, runs it isolated, meters it, produces evidence, and learns from the outcome. Today, Claude Code, Codex, Cursor, opencode, DeepSeek Harness, Hermes, and Pi are its coding executors.

Seven harnesses. Ten core plugins. One evidence contract. Runs stay inspectable from route decision to final hint.

$curl -fsSL https://github.com/Opus-Aether-AI/legion-core/releases/latest/download/install.sh | bash

Live run

Watch it work.

One request becomes a plan, routed slices, isolated changes, an independent review, and a validation record. This illustrative session follows the current routing policy and stops at a pull request you control.

session · 20260708-143207verified

add end-to-end multi-tenant org isolation to the API — org_id on every model, a deny-by-default guard on every resolver, a backfill migration, and an isolation test suite. then open a PR. Big one — it touches the schema, the request context, and every resolver, and it's security-sensitive. I'll take it through Legion: plan and grill the intent, fan the slices across the cohort in parallel, cross-verify, self-heal anything that fails your gates, then stop at a PR you approve. First — how wide is this? A scope guard is only safe if it covers every read. Here's the verified diff: the deny-by-default guard, and the resolver that leaked, failed your tests, and self-healed onto gpt-5.6-sol: GPT-5.6 Terra handled the scoped implementation, Luna took the bounded seed work, and Sol healed the failed security slice. Claude Opus 5 planned and signed off. Cursor Grok 4.6 High supplied an independent second opinion. Every slice was cross-verified. The leak was caught by your own tests and rerouted automatically. Nothing shipped on one model's say-so. Done — a verified PR: 9 slices, +884 −90, 412 tests green (28 new isolation specs), one cross-org leak caught and self-healed, $2.05 metered across four models. Yours to review and merge.

add end-to-end multi-tenant org isolation to the API — org_id on every model, a deny-by-default guard on every resolver, a backfill migration, and an isolation test suite. then open a PR

Big one — it touches the schema, the request context, and every resolver, and it's security-sensitive. I'll take it through Legion: plan and grill the intent, fan the slices across the cohort in parallel, cross-verify, self-heal anything that fails your gates, then stop at a PR you approve.

Update Todos

Map the blast radius — models + resolver sites

Run the task through legion-run

Review the verified diff + heal any failures

Open the PR

First — how wide is this? A scope guard is only safe if it covers every read.

Bash(rg -l "prisma\.\w+\.(findMany|findFirst|count)" src/resolvers | wc -l)

37

Bash(rg -n "^model (User|Org|Project|Invoice|ApiKey|Webhook)" prisma/schema.prisma)

12:model User { 41:model Org { 63:model Project {

98:model Invoice { 124:model ApiKey { 151:model Webhook {

37 resolver files · 6 models with no org scope

no tenant column anywhere yet — cross-cutting, not local. Deny-by-default so a missed site fails closed, not open. Good fit for fan-out.

Bash(legion-run --repo . \ --task "multi-tenant org isolation across the API, deny-by-default" \ --validate "npm test && npm run build && legion-doctor")

→ run 20260810-143207 · legion.heavy_task.v1

doctor

codex · cursor · router healthy · 7 harnesses linked

self-learn: loaded 3 lessons from .legion/memory (2 on data-loss migrations)

doctor· healthy · cohort ready

plan

grilling the prompt across claude-opus-5 + gpt-5.6-sol until the intent is sharp …

locked: isolate by org_id · deny-by-default · backfill from the ownership graph · admin bypass behind a role

decomposed the goal → 9 slices:

01 schema org_id + relations on 6 models

02 migration backfill org_id, then set NOT NULL

03 context resolve org from session → request ctx

04 guard withOrgScope() — deny-by-default

05 resolvers apply the scope to all 37 sites

06 admin audited cross-org bypass for internal role

07 tests isolation + leakage suite

08 seed multi-org fixtures

09 docs threat model + migration runbook

plan· 9 slices · deny-by-default

route

cost/capability policy → a model per slice:

01 schema → gpt-5.6-terra mechanical, scoped

02 migration → gpt-5.6-terra high effort

04 guard → gpt-5.6-terra security-sensitive

05 resolvers → gpt-5.6-terra bulk, patterned

07 tests → gpt-5.6-terra spec-driven

03·06·08·09 → terra · terra · luna · terra

route· 9 assigned · est $1.90

fanout-apply · 9 worktrees · parallel

spun 9 isolated worktrees under .legion/worktrees/143207/ …

01schemagpt-5.6-terra+48 −2 · verified

03contextgpt-5.6-terra+61 −4 · verified

04guardgpt-5.6-terra+73 −11 · verified

08seedgpt-5.6-luna+52 −0 · verified

05resolversgpt-5.6-terranpm test: 3 red · Invoice.list leaks across orgs

↻ heal: reroute 05 → gpt-5.6-sol at max, with the 3 failing specs as context

02migrationgpt-5.6-terra+96 −1 · verified

06admingpt-5.6-terra+40 −6 · verified

09docsgpt-5.6-terra+120 −0 · verified

07testsgpt-5.6-terra+180 −0 · verified

05resolversgpt-5.6-sol+214 −58 · 3 red → green · healed

fanout· 9/9 applied · 1 healed · +884 −90

review · cross-model

claude-opus-5 auditing the gpt-5.6-terra slices for scope gaps …

finding: Project.search() builds its own query, skips withOrgScope() → patched

cursor-grok-4.6-high taking an independent second opinion on the healed access path … clean

leakage probe: 240 cross-org access attempts → 240 denied (0 leaked)

review· clean · 1 gap closed

validate

$npm test

Test Suites: 34 passed, 34 total

Tests: 412 passed, 412 total (28 new isolation specs)

$npm run build

✓ compiled successfully · no type errors

$legion-doctor

── 0 fail, 0 warn ──

validate· 412 passed · build green

evaluate + report + share

eval harness: no regressions vs baseline · read p95 +2ms (index added)

wrote legion-observability.html · 47 spans emitted (legion.span.v1)

metered: gpt-5.6-terra $0.38 · claude-opus-5 $1.12 · gpt-5.6-sol $0.21 · cursor-grok-4.6-high $0.34

share· $2.05 metered across 4 models

self-learn + heal-plan

mined the run → 2 lessons: scope every new list resolver; escalate failed security slices to sol at max

heal-plan: 0 open defects

self-learn· 2 lessons written · 0 defects

legion-run ok · .legion/runs/20260810-143207 · 9 slices · 1 healed

Here's the verified diff: the deny-by-default guard, and the resolver that leaked, failed your tests, and self-healed onto gpt-5.6-sol:

diff src/middleware/org-scope.ts (new · gpt-5.6-terra)

@@ -0,0 +1,26 @@

+// Deny-by-default: a query with no org in context returns nothing.

+export function withOrgScope<T>(ctx: Ctx, where: T): T & { orgId: string } {

+ if (!ctx.orgId) throw new ForbiddenError("no org in context");

+ return { ...where, orgId: ctx.orgId };

+}

diff src/resolvers/invoice.ts (healed · gpt-5.6-terra → gpt-5.6-sol)

@@ -18,7 +18,7 @@ export const invoiceResolvers = {

list: (_p, args, ctx) =>

- db.invoice.findMany({ where: { status: args.status } }),

+ db.invoice.findMany({ where: withOrgScope(ctx, { status: args.status }) }),

get: (_p, { id }, ctx) =>

- db.invoice.findFirst({ where: { id } }),

+ db.invoice.findFirst({ where: withOrgScope(ctx, { id }) }),

diff prisma/migrations/20260810_org_isolation/migration.sql (gpt-5.6-terra)

@@ -0,0 +1,9 @@

+ALTER TABLE "Invoice" ADD COLUMN "orgId" TEXT;

+UPDATE "Invoice" i SET "orgId" = p."orgId"

+ FROM "Project" p WHERE i."projectId" = p."id";

+ALTER TABLE "Invoice" ALTER COLUMN "orgId" SET NOT NULL;

18 files changed · +884 −90 · 1 slice healed

GPT-5.6 Terra handled the scoped implementation, Luna took the bounded seed work, and Sol healed the failed security slice. Claude Opus 5 planned and signed off. Cursor Grok 4.6 High supplied an independent second opinion. Every slice was cross-verified. The leak was caught by your own tests and rerouted automatically. Nothing shipped on one model's say-so.

Update Todos

Map the blast radius — models + resolver sites

Run the task through legion-run

Review the verified diff + heal any failures

Open the PR

Bash(gh pr create --fill \ --title "feat(api): multi-tenant org isolation (deny-by-default)")

https://github.com/your-org/your-repo/pull/491

Done — a verified PR: 9 slices, +884 −90, 412 tests green (28 new isolation specs), one cross-org leak caught and self-healed, $2.05 metered across four models. Yours to review and merge.

cohort claude-opus-5 · gpt-5.6 terra/sol/luna · cursor-grok-4.6-high+884−90·412 ✓1 healed·$2.05

A heavy task becomes a proof trail.

Legion runs the execution loop and records what each stage decided. Model output is an input to validation, never the success signal by itself.

01

Inspect

Doctor checks the installation and the planner loads bounded lessons from earlier runs.

02

Plan

The goal becomes explicit slices with dependencies, scopes, gates, and review intent.

03

Route

Each slice resolves once to an executor, model role, sandbox, effort level, and fallback chain.

04

Execute

Ready slices run concurrently in isolated worktrees. Dependencies release as their own prerequisites finish.

05

Prove

Legion integrates in stable order, runs review, validation, evaluation, and writes JSON and HTML evidence.

06

Learn

Outcomes become bounded, typed hints for later runs. Source changes remain review-only proposals.

The merge remains yours. Legion can prepare a draft improvement PR, but it does not merge or deploy it.

One layer. Seven coding executors today.

Legion does not replace the tools your team already uses. It gives its current coding executors a shared execution contract, trace format, artifact model, and learning loop.

Current coding executors

Claude Code
Codex
Cursor
opencode
DeepSeek Harness
Hermes
Pi

legion-core

Ten released plugins

v0.27.1
doctorplanroutefanoutreviewvalidatelearn
legion-router0.8.2
legion-observability0.3.3
legion-orchestrate0.2.2
legion-run0.1.1
legion-setup0.2.10
legion-codex-mode0.1.3
legion-opencode-mode0.1.4
legion-hermes-mode0.1.3
legion-pi-mode0.1.2
legion-deepseek-mode0.1.0
legion-code-intel0.1.2

Durable output

reviewable diff
routes.json
validation.json
HTML report
typed hints

legion-code layers a larger catalog onto the engine without changing the execution contract.

86 plugins113 cross-harness skills20 original66 vendored

The long run

Long runs need boundaries, not confidence.

Legion gives each slice a sealed base, a narrow task, a sandbox, a budget, and a terminal record. Failed prerequisites block their dependants. Cancellation reaps descendant processes. Integration order stays stable even when workers finish in a different order.

A long run should leave artifacts and decisions, not a mystery diff.

The engine

Core stays small enough to embed and strict enough to trust. Ten plugins cover routing, execution, orchestration, evidence, setup, code intelligence, and harness-native operating modes.

01

Isolated delegation

Claude, Codex, Cursor, opencode, DeepSeek Harness, Hermes, and Pi workers receive a bounded task in a separate worktree. The parent decides whether to apply the diff.

02

Evidence and telemetry

Every unit of work emits a legion.span.v1 record with executor, model, timing, tokens, cost when available, trace lineage, and artifact paths.

03

Typed memory

The learner mines spans, review verdicts, benchmark misses, session corrections, and manual outcomes into bounded hints with provenance.

04

Review-only improvement

Doctor findings and typed proposals can enter an isolated repair lane with repeated gates and independent review. Draft mode opens a PR and stops.

05

Deterministic fanout

A completion-driven scheduler releases dependants as soon as their own prerequisites finish, then integrates results in stable input order.

06

Configured code intelligence

TypeScript and Pyright diagnostics run only for configured projects, share one adapter deadline, and emit bounded machine-readable artifacts.

spangpt-5.6-terraimplement12,847 tokmetered42sokspanclaude-opus-5review3,201 tokmetered11sokspanclaude-opus-5plan5,980 tokmetered18sokspancursor-grok-4.6-highsecond-opinion2,410 tokmetered9sokspangpt-5.6-lunascout9,336 tokmetered31sokspangpt-5.6-solhard-review4,102 tokmetered13sokspanclaude-opus-5frontend-polish6,744 tokmetered22sokspanopencode · gpt-5.6-terrahandoff2,836 tokmetered10sokspanhermes · gpt-5.6-terraorchestrate1,980 tokmetered7sokspandeepseek · deepseek-v3.2delegate3,140 tokmetered12sokspanpi · gpt-5.6-terradelegate2,104 tokmetered8sokspangpt-5.6-terraimplement12,847 tokmetered42sokspanclaude-opus-5review3,201 tokmetered11sokspanclaude-opus-5plan5,980 tokmetered18sokspancursor-grok-4.6-highsecond-opinion2,410 tokmetered9sokspangpt-5.6-lunascout9,336 tokmetered31sokspangpt-5.6-solhard-review4,102 tokmetered13sokspanclaude-opus-5frontend-polish6,744 tokmetered22sokspanopencode · gpt-5.6-terrahandoff2,836 tokmetered10sokspanhermes · gpt-5.6-terraorchestrate1,980 tokmetered7sokspandeepseek · deepseek-v3.2delegate3,140 tokmetered12sokspanpi · gpt-5.6-terradelegate2,104 tokmetered8sok

One command runs the whole lifecycle.

legion-run enforces a fixed proof loop for any heavy task, direct or through a domain plugin. It learns at both ends: past lessons feed the plan, this run's lessons feed the next.

$legion-run --repo . --task "..." --validate-command "npm test && npm run build" --json
legion-routerv0.8.2

The multi-model brain. Routes each slice to the cheapest capable model, runs it isolated, and meters the outcome.

legion-observabilityv0.3.3

See everything and close the loop. Telemetry in dollars, doctor, benchmarks, share accounting, self-learn, heal.

legion-orchestratev0.2.2

Dependency-aware planning, parallel fan-out, cross-verification, and synthesis for larger goals.

legion-runv0.1.1

The enforced lifecycle: doctor → plan → route → fan-out → review → validate → evidence → learn → heal.

legion-setupv0.2.10

Cross-harness installation, managed repo policy, shared skills, and executable bridges.

legion-codex-modev0.1.3

The mirror. When Legion runs under Codex, hand the hard calls up to Claude via legion-claude.

legion-opencode-modev0.1.4

Native opencode routing guidance with the same isolation, telemetry, and review contracts.

legion-hermes-modev0.1.3

Metered Hermes delegation guidance for bounded coding and domain-agent work.

legion-pi-modev0.1.2

A released Legion core component.

legion-deepseek-modev0.1.0

A released Legion core component.

legion-code-intelv0.1.2

Repo-native TypeScript / Pyright diagnostics on changed files, emitted as metered Legion artifacts and spans.

runs on

Claude Code · Codex · Cursor · opencode · DeepSeek Harness · Hermes · Pi

one legion-setup installs the marketplace, bridges, and CLIs across each selected harness. Daily refresh is opt-in.

  1. doctor
    $legion-doctor
  2. plan
    slices.jsonl
  3. route → fan out · apply
    $legion-route$legion-fanout$legion-delegate
    codex · gpt-5.6-terraimplements · workspace
    claude · claude-opus-5judges · read only
    cursor · cursor-grok-4.6-highchecks · plan mode
  4. review · cross-model
  5. validate · evaluate
    tests · build · eval
  6. verified PR
    $legion-report$legion-share
the learning loop
  1. self-learn
    mines this run — lessons out
    $legion-self-learn
  2. heal-plan
    drafts the fixes
    $legion-heal
  3. memory
    the lessons ledger
  4. self-learn-hints
    feeds the next plan — lessons in
    $legion-self-learn hints

It remembers what actually happened.

The learner advances verified byte cursors through local evidence, links outcomes to the narrowest catalog entity it can justify, and compiles only trusted active hints into the next stage.

spans · reviews · evals · sessions

Collect bounded evidence

normalized outcomes

Legion reads appended telemetry and manual outcomes incrementally. Session mining is capped, provenance-aware, and redacted by default.

Privacy

Counts and hashes by default. Evidence text stays local and opt-in.

Capacity

Project caps, expiry, retirement, and explicit rejection keep context small.

Authority

Memory guides a run. It cannot merge, deploy, or mutate source on its own.

evidence → outcome → hint → stage contextthe next run starts better informed

Route by role. Resolve once.

Routing policy maps an archetype to a semantic model role, executor, sandbox, effort, and fallback. A slice carries that immutable decision through execution and into routes.json.

archetypeexecutorcontract
implement-featurecodex_workhorse · gpt-5.6-terraworkspace
final-reviewclaude_default · claude-opus-5read only
orchestrateclaude_orchestrator · claude-opus-5inline
frontend-polishclaude_opus · claude-opus-5inline
second-opinion-reviewcursor_default · cursor-grok-4.6-highplan mode

Evidence over intuition.

The last number here came from a saturated tier, where every model passed everything and cost was the only signal left. DeepSWE is not that: 113 original, contamination-free repository tasks, and the best model on its public leaderboard scores 74%. Legion solved 12 of 20 across two runs of the same ten tasks, at $1.39 a task. The two runs disagreed about four of those ten — which is the more useful number, and the reason the one above it should not be quoted on its own.

DeepSWE · 2 × 10-task seeded subset · 2026-08-26

12 / 20
pass@1 · 2 runs · 95% CI 39–78%
$1.39
vs $6.46 direct
per task
gpt-5.6-sol · published leaderboard$6.46
legion → codex (workhorse role)$1.39

Two runs, same ten tasks, seed 0, one attempt each: 7/10 and 5/10. Four tasks flipped between them on identical code, so at this sample size pass@1 measures run-to-run variance more than it measures the harness — which is exactly why the public leaderboard runs all 113. We are publishing the combined 12/20 rather than the better draw, and the 95% interval (39–78%) overlaps every model on that board, so this ranks nothing. The costs are not measured the same way either: $6.46 is the leaderboard's API price across all 113 tasks, while $1.39 is Legion's own accounting at published token rates on a subscription account that is not billed per token. Directionally real, not like-for-like. Two tasks failed in both runs, and one of them fixed its target tests while breaking 51k passing ones — a failure a pass rate alone would hide. The full 113-task run is the number worth quoting, and we will publish it when it exists.

Two ways to run it

Yours to run. Or ours to run with you.

Open source

free forever

Install it, connect your own model accounts, and own the whole stack. Legion runs locally with no Legion cloud. The core is Apache-2.0 and available on GitHub and npm.

Enterprise

run with us

Run Legion inside your environment, gated by your standards, your Sonar and quality gates, your guardrails, with us on the line and an SLA. Or we build your domain agent on it.

The moat

Your agent. Our spine.

Build your domain agent on legion-core. Vendor the engine into your repo, and it stays fresh, gated, and accountable, while your domain stays yours.

your-agent · marketplace.json

"plugins": [

{ "name": "legion-router", "source": "git-subdir" },

{ "name": "legion-observability", "source": "git-subdir" },

{ "name": "trading-desk", "source": "./your-domain" }

]

$ legion-doctor

✓ marketplace · ✓ skills · ✓ codex bridge · ✓ cursor bridge · 0 findings

#212 chore: weekly legion-core refresh, the spine updates itself

Vendor the engine

One marketplace entry pulls the spine in. The engine stays ours to maintain; your domain stays yours.

It stays fresh

A weekly refresh PR updates the engine like any dependency. Review, merge, move on.

Gate everything

legion-doctor runs in CI and refuses to ship a broken garrison: skills, bridges, schemas, auth.

The engine is open source.
The business is accountability.

Enterprise is for teams who want to run it with us. We onboard your harnesses, design your routing policy, and hold the SLA. Or, we build your domain agent on legion-core.

Contact ai@opusaether.com