diff --git a/docs/ADRs/0112-task-grain-routing-policy-on-the-host.md b/docs/ADRs/0112-task-grain-routing-policy-on-the-host.md new file mode 100644 index 0000000000..4c170971e0 --- /dev/null +++ b/docs/ADRs/0112-task-grain-routing-policy-on-the-host.md @@ -0,0 +1,162 @@ +--- +title: "112. Runtime and model are routed per task by a config policy, on the host" +status: Accepted +relates_to: + - adaptive-agent-selection + - agent-architecture + - operational-observability +topics: + - config + - runtime + - routing + - cost +--- + +# 112. Runtime and model are routed per task by a config policy, on the host + +Date: 2026-09-11 + +## Status + +Accepted + + + +## Context + +A repo can say *which* runtime, model, effort and per-persona model an agent +uses ([ADR 0091](0091-per-agent-runtime-model-effort.md), +[ADR 0104](0104-per-persona-model-resolution.md)), but not *when*. Every +choice is static per agent, so a one-line docs change and a 2,000-line CI +refactor get the same opus-at-high review. CEL overlays cannot set `model` +or `effort` ([ADR 0088](0088-cel-guarded-overlays.md): both are operational, +not forge-specific), and the normalized event carries no diff size or paths. +Open issues ask for the next step from three directions: a cheaper model or +effort for trivially scoped changes +([#5777](https://github.com/fullsend-ai/fullsend/issues/5777), +[#6891](https://github.com/fullsend-ai/fullsend/issues/6891), +[#2842](https://github.com/fullsend-ai/fullsend/issues/2842), +[agents#497](https://github.com/fullsend-ai/agents/issues/497)), deeper +review when security signals are present +([agents#535](https://github.com/fullsend-ai/agents/issues/535)), and a way +to see the cost effect of a model change before merging it +([#6560](https://github.com/fullsend-ai/fullsend/issues/6560)). + +Two facts bound the design. The runtime-parity rule that *the deciding +session is never downgraded* ([#6527](https://github.com/fullsend-ai/fullsend/issues/6527)) +still holds. And catalog membership is not availability: four incidents +([#6964](https://github.com/fullsend-ai/fullsend/issues/6964), +[agents#1225](https://github.com/fullsend-ai/agents/issues/1225)) discovered +an unservable id at the first model call, after the sandbox existed, and +retried on opus at several times the cost. A closed draft +([#6361](https://github.com/fullsend-ai/fullsend/pull/6361)) prototyped +per-prompt routing with Claude Code hooks inside the sandbox and measured a +13-issue by 3-model grid on the code agent (opus a median 3.6× haiku; every +model stopped early on the no-change issues); it measured cost and +completion, not quality. +[adaptive-agent-selection.md](../problems/adaptive-agent-selection.md) asks +how selection should learn from outcomes and names the constraints any +learned policy must keep: selection only, shadow mode first, safety as a +constraint rather than an objective, no self-deployment. + +## Options + +**Per-prompt routing inside the sandbox** (the #6361 hooks). Rejected: the +sandbox sees only the prompt, which is author-controlled text; routing state +is per sandbox and lost; it is Claude-Code-only; and the decision comes after +the review has already read a diff it could have sized for free. + +**Routing in an LLM gateway.** Rejected as the place for the decision, kept +as an optional provider. On Vertex the model is addressed in the URL path, so +a gateway can route only if the client moves to the Anthropic Messages +endpoint and the gateway holds the credential the sandbox never sees today; a +silent rewrite also breaks the status-comment model echo, `per_model_usage` +and ADR 0104's closed set. Nothing a gateway sees carries the outcome that +arrives on a later forge event. + +**A heuristic in the GitHub Route job** (#6891's proposal). Rejected: GitHub +only, and a second place that decides model and effort next to the ADR 0091 +chain. + +## Decision + +`fullsend run` resolves runtime, model, effort and persona models **per task, +on the host, before the sandbox exists**, from a `routing:` block in +`.fullsend/config.yaml`. + +1. **Shape.** `routing.rules[]` each carry `agents:`, a CEL `when:` and a + `set:` that holds exactly the four fields an `agents:` entry holds + (`runtime`, `model`, `effort`, `subagents`); nothing else is routable. + All matching rules merge, later entries win per field (the ADR 0088 + semantics). `routing.mode` is `off`, `shadow` or `enforce`. +2. **Inputs are system-derived.** Rules see a `task` variable beside `event`, + `runtime` and `config`: change stats and paths from the forge files API, + a deterministic change pattern, actor kind and role, labels, attempt + count, linked-issue metadata. PR title, body, comments, commit messages + and branch names are never routing inputs. A downgrade rule may key on + labels only from `routing.trusted_labels`; an escalation rule may key on + any label. +3. **Precedence.** A rule sits below the `--runtime`/`--model`/`--effort` + flags and `FULLSEND_*` variables and above the agent's `agents:` entry, + so an explicit per-run override still wins and a rule only refines the + static choice. +4. **Guards, validated at config time and before the sandbox.** Every model a + rule names is in `routing.allowed_models` ∩ the catalog; a runtime change + must keep the agent's needs (no persona roster on codex, fallback chain + on Claude only); `routing.never_downgrade` (default `triage`, + `prioritize`, and the review orchestrator by implication) may only be + moved to an equal or higher tier, so a downgrade rule for `review` moves + effort and `subagents`, never the orchestrator's model; persona + `min_tier` floors from the persona files hold; the resolved model and + every persona model are checked against the project's served list once + per run, falling to the next fallback entry or the static entry on a + miss, never retried inside the sandbox. +5. **Effort before model, model before runtime.** A downgrade lowers effort + on the same model first, then moves within a vendor tier, then across + vendors; a runtime move is never a downgrade rule's job. +6. **Every choice is echoed** with the rule that fired: plan block, + `metrics.json` (`routing.{mode,rule,applied,static_model,static_effort}`), + root-span attributes `fullsend.routing.*`, status-comment footer. In + `shadow` the rules are evaluated and recorded and the static choice runs. +7. **Learning is offline and lands as a pull request.** The root span carries + the routing ledger (choice, rule, task facts, cost, status, verdict) on + the OTLP path of [ADR 0050](0050-distributed-tracing-instrumentation.md); + a replay over that ledger scores a candidate policy, and the only path + from a learned change to production is a reviewed edit to `routing:`. + No in-run adaptation, no self-deployment. + +## Consequences + +- A repo can express "sonnet at low effort for docs-only changes" and "opus + at xhigh with opus security and challenger personas when `internal/scaffold/` + changes" as reviewed config, resolving the downgrade and escalation issues + above with the same mechanism. +- Shadow mode plus the ledger produce the quality evidence #6361 lacked + before any default changes; cost is judged per work item including + re-review and fix rounds, never per run. +- The served-model preflight ends the retry-on-unavailable incident class for + routed and static runs alike. +- Presets may not ship `routing.rules` until the layered merge records which + layer a key came from (the provenance gap ADR 0104 deferred); a lower layer + may only tighten `never_downgrade` and `allowed_models`. +- The review orchestrator's model can move only by amending #6527's wording + in a later ADR, on shadow `per_model_usage` evidence; persona routing on the + Claude Code runtime remains the second half of ADR 0104. + +### Deferred + +- **A routing advisor.** Rules cannot read a diff; a short, read-only run on + the fast tier can, and its schema-validated verdict (`scope`, `risk`, + `domains`) can become a `task.assessment` fact beside the system-derived + ones, with an in-run counterpart that lets a worker consult a stronger + model without switching session model + ([#6531](https://github.com/fullsend-ai/fullsend/issues/6531)). That is a + follow-on decision. The constraint this record fixes for it: an assessment + read from author-controlled content may fire an escalation rule alone but + may satisfy a downgrade rule only together with a system-derived fact, and + it never widens the allowed set or crosses the never-downgrade floor. diff --git a/docs/architecture.md b/docs/architecture.md index 5257cd42a2..7b23a7cc8c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -230,6 +230,7 @@ flowchart TB **Decided (implementation):** - The `fullsend run` runner delegates in-sandbox agent execution to a `runtime.Runtime` interface; production orgs default to Claude Code, with [pi](https://github.com/earendil-works/pi) available as an opt-in second runtime (`runtime: pi`, Claude-on-Vertex through the same WIF credential path) and [codex](https://github.com/openai/codex) as a third (`runtime: codex`, OpenAI-only through a custom model provider whose bearer token comes from a runner-seeded file, with the sandbox tool hooks behind a translating adapter — [ADR 0099](ADRs/0099-codex-agent-runtime.md) and [ADR 0100](ADRs/0100-codex-sandbox-hooks.md)). Runtime selection is configured per repo with `runtime:` in `.fullsend/config.yaml` (per-agent `runtime`/`model`/`effort`/`subagents` on the agent's `agents:` entry sit above it and below the `--runtime`/`--model`/`--effort` flags and `FULLSEND_*` variables, [ADR 0091](ADRs/0091-per-agent-runtime-model-effort.md)) and resolved via `runtime.ResolveForAgent()`. Test-only runtimes — **dummy** (scripted operations) and **dummy-playback** (playlist-based replay of canned results) — execute in the real OpenShell sandbox for behaviour tests without inference. Bootstrap uses a portable `BootstrapInput` interface with optional extensions such as `SandboxHooksBootstrap` for the runtime-neutral sandbox tool hooks ([ADR 0090](ADRs/0090-runtime-neutral-sandbox-hooks-contract.md)); runtimes declare further capabilities through small optional interfaces (`DebugLogNamer`, `ContextBridger`) rather than `Name()` checks in the runner. Transcript and debug artifact handling use a separate `TranscriptHandler` interface. See [runtimes.md](runtimes.md) for the per-runtime security feature matrix required when adding a new backend. +- Runtime, model, effort and persona models are routed **per task** by a `routing:` policy in `.fullsend/config.yaml`, resolved by `fullsend run` on the host before the sandbox exists, from system-derived task facts only (forge change stats and paths, actor kind, allowlisted labels, attempt count — never PR text); a rule sits below the per-run flags and variables and above the agent's `agents:` entry, is bounded by `allowed_models`, a never-downgrade set, persona floors and a served-model preflight, and is echoed in the plan block, `metrics.json`, the root span and the status comment; `shadow` mode records the decision without acting on it, and learning lands only as a reviewed policy change ([ADR 0112](ADRs/0112-task-grain-routing-policy-on-the-host.md)). - Plugins are runtime-scoped harness resources: a harness declares `plugins:` as one list of directories in its own repository (same trust and fetch path as skills), and each entry's format decides which runtime loads it — a `plugin.json` bundle is Claude Code's, a directory pi's `-e` loader resolves is uploaded and loaded after a tree-hash preflight computed from the host copy. Each runtime names and skips the entries in the other format, so the list survives a runtime switch. Because `--no-extensions` plus explicit `-e` closes the set of code that can register tools, no per-tool declaration is needed ([ADR 0094](ADRs/0094-pi-extensions-are-harness-resources.md)). ### Behaviour testing diff --git a/docs/problems/adaptive-agent-selection.md b/docs/problems/adaptive-agent-selection.md index 30c274d56b..ddff4eb79c 100644 --- a/docs/problems/adaptive-agent-selection.md +++ b/docs/problems/adaptive-agent-selection.md @@ -203,9 +203,9 @@ The experiment should actively pressure-test three assumptions: - GA vs. Thompson Sampling — or both at different layers? TS for team/config selection, GA for workflow evolution is the leading hypothesis, but it needs validation. - How fine-grained should context tuples be? A hierarchical split-on-variance approach avoids committing to a fixed schema, but adds implementation complexity. - How do we handle model version changes — reset fitness data, apply a discount, or version-tag and keep history? -- Should the fitness function include a cost term from the start, or should cost optimization be a separate experiment after quality optimization is validated? +- Should the fitness function include a cost term from the start, or should cost optimization be a separate experiment after quality optimization is validated? (For runtime and model selection, [ADR 0112](../ADRs/0112-task-grain-routing-policy-on-the-host.md) judges cost per work item including re-review and fix rounds, and requires shadow-mode outcome evidence before any routed default changes; the composite fitness question remains open.) - What is the right exploration budget, and how should it decay? Too high wastes runs on poor configurations; too low starves new options. - Can fitness data transfer across repos with similar characteristics, and how do we measure "similar"? -- How should the adaptive layer interact with the deterministic safety model — is selection-only sufficient, or are there edge cases where the choice of configuration implicitly affects safety coverage? +- How should the adaptive layer interact with the deterministic safety model — is selection-only sufficient, or are there edge cases where the choice of configuration implicitly affects safety coverage? (Partially decided in [ADR 0112](../ADRs/0112-task-grain-routing-policy-on-the-host.md) for the runtime/model surface: selection only over four config fields, with a never-downgrade set, persona floors and a closed model set as constraints, and no author-controlled input as a routing key.) - What prevents a well-scoring configuration from being well-scoring only because it is assigned to a biased subset of tasks (selection bias in the evaluation)? - Should there be a human-in-the-loop approval step before any configuration is retired, or is soft retirement with recovery probing sufficient? diff --git a/docs/problems/cross-run-memory.md b/docs/problems/cross-run-memory.md index 24cb6ba5da..acfee64bf5 100644 --- a/docs/problems/cross-run-memory.md +++ b/docs/problems/cross-run-memory.md @@ -127,7 +127,7 @@ Retry loops can become flapping when the system does not converge. See [flapping ## Open questions -- Which run outcomes are safe to feed forward automatically, and which require human review first? +- Which run outcomes are safe to feed forward automatically, and which require human review first? (For routing decisions, [ADR 0112](../ADRs/0112-task-grain-routing-policy-on-the-host.md): none automatically — outcomes feed an offline replay whose result is a reviewed config change; the general question remains open.) - Should memory entries be observations only, or can any of them become instructions? - How should future agents distinguish system-derived facts from agent-authored interpretations? - Can non-review-gated memory be made safe enough, or should all durable memory promotion go through reviewed repo instructions or skills? diff --git a/docs/problems/operational-observability.md b/docs/problems/operational-observability.md index 5f8c2b9049..7c1ac1a444 100644 --- a/docs/problems/operational-observability.md +++ b/docs/problems/operational-observability.md @@ -191,7 +191,7 @@ This works for early experimentation when the volume is low and the operators ar - ~~How do we keep the triggering event and the agent run linked in the GitHub Actions UI for debugging?~~ Decided in [ADR 0041](../ADRs/0041-synchronous-workflow-call-event-dispatch.md) (synchronous `workflow_call` dispatch for the event path). - How should trace access be controlled? (JSONL trace exposure decided in [ADR 0021](../ADRs/0021-jsonl-reasoning-trace-exposure.md): owner-scoped storage with credential scanning as defense-in-depth. Broader question of balancing security and transparency for non-JSONL observability data remains open.) - What retention policy applies to traces? Indefinite retention supports audit requirements but increases storage cost and data sensitivity exposure. Time-bounded retention (e.g., 90 days) limits exposure but may lose traces needed for incident investigation. -- How do we measure "is the system getting better"? What metrics constitute a meaningful quality signal for an autonomous software factory? Merge revert rate? Human override rate? Time-to-review? Cost per decision? Some composite score? The choice of metric shapes what gets optimized. First-ship trend scores (trace fitness on wild runs, local `eval-measurements.jsonl`) are [ADR 0087](../ADRs/0087-eval-measurements-online-trace-scoring.md); richer quality signals remain open. +- How do we measure "is the system getting better"? What metrics constitute a meaningful quality signal for an autonomous software factory? Merge revert rate? Human override rate? Time-to-review? Cost per decision? Some composite score? The choice of metric shapes what gets optimized. First-ship trend scores (trace fitness on wild runs, local `eval-measurements.jsonl`) are [ADR 0087](../ADRs/0087-eval-measurements-online-trace-scoring.md); richer quality signals remain open. Routing decisions and the task facts behind them are recorded on the root span (`fullsend.routing.*`) so cost can be compared per work item across model choices ([ADR 0112](../ADRs/0112-task-grain-routing-policy-on-the-host.md)). - At what scale does a dedicated LLM observability platform justify its operational overhead (Postgres, ClickHouse, Redis, S3 for something like Langfuse)? Is there a threshold of agent activity below which structured logging suffices? Score files are local JSONL ([ADR 0087](../ADRs/0087-eval-measurements-online-trace-scoring.md)); remote scores reuse `OTEL_EXPORTER_OTLP_*`. Platform choice remains open. - ~~How do we handle the bootstrapping problem — the factory needs observability to improve, but building the observability infrastructure is itself work that competes with building the factory?~~ Decided in [ADR 0050](../ADRs/0050-distributed-tracing-instrumentation.md): zero-configuration baseline (local JSONL + summary files) eliminates infrastructure requirements for initial observability; OTLP export adds backends when the org is ready. - Should observability data feed back into agent instructions automatically (e.g., auto-adjusting prompts when false positive rates exceed a threshold), or should it only inform human-driven instruction changes? Automatic feedback creates the risk of instruction oscillation; human-only feedback is slower but more controlled.