Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(model-hub): inherit default routing for empty overrides (#1911)

Call White073d277fe577
diff --git a/config/v2_config.py b/config/v2_config.py
index cb86d73eb..e097c6888 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -3034,6 +3034,12 @@ class ModelHubRouteConfig:
return {"hops": [hop.to_payload() for hop in self.hops]}
+def normalized_model_hub_override(route: ModelHubRouteConfig | None) -> ModelHubRouteConfig | None:
+ """Normalize validated intent: only a nonempty route is a manual override."""
+
+ return route if route is not None and route.hops else None
+
+
@dataclass
class ModelHubMenuConfig:
view: Literal["featured", "full"] = "featured"
@@ -3430,6 +3436,15 @@ class ModelHubAgentSupplyConfig:
raise ValueError(
"Config 'model_hub.agents.models.native_protocol' is only valid for opencode"
)
+ # Validate original keys before omitting empties. Legacy fixed-menu
+ # readers above may derive catalog identities from those same keys.
+ menu_ids = {model.id for model in models}
+ extra_route = next((model_id for model_id in routes if model_id not in menu_ids), None)
+ # OpenCode retains dormant routes when a checked model is hidden.
+ if extra_route is not None and backend != "opencode":
+ raise ValueError(
+ f"Config 'model_hub.agents.{backend}.routes' contains non-menu model '{extra_route}'"
+ )
return cls(
backend=backend,
mode=mode,
@@ -3439,7 +3454,7 @@ class ModelHubAgentSupplyConfig:
if sources_payload is not None
else ModelHubAgentSourcesConfig()
),
- routes=routes,
+ routes={model_id: route for model_id, route in routes.items() if normalized_model_hub_override(route) is not None},
menu=menu,
models=models,
removed_model_ids=list(removed_model_ids),
@@ -3454,6 +3469,7 @@ class ModelHubAgentSupplyConfig:
"routes": {
model_id: route.to_payload()
for model_id, route in self.routes.items()
+ if normalized_model_hub_override(route) is not None
},
"menu": self.menu.to_payload() if self.menu else None,
}
@@ -3569,24 +3585,6 @@ class ModelHubConfig:
expected_backend=backend,
repairing=repairing,
)
- expected_menu_ids = tuple(
- model.id for model in agents[backend].models
- )
- extra_route = next(
- (
- model_id
- for model_id in agents[backend].routes
- if model_id not in expected_menu_ids
- ),
- None,
- )
- # The retained OpenCode menu endpoint can hide a checked model while
- # preserving its dormant Route for a later re-enable. Fixed-menu
- # backends have never had that compatibility state.
- if extra_route is not None and backend != "opencode":
- raise ValueError(
- f"Config 'model_hub.agents.{backend}.routes' contains non-menu model '{extra_route}'"
- )
config = cls(
enabled=enabled,
sources=sources,
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.py
index 3b459a289..a2dea1ce0 100644
--- a/core/handlers/model_hub/adapter.py
+++ b/core/handlers/model_hub/adapter.py
@@ -1,4 +1,4 @@
-"""Model Hub EngineAdapter interface. FINAL CONTRACT v9 (2026-09-06).
+"""Model Hub EngineAdapter interface. FINAL CONTRACT v10 (2026-09-06).
This file is the canonical adapter boundary and must remain byte-identical to
``core/handlers/model_hub/adapter.py``. The adapter owns one-Source operations:
diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.py
index ae4e84df9..69a7ac947 100644
--- a/core/handlers/model_hub/provenance.py
+++ b/core/handlers/model_hub/provenance.py
@@ -1721,7 +1721,7 @@ class TurnCorrelationRegistry:
self.store.put(
{
- "contract_version": 9,
+ "contract_version": 10,
"turn_id": normalized_turn_id,
"ts": ts or _utc_now_iso(),
"agent": trace.agent,
diff --git a/core/handlers/model_hub/resolver.py b/core/handlers/model_hub/resolver.py
index 4de90ba1d..a3f4546df 100644
--- a/core/handlers/model_hub/resolver.py
+++ b/core/handlers/model_hub/resolver.py
@@ -13,6 +13,7 @@ from config.v2_config import (
ModelHubRouteConfig,
ModelHubRouteHopConfig,
ModelHubSourceConfig,
+ normalized_model_hub_override,
)
@@ -235,9 +236,9 @@ def effective_model_route(
"""Choose one route tier before live health or transport restriction."""
agent = config.agents[backend]
- if requested_model in agent.routes:
- override = agent.routes[requested_model]
- return EffectiveModelRoute(override, "manual" if override.hops else None, override.hops)
+ override = normalized_model_hub_override(agent.routes.get(requested_model))
+ if override is not None:
+ return EffectiveModelRoute(override, "manual", override.hops)
if not requested_model or not any(model.id == requested_model for model in agent.models):
return EffectiveModelRoute(None, None, ())
by_id = {source.id: source for source in config.sources}
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 0e7860761..fdc19dc5f 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -34,6 +34,7 @@ from config.v2_config import (
normalize_storable_backend_model_text,
normalize_model_hub_base_url,
normalize_model_hub_vendor_id,
+ normalized_model_hub_override,
validate_model_hub_source_client_nonce,
)
from core.agent_auth_service import BackendLoginInProgressError
@@ -132,7 +133,7 @@ from .resolver import (
from .revocations import CredentialRevocationJournal
from .usage import USAGE_DEFAULT_WINDOW_DAYS, BoundedUsageLedger, SourceIdentity, UsageWriter
-CONTRACT_VERSION = 9
+CONTRACT_VERSION = 10
def _storable_backend_model_metadata(
@@ -155,8 +156,8 @@ def _storable_backend_model_metadata(
return proposed_display_name, proposed_efforts
-AGENT_CHAIN_CONTRACT_VERSION = 9
-PROBE_RESULT_CONTRACT_VERSION = 9
+AGENT_CHAIN_CONTRACT_VERSION = 10
+PROBE_RESULT_CONTRACT_VERSION = 10
_REORDER_ORDER_UNSET = object()
_REASONING_EFFORT_TELEMETRY_MAX_BYTES = 256
# Settlement generations are minted per attempt start and live only in this
@@ -719,7 +720,7 @@ def _runtime_payload(status: EngineStatus, *, enabled: bool) -> dict:
manager = EngineRuntimeManager()
return {
- "contract_version": 9,
+ "contract_version": 10,
"enabled": enabled,
"host_platform": status.host_platform or manager.host_platform(),
"manifest": manager.contract_manifest(),
@@ -900,7 +901,8 @@ class ModelHubService:
)
seen: set[str] = set()
model_ids: list[str] = []
- for model_id in [*primary, requested_model, *agent.routes]:
+ overrides = [model_id for model_id, route in agent.routes.items() if normalized_model_hub_override(route) is not None]
+ for model_id in [*primary, requested_model, *overrides]:
if model_id and model_id not in seen:
seen.add(model_id)
model_ids.append(model_id)
@@ -3195,8 +3197,9 @@ class ModelHubService:
add(pinned_model, name)
for model in agent.models:
add(model.id)
- for model_id in agent.routes:
- add(model_id)
+ for model_id, route in agent.routes.items():
+ if normalized_model_hub_override(route) is not None:
+ add(model_id)
return protected
def _would_interrupt(
@@ -3336,13 +3339,16 @@ class ModelHubService:
for item in invalidated_hops
}
for backend in MODEL_HUB_BACKENDS:
- for menu_model, route in config.agents[backend].routes.items():
+ agent = config.agents[backend]
+ for menu_model, route in list(agent.routes.items()):
route.hops = tuple(
hop
for hop in route.hops
if (backend, menu_model, hop.source_id, hop.model_id)
not in identities
)
+ if normalized_model_hub_override(route) is None:
+ agent.routes.pop(menu_model)
def _guard_inventory_mutation(
self,
@@ -3355,6 +3361,7 @@ class ModelHubService:
confirmed_interruptions: object,
) -> tuple[list[dict], list[dict]]:
invalidated = self._invalidated_route_hops(updated, source_id)
+ self._prune_invalidated_route_hops(updated, invalidated)
would_remove_hops = self._removed_effective_hops(previous, updated)
would_remove_hops.extend(item for item in invalidated if item not in would_remove_hops)
would_interrupt = self._introduced_interruptions(previous, updated)
@@ -3370,8 +3377,6 @@ class ModelHubService:
else "source_last_supplier"
),
)
- if invalidated:
- self._prune_invalidated_route_hops(updated, invalidated)
return would_remove_hops, would_interrupt
@staticmethod
@@ -3419,7 +3424,8 @@ class ModelHubService:
agent.sources.order = [item for item in agent.sources.order if item != source_id]
for model_id, route in list(agent.routes.items()):
route.hops = tuple(hop for hop in route.hops if hop.source_id != source_id)
- agent.routes[model_id] = route
+ if normalized_model_hub_override(route) is None:
+ agent.routes.pop(model_id)
would_interrupt = self._introduced_interruptions(
previous,
config,
@@ -3689,6 +3695,7 @@ class ModelHubService:
raise ModelHubError("mapping_target_unavailable", status=409) from None
config = self._clone_config(self.store.load())
agent = self._validate_route_override(config, backend, model_id, route)
+ route = normalized_model_hub_override(route)
if route is None:
agent.routes.pop(model_id, None)
else:
@@ -3716,6 +3723,7 @@ class ModelHubService:
previous = self.store.load()
config = self._clone_config(previous)
agent = self._validate_route_override(config, backend, model_id, route)
+ route = normalized_model_hub_override(route)
if route is None:
agent.routes.pop(model_id, None)
else:
@@ -4866,13 +4874,14 @@ class ModelHubService:
for item in source.models
if item.id != model_id
]
- removed_hops = self._removed_effective_hops(previous, config)
- removed_hops.extend(item for item in retired_hops if item not in removed_hops)
invalidated = (
self._invalidated_route_hops(config, source.id)
if not source_supports_passthrough(source)
else []
)
+ self._prune_invalidated_route_hops(config, [*retired_hops, *invalidated])
+ removed_hops = self._removed_effective_hops(previous, config)
+ removed_hops.extend(item for item in retired_hops if item not in removed_hops)
removed_hops.extend(item for item in invalidated if item not in removed_hops)
would_interrupt = self._introduced_interruptions(previous, config)
self._require_guard_plan(
@@ -4887,16 +4896,6 @@ class ModelHubService:
else "source_last_supplier"
),
)
- if force and retired_hops:
- for agent in config.agents.values():
- for route in agent.routes.values():
- route.hops = tuple(
- hop
- for hop in route.hops
- if not (hop.source_id == source.id and hop.model_id == model_id)
- )
- if invalidated:
- self._prune_invalidated_route_hops(config, invalidated)
await self._commit_synced(previous, config)
return {
"source": self._source_payload(source),
diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.md
index 056254fda..6b19c5630 100644
--- a/docs/plans/model-hub-contracts/README.md
+++ b/docs/plans/model-hub-contracts/README.md
@@ -1,19 +1,29 @@
# Model Hub contracts
-Status: **contract_version 9**, 2026-09-06: sparse manual overrides, shared effective
+Status: **contract_version 10**, 2026-09-06: sparse manual overrides, shared effective
planning and guarded Restore/default membership. The approved routing contract is
-`../model-hub-routing-modes.md`, frozen at `2db273891` before implementation, amended by owner decision `c1d398d5f`.
+`../model-hub-routing-modes.md`, including the owner-approved Empty Route Inheritance
+correction `352486374`; API-key-only scope remains unchanged.
Supported persisted configuration shapes remain readable under the repository's
-persisted-shape rule. Existing explicit arrays, including empty, stale and dormant
-OpenCode routes, retain their exact intent. Do not infer old authorship from array
-contents or Source order. Ephemeral envelopes use the terminal version; persisted
+persisted-shape rule. Existing nonempty arrays, including stale and dormant OpenCode
+routes, retain their exact intent. Validate supported original shapes before normalizing
+valid empty values to absence; invalid values never silently become inherited. Canonical
+maps omit empty values without dropping catalog identities or other configuration.
+Reads/preview are pure; normal saves persist normalization. Do not infer old authorship
+from array contents or Source order. Ephemeral envelopes use the terminal version; persisted
TurnProvenance accepts historical versions through the terminal one without new
required route fields. Existing persistence readers normalize retired reason values
before current-schema validation without changing the writer generation; raw historical
bytes need not already use today's reason vocabulary. Generation names in older implementation history are not a
current version declaration.
+The `minItems: 1` constraints on `AgentSupply.routes` values and
+`AgentChain.manual_override.hops` are canonical-output constraints only. Empty PUT
+and preview arrays remain accepted Restore inputs, and supported legacy config must
+validate its original shape before empty-value normalization; it must not be
+rejected against the output-only restriction.
+
The contracts and their consumers must coexist on one tested PR head before Model Hub
can be enabled. CI evaluates that head, not individual commits. A green intermediate
commit is not evidence that the complete final protocol has landed.
@@ -22,13 +32,15 @@ commit is not evidence that the complete final protocol has landed.
- Sources are upstream assets. A Source never owns ordering.
- Gateway stores one default Source membership/order per backend and sparse manual
- overrides per model. Absence inherits; presence overrides, including an empty array.
-- The shared pure planner returns manual hops verbatim, otherwise all accepted matches
+ overrides per model. Absent and valid empty values inherit; only nonempty arrays override.
+- The shared pure planner returns nonempty manual hops verbatim, otherwise all accepted matches
in default order, otherwise unchanged-id passthrough on eligible non-retired Hub API-key defaults.
- Reads, previews, summaries, guards, adoption, probes, launches and execution use that
effective plan. Health and process readiness annotate it without changing its origin.
- New catalog rows have no override; Source creation appends defaults but never writes
- manual hops. Restoring automatic deletes the key; saving equal hops remains manual.
+ manual hops. Restoring automatic or empty PUT deletes the key with identical exact
+ guards; saving equal nonempty hops remains manual. Removing the final hop previews
+ inherited routing through the same Restore/Undo/Save flow, never empty Manual.
- A hop whose upstream `model_id` differs from its menu model is an explicit configured
mapping. There is no separate mapping object or runtime mapping event.
- The protocol vocabulary is exactly `anthropic | openai_responses | openai_chat`.
@@ -69,8 +81,10 @@ No underlying engine expansion or OAuth alias substitution is part of this chang
Normalized persisted catalog/target identities do not lose edit, preview, restore
or history-read capability when a later new-identifier length bound is shorter.
4. Source deletion atomically removes its id from every backend Source order and every
- exact Route chain, preserving survivor order. Serialization and reload reject a
- dangling Source id.
+ exact Route chain, preserving nonempty survivor order. Removing the final manual
+ hop drops its override key and recomputes inherited routing before exact removal,
+ supply-gap and transport-target planning. Serialization and reload reject a
+ dangling Source id before empty-value normalization.
5. Manual Route membership and order survive unrelated state changes. Automatic routes
follow current defaults and matching evidence. For the same planning inputs, health,
quota and process readiness may change runnability/current but never tier or origin.
@@ -103,7 +117,7 @@ comparison. A gate may not report success by comparing stale input with itself.
## Version closure
-`contract_version` 9 must coexist in all registered version locations on the same tested head:
+`contract_version` 10 must coexist in all registered version locations on the same tested head:
- `mirror-registry.json`
- `agent-chain.schema.json`
diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.py
index 3b459a289..a2dea1ce0 100644
--- a/docs/plans/model-hub-contracts/adapter-interface.py
+++ b/docs/plans/model-hub-contracts/adapter-interface.py
@@ -1,4 +1,4 @@
-"""Model Hub EngineAdapter interface. FINAL CONTRACT v9 (2026-09-06).
+"""Model Hub EngineAdapter interface. FINAL CONTRACT v10 (2026-09-06).
This file is the canonical adapter boundary and must remain byte-identical to
``core/handlers/model_hub/adapter.py``. The adapter owns one-Source operations:
diff --git a/docs/plans/model-hub-contracts/agent-chain.schema.json b/docs/plans/model-hub-contracts/agent-chain.schema.json
index 39ed29677..a08403144 100644
--- a/docs/plans/model-hub-contracts/agent-chain.schema.json
+++ b/docs/plans/model-hub-contracts/agent-chain.schema.json
@@ -2,16 +2,16 @@
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "model-hub/agent-chain.schema.json",
"title": "AgentChain",
- "description": "Read projection of the shared effective route plan. A sparse manual override wins verbatim; otherwise the planner selects matching evidence or exact-id passthrough on Hub API-key sources in backend default order. Live inspection adds health, runnability, blocker, retry annotations, and current position without changing plan membership or origin.",
+ "description": "Canonical output of the shared effective route plan. A nonempty sparse manual override wins verbatim; absent or valid empty values inherit matching evidence or exact-id passthrough on Hub API-key sources in backend default order. Live inspection adds health, runnability, blocker, retry annotations, and current position without changing plan membership or origin. Output-only minimum hop counts do not restrict accepted empty PUT/preview input or supported configuration before normalization.",
"type": "object",
"required": ["contract_version", "backend", "model_id", "manual_override", "route_origin", "chain", "current", "supply_state"],
"additionalProperties": false,
"properties": {
- "contract_version": { "const": 9 },
+ "contract_version": { "const": 10 },
"backend": { "enum": ["claude", "codex", "opencode"] },
"model_id": { "type": "string" },
"manual_override": {
- "description": "Actual persisted override, or the draft override on preview. Null means absent and automatic; an object with empty hops is an explicit empty override. Equality with generated hops never determines intent.",
+ "description": "Normalized nonempty manual override, or null for inherited routing. Valid empty saved values and preview inputs normalize to null without a read-time write. Preview reports normalized draft intent. Nonempty equality with generated hops never determines intent; there is no empty-disable state.",
"anyOf": [
{ "type": "null" },
{
@@ -21,6 +21,7 @@
"properties": {
"hops": {
"type": "array",
+ "minItems": 1,
"items": {
"type": "object",
"required": ["source_id", "model_id"],
@@ -37,7 +38,7 @@
},
"route_origin": {
"enum": ["automatic", "manual", "passthrough", null],
- "description": "Origin of the nonempty effective plan, independent of health and native process readiness. Passthrough is restricted to Hub API-key Sources; unmatched subscription-only defaults yield an empty plan. Null exactly when chain is empty, including an explicit empty manual override."
+ "description": "Origin of the nonempty effective plan, independent of health and native process readiness. Passthrough is restricted to Hub API-key Sources; unmatched subscription-only defaults yield an empty plan. Null exactly when the inherited effective chain is empty. Empty input inherits and does not force null origin."
},
"current": {
"anyOf": [
@@ -140,15 +141,11 @@
"allOf": [
{
"if": { "properties": { "manual_override": { "type": "object" } }, "required": ["manual_override"] },
- "then": {
- "if": { "properties": { "manual_override": { "properties": { "hops": { "maxItems": 0 } }, "required": ["hops"] } } },
- "then": { "properties": { "chain": { "maxItems": 0 } } },
- "else": { "properties": { "chain": { "minItems": 1 } } }
- }
+ "then": { "properties": { "chain": { "minItems": 1 }, "route_origin": { "const": "manual" } } }
},
{
"if": { "properties": { "chain": { "maxItems": 0 } }, "required": ["chain"] },
- "then": { "properties": { "route_origin": { "type": "null" }, "current": { "type": "null" } } },
+ "then": { "properties": { "manual_override": { "type": "null" }, "route_origin": { "type": "null" }, "current": { "type": "null" } } },
"else": {
"properties": { "route_origin": { "enum": ["automatic", "manual", "passthrough"] } },
"if": { "properties": { "manual_override": { "type": "object" } }, "required": ["manual_override"] },
@@ -208,7 +205,7 @@
],
"examples": [
{
- "contract_version": 9,
+ "contract_version": 10,
"backend": "codex",
"model_id": "unlisted-model",
"manual_override": null,
@@ -218,17 +215,17 @@
"supply_state": "ok"
},
{
- "contract_version": 9,
+ "contract_version": 10,
"backend": "codex",
"model_id": "gpt-5.6",
- "manual_override": { "hops": [] },
- "route_origin": null,
- "chain": [],
- "current": null,
- "supply_state": "interrupted"
+ "manual_override": null,
+ "route_origin": "automatic",
+ "chain": [{ "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "channel": "native_cli", "health": "healthy", "runnable": true, "reason": null, "retry_at": null }],
+ "current": { "source_id": "src_chatgptplus", "model_id": "gpt-5.6" },
+ "supply_state": "ok"
},
{
- "contract_version": 9,
+ "contract_version": 10,
"backend": "claude",
"model_id": "claude-opus-4-6",
"manual_override": null,
@@ -238,7 +235,7 @@
"supply_state": "waiting"
},
{
- "contract_version": 9,
+ "contract_version": 10,
"backend": "opencode",
"model_id": "glm-5.2",
"manual_override": { "hops": [{ "source_id": "src_relay9c1x", "model_id": "glm-5.2" }] },
@@ -248,7 +245,7 @@
"supply_state": "waiting"
},
{
- "contract_version": 9,
+ "contract_version": 10,
"backend": "codex",
"model_id": "gpt-5.6",
"manual_override": null,
@@ -258,7 +255,7 @@
"supply_state": "interrupted"
},
{
- "contract_version": 9,
+ "contract_version": 10,
"backend": "codex",
"model_id": "gpt-5.6",
"manual_override": null,
@@ -268,7 +265,7 @@
"supply_state": "interrupted"
},
{
- "contract_version": 9,
+ "contract_version": 10,
"backend": "claude",
"model_id": "claude-haiku-4-5",
"manual_override": null,
diff --git a/docs/plans/model-hub-contracts/agent-supply.schema.json b/docs/plans/model-hub-contracts/agent-supply.schema.json
index d4719a874..ab501f5f1 100644
--- a/docs/plans/model-hub-contracts/agent-supply.schema.json
+++ b/docs/plans/model-hub-contracts/agent-supply.schema.json
@@ -108,7 +108,7 @@
},
"routes": {
"type": ["object", "null"],
- "description": "Sparse persisted manual overrides keyed by caller-facing canonical menu ids. Key absence means automatic. Key presence preserves exact hops, including empty, stale and dormant arrays. Saving equal-to-automatic hops remains manual; Restore deletes the key. New catalog rows receive no key.",
+ "description": "Canonical sparse manual overrides keyed by caller-facing canonical menu ids. Output contains only nonempty arrays, preserving exact stale and dormant overrides. Valid empty configuration/input values normalize to key absence and inherited routing; validate supported raw config before normalization, not against this output-only minimum. Nonempty equal-to-automatic saves remain manual. Restore or empty PUT deletes the key. New catalog rows receive no key; normalization never removes catalog identities.",
"additionalProperties": {
"type": "object",
"required": ["hops"],
@@ -116,6 +116,7 @@
"properties": {
"hops": {
"type": "array",
+ "minItems": 1,
"items": {
"type": "object",
"required": ["source_id", "model_id"],
diff --git a/docs/plans/model-hub-contracts/api-response.schema.json b/docs/plans/model-hub-contracts/api-response.schema.json
index 6f017b2b3..85bbe1066 100644
--- a/docs/plans/model-hub-contracts/api-response.schema.json
+++ b/docs/plans/model-hub-contracts/api-response.schema.json
@@ -27,7 +27,7 @@
{"method": "GET", "path": "/api/models/catalog/models-dev?query=<text>", "response_schema": "ModelsDevResponse", "exercise": {"path": "/api/models/catalog/models-dev?query=contract-model", "status": 200}},
{"method": "GET", "path": "/api/models/agents/<backend>/chains", "response_schema": "ChainListResponse", "exercise": {"path": "/api/models/agents/claude/chains", "status": 200}},
{"method": "GET", "path": "/api/models/agents/<backend>/chain?model=<id>", "response_schema": "ChainResponse", "exercise": {"path": "/api/models/agents/claude/chain?model=claude-opus-4-6", "status": 200}},
- {"method": "PUT", "path": "/api/models/agents/<backend>/chain?model=<id>", "response_schema": "ChainMutationResponse", "exercise": {"path": "/api/models/agents/claude/chain?model=claude-opus-4-6", "status": 200, "json": {"hops": [{"source_id": "src_conform001", "model_id": "claude-opus-4-6"}]}}},
+ {"method": "PUT", "path": "/api/models/agents/<backend>/chain?model=<id>", "response_schema": "ChainMutationResponse", "exercises": [{"path": "/api/models/agents/claude/chain?model=claude-opus-4-6", "status": 200, "json": {"hops": [{"source_id": "src_conform001", "model_id": "claude-opus-4-6"}]}}, {"path": "/api/models/agents/claude/chain?model=claude-opus-4-6", "status": 200, "json": {"hops": []}}]},
{"method": "DELETE", "path": "/api/models/agents/<backend>/chain?model=<id>", "response_schema": "ChainMutationResponse", "exercise": {"path": "/api/models/agents/claude/chain?model=claude-opus-4-6", "status": 200, "json": {}}},
{"method": "POST", "path": "/api/models/agents/<backend>/chain/preview?model=<id>", "response_schema": "ChainResponse", "exercises": [{"path": "/api/models/agents/claude/chain/preview?model=claude-opus-4-6", "status": 200, "json": {"manual_override": null}}, {"path": "/api/models/agents/claude/chain/preview?model=claude-opus-4-6", "status": 200, "json": {"manual_override": {"hops": []}}}]},
{"method": "POST", "path": "/api/models/agents/<backend>/probe", "response_schema": "ProbeResponse", "exercise": {"path": "/api/models/agents/claude/probe", "status": 200, "json": {"model": "claude-opus-4-6"}}},
@@ -142,7 +142,7 @@
"SuccessCore": {
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9}
+ "contract_version": {"const": 10}
}
},
"SourceListResponse": {
@@ -151,7 +151,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"sources": {"type": "array", "items": {"$ref": "#/definitions/SourceApi"}}
}
},
@@ -161,7 +161,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"observation": {"$ref": "model-hub/observation-result.schema.json"}
}
},
@@ -171,7 +171,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"source": {"$ref": "#/definitions/SourceApi"},
"added_to": {"type": "array", "items": {"$ref": "#/definitions/AddedTo"}},
"adopted_by": {"type": "array", "items": {"$ref": "#/definitions/AdoptedBy"}, "uniqueItems": true}
@@ -183,7 +183,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"source": {"$ref": "#/definitions/SourceApi"}
}
},
@@ -193,7 +193,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"source": {"$ref": "#/definitions/SourceApi"},
"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},
"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}
@@ -205,7 +205,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},
"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}
}
@@ -216,7 +216,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"agents": {"type": "array", "items": {"$ref": "#/definitions/AgentSupplyApi"}}
}
},
@@ -226,7 +226,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"agent": {"$ref": "#/definitions/AgentSupplyApi"}
}
},
@@ -239,7 +239,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"agent": {"$ref": "#/definitions/AgentSupplyApi"},
"removed_hops": {"type": "array", "minItems": 1, "items": {"$ref": "#/definitions/RouteHopRef"}, "uniqueItems": true},
"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}, "uniqueItems": true}
@@ -264,7 +264,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": false},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"error": {"const": "candidate_suppliers_changed"},
"detail": {"type": "string", "minLength": 1},
"changed": {
@@ -284,7 +284,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"agent": {
"type": "object",
"required": ["backend", "mode", "catalog_models"],
@@ -365,7 +365,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"candidates": {
"type": "object",
"required": ["builtin", "providers", "in_list"],
@@ -384,7 +384,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"matches": {
"type": "array",
"maxItems": 8,
@@ -418,7 +418,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"chain": {"$ref": "model-hub/agent-chain.schema.json"}
}
},
@@ -428,7 +428,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"chains": {"type": "array", "items": {"$ref": "model-hub/agent-chain.schema.json"}}
}
},
@@ -438,7 +438,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"chain": {"$ref": "model-hub/agent-chain.schema.json"},
"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},
"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}
@@ -450,7 +450,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"probe": {"$ref": "model-hub/probe-result.schema.json"}
}
},
@@ -460,7 +460,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"events": {"type": "array", "items": {"$ref": "model-hub/resolution-event.schema.json"}}
}
},
@@ -470,7 +470,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"usage": {"$ref": "model-hub/usage-summary.schema.json"}
}
},
@@ -480,7 +480,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"flow": {
"allOf": [
{"$ref": "model-hub/oauth-flow.schema.json"},
@@ -502,7 +502,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"flow": {
"allOf": [
{"$ref": "model-hub/oauth-flow.schema.json"},
@@ -525,7 +525,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"flow": {
"allOf": [
{"$ref": "model-hub/oauth-flow.schema.json"},
@@ -550,7 +550,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9}
+ "contract_version": {"const": 10}
}
},
"RuntimeApi": {
@@ -572,7 +572,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"scan": {"$ref": "model-hub/migration-scan.schema.json"}
}
},
@@ -582,7 +582,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"applied": {"type": "integer", "minimum": 0},
"sources": {"type": "array", "items": {"$ref": "#/definitions/SourceApi"}},
"added_to": {"type": "array", "items": {"$ref": "#/definitions/AddedTo"}}
@@ -594,7 +594,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"provenance": {"$ref": "model-hub/turn-provenance.schema.json"}
}
},
@@ -605,7 +605,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"provenance": {
"anyOf": [
{"$ref": "model-hub/turn-provenance.schema.json"},
@@ -620,7 +620,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 9},
+ "contract_version": {"const": 10},
"runtime": {"$ref": "#/definitions/RuntimeApi"}
}
}
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index ec6c93e03..8258b3ad8 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -1,10 +1,10 @@
# Model Hub — REST API contract
-Status: **Normative, `contract_version` 9** — Model Hub implementations must conform, and the response conformance guard enumerates this route table and validates one real server response for every route.
+Status: **Normative, `contract_version` 10** — Model Hub implementations must conform, and the response conformance guard enumerates this route table and validates one real server response for every route.
-Success envelope: `{ok: true, contract_version: 9, ...}`.
+Success envelope: `{ok: true, contract_version: 10, ...}`.
Failure envelope:
-`{ok: false, contract_version: 9, error: <machine_code>, detail?: <i18n_key>}`.
+`{ok: false, contract_version: 10, error: <machine_code>, detail?: <i18n_key>}`.
`detail` is always a string. Structured error data lives in a named sibling.
Guarded mutation refusals specialize that envelope through
`guard-refusal.schema.json`; both report arrays are required and together form the plan
@@ -16,7 +16,7 @@ table. The contract guard requires the two endpoint sets to be identical, requir
exercised HTTP response for every registry entry, and validates that response against
the route's named schema.
-The shared envelope and every versioned nested contract carry `contract_version` 9, the
+The shared envelope and every versioned nested contract carry `contract_version` 10, the
terminal value. Supported persisted config shapes and historical TurnProvenance
remain readable; ephemeral envelopes use only the terminal version.
@@ -46,9 +46,9 @@ remain readable; ephemeral envelopes use only the terminal version.
| GET `/api/models/catalog/models-dev?query=<text>` | → `{matches: ModelsDevMatch[]}` | Read-only metadata lookup through the server-owned conditional cache. Results keep the shipped provider fields, deduplicate aggregator copies by model id, rank first-party matches first, add `first_party`, derive `native_protocol` from the model id's last path segment through the vendor map, cap results at 8, and never persist automatically. |
| GET `/api/models/agents/<backend>/chains` | → `{chains: AgentChain[]}` | Hub only. Returns the complete Overview model set in menu order, followed by a selected model or configured Route not already present. All members share one config snapshot and observation time. Direct returns the documented `direct_mode` error. |
| GET `/api/models/agents/<backend>/chain?model=<id>` | → `{chain: AgentChain}` | Hub only. Direct returns the documented `direct_mode` error. |
-| PUT `/api/models/agents/<backend>/chain?model=<id>` | `{hops: RouteHop[], force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or `{chain, removed_hops, interrupted}` | Saves an explicit manual override, including equal-to-automatic and empty arrays. New pairs validate canonical ids, Source eligibility/existence and retirement; API-key pairs do not require inventory membership, while subscriptions retain existing membership admission/stale-hop retention. `mutation.route_replace` retains its protected-supply-only guard for visible edits. |
+| PUT `/api/models/agents/<backend>/chain?model=<id>` | `{hops: RouteHop[], force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or `{chain, removed_hops, interrupted}` | Nonempty hops save an exact manual override, including equal-to-automatic arrays. Empty hops remain accepted and use DELETE Restore semantics with identical exact effective-removal/supply guards. New pairs validate canonical ids, Source eligibility/existence and retirement; API-key pairs do not require inventory membership, while subscriptions retain existing membership admission/stale-hop retention. Only nonempty replacement uses the protected-supply-only `mutation.route_replace` guard. |
| DELETE `/api/models/agents/<backend>/chain?model=<id>` | optional `{force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or `{chain, removed_hops, interrupted}` | `mutation.route_restore` removes the key and recomputes defaults; absent key is idempotent. Guard actual effective removals and supply loss. |
-| POST `/api/models/agents/<backend>/chain/preview?model=<id>` | `{manual_override: null \| {hops: RouteHop[]}}` → `{chain: AgentChain}` | Shared planner over an isolated draft config. No persistence, events, engine startup/sync, credentials or egress, including when runtime is stopped. |
+| POST `/api/models/agents/<backend>/chain/preview?model=<id>` | `{manual_override: null \| {hops: RouteHop[]}}` → `{chain: AgentChain}` | Accepts empty hops and normalizes them to null before the shared planner evaluates isolated draft config. Output manual_override is nonempty or null; effective chain/origin follows inheritance. No persistence, events, engine startup/sync, credentials or egress, including when runtime is stopped. |
| POST `/api/models/agents/<backend>/probe` | `{model?}` → `{probe: ProbeResult}` | Hub only. Direct returns the same `direct_mode` error. |
| GET `/api/models/agents/<backend>/provenance?model=<id>` | → `{provenance: TurnProvenance \| null}` | On-demand read of the most recently persisted retained record for this exact backend and canonical catalog model, regardless of outcome. Validates backend/model; absent history is null. Uses only the existing bounded store and never starts or syncs the engine. No history field is added to AgentChain. |
| GET `/api/models/events?limit=<n>&before=<id>` | → `{events: ResolutionEvent[]}` | Bounded source-resolution feed. |
@@ -60,7 +60,7 @@ remain readable; ephemeral envelopes use only the terminal version.
| POST `/api/models/migration/scan` | → `{scan: MigrationScan}` | Read-only. |
| POST `/api/models/migration/apply` | `{item_ids: string[]}` → `{applied, sources, added_to}` | Each accepted import runs the same default placement and effective adoption as Add Source; original files remain byte-identical. |
| GET `/api/models/turns/<turn_id>/provenance` | → `{provenance: TurnProvenance}` or documented absence error | Debug read for exactly attributed Hub turns. |
-| GET `/api/models/runtime/status` | → `{runtime: RuntimeDependency}` | Read-only managed engine status. The nested object carries `contract_version` 9 and persisted user intent in `enabled`; `not_started` is installed lazy-start idleness, not an alarm. |
+| GET `/api/models/runtime/status` | → `{runtime: RuntimeDependency}` | Read-only managed engine status. The nested object carries `contract_version` 10 and persisted user intent in `enabled`; `not_started` is installed lazy-start idleness, not an alarm. |
| POST `/api/models/runtime/install` | → `{runtime: RuntimeDependency}` | Idempotently starts server-owned installation. It returns and persists `installing`; reload reads the same state. Uses the existing mutation authentication and CSRF guards. |
| POST `/api/models/runtime/start` | → `{runtime: RuntimeDependency}` | Persists `enabled: true` and explicitly starts the managed engine. Service startup restores this intent. Uses the existing mutation authentication and CSRF guards; status reads never start it. |
| POST `/api/models/runtime/stop` | → `{runtime: RuntimeDependency}` | Explicitly stops the managed engine, persists `enabled: false`, and returns it to `not_started`. The mutation is rejected with `runtime_in_use` while any Agent backend is configured for Hub mode, so disabling the shared runtime cannot strand a configured route. |
@@ -439,10 +439,16 @@ Owner decision `c1d398d5f` scopes unknown-model passthrough and inventory-indepe
manual invocation to Hub API-key Sources. Subscriptions retain known-model admission and
automatic matching; unmatched subscription-only defaults yield an empty/null-origin plan.
-`AgentSupply.routes` is a sparse map of `{hops: RouteHop[]}` overrides. No key means
-automatic; a present empty array is deliberately empty. PUT creates a manual key even
-when submitted hops equal the automatic result. DELETE removes that key. Manual arrays
-are exact and can use an eligible Source outside default membership. New or changed
+`AgentSupply.routes` is the canonical sparse map of nonempty `{hops: RouteHop[]}`
+overrides. Missing and valid empty values both inherit. Nonempty PUT creates a manual
+key even when hops equal the generated result; empty PUT and DELETE remove it. Canonical
+output omits empty map values and reports `manual_override: null` for inherited intent.
+Output-only `minItems: 1` is not an input validation rule: empty PUT/preview remains
+accepted, and supported raw config is strictly validated before normalization. Invalid
+records never become automatic accidentally. Normal saves persist the normalized map
+without discarding nonempty/stale/dormant routes, catalog identities or unrelated fields;
+read/preview performs no write. Nonempty manual arrays are exact and may use an eligible
+Source outside default membership. New or changed
pairs require canonical nonempty ids, Source existence/eligibility and no explicit
retirement. API-key targets do not require inventory membership; subscription targets
retain existing known-model admission and stale-hop retention. Retained stale hops remain
@@ -455,18 +461,24 @@ when a later admission bound is shorter. Newly introduced identifiers still pass
admission; padding aliases remain rejected, and existing source, channel, retirement
and stale-hop policies are unchanged.
-PUT uses `mutation.route_replace`: visible noninterrupting removals are ordinary
-success; protected-supply interruption returns the existing exact-plan refusal. DELETE
-uses `mutation.route_restore`: guard actual effective removals and supply loss, then
+Nonempty PUT uses `mutation.route_replace`: visible noninterrupting removals are ordinary
+success; protected-supply interruption returns the existing exact-plan refusal. Empty
+PUT and DELETE use the same `mutation.route_restore` operation: guard actual effective removals and supply loss, then
remove the key and recompute. Both return `{chain, removed_hops, interrupted}` and
-preserve the existing error family and confirmation arrays. DELETE is idempotent if
-there is no key.
+preserve the existing error family and confirmation arrays. Both restore entry points
+share idempotency, admission, leases, synchronization and rollback. All final-hop
+removals, including Source deletion/catalog reconciliation, normalize before calculating
+effective removal, interruption and transport registration.
Preview requires `manual_override`, whose value is null for automatic or an object
-with the draft hops. It uses the same pure planner with isolated draft configuration,
+with the draft hops, including an accepted empty array normalized to null. It uses the
+same pure planner with isolated draft configuration,
returns the existing chain success envelope, and performs no persistent mutation,
event, runtime startup/sync, credential access or upstream request. The returned
-`manual_override` describes the draft, not persisted intent. Preview is available
+`manual_override` describes normalized draft intent, not persisted intent. Empty input
+may therefore return Automatic or Passthrough; only an empty inherited plan has null
+origin. Removing the final manual hop uses this Restore preview and its existing
+Undo/Save/guard/Done flow; the old nonempty override stays saved until success. Preview is available
while runtime is stopped. Save responses remain authoritative, and failed/ambiguous
writes follow existing reconciliation using intent as well as effective hops.
@@ -496,7 +508,7 @@ The terminal result of both ordinary API-key creation and OAuth creation is:
```json
{
"ok": true,
- "contract_version": 9,
+ "contract_version": 10,
"source": {
"id": "src_anthkey01",
"kind": "api_key",
@@ -561,7 +573,8 @@ The protected model set for a backend is the union of:
1. explicit models of enabled named Vibe Agents;
2. checked open-menu models;
-3. every menu model with a persisted Route row, including an empty `hops` array.
+3. every model with a retained nonempty manual Route row, including dormant routes;
+ legacy empty keys normalize away without removing their catalog identities.
The guard evaluates each protected `(backend, model)` against the post-mutation
state. It counts only runnable exact hops in that model's effective Route chain, never
@@ -574,7 +587,7 @@ Every guarded Source/inventory mutation uses the §4.5 envelope matrix and the c
```json
{
"ok": false,
- "contract_version": 9,
+ "contract_version": 10,
"error": "source_last_supplier",
"would_remove_hops": [],
"would_interrupt": [
@@ -601,16 +614,18 @@ server-side confirmation state exists.
The shared layer recomputes the current guarded-impact plan and then applies this total
decision matrix. For Source, inventory, default-membership and Restore mutations, a plan is nonempty when the staged
mutation has at least one `would_remove_hops` or `would_interrupt` item. For
-`mutation.route_replace`, only a nonempty `would_interrupt` activates the plan; its
+nonempty `mutation.route_replace`, only a nonempty `would_interrupt` activates the plan; its
refusal also reports every submitted removal in `would_remove_hops`, while a
noninterrupting removal skips refusal and appears only in successful `removed_hops`.
+Empty PUT shares `mutation.route_restore` with DELETE and cannot bypass the exact
+effective-removal guard.
Recalculation, exact-array comparison, and any commit share one atomic boundary. Source DELETE carries `force` in the query and the
two echoed arrays in its JSON body; every other guarded mutation carries all confirmation
fields in the JSON body.
| Decision | `force` | Recomputed plan | Echoed refusal plan | HTTP/API result |
| --- | --- | --- | --- | --- |
-| `guard_decision.unforced_no_impact` | false | empty, including visible noninterrupting `route_replace` removals | absent or supplied; echo is inert | ordinary mutation success |
+| `guard_decision.unforced_no_impact` | false | empty, including visible noninterrupting nonempty-manual `route_replace` removals | absent or supplied; echo is inert | ordinary mutation success |
| `guard_decision.unforced_confirmation` | false | nonempty | absent or supplied; echo is inert | HTTP 409 `GuardRefusal` with the current plan |
| `guard_decision.forced_no_impact` | true | empty | absent, exact, or stale | ordinary mutation success; `force` and any echo are inert |
| `guard_decision.forced_confirmed` | true | nonempty | both arrays exactly equal the recomputed plan | commit once and return the row's success envelope |
@@ -706,7 +721,7 @@ API-key success:
```json
{
"ok": true,
- "contract_version": 9,
+ "contract_version": 10,
"source": {
"id": "src_relay9c1x",
"kind": "api_key",
@@ -797,7 +812,7 @@ Status and submit return the same terminal shape:
```json
{
"ok": true,
- "contract_version": 9,
+ "contract_version": 10,
"flow": {
"flow_id": "oaf_claude01",
"client_nonce": "ofn_01j5w8z7p4n6q2rt",
@@ -827,9 +842,10 @@ reference is created.
## Chain and probe
In Hub mode, `AgentChain.chain` is the shared effective per-model route in planner
-order. `manual_override` reports actual key presence and `route_origin` reports
-`automatic | manual | passthrough | null`, independently of live health. Empty chains
-have null origin, even with `{hops: []}` manual intent. Live inspection annotates it: cooling, missing, model-unsupported,
+order. `manual_override` reports a normalized nonempty manual override or null and
+`route_origin` reports `automatic | manual | passthrough | null`, independently of live
+health. Valid empty input inherits; an empty effective chain therefore has both null
+manual_override and null origin. Live inspection annotates it: cooling, missing, model-unsupported,
source-blocked, live connection-backoff, and process-unavailable native CLI hops stay at their effective-plan
positions with live annotations.
`AgentChain.current` is either null or the exact `{source_id, model_id}` identity of
@@ -859,9 +875,9 @@ a valid `interrupted` chain.
```json
{
"ok": true,
- "contract_version": 9,
+ "contract_version": 10,
"chain": {
- "contract_version": 9,
+ "contract_version": 10,
"backend": "codex",
"model_id": "gpt-5.6",
"manual_override": null,
@@ -888,7 +904,7 @@ In Direct mode both chain and probe refuse with:
```json
{
"ok": false,
- "contract_version": 9,
+ "contract_version": 10,
"error": "direct_mode",
"detail": "models.hub.direct_mode"
}
@@ -902,9 +918,9 @@ A successful probe nests its result:
```json
{
"ok": true,
- "contract_version": 9,
+ "contract_version": 10,
"probe": {
- "contract_version": 9,
+ "contract_version": 10,
"backend": "claude",
"channel": "hub",
"reachable": false,
@@ -927,7 +943,7 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.
```json
{
- "contract_version": 9,
+ "contract_version": 10,
"backend": "codex",
"channel": "native_cli",
"reachable": true,
@@ -940,7 +956,7 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.
```json
{
- "contract_version": 9,
+ "contract_version": 10,
"backend": "codex",
"channel": "native_cli",
"reachable": false,
@@ -956,7 +972,7 @@ No candidate is an API error with a typed model-scoped state:
```json
{
"ok": false,
- "contract_version": 9,
+ "contract_version": 10,
"error": "probe_no_candidate",
"detail": "models.probe.no_candidate.waiting",
"supply": {
@@ -1018,7 +1034,7 @@ The store retains at most 500 exactly attributed settled turns with its existing
writes. Ambiguous attribution remains excluded; this is not a log of every upstream
request. Null means no matching retained record, including eviction. A newer served,
canceled or other record without a terminal error supersedes older error display.
-Success uses exactly `{ok: true, contract_version: 9, provenance: TurnProvenance | null}`;
+Success uses exactly `{ok: true, contract_version: 10, provenance: TurnProvenance | null}`;
there is no `success` field or envelope exception.
New `terminal_error` records may contain `http_status` (integer 100-599 or null) and
@@ -1058,7 +1074,7 @@ ambiguous absence are explicit and distinguishable from an unknown turn:
```json
{
"ok": false,
- "contract_version": 9,
+ "contract_version": 10,
"error": "provenance_unavailable",
"detail": "models.provenance.direct_mode"
}
@@ -1067,7 +1083,7 @@ ambiguous absence are explicit and distinguishable from an unknown turn:
```json
{
"ok": false,
- "contract_version": 9,
+ "contract_version": 10,
"error": "provenance_unavailable",
"detail": "models.provenance.attribution_ambiguous"
}
diff --git a/docs/plans/model-hub-contracts/guard-refusal.schema.json b/docs/plans/model-hub-contracts/guard-refusal.schema.json
index 60d6bfc6a..2108e4a1e 100644
--- a/docs/plans/model-hub-contracts/guard-refusal.schema.json
+++ b/docs/plans/model-hub-contracts/guard-refusal.schema.json
@@ -62,7 +62,7 @@
],
"properties": {
"ok": { "const": false },
- "contract_version": { "const": 9 },
+ "contract_version": { "const": 10 },
"error": {
"enum": [
"source_last_supplier",
@@ -117,7 +117,7 @@
"examples": [
{
"ok": false,
- "contract_version": 9,
+ "contract_version": 10,
"error": "source_model_in_route_chain",
"detail": "modelHub.errors.source_model_in_route_chain",
"would_remove_hops": [
diff --git a/docs/plans/model-hub-contracts/mirror-registry.json b/docs/plans/model-hub-contracts/mirror-registry.json
index d516bee8d..c60dd94f3 100644
--- a/docs/plans/model-hub-contracts/mirror-registry.json
+++ b/docs/plans/model-hub-contracts/mirror-registry.json
@@ -1,5 +1,5 @@
{
- "contract_version": 9,
+ "contract_version": 10,
"input_generation": {
"mode": "same_run_live_files",
"external_snapshot": "content_fingerprint_required"
@@ -450,7 +450,7 @@
},
{
"id": "D27",
- "domain": "effective route planning",
+ "domain": "normalized effective route planning",
"authority": {
"kind": "markdown_table",
"file": "docs/plans/model-hub.md",
diff --git a/docs/plans/model-hub-contracts/observation-result.schema.json b/docs/plans/model-hub-contracts/observation-result.schema.json
index 131270d1e..c77890e51 100644
--- a/docs/plans/model-hub-contracts/observation-result.schema.json
+++ b/docs/plans/model-hub-contracts/observation-result.schema.json
@@ -16,7 +16,7 @@
],
"additionalProperties": false,
"properties": {
- "contract_version": { "const": 9 },
+ "contract_version": { "const": 10 },
"outcome": {
"enum": [
"observed",
@@ -150,7 +150,7 @@
],
"examples": [
{
- "contract_version": 9,
+ "contract_version": 10,
"outcome": "observed",
"reachable": true,
"authenticated": "authenticated",
@@ -165,7 +165,7 @@
]
},
{
- "contract_version": 9,
+ "contract_version": 10,
"outcome": "authentication_failed",
"reachable": true,
"authenticated": "rejected",
@@ -175,7 +175,7 @@
"model_metadata": []
},
{
- "contract_version": 9,
+ "contract_version": 10,
"outcome": "ambiguous",
"reachable": true,
"authenticated": "unknown",
@@ -185,7 +185,7 @@
"model_metadata": []
},
{
- "contract_version": 9,
+ "contract_version": 10,
"outcome": "unreachable",
"reachable": false,
"authenticated": "unknown",
@@ -195,7 +195,7 @@
"model_metadata": []
},
{
- "contract_version": 9,
+ "contract_version": 10,
"outcome": "adapter_error",
"reachable": null,
"authenticated": "unknown",
@@ -205,7 +205,7 @@
"model_metadata": []
},
{
- "contract_version": 9,
+ "contract_version": 10,
"outcome": "timeout",
"reachable": null,
"authenticated": "unknown",
diff --git a/docs/plans/model-hub-contracts/opencode-overlay.md b/docs/plans/model-hub-contracts/opencode-overlay.md
index 3e28a5ed5..634f537cd 100644
--- a/docs/plans/model-hub-contracts/opencode-overlay.md
+++ b/docs/plans/model-hub-contracts/opencode-overlay.md
@@ -113,9 +113,12 @@ each perturbation.
## Persisted compatibility
-Supported saved shapes use the existing safe loader. Preserve sparse manual intent,
-including empty, stale and dormant OpenCode entries; do not infer old authorship or
-automatic intent from array equality/default order. Legacy shapes outside supported
+Supported saved shapes use the existing safe loader. Preserve nonempty sparse manual
+intent, including stale and dormant OpenCode entries. Validate the supported original
+payload before normalizing valid empty values to absence and inherited routing. Keep
+catalog identities and unrelated configuration; read/preview never persists, while a
+normal save omits empty route values. Never infer old authorship or automatic intent
+from nonempty array equality/default order. Legacy shapes outside supported
conversion use documented safe degradation, never a blanket pre-release waiver.
## Spike record (S1–S6; evidence captured 2026-09-04 on OpenCode 1.18.18 and CLIProxyAPI 7.2.105 `4a2eb54d`, the binary Avibe's manifest pins, with the repo mock upstream recording path/headers/body)
diff --git a/docs/plans/model-hub-contracts/probe-result.schema.json b/docs/plans/model-hub-contracts/probe-result.schema.json
index fce82d385..1d7375dff 100644
--- a/docs/plans/model-hub-contracts/probe-result.schema.json
+++ b/docs/plans/model-hub-contracts/probe-result.schema.json
@@ -7,7 +7,7 @@
"required": ["contract_version", "backend", "channel", "reachable", "source_id", "model_id", "latency_ms", "error"],
"additionalProperties": false,
"properties": {
- "contract_version": { "const": 9 },
+ "contract_version": { "const": 10 },
"backend": { "enum": ["claude", "codex", "opencode"] },
"channel": { "enum": ["hub", "native_cli"] },
"reachable": { "type": "boolean" },
@@ -62,10 +62,10 @@
}
],
"examples": [
- { "contract_version": 9, "backend": "codex", "channel": "hub", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": 412, "error": null },
- { "contract_version": 9, "backend": "claude", "channel": "hub", "reachable": false, "source_id": "src_relay9c1x", "model_id": "glm-5.2", "latency_ms": 287, "error": "models.source.needs_action.balance_exhausted" },
- { "contract_version": 9, "backend": "codex", "channel": "hub", "reachable": false, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": "models.source.backoff.connection_failed" },
- { "contract_version": 9, "backend": "codex", "channel": "native_cli", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": null },
- { "contract_version": 9, "backend": "codex", "channel": "native_cli", "reachable": false, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": "models.probe.native_cli_unavailable" }
+ { "contract_version": 10, "backend": "codex", "channel": "hub", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": 412, "error": null },
+ { "contract_version": 10, "backend": "claude", "channel": "hub", "reachable": false, "source_id": "src_relay9c1x", "model_id": "glm-5.2", "latency_ms": 287, "error": "models.source.needs_action.balance_exhausted" },
+ { "contract_version": 10, "backend": "codex", "channel": "hub", "reachable": false, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": "models.source.backoff.connection_failed" },
+ { "contract_version": 10, "backend": "codex", "channel": "native_cli", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": null },
+ { "contract_version": 10, "backend": "codex", "channel": "native_cli", "reachable": false, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": "models.probe.native_cli_unavailable" }
]
}
diff --git a/docs/plans/model-hub-contracts/runtime-dependency.schema.json b/docs/plans/model-hub-contracts/runtime-dependency.schema.json
index 4a30cf111..ecc295724 100644
--- a/docs/plans/model-hub-contracts/runtime-dependency.schema.json
+++ b/docs/plans/model-hub-contracts/runtime-dependency.schema.json
@@ -7,7 +7,7 @@
"required": ["contract_version", "manifest", "status"],
"additionalProperties": false,
"properties": {
- "contract_version": { "const": 9 },
+ "contract_version": { "const": 10 },
"enabled": {
"type": "boolean",
"description": "Persisted user intent for the managed gateway. Missing on older payloads means clients must fall back to observed health."
@@ -131,7 +131,7 @@
},
"examples": [
{
- "contract_version": 9,
+ "contract_version": 10,
"host_platform": "darwin-arm64",
"manifest": {
"name": "cliproxyapi",
diff --git a/docs/plans/model-hub-contracts/turn-provenance.schema.json b/docs/plans/model-hub-contracts/turn-provenance.schema.json
index d381262cd..b2af1db3e 100644
--- a/docs/plans/model-hub-contracts/turn-provenance.schema.json
+++ b/docs/plans/model-hub-contracts/turn-provenance.schema.json
@@ -36,7 +36,7 @@
"additionalProperties": false,
"properties": {
"contract_version": {
- "enum": [5, 6, 7, 8, 9],
+ "enum": [5, 6, 7, 8, 9, 10],
"$comment": "The only versioned object written to disk, so released versions form a set rather than a constant. Historical records validate after the existing persistence-read normalization of retired reasons; tests/fixtures/model_hub/released_v5_permission_denied.json exercises that boundary, not raw-file validation. Reading preserves the writer generation and requires no new route fields. New records carry the terminal member. Other versioned objects are ephemeral envelopes pinned to that value alone.",
"description": "Generation that wrote this record. Readers retain every supported released value, apply existing retired-reason normalization independently of version, and do not require route_origin or manual_override."
},
@@ -394,7 +394,7 @@
],
"examples": [
{
- "contract_version": 9,
+ "contract_version": 10,
"turn_id": "turn_01k9x2m4",
"ts": "2026-07-29T06:32:11Z",
"agent": "claude",
@@ -419,7 +419,7 @@
"blockers": []
},
{
- "contract_version": 9,
+ "contract_version": 10,
"turn_id": "turn_01k9x33p",
"ts": "2026-07-29T06:41:02Z",
"agent": "opencode",
@@ -440,7 +440,7 @@
"blockers": []
},
{
- "contract_version": 9,
+ "contract_version": 10,
"turn_id": "turn_01k9x3zq",
"ts": "2026-07-29T06:48:20Z",
"agent": "codex",
@@ -460,7 +460,7 @@
]
},
{
- "contract_version": 9,
+ "contract_version": 10,
"turn_id": "turn_01k9x4b7",
"ts": "2026-07-29T07:02:44Z",
"agent": "claude",
@@ -480,7 +480,7 @@
"blockers": []
},
{
- "contract_version": 9,
+ "contract_version": 10,
"turn_id": "turn_modelmissing01",
"ts": "2026-09-05T17:31:10Z",
"agent": "claude",
@@ -502,7 +502,7 @@
"blockers": []
},
{
- "contract_version": 9,
+ "contract_version": 10,
"turn_id": "turn_01k9x5ca",
"ts": "2026-07-29T07:08:00Z",
"agent": "codex",
diff --git a/docs/plans/model-hub-e2e-test-plan.md b/docs/plans/model-hub-e2e-test-plan.md
index d3519f1a7..95027eddf 100644
--- a/docs/plans/model-hub-e2e-test-plan.md
+++ b/docs/plans/model-hub-e2e-test-plan.md
@@ -1,7 +1,8 @@
# Model Hub E2E Test Plan
-Status: routing-mode acceptance revision, 2026-09-06. Contract: `model-hub-routing-modes.md`
-(original `2db273891`, owner scope/synchronization decision `c1d398d5f`). The older survey
+Status: routing-mode acceptance revision, contract_version 10, 2026-09-06.
+Contract: `model-hub-routing-modes.md` (original `2db273891`, owner scope/synchronization
+decision `c1d398d5f`, Empty Route Inheritance `352486374`). The older survey
below remains background for unrelated capabilities; routing expectations follow this revision.
Companion inventories (kept in session, summarized here): capability list C1–C81 and issue list B1–B17 produced during the 2026-09-01 survey.
@@ -42,7 +43,7 @@ Out of scope (documented, not dropped silently):
### B. API-key sources (C16–C29)
| ID | Steps | Expect | Status |
|---|---|---|---|
-| B1 | observe against mock for each protocol, `protocol:'auto'` | correct protocol chosen by response shape; observation payload contract_version 9 | assert |
+| B1 | observe against mock for each protocol, `protocol:'auto'` | correct protocol chosen by response shape; observation payload contract_version 10 | assert |
| B2 | custom user-declared protocol differs from response shape, authentication succeeds | declaration badge and runtime-risk warning stay visible; explicit confirmation persists exactly the chosen protocol, not an inferred one. Authentication remains required. Auto still needs matching shape evidence (2026-09-04 declaration rule; adapter consumer rejects authenticated but unshaped Auto responses). | assert |
| B3 | pull models (mock returns `display_name`, `context_length`, `pricing`, `supported_parameters`) | unrelated metadata is dropped; `supported_parameters` is retained in observation and the provenance ladder applies protocol-default tiers | assert |
| B4 | discovery fails | 422 `inventory_unavailable` unless `accept_unavailable_inventory:true`; then source commits with `state.status=error` | assert |
@@ -111,17 +112,17 @@ Out of scope (documented, not dropped silently):
| ID | Property | Evidence |
| --- | --- | --- |
-| RM-1 | Manual intent survives every unrelated config/catalog/health/process transition; equal-to-automatic saves remain manual and explicit empty overrides remain empty | Seed every supported saved shape, mutate defaults/inventory/catalog, reload and compare exact arrays and unrelated config |
+| RM-1 | Nonempty manual intent survives unrelated config/catalog/health/process transitions; equal-to-automatic nonempty saves remain manual, while absent and valid empty values inherit across all backends | Seed every supported saved shape, mutate defaults/inventory/catalog, reload and compare exact nonempty/stale/dormant arrays, catalog identities and unrelated config; canonical output maps omit empty values and manual_override is nonempty or null |
| RM-2 | Automatic matching precedes passthrough, and live health/transport restrictions never choose another tier | All backends with API-key unknown passthrough only, unmatched subscription-only defaults Unconfigured, known-model subscription admission and stale-hop retention, native Claude aliases/date/version rules, complete non-retired evidence, literal API matching, native-only matching with Hub-only invocation, tombstones and empty inventories |
| RM-3 | One planning input produces identical effective hops/origin in preview, read/list, summaries, adoption, guards, probe, launch and execution | Real API/controller boundaries, assert canonical model ids and Source ids; unknown inventory carries no invented reasoning tiers |
-| RM-4 | Restore/Undo/Cancel/Save preserve draft and persistence truth | Browser GET -> edit -> preview null -> Undo or Cancel -> reload; Save DELETE vs manual PUT; equal arrays, explicit empty, failed saves, stale preview and duplicate submission |
-| RM-5 | Effective removal confirmation is exact and atomic for defaults/Restore/inventory/catalog/Source writes | Refuse, alter state, retry stale plan, confirm current plan; no partial writes; pure reorders preserve manual arrays and need no confirmation |
+| RM-4 | Restore/Undo/Cancel/Save preserve normalized draft and persistence truth, including final-hop removal | Browser GET -> edit -> remove final hop or Restore -> preview null -> Undo to prior unsaved draft or Cancel -> reload; inherited Save uses DELETE, nonempty manual Save uses PUT even when equal to automatic. Cover actual inherited origin/targets or Unconfigured, no empty Manual save, failed saves, stale preview, confirmation, Done and duplicate submission |
+| RM-5 | Effective removal confirmation is exact and atomic for defaults/Restore/inventory/catalog/Source writes | Refuse, alter state, retry stale plan, confirm current plan; no partial writes. Empty PUT and DELETE have identical effective-removal/supply guards, idempotency, admission/lease and rollback behavior; only nonempty manual PUT retains the visible-edit interruption-only guard. A cascade removing the final hop drops its override before recomputing inherited impact; pure reorders preserve nonempty manual arrays and need no confirmation |
| RM-6 | Pinned CPA reaches the selected upstream with the exact canonical unknown model, without fake inventory or cross-Source fallback | Real backend launch -> correlation/gateway -> adapter -> pinned CPA -> local upstream; Hub API-key credentials on all API protocols and admitted non-ASCII ids/payloads; no subscription expansion |
| RM-7 | Transport registration remains separate from inventory and capabilities | Compare truthful SourceBinding.model_ids/Source.models with deterministic route_model_ids and compiler union; load absent field as empty; unchanged target sets do not restart; registration changes drain active transport leases before supervised restart, block new invocations behind the barrier and release leases on completion/close/cancellation independently of service settlement; prove sync cancellation/rollback and concurrent Save without deadlock; Hub OAuth registration remains unchanged |
| RM-8 | Request-only unknown-model errors preserve Source health and existing failure/stream boundaries | Typed upstream model_not_found, exact Source/model attribution, no fallback or global health transition |
-| RM-9 | Released config and turn records remain readable | Seed every supported historical shape, empty/populated/stale/dormant OpenCode arrays and unrelated sections; read TurnProvenance versions 5 through 9 without required route-origin fields |
+| RM-9 | Released config and turn records remain readable; normalization is not a validation bypass | Seed supported valid empty/populated/stale/dormant routes on every backend and direct-constructed config: validate original shapes first, normalize valid empty values without losing nonempty routes, catalog identities or unrelated sections, and persist the normalized map only on normal save. Reject malformed wrappers/hops/identifiers and dangling references before normalization. Output manual arrays require minItems 1, but accepted empty PUT/preview and legacy configuration do not. Read TurnProvenance versions 5 through 10 without requiring new optional metadata on old records |
| RM-10 | Approved help, labels and layout work on desktop/mobile in both themes | Screenshots against approved routing frames; hover/focus/touch help, Escape/outside dismissal, no row-open from badge, no overlapping labels/buttons |
-| RM-11 | Preview is an operationally read-only request | With runtime stopped assert unchanged config/events/engine lifecycle, no credential access or upstream egress, for manual, empty and restored drafts |
+| RM-11 | Read and preview are operationally pure, including normalization of valid legacy empties | With runtime stopped assert unchanged config bytes/events/engine lifecycle, no credential access or upstream egress, for nonempty manual, accepted empty and null restored drafts. Empty and null previews return the same inherited chain/origin and manual_override null without changing stored intent |
| RM-12 | Recorded error detail uses the latest retained exactly attributed turn, never a synthetic last-request history | Exercise backend/model provenance GET against the existing bounded store: exact backend/model isolation, latest persisted ordering independent of outcome, later success/cancel clearing, empty/evicted/ambiguous history, old records without optional metadata and deleted historical Sources. Capture real model_not_found with observed HTTP status; reject unsafe upstream text and invented codes. Prove retrieval never starts/syncs the engine or writes config/history/events. Browser evidence covers the Latest recorded turn label, same-record structured details, generic old-record copy, retry, pending-read invalidation on close/model change, unchanged route origin and no history writes from Cancel/Restore/Save |
| RM-13 | Every actual invocation atomically admits a current effective candidate before transport, without holding the global mutation lock during network | Deterministically pause resolution across target removal/change and Source configuration changes; exercise ordinary/fallback, bounded credential-refresh retry and probe through the same admission path. Preserve failed-Source exclusions, reject stale exact refresh pairs without fabricated attempts or synthetic upstream errors, and verify service-mutation then adapter-routing lock order. Pre-admission failure/cancellation releases exclusion; callback failure releases the lease before network; post-admission completion/cancel releases it. Concurrent independent HTTP requests progress during buffered/first-token/stream waits, with no per-request registration or persistent generation store |
@@ -129,6 +130,19 @@ All fixtures use test-owned HOME/XDG/config/credentials and local upstreams. Nev
personal state. Development acceptance uses coordinated local Incus only, preserving
master state. Mocked peer suites do not replace the pinned-engine boundary proof.
+Implemented unit/contract evidence for the empty-inheritance boundary supplements
+the end-to-end properties above; these are actual consuming tests, not proposed cases:
+
+| Property | Existing consuming test |
+| --- | --- |
+| RM-1/RM-3/RM-11: absent/empty parity across consumers | `tests/test_model_hub_routing_modes.py::test_empty_override_equals_absence_at_all_route_consumers` |
+| RM-4/RM-5: empty PUT equals guarded Restore; final-hop deletion inherits | `tests/test_model_hub_routing_modes.py::test_empty_put_has_exact_restore_guard_and_final_hop_deletion_inherits` |
+| RM-9: original invalid input never becomes automatic | `tests/test_model_hub_routing_modes.py::test_invalid_empty_intent_is_validated_before_normalization` |
+| RM-5: inventory final-hop changes use inherited effective impact | `tests/test_model_hub_routing_modes.py::test_final_inventory_hop_removal_uses_inherited_guard_plan` |
+| RM-5/RM-7: failed sync rolls back canonical intent and permits retry | `tests/test_model_hub_routing_modes.py::test_failed_route_sync_rolls_back_canonical_intent_and_retry` |
+| RM-1/RM-9: dormant/direct empty keys do not fabricate routes or guards | `tests/test_model_hub_routing_modes.py::test_direct_dormant_empty_is_absent_from_route_and_guard_enumeration` |
+| RM-9/RM-11: load is read-only; normal save persists normalization | `tests/test_model_hub_config.py::test_v2_empty_route_normalizes_on_load_without_writing_until_save` |
+
The Python `MH-ROUTING` scenarios in
`tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py` remain
canonical catalog evidence. `ui/e2e/model-routing-origin.spec.ts` adds Playwright
diff --git a/docs/plans/model-hub-implementation.md b/docs/plans/model-hub-implementation.md
index ced627ea6..644928916 100644
--- a/docs/plans/model-hub-implementation.md
+++ b/docs/plans/model-hub-implementation.md
@@ -1,34 +1,43 @@
# Model Hub — Implementation Plan
-## Routing modes delivery - contract_version 9
+## Routing modes delivery - contract_version 10
The current implementation contract is `model-hub-routing-modes.md`: original freeze
`2db273891`, owner scope/synchronization decision `c1d398d5f`, recorded-error closure
-`0de3d2f47`/`9cb9ebb53`, and atomic-admission amendment `c50bc43a5`. Its delivery ownership replaces
+`0de3d2f47`/`9cb9ebb53`, atomic-admission amendment `c50bc43a5`, and Empty Route
+Inheritance correction `352486374`. Its delivery ownership replaces
the historical independent-lane workflow below for this feature: one assigned shared
worktree, disjoint file ownership, one atomic feature PR, and orchestrator-only
commit/push/review integration. Historical lane tables remain importer ownership indexes;
they do not authorize another write lane or override this contract.
-Persist `routes` as sparse manual overrides: absent means automatic, present means exact
-manual intent, including empty/stale/dormant arrays. Source creation and catalog reconcile
+Persist `routes` as sparse nonempty manual overrides: absent and valid empty values both
+inherit; only nonempty values carry exact manual intent, including stale/dormant arrays.
+Validate supported original config before normalizing empties; keep catalog identities
+and unrelated fields, and reject invalid records rather than treating them as automatic.
+Reads and preview never write, while ordinary saves persist the normalized map.
+Source creation and catalog reconcile
never seed or append manual routes. Sources PUT edits backend default membership/order;
-manual PUT creates intent even when equal to automatic, DELETE restores by removing the
-key, and preview evaluates an isolated draft without side effects. One pure resolver owner
+nonempty manual PUT creates intent even when equal to automatic; empty PUT and DELETE
+share the exact restore operation, guards, idempotency, admission and rollback. Preview
+accepts empty/null input and evaluates inherited routing without side effects. Final-hop
+removal through any mutation normalizes before effective guards/transport registration.
+Canonical output manual arrays require at least one item; accepted inputs and supported
+legacy config do not share that output restriction. One pure resolver owner
returns manual_override, route_origin and hops for every read, summary, guard, adoption,
probe, launch and execution consumer. Match eligible defaults first, then unchanged-id
passthrough only when no match exists; health and process availability never choose a tier.
-Schema/API/type/mirror closure is contract_version 9 on the complete tested head.
+Schema/API/type/mirror closure is contract_version 10 on the complete tested head.
D26 binds the RouteOrigin schema to actual Python/TypeScript consumers and AgentSupply;
D27 binds the effective-route decision table to API markers. Existing registry absence,
credential/channel, guard, outcome and ownership checks remain enforced.
-TurnProvenance accepts released versions 5 through 9 with its historical required fields;
+TurnProvenance accepts released versions 5 through 10 with its historical required fields;
no route-origin requirement is retrofitted onto persisted records. Compatibility fixtures
preserve every supported config shape and unrelated sections.
Recorded error detail reads the existing bounded provenance store on demand through
-the backend/model GET and the ordinary v9 envelope, never through AgentChain. Optional
+the backend/model GET and the ordinary v10 envelope, never through AgentChain. Optional
terminal HTTP status and recognized upstream machine code preserve old records;
diagnostic code selection follows `9cb9ebb53` without changing classification. D28
mirrors that decision table; the direct backend test
@@ -905,7 +914,7 @@ I1 owns the remaining implementation closure and any contract field not changed
freeze. The mechanical gate is a **same tested PR head**, not a commit boundary: the
registered version and protocol consumers must coexist on that head before I1 merges.
-- The terminal `contract_version` is owner-fixed at **9** in every registered version consumer:
+- The terminal `contract_version` is owner-fixed at **10** in every registered version consumer:
`docs/plans/model-hub-contracts/mirror-registry.json`,
`docs/plans/model-hub-contracts/agent-chain.schema.json`,
`docs/plans/model-hub-contracts/probe-result.schema.json`,
@@ -963,18 +972,18 @@ external resolver importers.
| ID | Contract file | Final required shape |
| --- | --- | --- |
-| **FC-01** | `README.md` | Names §4.2 as the sole effective planner and §4.3 as its executor, indexes every contract file, and requires contract_version 9 closure on one tested head. Documents sparse manual overrides, default membership/order, automatic matching and API-key passthrough, historical config/turn readability, custody and pull-only supply visibility. |
-| **FC-02** | `mirror-registry.json` | Mechanically covers every closed enum and cross-file identity used by the final files: three protocols, backend ids, Source/model origins, exact-hop blocker/reason/detail-key/remedy pairs (including `native_cli_unavailable` and live connection backoff in AgentChain, ProbeResult, the API marker, and both frontend locale objects), credential refresh-capability branches, guard/OAuth/Source-create state machines, the guard-error-to-required-plan-array relation, network phase totality, turn outcome/discriminator/copy-key rows, native-import actions and locale keys, event agents, the sole remaining eligibility reason, `added_to`/`adopted_by` shapes, channel defaults, the four `supply_status` labels, the derived takeover label, and UI locale homes. The D21 fixture compares every consumer individually to the reason authority and mutation-tests ProbeResult drift; a surviving consumer cannot mask a missing peer. API-boundary-only refusal values register their contract field, named negative route test, and forbidden UI/i18n scope instead of fabricating a render consumer. The same live-input invocation proves retired route literals are absent repo-wide and path identities do not reappear in the Source-model request bodies. Every mirror names an executable relation and terminal version **9**. **D21 consumer-completeness revision: 2026-08-11 23:49 K4.** |
+| **FC-01** | `README.md` | Names §4.2 as the sole effective planner and §4.3 as its executor, indexes every contract file, and requires contract_version 10 closure on one tested head. Documents sparse manual overrides, default membership/order, automatic matching and API-key passthrough, historical config/turn readability, custody and pull-only supply visibility. |
+| **FC-02** | `mirror-registry.json` | Mechanically covers every closed enum and cross-file identity used by the final files: three protocols, backend ids, Source/model origins, exact-hop blocker/reason/detail-key/remedy pairs (including `native_cli_unavailable` and live connection backoff in AgentChain, ProbeResult, the API marker, and both frontend locale objects), credential refresh-capability branches, guard/OAuth/Source-create state machines, the guard-error-to-required-plan-array relation, network phase totality, turn outcome/discriminator/copy-key rows, native-import actions and locale keys, event agents, the sole remaining eligibility reason, `added_to`/`adopted_by` shapes, channel defaults, the four `supply_status` labels, the derived takeover label, and UI locale homes. The D21 fixture compares every consumer individually to the reason authority and mutation-tests ProbeResult drift; a surviving consumer cannot mask a missing peer. API-boundary-only refusal values register their contract field, named negative route test, and forbidden UI/i18n scope instead of fabricating a render consumer. The same live-input invocation proves retired route literals are absent repo-wide and path identities do not reappear in the Source-model request bodies. Every mirror names an executable relation and terminal version **10**. **D21 consumer-completeness revision: 2026-08-11 23:49 K4.** |
| **FC-03** | `source.schema.json` | **Revised 2026-08-11 by the owner-authorized K4 completion and 19:56 network ruling.** `Source` requires canonical id, kind, vendor, `protocol: anthropic | openai_responses | openai_chat`, credential reference/custody, channel, ordinary `created_at` audit metadata, state/usage, and an unordered model inventory whose ids are unique within that Source. Every model is `{id, origin: "discovered" | "manual", reasoning_efforts: string[], retired?: boolean, display_name?, discovered_at?}`; omission means `retired: false`, only a discovered row may be true, and true is a persistent tombstone excluded from supply. The list is required, may be empty, and its reasoning list is editable for either origin. Only shaped explicit upstream errors enter existing non-permanent Source classifications; unclassified transport failures never write persistent health. Hub-held subscriptions require no flag, consent field, or acknowledgement record. |
| **FC-04** | `oauth-flow.schema.json` | Subscription flows carry explicit vendor and `supply_channel`; an omitted channel resolves Claude to `native_cli` and ChatGPT to `hub`, while both opposite explicit choices remain legal. The native option exposes `native_source_already_exists` plus `existing_source_id` before login when the backend singleton is occupied. Claude Hub carries one informational risk-copy key; no other path carries warning or consent state. |
-| **FC-05** | `agent-supply.schema.json` | Each backend stores mode, default sources.order and a sparse map of manual {hops} overrides. Key absence inherits; key presence is exact intent, including empty. Actual effective routes own adoption and summaries; every model_supply row requires route_origin and effective chain_length, with null origin and false has_runnable_hop exactly for zero-length plans. Health remains a separate projection. New menu rows receive no key. |
-| **FC-06** | `agent-chain.schema.json` | AgentChain requires manual_override and route_origin and returns effective Source/model hops in planner order. Manual arrays remain exact; empty plans have null origin. Live current/runnable/blocker/retry annotations preserve the tier and membership. API-key inventory absence alone is not model_unsupported; subscriptions retain known-model admission; explicit retirement remains a blocker. Existing healthy/cooldown/backoff/action/process precedence remains unchanged, including native_cli_unavailable and waiting/interrupted relations. |
+| **FC-05** | `agent-supply.schema.json` | Each backend stores mode, default sources.order and a sparse map of manual {hops} overrides. Absent or valid empty values inherit; canonical map values are exact nonempty intent. Empty input normalizes without dropping catalog identity. Actual effective routes own adoption and summaries; every model_supply row requires route_origin and effective chain_length, with null origin and false has_runnable_hop exactly for zero-length plans. Health remains a separate projection. New menu rows receive no key. |
+| **FC-06** | `agent-chain.schema.json` | AgentChain requires manual_override and route_origin and returns effective Source/model hops in planner order. Manual output arrays require minItems 1 and remain exact; manual_override is nonempty or null. Empty input is accepted and inherits; only empty inherited plans have null origin. Live current/runnable/blocker/retry annotations preserve the tier and membership. API-key inventory absence alone is not model_unsupported; subscriptions retain known-model admission; explicit retirement remains a blocker. Existing healthy/cooldown/backoff/action/process precedence remains unchanged, including native_cli_unavailable and waiting/interrupted relations. |
| **FC-07** | `observation-result.schema.json` + `probe-result.schema.json` | Keeps unsaved Add Source connectivity/protocol/inventory observation separate from saved-Route runtime probes. Add-flow results report classified reachability/authentication plus an observed protocol only after a real upstream response, never a credential ref or request/status evidence detail. A failed observation may request a manual three-value probe-order hint but cannot save a protocol without response proof. `ProbeResult` remains the configured-Route runtime domain; its distinct live backoff key for unclassified pre-output connection failure implies exactly `channel: hub`, `reachable: false`, and `latency_ms: null`, rejecting native probes and measured-latency results. **Probe relation revision: 2026-08-11 23:49; observation evidence expansion remains withdrawn by the 20:35 owner ruling.** |
-| **FC-08** | `turn-provenance.schema.json` | Gateway turn records preserve exact requested/attempted model ids, Source attribution, order and closed outcomes from §4.5. `requested_model_changed` is derived from those exact ids and is never persisted. Historical versions 5 through 9 remain readable without requiring manual_override or route_origin. Canceled attempts fabricate no Source failure; no separate mapping or compatibility discriminator is persisted. |
+| **FC-08** | `turn-provenance.schema.json` | Gateway turn records preserve exact requested/attempted model ids, Source attribution, order and closed outcomes from §4.5. `requested_model_changed` is derived from those exact ids and is never persisted. Historical versions 5 through 10 remain readable without requiring manual_override or route_origin. Canceled attempts fabricate no Source failure; no separate mapping or compatibility discriminator is persisted. |
| **FC-09** | `resolution-event.schema.json` | Removes `mapping_applied` and its `mapping` reason: an explicit model mapping is stored configuration, not a runtime resolution event. Remaining events carry exact Source/model attribution with mechanically mirrored reason/detail/severity fields. The feed is a pull surface; event descriptions contain no proactive-delivery or recipient-resolution contract. No mapping field, route-rewrite event, or internal-version conversion state exists. |
| **FC-10** | `adapter-interface.py` | Defines the three protocols, response-backed protocol observation, connectivity classification, credential refresh capability, discovery, all-inventory reasoning-efforts validation, transient credential cleanup on every unsaved-flow exit, and durable reconciliation on revoke failure. `invoke(reasoning_effort: str | None)` stays singular because §4.3 passes zero or one exact member. Runtime-local `engine_down` is distinct from Source failure. The checked-in interface and runtime adapter are byte-identical. |
| **FC-11** | `opencode-overlay.md` | OpenCode menu identity is bare canonical model id with server-owned native_protocol. The overlay generates one provider per downstream protocol. The shared planner uses literal inventory matching or unchanged-id Hub API-key passthrough, and invocation pins the selected effective Source/model pair; manual mappings remain exact. Overlay identity does not encode current Source, route origin, health or credentials. |
-| **FC-12** | `api.md` | **Revised 2026-08-11 by the owner-authorized K4 completion; guard/nonce simplified by the 20:35 owner subtraction ruling, with deletion/recreate, process-local reservation, direct-Route scope, guard error/plan relations, canonical plan order, blocker/Probe/credential-response ownership, both-channel re-auth acknowledgement, OAuth explicit-cancel totality, and terminal materialization-error response ownership closed through 2026-08-12 01:28.** Contracts Source CRUD, add-only unsaved connectivity/protocol observation and discovery, the sole saved `POST /sources/<id>/refresh` mutation, the unified `/sources/<source_id>/models` subresource for manual creation, all-inventory reasoning-list edits, discovered-model retirement, and manual deletion, the explicit backend Source-order PUT, effective route GET/list, manual PUT, DELETE Restore and POST preview, mode, events/provenance, native-config import, OAuth, and Direct-mode responses. Source create returns exact `added_to` positions; Source cards use `adopted_by`; an optional nonce is reserved only in process before work and persisted on the Source only at commit, while committed retries conflict and reconcile through the ordinary Source list. Nonce uniqueness covers only live-process reservations and live Sources: clients read before retry, and restart or deletion plus list miss makes a same-nonce request a fresh create. OAuth start claims its nonce/vendor/channel tuple before provider work and coalesces a concurrent retry; failure or task cancellation before a flow exists releases after cleanup, while explicit cancellation of a nonce-bearing committed flow retains that same terminal `cancelled` flow until its existing expiry and never starts the provider on a delayed retry. A no-nonce cancel still forgets. Every Source/inventory mutation mirrors §4.5's total matrix row-for-row, including unguarded writes that cannot change `id`, `origin`, or Routes. Every guard lead error requires its corresponding nonempty evidence array; both plan arrays are duplicate-free and `would_interrupt` uses canonical outer `(backend, model_id)` plus inner stable-Agent-id order; every nonempty forced guarded-impact plan requires exact echoes of the refusal's `would_remove_hops` and `would_interrupt`. A missing or changed echo returns the same 409 family with the new plan and never removes an unconfirmed hop, while an empty recomputed plan follows ordinary success with force/echo inert. API-key credential success uses only `{source, removed_hops, interrupted}` and exposes repair through `Source.state`. Successful terminal OAuth re-auth alone owns the complete `{recovered, interrupted_pairs}` tail and may report an empty array; a terminal materialization error instead uses the standard error envelope and carries nonempty `interrupted_pairs` if and only if acquisition-stage Source mutation has already stranded supply, otherwise omitting the field. A visible noninterrupting `route_replace` removal is ordinary success; only protected-supply interruption enters that guard. The network totality table uses `stream_started` at the first user-visible model-output byte: it admits shaped errors before or after that boundary to existing Source classifications, gives an unclassified pre-output connection failure bounded live backoff, clears the streak only on later output from that same Source, normalizes an expired overlay before API serialization, and makes an unclassified post-output interruption event-only. A live overlay applies only over a healthy capability-present hop; cooldown, needs-action, error, missing Source, and unsupported model keep their stronger projections, while native-process unavailability is the sole reason-priority exception. Probe `connection_failed` is confined to the Hub/unreachable/null-latency shape. Forced Source/manual-model deletion preserves survivor order; discovered-model DELETE instead persists `retired: true`, retains the row through refresh, and uses the same exact-hop and protected-supply guards. OAuth-start rejects a duplicate native Source before adapter invocation. No saved `/test`, separate saved discovery, second persisted route policy, separate mapping, takeover, experimental-consent, observation-evidence detail, durable pre-create claim, receipt/digest, or vendor-guessed protocol surface exists. |
+| **FC-12** | `api.md` | **Revised 2026-08-11 by the owner-authorized K4 completion; guard/nonce simplified by the 20:35 owner subtraction ruling, with deletion/recreate, process-local reservation, direct-Route scope, guard error/plan relations, canonical plan order, blocker/Probe/credential-response ownership, both-channel re-auth acknowledgement, OAuth explicit-cancel totality, and terminal materialization-error response ownership closed through 2026-08-12 01:28.** Contracts Source CRUD, add-only unsaved connectivity/protocol observation and discovery, the sole saved `POST /sources/<id>/refresh` mutation, the unified `/sources/<source_id>/models` subresource for manual creation, all-inventory reasoning-list edits, discovered-model retirement, and manual deletion, the explicit backend Source-order PUT, effective route GET/list, manual PUT, DELETE Restore and POST preview, mode, events/provenance, native-config import, OAuth, and Direct-mode responses. Source create returns exact `added_to` positions; Source cards use `adopted_by`; an optional nonce is reserved only in process before work and persisted on the Source only at commit, while committed retries conflict and reconcile through the ordinary Source list. Nonce uniqueness covers only live-process reservations and live Sources: clients read before retry, and restart or deletion plus list miss makes a same-nonce request a fresh create. OAuth start claims its nonce/vendor/channel tuple before provider work and coalesces a concurrent retry; failure or task cancellation before a flow exists releases after cleanup, while explicit cancellation of a nonce-bearing committed flow retains that same terminal `cancelled` flow until its existing expiry and never starts the provider on a delayed retry. A no-nonce cancel still forgets. Every Source/inventory mutation mirrors §4.5's total matrix row-for-row, including unguarded writes that cannot change `id`, `origin`, or Routes. Every guard lead error requires its corresponding nonempty evidence array; both plan arrays are duplicate-free and `would_interrupt` uses canonical outer `(backend, model_id)` plus inner stable-Agent-id order; every nonempty forced guarded-impact plan requires exact echoes of the refusal's `would_remove_hops` and `would_interrupt`. A missing or changed echo returns the same 409 family with the new plan and never removes an unconfirmed hop, while an empty recomputed plan follows ordinary success with force/echo inert. API-key credential success uses only `{source, removed_hops, interrupted}` and exposes repair through `Source.state`. Successful terminal OAuth re-auth alone owns the complete `{recovered, interrupted_pairs}` tail and may report an empty array; a terminal materialization error instead uses the standard error envelope and carries nonempty `interrupted_pairs` if and only if acquisition-stage Source mutation has already stranded supply, otherwise omitting the field. A visible noninterrupting nonempty `route_replace` removal is ordinary success; empty PUT instead uses DELETE Restore and its exact effective-removal/supply guards. The network totality table uses `stream_started` at the first user-visible model-output byte: it admits shaped errors before or after that boundary to existing Source classifications, gives an unclassified pre-output connection failure bounded live backoff, clears the streak only on later output from that same Source, normalizes an expired overlay before API serialization, and makes an unclassified post-output interruption event-only. A live overlay applies only over a healthy capability-present hop; cooldown, needs-action, error, missing Source, and unsupported model keep their stronger projections, while native-process unavailability is the sole reason-priority exception. Probe `connection_failed` is confined to the Hub/unreachable/null-latency shape. Forced Source/manual-model deletion preserves survivor order; discovered-model DELETE instead persists `retired: true`, retains the row through refresh, and uses the same exact-hop and protected-supply guards. OAuth-start rejects a duplicate native Source before adapter invocation. No saved `/test`, separate saved discovery, second persisted route policy, separate mapping, takeover, experimental-consent, observation-evidence detail, durable pre-create claim, receipt/digest, or vendor-guessed protocol surface exists. |
| **FC-13** | `migration-scan.schema.json` | Copy-only native config import uses the §6 action matrix. keep_native/import place Sources into backend defaults and report effective added_to positions without writing manual route keys. Original files remain byte-identical, duplicate native selection fails before OAuth/partial commit. Supported internal persisted shapes still use compatibility loading; import is a separate user workflow. |
| **FC-14** | `runtime-dependency.schema.json` | Defines the single local engine asset, immutable version/SHA, loopback binding, lifecycle/health, management and Gateway tokens, and fail-closed behavior. `installing` is exactly the unverified non-listening shape with null installed version; any verified/listening runtime settles outside that transition. Engine availability is local Gateway health and never mutates an upstream Source cooldown. This entry does not widen the GA asset-mirror or platform-matrix research scope. **Installing-shape revision: 2026-08-11 23:09 K4.** |
@@ -993,18 +1002,18 @@ collectively touch every applicable row and leave no downstream compatibility ta
| Landing point | Required result |
| --- | --- |
| `config/v2_config.py` | Final Source/model/protocol/configured-route types, one canonical validation boundary shared by every persisted-Source writer and subsequent load, singleton and exact-pair uniqueness validation, one default Source order per backend and sparse manual hops overrides, persisted discovered-model retirement plus the committed Source-create `client_nonce` column, serializer completeness, fresh-install Gateway construction, and existing-install-with-no-Hub-state Direct onboarding. No durable pre-create claim, receipt, digest, tombstone, terminal-envelope snapshot, plaintext key, or policy state exists. A committed nonce survives with its Source, Source deletion releases it, and the post-read same-nonce request creates a new id. Unclassified transport failure and live connection backoff never serialize into Source/config state. **Retirement/nonce/network revision: 2026-08-11 21:14 K4.** |
-| `core/handlers/model_hub/{service,resolver,classification,errors}.py` | One §4.3 effective-chain executor and one Add Source implementation of §4.2's placement policy; the latter persists default Source placement, then projects effective `added_to` without writing manual arrays. Also owns the complete credential-failure matrix keyed by refresh capability, closed error classes, `adopted_by`, Source-global health, local-engine distinction, and all route/inventory guards. After K4, #1312, and K6 merge, I7 owns `resolver.py`, `classification.py`, and `tests/test_model_hub_resolution.py`: Effective matching, new-Route validation, runnability, and invocation exclude explicit retired pairs; missing API-key inventory alone remains callable; subscription membership remains required; the network classifier executes every shaped/unclassified × `stream_started: false/true` cell at the first user-visible model-output boundary and alone owns live connection-backoff state. Only later output from the affected Source resets its streak; another Source's successful fallback does not. Before serialization, the read assembler normalizes an expired overlay to underlying non-backoff health. Concurrent cooldown, needs-action, error, missing-Source, or unsupported-model facts suppress a live overlay and keep the stronger projection; none may roll up as waiting. Simultaneous native-process unavailability is the sole exception and takes reason precedence while backoff health/deadline remains. `service.py` is the single shared guard planner for every matrix row; it recomputes and compares duplicate-free refusal arrays, emits SupplyGap rows in canonical `(backend, model_id)` order with stable-id-sorted `agents`, enforces each lead error's corresponding nonempty plan array, commits noninterrupting `route_replace` normally, and uses `source_last_supplier` only for interruption. It is also the sole AC-53 materialization decision owner: a failed terminal settlement attaches the exact nonempty acquisition-stage `interrupted_pairs` report only after persisted route impact, otherwise omitting the field. Discovered-model DELETE persists the retirement tombstone and refresh never revives it. Source-create reserves its nonce only in process before work, releases it only after retained-material reconciliation, atomically reclaims it after release, persists it only on success, and returns committed conflict for list-based reconciliation; process restart or deletion releases the live-only nonce and the post-read same-nonce request is a fresh create. Execution consumes the shared effective plan; it never reselects a tier or writes a network health verdict. A static-key `401` performs no retry; only refresh-capable credentials receive one bounded refresh. **Turn-outcome dependency revision: 2026-08-12 02:00 K4.** |
+| `core/handlers/model_hub/{service,resolver,classification,errors}.py` | One §4.3 effective-chain executor and one Add Source implementation of §4.2's placement policy; the latter persists default Source placement, then projects effective `added_to` without writing manual arrays. Also owns the complete credential-failure matrix keyed by refresh capability, closed error classes, `adopted_by`, Source-global health, local-engine distinction, and all route/inventory guards. After K4, #1312, and K6 merge, I7 owns `resolver.py`, `classification.py`, and `tests/test_model_hub_resolution.py`: Effective matching, new-Route validation, runnability, and invocation exclude explicit retired pairs; missing API-key inventory alone remains callable; subscription membership remains required; the network classifier executes every shaped/unclassified × `stream_started: false/true` cell at the first user-visible model-output boundary and alone owns live connection-backoff state. Only later output from the affected Source resets its streak; another Source's successful fallback does not. Before serialization, the read assembler normalizes an expired overlay to underlying non-backoff health. Concurrent cooldown, needs-action, error, missing-Source, or unsupported-model facts suppress a live overlay and keep the stronger projection; none may roll up as waiting. Simultaneous native-process unavailability is the sole exception and takes reason precedence while backoff health/deadline remains. `service.py` is the single shared guard planner for every matrix row; it recomputes and compares duplicate-free refusal arrays, emits SupplyGap rows in canonical `(backend, model_id)` order with stable-id-sorted `agents`, enforces each lead error's corresponding nonempty plan array, commits noninterrupting nonempty `route_replace` normally, delegates empty PUT to exact Restore guards, and uses `source_last_supplier` only for interruption. It is also the sole AC-53 materialization decision owner: a failed terminal settlement attaches the exact nonempty acquisition-stage `interrupted_pairs` report only after persisted route impact, otherwise omitting the field. Discovered-model DELETE persists the retirement tombstone and refresh never revives it. Source-create reserves its nonce only in process before work, releases it only after retained-material reconciliation, atomically reclaims it after release, persists it only on success, and returns committed conflict for list-based reconciliation; process restart or deletion releases the live-only nonce and the post-read same-nonce request is a fresh create. Execution consumes the shared effective plan; it never reselects a tier or writes a network health verdict. A static-key `401` performs no retry; only refresh-capable credentials receive one bounded refresh. **Turn-outcome dependency revision: 2026-08-12 02:00 K4.** |
| `modules/agents/model_hub.py`; Model Hub failure callbacks in `modules/agents/{base,claude_agent}.py`, `modules/agents/codex/{agent,event_handler}.py`, and `modules/agents/opencode/{agent,poll_loop}.py` | After K4, #1312, and K6 merge, I7 moves the native launch seam from persistent 30-second network cooldowns to AC-50's phase-aware decision. Each backend callback supplies exact failure shape and `stream_started`, which flips only at the first user-visible model-output byte; `modules/agents/model_hub.py` alone classifies and chooses persistent Source state, live connection backoff, or event-only handling. Exact cross-backend fixtures in `tests/{test_claude_agent_sessions,test_codex_agent,test_opencode_server}.py` cover both phases and prove zero persistent write for unclassified transport failures; the post-output same-current-hop fixture consumes K6's G-34 outcome/copy/payload row exactly. `tests/{test_claude_cli_path,test_multi_platform_runtime}.py` receive only required signature adaptations. I2 owns the equivalent raw phase facts only for the managed Gateway. **Turn-outcome dependency revision: 2026-08-12 02:00 K4.** |
| `core/handlers/model_hub/{oauth,native_oauth,revocations,migration}.py` | Vendor-specific OAuth defaults, duplicate-native rejection before adapter work, all-exit transient credential cleanup, durable revoke reconciliation, and pre-provider exact-tuple OAuth-start claim/coalescing/release/flow conversion and nonce echo. The registry releases only a failed/task-canceled start before a flow exists; it retains an explicitly canceled nonce-bearing committed flow as the same terminal `cancelled` flow until existing expiry, then releases the tuple. The row also owns the complete four-row native-config action matrix with original files untouched. Every imported Source passes the canonical final-shape validator before commit; no import writer bypasses it with direct dataclass construction. **OAuth explicit-cancel revision: 2026-08-12 00:37 K4.** |
-| `core/handlers/model_hub/{rpc,request,provenance,events}.py`, `vibe/ui_server.py`, `vibe/model_hub_client.py`, `core/controller.py` | Final API envelopes/routes mirror the guarded-mutation and guard-totality matrices, including current-plan refusal, exact plan-echo confirmation, empty-plan ordinary success, Source-delete, discovered-model retirement, ordinary noninterrupting Route replacement versus interrupted refusal, guarded default-order update, runtime install/no-op, all three nonce-retry states, read-before-retry plus restart/deletion fresh-create behavior, nonce-bearing canceled-flow replay/expiry versus no-nonce forget, terminal materialization error/report totality, and live connection-backoff reads. `rpc.py`, `request.py`, `ui_server.py`, and `model_hub_client.py` only carry refusal plans when a refusal exists; they do not mint or persist confirmation state. For AC-53, `ui_server.py` and `model_hub_client.py` preserve an exact nonempty `interrupted_pairs` error member and omit it otherwise; they never synthesize `[]`, `flow`, or future-tense `would_interrupt` on an error. After K6, `events.py` transfers from I1 to I7 and records each network-totality cell without turning an unclassified failure into persistent state; unclassified interruption after user-visible model output is event-only. Provenance mirrors the complete K6-frozen turn-outcome matrix, including `canceled` and G-34's selected row, and never invents an outcome id, copy key, or payload shape. Direct-mode responses remain explicit. During implementation, absence of `VIBE_MODEL_HUB_ENABLED` keeps the controller/routes/UI disabled; explicit enablement must construct the v3 aggregate. This is a release-control gate, not a compatibility layer. I6 removes it only after I5 evidence is green. **Turn-outcome dependency revision: 2026-08-12 02:00.** |
+| `core/handlers/model_hub/{rpc,request,provenance,events}.py`, `vibe/ui_server.py`, `vibe/model_hub_client.py`, `core/controller.py` | Final API envelopes/routes mirror the guarded-mutation and guard-totality matrices, including current-plan refusal, exact plan-echo confirmation, empty-plan ordinary success, Source-delete, discovered-model retirement, ordinary noninterrupting nonempty manual replacement versus interrupted refusal, empty PUT using exact DELETE Restore guards, guarded default-order update, runtime install/no-op, all three nonce-retry states, read-before-retry plus restart/deletion fresh-create behavior, nonce-bearing canceled-flow replay/expiry versus no-nonce forget, terminal materialization error/report totality, and live connection-backoff reads. `rpc.py`, `request.py`, `ui_server.py`, and `model_hub_client.py` only carry refusal plans when a refusal exists; they do not mint or persist confirmation state. For AC-53, `ui_server.py` and `model_hub_client.py` preserve an exact nonempty `interrupted_pairs` error member and omit it otherwise; they never synthesize `[]`, `flow`, or future-tense `would_interrupt` on an error. After K6, `events.py` transfers from I1 to I7 and records each network-totality cell without turning an unclassified failure into persistent state; unclassified interruption after user-visible model output is event-only. Provenance mirrors the complete K6-frozen turn-outcome matrix, including `canceled` and G-34's selected row, and never invents an outcome id, copy key, or payload shape. Direct-mode responses remain explicit. During implementation, absence of `VIBE_MODEL_HUB_ENABLED` keeps the controller/routes/UI disabled; explicit enablement must construct the v3 aggregate. This is a release-control gate, not a compatibility layer. I6 removes it only after I5 evidence is green. **Turn-outcome dependency revision: 2026-08-12 02:00.** |
| `core/handlers/model_hub/adapter.py` | Exact byte mirror of `model-hub-contracts/adapter-interface.py`, including three protocols and observation/cleanup signatures. |
| `core/handlers/model_hub/turn_gateway.py`, `vibe/model_hub_runtime/**` | Exact effective-hop execution, three-protocol transport, credential refresh capability, authoritative `stream_started` facts at the first user-visible model-output byte, pre-output fallthrough, post-output no replay, and local Gateway failures at any request phase excluded from Source state and fallback. I2 transports raw phase/shaped-error evidence but does not own the network taxonomy, Source decision, or live-backoff executor transferred to I7. The runtime owns the persisted install worker/lease, orphan reconciliation, host detection, installed-state no-op, and the exact installing shape `{installed_version: null, verified: false, listening: null}` without owning HTTP routes. Turn copy is selected only from the K6-frozen authoritative outcome matrix after I7's state decision and live annotation of the same effective chain. **Turn-outcome dependency revision: 2026-08-12 02:00 K4.** |
| `ui/src/components/settings/models/**` | Final Source/Gateway types and calls; protocol selector only after failed observation as a probe-order hint; Source cards reuse `adopted_by`; Add Source renders the stored backend Source order plus returned `added_to` positions without inferring newness from order; state ⑤ alone emits `accept_unavailable_inventory: true`, while clean creation and pull-origin state ⑤′ omit it; backend groups consume `supply_status`; takeover derives from the chain; saved Source details exposes only guarded Refresh models; Direct groups expose reversible mode actions. For frame 02, I4's current increment opens the editor from each model row, renders the drawing, and consumes the chain read projection only: it wires no chain-write caller and keeps Save disabled. Exact stored-hop/mapping editing and exact two-array plan echo belong to I4's second increment after K5 round 3 and I7 refusal fixtures merge. Live connection-backoff presentation also belongs to the second increment after K5 round 2 corrects its UI-spec copy and I7 freezes producer fixtures. AC-53 error-gap rendering likewise belongs to the second increment after K5 round 2 registers E6 and I7 freezes positive/negative payloads; `modelsApi.ts` carries only an actually present nonempty `interrupted_pairs`, and `OAuthConnectDialog.tsx` refetches Source state after the materialization error. The current increment consumes master's pre-I7 refusal shape and must not add inactive confirmation fields. K5 round 2 separately removes the withdrawn observation request/status detail slots. The current increment also consumes the already-specified install/unsupported-host states; the second consumes the remaining K4 projections/actions only after their named K5 round-2 upgrades. **Materialization-response revision: 2026-08-12 01:28 by PM ruling.** No bottom-only “new” section, redundant policy control, “not enabled” hint, latency/last-check copy, separate experimental-consent surface, separate mapping object, takeover field, supplying-backends field, or vendor default protocol exists. Any new-item marker is transient presentation state, not a route field. `vendorMeta.ts` may order probes but cannot choose a saved protocol. Narrowing `SourceProtocol` must be checked against production and test files, not only the production-only `tsconfig.app.json` program. |
| `ui/src/i18n/{en,zh}.json`, `vibe/i18n/{en,zh}.json` | Exact mirrored final reason/detail and `supply_status` keys, including `native_cli_unavailable` and `route_unconfigured`; every Turn-outcome copy-matrix key; the derived takeover label; distinct Direct/Native terms; the sole Claude Hub warning; compact protocol-observation failure copy; and no retired policy, separate experimental-consent, or mechanism-copy keys. After K5 round 2's UI-spec sync, I4's second increment adds the distinct short connection-backoff copy for `models.source.backoff.connection_failed`; it never reuses quota-cooldown wording. A registry-generated guard compares closed outcome/discriminator, blocker/remedy, and credential-remedy relations with both locale sets. |
| `tests/test_model_hub_config.py` | The adapter parity and terminal-version gates remain exact; round-trip/completeness fixtures use only final Source and route shapes. It validates committed Source `client_nonce` persistence and live-only uniqueness, deletion release, rejects durable claim/receipt/digest/tombstone fields and unregistered observation evidence, and mechanically closes OAuth cancel totality: pending-start cancellation releases, explicit nonce-bearing cancellation retains the same terminal flow until expiry, no-nonce cancellation forgets, and the old blanket-forget promise is absent. It proves live backoff cannot serialize as Source state, rejects pure cooldown/backoff chains mislabeled `interrupted`, and keeps durable/capability blockers interrupted under a concurrent deadline. D21 compares AgentChain, ProbeResult, the API marker, and both UI locales individually, with a ProbeResult mutation that must break equality. D22 proves the same five OAuth terminal decision ids exist exactly once in authority and API, success re-auth may carry an empty complete report, materialization errors carry an exact nonempty report if and only if persisted acquisition impact exists, and every other error omits the member. The narrow K4 ledger assertion binds AC-52 and the I3/auth-setup landing row to AUTH-SETUP-109, its two exact scenario files, the pre-adapter negative cells, the provider-once positive cell, the terminal repair projection, and the K4+#1312 activation edge. The same fixture rejects zero-length model supply marked runnable, each installing-shape contradiction, every guard error paired with an empty required plan array, duplicate hop/gap plan entries, and any credential response that revives the OAuth-only repair tail. The K4 AC-54 fixture validates the optional boolean, rejects non-booleans, and freezes every repeat-observation × consent row plus its owner/files/activation handoff. K6 never owns this file; after K6 freezes G-34, I7 adds the mechanical matrix/schema consumer fixture under the three-way activation edge. **Turn-outcome handoff revision: 2026-08-12 02:00 K4.** |
-| `tests/test_model_hub_api.py` | The current line-1204 `experimental_consent_at` assertion becomes an absence assertion; API fixtures cover unique final model entries, edited-effort and retirement preservation across rediscovery, distinct add-only unsaved operations versus the sole guarded saved refresh, all-exit discovery cleanup, three protocols, observation-before-save, all three pre-observation nonce retry states, deterministic policy-chosen Add Source placement with the returned persisted position, and every guarded-mutation row. OAuth API fixtures prove nonce-bearing explicit cancel retains the same `cancelled` flow and exact-tuple retry performs zero provider starts, existing expiry releases it for one fresh start, and no-nonce cancel forgets. Terminal materialization fixtures prove a native re-auth failure after acquisition has stranded at least one sibling emits that exact nonempty `interrupted_pairs` in the standard error envelope with no `flow`; the same materialization error with no gap and every non-materialization error omit the member rather than sending `[]`. Successful terminal re-auth keeps the complete array and may send `[]`. Guard fixtures cover every totality cell: unforced empty/nonempty plans, forced nonempty exact/missing/different plan echoes, and a forced request whose old nonempty echo recomputes to an empty plan. They prove every exactly confirmed nonempty plan commits once, every other nonempty forced plan returns the current refusal without removing a hop, every empty plan follows ordinary success, a noninterrupting `route_replace` removal succeeds once without 409, an interrupting replacement refuses with `source_last_supplier`, every produced guard code has its schema-required nonempty evidence array, every produced plan array is duplicate-free, and permuted guard inputs emit canonically ordered SupplyGap rows and agent ids. Source-create fixtures prove process-local pre-work reservation, read-before-retry, in-progress conflict/no work, released atomic reserve/exactly one fresh attempt including after restart, committed conflict plus list lookup of exactly one nonce-bearing Source, AC-26 pending-revocation settlement, and Source-delete release followed by same-nonce fresh creation with a new id and one upstream attempt. AC-54 adds repeated-observation fixtures for failed inventory with omitted/false rejection, true empty-inventory commit, successful rediscovery with stale true, and protocol-unproved rejection regardless of the flag. Observation fixtures reject request/status evidence not present in the six-field contract. Network fixtures cover all four shaped/transport × `stream_started: false/true` cells at the first user-visible model-output boundary, same-Source output reset, other-Source fallback non-reset, clocked future/expired read assembly, bounded auto-clearing live backoff, and zero config writes for unclassified failures. Concurrent-transition fixtures overlay an active deadline with healthy, cooldown, needs-action, error, missing-Source, unsupported-model, and unavailable-native facts: only healthy/capability-present hops project ordinary backoff; durable/capability blockers keep their established projection and `interrupted`; the native exception preserves deadline with reason priority. Probe payload fixtures cover the exact Hub/unreachable/null-latency relation. Credential PUT payloads use only the standard guarded Source envelope; the OAuth repair tail remains flow-only. AgentSupply fixtures prove the valid `{chain_length: 0, has_runnable_hop: false}` pair, reject the corresponding true pair, and prove pure process-available cooldown/backoff chains are waiting rather than interrupted. The same file covers Source deletion from all backend Source orders and routes with survivor order preserved, discovered retirement, guarded default-order update, exact installing shape plus runtime install/no-op, duplicate-native pre-adapter rejection, adoption, and absence of policy/enrollment/takeover/supplying sibling fields. **OAuth terminal fixture revision: 2026-08-12 01:28.** |
-| `tests/test_model_hub_{resolution,runtime,oauth,l3}.py` | After K6 merges, `tests/test_model_hub_resolution.py` transfers to I7 and proves `retired: false` filtering in Effective planning, manual validation, runnability, and invocation plus the complete network-classification/live-backoff table; I2 retains runtime/l3 files and supplies exact managed-Gateway raw shaped/transport facts and `stream_started` phase at the first user-visible model-output byte without owning state decisions, while I3 retains OAuth. Together they cover sole §4.3 effective-chain consumption, one shared effective planner, with no duplicate matching or substitution branch, exact effort membership, every K6-frozen turn-outcome/copy row including G-34, blocked `no_candidate` detail, `native_cli_unavailable`, engine loss before/during/after streaming with no Source mutation or replay, persisted install/restart/no-op behavior, canceled provenance, vendor OAuth defaults, and OAuth nonce released/in-flight/committed totality with pre-provider claim, concurrent coalescing, cleanup release, atomic flow conversion, echo, explicit canceled-flow replay with provider-zero, and expiry-triggered fresh start. Until I7 lands AC-50, only `test_probe_transport_failures_await_ac50_backoff_contract` carries the corrected narrow authorization: it already asserts the future `connection_failed` live-backoff projection and zero Source/config writes under strict xfail, while `test_chain_projection_and_probe_latency_partition` and all unrelated assertions remain active. I7's first mechanical action deletes only that marker in the same commit that makes these forward assertions XPASS; an accidental early implementation is therefore a failing XPASS. I1 moves the versioned contract/provenance fixtures in `test_model_hub_l3.py` to terminal version **9** through #1312; afterward I2 owns that file's runtime updates except for the one deletion. **Turn-outcome dependency revision: 2026-08-12 02:00.** |
-| `ui/src/components/settings/models/**/*.test.*` | No protocol control on the normal add flow, honest manual probe-order fallback, final inventory editing, visible and adjustable backend Source order plus policy-chosen Add Source placement, no position-based newness or bottom-only new section, one guarded saved refresh button, adopted/supply-status projection consumption, derived takeover versus exhausted rendering, reversible Direct mode, distinct Native copy, and no redundant policy/not-enabled/latency or separate experimental-consent surface. Under the 2026-08-11 18:10 PM ruling, the current-increment frame-02 fixture proves that a model row opens the drawn editor, renders the chain read projection, keeps Save disabled, and emits no chain mutation. Exact configured-chain editing and its save/refusal/reconciliation tests are second-increment obligations after K5 round 3 and I7 fixtures merge; a visible noninterrupting hop removal sends one ordinary PUT with no wire confirmation, while a protected-supply interruption echoes both returned refusal arrays, replaces the displayed plan when either differs after recomputation, and never forces a nonempty plan without an exact echo. The Add Source client reads Sources before a lost-response retry and treats a released nonce as fresh. Only state ⑤ sends `accept_unavailable_inventory: true`; clean creation, every retry that has not received that consent, and pull-origin state ⑤′ omit it. After K5 round 2 and I7 fixtures, the same second increment proves live connection backoff uses its distinct short-delay copy rather than quota cooldown copy; K5 round 2 removes the withdrawn observation request/status slots. I4 supplies a mechanical type-check gate that includes these test files despite `tsconfig.app.json` excluding them. |
+| `tests/test_model_hub_api.py` | The current line-1204 `experimental_consent_at` assertion becomes an absence assertion; API fixtures cover unique final model entries, edited-effort and retirement preservation across rediscovery, distinct add-only unsaved operations versus the sole guarded saved refresh, all-exit discovery cleanup, three protocols, observation-before-save, all three pre-observation nonce retry states, deterministic policy-chosen Add Source placement with the returned persisted position, and every guarded-mutation row. OAuth API fixtures prove nonce-bearing explicit cancel retains the same `cancelled` flow and exact-tuple retry performs zero provider starts, existing expiry releases it for one fresh start, and no-nonce cancel forgets. Terminal materialization fixtures prove a native re-auth failure after acquisition has stranded at least one sibling emits that exact nonempty `interrupted_pairs` in the standard error envelope with no `flow`; the same materialization error with no gap and every non-materialization error omit the member rather than sending `[]`. Successful terminal re-auth keeps the complete array and may send `[]`. Guard fixtures cover every totality cell: unforced empty/nonempty plans, forced nonempty exact/missing/different plan echoes, and a forced request whose old nonempty echo recomputes to an empty plan. They prove every exactly confirmed nonempty plan commits once, every other nonempty forced plan returns the current refusal without removing a hop, every empty plan follows ordinary success, a noninterrupting nonempty `route_replace` removal succeeds once without 409, while empty PUT equals DELETE including exact guards, an interrupting replacement refuses with `source_last_supplier`, every produced guard code has its schema-required nonempty evidence array, every produced plan array is duplicate-free, and permuted guard inputs emit canonically ordered SupplyGap rows and agent ids. Source-create fixtures prove process-local pre-work reservation, read-before-retry, in-progress conflict/no work, released atomic reserve/exactly one fresh attempt including after restart, committed conflict plus list lookup of exactly one nonce-bearing Source, AC-26 pending-revocation settlement, and Source-delete release followed by same-nonce fresh creation with a new id and one upstream attempt. AC-54 adds repeated-observation fixtures for failed inventory with omitted/false rejection, true empty-inventory commit, successful rediscovery with stale true, and protocol-unproved rejection regardless of the flag. Observation fixtures reject request/status evidence not present in the six-field contract. Network fixtures cover all four shaped/transport × `stream_started: false/true` cells at the first user-visible model-output boundary, same-Source output reset, other-Source fallback non-reset, clocked future/expired read assembly, bounded auto-clearing live backoff, and zero config writes for unclassified failures. Concurrent-transition fixtures overlay an active deadline with healthy, cooldown, needs-action, error, missing-Source, unsupported-model, and unavailable-native facts: only healthy/capability-present hops project ordinary backoff; durable/capability blockers keep their established projection and `interrupted`; the native exception preserves deadline with reason priority. Probe payload fixtures cover the exact Hub/unreachable/null-latency relation. Credential PUT payloads use only the standard guarded Source envelope; the OAuth repair tail remains flow-only. AgentSupply fixtures prove the valid `{chain_length: 0, has_runnable_hop: false}` pair, reject the corresponding true pair, and prove pure process-available cooldown/backoff chains are waiting rather than interrupted. The same file covers Source deletion from all backend Source orders and routes with survivor order preserved, discovered retirement, guarded default-order update, exact installing shape plus runtime install/no-op, duplicate-native pre-adapter rejection, adoption, and absence of policy/enrollment/takeover/supplying sibling fields. **OAuth terminal fixture revision: 2026-08-12 01:28.** |
+| `tests/test_model_hub_{resolution,runtime,oauth,l3}.py` | After K6 merges, `tests/test_model_hub_resolution.py` transfers to I7 and proves `retired: false` filtering in Effective planning, manual validation, runnability, and invocation plus the complete network-classification/live-backoff table; I2 retains runtime/l3 files and supplies exact managed-Gateway raw shaped/transport facts and `stream_started` phase at the first user-visible model-output byte without owning state decisions, while I3 retains OAuth. Together they cover sole §4.3 effective-chain consumption, one shared effective planner, with no duplicate matching or substitution branch, exact effort membership, every K6-frozen turn-outcome/copy row including G-34, blocked `no_candidate` detail, `native_cli_unavailable`, engine loss before/during/after streaming with no Source mutation or replay, persisted install/restart/no-op behavior, canceled provenance, vendor OAuth defaults, and OAuth nonce released/in-flight/committed totality with pre-provider claim, concurrent coalescing, cleanup release, atomic flow conversion, echo, explicit canceled-flow replay with provider-zero, and expiry-triggered fresh start. Until I7 lands AC-50, only `test_probe_transport_failures_await_ac50_backoff_contract` carries the corrected narrow authorization: it already asserts the future `connection_failed` live-backoff projection and zero Source/config writes under strict xfail, while `test_chain_projection_and_probe_latency_partition` and all unrelated assertions remain active. I7's first mechanical action deletes only that marker in the same commit that makes these forward assertions XPASS; an accidental early implementation is therefore a failing XPASS. I1 moves the versioned contract/provenance fixtures in `test_model_hub_l3.py` to terminal version **10** through #1312; afterward I2 owns that file's runtime updates except for the one deletion. **Turn-outcome dependency revision: 2026-08-12 02:00.** |
+| `ui/src/components/settings/models/**/*.test.*` | No protocol control on the normal add flow, honest manual probe-order fallback, final inventory editing, visible and adjustable backend Source order plus policy-chosen Add Source placement, no position-based newness or bottom-only new section, one guarded saved refresh button, adopted/supply-status projection consumption, derived takeover versus exhausted rendering, reversible Direct mode, distinct Native copy, and no redundant policy/not-enabled/latency or separate experimental-consent surface. Under the 2026-08-11 18:10 PM ruling, the current-increment frame-02 fixture proves that a model row opens the drawn editor, renders the chain read projection, keeps Save disabled, and emits no chain mutation. Exact configured-chain editing and its save/refusal/reconciliation tests are second-increment obligations after K5 round 3 and I7 fixtures merge; a visible noninterrupting hop removal with a nonempty manual result sends one ordinary PUT with no wire confirmation; final-hop removal instead previews inheritance and saves through DELETE/Restore guards, while a protected-supply interruption echoes both returned refusal arrays, replaces the displayed plan when either differs after recomputation, and never forces a nonempty plan without an exact echo. The Add Source client reads Sources before a lost-response retry and treats a released nonce as fresh. Only state ⑤ sends `accept_unavailable_inventory: true`; clean creation, every retry that has not received that consent, and pull-origin state ⑤′ omit it. After K5 round 2 and I7 fixtures, the same second increment proves live connection backoff uses its distinct short-delay copy rather than quota cooldown copy; K5 round 2 removes the withdrawn observation request/status slots. I4 supplies a mechanical type-check gate that includes these test files despite `tsconfig.app.json` excluding them. |
| `tests/scenarios/auth_setup/{catalog.yaml,test_auth_setup_scenarios.py}` | After K4 and #1312 merge, I3 owns AUTH-SETUP-210 and AUTH-SETUP-109. AUTH-SETUP-210 blocks the first OAuth-start provider call, loses that caller's response, overlaps a same-nonce retry that coalesces to the same terminal flow/provider, then asserts provider start exactly once. AUTH-SETUP-109 selects a Hub-held Source and proves missing and false re-auth acknowledgement return `reauth_confirmation_required` before any adapter/provider call, true acknowledgement starts exactly one Hub flow, and terminal status plus repair projection agree. Pending-start failure/task-cancellation release and committed-flow replay cover the other nonce rows; I3 unit/API fixtures separately prove explicit canceled-flow replay starts no provider and expiry permits exactly one fresh start. I5 consumes both completed scenarios but does not edit either file. **Hub re-auth scenario binding revised 2026-08-12 01:30 by PM ruling.** |
| `tests/scenarios/model_hub/**`, `tests/scenario_harness/model_hub_native_oauth.py` | End-to-end final-shape setup, all four native-import action rows, reversible Direct/Gateway onboarding, subscription custody, protocol observation, one-time add matching plus deterministic persisted placement, exact configured route execution and mapping, guarded saved refresh and Source-delete envelopes, silent successful takeover, truthful blocked/native/engine terminal copy, and exhaustion failure without takeover semantics. The I3-owned migration scenario validates each imported Source, serializes the full result, and reloads it through the same canonical validator. |
@@ -1712,9 +1721,11 @@ but the final five projections are `selected_model_id`, `sources`, `routes`,
`standard_vendors` remain mode-independent. *[Retired 2026-09-04: the `standard_vendors` projection is removed by catalogs spec v3 C9; see the v4 override at the top of this document.]*
**Acceptance.** I1 builds every fixture from an otherwise-valid payload. A Hub payload
-with any of the five final projections explicitly null is rejected by the Hub branch;
-the same payload with one explicit route row per menu model, including empty `hops`,
-validates. `sources` contains an explicit `order` and no policy. `selected_by_agent: null`
+with a required non-null Hub projection explicitly null is rejected by the Hub branch;
+the same payload with a sparse route map containing only nonempty overrides validates.
+Absent and valid empty input normalize to inherited output; an empty override object in
+canonical output is rejected. Nullable selection/status retain their current semantics.
+`sources` contains an explicit `order` and no policy. `selected_by_agent: null`
and `current: null` still validate. Direct mode has
its documented representation. The mechanical checker records the branch as a declared
non-required exception for historical examples while rejecting `mappings` or a policy
@@ -1735,10 +1746,14 @@ Review round 12, P2, on `docs/plans/model-hub-contracts/README.md`, [thread](htt
### AC-22 — Preserve sparse intent through one effective route planner
**Current authority: routing modes, 2026-09-06.** A backend owns default membership/order
-and sparse manual overrides. Key absence inherits; key presence preserves exact submitted
-hops, including empty and equal-to-automatic arrays. No second persisted policy flag or
+and sparse manual overrides. Absent and valid empty values inherit; nonempty values
+preserve exact submitted hops, including equal-to-automatic arrays. No empty-disable
+state, second persisted policy flag or
separate mapping object exists. Existing supported persisted arrays, including stale and
-dormant records, load without historical-authorship inference; new catalog rows have no key.
+dormant records, load without historical-authorship inference; valid empties normalize
+only after original-shape validation, without dropping catalog identities. Canonical
+responses omit empty manual values, while empty PUT/preview remain accepted restore
+inputs. New catalog rows have no key; reads/preview are pure and saves normalize.
**Acceptance.** One pure planner selects manual, matching defaults, or unchanged-id
passthrough. Every read/preview/summary/guard/adoption/probe/launch/execution consumer agrees
@@ -2297,10 +2312,11 @@ The fixture covers every row of the force/plan/echo totality matrix: unforced em
success; unforced nonempty refusal; forced nonempty exact two-array echo success; forced
nonempty absent or differing echo returning the newly recomputed plan; and a world change
where the forced retry carries the old nonempty echo but recomputes to an empty plan and
-takes ordinary success without a 409 or removed hop. A direct `route_replace` fixture
+takes ordinary success without a 409 or removed hop. A nonempty manual `route_replace` fixture
removes one hop while retaining runnable protected supply and succeeds once without 409;
its paired interruption fixture refuses with the existing `source_last_supplier` code
-and enters the same echo matrix. No token, digest, version receipt,
+and enters the same echo matrix. Empty PUT instead matches DELETE Restore, guarding
+actual inherited effective removals as well as interruption. No token, digest, version receipt,
server-side confirmation state, or parallel plan-changed discriminator exists. The
closed error vocabulary, error-to-plan relation, and guard-decision vocabulary are
checked through `mirror-registry.json`.
@@ -2376,7 +2392,7 @@ canceled flow with zero provider starts. Clocked expiry releases the tuple, and
same-tuple retry afterward starts exactly one fresh flow. Explicit cancellation without
a nonce forgets the flow. A different tuple cannot resolve to the retained flow, and a
new user action always generates a new nonce. This zero-new-concept closure keeps
-`contract_version: 9` under the PM ruling of 2026-08-12 00:37.
+`contract_version: 10` under the PM ruling of 2026-08-12 00:37.
The contract fixture accepts a nonce-bearing flow with a date-time expiry, rejects that
same flow with `expires_at: null`, and accepts the null expiry after `client_nonce` is
@@ -2542,7 +2558,7 @@ acknowledgement permits exactly one ordinary re-auth start. The rule does not ex
transactional API-key replacement through `PUT /credential`. A negative Hub fixture and
the corresponding native fixture prove zero adapter calls; positive fixtures prove both
channels cross the same server boundary. This additive pre-release correction keeps
-`contract_version: 9` under the PM ruling of 2026-08-12 00:15.
+`contract_version: 10` under the PM ruling of 2026-08-12 00:15.
**Binding handoff (owner / files / activation).** After K4, #1312, and K6 merge, I7 owns
`core/handlers/model_hub/{service,rpc,request,errors}.py`,
diff --git a/docs/plans/model-hub-routing-modes.md b/docs/plans/model-hub-routing-modes.md
index 8e662421a..c23e24158 100644
--- a/docs/plans/model-hub-routing-modes.md
+++ b/docs/plans/model-hub-routing-modes.md
@@ -13,7 +13,8 @@ retain contradictory current-policy claims when this implementation ships.
For backend defaults `[A, B]`, model M automatically uses B if B lists M and A does
not. A is not prepended as a speculative candidate. If neither lists M, the chain
is `[A/M, B/M]`, with M forwarded unchanged. A saved manual chain replaces this
-generated chain completely, including an explicitly empty manual chain.
+generated chain completely only when it contains at least one hop. An empty
+route value is equivalent to absence and inherits the generated route.
The upstream inventory is evidence for matching, not an invocation whitelist.
Credentials, protocol and channel compatibility, backend model admission, source
@@ -52,17 +53,20 @@ type RouteOrigin = "automatic" | "manual" | "passthrough" | null;
type ManualRouteOverrides = Record<string, ManualRouteOverride>;
```
-Key absence means automatic. Key presence means explicit override, including an
-empty array. Saving a model route always creates an override even when identical
-to the generated result. Restoring automatic deletes the key. There is no second
-persisted policy flag and no inference from array equality.
-
-Preserve existing override entries and exact arrays losslessly, including empty,
-stale, and dormant OpenCode entries. Historical discriminator-free records cannot
-reveal whether an old empty array was generated or deliberately cleared. Retained
-entries are frozen routes, not a claim of known historical human authorship. The
-UI can restore them explicitly. Do not globally reinterpret old empty arrays as
-automatic or clear existing config during regression deployment.
+Key absence or an empty hop array means inherited routing. Only a nonempty
+value is an explicit override. Saving a nonempty model route creates an override
+even when identical to the generated result. Restoring automatic deletes the key;
+empty input is normalized to that same operation. There is no second persisted
+policy flag, empty-route disable state, or inference from nonempty array equality.
+
+Preserve existing nonempty overrides and exact arrays losslessly, including stale
+and dormant OpenCode entries. Historical discriminator-free records cannot reveal
+whether an old empty array was generated or deliberately cleared. The owner now
+explicitly selects inherited behavior for both, superseding the former empty-key
+preservation policy. This is a documented compatibility normalization, not a claim
+of historical human authorship. Validate the original supported payload before
+normalizing empty values; invalid records must not become automatic by accident.
+Do not discard catalog identities or unrelated configuration while normalizing.
New catalog rows and missing fixed-menu rows receive no route key. Stop default
seeding and source-add appends to persisted routes. Older supported config shapes
@@ -77,7 +81,8 @@ It produces `{manual_override, route_origin, hops}` from current configuration,
backend, and canonical requested model. Preview may call it with an isolated
draft configuration; no public sentinel or duplicate matching algorithm is needed.
-1. A manual key returns the exact saved hops and order.
+1. A nonempty manual value returns the exact saved hops and order. Empty values
+ are treated exactly as key absence, including for directly constructed config.
2. Otherwise scan configuration-eligible sources in backend default order for
matching evidence. Include all accepted matching pairs in that order.
3. If there are no matching pairs, use each eligible API-key default source with
@@ -112,8 +117,8 @@ unknown passthrough models do not acquire invented capabilities or reasoning tie
## API Shapes and Responsibilities
-Advance the terminal in-request contract to `contract_version` 9 on the complete
-feature head. Retain readable historical TurnProvenance versions through 9.
+Advance the terminal in-request contract to `contract_version` 10 on the complete
+fix head. Retain readable historical TurnProvenance versions 5 through 10.
The server adds the following required fields to `AgentChain`:
@@ -122,11 +127,13 @@ manual_override: ManualRouteOverride | null;
route_origin: RouteOrigin;
```
-`manual_override` reports actual persisted key presence. `chain` is the effective
+`manual_override` reports the normalized nonempty manual override, or null.
+`chain` is the effective
ordered plan with existing live annotations, not the persisted map. Existing
`current`, `supply_state`, health, reason, and retry fields retain their meaning.
-For a saved empty override, `manual_override` is `{hops:[]}`, `chain` is empty and
-`route_origin` is null. Preview reports the draft override rather than saved intent.
+For a legacy or submitted empty override, `manual_override` is null and `chain`
+and `route_origin` come from the inherited plan. Only an actually empty inherited
+plan has null origin. Preview reports normalized draft intent without persistence.
`AgentSupply.routes` contains only manual overrides. Add required `route_origin`
to each `model_supply` summary and derive `chain_length` from the effective plan.
@@ -142,9 +149,9 @@ passthrough target.
| PUT `.../agents/<backend>/sources` | `{order, force?, would_remove_hops?, would_interrupt?}`; atomically replace default membership/order and preserve all manual overrides. Guard effective supply/hop removal using the existing exact-plan confirmation protocol. Pure reordering without removal needs no guard. |
| GET `.../agents/<backend>/chain?model=<id>` | Existing chain success envelope, extended AgentChain. |
| GET `.../agents/<backend>/chains` | Existing chain-list success envelope, same owner and fields for every routeable model. |
-| PUT `.../agents/<backend>/chain?model=<id>` | `{hops, force?, would_remove_hops?, would_interrupt?}`; persist explicit override, including equal and empty arrays. Return existing chain-mutation success envelope. |
+| PUT `.../agents/<backend>/chain?model=<id>` | `{hops, force?, would_remove_hops?, would_interrupt?}`; persist a nonempty explicit override, including an equal array. Empty hops use the exact restore operation and guards. Return existing chain-mutation success envelope. |
| DELETE `.../agents/<backend>/chain?model=<id>` | Optional `{force?, would_remove_hops?, would_interrupt?}`; remove override, recompute defaults, return the same mutation envelope. Idempotent if absent. Guard actual effective removal/supply loss. |
-| POST `.../agents/<backend>/chain/preview?model=<id>` | `{manual_override:null \| {hops:RouteHop[]}}`; return chain success envelope for draft replacement/removal. No persistence, events, engine startup/sync, credentials, or upstream egress. |
+| POST `.../agents/<backend>/chain/preview?model=<id>` | `{manual_override:null \| {hops:RouteHop[]}}`; normalize empty hops to null, then return chain success envelope for draft replacement/removal. No persistence, events, engine startup/sync, credentials, or upstream egress. |
| POST `.../agents/<backend>/chains/reorder` | Existing optional order plus optional guard fields; default-order compatibility entry point with the same effective guards. Never reorder manual arrays. With no order, return the current projection. New UI uses Sources PUT. |
| PUT `.../agents/<backend>/models` | Preserve existing baseline/concurrency/expected-suppliers/guard contract. New rows automatic, retained rows preserve intent, removal cleans intent through existing guarded mutation. |
@@ -190,7 +197,8 @@ Approved design: `avibe-docs/design.pen`, frames `bmi25` (dark), `ziils` (light)
and disable duplicate submissions. Default configuration changes must not leak
between backend groups.
- No eligible defaults show Unconfigured and a Configure default routing action.
- An explicit empty override stays empty and offers Restore automatic in the dialog.
+ Removing the last manual hop enters the same Restore automatic draft preview;
+ Undo restores the previous unsaved draft and Cancel performs no write.
- Request errors are separate from route origin. Model-not-found keeps Passthrough
and shows the recorded-turn detail surface below; do not mark the whole source failed.
- Apply complete EN/ZH localization and keyboard/touch behavior. Documentation
@@ -207,7 +215,7 @@ introduce a second history store or turn request failures into Source health eve
Add GET `/api/models/agents/<backend>/provenance?model=<id>` through the existing
service, RPC, client, and UI-server path. Validate the backend and its canonical
catalog model identifier. Reuse the existing envelope:
-`{ok:true,contract_version:9,provenance:TurnProvenance|null}`
+`{ok:true,contract_version:10,provenance:TurnProvenance|null}`
for the most recently persisted retained record matching both backend and requested
model, regardless of outcome; no record means null, not a fabricated success.
This is a read-only, on-demand dialog read and never starts or syncs the engine.
@@ -449,13 +457,57 @@ the source identity outside the row at narrow widths. The held-out plus action
uses the same visual treatment. Scope excludes unrelated drawer typography,
section composition, source order, inventory, and route persistence changes.
-The user's local Codex inspection found saved empty overrides taking precedence
-over otherwise eligible default sources. A read-only restore preview correctly
-returns automatic matching or passthrough. This is an upgrade-experience gap,
-not permission to reinterpret or delete persisted empty overrides. Preserve the
-existing compatibility contract and actual local state during this visual fix;
-the interface distinction and any explicit restoration require their own scope
-decision. Do not make acceptance green by changing the user's route intent.
+The drawer-only correction did not change saved routing intent. The subsequent
+owner-approved Empty Route Inheritance correction below supersedes the former
+empty-override compatibility policy; nonempty manual routes remain unchanged.
+
+## Empty Route Inheritance
+
+The user explicitly requested this correction after inspecting Codex in the local
+regression environment. At the observed configuration, normalizing the fifteen
+empty overrides produces eight Automatic routes, seven Passthrough routes and
+leaves the one nonempty gpt-5.3-codex-spark route Manual. These counts are evidence
+for that snapshot, not hardcoded behavior or immutable acceptance requirements.
+
+The invariant is that absent and empty overrides are equivalent across loading,
+serialization, preview, projection, registration, guards and invocation. Only
+nonempty routes carry manual intent. Canonical route maps omit empty values and
+canonical responses never emit `{hops:[]}` as `manual_override`. Existing empty
+configuration input and PUT/preview input remain accepted after strict shape and
+identifier validation, then normalize to absence; do not introduce an incompatible
+rejection or a separate migration flag. Read/preview does not write config or
+start the engine. Normal persistence writes the normalized sparse route map.
+
+Every mutation that can remove the final hop, including source deletion and
+catalog reconciliation, must use this same normalized planner before computing
+effective removals, interruptions and transport registration. Empty PUT has the
+same exact-plan guard/refusal, idempotency, admission, lease and rollback behavior
+as DELETE; do not bypass confirmation by retaining an empty route object. Existing
+invalid identifiers, explicit retirement, native/backend restrictions and the
+API-key-only unknown-target boundary are unchanged.
+
+In the dialog, removing the final manual hop explicitly previews inherited routing
+using the existing Restore/Undo flow. Do not present a saveable empty Manual state
+or merely relabel an empty chain. Save uses DELETE and the existing exact guard
+confirmation; read-only preview, retry invalidation, Undo/Cancel, success/Done and
+ambiguous-write reconciliation preserve their existing semantics. The saved
+nonempty override remains untouched until a confirmed successful save.
+
+Advance ephemeral API/schema/UI fixtures together to v10. The JSON wire field
+names and RouteOrigin vocabulary do not change; normalized manual output arrays
+have at least one item, while restoration inputs still accept an empty array.
+Historical provenance versions 5-9 and their records remain readable and unchanged;
+new v10 records use existing safe fields. F1 remains byte-identical to production.
+
+Acceptance must assert equivalence by exercising the same config with absent and
+empty values for all backends and protocol surfaces. Preserve every nonempty
+override and other source/default/catalog/credential field through load/save and
+refresh. Cover source deletion, guarded empty PUT versus DELETE, preview purity,
+default changes, live health independence, failed synchronization rollback and
+real gateway-to-pinned-CPA exact target registration. Update existing empty-state
+tests rather than disabling them. Cleanup compares canonical intent and must not
+restore an obsolete empty-disable state. Existing failed live artifacts stay
+immutable; the required browser flows and safety gates are not waived.
## Delivery Ownership
diff --git a/docs/plans/model-hub-ui-spec.md b/docs/plans/model-hub-ui-spec.md
index 2fa93e513..19206600c 100644
--- a/docs/plans/model-hub-ui-spec.md
+++ b/docs/plans/model-hub-ui-spec.md
@@ -12,6 +12,11 @@ drawn; this file is where those decisions land instead of evaporating.
## Routing modes revision - 2026-09-06
+Empty Route Inheritance (`352486374`, contract_version 10) supersedes empty-disable
+semantics across all backends. Absent and valid empty route values inherit; canonical
+manual_override is a nonempty object or null and canonical route maps omit empty values.
+This is server normalization, never client inventory matching or a health-derived origin.
+
Owner scope decision `c1d398d5f` restricts unknown-model passthrough and inventory-
independent manual invocation to Hub API-key Sources. Subscriptions keep existing
known-model matching/admission and stale-hop retention. Unmatched subscription-only
@@ -39,17 +44,20 @@ Passthrough and uses the retained-turn detail surface below without marking the
Inherited dialogs open with Edit route. Manual editing retains add/edit/remove/reorder
and accepts exact API-key upstream ids absent from inventory; subscription targets retain
-known-model admission. Restore automatic in the footer
+known-model admission. Restore automatic in the footer, or removing the final manual hop,
changes the draft to null and calls preview; its result may be Passthrough or Unconfigured.
Undo restore reinstates the prior manual draft. Cancel/close never writes. Save sends
-DELETE for restored automatic or PUT for manual hops, consuming the complete canonical
+DELETE for inherited intent or PUT for nonempty manual hops, consuming the complete canonical
mutation result and exact-plan guards. Failed saves retain draft intent; stale preview
responses cannot replace newer edits; duplicate submissions are disabled.
-Lost-response reconciliation compares actual `manual_override` as well as effective
+Lost-response reconciliation compares normalized `manual_override` as well as effective
pairs: equal arrays can represent different saved intent. Preview is read-only with runtime
-stopped and never starts the engine. An explicit empty override stays empty and offers
-Restore automatic; inherited emptiness offers Configure default routing. Backend changes
+stopped and never starts the engine. A valid empty value follows the actual inherited plan;
+only inherited emptiness offers Configure default routing. Removing the final manual hop
+previews that plan through existing Restore/Undo/Save/guard/Done, never a saveable empty
+Manual state. Undo restores the previous unsaved draft; the saved nonempty override stays
+untouched until confirmed successful Save. Backend changes
cannot leak drafts. Origin, runtime health, request errors and draft state remain separate.
### Latest recorded turn detail
@@ -58,7 +66,7 @@ The Recorded Error Detail Closure (`0de3d2f47`, corrected by `9cb9ebb53`) suppli
data through on-demand GET `/api/models/agents/<backend>/provenance?model=<id>`.
This read is independent of route draft/preview and returns the latest retained exactly
attributed settled turn for both identifiers, regardless of outcome, or null in the
-existing `{ok: true, contract_version: 9, provenance}` envelope. It reads
+existing `{ok: true, contract_version: 10, provenance}` envelope. It reads
the existing 500-record store only; neither AgentChain nor the pure planner owns history.
Show an error panel only when that latest record has `terminal_error`. A newer served,
@@ -681,7 +689,7 @@ register rather than borrowing a similar-looking tail from another route:
| R3 | §1.11 reauth acquisition and OAuth terminal | `api.md` OAuth completion, terminal `intent: reauth` | acquisition `flow`; terminal `flow`, `source`, `recovered`, `interrupted_pairs` | RR-1/RR-2 consume the acquisition `flow`; only a non-terminal flow owns presentation/polling, while a terminal flow is status-read first. §1.4 consumes the terminal `flow`. Hold `source` and classify its complete `state` before reading array cardinality: `needs_action` / `error` → Repair unresolved, rendering any non-empty `interrupted_pairs` there; non-blocked + non-empty pairs → Repair impact reported; non-blocked + empty pairs → M3 handoff. `interrupted_pairs` is evidence to render, never the repair verdict. `recovered` remains past-state evidence and selects no copy. M3 owns the affected projections. |
| R4 | §1.11 credential replacement | `model-hub.md` Source-mutation matrix, `mutation.credential_replace` | `source`, `removed_hops`, `interrupted` | Hold `source`. Render non-empty `removed_hops` and `interrupted` blocks in Repair impact reported; each empty member skips only its block. This producer has no `recovered` or `interrupted_pairs` member: those names belong only to R3's OAuth terminal. M4 owns the affected projections. |
| R5 | §1.4 / §1.11 E6 materialization error | `api.md` OAuth terminal-response matrix, `oauth_terminal.materialization_*` | standard `ok`, `contract_version`, `error`, optional `detail`; conditional `interrupted_pairs`; `flow` absent | `ok: false` and `error` select E6; `contract_version` is validated and not rendered. Optional `detail` selects no copy and is not surfaced because only registered localized keys may render. If `interrupted_pairs` is present it is exact, nonempty historical impact: render every SupplyGap row in OAuth materialization failed and hold the report through RR-5. If absent, render no report; absence is not an empty success tail and proves nothing about Source outcome. RR-5 still reconciles the full attempt scope. |
-| R6 | §1.2 exact Route replacement | `model-hub.md` Source-mutation matrix, `mutation.route_replace` | `chain`, `removed_hops`, `interrupted` | Hold `chain` as the authoritative post-commit AgentChain and write evidence. Render each non-empty `removed_hops` and `interrupted` block in Route impact reported; an empty member skips only its own block. If both arrays are empty, skip the report but retain both exact empty values. M6 owns every Route-derived projection before handoff. |
+| R6 | §1.2 Route save or Restore | `model-hub.md` Source-mutation matrix, `mutation.route_replace` / `mutation.route_restore` | `chain`, `removed_hops`, `interrupted` | Hold `chain` as the authoritative post-commit AgentChain and write evidence. Render each non-empty `removed_hops` and `interrupted` block in Route impact reported; an empty member skips only its own block. If both arrays are empty, skip the report but retain both exact empty values. M6 owns every Route-derived projection before handoff. |
**Mutation / authoritative absence → projection invalidation register** `[contract]` `[derived]`. A complete
response or an authoritative D-36 subject read can prove the write; an exact absent read or
@@ -869,16 +877,16 @@ state exit; held intent never bypasses the evidence column.
| §1.1 | Leaving the gateway | 切到直连 pressed on a gateway group `[frame]` D-30 — `PATCH /api/models/agents/<backend>/mode` | F1, in place on the group head | `gateway.switchToDirect`, `gateway.fail.switchToDirect`, `gateway.retry` | Success → the group re-renders in its 直连 form; when it was the last gateway backend the page is decided by the sources that are still there, not by the switch — no source left → 09, at least one source retained → **01**, which is §1.8's own *Retained sources* branch and not this frame; a failure keeps the group on the gateway and puts the line and 重试 on the group head, which is the slot the re-rendered form would have used |
| §1.2 | Loading route | A model row opens 02 with the exact `(backend, menu_model)` held; `GET /api/models/agents/<backend>/chain?model=<id>` owns the dialog body | F1 → Route unread | `route.title`, `route.loading`, `route.cancel` | ET-1–ET-4, ET-8a and ET-18a own opening, response dispatch, focus, retry and the non-mutating exit; an unlisted answer cannot leave this state |
| §1.2 | Route unread `[derived]` | The dialog-owned opening chain read failed while the containing page remains mounted | F1, in place | `route.fail.read`, `route.retry`, `route.cancel` | ET-3/ET-4/ET-8a own entry, Retry and the non-mutating exit; the independent dialog read never rewrites the held page row |
-| §1.2 | Ready | The exact AgentChain is held and the local pair projection is byte-identical to its opening `chain` | F5 | `route.title`, `route.section`, `route.addHop`, `route.reorder`, `route.hint`, `route.cancel`, `route.save`; `route.removeHop` / `route.grip` when `hops` is nonempty; `route.empty` only when it is empty; `route.add.none` when no candidate remains; `route.add.source`, `route.add.model`, `route.add.search`, `route.add.confirm` while the Add selector is open, and `route.add.noMatch` only while a typed filter excludes every candidate; `route.sourceMissing` only on a hop whose authoritative chain annotation reads `reason: source_missing`; `route.reorder.grabbed`, `route.reorder.position`, `route.reorder.dropped`, `route.reorder.cancelled`, `route.reorder.sorted`, `route.reorder.unchanged` only for their registered live-region event | ET-5a–ET-7f, ET-8a and ET-9a own every selector, local edit, grab, exit and submission edge |
-| §1.2 | Dirty | The ordered pair draft differs from the current reversible origin and remains V5-valid | F5 — every edit is local | Same normal-frame keys as Ready | ET-5a–ET-7f, ET-8a and ET-9a own every selector, local edit, grab, exit and submission edge |
+| §1.2 | Ready | The exact AgentChain is held and normalized draft intent equals its opening manual_override; inherited display uses the server effective chain | F5 | `route.title`, `route.section`, `route.addHop`, `route.reorder`, `route.hint`, `route.cancel`, `route.save`; `route.removeHop` / `route.grip` when `hops` is nonempty; `route.empty` only when it is empty; `route.add.none` when no candidate remains; `route.add.source`, `route.add.model`, `route.add.search`, `route.add.confirm` while the Add selector is open, and `route.add.noMatch` only while a typed filter excludes every candidate; `route.sourceMissing` only on a hop whose authoritative chain annotation reads `reason: source_missing`; `route.reorder.grabbed`, `route.reorder.position`, `route.reorder.dropped`, `route.reorder.cancelled`, `route.reorder.sorted`, `route.reorder.unchanged` only for their registered live-region event | ET-5a–ET-7f, ET-8a and ET-9a own every selector, local edit, grab, exit and submission edge |
+| §1.2 | Dirty | The nonempty manual draft or inherited null differs from the reversible normalized intent; a final-hop removal is a Restore preview, not empty Manual | F5 — every edit is local | Same normal-frame keys as Ready | ET-5a–ET-7f, ET-8a and ET-9a own every selector, local edit, grab, exit and submission edge |
| §1.2 | Invalid after refresh `[derived]` | ET-17e holds refreshed Hub AgentSupply/Source/chain authorities and at least one new or changed draft pair is now V5-invalid; unchanged persisted stale pairs do not enter this state | F5 — the refresh completed and no mutation is sent | Same normal-frame keys as Dirty plus `route.invalidAfterRefresh` on every offending row | ET-5a–ET-8a and ET-17e own repair, exit and focus. Every offending row stays removable; Save remains disabled with the rendered invalid lines as its description |
-| §1.2 | Saving | 保存 or guard confirmation activated — `PUT /api/models/agents/<backend>/chain?model=<id>` sends the complete submitted `hops`; the first request is non-forced and a confirmed retry carries `force: true` plus both exact refusal arrays `[contract]` | DP-2: the request owns the dialog and every dismissal path until classification | `route.saving` | ET-9a/ET-13b, ET-10, ET-12, ET-14, ET-15 and ET-18a own the complete response dispatch and destination focus for every answer/no-answer branch |
+| §1.2 | Saving | 保存 or guard confirmation activated — nonempty manual intent sends PUT and inherited intent sends DELETE on `/api/models/agents/<backend>/chain?model=<id>`; the first request is non-forced and a confirmed retry carries `force: true` plus both exact refusal arrays `[contract]` | DP-2: the request owns the dialog and every dismissal path until classification | `route.saving` | ET-9a/ET-13b, ET-10, ET-12, ET-14, ET-15 and ET-18a own the complete response dispatch and destination focus for every answer/no-answer branch |
| §1.2 | Route committed, reconciling `[derived]` | R6 success carries two empty impact arrays, or AR-D6 proves the desired Route from the exact chain endpoint while response-only arrays are unavailable; exact commit evidence is held while the active AR-M generation has an acquired member pending, a ready member awaiting acquisition, or an acquired member whose observation has not satisfied every required causal frontier. Mode-dependent deferred members are not pending obligations | F2 applies only to acquired members that AR-M3 marks stale; an Agents-first failure makes Agents the exact stale/Retry subset while Source/Route remain deferred. The Route write/desired state is already proven | `route.refreshing`, `route.impact.done` | ET-11 or ET-17c owns mutually exclusive entry; AR-M/AR-MD, ET-18aM/ET-18aP, ET-19, AS and ET-20 own member eligibility/epochs/frontiers, Direct handoff, Retry, page installation and the sole user exit |
| §1.2 | Route committed, refreshed `[derived]` | AR-M2 completed a mounted report-free M6 generation with every activated applicable member satisfying all causal frontiers and no member deferred behind an unresolved prerequisite; it installed the exact page behind the still-mounted modal and holds commit evidence until acknowledgement | F5 — no request remains and no impact report exists | `route.impact.title`, `route.impact.done` | ET-20 is the only exit. The page projection is already installed, and modal close invokes PF-1 because Done unmounts |
-| §1.2 | Route save refused `[derived]` `[contract]` | A non-forced or forced save returned `source_last_supplier` with the current nonempty `would_interrupt` plan and complete `would_remove_hops` projection | F3 — shared `Qp6FI`; G-23 remains the drawing gap for the detailed SupplyGap block | `guard.title.saveRoute`, `guard.subtitle.saveRoute`, `guard.confirm.saveRoute`, `guard.label`, `guard.count`, `guard.hop.position`, `guard.hint.interrupt`, `guard.gap.label`, `guard.gap.subject`, `guard.gap.agents`, `gateway.modelCount`, `guard.cancel` | ET-12, ET-13a and ET-13b separately own plan replacement, cancellation and confirmation |
-| §1.2 | Route save rejected `[derived]` | The server definitively rejected the route write outside the guarded-plan and `direct_mode` branches, so this attempt is `terminal-rejected` and did not commit | F1, in place; no D-36 read is started | `route.fail.save`, `route.retry`, `route.cancel` | ET-14 owns terminal entry. CA-R1 admits one explicit Retry only after ordinary V5 validation; ET-14a creates a **new** workflow generation and ordinary PUT, never a recovery/replay of the rejected attempt. ET-8a owns the non-mutating exit |
+| §1.2 | Route save refused `[derived]` `[contract]` | A non-forced or forced save returned the current exact refusal plan: nonempty manual PUT guards interruption; Restore/last-hop removal additionally guards effective hop removal | F3 — shared `Qp6FI`; G-23 remains the drawing gap for the detailed SupplyGap block | `guard.title.saveRoute`, `guard.subtitle.saveRoute`, `guard.confirm.saveRoute`, `guard.label`, `guard.count`, `guard.hop.position`, `guard.hint.interrupt`, `guard.gap.label`, `guard.gap.subject`, `guard.gap.agents`, `gateway.modelCount`, `guard.cancel` | ET-12, ET-13a and ET-13b separately own plan replacement, cancellation and confirmation |
+| §1.2 | Route save rejected `[derived]` | The server definitively rejected the route write outside the guarded-plan and `direct_mode` branches, so this attempt is `terminal-rejected` and did not commit | F1, in place; no D-36 read is started | `route.fail.save`, `route.retry`, `route.cancel` | ET-14 owns terminal entry. CA-R1 admits one explicit Retry only after ordinary V5 validation; ET-14a creates a **new** workflow generation and ordinary PUT or DELETE according to normalized intent, never a recovery/replay of the rejected attempt. ET-8a owns the non-mutating exit |
| §1.2 | Route save outcome unresolved `[derived]` | The route write initially produced no exact Route authority: either no HTTP/API answer or DM-2's shaped `direct_mode` response. The exact submitted draft and whether this was the non-forced or confirmed stage remain held while attempt settlement is `unknown`; an exact nonmatching chain is installed as the newest Route observation but does not settle that attempt. Direct changes only observation legality | F1; D-36 is read-only for this entire workflow | Mounted: `route.fail.unconfirmed` before/after nonmatch, `route.fail.reconcileRead` after a read or Source failure, `route.retry` only for the admitted read subset, and `route.cancel`. Page-owned Hub failure reuses the row's Chain-unresolved/D-35 read treatment; page-owned Direct makes no false Route claim | ET-15/DM-2, RO/AR-D/ET-16, LF/AS, ET-17 and ET-18a own entry, legality changes and D-36 reads. Every successful read installs before transition. Mounted dismissal explicitly abandons the old attempt through ET-8b and retains installed authority; it never transfers a recovery PUT right. CA-D admits exactly one read Retry; page-owned Retry is D-35 only. Reload is the sole implicit evidence drop and never resends |
-| §1.2 | Route impact reported `[derived]` `[contract]` | R6 holds a successful route-replace response with non-empty `removed_hops` and/or `interrupted`; the complete returned `chain` remains held while AR-M independently settles every activated member after all of that member's required causal frontiers | F2 only for the exact AR-M3 acquired failed subset; deferred companions are neither stale nor Retryable. The write already succeeded and DP-4 owns every exit | Report block keys always; `route.refreshing` while an acquired member is pending or a successful prerequisite is activating companions; `route.impact.refreshFail` and `route.retry` only in the settled-failure subphase; neither retry key after AR-M2 success | ET-10, AR-M/AR-MD, ET-18aM, ET-19, AS and ET-20 own report entry, acquisition eligibility/member settlement/Direct handoff/Retry/install and the sole user exit; successful authority is installed immediately and never dismisses the report |
+| §1.2 | Route impact reported `[derived]` `[contract]` | R6 holds a successful route-replace or route-restore response with non-empty `removed_hops` and/or `interrupted`; the complete returned `chain` remains held while AR-M independently settles every activated member after all of that member's required causal frontiers | F2 only for the exact AR-M3 acquired failed subset; deferred companions are neither stale nor Retryable. The write already succeeded and DP-4 owns every exit | Report block keys always; `route.refreshing` while an acquired member is pending or a successful prerequisite is activating companions; `route.impact.refreshFail` and `route.retry` only in the settled-failure subphase; neither retry key after AR-M2 success | ET-10, AR-M/AR-MD, ET-18aM, ET-19, AS and ET-20 own report entry, acquisition eligibility/member settlement/Direct handoff/Retry/install and the sole user exit; successful authority is installed immediately and never dismisses the report |
| §1.3 | Ready | Drawer opened and the eligible sources resolved | F1, in the region the list would have filled → Sources unread | `order.title`, `order.subtitle`, `order.section.ordered`, `order.section.ordered.note`, `order.section.heldOut` | 取消 / 关闭 / Escape → close, discarding uncommitted moves; 保存顺序 → Saving |
| §1.3 | Sources unread | The eligible-source read came back failed while the page behind the drawer is still rendering a healthy runtime `[derived]` | F1, in place | `order.fail.read`, `order.retry` | 重试 → the read runs again, and what it answers with decides: at least one eligible source → Ready, none → Zero eligible sources, another failure → back here; 取消 / 关闭 / Escape → close, having changed nothing |
| §1.3 | Zero eligible sources | No source is eligible for this backend | F5 | `order.empty.noEligible` | 关闭. A source becomes eligible → Ready. 保存顺序 is disabled |
@@ -2023,8 +2031,10 @@ pairs; Restore automatic stages null. Live `channel`, `health`, `runnable`, `rea
`retry_at`, `current` and `supply_state` remain read annotations and are never echoed
into a write. The reversible origin includes saved intent as well as pairs, so equal
arrays cannot settle a lost response with different manual intent. Local edits operate
-on a copy; Cancel never writes. Empty `hops` is an explicit empty manual override,
-not absence of a Route. Preview reports the draft and cannot replace saved authority.
+on a copy; Cancel never writes. Removing the last hop stages inherited null and previews
+the same plan as Restore automatic. Empty input is accepted at the API boundary but
+never persists as a manual override. Preview reports normalized draft intent and cannot
+replace saved authority. Undo restores the prior unsaved nonempty draft.
V5 is the sole Add-hop and draft validator. 添加一跳 opens the product's standard anchored
selection surface without assigning new frame geometry: candidates come from the current
@@ -2074,15 +2084,15 @@ control only sorts the one route draft held by frame 02.
| Step | Evidence held | Request / disposition |
| --- | --- | --- |
-| RS-1 — local edit | opening AgentChain intent + V5-valid ordered draft or restored null | No mutation. Preview may project the draft read-only. Save compares intent as well as pairs: equal-to-automatic manual saves and explicit empty overrides are valid changes. Undo restore reinstates the previous draft; Cancel never writes |
+| RS-1 — local edit | opening AgentChain intent + V5-valid nonempty ordered draft or inherited null | No mutation. Last-hop removal enters Restore preview, preserving the prior unsaved draft for Undo. Save compares normalized intent as well as pairs: nonempty equal-to-automatic saves remain manual. Empty Manual is not a saveable state; inherited Save uses DELETE. Cancel never writes |
| RS-2 — first save | one immutable submitted manual override or restored null | Send the complete manual array with PUT, or DELETE for restored null, without `force` or plan echoes; transfer focus/ownership to Saving |
| RS-3 — ordinary success | R6 `{chain, removed_hops, interrupted}` | Hold all three members; cardinality is evidence consumed by ET-10/ET-11, which alone select the report or report-free M6 edge |
-| RS-4 — guarded refusal | Existing HTTP 409 guard envelope and both complete refusal arrays | PUT guards protected-supply interruption; DELETE Restore guards actual effective removal or supply loss. Render the applicable existing guard and evidence blocks. The refusal persists nothing and retains draft intent |
+| RS-4 — guarded refusal | Existing HTTP 409 guard envelope and both complete refusal arrays | Nonempty manual PUT guards protected-supply interruption; inherited DELETE Restore guards actual effective removal or supply loss. Render the applicable existing guard and evidence blocks. The refusal persists nothing and retains draft intent |
| RS-5 — confirm | immutable submitted intent + both exact arrays from the currently displayed refusal | Re-send the same PUT or DELETE with `force: true`, `would_remove_hops` and `would_interrupt`; confirmation never changes the submitted intent |
| RS-6 — plan changed | a forced request returns another guarded 409 | ET-12 replaces both displayed arrays with the recomputed plan and requires another explicit confirmation; the old preview is discarded |
| RS-7 — impact disappeared | the forced request recomputes an empty guarded plan | The server returns ordinary R6 success; ET-10/ET-11 consume the actual envelope and the UI fabricates no refusal |
| RS-8 — shaped rejection | a non-guard, non-`direct_mode` error response | Settle that attempt terminal-rejected. Retry revalidates retained intent, freezes a new generation and sends one ordinary non-forced PUT or DELETE as appropriate. It never runs D-36 or reuses prior force/plan evidence |
-| RS-9 — no response / no Route authority | transport no-answer or `direct_mode` without an exact Route result | ET-15/ET-18a set attempt settlement `unknown`. D-36 may read only: matching proves commit; nonmatching or failed observation never proves the old PUT terminal and never emits a recovery PUT. The user may abandon; any later edit begins a distinct workflow from newly read authority |
+| RS-9 — no response / no Route authority | transport no-answer or `direct_mode` without an exact Route result | ET-15/ET-18a set attempt settlement `unknown`. D-36 may read only: matching proves commit; nonmatching or failed observation never proves the old write terminal and never emits a recovery mutation. The user may abandon; any later edit begins a distinct workflow from newly read authority |
**Direct-mode evidence retires the editor; only `AgentSupply` projects the destination
page** `[contract]` `[derived]`. This is an evidence register, not a second transition
@@ -2092,7 +2102,7 @@ any next read:
| ID | Evidence producer | What the evidence proves | Landing payload available here | Edge owner |
| --- | --- | --- | --- | --- |
| DM-1 | Opening `GET /api/models/agents/<backend>/chain?model=<id>` returns `direct_mode` | The Route surface is illegal at this observation point | None — the standard error envelope carries no `AgentSupply` | ET-18a starts/transfers the mounted page's existing Agents read |
-| DM-2 | Route `PUT` returns `direct_mode` | The editor is now illegal; no exact Route authority exists, so RO sets attempt settlement `unknown` for the submitted pairs even though the response is shaped | None — the error may not label the row or page Direct | ET-18a starts/transfers the same Agents read and changes only ownership/legality around that retained unknown attempt |
+| DM-2 | Route `PUT` or `DELETE` returns `direct_mode` | The editor is now illegal; no exact Route authority exists, so RO sets attempt settlement `unknown` for the submitted normalized intent even though the response is shaped | None — the error may not label the row or page Direct | ET-18a starts/transfers the same Agents read and changes only ownership/legality around that retained unknown attempt |
| DM-3 | D-36 or another post-failure chain read returns `direct_mode` | Exact Route observation is temporarily illegal; this changes RO legality to Direct-suspended and does **not** settle the held attempt | None — no second chain or Source read can manufacture one | ET-18a starts/transfers the same Agents read; RO retains every other axis until a producer-independent Hub post-Source hook makes observation legal |
| DM-4 | ET-16a's first reconciliation read returns the exact backend `AgentSupply` with `mode: direct` | Direct is the authoritative current backend mode, so no Route read or V5 validation is legal now; mode still proves neither Route commit nor non-commit | The returned AgentSupply row itself; it is installed exactly and no second Agents read is sent | AS-1 consumes this payload; RO derives attempt settlement only from held Route evidence, never from this mode producer |
@@ -2110,10 +2120,10 @@ that mutation.
The current guard-totality contract deliberately has **no `guard_token`, digest, version
receipt or server-held confirmation state** `[contract]`. Only an exact unchanged echo of
-both refusal arrays confirms a nonempty recomputed plan. For `mutation.route_replace`,
+both refusal arrays confirms a nonempty recomputed plan. For nonempty manual `mutation.route_replace`,
submitted removals by themselves do not activate the guard: a visible noninterrupting
removal succeeds ordinarily and appears in `removed_hops`; only nonempty
-`would_interrupt` refuses. For `mutation.route_restore`, actual effective removals also
+`would_interrupt` refuses. For `mutation.route_restore` (DELETE or accepted empty PUT), actual effective removals also
activate the existing guard even without interruption. Every refusal carries its exact
current plan and mutates nothing. ET-13a and ET-13b own abandoning and confirming it.
@@ -2204,8 +2214,11 @@ error itself is no landing payload. LF-H establishes the Hub-landing frontier be
acquires or accepts a Source member, so only a post-landing Source observation can call that
Hub projection current. In Hub,
only the exact AgentChain returned by `GET /api/models/agents/<backend>/chain?model=<id>`
-compares the submitted ordered pairs for D-36, including empty-to-empty. A matching chain
-starts M6 with response-only tails unavailable. A nonmatching chain is installed as the
+compares normalized submitted intent for D-36: a nonempty manual override must match
+the submitted pairs; inherited intent requires `manual_override: null`, not equality
+with a prior effective chain or an empty-to-empty comparison. Matching intent
+starts M6 with response-only tails unavailable and the actual current inherited plan.
+A nonmatching observation is installed as the
latest Route authority but leaves the old attempt `unknown`; it authorizes only another
explicit exact-chain read or abandonment, never a PUT. The latest installed authoritative page projection becomes the
reversible exit origin, so later failure cannot reveal an older opening snapshot.
@@ -2226,7 +2239,7 @@ from LF's page-form settlement. Mutation-attempt settlement is exactly
recorded as `matching | nonmatching | read-failed` plus their acquisition epoch; before an
observation settles that register is absent and its in-flight generation belongs to RL.
Owner is `mounted editor | page session`, and legality is
-`Hub-observable | Direct-suspended`. The immutable submitted pairs/stage and workflow
+`Hub-observable | Direct-suspended`. The immutable normalized submitted intent/stage and workflow
generation are attached only to `unknown`; no producer name is part of any axis:
| Axis | Values | Only authority that changes it | Invariant |
@@ -2240,7 +2253,7 @@ The product's legal work and settlement are total:
| ID | Product predicate | Exact work owner | Result / visible disposition |
| --- | --- | --- | --- |
-| RO-R — terminal rejection | `(terminal-rejected, mounted editor, *)` | No D-36 read is legal. CA-R1 may admit an explicit Retry only while the retained draft passes ordinary V5; activation freezes a **new** workflow generation and sends its first PUT | The old attempt remains terminal-rejected and is never resumed. Invalid V5 disables Retry and renders its ordinary row feedback; Cancel abandons without mutation |
+| RO-R — terminal rejection | `(terminal-rejected, mounted editor, *)` | No D-36 read is legal. CA-R1 may admit an explicit Retry only while the retained draft passes ordinary V5; activation freezes a **new** workflow generation and sends nonempty PUT or inherited DELETE according to normalized intent | The old attempt remains terminal-rejected and is never resumed. Invalid V5 disables Retry and renders its ordinary row feedback; Cancel abandons without mutation |
| RO-O — observable unknown | `(unknown, mounted editor, Hub-observable)` or `(unknown, page session, Hub-observable)` with no current exact-chain generation | Admit exactly one exact-chain observation for the held pairs. Mounted entry is acquired/settled as an AR-D member; first page-session entry is acquired by the producer-independent LF-H post-Source hook and a later successor only by D-35. A second Hub payload cannot acquire a sibling generation | Match installs the AgentChain, changes settlement to `terminal-committed` and enters M6. Nonmatch installs the AgentChain but leaves settlement `unknown`; read failure also leaves it `unknown`. Both are read-only: another admitted action may read again, never send PUT |
| RO-S — suspended unknown | `(unknown, *, Direct-suspended)` | Retain generation/pairs/stage across Direct/Hub page-form transitions; cancel/disown only an illegal exact-chain generation | Expose no mutation Retry and make no commit/non-commit claim. The next LF-H post-Source success changes only legality, then RO-O may acquire exactly one observation |
| RO-C — committed | `(terminal-committed, *, *)` | No further D-36 classification is legal; M6 owns projection reconciliation | Mode changes and dismissal cannot question or repeat the mutation; response-only impact members remain unavailable after inferred commit |
@@ -2275,9 +2288,9 @@ total; intentionally unconsumed members remain recorded rather than being descri
| --- | --- | --- | --- |
| AP-1 | `AgentSupply.mode` and the returned backend's page projection | `model-hub-contracts/agent-supply.schema.json`; `GET /api/models/agents` (`api.md` route table) | `mode` is required and consumed for page-form dispatch. The exact returned AgentSupply is installed as page authority |
| AP-2 | `AgentSupply.routes` | `model-hub-contracts/agent-supply.schema.json`; `GET /api/models/agents` | The member is schema-declared but optional and is deliberately not consumed by D-36. Its presence or equality cannot prove this Route write |
-| AP-3 | `AgentChain.chain[*].source_id/model_id` | `model-hub-contracts/agent-chain.schema.json`; exact chain GET (`api.md` route table) | `chain` and each pair identity are required. This endpoint is the sole lost-response equality authority for the edited Route |
+| AP-3 | `AgentChain.manual_override` and `chain[*].source_id/model_id` | `model-hub-contracts/agent-chain.schema.json`; exact chain GET (`api.md` route table) | Normalized manual_override and effective chain are required. This endpoint alone compares submitted intent after a lost response: exact nonempty manual pairs or inherited null. Effective pair equality alone cannot prove intent |
| AP-4 | `Source[]` | `model-hub-contracts/source.schema.json`; `GET /api/models/sources` (`api.md` route table) | Consumed for V5 eligibility and the complete Source/adoption projection; it never proves Route commit |
-| AP-5 | R6 `chain`, `removed_hops`, `interrupted` | route-replace success schema/mutation matrix; exact chain PUT (`api.md` route table) | All returned members are consumed. D-36 inference has no response envelope, so both response-only impact arrays are marked unavailable |
+| AP-5 | R6 `chain`, `removed_hops`, `interrupted` | route-replace/Restore success schema and mutation matrix; exact chain PUT/DELETE (`api.md` route table) | All returned members are consumed. D-36 inference has no response envelope, so both response-only impact arrays are marked unavailable |
| ID / workflow generation | Independent reducer edge + acquisition eligibility / observation epoch | Required frontiers / Route outcome | Decisive page evidence | Immediately installed / held authority | Applicable set after decisive evidence | Awaited / deferred / stale members | Cancellation / late result | Destination / Retry subset |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
@@ -2286,8 +2299,8 @@ total; intentionally unconsumed members remain recorded rather than being descri
| AR-D3 — Hub AgentSupply | Agents succeeds with exact `mode: hub` | Attempt remains `unknown`; the landing self-satisfies Agents and establishes a Hub-landing frontier required by Source | Hub permits exact reconciliation but proves no Route equality | **Install Hub AgentSupply first** as reversible page origin; retain immutable draft/stage | Agents, Sources and exact AgentChain | One Source generation acquired after this landing + exact AgentChain | ET-17a acquires both after installation in this workflow generation; AP-2 stays unconsumed | Originating unknown failure, pending; no Retry while active |
| AR-D4 — Hub members pending | AR-D3 plus independently settling Source and exact-chain members | Each member settles only its own slot; no sibling result changes attempt settlement or Route observation | No attempt decision until exact match or a terminal producer answer exists | Retain AS-2 and install every successful member before any edge | Agents, Sources and exact AgentChain | Pending or failed Source/chain slots | Own both reads until AR-D5–AR-D9 or RL disown | Derive the destination only from the orthogonal product table below |
| AR-D5 — chain becomes Direct | Chain settles `direct_mode`; Source may be pending, successful or failed in its own epoch | Attempt remains `unknown`; change only legality to Direct-suspended | Chain Direct takes the common Direct page-form edge but proves no mutation outcome | Install every successful Source/Agents member first; hold illegality evidence plus generation/pairs/stage. The error is no landing payload | Source + authoritative landing Agents; exact Route observation is suspended while Direct | Landing Agents read unless the decisive member itself was Agents | Preserve settled Source; disown only pending comparison work; ignore its late results; keep the complete RO product state | ET-18a family → page Partial or retained committed modal; Retry only landing reads, never the mutation. Any later LF-H post-Source hook re-evaluates RO-O |
-| AR-D6 — exact chain match / commit frontier | Exact chain matches submitted pairs, regardless of Source settlement or response order | Install `matching@epoch`, then set attempt `terminal-committed` and establish CF-R. The matching chain self-satisfies Route | Exact equality proves commit before any sibling result | **Install exact AgentChain first** as D-36 evidence; keep earlier successes installed as latest-known only | M6 Source, Agents and Route-chain projections | Acquire an Agents successor first; after its exact landing, acquire the Source successor required by CF-R and any CF-H | Supersede/disown a predecessor member only when its successor is acquired; ignore predecessor late results | ET-17c → M6; later Source success/failure cannot change commit; Retry only a frontier-satisfying failed subset |
-| AR-D7 — exact chain nonmatch | Exact chain differs from submitted pairs, regardless of Source settlement or response order | Record `nonmatching@epoch`; attempt remains `unknown` and no commit frontier exists | Exact inequality is only a Route observation and never selects page form or proves the PUT terminal | **Install exact AgentChain first** as the row's newest Route authority; preserve independently installed Source/Agents | Agents, Sources and exact chain | Only the Source slot may remain pending or failed | Settle only the chain generation; Source cannot change attempt settlement or the installed observation | Read-only product table below; another explicit Retry may issue only a newer exact-chain read, never a PUT |
+| AR-D6 — exact chain match / commit frontier | Exact AgentChain manual_override matches normalized submitted intent, regardless of Source settlement or response order | Install `matching@epoch`, then set attempt `terminal-committed` and establish CF-R. The matching chain self-satisfies Route | Exact equality proves commit before any sibling result | **Install exact AgentChain first** as D-36 evidence; keep earlier successes installed as latest-known only | M6 Source, Agents and Route-chain projections | Acquire an Agents successor first; after its exact landing, acquire the Source successor required by CF-R and any CF-H | Supersede/disown a predecessor member only when its successor is acquired; ignore predecessor late results | ET-17c → M6; later Source success/failure cannot change commit; Retry only a frontier-satisfying failed subset |
+| AR-D7 — exact chain nonmatch | Exact AgentChain manual_override differs from normalized submitted intent, regardless of Source settlement or response order | Record `nonmatching@epoch`; attempt remains `unknown` and no commit frontier exists | Exact inequality is only a Route observation and never selects page form or proves the PUT terminal | **Install exact AgentChain first** as the row's newest Route authority; preserve independently installed Source/Agents | Agents, Sources and exact chain | Only the Source slot may remain pending or failed | Settle only the chain generation; Source cannot change attempt settlement or the installed observation | Read-only product table below; another explicit Retry may issue only a newer exact-chain read, never a PUT |
| AR-D8 — exact chain read failure | Non-Direct exact-chain observation fails | Record `read-failed@epoch`; attempt remains `unknown`. No commit frontier exists | No new Route authority | Retain every successful Source/Agents member already installed | Agents, Sources and exact chain | Chain failed plus any still-pending/failed Source | Settle only chain failure; no success or axis is rolled back | After all pending members settle, ET-17b; Retry only the exact failed read subset, never an already-successful member or mutation |
| AR-D9 — Source member settles, mode-neutral | The post-Hub-landing Source generation returns success or failure before or after AR-D6/AR-D7/AR-D8 | Success or failure settles only Source at its acquisition epoch and changes no attempt/observation axis. If a later commit/Hub frontier applies, acquire a successor instead of treating this slot as current/stale | Source carries no page-form or Route-attempt evidence | **Install Source success before any transition**; mark only a frontier-satisfying failure stale | The mode-selected set is unchanged | Source alone becomes current, failed or pending for a newer frontier | Chain settlement cannot undo Source; Source settlement cannot undo Route observation | Re-evaluate the product table. A Source-only failure Retry never rereads Agents or exact chain |
| AR-M1 — acquired member settles, mode-neutral | Active M6 + an `acquired` Source, Agents or Route-chain member returns success or failure | Settle only that member. It closes its slot only if its acquisition epoch satisfies every required frontier; otherwise retain it as latest-known and make one successor `ready` for acquisition. Activating the held commit chain is an immediate successful settlement, not a request | Only an exact successful Agents mode payload may select LF/AS page form. Source success/failure, Agents failure and non-Direct Route settlement carry no page-form evidence | Install/hold a success monotonically; mark only a frontier-satisfying acquired failure stale. Successful Agents invokes LF/AS; every other result updates only its member authority/staleness | Before decisive mode, Agents is applicable/acquired and Source/Route applicability is deferred. Exact Direct activates Source and makes Route not applicable; exact Hub activates Source and the held self-satisfying Route evidence. Agents remains applicable in both | Acquired pending members; deferred companions before mode; exact acquired failures after settlement | Sibling failure cannot undo a success. A failed prerequisite leaves dependants deferred and does not make them stale; ignore predecessor-epoch results | Keep the currently installed Direct/Hub page and mounted/transferred ownership unchanged. Agents-first failure settles through AR-M3 with Agents alone retryable; successful Agents Retry activates companions. A late Direct-mode Source result settles only Source and never resurrects Hub |
@@ -2424,14 +2437,14 @@ generation is ignored and cannot install authority, feedback or focus.
| ID / event | Origin + held evidence | Authority dispatch order | Transient cleanup | Destination | Visible feedback | Entry focus | Next request/read owner |
| --- | --- | --- | --- | --- | --- | --- | --- |
| ET-1 — open model row | Mounted §1.1 row + exact `(backend, menu_model)` | Acquire the RL opening generation and start the exact chain GET; infer no projection | Close the row menu; no draft/grab exists | Loading route | `route.loading` | FF-1-valid `route.cancel` | Dialog-owned chain GET |
-| ET-2 — opening chain success | Loading route + returned AgentChain | Validate the envelope, then install its exact pair array as origin and draft | Clear loading only | Ready | Normal frame copy | Keep `route.cancel`; payload arrival does not steal focus | None |
+| ET-2 — opening chain success | Loading route + returned AgentChain | Validate the envelope, then install its normalized manual_override and effective pairs as reversible origin and draft | Clear loading only | Ready | Normal frame copy | Keep `route.cancel`; payload arrival does not steal focus | None |
| ET-3 — opening non-direct failure | Loading route + held page row; DM-1 is reserved for ET-18a | Exclude `direct_mode`, then classify the shaped/transport failure | Clear loading; retain the independent page row | Route unread | `route.fail.read` | `route.retry` | None until explicit Retry |
| ET-4 — unread Retry | Route unread + exact identity/page row | Settle the old RL generation, acquire its successor and reissue only the opening chain GET | Clear the old error | Loading route | `route.loading` | FF-1-valid `route.cancel` | Dialog-owned chain GET |
| ET-5a — open Add selector | Ready, Dirty or Invalid after refresh + current V5 authorities | Materialize current V5 candidates, focus the filter field and make the first listed candidate the single active/selected pair carried as its active descendant | Clear any prior selector owner before assigning that pair | Same editor state + selector open | Selector keys; existing invalid lines remain | The active/selected first exact candidate | None |
| ET-5b — dismiss Add selector | Open selector + unchanged draft | Send/read nothing | Clear selector selection and close only the selector | Owning Ready, Dirty or Invalid state | Normal frame copy; existing invalid lines remain | `route.addHop` | None |
| ET-5c — confirm Add candidate | Open selector + selected exact pair | Revalidate the pair through V5, then append it | Clear selection and close selector | Ready if equal to origin, otherwise Dirty or existing Invalid after refresh | Normal copy plus every remaining invalid line | New row's grip | None |
| ET-5d — choose another Add candidate | Open selector + current active/selected candidate | Send/read nothing; Arrow/Home/End from the filter field, pointer activation, or a filter change that drops the active candidate atomically makes the destination candidate both active and selected | Replace the one prior active/selected owner | Same open selector | Existing selector copy | Newly active/selected candidate | None |
-| ET-6a — remove one row | Ready, Dirty or Invalid after refresh + exact row/draft | Remove locally, then re-run V5 | Drop selector/grab state owned by that row | Ready if equal to origin; Dirty if changed and valid; Invalid only while a marked row remains | Normal copy plus every remaining invalid line | First FF-1-valid target: successor grip; predecessor grip; when empty `route.addHop` only if V5 admits it; then `route.reorder`; finally enabled `route.cancel` | None |
+| ET-6a — remove one row | Ready, Dirty or Invalid after refresh + exact row/draft | If a nonempty draft survives, remove locally and re-run V5. Removing the final hop instead preserves the prior unsaved draft for Undo and enters the existing null Restore preview | Drop selector/grab state owned by that row; invalidate older previews | Nonempty draft: Ready/Dirty/Invalid by normalized intent and V5. Final hop: inherited preview loading/result/retry; never empty Manual | Existing manual or Restore/Undo copy and actual inherited target/origin | Nonempty: successor/predecessor grip then enabled Cancel. Final hop: existing Undo restore focus target | Final hop only: read-only preview null; no persistence |
| ET-6b — pointer move one row | Ready, Dirty or Invalid after refresh + exact row/draft | Apply the one pointer move, then re-run V5 | Finish the pointer operation | Ready if equal to origin; Dirty if changed and valid; existing Invalid while marked rows remain | `route.reorder.position` plus registered invalid lines | Moved row's grip | None |
| ET-6c — global draft sort | Ready, Dirty or Invalid after refresh + exact draft and page-held Source order | Apply the registered stable local sort once, then re-run V5; no-op is valid | Finish only the sort gesture | Ready if equal to origin; Dirty if changed and valid; existing Invalid while marked rows remain | Changed → `route.reorder.sorted`; no-op → `route.reorder.unchanged`; retain registered invalid lines | `route.reorder`, including after a no-op | None |
| ET-7a — ungrabbed row-focus move | Ready, Dirty or Invalid after refresh + focused grip | Send/read nothing; Arrow/Home/End changes only the roving row | Replace the prior roving focus | Same editor state | Existing row copy | Destination row's grip | None |
@@ -2442,20 +2455,20 @@ generation is ignored and cannot install authority, feedback or focus.
| ET-7f — Tab from grabbed row | Grabbed row + current draft | Settle current order and re-run V5 before focus movement | Clear `aria-grabbed` and snapshot, then perform ordinary Tab/Shift+Tab | Ready, Dirty or Invalid by settled V5 result | `route.reorder.dropped` plus registered invalid lines | Ordinary next/previous enabled modal control | None |
| ET-8a — ordinary / terminal-rejected reversible exit | Loading route, Route unread, Ready, Dirty, Invalid after refresh or Route save rejected + latest installed authoritative page projection | Send no mutation; disown the current RL opening generation before close. A terminal rejection owns no D-36 generation | Close selector; restore/cancel any grab; discard local/submitted draft and terminal rejection evidence; ignore every late result from disowned opening reads | Reveal the latest installed page authority | Exact latest projection; retain its existing unresolved marker if any. No recovery read or false commit report follows | Preserve an FF-1-valid active page target, otherwise PF-1 after the modal target unmounts | None; an already-unresolved row retains D-35 |
| ET-8b — explicit unknown-attempt abandonment | Attempt settlement is `unknown`, owner is mounted editor, legality is Hub-observable or Direct-suspended, and the latest successful members are already installed | Send no mutation/read; explicitly abandon this old workflow and disown every mounted AR-D/RO generation before close | Close selector; restore/cancel any grab; discard submitted pairs/stage and all old-workflow rights. Ignore every later result from disowned generations | Reveal the latest installed authority, including an AgentSupply, Source or matching/nonmatching AgentChain installed before this edge | Exact latest projection with no old-attempt Retry. A later row open starts from current authority as a new workflow; it never resumes or replays this attempt | Preserve an FF-1-valid page target, otherwise PF-1 after modal close | None |
-| ET-9a — first Route PUT | V5-valid Dirty draft | Freeze and send the complete array without `force` or plan echoes | Close selector; settle any grab | Saving | `route.saving` | Programmatically focusable progress status | One owned Route PUT |
-| ET-10 — R6 success with impact | Saving + exact R6 envelope with either array nonempty | Consume every R6 member, establish CF-R, mount its report and start AR-M with Agents acquired and Source/Route applicability deferred | Release PUT/refusal ownership; retain the entire envelope and held self-satisfying chain | Route impact reported with AR-M pending | Impact title/detail and each nonempty block | `route.impact.done` | Agents landing read; mode then acquires Sources under Direct or after CF-H under Hub and activates/drops the held Route evidence |
-| ET-11 — two-empty R6 commit | Saving + exact R6 envelope whose two impact arrays are empty | Preserve the exact envelope, establish CF-R and start AR-M with Agents acquired and Source/Route applicability deferred | Release PUT ownership; retain the held self-satisfying chain; no origin can be restored | Route committed, reconciling | `route.refreshing` | `route.impact.done` | Agents landing read; mode then acquires Sources under Direct or after CF-H under Hub and activates/drops the held Route evidence |
-| ET-12 — guarded 409 | Saving + immutable draft + complete current refusal arrays | Validate guard code and both arrays; a later 409 atomically replaces both | Release PUT ownership only after the current plan is held | Route save refused | Shared Qp6FI copy and current arrays | `guard.cancel` | None until explicit user action |
+| ET-9a — first Route save | V5-valid nonempty manual draft or ready inherited preview | Freeze normalized intent and send nonempty PUT or inherited DELETE without `force` or plan echoes | Close selector; settle any grab | Saving | `route.saving` | Programmatically focusable progress status | One owned Route PUT or DELETE matching the immutable intent |
+| ET-10 — R6 success with impact | Saving + exact R6 envelope with either array nonempty | Consume every R6 member, establish CF-R, mount its report and start AR-M with Agents acquired and Source/Route applicability deferred | Release mutation/refusal ownership; retain the entire envelope and held self-satisfying chain | Route impact reported with AR-M pending | Impact title/detail and each nonempty block | `route.impact.done` | Agents landing read; mode then acquires Sources under Direct or after CF-H under Hub and activates/drops the held Route evidence |
+| ET-11 — two-empty R6 commit | Saving + exact R6 envelope whose two impact arrays are empty | Preserve the exact envelope, establish CF-R and start AR-M with Agents acquired and Source/Route applicability deferred | Release mutation ownership; retain the held self-satisfying chain; no origin can be restored | Route committed, reconciling | `route.refreshing` | `route.impact.done` | Agents landing read; mode then acquires Sources under Direct or after CF-H under Hub and activates/drops the held Route evidence |
+| ET-12 — guarded 409 | Saving + immutable draft + complete current refusal arrays | Validate guard code and both arrays; a later 409 atomically replaces both | Release mutation ownership only after the current plan is held | Route save refused | Shared Qp6FI copy and current arrays | `guard.cancel` | None until explicit user action |
| ET-13a — abandon guard | Route save refused + immutable draft/current arrays | Send/read nothing | Drop the refusal plan only | Dirty | Normal draft | `route.save` | None |
-| ET-13b — confirm guard and send | Route save refused + immutable draft/current arrays | Revalidate exact echoes, then send the same draft with `force: true` and both arrays | Drop the rendered refusal as the immutable values freeze into the request | Saving | `route.saving` | Programmatically focusable progress status | One owned Route PUT |
-| ET-14 — definitive non-guard rejection | Saving + submitted draft; DM-2 is reserved for ET-18a | Exclude guard and `direct_mode`, then settle this attempt `terminal-rejected` | Release PUT ownership; retain only the locally validated draft for an explicit new workflow | Route save rejected | `route.fail.save` | FF-1-valid `route.retry` | None; rejection never enters D-36 |
-| ET-14a — explicit new attempt after rejection | Route save rejected + retained draft + CA-R1 admission | Re-run ordinary V5; when valid create a new workflow generation and send the ordinary non-forced PUT body. The prior terminal attempt supplies no request identity, force flag, plan echo or replay right | Clear old rejection feedback only as the new generation acquires PUT ownership | Saving | `route.saving` | Programmatically focusable progress status | One new owned Route PUT; any returned guard begins a new Qp6FI phase |
-| ET-15 — no response evidence | Saving + submitted draft + initial/confirmed stage | Set attempt settlement `unknown`; infer neither commit nor refusal | Release PUT ownership; retain immutable attempt evidence | Route save outcome unresolved | `route.fail.unconfirmed` | `route.retry` | None until a read-only Retry |
+| ET-13b — confirm guard and send | Route save refused + immutable draft/current arrays | Revalidate exact echoes, then send the same draft with `force: true` and both arrays | Drop the rendered refusal as the immutable values freeze into the request | Saving | `route.saving` | Programmatically focusable progress status | One owned Route PUT or DELETE matching the immutable intent |
+| ET-14 — definitive non-guard rejection | Saving + submitted draft; DM-2 is reserved for ET-18a | Exclude guard and `direct_mode`, then settle this attempt `terminal-rejected` | Release mutation ownership; retain only the locally validated draft for an explicit new workflow | Route save rejected | `route.fail.save` | FF-1-valid `route.retry` | None; rejection never enters D-36 |
+| ET-14a — explicit new attempt after rejection | Route save rejected + retained draft + CA-R1 admission | Re-run ordinary V5; when valid create a new workflow generation and send ordinary non-forced nonempty PUT or inherited DELETE. The prior terminal attempt supplies no request identity, force flag, plan echo or replay right | Clear old rejection feedback only as the new generation acquires mutation ownership | Saving | `route.saving` | Programmatically focusable progress status | One new owned Route PUT or DELETE matching normalized intent; any returned guard begins a new Qp6FI phase |
+| ET-15 — no response evidence | Saving + submitted draft + initial/confirmed stage | Set attempt settlement `unknown`; infer neither commit nor refusal | Release mutation ownership; retain immutable attempt evidence | Route save outcome unresolved | `route.fail.unconfirmed` | `route.retry` | None until a read-only Retry |
| ET-16a — begin unknown reconciliation | Route save outcome unresolved in CA-D1 initial idle + held draft/stage | Start one AR-D generation with `GET /api/models/agents` | Keep error body/draft; CA-D2 owns focus transfer plus Retry busy/inert admission | Same unknown failure, reconciliation pending | Existing failure copy | CA-D2 handoff | One AR-D Agents read; no second generation is admitted |
| ET-16b — AR-D1 failure handoff | AR-D1 selected after the Agents member failed | Do not choose a page form | Clear active generation/busy; retain error body/draft and latest page authority | Originating failure | `route.fail.reconcileRead` | FF-1-valid `route.retry` | None until a newly admitted ET-16a |
| ET-17a — AR-D3 Hub comparison begins | AR-D3 selected after AS-2 installs the exact Hub AgentSupply | Under the same workflow generation read current Sources and the exact chain endpoint; record a member epoch for each and never inspect AP-2 for equality | Keep modal/draft; CA-D2 retains its completed handoff and Retry admission | Originating failure, Hub reconciliation pending over the installed Hub page; accumulator enters AR-D4 | Existing failure copy | Preserve CA-D2's FF-1-valid owner | One Source read + one exact-chain read in the current AR-D generation |
| ET-17b — settled AR-D read failure | The orthogonal unknown-attempt product has no pending member and at least one failed Source/chain slot, except the dedicated nonmatching-observation + Source failure row ET-17f | Preserve every attempt/observation axis and successful installed member; do not restart an already-authoritative read | Clear active generation/busy; retain draft and latest installed page projection | Route save outcome unresolved | `route.fail.reconcileRead` | FF-1-valid `route.retry` | CA-D3 admits a successor for exactly the failed Source/chain subset; CA-D4 owns its pending phase |
-| ET-17c — AR-D6 matching chain proves commit | AR-D6 selected from an exact AgentChain equal to submitted pairs | The exact AgentChain is already installed; record `matching@epoch`, settle the attempt `terminal-committed`, mark response-only tails unavailable and establish CF-R before transferring to AR-M | Clear comparison busy; discard obsolete read Retry state; retain earlier successes as latest-known but frontier-insufficient | Route committed, reconciling | `route.refreshing` | FF-1-valid `route.impact.done` | Acquire Agents first; LF-H then establishes CF-H and acquires Sources. Keep the matching chain self-satisfied |
+| ET-17c — AR-D6 matching chain proves commit | AR-D6 selected from an exact AgentChain whose manual_override matches normalized submitted intent | The exact AgentChain is already installed; record `matching@epoch`, settle the attempt `terminal-committed`, mark response-only tails unavailable and establish CF-R before transferring to AR-M | Clear comparison busy; discard obsolete read Retry state; retain earlier successes as latest-known but frontier-insufficient | Route committed, reconciling | `route.refreshing` | FF-1-valid `route.impact.done` | Acquire Agents first; LF-H then establishes CF-H and acquires Sources. Keep the matching chain self-satisfied |
| ET-17d — repeat exact observation after nonmatch | Attempt remains `unknown`; AR-D7 holds an installed `nonmatching@epoch`; AR-D9 holds Source success satisfying current CF-H; CA-D7 admits the read | Acquire one successor exact-chain GET under the same read-only workflow; send no PUT and do not run V5 as a mutation gate | Retain draft/evidence and every installed authority; CA-D2 owns focus transfer plus Retry busy/inert admission | Route save outcome unresolved, exact read pending | Existing unresolved copy | CA-D2 handoff | One exact-chain successor; match enters ET-17c, nonmatch updates the observation epoch, failure enters ET-17b |
| ET-17e — independent refresh invalidates local draft | Ready, Dirty or Route save rejected with no mutation owned + newly installed authoritative Source/chain projection that makes a new/changed pair fail V5 | Install the authority first and re-run V5; send no PUT | Clear selector/grab state invalidated by the refresh; when present discard terminal rejection evidence while retaining editable rows | Invalid after refresh | `route.invalidAfterRefresh` on every offender | First offending row's FF-1-valid Remove action | None |
| ET-17f — nonmatching observation + Source failure | AR-D7 holds installed `nonmatching@epoch` and AR-D9 settles a Source failure satisfying current CF-H, in either response order | Preserve attempt `unknown` and the exact observation; classify only Sources stale | Clear active generation/busy; retain draft, AgentSupply and installed exact chain authority | Route save outcome unresolved with Source stale | `route.fail.reconcileRead` | FF-1-valid `route.retry` | CA-D5 admits only ET-17g; Agents/chain and the mutation are not eligible |
@@ -2612,7 +2625,7 @@ shared `models.hub.guard.*` owner.
| `reorder.sorted` `[derived]` | 已按来源顺序重排。 | Reordered by Source order. |
| `reorder.unchanged` `[derived]` | 路由链已经符合来源顺序。 | The route chain already matches Source order. |
| `hint` `[frame]` | 这条链是写下来的配置。以后调整来源顺序时,其中的来源会按新的顺序重排。 | This chain is stored configuration. Later Source order changes reorder its hops to match. |
-| `empty` `[derived]` | 这条路由链是空的。添加一跳,或保持为空配置。 | This route chain is empty. Add a hop, or leave it unconfigured. |
+| `empty` `[derived]` | 没有可继承的路由。请配置默认路由。 | No inherited route is available. Configure default routing. |
| `removeHop` `[derived]` | 移除这一跳 | Remove this hop |
| `grip` `[derived]` | 调整这一跳的顺序 | Reorder this hop |
| `loading` `[derived]` | 正在读取路由链… | Loading route chain… |
@@ -3696,6 +3709,12 @@ the operation vary by caller. That split is the copy-level form of the same rule
geometry follows: **one surface, one reading of `would_interrupt`; each operation names
only what it is about to do.**
+The old frame-only `hint.removeSource` statement about retaining emptied manual
+chains is superseded by Empty Route Inheritance. It is not a production locale key
+and requires no new consumer. Current guard hints use the existing
+`settings.models.guard.hint.safe` / `settings.models.guard.hint.interrupt` keys and
+the recomputed inherited impact; a final-hop removal never forces an empty Manual state.
+
| Key | 中文 | English |
| --- | --- | --- |
| `label` | 会被移除的跳 | Hops that will be removed |
@@ -3706,7 +3725,6 @@ only what it is about to do.**
| `hop.position.removeSource` `[frame]` | 第 {{n}} 跳 | Hop {{n}} |
| `hint.safe` | 这些型号还有别的来源可用。 | These models still have another source available. |
| `hint.interrupt` | 有型号会因此没有可用来源。 | Some models will be left with no usable source. |
-| `hint.removeSource` `[frame]` | 一个事务:来源从每个后端的顺序与所有路由链一起移除;空掉的链保留并标「中断」,其余跳顺序不变。 | One transaction removes the source from every backend order and every route chain. Empty chains remain and are marked interrupted; all other hop order stays unchanged. |
| `gap.label` `[derived]` | 会失去可用来源的型号 | Models that will be left with no source |
| `gap.subject` `[derived]` | {{backend}} · {{menuModel}} | {{backend}} · {{menuModel}} |
| `gap.agents` `[derived]` | 已指定它的 Agent:{{agents}} | Agents pinned to it: {{agents}} |
@@ -3939,12 +3957,13 @@ Five rules:
with `guard.gap.*` naming the models and Agents behind that sentence. 仍要拉取 re-sends
with `force`, and the contract is equally explicit about what that does: it 「applies the inventory change and removes only
those invalidated hops in one transaction, preserving the identity and relative order of
- all survivors and keeping an empty route configured」, reporting every resulting gap —
+ all surviving nonempty manual arrays」. Removing a final hop drops its override key
+ and evaluates inheritance before reporting every effective removal and resulting gap —
`force` is confirmation, not a claim that the change is interruption-free.
- **This is not the chain changing by itself; it is the only way it changes at all.** No
- path in this product removes a hop without a `409` that names each one and a confirm the
- user answers — that is what S-1 means by the chain being the user's, and §4.6 says the
+ **The guards protect exact effective impact, not an empty-disable state.** Source
+ mutations use the shared exact plan, while nonempty manual PUT retains its visible
+ noninterrupting-removal exception. Empty PUT/DELETE use Restore guards. §4.6 says the
same thing from the storage side: a hop's live reason stays visible 「until the Source
recovers, the user removes or changes the pair, **or a guarded cascade removes it**」.
Until this round that sentence was quoted here without its last clause, and the missing
@@ -3962,9 +3981,10 @@ Five rules:
position. A nonempty chain renders `legend.unavailable` in its existing
current-text slot; `chain_length: 0` branches first to the existing
`models.launch.route_unconfigured` family. The projection
- is reached both by the retained-hop path and by a confirmed cascade that empties a route
- — an emptied route stays an explicit empty configuration, so the menu still has something
- to mark. **No stale row is invented on frame 06.** Frame 01 is the registered model-row
+ follows the actual inherited plan after a cascade removes the last manual hop. Its
+ catalog row survives normalization; an empty inherited plan is Unconfigured, while a
+ nonempty inherited plan shows its automatic/passthrough origin and live status.
+ **No stale row is invented on frame 06.** Frame 01 is the registered model-row
consumer; the Source inventory remains only the Source's current inventory.
*What that costs, said here too because this is the page where it is felt.* The source a
@@ -5581,9 +5601,11 @@ and a poll cadence this file has no basis to choose; the frame rules out the fir
subject's identifier.** F1 leaves a mutation's outcome unknown and the repair is always
a read; what decides whether that read is a *reconciliation* or merely a refresh is
whether the client can name what it is asking about. §1.2 holds `(backend, menu_model)`
-and the exact submitted ordered pair array. Only the exact chain `GET` is presence-total for
-the Route under comparison: its ordered `(source_id, model_id)` pairs equal to that array
-prove the desired Route committed, including empty-to-empty. `AgentSupply.routes` is a real
+and normalized submitted intent. Only the exact chain `GET` is presence-total for
+the Route under comparison: manual intent must equal the submitted nonempty exact array;
+restored intent must be `manual_override: null`, irrespective of changing inherited hops.
+Array equality alone cannot prove intent. Legacy empty input and absent values compare
+canonically as inheritance, never as an empty-disable state. `AgentSupply.routes` is a real
but optional schema member and this workflow deliberately does not consume it; the Agents
read settles mode/page authority only. Runtime annotations do not participate in the chain
comparison. Mode and Route attempt settlement are orthogonal: Direct mode makes that exact
diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.md
index 65a09b1bc..540951172 100644
--- a/docs/plans/model-hub.md
+++ b/docs/plans/model-hub.md
@@ -1,8 +1,9 @@
# Model Hub — Product Spec
-Status: **Routing modes, contract_version 9** (2026-09-06).
+Status: **Routing modes, contract_version 10** (2026-09-06).
Owner-approved implementation contract: `model-hub-routing-modes.md`, frozen before
-implementation at `2db273891`, amended by owner scope/synchronization decision `c1d398d5f`. It replaces one-time matching with sparse manual
+implementation at `2db273891`, with API-key scope/synchronization decision `c1d398d5f`
+and Empty Route Inheritance correction `352486374`. It replaces one-time matching with sparse manual
intent and a shared effective planner. The complete schema, runtime, UI and consumer
closure lands on one tested feature head. Supported persisted shapes and historical
TurnProvenance remain readable under the repository persisted-shape rule.
@@ -22,10 +23,10 @@ Its end-to-end product model is:
Every `(backend, menu model)` has one effective ordered route. A sparse persisted
`routes` map stores only manual overrides; every hop names the exact
-`(source_id, model_id)` to call. Absence inherits automatic defaults, while a present
-empty override intentionally supplies nothing. Saving a route establishes manual
-intent even when its array equals the generated result; restoring automatic deletes
-the key.
+`(source_id, model_id)` to call. Absence and a valid empty hop array both inherit
+defaults. Only a nonempty route establishes manual intent, even when its array equals
+the generated result. Restoring automatic or submitting empty hops deletes the key
+through the same exact guarded operation; canonical output never retains an empty value.
For API-key defaults [A, B], model M uses B alone when only B lists M. When neither lists M,
the route is [A/M, B/M], forwarding M unchanged. A saved manual route replaces the
@@ -34,8 +35,10 @@ their existing known-model admission, matching and stale-hop retention rules. Un
passthrough is restricted to eligible Hub API-key Sources; unmatched subscription-only
defaults are Unconfigured.
§4.2 owns effective planning and §4.3 owns execution of that plan. There is no separate
-mapping structure or second persisted policy flag. Existing populated, empty, stale
-and dormant overrides remain exact; historical arrays do not prove human authorship.
+mapping structure or second persisted policy flag. Nonempty overrides remain exact,
+including stale and dormant entries. Supported legacy empties normalize to absence
+after validation without dropping catalog identities or other configuration; historical
+arrays do not prove human authorship. Reads and previews never persist normalization.
**Subscription ruling (owner 2026-08-07, amended later the same day).** Recommended
custody is vendor-specific. Claude subscriptions stay in Claude Code's local login by
@@ -98,7 +101,7 @@ base URLs, protocol conversion, account pools or routers.
native attempt ahead of a user-owned configured chain.
3. **Every route exposes its intent and effective result.** Backend defaults generate
automatic matches or unchanged-id API-key passthrough. A manual override replaces that result
- exactly, including an empty array; Restore automatic removes the override.
+ exactly only when nonempty; Restore automatic or empty input removes the override.
4. **The user owns every configured order and mapping.** No health score, learned
ranking or vendor label rewrites manual intent. Automatic routes follow current
defaults and evidence; live availability only annotates the chosen plan.
@@ -437,10 +440,10 @@ evaluated in this order, before transient health or invocation-channel filtering
| Decision | Condition | Effective hops | Origin |
| --- | --- | --- | --- |
-| `route_plan.manual` | a manual key exists | exact saved array and order, including empty | manual when nonempty, otherwise null |
-| `route_plan.automatic` | no manual key; eligible defaults provide matching evidence | all accepted matching pairs in default order | automatic |
-| `route_plan.passthrough` | no manual key and no matching pairs; eligible non-retired Hub API-key defaults remain | exact requested id on each such API-key Source; no subscription speculation | passthrough |
-| `route_plan.empty` | no manual key and neither tier has any eligible pair | empty | null |
+| `route_plan.manual` | a nonempty manual value exists | exact saved nonempty array and order | manual |
+| `route_plan.automatic` | absent or valid empty manual value; eligible defaults provide matching evidence | all accepted matching pairs in default order | automatic |
+| `route_plan.passthrough` | absent or valid empty manual value and no matching pairs; eligible non-retired Hub API-key defaults remain | exact requested id on each such API-key Source; no subscription speculation | passthrough |
+| `route_plan.empty` | absent or valid empty manual value and neither inherited tier has any eligible pair | empty | null |
Matching uses complete non-retired inventory, independent of health and CLI readiness:
@@ -462,7 +465,8 @@ removes its references under §4.5 guards.
The planner never writes configuration. Manual intent survives Source additions,
default edits, discovery, catalog changes, health changes and reload. Automatic routes
follow current defaults and evidence. Equal-to-automatic manual saves remain manual;
-there is no historical-authorship inference or global reinterpretation of empty arrays.
+nonempty arrays never imply historical authorship. Valid empty values inherit under the
+explicit owner compatibility correction, including directly constructed configuration.
Source health, quota, latency, cost, usage and timestamps never choose a tier or reorder
it. Live inspection only annotates runnability, current position and recovery state.
@@ -1123,7 +1127,8 @@ source_id, model_id)` reference. `force=true` with that refusal's exact
`would_remove_hops` and `would_interrupt` arrays is an explicit cascade confirmation:
the same transaction deletes the Source and every exact hop that names it across every
backend route, while the identity and relative order of all surviving hops remain
-unchanged. An emptied route remains an explicit empty configuration.
+unchanged. If pruning removes the final manual hop, remove that key and recompute the
+inherited plan before calculating effective removals, supply gaps and transport targets.
Any resulting protected-model gap is reported through the existing
`would_interrupt` projection alongside `would_remove_hops`. Each `RouteHopRef` also
carries one-based `position` in that named Route before the attempted mutation;
@@ -1139,15 +1144,19 @@ model-membership admission remains unchanged. Explicit retirement
excludes the exact pair, while manual inventory deletion removes matching evidence
without deleting explicit API-key hops; subscription admission remains unchanged. Refusals report complete effective removals and protected
supply loss in the existing arrays. Forced success must match both echoed arrays and
-preserves surviving manual intent; Source deletion removes its actual references.
-Automatic recomputation never persists a generated route or rewrites manual intent.
+preserves surviving nonempty manual intent; Source deletion removes its actual references.
+Every final-hop removal, including catalog reconciliation, uses the same normalized
+planner. Normal saves persist the canonical sparse map; pure reads/preview never write.
+Automatic recomputation never persists a generated route or rewrites nonempty intent.
**Guard confirmation totality matrix (authoritative and exhaustive; owner subtraction
ruling 2026-08-11 20:35, with direct-Route scope corrected at 21:14).** The shared layer
recomputes under the atomic commit boundary. For Source, inventory, default-membership and Restore mutations, a
guarded-impact plan is nonempty when the staged mutation has at least one
`would_remove_hops` or `would_interrupt` item. For `mutation.route_replace`, only a
-nonempty `would_interrupt` activates the plan: the refusal also reports its submitted
+nonempty `would_interrupt` activates the plan for nonempty manual replacement; empty PUT
+instead uses `mutation.route_restore` and its exact effective-removal/supply guards.
+For nonempty replacement the refusal also reports its submitted
removals, but a visible noninterrupting removal is ordinary success and reports those
items only as `removed_hops`. Confirmation is only the client's unchanged echo of the
two refusal arrays; no token, digest, version receipt, or server-side confirmation state
@@ -1155,7 +1164,7 @@ exists.
| Decision | `force` | Recomputed plan | Echoed refusal plan | HTTP/API result |
| --- | --- | --- | --- | --- |
-| `guard_decision.unforced_no_impact` | false | empty, including visible noninterrupting `route_replace` removals | absent or supplied; echo is inert | ordinary mutation success |
+| `guard_decision.unforced_no_impact` | false | empty, including visible noninterrupting nonempty-manual `route_replace` removals | absent or supplied; echo is inert | ordinary mutation success |
| `guard_decision.unforced_confirmation` | false | nonempty | absent or supplied; echo is inert | HTTP 409 `GuardRefusal` with the current plan |
| `guard_decision.forced_no_impact` | true | empty | absent, exact, or stale | ordinary mutation success; `force` and any echo are inert because no guarded impact remains |
| `guard_decision.forced_confirmed` | true | nonempty | both arrays exactly equal the recomputed plan | commit once and return the matrix row's success envelope |
@@ -1192,8 +1201,8 @@ present even when empty.
| `mutation.model_efforts` | replace one model entry's capability list | `PATCH /api/models/sources/<source_id>/models/<model_id>` with `{reasoning_efforts}` | not guarded: it changes no `id`, `origin`, or Route | `{source: Source}` |
| `mutation.model_delete` | retire a discovered pair or remove manual matching evidence | `DELETE /api/models/sources/<source_id>/models/<model_id>` with `{force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` | same guarded `409`; recompute effective impact after retirement or evidence removal; manual deletion preserves explicit hops | same Source success envelope; discovered success preserves the row with `retired: true`, manual success removes it |
| `mutation.source_delete` | delete Source | `DELETE /api/models/sources/<id>?force=<bool>` with body `{would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` | same guarded `409`; a nonempty recomputed plan commits only when both arrays exactly match | `{removed_hops: RouteHopRef[], interrupted: SupplyGap[]}` after atomically pruning the Source from every backend Source order and every Route chain while preserving each survivor order; the deleted Source is not returned and legacy `{ok}` is invalid |
-| `mutation.route_replace` | replace one model's complete Route chain | `PUT /api/models/agents/<backend>/chain?model=<id>` with `{hops: RouteHop[], force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` | only when `would_interrupt` is nonempty: `source_last_supplier` in the same guarded `409`, including all submitted removals; noninterrupting removal is ordinary success because it is the user's visible direct edit | `{chain: AgentChain, removed_hops: RouteHopRef[], interrupted: SupplyGap[]}`; noninterrupting removal needs no wire confirmation, and survivor order is the submitted order |
-| `mutation.route_restore` | restore automatic for one model | `DELETE /api/models/agents/<backend>/chain?model=<id>` with optional `{force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` | same guarded `409` for actual effective removal or protected-supply loss | `{chain: AgentChain, removed_hops: RouteHopRef[], interrupted: SupplyGap[]}`; absent key is idempotent |
+| `mutation.route_replace` | save one model's nonempty manual override | `PUT /api/models/agents/<backend>/chain?model=<id>` with `{hops: RouteHop[], force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` and nonempty `hops`; accepted empty input instead uses `mutation.route_restore` | only for this nonempty manual write, when `would_interrupt` is nonempty: `source_last_supplier` in the same guarded `409`, including all submitted removals; noninterrupting removal is ordinary success because it is the user's visible direct edit | `{chain: AgentChain, removed_hops: RouteHopRef[], interrupted: SupplyGap[]}`; noninterrupting removal needs no wire confirmation, and survivor order is the submitted nonempty order |
+| `mutation.route_restore` | restore inherited routing for one model | `DELETE /api/models/agents/<backend>/chain?model=<id>` with optional `{force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}`; an accepted empty-hop PUT on that same route is equivalent | same guarded `409` for actual effective removal or protected-supply loss, identically for DELETE and empty PUT | `{chain: AgentChain, removed_hops: RouteHopRef[], interrupted: SupplyGap[]}`; normalized absent key is idempotent; admission, leases and rollback are shared |
| `mutation.default_sources` | replace backend default membership/order | `PUT /api/models/agents/<backend>/sources` with `{order: string[], force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}`; compatibility `POST .../chains/reorder` accepts optional order and the same guards | same guarded `409` for effective removal or protected-supply loss; pure reorder needs none | `{agent: AgentSupply}`; preserve manual arrays; omitted reorder order returns current projection |
The request carrier shown in each row is the only one. The final `api.md`, server/client
@@ -1227,7 +1236,7 @@ still surfaces as 需处理 on the Models page, not as an appended turn message.
This promise needs an interface, not just a paragraph, so the frozen contract carries one:
`turn-provenance.schema.json`, existing GET `/api/models/turns/<turn_id>/provenance`,
and on-demand GET `/api/models/agents/<backend>/provenance?model=<id>`.
-The latter uses the standard v9 envelope and returns the latest persisted retained
+The latter uses the standard v10 envelope and returns the latest persisted retained
record matching backend/requested model, regardless of outcome, or null. It never
starts/syncs the engine or adds history to AgentChain. The existing
`BoundedProvenanceStore` remains the sole owner, with atomic writes and 500-record
@@ -1328,34 +1337,42 @@ write down, instead of invariants prose asks every implementer to respect.
### 4.6 Route intent storage and mutation
-The sparse `routes` map stores only manual overrides:
+The canonical sparse `routes` map stores only nonempty manual overrides:
```json
{
"sources": {"order": ["src_default01", "src_default02"]},
"routes": {
- "explicit-model": {"hops": [{"source_id": "src_default02", "model_id": "upstream-id"}]},
- "deliberately-empty": {"hops": []}
+ "explicit-model": {"hops": [{"source_id": "src_default02", "model_id": "upstream-id"}]}
}
}
```
Other model ids have no key and follow §4.2. Manual sources may be eligible Sources
-outside the default subset. Preserve every existing override and exact array, including
-empty, stale and dormant OpenCode entries; older supported config shapes use the safe
-loader and explicit historical intent where available, never inference from Source
-order. Unrelated config remains unchanged across compatibility loading and reload.
+outside the default subset. Preserve every nonempty override and exact array, including
+stale and dormant OpenCode entries. A legacy input such as `{"hops": []}` remains valid
+but normalizes to key absence, never a disabled model. Validate the original supported
+shape and identifiers before normalization; malformed values must not become automatic.
+Older shapes use the safe loader and explicit historical intent where available, never
+inference from Source order. Preserve catalog identities and unrelated config on load/save.
+The same pure planner treats valid empty values as absent even in directly built config.
GET chain and chains return effective hops with `manual_override` and `route_origin`.
-PUT chain always persists the submitted override. DELETE chain removes the key,
-recomputes defaults and is idempotent when absent. POST chain/preview requires
+PUT chain persists only a nonempty submitted override; an accepted empty array uses
+the same operation as DELETE, including exact guards, idempotency, admission, leases
+and synchronization rollback. DELETE removes the key and recomputes defaults.
+POST chain/preview requires
`{manual_override: null | {hops: RouteHop[]}}` and returns the same AgentChain read
envelope without persistence, events, engine startup/sync, credentials or upstream
-egress, even with runtime stopped. Empty effective chains have null origin; a present
-empty override is distinguished by `manual_override: {hops: []}`.
-
-Restore automatic changes the editor draft only. Undo restores the manual draft;
-Cancel writes nothing. Save sends DELETE for restored automatic or PUT for manual,
+egress, even with runtime stopped. Empty draft input is accepted and normalized to null.
+Output `manual_override` is nonempty or null; output `AgentSupply.routes` omits empty
+values. An actually empty inherited plan alone has null origin. Output-only `minItems: 1`
+must not reject empty PUT/preview inputs or supported old config before normalization.
+Reads are pure; the next ordinary save writes the normalized sparse map.
+
+Restore automatic or removing the final manual hop changes the draft to inherited and
+previews its actual target/origin. Undo restores the previous unsaved manual draft;
+Cancel writes nothing. Save sends DELETE for inherited intent or PUT for nonempty manual,
consumes the authoritative mutation envelope, retains failed drafts and follows the
existing exact-plan guard/reconciliation protocol. Sources PUT and compatibility
chains/reorder update defaults only, preserving manual arrays and using effective
@@ -1398,7 +1415,7 @@ A manual hop's differing model id is the mapping itself. Automatic native alias
matching is confined to §4.2's existing parser; API-key passthrough preserves the requested id.
All read and write wrappers expose the same GET/PUT/DELETE/preview operations and
server-authored fields. Historical TurnProvenance keeps its exact attempts and remains
-readable for released versions through 9 without requiring new route fields.
+readable for released versions through 10 without requiring new route fields.
### 4.7 Downstream — Agents
@@ -1774,7 +1791,8 @@ directions into questions that later lanes must answer before writing mechanical
- [ ] §4.3 executes the shared effective plan without changing its tier or membership;
live annotations and the non-persisted takeover view remain independent of origin.
- [ ] Sparse manual intent distinguishes key absence, equal-to-automatic explicit saves,
- and explicit empty overrides. Restore/Preview/Undo/Cancel/Save follow the frozen API.
+ and valid empty input normalized to inherited intent. Final-hop removal uses the
+ existing Restore/Preview/Undo/Cancel/Save/guard/Done flow and never saves empty Manual.
- [ ] §4.5 keeps state source-global, status live-derived, and every successful
takeover silent; `supply_status` is the sole backend-health line, and a no-runnable-
hop exhaustion never borrows takeover semantics; terminal in-turn errors plus
diff --git a/tests/e2e/test_model_hub_routing.py b/tests/e2e/test_model_hub_routing.py
index 0c1308ebd..81bc741af 100644
--- a/tests/e2e/test_model_hub_routing.py
+++ b/tests/e2e/test_model_hub_routing.py
@@ -264,6 +264,117 @@ def test_mh_routing_009_save_drains_active_stream_without_truncation_or_deadlock
asyncio.run(exercise(adapter, mock))
[email protected]("protocol", ["openai_responses", "openai_chat", "anthropic"])
[email protected]("legacy_empty", [False, True], ids=["absent", "legacy-empty"])
+def test_mh_routing_013_legacy_empty_inherits_matching_and_exact_passthrough_through_real_cpa(
+ tmp_path, monkeypatch, protocol, legacy_empty,
+):
+ """MH-ROUTING-013: empty and absent loaded routes share matching, passthrough and stable registration."""
+ async def exercise(adapter, mocks):
+ backend = {"openai_responses": "codex", "openai_chat": "opencode", "anthropic": "claude"}[protocol]
+ arranged, _, _, sources = _real_route_service(tmp_path, adapter, mocks, protocol, [], backend=backend)
+ config = arranged.store.load()
+ agent = config.agents[backend]
+ if backend == "opencode":
+ agent.models = [ModelHubBackendModelConfig(id=model, origin="manual", native_protocol="openai_responses")
+ for model in ("vendor/inherited-known", "vendor/inherited-unknown", "vendor/manual-control")]
+ agent.menu.checked = [item.id for item in agent.models]
+ known, unknown, manual_menu = [item.id for item in agent.models][:3]
+ manual_target = "vendor/unlisted-manual-control"
+ inventories = [["unrelated-inventory-model"], [known], []]
+ for item, upstream, inventory in zip(sources, mocks, inventories, strict=True):
+ item.models = [source_model(model) for model in inventory]
+ upstream.configure(protocol=protocol, models=[{"id": model} for model in inventory])
+ agent.sources.order = [sources[0].id, sources[1].id]
+ agent.routes = {manual_menu: ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(sources[2].id, manual_target),))}
+ payload = config.to_payload()
+ if legacy_empty:
+ payload["agents"][backend]["routes"].update({known: {"hops": []}, unknown: {"hops": []}})
+ persisted = tmp_path / "persisted-inheritance.json"
+ persisted.write_text(json.dumps(payload), encoding="utf-8")
+ original_bytes = persisted.read_bytes()
+ loaded = ModelHubConfig.from_payload(json.loads(original_bytes))
+ absent_payload = json.loads(original_bytes)
+ for model in (known, unknown):
+ absent_payload["agents"][backend]["routes"].pop(model, None)
+ assert loaded.to_payload() == ModelHubConfig.from_payload(absent_payload).to_payload()
+ assert known not in loaded.agents[backend].routes and unknown not in loaded.agents[backend].routes
+ manual = {"hops": [{"source_id": sources[2].id, "model_id": manual_target}]}
+ service = service_for(tmp_path, MemoryModelHubStore(loaded), adapter)
+ await service.runtime_start()
+ connection = adapter.supervisor.client_if_running().connection
+ config_path = next(adapter.state_store.root.glob("instances/*/config.yaml"))
+ engine_before = (config_path.read_bytes(), config_path.stat().st_mtime_ns)
+ registration = [adapter.state_store.get_source(item.id) for item in sources]
+ source_before = [item.to_payload() for item in service.store.load().sources]
+ catalog_before = service.store.load().agents[backend].to_payload()
+ gateway = ModelHubTurnGateway(service)
+ path = {"anthropic": "messages", "openai_responses": "responses", "openai_chat": "chat/completions"}[protocol]
+ evidence = []
+ try:
+ async with aiohttp.ClientSession(trust_env=False) as client:
+ for order in ([0, 1], [1, 0]):
+ ordered_ids = [sources[index].id for index in order]
+ if service.store.load().agents[backend].sources.order != ordered_ids:
+ await service.set_agent_sources(backend, {"order": ordered_ids})
+ for model, selected, target, origin in (
+ (known, 1, known, "automatic"),
+ (unknown, order[0], unknown, "passthrough"),
+ (manual_menu, 2, manual_target, "manual"),
+ ):
+ chain = service.agent_chain(backend, model)
+ assert chain["manual_override"] == (manual if origin == "manual" else None)
+ assert chain["route_origin"] == origin
+ expected_chain = ([(sources[index].id, unknown) for index in order] if origin == "passthrough"
+ else [(sources[selected].id, target)])
+ assert [(hop["source_id"], hop["model_id"]) for hop in chain["chain"]] == expected_chain
+ base_url, token = await gateway.endpoint(
+ backend, process_scope=f"{tmp_path}/{len(evidence)}", turn_id=f"turn_inherited_{len(evidence)}",
+ requested_model_id=model, resolved_model_id=target, source_id=sources[selected].id,
+ )
+ # Prepared Claude/Codex launches send the resolved target;
+ # OpenCode requests its menu id through the native overlay.
+ request = {"model": model if backend == "opencode" else target, "stream": False}
+ prompt = "Inherited exact route: \u4e2d\u6587"
+ if protocol == "openai_responses":
+ request["input"] = prompt
+ else:
+ request.update(max_tokens=32, messages=[{"role": "user", "content": prompt}])
+ for upstream in mocks:
+ upstream.reset_requests()
+ async with client.post(f"{base_url}/v1/{path}", json=request,
+ headers={"Authorization": f"Bearer {token}"}) as response:
+ raw = await asyncio.wait_for(response.read(), timeout=15)
+ assert response.status == 200, raw
+ assert b"mock response" in raw
+ received = [row for row in mocks[selected].requests() if row["path"] == f"/v1/{path}"]
+ assert len(received) == 1
+ assert received[0]["body"]["model"] == target
+ assert _request_credential(received[0]) == f"sk-synthetic-gateway-{selected}"
+ assert prompt in json.dumps(received[0]["body"], ensure_ascii=False)
+ assert not [row for index, upstream in enumerate(mocks) if index != selected
+ for row in upstream.requests() if row["method"] == "POST"]
+ assert [item.to_payload() for item in service.store.load().sources] == source_before
+ assert [adapter.state_store.get_source(item.id) for item in sources] == registration
+ assert [adapter.state_store.get_source(item.id).model_ids for item in sources] == [tuple(value) for value in inventories]
+ assert (config_path.read_bytes(), config_path.stat().st_mtime_ns) == engine_before
+ assert adapter.supervisor.client_if_running().connection == connection
+ actual_agent = service.store.load().agents[backend].to_payload()
+ assert actual_agent == {**catalog_before, "sources": {"order": ordered_ids}}
+ assert persisted.read_bytes() == original_bytes
+ evidence.append({"requested_model": model, "gateway_model": request["model"], "source_id": sources[selected].id,
+ "route_origin": origin, "default_order": ordered_ids,
+ "received": {"path": received[0]["path"], "model": received[0]["body"]["model"],
+ "synthetic_key": _request_credential(received[0])}})
+ finally:
+ await gateway.close()
+ (tmp_path / "received-inherited-routes.json").write_text(json.dumps(evidence, indent=2), encoding="utf-8")
+
+ with MockLLMUpstream() as first, MockLLMUpstream() as second, MockLLMUpstream() as outside, \
+ _isolated_engine_adapter(tmp_path, monkeypatch) as adapter:
+ asyncio.run(exercise(adapter, [first, second, outside]))
+
+
@pytest.mark.parametrize("protocol", ["openai_responses", "openai_chat", "anthropic"])
def test_mh_routing_010_model_not_found_stays_request_scoped_through_real_gateway_cpa(tmp_path, monkeypatch, protocol):
"""MH-ROUTING-010: an unlisted-model error does not poison source health or retry another source."""
diff --git a/tests/e2e/test_model_hub_runtime.py b/tests/e2e/test_model_hub_runtime.py
index 8c1404ca7..e2b4a8a59 100644
--- a/tests/e2e/test_model_hub_runtime.py
+++ b/tests/e2e/test_model_hub_runtime.py
@@ -643,7 +643,7 @@ def test_a1_feature_flag_disables_the_complete_models_api(
assert response.status == 404, (method, path, body)
assert body == {
"ok": False,
- "contract_version": 9,
+ "contract_version": 10,
"error": "feature_disabled",
}
diff --git a/tests/e2e/test_model_hub_sources.py b/tests/e2e/test_model_hub_sources.py
index f565d4d97..dedc15da2 100644
--- a/tests/e2e/test_model_hub_sources.py
+++ b/tests/e2e/test_model_hub_sources.py
@@ -13,7 +13,7 @@ from tests.e2e.drivers.mock_llm_upstream import MockLLMUpstream
pytestmark = pytest.mark.e2e_model_hub
-CONTRACT_VERSION = 9
+CONTRACT_VERSION = 10
MENU_MODEL = "claude-sonnet-4-6"
SYNTHETIC_API_KEY = "sk-model-hub-e2e-not-real"
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 2d7a20d9d..0455f0a85 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -162,7 +162,7 @@ scenarios:
layer: scenario
test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_routing_002_match_tier_precedes_passthrough_and_health_never_changes_membership
- id: MH-ROUTING-003
- name: Manual unknown and empty targets survive refresh, default reorder, and reload
+ name: Nonempty manual targets persist while absent and legacy-empty routes inherit current defaults through refresh and reload
status: covered
kind: persistence
layer: scenario
@@ -209,6 +209,12 @@ scenarios:
kind: compatibility
layer: e2e
test: tests/e2e/test_model_hub_routing.py::test_mh_routing_012_persisted_dormant_opencode_override_reaches_exact_source_and_target
+ - id: MH-ROUTING-013
+ name: Legacy-empty and absent routes inherit matching and exact passthrough through pinned CPA without changing nonempty manual intent or registration per request
+ status: assert
+ kind: compatibility
+ layer: e2e
+ test: tests/e2e/test_model_hub_routing.py::test_mh_routing_013_legacy_empty_inherits_matching_and_exact_passthrough_through_real_cpa
- id: MH-PROTOCOL-001
name: Source protocol is response-observed before persistence with no transient residue
status: covered
diff --git a/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py b/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
index ed2b45f78..73adf407d 100644
--- a/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
@@ -70,14 +70,15 @@ def _routing_config(backend, sources, *, manual=None):
@pytest.mark.parametrize("backend", ["claude", "codex", "opencode"])
@pytest.mark.parametrize("inventory", [[], ["unrelated-inventory-model"]], ids=["empty", "incomplete"])
[email protected]("override", [None, []], ids=["absent-route", "legacy-empty-route"])
def test_mh_routing_002_match_tier_precedes_passthrough_and_health_never_changes_membership(
- tmp_path, backend, inventory,
+ tmp_path, backend, inventory, override,
):
"""MH-ROUTING-002: inventory evidence selects the tier; health only annotates its ordered members."""
first = source("src_routefirst", inventory)
second = source("src_routesecond", inventory)
outside = source("src_routeoutside", [])
- config, model = _routing_config(backend, [first, second, outside])
+ config, model = _routing_config(backend, [first, second, outside], manual=override)
outside.models = [source_model(model)]
config.agents[backend].sources.order = [second.id, first.id]
store = MemoryModelHubStore(config)
@@ -104,30 +105,40 @@ def test_mh_routing_002_match_tier_precedes_passthrough_and_health_never_changes
@pytest.mark.parametrize("backend", ["claude", "codex", "opencode"])
[email protected]("empty", [False, True], ids=["unknown-target", "explicit-empty"])
-def test_mh_routing_003_manual_intent_survives_refresh_default_reorder_and_reload(tmp_path, backend, empty):
- """MH-ROUTING-003: manual targets, including empty overrides, survive unrelated configuration changes."""
[email protected]("intent", ["manual", "absent", "legacy-empty"])
+def test_mh_routing_003_manual_intent_survives_refresh_default_reorder_and_reload(tmp_path, backend, intent):
+ """MH-ROUTING-003: nonempty manual targets persist; absent and empty routes inherit current defaults."""
first = source("src_manualfirst", ["listed-only"])
second = source("src_manualsecond", ["listed-only"])
- manual = [] if empty else [(first.id, "vendor/unlisted-original")]
+ manual = {"manual": [(first.id, "vendor/unlisted-original")], "absent": None, "legacy-empty": []}[intent]
config, model = _routing_config(backend, [first, second], manual=manual)
store = MemoryModelHubStore(config)
adapter = ModelHubScenarioAdapter(refresh_models=("new-discovered-model",))
service = service_for(tmp_path, store, adapter)
- original = config.agents[backend].routes[model].to_payload()
+ original = {"hops": [{"source_id": first.id, "model_id": "vendor/unlisted-original"}]} if intent == "manual" else None
asyncio.run(service.refresh_source(first.id))
asyncio.run(service.set_agent_sources(backend, {"order": [second.id, first.id]}))
+ reordered = service.agent_chain(backend, model)
+ assert reordered["manual_override"] == original
+ assert [(hop["source_id"], hop["model_id"]) for hop in reordered["chain"]] == (
+ manual if intent == "manual" else [(second.id, model), (first.id, model)]
+ )
asyncio.run(service.reorder_agent_chains(backend, [first.id, second.id]))
reloaded = service_for(tmp_path / "reload", MemoryModelHubStore(round_trip(store.load())), adapter)
chain = reloaded.agent_chain(backend, model)
assert chain["manual_override"] == original
- assert chain["route_origin"] == (None if empty else "manual")
- assert [(hop["source_id"], hop["model_id"]) for hop in chain["chain"]] == manual
+ assert chain["route_origin"] == ("manual" if intent == "manual" else "passthrough")
+ assert [(hop["source_id"], hop["model_id"]) for hop in chain["chain"]] == (
+ manual if intent == "manual" else [(first.id, model), (second.id, model)]
+ )
+ if intent != "manual":
+ assert model not in round_trip(store.load()).agents[backend].routes
assert [item.id for item in store.load().sources[0].models] == ["new-discovered-model"]
@pytest.mark.parametrize("backend", ["claude", "codex", "opencode"])
-def test_mh_routing_004_preview_cancel_undo_are_inert_and_restore_deletes_only_override(tmp_path, backend, monkeypatch):
[email protected]("operation", ["delete", "empty-put"])
+def test_mh_routing_004_preview_cancel_undo_are_inert_and_restore_deletes_only_override(tmp_path, backend, monkeypatch, operation):
"""MH-ROUTING-004: draft restore is read-only; committed restore removes the override idempotently."""
first = source("src_restorefirst", [])
config, model = _routing_config(backend, [first], manual=[(first.id, "vendor/manual-target")])
@@ -142,6 +153,7 @@ def test_mh_routing_004_preview_cancel_undo_are_inert_and_restore_deletes_only_o
monkeypatch.setattr(adapter, "start", forbidden_start)
before_events = service.events.list()
preview = service.preview_agent_chain(backend, model, {"manual_override": None})
+ assert service.preview_agent_chain(backend, model, {"manual_override": {"hops": []}}) == preview
assert preview["manual_override"] is None
assert preview["route_origin"] == "passthrough"
assert [(hop["source_id"], hop["model_id"]) for hop in preview["chain"]] == [(first.id, model)]
@@ -153,14 +165,24 @@ def test_mh_routing_004_preview_cancel_undo_are_inert_and_restore_deletes_only_o
assert store.saved_payloads == adapter.synced == adapter.invocations == []
assert service.events.list() == before_events
+ async def restore(payload=None):
+ if operation == "empty-put":
+ return await service.set_agent_chain(backend, model, {"hops": [], **(payload or {})})
+ return await service.delete_agent_chain(backend, model, payload)
+
with pytest.raises(ModelHubError) as refused:
- asyncio.run(service.delete_agent_chain(backend, model))
+ asyncio.run(restore())
+ assert refused.value.code == "source_in_route_chain"
+ assert refused.value.data == {"would_remove_hops": [{
+ "backend": backend, "menu_model": model, "source_id": first.id,
+ "model_id": "vendor/manual-target", "position": 1,
+ }], "would_interrupt": []}
assert store.load().to_payload() == original
- restored = asyncio.run(service.delete_agent_chain(backend, model, {"force": True, **refused.value.data}))
+ restored = asyncio.run(restore({"force": True, **refused.value.data}))
assert restored["chain"]["manual_override"] is None
assert restored["chain"]["route_origin"] == "passthrough"
assert model not in round_trip(store.load()).agents[backend].routes
- repeated = asyncio.run(service.delete_agent_chain(backend, model))
+ repeated = asyncio.run(restore())
assert repeated["chain"]["manual_override"] is None
assert repeated["removed_hops"] == repeated["interrupted"] == []
@@ -443,8 +465,9 @@ def test_mh_menu_add_001_seeds_overlapping_suppliers_in_source_order(
assert after["agents"]["opencode"] == before["agents"]["opencode"]
[email protected]("last_manual_hop", [False, True], ids=["nonempty-survivors", "inherit-after-last-hop"])
def test_mh_source_delete_001_removes_every_reference_and_preserves_survivor_order(
- tmp_path: Path,
+ tmp_path: Path, last_manual_hop: bool,
) -> None:
"""MH-SRC-DELETE-001: source deletion is one transaction across all backend orders and chains."""
@@ -459,7 +482,7 @@ def test_mh_source_delete_001_removes_every_reference_and_preserves_survivor_ord
[first, doomed, last],
backend="claude",
menu_model=claude_model,
- hops=[
+ hops=[(doomed.id, claude_model)] if last_manual_hop else [
(first.id, claude_model),
(doomed.id, claude_model),
(last.id, claude_model),
@@ -479,7 +502,8 @@ def test_mh_source_delete_001_removes_every_reference_and_preserves_survivor_ord
)
]
agent.routes[menu_model] = ModelHubRouteConfig(
- hops=tuple(ModelHubRouteHopConfig(item.id, upstream_model) for item in (first, doomed, last))
+ hops=tuple(ModelHubRouteHopConfig(item.id, upstream_model)
+ for item in ((doomed,) if last_manual_hop else (first, doomed, last)))
)
store = MemoryModelHubStore(config)
adapter = ModelHubScenarioAdapter()
@@ -505,7 +529,15 @@ def test_mh_source_delete_001_removes_every_reference_and_preserves_survivor_ord
("opencode", opencode_model),
):
assert doomed.id not in store.load().agents[backend].sources.order
- assert [hop.source_id for hop in store.load().agents[backend].routes[menu_model].hops] == [first.id, last.id]
+ chain = service.agent_chain(backend, menu_model)
+ assert [hop["source_id"] for hop in chain["chain"]] == [first.id, last.id]
+ if last_manual_hop:
+ assert menu_model not in store.load().agents[backend].routes
+ assert chain["manual_override"] is None
+ assert chain["route_origin"] == "automatic"
+ else:
+ assert [hop.source_id for hop in store.load().agents[backend].routes[menu_model].hops] == [first.id, last.id]
+ assert chain["route_origin"] == "manual"
assert round_trip(store.load()).to_payload() == store.load().to_payload()
assert adapter.revoked == [doomed.credential_ref]
@@ -765,7 +797,11 @@ def test_mh_ac29_001_persisted_source_payload_round_trips_through_the_canonical_
assert persisted_sources == response_sources
assert store.saved_payloads
assert reloaded.to_payload() == store.load().to_payload()
- assert set(_route_pairs(reloaded, "claude", menu_model)) == {
+ assert menu_model not in reloaded.agents["claude"].routes
+ inherited = service_for(tmp_path, MemoryModelHubStore(reloaded), adapter).agent_chain("claude", menu_model)
+ assert inherited["manual_override"] is None
+ assert inherited["route_origin"] == "automatic"
+ assert {(hop["source_id"], hop["model_id"]) for hop in inherited["chain"]} == {
(position["source_id"], position["model_id"])
for position in result["added_to"]
if position["backend"] == "claude" and position["menu_model"] == menu_model
diff --git a/tests/test_model_hub_admission.py b/tests/test_model_hub_admission.py
index 2b2a92278..2958c1204 100644
--- a/tests/test_model_hub_admission.py
+++ b/tests/test_model_hub_admission.py
@@ -50,7 +50,7 @@ def _gate_method(owner, name, *, call_number=1):
@pytest.mark.parametrize("probe", [False, True])
[email protected]("change", ["target", "source", "empty"])
[email protected]("change", ["target", "source", "empty", "no_defaults"])
def test_demand_snapshot_is_revalidated_before_transport_and_observer(tmp_path, probe, change):
async def run():
source = _source("src_race0001", ())
@@ -71,8 +71,13 @@ def test_demand_snapshot_is_revalidated_before_transport_and_observer(tmp_path,
elif change == "source":
await service.patch_source(source.id, {"display_name": "Changed source"})
expected = MODEL
- else:
+ elif change == "empty":
await _save_route(service, [])
+ expected = MODEL
+ else:
+ with pytest.raises(ModelHubError) as refusal:
+ await service.set_agent_sources("claude", {"order": []})
+ await service.set_agent_sources("claude", {"order": [], "force": True, **refusal.value.data})
expected = None
adapter.outcomes.append(_outcome(source, expected or MODEL))
release.set()
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index edd4de741..19f4524a2 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -917,7 +917,7 @@ def test_runtime_start_is_explicit_and_returns_v4_status(tmp_path):
assert adapter.start_calls == 1
assert store.config.enabled is True
assert runtime["enabled"] is True
- assert runtime["contract_version"] == 9
+ assert runtime["contract_version"] == 10
assert runtime["status"]["health"] == "ok"
_assert_valid("runtime-dependency.schema.json", runtime)
@@ -1137,7 +1137,7 @@ def test_runtime_start_crosses_the_controller_rpc_boundary(monkeypatch):
async def rpc(operation, payload=None):
calls.append((operation, payload))
- return {"contract_version": 9, "status": {"health": "ok"}}
+ return {"contract_version": 10, "status": {"health": "ok"}}
monkeypatch.setattr(model_hub_client, "_rpc", rpc)
@@ -1154,7 +1154,7 @@ def test_runtime_stop_crosses_the_controller_rpc_boundary(monkeypatch):
async def rpc(operation, payload=None):
calls.append((operation, payload))
- return {"contract_version": 9, "status": {"health": "not_started"}}
+ return {"contract_version": 10, "status": {"health": "not_started"}}
monkeypatch.setattr(model_hub_client, "_rpc", rpc)
@@ -1171,7 +1171,7 @@ def test_runtime_install_crosses_the_controller_rpc_boundary(monkeypatch):
async def rpc(operation, payload=None):
calls.append((operation, payload))
- return {"contract_version": 9, "status": {"health": "installing"}}
+ return {"contract_version": 10, "status": {"health": "installing"}}
monkeypatch.setattr(model_hub_client, "_rpc", rpc)
@@ -1189,7 +1189,7 @@ def test_runtime_dependency_ensure_crosses_the_controller_rpc_boundary(monkeypat
def rpc(operation, payload=None):
calls.append((operation, payload))
return {
- "contract_version": 9,
+ "contract_version": 10,
"changed": True,
"status": {"health": "not_started", "verified": True},
}
@@ -1223,7 +1223,8 @@ def test_reorder_client_preserves_explicit_null_order(monkeypatch):
assert calls == [("reorder_agent_chains", {"backend": "claude", "order": None})]
-def test_preview_and_restore_cross_client_and_controller_without_preview_sync(monkeypatch, tmp_path):
[email protected]("empty_input", [False, True])
+def test_preview_and_restore_cross_client_and_controller_without_preview_sync(monkeypatch, tmp_path, empty_input):
from core.handlers.model_hub.rpc import dispatch_model_hub_rpc
from vibe import model_hub_client
@@ -1241,22 +1242,29 @@ def test_preview_and_restore_cross_client_and_controller_without_preview_sync(mo
monkeypatch.setattr(model_hub_client, "_rpc", rpc)
monkeypatch.setattr(model_hub_client, "_rpc_sync", lambda operation, payload=None: asyncio.run(rpc(operation, payload)))
remote = ModelHubRemoteService()
- draft = remote.preview_agent_chain("claude", model_id, {"manual_override": None})
+ override = {"hops": []} if empty_input else None
+ draft = remote.preview_agent_chain("claude", model_id, {"manual_override": override})
assert draft["route_origin"] == "automatic"
assert draft["manual_override"] is None
assert store.config.to_payload() == before
assert adapter.synced == []
- restored = asyncio.run(remote.delete_agent_chain("claude", model_id))
+ restored = asyncio.run(
+ remote.set_agent_chain("claude", model_id, {"hops": []})
+ if empty_input else remote.delete_agent_chain("claude", model_id)
+ )
assert restored["chain"] == draft
assert model_id not in store.config.agents["claude"].routes
assert calls == [
- ("preview_agent_chain", {"backend": "claude", "model_id": model_id, "chain": {"manual_override": None}}),
- ("delete_agent_chain", {"backend": "claude", "model_id": model_id, "chain": None}),
+ ("preview_agent_chain", {"backend": "claude", "model_id": model_id, "chain": {"manual_override": override}}),
+ ("set_agent_chain" if empty_input else "delete_agent_chain", {
+ "backend": "claude", "model_id": model_id, "chain": override,
+ }),
]
-def test_chain_preview_is_read_only_and_restore_accepts_no_http_body(monkeypatch, tmp_path):
[email protected]("empty_input", [False, True])
+def test_chain_preview_is_read_only_and_restore_accepts_no_http_body(monkeypatch, tmp_path, empty_input):
service, store, adapter = _service(tmp_path)
model_id = "claude-opus-4-6"
_set_claude_route_fixture(store, ("src_http0001",), model_id)
@@ -1268,7 +1276,7 @@ def test_chain_preview_is_read_only_and_restore_accepts_no_http_body(monkeypatch
headers = csrf_headers(client, origin)
response = client.post(
f"/api/models/agents/claude/chain/preview?model={model_id}",
- json={"manual_override": None}, headers=headers, base_url=origin,
+ json={"manual_override": {"hops": []} if empty_input else None}, headers=headers, base_url=origin,
)
assert response.status_code == 200
draft = response.get_json()["chain"]
@@ -1276,8 +1284,10 @@ def test_chain_preview_is_read_only_and_restore_accepts_no_http_body(monkeypatch
assert draft["route_origin"] == "automatic"
assert store.config.to_payload() == before
assert adapter.synced == []
- restored = client.delete(
- f"/api/models/agents/claude/chain?model={model_id}", headers=headers, base_url=origin,
+ endpoint = f"/api/models/agents/claude/chain?model={model_id}"
+ restored = (
+ client.put(endpoint, json={"hops": []}, headers=headers, base_url=origin)
+ if empty_input else client.delete(endpoint, headers=headers, base_url=origin)
)
assert restored.status_code == 200
assert restored.get_json()["chain"] == draft
@@ -3148,7 +3158,7 @@ def test_backend_catalog_mutations_leave_every_unrelated_model_shape_byte_identi
"models": [
model.to_payload() for model in store.config.agents["codex"].models if model.id.startswith("shape-")
],
- "routes": {model.id: store.config.agents["codex"].routes[model.id].to_payload() for model in seeded},
+ "routes": store.config.agents["codex"].to_payload()["routes"],
"sources": [source.to_payload() for source in store.config.sources],
"source_order": store.config.agents["codex"].sources.to_payload(),
"other_agents": {
@@ -3726,14 +3736,15 @@ def test_agent_chains_returns_the_complete_overview_from_one_snapshot(tmp_path):
agent = store.config.agents["claude"]
routed_extra = "claude-route-only"
selected_extra = "claude-selected-only"
- agent.routes[routed_extra] = ModelHubRouteConfig()
+ agent.routes[routed_extra] = ModelHubRouteConfig(hops=(ModelHubRouteHopConfig("src_snapshot01", "exact"),))
+ agent.routes["empty-route-only"] = ModelHubRouteConfig()
store.requested_models["claude"] = selected_extra
expected_model_ids = list(
dict.fromkeys(
[
*service.get_agent_sources("claude")["builtin_models"],
selected_extra,
- *agent.routes,
+ routed_extra,
]
)
)
@@ -3754,6 +3765,7 @@ def test_agent_chains_returns_the_complete_overview_from_one_snapshot(tmp_path):
assert model_ids == expected_model_ids
assert selected_extra in model_ids
assert routed_extra in model_ids
+ assert "empty-route-only" not in model_ids
assert len(model_ids) == len(set(model_ids))
for chain in chains:
_assert_valid("agent-chain.schema.json", chain)
@@ -3982,7 +3994,7 @@ def test_agent_models_route_returns_only_picker_catalog_fields(monkeypatch):
assert response.status_code == 200
assert response.get_json() == {
"ok": True,
- "contract_version": 9,
+ "contract_version": 10,
"agent": {
"backend": "codex",
"mode": "hub",
@@ -5385,6 +5397,7 @@ def test_chain_route_guard_requires_and_replays_the_exact_current_plan(monkeypat
(first_id, second_id),
model_id,
)
+ store.config.agents["claude"].sources.order = []
monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)
client = app.test_client()
base_url = "http://127.0.0.1:15131"
@@ -5462,7 +5475,7 @@ def test_chain_route_guard_requires_and_replays_the_exact_current_plan(monkeypat
refusal["would_interrupt"], separators=(",", ":")
)
assert success["chain"]["chain"] == []
- assert store.config.agents["claude"].routes[model_id].hops == ()
+ assert model_id not in store.config.agents["claude"].routes
def test_chain_route_noninterrupting_success_is_force_invariant(monkeypatch, tmp_path):
@@ -5510,7 +5523,7 @@ def test_chain_route_noninterrupting_success_is_force_invariant(monkeypatch, tmp
]
-def test_delete_guard_reports_only_routes_emptied_by_this_mutation(tmp_path):
+def test_delete_guard_includes_all_newly_unsupplied_inherited_routes(tmp_path):
service, store, _ = _service(tmp_path)
source = ModelHubSourceConfig(
id="src_guard0001",
@@ -5545,9 +5558,10 @@ def test_delete_guard_reports_only_routes_emptied_by_this_mutation(tmp_path):
assert exc_info.value.data["would_interrupt"] == [
{
"backend": "claude",
- "model_id": "claude-opus-4-6",
+ "model_id": model.id,
"agents": [],
}
+ for model in claude.models
]
@@ -8155,7 +8169,7 @@ def test_runtime_start_route_requires_csrf_before_starting_engine(monkeypatch, t
assert accepted.status_code == 200
runtime = accepted.get_json()["runtime"]
assert adapter.start_calls == 1
- assert runtime["contract_version"] == 9
+ assert runtime["contract_version"] == 10
_assert_valid("runtime-dependency.schema.json", runtime)
diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.py
index a11eab7df..c8adef7c9 100644
--- a/tests/test_model_hub_config.py
+++ b/tests/test_model_hub_config.py
@@ -106,7 +106,7 @@ def test_protocol_vocabulary_matches_authority_and_rejects_removed_alias():
def test_unsaved_observation_schema_closes_all_terminal_shapes():
schema = _schema("observation-result.schema.json")
- assert schema["properties"]["contract_version"]["const"] == 9
+ assert schema["properties"]["contract_version"]["const"] == 10
assert tuple(schema["properties"]["outcome"]["enum"]) == tuple(
member.value for member in ObservationOutcome
)
@@ -130,7 +130,7 @@ def test_observation_terminal_authority_and_schema_accept_the_same_products():
def payload(observation: SourceObservation) -> dict:
return {
- "contract_version": 9,
+ "contract_version": 10,
"outcome": observation.outcome.value,
"reachable": observation.reachable,
"authenticated": (
@@ -653,10 +653,10 @@ def test_source_create_unavailable_inventory_consent_is_explicit_and_total():
def test_sparse_override_contract_has_one_default_order_owner():
contract = (CONTRACTS.parent / "model-hub-routing-modes.md").read_text(encoding="utf-8")
assert "sources.order` is the sole backend-default" in contract
- assert "Key absence means automatic" in contract
+ assert "Key absence or an empty hop array means inherited routing" in contract
assert "Restoring automatic deletes the key" in contract
assert "Never reorder manual arrays" in contract
- assert "no inference from array equality" in contract
+ assert "inference from nonempty array equality" in contract
def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():
@@ -685,7 +685,7 @@ def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():
route_refusal = {
"ok": False,
- "contract_version": 9,
+ "contract_version": 10,
"error": "source_in_route_chain",
"detail": "modelHub.errors.source_in_route_chain",
"would_remove_hops": [hop],
@@ -701,7 +701,7 @@ def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():
}
candidate_refusal = {
"ok": False,
- "contract_version": 9,
+ "contract_version": 10,
"error": "candidate_suppliers_changed",
"detail": "modelHub.errors.candidate_suppliers_changed",
"changed": {
@@ -783,7 +783,7 @@ def test_v8_mirror_registry_is_executable_and_complete():
registry = json.loads((CONTRACTS / "mirror-registry.json").read_text(encoding="utf-8"))
schemas = _mirror_schemas(registry)
- assert registry["contract_version"] == 9
+ assert registry["contract_version"] == 10
ids = [entry["id"] for entry in registry["entries"]]
assert ids
assert len(ids) == len(set(ids))
@@ -1015,8 +1015,8 @@ def test_model_hub_authority_closure_anchors_the_persisted_version_floor(monkeyp
"kind": "contract_version_schema_drift",
"domain": "V1",
"file": "docs/plans/model-hub-contracts/turn-provenance.schema.json",
- "values": [6, 7, 8, 9],
- "expected": [5, 6, 7, 8, 9],
+ "values": [6, 7, 8, 9, 10],
+ "expected": [5, 6, 7, 8, 9, 10],
} in result["findings"]
@@ -1309,7 +1309,7 @@ def test_v5_shape_amendments_reject_the_false_states_they_replace():
with pytest.raises(ValidationError):
chain_validator.validate(interrupted)
exact_hop = {
- "contract_version": 9,
+ "contract_version": 10,
"backend": "claude",
"model_id": "claude-opus-4-6",
"manual_override": None,
@@ -2245,7 +2245,7 @@ def test_config_reload_allows_empty_target_on_disabled_legacy_mapping(monkeypatc
loaded = V2Config.load(config_path=config_path)
assert loaded.load_warnings == ()
- assert loaded.model_hub.agents["claude"].routes["opus"].hops == ()
+ assert "opus" not in loaded.model_hub.agents["claude"].routes
def test_invalid_json_recovery_backs_up_the_original_snapshot(monkeypatch, tmp_path):
@@ -3014,7 +3014,7 @@ def test_persisted_hub_config_requires_sparse_override_object():
dormant["agents"]["opencode"]["routes"]["dormant-model"] = {"hops": []}
restored = ModelHubConfig.from_payload(dormant)
assert restored.agents["opencode"].models == []
- assert "dormant-model" in restored.agents["opencode"].routes
+ assert restored.agents["opencode"].routes == {}
def test_backend_model_modalities_match_the_contract_directions():
@@ -3043,12 +3043,52 @@ def test_config_reload_preserves_legacy_routes_without_seeding_missing_models(tm
migrated_routes = loaded.model_hub.agents["claude"].routes
migrated_models = loaded.model_hub.agents["claude"].models
- assert set(migrated_routes) == ({*original_ids, stale_id} - {removed_id})
+ assert migrated_routes == {}
assert removed_id not in migrated_routes
- assert migrated_routes[stale_id].hops == ()
+ assert {*original_ids, stale_id} <= {model.id for model in migrated_models}
assert next(model for model in migrated_models if model.id == stale_id).origin == "manual"
[email protected]("backend", ["claude", "codex", "opencode"])
+def test_v2_empty_route_normalizes_on_load_without_writing_until_save(tmp_path, backend):
+ from tests.test_model_hub_routing_modes import MODEL, _loaded_catalog_config
+ from tests.test_model_hub_resolution import _source
+
+ payload = api.config_to_payload(default_config())
+ payload["model_hub"] = _loaded_catalog_config(backend, MODEL, _source("src_v2empty01", (MODEL,))).to_payload()
+ payload["model_hub"]["agents"][backend]["routes"][MODEL] = {"hops": []}
+ path = tmp_path / "config.json"
+ path.write_text(json.dumps(payload), encoding="utf-8")
+ before = path.read_bytes()
+ loaded = V2Config.load(config_path=path)
+ assert loaded.load_warnings == ()
+ assert loaded.model_hub.agents[backend].routes == {}
+ assert path.read_bytes() == before
+ assert list(tmp_path.glob("config.json.bak-*")) == []
+ loaded.save(config_path=path)
+ expected = copy.deepcopy(payload["model_hub"])
+ expected["agents"][backend]["routes"] = {}
+ assert json.loads(path.read_text())["model_hub"] == expected
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
[email protected]("bad_key", ["", "authorization=sk-unsafe-fixture"])
+def test_invalid_empty_route_key_keeps_v2_recovery_fence(tmp_path, backend, bad_key):
+ payload = api.config_to_payload(default_config())
+ payload["model_hub"]["agents"][backend]["routes"][bad_key] = {"hops": []}
+ path = tmp_path / "config.json"
+ path.write_text(json.dumps(payload), encoding="utf-8")
+ before = path.read_bytes()
+ loaded = V2Config.load(config_path=path)
+ assert loaded.load_warnings
+ assert "model_hub" in loaded.recovered_sections
+ assert loaded.model_hub.sources == []
+ assert all(agent.mode == "direct" for agent in loaded.model_hub.agents.values())
+ assert path.read_bytes() == before
+ with pytest.raises(ValueError, match="recovery warnings"):
+ loaded.save(config_path=path)
+
+
@pytest.mark.parametrize(
("status", "retry_at", "detail_key"),
[
diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.py
index 62f0b8451..0cdef649b 100644
--- a/tests/test_model_hub_l3.py
+++ b/tests/test_model_hub_l3.py
@@ -5577,6 +5577,7 @@ def test_opencode_overlay_partitions_every_row_by_native_protocol(tmp_path: Path
assert {launch.target_model for launch in overlay.launches} == {
"first-model",
"second-model",
+ "empty-route-model",
}
@@ -6444,7 +6445,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(
_assert_valid(
"observation-result.schema.json",
{
- "contract_version": 9,
+ "contract_version": 10,
"outcome": "adapter_error",
"reachable": True,
"authenticated": "unknown",
@@ -8570,7 +8571,7 @@ def test_native_chain_visibility_and_probe_readiness(tmp_path: Path) -> None:
probe = asyncio.run(service.probe_agent("codex", "shared-model"))
assert probe == {
- "contract_version": 9,
+ "contract_version": 10,
"backend": "codex",
"channel": "native_cli",
"reachable": True,
diff --git a/tests/test_model_hub_provenance.py b/tests/test_model_hub_provenance.py
index b0c768d23..8f91fac2a 100644
--- a/tests/test_model_hub_provenance.py
+++ b/tests/test_model_hub_provenance.py
@@ -22,7 +22,7 @@ from vibe import model_hub_client, ui_server
def _record(turn_id, *, backend="claude", model=MODEL, outcome="failed_terminal"):
identity = {"source_id": "src_deleted01", "configured_model_id": "unknown-model", "channel": "hub"}
return {
- "contract_version": 9,
+ "contract_version": 10,
"turn_id": turn_id,
"ts": "2026-09-06T00:00:00Z",
"agent": backend,
@@ -60,6 +60,18 @@ def test_latest_record_is_backend_model_isolated_bounded_and_not_latest_error(tm
assert len(json.loads(path.read_text())) == 3
[email protected]("version", range(5, 11))
+def test_persisted_versions_remain_readable_without_rewriting(tmp_path, version):
+ record = {**_record("historical"), "contract_version": version}
+ path = tmp_path / "provenance.json"
+ path.write_text(json.dumps([record]), encoding="utf-8")
+ before = path.read_bytes()
+ store = BoundedProvenanceStore(path)
+ assert store.get("historical") == record
+ assert store.latest_for_model("claude", MODEL) == record
+ assert path.read_bytes() == before
+
+
@pytest.mark.parametrize("status,expected_status", [(404, 404), (True, None), (99, None), (600, None), (None, None)])
@pytest.mark.parametrize(
"code,expected_code", [("model_not_found", "model_not_found"), ("arbitrary credential=secret", None), (None, None)]
@@ -205,6 +217,6 @@ def test_model_history_client_rpc_http_share_nullable_read_only_result(monkeypat
f"/api/models/agents/claude/provenance?model={MODEL}", headers=csrf_headers(client, origin), base_url=origin
)
assert response.status_code == 200
- assert response.get_json() == {"ok": True, "contract_version": 9, "provenance": record}
+ assert response.get_json() == {"ok": True, "contract_version": 10, "provenance": record}
assert store.config.to_payload() == before
assert adapter.synced == []
diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.py
index 4893f189d..5569c19e5 100644
--- a/tests/test_model_hub_resolution.py
+++ b/tests/test_model_hub_resolution.py
@@ -303,7 +303,7 @@ def _config(sources: list[ModelHubSourceConfig], *, model: str = "claude-opus-4-
for backend in ("claude", "codex", "opencode")
}
for backend, agent in agents.items():
- # Existing persisted routes remain explicit, including old empty seeds.
+ # Historical empty seeds now inherit the backend defaults.
agent.routes = {entry.id: ModelHubRouteConfig() for entry in agent.models}
eligible = [source.id for source in sources if ModelHubConfig.source_eligible_for_backend(source, backend)]
agent.sources.order = eligible
@@ -1139,12 +1139,13 @@ def test_runtime_filters_reasoning_effort_forms_independently(tmp_path):
assert adapter.invocation_requests[0]["reasoning"] == {"summary": "auto"}
-def test_runtime_does_not_alias_unpersisted_claude_request():
+def test_runtime_inherits_exact_passthrough_without_aliasing_api_inventory():
source = _source("src_route003", ("claude-opus-4-6-20260115",))
config = _config([source], model="claude-opus-4-6-20260115")
resolution = resolve_model_hub_turn(config, "claude", "claude-opus-4-6")
- assert resolution.source is None
- assert resolution.supply_status == "interrupted"
+ assert resolution.source is source
+ assert resolution.target_model == "claude-opus-4-6"
+ assert resolution.route_origin == "passthrough"
def test_resolution_preserves_unlisted_manual_target():
@@ -1422,7 +1423,10 @@ def test_set_agent_chain_reports_removed_hops_and_syncs_transport_targets(tmp_pa
}
]
assert len(adapter.synced) == 1
- assert adapter.synced[0][1].route_model_ids == ()
+ assert menu_model not in adapter.synced[0][1].route_model_ids
+ assert set(adapter.synced[0][1].route_model_ids) == {
+ model.id for agent in config.agents.values() for model in agent.models if model.id != menu_model
+ }
def test_set_agent_chain_ignores_unrelated_existing_gap(tmp_path):
@@ -1460,7 +1464,10 @@ def test_set_agent_chain_ignores_unrelated_existing_gap(tmp_path):
assert result["interrupted"] == []
assert len(adapter.synced) == 1
- assert adapter.synced[0][-1].route_model_ids == ("other",)
+ assert set(adapter.synced[0][-1].route_model_ids) == {
+ "other", *(model.id for agent in config.agents.values() for model in agent.models
+ if model.id not in {menu_model, "claude-sonnet-4-6"})
+ }
assert [hop.source_id for hop in store.load().agents["claude"].routes[menu_model].hops] == [second.id, first.id]
@@ -1769,7 +1776,7 @@ def test_service_accepts_authoritative_reachable_adapter_error(tmp_path):
)
assert result["observation"] == {
- "contract_version": 9,
+ "contract_version": 10,
"outcome": "adapter_error",
"reachable": True,
"authenticated": "unknown",
@@ -1800,7 +1807,7 @@ def test_unknown_adapter_error_does_not_claim_connection(tmp_path):
assert exc.value.code == "discovery_failed"
assert exc.value.detail == "modelHub.errors.adapter_error"
assert exc.value.data["observation"] == {
- "contract_version": 9,
+ "contract_version": 10,
"outcome": "adapter_error",
"reachable": None,
"authenticated": "unknown",
@@ -2151,7 +2158,7 @@ def test_delete_source_reports_and_then_prunes_exact_hops(tmp_path):
with pytest.raises(ModelHubError) as exc:
asyncio.run(service.delete_source(source.id))
assert exc.value.code == "source_in_route_chain"
- assert exc.value.data["would_remove_hops"][0]["model_id"] == menu_model
+ assert menu_model in {hop["model_id"] for hop in exc.value.data["would_remove_hops"]}
with pytest.raises(ModelHubError) as unconfirmed:
asyncio.run(service.delete_source(source.id, force=True))
assert unconfirmed.value.code == exc.value.code
@@ -2166,7 +2173,7 @@ def test_delete_source_reports_and_then_prunes_exact_hops(tmp_path):
)
assert result["removed_hops"]
assert store.load().sources == []
- assert store.load().agents["claude"].routes[menu_model].hops == ()
+ assert store.load().agents["claude"].routes == {}
def test_refresh_source_uses_guarded_success_shape(tmp_path):
@@ -2243,7 +2250,10 @@ def test_inventory_mutations_share_the_successful_discovery_finalizer(
assert [model["retired"] for model in response_source["models"]] == [
False
] * len(discovered)
- assert response_source["adopted_by"] == [{"backend": "claude", "menu_model": "claude-opus-4-6"}]
+ assert response_source["adopted_by"] == sorted(
+ [{"backend": backend, "menu_model": model.id} for backend, agent in config.agents.items() for model in agent.models],
+ key=lambda item: (item["backend"], item["menu_model"]),
+ )
persisted_projection = {
key: value
for key, value in response_source.items()
diff --git a/tests/test_model_hub_retention.py b/tests/test_model_hub_retention.py
index 8d87c85b9..21f67d75a 100644
--- a/tests/test_model_hub_retention.py
+++ b/tests/test_model_hub_retention.py
@@ -542,6 +542,7 @@ def test_noninvoking_request_must_exit_before_finalization(tmp_path, no_candidat
request = _prepared_gateway_request(gateway, turn_id="noninvoking", requested_model=model, source_id=source.id, stream=True)
if no_candidate:
service.store.config.agents["codex"].routes[model] = ModelHubRouteConfig()
+ service.store.config.agents["codex"].sources.order = []
else:
request.json.return_value = {}
response_ready = asyncio.Event()
diff --git a/tests/test_model_hub_routing_modes.py b/tests/test_model_hub_routing_modes.py
index 02e4dbe79..29253fa60 100644
--- a/tests/test_model_hub_routing_modes.py
+++ b/tests/test_model_hub_routing_modes.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
+import copy
import json
from dataclasses import asdict, replace
from pathlib import Path
@@ -165,7 +166,7 @@ def test_mixed_unmatched_defaults_only_use_api_key_passthrough():
assert _pairs(plan) == [(api.id, MODEL)]
-def test_equal_save_has_manual_provenance_and_empty_override_survives_changes(tmp_path):
+def test_equal_save_is_manual_and_empty_save_restores_inherited_changes(tmp_path):
source = _source("src_first001")
config = _sparse_config(source)
service, store, adapter = _service(tmp_path, config)
@@ -173,16 +174,17 @@ def test_equal_save_has_manual_provenance_and_empty_override_survives_changes(tm
saved = asyncio.run(service.set_agent_chain("claude", MODEL, {"hops": hops}))
assert saved["chain"]["route_origin"] == "manual"
assert saved["chain"]["manual_override"] == {"hops": hops}
- with pytest.raises(ModelHubError) as guard:
- asyncio.run(service.set_agent_chain("claude", MODEL, {"hops": []}))
- empty = asyncio.run(service.set_agent_chain("claude", MODEL, {"hops": [], "force": True, **guard.value.data}))
- assert empty["chain"]["manual_override"] == {"hops": []}
- assert empty["chain"]["route_origin"] is None
- asyncio.run(service.set_agent_sources("claude", {"order": []}))
+ empty = asyncio.run(service.set_agent_chain("claude", MODEL, {"hops": []}))
+ assert empty["chain"]["manual_override"] is None
+ assert empty["chain"]["route_origin"] == "automatic"
store.config.sources[0].models.clear()
reloaded = ModelHubConfig.from_payload(store.config.to_payload())
- assert reloaded.agents["claude"].routes[MODEL].hops == ()
- assert effective_model_route(reloaded, "claude", MODEL).hops == ()
+ assert reloaded.agents["claude"].routes == {}
+ assert effective_model_route(reloaded, "claude", MODEL).route_origin == "passthrough"
+ with pytest.raises(ModelHubError) as guard:
+ asyncio.run(service.set_agent_sources("claude", {"order": []}))
+ asyncio.run(service.set_agent_sources("claude", {"order": [], "force": True, **guard.value.data}))
+ assert service.agent_chain("claude", MODEL)["route_origin"] is None
assert adapter.synced
@@ -207,7 +209,7 @@ def test_preview_and_restore_use_same_plan_without_preview_side_effects(tmp_path
assert MODEL not in store.config.agents["claude"].routes
repeated = asyncio.run(service.delete_agent_chain("claude", MODEL))
assert repeated == restored
- assert len(adapter.synced) == 1
+ assert adapter.synced == []
def test_restore_guards_effective_removal_and_accepts_only_exact_echo(tmp_path):
@@ -372,6 +374,249 @@ def _loaded_catalog_config(backend, requested, *sources):
return ModelHubConfig.from_payload(config.to_payload())
[email protected]("backend", ["claude", "codex", "opencode"])
[email protected]("matched", [False, True])
+def test_empty_override_equals_absence_at_all_route_consumers(tmp_path, backend, matched):
+ source = _source("src_inherit01", (MODEL,) if matched else ())
+ config = _loaded_catalog_config(backend, MODEL, source)
+ service, store, adapter = _service(tmp_path, config)
+ expected = service.agent_chain(backend, MODEL)
+ bindings = service._bindings(config)
+ config.agents[backend].routes[MODEL] = ModelHubRouteConfig()
+ assert service.agent_chain(backend, MODEL) == expected
+ assert service._bindings(config) == bindings
+ assert service.get_agent_sources(backend)["routes"] == {}
+ for draft in (None, {"hops": []}):
+ assert service.preview_agent_chain(backend, MODEL, {"manual_override": draft}) == expected
+ assert adapter.synced == []
+ payload = config.to_payload()
+ assert payload["agents"][backend]["routes"] == {}
+ payload["agents"][backend]["routes"][MODEL] = {"hops": []}
+ loaded = ModelHubConfig.from_payload(payload)
+ assert loaded.agents[backend].routes == {}
+ assert effective_model_route(loaded, backend, MODEL).route_origin == ("automatic" if matched else "passthrough")
+ saved = asyncio.run(service.set_agent_chain(backend, MODEL, {"hops": []}))
+ assert saved["chain"] == expected
+ assert store.config.agents[backend].routes == {}
+ assert asyncio.run(service.delete_agent_chain(backend, MODEL)) == saved
+ adapter.outcomes.append(RawCallOutcome(
+ kind=RawOutcomeKind.SUCCESS, http_status=200, error_code=None, redacted_message=None,
+ stream_started=False, source_id=source.id, model_id=MODEL,
+ ))
+ assert asyncio.run(service.probe_agent(backend, MODEL))["reachable"] is True
+ assert adapter.invocations == [(source.id, MODEL)]
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
+def test_empty_put_has_exact_restore_guard_and_final_hop_deletion_inherits(tmp_path, backend):
+ default = _source("src_default01", (MODEL,))
+ manual = _source("src_manual001", ("mapped",))
+ config = _loaded_catalog_config(backend, MODEL, default)
+ config.sources.append(manual)
+ config.agents[backend].routes[MODEL] = ModelHubRouteConfig(
+ hops=(ModelHubRouteHopConfig(manual.id, "mapped"),)
+ )
+ service, store, _ = _service(tmp_path, config)
+ before = config.to_payload()
+ with pytest.raises(ModelHubError) as restored:
+ asyncio.run(service.delete_agent_chain(backend, MODEL))
+ with pytest.raises(ModelHubError) as empty:
+ asyncio.run(service.set_agent_chain(backend, MODEL, {"hops": []}))
+ assert (empty.value.code, empty.value.data) == (restored.value.code, restored.value.data)
+ assert empty.value.data["would_interrupt"] == []
+ assert store.config.to_payload() == before
+ with pytest.raises(ModelHubError) as deletion:
+ asyncio.run(service.delete_source(manual.id))
+ assert deletion.value.data["would_interrupt"] == []
+ asyncio.run(service.delete_source(manual.id, force=True,
+ confirmed_remove_hops=deletion.value.data["would_remove_hops"],
+ confirmed_interruptions=deletion.value.data["would_interrupt"],
+ ))
+ assert store.config.agents[backend].routes == {}
+ assert service.agent_chain(backend, MODEL)["current"] == {"source_id": default.id, "model_id": MODEL}
+ assert service._bindings(store.config)[0].route_model_ids == (MODEL,)
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
[email protected]("bad", [{}, {"hops": None}, {"hops": [], "unknown": True}, {"hops": [{}]}])
+def test_invalid_empty_intent_is_validated_before_normalization(tmp_path, backend, bad):
+ config = _loaded_catalog_config(backend, MODEL, _source("src_inherit01", (MODEL,)))
+ raw = config.to_payload()
+ raw["agents"][backend]["routes"][MODEL] = bad
+ for repairing in (False, True):
+ with pytest.raises(ValueError):
+ ModelHubConfig.from_payload(raw, repairing=repairing)
+ service, store, adapter = _service(tmp_path, config)
+ with pytest.raises(ModelHubError):
+ service.preview_agent_chain(backend, MODEL, {"manual_override": bad})
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.set_agent_chain(backend, MODEL, bad))
+ assert store.config.to_payload() == config.to_payload()
+ assert adapter.synced == []
+
+
[email protected]("backend", ["claude", "codex"])
+def test_legacy_empty_key_keeps_derived_catalog_but_invalid_nonmenu_key_is_not_repaired(backend):
+ config = _loaded_catalog_config(backend, MODEL)
+ raw = config.to_payload()
+ agent = raw["agents"][backend]
+ agent["routes"] = {"legacy-empty-row": {"hops": []}}
+ for repairing in (False, True):
+ with pytest.raises(ValueError, match="non-menu"):
+ ModelHubConfig.from_payload(raw, repairing=repairing)
+ agent.pop("models")
+ loaded = ModelHubConfig.from_payload(raw)
+ assert "legacy-empty-row" in {model.id for model in loaded.agents[backend].models}
+ assert loaded.agents[backend].routes == {}
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
[email protected]("operation", ["retire_discovered", "remove_subscription_manual", "refresh_subscription"])
+def test_final_inventory_hop_removal_uses_inherited_guard_plan(tmp_path, backend, operation):
+ default = _source("src_default01", (MODEL,))
+ manual = _source("src_manual001", ("mapped",), kind="api_key" if operation == "retire_discovered" else "subscription")
+ if operation == "remove_subscription_manual":
+ manual.models[0].provenance = "manual"
+ config = _loaded_catalog_config(backend, MODEL, default)
+ config.sources.append(manual)
+ config.agents[backend].routes[MODEL] = ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(manual.id, "mapped"),))
+ service, store, adapter = _service(tmp_path, config)
+ adapter.discovered = ()
+
+ def mutate(**kwargs):
+ if operation == "refresh_subscription":
+ return service.refresh_source(manual.id, **kwargs)
+ return service.delete_custom_model(manual.id, "mapped", **kwargs)
+
+ before = config.to_payload()
+ with pytest.raises(ModelHubError) as refusal:
+ asyncio.run(mutate())
+ assert refusal.value.data["would_interrupt"] == []
+ assert refusal.value.data["would_remove_hops"] == [{
+ "backend": backend, "menu_model": MODEL, "source_id": manual.id, "model_id": "mapped", "position": 1,
+ }]
+ assert store.config.to_payload() == before
+ result = asyncio.run(mutate(force=True,
+ confirmed_remove_hops=refusal.value.data["would_remove_hops"],
+ confirmed_interruptions=refusal.value.data["would_interrupt"],
+ ))
+ assert result["interrupted"] == []
+ assert store.config.agents[backend].routes == {}
+ assert service.agent_chain(backend, MODEL)["current"] == {"source_id": default.id, "model_id": MODEL}
+ assert service._bindings(store.config)[0].route_model_ids == (MODEL,)
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
+def test_normalization_preserves_nonempty_intent_and_other_config_through_refresh(tmp_path, backend):
+ api = _source("src_preserve01", (MODEL,))
+ retired = _source("src_preserve03", ("retired",))
+ retired.models[0].retired = True
+ subscription = _source("src_preserve02", ("known",), kind="subscription")
+ config = _loaded_catalog_config(backend, MODEL, api, subscription)
+ config.sources.append(retired)
+ agent = config.agents[backend]
+ shapes = {
+ "exact": [(api.id, MODEL)],
+ "unknown-long": [(api.id, "legacy-" + "x" * MODEL_ID_MAX_LENGTH)],
+ "retired": [(retired.id, "retired")],
+ "subscription-stale": [(subscription.id, "stale")],
+ "ordered": [(subscription.id, "known"), (api.id, "mapped")],
+ }
+ for name, pairs in shapes.items():
+ agent.models.append(ModelHubBackendModelConfig(id=name, origin="manual", native_protocol="openai_responses" if backend == "opencode" else None))
+ agent.routes[name] = ModelHubRouteConfig(hops=tuple(ModelHubRouteHopConfig(*pair) for pair in pairs))
+ before = config.to_payload()
+ before["agents"][backend]["routes"][MODEL] = {"hops": []}
+ original = copy.deepcopy(before)
+ loaded = ModelHubConfig.from_payload(before)
+ assert before == original
+ expected = copy.deepcopy(before)
+ del expected["agents"][backend]["routes"][MODEL]
+ if backend == "opencode":
+ expected["agents"][backend]["menu"]["checked"] = [model.id for model in agent.models]
+ assert loaded.to_payload() == expected
+ service, store, adapter = _service(tmp_path, loaded)
+ adapter.discovered = (MODEL,)
+ asyncio.run(service.refresh_source(api.id))
+ assert store.config.agents[backend].to_payload() == expected["agents"][backend]
+ assert store.config.sources[1].to_payload() == expected["sources"][1]
+ assert store.config.sources[0].credential_ref == api.credential_ref
+
+
+def test_direct_dormant_empty_is_absent_from_route_and_guard_enumeration(tmp_path):
+ source = _source("src_dormant01", (MODEL,))
+ config = _loaded_catalog_config("opencode", MODEL, source)
+ service, _, _ = _service(tmp_path, config)
+ before = service.agent_chains("opencode")
+ protected = service._protected_menu_models(config, "opencode")
+ config.agents["opencode"].routes["dormant"] = ModelHubRouteConfig()
+ assert service.agent_chains("opencode") == before
+ assert service._protected_menu_models(config, "opencode") == protected
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
[email protected]("restore", [False, True])
+def test_failed_route_sync_rolls_back_canonical_intent_and_retry(tmp_path, backend, restore):
+ source = _source("src_rollback1", ())
+ config = _loaded_catalog_config(backend, MODEL, source)
+ manual = {"hops": [{"source_id": source.id, "model_id": "mapped"}]}
+ config.agents[backend].routes[MODEL] = ModelHubRouteConfig.from_payload(manual) if restore else ModelHubRouteConfig()
+ service, store, adapter = _service(tmp_path, config)
+ before = config.to_payload()
+ payload = {"hops": []} if restore else manual
+ if restore:
+ with pytest.raises(ModelHubError) as refusal:
+ asyncio.run(service.set_agent_chain(backend, MODEL, payload))
+ payload = {**payload, "force": True, **refusal.value.data}
+ original_sync = adapter.sync_sources
+ failures = 1
+
+ async def fail_once(bindings):
+ nonlocal failures
+ if failures:
+ failures -= 1
+ raise RuntimeError("synthetic sync failure")
+ await original_sync(bindings)
+
+ adapter.sync_sources = fail_once
+ with pytest.raises(ModelHubError, match="engine_down"):
+ asyncio.run(service.set_agent_chain(backend, MODEL, payload))
+ assert store.config.to_payload() == before
+ assert all(route.hops for route in store.config.agents[backend].routes.values())
+ result = asyncio.run(service.set_agent_chain(backend, MODEL, payload))
+ assert result["chain"]["manual_override"] == (None if restore else manual)
+ assert all(route.hops for route in store.config.agents[backend].routes.values())
+ assert adapter.synced[-1][0].route_model_ids == ((MODEL,) if restore else ("mapped",))
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
+def test_empty_intent_follows_refresh_defaults_and_health_without_reseeding(tmp_path, backend):
+ first = _source("src_refresh01", ())
+ second = _source("src_refresh02", ())
+ config = _loaded_catalog_config(backend, MODEL, first, second)
+ config.agents[backend].routes[MODEL] = ModelHubRouteConfig()
+ service, store, adapter = _service(tmp_path, config)
+ assert service.agent_chain(backend, MODEL)["route_origin"] == "passthrough"
+ adapter.discovered = (MODEL,)
+ with pytest.raises(ModelHubError) as refusal:
+ asyncio.run(service.refresh_source(second.id))
+ asyncio.run(service.refresh_source(second.id, force=True,
+ confirmed_remove_hops=refusal.value.data["would_remove_hops"],
+ confirmed_interruptions=refusal.value.data["would_interrupt"],
+ ))
+ assert service.agent_chain(backend, MODEL)["route_origin"] == "automatic"
+ bindings = service._bindings(store.config)
+ store.config.sources[1].state = ModelHubSourceStateConfig(status="error", detail_key="models.source.error.unclassified")
+ assert service.agent_chain(backend, MODEL)["route_origin"] == "automatic"
+ assert service.agent_chain(backend, MODEL)["current"] is None
+ assert service._bindings(store.config) == bindings
+ with pytest.raises(ModelHubError) as defaults:
+ asyncio.run(service.set_agent_sources(backend, {"order": [first.id]}))
+ asyncio.run(service.set_agent_sources(backend, {"order": [first.id], "force": True, **defaults.value.data}))
+ assert service.agent_chain(backend, MODEL)["route_origin"] == "passthrough"
+ assert store.config.agents[backend].routes == {}
+
+
@pytest.mark.parametrize("backend", ["claude", "codex"])
@pytest.mark.parametrize("state", ["automatic", "manual", "empty"])
@pytest.mark.parametrize("operation", ["put", "preview", "restore_preview", "restore_save"])
@@ -387,10 +632,10 @@ def test_persisted_legacy_catalog_identity_survives_route_consumers(tmp_path, ba
before = config.to_payload()
if operation == "put":
result = asyncio.run(service.set_agent_chain(backend, requested, route))["chain"]
- assert result["manual_override"] == route
+ assert result["manual_override"] == (route if route["hops"] else None)
elif operation == "preview":
result = service.preview_agent_chain(backend, requested, {"manual_override": route})
- assert result["manual_override"] == route
+ assert result["manual_override"] == (route if route["hops"] else None)
elif operation == "restore_preview":
result = service.preview_agent_chain(backend, requested, {"manual_override": None})
assert result["route_origin"] == "automatic"
@@ -560,7 +805,7 @@ def test_retained_opencode_route_registration_matches_resolver_without_inventing
binding = service._bindings(config)[0]
assert binding.route_model_ids == expected_targets
assert binding.model_ids == tuple(model.id for model in config.sources[0].models if not model.retired)
- assert {item["model_id"] for item in service.agent_chains("opencode")} == {catalog, dormant}
+ assert {item["model_id"] for item in service.agent_chains("opencode")} == ({catalog} if state == "empty" else {catalog, dormant})
if state != "empty":
assert {"backend": "opencode", "menu_model": dormant} in service._adopted_by(source.id)
assert any(item["menu_model"] == dormant for item in service._added_to(source.id))
diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.py
index 6a81fb7b0..24913c6e1 100644
--- a/tests/test_model_hub_runtime.py
+++ b/tests/test_model_hub_runtime.py
@@ -1293,7 +1293,7 @@ def test_manifest_resolution_drives_admission_persistence_and_schema(
installer=manager,
state_store=EngineStateStore(tmp_path / "state"),
)
- projected = {"contract_version": 9, **supervisor.status()}
+ projected = {"contract_version": 10, **supervisor.status()}
schema = json.loads(
Path("docs/plans/model-hub-contracts/runtime-dependency.schema.json").read_text(
encoding="utf-8"
diff --git a/ui/e2e/model-route-cleanup.spec.ts b/ui/e2e/model-route-cleanup.spec.ts
index 655ee42fe..676897deb 100644
--- a/ui/e2e/model-route-cleanup.spec.ts
+++ b/ui/e2e/model-route-cleanup.spec.ts
@@ -166,7 +166,7 @@ test('Agent-only cleanup preserves the existing missing-Agent policy', async ()
});
for (const override of [null, { hops: [] }, { hops: [{ source_id: 'src_operator', model_id: 'vendor/model' }] }]) {
- test(`route cleanup preserves ${override === null ? 'absence' : override.hops.length ? 'manual hops' : 'explicit empty'}`, async () => {
+ test(`route cleanup preserves canonical ${override === null ? 'absence' : override.hops.length ? 'manual hops' : 'empty inheritance'}`, async () => {
let saved: AgentChain['manual_override'] = override;
const writes: string[] = [];
const api = {
@@ -185,21 +185,35 @@ for (const override of [null, { hops: [] }, { hops: [{ source_id: 'src_operator'
} as unknown as HubApi;
const route = { backend: 'claude', model: 'menu-model' };
const snapshot = await captureAgentChain(api, route);
- expect(snapshot.manual_override).toEqual(override);
+ const canonical = override?.hops.length ? override : null;
+ expect(snapshot.manual_override).toEqual(canonical);
saved = { hops: [{ source_id: 'src_test', model_id: 'test-target' }] };
await restoreAgentChain(api, route, snapshot);
- expect(saved).toEqual(override);
- expect(writes).toEqual([override === null ? 'DELETE' : 'PUT']);
+ expect(saved).toEqual(canonical);
+ expect(writes).toEqual([canonical === null ? 'DELETE' : 'PUT']);
});
}
-test('route cleanup rejects successful responses whose persisted intent was not restored', async () => {
+for (const readback of [{ hops: [] }, { hops: [{ source_id: 'src_wrong', model_id: 'wrong-target' }] }, undefined]) {
+ test(`route cleanup rejects noncanonical or false-success readback ${JSON.stringify(readback)}`, async () => {
+ const api = {
+ deleteAgentChain: async () => true,
+ agentChain: async () => ({ manual_override: readback }),
+ } as unknown as HubApi;
+ await expect(restoreAgentChain(api, { backend: 'claude', model: 'menu-model' }, { manual_override: null }))
+ .rejects.toThrow('Teardown must restore route intent');
+ });
+}
+
+test('a legacy empty snapshot restores with DELETE and never recreates an empty manual value', async () => {
+ const writes: string[] = [];
const api = {
- deleteAgentChain: async () => true,
- agentChain: async () => ({ manual_override: { hops: [] } }),
+ deleteAgentChain: async () => { writes.push('DELETE'); return true; },
+ putAgentChain: async () => { writes.push('PUT'); return true; },
+ agentChain: async () => ({ manual_override: null }),
} as unknown as HubApi;
- await expect(restoreAgentChain(api, { backend: 'claude', model: 'menu-model' }, { manual_override: null }))
- .rejects.toThrow('Teardown must restore route intent');
+ await restoreAgentChain(api, { backend: 'codex', model: 'menu-model' }, { manual_override: { hops: [] } });
+ expect(writes).toEqual(['DELETE']);
});
test('route cleanup preserves existing fixture-source references verbatim', async () => {
diff --git a/ui/e2e/model-routing-origin.spec.ts b/ui/e2e/model-routing-origin.spec.ts
index ec719b799..64feac07f 100644
--- a/ui/e2e/model-routing-origin.spec.ts
+++ b/ui/e2e/model-routing-origin.spec.ts
@@ -1,12 +1,25 @@
+import type { AgentChain } from './support/api';
import { hub as copy } from './support/copy';
+import { BASE_URL } from './support/env';
import { expect, test } from './support/gateway';
import { labelledButton } from './support/hub';
import { captureAgentChain, restoreAgentChain } from './support/restore';
test('MH-ROUTING-007 restore, undo, cancel, and save preserve explicit route intent', async ({ api, gateway, hub, page }) => {
const original = await captureAgentChain(api, gateway);
- const manual = { hops: [{ source_id: gateway.sources[0].id, model_id: gateway.model }] };
+ const originalOrder = await api.defaultSourceOrder(gateway.backend);
+ const manual = { hops: [{ source_id: gateway.sources[0].id, model_id: `${gateway.model}/manual-original` }] };
+ const unsavedModel = `${gateway.model}/manual-draft`;
+ const identities = (chain: AgentChain) => chain.chain.map(({ source_id, model_id }) => ({ source_id, model_id }));
+ const chainUrl = new URL(`/api/models/agents/${gateway.backend}/chain?model=${encodeURIComponent(gateway.model)}`, BASE_URL).href;
+ const previewUrl = new URL(`/api/models/agents/${gateway.backend}/chain/preview?model=${encodeURIComponent(gateway.model)}`, BASE_URL).href;
try {
+ await api.setDefaultSourceOrder(gateway.backend, gateway.sources.map((source) => source.id));
+ expect(await api.deleteAgentChain(gateway.backend, gateway.model)).toBe(true);
+ const inherited = await api.agentChain(gateway.backend, gateway.model);
+ expect(inherited.manual_override).toBeNull();
+ expect(inherited.chain.length).toBeGreaterThan(0);
+ expect(identities(inherited).every((hop) => gateway.sources.some((source) => source.id === hop.source_id))).toBe(true);
expect(await api.putAgentChain(gateway.backend, gateway.model, manual.hops)).toBe(true);
await hub.goto();
await hub.openRoute(gateway.backend, gateway.model);
@@ -14,42 +27,106 @@ test('MH-ROUTING-007 restore, undo, cancel, and save preserve explicit route int
await expect(dialog).toBeVisible();
const mutations: string[] = [];
page.on('request', (request) => {
- if (['PUT', 'DELETE'].includes(request.method()) && new URL(request.url()).pathname.endsWith('/chain')) {
+ if (['PUT', 'DELETE'].includes(request.method()) && request.url() === chainUrl) {
mutations.push(request.method());
}
});
- const restore = () => labelledButton(dialog, copy('routing.restoreAutomatic')).click();
- await restore();
- await expect(labelledButton(dialog, copy('routing.undoRestore'))).toBeVisible();
- expect((await api.agentChain(gateway.backend, gateway.model)).manual_override).toEqual(manual);
+ const preview = async (action: () => Promise<void>) => {
+ const responsePromise = page.waitForResponse((response) => response.url() === previewUrl && response.request().method() === 'POST');
+ await action();
+ const response = await responsePromise;
+ expect(response.status()).toBe(200);
+ expect(response.request().postDataJSON()).toEqual({ manual_override: null });
+ const body = await response.json() as { ok: boolean; contract_version: number; chain: AgentChain };
+ expect(body.ok).toBe(true);
+ expect(body.contract_version).toBe(10);
+ expect(body.chain.manual_override).toBeNull();
+ expect(body.chain.route_origin).toBe(inherited.route_origin);
+ expect(identities(body.chain)).toEqual(identities(inherited));
+ await expect(dialog.locator('.model-hub-route-preview')).toHaveAttribute('data-origin', inherited.route_origin!);
+ await expect(dialog.locator('.model-hub-route-hop-model')).toHaveText(inherited.chain.map((hop) => hop.model_id));
+ await expect(labelledButton(dialog, copy('routing.undoRestore'))).toBeEnabled();
+ await expect(labelledButton(dialog, copy('routeDialog.save'))).toBeEnabled();
+ expect((await api.agentChain(gateway.backend, gateway.model)).manual_override).toEqual(manual);
+ expect(mutations).toEqual([]);
+ };
+ const removeLast = async () => {
+ await expect(dialog.locator('.model-hub-route-hop')).toHaveCount(1);
+ await preview(() => dialog.getByRole('button', { name: copy('routeDialog.removeHop'), exact: true }).press('Enter'));
+ };
+ await preview(() => labelledButton(dialog, copy('routing.restoreAutomatic')).click());
await labelledButton(dialog, copy('routing.undoRestore')).click();
await expect(labelledButton(dialog, copy('routing.restoreAutomatic'))).toBeVisible();
+ await expect(dialog.locator('.model-hub-route-hop-model')).toHaveText([manual.hops[0].model_id]);
expect((await api.agentChain(gateway.backend, gateway.model)).manual_override).toEqual(manual);
expect(mutations).toEqual([]);
- await restore();
- await expect(labelledButton(dialog, copy('routing.undoRestore'))).toBeVisible();
+ // Undo must preserve the unsaved candidate, not reconstruct the saved route.
+ await dialog.getByRole('button', { name: copy('routeDialog.editHop'), exact: true }).click();
+ const selector = page.locator('.model-hub-route-selector');
+ await selector.getByLabel(copy('routeDialog.add.source'), { exact: true }).selectOption(gateway.sources[0].id);
+ await selector.getByLabel(copy('routing.exactModel'), { exact: true }).fill(unsavedModel);
+ await expect(selector.getByRole('button', { name: copy('routeDialog.add.confirm'), exact: true })).toHaveCount(0);
+ const replace = selector.getByRole('button', { name: copy('routeDialog.edit.confirm'), exact: true });
+ await expect(replace).toBeEnabled();
+ await replace.click();
+ await expect(selector).toHaveCount(0);
+ await expect(dialog.locator('.model-hub-route-hop-name')).toHaveText([gateway.sources[0].display_name]);
+ await expect(dialog.locator('.model-hub-route-hop-model')).toHaveText([unsavedModel]);
+ await removeLast();
+ await labelledButton(dialog, copy('routing.undoRestore')).click();
+ await expect(dialog.locator('.model-hub-route-hop-name')).toHaveText([gateway.sources[0].display_name]);
+ await expect(dialog.locator('.model-hub-route-hop-model')).toHaveText([unsavedModel]);
+ await removeLast();
await labelledButton(dialog, copy('routeDialog.cancel')).click();
await expect(dialog).not.toBeVisible();
expect((await api.agentChain(gateway.backend, gateway.model)).manual_override).toEqual(manual);
expect(mutations).toEqual([]);
await hub.openRoute(gateway.backend, gateway.model);
- await restore();
- await expect(labelledButton(dialog, copy('routing.undoRestore'))).toBeVisible();
+ await removeLast();
+ const refusedPromise = page.waitForResponse((response) => response.url() === chainUrl && response.request().method() === 'DELETE');
await labelledButton(dialog, copy('routeDialog.save')).click();
- await expect.poll(async () => (
- (await api.agentChain(gateway.backend, gateway.model)).manual_override === null
- || await labelledButton(dialog, copy('guard.confirm.saveRoute')).isVisible()
- )).toBe(true);
+ const refused = await refusedPromise;
+ expect(refused.status()).toBe(409);
+ expect(refused.request().postDataJSON()).toEqual({});
+ const plan = {
+ would_remove_hops: [{ backend: gateway.backend, menu_model: gateway.model, ...manual.hops[0], position: 1 }],
+ would_interrupt: [],
+ };
+ expect(await refused.json()).toMatchObject({ ok: false, contract_version: 10, error: 'source_in_route_chain', ...plan });
+ expect((await api.agentChain(gateway.backend, gateway.model)).manual_override).toEqual(manual);
+ await expect(dialog.locator('.model-hub-guard-hop')).toHaveCount(1);
+ await expect(dialog.locator('.model-hub-guard-hop strong')).toHaveText(`${copy(`backends.${gateway.backend}`)} · ${gateway.model}`);
+ await expect(dialog.locator('.model-hub-guard-hop > span > span')).toHaveText(`${manual.hops[0].model_id} · ${copy('guard.hop.position', { n: 1 })}`);
const confirm = labelledButton(dialog, copy('guard.confirm.saveRoute'));
- if (await confirm.isVisible()) await confirm.click();
+ await expect(confirm).toBeVisible();
+ const committedPromise = page.waitForResponse((response) => response.url() === chainUrl && response.request().method() === 'DELETE');
+ await confirm.click();
+ const committed = await committedPromise;
+ expect(committed.status()).toBe(200);
+ expect(committed.request().postDataJSON()).toEqual({ force: true, ...plan });
await expect.poll(async () => (await api.agentChain(gateway.backend, gateway.model)).manual_override).toBeNull();
- expect(mutations.length).toBeGreaterThan(0);
- expect(new Set(mutations)).toEqual(new Set(['DELETE']));
+ expect(identities(await api.agentChain(gateway.backend, gateway.model))).toEqual(identities(inherited));
+ expect(mutations).toEqual(['DELETE', 'DELETE']);
+ const done = labelledButton(dialog, copy('routeDialog.impact.done'));
+ await expect(done).toBeEnabled();
+ await done.click();
+ await expect(dialog).toHaveCount(0);
await page.reload();
- expect((await api.agentChain(gateway.backend, gateway.model)).manual_override).toBeNull();
+ const reloaded = await api.agentChain(gateway.backend, gateway.model);
+ expect(reloaded.manual_override).toBeNull();
+ expect(reloaded.route_origin).toBe(inherited.route_origin);
+ expect(identities(reloaded)).toEqual(identities(inherited));
+ await expect(hub.routeRow(gateway.backend, gateway.model).locator('button.model-hub-route-origin')).toHaveText(copy(`routing.origin.${reloaded.route_origin}`));
+ await hub.openRoute(gateway.backend, gateway.model);
+ await expect(labelledButton(dialog, copy('routing.editRoute'))).toBeVisible();
+ await labelledButton(dialog, copy('routing.close')).click();
} finally {
- await restoreAgentChain(api, gateway, original);
+ try {
+ await api.setDefaultSourceOrder(gateway.backend, originalOrder);
+ } finally {
+ await restoreAgentChain(api, gateway, original);
+ }
}
});
diff --git a/ui/e2e/support/api.ts b/ui/e2e/support/api.ts
index d0c98f513..1b557c381 100644
--- a/ui/e2e/support/api.ts
+++ b/ui/e2e/support/api.ts
@@ -354,8 +354,8 @@ export class HubApi {
const payload = await this.read<{ ok: boolean; contract_version: number; provenance: RecordedTurn | null }>(
`/api/models/agents/${backend}/provenance?model=${encodeURIComponent(model)}`,
);
- if (payload.ok !== true || payload.contract_version !== 9 || !('provenance' in payload)) {
- throw new Error('Latest recorded turn did not use the v9 provenance envelope');
+ if (payload.ok !== true || payload.contract_version !== 10 || !('provenance' in payload)) {
+ throw new Error('Latest recorded turn did not use the v10 provenance envelope');
}
return payload.provenance;
}
diff --git a/ui/e2e/support/restore.ts b/ui/e2e/support/restore.ts
index ec3f1b785..10ae049f5 100644
--- a/ui/e2e/support/restore.ts
+++ b/ui/e2e/support/restore.ts
@@ -31,6 +31,12 @@ import { expect, runtimeIsRunning } from './fixtures';
export type AgentChainSnapshot = Pick<AgentChain, 'manual_override'>;
+/** Legacy empty input carries the same intent as absence; nonempty hops stay exact. */
+export const canonicalManualOverride = (override: AgentChain['manual_override']): AgentChain['manual_override'] =>
+ override === null || override.hops.length === 0 ? null : {
+ hops: override.hops.map((hop) => ({ source_id: hop.source_id, model_id: hop.model_id })),
+ };
+
/** Capture persisted intent, not an effective chain that includes fixture sources. */
export const captureAgentChain = async (
api: HubApi,
@@ -39,21 +45,20 @@ export const captureAgentChain = async (
const chain = await api.agentChain(route.backend, route.model);
expect(chain).toHaveProperty('manual_override');
return {
- manual_override: chain.manual_override === null ? null : {
- hops: chain.manual_override.hops.map((hop) => ({ source_id: hop.source_id, model_id: hop.model_id })),
- },
+ manual_override: canonicalManualOverride(chain.manual_override),
};
};
-/** Automatic absence and a persisted empty manual route are different states. */
+/** Restore canonical intent without recreating the obsolete empty-disable value. */
export const restoreAgentChain = async (
api: HubApi,
route: { backend: string; model: string },
original: AgentChainSnapshot,
): Promise<void> => {
- const restored = original.manual_override === null
+ const expected = canonicalManualOverride(original.manual_override);
+ const restored = expected === null
? await api.deleteAgentChain(route.backend, route.model)
- : await api.putAgentChain(route.backend, route.model, original.manual_override.hops);
+ : await api.putAgentChain(route.backend, route.model, expected.hops);
expect(
restored,
`Teardown failed to restore the original route chain for ${route.backend}/${route.model} — `
@@ -61,7 +66,7 @@ export const restoreAgentChain = async (
).toBe(true);
const actual = await api.agentChain(route.backend, route.model);
expect(actual.manual_override, 'Teardown must restore route intent, not only effective hops')
- .toEqual(original.manual_override);
+ .toEqual(expected);
};
/**
diff --git a/ui/src/components/settings/models/AgentCard.test.tsx b/ui/src/components/settings/models/AgentCard.test.tsx
index c709af0fb..c47e14d4b 100644
--- a/ui/src/components/settings/models/AgentCard.test.tsx
+++ b/ui/src/components/settings/models/AgentCard.test.tsx
@@ -16,7 +16,7 @@ import { freshRuntimeProjection } from './runtimeLifecycle';
import type { AgentSupply, RuntimeDependency, Source } from './types';
const runtime: RuntimeDependency = {
- contract_version: 9,
+ contract_version: 10,
manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'fixture', assets: [] },
status: { installed_version: '1.0.0', verified: true, listening: null, health: 'ok', last_check: null },
};
@@ -329,7 +329,7 @@ describe('AgentCard', () => {
['zh', 'Backup → claude-opus-4-6(已自动切换)', '打开 claude-opus-4-6 的路由 · Backup → claude-opus-4-6(已自动切换)'],
] as const)('derives and announces takeover from the exact current hop in %s', (lng, mappingCopy, accessibleName) => {
const key = modelChainKey('claude', 'claude-opus-4-6');
- render(<I18nextProvider i18n={localeInstance(lng)}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 9, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
+ render(<I18nextProvider i18n={localeInstance(lng)}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 10, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
expect(screen.getByText(/Backup/)).toBeTruthy();
expect(screen.getByTitle(mappingCopy)).toBeTruthy();
expect(screen.getByRole('button', { name: accessibleName })).toBeTruthy();
@@ -347,7 +347,7 @@ describe('AgentCard', () => {
sources={[source('src_b', 'Backup source')]}
chains={{
[key]: readyRegion({ manual_override: {hops:[{source_id:'src_b',model_id:'routed-opus'}]}, route_origin: "manual" as const,
- contract_version: 9,
+ contract_version: 10,
backend: 'claude',
model_id: 'claude-opus-4-6',
current: { source_id: 'src_b', model_id: 'routed-opus' },
@@ -377,7 +377,7 @@ describe('AgentCard', () => {
it('does not call a later current hop takeover unless the head is unavailable for cooldown', () => {
const key = modelChainKey('claude', 'claude-opus-4-6');
- render(<I18nextProvider i18n={i18n}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 9, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'native_cli', health: 'healthy', runnable: false, reason: 'native_cli_unavailable', retry_at: null }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
+ render(<I18nextProvider i18n={i18n}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 10, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'native_cli', health: 'healthy', runnable: false, reason: 'native_cli_unavailable', retry_at: null }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
expect(screen.getByText(/Backup/)).toBeTruthy();
expect(screen.queryByText(/takeover/i)).toBeNull();
});
@@ -385,7 +385,7 @@ describe('AgentCard', () => {
it('hides current and takeover projections while the runtime is stopped', () => {
const key = modelChainKey('claude', 'claude-opus-4-6');
const stopped = { ...runtime, status: { ...runtime.status, health: 'down' as const } };
- render(<I18nextProvider i18n={i18n}><RuntimeAgentCard runtime={freshRuntimeProjection(readyRegion(stopped))} agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 9, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
+ render(<I18nextProvider i18n={i18n}><RuntimeAgentCard runtime={freshRuntimeProjection(readyRegion(stopped))} agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 10, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
expect(screen.queryByText(/Backup/)).toBeNull();
expect(screen.queryByText(/takeover/i)).toBeNull();
@@ -397,7 +397,7 @@ describe('AgentCard', () => {
const onOpenModels = vi.fn();
const key = modelChainKey('claude', 'claude-opus-4-6');
const directAgent: AgentSupply = { ...hubAgent, mode: 'direct', sources: null, routes: null, supply_status: null, model_supply: null };
- render(<I18nextProvider i18n={i18n}><AgentCard agents={[directAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 9, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={onOpenModels} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
+ render(<I18nextProvider i18n={i18n}><AgentCard agents={[directAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 10, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={onOpenModels} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
expect(screen.queryByText(/Adjust priority/i)).toBeNull();
expect(screen.queryByRole('button', { name: /route chain/i })).toBeNull();
expect(screen.queryByText(/Backup/)).toBeNull();
diff --git a/ui/src/components/settings/models/EnableGatewayDialog.test.tsx b/ui/src/components/settings/models/EnableGatewayDialog.test.tsx
index 8879545a9..895f69417 100644
--- a/ui/src/components/settings/models/EnableGatewayDialog.test.tsx
+++ b/ui/src/components/settings/models/EnableGatewayDialog.test.tsx
@@ -34,7 +34,7 @@ const runtime = (
? 'unresolved' as const
: hostPlatform === 'linux-amd64' ? 'unsupported' as const : 'resolved' as const;
return {
- contract_version: 9,
+ contract_version: 10,
...(hostPlatform === undefined ? {} : { host_platform: hostPlatform }),
manifest: resolution === 'unresolved'
? { name: 'cliproxyapi', resolution, assets: [] }
diff --git a/ui/src/components/settings/models/InstallGatewayDialog.test.tsx b/ui/src/components/settings/models/InstallGatewayDialog.test.tsx
index bfde134fe..c0131d2fc 100644
--- a/ui/src/components/settings/models/InstallGatewayDialog.test.tsx
+++ b/ui/src/components/settings/models/InstallGatewayDialog.test.tsx
@@ -10,7 +10,7 @@ import { modelsApi } from './modelsApi';
import type { RuntimeDependency } from './types';
const runtime = (health: RuntimeDependency['status']['health']): RuntimeDependency => ({
- contract_version: 9,
+ contract_version: 10,
manifest: {
name: 'cliproxyapi',
resolution: 'resolved',
diff --git a/ui/src/components/settings/models/RouteChainDialog.test.tsx b/ui/src/components/settings/models/RouteChainDialog.test.tsx
index 98648a92f..8b4a183c5 100644
--- a/ui/src/components/settings/models/RouteChainDialog.test.tsx
+++ b/ui/src/components/settings/models/RouteChainDialog.test.tsx
@@ -5,6 +5,8 @@ import { I18nextProvider } from "react-i18next";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import i18n from "@/i18n";
+import en from '@/i18n/en.json';
+import zh from '@/i18n/zh.json';
import { ApiCallError, modelsApi } from "./modelsApi";
import {
RouteChainDialog,
@@ -52,7 +54,7 @@ const sources: Source[] = [
},
];
const chain: AgentChain = { manual_override: {hops:[{source_id:"src_a",model_id:"claude-opus-5"},{source_id:"src_b",model_id:"opus-5"}]}, route_origin: "manual" as const,
- contract_version: 9,
+ contract_version: 10,
backend: "claude",
model_id: "opus-5",
current: { source_id: "src_b", model_id: "opus-5" },
@@ -383,23 +385,203 @@ describe("RouteChainDialog", () => {
expect(screen.queryByRole('button', { name: 'Restore automatic' })).toBeNull();
});
- it('retains restore and undo for a saved manual-empty route without admissible targets', async () => {
+ it('reads legacy empty storage only as server-normalized inheritance with no admissible targets', async () => {
+ renderEmptyRoute({ ...agent, sources: { order: [], eligibility: [] } }, []);
+ await screen.findByRole('button', { name: 'Configure default routing' });
+ expect(screen.getByText('Unconfigured')).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'Restore automatic' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Save' })).toBeNull();
+ expect(screen.queryByText(/saved route is empty/)).toBeNull();
+ });
+
+ it('cannot save an empty newly opened editor as Manual', async () => {
const user = userEvent.setup();
- vi.spyOn(modelsApi, 'previewAgentChain').mockResolvedValue(inherited);
- const restore = vi.spyOn(modelsApi, 'restoreAgentChain').mockResolvedValue(mutation(inherited));
+ renderEmptyRoute({ ...agent, sources: {
+ order: [], eligibility: [{ source_id: sources[0].id, eligible: true }],
+ } }, [sources[0]]);
+ await user.click(await screen.findByRole('button', { name: 'Edit route' }));
+ expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(true);
+ expect(screen.queryByText(/saved route is empty/)).toBeNull();
+ });
+ });
+
+ describe('last-hop clear inherits routing', () => {
+ const inherited: AgentChain = { ...chain, manual_override: null, route_origin: 'automatic' };
+ const unconfigured: AgentChain = { ...inherited, route_origin: null, current: null, chain: [], supply_state: 'interrupted' };
+ const clear = async (user: ReturnType<typeof userEvent.setup>) => {
+ await screen.findAllByRole('button', { name: 'Remove hop' });
+ await user.click(screen.getAllByRole('button', { name: 'Remove hop' })[0]);
+ await user.click(screen.getByRole('button', { name: 'Remove hop' }));
+ };
+
+ it.each(['manual', 'automatic'] as const)('previews clear from %s, undoes only the previous unsaved draft and cancels without writes', async (origin) => {
+ const user = userEvent.setup();
+ const preview = vi.spyOn(modelsApi, 'previewAgentChain').mockResolvedValue(inherited);
const put = vi.spyOn(modelsApi, 'putAgentChain');
- renderEmptyRoute({ ...agent, sources: { order: [], eligibility: [] } }, [], {
- ...inherited, manual_override: { hops: [] },
- });
+ const restore = vi.spyOn(modelsApi, 'restoreAgentChain');
+ const close = vi.fn();
+ renderDialog(vi.fn(), close);
+ if (origin === 'automatic') {
+ vi.mocked(modelsApi.getAgentChain).mockResolvedValue(inherited);
+ cleanup();
+ render(<I18nextProvider i18n={i18n}><RouteChainDialog selection={{ agent, modelId: 'opus-5', read: readyRegion(inherited) }} sources={sources} onClose={close} readAgents={vi.fn()} readSources={vi.fn()} /></I18nextProvider>);
+ await user.click(await screen.findByRole('button', { name: 'Edit route' }));
+ }
+ await clear(user);
+ await screen.findByText('After restore: automatic matching');
+ expect(preview).toHaveBeenCalledWith('claude', 'opus-5', { manual_override: null });
+ expect(screen.queryByRole('button', { name: 'Remove hop' })).toBeNull();
+ expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(false);
+ await user.click(screen.getByRole('button', { name: 'Undo restore' }));
+ expect(screen.getAllByRole('button', { name: 'Remove hop' })).toHaveLength(1);
+ expect(document.querySelector('.model-hub-route-hop-model')?.textContent).toBe('opus-5');
+ await user.click(screen.getByRole('button', { name: 'Remove hop' }));
+ await screen.findByText('After restore: automatic matching');
+ await user.click(within(document.querySelector<HTMLElement>('.model-hub-route-foot')!).getByRole('button', { name: 'Cancel' }));
+ expect(close).toHaveBeenCalledOnce();
+ expect(put).not.toHaveBeenCalled();
+ expect(restore).not.toHaveBeenCalled();
+ expect(chain.manual_override?.hops).toHaveLength(2);
+ });
- await user.click(await screen.findByRole('button', { name: 'Restore automatic' }));
- await user.click(await screen.findByRole('button', { name: 'Undo restore' }));
- expect(screen.queryByRole('button', { name: 'Edit route' })).toBeNull();
+ it('clears to no-key Unconfigured, confirms the exact DELETE guard and shows actual impact then Done', async () => {
+ const user = userEvent.setup();
+ const gap = { backend: 'claude' as const, model_id: 'opus-5', agents: ['writer'] };
+ const hop = { backend: 'claude' as const, menu_model: 'opus-5', ...chain.manual_override!.hops[0], position: 1 };
+ vi.spyOn(modelsApi, 'previewAgentChain').mockResolvedValue(unconfigured);
+ const restore = vi.spyOn(modelsApi, 'restoreAgentChain')
+ .mockRejectedValueOnce(new ApiCallError('source_last_supplier', undefined, true, [gap], [], [hop]))
+ .mockResolvedValueOnce(mutation(unconfigured, { removed_hops: [hop], interrupted: [gap] }));
+ const put = vi.spyOn(modelsApi, 'putAgentChain');
+ const committed = vi.fn();
+ vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(chain);
+ render(<I18nextProvider i18n={i18n}><RouteChainDialog
+ selection={{ agent: { ...agent, sources: { order: [], eligibility: [] } }, modelId: 'opus-5', read: readyRegion(chain) }}
+ sources={[]} onClose={vi.fn()} onCommitted={committed} readAgents={vi.fn()} readSources={vi.fn()}
+ /></I18nextProvider>);
+ await clear(user);
+ await screen.findByText('After restore: unconfigured');
+ expect(restore).not.toHaveBeenCalled();
+ await user.click(screen.getByRole('button', { name: 'Save' }));
+ await user.click(await screen.findByRole('button', { name: 'Save anyway' }));
+ await within(document.querySelector<HTMLElement>('.model-hub-route-foot')!).findByRole('button', { name: 'Done' });
+ expect(restore.mock.calls).toEqual([
+ ['claude', 'opus-5', undefined],
+ ['claude', 'opus-5', { force: true, would_remove_hops: [hop], would_interrupt: [gap] }],
+ ]);
+ expect(committed).toHaveBeenCalledWith(mutation(unconfigured, { removed_hops: [hop], interrupted: [gap] }));
+ expect(screen.getByText('Agents pinned to it: writer')).toBeTruthy();
+ expect(put).not.toHaveBeenCalled();
+ });
+
+ it('keeps clear intent and Undo through a failed preview, retries without enabling stale Save', async () => {
+ const user = userEvent.setup();
+ const pending = deferred<AgentChain>();
+ vi.spyOn(modelsApi, 'previewAgentChain').mockRejectedValueOnce(new Error('offline')).mockReturnValueOnce(pending.promise);
+ const restore = vi.spyOn(modelsApi, 'restoreAgentChain');
+ renderDialog();
+ await clear(user);
+ await screen.findByRole('alert');
+ expect(screen.getByRole('button', { name: 'Undo restore' })).toBeTruthy();
expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(true);
- await user.click(screen.getByRole('button', { name: 'Restore automatic' }));
- await screen.findByRole('button', { name: 'Undo restore' });
+ expect(screen.queryByText('Manual', { exact: true })).toBeNull();
+ await user.click(screen.getByRole('button', { name: 'Retry' }));
+ expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(true);
+ await act(async () => pending.resolve({ ...inherited, route_origin: 'passthrough' }));
+ await screen.findByText('After restore: original-name passthrough');
+ expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(false);
+ expect(restore).not.toHaveBeenCalled();
+ await user.click(screen.getByRole('button', { name: 'Undo restore' }));
+ expect(document.querySelector('.model-hub-route-hop-model')?.textContent).toBe('opus-5');
+ });
+
+ it.each(['undo', 'close'] as const)('invalidates a late clear preview after %s', async (action) => {
+ const user = userEvent.setup();
+ const pending = deferred<AgentChain>();
+ vi.spyOn(modelsApi, 'previewAgentChain').mockReturnValue(pending.promise);
+ const close = vi.fn();
+ renderDialog(vi.fn(), close);
+ await clear(user);
+ const footer = within(document.querySelector<HTMLElement>('.model-hub-route-foot')!);
+ expect((footer.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(true);
+ await user.click(footer.getByRole('button', { name: action === 'undo' ? 'Undo restore' : 'Cancel' }));
+ await act(async () => pending.resolve(inherited));
+ expect(screen.queryByText('After restore: automatic matching')).toBeNull();
+ if (action === 'undo') {
+ expect(screen.getAllByRole('button', { name: 'Remove hop' })).toHaveLength(1);
+ expect(document.querySelector('.model-hub-route-hop-model')?.textContent).toBe('opus-5');
+ expect((footer.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(false);
+ } else expect(close).toHaveBeenCalledOnce();
+ });
+
+ it('invalidates old clear preview on Default routing navigation and keeps Undo through refresh failure', async () => {
+ const user = userEvent.setup();
+ const old = deferred<AgentChain>();
+ const preview = vi.spyOn(modelsApi, 'previewAgentChain')
+ .mockReturnValueOnce(old.promise).mockRejectedValueOnce(new Error('offline')).mockResolvedValue(unconfigured);
+ vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(chain);
+ const openDefaults = vi.fn();
+ const props = { selection: { agent, modelId: 'opus-5', read: readyRegion(chain) }, sources, onClose: vi.fn(), onOpenDefaults: openDefaults, readAgents: vi.fn(), readSources: vi.fn() };
+ const view = (covered: boolean) => <I18nextProvider i18n={i18n}><RouteChainDialog {...props} covered={covered} /></I18nextProvider>;
+ const { rerender } = render(view(false));
+ await clear(user);
+ await user.click(screen.getByRole('button', { name: /Default routing/ }));
+ expect(openDefaults).toHaveBeenCalledOnce();
+ rerender(view(true));
+ rerender(view(false));
+ await screen.findByRole('alert');
+ await act(async () => old.resolve(inherited));
+ expect(screen.queryByText('After restore: automatic matching')).toBeNull();
+ expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(true);
+ await user.click(screen.getByRole('button', { name: 'Retry' }));
+ await screen.findByText('After restore: unconfigured');
+ expect(preview).toHaveBeenCalledTimes(3);
+ await user.click(screen.getByRole('button', { name: 'Undo restore' }));
+ expect(document.querySelector('.model-hub-route-hop-model')?.textContent).toBe('opus-5');
+ });
+
+ it.each(['en', 'zh'] as const)('renders inherited preview, failure, Undo and Save copy in %s', async (lng) => {
+ const user = userEvent.setup();
+ const locale = i18n.cloneInstance({ lng });
+ const copy = (lng === 'en' ? en : zh).settings.models;
+ const pending = deferred<AgentChain>();
+ vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(chain);
+ vi.spyOn(modelsApi, 'previewAgentChain').mockReturnValueOnce(pending.promise).mockResolvedValue(inherited);
+ render(<I18nextProvider i18n={locale}><RouteChainDialog selection={{ agent, modelId: 'opus-5', read: readyRegion(chain) }} sources={sources} onClose={vi.fn()} readAgents={vi.fn()} readSources={vi.fn()} /></I18nextProvider>);
+ await screen.findAllByRole('button', { name: copy.routeDialog.removeHop });
+ await user.click(screen.getAllByRole('button', { name: copy.routeDialog.removeHop })[0]);
+ await user.click(screen.getByRole('button', { name: copy.routeDialog.removeHop }));
+ expect(screen.getByText(copy.routing.previewLoading)).toBeTruthy();
+ const footer = within(document.querySelector<HTMLElement>('.model-hub-route-foot')!);
+ expect(footer.getAllByRole('button').map((button) => button.textContent)).toEqual([copy.routing.undoRestore, copy.routeDialog.cancel, copy.routeDialog.save]);
+ expect((footer.getByRole('button', { name: copy.routeDialog.save }) as HTMLButtonElement).disabled).toBe(true);
+ await act(async () => pending.reject(new Error('offline')));
+ expect(screen.getByRole('alert').textContent).toContain(copy.routing.previewFailed);
+ await user.click(screen.getByRole('button', { name: copy.routeDialog.retry }));
+ await screen.findByText(copy.routing.preview.automatic);
+ await user.click(footer.getByRole('button', { name: copy.routing.undoRestore }));
+ expect(screen.getByText(copy.routing.undoDone)).toBeTruthy();
+ });
+
+ it('reconciles an ambiguous DELETE by inherited intent, retries only failed reads and never repeats the write', async () => {
+ const user = userEvent.setup();
+ const committed = vi.fn();
+ vi.spyOn(modelsApi, 'previewAgentChain').mockResolvedValue(inherited);
+ const restore = vi.spyOn(modelsApi, 'restoreAgentChain').mockRejectedValue(new Error('lost response'));
+ const put = vi.spyOn(modelsApi, 'putAgentChain');
+ renderDialog(committed);
+ vi.mocked(modelsApi.getAgentChain).mockRejectedValueOnce(new Error('offline')).mockResolvedValue(unconfigured);
+ await clear(user);
+ await screen.findByText('After restore: automatic matching');
await user.click(screen.getByRole('button', { name: 'Save' }));
- await waitFor(() => expect(restore).toHaveBeenCalledWith('claude', 'opus-5', undefined));
+ await user.click(await screen.findByRole('button', { name: 'Retry' }));
+ await waitFor(() => expect(modelsApi.getAgentChain).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect((screen.getByRole('button', { name: 'Retry' }) as HTMLButtonElement).disabled).toBe(false));
+ expect(committed).not.toHaveBeenCalled();
+ await user.click(screen.getByRole('button', { name: 'Retry' }));
+ await within(document.querySelector<HTMLElement>('.model-hub-route-foot')!).findByRole('button', { name: 'Done' });
+ expect(committed).toHaveBeenCalledWith({ chain: unconfigured, removed_hops: null, interrupted: null });
+ expect(restore).toHaveBeenCalledOnce();
expect(put).not.toHaveBeenCalled();
});
});
diff --git a/ui/src/components/settings/models/RouteChainDialog.tsx b/ui/src/components/settings/models/RouteChainDialog.tsx
index e4b46983c..3b5f36ca5 100644
--- a/ui/src/components/settings/models/RouteChainDialog.tsx
+++ b/ui/src/components/settings/models/RouteChainDialog.tsx
@@ -199,7 +199,9 @@ export const RouteChainDialog: React.FC<{
const valid = agent
? validateRouteDraft(agent, sources, origin, draft)
: { invalidIndexes: [], valid: false };
- const dirty = manualDraft ? savedOverride === null || !sameRouteDraft(savedOverride.hops, draft) : savedOverride !== null;
+ const restoring = restoreUndo.current !== null;
+ const unresolvedPreview = restoring && preview === null;
+ const dirty = manualDraft ? savedOverride === null || !sameRouteDraft(savedOverride.hops, draft) : restoring;
const draftOrigin = manualDraft ? (draft.length ? 'manual' : null) : (preview ?? chain)?.route_origin ?? null;
const announce = (key: string, params?: Record<string, unknown>) =>
setAnnouncement({ key, params });
@@ -210,6 +212,11 @@ export const RouteChainDialog: React.FC<{
const readChain = React.useCallback(async () => {
if (!selectionBackend) return;
const token = ++generation.current;
+ previewGeneration.current += 1;
+ restoreUndo.current = null;
+ setPreview(null);
+ setPreviewPending(false);
+ setPreviewFailed(false);
setPhase("loading");
try {
const next = await modelsApi.getAgentChain(selectionBackend, modelId);
@@ -274,6 +281,7 @@ export const RouteChainDialog: React.FC<{
return;
}
generation.current += 1;
+ previewGeneration.current += 1;
onClose();
}, [onClose, phase, selection]);
@@ -319,6 +327,11 @@ export const RouteChainDialog: React.FC<{
const remove = (index: number) => {
if (phase === "saving" || phase === "impact" || phase === "refreshing")
return;
+ if (draft.length === 1) {
+ void restoreAutomatic();
+ focusAfterRender(reseedButtonRef);
+ return;
+ }
const next = advanceInteraction({ type: "remove", index });
const nextDraft = next.draft;
const focusedIndex = next.focusIndex;
@@ -422,10 +435,13 @@ export const RouteChainDialog: React.FC<{
committedHops: RouteHop[],
) => {
generation.current += 1;
+ previewGeneration.current += 1;
setChain(nextReport.chain);
setSavedOverride(nextReport.chain.manual_override);
setManualDraft(nextReport.chain.manual_override !== null);
setPreview(null);
+ setPreviewPending(false);
+ setPreviewFailed(false);
restoreUndo.current = null;
setReport(nextReport);
setOrigin(committedHops);
@@ -442,7 +458,7 @@ export const RouteChainDialog: React.FC<{
};
const submit = async (confirmation?: GuardState) => {
- if (!selection || !agent || phase === "saving" || previewPending || (!manualDraft && previewFailed) || (manualDraft && !valid.valid) || !dirty)
+ if (!selection || !agent || phase === "saving" || covered || previewPending || unresolvedPreview || (!manualDraft && previewFailed) || (manualDraft && !valid.valid) || !dirty)
return;
const hops = (confirmation ? (submitted ?? draft) : draft).map((hop) => ({
...hop,
@@ -665,15 +681,18 @@ export const RouteChainDialog: React.FC<{
const restoreAutomatic = React.useCallback(async () => {
if (!agent || previewPending || phase !== 'ready') return;
const token = ++previewGeneration.current;
- const previousDraft = draft.map((hop) => ({ ...hop }));
+ // Record intent before reading: failure must not leave a saveable empty Manual draft.
+ if (manualDraft) restoreUndo.current = draft.map((hop) => ({ ...hop }));
+ setManualDraft(false);
+ setPreview(null);
setPreviewPending(true);
setPreviewFailed(false);
+ advanceInteraction({ type: 'drop-grab' });
+ setSelectorEpoch((current) => current + 1);
try {
const next = await modelsApi.previewAgentChain(agent.backend, modelId, { manual_override: null });
if (token !== previewGeneration.current) return;
- if (manualDraft) restoreUndo.current = previousDraft;
setPreview(next);
- setManualDraft(false);
advanceInteraction({ type: 'reset', draft: next.chain.map(({ source_id, model_id }) => ({ source_id, model_id })) });
setAnnouncement({ key: 'settings.models.routing.restorePending' });
} catch {
@@ -684,8 +703,15 @@ export const RouteChainDialog: React.FC<{
}, [advanceInteraction, agent, draft, manualDraft, modelId, phase, previewPending]);
const wasCovered = React.useRef(covered);
React.useEffect(() => {
+ const leaving = !wasCovered.current && covered;
const returning = wasCovered.current && !covered;
wasCovered.current = covered;
+ if (leaving && restoreUndo.current !== null) {
+ previewGeneration.current += 1;
+ setPreview(null);
+ setPreviewPending(false);
+ setPreviewFailed(false);
+ }
if (!returning || manualDraft) return;
// Defaults can change while this dialog is hidden; explicit drafts remain local.
if (restoreUndo.current) void restoreAutomatic();
@@ -694,6 +720,7 @@ export const RouteChainDialog: React.FC<{
const undoRestore = () => {
previewGeneration.current += 1;
setPreview(null);
+ setPreviewPending(false);
setPreviewFailed(false);
setManualDraft(true);
advanceInteraction({ type: 'reset', draft: restoreUndo.current ?? origin });
@@ -938,7 +965,7 @@ export const RouteChainDialog: React.FC<{
<Button
ref={retryButtonRef}
type="button"
- disabled={!valid.valid}
+ disabled={manualDraft && !valid.valid}
onClick={() => {
generation.current += 1;
void submit();
@@ -1022,15 +1049,19 @@ export const RouteChainDialog: React.FC<{
</div>
) : (
<div className="model-hub-route-body flex flex-col">
- <div className="model-hub-route-origin-line">
+ {!unresolvedPreview && !(manualDraft && draft.length === 0) && <div className="model-hub-route-origin-line">
<RouteOriginBadge origin={draftOrigin} backend={agent!.backend} interactive={false} />
<span>{t(manualDraft ? 'settings.models.routing.frozen' : 'settings.models.routing.follows', { backend })}</span>
- </div>
+ </div>}
+ {unresolvedPreview && <div className="model-hub-route-preview" role="status">
+ {previewPending && <strong>{t('settings.models.routing.previewLoading')}</strong>}
+ <span>{t('settings.models.routing.restorePending')}</span>
+ </div>}
{preview && <div className="model-hub-route-preview" data-origin={preview.route_origin ?? 'unconfigured'} role="status">
<strong>{t(`settings.models.routing.preview.${preview.route_origin ?? 'unconfigured'}`)}</strong>
<span>{t('settings.models.routing.restorePending')}</span>
</div>}
- <h3 className="model-hub-route-label font-bold">
+ {!unresolvedPreview && <><h3 className="model-hub-route-label font-bold">
{t(preview ? 'settings.models.routing.afterSave' : "settings.models.routeDialog.section")}
</h3>
<div inert={previewPending} className="model-hub-route-list flex flex-col border border-border bg-background">
@@ -1046,7 +1077,7 @@ export const RouteChainDialog: React.FC<{
))
) : (
<div className="model-hub-route-empty text-xs text-muted">
- <p>{t(manualDraft ? 'settings.models.routing.manualEmpty' : 'settings.models.routing.noDefaults')}</p>
+ <p>{t(manualDraft ? 'settings.models.routing.draftEmpty' : 'settings.models.routing.noDefaults')}</p>
{!manualDraft && onOpenDefaults && <Button variant="outline" onClick={onOpenDefaults}><ListOrdered aria-hidden />{t('settings.models.routing.configureDefaults')}</Button>}
</div>
)}
@@ -1076,8 +1107,8 @@ export const RouteChainDialog: React.FC<{
</button>
}
/>}
- </div>
- {onOpenDefaults && <button type="button" disabled={previewPending} onClick={onOpenDefaults} className="model-hub-route-reseed flex items-center gap-1.5 self-start font-semibold text-cyan-ink">
+ </div></>}
+ {onOpenDefaults && <button type="button" onClick={onOpenDefaults} className="model-hub-route-reseed flex items-center gap-1.5 self-start font-semibold text-cyan-ink">
<ListOrdered aria-hidden="true" />
{t('settings.models.routing.defaultRouting')}
<span className="text-muted">{(agent?.sources?.order ?? []).map((id) => sourceName(sources, id)).join(' → ')}</span>
@@ -1094,7 +1125,7 @@ export const RouteChainDialog: React.FC<{
</span>
</p>
{previewFailed && <div role="alert" className="text-destructive-ink text-xs"><p>{t('settings.models.routing.previewFailed')}</p><Button variant="ghost" size="sm" disabled={previewPending} onClick={() => void restoreAutomatic()}><RefreshCw aria-hidden />{t('settings.models.routeDialog.retry')}</Button></div>}
- {valid.invalidIndexes.length > 0 && (
+ {manualDraft && valid.invalidIndexes.length > 0 && (
<p
id="model-hub-route-invalid-summary"
className="model-hub-route-invalid-summary"
@@ -1115,6 +1146,7 @@ export const RouteChainDialog: React.FC<{
<DialogPrimitive.Content
aria-busy={
phase === "saving" ||
+ previewPending ||
phase === "refreshing" ||
phase === "reconciling"
}
@@ -1204,7 +1236,7 @@ export const RouteChainDialog: React.FC<{
</span>
) : (
<>
- {(manualDraft || restoreUndo.current) && <Button ref={reseedButtonRef} variant="outline" className="model-hub-dialog-action mr-auto" disabled={phase !== 'ready' || previewPending} onClick={() => restoreUndo.current ? undoRestore() : void restoreAutomatic()}>
+ {(manualDraft || restoring) && <Button ref={reseedButtonRef} variant="outline" className="model-hub-dialog-action mr-auto" disabled={phase !== 'ready'} onClick={() => restoring ? undoRestore() : void restoreAutomatic()}>
{previewPending ? <LoaderCircle className="animate-spin" aria-hidden /> : restoreUndo.current ? <Undo2 aria-hidden /> : <RotateCcw aria-hidden />}
{t(restoreUndo.current ? 'settings.models.routing.undoRestore' : 'settings.models.routing.restoreAutomatic')}
</Button>}
@@ -1215,14 +1247,14 @@ export const RouteChainDialog: React.FC<{
className="model-hub-dialog-action"
onClick={close}
>
- {t(manualDraft || preview ? "settings.models.routeDialog.cancel" : 'settings.models.routing.close')}
+ {t(manualDraft || restoring ? "settings.models.routeDialog.cancel" : 'settings.models.routing.close')}
</Button>
- {!manualDraft && !preview ? (canEditRoute && <Button variant="outline" className="model-hub-dialog-action" disabled={phase !== 'ready'} onClick={() => setManualDraft(true)}><Pencil aria-hidden />{t('settings.models.routing.editRoute')}</Button>) : <Button
+ {!manualDraft && !restoring ? (canEditRoute && <Button variant="outline" className="model-hub-dialog-action" disabled={phase !== 'ready'} onClick={() => setManualDraft(true)}><Pencil aria-hidden />{t('settings.models.routing.editRoute')}</Button>) : <Button
ref={saveButtonRef}
type="button"
className="model-hub-dialog-action"
aria-describedby={
- valid.invalidIndexes.length > 0
+ manualDraft && valid.invalidIndexes.length > 0
? [
"model-hub-route-invalid-summary",
...valid.invalidIndexes.map(
@@ -1231,7 +1263,7 @@ export const RouteChainDialog: React.FC<{
].join(" ")
: undefined
}
- disabled={phase !== "ready" || previewPending || (!manualDraft && previewFailed) || !dirty || (manualDraft && !valid.valid)}
+ disabled={phase !== "ready" || covered || previewPending || unresolvedPreview || (!manualDraft && previewFailed) || !dirty || (manualDraft && !valid.valid)}
onClick={() => void submit()}
>
{t("settings.models.routeDialog.save")}
diff --git a/ui/src/components/settings/models/RouteRecordedTurn.test.tsx b/ui/src/components/settings/models/RouteRecordedTurn.test.tsx
index 4911cfacb..af388321c 100644
--- a/ui/src/components/settings/models/RouteRecordedTurn.test.tsx
+++ b/ui/src/components/settings/models/RouteRecordedTurn.test.tsx
@@ -10,7 +10,7 @@ import { PERSISTED_TURN_CONTRACT_VERSIONS } from './types';
import type { TurnProvenance } from './types';
const record: TurnProvenance = {
- contract_version: 9, turn_id: 'turn-recorded', ts: '2026-09-05T15:00:00Z', agent: 'codex', requested_model_id: 'requested-model',
+ contract_version: 10, turn_id: 'turn-recorded', ts: '2026-09-05T15:00:00Z', agent: 'codex', requested_model_id: 'requested-model',
outcome: 'failed_terminal', failed_attempts: [], served: null, canceled_attempt: null, model_supply_state: null, blockers: [],
terminal_error: { source_id: 'src_historical', configured_model_id: 'historical-model', channel: 'hub', reason: 'invalid_parameter', stream_started: false, http_status: 404, upstream_error_code: 'model_not_found' },
};
@@ -28,11 +28,15 @@ describe('recorded turn error', () => {
await user.click(screen.getByRole('button', { name: 'View error details' }));
expect(screen.getByRole('dialog').querySelector('pre')?.textContent).toBe(JSON.stringify(record, null, 2));
});
- it('reads old terminal errors without inventing model-not-found evidence', async () => {
- vi.spyOn(modelsApi, 'getAgentProvenance').mockResolvedValue({ ...record, contract_version: PERSISTED_TURN_CONTRACT_VERSIONS[0], terminal_error: { source_id: 'src_old', configured_model_id: 'old-model', channel: 'hub', reason: 'invalid_parameter', stream_started: false } });
+ it.each(PERSISTED_TURN_CONTRACT_VERSIONS)('reads v%s terminal errors without rewriting records or inventing model-not-found evidence', async (version) => {
+ const user = userEvent.setup();
+ const historical: TurnProvenance = { ...record, contract_version: version, terminal_error: { source_id: 'src_old', configured_model_id: 'old-model', channel: 'hub', reason: 'invalid_parameter', stream_started: false } };
+ vi.spyOn(modelsApi, 'getAgentProvenance').mockResolvedValue(historical);
render(view());
expect(await screen.findByText(/Latest recorded turn.*Request parameters rejected/)).toBeTruthy();
expect(screen.queryByText(/model not found/)).toBeNull();
+ await user.click(screen.getByRole('button', { name: 'View error details' }));
+ expect(screen.getByRole('dialog').querySelector('pre')?.textContent).toBe(JSON.stringify(historical, null, 2));
});
it.each(['served', 'canceled', null] as const)('does not show an old error when latest outcome is %s', async (outcome) => {
const read = vi.spyOn(modelsApi, 'getAgentProvenance').mockResolvedValue(outcome ? { ...record, outcome, terminal_error: null } : null);
diff --git a/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx b/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx
index 0f5757a33..6ff7e69ee 100644
--- a/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx
+++ b/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx
@@ -31,7 +31,7 @@ const runtime = (
? 'unresolved' as const
: hostPlatform === 'linux-amd64' ? 'unsupported' as const : 'resolved' as const;
return {
- contract_version: 9,
+ contract_version: 10,
...(hostPlatform === undefined ? {} : { host_platform: hostPlatform }),
manifest: resolution === 'unresolved'
? { name: 'cliproxyapi', resolution, assets: [] }
diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
index 29431b9a8..81a21e09d 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
@@ -33,7 +33,7 @@ const manifest = {
} satisfies RuntimeManifest;
const runtime: RuntimeDependency = {
- contract_version: 9,
+ contract_version: 10,
manifest,
status: { installed_version: '1', verified: true, health: 'ok' },
};
@@ -84,7 +84,7 @@ const takeoverAgent: AgentSupply = {
};
const takeoverChain: AgentChain = { manual_override: {hops:[{source_id:'src_head',model_id:'gpt-5.6-sol'},{source_id:'src_relay',model_id:'gpt-5.6-sol'}]}, route_origin: "manual" as const,
- contract_version: 9,
+ contract_version: 10,
backend: 'codex',
model_id: 'gpt-5.6-sol',
current: { source_id: 'src_relay', model_id: 'gpt-5.6-sol' },
@@ -1016,7 +1016,7 @@ describe('SettingsModelsPage surface branches', () => {
builtin_models: [modelId],
};
const affectedChain: AgentChain = { manual_override: {hops:[{source_id:retainedSource.id,model_id:modelId}]}, route_origin: "manual" as const,
- contract_version: 9,
+ contract_version: 10,
backend: 'claude',
model_id: modelId,
current: { source_id: retainedSource.id, model_id: modelId },
diff --git a/ui/src/components/settings/models/SupplyGraph.test.ts b/ui/src/components/settings/models/SupplyGraph.test.ts
index 5990654c7..2397e1474 100644
--- a/ui/src/components/settings/models/SupplyGraph.test.ts
+++ b/ui/src/components/settings/models/SupplyGraph.test.ts
@@ -7,7 +7,7 @@ import { buildSupplyRelations as buildRelations } from './supplyRelations';
import type { AgentChain, AgentSupply, RuntimeDependency, Source } from './types';
const runtime: RuntimeDependency = {
- contract_version: 9,
+ contract_version: 10,
manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'fixture', assets: [] },
status: { installed_version: '1.0.0', verified: true, listening: null, health: 'ok', last_check: null },
};
@@ -47,7 +47,7 @@ const agent: AgentSupply = {
};
const chain = (current: string, headHealth: AgentChain['chain'][number]['health'] = 'healthy', headRunnable = true, reason: AgentChain['chain'][number]['reason'] = null): AgentChain => ({ manual_override: {hops:[{source_id:'native',model_id:'model-a'},{source_id:'relay',model_id:'model-a'},{source_id:'unused',model_id:'model-a'}]}, route_origin: "manual" as const,
- contract_version: 9,
+ contract_version: 10,
backend: 'claude',
model_id: 'model-a',
current: { source_id: current, model_id: 'model-a' },
diff --git a/ui/src/components/settings/models/apiFailure.test.ts b/ui/src/components/settings/models/apiFailure.test.ts
index 0d650bb2b..4f7a73c93 100644
--- a/ui/src/components/settings/models/apiFailure.test.ts
+++ b/ui/src/components/settings/models/apiFailure.test.ts
@@ -33,7 +33,7 @@ afterEach(() => {
describe('apiFailure — whether the route named the failure', () => {
it('posts installation to the dedicated runtime route', async () => {
const runtime = {
- contract_version: 9,
+ contract_version: 10,
manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1', source_sha: 'sha', assets: [] },
status: { installed_version: null, verified: false, listening: null, health: 'installing', last_check: null },
} as const;
diff --git a/ui/src/components/settings/models/gatewayAdoption.test.ts b/ui/src/components/settings/models/gatewayAdoption.test.ts
index 73501654d..2eba9a156 100644
--- a/ui/src/components/settings/models/gatewayAdoption.test.ts
+++ b/ui/src/components/settings/models/gatewayAdoption.test.ts
@@ -14,7 +14,7 @@ const agent = (mode: AgentSupply['mode']): AgentSupply => ({
});
const runtime = (health: RuntimeDependency['status']['health']): RuntimeDependency => ({
- contract_version: 9,
+ contract_version: 10,
manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1', source_sha: 'a'.repeat(40), assets: [] },
status: { installed_version: health === 'not_installed' ? null : '1', verified: health !== 'not_installed', health },
});
diff --git a/ui/src/components/settings/models/routeChainDraft.test.ts b/ui/src/components/settings/models/routeChainDraft.test.ts
index 79e9c0fd7..a4884ae3c 100644
--- a/ui/src/components/settings/models/routeChainDraft.test.ts
+++ b/ui/src/components/settings/models/routeChainDraft.test.ts
@@ -3,6 +3,8 @@ import { describe, expect, it } from "vitest";
import {
reorderRouteDraft,
routeCandidates,
+ routeChainMatchesAttempt,
+ sameManualOverride,
validateRouteDraft,
} from "./routeChainDraft";
import type { AgentSupply, RouteHop, Source } from "./types";
@@ -45,6 +47,16 @@ const sources = [
];
describe("routeChainDraft", () => {
+ it('requires a nonempty Manual draft and compares compatibility-empty attempts as inherited intent', () => {
+ expect(validateRouteDraft(agent, sources, [], []).valid).toBe(false);
+ expect(sameManualOverride(null, { hops: [] })).toBe(true);
+ expect(sameManualOverride({ hops: [] }, null)).toBe(true);
+ const hops = [{ source_id: 'src_a', model_id: 'model-a' }];
+ expect(sameManualOverride(null, { hops })).toBe(false);
+ expect(routeChainMatchesAttempt({ backend: 'claude', model_id: 'opus-5', manual_override: null } as Parameters<typeof routeChainMatchesAttempt>[0], {
+ backend: 'claude', modelId: 'opus-5', submitted: [], manual_override: { hops: [] },
+ })).toBe(true);
+ });
it('allows unknown API-key models while keeping subscription admission and retirement', () => {
const unknown = { source_id: 'src_a', model_id: 'unlisted' };
expect(validateRouteDraft(agent, sources, [], [unknown]).valid).toBe(true);
diff --git a/ui/src/components/settings/models/routeChainDraft.ts b/ui/src/components/settings/models/routeChainDraft.ts
index 00c63671d..aca698f8f 100644
--- a/ui/src/components/settings/models/routeChainDraft.ts
+++ b/ui/src/components/settings/models/routeChainDraft.ts
@@ -83,7 +83,7 @@ export function validateRouteDraft(
});
return {
invalidIndexes: allInvalidIndexes,
- valid: allInvalidIndexes.length === 0,
+ valid: draft.length > 0 && allInvalidIndexes.length === 0,
};
}
@@ -113,7 +113,7 @@ export const sameRouteDraft = (left: RouteHop[], right: RouteHop[]): boolean =>
left.every((hop, index) => identity(hop) === identity(right[index]));
export const sameManualOverride = (left: ManualRouteOverride | null, right: ManualRouteOverride | null): boolean =>
- left === null || right === null ? left === right : sameRouteDraft(left.hops, right.hops);
+ sameRouteDraft(left?.hops ?? [], right?.hops ?? []);
export const routeChainMatchesAttempt = (
chain: AgentChain,
diff --git a/ui/src/components/settings/models/runtimeLifecycle.test.ts b/ui/src/components/settings/models/runtimeLifecycle.test.ts
index da5634c47..b4ba4b3c3 100644
--- a/ui/src/components/settings/models/runtimeLifecycle.test.ts
+++ b/ui/src/components/settings/models/runtimeLifecycle.test.ts
@@ -11,7 +11,7 @@ const asset = (platform: 'darwin-arm64' | 'linux-amd64') => ({
});
const runtime = (resolution: 'resolved' | 'unresolved' | 'unsupported'): RuntimeDependency => ({
- contract_version: 9,
+ contract_version: 10,
host_platform: 'darwin-arm64',
manifest: resolution === 'unresolved'
? { name: 'cliproxyapi', resolution, assets: [] }
diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.ts
index 17bb5f341..31d2fd87a 100644
--- a/ui/src/components/settings/models/types.ts
+++ b/ui/src/components/settings/models/types.ts
@@ -10,8 +10,8 @@
// and the PR records the server implementation and feature-flag activation
// edge. The client never synthesizes a fallback payload shape.
-export const CONTRACT_VERSION = 9 as const;
-export const PERSISTED_TURN_CONTRACT_VERSIONS = [5, 6, 7, 8, 9] as const;
+export const CONTRACT_VERSION = 10 as const;
+export const PERSISTED_TURN_CONTRACT_VERSIONS = [5, 6, 7, 8, 9, 10] as const;
export const AGENT_CHAIN_CONTRACT_VERSION = CONTRACT_VERSION;
export const PROBE_RESULT_CONTRACT_VERSION = CONTRACT_VERSION;
diff --git a/ui/src/components/settings/models/vocabulary.test.ts b/ui/src/components/settings/models/vocabulary.test.ts
index 3c47bb066..f5a5d149c 100644
--- a/ui/src/components/settings/models/vocabulary.test.ts
+++ b/ui/src/components/settings/models/vocabulary.test.ts
@@ -11,6 +11,11 @@ const leaves = (node: unknown): string[] =>
: [];
describe('Models page vocabulary', () => {
+ it('describes an empty inherited route as lacking an eligible default provider', () => {
+ expect(en.settings.models.routeDialog.empty).toBe('This model follows default routing, but no eligible provider can route it.');
+ expect(zh.settings.models.routeDialog.empty).toBe('此模型跟随默认路由,但目前没有符合条件的供应商。');
+ });
+
it('contains none of the retired user-facing terms', () => {
const copy = leaves(zh.settings.models).join('\n');
expect(copy).not.toMatch(/菜单固定|跟随推荐|中枢 Hub|按量\s*\$|映射|供给|来源|型号|自定义顺序|已改为手动|恢复默认/);
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 6d561e448..51faff206 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1193,8 +1193,9 @@
"restorePending": "Not saved yet. The saved route is still in use.",
"afterSave": "Route after saving",
"preview": { "automatic": "After restore: automatic matching", "passthrough": "After restore: original-name passthrough", "unconfigured": "After restore: unconfigured" },
- "previewFailed": "Could not preview automatic routing. Your draft is unchanged. Try again.",
- "manualEmpty": "This saved route is empty. Restore automatic to follow defaults.",
+ "previewLoading": "Reading inherited routing...",
+ "previewFailed": "Could not preview inherited routing. Nothing has been saved. Retry or undo the restore.",
+ "draftEmpty": "No route entries in this draft.",
"noDefaults": "No default provider can route this model. Add a matching provider or an eligible API-key provider.",
"inventoryNotProvided": "Model list not provided",
"configureDefaults": "Configure default routing",
@@ -1404,7 +1405,7 @@
"refreshing": "Route chain saved. Refreshing the model surface…",
"fail": { "read": "The route chain could not be read", "save": "The route chain was not saved", "unconfirmed": "The save outcome is not confirmed", "reconcileRead": "The current model surface could not be read" },
"retry": "Retry",
- "empty": "This route chain is empty. Add a hop, or leave it unconfigured.",
+ "empty": "This model follows default routing, but no eligible provider can route it.",
"impact": { "title": "The route chain was saved", "detail": "These are the items this save actually removed or interrupted.", "refreshFail": "The route chain was saved, but the model surface could not be refreshed.", "done": "Done" },
"hint": "This model has a saved, fixed route. Default routing changes do not overwrite it."
},
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 5a6144fb9..4eeee835b 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1193,8 +1193,9 @@
"restorePending": "尚未保存,当前仍使用已保存的路由。",
"afterSave": "保存后的路由",
"preview": { "automatic": "恢复后:自动匹配", "passthrough": "恢复后:原名透传", "unconfigured": "恢复后:未配置" },
- "previewFailed": "自动路由预览暂时不可用,草稿保持不变。请重试。",
- "manualEmpty": "此模型已保存空路由。恢复自动后可跟随默认路由。",
+ "previewLoading": "正在读取继承路由…",
+ "previewFailed": "无法预览继承路由,尚未保存任何更改。请重试或撤销恢复。",
+ "draftEmpty": "草稿中暂无路由条目。",
"noDefaults": "暂无可路由此模型的默认供应商。请加入匹配的供应商或符合条件的 API Key 供应商。",
"inventoryNotProvided": "模型列表未提供",
"configureDefaults": "设置默认路由",
@@ -1404,7 +1405,7 @@
"refreshing": "路由已保存,正在刷新模型页面…",
"fail": { "read": "路由暂时不可用", "save": "路由没有保存", "unconfirmed": "保存结果还没确认", "reconcileRead": "当前模型页面暂时不可用" },
"retry": "重试",
- "empty": "这条路由是空的。添加一个路由项,或保持为空。",
+ "empty": "此模型跟随默认路由,但目前没有符合条件的供应商。",
"impact": { "title": "路由已保存", "detail": "以下是这次保存实际移除或中断的项目。", "refreshFail": "路由已保存,但模型页面暂时无法刷新。", "done": "完成" },
"hint": "此模型已保存固定路由,默认路由的调整不会覆盖它。"
},