Make Codex and Claude Code subscriptions go further: a local model router that gives routine agent work to economical models and keeps your strongest model for the hard parts.
Rust ai-agentsai-gatewayclaude-codecodexcoding-agentcost-optimizationdeepseekllm-gatewayllm-routerlocal-firstmodel-routingrusttask-routingtauri
fix: attribute model budget conflicts to active consumers (#115)
澄潭d526960e7abf
diff --git a/apps/desktop/src-tauri/src/bridge_command_acl_tests.rs b/apps/desktop/src-tauri/src/bridge_command_acl_tests.rsindex 1e1e0396..7a30958f 100644--- a/apps/desktop/src-tauri/src/bridge_command_acl_tests.rs+++ b/apps/desktop/src-tauri/src/bridge_command_acl_tests.rs@@ -107,6 +107,7 @@ fn action_results_and_failures_classify_without_business_text() {let succeeded = MutationOutcome {state: "submitted".into(),operation: Some(ClientOperationViewV1 {+ model_budget_conflict: None,operation_id: "op_diagnostics".into(),state: "succeeded".into(),sequence: 1,diff --git a/apps/desktop/src-tauri/src/fault_tests.rs b/apps/desktop/src-tauri/src/fault_tests.rsindex c5fe32f3..91f72cac 100644--- a/apps/desktop/src-tauri/src/fault_tests.rs+++ b/apps/desktop/src-tauri/src/fault_tests.rs@@ -90,6 +90,7 @@ async fn independent_change(session: &mut Session, key: String) -> String {request_id: "independent-apply".into(),operation_id: "ApplyAgentPlanChange".into(),payload: serde_json::to_value(PlanContentApplyRequestV2 {+ include_model_budget_conflict: false,change,accept_digest: preview.change_digest,expected_revisions: preview.expected_revisions,@@ -190,6 +191,7 @@ async fn accepted_apply_response_loss_recovers_without_another_apply() {"FindOperationByIdempotency","other-principal",&OperationIdempotencyLookupV1 {+ include_model_budget_conflict: true,principal_kind: PrincipalKind::Desktop,operation_kind: hint.operation_kind,idempotency_key: hint.idempotency_key,diff --git a/apps/desktop/src-tauri/src/operation_observation.rs b/apps/desktop/src-tauri/src/operation_observation.rsindex 440f0c0d..7fbb4eb6 100644--- a/apps/desktop/src-tauri/src/operation_observation.rs+++ b/apps/desktop/src-tauri/src/operation_observation.rs@@ -75,6 +75,7 @@ pub(crate) async fn lookup(client,"FindOperationByIdempotency",&OperationIdempotencyLookupV1 {+ include_model_budget_conflict: true,principal_kind: hint.principal_kind,operation_kind: hint.operation_kind.clone(),idempotency_key: hint.idempotency_key.clone(),diff --git a/apps/desktop/src-tauri/src/session.rs b/apps/desktop/src-tauri/src/session.rsindex 928e9adf..ad7637d6 100644--- a/apps/desktop/src-tauri/src/session.rs+++ b/apps/desktop/src-tauri/src/session.rs@@ -32,6 +32,8 @@ struct NativePlanApply {accept_digest: CanonicalDigest,expected_revisions: RevisionSetV1,idempotency_key: String,+ #[serde(skip_serializing_if = "std::ops::Not::not")]+ include_model_budget_conflict: bool,}impl From<PlanContentApplyRequestV2> for NativePlanApply {fn from(request: PlanContentApplyRequestV2) -> Self {@@ -40,6 +42,7 @@ impl From<PlanContentApplyRequestV2> for NativePlanApply {accept_digest: request.accept_digest,expected_revisions: request.expected_revisions,idempotency_key: request.idempotency_key,+ include_model_budget_conflict: request.include_model_budget_conflict,}}}@@ -553,6 +556,7 @@ impl Session {accept_digest: preview.change_digest,expected_revisions: preview.expected_revisions,idempotency_key,+ include_model_budget_conflict: true,}.into(),})@@ -810,6 +814,7 @@ fn accepted_operation_view(hint.operation_id = Some(reference.operation_id.clone());hint.after_sequence = reference.sequence;Ok(ClientOperationViewV1 {+ model_budget_conflict: None,operation_id: reference.operation_id,state: reference.state,sequence: reference.sequence,diff --git a/apps/desktop/src-tauri/src/session/authoring.rs b/apps/desktop/src-tauri/src/session/authoring.rsindex 5185f10f..f5bb1d3a 100644--- a/apps/desktop/src-tauri/src/session/authoring.rs+++ b/apps/desktop/src-tauri/src/session/authoring.rs@@ -85,6 +85,7 @@ impl Session {},message_override: Some(label),request: NativePlanApply {+ include_model_budget_conflict: change["schema"] == PLAN_CONTENT_CHANGE_SCHEMA_V2,change,accept_digest: preview.change_digest,expected_revisions: preview.expected_revisions,@@ -330,6 +331,7 @@ impl Session {},message_override: Some(message),request: NativePlanApply {+ include_model_budget_conflict: change["schema"] == PLAN_CONTENT_CHANGE_SCHEMA_V2,change,accept_digest: digest,expected_revisions: revisions,diff --git a/apps/desktop/src-tauri/tests/production_bootstrap.rs b/apps/desktop/src-tauri/tests/production_bootstrap.rsindex f71cb489..25ff395c 100644--- a/apps/desktop/src-tauri/tests/production_bootstrap.rs+++ b/apps/desktop/src-tauri/tests/production_bootstrap.rs@@ -191,6 +191,7 @@ async fn real_role_all_child_ack_and_read_only_lookup_use_shared_core() {operation_kind: "ApplyAgentPlanChange".into(),idempotency_key: "never-submitted".into(),accepted_digest: digest,+ include_model_budget_conflict: false,};let result: MachineEnvelopeV2<OperationIdempotencyResultV1> = resident.clientdiff --git a/apps/desktop/src/features/agents/status.ts b/apps/desktop/src/features/agents/status.tsindex 46dfca4b..b31785ca 100644--- a/apps/desktop/src/features/agents/status.ts+++ b/apps/desktop/src/features/agents/status.ts@@ -1,4 +1,15 @@-import type { Agent, ModelStatus } from './types';+import type { Agent, AgentModelSelection, ModelStatus } from './types';++/** Every model selection projects its own explicit Plan references through this boundary. */+export function agentModelPlanIds(selection: AgentModelSelection | null | undefined): string[] {+ if (!selection) return [];+ if ('allowed_plan_ids' in selection) {+ const defaultId = selection.mode === 'codex_default' && selection.default_selection.kind === 'plan'+ ? [selection.default_selection.plan_id] : [];+ return [...new Set([...selection.allowed_plan_ids, ...defaultId])];+ }+ return [...new Set(Object.values(selection.preset_mappings).flatMap(choice => choice.kind === 'plan' ? [choice.plan_id] : []))];+}/** Collaboration-only status has no model facet; absence is not an unconfigured model. */export function agentModelStatus(agent: Agent | null | undefined): ModelStatus | null {diff --git a/apps/desktop/src/occami/styles/pages.css b/apps/desktop/src/occami/styles/pages.cssindex 379be2d1..3e3c09a0 100644--- a/apps/desktop/src/occami/styles/pages.css+++ b/apps/desktop/src/occami/styles/pages.css@@ -348,6 +348,7 @@ button.list-row { width: 100%; border-top: 0; border-right: 0; border-left: 0; c.plan-editor { width: 100%; max-width: 1000px; margin: 0 auto; padding: 28px 30px 70px; }.editor-header { display: flex; align-items: flex-start; justify-content: space-between; gap: 24px; padding-bottom: 20px; border-bottom: 1px solid var(--divider); }+.editor-title { flex: 1; min-width: 0; max-width: 100%; }.editor-title h2 { margin: 0; font-size:calc(24px * var(--hr-text-scale)); }.editor-title p { margin: 6px 0 0; color: var(--text-muted); font-size:calc(13px * var(--hr-text-scale)); }.editor-actions { display: flex; gap: 8px; flex-shrink: 0; }diff --git a/apps/desktop/src/plan-editor-errors.ts b/apps/desktop/src/plan-editor-errors.tsindex 3547ae0d..323c4c9d 100644--- a/apps/desktop/src/plan-editor-errors.ts+++ b/apps/desktop/src/plan-editor-errors.ts@@ -1,17 +1,69 @@+export type ModelBudgetConflict = {+ schema: 'hiroute.agent-model-budget-conflict/v1';+ blockers: {+ agent_kind: 'qoder' | 'pi' | 'deepseek_harness'; context_id: string;+ plan_id: string; model_alias: string;+ reason: 'capacity_reduced' | 'plan_missing' | 'budget_unavailable';+ declared: { context_window_tokens: number; max_output_tokens: number };+ proposed: { context_window_tokens: number; max_output_tokens: number } | null;+ }[];+};++/** Accept only the safe typed capacity projection; raw wire/native error text is never copy. */+export function modelBudgetConflict(error: unknown): ModelBudgetConflict | null {+ if (!error || typeof error !== 'object') return null;+ const source = error as { model_budget_conflict?: unknown; envelope?: { error?: { model_budget_conflict?: unknown } } };+ const value = (source.model_budget_conflict ?? source.envelope?.error?.model_budget_conflict) as ModelBudgetConflict | undefined;+ const positive = (value: unknown) => typeof value === 'number' && Number.isSafeInteger(value) && value > 0;+ const budget = (value: ModelBudgetConflict['blockers'][number]['declared'] | null | undefined) => value+ && positive(value.context_window_tokens) && positive(value.max_output_tokens);+ if (value?.schema !== 'hiroute.agent-model-budget-conflict/v1' || !Array.isArray(value.blockers) || !value.blockers.length) return null;+ const valid = value.blockers.every(blocker => blocker+ && ['qoder', 'pi', 'deepseek_harness'].includes(blocker.agent_kind)+ && typeof blocker.context_id === 'string' && /^agent-context\/[A-Za-z0-9/_:-]{1,242}$/.test(blocker.context_id)+ && typeof blocker.plan_id === 'string' && /^[A-Za-z0-9/_:-]{1,256}$/.test(blocker.plan_id)+ && typeof blocker.model_alias === 'string' && /^(?:hiroute\/[0-9a-f]{16}|[a-z0-9][a-z0-9._-]{0,63})$/.test(blocker.model_alias)+ && budget(blocker.declared)+ && (blocker.reason === 'capacity_reduced'+ ? budget(blocker.proposed) && (blocker.proposed!.context_window_tokens < blocker.declared.context_window_tokens || blocker.proposed!.max_output_tokens < blocker.declared.max_output_tokens)+ : ['plan_missing', 'budget_unavailable'].includes(blocker.reason) && blocker.proposed === null));+ return valid ? value : null;+}+/** Read only structured error codes, never render a wire envelope as product copy. */export function planErrorCode(error: unknown): string {if (typeof error === 'string') return /^[A-Z][A-Z0-9_]{0,80}$/.test(error) ? error : 'REQUEST_FAILED';if (!error || typeof error !== 'object') return 'REQUEST_FAILED';- const value = error as { code?: unknown; failure?: { code?: unknown }; envelope?: { error?: { code?: unknown } } };- return planErrorCode(value.envelope?.error?.code ?? value.failure?.code ?? value.code);+ const value = error as { code?: unknown; safe_error_code?: unknown; failure?: { code?: unknown }; envelope?: { error?: { code?: unknown } } };+ const code = planErrorCode(value.envelope?.error?.code ?? value.failure?.code ?? value.code ?? value.safe_error_code);+ return modelBudgetConflict(error) && ['REVISION_CONFLICT', 'QODER_MODEL_BUDGET_CONFLICT', 'AGENT_MODEL_BUDGET_CONFLICT'].includes(code)+ ? 'AGENT_MODEL_BUDGET_CONFLICT' : code;}export function planErrorMessage(error: unknown, language: 'zh' | 'en'): string {+ const conflict = modelBudgetConflict(error);+ if (conflict && planErrorCode(error) === 'AGENT_MODEL_BUDGET_CONFLICT') {+ const zh = language === 'zh';+ const names = { qoder: 'Qoder', pi: 'Pi', deepseek_harness: 'DeepSeek Harness' };+ const number = (value: number) => value.toLocaleString('en-US');+ const blockers = conflict.blockers.map(blocker => {+ const changes: string[] = [];+ if (blocker.proposed) {+ if (blocker.proposed.context_window_tokens < blocker.declared.context_window_tokens) changes.push(`${zh ? '上下文' : 'context'} ${number(blocker.declared.context_window_tokens)} → ${number(blocker.proposed.context_window_tokens)}`);+ if (blocker.proposed.max_output_tokens < blocker.declared.max_output_tokens) changes.push(`${zh ? '最大输出' : 'max output'} ${number(blocker.declared.max_output_tokens)} → ${number(blocker.proposed.max_output_tokens)}`);+ } else changes.push(blocker.reason === 'plan_missing' ? (zh ? '计划不可用' : 'plan unavailable') : (zh ? '预算不可计算' : 'budget unavailable'));+ return `${names[blocker.agent_kind]}「${blocker.model_alias}」: ${changes.join(', ')}`;+ }).join('; ');+ return zh+ ? `已接入的模型路由容量受保护。${blockers}。请在 Agent 页面调整这些连接,取消接入受影响计划或停用其模型路由,再发布并重新接入。任务协作无需停用,当前输入已保留。`+ : `Installed model routing capacity is protected. ${blockers}. On the Agent page, remove the affected plan from these connections or disable their model routing, then publish and reconnect. Task collaboration can stay enabled. Your input is retained.`;+ }const messages: Record<string, [string, string]> = {PLAN_UNCHANGED: ['没有待发布更改。', 'No changes to publish.'],EDITOR_INVALID: ['请检查名称、使用场景及模型设置,当前输入已保留。', 'Check the name, purpose and model settings. Your input is retained.'],INVALID_ARGUMENTS: ['部分路由设置未通过校验,请检查输入后重试。', 'Some routing settings failed validation. Check your input and retry.'],CONFLICT: ['配置已在其他地方变化,请重新读取后再提交。当前输入已保留。', 'The configuration changed elsewhere. Reload before submitting. Your input is retained.'],QODER_MODEL_BUDGET_CONFLICT: ['新预算低于 Qoder 当前已接入模型声明的容量。请先在 Agent 页面停用 Qoder 的模型路由,再发布此计划并重新配置模型路由;任务协作无需停用。当前输入已保留。', 'The new budget is below the capacity declared by the current Qoder model connection. Disable Qoder model routing on the Agent page, publish this plan, then configure model routing again. Task collaboration can stay enabled. Your input is retained.'],+ AGENT_MODEL_BUDGET_CONFLICT: ['已接入的 Agent 模型路由容量受保护。请读取连接状态,调整受影响的模型路由后重新发布。任务协作无需停用,当前输入已保留。', 'Installed Agent model routing capacity is protected. Read connection status and adjust the affected model routing before publishing again. Task collaboration can stay enabled. Your input is retained.'],PLAN_HEAD_STALE: ['当前路由已在其他地方发布新版本。你的输入已保留,请读取当前生效配置后重新编辑。', 'A newer route version was published elsewhere. Your input is retained; reload the active route before editing again.'],DRAFT_REVISION_STALE: ['该草稿已在其他地方更新或移除。你的输入已保留,请读取最新草稿和生效配置后重试。', 'This draft was updated or removed elsewhere. Your input is retained; reload the latest draft and active route before retrying.'],RESIDENT_UNAVAILABLE: ['暂时无法连接本机服务,当前输入已保留。请稍后重试。', 'Cannot connect to the local service. Your input is retained. Try again.'],diff --git a/apps/desktop/src/plan-editor-persistence.ts b/apps/desktop/src/plan-editor-persistence.tsindex 16d55827..487976c9 100644--- a/apps/desktop/src/plan-editor-persistence.ts+++ b/apps/desktop/src/plan-editor-persistence.ts@@ -24,6 +24,7 @@ export type PersistenceIdentity = {};export type PlanOperation = {+ model_budget_conflict?: import('./plan-editor-errors').ModelBudgetConflict | null;operation_id: string;state: string;sequence: number;diff --git a/apps/desktop/src/product/DesktopApp.tsx b/apps/desktop/src/product/DesktopApp.tsxindex 103f231d..ba6bfc12 100644--- a/apps/desktop/src/product/DesktopApp.tsx+++ b/apps/desktop/src/product/DesktopApp.tsx@@ -84,8 +84,8 @@ function failureCode(error: unknown): string {return safeDiagnosticCode(error, 'CLIENT_ERROR');}-function failureHelp(code: string, language: 'zh' | 'en'): string {- if (code === 'QODER_MODEL_BUDGET_CONFLICT') return planErrorMessage(code, language);+function failureHelp(code: string, language: 'zh' | 'en', operation?: DesktopOperation | null): string {+ if (code === 'QODER_MODEL_BUDGET_CONFLICT' || code === 'AGENT_MODEL_BUDGET_CONFLICT') return planErrorMessage(operation ?? code, language);const messages: Record<string, [string, string]> = {CONFIRMATION_EXPIRED: ['确认已过期,请重新预览。输入已保留。', 'Confirmation expired. Preview again; your input is retained.'],CONFIRMATION_STALE: ['确认已失效,请重新预览。', 'This confirmation is no longer valid. Preview again.'],@@ -775,7 +775,7 @@ export function DesktopApp() {</div></div><p>{operationView.detail}</p>- {operation?.safe_error_code && <div className="callout bad" role="alert" data-error-code={operation.safe_error_code}><UiIcon name="warning" /><span>{failureHelp(operation.safe_error_code, language)}</span></div>}+ {operation?.safe_error_code && <div className="callout bad" role="alert" data-error-code={operation.safe_error_code}><UiIcon name="warning" /><span>{failureHelp(operation.safe_error_code, language, operation)}</span></div>}</article>}</main></div>diff --git a/apps/desktop/src/product/RoutingPage.tsx b/apps/desktop/src/product/RoutingPage.tsxindex e38bc001..3e8a0962 100644--- a/apps/desktop/src/product/RoutingPage.tsx+++ b/apps/desktop/src/product/RoutingPage.tsx@@ -7,7 +7,7 @@ import { requestEditorReplacement } from '../ui/discard-guard';import { ProductPage, UiIcon } from '../ui';import type { DesktopOperation, DesktopSnapshot } from './home-projections';import type { AgentSnapshot } from '../agents';-import { agentModelStatus } from '../features/agents/status';+import { agentModelPlanIds, agentModelStatus } from '../features/agents/status';import { agentBrand, agentDisplayName } from '../features/agents/ecosystems';import { routingEditorEntries } from '../routing-editor-entries';@@ -119,11 +119,7 @@ export function RoutingPage({ language, active = true, refreshVersion = 0, snapsconst isDefault = model?.mode === 'codex_default'&& model.default_selection.kind === 'plan'&& model.default_selection.plan_id === editor.plan!.agent_plan_id;- const isAllowed = model?.mode === 'codex_default' || model?.mode === 'qoder_additional'- ? model.allowed_plan_ids.includes(editor.plan!.agent_plan_id)- : model?.mode === 'claude_launcher'- ? Object.values(model.preset_mappings).some(selection => selection.kind === 'plan' && selection.plan_id === editor.plan!.agent_plan_id)- : false;+ const isAllowed = agentModelPlanIds(model).includes(editor.plan!.agent_plan_id);return isDefault || isAllowed ? [{ id: agent.agent_id, name: agentDisplayName(agent.agent_id, language), brand: agentBrand(agent.agent_id), isDefault }] : [];}) : [];const pageLocked = busy || localBusy || editorBusy || !mutable;diff --git a/apps/desktop/src/product/home-projections.ts b/apps/desktop/src/product/home-projections.tsindex 80a30ae8..7787cfa7 100644--- a/apps/desktop/src/product/home-projections.ts+++ b/apps/desktop/src/product/home-projections.ts@@ -36,6 +36,7 @@ export type DesktopSnapshot = {};export type DesktopOperation = {+ model_budget_conflict?: import('../plan-editor-errors').ModelBudgetConflict | null;operation_id: string;state: string;sequence: number;diff --git a/apps/desktop/tests/README.md b/apps/desktop/tests/README.mdindex 48c6a6a6..f0186722 100644--- a/apps/desktop/tests/README.md+++ b/apps/desktop/tests/README.md@@ -22,7 +22,7 @@ proves native authorization, persistence, process cleanup or real model calls.| Resume incomplete Qoder model configuration | `qoder.routing.resume-pending` | Recovery requires trusted authority and the exact original context/Operation; it refreshes backend state, creates no new setup, preserves collaboration and does not fabricate verification. || Select Qoder as a Worker | `qoder.installation.single-cli` | A single CLI is saved through the existing confirmation flow without adapter/Node placeholders; switching execution Agents preserves each installation. || Continue editing after route save | `routing.save.unobserved-editable` | An unobserved result does not lock the editor or other routes. |-| Publish a smaller budget used by Qoder | `routing.publish.qoder-budget-conflict`, `desktop.routing.qoder-budget-checkpoint` | Both immediate rejection and an accepted operation's checkpoint failure keep edits and explain disabling only Qoder model routing before publication and reconfiguration; neither disables collaboration nor calls models. |+| Publish a smaller budget used by installed Agents | `routing.publish.qoder-budget-conflict`, `desktop.routing.qoder-budget-checkpoint`, `desktop.routing.additional-budget-consumers` | All actual Pi/DSH consumers and output reductions are visible; both immediate rejection and an accepted operation's checkpoint failure keep edits and explain disabling only Qoder model routing before publication and reconfiguration; neither disables collaboration nor calls models. || Follow a submitted operation | `desktop.operation.dismiss-observes`, `desktop.operation.identity-retry-converges`, `desktop.operation.repeated-submission` in [shell scenarios](v3/browser/product-shell-scenarios.mjs); [operation rules](operation-feedback.test.mjs) | Dismissal does not cancel observation; mismatched identity stays neutral through grace/retry; repeated accepted or unknown saves restart observation; success refreshes and dismisses. Pure tests retain identity, sequence and terminal-state edges. || Adjust presentation | `desktop.settings.fixed-scale`; [preference tests](presentation-preferences.test.mjs) | Settings retain language and appearance controls; application text stays at 100% with no size selector. Previous 150/200% browser preferences normalize to 100% without changing language or theme, including after remount. Storage failure rules remain separately testable. || Configure the shared subscription proxy from a device scan | `desktop.models.subscription-proxy.inline-cancel`, `desktop.models.subscription-proxy.read-retry`, `desktop.models.subscription-proxy.save-retry-return`; [restart hint tests](subscription-proxy-return.test.mjs) | The inline editor preserves scan results and selection, removes the Settings entry, prevents an unread-policy overwrite and retains failed-save input. A simulated restart reloads the scan and saved policy; native restart, persistence and provider transport require production acceptance. |diff --git a/apps/desktop/tests/agent-status.test.mjs b/apps/desktop/tests/agent-status.test.mjsindex ad3abb55..14e52d55 100644--- a/apps/desktop/tests/agent-status.test.mjs+++ b/apps/desktop/tests/agent-status.test.mjs@@ -45,3 +45,15 @@ test('Agent presentation follows configuration and recovery rather than model veagent.settings.state = 'pending';assert.equal(project().model, 'pending');});+++import { agentModelPlanIds } from '../src/features/agents/status.ts';+test('plan usage covers every typed model selection and excludes restored connections', () => {+ for (const mode of ['qoder_additional', 'pi_additional', 'dsh_additional']) {+ assert.deepEqual(agentModelPlanIds({ mode, allowed_plan_ids: ['plan/free', 'plan/free'] }), ['plan/free']);+ }+ assert.deepEqual(agentModelPlanIds({ mode: 'codex_default', allowed_plan_ids: ['plan/free'], default_selection: { kind: 'plan', plan_id: 'plan/default' } }), ['plan/free', 'plan/default']);+ assert.deepEqual(agentModelPlanIds({ mode: 'claude_launcher', preset_mappings: { opus: { kind: 'plan', plan_id: 'plan/free' }, sonnet: { kind: 'plan', plan_id: 'plan/free' }, haiku: { kind: 'preserve_native' } } }), ['plan/free']);+ assert.deepEqual(agentModelPlanIds(null), []);+ assert.deepEqual(agentModelPlanIds(undefined), []);+});diff --git a/apps/desktop/tests/plan-editor-errors.test.mjs b/apps/desktop/tests/plan-editor-errors.test.mjsindex 65f47213..987f9d82 100644--- a/apps/desktop/tests/plan-editor-errors.test.mjs+++ b/apps/desktop/tests/plan-editor-errors.test.mjs@@ -7,6 +7,30 @@ test('backend envelope is decoded without exposing payloads or stack traces', ()assert.match(planErrorMessage(failure,'zh'),/校验/);assert.ok(!planErrorMessage(failure,'zh').includes('private-debug-content'));});+test('all live consumers and both capacity dimensions are shown without native payloads', () => {+ const blocker = (kind, context) => ({ agent_kind: kind, context_id: `agent-context/${context}/sha256:abc`, plan_id: 'plan/free', model_alias: 'free.plan', reason: 'capacity_reduced', declared: { context_window_tokens: 262144, max_output_tokens: 235929 }, proposed: { context_window_tokens: 262144, max_output_tokens: 131072 } });+ const conflict = { schema: 'hiroute.agent-model-budget-conflict/v1', blockers: [blocker('pi', 'pi'), blocker('deepseek_harness', 'dsh')] };+ const error = { envelope: { error: { code: 'REVISION_CONFLICT', details: 'private-native-config', model_budget_conflict: conflict } } };+ assert.equal(planErrorCode(error), 'AGENT_MODEL_BUDGET_CONFLICT');+ const message = planErrorMessage(error, 'zh');+ assert.match(message, /Pi「free.plan」.*最大输出 235,929 → 131,072.*DeepSeek Harness「free.plan」/);+ assert.doesNotMatch(message, /Qoder|private-native-config|上下文 262/);+ assert.match(message, /取消接入受影响计划.*任务协作无需停用.*输入已保留/);+ assert.match(planErrorMessage({ safe_error_code: 'AGENT_MODEL_BUDGET_CONFLICT', model_budget_conflict: conflict }, 'en'), /Pi.*max output.*DeepSeek Harness/);+ const contextOnly = { ...conflict, blockers: [{ ...blocker('qoder', 'qoder'), proposed: { context_window_tokens: 32000, max_output_tokens: 235929 } }] };+ assert.match(planErrorMessage({ code: 'QODER_MODEL_BUDGET_CONFLICT', model_budget_conflict: contextOnly }, 'zh'), /Qoder.*上下文 262,144 → 32,000/);+ for (const reason of ['plan_missing', 'budget_unavailable']) {+ const value = { ...conflict, blockers: [{ ...blocker('pi', 'pi'), reason, proposed: null }] };+ assert.match(planErrorMessage({ code: 'AGENT_MODEL_BUDGET_CONFLICT', model_budget_conflict: value }, 'zh'), reason === 'plan_missing' ? /计划不可用/ : /预算不可计算/);+ }+});+test('malformed capacity projections fall back safely', () => {+ for (const blockers of [[], [null], [{ agent_kind: 'qoder', context_id: '/private/settings.json' }]]) {+ const error = { envelope: { error: { code: 'REVISION_CONFLICT', model_budget_conflict: { schema: 'hiroute.agent-model-budget-conflict/v1', blockers } } } };+ assert.equal(planErrorCode(error), 'REVISION_CONFLICT');+ assert.doesNotMatch(planErrorMessage(error, 'zh'), /settings.json|停用 Qoder/);+ }+});test('unchanged publication is distinguishable from malformed failures', () => {assert.equal(planErrorCode({envelope:{error:{code:'PLAN_UNCHANGED'}}}),'PLAN_UNCHANGED');for(const value of [null, {}, new Error('private stack'), '{"code":"PLAN_UNCHANGED"}']) assert.equal(planErrorCode(value),'REQUEST_FAILED');diff --git a/apps/desktop/tests/v3/browser/product-shell-scenarios.mjs b/apps/desktop/tests/v3/browser/product-shell-scenarios.mjsindex 14d356f8..affcabb5 100644--- a/apps/desktop/tests/v3/browser/product-shell-scenarios.mjs+++ b/apps/desktop/tests/v3/browser/product-shell-scenarios.mjs@@ -798,6 +798,40 @@ const scenarios = [assert(contextWindow.value === '32000' && !contextWindow.disabled && !button('发布更改').disabled, 'Checkpoint failure discarded or locked the local edit');assert(calls('preview_agent_settings').length === 0 && calls('check_agent_live').length === 0, 'Checkpoint failure implicitly changed an Agent connection or called a model');}),+ scenario('desktop.routing.additional-budget-consumers', ['routing-editor', 'pi', 'dsh'], 'Both admission and checkpoint failures identify Pi/DSH and keep the route draft', async () => {+ for (const checkpoint of [false, true]) {+ await fresh(() => {+ const plan = c().desktop.catalog.plans[0];+ const base = c().agents.agents[0];+ for (const [id, mode] of [['agent_pi_default', 'pi_additional'], ['agent_dsh_default', 'dsh_additional']]) {+ c().agents.agents.push({ ...base, agent_id: id, context_id: `agent-context/${mode}/sha256:abc`, settings: { ...base.settings, current_selection: { mode, allowed_plan_ids: [plan.agent_plan_id] } } });+ }+ const conflict = { schema: 'hiroute.agent-model-budget-conflict/v1', blockers: [+ { agent_kind: 'pi', context_id: 'agent-context/pi/sha256:abc', plan_id: plan.agent_plan_id, model_alias: plan.model_alias, reason: 'capacity_reduced', declared: { context_window_tokens: 262144, max_output_tokens: 235929 }, proposed: { context_window_tokens: 262144, max_output_tokens: 131072 } },+ { agent_kind: 'deepseek_harness', context_id: 'agent-context/dsh/sha256:abc', plan_id: plan.agent_plan_id, model_alias: plan.model_alias, reason: 'capacity_reduced', declared: { context_window_tokens: 262144, max_output_tokens: 235929 }, proposed: { context_window_tokens: 262144, max_output_tokens: 131072 } },+ ] };+ c().handlers.preview_plan_editor = checkpoint ? () => ({ state: 'applied', operation: operation() }) : () => { throw { source: 'backend', envelope: { error: { code: 'REVISION_CONFLICT', model_budget_conflict: conflict } } }; };+ c().handlers.observe_operation = () => ({ ...operation('rolled_back'), sequence: 2, safe_error_code: 'AGENT_MODEL_BUDGET_CONFLICT', model_budget_conflict: conflict });+ });+ await routing();+ const usage = document.querySelector('.plan-editor .agent-card-list');+ assert(usage?.textContent.includes('Pi') && usage.textContent.includes('DeepSeek Harness') && !usage.textContent.includes('Qoder'), 'Where it is used omits the actual Pi/DSH connections or includes an unrelated Qoder');+ const name = document.querySelector('.plan-identity-fields input');+ const draftName = 'Budget retained draft with a long route name';+ setInput(name, draftName);+ await until(() => document.querySelector('[data-codex-capability-state=available]'), 'current model options before publication');+ const header = document.querySelector('.plan-editor .editor-header').getBoundingClientRect();+ const publish = button('发布更改').getBoundingClientRect();+ assert(publish.left >= header.left - 1 && publish.right <= header.right + 1,+ 'The retained draft title pushes publication outside the editor');+ await click('发布更改');+ await until(() => (checkpoint ? feedback() : document.querySelector('.plan-editor [role="alert"]'))?.textContent.includes('最大输出 235,929 → 131,072'), 'typed output-budget rejection');+ const message = (checkpoint ? feedback() : document.querySelector('.plan-editor [role="alert"]')).textContent;+ assert(message.includes('Pi') && message.includes('DeepSeek Harness') && !message.includes('Qoder') && message.includes('任务协作无需停用'), 'Recovery guidance misattributes the constraint');+ assert(name.value === draftName && !name.disabled && !button('发布更改').disabled, 'Budget rejection discarded or locked the draft');+ assert(calls('preview_agent_settings').length === 0 && calls('check_agent_live').length === 0, 'Budget rejection implicitly changed native routes or called a model');+ }+ }),scenario('desktop.home.reactivation-usage', ['home', 'sessions'], 'Returning home refreshes usage alongside recent activity without remounting the app', async () => {let input = 2400;const usage = () => document.querySelector('.v3-usage-body')?.textContent ?? '';diff --git a/apps/desktop/tests/v3/browser/scenario-requirements.mjs b/apps/desktop/tests/v3/browser/scenario-requirements.mjsindex 4a99a379..de6207ae 100644--- a/apps/desktop/tests/v3/browser/scenario-requirements.mjs+++ b/apps/desktop/tests/v3/browser/scenario-requirements.mjs@@ -50,6 +50,7 @@ export const focusedRequirements = {};export const productShellRequired = [+ 'desktop.routing.additional-budget-consumers','desktop.models.subscription-scan.recommended-login','desktop.models.subscription-scan.append-to-login','desktop.models.subscription-proxy.inline-cancel',diff --git a/apps/desktop/tests/v3/visual/agent-trust-active.mjs b/apps/desktop/tests/v3/visual/agent-trust-active.mjsindex ba484f0a..7d1d50b6 100644--- a/apps/desktop/tests/v3/visual/agent-trust-active.mjs+++ b/apps/desktop/tests/v3/visual/agent-trust-active.mjs@@ -92,7 +92,8 @@ try {: { requiredIds: productShellRequired });const results = [];for (const { id } of selected) {- const viewport = id === 'desktop.models.subscription-scan.recommended-login'+ const viewport = ['desktop.models.subscription-scan.recommended-login',+ 'desktop.routing.additional-budget-consumers'].includes(id)? { width: 755, height: 600 } : { width: 1280, height: 900 };await client.send('Emulation.setDeviceMetricsOverride', { ...viewport, deviceScaleFactor: 1, mobile: false });const batch = await evaluate(client, `import('/product-shell-scenarios.mjs').then(module => module.runProductShellScenarios(${JSON.stringify({ ids: [id], requiredIds: [id] })}))`);diff --git a/contracts/cli/contract-set.v1.json b/contracts/cli/contract-set.v1.jsonindex 450dbc84..b0766429 100644--- a/contracts/cli/contract-set.v1.json+++ b/contracts/cli/contract-set.v1.json@@ -15,7 +15,7 @@"empty-request.v1.schema.json": "sha256:44d40c4601343ddfb543fd04751cc0a0a994fe8d7963adc541fe4a245ceba2b1","local-control-hello.v2.schema.json": "sha256:32fbce882152a886b79bd139d3b4e459b48d94e0634e56ccb189b2c9971ad772","local-control.v2.schema.json": "sha256:4b654de90cd6e333b3953379e5b2e1c5125f1dcbe307b7c7c73f12bb2032d18c",- "machine-envelope.v2.schema.json": "sha256:5a0b47ce1fd80628f760a3da5a88de7dc01f6df83cb6eef47fd4a6c8289070ba",+ "machine-envelope.v2.schema.json": "sha256:23e019a3d024ae302a44105caff4ec95d3fb409a29f936dea1360e543ae6abd6","manifest.v1.json": "sha256:58786a9e169957e4ff2d651698d2671919aef87fea9a57e79954ce268afd15e1","operation-cancel-request.v1.schema.json": "sha256:0071cbcf27de3bfb7f6644478fe2b73bb5387ebe33db93629ff5672959e8495f","operation-lookup.v1.schema.json": "sha256:0fbaaa15b0e75b4186979bdd856bed0485d55a4bd33a33f3caf3bd92e01a7850",diff --git a/contracts/cli/machine-envelope.v2.schema.json b/contracts/cli/machine-envelope.v2.schema.jsonindex 25e315b0..a222bf4b 100644--- a/contracts/cli/machine-envelope.v2.schema.json+++ b/contracts/cli/machine-envelope.v2.schema.json@@ -27,6 +27,9 @@"minLength": 1,"type": "string"},+ "model_budget_conflict": {+ "$ref": "#/$defs/model_budget_conflict"+ },"operation_id": {"minLength": 1,"type": "string"@@ -44,6 +47,124 @@],"type": "object"},+ "model_budget_blocker": {+ "additionalProperties": false,+ "allOf": [+ {+ "else": {+ "properties": {+ "proposed": {+ "type": "null"+ }+ }+ },+ "if": {+ "properties": {+ "reason": {+ "const": "capacity_reduced"+ }+ }+ },+ "then": {+ "properties": {+ "proposed": {+ "$ref": "#/$defs/model_token_budget"+ }+ }+ }+ }+ ],+ "properties": {+ "agent_kind": {+ "enum": [+ "qoder",+ "pi",+ "deepseek_harness"+ ]+ },+ "context_id": {+ "pattern": "^agent-context/[A-Za-z0-9/_:-]{1,242}$",+ "type": "string"+ },+ "declared": {+ "$ref": "#/$defs/model_token_budget"+ },+ "model_alias": {+ "pattern": "^(hiroute/[0-9a-f]{16}|[a-z0-9][a-z0-9._-]{0,63})$",+ "type": "string"+ },+ "plan_id": {+ "maxLength": 256,+ "minLength": 1,+ "type": "string"+ },+ "proposed": {+ "oneOf": [+ {+ "$ref": "#/$defs/model_token_budget"+ },+ {+ "type": "null"+ }+ ]+ },+ "reason": {+ "enum": [+ "capacity_reduced",+ "plan_missing",+ "budget_unavailable"+ ]+ }+ },+ "required": [+ "agent_kind",+ "context_id",+ "plan_id",+ "model_alias",+ "reason",+ "declared",+ "proposed"+ ],+ "type": "object"+ },+ "model_budget_conflict": {+ "additionalProperties": false,+ "properties": {+ "blockers": {+ "items": {+ "$ref": "#/$defs/model_budget_blocker"+ },+ "minItems": 1,+ "type": "array"+ },+ "schema": {+ "const": "hiroute.agent-model-budget-conflict/v1"+ }+ },+ "required": [+ "schema",+ "blockers"+ ],+ "type": "object"+ },+ "model_token_budget": {+ "additionalProperties": false,+ "properties": {+ "context_window_tokens": {+ "minimum": 1,+ "type": "integer"+ },+ "max_output_tokens": {+ "minimum": 1,+ "type": "integer"+ }+ },+ "required": [+ "context_window_tokens",+ "max_output_tokens"+ ],+ "type": "object"+ },"next_action": {"additionalProperties": false,"properties": {diff --git a/contracts/compatibility-support.v1.json b/contracts/compatibility-support.v1.jsonindex aa20fa5a..b74fbc24 100644--- a/contracts/compatibility-support.v1.json+++ b/contracts/compatibility-support.v1.json@@ -26,6 +26,7 @@"hiroute.agent-launch-descriptor-request/v1","hiroute.agent-live-check-evidence/v1","hiroute.agent-live-check-receipt/v1",+ "hiroute.agent-model-budget-conflict/v1","hiroute.agent-model-grant/v3","hiroute.agent-model-settings-status/v2","hiroute.agent-plan-alias-registry/v1",diff --git a/crates/application-api/src/client_access.rs b/crates/application-api/src/client_access.rsindex 5fe1935d..1ad4fa3c 100644--- a/crates/application-api/src/client_access.rs+++ b/crates/application-api/src/client_access.rs@@ -78,11 +78,16 @@ pub struct OperationIdempotencyLookupV1 {pub operation_kind: String,pub idempotency_key: String,pub accepted_digest: CanonicalDigest,+ /// Keep extensions last for released positional inputs; false preserves the response shape.+ #[serde(default, skip_serializing_if = "is_false")]+ pub include_model_budget_conflict: bool,}#[derive(Clone, Debug, Deserialize, Serialize)]#[serde(deny_unknown_fields)]pub struct ClientOperationViewV1 {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub model_budget_conflict: Option<hiroute_domain::AgentModelBudgetConflictV1>,pub operation_id: String,pub state: String,pub sequence: u64,@@ -123,3 +128,42 @@ impl Default for AgentPlanCatalogQueryV2 {}}}++fn is_false(value: &bool) -> bool {+ !*value+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn released_idempotency_lookup_keeps_positional_field_order() {+ let digest = format!("sha256:{}", "0".repeat(64));+ let original = json!(["interactive_user", "change", "test", digest]);+ for projection in [None, Some(false), Some(true)] {+ let mut request = original.clone();+ if let Some(projection) = projection {+ request.as_array_mut().unwrap().push(json!(projection));+ }+ let lookup: OperationIdempotencyLookupV1 =+ serde_json::from_value(request).expect("released V1 positional lookup");+ assert_eq!(lookup.principal_kind, PrincipalKind::InteractiveUser);+ assert_eq!(lookup.operation_kind, "change");+ assert_eq!(lookup.idempotency_key, "test");+ assert_eq!(lookup.accepted_digest.as_str(), digest);+ assert_eq!(+ lookup.include_model_budget_conflict,+ projection == Some(true)+ );+ let wire = serde_json::to_value(lookup).unwrap();+ assert_eq!(wire["accepted_digest"], digest);+ if projection == Some(true) {+ assert_eq!(wire["include_model_budget_conflict"], true);+ } else {+ assert!(wire.get("include_model_budget_conflict").is_none());+ }+ }+ }+}diff --git a/crates/application-api/src/generated.rs b/crates/application-api/src/generated.rsindex ea8844d7..9d65b0b8 100644--- a/crates/application-api/src/generated.rs+++ b/crates/application-api/src/generated.rs@@ -123,7 +123,42 @@ fn machine_envelope_v2_schema() -> Value {"message_key": { "type": "string", "minLength": 1 },"retryable": { "type": "boolean" },"operation_id": { "type": "string", "minLength": 1 },- "details_schema": { "type": "string", "minLength": 1 }+ "details_schema": { "type": "string", "minLength": 1 },+ "model_budget_conflict": { "$ref": "#/$defs/model_budget_conflict" }+ }+ },+ "model_token_budget": {+ "type": "object", "additionalProperties": false,+ "required": ["context_window_tokens", "max_output_tokens"],+ "properties": {+ "context_window_tokens": { "type": "integer", "minimum": 1 },+ "max_output_tokens": { "type": "integer", "minimum": 1 }+ }+ },+ "model_budget_blocker": {+ "type": "object", "additionalProperties": false,+ "required": ["agent_kind", "context_id", "plan_id", "model_alias", "reason", "declared", "proposed"],+ "properties": {+ "agent_kind": { "enum": ["qoder", "pi", "deepseek_harness"] },+ "context_id": { "type": "string", "pattern": "^agent-context/[A-Za-z0-9/_:-]{1,242}$" },+ "plan_id": { "type": "string", "minLength": 1, "maxLength": 256 },+ "model_alias": { "type": "string", "pattern": "^(hiroute/[0-9a-f]{16}|[a-z0-9][a-z0-9._-]{0,63})$" },+ "reason": { "enum": ["capacity_reduced", "plan_missing", "budget_unavailable"] },+ "declared": { "$ref": "#/$defs/model_token_budget" },+ "proposed": { "oneOf": [{ "$ref": "#/$defs/model_token_budget" }, { "type": "null" }] }+ },+ "allOf": [{+ "if": { "properties": { "reason": { "const": "capacity_reduced" } } },+ "then": { "properties": { "proposed": { "$ref": "#/$defs/model_token_budget" } } },+ "else": { "properties": { "proposed": { "type": "null" } } }+ }]+ },+ "model_budget_conflict": {+ "type": "object", "additionalProperties": false,+ "required": ["schema", "blockers"],+ "properties": {+ "schema": { "const": "hiroute.agent-model-budget-conflict/v1" },+ "blockers": { "type": "array", "minItems": 1, "items": { "$ref": "#/$defs/model_budget_blocker" } }}}}diff --git a/crates/application-api/src/plan_authoring.rs b/crates/application-api/src/plan_authoring.rsindex d72c58b0..5d2d6598 100644--- a/crates/application-api/src/plan_authoring.rs+++ b/crates/application-api/src/plan_authoring.rs@@ -83,6 +83,13 @@ pub struct PlanContentApplyRequestV2 {pub accept_digest: CanonicalDigest,pub expected_revisions: RevisionSetV1,pub idempotency_key: String,+ /// Opt-in diagnostic projection; never part of Plan identity or write authorization.+ #[serde(default, skip_serializing_if = "is_false")]+ pub include_model_budget_conflict: bool,+}++fn is_false(value: &bool) -> bool {+ !value}/// Ordinary publication confirms the exact editing intent and observed resource versions.diff --git a/crates/application-api/src/protocol.rs b/crates/application-api/src/protocol.rsindex eec59e71..7f7fc446 100644--- a/crates/application-api/src/protocol.rs+++ b/crates/application-api/src/protocol.rs@@ -675,6 +675,8 @@ pub struct ErrorV1 {#[serde(skip_serializing_if = "Option::is_none")]pub operation_id: Option<String>,pub details_schema: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub model_budget_conflict: Option<Box<hiroute_domain::AgentModelBudgetConflictV1>>,}impl ErrorV1 {@@ -690,6 +692,7 @@ impl ErrorV1 {retryable,operation_id: None,details_schema: "hiroute.error-details/none-v1".to_owned(),+ model_budget_conflict: None,}}}diff --git a/crates/application/src/client_access.rs b/crates/application/src/client_access.rsindex 7f489292..1f3a1a58 100644--- a/crates/application/src/client_access.rs+++ b/crates/application/src/client_access.rs@@ -57,6 +57,11 @@ pub(crate) fn dispatch(.as_ref().is_none_or(|op| op.accepted_digest == lookup.accepted_digest);let operation = operation.map(|op| ClientOperationViewV1 {+ model_budget_conflict: if lookup.include_model_budget_conflict {+ op.model_budget_conflict+ } else {+ None+ },operation_id: op.operation_id.to_string(),state: op.state.as_str().into(),sequence: op.generation,diff --git a/crates/application/src/control_plane/plan_content.rs b/crates/application/src/control_plane/plan_content.rsindex 1661f852..865b34f3 100644--- a/crates/application/src/control_plane/plan_content.rs+++ b/crates/application/src/control_plane/plan_content.rs@@ -66,6 +66,7 @@ pub(super) fn dispatch_apply(if payload.idempotency_key.is_empty() {return failed(ErrorCode::InvalidArguments, request.request_id);}+ let include_model_budget_conflict = payload.include_model_budget_conflict;if let Some(replay) = replay_apply(ports.control.as_ref(),PrincipalKind::InteractiveUser,@@ -120,7 +121,7 @@ pub(super) fn dispatch_apply(};match mutation.apply_local_prepared_change(prepared) {Ok(operation) => super::accepted_apply(operation, request.request_id),- Err(error) => failed(error.error_code(), request.request_id),+ Err(error) => error.envelope(request.request_id, include_model_budget_conflict),}}diff --git a/crates/application/src/lib.rs b/crates/application/src/lib.rsindex e82d1941..610095a2 100644--- a/crates/application/src/lib.rs+++ b/crates/application/src/lib.rs@@ -268,7 +268,7 @@ impl ApplicationService {}match mutation.preview_change(preview) {Ok(result) => succeeded(result, request.request_id),- Err(error) => failed(error.error_code(), request.request_id),+ Err(error) => error.envelope(request.request_id, false),}}@@ -295,7 +295,7 @@ impl ApplicationService {}match mutation.apply_local_change(apply) {Ok(operation) => accepted_apply(operation, request.request_id),- Err(error) => failed(error.error_code(), request.request_id),+ Err(error) => error.envelope(request.request_id, false),}}diff --git a/crates/application/src/operations/mod.rs b/crates/application/src/operations/mod.rsindex 8568fc13..18d959a9 100644--- a/crates/application/src/operations/mod.rs+++ b/crates/application/src/operations/mod.rs@@ -295,6 +295,15 @@ wherecontinue;}if let Err(error) = self.run_step(&mut operation, kind) {+ if let Some(conflict) = error.model_budget_conflict() {+ operation.step_mut(kind).terminal_result = Some(+ serde_json::to_string(conflict).expect("safe capacity facts serialize"),+ );+ operation.safe_error_code = Some(error.safe_code().to_owned());+ // Publication abort checks the durable journal's exact ownership. Persist+ // the diagnostic first so rollback observes the same operation snapshot.+ self.control.save_operation(&mut operation)?;+ }if let Some(receipt) = settings_service_receipt(&operation)&& matches!(settings_service_completion_digest(@@ -568,7 +577,9 @@ where}}}- operation.safe_error_code = Some(safe_error_code.to_owned());+ if safe_error_code != "RECOVERY_ROLLBACK" || operation.model_budget_conflict().is_none() {+ operation.safe_error_code = Some(safe_error_code.to_owned());+ }if operation.state != OperationState::RollingBack {operation.transition(OperationState::RollingBack)?;}@@ -608,7 +619,16 @@ whereOk(()) => {let step = operation.step_mut(kind);step.status = OperationStepStatus::Compensated;- step.terminal_result = Some("compensated".to_owned());+ // Keep the frozen rejection through compensation and restart. It has no+ // effect ownership or replay authority; status projection validates its schema.+ if step+ .terminal_result+ .as_deref()+ .and_then(hiroute_domain::AgentModelBudgetConflictV1::parse)+ .is_none()+ {+ step.terminal_result = Some("compensated".to_owned());+ }}Err(_) => {uncertain = true;@@ -956,7 +976,44 @@ pub enum TransactionError {}impl TransactionError {+ pub fn model_budget_conflict(&self) -> Option<&hiroute_domain::AgentModelBudgetConflictV1> {+ match self {+ Self::Port(error) | Self::Preparation(ChangePreparationError::Port(error))+ if error.code == hiroute_domain::PortErrorCode::Conflict =>+ {+ error+ .model_budget_conflict+ .as_deref()+ .filter(|value| value.is_valid())+ }+ _ => None,+ }+ }++ pub(crate) fn envelope(+ &self,+ request_id: String,+ include_model_budget_conflict: bool,+ ) -> hiroute_application_api::MachineEnvelopeV2<serde_json::Value> {+ let mut error = hiroute_application_api::ErrorV1::new(self.error_code());+ if include_model_budget_conflict && let Some(conflict) = self.model_budget_conflict() {+ error.details_schema = hiroute_domain::AGENT_MODEL_BUDGET_CONFLICT_SCHEMA_V1.into();+ // Released readers deserialize data as the command's success DTO. Keep failures+ // data-free; ErrorV1 supports additive metadata without changing that DTO.+ error.model_budget_conflict = Some(Box::new(conflict.clone()));+ }+ hiroute_application_api::MachineEnvelopeV2::failed(error, Some(request_id))+ }+pub fn error_code(&self) -> ErrorCode {+ if let Some(conflict) = self.model_budget_conflict() {+ return if conflict.safe_code() == "QODER_MODEL_BUDGET_CONFLICT" {+ ErrorCode::QoderModelBudgetConflict+ } else {+ // Preserve the released closed ErrorCode enum for strict older callers.+ ErrorCode::RevisionConflict+ };+ }match self {Self::Port(error) | Self::Preparation(ChangePreparationError::Port(error))if error.code == hiroute_domain::PortErrorCode::Conflict@@ -998,6 +1055,9 @@ impl TransactionError {}fn safe_code(&self) -> &'static str {+ if let Some(conflict) = self.model_budget_conflict() {+ return conflict.safe_code();+ }match self {Self::Port(error) | Self::Preparation(ChangePreparationError::Port(error))if error.code == hiroute_domain::PortErrorCode::Conflictdiff --git a/crates/application/src/operations/tests/mod.rs b/crates/application/src/operations/tests/mod.rsindex facdf822..0c21ceb7 100644--- a/crates/application/src/operations/tests/mod.rs+++ b/crates/application/src/operations/tests/mod.rs@@ -1038,3 +1038,100 @@ fn qoder_budget_conflict_has_the_same_public_and_terminal_error_code() {assert_eq!(error.safe_code(), "ADAPTER_FAILURE");}}++#[test]+fn model_budget_error_keeps_success_data_absent_for_typed_callers() {+ use hiroute_domain::{+ AgentKindV1, AgentModelBudgetBlockerV1, AgentModelBudgetConflictV1,+ AgentModelBudgetReasonV1, AgentModelTokenBudgetV1,+ };+ let conflict = AgentModelBudgetConflictV1::new(vec![AgentModelBudgetBlockerV1 {+ agent_kind: AgentKindV1::Pi,+ context_id: "agent-context/pi/sha256:abc".into(),+ plan_id: hiroute_domain::AgentPlanId::parse("plan/free").unwrap(),+ model_alias: hiroute_domain::ModelAlias::parse("free.plan").unwrap(),+ reason: AgentModelBudgetReasonV1::CapacityReduced,+ declared: AgentModelTokenBudgetV1 {+ context_window_tokens: 262_144,+ max_output_tokens: 235_929,+ },+ proposed: Some(AgentModelTokenBudgetV1 {+ context_window_tokens: 262_144,+ max_output_tokens: 131_072,+ }),+ }]);+ assert!(conflict.is_valid());+ let error = TransactionError::Port(+ PortError::new(PortErrorCode::Conflict, "agent.model.budget.conflict")+ .with_model_budget_conflict(conflict.clone()),+ );+ let legacy = serde_json::to_value(error.envelope("legacy-budget-error".into(), false)).unwrap();+ assert!(legacy["error"].get("model_budget_conflict").is_none());+ assert_eq!(+ legacy["error"]["details_schema"],+ "hiroute.error-details/none-v1"+ );+ let wire = serde_json::to_value(error.envelope("budget-error".into(), true)).unwrap();+ assert!(wire.get("data").is_none());+ assert_eq!(wire["error"]["code"], "REVISION_CONFLICT");+ let schema: Value = serde_json::from_str(+ &hiroute_application_api::generated_contract_files()+ .into_iter()+ .find(|file| file.relative_path == "machine-envelope.v2.schema.json")+ .unwrap()+ .contents,+ )+ .unwrap();+ // Actual serialized errors must fit every closed object in the published schema.+ // This catches adding a Rust field while forgetting the unique schema producer.+ for (object, definition) in [+ (&wire["error"], "error"),+ (+ &wire["error"]["model_budget_conflict"],+ "model_budget_conflict",+ ),+ (+ &wire["error"]["model_budget_conflict"]["blockers"][0],+ "model_budget_blocker",+ ),+ (+ &wire["error"]["model_budget_conflict"]["blockers"][0]["declared"],+ "model_token_budget",+ ),+ (+ &wire["error"]["model_budget_conflict"]["blockers"][0]["proposed"],+ "model_token_budget",+ ),+ ] {+ let definition = &schema["$defs"][definition];+ assert_eq!(definition["additionalProperties"], false);+ for key in object.as_object().unwrap().keys() {+ assert!(+ definition["properties"].get(key).is_some(),+ "undeclared wire field {key}"+ );+ }+ for key in definition["required"].as_array().unwrap() {+ assert!(object.get(key.as_str().unwrap()).is_some());+ }+ }+ // Released 0.3.1 ErrorV1 accepts additive fields; a command's strict success DTO+ // must never deserialize error details. This fails if budget facts move into data.+ let typed: hiroute_application_api::MachineEnvelopeV2<+ hiroute_application_api::AgentPlanStatusV2,+ > = serde_json::from_value(wire.clone()).unwrap();+ assert!(typed.data.is_none());+ assert_eq!(+ typed.error.unwrap().model_budget_conflict,+ Some(Box::new(conflict))+ );+ let mut old = wire;+ old["error"]+ .as_object_mut()+ .unwrap()+ .remove("model_budget_conflict");+ let typed: hiroute_application_api::MachineEnvelopeV2<+ hiroute_application_api::AgentPlanStatusV2,+ > = serde_json::from_value(old).unwrap();+ assert!(typed.error.unwrap().model_budget_conflict.is_none());+}diff --git a/crates/cli/tests/request_input.rs b/crates/cli/tests/request_input.rsindex f565349a..d88e8e91 100644--- a/crates/cli/tests/request_input.rs+++ b/crates/cli/tests/request_input.rs@@ -246,6 +246,72 @@ fn conflicting_missing_and_nonregular_request_files_are_usage_errors() {}}+#[test]+fn budget_detail_opt_in_preserves_legacy_inputs_across_both_sources() {+ let root = tempfile::tempdir().unwrap();+ let file = root.path().join("budget-projection.json");+ let digest = format!("sha256:{}", "0".repeat(64));+ let lookup = json!({+ "principal_kind":"interactive_user", "operation_kind":"change",+ "idempotency_key":"test", "accepted_digest":digest+ });+ let publication = json!({+ "change":{+ "schema":"hiroute.plan-content-change/v2",+ "target":{"intent":"create","creation_key":"budget-compatibility"},+ "editor":{+ "schema":"hiroute.plan-editor/v2", "display_name":"Budget compatibility",+ "purpose":"Check request projection", "mode":"fixed_model", "candidates":[],+ "smart":{+ "economy":[], "primary":[],+ "judgment":hiroute_domain::JudgmentSettingsV1::default(),+ "reselect_on_user_message":false, "classifier":{"kind":"local_rules"},+ "complex_keywords":[]+ },+ "free":{"candidates":[],"primary":[],"primary_fallback":false},+ "delegation_enabled":false,+ "requirements":hiroute_domain::CapabilityRequirementsV1::default(),+ "limits":{"maximum_attempts":1,"request_timeout_ms":1000,"attempt_timeout_ms":1000}+ },+ "consumed_draft":null+ },+ "accept_digest":digest, "expected_revisions":{"target":0},+ "idempotency_key":"budget-compatibility"+ });+ for (path, original) in [+ (vec!["operations", "find"], lookup),+ (+ vec!["operations", "find"],+ json!(["interactive_user", "change", "test", digest]),+ ),+ (vec!["routing", "apply"], publication),+ ] {+ for projection in [None, Some(false), Some(true)] {+ let mut request = original.clone();+ if let Some(projection) = projection {+ if let Some(fields) = request.as_array_mut() {+ fields.push(json!(projection));+ } else {+ request["include_model_budget_conflict"] = json!(projection);+ }+ }+ let bytes = serde_json::to_vec(&request).unwrap();+ std::fs::write(&file, &bytes).unwrap();+ for source in [+ vec!["--request-file", file.to_str().unwrap()],+ vec!["--request-stdin"],+ ] {+ let mut args = path.clone();+ args.extend(source);+ let (exit, envelope) = invoke(root.path(), &args, &bytes);+ // A syntactically valid request reaches transport; no daemon or grant is created.+ assert_eq!(exit, 6, "{args:?} {request}: {envelope}");+ assert_eq!(envelope["error"]["code"], "DAEMON_UNAVAILABLE");+ }+ }+ }+}+#[test]fn existing_per_command_byte_limits_apply_to_files_and_stdin() {let root = tempfile::tempdir().unwrap();diff --git a/crates/daemon/src/control/runtime/additional_model_budget.rs b/crates/daemon/src/control/runtime/additional_model_budget.rsindex f11395a9..54270c60 100644--- a/crates/daemon/src/control/runtime/additional_model_budget.rs+++ b/crates/daemon/src/control/runtime/additional_model_budget.rs@@ -4,9 +4,10 @@ use hiroute_application::agent_connection::{AdditionalModelFileAction, settings_additional_model_file_for_operation,};use hiroute_domain::{- AgentAccessGrantRefV1, AgentModelRouteV2, ControlRepositoryPort, OperationStepKind, PortError,- PortErrorCode, PortResult, PublicationRecordV1, SecretStorePort, WorkspaceId,- is_agent_access_grant_effect,+ AgentAccessGrantRefV1, AgentModelBudgetBlockerV1, AgentModelBudgetConflictV1,+ AgentModelBudgetReasonV1, AgentModelRouteV2, AgentModelTokenBudgetV1, ControlRepositoryPort,+ ModelAlias, OperationStepKind, PortError, PortErrorCode, PortResult, PublicationRecordV1,+ SecretStorePort, WorkspaceId, is_agent_access_grant_effect,};impl LocalControlAdapter {@@ -20,13 +21,14 @@ impl LocalControlAdapter {}/// Run at admission and again before sealing Install. A published smaller budget would- /// otherwise leave Qoder sending requests under a larger persisted native declaration.+ /// otherwise leave installed clients sending requests under a larger persisted native declaration.pub(super) fn validate_additional_installed_model_budgets(&self,record: &PublicationRecordV1,) -> PortResult<()> {let next = record.verify().map_err(|_| invalid())?;let stores = self.stores_lock()?;+ let mut blockers = Vec::new();for operation in stores.control().succeeded_agent_operations_for_kind(&WorkspaceId::default(),"ApplyAgentConnectionChange",@@ -71,31 +73,69 @@ impl LocalControlAdapter {else {return Err(invalid());};- let plan = next+ let declared = AgentModelTokenBudgetV1 {+ context_window_tokens: model.context_window_tokens,+ max_output_tokens: model.max_output_tokens,+ };+ let projection = next.plans.iter().find(|plan| plan.agent_plan_id() == plan_id)- .ok_or_else(shrinking)?- .clone()- .into_current()- .map_err(|_| shrinking())?;- let budget = (if matches!(- kind,- hiroute_domain::AgentKindV1::Pi | hiroute_domain::AgentKindV1::DeepseekHarness- ) {- hiroute_integrations::pi_plan_token_budget(&plan.body.materialized)- } else {- hiroute_integrations::qoder_plan_token_budget(&plan.body.materialized)- })- .map_err(|_| shrinking())?;- if budget.context_window_tokens < model.context_window_tokens- || budget.max_output_tokens < model.max_output_tokens- {- return Err(shrinking());- }+ .ok_or(AgentModelBudgetReasonV1::PlanMissing)+ .and_then(|plan| {+ let plan = plan+ .clone()+ .into_current()+ .map_err(|_| AgentModelBudgetReasonV1::BudgetUnavailable)?;+ let budget = if matches!(+ kind,+ hiroute_domain::AgentKindV1::Pi+ | hiroute_domain::AgentKindV1::DeepseekHarness+ ) {+ hiroute_integrations::pi_plan_token_budget(&plan.body.materialized)+ } else {+ hiroute_integrations::qoder_plan_token_budget(&plan.body.materialized)+ }+ .map_err(|_| AgentModelBudgetReasonV1::BudgetUnavailable)?;+ Ok(AgentModelTokenBudgetV1 {+ context_window_tokens: budget.context_window_tokens,+ max_output_tokens: budget.max_output_tokens,+ })+ });+ let (reason, proposed) = match projection {+ Ok(proposed)+ if proposed.context_window_tokens >= declared.context_window_tokens+ && proposed.max_output_tokens >= declared.max_output_tokens =>+ {+ continue;+ }+ Ok(proposed) => (AgentModelBudgetReasonV1::CapacityReduced, Some(proposed)),+ Err(reason) => (reason, None),+ };+ blockers.push(AgentModelBudgetBlockerV1 {+ agent_kind: kind,+ context_id: payload.context_id.clone(),+ plan_id: plan_id.clone(),+ model_alias: ModelAlias::parse(model.alias).map_err(|_| invalid())?,+ reason,+ declared,+ proposed,+ });}}- Ok(())+ if blockers.is_empty() {+ return Ok(());+ }+ let conflict = AgentModelBudgetConflictV1::new(blockers);+ if !conflict.is_valid() {+ return Err(invalid());+ }+ let context = if conflict.safe_code() == "QODER_MODEL_BUDGET_CONFLICT" {+ "qoder.model.budget.shrink"+ } else {+ "agent.model.budget.conflict"+ };+ Err(PortError::new(PortErrorCode::Conflict, context).with_model_budget_conflict(conflict))}}@@ -132,6 +172,3 @@ pub(super) fn guard_pending_model_change(fn invalid() -> PortError {PortError::new(PortErrorCode::InvalidData, "qoder.model.budget.binding")}-fn shrinking() -> PortError {- PortError::new(PortErrorCode::Conflict, "qoder.model.budget.shrink")-}diff --git a/crates/daemon/src/control/runtime/settings_entry_model_budget_tests.rs b/crates/daemon/src/control/runtime/settings_entry_model_budget_tests.rsnew file mode 100644index 00000000..93744c7e--- /dev/null+++ b/crates/daemon/src/control/runtime/settings_entry_model_budget_tests.rs@@ -0,0 +1,333 @@+//! Real stores and transaction entrypoints, with explicit native-capability fixtures.+use super::*;+use hiroute_domain::{AgentModelBudgetConflictV1, AgentModelBudgetReasonV1};++fn configure(fixture: &QoderFixture, agent: &str, mode: &str, plan: &str, key: &str) {+ let context = fixture+ .runtime+ .adapter+ .settings_context_for_agent(agent)+ .unwrap();+ apply(+ &fixture.service,+ &fixture.runtime,+ json!({+ "schema_version":{"major":2,"minor":0},"context_id":context,+ "model":{"intent":"configure","settings":{"mode":mode,"allowed_plan_ids":[plan]}}+ }),+ key,+ );+}++fn status(fixture: &QoderFixture, agent: &str) -> serde_json::Value {+ let context = fixture+ .runtime+ .adapter+ .settings_context_for_agent(agent)+ .unwrap();+ fixture+ .service+ .dispatch_wire(request(+ "GetAgentConnectionStatus",+ json!({+ "schema_version":{"major":2,"minor":0},"context_id":context+ }),+ None,+ ))+ .data+ .unwrap()+}++fn restore(fixture: &QoderFixture, agent: &str, key: &str) {+ let state = status(fixture, agent);+ let context = fixture+ .runtime+ .adapter+ .settings_context_for_agent(agent)+ .unwrap();+ apply(+ &fixture.service,+ &fixture.runtime,+ json!({+ "schema_version":{"major":2,"minor":0},"context_id":context,+ "model":{"intent":"restore","restore_point_ref":state["restore_point_ref"]}+ }),+ key,+ );+ assert_eq!(status(fixture, agent)["state"], "not_configured");+}++fn rejected(+ fixture: &QoderFixture,+ alias: &str,+) -> (OperationV1, PublicationRecordV1, AgentModelBudgetConflictV1) {+ let (operation, record) = models::budget_change_operation(fixture, Some(alias.into()), true);+ let error = fixture+ .runtime+ .adapter+ .validate_external_admission(&operation.plan.external()[0])+ .unwrap_err();+ assert_eq!(error.context, "agent.model.budget.conflict");+ let conflict = *error.model_budget_conflict.unwrap();+ assert!(conflict.is_valid());+ for blocker in &conflict.blockers {+ assert_ne!(blocker.agent_kind, AgentKindV1::Qoder);+ assert_eq!(blocker.model_alias.as_str(), alias);+ assert_eq!(blocker.reason, AgentModelBudgetReasonV1::CapacityReduced);+ let next = blocker.proposed.unwrap();+ assert_eq!(+ next.context_window_tokens,+ blocker.declared.context_window_tokens+ );+ assert_eq!(+ next.max_output_tokens + 1,+ blocker.declared.max_output_tokens+ );+ }+ (operation, record, conflict)+}++#[test]+fn output_shrink_names_all_live_consumers_and_preserves_checkpoint_details_after_reopen() {+ let tools = crate::test_support::private_tempdir();+ let node = tools.path().join("node");+ private_file(&node, b"#!/bin/sh\nif [ \"$1\" = --version ]; then echo v22.19.0; elif [ \"$2\" = --check ] && [ \"$4\" = models ]; then echo hiroute.pi-sdk-capability/v1:ok; else exit 97; fi\n");+ fs::set_permissions(&node, fs::Permissions::from_mode(0o700)).unwrap();+ let path =+ std::env::join_paths([tools.path(), Path::new("/usr/bin"), Path::new("/bin")]).unwrap();+ if crate::test_support::isolated_agent_home_with_path(+ "control::runtime::native_model::tests::settings_entry_tests::qoder::budget_tests::output_shrink_names_all_live_consumers_and_preserves_checkpoint_details_after_reopen",+ &path,+ ) {+ return;+ }+ let fixture = QoderFixture::with_all_models();+ let published = fixture+ .runtime+ .adapter+ .stores_lock()+ .unwrap()+ .control()+ .active_publication(&WorkspaceId::default())+ .unwrap()+ .unwrap()+ .verify()+ .unwrap();+ let plans: Vec<_> = published+ .published_agent_plans()+ .unwrap()+ .into_iter()+ .filter(|plan| {+ plan.active+ && plan+ .supported_ingress+ .contains(&AgentIngressProtocolV1::Responses)+ })+ .collect();+ assert!(plans.len() >= 2);+ let free = plans[0].agent_plan_id.as_str();+ let other = plans[1].agent_plan_id.as_str();+ let alias = published+ .plans+ .iter()+ .find(|plan| plan.agent_plan_id().as_str() == free)+ .unwrap()+ .model_alias()+ .as_str()+ .to_owned();+ configure(+ &fixture,+ "agent_qoder_default",+ "qoder_additional",+ other,+ "budget-unrelated-qoder",+ );+ configure(+ &fixture,+ "agent_pi_default",+ "pi_additional",+ free,+ "budget-pi",+ );+ configure(+ &fixture,+ "agent_dsh_default",+ "dsh_additional",+ free,+ "budget-dsh",+ );+ // A new generation supersedes its historical declaration, without deleting history.+ configure(+ &fixture,+ "agent_pi_default",+ "pi_additional",+ free,+ "budget-pi-next-generation",+ );+ let (_, _, before) = rejected(&fixture, &alias);+ assert_eq!(+ before+ .blockers+ .iter()+ .map(|b| b.agent_kind)+ .collect::<Vec<_>>(),+ vec![AgentKindV1::Pi, AgentKindV1::DeepseekHarness]+ );+ restore(+ &fixture,+ "agent_qoder_default",+ "budget-stop-unrelated-qoder",+ );+ let (operation, _, after) = rejected(&fixture, &alias);+ assert_eq!(before, after);+ let native_before =+ ["agent_pi_default", "agent_dsh_default"].map(|agent| status(&fixture, agent));+ let published_before = fixture+ .runtime+ .adapter+ .stores_lock()+ .unwrap()+ .control()+ .active_publication(&WorkspaceId::default())+ .unwrap();++ // Inject only the accepted journal to independently exercise the Install checkpoint.+ fixture+ .runtime+ .adapter+ .stores_lock()+ .unwrap()+ .control()+ .begin_local_operation(&operation)+ .unwrap();+ let adapter = fixture.runtime.adapter.as_ref();+ let rolled_back = hiroute_application::TransactionCoordinator::new(+ adapter,+ adapter,+ adapter,+ adapter,+ adapter,+ &adapter.admission,+ )+ .run(&operation.operation_id)+ .unwrap();+ assert_eq!(rolled_back.state, OperationState::RolledBack);+ assert_eq!(+ rolled_back.safe_error_code.as_deref(),+ Some("AGENT_MODEL_BUDGET_CONFLICT")+ );+ assert_eq!(rolled_back.model_budget_conflict(), Some(after.clone()));+ assert_eq!(+ ["agent_pi_default", "agent_dsh_default"].map(|agent| status(&fixture, agent)),+ native_before+ );+ assert_eq!(+ fixture+ .runtime+ .adapter+ .stores_lock()+ .unwrap()+ .control()+ .active_publication(&WorkspaceId::default())+ .unwrap(),+ published_before+ );+ // Cold decoding retains the frozen diagnostic and does not create new authorization.+ let reopened = fixture+ .runtime+ .adapter+ .stores_lock()+ .unwrap()+ .control()+ .load_operation(&operation.operation_id)+ .unwrap()+ .unwrap();+ assert_eq!(reopened.model_budget_conflict(), Some(after.clone()));+ let lookup = json!({"principal_kind":"interactive_user","operation_kind":"ApplyAgentPlanChange",+ "idempotency_key":operation.idempotency.key,"accepted_digest":operation.accepted_digest});+ let legacy =+ fixture+ .service+ .dispatch_wire(request("FindOperationByIdempotency", lookup.clone(), None));+ assert!(legacy.error.is_none(), "{legacy:?}");+ assert!(+ legacy.data.as_ref().unwrap()["operation"]+ .get("model_budget_conflict")+ .is_none()+ );+ let mut detailed = lookup;+ detailed["include_model_budget_conflict"] = json!(true);+ let response =+ fixture+ .service+ .dispatch_wire(request("FindOperationByIdempotency", detailed, None));+ assert_eq!(+ response.data.unwrap()["operation"]["model_budget_conflict"],+ serde_json::to_value(&after).unwrap()+ );++ restore(&fixture, "agent_pi_default", "budget-stop-pi");+ let (_, _, remaining) = rejected(&fixture, &alias);+ assert_eq!(remaining.blockers.len(), 1);+ assert_eq!(+ remaining.blockers[0].agent_kind,+ AgentKindV1::DeepseekHarness+ );+ restore(&fixture, "agent_dsh_default", "budget-stop-dsh");+ let (operation, _) = models::budget_change_operation(&fixture, Some(alias), true);+ fixture+ .runtime+ .adapter+ .validate_external_admission(&operation.plan.external()[0])+ .unwrap();+ let scope = hiroute_domain::IdempotencyScopeV1::new(+ "interactive-user",+ "ApplyAgentPlanChange",+ "budget-after-all-consumers-removed",+ )+ .unwrap();+ let digest = CanonicalDigest::of_bytes(b"budget-after-all-consumers-removed");+ let final_operation = OperationV1::new(+ OperationId::derive(&WorkspaceId::default(), &scope, &digest),+ WorkspaceId::default(),+ scope,+ digest.clone(),+ digest,+ operation.expected_revisions.clone(),+ (*operation.plan).clone(),+ )+ .unwrap();+ fixture+ .runtime+ .adapter+ .stores_lock()+ .unwrap()+ .control()+ .begin_local_operation(&final_operation)+ .unwrap();+ let installed = hiroute_application::TransactionCoordinator::new(+ adapter,+ adapter,+ adapter,+ adapter,+ adapter,+ &adapter.admission,+ )+ .run(&final_operation.operation_id)+ .unwrap();+ assert_eq!(installed.state, OperationState::Succeeded, "{installed:#?}");+ assert!(+ !fixture+ .runtime+ .adapter+ .stores_lock()+ .unwrap()+ .control()+ .succeeded_agent_operations_for_kind(+ &WorkspaceId::default(),+ "ApplyAgentConnectionChange"+ )+ .unwrap()+ .is_empty()+ );+}diff --git a/crates/daemon/src/control/runtime/settings_entry_qoder_model_tests.rs b/crates/daemon/src/control/runtime/settings_entry_qoder_model_tests.rsindex 1b1106e2..b430c736 100644--- a/crates/daemon/src/control/runtime/settings_entry_qoder_model_tests.rs+++ b/crates/daemon/src/control/runtime/settings_entry_qoder_model_tests.rs@@ -385,6 +385,14 @@ fn qoder_restore_rejects_native_default_reference_then_preserves_unrelated_edits}fn smaller_budget_operation(fixture: &QoderFixture) -> (OperationV1, PublicationRecordV1) {+ budget_change_operation(fixture, None, false)+}++pub(super) fn budget_change_operation(+ fixture: &QoderFixture,+ selected_alias: Option<String>,+ output_only: bool,+) -> (OperationV1, PublicationRecordV1) {let stores = fixture.runtime.adapter.stores_lock().unwrap();let current = stores.control()@@ -392,17 +400,18 @@ fn smaller_budget_operation(fixture: &QoderFixture) -> (OperationV1, Publication.unwrap().unwrap();let mut next = current.verify().unwrap();- let alias = next- .grants- .iter()- .find(|grant| grant.model_grant.protocol == AgentIngressProtocolV1::Responses)- .unwrap()- .model_grant- .routes- .keys()- .next()- .unwrap()- .clone();+ let alias = selected_alias.unwrap_or_else(|| {+ next.grants+ .iter()+ .find(|grant| grant.model_grant.protocol == AgentIngressProtocolV1::Responses)+ .unwrap()+ .model_grant+ .routes+ .keys()+ .next()+ .unwrap()+ .clone()+ });let index = next.plans.iter()@@ -445,8 +454,25 @@ fn smaller_budget_operation(fixture: &QoderFixture) -> (OperationV1, Publication.clone();let mut body = (*next.plans[index].body).clone();let budget = hiroute_integrations::qoder_plan_token_budget(&body.materialized).unwrap();- body.materialized.attempt_owned.limits.context_window_tokens =- Some(budget.context_window_tokens - 1);+ if output_only {+ for candidate in body+ .materialized+ .attempt_owned+ .groups+ .iter_mut()+ .flat_map(|group| &mut group.candidates)+ {+ for profile in &mut candidate.protocol_profiles {+ profile.capability.context.max_output_tokens =+ hiroute_domain::GatewayCriticalFactV1::Exact(budget.max_output_tokens - 1);+ }+ candidate.protocol_profile_digest =+ hiroute_domain::CanonicalDigest::of(&candidate.protocol_profiles).unwrap();+ }+ } else {+ body.materialized.attempt_owned.limits.context_window_tokens =+ Some(budget.context_window_tokens - 1);+ }body.agent_plan_revision += 1;body.materialized_route_digest = body.materialized.route_digest().unwrap();let compiled = hiroute_domain::CompiledAgentPlanV1::seal_current(body).unwrap();diff --git a/crates/daemon/src/control/runtime/settings_entry_qoder_tests.rs b/crates/daemon/src/control/runtime/settings_entry_qoder_tests.rsindex 6632883c..7a1e9b29 100644--- a/crates/daemon/src/control/runtime/settings_entry_qoder_tests.rs+++ b/crates/daemon/src/control/runtime/settings_entry_qoder_tests.rs@@ -25,6 +25,14 @@ impl QoderFixture {}fn with_kind(models: bool, kind: AgentKindV1) -> Self {+ Self::with_agents(models, kind, false)+ }++ fn with_all_models() -> Self {+ Self::with_agents(true, AgentKindV1::Qoder, true)+ }++ fn with_agents(models: bool, kind: AgentKindV1, all: bool) -> Self {let pi = kind == AgentKindV1::Pi;let root = tempfile::tempdir().unwrap();fs::set_permissions(root.path(), fs::Permissions::from_mode(0o700)).unwrap();@@ -66,6 +74,28 @@ impl QoderFixture {} else {layout.qoder_executable = root.path().join("missing-qoder");}+ if all {+ let package = root.path().join("all-pi-package");+ private_file(&package.join("package.json"), br#"{"name":"@earendil-works/pi-coding-agent","version":"1.0.2","bin":{"pi":"dist/bundle/cli.js"}}"#);+ private_file(&package.join("dist/index.js"), b"fixture SDK location only");+ private_file(&package.join("dist/bundle/cli.js"), b"#!/bin/sh\nexit 97\n");+ fs::set_permissions(+ package.join("dist/bundle/cli.js"),+ fs::Permissions::from_mode(0o700),+ )+ .unwrap();+ layout.pi_executable = package.join("dist/bundle/cli.js");+ layout.pi_config_root = home.join("budget-pi");+ private_file(+ &layout.pi_config_root.join("settings.json"),+ br#"{"defaultProvider":"native","defaultModel":"default"}"#,+ );+ layout.dsh_executable = root.path().join("dsh-fixture");+ private_file(&layout.dsh_executable, b"#!/bin/sh\nif [ \"$1\" = --version ]; then echo 'DSH fixture'; else printf '%s\\n' '- id: llm-pi-ai' '- id: skill' '- id: skill-filesystem' '- id: tool-skill' '- id: tool-fs' '- id: tool-bash'; fi\n");+ fs::set_permissions(&layout.dsh_executable, fs::Permissions::from_mode(0o700)).unwrap();+ layout.dsh_config_root = home.join("budget-dsh");+ private_file(&layout.dsh_config_root.join("cordis.patch.yml"), b"[]\n");+ }let registry = serde_json::from_slice(include_bytes!("../../../../../assets/connector-registry/current/registry-seed.json"))@@ -79,6 +109,10 @@ impl QoderFixture {ClaudeRegistrationIndexV1::from_verified_model_data(®istry, &model_data.data).unwrap(),);+ if all {+ private_file(&scanner.pi_user_models_target(), br#"{"providers":{}}"#);+ private_file(&scanner.dsh_user_models_target(), b"[]\n");+ }let native_config = if pi {scanner.pi_user_models_target()} else {@@ -663,3 +697,6 @@ fn qoder_borrowed_skill_restore_releases_only_the_reference_after_user_edits() {#[path = "settings_entry_qoder_model_tests.rs"]mod models;++#[path = "settings_entry_model_budget_tests.rs"]+mod budget_tests;diff --git a/crates/domain/src/agents/mod.rs b/crates/domain/src/agents/mod.rsindex ec6d4e83..78efb200 100644--- a/crates/domain/src/agents/mod.rs+++ b/crates/domain/src/agents/mod.rs@@ -6,6 +6,7 @@ mod collaboration;mod context_window;mod emulator;mod managed_launch;+mod model_budget_conflict;mod model_grant;mod native_artifacts;mod plan_references;@@ -20,6 +21,7 @@ pub use collaboration::*;pub use context_window::*;pub use emulator::*;pub use managed_launch::*;+pub use model_budget_conflict::*;pub use model_grant::*;pub use native_artifacts::*;pub use plan_references::*;diff --git a/crates/domain/src/agents/model_budget_conflict.rs b/crates/domain/src/agents/model_budget_conflict.rsnew file mode 100644index 00000000..812a3f4f--- /dev/null+++ b/crates/domain/src/agents/model_budget_conflict.rs@@ -0,0 +1,120 @@+//! Safe capacity facts for installed model consumers, never native configuration or authority.+use crate::{AgentKindV1, AgentPlanId, ModelAlias};+use serde::{Deserialize, Serialize};++pub const AGENT_MODEL_BUDGET_CONFLICT_SCHEMA_V1: &str = "hiroute.agent-model-budget-conflict/v1";+pub const AGENT_MODEL_BUDGET_CONFLICT_CODE: &str = "AGENT_MODEL_BUDGET_CONFLICT";++#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]+#[serde(deny_unknown_fields)]+pub struct AgentModelTokenBudgetV1 {+ pub context_window_tokens: u64,+ pub max_output_tokens: u64,+}++#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum AgentModelBudgetReasonV1 {+ CapacityReduced,+ PlanMissing,+ BudgetUnavailable,+}++#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]+#[serde(deny_unknown_fields)]+pub struct AgentModelBudgetBlockerV1 {+ pub agent_kind: AgentKindV1,+ pub context_id: String,+ pub plan_id: AgentPlanId,+ pub model_alias: ModelAlias,+ pub reason: AgentModelBudgetReasonV1,+ pub declared: AgentModelTokenBudgetV1,+ pub proposed: Option<AgentModelTokenBudgetV1>,+}++#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]+#[serde(deny_unknown_fields)]+pub struct AgentModelBudgetConflictV1 {+ pub schema: String,+ pub blockers: Vec<AgentModelBudgetBlockerV1>,+}++impl AgentModelBudgetConflictV1 {+ pub fn new(mut blockers: Vec<AgentModelBudgetBlockerV1>) -> Self {+ blockers.sort_by(|a, b| {+ (+ a.agent_kind,+ &a.context_id,+ &a.plan_id,+ &a.model_alias,+ a.reason,+ )+ .cmp(&(+ b.agent_kind,+ &b.context_id,+ &b.plan_id,+ &b.model_alias,+ b.reason,+ ))+ });+ blockers.dedup();+ Self {+ schema: AGENT_MODEL_BUDGET_CONFLICT_SCHEMA_V1.into(),+ blockers,+ }+ }++ pub fn is_valid(&self) -> bool {+ self.schema == AGENT_MODEL_BUDGET_CONFLICT_SCHEMA_V1+ && !self.blockers.is_empty()+ && self.blockers.iter().all(|blocker| {+ matches!(+ blocker.agent_kind,+ AgentKindV1::Qoder | AgentKindV1::Pi | AgentKindV1::DeepseekHarness+ ) && blocker.context_id.starts_with("agent-context/")+ && blocker.context_id.len() <= 256+ && blocker+ .context_id+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || b"/-_:".contains(&b))+ && AgentPlanId::parse(blocker.plan_id.as_str()).is_ok()+ && ModelAlias::parse(blocker.model_alias.as_str()).is_ok()+ && blocker.declared.context_window_tokens > 0+ && blocker.declared.max_output_tokens > 0+ && match (blocker.reason, blocker.proposed) {+ (AgentModelBudgetReasonV1::CapacityReduced, Some(next)) => {+ next.context_window_tokens > 0+ && next.max_output_tokens > 0+ && (next.context_window_tokens+ < blocker.declared.context_window_tokens+ || next.max_output_tokens < blocker.declared.max_output_tokens)+ }+ (+ AgentModelBudgetReasonV1::PlanMissing+ | AgentModelBudgetReasonV1::BudgetUnavailable,+ None,+ ) => true,+ _ => false,+ }+ })+ }++ /// Retain the released Qoder code only when every actual blocker belongs to Qoder.+ pub fn safe_code(&self) -> &'static str {+ if self+ .blockers+ .iter()+ .all(|blocker| blocker.agent_kind == AgentKindV1::Qoder)+ {+ "QODER_MODEL_BUDGET_CONFLICT"+ } else {+ AGENT_MODEL_BUDGET_CONFLICT_CODE+ }+ }++ /// A terminal result is diagnostic data. Parsing it never authorizes recovery effects.+ pub fn parse(encoded: &str) -> Option<Self> {+ let value: Self = serde_json::from_str(encoded).ok()?;+ value.is_valid().then_some(value)+ }+}diff --git a/crates/domain/src/error/mod.rs b/crates/domain/src/error/mod.rsindex cebeb393..bc9614f5 100644--- a/crates/domain/src/error/mod.rs+++ b/crates/domain/src/error/mod.rs@@ -11,17 +11,29 @@ pub enum PortErrorCode {Unavailable,}-/// Adapter errors intentionally carry only a bounded, non-sensitive context label.+/// Adapter errors carry a bounded context label and optional typed, non-secret capacity facts.#[derive(Clone, Debug, Error, Eq, PartialEq)]#[error("{code:?} at {context}")]pub struct PortError {pub code: PortErrorCode,pub context: &'static str,+ pub model_budget_conflict: Option<Box<crate::AgentModelBudgetConflictV1>>,}impl PortError {pub const fn new(code: PortErrorCode, context: &'static str) -> Self {- Self { code, context }+ Self {+ code,+ context,+ model_budget_conflict: None,+ }+ }+ pub fn with_model_budget_conflict(+ mut self,+ conflict: crate::AgentModelBudgetConflictV1,+ ) -> Self {+ self.model_budget_conflict = Some(Box::new(conflict));+ self}}diff --git a/crates/domain/src/operation/mod.rs b/crates/domain/src/operation/mod.rsindex 71c05c68..90baf01b 100644--- a/crates/domain/src/operation/mod.rs+++ b/crates/domain/src/operation/mod.rs@@ -1358,6 +1358,7 @@ pub struct OperationV1 {/// Read-only status, deliberately insufficient to execute or authorize an Operation.#[derive(Clone, Debug, PartialEq)]pub struct OperationStatus {+ pub model_budget_conflict: Option<crate::AgentModelBudgetConflictV1>,pub operation_id: OperationId,pub state: OperationState,pub generation: u64,@@ -1366,6 +1367,19 @@ pub struct OperationStatus {}impl OperationV1 {+ pub fn model_budget_conflict(&self) -> Option<crate::AgentModelBudgetConflictV1> {+ if !matches!(+ self.safe_error_code.as_deref(),+ Some("QODER_MODEL_BUDGET_CONFLICT" | "AGENT_MODEL_BUDGET_CONFLICT")+ ) {+ return None;+ }+ self.steps+ .iter()+ .filter_map(|step| step.terminal_result.as_deref())+ .find_map(crate::AgentModelBudgetConflictV1::parse)+ }+#[allow(clippy::too_many_arguments)]pub fn new(operation_id: OperationId,diff --git a/crates/integrations/src/agents/additional_native/README.md b/crates/integrations/src/agents/additional_native/README.mdindex 3b918f48..e8e480b5 100644--- a/crates/integrations/src/agents/additional_native/README.md+++ b/crates/integrations/src/agents/additional_native/README.md@@ -41,7 +41,26 @@ A native provider name alone never grants ownership of an existing user entry.are native project configuration, outside the global default ownership contract.- [Budget admission](../../../../daemon/src/control/runtime/additional_model_budget.rs)keeps installed declarations compatible with publication changes and blocks a- second mutation while the original operation has a pending tail.+ second mutation while the original operation has a pending tail. Only the exact active+ grant generation retained in the next publication owns a declaration. All affected+ Qoder/Pi/DSH contexts are reported with their Plan ID/alias, declared/proposed context+ and output, or a distinct missing/uncomputable reason. Sharing an upstream binding+ does not establish a Plan dependency.++Budget rejections use `hiroute.agent-model-budget-conflict/v1` safe facts. Admission+returns them as optional `error.model_budget_conflict`, leaving success `data`+absent so released typed envelope readers still work; an Install rejection freezes the same facts in+that step's existing terminal result and retains them through rollback/restart.+This diagnostic has no effect ownership or recovery authority. Qoder-only conflicts+keep the released Qoder code; other consumers use the released general conflict+category and `AGENT_MODEL_BUDGET_CONFLICT` terminal code. Error facts require+`PlanContentApplyRequestV2.include_model_budget_conflict=true`, which the Desktop+sets only for content publication. Omitted/false and generic preview/apply calls+retain the released closed error shape. This presentation flag is outside the+change spec and confirmation digest and never grants write authority. `operations.find` emits+these facts only when `include_model_budget_conflict=true`; omitted/false requests+retain the old strict response shape. Existing operation inputs, grant formats,+SQL schema and native settings formats are unchanged.The prepared local grant is written only to the private native provider, mode0600. Public journals contain no bearer or original native settings. Status readsdiff --git a/crates/integrations/src/agents/native_effects.rs b/crates/integrations/src/agents/native_effects.rsindex 75c253ea..0af2d694 100644--- a/crates/integrations/src/agents/native_effects.rs+++ b/crates/integrations/src/agents/native_effects.rs@@ -207,5 +207,5 @@ pub(super) fn replay(}}fn error(code: PortErrorCode, context: &'static str) -> PortError {- PortError { code, context }+ PortError::new(code, context)}diff --git a/crates/local-storage/src/control/operation_status.rs b/crates/local-storage/src/control/operation_status.rsindex 8402236e..6372fdeb 100644--- a/crates/local-storage/src/control/operation_status.rs+++ b/crates/local-storage/src/control/operation_status.rs@@ -11,13 +11,17 @@ impl ControlStore {let connection = self.connection.borrow();let row = connection.query_row("SELECT operation_id, state, generation, request_digest, accepted_change_digest,- json_extract(operation_json, '$.safe_error_code')+ json_extract(operation_json, '$.safe_error_code'),+ (SELECT json_group_array(json_extract(value, '$.terminal_result'))+ FROM json_each(operation_json, '$.steps'))FROM operations WHERE workspace_id=?1 AND principal=?2 AND operation_kind=?3 AND idempotency_key=?4",params![workspace.as_str(), scope.principal, scope.operation_kind, scope.key],|row| Ok((row.get::<_,String>(0)?, row.get::<_,String>(1)?, row.get::<_,u64>(2)?,- row.get::<_,String>(3)?, row.get::<_,String>(4)?, row.get::<_,Option<String>>(5)?)),+ row.get::<_,String>(3)?, row.get::<_,String>(4)?, row.get::<_,Option<String>>(5)?, row.get::<_,String>(6)?)),).optional().map_err(|_| port(PortErrorCode::Corrupt, "control.operation.status_read"))?;- let Some((id, state, generation, request, accepted, safe_error_code)) = row else {+ let Some((id, state, generation, request, accepted, safe_error_code, terminal_results)) =+ row+ else {return Ok(None);};let invalid = || port(PortErrorCode::Corrupt, "control.operation.status_identity");@@ -28,7 +32,21 @@ impl ControlStore {}let state = serde_json::from_value(Value::String(state)).map_err(|_| invalid())?;let accepted_digest = CanonicalDigest::parse(accepted).map_err(|_| invalid())?;+ let model_budget_conflict = if matches!(+ safe_error_code.as_deref(),+ Some("QODER_MODEL_BUDGET_CONFLICT" | "AGENT_MODEL_BUDGET_CONFLICT")+ ) {+ let results: Vec<Option<String>> =+ serde_json::from_str(&terminal_results).map_err(|_| invalid())?;+ results+ .iter()+ .flatten()+ .find_map(|result| hiroute_domain::AgentModelBudgetConflictV1::parse(result))+ } else {+ None+ };Ok(Some(OperationStatus {+ model_budget_conflict,operation_id,state,generation,diff --git a/docs/code-map/testing.md b/docs/code-map/testing.mdindex 7733febd..b383abd5 100644--- a/docs/code-map/testing.md+++ b/docs/code-map/testing.md@@ -106,10 +106,11 @@ HTTP path or old restore fixture does not prove route revocation or native execureused evidence at its original SHA; assess the three slowest measured modulesonce without automatically refactoring the frozen candidate.-The managed backend DAG's preparation boundary lives in-[`validation-schedule.py`](../../scripts/validation-schedule.py).-Its [regressions](../../scripts/test-validation-schedule.py) check current Gateway-runtime fixture consumers before an expensive workspace run.+Final backend DAG admission and preparation are owned by+[validation-schedule.py](../../scripts/validation-schedule.py), with+[regressions](../../scripts/test-validation-schedule.py). CPA bridge process fixtures+run in an isolated lane before other listeners; Gateway runtime consumers wait for+prepared product roles.Code-map and local ownership-guide edits require link/owner review and the selectedcontract checks, not new model calls. Runtime-embedded Markdown and shipped Skillsdiff --git a/docs/code-map/worker-context.md b/docs/code-map/worker-context.mdindex 06f08d5d..1ef95a02 100644--- a/docs/code-map/worker-context.md+++ b/docs/code-map/worker-context.md@@ -19,7 +19,10 @@ Qoder/Pi/DSH saved models use one owned provider per Plan with an explicitResponses/Messages choice. [Route grants](../../crates/domain/src/agents/model_grant.rs)and [Gateway trust](../../crates/gateway/src/publication/trust.rs) preserve alias,protocol and receipt authority across publication/restart. `work.protocol` is the-independent frozen Worker choice. Native defaults and collaboration stay independent;+independent frozen Worker choice. [Publication budget guards](../../crates/daemon/src/control/runtime/additional_model_budget.rs)+report the actual installed consumers; [safe conflict facts](../../crates/domain/src/agents/model_budget_conflict.rs)+retain rejection identity through compensation and client observation.+Native defaults and collaboration stay independent;restoration must verify ownership rather than infer it from a provider name.## Follow a task through its ownersdiff --git a/scripts/test-validation-schedule.py b/scripts/test-validation-schedule.pyindex c2cb87a4..af452782 100644--- a/scripts/test-validation-schedule.py+++ b/scripts/test-validation-schedule.py@@ -1,5 +1,6 @@#!/usr/bin/env python3"""Prove phase isolation, exact coverage and shared-slot execution without Rust."""+import contextlibimport importlib.utilimport ioimport json@@ -8,6 +9,8 @@ from pathlib import Pathimport subprocessimport sysimport tempfile+import threading+from types import SimpleNamespaceimport unittestfrom unittest.mock import patch@@ -45,15 +48,161 @@ sys.exit(101 if bad else 0)class Schedule(unittest.TestCase):- def test_gateway_runtime_consumers_require_product_preparation(self):+ def run_dag_isolation_fixture(self, fail_cpa=False, fail_fast=True, omit_cpa=False):+ """Exercise the real DAG controller with bounded fake build/target processes."""+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ run = root / 'run'+ run.mkdir()+ names = ['hiroute_cpa_bridge', 'hiroute_gateway', 'smoke_cli']+ if omit_cpa:+ names.remove('hiroute_cpa_bridge')+ targets = [dict(name=name, package=name.replace('_', '-'), source=name,+ cwd=str(root), test_source='src/lib.rs', label=name)+ for name in names]+ metadata = {'packages': [dict(id=row['package'], name=row['package'])+ for row in targets]}+ cpa_done = threading.Event()+ admitted = []++ class FixtureRunner:+ @staticmethod+ def save(path, data):+ Path(path).write_text(json.dumps(data))+ @staticmethod+ def command(_args, _cwd):+ return json.dumps(metadata)+ @staticmethod+ def reporting():+ return reporting+ @staticmethod+ def test_summary(_text, _command):+ return dict(counts=dict(passed=1, failed=0, ignored=0))+ @staticmethod+ def start_locked_command(args, _cwd, _env, output, _handles):+ if '--no-run' not in args:+ self.assertTrue(cpa_done.is_set(), 'CPA must finish before preparation/doctests')+ if '--doc' in args:+ output.write(' Doc-tests fixture\nrunning 1 test\n'+ 'test fixture_doc ... ok\n'+ 'test result: ok. 1 passed; 0 failed; 0 ignored; '+ '0 measured; 0 filtered out; finished in 0.01s\n')+ return SimpleNamespace(wait=lambda timeout: 0)++ def run_targets(_runner, _root, _run, selected, *_args, **kwargs):+ results = []+ for item in selected:+ name = item['name']+ if name == 'hiroute_cpa_bridge':+ self.assertEqual([row['name'] for row in selected], [name],+ 'CPA fixtures must have their own target lane')+ self.assertEqual(item.get('test_threads'), 1,+ 'CPA port handoffs must not race inside its binary')+ cpa_done.set()+ else:+ self.assertTrue(cpa_done.is_set(), 'No runtime target may overlap CPA')+ admitted.append(name)+ failed = fail_cpa and name == 'hiroute_cpa_bridge'+ path = run / ('fixture-' + name + '.log')+ path.write_text(name + '\n')+ results.append(dict(name=name, log=str(path), complete=not failed,+ process_exit=int(failed),+ counts=dict(passed=int(not failed), failed=int(failed), ignored=0)))+ stop_event = kwargs.get('stop_event', _args[-1] if _args else None)+ if failed and fail_fast and stop_event is not None:+ stop_event.set()+ return results++ mocks = dict(dag_catalog=lambda *_args: targets,+ dag_list=lambda source, *_args: ['default_two_domain_smoke' if source == 'smoke_cli' else source],+ dag_snapshot=lambda *_args: None,+ dag_daemon_fixture=lambda *_args: {},+ dag_bind_daemon_fixture=lambda *_args: None,+ dag_bind_metadata=lambda *_args: None,+ dag_toolchain_context=lambda *_args: {'path': '/fixture/toolchain'},+ dag_products=lambda *_args: {},+ dag_publication_daemon=lambda *_args: root,+ dag_run_targets=run_targets)+ output = io.StringIO()+ with contextlib.ExitStack() as stack:+ for name, replacement in mocks.items():+ stack.enter_context(patch.object(scheduler, name, side_effect=replacement))+ command = COMMAND + ([] if fail_fast else ['--no-fail-fast'])+ result = scheduler.execute_dag(FixtureRunner, root, run, root,+ dict(command=command, timeout=15, sha='a'*40),+ None, output, reserved_handles=[])+ return result, admitted, output.getvalue()++ def test_cpa_isolation_keeps_every_target_and_case(self):+ result, admitted, _ = self.run_dag_isolation_fixture()+ self.assertTrue(result['complete'], result)+ self.assertEqual(admitted, ['hiroute_cpa_bridge', 'hiroute_gateway', 'smoke_cli'])+ self.assertEqual(result['expected_tests'], 3)+ self.assertEqual(result['executed_targets'], 3)+ self.assertEqual(result['counts'], dict(passed=4, failed=0, ignored=0))++ def test_failed_isolated_target_obeys_fail_fast_and_keeps_its_log(self):+ result, admitted, log = self.run_dag_isolation_fixture(fail_cpa=True)+ self.assertFalse(result['complete'])+ self.assertEqual(admitted, ['hiroute_cpa_bridge'])+ self.assertEqual(result['executed_targets'], 1)+ self.assertIn('hiroute_cpa_bridge', log)+ result, admitted, _ = self.run_dag_isolation_fixture(fail_cpa=True, fail_fast=False)+ self.assertFalse(result['complete'])+ self.assertEqual(len(admitted), 3)+ self.assertEqual(result['counts']['failed'], 1)++ def test_missing_cpa_isolation_target_cannot_silently_narrow_the_schedule(self):+ result, admitted, _ = self.run_dag_isolation_fixture(omit_cpa=True)+ self.assertFalse(result['complete'])+ self.assertEqual(admitted, [])+ self.assertIn('CPA library target', result['error'])++ def test_isolated_binary_runs_all_cases_with_one_thread_and_exec_audit(self):+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ executable = root / 'fixture'+ executable.write_bytes(b'compiled fixture')+ item = dict(name='hiroute_cpa_bridge', package_name='hiroute-cpa-bridge',+ executable=str(executable), sha256=scheduler.file_digest(executable),+ index=0, label='src/lib.rs', cwd=str(root), test_threads=1,+ cases=['case_one', 'case_two'])+ class FixtureRunner:+ @staticmethod+ def reporting():+ return reporting+ @staticmethod+ def save(path, data):+ Path(path).write_text(json.dumps(data))+ @staticmethod+ def start_locked_command(args, _cwd, _env, output, _handles):+ self.assertEqual(args[-2:], [str(executable), '--test-threads=1'])+ trace = Path(args[args.index('-o') + 1])+ trace.write_text('123 execve("/fixture/test", [...], 0x1) = 0\n')+ output.write('running 2 tests\ntest case_one ... ok\n'+ 'test case_two ... ignored, fixture\n'+ 'test result: ok. 1 passed; 0 failed; 1 ignored; '+ '0 measured; 0 filtered out; finished in 0.01s\n')+ return SimpleNamespace(wait=lambda timeout: 0)+ with patch.object(scheduler.sys, 'platform', 'linux'), \+ patch.object(scheduler.shutil, 'which', return_value='/fixture/strace'):+ results = scheduler.dag_run_targets(+ FixtureRunner, root, root, [item], root, None, {},+ scheduler.time.monotonic() + 5, workers=1, reserved_handles=[])+ self.assertEqual(len(results), 1)+ self.assertTrue(results[0]['complete'], results)+ self.assertEqual(results[0]['counts'], dict(passed=1, failed=0, ignored=1))+ self.assertEqual(results[0]['exec_audit']['cargo_rustc_starts'], 0)++ def test_gateway_runtime_consumers_wait_for_prepared_products(self):tests = Path(__file__).resolve().parents[1] / 'tools/e2e-harness/tests'- consumers = {- source.stem for source in tests.glob('*.rs')- if 'mod runtime_support;' in source.read_text()- }+ consumers = {source.stem for source in tests.glob('*.rs')+ if 'mod runtime_support;' in source.read_text()}+ self.assertTrue(consumers, 'Gateway runtime consumer inventory must be nonempty')self.assertIn('p0_gateway_native_sessions', consumers)- self.assertEqual(consumers - scheduler.PRODUCT_TARGETS, set(),- 'Gateway runtime targets must wait for prepared product binaries')+ self.assertFalse(consumers - scheduler.PRODUCT_TARGETS,+ 'Gateway runtime consumers must wait for prepared products: '+ + ', '.join(sorted(consumers - scheduler.PRODUCT_TARGETS)))def test_exec_audit_rejects_runtime_cargo_without_storing_arguments(self):trace = ('123 execve("/tmp/bin/test", [...], 0x1) = 0\n'diff --git a/scripts/validation-schedule.py b/scripts/validation-schedule.pyindex eb90ba63..22c475fd 100644--- a/scripts/validation-schedule.py+++ b/scripts/validation-schedule.py@@ -615,7 +615,8 @@ def dag_run_targets(runner, root, run, targets, checkout, lease, environment, deif name == "smoke_cli":env.update(item.get("smoke_environment", {}))env.update(environment)- args = [selected, "--test-threads=" + str(1 if name == "smoke_cli" else 8)]+ args = [selected, "--test-threads=" + str(item.get(+ "test_threads", 1 if name == "smoke_cli" else 8))]trace = run / ("dag-exec-" + str(item["index"]) + ".log")traced = [tracer, "-f", "-e", "trace=execve,execveat", "-s", "0","-o", str(trace), *args]@@ -742,11 +743,21 @@ def execute_dag(runner, root, run, checkout, request, lease, output, reserved_hadag_bind_metadata(targets, metadata_artifact)for item in targets:item.setdefault("external_artifacts", []).append(toolchain_artifact)+ # CPA's external-process fixture releases its selected port before the+ # child binds it. Keep this whole library, including its internal cases,+ # separate from other listeners until the child lifecycle is complete.+ isolated = [item for item in targets+ if item["package_name"] == "hiroute-cpa-bridge"+ and item["test_source"] == "src/lib.rs"]+ if len(isolated) != 1:+ raise ValueError("CPA library target missing or duplicated in isolation lane")+ isolated[0]["test_threads"] = 1runner.save(run / "dag-validation-plan.json", dict(schema="hiroute.validation-plan/v1", sha=request["sha"],command=request["command"], targets=targets, expected_tests=expected))- independent = sorted((item for item in targets if item["name"] not in PRODUCT_TARGETS),+ independent = sorted((item for item in targets+ if item not in isolated and item["name"] not in PRODUCT_TARGETS),key=lambda item: (item["name"] != "hiroute_daemon", item["name"]))dependent = [item for item in targets if item["name"] in PRODUCT_TARGETS]stop_event = threading.Event() if fail_fast else None@@ -754,11 +765,24 @@ def execute_dag(runner, root, run, checkout, request, lease, output, reserved_haif (item["test_source"].startswith("tests/")and "mod runtime_support;" in (Path(item["cwd"]) / item["test_source"]).read_text(errors="replace")):raise ValueError("Gateway runtime consumer lacks product preparation: " + item["name"])+ execution_env = dict(os.environ, HIROUTE_VALIDATION_EXECUTION="1",+ HIROUTE_VALIDATION_TOOLCHAIN_JSON=toolchain_artifact["path"])+ results = dag_run_targets(runner, root, run, isolated, checkout, lease,+ execution_env, deadline, slots=4, workers=1,+ fail_fast=fail_fast, reserved_handles=reserved_handles,+ stop_event=stop_event)+ if stop_event is not None and stop_event.is_set():+ for result in results:+ if result.get("log"):+ output.write(Path(result["log"]).read_text(errors="replace") + "\n")+ outcome.update(expected_tests=expected, targets=len(targets),+ executed_targets=len(results), target_results=results,+ error="Isolated test target failed; remaining targets and doctests were not admitted")+ return outcomewith ThreadPoolExecutor(max_workers=2) as pool:prepared = pool.submit(cargo_phase, "prepare", commands(base)["prepare"], 4)ordinary = pool.submit(dag_run_targets, runner, root, run, independent, checkout,- lease, dict(os.environ, HIROUTE_VALIDATION_EXECUTION="1",- HIROUTE_VALIDATION_TOOLCHAIN_JSON=toolchain_artifact["path"]),+ lease, execution_env,deadline, 4, 4, fail_fast, reserved_handles, stop_event)preparation_log = prepared.result()summary = runner.test_summary(preparation_log, commands(base)["prepare"])@@ -782,7 +806,7 @@ def execute_dag(runner, root, run, checkout, request, lease, output, reserved_hareserved_handles=reserved_handles,stop_event=stop_event)first = ordinary.result()- results = first + remaining+ results += first + remainingfor result in sorted(results, key=lambda item: item.get("log", "")):if result.get("log"):output.write(Path(result["log"]).read_text(errors="replace") + "\n")diff --git a/tools/product-e2e/src/smoke/control.rs b/tools/product-e2e/src/smoke/control.rsindex f5b38fe6..0bfb18dc 100644--- a/tools/product-e2e/src/smoke/control.rs+++ b/tools/product-e2e/src/smoke/control.rs@@ -311,6 +311,7 @@ pub(super) fn discover(ctx: &mut Context<'_>) -> Result<()> {accepted_digest: CanonicalDigest::of_bytes(format!("mvp17-lookup-{}", ctx.run_id).as_bytes(),),+ include_model_budget_conflict: false,};let lookup_payload = serde_json::to_value(&lookup)?;let lookup_input = serde_json::to_vec(&lookup)?;