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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
docs(model-hub): close K4 contract gaps (#1326)
Call Whiteea26ee6a07be
diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.mdindex d8609f44a..6670b0737 100644--- a/docs/plans/model-hub-contracts/README.md+++ b/docs/plans/model-hub-contracts/README.md@@ -1,11 +1,12 @@# Model Hub contracts-Status: **FINAL v5 shape, implementation-gated (2026-08-09)**.+Status: **FINAL v5 shape, implementation-gated (2026-08-11 contract completion)**.These files describe the terminal contract for Model Hub before first release. There isno v4-to-v5 data migration, compatibility reader, conversion transaction, or versiondiscriminator: Model Hub has not shipped. `contract_version` is 5 wherever a versioned-object exists.+object exists. The owner-approved pre-release network correction removes the earlier+persistent network/timeout cooldown spelling without adding a compatibility path.The contracts and their consumers must coexist on one tested PR head before Model Hubcan be enabled. CI evaluates that head, not individual commits. A green intermediate@@ -25,8 +26,9 @@ commit is not evidence that the complete final protocol has landed.- The protocol vocabulary is exactly `anthropic | openai_responses | openai_chat`.`base_url` already distinguishes official endpoints from relays and self-hostedgateways; no fourth protocol value is defined.-- Source health is global. Native CLI process availability and exact-hop integrity are- live execution facts and never silently rewrite stored configuration.+- Source health is global and changes only from shaped explicit upstream classifications.+ Native CLI availability, exact-hop integrity, and bounded pre-first-byte connection+ backoff are live execution facts and never silently rewrite stored configuration.- Supply state is pull-oriented. Successful fallback is silent; Gateway and Usage arethe user-visible inspection surfaces.@@ -56,8 +58,9 @@ Contract prose points to those authorities and does not add branches.across time, quota, and health changes. Live runnability and current executionposition may change; Route membership and order may not.6. Every Source model id is unique within that Source. The final model item shape is- `{id, origin, reasoning_efforts, display_name?, discovered_at?}`; effort lists are- editable capability declarations, may be empty, and have no selected/default item.+ `{id, origin, reasoning_efforts, retired?, display_name?, discovered_at?}`; effort+ lists are editable capability declarations, may be empty, and have no selected/default+ item. `retired: true` is a persistent discovered-model tombstone and never supplies.7. A backend has at most one `native_cli` Source. Additional accounts are Hub-heldSources.8. Direct mode and a Native hop are distinct. Direct bypasses Gateway for the backend;@@ -87,6 +90,7 @@ The terminal value 5 must coexist in all registered version locations on the sam- `probe-result.schema.json`- `observation-result.schema.json`- `runtime-dependency.schema.json`+- `guard-refusal.schema.json`- `turn-provenance.schema.json`- `core/handlers/model_hub/service.py`- `core/handlers/model_hub/provenance.py`@@ -106,15 +110,17 @@ revision; the discovering lane does not reinterpret or edit the contract in plac| File | Authority and consumer role || --- | --- || `source.schema.json` | Source identity, channel, three protocols, state, usage, inventory, credential reference, and audit metadata. |+| `source-create.schema.json` | API-key Source creation request, transient credential boundary, probe-order hint, and lost-response correlation. || `agent-supply.schema.json` | Backend mode, explicit policy-free Source order, configuration eligibility, model-supply and backend-health projections. |-| `agent-chain.schema.json` | Read projection of exact stored hops plus current execution position, runnability, blockers, retry metadata, and model supply state. |-| `probe-result.schema.json` | Saved recovery probes and route probes over exact configured hops. |+| `agent-chain.schema.json` | Read projection of exact stored hops plus current execution position, runnability, blockers, live connection backoff, retry metadata, and model supply state. |+| `probe-result.schema.json` | Saved recovery probes and route probes over exact configured hops, including the live connection-backoff reason without persistent network health. || `observation-result.schema.json` | Non-persisting Add-time connectivity, authentication, response-backed protocol, and inventory observation. || `turn-provenance.schema.json` | Exactly attributed turn attempts and terminal outcome; no policy or mapping discriminator. || `resolution-event.schema.json` | Pull-feed Source/resolution records and their closed reason/detail vocabulary. || `oauth-flow.schema.json` | Subscription creation and re-auth presentation without secret material. || `migration-scan.schema.json` | Copy-only import of existing native CLI/provider configuration; not an internal contract migration. || `runtime-dependency.schema.json` | Managed local Gateway asset, lifecycle, and health. |+| `guard-refusal.schema.json` | Shared guarded-mutation refusal whose two arrays are the exact plan echoed by a confirmed retry. || `api.md` | Routes, envelopes, exact Source order and Route-chain writes, guards, OAuth/import results, provenance, and runtime status. || `opencode-overlay.md` | Stable OpenCode provider/model identifiers and exact configured-hop overlay behavior. || `adapter-interface.py` | Adapter protocol, observation, credential, discovery, invocation, cleanup, and classification boundary. |diff --git a/docs/plans/model-hub-contracts/agent-chain.schema.json b/docs/plans/model-hub-contracts/agent-chain.schema.jsonindex acd60ccd6..4574a813b 100644--- a/docs/plans/model-hub-contracts/agent-chain.schema.json+++ b/docs/plans/model-hub-contracts/agent-chain.schema.json@@ -36,11 +36,15 @@"source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },"model_id": { "type": "string", "minLength": 1 },"channel": { "enum": ["hub", "native_cli"] },- "health": { "enum": ["healthy", "cooldown", "needs_action", "error"] },+ "health": {+ "enum": ["healthy", "cooldown", "backoff", "needs_action", "error"],+ "description": "Source-global health mapped to this hop, plus live backoff. backoff is an in-memory connection throttle before the first user-visible model-output byte and is never persisted on Source or configuration. It is projected only over an otherwise healthy hop whose exact Source/model capability is present; every durable Source/capability blocker suppresses it."+ },"runnable": { "type": "boolean" },"reason": {"anyOf": [{ "const": "native_cli_unavailable" },+ { "const": "models.source.backoff.connection_failed" },{"enum": ["source_missing",@@ -55,7 +59,11 @@{ "type": "null" }]},- "retry_at": { "type": ["string", "null"], "format": "date-time" }+ "retry_at": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "When health is backoff, this live deadline is strictly later than the read assembler's captured assembly time. The API normalizes an expired overlay to its underlying non-backoff health before validation and serialization; JSON Schema enforces only the date-time shape, not the relation to a moving clock."+ }},"allOf": [{@@ -73,13 +81,31 @@{"if": { "properties": { "health": { "const": "cooldown" } }, "required": ["health"] },"then": { "required": ["retry_at"], "properties": { "retry_at": { "type": "string" } } }+ },+ {+ "if": { "properties": { "health": { "const": "backoff" } }, "required": ["health"] },+ "then": {+ "required": ["reason", "retry_at"],+ "properties": {+ "runnable": { "const": false },+ "reason": {+ "enum": ["models.source.backoff.connection_failed", "native_cli_unavailable"],+ "description": "Connection backoff is the reason unless an unavailable native CLI is the simultaneous actionable process blocker; in that combined state native_cli_unavailable takes the single reason slot while health and retry_at retain the backoff facts."+ },+ "retry_at": { "type": "string" }+ }+ }+ },+ {+ "if": { "properties": { "health": { "enum": ["healthy", "cooldown", "needs_action", "error"] } }, "required": ["health"] },+ "then": { "properties": { "reason": { "not": { "const": "models.source.backoff.connection_failed" } } } }}]}},"supply_state": {"enum": ["ok", "waiting", "interrupted"],- "description": "ok has a runnable hop; waiting is a non-empty all-cooldown chain with no process blocker; interrupted covers an empty chain or an action/process blocker."+ "description": "ok has a runnable hop; waiting is a non-empty chain whose only blockers are Source cooldown or live connection backoff and which has no process blocker; interrupted covers an empty chain or an action/process blocker. A durable blocker cannot be hidden by a simultaneous live backoff."}},"allOf": [@@ -97,10 +123,40 @@"properties": {"chain": {"minItems": 1,- "items": { "properties": { "health": { "const": "cooldown" }, "runnable": { "const": false }, "reason": { "type": "null" } }, "required": ["health", "runnable", "reason"] }+ "items": {+ "properties": {+ "health": { "enum": ["cooldown", "backoff"] },+ "runnable": { "const": false },+ "reason": { "enum": [null, "models.source.backoff.connection_failed"] }+ },+ "required": ["health", "runnable", "reason"]+ }}}}+ },+ {+ "if": {+ "properties": {+ "chain": {+ "minItems": 1,+ "items": {+ "properties": {+ "health": { "enum": ["cooldown", "backoff"] },+ "runnable": { "const": false },+ "reason": { "enum": [null, "models.source.backoff.connection_failed"] }+ },+ "required": ["health", "runnable", "reason"]+ }+ }+ },+ "required": ["chain"]+ },+ "then": {+ "properties": {+ "supply_state": { "const": "waiting" }+ }+ }}],"examples": [@@ -112,6 +168,14 @@"current": null,"supply_state": "waiting"},+ {+ "contract_version": 5,+ "backend": "opencode",+ "model_id": "custom/glm-5.2",+ "chain": [{ "source_id": "src_relay9c1x", "model_id": "glm-5.2", "channel": "hub", "health": "backoff", "runnable": false, "reason": "models.source.backoff.connection_failed", "retry_at": "2026-08-11T11:55:08Z" }],+ "current": null,+ "supply_state": "waiting"+ },{"contract_version": 5,"backend": "codex",@@ -120,6 +184,14 @@"current": null,"supply_state": "interrupted"},+ {+ "contract_version": 5,+ "backend": "codex",+ "model_id": "gpt-5.6",+ "chain": [{ "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "channel": "native_cli", "health": "backoff", "runnable": false, "reason": "native_cli_unavailable", "retry_at": "2026-08-11T11:55:08Z" }],+ "current": null,+ "supply_state": "interrupted"+ },{"contract_version": 5,"backend": "claude",diff --git a/docs/plans/model-hub-contracts/agent-supply.schema.json b/docs/plans/model-hub-contracts/agent-supply.schema.jsonindex 9c5fb4db6..2495562e4 100644--- a/docs/plans/model-hub-contracts/agent-supply.schema.json+++ b/docs/plans/model-hub-contracts/agent-supply.schema.json@@ -8,6 +8,10 @@"additionalProperties": false,"properties": {"backend": { "enum": ["claude", "codex", "opencode"] },+ "cli_present": {+ "type": "boolean",+ "description": "Server-authoritative fact that this backend's configured CLI executable is present on the Avibe host. It does not prove login, process readiness, or Source health. OPTIONAL in the reusable schema and REQUIRED on AgentSupply API payloads."+ },"mode": {"enum": ["hub", "direct"],"description": "Gateway or Direct. Existing installations start Direct until the user switches; fresh installations default Gateway. A native_cli Source is one configured Gateway hop and is distinct from Direct mode."@@ -124,7 +128,7 @@"type": ["string", "null"],"enum": ["ok", "degraded", "waiting", "interrupted", null],"$comment": "This rollup is process-aware, not health-only. A process-unavailable native hop makes a no-runnable chain interrupted rather than waiting.",- "description": "Derived supply rollup (spec §4.5), computed per request and never persisted, for the model of the route named by `selected_by_agent`. It reads the same complete runnability predicate as AgentChain: source-global health permits AND this process can serve the channel. ok = serving from the intended head; degraded = serving through fallback and/or with blocked members; waiting = no runnable member and every member is a not-retry-ready cooldown that is process-available; interrupted = no runnable member and at least one blocker needs action — including a native CLI unavailable in this process at any health — or the capability chain is empty. null when mode=direct or when Hub has no pinned selection."+ "description": "Derived supply rollup (spec §4.5), computed per request and never persisted, for the model of the route named by `selected_by_agent`. It reads the same complete runnability predicate as AgentChain: source-global health permits AND no live connection backoff applies AND this process can serve the channel. ok = serving from the intended head; degraded = serving through fallback and/or with blocked members; waiting = no runnable member and every member is a Source cooldown or live connection backoff that is process-available; interrupted = no runnable member and at least one blocker needs action — including a native CLI unavailable in this process at any health — or the capability chain is empty. null when mode=direct or when Hub has no pinned selection."},"menu": {"type": ["object", "null"],@@ -157,9 +161,24 @@"type": "integer","minimum": 0,"$comment": "Configuration visibility is not candidate availability. Every stored hop remains counted regardless of live runnability.",- "description": "Length of the exact configured Route chain, including cooling and process-unavailable native CLI hops. It is not a count of currently runnable candidates. Zero marks a structurally empty Route; live blockers appear through supply_status."+ "description": "Length of the exact configured Route chain, including cooling, live-connection-backoff, and process-unavailable native CLI hops. It is not a count of currently runnable candidates. Zero marks a structurally empty Route; live blockers appear through supply_status."+ },+ "has_runnable_hop": {+ "type": "boolean",+ "description": "True exactly when at least one exact stored hop is runnable under the same source-health AND process-availability axiom as AgentChain. False distinguishes an all-stale or empty Route from a Route with live supply without changing chain_length. OPTIONAL in the reusable schema and REQUIRED on AgentSupply API payloads."}- }+ },+ "allOf": [+ {+ "if": {+ "properties": { "chain_length": { "const": 0 } },+ "required": ["chain_length"]+ },+ "then": {+ "properties": { "has_runnable_hop": { "const": false } }+ }+ }+ ]}},"named_agents": {diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex 5423f4016..60e08c6c2 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -1,11 +1,14 @@# Model Hub — REST API contract-Status: **FINAL v5 (2026-08-09)**. All endpoints live under `/api/models/`.+Status: **FINAL v5 (2026-08-11 contract completion)**. All endpoints live under `/api/models/`.Success envelope: `{ok: true, contract_version: 5, ...}`.Failure envelope:`{ok: false, contract_version: 5, 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+that a confirmed retry echoes unchanged.Authentication and CSRF rules are the existing UI-server rules.The shared envelope and every versioned nested contract use terminal version 5. Model@@ -15,34 +18,36 @@ Hub has not shipped, so there is no internal contract migration or compatibility| Method and path | Request → response | Normative notes || --- | --- | --- |-| GET `/api/models/sources` | → `{sources: Source[]}` | Unordered asset inventory. Array order is never a spend order. |+| GET `/api/models/sources` | → `{sources: Source[]}` | Unordered asset inventory. Every Source carries server-derived `adopted_by` and any persisted `client_nonce`; array order is never a spend order. || POST `/api/models/sources/observe` | `{vendor, base_url?, key, protocol_order?}` → `{observation: SourceObservation}` | Non-persisting connectivity/authentication/protocol/inventory observation. `protocol_order` only orders the three probes; it never supplies a conclusion. No credential reference is returned. |-| POST `/api/models/sources` | `SourceCreate` → `{source: Source, added_to: AddedTo[], adopted_by: AdoptedBy[]}` | The server assigns `id` and `created_at`; plaintext keys are transient. Add-time matching and placement are materialized before response. |-| PATCH `/api/models/sources/<id>` | `{display_name?, base_url?, force?: boolean}` → guarded Source-mutation envelope | Metadata/Base-URL mutation from the authoritative matrix in `model-hub.md` §4.5. |-| PUT `/api/models/sources/<id>/credential` | `{key, force?: boolean}` → guarded Source-mutation envelope | API-key replacement. `force` is a JSON body field, never a query parameter. |-| POST `/api/models/sources/<id>/reauth` | `{acknowledge_irreversible?: true}` → `{flow: OAuthFlow}` | A `native_cli` source requires the acknowledgement before OAuth starts. See repair rules. |-| DELETE `/api/models/sources/<id>?force=<bool>` | → guarded `409` or `{removed_hops, interrupted}` | A confirmed delete removes the Source from every backend Source order and Route chain in one transaction. |-| POST `/api/models/sources/<id>/refresh` | `{force?: boolean}` → guarded Source-mutation envelope | The sole saved connectivity/discovery/recovery mutation. |+| POST `/api/models/sources` | `source-create.schema.json` → `{source: Source, added_to: AddedTo[], adopted_by: AdoptedBy[]}` | The server assigns `id` and `created_at`; plaintext keys are transient. Add-time matching and placement are materialized before response. An optional `client_nonce` is reserved only in process before work and persisted only on the committed Source for list-based lost-response reconciliation. |+| PATCH `/api/models/sources/<id>` | `{display_name?, base_url?, force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded Source-mutation envelope | Metadata/Base-URL mutation from the authoritative matrix in `model-hub.md` §4.5. A forced retry confirms only an exact echo of the refusal plan. |+| PUT `/api/models/sources/<id>/credential` | `{key, force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded Source-mutation envelope | API-key replacement. Confirmation fields are JSON body fields. Success is exactly `{source, removed_hops, interrupted}`; the OAuth-only repair tail never appears here. |+| POST `/api/models/sources/<id>/reauth` | `{acknowledge_irreversible?: true}` → `{flow: OAuthFlow}` | Both Hub OAuth and `native_cli` Sources require the acknowledgement before OAuth starts. Missing or false acknowledgement returns `reauth_confirmation_required` before any adapter call. See repair rules. |+| DELETE `/api/models/sources/<id>?force=<bool>` | `{would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or `{removed_hops, interrupted}` | A confirmed delete removes the Source from every backend Source order and Route chain in one transaction. A nonempty destructive plan commits only when the body exactly echoes the current refusal plan. |+| POST `/api/models/sources/<id>/refresh` | `{force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded Source-mutation envelope | The sole saved connectivity/discovery/recovery mutation. || POST `/api/models/sources/<source_id>/models` | `{model_id, display_name?, reasoning_efforts}` → `{source: Source}` | Creates one user-authored model entry. The Source identity comes only from the path. || PATCH `/api/models/sources/<source_id>/models/<model_id>` | `{reasoning_efforts}` → `{source: Source}` | Replaces the complete capability list on either model origin without changing identity, origin, or Routes. |-| DELETE `/api/models/sources/<source_id>/models/<model_id>` | `{force?: boolean}` → API-boundary refusal, guarded `409`, or Source-mutation success | Deletes only a user-authored entry. A discovered entry returns `source_model_managed_upstream`. |-| GET `/api/models/agents` | → `{agents: AgentSupply[]}` | Backend records include `named_agents`, the enabled named-Agent live projection. |+| DELETE `/api/models/sources/<source_id>/models/<model_id>` | `{force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or Source-mutation success | Deletes a manual entry; for a discovered entry it persists `retired: true` without deleting the row. Both outcomes use the same exact-hop and supply guards. |+| GET `/api/models/agents` | → `{agents: AgentSupply[]}` | Backend records include server-authoritative `cli_present` and `named_agents`, the enabled named-Agent live projection. || GET `/api/models/agents/<backend>/sources` | → `{agent: AgentSupply}` | Returns the authoritative effective order and eligibility. |-| PUT `/api/models/agents/<backend>/sources` | `{order: string[]}` → `{agent: AgentSupply}` | Stores and re-echoes the complete canonical order; no policy state exists. |-| PATCH `/api/models/agents/<backend>/mode` | `{mode}` → `{agent: AgentSupply}` | Explicit `hub` / `direct` switch. |+| PUT `/api/models/agents/<backend>/sources` | `{order: string[]}` → `{agent: AgentSupply}` | Stores and re-echoes the complete canonical order; no policy state exists. This route never touches a Route chain and has no guarded `409` branch. |+| POST `/api/models/agents/<backend>/chains/reorder` | → `{agent: AgentSupply}` | Idempotently reorders every stored Route by the current Source order without adding, removing, remapping, matching, or guarding. The total order is defined below. |+| PATCH `/api/models/agents/<backend>/mode` | `{mode}` → `{agent: AgentSupply}` | Explicit `hub` / `direct` switch. A qualifying Direct → Gateway switch atomically adopts the recognized CLI login as the first native Source; other switches create nothing. || PUT `/api/models/agents/opencode/menu` | `{menu}` → `{agent: AgentSupply}` | Open-menu configuration. || 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}` → guarded `409` or `{chain, removed_hops, interrupted}` | Replaces the exact Source/model pairs in submitted order after validating new or changed pairs; it is the `mutation.route_replace` row of the authoritative mutation matrix. |+| 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}` | Replaces the exact Source/model pairs in submitted order after validating new or changed pairs; it is the `mutation.route_replace` row of the authoritative mutation matrix. A visible noninterrupting hop removal is ordinary success; only a resulting protected-supply interruption enters the guard. || POST `/api/models/agents/<backend>/probe` | `{model?}` → `{probe: ProbeResult}` | Hub only. Direct returns the same `direct_mode` error. || GET `/api/models/events?limit=<n>&before=<id>` | → `{events: ResolutionEvent[]}` | Bounded source-resolution feed. |-| POST `/api/models/oauth/start` | `{vendor, channel}` → `{flow: OAuthFlow}` | Starts creation of a new subscription source. |+| POST `/api/models/oauth/start` | `{vendor, channel, client_nonce?}` → `{flow: OAuthFlow}` | Starts creation of a new subscription source. Before provider work, the optional exact `(client_nonce, vendor, channel)` tuple is atomically claimed; concurrent retries coalesce to its one pending start and terminal result. || GET `/api/models/oauth/status/<flow_id>` | → OAuth result | Terminal create and reauth shapes are below. || POST `/api/models/oauth/submit` | `{flow_id, value}` → OAuth result | Same terminal shape as status. |-| POST `/api/models/oauth/cancel` | `{flow_id}` → `{ok}` | Cancels and forgets the flow. |+| POST `/api/models/oauth/cancel` | `{flow_id}` → `{ok}` | Cancels provider work. A committed flow with `client_nonce` remains the same bounded terminal `OAuthFlow` with `state: "cancelled"` until its existing `expires_at`; a flow without a nonce is forgotten. || 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 one-time matching and placement 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 is contract v5; `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}` | Explicitly starts the managed engine. Uses the existing mutation authentication and CSRF guards; status reads never start it. |The removed global route `PUT /api/models/priority` has no replacement. Backend Source@@ -80,6 +85,63 @@ Source health reflecting that uncertainty. Subscription OAuth creation follows ivendor-specific observation flow before commit. Saved Sources use the storedprotocol for every later operation.+`source-create.schema.json` is the complete `SourceCreate` request. Its field table is+authoritative; no Source response field may be inferred backwards into the request:++| Field | Required | Producer → consumer | Rule |+| --- | --- | --- | --- |+| `vendor` | yes | Add Source client → observation adapter | Same normalized vendor id as the unsaved observation request. |+| `display_name` | no | Add Source client → Source metadata | Omission uses the server's canonical vendor label; it never carries credential material. |+| `base_url` | no | Add Source client → observation adapter | null or omission selects the official endpoint; a custom URL is validated before provisioning. |+| `key` | yes | Add Source client → transient and committed credential provisioning | Plaintext is write-only and never appears in a response, Source record, event, or log. |+| `protocol_order` | no | Add Source client → observation adapter | Contains all three protocols exactly once and only orders probes. |+| `client_nonce` | no | Add Source client → process-local create reservation and persisted Source read projection | Client-generated before send and atomically reserved in the live process before observation or credential work; only the successful commit persists and echoes it unchanged so an ordinary list read can reconcile a lost response. |++The request has no `id`, `created_at`, `state`, `usage`, `protocol`, discovered-model,+credential-ref, billing, or supply-channel field. The server assigns or observes all of+them. A successfully observed empty inventory is represented by the returned+`source.models: []`; the client never submits a discovered inventory as authority.++When `client_nonce` is present, the server atomically reserves it in the live process+before observation, transient-ref creation, or committed credential provisioning. The+reservation is not a Source row and has no durable representation. Only successful+commit persists the unchanged value as `Source.client_nonce`; neither representation+stores a request digest, terminal envelope, or plaintext credential. After a lost+response, the client first reads+`GET /api/models/sources`: an exact nonce match reconciles the committed Source, while a+miss permits a same-nonce retry. A retry that races unfinished work receives an+in-progress conflict and waits; a retry that races a newly committed Source receives a+committed conflict and repeats the list read. The server applies this total state/action+table:++| Decision | Live state at retry | Retry relation | Server action and HTTP/API result | Upstream work |+| --- | --- | --- | --- | --- |+| `nonce.in_flight` | this process holds the nonce reservation for unfinished create work | same nonce with any otherwise-valid request | retain the reservation; HTTP 409 `source_create_in_progress` | none |+| `nonce.released` | no live-process reservation and no live Source owns the nonce, including after process restart | same nonce with any otherwise-valid request | atomically reserve the nonce in process and run a fresh create | exactly one new attempt under the reservation |+| `nonce.committed` | one live Source carries the nonce | same nonce with any otherwise-valid request | HTTP 409 `source_nonce_conflict`; client reads the ordinary Source list and finds the exact nonce | none |++The successful Source commit atomically removes the process reservation while writing the+visible `Source.client_nonce`; there is no live-process overlap or unclaimed interval.+Pre-commit failure or cancellation releases the reservation only after every transient or+uncommitted credential ref has been revoked or entered the durable pending-revocation+journal under AC-26. Process termination ends both the in-flight work and its process-local+reservation; reconstruction reconciles any durable pending-revocation entry before a+same-nonce retry begins as a fresh attempt. No ownerless claim is reconstructed.+Uniqueness covers only live-process reservations and live Sources. Source deletion releases its nonce; after the required+list read observes no matching live Source, a later same-nonce request is definitionally+a fresh create and may create one new Source. Protecting a deleted Source from a stale+nonconforming caller is outside this single-user client's D-36 recovery protocol. No+receipt, digest, terminal-envelope snapshot, released-state record, or separate+reconciliation endpoint exists.++Cancellation has one commit boundary. Before the durable Source commit, AC-26 applies:+the transient or uncommitted ref is revoked, or is named by the durable pending-+revocation journal, before cancellation settles. After that commit, cancellation ends+only the caller's wait. The transaction completes normally, the Source and all accepted+placements remain committed, and the next Source/Agent read returns a coherent state+even if no client received the create response. There is no server-side abort path after+the commit point.+The observation result has six terminal outcomes: `observed`, `ambiguous`,`unreachable`, `authentication_failed`, `adapter_error`, and `timeout`. Its`protocol` is non-null only when a real upstream response shape and positive@@ -112,6 +174,29 @@ therefore reports `succeeded` or `failed`; every other terminal reports- Source event references are checked when emitted. Retained feed entries remainvalid after a later legal source deletion.+## K4 v5 field registry++These rows are authoritative for the new payload members only. They do not classify+every K4 route change as read-only or compatibility-neutral. G-3's discovered-model+DELETE behavior and G-14's mode-switch transaction are separately specified pre-release+route corrections. The owner-approved 2026-08-11 19:44–19:56 pre-release correction+also removes persistent network/timeout cooldown causes in favor of live `backoff`;+every other existing field and enum meaning remains unchanged.++| Field | Producer | First consumer | Invariant |+| --- | --- | --- | --- |+| `Source.client_nonce` | Source create commit | lost-create reconciliation | Exact optional echo of `SourceCreate.client_nonce`, written only at commit; unique across live Sources and live-process reservations, and never used for routing. |+| `Source.models[].retired` | discovered-model DELETE | Source detail inventory | Omission means false; only a discovered row may be true; true rows remain readable and never supply. |+| `Source.adopted_by` | Source read assembler | Source cards and Source detail status | Complete unique persisted-reference projection sorted by backend then menu model; clients do not derive it from `hops`. |+| `AgentSupply.cli_present` | backend CLI detector | zero-installed-backend state | Boolean installation fact only; it does not imply login or process readiness. |+| `AgentSupply.model_supply[].has_runnable_hop` | exact-chain live annotator | backend-group collapse predicate | Uses the AgentChain runnability axiom rather than inferring liveness from configured membership. `chain_length: 0` forces false; a nonzero length may carry either value. |+| `RuntimeDependency.host_platform` | server host detector | unsupported-host runtime pill | Names the Avibe host, not the browser; exact membership in `manifest.assets[].platform` decides install support. |+| `RuntimeDependency.status.error_key` | runtime installer | install-failed runtime state | Closed persisted i18n key: `settings.models.install.fail.detail` after installation fails; null after a new attempt begins and in every non-failure state. |+| `RouteHopRef.position` | guarded mutation planner | guarded-change hop row | One-based position in the named Route before the attempted mutation. |+| `OAuthStart.client_nonce` | OAuth client before send | OAuth start idempotency | Optional client-generated correlation; the server claims its exact tuple with vendor and channel before provider work, coalesces an in-flight retry, releases after failure or task cancellation before a flow exists, and converts success atomically to the flow. Explicitly canceling that committed flow retains its terminal `cancelled` correlation until the existing expiry. |+| `OAuthFlow.client_nonce` | OAuth start echo | lost-start reconciliation | When the request supplied the nonce, every flow response echoes it unchanged and carries a non-null date-time `expires_at`; flows without a nonce retain the existing nullable expiry branch. |+| `AgentChain.chain[].health: backoff` | configured-chain live annotator | chain/AgentSupply health reads | Source-scoped in-memory connection throttle before the first user-visible model-output byte, with `retry_at` strictly later than the assembler's captured read time, never persisted in Source/config. It overlays only an otherwise healthy hop whose exact Source/model capability is present. Cooldown, durable Source health, missing Source, or unsupported model suppresses it and keeps the stronger blocker's established projection; simultaneous native-process unavailability is the sole exception and takes the reason slot without erasing the deadline. Before serialization, an expired overlay is normalized to the underlying non-backoff facts. Ordinary backoff rolls up `waiting`; every durable/capability/process blocker rolls up `interrupted`. |+## AgentSupply read projectionEach backend entry on `GET /api/models/agents` carries the v5 API-boundary keys:@@ -119,6 +204,7 @@ Each backend entry on `GET /api/models/agents` carries the v5 API-boundary keys:```json{"backend": "claude",+ "cli_present": true,"mode": "hub","selected_by_agent": "pm","selected_model_id": "claude-opus-4-6",@@ -151,7 +237,7 @@ Each backend entry on `GET /api/models/agents` carries the v5 API-boundary keys:},"supply_status": "degraded","model_supply": [- {"model_id": "claude-opus-4-6", "chain_length": 2}+ {"model_id": "claude-opus-4-6", "chain_length": 2, "has_runnable_hop": true}],"named_agents": [{@@ -185,6 +271,19 @@ Agents payload stays at per-named-Agent selection and supply-status grain.Disabled Agents are absent. In Direct mode each named Agent may still have aneffective model, but its Hub `supply_status` is null.+Every backend record remains present even when its executable is absent.+`cli_present` is server-authoritative, and the zero-installed-backend state is exactly+the payload where every record carries false. Login recognition is a separate fact used+only by the Direct → Gateway adoption transaction; neither login nor process readiness+may be inferred from `cli_present`.++Each `model_supply` row carries both configured `chain_length` and live+`has_runnable_hop`. A nonzero length with false is an all-stale Route; zero with false is+structurally empty, and zero with true is invalid. The boolean is computed from the+complete exact chain with the same source-health AND process-availability rule as+`AgentChain`, so the page never issues a chain read per row and never treats configured+membership as live supply.+The `sources.eligibility` inventory is also the one complete source-signalprojection. Every existing source remains represented, including a source outsidethe selected model's capability chain. `in_current_model_chain` is true or false@@ -198,7 +297,8 @@ source that does not supply the selected model is absent from that chain, so itsprocess-availability fact vanishes at exactly the drawer grain that still rendersthe source. Evidence at master `05f72ae5`: `service.py:1843-1891` computes theper-backend unavailable set beside the complete eligibility inventory, while-`model_supply` carries only `chain_length`.+`model_supply` carries both configured `chain_length` and live+`has_runnable_hop`; it still carries no Route body or serving head.### Honest null selection@@ -234,18 +334,59 @@ The request is total:- Add Source and native import invoke `placement-v1` once and persist its chosenposition. Refresh, restart, health changes, and turns never recompute this order.+The whole-order PUT is intentionally outside the §4.5 Source-mutation envelope matrix.+It stores only `sources.order`, never reads or writes a Route chain, and therefore never+returns a guarded `409`. This is the G-9 tombstone: adding a guard branch would imply an+order save is allowed to mutate supply, which violates S-1.++`POST /api/models/agents/<backend>/chains/reorder` is the only operation that applies+the stored Source order to existing Routes. For each Route, give every hop its original+zero-based index `i` and sort by this total key:++```text+source_id in sources.order -> (0, sources.order.index(source_id), i)+source_id not in the order -> (1, i, i)+```++Thus ordered Sources come first in Source-order sequence; hops of the same Source keep+their prior order; every unlisted hop follows and all unlisted hops keep their relative+order. The operation changes only hop order. It preserves the multiset of exact+`(source_id, model_id)` pairs byte-for-byte, never runs matching, and never adds,+removes, or remaps a hop. It is idempotent and has no `force`, guarded refusal, removed-+hop, or interruption branch: changing a preferred first hop is an explicit non-+destructive configuration edit, not loss of supply. This route is the first consumer of+the Source-order sequence under the current `placement-v1` policy.+Eligibility is server-authoritative. An ineligible row carries exactly one closed`reason_key` from `agent-supply.schema.json`; an eligible row carries null.+### Direct-to-Gateway native adoption++For `PATCH /api/models/agents/<backend>/mode`, a transition from `direct` to `hub`+reuses the same sanctioned native-login recognition and response-backed observation+boundary as native import. If that backend has a recognized CLI login and has no+`native_cli` Source, the mode change, creation of the backend's singleton native Source,+`placement-v1` Source-order insertion, and every accepted add-time exact match commit in+one transaction. The returned `AgentSupply` is assembled after that commit and exposes+the resulting order, eligibility, Routes, and supply summaries.++An existing native Source, an unrecognized or absent CLI login, or any transition other+than `direct` → `hub` creates nothing. The mode switch itself remains legal in those+cases. Repeating the request never creates a second native Source. `cli_present` alone+does not satisfy the recognition predicate.+### Exact Route-chain configurationEvery menu model stores one `hops` array. Each hop is an exact`{source_id, model_id}` pair; a differing upstream id is the mapping itself, not aseparate mapping object. A write validates only newly introduced or changed pairs.-The whole-array PUT uses `force` in the JSON body and the same guarded refusal/reporting-family as Source mutations. A successful write returns `{chain, removed_hops,-interrupted}`; a non-forced write that would empty protected supply returns the shared-`409 {error, would_remove_hops, would_interrupt}` envelope.+The whole-array PUT uses `force` plus the optional echoed `would_remove_hops` and+`would_interrupt` arrays in the JSON body only when the submitted edit would interrupt+protected supply. A successful write returns `{chain, removed_hops, interrupted}`.+Removing a hop while leaving protected supply runnable is the user's visible direct edit+and succeeds without a guard round trip; a non-forced write that would interrupt+protected supply returns the shared `GuardRefusal` envelope with+`error: source_last_supplier`.An unchanged stale pair may be retained or reordered so a user can add a workingfallback without discarding a temporarily unavailable configured hop. Runtime walksthe stored array verbatim and annotates only live runnability.@@ -275,7 +416,14 @@ The terminal result of both ordinary API-key creation and OAuth creation is:{"ok": true,"contract_version": 5,- "source": {"id": "src_anthkey01", "kind": "api_key"},+ "source": {+ "id": "src_anthkey01",+ "kind": "api_key",+ "client_nonce": "scn_01j5w8z7p4n6q2rt",+ "adopted_by": [+ {"backend": "claude", "menu_model": "claude-opus-4-6"}+ ]+ },"added_to": [{"backend": "claude", "menu_model": "claude-opus-4-6", "source_id": "src_anthkey01", "model_id": "claude-opus-4-6", "position": 2}],@@ -287,9 +435,31 @@ The terminal result of both ordinary API-key creation and OAuth creation is:The public HTTP wrapper, RPC layer, and client pass this shape through directly; noextra `source` or `flow` nesting is added.+The top-level `adopted_by` remains the creation-result projection and is byte-equal to+`source.adopted_by` in that response. Later `GET /api/models/sources` reads carry the+same Source field recomputed from current persisted references; `client_nonce`, when+present, is the exact persisted create correlation.## Supply guard+`RouteHopRef` is the immutable pre-mutation reference used by both+`would_remove_hops` and `removed_hops`:++```json+{+ "backend": "claude",+ "menu_model": "claude-opus-4-6",+ "source_id": "src_anthkey01",+ "model_id": "claude-opus-4-6",+ "position": 2+}+```++`position` is one-based in the named persisted Route before the attempted mutation.+It is not the entry's index in the cross-Route reporting array. Reporting order is+backend id, then menu-model id, then this pre-mutation position; a forced success+returns the same references and positions as the corresponding refusal.+`SupplyGap` is:```json@@ -301,7 +471,10 @@ extra `source` or `flow` nesting is added.````agents` is the set of enabled named Vibe Agents whose explicit model is the-menu-side `model_id`. It is present and may be empty.+menu-side `model_id`. It is present and may be empty. The planner emits+`would_interrupt` in ascending `(backend, model_id)` order and each `agents` array in+ascending stable Agent-id lexicographic order. This is the canonical JSON order used+by exact plan echo; enumeration or insertion order never changes plan identity.The protected model set for a backend is the union of:@@ -314,7 +487,8 @@ state. It counts only runnable exact hops in that model's stored Route chain, neeligible inventory or the backend Source order by itself. A pair with no runnable hopappears once in `would_interrupt` or `interrupted`.-Every guarded Source/inventory mutation uses the §4.5 envelope matrix. A refusal is:+Every guarded Source/inventory mutation uses the §4.5 envelope matrix and the complete+`guard-refusal.schema.json` shape. The first refusal is:```json{@@ -332,8 +506,43 @@ Every guarded Source/inventory mutation uses the §4.5 envelope matrix. A refusa}```-DELETE uses the query `force=true`; the other guarded mutations use the JSON body-`force: true`. Success returns the exact envelope selected by the authoritative matrix.+The lead error and its evidence array are inseparable: `source_in_route_chain` and+`source_model_in_route_chain` require nonempty `would_remove_hops`, while+`source_last_supplier` requires nonempty `would_interrupt`. The other array remains a+complete projection and may independently be empty or nonempty.++The shared guard planner stages the complete post-mutation Source/Route result and its+ordered guard-report arrays. On confirmation the client resends the same substantive+mutation with `force: true` and byte-for-byte equivalent JSON values for the refusal's+`would_remove_hops` and `would_interrupt` arrays. No token, digest, version receipt, or+server-side confirmation state exists.++The shared layer recomputes the current guarded-impact plan and then applies this total+decision matrix. For Source and inventory 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+refusal also reports every submitted removal in `would_remove_hops`, while a+noninterrupting removal skips refusal and appears only in successful `removed_hops`.+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_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 |+| `guard_decision.forced_unconfirmed` | true | nonempty | either array absent or either array differs | HTTP 409 `GuardRefusal` with the newly recomputed plan; remove nothing |++Thus every destructive guarded impact that commits is the exact plan the user confirmed.+If a previously refused request recomputes to an empty plan, including a request carrying+an old nonempty echo, there is no destructive referent left to confirm: the ordinary path+commits without inventing a guard error or request-validation variant. Every 409 plan is+nonempty, and no refused branch removes a hop.++Success returns the exact envelope selected by the authoritative matrix and the+byte-identical `RouteHopRef` array from the accepted plan.## Credential replacement and reauth@@ -362,14 +571,19 @@ differently only if all invariants remain true:Hub OAuth material is engine-owned but identity-bound to a stable ref, so replacingits grant is irreversible once the new material is written. Native credentials areCLI-owned and replacement is likewise irreversible once login starts.-5. **Server-enforced native acknowledgement.** For a `native_cli` source,- `POST …/reauth` requires `{"acknowledge_irreversible": true}`. Missing or false- returns `reauth_confirmation_required` before any OAuth adapter call. This is- unconditional and does not claim that a pre-login supply prediction exists.- Hub-channel repair does not require this acknowledgement.-6. **Recovery symmetry.** Both routes return the same repair tail:- `{source, recovered, interrupted_pairs}`. `recovered` is true exactly when the- prior source state was `needs_action` or `error`.+5. **Server-enforced OAuth re-auth acknowledgement.** For both Hub OAuth and+ `native_cli` Sources, `POST …/reauth` requires+ `{"acknowledge_irreversible": true}`. Missing or false returns+ `reauth_confirmation_required` before any OAuth adapter call. This is unconditional+ across both supply channels and does not claim that a pre-login supply prediction+ exists. Transactional API-key repair through `PUT …/credential` remains outside+ this acknowledgement rule.+6. **Repair-result ownership.** API-key replacement returns only the standard guarded+ Source-mutation success envelope `{source, removed_hops, interrupted}`. Its repair+ effect is read from the returned `Source.state`, while `removed_hops` and+ `interrupted` report the exact Route impact. `recovered` and `interrupted_pairs`+ belong only to a terminal OAuth flow with `intent: "reauth"`; they never appear on+ `PUT …/credential`.7. **Durable failed-revocation reconciliation.** If old engine material cannot berevoked after commit, the service persists a pending-revocation record beforereturning success. A reconstructed service reads the same journal and retries it.@@ -412,9 +626,13 @@ API-key success:{"ok": true,"contract_version": 5,- "source": {"id": "src_relay9c1x", "kind": "api_key"},- "recovered": true,- "interrupted_pairs": []+ "source": {+ "id": "src_relay9c1x",+ "kind": "api_key",+ "state": {"status": "standby"}+ },+ "removed_hops": [],+ "interrupted": []}```@@ -433,13 +651,65 @@ state, preserves the last successful model list and timestamp, and returns the nsafe error. This route is the only refresh/recovery operation; there is no parallel“test” or “recover” endpoint.-## OAuth completion+Discovered-model retirement is a persistent exception to replacement. DELETE on a+discovered model stages `retired: true` on that row instead of deleting it, then runs+the same exact-hop and protected-supply guards. Forced success removes only invalidated+Route references and keeps the retired inventory row. Every later refresh preserves+that row, its edited metadata, and `retired: true` whether the upstream still advertises+the id or no longer does. A retired row is excluded from add-time matching, model-+capability eligibility, new Route validation, live runnability, and invocation. There is+no automatic or refresh-driven unretire path. DELETE on a manual row retains its+existing remove-row semantics.-`OAuthFlow.intent` makes the terminal shape a function of the flow:+## OAuth completion-- non-terminal, failed, or canceled → `{flow}`;-- terminal `intent: "create"` → `{flow, source, added_to, adopted_by}`;-- terminal `intent: "reauth"` → `{flow, source, recovered, interrupted_pairs}`.+`POST /api/models/oauth/start` optionally accepts a client-generated `client_nonce`+matching `^ofn_[a-z0-9]{16,64}$`. The claim key is the exact+`(client_nonce, vendor, channel)` tuple; a different vendor or channel is a different key+and never resolves to another tuple's flow. Every flow produced from a nonce-bearing+request carries a non-null date-time `expires_at` from its first response through every+terminal replay; an ordinary or presentation-only flow without a nonce may retain+`expires_at: null`. Before invoking the provider, the server+atomically claims the tuple and applies this total state/action table:++| Decision | Tuple state at start | Server action and HTTP/API result | Provider starts |+| --- | --- | --- | --- |+| `oauth_nonce.released` | no claim or unexpired flow exists, including after a shared pending-start failure/task cancellation or after a retained canceled flow reaches its existing `expires_at` | atomically claim, start once, and make every coalesced caller await the same terminal result | exactly one under the new claim |+| `oauth_nonce.in_flight` | a provider start owns the claim but has not produced a flow | coalesce with that pending start and return its same terminal result; never create a parallel flow | none for the retry |+| `oauth_nonce.committed` | provider success atomically converted the claim into one unexpired `OAuthFlow`, including one explicitly canceled afterward | return that same `flow_id`, current state, and presentation; explicit cancellation returns the retained `state: "cancelled"` flow | none |++A shared provider-start failure or task cancellation before a flow exists returns the+same terminal failure to all coalesced callers and releases the claim only after cleanup+settles; the next exact-tuple retry therefore enters `oauth_nonce.released`. Provider+success converts the claim to `OAuthFlow` atomically, with no unclaimed interval. If the+user then explicitly cancels a nonce-bearing committed flow, the provider work is+canceled but that same flow remains as bounded terminal `state: "cancelled"`; a delayed+exact-tuple retry returns it without another provider start. Its existing `expires_at`+ends the reconciliation window and releases the tuple, so a later retry is a fresh+start. Canceling a flow created without a nonce forgets it because no D-36 correlation+promise exists. Every returned flow echoes the nonce. A new user action generates a new+nonce. Omitting it otherwise preserves ordinary one-action/one-start behavior.++`OAuthFlow.intent` and local materialization make the terminal shape total. A+materialization error is an error raised only after the upstream flow reached terminal+success while the service was committing the created or repaired Source. Its+`interrupted_pairs` uses the existing `SupplyGap` shape and reports persisted impact that+already happened; it never aliases the future-tense guard field `would_interrupt`.++| Decision | Flow/service condition | HTTP/API result | `interrupted_pairs` |+| --- | --- | --- | --- |+| `oauth_terminal.flow_only` | non-terminal flow, or adapter terminal `failed`/`cancelled` without local materialization error | successful `{flow}` | absent |+| `oauth_terminal.create_success` | terminal create and Source materialization succeed | `{flow, source, added_to, adopted_by}` | absent |+| `oauth_terminal.reauth_success` | terminal re-auth and existing-Source materialization succeed | `{flow, source, recovered, interrupted_pairs}` | present as the complete report and may be empty |+| `oauth_terminal.materialization_interrupted` | local terminal materialization fails after an acquisition-stage Source mutation has already produced at least one exact supply gap | standard `{ok: false, contract_version, error, detail?}` envelope plus the exact report; `flow` is absent | present and nonempty |+| `oauth_terminal.materialization_plain_error` | local terminal materialization fails before such an interruption or its exact report is empty | standard error envelope; `flow` is absent | absent, never an empty placeholder |++The same existing materialization error code may enter either error row. The server adds+`interrupted_pairs` if and only if the acquisition-stage mutation produced a nonempty+report; every other error envelope omits the field. Native re-auth `discovery_failed`+after clearing/marking the Source is the positive fixture. The same error before an+interruption, and any materialization failure whose computed report is empty, are+negative fixtures. A later Source read cannot recreate the historical report.Status and submit return the same terminal shape:@@ -449,11 +719,18 @@ Status and submit return the same terminal shape:"contract_version": 5,"flow": {"flow_id": "oaf_claude01",+ "client_nonce": "ofn_01j5w8z7p4n6q2rt","intent": "create","state": "success","source_id": "src_claudepro1"},- "source": {"id": "src_claudepro1", "kind": "subscription"},+ "source": {+ "id": "src_claudepro1",+ "kind": "subscription",+ "adopted_by": [+ {"backend": "claude", "menu_model": "claude-opus-4-6"}+ ]+ },"added_to": [{"backend": "claude", "menu_model": "claude-opus-4-6", "source_id": "src_claudepro1", "model_id": "claude-opus-4-6", "position": 1}],@@ -470,22 +747,31 @@ reference is created.In Hub mode, `AgentChain.chain` is the exact stored per-model Route chain in the sameorder. Runtime does not filter or rebuild it: cooling, missing, model-unsupported,-source-blocked, and process-unavailable native CLI hops stay at their configured+source-blocked, live connection-backoff, and process-unavailable native CLI hops stay at their configuredpositions with live annotations.`AgentChain.current` is either null or the exact `{source_id, model_id}` identity ofthe hop that is current for the next execution. Recovery changes `current` on the nextturn without changing the stored `chain` array.-Each item carries `channel`, source-global `health`, process-aware `runnable`, and-nullable `reason`. The complete axiom is:+Each item carries `channel`, Source-global health or the distinct live `backoff`+overlay, process-aware `runnable`, and nullable `reason`. The complete axiom is:-`runnable = health-permits AND process-available`.+`runnable = source-health-permits AND no-live-backoff AND process-available`.Process availability is definitionally true for `channel: "hub"` in v2; there is noconfiguration knob for it. For `native_cli`, `reason: "native_cli_unavailable"` is anorthogonal process fact legal at every health and always forces `runnable: false`. Theitem stays visible and dimmed, and makes a fully blocked chain `interrupted`, even when-its health is `cooldown`; `reason: null` means process-available. An empty Hub chain-remains a valid `interrupted` chain.+its health is `cooldown` or `backoff`. A short connection throttle overlays only an+otherwise healthy, capability-present Hub or process-available native hop. Source+cooldown, `needs_action`, `error`, `source_missing`, and `model_unsupported` suppress+that overlay and retain their established health/reason/retry projection. An eligible+throttled hop carries `health: backoff`,+`reason: models.source.backoff.connection_failed`, and the future deadline in+`retry_at`; this blocker rolls up as `waiting`. If the native CLI also becomes+unavailable, the actionable process fact takes the single `reason` slot, while+`health: backoff` and the same `retry_at` remain visible; the chain is `interrupted`.+Outside those blockers, `reason: null` means process-available. An empty Hub chain remains+a valid `interrupted` chain.```json{@@ -595,6 +881,47 @@ No candidate is an API error with a typed model-scoped state:}```+The §4.3 network-failure matrix is mirrored here in full. The retained `*_first_byte`+decision ids refer specifically to the existing `stream_started` boundary: the first+user-visible model-output byte, not HTTP status, headers, or another response byte. The+server transport supplies that fact; neither the client nor an HTTP timeout label may+infer it. A shaped result is one of the existing explicit closed classifiers, while+transport means there is no explicit code:++| Decision | Failure shape | Phase | Source/config write | Backoff/read projection | Execution result |+| --- | --- | --- | --- | --- | --- |+| `network_failure.shaped_before_first_byte` | explicit closed quota/rate/auth/server classification | `stream_started: false`; before first user-visible model output | existing non-permanent family only | none | existing retry/fallback and redacted event |+| `network_failure.transport_before_first_byte` | no explicit code; connection failure | `stream_started: false`; before first user-visible model output | none | Source-scoped in-memory `backoff`, delays 1/2/4/8/16/30 seconds, reason `models.source.backoff.connection_failed`, future `retry_at` | continue to next runnable hop; redacted `network` event |+| `network_failure.shaped_after_first_byte` | explicit closed classification after output started | `stream_started: true`; after first user-visible model output | existing non-permanent family only, with its unchanged recovery rule | none | terminal, no replay; existing redacted event only |+| `network_failure.transport_after_first_byte` | no explicit code; stream interruption | `stream_started: true`; after first user-visible model output | none | none | terminal, no replay; redacted `network` event only |++The backoff deadline expiring makes the hop runnable without persistence. Before any+chain, AgentSupply, or probe response is validated and serialized, the read assembler+captures one assembly time and normalizes every expired live overlay to that Source's+underlying non-backoff health and runnability; it never emits a stale `backoff` or expired+live `retry_at`. The first later user-visible model-output byte produced by that same+affected Source, Source endpoint/credential replacement, or process reconstruction+clears its deadline and consecutive-failure streak. Output from a different fallback+Source does not clear the affected Source's streak. The delay is capped at 30 seconds.+For a native hop whose process is simultaneously unavailable, the live deadline remains+visible but `native_cli_unavailable` takes the single reason slot and the chain remains+`interrupted`; restoring the process reveals any still-live connection backoff.+Projection precedence while a deadline is live is total:++| Underlying hop fact | Backoff overlay | Emitted facts | Fully blocked rollup |+| --- | --- | --- | --- |+| healthy + exact capability present + process available | apply | `backoff`, `connection_failed`, future deadline | `waiting` when all hops are cooldown/ordinary backoff |+| cooldown | suppress | existing cooldown health/reason/deadline | `waiting` when all hops are cooldown/ordinary backoff |+| `needs_action` or `error` | suppress | existing Source health/reason/retry facts | `interrupted` |+| `source_missing` or `model_unsupported` | suppress | existing capability-blocker health/reason/retry facts | `interrupted` |+| healthy + exact capability present + native process unavailable | apply with process-reason exception | `backoff`, `native_cli_unavailable`, same future deadline | `interrupted` |++`Source.state`, Source serialization, and every `models.source.cooldown.*` key remain+untouched by unclassified transport failure. Probe connection failure uses the same+closed live key and validates only as `channel: hub`, `reachable: false`, and+`latency_ms: null`; native probes and Hub probes with measured latency cannot carry it.+It never reports the removed persistent network/timeout cooldown keys.+## Turn provenance absence`TurnProvenance` is returned only for an exactly attributed Hub turn. Direct and@@ -633,24 +960,65 @@ Model-scoped kinds require a string. `agent: system` is invalid on backend-scope`supply_interrupted`. Source endpoints use canonical ids and are checked for existencewhen emitted.+## Runtime installation and host support++Every runtime response carries `host_platform`, and every status carries `error_key`.+The server detects the Avibe host; clients never substitute the browser platform.+Installation is supported exactly when one `manifest.assets[].platform` equals+`host_platform`. An unsupported host leaves `health: "not_installed"`; the install+route fails before download with HTTP 422 and+`error: "runtime_platform_unsupported"`; the next status read remains truthful with+`error_key: null`.++`POST /api/models/runtime/install` is idempotent. Only `not_installed` on a supported+host starts work: it clears the previous `error_key`, durably enters `installing` with+exactly `installed_version: null`, `verified: false`, and `listening: null`, starts the+owned install job, and returns that state. A reload and concurrent repeat while+`installing` read/return the same state instead of starting another job. Calls from+`not_started`, `ok`, `degraded`, or `down` are HTTP 200 no-ops that return the current+RuntimeDependency without mutating runtime state: they start no download, do not clear+or replace the verified binary, and neither start, stop, nor restart the process.+Installed-state handling precedes host-support refusal, so an existing verified+installation is never disrupted merely because the current manifest lacks that+platform. Successful+verification settles at `not_started` with `error_key: null`; it does not start the+runtime. Failure settles at `not_installed` with+`error_key: "settings.models.install.fail.detail"`. The key is the closed presentation+carrier for the persisted failure; raw downloader or verifier text remains only in+scrubbed logs. `/start` never performs installation.++On service bootstrap, persisted `installing` with no worker owned by the reconstructed+process is an orphaned install, never a live-job proof. Before runtime endpoints become+ready, the server first verifies the pinned target: a complete manifest-matching binary+settles directly at `not_started`; otherwise it discards only uncommitted staging,+atomically claims the singleton install lease, and restarts the pinned installation+from scratch while retaining `installing`. Failure to claim or schedule that recovery+settles at `not_installed` with the same closed `error_key`. Thus a page reload observes+a live owned job, while a service restart cannot strand the state permanently.+## Error codesMinimum v5 set:`source_not_found`, `flow_not_found`, `flow_expired`, `discovery_failed`,-`invalid_source_order`, `source_last_supplier`, `source_in_route_chain`,+`invalid_source_order`, `source_create_in_progress`, `source_nonce_conflict`, `source_last_supplier`,+`source_in_route_chain`,`source_model_in_route_chain`, `mode_switch_blocked`, `engine_down`,-`reauth_confirmation_required`, `source_model_managed_upstream`,-`native_source_already_exists`, `migration_item_conflict`, `turn_not_found`,+`runtime_platform_unsupported`, `reauth_confirmation_required`,+`native_source_already_exists`,+`migration_item_conflict`, `turn_not_found`,`provenance_unavailable`, `probe_no_candidate`, `direct_mode`.`native_source_already_exists` is an API-boundary refusal for native OAuth start;its structured sibling is `{existing_source_id}` and the adapter is not invoked.Boundary-only action-refusal values cover operations the UI already does not offer but-a script or regression can call directly. `reauth_confirmation_required` and-`source_model_managed_upstream` are API/test-only truth: they have no product copy key-or rendering slot.+a script or regression can call directly. `reauth_confirmation_required` is API/test-+only truth: it has no product copy key or rendering slot.++The top-level guard vocabulary remains exactly `source_last_supplier |+source_in_route_chain | source_model_in_route_chain`; a changed confirmation plan returns+the same family with newly recomputed arrays rather than a parallel discriminator.Removed: `invalid_priority_order`.@@ -666,6 +1034,16 @@ contract harness and API-boundary tests enforce:<!-- authority-consumer: protocol anthropic openai_responses openai_chat --><!-- authority-consumer: observation.outcome observed ambiguous unreachable authentication_failed adapter_error timeout --><!-- authority-consumer: observation.discovery succeeded failed not_attempted -->+<!-- authority-consumer: runtime.health ok degraded down not_installed installing not_started -->+<!-- authority-consumer: runtime.install_error runtime_platform_unsupported -->+<!-- authority-consumer: source.create_nonce nonce.in_flight nonce.released nonce.committed -->+<!-- authority-consumer: guard.error source_last_supplier source_in_route_chain source_model_in_route_chain -->+<!-- authority-consumer: guard.decision guard_decision.unforced_no_impact guard_decision.unforced_confirmation guard_decision.forced_no_impact guard_decision.forced_confirmed guard_decision.forced_unconfirmed -->+<!-- authority-consumer: oauth.start_nonce oauth_nonce.released oauth_nonce.in_flight oauth_nonce.committed -->+<!-- authority-consumer: oauth.terminal oauth_terminal.flow_only oauth_terminal.create_success oauth_terminal.reauth_success oauth_terminal.materialization_interrupted oauth_terminal.materialization_plain_error -->+<!-- authority-consumer: network.failure network_failure.shaped_before_first_byte network_failure.transport_before_first_byte network_failure.shaped_after_first_byte network_failure.transport_after_first_byte -->+<!-- authority-consumer: live_backoff.health backoff -->+<!-- authority-consumer: live_backoff.reason models.source.backoff.connection_failed -->| Guard | Boundary || --- | --- |@@ -680,8 +1058,20 @@ contract harness and API-boundary tests enforce:| probe `source_id` names an existing source | probe assembler || non-null event endpoints name existing sources at emission time | event emitter || `channel_switch.from_source == channel_switch.to_source` | event emitter |-| API AgentSupply includes `selected_by_agent`, `selected_model_id`, `selected_model_explicit`, policy-free `sources.order`, `supply_status`, `model_supply`, and `named_agents`; every Source includes persisted `last_discovered_at`; source creation returns `added_to` and `adopted_by`; saved refresh uses the guarded Source envelope | API payload test |+| API AgentSupply includes `cli_present`, `selected_by_agent`, `selected_model_id`, `selected_model_explicit`, policy-free `sources.order`, `supply_status`, `model_supply[].has_runnable_hop`, and `named_agents`; every Source includes persisted `last_discovered_at`, optional persisted `client_nonce`, derived `adopted_by`, and model retirement tombstones; source creation returns `added_to` and top-level `adopted_by` equal to `source.adopted_by`; saved refresh and discovered-model retirement use the guarded Source envelope | API payload test || every OAuthFlow response includes `intent` | API payload test |+| Hub OAuth and native CLI `POST /sources/<id>/reauth` requests with missing or false `acknowledge_irreversible` return `reauth_confirmation_required` before the OAuth adapter is called; true acknowledgement is the only start path, while transactional API-key PUT is unaffected | API route negative/positive fixtures |+| OAuth start claims `(client_nonce, vendor, channel)` before provider work; a blocked first call plus concurrent same-tuple retry coalesces to one pending result and exactly one provider start; pending-start failure/task cancellation releases after cleanup; success atomically exposes one echoed-nonce flow; explicit cancellation retains that nonce-bearing flow as `cancelled` so a same-tuple retry starts no provider, while existing expiry releases it for exactly one fresh start; no-nonce cancellation forgets | OAuth registry totality, clocked expiry, API payload, and auth-setup closed-loop tests |+| every RuntimeDependency API payload includes server-derived `host_platform` and `status.error_key`; `installing` has exactly null `installed_version`, false `verified`, and null `listening`, with one positive and each-field contradiction fixtures; only supported `not_installed` starts a download, installed states are state-preserving no-ops, page reload preserves a live `installing` job, and service bootstrap reconciles an orphan before serving runtime endpoints | RuntimeDependency schema and API payload tests |+| Source create reserves `client_nonce` in process before work; the client reads Sources before any lost-response retry; fixtures cover `nonce.in_flight` (`source_create_in_progress`/no work), `nonce.released` (atomic reserve/exactly one fresh attempt), and `nonce.committed` (`source_nonce_conflict` followed by a list read that finds exactly one Source with that nonce), while AC-26 cleanup or process restart releases any live reservation and Source deletion releases its committed nonce; after restart or deletion and a list miss, same-nonce create is positively asserted as a fresh creation | config, API payload, cancellation/restart, Source-delete, and client retry tests |+| Source observation rejects unregistered request/status evidence fields; clients consume only the contracted outcome, reachability, authentication, protocol, discovery, and models facts | observation schema and API payload tests |+| network fixtures cover shaped/transport × `stream_started: false/true`, where the boundary is the first user-visible model-output byte: shaped results at either phase enter only their existing non-permanent Source classifier; unclassified pre-output connection failure creates bounded live backoff with no config write; only later output from that same Source clears its streak, while another Source's successful fallback does not; the API/read assembler emits a future deadline for a live overlay and normalizes an expired overlay before serialization; concurrent cooldown/needs-action/error/missing-Source/unsupported-model facts suppress the overlay and keep stronger projections, so waiting never hides a durable blocker; simultaneous native-process unavailability alone preserves backoff health/deadline while taking reason precedence and yielding interrupted; probe `connection_failed` requires the exact Hub/unreachable/null-latency shape | clocked table-driven resolver/API/event, AgentChain precedence, ProbeResult relation, and concurrent-transition tests |+| every `GuardRefusal` validates against `guard-refusal.schema.json` and has a nonempty current plan; fixtures cover every guard-decision row, including unforced refusal, exact echoed-plan confirmation, missing/different echo returning the new plan, and old-echo empty-plan ordinary success without a fabricated 409 | API payload and concurrent-mutation test |+| `PUT /sources/<id>/credential` success contains exactly the standard `{source, removed_hops, interrupted}` mutation tail; `{recovered, interrupted_pairs}` is absent there and remains owned only by terminal OAuth `intent: "reauth"` | contract negative fixture and API payload test |+| OAuth status/submit covers every `oauth_terminal.*` row; a native re-auth materialization error with a nonempty acquired-side-effect report emits that exact `interrupted_pairs`, while the same error with no report and every non-materialization error omit the field rather than sending `[]` | contract totality fixture plus positive/negative API and client payload tests |+| each `source_in_route_chain` or `source_model_in_route_chain` refusal has nonempty `would_remove_hops`; each `source_last_supplier` refusal has nonempty `would_interrupt`; mismatched code/empty-required-array combinations fail schema validation even when the other array is nonempty | guard schema relation fixture |+| both GuardRefusal plan arrays contain unique objects; duplicate hop and supply-gap entries fail schema validation; producers emit SupplyGap rows in ascending `(backend, model_id)` order and each `agents` array in stable-id lexicographic order, with permutation fixtures proving canonical output | guard schema uniqueness and producer-order fixtures |+| `model_supply[].chain_length: 0` implies `has_runnable_hop: false`; the opposite pair fails schema validation | AgentSupply schema correlation fixture || contract and in-repo adapter interface copies are byte-identical; the five retained-material enum members and ref-pairing predicates are mutation-tested | contract harness |Serializer completeness follows the issue #939 pattern. Persisted fields mustdiff --git a/docs/plans/model-hub-contracts/guard-refusal.schema.json b/docs/plans/model-hub-contracts/guard-refusal.schema.jsonnew file mode 100644index 000000000..2c178988e--- /dev/null+++ b/docs/plans/model-hub-contracts/guard-refusal.schema.json@@ -0,0 +1,136 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "$id": "model-hub/guard-refusal.schema.json",+ "title": "GuardRefusal",+ "$comment": "<!-- authority-consumer: guard.error_plan guard_error.source_in_route_chain guard_error.source_model_in_route_chain guard_error.source_last_supplier -->",+ "description": "The shared HTTP 409 envelope for a guarded Model Hub mutation with a nonempty current guarded-impact plan. A forced retry confirms this plan by echoing would_remove_hops and would_interrupt unchanged; the server recomputes the plan and commits only when both arrays match exactly.",+ "type": "object",+ "required": [+ "ok",+ "contract_version",+ "error",+ "would_remove_hops",+ "would_interrupt"+ ],+ "additionalProperties": false,+ "anyOf": [+ {+ "properties": {+ "would_remove_hops": { "minItems": 1 }+ }+ },+ {+ "properties": {+ "would_interrupt": { "minItems": 1 }+ }+ }+ ],+ "allOf": [+ {+ "if": {+ "properties": {+ "error": {+ "enum": [+ "source_in_route_chain",+ "source_model_in_route_chain"+ ]+ }+ },+ "required": ["error"]+ },+ "then": {+ "properties": {+ "would_remove_hops": { "minItems": 1 }+ }+ }+ },+ {+ "if": {+ "properties": {+ "error": { "const": "source_last_supplier" }+ },+ "required": ["error"]+ },+ "then": {+ "properties": {+ "would_interrupt": { "minItems": 1 }+ }+ }+ }+ ],+ "properties": {+ "ok": { "const": false },+ "contract_version": { "const": 5 },+ "error": {+ "enum": [+ "source_last_supplier",+ "source_in_route_chain",+ "source_model_in_route_chain"+ ],+ "description": "Existing lead guard code selected by the Source-mutation matrix. A changed plan returns the same top-level guard error family with the newly recomputed arrays."+ },+ "would_remove_hops": {+ "type": "array",+ "items": { "$ref": "#/definitions/RouteHopRef" },+ "uniqueItems": true+ },+ "would_interrupt": {+ "type": "array",+ "items": { "$ref": "#/definitions/SupplyGap" },+ "uniqueItems": true,+ "description": "Canonical order is ascending by (backend, model_id); each SupplyGap.agents array is ascending by stable Agent id."+ }+ },+ "definitions": {+ "RouteHopRef": {+ "type": "object",+ "required": ["backend", "menu_model", "source_id", "model_id", "position"],+ "additionalProperties": false,+ "properties": {+ "backend": { "enum": ["claude", "codex", "opencode"] },+ "menu_model": { "type": "string", "minLength": 1 },+ "source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },+ "model_id": { "type": "string", "minLength": 1 },+ "position": { "type": "integer", "minimum": 1 }+ }+ },+ "SupplyGap": {+ "type": "object",+ "required": ["backend", "model_id", "agents"],+ "additionalProperties": false,+ "properties": {+ "backend": { "enum": ["claude", "codex", "opencode"] },+ "model_id": { "type": "string", "minLength": 1 },+ "agents": {+ "type": "array",+ "items": { "type": "string", "minLength": 1 },+ "uniqueItems": true,+ "description": "Enabled named Agent ids in ascending lexicographic order."+ }+ }+ }+ },+ "examples": [+ {+ "ok": false,+ "contract_version": 5,+ "error": "source_model_in_route_chain",+ "would_remove_hops": [+ {+ "backend": "claude",+ "menu_model": "claude-opus-4-6",+ "source_id": "src_anthkey01",+ "model_id": "claude-opus-4-6",+ "position": 2+ }+ ],+ "would_interrupt": [+ {+ "backend": "claude",+ "model_id": "claude-opus-4-6",+ "agents": ["pm"]+ }+ ]+ }+ ]+}diff --git a/docs/plans/model-hub-contracts/mirror-registry.json b/docs/plans/model-hub-contracts/mirror-registry.jsonindex b86f80f11..a0fa59a40 100644--- a/docs/plans/model-hub-contracts/mirror-registry.json+++ b/docs/plans/model-hub-contracts/mirror-registry.json@@ -61,18 +61,6 @@"ui/src/i18n/*.json","vibe/i18n/*.json"]- },- {- "value": "source_model_managed_upstream",- "contract_file": "docs/plans/model-hub-contracts/api.md",- "negative_test_file": "tests/test_model_hub_api.py",- "negative_test": "test_discovered_source_model_delete_is_rejected_as_upstream_managed",- "forbidden_ui_globs": [- "ui/src/components/settings/models/**/*.ts",- "ui/src/components/settings/models/**/*.tsx",- "ui/src/i18n/*.json",- "vibe/i18n/*.json"- ]}],"repo_absence_checks": [@@ -109,7 +97,10 @@"schema": "probe-result.schema.json","paths": ["/properties/error"],"exclude": [null],- "extras": ["models.probe.native_cli_unavailable"]+ "extras": [+ "models.probe.native_cli_unavailable",+ "models.source.backoff.connection_failed"+ ]}]},@@ -123,7 +114,8 @@},"target": {"schema": "agent-chain.schema.json",- "path": "/properties/chain/items/properties/health"+ "path": "/properties/chain/items/properties/health",+ "exclude": ["backoff"]},"mapping": {"active": "healthy",@@ -223,6 +215,10 @@"schema": "agent-chain.schema.json","paths": ["/properties/backend"]},+ {+ "schema": "source.schema.json",+ "paths": ["/properties/adopted_by/items/properties/backend"]+ },{"schema": "probe-result.schema.json","paths": ["/properties/backend"]@@ -289,8 +285,7 @@"path": "/properties/error","exclude": [null,- "models.source.cooldown.network",- "models.source.cooldown.timeout",+ "models.source.backoff.connection_failed","models.source.cooldown.rate_limited","models.source.cooldown.quota_exhausted","models.source.cooldown.server_error",@@ -424,6 +419,11 @@"kind": "marker_tail","file": "docs/plans/model-hub-contracts/api.md","marker": "authority-consumer: protocol "+ },+ {+ "kind": "schema_vocabulary",+ "schema": "source-create.schema.json",+ "paths": ["/properties/protocol_order/items"]}]},@@ -501,6 +501,267 @@"marker": "authority-consumer: observation.discovery "}]+ },+ {+ "id": "D9",+ "domain": "runtime dependency health schema",+ "authority": {+ "kind": "markdown_table",+ "file": "docs/plans/model-hub.md",+ "heading": "Runtime dependency state matrix",+ "column": "Decision"+ },+ "consumers": [+ {+ "kind": "schema_vocabulary",+ "schema": "runtime-dependency.schema.json",+ "paths": ["/properties/status/properties/health"]+ }+ ]+ },+ {+ "id": "D10",+ "domain": "runtime dependency health API",+ "authority": {+ "kind": "markdown_table",+ "file": "docs/plans/model-hub.md",+ "heading": "Runtime dependency state matrix",+ "column": "Decision"+ },+ "consumers": [+ {+ "kind": "marker_tail",+ "file": "docs/plans/model-hub-contracts/api.md",+ "marker": "authority-consumer: runtime.health "+ }+ ]+ },+ {+ "id": "D11",+ "domain": "runtime install failure presentation keys",+ "authority": {+ "kind": "schema_vocabulary",+ "schema": "runtime-dependency.schema.json",+ "paths": ["/properties/status/properties/error_key"],+ "exclude": [null]+ },+ "consumers": [+ {+ "kind": "json_object_keys",+ "file": "ui/src/i18n/en.json",+ "path": "/settings/models/install/fail",+ "prefix": "settings.models.install.fail."+ },+ {+ "kind": "json_object_keys",+ "file": "ui/src/i18n/zh.json",+ "path": "/settings/models/install/fail",+ "prefix": "settings.models.install.fail."+ }+ ]+ },+ {+ "id": "D12",+ "domain": "runtime install synchronous refusals",+ "authority": {+ "kind": "markdown_table",+ "file": "docs/plans/model-hub.md",+ "heading": "Runtime install refusal matrix",+ "column": "Decision"+ },+ "consumers": [+ {+ "kind": "marker_tail",+ "file": "docs/plans/model-hub-contracts/api.md",+ "marker": "authority-consumer: runtime.install_error "+ }+ ]+ },+ {+ "id": "D13",+ "domain": "Source-create nonce claim states",+ "authority": {+ "kind": "markdown_table",+ "file": "docs/plans/model-hub.md",+ "heading": "Source-create nonce state machine",+ "column": "Decision"+ },+ "consumers": [+ {+ "kind": "marker",+ "file": "docs/plans/model-hub-contracts/api.md",+ "prefix": "nonce."+ }+ ]+ },+ {+ "id": "D15",+ "domain": "guard refusal error codes",+ "authority": {+ "kind": "schema_vocabulary",+ "schema": "guard-refusal.schema.json",+ "paths": ["/properties/error"]+ },+ "consumers": [+ {+ "kind": "marker_tail",+ "file": "docs/plans/model-hub-contracts/api.md",+ "marker": "authority-consumer: guard.error "+ }+ ]+ },+ {+ "id": "D16",+ "domain": "guard confirmation totality",+ "authority": {+ "kind": "markdown_table",+ "file": "docs/plans/model-hub.md",+ "heading": "Guard confirmation totality matrix",+ "column": "Decision"+ },+ "consumers": [+ {+ "kind": "marker",+ "file": "docs/plans/model-hub-contracts/api.md",+ "prefix": "guard_decision."+ }+ ]+ },+ {+ "id": "D17",+ "domain": "OAuth-start nonce claim states",+ "authority": {+ "kind": "markdown_table",+ "file": "docs/plans/model-hub.md",+ "heading": "OAuth-start nonce state machine",+ "column": "Decision"+ },+ "consumers": [+ {+ "kind": "marker",+ "file": "docs/plans/model-hub-contracts/api.md",+ "prefix": "oauth_nonce."+ }+ ]+ },+ {+ "id": "D18",+ "domain": "guard refusal error-to-plan relation",+ "authority": {+ "kind": "markdown_table",+ "file": "docs/plans/model-hub.md",+ "heading": "Guard error-plan relation",+ "column": "Decision"+ },+ "consumers": [+ {+ "kind": "marker_tail",+ "file": "docs/plans/model-hub-contracts/guard-refusal.schema.json",+ "marker": "authority-consumer: guard.error_plan "+ }+ ]+ },+ {+ "id": "D19",+ "domain": "network failure phase totality",+ "authority": {+ "kind": "markdown_table",+ "file": "docs/plans/model-hub.md",+ "heading": "Network-failure totality matrix",+ "column": "Decision"+ },+ "consumers": [+ {+ "kind": "marker",+ "file": "docs/plans/model-hub-contracts/api.md",+ "prefix": "network_failure."+ }+ ]+ },+ {+ "id": "D20",+ "domain": "live connection backoff health",+ "authority": {+ "kind": "markdown_table",+ "file": "docs/plans/model-hub.md",+ "heading": "Live connection-backoff projection",+ "column": "Decision"+ },+ "consumers": [+ {+ "kind": "schema_vocabulary",+ "schema": "agent-chain.schema.json",+ "paths": ["/properties/chain/items/properties/health"],+ "exclude": ["healthy", "cooldown", "needs_action", "error"]+ },+ {+ "kind": "marker_tail",+ "file": "docs/plans/model-hub-contracts/api.md",+ "marker": "authority-consumer: live_backoff.health "+ }+ ]+ },+ {+ "id": "D21",+ "domain": "live connection backoff reason",+ "authority": {+ "kind": "schema_vocabulary",+ "schema": "agent-chain.schema.json",+ "paths": ["/properties/chain/items/properties/reason/anyOf/1"]+ },+ "consumers": [+ {+ "kind": "marker_tail",+ "file": "docs/plans/model-hub-contracts/api.md",+ "marker": "authority-consumer: live_backoff.reason "+ },+ {+ "kind": "schema_vocabulary",+ "schema": "probe-result.schema.json",+ "paths": ["/properties/error"],+ "exclude": [+ null,+ "models.source.cooldown.rate_limited",+ "models.source.cooldown.quota_exhausted",+ "models.source.cooldown.server_error",+ "models.source.needs_action.oauth_expired",+ "models.source.needs_action.balance_exhausted",+ "models.source.needs_action.credential_revoked",+ "models.source.needs_action.account_banned",+ "models.source.error.unclassified",+ "models.probe.native_cli_unavailable"+ ]+ },+ {+ "kind": "json_object_keys",+ "file": "ui/src/i18n/en.json",+ "path": "/models/source/backoff",+ "prefix": "models.source.backoff."+ },+ {+ "kind": "json_object_keys",+ "file": "ui/src/i18n/zh.json",+ "path": "/models/source/backoff",+ "prefix": "models.source.backoff."+ }+ ]+ },+ {+ "id": "D22",+ "domain": "OAuth terminal response and materialization-error totality",+ "authority": {+ "kind": "markdown_table",+ "file": "docs/plans/model-hub.md",+ "heading": "OAuth terminal response and materialization-error matrix",+ "column": "Decision"+ },+ "consumers": [+ {+ "kind": "marker",+ "file": "docs/plans/model-hub-contracts/api.md",+ "prefix": "oauth_terminal."+ }+ ]}],"ownership_checks": [diff --git a/docs/plans/model-hub-contracts/oauth-flow.schema.json b/docs/plans/model-hub-contracts/oauth-flow.schema.jsonindex 7b4f41239..41e97d404 100644--- a/docs/plans/model-hub-contracts/oauth-flow.schema.json+++ b/docs/plans/model-hub-contracts/oauth-flow.schema.json@@ -9,9 +9,14 @@"additionalProperties": false,"properties": {"flow_id": { "type": "string" },+ "client_nonce": {+ "type": "string",+ "pattern": "^ofn_[a-z0-9]{16,64}$",+ "description": "Optional client-generated OAuth-start correlation echoed from the start request. Before provider work the server atomically claims the exact (client_nonce, vendor, channel) tuple; concurrent retries coalesce to its one pending start and terminal result. Provider failure or task cancellation before a flow exists releases the claim after cleanup, while success atomically converts it to the one OAuthFlow returned by every retry until its existing expires_at. Explicit cancellation retains that committed flow with state cancelled until expiry and starts no provider on a same-tuple retry."+ },"intent": {"enum": ["create", "reauth"],- "description": "The flow intent determines its terminal response: create returns `{flow, source, added_to, adopted_by}`; reauth returns `{flow, source, recovered, interrupted_pairs}`. It is explicit because source_id cannot distinguish create from reauth and clients must not infer response shape from remembered UI state."+ "description": "The flow intent determines its successful terminal response: create returns `{flow, source, added_to, adopted_by}`; reauth returns `{flow, source, recovered, interrupted_pairs}`. A local terminal materialization error instead uses the standard error envelope; only a nonempty acquisition-stage interruption report adds `interrupted_pairs`. Intent is explicit because source_id cannot distinguish create from reauth and clients must not infer response shape from remembered UI state."},"source_id": { "type": ["string", "null"], "description": "Pending or existing Source this flow binds to. Both hub and native_cli create/reauth flows set it; null is reserved for presentation-only flows outside Model Hub." },"vendor": { "type": "string" },@@ -29,11 +34,22 @@}},"error_key": { "type": ["string", "null"], "description": "i18n key; raw upstream errors never surface" },- "expires_at": { "type": ["string", "null"], "format": "date-time" }+ "expires_at": { "type": ["string", "null"], "format": "date-time", "description": "Flow expiry. A flow without client_nonce may use null for ordinary or presentation-only lifetime handling; a nonce-bearing flow always carries a non-null date-time that bounds reconciliation and retained cancellation." }},+ "allOf": [+ {+ "if": { "required": ["client_nonce"] },+ "then": {+ "properties": {+ "expires_at": { "type": "string", "format": "date-time" }+ }+ }+ }+ ],"examples": [{"flow_id": "oaf_claude01",+ "client_nonce": "ofn_01j5w8z7p4n6q2rt","intent": "create","source_id": "src_claudepro1","vendor": "anthropic",diff --git a/docs/plans/model-hub-contracts/probe-result.schema.json b/docs/plans/model-hub-contracts/probe-result.schema.jsonindex f7c950096..59bb1b54b 100644--- a/docs/plans/model-hub-contracts/probe-result.schema.json+++ b/docs/plans/model-hub-contracts/probe-result.schema.json@@ -18,8 +18,7 @@"type": ["string", "null"],"enum": [null,- "models.source.cooldown.network",- "models.source.cooldown.timeout",+ "models.source.backoff.connection_failed","models.source.cooldown.rate_limited","models.source.cooldown.quota_exhausted","models.source.cooldown.server_error",@@ -43,7 +42,7 @@},{"if": { "properties": { "channel": { "const": "hub" }, "latency_ms": { "type": "null" } }, "required": ["channel", "latency_ms"] },- "then": { "properties": { "error": { "enum": ["models.source.cooldown.network", "models.source.cooldown.timeout"] } } }+ "then": { "properties": { "error": { "const": "models.source.backoff.connection_failed" } } }},{"if": { "properties": { "channel": { "const": "native_cli" } }, "required": ["channel"] },@@ -56,11 +55,16 @@{"if": { "properties": { "error": { "const": "models.probe.native_cli_unavailable" } }, "required": ["error"] },"then": { "properties": { "channel": { "const": "native_cli" }, "reachable": { "const": false }, "latency_ms": { "type": "null" } } }+ },+ {+ "if": { "properties": { "error": { "const": "models.source.backoff.connection_failed" } }, "required": ["error"] },+ "then": { "properties": { "channel": { "const": "hub" }, "reachable": { "const": false }, "latency_ms": { "type": "null" } } }}],"examples": [{ "contract_version": 5, "backend": "codex", "channel": "hub", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": 412, "error": null },{ "contract_version": 5, "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": 5, "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": 5, "backend": "codex", "channel": "native_cli", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": null },{ "contract_version": 5, "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.jsonindex 4003e704a..84132fba7 100644--- a/docs/plans/model-hub-contracts/runtime-dependency.schema.json+++ b/docs/plans/model-hub-contracts/runtime-dependency.schema.json@@ -2,12 +2,17 @@"$schema": "http://json-schema.org/draft-07/schema#","$id": "model-hub/runtime-dependency.schema.json","title": "RuntimeDependency",- "description": "v5 (2026-07-31 targeted amendment): managed engine dependency manifest + status. The installed lazy-start state is not a failure: not_started means no start has been demanded in this service lifetime; down means a demanded runtime failed or stopped. Pinned manifest values remain normative until the next explicit re-pin.",+ "description": "v5 managed engine dependency manifest + server-owned installation and runtime status. not_installed -> installing -> not_started is the installation path; not_started is installed lazy-start idleness, and down means a demanded runtime failed or stopped. Pinned manifest values remain normative until the next explicit re-pin.","type": "object","required": ["contract_version", "manifest", "status"],"additionalProperties": false,"properties": {"contract_version": { "const": 5 },+ "host_platform": {+ "type": "string",+ "pattern": "^[a-z0-9]+(?:-[a-z0-9_]+)+$",+ "description": "Server-authoritative platform key for the Avibe host, never the browser device. Installation is supported exactly when manifest.assets contains an exact platform match. OPTIONAL in the reusable schema and REQUIRED on runtime API payloads."+ },"manifest": {"type": "object","required": ["name", "version", "source_sha", "assets"],@@ -36,6 +41,41 @@"type": "object","required": ["installed_version", "verified", "health"],"additionalProperties": false,+ "allOf": [+ {+ "$comment": "Only not_installed may carry a persisted install-failure key. Initial absence and an unsupported host may still carry null.",+ "if": {+ "properties": {+ "health": {+ "not": { "const": "not_installed" }+ }+ },+ "required": ["health"]+ },+ "then": {+ "properties": {+ "error_key": { "type": "null" }+ }+ }+ },+ {+ "$comment": "installing is the unverified, non-listening transition entered only from not_installed. A verified binary settles at not_started before it may listen.",+ "if": {+ "properties": {+ "health": { "const": "installing" }+ },+ "required": ["health"]+ },+ "then": {+ "required": ["listening"],+ "properties": {+ "installed_version": { "type": "null" },+ "verified": { "const": false },+ "listening": { "type": "null" }+ }+ }+ }+ ],"properties": {"installed_version": { "type": ["string", "null"] },"verified": { "type": "boolean", "description": "SHA256 of installed binary matches manifest" },@@ -49,16 +89,21 @@}},"health": {- "enum": ["ok", "degraded", "down", "not_started", "not_installed"],- "description": "not_started is installed and intentionally idle until first demand; down is a runtime that was demanded and is no longer available."+ "enum": ["ok", "degraded", "down", "not_installed", "installing", "not_started"],+ "description": "not_installed is the stable absence state; installing is the server-owned transition after an install request; not_started is verified installation and intentional lazy-start idleness; down is a runtime that was demanded and is no longer available."},- "last_check": { "type": ["string", "null"], "format": "date-time" }+ "last_check": { "type": ["string", "null"], "format": "date-time" },+ "error_key": {+ "enum": [null, "settings.models.install.fail.detail"],+ "description": "Persisted closed i18n key for the most recent install failure. A failed install settles at not_installed with settings.models.install.fail.detail; a new install attempt clears it before entering installing, and every other health carries null. OPTIONAL in the reusable schema and REQUIRED on runtime API payloads."+ }}}},"examples": [{"contract_version": 5,+ "host_platform": "darwin-arm64","manifest": {"name": "cliproxyapi","version": "v7.2.95",@@ -75,7 +120,8 @@"verified": true,"listening": { "host": "127.0.0.1", "port": 15220 },"health": "ok",- "last_check": "2026-07-23T03:40:00+08:00"+ "last_check": "2026-07-23T03:40:00+08:00",+ "error_key": null}}]diff --git a/docs/plans/model-hub-contracts/source-create.schema.json b/docs/plans/model-hub-contracts/source-create.schema.jsonnew file mode 100644index 000000000..b195c08bc--- /dev/null+++ b/docs/plans/model-hub-contracts/source-create.schema.json@@ -0,0 +1,56 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "$id": "model-hub/source-create.schema.json",+ "title": "SourceCreate",+ "description": "API-key Source creation input. It extends the unsaved observation request with display and reconciliation data; the server still owns Source identity, protocol evidence, discovered inventory, health, usage, custody metadata, and timestamps. When client_nonce is present, the server reserves it atomically in process before observation or credential work; only a successful commit persists Source.client_nonce unchanged. A lost-response client reconciles through the ordinary Source list without a receipt or separate endpoint. Nonce uniqueness covers live-process reservations and live Sources; process restart or Source deletion releases it, and a later same-nonce request after the required list read is a fresh create.",+ "type": "object",+ "required": ["vendor", "key"],+ "additionalProperties": false,+ "properties": {+ "vendor": {+ "type": "string",+ "pattern": "^[a-z0-9]+(?:[._-][a-z0-9]+)*$",+ "description": "Vendor id used by the response-backed observation."+ },+ "display_name": {+ "type": "string",+ "maxLength": 64,+ "description": "Optional user-facing name. Omission uses the server's canonical vendor label."+ },+ "base_url": {+ "type": ["string", "null"],+ "description": "null selects the vendor's official endpoint; a custom value selects a relay or self-hosted endpoint."+ },+ "key": {+ "type": "string",+ "minLength": 1,+ "writeOnly": true,+ "description": "Transient plaintext credential. It is never returned or persisted in Source state."+ },+ "protocol_order": {+ "type": "array",+ "items": {+ "enum": ["anthropic", "openai_responses", "openai_chat"]+ },+ "minItems": 3,+ "maxItems": 3,+ "uniqueItems": true,+ "description": "Optional one-time probe order containing every protocol exactly once. It orders observation and never supplies a protocol conclusion."+ },+ "client_nonce": {+ "type": "string",+ "pattern": "^scn_[a-z0-9]{16,64}$",+ "description": "Optional client-generated create correlation held before submission. The server atomically reserves it in process before observation or credential work and writes Source.client_nonce only on successful commit; no durable pre-create claim record exists. A lost-response client reads Sources before retrying. A same-nonce retry receives an in-progress conflict, atomically reclaims a released slot as a fresh create, or receives a committed conflict and reconciles by finding that nonce in the ordinary Source list. Uniqueness applies only while a live-process reservation or live Source exists; process restart and Source deletion release it. It is not Source identity, credential material, or a routing input."+ }+ },+ "examples": [+ {+ "vendor": "custom",+ "display_name": "relay.example",+ "base_url": "https://relay.example/v1",+ "key": "<transient plaintext key>",+ "protocol_order": ["openai_chat", "openai_responses", "anthropic"],+ "client_nonce": "scn_01j5w8z7p4n6q2rt"+ }+ ]+}diff --git a/docs/plans/model-hub-contracts/source.schema.json b/docs/plans/model-hub-contracts/source.schema.jsonindex 55a8c733f..968f26f7c 100644--- a/docs/plans/model-hub-contracts/source.schema.json+++ b/docs/plans/model-hub-contracts/source.schema.json@@ -31,6 +31,11 @@"format": "date-time","description": "When the Source was added, retained as ordinary audit/display metadata. Add-time placement and runtime routing do not read this field. Optional in the schema and nullable when the creation time is unknown."},+ "client_nonce": {+ "type": "string",+ "pattern": "^scn_[a-z0-9]{16,64}$",+ "description": "Optional client-generated create correlation persisted unchanged only when SourceCreate commits. It is unique among live Sources and live-process Source-create reservations, and lets a client recognize a committed Source after the create response is lost. Process restart ends an in-flight reservation; Source deletion releases a committed nonce. It is not Source identity, a credential, or a routing input."+ },"last_discovered_at": {"type": ["string",@@ -116,7 +121,7 @@}},{- "$comment": "v2 (07-29, review round 4; vocabulary closed in round 5): `cooldown` is the ONLY status whose `retry_at` is non-null — spec §4.5 defines it as 'self-healing, `retry_at` known', and 「约 09:15 恢复」 is the whole copy of the state. A cooldown with a null stamp leaves the UI able to say only 暂不可用 with no recovery time, which is indistinguishable to the user from 需处理 — the one distinction this taxonomy exists to make. `detail_key` stays optional here (the recovery time is the load-bearing fact, the cause is a nicety) but its vocabulary is now a CLOSED ENUM rather than the `^models\\.source\\.cooldown\\..+` pattern round 4 used. The round-5 review named that bypass on probe-result's `error`, where the identical construction let `models.source.cooldown.network: <raw upstream body>` validate; the same prefix-plus-`.+` shape was here too and is the same hole, so it is closed in both files rather than only where it was spotted. `.+` after a trusted prefix is a naming convention, not a redaction boundary — the whole point of `detail_key` is that raw upstream text never reaches config or the UI. The five keys are the self-healing causes the adapter classifies; `needs_action` keys remain unwritable here, so a dead source still cannot be filed under a status that promises recovery.",+ "$comment": "v2 (07-29, review round 4; vocabulary closed in round 5; network correction 2026-08-11): `cooldown` is the ONLY persisted Source status whose `retry_at` is non-null — spec §4.5 defines it as self-healing with a known retry time. `detail_key` stays optional here, but its vocabulary is a CLOSED ENUM rather than the earlier `^models\\.source\\.cooldown\\..+` pattern: a trusted prefix plus `.+` is a naming convention, not a redaction boundary. The retained quota, rate-limit, and server-error keys are shaped explicit upstream classifications. Unclassified connection failures use the separate live AgentChain backoff projection; the historical persistent network/timeout keys are not legal Source state. `needs_action` keys remain unwritable here, so a dead source still cannot be filed under a status that promises unattended recovery.","if": {"properties": {"status": {@@ -138,8 +143,6 @@"detail_key": {"enum": [null,- "models.source.cooldown.network",- "models.source.cooldown.timeout","models.source.cooldown.rate_limited","models.source.cooldown.quota_exhausted","models.source.cooldown.server_error"@@ -217,7 +220,7 @@"error"],"$comment": "Source-global health never implies process-local native CLI availability. Live process availability is resolved separately and takes precedence when deciding hop runnability.",- "description": "Source-global recovery state. cooldown is self-healing with retry_at; needs_action and error require user action; active and standby are healthy. Process availability is a distinct live fact carried by Route-hop annotations, so a globally healthy Source may still have a native_cli_unavailable hop. Quota and upstream reachability share one Source-global state across backends."+ "description": "Source-global recovery state. cooldown is self-healing with retry_at; needs_action and error require user action; active and standby are healthy. Process availability and short connection backoff are distinct live facts carried by Route-hop annotations, so neither is persisted here. Only shaped explicit upstream classifications may change Source-global health; an unclassified transport failure never does."},"retry_at": {"type": [@@ -233,10 +236,8 @@"string","null"],- "description": "Closed i18n key, never raw upstream error text. Healthy states require null. Cooldown may carry a self-healing cause; needs_action requires the cause/remedy key selected by its schema branch; error requires the generic unclassified key. The mirror registry checks this vocabulary against probe and resolution-event consumers.",+ "description": "Closed i18n key, never raw upstream error text. Healthy states require null. Cooldown may carry a shaped self-healing quota, rate-limit, or server-error cause; unclassified connection failures use only the live AgentChain backoff projection. needs_action requires the cause/remedy key selected by its schema branch; error requires the generic unclassified key. The mirror registry checks this vocabulary against probe and resolution-event consumers.","examples": [- "models.source.cooldown.network",- "models.source.cooldown.timeout","models.source.cooldown.rate_limited","models.source.cooldown.quota_exhausted","models.source.cooldown.server_error",@@ -312,6 +313,29 @@"properties": {"discovered_at": {"type": "null"+ },+ "retired": {+ "const": false+ }+ }+ }+ },+ {+ "$comment": "Only an upstream-discovered model can be retired. The flag is a persistent tombstone: refresh preserves the row and never clears the flag, even when the upstream advertises the model again.",+ "if": {+ "properties": {+ "retired": {+ "const": true+ }+ },+ "required": [+ "retired"+ ]+ },+ "then": {+ "properties": {+ "origin": {+ "const": "discovered"}}}@@ -341,6 +365,11 @@"items": { "type": "string", "minLength": 1 },"uniqueItems": true},+ "retired": {+ "type": "boolean",+ "default": false,+ "description": "Persistent retirement tombstone. Omission means false. Only a discovered entry may be true; a retired entry remains readable but supplies no route, match, or invocation and refresh never revives it."+ },"discovered_at": {"type": ["string",@@ -351,6 +380,25 @@}}},+ "adopted_by": {+ "type": "array",+ "description": "Server-derived Source-card projection of persisted Route references, sorted by backend then menu_model. It is returned on every current Source read and creation payload, is never persisted on the Source record, and must not be reconstructed by clients from live chains.",+ "uniqueItems": true,+ "items": {+ "type": "object",+ "required": ["backend", "menu_model"],+ "additionalProperties": false,+ "properties": {+ "backend": {+ "enum": ["claude", "codex", "opencode"]+ },+ "menu_model": {+ "type": "string",+ "minLength": 1+ }+ }+ }+ },"credential_ref": {"type": ["string",@@ -513,7 +561,7 @@"state": {"status": "cooldown","retry_at": "2026-07-23T04:00:00Z",- "detail_key": "models.source.cooldown.timeout"+ "detail_key": "models.source.cooldown.server_error"},"usage": {"cycle_used_pct": null,diff --git a/docs/plans/model-hub-implementation.md b/docs/plans/model-hub-implementation.mdindex 357125a5c..ea76857d7 100644--- a/docs/plans/model-hub-implementation.md+++ b/docs/plans/model-hub-implementation.md@@ -109,49 +109,79 @@ The v3 batch separates product truth and fidelity evidence from implementationlanes with exclusive file ownership. K1 and K2 may run in parallel. K1 owns thisorchestrator-authorized S-1 contract consolidation and the generated authority guard;after this head, those contract files transfer to I1 and then freeze for downstream-lanes. The I1–I6 split is **tentative pending the UI lane's design-to-spec reconciliation table**;+lanes. The K5/K6/I1–I7 split is **tentative pending the UI lane's design-to-spec reconciliation table**;that reconciliation may change content but is not expected to change file ownership.| Lane | Executor preference | Exclusive scope | Depends on || --- | --- | --- | --- || **K1 spec v3 sync** | codex | This PR's planning documents plus the owner-authorized final S-1/protocol edits under `docs/plans/model-hub-contracts/`, their byte-mirror/version consumers, and the live-input authority guard. It does not implement the remaining Gateway runtime | — || **K2 conversion fidelity** | codex | Preserve the recorded M0 measurements and go/no-go rows; record the 2026-08-08 owner waiver of an official-API attribution re-test and the accepted relay-attributed reasoning degradation without rewriting the evidence or adding product/UI scope | — |-| **I1 contracts and config core** *(tentative)* | codex | All files under `docs/plans/model-hub-contracts/`; `config/v2_config.py`; `core/controller.py`; `core/handlers/model_hub/adapter.py` and the byte-identical contract interface; `core/handlers/model_hub/{service,resolver,classification,errors,provenance,rpc,request,events}.py`; `modules/agents/model_hub.py`; `vibe/{ui_server,model_hub_client}.py`; `tests/test_model_hub_config.py`; `tests/test_model_hub_api.py`; `tests/test_model_hub_resolution.py`; `tests/test_model_hub_injection.py`; `tests/test_controller_model_hub_gate.py`; `tests/test_model_hub_l3.py` through the same-tested-head contract transition. `tests/test_multi_platform_runtime.py` and `tests/test_claude_cli_path.py` are read-only dependency checks: I1 repairs breakage caused by removed resolver symbols but does not refactor them. Owns the §8 final contracts, same-tested-head closure, §4.3 configured-chain executor, serializers, API envelopes, shared validation, and the default-off release gate while I1 is active | K1. **Merges first** |-| **I2 runtime transport** *(tentative)* | codex | `core/handlers/model_hub/turn_gateway.py`; `vibe/model_hub_runtime/**`; `tests/test_model_hub_runtime.py`; after I1 merges, `tests/test_model_hub_l3.py` transfers wholly to I2 for runtime behavior | I1 |-| **I3 subscription custody and native import** *(tentative)* | codex | `core/handlers/model_hub/{oauth,native_oauth,revocations,migration}.py`; `tests/test_model_hub_oauth.py`; `tests/scenarios/model_hub/test_model_hub_migration_scenarios.py`; `tests/scenarios/auth_setup/catalog.yaml`; `tests/scenarios/auth_setup/test_auth_setup_scenarios.py`. The migration scenario and complete auth-setup catalog/test loop are the sole carve-outs from I5's scenario tree | I1 |-| **I4 Sources / Gateway UI** *(tentative)* | codex | `ui/src/components/settings/models/**`; `ui/src/i18n/*.json`; `vibe/i18n/*.json`; UI tests. Both i18n trees are I4-exclusive | I1's API envelopes + the UI-spec PR |-| **I5 scenario validation** *(tentative)* | codex | `tests/scenarios/model_hub/**` except I3's native-import scenario; `tests/scenario_harness/**` | I1–I4 |+| **K5 UI specification closure** | codex | Sole ownership of `docs/plans/model-hub-ui-spec.md` across three serialized rounds: (1) the frame registry in in-flight PR #1336; (2) K4 gap-reference upgrades plus the AC-49 withdrawn-evidence cleanup and AC-50 live-backoff presentation registration; (3) the G-32 interaction specification. K5 edits no contract, implementation, locale, or UI file. **K3 residual-queue transfer recorded by PM ruling 2026-08-11 23:09.** | round 1 is independently in flight; round 2 waits for K4 merged; round 3 waits for rounds 1 and 2 merged and must merge before I4's second increment |+| **K6 post-#1312 Turn-outcome contract closure** | codex; dispatch at activation | One bounded contract round, dispatched by the orchestrator only after K4 and #1312 merge. Exclusive scope is `docs/plans/model-hub.md` §4.5's Turn-outcome matrix/consumer segment; `docs/plans/model-hub-contracts/{api.md,turn-provenance.schema.json,resolution-event.schema.json,mirror-registry.json}`; and the corresponding binding/ledger rows in this document. It closes only registered G-34 plus any §4.5 gap row left by the merged #1312 head, changes either schema only when the selected outcome/copy/payload requires it, and owns no implementation, test, UI, or locale file. **Single-round scope and dispatch edge fixed by PM ruling 2026-08-12 02:00.** | K4 + #1312 merged; must merge before I7 starts |+| **I1 contracts and config core** *(tentative)* | codex | All files under `docs/plans/model-hub-contracts/`; `config/v2_config.py`; `core/controller.py`; `core/handlers/model_hub/adapter.py` and the byte-identical contract interface; `core/handlers/model_hub/{service,resolver,classification,errors,provenance,rpc,request,events}.py`; `vibe/{ui_server,model_hub_client}.py`; `tests/test_model_hub_config.py`; `tests/test_model_hub_api.py`; resolver unit coverage through #1312; `tests/test_model_hub_injection.py`; `tests/test_controller_model_hub_gate.py`; `tests/test_model_hub_l3.py` through #1312's same-tested-head transition. I1 also finishes #1312's already-open shared native-launch-module edits before the transfer recorded solely in I7's row. `tests/test_multi_platform_runtime.py` and `tests/test_claude_cli_path.py` are read-only dependency checks during I1: I1 repairs breakage caused by removed resolver symbols but does not refactor them. I1 owns the §8 final contracts, same-tested-head closure, §4.3 configured-chain executor, serializers, API envelopes, shared validation, and the default-off release gate while #1312 is active. After #1312 merges, only K6's bounded contract scope transfers immediately; the implementation/test files explicitly named by I7 remain unavailable to I7 until K6 merges, and the other I1 files retain their stated owner. **Turn-outcome transfer revised 2026-08-12 02:00.** | K1. **Merges first** |+| **I2 runtime transport** *(tentative)* | codex | `core/handlers/model_hub/turn_gateway.py`; `vibe/model_hub_runtime/**`; `tests/test_model_hub_runtime.py`; after #1312 merges, `tests/test_model_hub_l3.py` transfers to I2 for managed-Gateway runtime behavior, except for I7's one authorized AC-50 strict-xfail marker deletion. I2 owns authoritative raw shaped-error and `stream_started` facts produced by the managed Gateway only; this boundary flips at the first user-visible model-output byte, never at HTTP status, headers, or another response byte. Native backend callback facts and every classification/state decision belong to I7. The K4 increment additionally owns AC-38's install worker, persisted status/lease, orphan reconciliation, and runtime-level no-op assertions without moving the HTTP/API boundary out of I7. **Native failure ownership revised 2026-08-11 22:37.** | I1 + K4 merged; `test_model_hub_l3.py` transfer waits for #1312 merged |+| **I3 subscription custody and native import** *(tentative)* | codex | `core/handlers/model_hub/{oauth,native_oauth,revocations,migration}.py`; `tests/test_model_hub_oauth.py`; `tests/scenarios/model_hub/test_model_hub_migration_scenarios.py`; `tests/scenarios/auth_setup/catalog.yaml`; `tests/scenarios/auth_setup/test_auth_setup_scenarios.py`. The migration scenario and complete auth-setup catalog/test loop are the sole carve-outs from I5's scenario tree. The K4 increment owns AC-48's OAuth registry: it atomically claims the exact nonce/vendor/channel tuple before provider work, coalesces concurrent retries to one pending terminal result, releases failure/task cancellation only before a flow exists, atomically converts success to one echoed-nonce flow, retains an explicitly canceled nonce-bearing flow as the same terminal `cancelled` flow until its existing expiry, and releases the tuple at expiry. AUTH-SETUP-210 blocks the first provider call, overlaps the same-nonce retry, and proves provider invocation exactly once. For AC-52, AUTH-SETUP-109 is the Hub-held re-auth closed loop: missing/false acknowledgement rejects before any adapter/provider call, true acknowledgement starts exactly one Hub flow, and terminal status/repair projection agrees; I7 owns the API/service gate and I5 only consumes the completed scenario. **Explicit-cancel totality revised 2026-08-12 00:37; Hub re-auth scenario binding revised 2026-08-12 01:30.** | K4 merged + #1312 merged |+| **I4 Sources / Gateway UI** *(tentative; one lane, two increments)* | codex | `ui/src/components/settings/models/**`; `ui/src/i18n/*.json`; `vibe/i18n/*.json`; UI tests. Both i18n trees are I4-exclusive. The current increment consumes the already-specified install/unsupported-host surfaces for AC-38/AC-43; each model row may open frame 02, render the drawing, and consume the chain read projection, but no chain-write caller is wired and Save remains disabled. Exact-chain editing and its UI tests belong to the second increment only after K5's third-round G-32 specification merges. That second increment sends visible noninterrupting hop removal as one ordinary PUT and echoes both refusal-plan arrays unchanged only when protected supply would be interrupted, after I7 freezes both fixtures; the current increment continues to consume master's pre-I7 refusal shape and must not add inactive confirmation fields. It consumes AC-36/37/39–42/44–50 only after K5 round 2 changes their G rows from gaps to contract references and registers the live-backoff presentation; AC-51's read-before-retry client rule activates in the second increment after I7 freezes the deletion/recreate fixture. AC-53's materialization-error `interrupted_pairs` consumer activates only in that second increment after K5 round 2 registers E6 and I7 freezes positive/negative API payload fixtures. This is an ordering split inside I4, not a new lane identity. **Revised 2026-08-12 01:28 by PM ruling.** | current increment: I1 envelopes + K4 contracts; second increment: K5 rounds 1–3 merged + frozen I7/I2/I3 fixtures |+| **I7 contract-completion implementation (backend)** | codex | After K6 merges, exclusive ownership transfers from I1 for `config/v2_config.py`; `core/handlers/model_hub/{service,resolver,classification,rpc,request,errors,events}.py`; `modules/agents/model_hub.py`; `vibe/{ui_server,model_hub_client}.py`; `tests/test_model_hub_config.py`; `tests/test_model_hub_api.py`; and `tests/test_model_hub_resolution.py`. For the Model Hub failure-callback seam only, I7 also exclusively owns `modules/agents/base.py`, `modules/agents/claude_agent.py`, `modules/agents/codex/{agent,event_handler}.py`, `modules/agents/opencode/{agent,poll_loop}.py`, exact cross-backend phase fixtures in `tests/{test_claude_agent_sessions,test_codex_agent,test_opencode_server}.py`, and mechanical signature consumers in `tests/{test_claude_cli_path,test_multi_platform_runtime}.py`. I7 owns AC-35–AC-47 and AC-50–AC-53's backend producers/tests plus AC-48's API/service half. `service.py` is the sole shared guard-plan owner and implements every guard-totality row and the error-to-required-array relation; it also enforces AC-52's both-channel re-auth acknowledgement before any OAuth adapter call and AC-53's materialization-error response condition. `modules/agents/model_hub.py` owns the native classification/state decision: backend callbacks supply raw failure shape and phase only, and no native path writes a persistent network cooldown. The transferred resolver/classifier/event boundary owns `retired: false` filtering and all four network-failure cells; its post-output executor/provenance fixture consumes K6's G-34 row without inventing an outcome id, copy key, or payload shape. I7 delegates OAuth tuple claim/coalescing and terminal-flow expiry to I3's registry; its service/API half branches explicit cancellation by nonce presence, retaining the I3 flow for nonce-bearing reconciliation and forgetting only no-nonce flows. Its first AC-50 mechanical action is the sole owner-authorized I2-file exception: delete the strict xfail marker from `tests/test_model_hub_l3.py::test_probe_transport_failures_await_ac50_backoff_contract` in the same commit that makes its forward contract assertions XPASS; it otherwise consumes I2 managed-Gateway facts and I3 OAuth fixtures without editing their files. It never edits contracts, UI/i18n, scenario trees, or any other I2–I5 file. **Revised through the 2026-08-12 02:00 PM ruling.** | K4 + #1312 + K6 merged; every listed transfer and native callback seam activates only after all three merge |+| **I5 scenario validation** *(tentative)* | codex | `tests/scenarios/model_hub/**` except I3's native-import scenario; `tests/scenario_harness/**` | I1–I4 + I7 || **I6 release-gate removal** *(tentative)* | codex | After I5 merges, exclusive ownership transfers from I1 for `is_model_hub_enabled()` and every call site, `_init_model_hub()`, `core/controller.py`, and `tests/test_controller_model_hub_gate.py`. Delete the gate function rather than leaving a constant-true shell; invert the gate test so the final default state always constructs the v3 aggregate | I5 merged and all Model Hub scenarios green |-**Executor ruling (owner, 2026-08-09).** Every new I1–I6 implementation lane uses+**Executor ruling (owner, 2026-08-09; I7/K5/K6 registry completed 2026-08-12).** Every new K5, K6, and I1–I7 lane uses`codex`, including frontend work. Visual-fidelity risk is closed by process rather thanby changing executor: `design.pen` is the pixel-level authority, and a separate Codexacceptance thread compares the built UI against its design frames. Already-dispatchedClaude lanes complete their current specification work; subsequent implementation usesthe table above.-**Merge order:** K1 first for product authority; K2 remains independent evidence. I1-must merge before I2–I5. I2 and I3 may then proceed in parallel under the exclusive-file split; I4 additionally waits for the UI-spec PR; I5 closes integration after-I1–I4; I6 removes the release gate only after that evidence is merged. Every lane-follows `pr-delivery-loop`; no lane merges itself.--**Exclusive-file circuit breakers.** `service.py` and-`tests/test_model_hub_config.py` are I1-only. Both adapter copies move together under-I1. `modules/agents/model_hub.py`, `tests/test_model_hub_injection.py`,-`core/controller.py`, and `tests/test_controller_model_hub_gate.py` are I1-only until-the explicit I6 transfer for the release-gate pair. `tests/test_model_hub_l3.py` has one serial ownership transfer: I1 alone updates its-versioned contract/provenance fixtures on the first tested head; only after I1 merges-does I2 own the whole file. I2–I5 stop and report to the orchestrator if their work-requires any other I1 file. `ui/src/i18n/*.json` is I4-only: I3 or I5 requests any new+**Merge order:** K1 first for product authority; K2 remains independent evidence. K5+round 1 is independently in flight as PR #1336; round 2 starts only after K4 merges, and+round 3 starts only after K5 rounds 1 and 2 merge. I1 must merge before I2–I5. K6 is+dispatched only after #1312 merges and must merge after K4 and before I7; I7's whole lane,+including every AC-50 producer and fixture, therefore depends on K4 + #1312 + K6 rather+than a partial activation. I2 and I3 may proceed under their existing edges while K6 runs;+I7 starts only after the three-way edge closes. I4's current increment may+consume the already-specified install/host contracts and render frame 02 from the chain+read projection with Save disabled; its second increment waits for the G-32 specification+in K5 round 3 and frozen I7/I2/I3 fixtures. I5 closes integration after I1–I4 and+I7; I6 removes the release gate only after that evidence is merged. Every lane follows+`pr-delivery-loop`; no lane merges itself.++**Exclusive-file circuit breakers.** `service.py`, `classification.py`, `events.py`,+`tests/test_model_hub_config.py`, `core/handlers/model_hub/resolver.py`, and+`tests/test_model_hub_resolution.py` are I1-only through #1312 and remain unavailable to+K6, then transfer to I7 only after K6 merges under the explicit row above. The §4.5+Turn-outcome matrix/consumer segment and+`docs/plans/model-hub-contracts/{api.md,turn-provenance.schema.json,resolution-event.schema.json,mirror-registry.json}`+are I1/#1312-only until #1312 merges, K6-only for its one bounded registered-gap round,+and read-only to I7. `docs/plans/model-hub-ui-spec.md` is K5-only for all three+serialized rounds; K4 and I1–I7 consume it without editing it. Both adapter copies move+together under I1.+`modules/agents/model_hub.py` is I1-only through #1312 and then transfers to I7 only after+K6 merges; it does+not transfer to I2. `tests/test_model_hub_injection.py` remains I1-owned. `core/controller.py`+and `tests/test_controller_model_hub_gate.py` remain I1-only until their explicit I6+release-gate transfer. The narrow Model Hub failure-callback seams and exact fixtures named+in I7's row belong only to I7 after K4, #1312, and K6 merge; no ownership of unrelated behavior+in those backend files is implied. `tests/test_model_hub_l3.py` has one serial ownership+transfer: I1 alone updates its versioned contract/provenance fixtures through #1312; after+#1312, I2 owns the file except for I7's one AC-50 strict-xfail marker deletion. I2–I5 stop and report to the orchestrator if their work+requires any I1/I7 file not explicitly transferred to them. `ui/src/i18n/*.json` is I4-only: I3 or I5 requests any newmigration-scenario note key through the orchestrator and never edits UI i18n locally.The authority guard discovers every Python file outside the resolver package thatimports `core.handlers.model_hub.resolver` and requires each discovered file to occurin exactly one binding lane scope; the importer list is never copied into the guard.+For the K4 implementation batch, I7's listed files and narrow backend callback seams+activate only after K4, #1312, and the dispatched K6 round merge.+I7 must not edit I2 runtime files, I3 OAuth/custody files, I4 UI/i18n files, or I5+scenario files; those lanes consume the frozen contracts and exchange fixtures instead.+Any newly required implementation file stops the lane for an ownership ruling rather+than widening I7 by inference.**Final-contract anti-drift rule.** I1 owns every final-shape edit under-`model-hub-contracts/` and the exact mechanical closure in §8. After I1 merges, those-files are read-only to I2–I5. All remaining handoff rows still must land before release;+`model-hub-contracts/` and the exact mechanical closure in §8 through #1312. K6 is the+sole orchestrator-dispatched exception after #1312 and may edit only its registered+Turn-outcome closure scope; after K6 merges, those files are read-only to I2–I7. All+remaining handoff rows still must land before release;an implementation-proven mismatchescalates for an orchestrator-owned targeted revision; it is never patched by thediscovering lane.@@ -521,7 +551,7 @@ The contracts README's wording stays as written: it is still true, and still GA-canvas. For the v2 lanes that means **V6 01–04 and M01/M02** (§3); the framesthis item originally named were V4's.-## 8. Implementation acceptance criteria (AC-1–AC-34; v3 addenda through 2026-08-09)+## 8. Implementation acceptance criteria (AC-1–AC-51; v3/K4 addenda through 2026-08-11)**Current authority.** AC-1 through AC-21 retain their existing order and historicalrecord; AC-19's final acceptance is amended in place below. S-1 supersedes every@@ -767,9 +797,10 @@ to AC-17** are not implementation work: lane L0 applied them to the blocks theyand they are listed so the repairs are traceable to the findings that caused them.The counts and completion statements above apply to the historical AC-1–AC-21-inventory. The current ledger has **thirty-three** criteria. AC-22 onward are-owner-settled; only the explicitly owner-vetoable final-shape and vocabulary choices in-the v3 spec remain open to veto, not to lane-level invention.+inventory. The ledger had **thirty-three** criteria at the K1 freeze and now has+**fifty-one** after the owner-settled K4 addenda below. AC-22 onward are owner-settled;+only the explicitly owner-vetoable final-shape and vocabulary choices in the v3 spec+remain open to veto, not to lane-level invention.### Final contract shape handoff — owner rulings 2026-08-09@@ -837,19 +868,19 @@ external resolver importers.| ID | Contract file | Final required shape || --- | --- | --- || **FC-01** | `README.md` | Names §4.3 as the sole configured-chain execution authority and §4.2 as the sole Add-time Source placement authority; documents the same-tested-head terminal closure, the prelaunch full-handoff gate, and downstream read-only ownership; indexes the contract files and terminal `contract_version: 5`; describes Sources, exact configured routes, add-time matching, channel custody, configuration eligibility, inventory, adoption, and pull-only supply visibility without reproducing either authority. |-| **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`), credential refresh-capability branches, 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. 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 **5**. |-| **FC-03** | `source.schema.json` | `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[], display_name?, discovered_at?}`; the list is required, may be empty, and is editable for either origin. Hub-held subscriptions require no flag, consent field, or acknowledgement record. |+| **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 **5**. **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: hub | direct`, one explicit `sources.order`, and exactly one `{hops: [{source_id, model_id}, ...]}` row per menu model. `hops` is always present and may be empty; neither order has a policy discriminator. It enforces at most one native Source per backend and exposes `adopted_by: [{backend, menu_model}]` from persisted references; Source-card attribution reuses that projection. `supply_status` is the sole backend-health projection. Fresh-install construction uses Gateway; the onboarding service supplies Direct for an existing installation with no Model Hub state. No separate mapping, matching, enrollment, or takeover field exists. |-| **FC-06** | `agent-chain.schema.json` | Returns the stored exact Source/model hops in the same order with only `current`, `runnable`, closed blocker reasons (`source_missing`, `model_unsupported`, `native_cli_unavailable`, and Source-state reasons), and retry metadata added. It has no route-policy or capability-matching discriminator. Takeover derives from stored first hop plus live current position and adds no field. |-| **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. 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. |+| **FC-05** | `agent-supply.schema.json` | Each backend stores `mode: hub | direct`, one explicit `sources.order`, and exactly one `{hops: [{source_id, model_id}, ...]}` row per menu model. `hops` is always present and may be empty; neither order has a policy discriminator. It enforces at most one native Source per backend and exposes `adopted_by: [{backend, menu_model}]` from persisted references; Source-card attribution reuses that projection. `supply_status` is the sole backend-health projection, and every `model_supply` row with `chain_length: 0` must carry `has_runnable_hop: false`. Fresh-install construction uses Gateway; the onboarding service supplies Direct for an existing installation with no Model Hub state. No separate mapping, matching, enrollment, or takeover field exists. **Empty-chain correlation revision: 2026-08-11 22:37 K4.** |+| **FC-06** | `agent-chain.schema.json` | Returns the stored exact Source/model hops in the same order with only `current`, `runnable`, closed blocker reasons (`source_missing`, `model_unsupported`, `native_cli_unavailable`, Source-state reasons, and live `models.source.backoff.connection_failed`), and retry metadata added. `health: backoff` is a Source-scoped in-memory connection throttle before the first user-visible model-output byte with a `retry_at` strictly later than the read assembler's captured time; an expired overlay is normalized to underlying non-backoff health before serialization and never persists in Source/config state. Only output from that affected Source clears its streak; another Source's fallback output does not. The live overlay applies only over an otherwise healthy, exact-capability-present hop. Cooldown, needs-action, error, missing-Source, and unsupported-model facts suppress it and retain their established projection, so durable blockers roll up `interrupted`; only the native-process exception preserves backoff health/deadline while `native_cli_unavailable` takes the reason slot. A nonempty process-available chain blocked only by cooldown/ordinary backoff validates as `waiting` and cannot validate as `interrupted`. The shape has no route-policy or capability-matching discriminator. Takeover derives from stored first hop plus live current position and adds no field. **Blocker-precedence revision: 2026-08-11 23:49 K4.** |+| **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 contain no route-policy discriminator; they record exact requested/configured model ids, exact Source attribution, ordered attempts, and the closed outcome set owned by §4.5's authoritative Turn-outcome copy matrix. `requested_model_changed` is derived from those exact ids and is never persisted. The schema mirrors the outcome set without reproducing its branches. A canceled in-flight attempt carries no fabricated Source failure. No separate mapping field, compatibility discriminator, or internal-version conversion state exists. || **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` | Keeps stable normalized provider ids for menu identity and add-time match suggestions, supports the three protocols, and pins the exact configured Source/model hop per invocation. Runtime performs no provider matching, and no vendor metadata chooses a saved protocol. |-| **FC-12** | `api.md` | 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, and user-authored deletion, the explicit backend Source-order PUT, exact route GET/PUT, mode, events/provenance, native-config import, OAuth, and Direct-mode responses. Source create returns exact `added_to` positions; Source cards use `adopted_by`. Every Source/inventory mutation mirrors §4.5's total matrix row-for-row, including unguarded writes that cannot change `id`, `origin`, or Routes and forced Source/model deletion that preserves survivor order. A discovered-model delete returns the API-only `source_model_managed_upstream`; no UI action or copy consumes it. OAuth-start rejects a duplicate native Source before adapter invocation. No saved `/test`, separate saved discovery, route policy, separate mapping, takeover, experimental-consent, 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, exact route GET/PUT, 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, 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` | Describes only the user-facing copy-only import of existing Claude, Codex, and OpenCode local configuration. Its action enum and one contract example/fixture per value mirror §6's authoritative Native-config import action matrix, including the `keep_native` default and the rejected/deferred `reauth` and `controlled_import` cases. Successful `keep_native` and `import` items run Add Source's one-time match and sole §4.2 placement policy, then report the same visible `added_to` positions. Originals are never modified or deleted, duplicate native selection fails before OAuth or partial commit, and it contains no Model Hub internal contract/data conversion. |-| **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. 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. |+| **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.** |The final set contains no `subscription_hub_experimental`, `experimental_consent_at`,per-source consent record, `consent_required`, `opencode_api_key_only`,@@ -857,26 +888,28 @@ per-source consent record, `consent_required`, `opencode_api_key_only`,route `policy`, `order_enrolled_by`, separate `mappings` field, `mapping_applied` event,`mapping` event reason, compatibilitydiscriminator, or internal contract-conversion transaction. I1 verifies the contract,-core, and shared-test absences; I2–I5 verify their owned runtime, UI, fixture, scenario,+core, and shared-test absences; I2–I5 and I7 verify their owned runtime, UI, fixture, scenario,and locale surfaces before release.-**Implementation and test landing checklist (complete before release).** The I1–I5 PRs+**Implementation and test landing checklist (complete before release).** The K5, K6, I1–I5, and I7 PRscollectively touch every applicable row and leave no downstream compatibility task:| 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 explicit Source order per backend and one explicit hops array per menu model, serializer completeness, fresh-install Gateway construction, and existing-install-with-no-Hub-state Direct onboarding. No policy state exists. |-| `core/handlers/model_hub/{service,resolver,classification,errors}.py` | One §4.3 stored-chain executor and one Add Source implementation of §4.2's placement policy; the latter chooses and persists each matched hop position before returning `added_to`. 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. Runtime never matches, places, or substitutes. A static-key `401` performs no retry; only refresh-capable credentials receive one bounded refresh. |-| `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 the complete four-row native-config action matrix with original files untouched. Every imported Source passes I1's canonical final-shape validator before commit; no import writer bypasses it with direct dataclass construction. |-| `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 matrix, including forced Source-delete and whole-Route replacement in the shared `{removed_hops, interrupted}` reporting family; provenance/events mirror the complete turn-outcome matrix including `canceled`; Direct-mode responses remain explicit. During I1–I5, 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. |+| `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 explicit Source order per backend and one explicit hops array per menu model, 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 stored-chain executor and one Add Source implementation of §4.2's placement policy; the latter chooses and persists each matched hop position before returning `added_to`. 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`: Add-time matching, inventory membership, new-Route validation, runnability, and invocation admit only `retired: false` rows; 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. Runtime never matches, places, substitutes, 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, existing-chain reorder, 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/{config,client,state,adapter}.py` | Exact stored-hop execution, three-protocol transport, credential refresh capability, pre-stream fallthrough, post-stream no replay with classified health, and local Gateway failures at any request phase excluded from Source state and fallback. Turn copy is selected from the authoritative outcome matrix after state persistence and live annotation of the same stored chain. |-| `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; every model row edits the exact stored hops and mappings runtime executes; backend groups consume `supply_status`; takeover derives from the chain; saved Source details exposes only guarded Refresh models; Direct groups expose reversible mode actions. No bottom-only “new” section, policy control, “not enabled” hint, latency/last-check copy, consent/experimental 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, consent, experimental, or mechanism-copy keys. 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 gate at current line 159 remains exact; the mirror-registry version gate at current line 236 and provenance version gate at current line 314 use terminal value **5**; round-trip/completeness fixtures use only final Source and route shapes. |-| `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 preservation across rediscovery, distinct add-only unsaved operations versus the sole guarded saved refresh, all-exit discovery cleanup, three protocols, observation-before-save, deterministic policy-chosen Add Source placement with the returned persisted position, every guarded-mutation row including Source deletion from all backend Source orders and routes with survivor order preserved, duplicate-native pre-adapter rejection, adoption, and absence of policy/enrollment/takeover/supplying sibling fields. |-| `tests/test_model_hub_{resolution,runtime,oauth,l3}.py` | Sole §4.3 stored-chain consumption, no runtime matching or substitution branch, exact effort membership, every credential-capability row, configured-order fallthrough, every turn-outcome/copy row, blocked `no_candidate` detail, `native_cli_unavailable`, engine loss before/during/after streaming with no Source mutation or replay, canceled provenance, vendor OAuth defaults, and exact diagnostic shapes. I1 moves the versioned contract/provenance fixtures in `test_model_hub_l3.py` to terminal version **5** on its same tested head; after I1 merges, I2 owns that whole file's runtime-behavior updates. |-| `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, exact configured-chain editing, one guarded saved refresh button, adopted/supply-status projection consumption, derived takeover versus exhausted rendering, reversible Direct mode, distinct Native copy, and no policy/not-enabled/latency/consent surface. I4 supplies a mechanical type-check gate that includes these test files despite `tsconfig.app.json` excluding them. |+| `core/handlers/model_hub/turn_gateway.py`, `vibe/model_hub_runtime/**` | Exact stored-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 stored 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; 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, policy control, “not enabled” hint, latency/last-check copy, consent/experimental 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, consent, experimental, 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. 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. 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, existing-chain reorder, 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 Add-time matching, inventory membership, new-Route 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 stored-chain consumption, no runtime 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 **5** 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 policy/not-enabled/latency/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. 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. |#### Sealed current-consumer findings — reviewed head `5cffd3fff7`@@ -1948,9 +1981,10 @@ a parallel branch outside those tables.### AC-34 — Make Source-model ownership and routes one total resource contract-**Owner ruling, 2026-08-09.** Source inventory is a subresource of one Source. A-`discovered` entry's existence is upstream-owned; a user may edit its declared-`reasoning_efforts`, but only user-authored entries can be created or deleted.+**Owner ruling, revised 2026-08-11.** Source inventory is a subresource of one Source.+A `discovered` entry is an upstream record whose user correction is persisted as+`retired: true`; a user may also edit its declared `reasoning_efforts`. User-authored+entries alone can be created, and their DELETE removes the row.**Acceptance.** Model creation, capability-list replacement, and user-authored deletionuse only the three `/api/models/sources/<source_id>/models` family routes registered in@@ -1958,15 +1992,549 @@ use only the three `/api/models/sources/<source_id>/models` family routes registby those request bodies. POST and PATCH cannot change an existing `id`, `origin`, orRoute, so their matrix rows are explicitly unguarded; DELETE reuses the registeredguarded Source envelope. Rediscovery of the same id continues to preserve the edited-`reasoning_efforts`, `display_name`, and `discovered_at` as one total merge rule.--A direct DELETE of `origin: "discovered"` returns-`source_model_managed_upstream`. The registry names the contract error and-`test_discovered_source_model_delete_is_rejected_as_upstream_managed` as its negative-route consumer and rejects the value from Model Hub UI/i18n files. No UI entry may exist-whose only possible result is this refusal. The generated same-run closure also proves-the retired parallel route literal is absent repo-wide and that no Source-model request-body repeats `source_id`; these are derived checks, not copied occurrence counts.+`reasoning_efforts`, `display_name`, `discovered_at`, and retirement tombstone as one+total merge rule. DELETE on a discovered row stages retirement and uses the same guard;+confirmed success retains the row and excludes it from supply. The generated same-run+closure also proves that no Source-model request body repeats `source_id`; this is a+derived check, not a copied occurrence count.++### AC-35 — Preserve the G-9 Source-order tombstone++**Acceptance.** For a fixture with at least two nonempty stored Routes, every successful+`PUT /api/models/agents/<backend>/sources` changes and re-echoes only+`sources.order`. Before/after Route documents are byte-identical, and the route exposes+no `force`, guarded `409`, `would_remove_hops`, or `would_interrupt` branch. The API+route table and §4.5 explicitly keep this write outside the exhaustive Source-mutation+matrix.++**Binding handoff (owner / files / activation).** After K4, #1312, and K6 merge, I7 owns+`core/handlers/model_hub/{service,rpc,request}.py`, `vibe/{ui_server,model_hub_client}.py`,+and `tests/test_model_hub_api.py` for the byte-before/after Route fixture. There is no+I4 write consumer. After that fixture freezes, I5 consumes it in+`tests/scenarios/model_hub/{catalog.yaml,test_model_hub_live_resolution_scenarios.py}`.++### AC-36 — Expose G-11 CLI installation presence per backend++**Acceptance.** Every AgentSupply API row includes one server-produced boolean+`cli_present`, including absent executables and Direct-mode backends. In a three-backend+fixture, the zero-installed state is mechanically equivalent to+`all(agent.cli_present is false)`. Changing login or process-readiness fixtures without+changing executable presence cannot change the boolean.++**Binding handoff (owner / files / activation).** After K4, #1312, and K6 merge, I7 owns+`core/handlers/model_hub/{service,rpc}.py`, `vibe/{ui_server,model_hub_client}.py`, and+`tests/test_model_hub_api.py` for CLI detection and the three-row AgentSupply fixture.+After K5 round 2 upgrades G-11 and that fixture freezes, I4's second increment owns+`ui/src/components/settings/models/{types.ts,SettingsModelsPage.tsx,modelRows.ts,modelRows.test.ts}`.+I5 then consumes the frozen backend/UI result in+`tests/scenarios/model_hub/{catalog.yaml,test_model_hub_live_resolution_scenarios.py}`.++### AC-37 — Persist G-3 discovered-model retirement++**Acceptance.** FC-03 and FC-12 are the single final-shape authorities: DELETE on a+discovered model stages `retired: true`, applies the same exact-hop and protected-supply+guards as manual deletion, and on confirmed success retains exactly one row with the+same `id`, `origin`, and edited metadata. Manual DELETE still removes the row. Refresh+fixtures in which the upstream both includes and omits that id retain `retired: true`;+matching, model-capability eligibility, new-Route validation, runnability, and+invocation fixtures never consume the retired row.++**Binding handoff (owner / files / activation).** After K4, #1312, and K6 merge, ownership of+`config/v2_config.py`, `core/handlers/model_hub/{service,resolver,rpc,request,errors}.py`,+`vibe/{ui_server,model_hub_client}.py`, and+`tests/test_model_hub_{config,api,resolution}.py` transfers from I1 to I7. Those files+own persistence, refresh/DELETE/guard behavior, and `retired: false` filtering in+Add-time matching, inventory membership, new-Route validation, runnability, and+invocation. After K5 round 2 upgrades G-3 and I7 freezes the guarded Source fixtures, I4's+second increment owns `ui/src/components/settings/models/{types.ts,SourceRow.tsx,SourceRowMenu.tsx,SourceRow.test.tsx,modelRows.ts,modelRows.test.ts}`.+I5 then consumes the result in+`tests/scenarios/model_hub/{catalog.yaml,test_model_hub_live_resolution_scenarios.py}`.++### AC-38 — Own the G-10 runtime installation state on the server++**Acceptance.** Runtime health validates against exactly the six registered decisions.+On a supported host, install persists `installing` before work with exactly+`installed_version: null`, `verified: false`, and `listening: null`; status reload and a+concurrent repeated install return that same state and start one job. One positive schema+fixture validates that shape, while separate negative fixtures make each of the three+fields contradictory and fail validation. Verified success+settles at `not_started` with null `error_key`; failure settles at `not_installed` with+`settings.models.install.fail.detail`. On process reconstruction, an orphaned+`installing` fixture either verifies an already-complete target to `not_started`, claims+one fresh job while staying `installing`, or settles at `not_installed` with that key;+it never remains ownerless. On an unsupported exact `host_platform`, the route performs+no download, returns `runtime_platform_unsupported`, and status remains+`not_installed`. Calls from `not_started`, `ok`, `degraded`, and `down` return the exact+current RuntimeDependency with HTTP 200, perform zero downloads, preserve the verified+binary, and neither start, stop, nor restart the process. Install has the same+authentication and CSRF negative fixtures as runtime start, while `/start` never+installs.++**Binding handoff (owner / files / activation).** After K4 and #1312 merge, I2 owns+`core/handlers/model_hub/turn_gateway.py`, `vibe/model_hub_runtime/**`, and+`tests/test_model_hub_runtime.py` for installer lifecycle, persisted lease/recovery, and+runtime no-op fixtures. After K6 also merges, I7 owns+`core/handlers/model_hub/{service,rpc,request,errors}.py`,+`vibe/{ui_server,model_hub_client}.py`, `tests/test_model_hub_config.py`, and+`tests/test_model_hub_api.py` for the schema, RPC/HTTP/client, CSRF, and error boundary+without editing I2 files. Once both producers+freeze success, failure, unsupported, concurrent, installed-no-op, and restart fixtures,+I4's current increment owns+`ui/src/components/settings/models/{types.ts,runtimeLifecycle.ts,SettingsModelsPage.tsx,RuntimeNotStartedAction.test.tsx}`+plus `ui/src/i18n/{en,zh}.json` and `vibe/i18n/{en,zh}.json`. I5 consumes the combined+result in `tests/scenarios/model_hub/{catalog.yaml,test_model_hub_live_resolution_scenarios.py}`.++### AC-39 — Apply G-13 order to existing chains and close G-26++**Acceptance.** Seed Routes containing repeated listed Sources and multiple unlisted+Sources, invoke reorder, and sort the original hops by §4.6's exact stable key. The+response equals that expected order for every Route; the multiset of exact+`(source_id, model_id)` pairs and every explicit model mapping are unchanged. A second+invocation is byte-identical. No matching, add/remove, guard, force, or interruption+path runs. The route is the registered existing-chain consumer of `sources.order`.++**Binding handoff (owner / files / activation).** After K4, #1312, and K6 merge, I7 owns+`core/handlers/model_hub/{service,rpc,request}.py`, `vibe/{ui_server,model_hub_client}.py`,+and `tests/test_model_hub_api.py` for the reorder route and before/after property fixture.+After K5 round 3 specifies G-32, K5 round 2 upgrades G-13/G-26, and that fixture+freezes, I4's second increment owns+`ui/src/components/settings/models/{types.ts,modelsApi.ts,ModelRoutePicker.tsx,reorder.ts,reorder.test.ts}`.+I5 then consumes it in+`tests/scenarios/model_hub/{catalog.yaml,test_model_hub_live_resolution_scenarios.py}`.++### AC-40 — Commit the G-14 native takeover transaction atomically++**Acceptance.** For `direct` → `hub` with a sanctioned recognized CLI login and no+native Source, one transaction creates exactly one backend-bound `native_cli` Source,+applies `placement-v1`, commits all accepted exact matches, changes mode, and returns an+AgentSupply that already contains those results. Injected failures at every commit seam+leave both mode and Source/Route state unchanged. Existing-native, absent-login,+unrecognized-login, non-transition, and repeated-request fixtures create zero Sources;+`cli_present` alone never satisfies recognition.++**Binding handoff (owner / files / activation).** After K4, #1312, and K6 merge, I7 owns+`config/v2_config.py`, `core/handlers/model_hub/{service,rpc,request}.py`,+`vibe/{ui_server,model_hub_client}.py`, and+`tests/test_model_hub_{config,api}.py` for recognition reuse and the atomic transaction.+After K5 round 2 upgrades G-14 and I7 freezes all five transition fixtures, I4's second+increment owns+`ui/src/components/settings/models/{types.ts,modelsApi.ts,BackendSupplyModeCard.tsx,AgentCard.test.tsx}`.+I5 then consumes them in+`tests/scenarios/model_hub/{catalog.yaml,test_model_hub_live_resolution_scenarios.py}`.++### AC-41 — Close the G-19 post-commit cancellation boundary++**Acceptance.** AC-26 and I1 continue to own every pre-commit cancellation cleanup+fixture. For cancellation after the durable Source commit, the server exposes no abort+branch: the Source, accepted placements, and AgentSupply state complete normally and+are coherent on the next read even when the response is never received. The fixture+contains neither Source deletion nor committed-credential revocation after that point.++**Binding handoff (owner / files / activation).** After K4, #1312, and K6 merge, I7 owns+`core/handlers/model_hub/{service,rpc,request}.py`, `vibe/{ui_server,model_hub_client}.py`,+and `tests/test_model_hub_api.py` for cancellation ownership, commit-boundary faults,+and coherent readback. After K5 round 2 upgrades G-19 and I7 freezes both boundary fixtures,+I4's second increment owns+`ui/src/components/settings/models/{types.ts,modelsApi.ts,AddApiKeyDialog.tsx,asyncLifetime.ts,asyncLifetime.test.ts}`.+I5 then consumes them in+`tests/scenarios/model_hub/{catalog.yaml,test_model_hub_live_resolution_scenarios.py}`.++### AC-42 — Reload G-20 Source adoption facts++**Acceptance.** Every Source returned by list, detail/mutation, API-key create, and OAuth+create carries `adopted_by` with the schema's exact item shape. After process restart,+the Source list projection equals the complete set of persisted `(backend, menu_model)`+references to that Source, uniquely sorted by backend then menu model, independent of+hop health and without a client chain walk.+In creation responses, top-level `adopted_by` is byte-equal to+`source.adopted_by`.++**Binding handoff (owner / files / activation).** After K4, #1312, and K6 merge, I7 owns+`core/handlers/model_hub/{service,rpc}.py`, `vibe/{ui_server,model_hub_client}.py`, and+`tests/test_model_hub_api.py` for Source read assembly and sorted serializer fixtures.+After K5 round 2 upgrades G-20 and those fixtures freeze, I4's second increment owns+`ui/src/components/settings/models/{types.ts,SourceRow.tsx,SourceRow.test.tsx,AdoptionNote.tsx,AdoptionNote.test.tsx}`.+I5 then consumes them in+`tests/scenarios/model_hub/{catalog.yaml,test_model_hub_live_resolution_scenarios.py}`.++### AC-43 — Derive G-24 host support from the server platform++**Acceptance.** Every runtime API payload includes the server-detected+`host_platform`. Installation support is true if and only if that exact string appears+in `manifest.assets[].platform`; changing only the browser user agent or client platform+cannot change it. The unsupported-host install fixture performs no asset request.++**Binding handoff (owner / files / activation).** After K4 and #1312 merge, I2 owns+`vibe/model_hub_runtime/**` and `tests/test_model_hub_runtime.py` for host detection and+the manifest producer. After K6 also merges, I7 owns+`core/handlers/model_hub/{service,rpc,request,errors}.py`,+`vibe/{ui_server,model_hub_client}.py`, and `tests/test_model_hub_api.py` for the API+projection and exact 422. Once both supported/unsupported fixtures freeze, I4's current+increment owns+`ui/src/components/settings/models/{types.ts,runtimeLifecycle.ts,SettingsModelsPage.tsx,RuntimeNotStartedAction.test.tsx}`+plus `ui/src/i18n/{en,zh}.json` and `vibe/i18n/{en,zh}.json`. I5 consumes the combined+result in `tests/scenarios/model_hub/{catalog.yaml,test_model_hub_live_resolution_scenarios.py}`.++### AC-44 — Distinguish G-25 all-stale Routes from empty Routes++**Acceptance.** Every `model_supply` row includes `has_runnable_hop`, and its value+equals `any(hop.runnable for hop in the complete exact AgentChain)`. A nonempty fixture+whose every hop is stale yields `{chain_length: N, has_runnable_hop: false}` with+`N > 0`; an empty fixture yields `{chain_length: 0, has_runnable_hop: false}`. No+consumer infers the boolean from length. The schema accepts the empty/false pair and+rejects `{chain_length: 0, has_runnable_hop: true}`; producer and API fixtures cover+both cells.++**Binding handoff (owner / files / activation).** After K4, #1312, and K6 merge, I7 owns+`core/handlers/model_hub/{service,rpc}.py`, `vibe/{ui_server,model_hub_client}.py`, and+`tests/test_model_hub_api.py` for exact-chain annotation and live/all-stale/empty+AgentSupply fixtures. After K5 round 2 upgrades G-25 and those fixtures freeze, I4's second+increment owns+`ui/src/components/settings/models/{types.ts,modelRows.ts,modelRows.test.ts,sufficiency.ts,sufficiency.test.ts}`.+I5 then consumes them in+`tests/scenarios/model_hub/{catalog.yaml,test_model_hub_live_resolution_scenarios.py}`.++### AC-45 — Define the complete G-27 SourceCreate request++**Acceptance.** `source-create.schema.json` rejects every property outside its six+registered fields, requires `vendor` and nonempty write-only `key`, and accepts optional+display, endpoint, full three-value probe order, and client nonce. Contract examples+validate. Create responses and logs contain no plaintext key, and request fixtures+cannot submit server-owned identity, protocol conclusion, inventory, health, usage,+custody, or timestamp fields.++**Binding handoff (owner / files / activation).** After K4, #1312, and K6 merge, I7 owns+`core/handlers/model_hub/{service,rpc,request}.py`, `vibe/{ui_server,model_hub_client}.py`,+and `tests/test_model_hub_api.py` for request validation and provisioning boundaries.+After K5 round 2 upgrades G-27 and I7 freezes valid, empty-inventory, and rejected-body+fixtures, I4's second increment owns+`ui/src/components/settings/models/{types.ts,modelsApi.ts,AddApiKeyDialog.tsx,dialogFields.tsx,dialogFields.test.tsx}`.+I5 then consumes them in+`tests/scenarios/model_hub/{catalog.yaml,test_model_hub_live_resolution_scenarios.py}`.++### AC-46 — Bind and number every G-28 guarded mutation plan++**Acceptance.** Every `would_remove_hops` and `removed_hops` item includes one-based+`position` in its named pre-mutation Route. Cross-Route output sorts by backend, menu+model, then position. For the same planned mutation, refusal and confirmed success+report byte-identical RouteHopRef arrays even though the latter commits the cascade.+Every refusal validates against `guard-refusal.schema.json`, has a nonempty current+plan, and pairs its lead error with the corresponding nonempty evidence array:+route/source-model errors require `would_remove_hops`, while `source_last_supplier`+requires `would_interrupt`. Positive fixtures cover all three relations; negative+fixtures keep the other array nonempty while leaving the required array empty and fail+schema validation. Both plan arrays are sets: a structurally duplicate `RouteHopRef` or+`SupplyGap` item fails schema validation, and positive plus duplicate-negative fixtures+cover each array. `would_interrupt` has one canonical producer order: ascending+`(backend, model_id)`, with every nested `agents` array ascending by stable Agent id.+Producer fixtures permute both input levels and assert byte-identical ordered output.+The fixture covers every row of the force/plan/echo totality matrix: unforced empty+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+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,+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`.++**Binding handoff (owner / files / activation).** K4 freezes+`docs/plans/model-hub-contracts/{guard-refusal.schema.json,api.md,mirror-registry.json}`.+After K4, #1312, and K6 merge, I7 owns the sole shared guard planner and exact-array comparison in+`core/handlers/model_hub/service.py`; transport-only changes in+`core/handlers/model_hub/{rpc,request,errors}.py` and+`vibe/{ui_server,model_hub_client}.py`; and every totality/concurrent fixture in+`tests/test_model_hub_api.py`. K4's negative schema-relation fixture lives in+`tests/test_model_hub_config.py`; K6 never owns that test, and I7 consumes and extends it+only after all three prerequisites merge.+After K5 round 3 specifies G-32, K5 round 2 upgrades G-28, and I7 freezes those+fixtures, I4's second increment owns+`ui/src/components/settings/models/{types.ts,modelsApi.ts,ModelRoutePicker.tsx,ModelRoutePicker.test.tsx}`+for numbered rows, ordinary noninterrupting removal, interruption-only two-array plan+echo, and replacement by a newly refused plan.+I4's current increment owns none of this confirmation path. I5 then consumes the frozen result in+`tests/scenarios/model_hub/{catalog.yaml,test_model_hub_live_resolution_scenarios.py}`.++### AC-47 — Reconcile G-29 lost Source-create responses++**Acceptance.** When SourceCreate supplies a valid `client_nonce`, the server atomically+reserves that unique value in process before observation or credential work and stores+no durable claim, digest, terminal envelope, or plaintext credential with it. The+committed Source alone persists and+echoes the nonce unchanged so list reads expose exactly one match. After a lost response,+the client reads Sources before retrying; a match terminates reconciliation and a miss+permits the same-nonce state-machine action. One table-driven+fixture covers every state/action cell. `nonce.in_flight` returns HTTP 409+`source_create_in_progress` before observation or provisioning. `nonce.released` first+settles AC-26 cleanup, then the same-nonce retry atomically reserves the value and performs+exactly one fresh attempt. `nonce.committed` returns HTTP 409 `source_nonce_conflict`+without upstream work or a replay promise; the client then reads Sources and recognizes+the committed row by exact nonce. Source deletion releases the nonce and makes it+claimable again; AC-51 owns the positive fresh-create boundary after that deletion.+After a simulated lost response, in-progress waits/retries, committed conflict reads,+and a released/list-miss retry all terminate without a separate endpoint.+Process termination ends the work and its in-memory reservation. Reconstruction+reconciles only AC-26 durable pending-revocation material; the next same-nonce attempt is+fresh and no ownerless claim is reconstructed.+Omitting the nonce preserves existing create behavior.++**Binding handoff (owner / files / activation).** After K4, #1312, and K6 merge, I7 owns+`config/v2_config.py`, `core/handlers/model_hub/{service,rpc,request,errors}.py`,+`vibe/{ui_server,model_hub_client}.py`, and+`tests/test_model_hub_{config,api}.py` for committed-column validation, process-local+reservation, cleanup/restart, Source-delete release, and the complete state/action AC-47+fixture. After K5 round 2 upgrades G-29 and I7 freezes in-progress conflict, committed conflict+plus list lookup, released reclaim, cleanup/recovery, Source-delete release, and+lost-response fixtures, I4's second increment+owns `ui/src/components/settings/models/{types.ts,modelsApi.ts,AddApiKeyDialog.tsx,asyncLifetime.ts,asyncLifetime.test.ts}`.+I5 then consumes them in+`tests/scenarios/model_hub/{catalog.yaml,test_model_hub_live_resolution_scenarios.py}`.++### AC-48 — Reconcile G-30 lost OAuth-start responses++**Acceptance.** When OAuth start supplies `client_nonce`, the server atomically claims+the exact `(client_nonce, vendor, channel)` tuple before provider work and every flow+response echoes it. One table-driven fixture covers all three states and every exit:+released claims start exactly once, including after cleanup from a provider-start+failure/task cancellation before a flow exists; an in-flight same-tuple retry coalesces+to the same pending terminal result without a second provider invocation; and committed+retries return the same `flow_id`, state, and presentation. Provider success atomically+converts the claim to a flow with a non-null date-time `expires_at`, and every later+response for that flow preserves the same bounded deadline. An ordinary or+presentation-only flow without a nonce retains the existing nullable expiry branch.+Explicitly canceling a nonce-bearing committed flow+cancels provider work but retains that same bounded terminal flow as `state: "cancelled"`+until its existing `expires_at`; a same-tuple retry inside that window returns the+canceled flow with zero provider starts. Clocked expiry releases the tuple, and the first+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: 5` 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+omitted. These three cells mechanically prove both the nonce implication and preservation+of the pre-existing non-nonce branch.++**Binding handoff (owner / files / activation).** After K4 and #1312 merge, I3 owns+`core/handlers/model_hub/oauth.py`, `tests/test_model_hub_oauth.py`,+`tests/scenarios/auth_setup/catalog.yaml`, and+`tests/scenarios/auth_setup/test_auth_setup_scenarios.py`. AUTH-SETUP-210 blocks the+first provider call, loses that caller's response, overlaps a same-nonce retry, receives+the same terminal flow/provider through both callers, and proves provider start exactly+once. The OAuth unit table additionally covers pending-start cleanup/release, explicit+cancel followed by same-tuple canceled replay with zero provider calls, existing-expiry+release followed by one fresh provider start, different-tuple isolation, and no-nonce+forget. After K6 also merges, I7 owns only+`core/handlers/model_hub/{service,rpc,request,errors}.py`,+`vibe/{ui_server,model_hub_client}.py`, and `tests/test_model_hub_api.py` for the service+and API envelope, including the nonce-aware cancel branch and clocked expiry boundary.+After K5 round 2 upgrades G-30 and I3/I7 freeze same-tuple, different-tuple,+omitted-nonce, released/in-flight/committed, canceled-replay/expiry, and concurrent+lost-response fixtures, I4's second increment owns+`ui/src/components/settings/models/{types.ts,modelsApi.ts,OAuthConnectDialog.tsx,oauthResult.test.ts}`.+I5 only consumes the completed flow in+`tests/scenarios/model_hub/{catalog.yaml,test_model_hub_native_oauth_scenarios.py}` after+all producer and UI fixtures settle.++### AC-49 — Withdraw the observation evidence expansion++**Acceptance.** Under the 2026-08-11 20:35 owner subtraction ruling,+`observation-result.schema.json` has `contract_version` plus exactly the established six result fields and rejects+an `evidence`, `request`, or `status` sibling. Model Hub contracts and implementation+lanes add no evidence producer, mirror vocabulary, or UI payload field; protocol and+discovery decisions continue to use the existing semantic result only.++**Binding handoff (owner / files / activation).** K4 freezes the absence in+`docs/plans/model-hub-contracts/{observation-result.schema.json,api.md,mirror-registry.json}`.+After K4 merges, K5 round 2 alone owns `docs/plans/model-hub-ui-spec.md` §1.5 and removes+its request/status slots under the 20:35 ruling; no backend or I4 implementation file is+activated by AC-49.++### AC-50 — Classify network failures without inventing persistent health++**Acceptance.** One table-driven fixture covers the Cartesian product of failure shape+(`shaped` explicit closed upstream classification versus unclassified `transport`) and+phase (`stream_started: false` versus `stream_started: true`). `stream_started` is false+until the first user-visible model-output byte and true from that byte onward; HTTP+status, headers, and other response bytes do not cross it. The existing+`network_failure.*_before_first_byte` and `network_failure.*_after_first_byte` decision+IDs retain their spelling but refer to this canonical model-output boundary. Both shaped+cells enter exactly their existing non-permanent Source classification and unchanged+recovery rule; phase changes only retry/replay behavior. Unclassified pre-output+connection failure retains Source/config bytes exactly, emits the redacted network+event, and creates one+Source-scoped in-memory `health: backoff` projection with+`reason: models.source.backoff.connection_failed`, a future `retry_at`, and the exact+bounded delays 1, 2, 4, 8, 16, then 30 seconds. Expiry makes the hop runnable; a later+first user-visible model-output byte from that same affected Source, Source+endpoint/credential replacement, or process reconstruction clears the streak. A+successful fallback from another Source is a negative fixture and does not clear it.+Before serialization, the API/read assembler captures one read time: a live backoff+must have `retry_at` strictly after that time, while an expired overlay is normalized to+the Source's underlying non-backoff health and runnability and is never emitted as stale+backoff. Clocked positive/expired fixtures cover this boundary in I7 API/service tests;+the contract fixture records the boundary because Draft-07 cannot compare a date-time to+the moving clock. While the deadline is live, the overlay applies only over an otherwise+healthy hop whose exact Source/model capability remains present. Concurrent cooldown,+`needs_action`, `error`, `source_missing`, or `model_unsupported` suppresses the overlay+and emits that blocker's established health/reason/retry facts; the four non-self-healing+rows roll up `interrupted`, so `waiting` cannot mask a durable blocker. The sole overlay+exception is the native-process row below. A nonempty process-available chain blocked only by+cooldown/backoff must validate as `waiting` and must fail validation as `interrupted`;+positive and negative schema fixtures cover that converse. If a `native_cli` process is+simultaneously unavailable, its actionable+`native_cli_unavailable` fact takes the single reason slot; `health: backoff` and the+future `retry_at` remain unchanged, `runnable` stays false, and the chain is+`interrupted`. Restoring the process reveals any still-live connection backoff.+Unclassified post-output interruption emits only the event: it writes no+Source/config state, creates no backoff, performs no replay, and does not change the+chain. Schema fixtures reject the removed persistent network/timeout cooldown keys,+reject backoff on Source state, and reject any backoff hop without false runnability,+one of the two precedence-valid closed reasons, and a date-time deadline. A ProbeResult+carrying `models.source.backoff.connection_failed` implies exactly `channel: hub`,+`reachable: false`, and `latency_ms: null`; native-channel and non-null-latency fixtures+fail. Contract version+stays 5 under the owner’s+pre-release semantic correction of 2026-08-11 19:44–19:56 and the blocker/Probe closure+of 2026-08-11 23:49.++**Binding handoff (owner / files / activation).** K4 freezes+`docs/plans/model-hub-contracts/{source,agent-chain,agent-supply,probe-result}.schema.json`,+`api.md`, and `mirror-registry.json`. After K4 and #1312 merge, the orchestrator dispatches K6+for one bounded round over `docs/plans/model-hub.md` §4.5's Turn-outcome segment and+`docs/plans/model-hub-contracts/{api.md,turn-provenance.schema.json,resolution-event.schema.json,mirror-registry.json}`.+K6 freezes G-34's exact outcome id, copy key, and payload shape plus any §4.5 gap row left+by #1312; it edits either schema only when that selected shape requires it and owns no+implementation or test file. After K4, #1312, and K6 merge, ownership transfers from+I1 to I7 for `core/handlers/model_hub/{service,resolver,classification,errors,events,rpc}.py`,+`modules/agents/model_hub.py`, `vibe/{ui_server,model_hub_client}.py`, and+`tests/test_model_hub_{api,resolution}.py`. For the Model Hub failure-callback seam only,+the same three-way activation transfers `modules/agents/base.py`, `modules/agents/claude_agent.py`,+`modules/agents/codex/{agent,event_handler}.py`,+`modules/agents/opencode/{agent,poll_loop}.py`, exact phase fixtures in+`tests/{test_claude_agent_sessions,test_codex_agent,test_opencode_server}.py`, and+mechanical signature consumers in+`tests/{test_claude_cli_path,test_multi_platform_runtime}.py` to I7. I7 alone owns the+native classifier/state decision, cross-backend raw-shape/phase handoff, live-backoff+executor/read projection, Source no-write assertions, same- versus other-Source reset,+clocked live/expired API assembly, the concurrent transition matrix for cooldown,+needs-action, error, missing Source, unsupported model, and native-process precedence,+the exact ProbeResult relation, and the event-only cell plus its K6-defined G-34+executor/provenance fixture;+no native callback may persist the old 30-second network cooldown.+I2 retains+`core/handlers/model_hub/turn_gateway.py`, `vibe/model_hub_runtime/**`,+`tests/test_model_hub_runtime.py`, and `tests/test_model_hub_l3.py`; it supplies the raw+shaped/transport and `stream_started` facts at the model-output boundary for the managed+Gateway but does not classify or+mutate Source/backoff state. Under the 2026-08-11 20:20 gate ruling as corrected through+the 21:58 PM ruling, the future contract assertions live alone in the adjacent strict-xfail test+`tests/test_model_hub_l3.py::test_probe_transport_failures_await_ac50_backoff_contract`;+the mixed chain/probe test remains active. I7's first mechanical action is to delete that+strict marker in the same commit that makes its `connection_failed` live-backoff and zero+Source/config-write assertions XPASS; no other I2-file+edit is authorized. After K5 round 2 registers the distinct short-backoff copy and I7+freezes all four cells plus same-Source reset, other-Source non-reset, clock, and cap+fixtures, I4's second increment owns+`ui/src/components/settings/models/{types.ts,modelsApi.ts,modelRows.ts,modelRows.test.ts,sufficiency.ts,sufficiency.test.ts}`+and both locale trees. I5 then consumes the frozen behavior in+`tests/scenarios/model_hub/{catalog.yaml,test_model_hub_live_resolution_scenarios.py}`.++### AC-51 — Make G-29 nonce release after Source deletion explicit++**Acceptance.** Nonce uniqueness exists only while a live-process reservation or live+Source owns the value. A positive fixture commits a nonce-bearing Source, deletes that+Source, reads the Source list and observes no matching nonce, then submits the same nonce+again. The server treats that request as a fresh create: it performs exactly one new+upstream attempt and commits exactly one new Source with a new server-issued id and the+same nonce. No tombstone, gone result, receipt, digest, replay, or deleted-Source+protection state exists. The supported UI client always performs the D-36 Source read+before a lost-response retry; a stale client that skips that read and recreates a deleted+Source is explicitly outside the single-user threat model. A restart fixture proves the+in-process reservation disappears, AC-26 pending-revocation material settles, and the+next same-nonce request is one fresh attempt; no durable claim collection is serialized.++**Binding handoff (owner / files / activation).** After K4, #1312, and K6 merge, I7 owns+`config/v2_config.py`, `core/handlers/model_hub/{service,rpc,request,errors}.py`,+`vibe/{ui_server,model_hub_client}.py`, and+`tests/test_model_hub_{config,api}.py` for live-only uniqueness, restart release,+Source-delete release, new-id recreation, and upstream-once fixtures. After K5 round 2 upgrades G-29 and I7 freezes+those fixtures, I4's second increment owns+`ui/src/components/settings/models/{types.ts,modelsApi.ts,AddApiKeyDialog.tsx,asyncLifetime.ts,asyncLifetime.test.ts}`+for the mandatory read-before-retry client branch. I5 then consumes the frozen behavior+in `tests/scenarios/model_hub/{catalog.yaml,test_model_hub_live_resolution_scenarios.py}`.++### AC-52 — Require acknowledgement before OAuth re-auth on either supply channel++**Acceptance.** `POST /api/models/sources/<id>/reauth` starts no OAuth adapter work+unless the request carries `{"acknowledge_irreversible": true}`. This is identical for+Hub OAuth and `native_cli` Sources: missing or false acknowledgement returns the existing+`reauth_confirmation_required` error before the adapter is called, and a true+acknowledgement permits exactly one ordinary re-auth start. The rule does not extend to+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: 5` 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`,+`vibe/{ui_server,model_hub_client}.py`, and `tests/test_model_hub_api.py` for the shared+pre-adapter acknowledgement gate and both-channel positive/negative route fixtures. At+the earlier K4 + #1312 edge, I3 owns `tests/scenarios/auth_setup/catalog.yaml` and+`tests/scenarios/auth_setup/test_auth_setup_scenarios.py` for AUTH-SETUP-109. The case+selects a Hub-held Source, proves missing and false acknowledgement return+`reauth_confirmation_required` before any adapter/provider call, proves true+acknowledgement starts exactly one Hub flow, and closes only after terminal status and the+repair read projection agree. `core/handlers/model_hub/oauth.py` remains downstream of+the I7 gate and requires no ownership transfer. I5 consumes the completed scenario but+does not edit either I3 file. Existing UI confirmation consumes the same request field;+this criterion creates no UI-spec or locale change. K4's narrow+`tests/test_model_hub_config.py` ledger assertion freezes the scenario id, both files,+journey, lane split, and activation edge before implementation starts.++### AC-53 — Make OAuth materialization-error route impact observable exactly once++**Acceptance.** OAuth status/submit implements all five rows of the authoritative+`oauth_terminal.*` matrix. A successful terminal re-auth response owns the complete+`interrupted_pairs` array and may return it empty. A local terminal materialization error+uses the standard error envelope and never returns `flow`: when acquisition-stage Source+mutation has already left one or more exact `(backend, model_id, agents)` supply gaps,+the envelope contains that exact nonempty `interrupted_pairs`; when no persisted+interruption exists, the member is absent rather than `[]`. The same materialization+error code may take either branch, so code identity alone cannot decide the payload.+Ordinary adapter failure/cancellation remains successful `{flow}` state settlement, and+every non-materialization error omits `interrupted_pairs`. The error member never aliases+the future-tense guard field `would_interrupt`, and no new field, error code, or contract+version is introduced.++A positive fixture drives native re-auth materialization failure after acquisition has+already stranded a sibling and asserts the exact nonempty report, standard error+envelope, absent `flow`, persisted Source state, and subsequent Source-list refetch. The+negative table drives the same materialization error with no gap, a materialization+failure before route impact, and an ordinary non-materialization error; all omit the+member. A success fixture proves re-auth still sends the complete array and accepts `[]`.++**Binding handoff (owner / files / activation).** After K4, #1312, and K6 merge, I7 owns+`core/handlers/model_hub/{service,errors}.py`, `vibe/{ui_server,model_hub_client}.py`, and+`tests/test_model_hub_api.py` for the sole materialization decision, exact error-envelope+transport, persisted-impact positive fixture, same-error/no-gap negative fixture, and+ordinary-error negative fixture. After K4 merges, K5 round 2 alone records E6 in+`docs/plans/model-hub-ui-spec.md`; it edits no contract or implementation file. After+that K5 round and the I7 payload fixtures freeze, I4's second increment owns+`ui/src/components/settings/models/{modelsApi.ts,OAuthConnectDialog.tsx,apiFailure.test.ts,oauthResult.test.ts}`+for exact optional error-member consumption and the Source-list refetch. I5 consumes the+settled behavior only after I7 and I4 finish; it owns no AC-53 producer. K4's contract+fixture in `tests/test_model_hub_config.py` freezes the five decision ids, D22 mirror,+presence/absence totality, and this lane/file/activation handoff.++### K4 open contract-gap registry++| Gap | Missing contract truth | Consumer | Activation edge |+| --- | --- | --- | --- |+| **G-34 — truncated stream with the same current hop** | §4.5 has no Turn-outcome row for a stream truncated after user-visible model output when the network policy writes no Source state and the same hop remains `current`. The current `streamed_fallback` behavior depends on the persistent cooldown that I7 must remove, so it cannot be treated as the future row. This entry records the absence only; it does not choose an outcome id, copy key, or payload shape. G-33 remains the K5/UI-owned OAuth device-code/helper presentation gap and never names this behavior. | K6 contract authority, then I7 executor/provenance implementation and its exact turn fixture | After K4 and #1312 merge and the §4.5 Turn-outcome matrix segment is unfrozen, the orchestrator dispatches K6 for its single registered-gap round; K6 must merge before I7 starts. **PM rulings: 2026-08-12 00:18 and 02:00.** |### Post-consolidation review ledger — sealed 2026-08-08@@ -1999,12 +2567,12 @@ architecture inputs to S-1, not sealed-ledger deferrals.| Finding (verbatim) | AC | Implementation landing point | Responsible lane || --- | --- | --- | --- || **Guard the saved Fetch models mutation**<br><br>When a user runs the newly specified “Fetch models” action from saved Source details and upstream discovery removes a referenced model, lines 185–191 say that operation replaces the discovered slice, but this exhaustive guard list covers refresh/recovery and manual deletion without covering saved discovery. Fresh evidence beyond the earlier inventory-shrink thread is that Fetch models is now a separate saved-Source mutation; unless it is explicitly defined as an alias of guarded refresh or given the same exact-hop and supply-gap handling, it can invalidate a Custom hop or the last Follow supplier without refusal, cascade confirmation, or stale-hop retention. | AC-26 | `core/handlers/model_hub/service.py`; final `api.md`; `tests/test_model_hub_api.py`; saved Source-details Fetch-models UI test | I1 (shape/guard) + I4 (action) + I5 (scenario) |-| **Include the required auth-setup scenarios**<br><br>When K3/K4 change the multi-step OAuth flows—vendor-specific defaults, duplicate-native rejection before adapter work, re-auth acknowledgement, polling, cancellation, and retry—the final landing checklist names only `tests/scenarios/model_hub/**` and the lower-level native OAuth harness. That can leave the repository's auth/setup catalog and its closed-loop user journey on the old flow even while all listed Model Hub tests pass; add or update the mandated `tests/scenarios/auth_setup/catalog.yaml` entry and `test_auth_setup_scenarios.py` case in this handoff.<br><br>AGENTS.md reference: [AGENTS.md:L253-L253](https://github.com/avibe-bot/avibe/blob/7984aabf4e1d9d541084c7078dba093f2832045d/AGENTS.md#L253-L253) | AC-23 + AC-25 | `tests/scenarios/auth_setup/catalog.yaml`; `tests/scenarios/auth_setup/test_auth_setup_scenarios.py` | I1 (final auth envelopes) + I3 (catalog/test) + I5 (integration gate) |+| **Include the required auth-setup scenarios**<br><br>When contract rounds change the multi-step OAuth flows—vendor-specific defaults, duplicate-native rejection before adapter work, re-auth acknowledgement, polling, cancellation, and retry—the final landing checklist names only `tests/scenarios/model_hub/**` and the lower-level native OAuth harness. That can leave the repository's auth/setup catalog and its closed-loop user journey on the old flow even while all listed Model Hub tests pass; add or update the mandated `tests/scenarios/auth_setup/catalog.yaml` entry and `test_auth_setup_scenarios.py` case in this handoff.<br><br>AGENTS.md reference: [AGENTS.md:L253-L253](https://github.com/avibe-bot/avibe/blob/7984aabf4e1d9d541084c7078dba093f2832045d/AGENTS.md#L253-L253) | AC-23 + AC-25 | `tests/scenarios/auth_setup/catalog.yaml`; `tests/scenarios/auth_setup/test_auth_setup_scenarios.py` | I1 (final auth envelopes) + I3 (catalog/test) + I5 (integration gate) || **Define protocol observation for OAuth-created Sources**<br><br>When a Claude/Codex native login or a Hub-held subscription OAuth flow completes, the resulting Source still requires a `protocol`, but the specified observation workflow covers only the API-key Add form and never defines how OAuth credentials are probed before commit. The current OAuth creation path uses `core/handlers/model_hub/service.py::_default_protocol(binding.vendor)`, which this rule explicitly forbids; removing that default leaves OAuth creation without a contract-valid value, while retaining it violates AC-27. Define response-backed observation and failure/credential-cleanup behavior for OAuth Sources, or make `protocol` conditional where native dispatch does not use it. | AC-23 + AC-27 | final `source.schema.json`, `oauth-flow.schema.json`, `probe-result.schema.json`, and `api.md`; `core/handlers/model_hub/{service,oauth,native_oauth,revocations}.py`; OAuth/API/scenario tests | I1 (final shape/API) + I3 (OAuth observation/cleanup) + I5 (scenario) || **Define discovery collisions with manual model IDs**<br><br>When a user manually adds model id `foo` and a later Fetch models result also contains `foo`, the preceding discovery rule says to preserve the manual entry while these lines require unique ids and say discovery creates a discovered entry. Without collision precedence, an implementation must either emit duplicate ids, fail the refresh, or overwrite the user's manual origin and edited capability metadata. Define a deterministic coalescing rule for manual/discovered collisions and cover it in the discovery fixtures. | AC-26 | final `source.schema.json`, `api.md`, and adapter interface; `core/handlers/model_hub/service.py`; API, adapter, Source-details UI, and scenario fixtures | I1 (shape/consumer) + I4 (result rendering) + I5 (scenario) |-| **Observe protocols before committing imported Sources**<br><br>When a user applies native-config import, this universal invariant conflicts with the retained import flow in §6: the current scanners derive `protocol` from vendor or local wire configuration (`core/handlers/model_hub/migration.py:180-220`, `285-306`, and `489-520`), and `_source_from_item` persists that value directly at lines 596-605 without obtaining an upstream response. K3 must therefore either preserve import while violating AC-27, or enforce AC-27 and prevent an imported Source from being created whenever the upstream is unavailable; FC-12/FC-13 define neither observation nor its failure/credential-cleanup behavior. Require response-backed observation during import, or explicitly scope and contract an exception.<br><br>AGENTS.md reference: [AGENTS.md:L145-L147](https://github.com/avibe-bot/avibe/blob/0ce001cfd62fdab736492c094914aa32a4991688/AGENTS.md#L145-L147) | AC-23 + AC-27 | final `migration-scan.schema.json`, `probe-result.schema.json`, and `api.md`; `core/handlers/model_hub/{migration,service,revocations}.py`; native-import API and scenario tests | I1 (final shape/API) + I3 (import observation/cleanup) + I5 (scenario) |+| **Observe protocols before committing imported Sources**<br><br>When a user applies native-config import, this universal invariant conflicts with the retained import flow in §6: the current scanners derive `protocol` from vendor or local wire configuration (`core/handlers/model_hub/migration.py:180-220`, `285-306`, and `489-520`), and `_source_from_item` persists that value directly at lines 596-605 without obtaining an upstream response. I1 must therefore either preserve import while violating AC-27, or enforce AC-27 and prevent an imported Source from being created whenever the upstream is unavailable; FC-12/FC-13 define neither observation nor its failure/credential-cleanup behavior. Require response-backed observation during import, or explicitly scope and contract an exception.<br><br>AGENTS.md reference: [AGENTS.md:L145-L147](https://github.com/avibe-bot/avibe/blob/0ce001cfd62fdab736492c094914aa32a4991688/AGENTS.md#L145-L147) | AC-23 + AC-27 | final `migration-scan.schema.json`, `probe-result.schema.json`, and `api.md`; `core/handlers/model_hub/{migration,service,revocations}.py`; native-import API and scenario tests | I1 (final shape/API) + I3 (import observation/cleanup) + I5 (scenario) || **Assign the actual auth-setup scenario file**<br><br>Fresh evidence after the recorded auth-scenario thread is the repository layout: repo-wide search finds the harness at `tests/scenarios/auth_setup/test_auth_setup_scenarios.py`, while this lane assigns the nonexistent `tests/test_auth_setup_scenarios.py`. Because I5 owns only the Model Hub scenario tree, the real closed-loop OAuth/setup test remains outside every active lane and can stay stale while the listed work completes; correct the path and ownership here and in the landing ledger.<br><br>AGENTS.md reference: [AGENTS.md:L253-L253](https://github.com/avibe-bot/avibe/blob/0309b62d167ede209bd429afc401144c93cc677a/AGENTS.md#L253-L253) | AC-23 + AC-25 | `tests/scenarios/auth_setup/catalog.yaml`; `tests/scenarios/auth_setup/test_auth_setup_scenarios.py` | I3 |-| **Assign the shared backend launch seam to an active lane**<br><br>When I1 replaces resolver/config shapes and I2 changes exact-hop transport, `modules/agents/model_hub.py` must change as well: it is the shared launch boundary for Claude, Codex, and OpenCode and currently imports and executes the runtime-matching resolver through `resolve_model_hub_turn`, `matching_sources`, and eligibility walks. None of the active I1–I5 scopes or landing rows owns this file; its only assignment is in the explicitly non-binding historical L3 table, so every active lane can complete while backend launches still use the retired routing model. Assign this shared seam and its backend call-site coverage to I1 or I2.<br><br>AGENTS.md reference: [AGENTS.md:L28-L30](https://github.com/avibe-bot/avibe/blob/0309b62d167ede209bd429afc401144c93cc677a/AGENTS.md#L28-L30) | AC-22 | `modules/agents/model_hub.py`; shared Claude/Codex/OpenCode launch call-site tests | I2 |+| **Assign the shared backend launch seam to an active lane**<br><br>**Closed by PM rulings 2026-08-11 22:37 and 2026-08-12 02:00.** Through #1312, I1 owns `modules/agents/model_hub.py`. After K4, #1312, and K6 merge, I7 exclusively owns that shared classification/state seam plus the narrow Model Hub failure callbacks in Claude, Codex, and OpenCode. Backend callbacks supply raw failure shape and exact `stream_started` phase, whose boundary is the first user-visible model-output byte; I7 removes the native 30-second persistent network cooldown and implements AC-50's live-backoff/event-only totality, consuming K6's G-34 Turn-outcome row for the post-output same-current-hop case. I2 retains only managed-Gateway raw phase facts. Exact cross-backend phase fixtures and mechanical signature consumers are named in the binding table and landing checklist, leaving one active owner and one three-way activation edge.<br><br>AGENTS.md reference: [AGENTS.md:L28-L30](https://github.com/avibe-bot/avibe/blob/0309b62d167ede209bd429afc401144c93cc677a/AGENTS.md#L28-L30) | AC-22 + AC-50 | `modules/agents/model_hub.py`; Model Hub callbacks in `modules/agents/{base,claude_agent}.py`, `modules/agents/codex/{agent,event_handler}.py`, `modules/agents/opencode/{agent,poll_loop}.py`; `tests/{test_claude_agent_sessions,test_codex_agent,test_opencode_server,test_claude_cli_path,test_multi_platform_runtime}.py` | I7 after K4 + #1312 + K6 merge || **Specify the add-time model matching algorithm**<br><br>**Closed by owner ruling 2026-08-09: `matching-v1`.** The Add Source path transcribes the former resolver semantics: Claude native aliases use discovered-only inventory and the deterministic `(version_tuple, date_or_zero, model_id)` maximum; OpenCode uses exact checked identifiers or a unique bare suffix; Codex and non-native sources use literal equality. The stored hop is the concrete upstream id and runtime never repeats matching. | AC-22 | `model-hub.md` §4.2 `matching-v1`, `opencode-overlay.md`, `api.md`, `core/handlers/model_hub/{service,resolver}.py`, and backend fixtures in `tests/test_model_hub_{api,resolution}.py` | I1 || **Assign the controller gate removal to I1**<br><br>Fresh evidence beyond the resolved default-off thread is that this landing row promises an available Models controller but assigns only handler files and `vibe/ui_server.py`; neither the active lane scopes nor the complete checklist includes `core/controller.py` or `tests/test_controller_model_hub_gate.py`. The current controller returns early when `VIBE_MODEL_HUB_ENABLED` is absent, and that test explicitly expects `model_hub_runtime is None`, so I1 can satisfy every named file/test while fresh installations still have no runtime. Add the controller and its gate test to I1's owned transition.<br><br>AGENTS.md reference: [AGENTS.md:L145-L147](https://github.com/avibe-bot/avibe/blob/0309b62d167ede209bd429afc401144c93cc677a/AGENTS.md#L145-L147) | AC-22 + AC-31 | `core/controller.py`; `tests/test_controller_model_hub_gate.py` | I1 |diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.mdindex e4035dc2a..8ee7c8238 100644--- a/docs/plans/model-hub.md+++ b/docs/plans/model-hub.md@@ -166,6 +166,10 @@ URL (api_key kind; prefilled for known vendors), a **model list** it can supplymodel entries), billing type (包月 | 按量 ¥), state (§4.5), and usage(subscription cycle % / monthly spend). Existing `last_discovered_at` records the lastsuccessful full inventory replacement; it is not a connectivity-check timestamp.+Every Source read also carries the server-derived+`adopted_by: [{backend, menu_model}]` projection of its persisted Route references.+That unique projection is sorted by backend then menu model. It is reloadable Source-+card data, not persisted Source state, and clients never reconstruct it from live chains.The Source workflow is complete at both entry points:@@ -198,21 +202,28 @@ The Source workflow is complete at both entry points:Source gets the same discovery behavior only through the refresh operation above;there is no parallel saved discovery route. Discovery uses the observed protocoladapter, replaces only the discovered slice, preserves manual entries, and renders- added, removed, unchanged, and failed results. Rediscovering an unchanged model id preserves its edited- `reasoning_efforts`, `display_name`, and `discovered_at`; only an id absent from the- new upstream list leaves the discovered slice. Unsaved Add Source discovery applies+ added, removed, unchanged, and failed results. Rediscovering an unchanged model id+ preserves its edited `reasoning_efforts`, `display_name`, `discovered_at`, and+ `retired` value. A non-retired discovered id absent from the new upstream list leaves+ the discovered slice; a retired row is the exception and remains a persistent+ tombstone whether the id is present or absent upstream. Unsaved Add Source discovery appliesthe same transient credential rule as connectivity observation: success, failure,timeout, and cancellation all revoke the provisioned ref, and a revoke failure entersdurable pending-revocation reconciliation before the operation settles.The saved Source surface may render freshness only as “Model list updated at …” /「型号列表更新于…」 from `last_discovered_at`. It carries no latency or “last checked”field or copy.-- **Model inventory and manual entries.** A `discovered` entry's existence is an- upstream fact, not a user decision; creating and deleting inventory entries therefore- applies only to entries the user wrote. Model `id` is unique within a Source. Every+- **Model inventory and manual entries.** Model `id` is unique within a Source. Everymodel-list item has- `{id, origin: "discovered" | "manual", reasoning_efforts: string[]}`; discovery+ `{id, origin: "discovered" | "manual", reasoning_efforts: string[], retired?:+ boolean}`; discoverycreates `origin: "discovered"`, while a user-created entry uses `origin: "manual"`.+ Omitted `retired` means false, and only a discovered entry may carry true. A retired+ row remains readable but is excluded from add-time matching, model-capability+ eligibility, new Route validation, live runnability, and invocation. DELETE on a+ discovered entry stages `retired: true`; DELETE on a manual entry removes the row.+ Both use §4.5's exact-hop and protected-supply guards, and no refresh automatically+ clears retirement.`reasoning_efforts` is required and may be empty. It declares the exact reasoningeffort values that the upstream model supports; it does not select one value. Anempty list declares none, and no entry receives a default, selected value, or@@ -225,13 +236,94 @@ The Source workflow is complete at both entry points:`PATCH /api/models/sources/<source_id>/models/<model_id>` mutation with`{reasoning_efforts}`; the adapter validates the submitted listand re-echoes the canonical stored value as `{source: Source}`. Editing the list never- changes `id`, `origin`, or a route chain. Model creation and deletion use the same- Source-model subresource; deleting a discovered entry is rejected at the API boundary- with `source_model_managed_upstream`. This all-inventory editing scope is an+ changes `id`, `origin`, or a route chain. Model creation, retirement, and manual+ deletion use the same Source-model subresource. This all-inventory editing scope is anowner-vetoable orchestratorruling dated 2026-08-08: discovery endpoints commonly return only ids, so adiscovered-only immutable list would leave the capability permanently undeclarable.+**Source-create boundary.** `source-create.schema.json` is the complete API-key create+request: `vendor` and transient `key`, plus optional `display_name`, `base_url`, probe-+only `protocol_order`, and client-generated `client_nonce`. Source identity, protocol+evidence, discovered inventory, health, usage, custody metadata, and timestamps remain+server-owned. When supplied, `client_nonce` is unique among live Sources and live-process+create reservations. The server reserves it atomically in process before observation or+credential work and persists `Source.client_nonce` unchanged only on commit, so a client+that loses the response can identify the committed row on the next Source list read.+There is no durable pre-create claim record, and neither representation stores a request+digest, terminal envelope, or plaintext credential. Pre-commit failure or+cancellation releases it only after AC-26 retained-material settlement. On restart an+in-flight create and its process-local reservation no longer exist; pending revocation+is reconciled before a retry begins fresh. Source deletion releases the nonce. A lost-response client+must read Sources before retrying; after that read observes no live nonce owner, a+same-nonce request is a fresh create, including after deletion. It is not Source identity+or a routing input.++**Source-create nonce state machine (authoritative and exhaustive; simplified by owner+subtraction ruling 2026-08-11 20:35, superseding the 19:10/19:42 receipt design).** After+a lost response the client reads Sources before retrying the same nonce. An exact match+reconciles the Source; a list miss permits a fresh retry. An in-progress conflict means+wait and retry; a committed conflict means repeat the Source read and select the exact+`client_nonce` match. Malformed request fields retain shared request-validation behavior.++| Decision | Live condition | Retry relation | Server action and HTTP/API result | Upstream work | First consumer |+| --- | --- | --- | --- | --- | --- |+| `nonce.in_flight` | this process holds the nonce reservation for unfinished create work | same nonce with any otherwise-valid request | retain reservation; HTTP 409 `source_create_in_progress` | none | Add Source wait/retry loop and concurrent-create fixture |+| `nonce.released` | no live-process reservation and no live Source owns the nonce, including after restart | same nonce with any otherwise-valid request | atomically reserve the nonce in process and proceed as a fresh create | exactly one new attempt owned by the reservation | create retry loop, AC-26 cleanup/recovery, restart, and Source-delete tests |+| `nonce.committed` | one live Source carries the nonce | same nonce with any otherwise-valid request | HTTP 409 `source_nonce_conflict`; client list read finds exactly one Source with that nonce | none | D-36 list reconciliation and committed-conflict fixture |++There is no committed replay promise: ordinary Source reads, not a stored terminal+envelope, reconcile the rare lost-response path. `released` is absence, not a tombstone+row; Source deletion makes the nonce claimable again, and a same-nonce create after the+required list miss is definitionally new. A stale client that skips the D-36 read can+recreate a deleted Source and is outside the single supported UI client's threat model.+These rules add no endpoint, receipt, digest, or server-side response snapshot.++**OAuth-start nonce state machine (authoritative and exhaustive; owner ruling+2026-08-11 19:42).** The key is the exact `(client_nonce, vendor, channel)` tuple and is+claimed before provider work. A different tuple never resolves to this claim or flow.+Every flow created from a nonce-bearing request has a non-null date-time `expires_at`+from its first response through every terminal replay, which bounds both reconciliation+and retained cancellation. A flow without a nonce keeps the existing nullable expiry+branch for ordinary or presentation-only lifetime handling.++| Decision | Tuple condition | Server action and HTTP/API result | Provider starts | First consumer |+| --- | --- | --- | --- | --- |+| `oauth_nonce.released` | no claim or unexpired flow exists, including after pending-start failure/task-cancellation cleanup or after a retained canceled flow reaches its existing `expires_at` | atomically claim, start once, and make all coalesced callers await the same terminal result | exactly one under the new claim | I3 OAuth registry, cleanup-release fixture, and clocked expiry/restart fixture |+| `oauth_nonce.in_flight` | one provider start owns the claim but has not produced a flow | coalesce the exact-tuple retry with that pending start and return its same terminal result | none for the retry | AUTH-SETUP-210 blocked-first-call/concurrent-retry fixture |+| `oauth_nonce.committed` | provider success atomically converted the claim into one unexpired `OAuthFlow`, including one explicitly canceled afterward | return the same `flow_id`, current state, presentation, and echoed nonce; a canceled retry returns the retained `state: "cancelled"` flow | none | OAuth API idempotency and canceled-retry/provider-zero fixtures |++A shared provider-start failure or task cancellation before a flow exists settles+cleanup and releases the claim; success creates the flow atomically with no claim gap.+Explicitly canceling a nonce-bearing committed flow cancels provider work but retains+that same bounded terminal flow until its existing expiry, so a delayed exact-tuple+retry cannot reverse the user's cancellation. Expiry releases the tuple and makes a+later same-tuple request a fresh start. Canceling a flow without a nonce forgets it. A+new user action uses a new nonce. Source-create and OAuth-start correlation therefore+share D-36's rule: reconciliation is possible only when the client held the subject+correlation before sending.++**OAuth terminal response and materialization-error matrix (authoritative and exhaustive;+PM ruling 2026-08-12 01:28).** This matrix governs status/submit settlement.+`interrupted_pairs` uses the existing `SupplyGap` shape and reports a persisted effect+that already happened; it is never a refusal plan and never aliases `would_interrupt`.++| Decision | Flow/service condition | HTTP/API result | `interrupted_pairs` | First consumer |+| --- | --- | --- | --- | --- |+| `oauth_terminal.flow_only` | flow is non-terminal, or the adapter terminal is `failed` or `cancelled` without a local materialization error | successful `{flow}` | absent | OAuth poll/submit state machine |+| `oauth_terminal.create_success` | terminal create succeeds and its Source materializes | `{flow, source, added_to, adopted_by}` | absent | Add Subscription completion |+| `oauth_terminal.reauth_success` | terminal re-auth succeeds and its existing Source materializes | `{flow, source, recovered, interrupted_pairs}` | present as the complete report; may be empty | repair completion UI |+| `oauth_terminal.materialization_interrupted` | local terminal materialization fails after an acquisition-stage Source mutation has already left at least one sibling `(backend, model_id)` without supply | standard error envelope with the existing materialization error, no `flow`, and the exact nonempty report | present and nonempty | re-auth failure gap report and Source-list refetch |+| `oauth_terminal.materialization_plain_error` | local terminal materialization fails before any such interruption, or its exact report is empty | standard error envelope with the existing materialization error and no `flow` | absent, never an empty placeholder | ordinary OAuth failure rendering and Source-list refetch |++The same materialization error code can enter either error row; the deciding fact is the+persisted acquisition-stage route impact, not the error name. In particular, native+re-auth discovery failure after the Source has been cleared and marked unavailable+enters `oauth_terminal.materialization_interrupted` only when the computed report is+nonempty. Create materialization and re-auth failures with no stranded sibling enter the+plain-error row. No later Source read can reconstruct the historical report, so the+error envelope carries it exactly once.+**Protocol observation (owner ruling 2026-08-09, superseding AC-27's 2026-08-07manual-choice ruling).** Every stored `protocol` is traceable to a real response fromthat upstream before Save. Avibe never infers the value from vendor name or Base URL;@@ -315,6 +407,12 @@ restart, health change, catalog change, or turn never repeats matching. Users mathe persisted chains directly: add or remove a hop, move it, or edit its explicitupstream `model_id` mapping.+Cancellation of Source creation has one commit boundary. Before the durable Source+commit, AC-26's transient-reference cleanup and pending-revocation accounting complete+before cancellation settles. After the commit, cancellation only ends the caller's+wait: Source creation and accepted placement finish atomically, remain readable after+reload, and have no server-side abort or rollback branch.+**Add-time Source placement policy (sole authority; owner 2026-08-09 S-1).** The AddSource service owns one write-time rule that chooses deterministic positions for thenew Source and every accepted exact match. The same transaction writes those positions,@@ -337,6 +435,20 @@ No health score, latency, cost, usage, vendor label, creation timestamp, or lateinventory result reorders existing configuration. `created_at` remains ordinary Sourcemetadata for audit/display; routing and placement never read or mutate it.+The explicit `POST /api/models/agents/<backend>/chains/reorder` operation is the sole+post-creation consumer of the current Source-order sequence. It reorders existing hops+only, preserves every exact `(source_id, model_id)` member and mapping, and never reruns+matching. Its complete stable order is defined in §4.6. Because it cannot remove supply,+it has no guarded `409`, `force`, or interruption branch even when the first hop changes.++On `PATCH /api/models/agents/<backend>/mode`, a `direct` → `hub` transition also owns+one bounded adoption transaction. If the backend has a sanctioned, recognized CLI+login and no `native_cli` Source, that transaction creates the singleton native Source,+applies `placement-v1`, commits every accepted exact match, changes mode, and only then+assembles the returned AgentSupply. An existing native Source, an absent or+unrecognized login, or another mode transition creates nothing. Repetition cannot+create a second native Source.+**Current matching value (`matching-v1`).** Add Source uses the same observed-inventorymatching semantics that preceded the configured-chain freeze, then persists the concreteupstream id in the Route hop. It runs once, after connectivity, protocol, and inventory@@ -418,7 +530,7 @@ for hop in C, in stored order:if result is terminal_request_error: return FAILED_TERMINAL(result)if result is engine_down_at_any_request_phase: return FAILED_TERMINAL(engine_down)- persist_attributable_source_state(result)+ apply_attributable_failure_decision(result)if result.output_started: return FAILED_TERMINAL(result)if result is fallback_class: continuereturn FAILED_TERMINAL(result)@@ -444,15 +556,18 @@ value; otherwise pass `null`, with no approximation or downgrade.Parameter, protocol, and tool-compatibility failures are terminal without fallthrough.A local Gateway start, listener, or process loss at **any** request phase is terminal`engine_down`: it mutates no Source, does not replay output, and does not walk another-hop. Credential failures follow the authoritative matrix below. Before output starts,-explicit quota exhaustion, 429, transient 5xx, or attributable upstream network failure-persists its classified Source-global blocker and continues to the next configured hop.-After output starts, no failure is replayed; attributable Source state is still-persisted for the next turn.+hop. Credential failures follow the authoritative matrix below. The network-failure+matrix owns every upstream transport branch. While `stream_started` is false, shaped+quota/429/authentication/5xx results retain their existing classifier while an+unclassified connection failure creates only live short backoff. The fact flips only at+the first user-visible model-output byte, never at HTTP status, headers, or another+response byte. After it flips, a stream interruption creates only its existing redacted+event and never mutates Source health or creates backoff. No post-output failure is+replayed.The read projection is `C` with live annotations plus `current`, never a reconstructedprovider list. Takeover remains derived: the current hop is not `C[0]` and `C[0]` is-unavailable for a recoverable quota/cooldown reason. Recovery changes current execution+unavailable for a recoverable quota/cooldown or live connection-backoff reason. Recovery changes current executionposition on the next turn without changing `C`. Every switch is recorded for pullsurfaces; a successful handoff emits no conversation notice or setting.@@ -471,6 +586,66 @@ credential-failure branch.| `credential.account_classified` | classified `402/403` account result | any | no credential refresh; retain the adapter's existing source-global credential classification | `needs_action`; choose the remedy from both classification and credential capability: refresh-capable auth re-authorizes, a static key is replaced, balance is topped up, and a banned account goes to the vendor | before output, continue to the next runnable hop || `credential.request_nonfallback` | a non-fallback request-level failure | any | no credential refresh and no Source-global credential classification | no Source-health mutation; surface the request failure | terminal without fallback |+**Network-failure totality matrix (authoritative and exhaustive; owner ruling+2026-08-11 19:44–19:56).** “Shaped” means the adapter received an explicit, closed+machine classification such as quota exhaustion/429, an authentication-family result,+or 5xx. “Transport” means connection or stream failure without such a code. The phase is+the existing `stream_started` fact: false until the first user-visible model-output byte,+and true from that byte onward. HTTP status, headers, and other response bytes do not+start the model-output stream.++| Decision | Failure shape | Phase | Persisted Source judgment | Live backoff | Route/event effect |+| --- | --- | --- | --- | --- | --- |+| `network_failure.shaped_before_first_byte` | explicit closed code/classification | `stream_started: false`; before first user-visible model output | apply the existing non-permanent quota/rate/auth/server family and its unchanged recovery rule | none | before output, follow that family's existing retry/fallback rule and emit its existing redacted event |+| `network_failure.transport_before_first_byte` | no explicit code; connection failed | `stream_started: false`; before first user-visible model output | none; retain the prior Source state byte-for-byte | set Source-scoped in-memory connection backoff, then continue to the next runnable hop | emit redacted `network` event; no configuration mutation |+| `network_failure.shaped_after_first_byte` | explicit closed code/classification arrives only after model output began | `stream_started: true`; after first user-visible model output | apply that existing non-permanent family and its unchanged recovery rule | none | terminal, no replay; emit only the existing redacted event |+| `network_failure.transport_after_first_byte` | stream interrupted without explicit code | `stream_started: true`; after first user-visible model output | none; the successful connection/authentication/output evidence wins | none | terminal, no replay; emit only the existing redacted `network` event |++Connection backoff is live execution state, never Source/configuration state. For the+same Source, consecutive `transport_before_first_byte` decisions use delays+`1, 2, 4, 8, 16, 30, 30, ...` seconds. While the deadline is future, it overlays only+an otherwise `healthy` exact hop whose Source and configured model capability are still+present. That hop reads `health: backoff`, `runnable: false`, the deadline as `retry_at`,+and `reason: models.source.backoff.connection_failed`. Source cooldown,+`needs_action`, `error`, `source_missing`, or `model_unsupported` suppresses the live+overlay and keeps that durable/self-healing blocker's established health, reason, and+retry facts. The one process-layer exception is simultaneous `native_cli` unavailability:+its actionable `native_cli_unavailable` reason takes the single reason slot while the+backoff health and deadline remain visible and the chain is `interrupted`.+Deadline expiry makes the hop runnable again without a write. The first subsequent+user-visible model-output byte produced by that same affected Source clears both+deadline and streak automatically; successful fallback output from another Source does+not. Source endpoint/credential replacement and process reconstruction also clear them+because the state is in-memory and identity-specific. Before an API read is serialized,+the assembler captures one read time and normalizes an expired overlay to the Source's+underlying non-backoff health and runnability; a stale backoff deadline never crosses the+API boundary. The maximum is 30 seconds. This family never uses+`models.source.cooldown.*`, never writes `Source.state`, and never creates a permanent+health verdict.++**Live connection-backoff projection (authoritative and exhaustive; owner ruling+2026-08-11 19:44–19:56).** This table owns the one live health value that has no+persisted Source-state counterpart.++| Decision | Required live annotation | Persistence | First consumer |+| --- | --- | --- | --- |+| `backoff` | `runnable: false`, future `retry_at`, and `reason: models.source.backoff.connection_failed`; simultaneous native-process unavailability instead takes reason precedence as `native_cli_unavailable` without erasing health/deadline | in-memory only; never Source/configuration state | AgentChain and AgentSupply health reads |++**Live-backoff blocker-precedence totality (exhaustive; PM ruling+2026-08-11 23:49).** This is projection precedence, not a second health classifier.+An internal deadline may continue to age while a stronger fact suppresses its read+overlay.++| Underlying hop fact while the deadline is live | Backoff projection | Emitted hop facts | Fully blocked chain rollup |+| --- | --- | --- | --- |+| Source `healthy`, exact Source/model capability present, process available | apply | `backoff`, `connection_failed`, future deadline, not runnable | `waiting` when every hop is cooldown or this row |+| Source `cooldown` | suppress | existing cooldown health/reason/deadline, not runnable | `waiting` when every hop is cooldown or ordinary backoff |+| Source `needs_action` | suppress | existing `needs_action` health/reason and retry facts, not runnable | `interrupted` |+| Source `error` | suppress | existing `error` health/reason and retry facts, not runnable | `interrupted` |+| Source absent (`source_missing`) | suppress | existing missing-Source health, `source_missing`, and retry facts, not runnable | `interrupted` |+| Exact model capability absent (`model_unsupported`) | suppress | existing capability-missing health, `model_unsupported`, and retry facts, not runnable | `interrupted` |+| Source `healthy`, exact capability present, `native_cli` process unavailable | apply with the process-reason exception | `backoff`, `native_cli_unavailable`, the same future deadline, not runnable | `interrupted` |+The final mirror registry checks the closed (classification, credential capability) →`detail_key` → remedy relation in both directions. The resolver suite executes everyrow and fails any extra retry or unlisted remedy.@@ -483,7 +658,7 @@ connector color, recent switches, and usage; provenance remains a debug affordan**Takeover projection.** A configured route is in **takeover** exactly when its currenthop is not the first stored hop and that first hop is unavailable for a-self-healing quota/cooldown reason. This is computed from the resolved chain's current+self-healing quota/cooldown or live connection-backoff reason. This is computed from the resolved chain's currenthop and live runnability; it is never a stored boolean or a second routing field. Achain with no runnable hop is not takeover: it reaches §4.5's truthful `exhausted`terminal outcome and must not reuse takeover's visual semantics.@@ -566,7 +741,7 @@ Three classes, because the action owed by the user differs in each.| --- | --- | --- | --- || `active` | 使用中 | — | currently serving || `standby` | 备用 | — | healthy, but not currently serving any configured route |-| `cooldown` | 暂不可用 (gold) | **yes** | quota/rate/network; `retry_at` known; recovers unattended |+| `cooldown` | 暂不可用 (gold) | **yes** | shaped quota/rate/server result; persisted `retry_at` known; recovers unattended || `needs_action` | 需处理 (rose) | **no** | OAuth expired, balance exhausted, key revoked/banned — dead until the user acts || `error` | 异常 | **no** | unclassified failure — no `retry_at`, so nothing clears it unattended |@@ -574,6 +749,47 @@ Three classes, because the action owed by the user differs in each.row can offer **one tap to fix it** (re-auth, top up, replace key) instead of adead-end error string.+**Runtime dependency state matrix (authoritative and exhaustive; owner ruling+2026-08-11).** `host_platform` is detected on the Avibe server, never from the browser,+and installation is supported exactly when it equals one+`manifest.assets[].platform`. The install route and status reads mirror this closed+state set; prose cannot add another runtime health value.++| Decision | Meaning | Entry and exit rule | `status.error_key` |+| --- | --- | --- | --- |+| `ok` | verified runtime is listening and healthy | successful start or health recovery; a demanded loss exits to `down` | null |+| `degraded` | runtime is listening but its health check proves impaired service | current health evidence only; recovery exits to `ok`, loss exits to `down` | null |+| `down` | an installed runtime was demanded and failed or stopped | failed start or demanded process loss; a successful later start exits to `ok` | null |+| `not_installed` | no verified managed binary is installed | initial/unsupported state, or failed install; supported install enters `installing` | null initially/unsupported; `settings.models.install.fail.detail` after install failure |+| `installing` | one server-owned installation job is in progress | persisted before work begins with `installed_version: null`, `verified: false`, and `listening: null`; reload/repeat stays here; verified success exits to `not_started`, failure to `not_installed` | null |+| `not_started` | binary is installed and verified but intentionally idle | successful installation or pre-demand restart; explicit/runtime demand exits to `ok` or `down` | null |++`POST /api/models/runtime/install` is idempotent and owns the+`not_installed → installing → not_started | not_installed` transition. It fails before+download on an unsupported `host_platform`; a reload never translates `installing`+back to `not_installed`, and `/start` never performs installation. Calls from+`not_started`, `ok`, `degraded`, or `down` return the current RuntimeDependency as an+HTTP 200 no-op. They start no download, do not replace the verified binary, and never+start, stop, or restart the process; this installed-state no-op is evaluated before the+unsupported-host branch.++A service restart distinguishes persisted state from a live worker. Before runtime+endpoints become ready, an `installing` row with no worker in the reconstructed process+is reconciled atomically: a complete binary that verifies against the pinned manifest+settles at `not_started`; otherwise uncommitted staging is discarded and exactly one+fresh install job is claimed while health remains `installing`. If that recovery cannot+be claimed or scheduled, it settles at `not_installed` with+`settings.models.install.fail.detail`. A page reload therefore retains the live job,+while a process restart cannot preserve an ownerless transition forever.++**Runtime install refusal matrix (authoritative and exhaustive; owner ruling+2026-08-11).** Authentication and CSRF failures retain their shared HTTP contract; this+table owns the runtime-specific synchronous refusal branch.++| Decision | Entry condition | HTTP/API result | First consumer |+| --- | --- | --- | --- |+| `runtime_platform_unsupported` | exact `host_platform` has no equal `manifest.assets[].platform` | HTTP 422 normal failure envelope; no download; runtime remains `not_installed` with null `error_key` | install API client and boundary test |+**`error` is a blocker, not a third class** (07-29, review round 6). This tablefirst wrote its self-healing column as 「unknown」, and that word was the root of areal gap: `error` carries no `retry_at`, so nothing will clear it unattended, and the@@ -622,7 +838,7 @@ splits — on whether the user owes an action:| --- | --- | --- | --- || `ok` | 正常 | — | serving from the intended head of the chain || `degraded` | 降级 | — | serving via a fallback, and/or some sources in the chain are down |-| `waiting` | 暂时全部在冷却 | **yes** | nothing runnable right now, but every blocker is a cooldown — recovers unattended at the earliest `retry_at` |+| `waiting` | 暂时全部在冷却 | **yes** | nothing runnable right now, but every blocker is a persisted cooldown or live connection backoff — recovers unattended at the earliest `retry_at` || `interrupted` | 无可用来源 | **no** | nothing runnable and the stored chain is empty or at least one hop has a non-self-healing blocker: `needs_action`, `error`, `source_missing`, `model_unsupported`, or `native_cli_unavailable` |These four values are the **only backend-level supply-health wording**. The Gateway@@ -632,6 +848,13 @@ surface invents a parallel prose status. `takeover` is a separate display term fpersisted field. A mechanical mirror/locale guard keeps the four status labels and thetakeover label synchronized across both locale sets.+AgentSupply also carries two orthogonal read facts. `cli_present` is the server-+authoritative per-backend executable-presence boolean; false on every backend is the+complete zero-installed-backend state, and the field proves neither login nor process+readiness. Every `model_supply` row carries `has_runnable_hop`, computed with §4.3's+exact-chain live predicate. Thus `chain_length > 0 && !has_runnable_hop` is an all-stale+Route, while `chain_length == 0 && !has_runnable_hop` is structurally empty.+`interrupted` is the honest name for the state v1 could not express: the sourcelist or configured chain can look populated, yet *this* Agent has nothing left to call. The UI shows「当前无可用来源」 with a cause breakdown and exactly two exits — fix the@@ -640,7 +863,8 @@ detail/remedy copy for restoring the sanctioned local CLI; it is never presentedupstream Source cooldown.`waiting` exists to keep the surfacing rule below consistent. An agent whose-sources are *all* mid-cooldown has nothing runnable, but nothing is owed either —+sources are *all* in persisted cooldown or live connection backoff has nothing runnable,+but nothing is owed either —it heals itself in minutes. Collapsing that into `interrupted` would tell the user togo fix a problem that resolves before they finish reading the sentence, which isexactly what the self-healing tier is supposed to prevent. The Turn-outcome copy matrix@@ -663,7 +887,8 @@ rollup stays what its name says. One taxonomy, two grains, and only one definitiThe predicate itself is stated **once, here**, and every contract that carries eithergrain points back at this table rather than restating it: `interrupted` when the chainis empty **or at least one blocker needs the user**, `waiting` only when every blocker-is a cooldown. The asymmetry is deliberate and load-bearing — `interrupted` is the+is a persisted cooldown or live connection backoff. The asymmetry is deliberate and+load-bearing — `interrupted` is theOR-branch, `waiting` the AND-branch, so a chain holding one cooling source and onerevoked key is `interrupted`. Reading it as "every member needs the user" leaves thatmixed chain matching neither value and, worse, hides the action the user is owed for@@ -847,18 +1072,23 @@ Exact-hop referential integrity is a separate guard from the supply-gap calculatA non-forced Source DELETE refuses whenever any configured chain names that Source, evenwhen a later hop still supplies the menu model, and returns `source_in_route_chain`plus ordered `would_remove_hops` entries naming each `(backend, menu_model,-source_id, model_id)` reference. `force=true` is an explicit cascade confirmation:+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 everybackend route, while the identity and relative order of all surviving hops remainunchanged. An emptied route remains an explicit empty configuration.Any resulting protected-model gap is reported through the existing-`would_interrupt` projection alongside `would_remove_hops`. This explicit cascade is+`would_interrupt` projection alongside `would_remove_hops`. Each `RouteHopRef` also+carries one-based `position` in that named Route before the attempted mutation;+reporting sorts by backend, menu model, then that position, and a forced success repeats+the same references and positions as its refusal. This explicit cascade isnot the silent side effect prohibited by §2; without the confirmation, neither theSource nor any chain changes.The same invariant applies to **every Source-inventory mutation**, not only Sourcedeletion. Reversible or transactional changes — API-key Base URL replacement, API-key-credential replacement, explicit refresh/recovery, and manual-model deletion — first+credential replacement, explicit refresh/recovery, discovered-model retirement, and+manual-model deletion — firststage the resulting inventory and run **both** guards: compare it with every exactconfigured hop and recompute `would_interrupt` for every protected menu model. If anexact configured model would cease to be callable, the non-forced mutation is refused@@ -866,31 +1096,69 @@ with `source_model_in_route_chain` and ordered `would_remove_hops`; another Soursupplying the same menu model does not make that exact reference disposable. If noexact hop is lost but a protected route loses its last supplier, it is refused with`source_last_supplier`. When both apply, the exact-hop error leads and the response-still carries both complete arrays. A confirmed `force=true` applies the inventory+still carries both complete arrays. A confirmed `force=true` with an exact echo of both arrays applies the inventorychange and removes only those invalidated hops in one transaction, preserving theidentity and relative order of all survivors and keeping an empty route configured.It also reports every resulting supply gap; force is confirmation, not a claim thatthe mutation is interruption-free.+**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 and inventory 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+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+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_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 |+| `guard_decision.forced_unconfirmed` | true | nonempty | either array absent or either array differs | HTTP 409 `GuardRefusal` with the newly recomputed plan; remove nothing |++Every destructive guarded impact that commits therefore exactly matches the echoed plan. Every+409 carries a nonempty current plan and mutates no Route. A previously refused request+that now recomputes to an empty plan, including one carrying its old plan echo, follows the+ordinary success path without a fabricated guard error or request-validation variant.++**Guard error-plan relation (authoritative and exhaustive; owner ruling 2026-08-11+21:58).** The lead error always names a nonempty array that proves the refused impact;+the other array remains a complete projection and may independently be empty or nonempty.++| Decision | `error` | Required nonempty plan array | Other array |+| --- | --- | --- | --- |+| `guard_error.source_in_route_chain` | `source_in_route_chain` | `would_remove_hops` | `would_interrupt` remains complete |+| `guard_error.source_model_in_route_chain` | `source_model_in_route_chain` | `would_remove_hops` | `would_interrupt` remains complete |+| `guard_error.source_last_supplier` | `source_last_supplier` | `would_interrupt` | `would_remove_hops` remains complete |+**Source-mutation envelope matrix (authoritative and exhaustive; owner rulings-2026-08-09).** These are all Source/inventory mutations, including writes that cannot+2026-08-09, confirmation binding simplified 2026-08-11 20:35).** These are all Source/inventory mutations, including writes that cannotremove supply. Prose may describe their guard rationale but cannot define a request orsuccess envelope outside this table. Omitted `force` is false; every reported array ispresent even when empty.| Decision | Mutation | Request | Guarded `409` | Success || --- | --- | --- | --- | --- |-| `mutation.source_metadata` | change Source metadata/Base URL | `PATCH /api/models/sources/<id>` with `{display_name?, base_url?, force?: boolean}`; `force` matters only when `base_url` changes | `{error, would_remove_hops: RouteHopRef[], would_interrupt: SupplyGap[]}` | `{source: Source, removed_hops: RouteHopRef[], interrupted: SupplyGap[]}` |-| `mutation.credential_replace` | replace API key | `PUT /api/models/sources/<id>/credential` with `{key, force?: boolean}` | same guarded `409` | same Source success envelope |-| `mutation.source_refresh` | refresh/recover saved Source | `POST /api/models/sources/<id>/refresh` with `{force?: boolean}` | same guarded `409` | same Source success envelope |+| `mutation.source_metadata` | change Source metadata/Base URL | `PATCH /api/models/sources/<id>` with `{display_name?, base_url?, force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` | `{error, would_remove_hops: RouteHopRef[], would_interrupt: SupplyGap[]}` | `{source: Source, removed_hops: RouteHopRef[], interrupted: SupplyGap[]}` |+| `mutation.credential_replace` | replace API key | `PUT /api/models/sources/<id>/credential` with `{key, force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` | same guarded `409` | same Source success envelope |+| `mutation.source_refresh` | refresh/recover saved Source | `POST /api/models/sources/<id>/refresh` with `{force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` | same guarded `409` | same Source success envelope || `mutation.model_create` | create a user-authored model entry | `POST /api/models/sources/<source_id>/models` with `{model_id, display_name?, reasoning_efforts}` | not guarded: it creates one new exact `id` with `origin: "manual"` and changes no existing `id`, `origin`, or Route | `{source: Source}` || `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` | delete a user-authored model entry | `DELETE /api/models/sources/<source_id>/models/<model_id>` with `{force?: boolean}` | deleting `origin: "discovered"` returns `source_model_managed_upstream`; otherwise the same guarded `409` | same Source success envelope |-| `mutation.source_delete` | delete Source | `DELETE /api/models/sources/<id>?force=<bool>` | same guarded `409` | `{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}` | same guarded `409` | `{chain: AgentChain, removed_hops: RouteHopRef[], interrupted: SupplyGap[]}`; the reporting fields are the same guarded-mutation family as Source success |+| `mutation.model_delete` | retire a discovered model or delete a manual model | `DELETE /api/models/sources/<source_id>/models/<model_id>` with `{force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` | same guarded `409`; discovered retirement is staged before evaluating exact-hop and protected-supply loss | 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 |The request carrier shown in each row is the only one. The final `api.md`, server/clientenvelopes, confirmation UI, and route tests mirror this matrix row-for-row.+`PUT /api/models/agents/<backend>/sources` is intentionally outside the matrix: it+changes only the Add-time Source-order sequence, never a Route chain or its members, and+must not gain a guarded `409` branch. This is the G-9 behavioral tombstone; a guard here+would imply the forbidden behavior of rewriting Routes during Source-order storage.Automatic background discovery never performs this cascade: when neither literalinventory nor sanctioned-alias evidence remains, it records the model as`model_unsupported`, keeps the configured hop visible and non-runnable, and waits for@@ -1001,6 +1269,17 @@ eligible Source ids, and has no `follow | custom` or other policy discriminator.Source deletion removes its id from every backend order in the same transaction andpreserves the relative order of survivors. Serialization/reload rejects a dangling id.+`POST /api/models/agents/<backend>/chains/reorder` applies that sequence to every+existing Route without changing Route membership or mappings. For an original hop at+index `i`, use stable key `(0, source_order_index, i)` when its Source appears in the+current order and `(1, i, i)` otherwise, then sort lexicographically. Thus all listed+Sources come first in configured order, hops sharing a listed Source retain their+relative order, and all unlisted-Source hops follow while retaining their mutual+relative order. The operation is idempotent, never runs matching, and never adds,+removes, remaps, guards, or reports interruption. It is the only existing-chain+consumer of `sources.order`; storing a new Source order alone leaves every Route byte-+identical.+`hops` may be empty and is always present. A newly introduced menu model starts with anempty route; catalog expansion and inventory refresh do not retroactively match it.Only Add Source's one-time match or an explicit user edit changes the array. Hop order,diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex 9f21c11a1..f687735d2 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -438,6 +438,49 @@ def test_every_frozen_schema_example_is_valid_and_json_round_trips():assert _canonical(json.loads(_canonical(example))) == _canonical(example)+def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():+ validator = Draft7Validator(_schema("guard-refusal.schema.json"))+ hop = {+ "backend": "claude",+ "menu_model": "claude-opus-4-6",+ "source_id": "src_anthkey01",+ "model_id": "claude-opus-4-6",+ "position": 1,+ }+ gap = {+ "backend": "claude",+ "model_id": "claude-opus-4-6",+ "agents": ["pm"],+ }++ route_refusal = {+ "ok": False,+ "contract_version": 5,+ "error": "source_in_route_chain",+ "would_remove_hops": [hop],+ "would_interrupt": [],+ }+ model_refusal = {**route_refusal, "error": "source_model_in_route_chain"}+ supplier_refusal = {+ **route_refusal,+ "error": "source_last_supplier",+ "would_remove_hops": [],+ "would_interrupt": [gap],+ }+ for payload in (route_refusal, model_refusal, supplier_refusal):+ validator.validate(payload)++ for payload in (+ {**route_refusal, "would_remove_hops": [], "would_interrupt": [gap]},+ {**model_refusal, "would_remove_hops": [], "would_interrupt": [gap]},+ {**supplier_refusal, "would_remove_hops": [hop], "would_interrupt": []},+ {**route_refusal, "would_remove_hops": [hop, hop]},+ {**supplier_refusal, "would_interrupt": [gap, gap]},+ ):+ with pytest.raises(ValidationError):+ validator.validate(payload)++def test_agent_supply_contract_accepts_unmapped_native_alias_selection():payload = {"backend": "claude",@@ -526,6 +569,62 @@ def test_v5_mirror_registry_mutation_probes_detect_every_comparable_drift():_validate_mirror_entry(entry, mutated)+def test_d21_live_backoff_reason_consumers_match_authority_individually():+ registry = json.loads(+ (CONTRACTS / "mirror-registry.json").read_text(encoding="utf-8")+ )+ decision = next(+ item for item in registry["decision_tables"] if item["id"] == "D21"+ )+ authority_spec = decision["authority"]+ authority = _vocabulary(+ _schema(authority_spec["schema"]), authority_spec["paths"]+ )++ observed = []+ for consumer in decision["consumers"]:+ if consumer["kind"] == "schema_vocabulary":+ observed.append(+ _vocabulary(+ _schema(consumer["schema"]),+ consumer["paths"],+ exclude=consumer.get("exclude", ()),+ )+ )+ elif consumer["kind"] == "marker_tail":+ values = set()+ for line in Path(consumer["file"]).read_text(encoding="utf-8").splitlines():+ if consumer["marker"] in line:+ tail = line.split(consumer["marker"], 1)[1].split("-->", 1)[0]+ values.update(tail.split())+ observed.append(values)+ elif consumer["kind"] == "json_object_keys":+ payload = json.loads(Path(consumer["file"]).read_text(encoding="utf-8"))+ keys = _json_pointer(payload, consumer["path"])+ observed.append({f"{consumer.get('prefix', '')}{key}" for key in keys})+ else:+ raise AssertionError(consumer)++ assert observed+ assert all(values == authority for values in observed)++ mutated_probe = _schema("probe-result.schema.json")+ mutated_probe["properties"]["error"]["enum"].remove(+ "models.source.backoff.connection_failed"+ )+ probe_spec = next(+ item for item in decision["consumers"] if item["kind"] == "schema_vocabulary"+ )+ assert (+ _vocabulary(+ mutated_probe,+ probe_spec["paths"],+ exclude=probe_spec.get("exclude", ()),+ )+ != authority+ )++def test_model_hub_authority_closure_is_generated_from_live_files():result = check_model_hub_authorities(Path.cwd())assert result["input_mode"] == "same_run_live_files"@@ -579,7 +678,119 @@ def test_targeted_permission_denial_contract_is_request_scoped_and_mirrored():)+def test_oauth_nonce_explicit_cancel_totality_is_closed():+ api_contract = (CONTRACTS / "api.md").read_text(encoding="utf-8")+ model_hub_plan = (CONTRACTS.parent / "model-hub.md").read_text(encoding="utf-8")+ implementation_plan = (+ CONTRACTS.parent / "model-hub-implementation.md"+ ).read_text(encoding="utf-8")++ cancel_route = next(+ line+ for line in api_contract.splitlines()+ if "POST `/api/models/oauth/cancel`" in line+ )+ assert "Cancels and forgets the flow." not in api_contract+ assert "committed flow with `client_nonce`" in cancel_route+ assert '`state: "cancelled"`' in cancel_route+ assert "existing `expires_at`" in cancel_route+ assert "flow without a nonce is forgotten" in cancel_route++ api_oauth = api_contract.split("## OAuth completion", 1)[1].split(+ "## Chain and probe", 1+ )[0]+ plan_oauth = model_hub_plan.split(+ "**OAuth-start nonce state machine", 1+ )[1].split("**Protocol observation", 1)[0]+ for section in (api_oauth, plan_oauth):+ assert section.count("| `oauth_nonce.released` |") == 1+ assert section.count("| `oauth_nonce.in_flight` |") == 1+ assert section.count("| `oauth_nonce.committed` |") == 1+ assert "retained canceled flow" in section+ assert "existing `expires_at`" in section+ assert 'retained `state: "cancelled"` flow' in section+ assert "none" in next(+ line+ for line in section.splitlines()+ if line.startswith("| `oauth_nonce.committed` |")+ )++ nonce_description = _schema("oauth-flow.schema.json")["properties"][+ "client_nonce"+ ]["description"]+ assert "Explicit cancellation retains that committed flow" in nonce_description+ assert "starts no provider on a same-tuple retry" in nonce_description++ oauth_schema = _schema("oauth-flow.schema.json")+ oauth_validator = Draft7Validator(oauth_schema, format_checker=FormatChecker())+ nonce_with_expiry = copy.deepcopy(oauth_schema["examples"][0])+ oauth_validator.validate(nonce_with_expiry)++ nonce_without_expiry = copy.deepcopy(nonce_with_expiry)+ nonce_without_expiry["expires_at"] = None+ with pytest.raises(ValidationError):+ oauth_validator.validate(nonce_without_expiry)++ ordinary_without_expiry = copy.deepcopy(nonce_without_expiry)+ ordinary_without_expiry.pop("client_nonce")+ oauth_validator.validate(ordinary_without_expiry)++ ac_48 = implementation_plan.split("### AC-48", 1)[1].split("### AC-49", 1)[0]+ for fixture_pattern in (+ r"same-tuple canceled replay with zero provider calls",+ r"existing-expiry\s+release followed by one fresh provider start",+ r"no-nonce\s+forget",+ ):+ assert re.search(fixture_pattern, ac_48)++def test_v5_shape_amendments_reject_the_false_states_they_replace():+ api_contract = (CONTRACTS / "api.md").read_text(encoding="utf-8")+ credential_contract = api_contract.split(+ "## Credential replacement and reauth", 1+ )[1].split("## Source refresh and blocked-source recovery", 1)[0]+ assert "{source, recovered, interrupted_pairs}" not in credential_contract+ assert '"recovered"' not in credential_contract+ assert '"interrupted_pairs"' not in credential_contract+ assert api_contract.count("| `oauth_terminal.reauth_success` |") == 1+ reauth_contract = api_contract.split(+ "## Credential replacement and reauth", 1+ )[1].split("## Source refresh and blocked-source recovery", 1)[0]+ assert "Hub-channel repair does not require this acknowledgement" not in reauth_contract+ assert "For both Hub OAuth and\n `native_cli` Sources" in reauth_contract+ assert re.search(+ r"Missing or false returns\s+`reauth_confirmation_required` before any OAuth adapter call",+ reauth_contract,+ )+ assert "Transactional API-key repair through `PUT …/credential` remains outside" in reauth_contract++ runtime_schema = _schema("runtime-dependency.schema.json")+ runtime_validator = Draft7Validator(runtime_schema)+ installing_runtime = copy.deepcopy(runtime_schema["examples"][0])+ installing_runtime["status"].update(+ {+ "installed_version": None,+ "verified": False,+ "listening": None,+ "health": "installing",+ "error_key": None,+ }+ )+ runtime_validator.validate(installing_runtime)+ for field, contradiction in (+ ("installed_version", "v7.2.95"),+ ("verified", True),+ ("listening", {"host": "127.0.0.1", "port": 15220}),+ ):+ invalid_installing = copy.deepcopy(installing_runtime)+ invalid_installing["status"][field] = contradiction+ with pytest.raises(ValidationError):+ runtime_validator.validate(invalid_installing)+ missing_installing_shape = copy.deepcopy(installing_runtime)+ del missing_installing_shape["status"]["listening"]+ with pytest.raises(ValidationError):+ runtime_validator.validate(missing_installing_shape)+supply_schema = _schema("agent-supply.schema.json")supply_validator = Draft7Validator(supply_schema)base_supply = {@@ -681,10 +892,55 @@ def test_v5_shape_amendments_reject_the_false_states_they_replace():with pytest.raises(ValidationError):event_validator.validate(invalid_event)- probe = copy.deepcopy(_schema("probe-result.schema.json")["examples"][0])+ probe_schema = _schema("probe-result.schema.json")+ probe_validator = Draft7Validator(probe_schema)+ connection_failure = next(+ copy.deepcopy(example)+ for example in probe_schema["examples"]+ if example["error"] == "models.source.backoff.connection_failed"+ )+ probe_validator.validate(connection_failure)+ for contradiction in (+ {"channel": "native_cli"},+ {"latency_ms": 1},+ ):+ invalid_connection_failure = {**connection_failure, **contradiction}+ with pytest.raises(ValidationError):+ probe_validator.validate(invalid_connection_failure)++ probe = copy.deepcopy(probe_schema["examples"][0])probe["source_id"] = "direct"with pytest.raises(ValidationError):- Draft7Validator(_schema("probe-result.schema.json")).validate(probe)+ probe_validator.validate(probe)++ chain_schema = _schema("agent-chain.schema.json")+ chain_validator = Draft7Validator(chain_schema)+ ordinary_backoff = next(+ copy.deepcopy(example)+ for example in chain_schema["examples"]+ if example["chain"]+ and example["chain"][0]["reason"]+ == "models.source.backoff.connection_failed"+ )+ for blocker in (+ {+ "health": "needs_action",+ "reason": "models.source.needs_action.credential_revoked",+ "retry_at": None,+ },+ {+ "health": "healthy",+ "reason": "model_unsupported",+ "retry_at": None,+ },+ ):+ blocked = copy.deepcopy(ordinary_backoff)+ blocked["chain"][0].update(blocker)+ blocked["supply_state"] = "interrupted"+ chain_validator.validate(blocked)+ mislabeled_waiting = {**blocked, "supply_state": "waiting"}+ with pytest.raises(ValidationError):+ chain_validator.validate(mislabeled_waiting)canceled = next(example@@ -701,6 +957,11 @@ def test_v5_shape_amendments_reject_the_false_states_they_replace():chain_validator = Draft7Validator(chain_schema)for example in chain_schema["examples"]:chain_validator.validate(example)+ for waiting in chain_schema["examples"][:2]:+ interrupted = copy.deepcopy(waiting)+ interrupted["supply_state"] = "interrupted"+ with pytest.raises(ValidationError):+ chain_validator.validate(interrupted)exact_hop = {"contract_version": 5,"backend": "claude",@@ -728,6 +989,20 @@ def test_v5_shape_amendments_reject_the_false_states_they_replace():with pytest.raises(ValidationError):chain_validator.validate(invalid_reason)+ model_supply_validator = Draft7Validator(+ supply_schema["properties"]["model_supply"]["items"]+ )+ empty_model_supply = {+ "model_id": "claude-opus-4-6",+ "chain_length": 0,+ "has_runnable_hop": False,+ }+ model_supply_validator.validate(empty_model_supply)+ with pytest.raises(ValidationError):+ model_supply_validator.validate(+ {**empty_model_supply, "has_runnable_hop": True}+ )+probe_schema = _schema("probe-result.schema.json")probe_validator = Draft7Validator(probe_schema)native_ready = copy.deepcopy(probe_schema["examples"][-2])@@ -749,6 +1024,108 @@ def test_v5_shape_amendments_reject_the_false_states_they_replace():probe_validator.validate(timed_native_not_ready)+def test_oauth_terminal_materialization_matrix_and_handoffs_are_total():+ api_contract = (CONTRACTS / "api.md").read_text(encoding="utf-8")+ model_hub_plan = (CONTRACTS.parent / "model-hub.md").read_text(encoding="utf-8")+ implementation_plan = (+ CONTRACTS.parent / "model-hub-implementation.md"+ ).read_text(encoding="utf-8")+ mirror_registry = _schema("mirror-registry.json")++ decisions = (+ "oauth_terminal.flow_only",+ "oauth_terminal.create_success",+ "oauth_terminal.reauth_success",+ "oauth_terminal.materialization_interrupted",+ "oauth_terminal.materialization_plain_error",+ )+ api_oauth = api_contract.split("## OAuth completion", 1)[1].split(+ "## Chain and probe", 1+ )[0]+ plan_oauth = model_hub_plan.split(+ "**OAuth terminal response and materialization-error matrix", 1+ )[1].split("**Protocol observation", 1)[0]+ for section in (api_oauth, plan_oauth):+ for decision in decisions:+ assert section.count(f"| `{decision}` |") == 1++ reauth_success = next(+ line+ for line in section.splitlines()+ if line.startswith("| `oauth_terminal.reauth_success` |")+ )+ interrupted_error = next(+ line+ for line in section.splitlines()+ if line.startswith("| `oauth_terminal.materialization_interrupted` |")+ )+ plain_error = next(+ line+ for line in section.splitlines()+ if line.startswith("| `oauth_terminal.materialization_plain_error` |")+ )+ assert "may be empty" in reauth_success+ assert "present and nonempty" in interrupted_error+ assert "no `flow`" in interrupted_error or "`flow` is absent" in interrupted_error+ assert "absent" in plain_error+ assert "empty placeholder" in plain_error++ d22 = next(+ rule for rule in mirror_registry["decision_tables"] if rule["id"] == "D22"+ )+ assert d22["authority"]["heading"] == (+ "OAuth terminal response and materialization-error matrix"+ )+ assert d22["consumers"] == [+ {+ "kind": "marker",+ "file": "docs/plans/model-hub-contracts/api.md",+ "prefix": "oauth_terminal.",+ }+ ]++ ac_52 = implementation_plan.split("### AC-52", 1)[1].split("### AC-53", 1)[0]+ i3_lane = next(+ line+ for line in implementation_plan.splitlines()+ if line.startswith("| **I3 subscription custody and native import**")+ )+ auth_setup_landing = next(+ line+ for line in implementation_plan.splitlines()+ if line.startswith("| `tests/scenarios/auth_setup/")+ )+ for section in (ac_52, i3_lane, auth_setup_landing):+ assert "AUTH-SETUP-109" in section+ for path in (+ "tests/scenarios/auth_setup/catalog.yaml",+ "tests/scenarios/auth_setup/test_auth_setup_scenarios.py",+ ):+ assert path in ac_52+ assert "After K4, #1312, and K6 merge" in ac_52+ assert "earlier K4 + #1312 edge" in ac_52+ assert "missing and false acknowledgement" in ac_52+ assert "before any adapter/provider call" in ac_52+ assert "starts exactly one Hub flow" in ac_52+ assert "terminal status and the\nrepair read projection agree" in ac_52++ ac_53 = implementation_plan.split("### AC-53", 1)[1].split(+ "### K4 open contract-gap registry", 1+ )[0]+ assert "all five rows" in ac_53+ for path in (+ "core/handlers/model_hub/{service,errors}.py",+ "vibe/{ui_server,model_hub_client}.py",+ "tests/test_model_hub_api.py",+ "ui/src/components/settings/models/{modelsApi.ts,OAuthConnectDialog.tsx,apiFailure.test.ts,oauthResult.test.ts}",+ ):+ assert path in ac_53+ assert "After K4, #1312, and K6 merge" in ac_53+ assert "After K4 merges, K5 round 2" in ac_53+ assert "After\nthat K5 round and the I7 payload fixtures freeze" in ac_53+ assert "same-error/no-gap negative fixture" in ac_53++def test_model_hub_config_round_trip_and_serializer_completeness(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))source_example = {diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pyindex 8ff0c8868..029d76337 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -2241,32 +2241,6 @@ def test_chain_projection_and_probe_latency_partition(tmp_path: Path) -> None:assert probe["error"] is None_assert_valid("probe-result.schema.json", probe)- network_service = _service(- tmp_path / "network",- sources=[_source("src_primary01", "Primary")],- outcomes=[_outcome(RawOutcomeKind.NETWORK_ERROR)],- )- network_model = _canonicalize_fixed_test_routes(network_service)["claude"]- network = asyncio.run(network_service.probe_agent("claude", network_model))- assert network["reachable"] is False- assert network["latency_ms"] is None- assert network["error"] == "models.source.cooldown.network"- _assert_valid("probe-result.schema.json", network)-- timeout_service = _service(- tmp_path / "timeout",- sources=[_source("src_primary01", "Primary")],- outcomes=[_outcome(RawOutcomeKind.TIMEOUT)],- )- timeout_model = _canonicalize_fixed_test_routes(timeout_service)["claude"]- timeout = asyncio.run(timeout_service.probe_agent("claude", timeout_model))- assert timeout["reachable"] is False- assert timeout["latency_ms"] is None- assert timeout["error"] == "models.source.cooldown.timeout"- assert timeout_service.store.load().sources[0].state.detail_key == ("models.source.cooldown.timeout")- assert timeout_service.events.list(limit=10)[0]["reason"] == "network"- _assert_valid("probe-result.schema.json", timeout)-rate_service = _service(tmp_path / "rate",sources=[_source("src_primary01", "Primary")],@@ -2343,6 +2317,49 @@ def test_chain_projection_and_probe_latency_partition(tmp_path: Path) -> None:_assert_valid("probe-result.schema.json", not_found)+ strict=True,+ reason="AC-50: cooldown.network → backoff.connection_failed 契约先行,实现随 I7 落地",+)+def test_probe_transport_failures_await_ac50_backoff_contract(tmp_path: Path) -> None:+ for name, kind in (+ ("network", RawOutcomeKind.NETWORK_ERROR),+ ("timeout", RawOutcomeKind.TIMEOUT),+ ):+ outcome = _outcome(kind)+ assert outcome.stream_started is False+ service = _service(+ tmp_path / name,+ sources=[_source("src_primary01", "Primary")],+ outcomes=[outcome],+ )+ menu_model = _canonicalize_fixed_test_routes(service)["claude"]+ config_before = json.loads(json.dumps(service.store.load().to_payload()))+ service.store.save = Mock(wraps=service.store.save)++ result = asyncio.run(service.probe_agent("claude", menu_model))++ assert result["reachable"] is False+ assert result["latency_ms"] is None+ assert result["error"] == "models.source.backoff.connection_failed"+ _assert_valid("probe-result.schema.json", result)+ service.store.save.assert_not_called()+ assert service.store.load().to_payload() == config_before+ assert service.store.load().sources[0].state.status == "standby"+ assert service.store.load().sources[0].state.detail_key is None++ chain = service.agent_chain("claude", menu_model)+ hop = chain["chain"][0]+ assert hop["health"] == "backoff"+ assert hop["runnable"] is False+ assert hop["reason"] == "models.source.backoff.connection_failed"+ assert datetime.fromisoformat(hop["retry_at"]) > NOW+ assert chain["current"] is None+ assert chain["supply_state"] == "waiting"+ assert service.events.list(limit=10)[0]["reason"] == "network"+ _assert_valid("agent-chain.schema.json", chain)++def test_probe_401_uses_exact_credential_refresh_capability(tmp_path: Path) -> None:static_source = _source("src_staticprobe", "Static")static_service = _service(diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex f4b7f7365..9ee312175 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -710,6 +710,11 @@"startNow": "Start now","starting": "Starting"},+ "install": {+ "fail": {+ "detail": "The install did not finish, and the component may be left incomplete. Retrying installs it again from scratch."+ }+ },"experimental": "Experimental","agents": {"title": "Agent",@@ -1226,6 +1231,9 @@"quota_exhausted": "Cycle quota used up","server_error": "Upstream server error"},+ "backoff": {+ "connection_failed": "Connection failed, retrying shortly"+ },"needs_action": {"oauth_expired": "Needs a new sign-in","balance_exhausted": "Out of balance — top it up",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 933d4b4e3..2dc8edc6f 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -710,6 +710,11 @@"startNow": "立即启动","starting": "正在启动"},+ "install": {+ "fail": {+ "detail": "这次安装没有完成,组件可能处于未完成状态。重试会重新装一遍。"+ }+ },"experimental": "实验","agents": {"title": "Agent",@@ -1226,6 +1231,9 @@"quota_exhausted": "本周期额度用完","server_error": "上游服务异常"},+ "backoff": {+ "connection_failed": "连接失败,短暂退避"+ },"needs_action": {"oauth_expired": "需要重新登录","balance_exhausted": "余额不足,需要充值",