Skip to content

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.

feat(models): manage named connections and safely remove models (#80)

澄潭785fe64c2500
diff --git a/apps/desktop/src-tauri/build.rs b/apps/desktop/src-tauri/build.rs
index a3ac0088..86f3f1c1 100644
--- a/apps/desktop/src-tauri/build.rs
+++ b/apps/desktop/src-tauri/build.rs
@@ -27,6 +27,7 @@ fn main() {
"save_classifier_openapi",
"preview_rename",
"preview_plan_editor",
+ "refresh_route_references",
"plan_editor_options",
"preview_restore_name",
"preview_price_change",
diff --git a/apps/desktop/src-tauri/capabilities/main.json b/apps/desktop/src-tauri/capabilities/main.json
index f4fcf094..360699dd 100644
--- a/apps/desktop/src-tauri/capabilities/main.json
+++ b/apps/desktop/src-tauri/capabilities/main.json
@@ -43,6 +43,7 @@
"allow-web-confirmation-snapshot",
"allow-resolve-web-confirmation",
"allow-preview-plan-editor",
+ "allow-refresh-route-references",
"allow-plan-editor-options",
"allow-observation-read",
"allow-observation-delete",
diff --git a/apps/desktop/src-tauri/permissions/autogenerated/refresh_route_references.toml b/apps/desktop/src-tauri/permissions/autogenerated/refresh_route_references.toml
new file mode 100644
index 00000000..1b04d210
--- /dev/null
+++ b/apps/desktop/src-tauri/permissions/autogenerated/refresh_route_references.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-refresh-route-references"
+description = "Enables the refresh_route_references command without any pre-configured scope."
+commands.allow = ["refresh_route_references"]
+
+[[permission]]
+identifier = "deny-refresh-route-references"
+description = "Denies the refresh_route_references command without any pre-configured scope."
+commands.deny = ["refresh_route_references"]
diff --git a/apps/desktop/src-tauri/src/bridge.rs b/apps/desktop/src-tauri/src/bridge.rs
index d7482fd6..ec0c74f0 100644
--- a/apps/desktop/src-tauri/src/bridge.rs
+++ b/apps/desktop/src-tauri/src/bridge.rs
@@ -247,6 +247,35 @@ pub async fn desktop_snapshot(
session.snapshot().await
}
#[tauri::command]
+pub async fn refresh_route_references(
+ window: WebviewWindow,
+ state: State<'_, DesktopState>,
+ language: String,
+) -> Result<MutationOutcome, DesktopFailure> {
+ main_window(&window)?;
+ let epoch = state.2.load(Ordering::SeqCst);
+ let action = ActionDiagnostics::begin(&state.3, ActionOperation::PlanEditor);
+ action.preview(PreviewPhase::Begin, None);
+ let context = state
+ .0
+ .lock()
+ .await
+ .as_mut()
+ .ok_or("RESIDENT_UNAVAILABLE")?
+ .preview_reference_refresh(language)
+ .await?;
+ action.preview(PreviewPhase::End, Some(context.revision()));
+ confirm(
+ &window,
+ &state,
+ ActionOperation::PlanEditor,
+ NativeConfirmation::Rename(Box::new(context)),
+ epoch,
+ )
+ .await?
+ .mutation()
+}
+#[tauri::command]
pub async fn preview_plan_editor(
window: WebviewWindow,
state: State<'_, DesktopState>,
@@ -991,6 +1020,7 @@ pub fn run() {
desktop_snapshot,
preview_rename,
preview_plan_editor,
+ refresh_route_references,
plan_editor_options,
preview_restore_name,
preview_price_change,
diff --git a/apps/desktop/src-tauri/src/bridge/model_connection_web.rs b/apps/desktop/src-tauri/src/bridge/model_connection_web.rs
index 30565327..1bee32f3 100644
--- a/apps/desktop/src-tauri/src/bridge/model_connection_web.rs
+++ b/apps/desktop/src-tauri/src/bridge/model_connection_web.rs
@@ -231,6 +231,8 @@ pub(super) struct WebComputeManagementChangeV2 {
key_edits: Vec<ComputeKeyEditV2>,
#[serde(default, skip_serializing_if = "Option::is_none")]
validation: Option<WebValidationRefV2>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ edit: Option<hiroute_application_api::ComputeManagementEditV1>,
}
impl From<ComputeManagementChangeV2> for WebComputeManagementChangeV2 {
@@ -243,6 +245,7 @@ impl From<ComputeManagementChangeV2> for WebComputeManagementChangeV2 {
intent: value.intent,
key_edits: value.key_edits,
validation: value.validation.map(Into::into),
+ edit: value.edit,
}
}
}
@@ -259,6 +262,7 @@ impl TryFrom<WebComputeManagementChangeV2> for ComputeManagementChangeV2 {
intent: value.intent,
key_edits: value.key_edits,
validation: value.validation.map(TryInto::try_into).transpose()?,
+ edit: value.edit,
})
}
}
@@ -531,6 +535,7 @@ mod tests {
dependencies: BTreeMap::new(),
};
let change = ComputeManagementChangeV2 {
+ edit: None,
schema: COMPUTE_MANAGEMENT_CHANGE_SCHEMA_V2.into(),
subject: ComputeManagementSubjectV2::Candidate {
candidate: ComputeCandidateRefV2 {
diff --git a/apps/desktop/src-tauri/src/session/authoring.rs b/apps/desktop/src-tauri/src/session/authoring.rs
index 7043e69e..5185f10f 100644
--- a/apps/desktop/src-tauri/src/session/authoring.rs
+++ b/apps/desktop/src-tauri/src/session/authoring.rs
@@ -34,6 +34,64 @@ impl EditorAction {
}
}
impl Session {
+ pub async fn preview_reference_refresh(
+ &mut self,
+ language: String,
+ ) -> Result<Confirmation, DesktopFailure> {
+ if self.confirmation.is_open() {
+ return Err("CONFIRMATION_ALREADY_OPEN".into());
+ }
+ if !matches!(language.as_str(), "zh" | "en") {
+ return Err("INVALID_LANGUAGE".into());
+ }
+ let snapshot = self.snapshot().await?;
+ if !snapshot.trusted_authority || !snapshot.service.mutation_available {
+ return Err("TRUSTED_AUTHORITY_UNAVAILABLE".into());
+ }
+ let change = serde_json::to_value(PublicationCheckpointChangeV1 {
+ schema: PUBLICATION_CHECKPOINT_CHANGE_SCHEMA_V1.into(),
+ })
+ .map_err(|_| "REQUEST_INVALID")?;
+ let intent = IntentEvidence {
+ schema: "hiroute.desktop-plan-intent/v1".into(),
+ digest: CanonicalDigest::of(&change).map_err(|_| "REQUEST_INVALID")?,
+ };
+ let retry = self.retry_key(&intent).await?;
+ let preview: PublicationCheckpointPreviewV1 = query(
+ &self.client,
+ "PreviewAgentPlanChange",
+ &serde_json::json!({"change":change}),
+ )
+ .await?;
+ if preview.schema != PUBLICATION_CHECKPOINT_PREVIEW_SCHEMA_V1 {
+ return Err("PREVIEW_INVALID".into());
+ }
+ let label = if language == "en" {
+ "Update references"
+ } else {
+ "更新引用状态"
+ }
+ .to_owned();
+ Ok(Confirmation {
+ requires_confirmation: false,
+ action_label: label.clone(),
+ permit: self.confirmation.begin()?,
+ intent,
+ previous_name: String::new(),
+ input: RenameInput {
+ plan_id: "publication/current".into(),
+ display_name: label.clone(),
+ language,
+ },
+ message_override: Some(label),
+ request: NativePlanApply {
+ change,
+ accept_digest: preview.change_digest,
+ expected_revisions: preview.expected_revisions,
+ idempotency_key: retry.unwrap_or(crate::random_id()?),
+ },
+ })
+ }
pub async fn preview_editor(
&mut self,
input: EditorInput,
diff --git a/apps/desktop/src/features/model-connections/ConnectionTemplatePicker.tsx b/apps/desktop/src/features/model-connections/ConnectionTemplatePicker.tsx
new file mode 100644
index 00000000..5e4c4a43
--- /dev/null
+++ b/apps/desktop/src/features/model-connections/ConnectionTemplatePicker.tsx
@@ -0,0 +1,31 @@
+import { useState } from 'react';
+import { ProviderIcon } from '../../ui/ProviderIcon';
+import { connectionName } from '../../ui/provider-identity';
+import type { ComputeConnectionOption, Language } from './types';
+
+export function ConnectionTemplatePicker({ options, value, language, onChange }: {
+ options: ComputeConnectionOption[];
+ value: string;
+ language: Language;
+ onChange(id: string): void;
+}) {
+ const zh = language === 'zh';
+ const [query, setQuery] = useState('');
+ const [filter, setFilter] = useState<'all' | 'paid' | 'free'>('all');
+ const [page, setPage] = useState(0);
+ const needle = query.trim().toLocaleLowerCase();
+ const matches = options.filter(option => (filter === 'all' || option.billing_class === filter)
+ && `${connectionName(option.connection_option_id, language, option.display_name)} ${option.display_name} ${option.connection_option_id}`.toLocaleLowerCase().includes(needle));
+ const pages = Math.max(1, Math.ceil(matches.length / 6));
+ const currentPage = Math.min(page, pages - 1);
+ return <section className="mc-template-directory" aria-label={zh ? '接入模板' : 'Connection templates'}>
+ <label className="field"><span className="field-label">{zh ? '搜索接入模板' : 'Search connection templates'}</span><input className="input" type="search" placeholder={zh ? '供应商或产品,如百炼、Coding Plan' : 'Provider or product, such as Bailian or Coding Plan'} value={query} onChange={event => { setQuery(event.target.value); setPage(0); }} /></label>
+ <div className="actions" role="group" aria-label={zh ? '模板类型' : 'Template type'}>{(['all', 'paid', 'free'] as const).map(kind => <button className="filter-chip" type="button" key={kind} aria-pressed={filter === kind} onClick={() => { setFilter(kind); setPage(0); }}>{kind === 'all' ? zh ? '全部' : 'All' : kind === 'paid' ? zh ? '付费 API' : 'Paid API' : zh ? '免费' : 'Free'}</button>)}</div>
+ <div role="radiogroup" aria-label={zh ? '选择接入模板' : 'Choose a connection template'}>{matches.slice(currentPage * 6, (currentPage + 1) * 6).map(option => <label className={`mc-template-row${value === option.connection_option_id ? ' selected' : ''}`} key={option.connection_option_id}>
+ <input type="radio" name="connection-template" value={option.connection_option_id} checked={value === option.connection_option_id} onChange={() => onChange(option.connection_option_id)} />
+ <ProviderIcon optionId={option.connection_option_id} language={language} /><span className="row-main"><strong>{connectionName(option.connection_option_id, language, option.display_name)}</strong><span className="field-help">{[...new Set(option.endpoints?.map(endpoint => endpoint.protocol) ?? [])].join(' · ')}</span></span>
+ </label>)}</div>
+ {!matches.length && <p role="status">{zh ? '没有匹配的模板。可以使用自定义 API 手动填写。' : 'No matching templates. Use Custom API to enter connection settings.'}</p>}
+ <div className="mc-template-pagination"><span>{matches.length} {zh ? '种接入模板' : 'templates'}</span><button className="btn btn-quiet" type="button" disabled={currentPage === 0} onClick={() => setPage(currentPage - 1)}>{zh ? '上一页' : 'Previous'}</button><span>{currentPage + 1}/{pages}</span><button className="btn btn-quiet" type="button" disabled={currentPage + 1 >= pages} onClick={() => setPage(currentPage + 1)}>{zh ? '下一页' : 'Next'}</button></div>
+ </section>;
+}
diff --git a/apps/desktop/src/features/model-connections/ModelConnectionForm.tsx b/apps/desktop/src/features/model-connections/ModelConnectionForm.tsx
index d9aef10c..81f8124b 100644
--- a/apps/desktop/src/features/model-connections/ModelConnectionForm.tsx
+++ b/apps/desktop/src/features/model-connections/ModelConnectionForm.tsx
@@ -1,4 +1,5 @@
import { connectionName, connectionTemplate } from '../../ui/provider-identity';
+import { ConnectionTemplatePicker } from './ConnectionTemplatePicker';
import { ProviderIcon } from '../../ui/ProviderIcon';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { invoke } from '@tauri-apps/api/core';
@@ -37,7 +38,7 @@ import type {
} from './types';
import { checkFailureCode, modelAvailabilityMessage } from './copy';
import { metadataModelPrefill } from './metadata-prefill';
-import { customApiPrefillOptions, metadataProviderCandidates, metadataProviderOption, registeredModelCandidates, sortMetadataProviders, sortRegisteredOptions, templateEndpointForProtocol } from './registered-metadata';
+import { customApiPrefillOptions, metadataProviderCandidates, metadataProviderOption, registeredModelCandidates, sortRegisteredOptions, templateEndpointForProtocol } from './registered-metadata';
import {
connectionErrorMessage,
ManualModelEditor,
@@ -99,11 +100,7 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {
const registeredCandidates = useMemo(() => registeredOption
? registeredModelCandidates(registeredOption, connectionOptions?.metadata_catalog)
: [], [registeredOption, connectionOptions]);
- const metadataProviders = useMemo(() => sortMetadataProviders(connectionOptions?.metadata_catalog?.provider_records.filter(provider =>
- provider.usable_for.includes('custom-api-endpoint-prefill')
- && provider.base_url_candidates.length > 0
- && provider.protocol_candidates.length > 0
- ) ?? []), [connectionOptions]);
+ const metadataProviders: ProviderMetadataRecord[] = []; // Broad metadata remains internal; only native templates are selectable.
const metadataPrefills = useMemo(() => customApiPrefillOptions(registeredOptions, metadataProviders), [registeredOptions, metadataProviders]);
const selectedPrefill = metadataPrefills.find(prefill => prefill.key === metadataPrefillKey) ?? null;
const metadataCandidates = useMemo(() => selectedPrefill?.kind === 'template'
@@ -113,6 +110,13 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {
: [], [selectedPrefill, connectionOptions, registeredOptions]);
useDiscardGuard('models', () => dirty && !saveCompletedRef.current, language, confirmReplacement);
+ function suggestedName(base: string) {
+ const names = new Set(props.existingNames ?? []);
+ let value = base;
+ for (let suffix = 2; names.has(value); suffix++) value = `${base} · ${suffix}`;
+ return value;
+ }
+
const releaseProtectedInput = useCallback(() => {
const input = protectedInputRef.current;
protectedInputRef.current = null;
@@ -130,6 +134,10 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {
setRegisteredOptionId(current => executable.some(option => option.connection_option_id === current)
? current
: executable[0]?.connection_option_id ?? '');
+ if (!custom && executable[0] && !draftRef.current.display_name.trim()) {
+ const name = suggestedName(connectionName(executable[0].connection_option_id, language, executable[0].display_name));
+ setDraft(current => { const next = { ...current, display_name: name }; draftRef.current = next; return next; });
+ }
if (!custom && executable.length === 0) {
setError('MODEL_CONNECTION_OPTION_UNAVAILABLE');
}
@@ -208,7 +216,7 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {
setMetadataPrefillKey(`template:${option.connection_option_id}`);
invalidate(current => ({ ...current,
entry_kind: 'custom_api', display_template_id: option.connection_option_id,
- display_name: connectionName(option.connection_option_id, language, option.display_name),
+ display_name: draftRef.current.display_name.trim() || suggestedName(connectionName(option.connection_option_id, language, option.display_name)),
base_url: endpoint.base_url, base_kind: 'api_root',
request_path_override: endpoint.request_path, inventory_path_override: endpoint.inventory_path ?? null,
protocol: endpoint.protocol, protocol_profile_id: `profile/custom/${endpoint.protocol}`,
@@ -291,13 +299,16 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {
}
setPhase('saving');
try {
- const preview = await backend.previewComputeSave(buildSaveChange({
+ const change = buildSaveChange({
result: checked,
expectedRevisions: props.expectedRevisions,
selectedModelRefs: selectedRefs,
- enable: true,
+ enable: (props.appendTo ?? props.savedSource)?.state !== 'disabled',
protectedInput: protectedInputRef.current,
- }));
+ });
+ if (props.appendTo) { change.edit = { action: 'append_models' }; change.key_edits = []; }
+ else if (draftRef.current.display_name.trim()) change.edit = { action: 'rename', display_name: draftRef.current.display_name.trim() };
+ const preview = await backend.previewComputeSave(change);
if (!aliveRef.current) {
releaseProtectedInput();
return;
@@ -381,6 +392,7 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {
? [...base.models, blankModel(inferenceModelId)] : base.models;
const current = { ...base, inference_model_id: inferenceModelId,
models: selectedModels.map(withCapabilityFallback) };
+ if (current.display_name.trim().length > 60 || (!current.existing_source_id && (props.existingNames ?? []).includes(current.display_name.trim()))) { setError('CONNECTION_NAME_CONFLICT'); return; }
const allowedIds = new Set([...preservedModelIds.current,
...(!custom ? registeredCandidates.map(model => model.upstream_model_id) : [])]);
// Check every route to the backend, including returning to connection check
@@ -581,7 +593,7 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {
? (zh ? '选择模型' : 'Select models')
: screen === 'manual'
? (zh ? '补充未知模型' : 'Complete unknown model details')
- : custom ? (zh ? '自定义 API' : 'Custom API') : (zh ? '连接 API' : 'Connect an API');
+ : props.appendTo ? (zh ? `向「${props.appendTo.display_name}」添加模型` : `Add models to “${props.appendTo.display_name}”`) : custom ? (zh ? '自定义 API' : 'Custom API') : (zh ? '连接 API' : 'Connect an API');
const footer = busy
? <button className="btn" type="button" disabled={phase === 'saving'} onClick={() => discardAndClose('cancel')}>{phase === 'saving' ? (zh ? '正在保存…' : 'Saving…') : (zh ? '取消检查' : 'Cancel check')}</button>
: screen === 'connection'
@@ -592,22 +604,21 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {
return <Dialog open title={title} closeLabel={phase === 'saving' ? (zh ? '正在保存' : 'Saving') : (zh ? '取消添加' : 'Cancel')} closeDisabled={phase === 'saving'} onClose={() => discardAndClose('cancel')} footer={footer}>
<section className="connection-flow" aria-label={zh ? '添加模型连接' : 'Add model connection'}>
+ {props.appendTo && <p className="field-help">{zh ? '复用此接入的端点和凭据。检查后添加模型,已有模型与启停状态将保留。' : 'Reuse saved endpoints and credentials. Add models after checking; existing models and enabled state are retained.'}</p>}
{!props.mutable && !busy && <div className="callout warn" role="status"><UiIcon name="warning" /><span>{zh ? '本机服务连接中断。当前输入已保留,重新连接后再保存。' : 'The local service disconnected. Your input is retained; reconnect before saving.'}</span></div>}
{busy ? <div className="oc-status-row" role="status"><span className="oc-spinner" /><div className="row-main"><strong>{phase === 'checking' ? (zh ? '正在检查接入' : 'Checking connection') : (zh ? '正在保存接入' : 'Saving connection')}</strong><p>{phase === 'checking' ? (zh ? '检查配置,并在提供目录时读取模型。' : 'Checking configuration and reading the model directory when configured.') : (zh ? '保存所选模型与凭据。' : 'Saving the selected models and credential.')}</p></div></div> : <>
<form hidden={screen !== 'connection'} id="mc-connection-form" onSubmit={event => { event.preventDefault(); void runCheck(false); }}>
- <fieldset className="connection-fields" disabled={!props.mutable}>
+ <fieldset className="connection-fields" disabled={!props.mutable || Boolean(props.appendTo)}>
{!custom && !free && <button className="btn btn-quiet" type="button" onClick={() => { setCustom(true); invalidate(current => ({ ...current, entry_kind: 'custom_api' }), true, 'connection'); }}>{zh ? '自定义 API' : 'Custom API'}</button>}
{custom ? <>
<ProviderIcon optionId={draft.display_template_id} language={language} />
{!optionsLoading && metadataPrefills.length > 0 && <div className="connection-fields metadata-prefill-fields">
- <label className="field"><span className="field-label">{zh ? '接入资料预填(可选)' : 'Connection prefill (optional)'}</span><select className="select" value={metadataPrefillKey} onChange={event => selectMetadataPrefill(event.target.value)}>
- <option value="">{zh ? '不使用预填' : 'No prefill'}</option>
+ <label className="field"><span className="field-label">{zh ? '接入模板(可选)' : 'Connection template (optional)'}</span><select className="select" value={metadataPrefillKey} onChange={event => selectMetadataPrefill(event.target.value)}>
+ <option value="">{zh ? '手动填写' : 'Enter manually'}</option>
<optgroup label={zh ? '内置接入' : 'Built-in connections'}>
{metadataPrefills.filter(prefill => prefill.kind === 'template').map(prefill => <option key={prefill.key} value={prefill.key}>{connectionName(prefill.option.connection_option_id, language, prefill.option.display_name)}</option>)}
</optgroup>
- {metadataProviders.length > 0 && <optgroup label={zh ? '供应商资料记录' : 'Provider metadata records'}>
- {metadataPrefills.filter(prefill => prefill.kind === 'provider').map(prefill => <option key={prefill.key} value={prefill.key}>{prefill.provider.display_name}</option>)}
- </optgroup>}
+
</select></label>
{selectedPrefill && <p className="field-help">{zh
? `已收录 ${metadataCandidates.length} 个模型,检查接入后统一选择;未知能力采用可编辑兜底:上下文 200K、输出 32K、工具与流式开启、视觉关闭、思考开关。`
@@ -649,11 +660,13 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {
</> : optionsLoading
? <div className="oc-status-row" role="status"><span className="oc-spinner" /><div className="row-main"><strong>{zh ? '正在读取接入方式' : 'Loading connection'}</strong><p>{zh ? '从本机可信目录确认当前支持的产品。' : 'Checking supported products in the local trusted catalog.'}</p></div></div>
: registeredOption
- ? <label className="field"><span className="field-label">{zh ? '接入方式' : 'Connection'}</span><select className="select" value={registeredOption.connection_option_id} onChange={event => {
- setRegisteredOptionId(event.target.value);
- invalidate(current => ({ ...current, candidate_ref: null, models: [] }), true, 'connection');
- }}>{registeredOptions.map(option => <option key={option.connection_option_id} value={option.connection_option_id}>{connectionName(option.connection_option_id, language, option.display_name)}</option>)}</select><span className="field-help">{registeredLabel.detail}</span></label>
+ ? <ConnectionTemplatePicker options={registeredOptions} value={registeredOption.connection_option_id} language={language} onChange={id => {
+ setRegisteredOptionId(id);
+ const option = registeredOptions.find(value => value.connection_option_id === id)!;
+ invalidate(current => ({ ...current, candidate_ref: null, models: [], display_name: suggestedName(connectionName(id, language, option.display_name)) }), true, 'connection');
+ }} />
: <div className="callout warn"><UiIcon name="warning" /><div><strong>{zh ? '当前没有可用的内置接入' : 'No built-in connection is available'}</strong><p>{connectionErrorMessage(error || 'MODEL_CONNECTION_OPTION_UNAVAILABLE', zh)}</p><button className="btn" type="button" onClick={() => void loadConnectionOptions()}>{zh ? '重新读取' : 'Reload'}</button></div></div>}
+ {!custom && <label className="field"><span className="field-label">{zh ? '接入名称' : 'Connection name'}</span><input className="input" maxLength={60} value={draft.display_name} placeholder={zh ? '例如:百炼 · 团队' : 'e.g. Bailian · Team'} onChange={event => invalidate(current => ({ ...current, display_name: event.target.value }), false, 'connection')} /><span className="field-help">{zh ? '同一模板可以保存多份独立接入,分别管理凭据和模型。' : 'Save independent connections from the same template, each with its own keys and models.'}</span></label>}
{!custom && registeredOption && <section>
<ProviderIcon optionId={registeredOption.connection_option_id} language={language} />
<p>{connectionTemplate(registeredOption.connection_option_id)?.description[language]}</p>
@@ -714,7 +727,7 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {
{result.directory === 'partial' && <div className="callout warn"><UiIcon name="warning" /><span>{zh ? '模型目录只读取到一部分。可以先保存已确认的模型,稍后再重新检查。' : 'Only part of the model catalog was read. You can save confirmed models and check again later.'}</span></div>}
<fieldset className="v3-catalog model-result-list" disabled={!props.mutable}><legend className="sr-only">{zh ? '选择保存的模型' : 'Select models to save'}</legend>{result.candidate.models.map(model => {
const canSelect = modelCanBeSelected(result, model, true);
- return <div className="model-result-row" key={model.model_ref}><label className="check-row"><input type="checkbox" disabled={!canSelect} checked={canSelect && selected.has(model.model_ref)} onChange={event => setSelected(current => { const next = new Set(current); if (event.target.checked) next.add(model.model_ref); else next.delete(model.model_ref); setError(''); return next; })} /><div><strong>{model.display_name}</strong><span>{custom ? draft.display_name : `${registeredLabel.title} · ${registeredLabel.detail}`}{model.fact_basis === 'runtime_fallback' ? ` · ${zh ? '运行时保守兜底' : 'Conservative runtime fallback'}` : ''}{!canSelect ? ` · ${modelAvailabilityMessage(model.reason, zh)}` : ''}</span></div></label>{custom && !canSelect && <button className="btn btn-quiet" type="button" onClick={() => {
+ return <div className="model-result-row" key={model.model_ref}><label className="check-row"><input type="checkbox" disabled={!canSelect} checked={canSelect && selected.has(model.model_ref)} onChange={event => setSelected(current => { const next = new Set(current); if (event.target.checked) next.add(model.model_ref); else next.delete(model.model_ref); setError(''); return next; })} /><div><strong>{model.display_name}</strong><span>{draft.display_name || registeredLabel.title}{model.fact_basis === 'runtime_fallback' ? ` · ${zh ? '运行时保守兜底' : 'Conservative runtime fallback'}` : ''}{!canSelect ? ` · ${modelAvailabilityMessage(model.reason, zh)}` : ''}</span></div></label>{custom && !canSelect && <button className="btn btn-quiet" type="button" onClick={() => {
const prefilled = draftRef.current.models.find(value => value.upstream_model_id === model.upstream_model_id);
const manualDraft = { ...draftRef.current, edit_revision: draftRef.current.edit_revision + 1, check_id: '', models: [prefilled ?? blankModel(model.upstream_model_id, model.display_name)] };
draftRef.current = manualDraft; setDraft(manualDraft); setResult(null); setScreen('manual'); setError('');
diff --git a/apps/desktop/src/features/model-connections/form-support.tsx b/apps/desktop/src/features/model-connections/form-support.tsx
index 68232d35..42209cdc 100644
--- a/apps/desktop/src/features/model-connections/form-support.tsx
+++ b/apps/desktop/src/features/model-connections/form-support.tsx
@@ -42,6 +42,7 @@ export function connectionErrorMessage(code: string, zh: boolean): string {
if (code === 'MODEL_REASONING_INVALID') return zh
? '请填写有效的思考档位或预算范围。'
: 'Enter valid reasoning levels or a valid budget range.';
+ if (code === 'CONNECTION_NAME_CONFLICT') return zh ? '请输入 1–60 个字符的名称,并与其他接入区分。' : 'Use a distinct connection name with 1–60 characters.';
if (code === 'MODEL_SELECTION_REQUIRED') return zh ? '至少选择一个模型。' : 'Select at least one model.';
if (code === 'MODEL_DIRECTORY_EMPTY') return zh
? '没有读取到可接入的模型。请检查服务地址,或使用自定义 API 补充未知模型。'
diff --git a/apps/desktop/src/features/model-connections/types.ts b/apps/desktop/src/features/model-connections/types.ts
index 852cc26e..be03cb5b 100644
--- a/apps/desktop/src/features/model-connections/types.ts
+++ b/apps/desktop/src/features/model-connections/types.ts
@@ -293,6 +293,7 @@ export type ChangeSpec = {
desired_state: unknown;
};
export type ComputeManagementChange = {
+ edit?: import('../models/types').ManagementChange['edit'];
schema: 'hiroute.compute-management-change/v2';
subject: { kind: 'candidate'; candidate: ComputeCandidateRef };
expected_revisions: RevisionSet;
@@ -379,6 +380,9 @@ export type ModelConnectionBackend = {
};
export type ModelConnectionFormProps = {
+ existingNames?: string[];
+ appendTo?: import('../models/types').ManagedSource;
+ savedSource?: import('../models/types').ManagedSource;
language: Language;
mutable: boolean;
initialDraft: ModelConnectionDraft;
diff --git a/apps/desktop/src/features/models/AppendConnectionModels.tsx b/apps/desktop/src/features/models/AppendConnectionModels.tsx
new file mode 100644
index 00000000..da55a41b
--- /dev/null
+++ b/apps/desktop/src/features/models/AppendConnectionModels.tsx
@@ -0,0 +1,57 @@
+import { useEffect, useRef, useState } from 'react';
+import { Dialog } from '../../ui';
+import type { ModelConnectionCheckView } from '../model-connections/types';
+import type { ManagedSource, ManagementChange, RevisionSet, SavePreview } from './types';
+
+export function AppendConnectionModels(props: {
+ source: ManagedSource; language: 'zh' | 'en'; mutable: boolean;
+ onLoad(source: ManagedSource): Promise<{ checked: ModelConnectionCheckView; revisions: RevisionSet }>;
+ onPreview(change: ManagementChange): Promise<SavePreview>;
+ onApply(preview: SavePreview): Promise<'saved' | 'uncertain'>;
+ onRefresh(): Promise<void>; onClose(): void; onManual?(): void;
+}) {
+ const zh = props.language === 'zh';
+ const [result, setResult] = useState<Awaited<ReturnType<typeof props.onLoad>> | null>(null);
+ const [selected, setSelected] = useState<Set<string>>(new Set());
+ const [query, setQuery] = useState('');
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState('');
+ const [attempt, setAttempt] = useState(0);
+ const submitting = useRef(false);
+ useEffect(() => {
+ let active = true;
+ setLoading(true); setError(''); setResult(null); setSelected(new Set());
+ props.onLoad(props.source).then(value => { if (active) setResult(value); }).catch(() => {
+ if (active) setError(zh ? '无法读取这份接入的模型。请检查凭据和网络后重试。' : 'Could not read models for this connection. Check credentials and network, then retry.');
+ }).finally(() => { if (active) setLoading(false); });
+ return () => { active = false; };
+ }, [props.source.source_id, props.source.revision, attempt]);
+ const existing = new Set(props.source.models.map(model => model.upstream_model_id));
+ const models = result?.checked.candidate.models.filter(model => `${model.display_name} ${model.upstream_model_id}`.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase())) ?? [];
+ async function save() {
+ if (!result || !selected.size || submitting.current || !props.mutable) return;
+ submitting.current = true; setSaving(true); setError('');
+ try {
+ const preview = await props.onPreview({ schema: 'hiroute.compute-management-change/v2',
+ subject: { kind: 'candidate', candidate: result.checked.candidate.candidate },
+ expected_revisions: result.revisions, selected_model_refs: [...selected],
+ intent: props.source.state === 'disabled' ? 'save_disabled' : 'save_ready', key_edits: [],
+ edit: { action: 'append_models' }, validation: result.checked.candidate.validation });
+ await props.onApply(preview);
+ props.onClose();
+ await props.onRefresh();
+ } catch { setError(zh ? '未能添加模型,已有配置未被替换。请重新读取后重试。' : 'Models could not be added. Existing settings were not replaced. Reload and retry.'); setResult(null); }
+ finally { submitting.current = false; setSaving(false); }
+ }
+ return <Dialog open title={zh ? `向「${props.source.display_name}」添加模型` : `Add models to “${props.source.display_name}”`} closeLabel={zh ? '关闭' : 'Close'} closeDisabled={saving} onClose={props.onClose}
+ footer={<><button className="btn" type="button" disabled={saving} onClick={props.onClose}>{zh ? '取消' : 'Cancel'}</button><span className="mc-footer-spacer" /><button className="btn btn-primary" type="button" disabled={!props.mutable || loading || saving || !result || !selected.size} onClick={() => void save()}>{saving ? zh ? '正在添加…' : 'Adding…' : zh ? `添加 ${selected.size} 个模型` : `Add ${selected.size} models`}</button></>}>
+ <p>{zh ? `复用此接入的端点和凭据,保留已有 ${props.source.models.length} 个模型。` : `Reuse this connection's endpoints and credentials; retain its ${props.source.models.length} existing models.`}</p>
+ {props.source.state === 'disabled' && <p className="field-help">{zh ? '添加后此接入仍保持停用。' : 'This connection will remain disabled after adding models.'}</p>}
+ {loading ? <p role="status">{zh ? '正在读取可添加的模型…' : 'Reading available models…'}</p> : <>
+ {error && <div className="callout warn" role="alert">{error}<button className="btn" type="button" onClick={() => setAttempt(value => value + 1)}>{zh ? '重新读取' : 'Reload'}</button></div>}
+ {result && <><label className="field"><span className="field-label">{zh ? '搜索模型' : 'Search models'}</span><input className="input" value={query} onChange={event => setQuery(event.target.value)} /></label><div className="model-result-list">{models.map(model => <label className="check-row" key={model.model_ref}><input type="checkbox" disabled={saving || existing.has(model.upstream_model_id) || !model.selectable} checked={existing.has(model.upstream_model_id) || selected.has(model.model_ref)} onChange={event => setSelected(current => { const next = new Set(current); if (event.target.checked) next.add(model.model_ref); else next.delete(model.model_ref); return next; })} /><span><strong>{model.display_name}</strong><span className="field-help">{existing.has(model.upstream_model_id) ? zh ? '已添加' : 'Already added' : model.upstream_model_id}</span></span></label>)}</div>{!models.length && <p role="status">{zh ? '没有匹配的可添加模型。' : 'No matching models to add.'}</p>}</>}
+ {props.onManual && <button className="btn btn-quiet" type="button" disabled={saving} onClick={props.onManual}>{zh ? '手工添加模型 ID' : 'Add a model ID manually'}</button>}
+ </>}
+ </Dialog>;
+}
diff --git a/apps/desktop/src/features/models/ConnectionLifecycleDialog.tsx b/apps/desktop/src/features/models/ConnectionLifecycleDialog.tsx
new file mode 100644
index 00000000..2f444f4b
--- /dev/null
+++ b/apps/desktop/src/features/models/ConnectionLifecycleDialog.tsx
@@ -0,0 +1,106 @@
+import { useEffect, useRef, useState } from 'react';
+import { invoke } from '@tauri-apps/api/core';
+import { Dialog } from '../../ui';
+import type { ManagedModel, ManagedSource, ManagementChange, ManagementSnapshot, SavePreview } from './types';
+
+type Props = {
+ language: 'zh' | 'en';
+ source: ManagedSource;
+ model?: ManagedModel;
+ action: 'rename' | 'remove' | 'delete';
+ snapshot: ManagementSnapshot;
+ mutable: boolean;
+ planNames: Record<string, string>;
+ onPreview(change: ManagementChange): Promise<SavePreview>;
+ onApply(preview: SavePreview): Promise<'saved' | 'uncertain'>;
+ onRefresh(): Promise<void>;
+ onClose(): void;
+ onOpenPlan?(id: string): void;
+};
+
+export function ConnectionLifecycleDialog(props: Props) {
+ const { source, model, action } = props;
+ const zh = props.language === 'zh';
+ const text = (cn: string, en: string) => zh ? cn : en;
+ const rename = action === 'rename';
+ const changed = props.snapshot.sources.find(item => item.source_id === source.source_id)?.revision !== source.revision;
+ const entire = action === 'delete' || (!rename && source.models.length === 1);
+ const [name, setName] = useState(source.display_name);
+ const [preview, setPreview] = useState<SavePreview | null>(null);
+ const [loading, setLoading] = useState(!rename);
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState('');
+ const submitting = useRef(false);
+ const change = (displayName = name): ManagementChange => ({
+ schema: 'hiroute.compute-management-change/v2',
+ subject: { kind: 'saved_source', source_id: source.source_id },
+ expected_revisions: props.snapshot.revisions,
+ selected_model_refs: !rename && !entire && model ? [model.model_ref] : [],
+ intent: source.state === 'disabled' ? 'save_disabled' : 'save_ready',
+ key_edits: [],
+ edit: rename ? { action: 'rename', display_name: displayName.trim() } : { action: entire ? 'delete' : 'remove_models' },
+ });
+ useEffect(() => {
+ if (rename || changed) return;
+ let active = true;
+ setLoading(true);
+ setPreview(null);
+ setError('');
+ props.onPreview(change()).then(value => { if (active) setPreview(value); }).catch(() => {
+ if (active) setError(text('暂时无法确认引用情况,请刷新后重试。', 'References could not be checked. Refresh and try again.'));
+ }).finally(() => { if (active) setLoading(false); });
+ return () => { active = false; };
+ // A changed management revision invalidates the preview. Callback identity is not a revision.
+ }, [source.source_id, source.revision, model?.model_ref, action, changed, props.snapshot.revisions.target]);
+ const references = preview?.affected_plan_refs ?? [];
+ async function refreshReferences() {
+ if (changed || submitting.current || !props.mutable) return;
+ submitting.current = true;
+ setSaving(true);
+ setError('');
+ try {
+ await invoke('refresh_route_references', { language: props.language });
+ // Native Session retains the operation identity and observes uncertain responses.
+ // Reopen after that operation completes to obtain a fresh deletion preview.
+ props.onClose();
+ await props.onRefresh();
+ } catch {
+ setError(text('引用状态暂未更新,请稍后重试。未删除任何配置。', 'References could not be updated. Retry later; no configuration was deleted.'));
+ } finally { submitting.current = false; setSaving(false); }
+ }
+ async function apply() {
+ if (changed || submitting.current || !props.mutable || (!rename && (!preview || references.length))) return;
+ if (rename && (!name.trim() || name.trim().length > 60 || /[\u0000-\u001f\u007f]/.test(name)
+ || props.snapshot.sources.some(other => other.source_id !== source.source_id && other.display_name.trim() === name.trim()))) {
+ setError(text('请输入 1–60 个字符的名称,并与其他接入区分。', 'Use a distinct connection name with 1–60 characters.'));
+ return;
+ }
+ submitting.current = true;
+ setSaving(true);
+ setError('');
+ try {
+ const accepted = rename ? await props.onPreview(change()) : preview!;
+ await props.onApply(accepted);
+ // The host owns pending-operation recovery; an uncertain response must not invite a
+ // second delete with a fresh idempotency key.
+ props.onClose();
+ await props.onRefresh();
+ } catch {
+ setError(text('未能完成操作。配置或引用可能已变化,请刷新后重试。', 'The operation did not complete. Configuration or references may have changed; refresh and retry.'));
+ setPreview(null);
+ } finally { submitting.current = false; setSaving(false); }
+ }
+ const title = rename ? text('重命名接入', 'Rename connection') : entire ? text(`删除「${source.display_name}」?`, `Delete “${source.display_name}”?`) : text(`移除「${model?.display_name}」?`, `Remove “${model?.display_name}”?`);
+ return <Dialog open title={title} closeLabel={text('关闭', 'Close')} closeDisabled={saving} onClose={props.onClose}
+ footer={<><button className="btn" type="button" disabled={saving} onClick={props.onClose}>{text('取消', 'Cancel')}</button><span className="mc-footer-spacer" /><button className={`btn ${rename ? 'btn-primary' : 'btn-danger'}`} type="button" disabled={changed || !props.mutable || loading || saving || (!rename && (!preview || references.length > 0))} onClick={() => void apply()}>{saving ? text('正在保存…', 'Saving…') : rename ? text('保存名称', 'Save name') : entire ? text('删除接入', 'Delete connection') : text('移除模型', 'Remove model')}</button></>}>
+ {rename ? <label className="field"><span className="field-label">{text('接入名称', 'Connection name')}</span><input data-autofocus className="input" maxLength={60} value={name} disabled={saving} onChange={event => setName(event.target.value)} /></label> : <>
+ <p>{entire ? text(`将删除这份接入及所属 ${source.models.length} 个模型。`, `Delete this connection and its ${source.models.length} models.`) : text('仅从这份接入移除此模型,保留其他模型及共享凭据。', 'Remove this model from this connection; retain other models and shared credentials.')}</p>
+ {entire && <p className="muted">{source.provenance === 'connector_owned' ? text('保留原生客户端登录和配置;再次扫描后需重新添加。', 'Native client sign-ins and configuration are retained. Add the connection again after a new scan.') : text('同时清理这份接入在 HiRoute 中保存的专属凭据。历史使用记录保留。', 'Also remove credentials owned by this HiRoute connection. Usage history is retained.')}</p>}
+ {action === 'remove' && entire && <p className="field-help">{text('这是最后一个模型,将一并删除所属接入。', 'This is the last model; its connection will also be deleted.')}</p>}
+ {loading && <p role="status">{text('正在检查路由和任务引用…', 'Checking route and task references…')}</p>}
+ {!!references.length && <div className="callout warn" role="alert"><div><strong>{text('仍被引用,请先调整引用再删除。', 'Still referenced. Update references before deleting.')}</strong><p>{text('已停用的路由和仍保留执行版本的任务也会阻止删除。', 'Disabled routes and retained execution versions also prevent deletion.')}</p>{references.map(id => <button key={id} className="btn btn-quiet" type="button" disabled={saving || !props.onOpenPlan || !props.planNames[id]} onClick={() => { props.onClose(); props.onOpenPlan?.(id); }}>{props.planNames[id] ?? id}</button>)}<p>{text('若已删除路由或调整其模型,请更新引用状态,完成后再次打开此窗口确认删除。', 'After deleting a route or changing its models, update references, then reopen this dialog to confirm removal.')}</p><button className="btn" type="button" disabled={changed || !props.mutable || saving || loading} onClick={() => void refreshReferences()}>{text('更新引用状态', 'Update references')}</button></div></div>}
+ </>}
+ {changed && <p className="callout warn" role="alert">{text('这份接入已发生变化,请关闭后重新打开,确认当前配置。', 'This connection changed. Close and reopen to review its current configuration.')}</p>}
+ {error && <div className="callout bad" role="alert">{error}</div>}
+ </Dialog>;
+}
diff --git a/apps/desktop/src/features/models/Models.tsx b/apps/desktop/src/features/models/Models.tsx
index 421157c5..a1eaa851 100644
--- a/apps/desktop/src/features/models/Models.tsx
+++ b/apps/desktop/src/features/models/Models.tsx
@@ -10,6 +10,7 @@ import type { PriceDisplay } from '../model-reference/types';
import { clientOperationId } from '../model-connections/state';
import { addDraftKey, clearSecrets, createDraft, moveDraftKey, type ModelDraft } from './model-draft';
import { subscriptionAttentionCopy } from './subscription-copy';
+import { ConnectionLifecycleDialog } from './ConnectionLifecycleDialog';
import type {
CandidateRef,
KeyEdit,
@@ -41,6 +42,7 @@ type Props = {
onRecheck?(source: ManagedSource, checkId: string, editRevision: number): Promise<'saved' | 'uncertain'>;
onCancelRecheck?(checkId: string): Promise<void>;
onReconnect?(source: ManagedSource): void;
+ onAppend?(source: ManagedSource): void;
onSourceStateSaved?(enabled: boolean): void;
mutable: boolean;
};
@@ -59,7 +61,13 @@ function modelMatchesFilter(source: ManagedSource, model: ManagedModel | undefin
return sourceAccess(source) === filter;
}
-function modelAvailability(_source: ManagedSource, model: ManagedModel | undefined) {
+function modelAvailability(source: ManagedSource, model: ManagedModel | undefined): NonNullable<ManagedModel['presentation']>['availability'] {
+ if (!model) {
+ if (source.state === 'disabled') return 'disabled';
+ if (source.state === 'needs_credential' || source.state === 'needs_authorization') return 'needs_credentials';
+ if (source.models.some(member => member.presentation?.availability === 'available')) return 'available';
+ if (source.models.length && source.models.every(member => member.presentation?.availability === 'unavailable')) return 'unavailable';
+ }
if (model?.presentation?.availability) return model.presentation.availability;
// Source health is not a per-binding readiness proof. Older or partial
// snapshots keep their saved rows visible, but fail closed until the model
@@ -86,7 +94,10 @@ export function Models(props: Props) {
const text = (cn: string, en: string) => zh ? cn : en;
const [query, setQuery] = useState('');
const [filter, setFilter] = useState<Filter>('all');
+ const [view, setView] = useState<'models' | 'connections'>('models');
+ const [lifecycle, setLifecycle] = useState<{ source: ManagedSource; model?: ManagedModel; action: 'rename' | 'remove' | 'delete' } | null>(null);
const [selectedSourceId, setSelectedSourceId] = useState<string | null>(props.initialSourceId ?? props.snapshot.sources[0]?.source_id ?? null);
+ const appliedInitialSource = useRef<string | null>(null);
const [selectedModelId, setSelectedModelId] = useState<string | null>(null);
const [detailOpen, setDetailOpen] = useState(false);
const [draft, setDraft] = useState<ModelDraft | null>(null);
@@ -104,20 +115,22 @@ export function Models(props: Props) {
const needle = query.trim().toLocaleLowerCase();
const entries = useMemo(() => props.snapshot.sources.flatMap<{ source: ManagedSource; model: ManagedModel | undefined }>(source => {
- const models = source.models.length ? source.models : [undefined];
+ const models = view === 'connections' ? [undefined] : source.models.length ? source.models : [undefined];
return models
- .filter(model => modelMatchesFilter(source, model, filter))
- .filter(model => !needle || `${model?.display_name ?? ''} ${source.display_name} ${source.connection_identity?.product_label ?? ''}`.toLocaleLowerCase().includes(needle))
+ .filter(model => view === 'connections' && filter === 'free' ? source.models.some(member => modelMatchesFilter(source, member, filter)) : modelMatchesFilter(source, model, filter))
+ .filter(model => !needle || `${model?.display_name ?? source.models.map(member => member.display_name).join(' ')} ${source.display_name} ${source.connection_identity?.product_label ?? ''}`.toLocaleLowerCase().includes(needle))
.map(model => ({ source, model }));
- }), [filter, needle, props.snapshot.sources]);
+ }), [filter, needle, props.snapshot.sources, view]);
const selectedEntry = entries.find(item => item.source.source_id === selectedSourceId
- && (!selectedModelId || item.model?.model_ref === selectedModelId));
+ && (view === 'connections' || !selectedModelId || item.model?.model_ref === selectedModelId));
const activeEntry = selectedEntry ?? entries[0];
const source = activeEntry?.source;
const model = activeEntry?.model;
const access = source ? sourceAccess(source) : 'unknown';
- const sourceLabel = source ? connectionLabel(source, props.language) : '';
+ const duplicateName = (item: ManagedSource) => props.snapshot.sources.filter(other => other.display_name === item.display_name).length > 1;
+ const nameLabel = (item: ManagedSource) => duplicateName(item) ? `${item.display_name} · ${item.source_id.slice(-8)}` : item.display_name;
+ const sourceLabel = source ? `${connectionLabel(source, props.language)}${duplicateName(source) ? ` · ${source.source_id.slice(-8)}` : ''}` : '';
const subscriptionMode = props.snapshot.subscription_modes?.find(item => item.source_id === source?.source_id && item.source_revision === source?.revision)?.mode;
const connectorManaged = source?.provenance === 'connector_owned';
const canManageCredentials = Boolean(props.mutable && source && !connectorManaged && access !== 'subscription'
@@ -125,7 +138,7 @@ export function Models(props: Props) {
&& source.actions.some(action => action === 'edit' || action === 'add_key' || action === 'enable' || action === 'disable'));
const canReauthorize = Boolean(props.mutable && source?.actions.includes('reauthorize') && props.onReauthorize);
const usedPlans = useMemo(() => !model ? [] : (props.plans ?? []).filter(plan => {
- if (plan.head.status !== 'enabled') return false;
+ if (plan.head.status === 'deleted') return false;
const strategy = plan.desired.strategy;
const selections = strategy.routing ? branchSelections(strategy.routing)
: [...(strategy.candidates ?? []), ...(strategy.economy ?? []), ...(strategy.primary ?? [])];
@@ -137,9 +150,13 @@ export function Models(props: Props) {
useDiscardGuard('models', dirty, props.language, confirmCredentialReplacement);
useEffect(() => {
+ if (!props.initialSourceId) { appliedInitialSource.current = null; return; }
+ if (appliedInitialSource.current === props.initialSourceId) return;
if (!props.initialSourceId || !props.snapshot.sources.some(item => item.source_id === props.initialSourceId)) return;
+ appliedInitialSource.current = props.initialSourceId;
setFilter('all');
setQuery('');
+ setSelectedModelId(null);
setSelectedSourceId(props.initialSourceId);
}, [props.initialSourceId, props.snapshot.sources]);
@@ -363,12 +380,16 @@ export function Models(props: Props) {
</div>
</div>
<nav className="master-list native-list" aria-label={text('模型', 'Models')}>
+ <div className="filter-row" role="group" aria-label={text('查看方式', 'View')}>
+ <button className="filter-chip" type="button" aria-pressed={view === 'models'} onClick={() => setView('models')}>{text('按模型', 'Models')}</button>
+ <button className="filter-chip" type="button" aria-pressed={view === 'connections'} onClick={() => setView('connections')}>{text('按接入', 'Connections')}</button>
+ </div>
{entries.map(item => {
const active = source?.source_id === item.source.source_id && model?.model_ref === item.model?.model_ref;
const itemStatus = modelAvailability(item.source, item.model);
return <button ref={active ? activeRow : undefined} className={`list-row${active ? ' active' : ''}`} key={item.model?.binding_id ?? item.source.source_id} aria-current={active ? 'page' : undefined} onClick={() => selectEntry(item.source, item.model)}>
<ProviderIcon optionId={item.source.display_template_id ?? item.source.connection_identity?.connection_option_id} language={props.language} />
- <span className="row-main"><span className="row-title">{item.model?.display_name || item.source.display_name}</span><span className="row-meta">{connectionLabel(item.source, props.language)}</span></span>
+ <span className="row-main"><span className="row-title">{item.model?.display_name || nameLabel(item.source)}</span><span className="row-meta">{view === 'connections' ? `${connectionName(item.source.connection_identity?.connection_option_id, props.language, item.source.connection_identity?.product_label ?? '')} · ${item.source.models.length} ${text('个模型', 'models')}` : `${connectionLabel(item.source, props.language)}${duplicateName(item.source) ? ` · ${item.source.source_id.slice(-8)}` : ''}`}</span></span>
<StatusBadge value={itemStatus} reason={item.model?.presentation?.reason_code} subscription={sourceAccess(item.source) === 'subscription'} compact language={props.language} />
</button>;
})}
@@ -400,6 +421,10 @@ export function Models(props: Props) {
<section className="detail-section">
<div className="detail-section-head"><h3>{text('接入来源', 'Connection')}</h3>{canManageCredentials && <button className="btn btn-quiet" type="button" onClick={() => setDraft(createDraft(source))}>{text('管理凭据', 'Manage credentials')}</button>}</div>
+ <strong>{source.display_name}</strong>
+ <p className="field-help">{connectionName(source.connection_identity?.connection_option_id, props.language, source.connection_identity?.product_label ?? '')}</p>
+ <div className="actions"><button className="btn btn-quiet" type="button" disabled={!props.mutable || submitting} onClick={() => setLifecycle({ source, action: 'rename' })}>{text('重命名', 'Rename')}</button>{props.onAppend && <button className="btn" type="button" disabled={!props.mutable || submitting} onClick={() => props.onAppend?.(source)}>{text('向此接入添加模型', 'Add models to this connection')}</button>}</div>
+ <p className="field-help">{text(`此接入包含 ${source.models.length} 个模型。端点、Key 和启停操作作用于这份接入。`, `This connection has ${source.models.length} models. Endpoints, keys and enabled state belong to this connection.`)}</p>
<p className="muted">{access === 'subscription'
? subscriptionMode === 'cpa_managed'
? text('独立登录 · 由 HiRoute 自动续期,不依赖原生客户端。', 'Independent sign-in · HiRoute renews access without the native client.')
@@ -415,6 +440,8 @@ export function Models(props: Props) {
{source.provenance === 'user_configured' && props.onReconnect && <div className="actions"><button className="btn" type="button" disabled={!props.mutable || submitting} onClick={() => props.onReconnect?.(source)}>{text('编辑端点', 'Edit endpoints')}</button><span className="field-help">{text('一个来源的端点共用已保存的 API Key。', 'Endpoints in one connection share the saved API key.')}</span></div>}
{source.provenance !== 'connector_owned' && <div className="actions"><button className="btn" type="button" disabled={!props.mutable || submitting || !source.actions.includes(source.state === 'disabled' ? 'enable' : 'disable')} onClick={() => void changeSourceState(source.state === 'disabled')}>{submitting ? text('正在保存…', 'Saving…') : source.state === 'disabled' ? text('启用接入', 'Enable connection') : text('停用接入', 'Disable connection')}</button></div>}
{stateChangeError && <div className="callout bad" role="alert" data-error-code={stateChangeError}><UiIcon name="warning" /><span>{text('接入状态未修改;请刷新后重试。', 'The connection state was not changed. Refresh and try again.')}</span></div>}
+ {view === 'connections' && <div>{source.models.map(member => <button key={member.binding_id} className="list-row" type="button" onClick={() => { setView('models'); selectEntry(source, member); }}><span className="row-main">{member.display_name}</span><UiIcon name="chevronRight" /></button>)}</div>}
+ <button className="btn btn-quiet" type="button" disabled={!props.mutable || submitting} onClick={() => setLifecycle({ source, action: 'delete' })}>{text('删除接入', 'Delete connection')}</button>
</section>
{model && <section className="detail-section">
@@ -424,13 +451,16 @@ export function Models(props: Props) {
{model && <section className="detail-section">
<div className="detail-section-head"><h3>{text('用于这些路由', 'Used in these routes')}</h3></div>
- {usedPlans.length ? usedPlans.map(plan => <button className="list-row v3-linked" type="button" key={plan.agent_plan_id} onClick={() => props.onOpenPlan?.(plan.agent_plan_id)} disabled={!props.onOpenPlan}><UiIcon name="route" /><span className="row-main">{plan.desired.display_name}</span><UiIcon name="chevronRight" /></button>) : <><p className="muted">{text('还没有加入已发布的路由。', 'Not used by a published route yet.')}</p>{props.onCreatePlan && model && <button className="btn" type="button" onClick={() => props.onCreatePlan?.(model.binding_id)}><UiIcon name="plus" />{text('创建智能路由', 'Create routing')}</button>}</>}
+ {usedPlans.length ? usedPlans.map(plan => <button className="list-row v3-linked" type="button" key={plan.agent_plan_id} onClick={() => props.onOpenPlan?.(plan.agent_plan_id)} disabled={!props.onOpenPlan}><UiIcon name="route" /><span className="row-main">{plan.desired.display_name}{plan.head.status === 'disabled' ? text('(已停用)', ' (disabled)') : ''}</span><UiIcon name="chevronRight" /></button>) : <><p className="muted">{text('还没有加入已发布的路由。', 'Not used by a published route yet.')}</p>{props.onCreatePlan && model && <button className="btn" type="button" onClick={() => props.onCreatePlan?.(model.binding_id)}><UiIcon name="plus" />{text('创建智能路由', 'Create routing')}</button>}</>}
</section>}
+ {model && <section className="detail-section"><div className="detail-section-head"><h3>{text('移除模型', 'Remove model')}</h3><button className="btn btn-quiet" type="button" disabled={!props.mutable || submitting} onClick={() => setLifecycle({ source, model, action: 'remove' })}>{text('移除模型', 'Remove model')}</button></div><p className="muted">{text('仅从所属接入移除这个模型。', 'Remove this model from its connection.')}</p></section>}
+
</div> : <div className="empty-state"><div><div className="empty-icon"><UiIcon name="models" /></div><h3>{text('选择一个模型', 'Select a model')}</h3></div></div>}
</section>
</div>
+ {lifecycle && <ConnectionLifecycleDialog {...lifecycle} language={props.language} snapshot={props.snapshot} mutable={props.mutable} planNames={Object.fromEntries((props.plans ?? []).map(plan => [plan.agent_plan_id, `${plan.desired.display_name}${plan.head.status === 'disabled' ? text('(已停用)', ' (disabled)') : ''}`]))} onPreview={props.onPreview} onApply={props.onApply} onRefresh={props.onRefresh} onOpenPlan={props.onOpenPlan} onClose={() => setLifecycle(null)} />}
<Dialog
open={Boolean(draft && source)}
title={text('管理接入凭据', 'Manage connection credentials')}
@@ -449,9 +479,10 @@ function connectionLabel(source: ManagedSource, language: 'zh' | 'en') {
const product = connectionName(source.connection_identity?.connection_option_id, language, source.connection_identity?.product_label ?? '');
const access = sourceAccess(source);
if (product) {
- if (access === 'subscription') return `${product} · OAuth`;
- if (access === 'api') return `${product} · API`;
- return product;
+ if (source.display_name && source.display_name !== product) return `${source.display_name} · ${product}`;
+ if (access === 'subscription') return `${source.display_name || product} · OAuth`;
+ if (access === 'api') return `${source.display_name || product} · API`;
+ return source.display_name || product;
}
return source.display_name || (language === 'zh' ? '已保存接入' : 'Saved connection');
}
diff --git a/apps/desktop/src/features/models/types.ts b/apps/desktop/src/features/models/types.ts
index 70507e34..1418a130 100644
--- a/apps/desktop/src/features/models/types.ts
+++ b/apps/desktop/src/features/models/types.ts
@@ -73,7 +73,7 @@ export type ManagedSource = {
models: ManagedModel[];
keys: ManagedKey[];
ready_model_count: number;
- actions: ('edit' | 'add_key' | 'recheck' | 'reauthorize' | 'enable' | 'disable')[];
+ actions: ('edit' | 'rename' | 'append_models' | 'remove_models' | 'delete' | 'add_key' | 'recheck' | 'reauthorize' | 'enable' | 'disable')[];
};
export type SubscriptionMode = 'native_borrowed' | 'cpa_managed';
@@ -94,6 +94,7 @@ export type KeyEdit =
| { action: 'set_order'; key_ids: string[] };
export type ManagementChange = {
+ edit?: { action: 'rename'; display_name: string } | { action: 'append_models' | 'remove_models' | 'delete' };
schema: 'hiroute.compute-management-change/v2';
subject:
| { kind: 'saved_source'; source_id: string }
diff --git a/apps/desktop/src/occami/styles.css b/apps/desktop/src/occami/styles.css
index 0c28c34a..b602c5bf 100644
--- a/apps/desktop/src/occami/styles.css
+++ b/apps/desktop/src/occami/styles.css
@@ -6,6 +6,13 @@
@import './styles/collaboration.css';
@import './styles/v3.css';
@import './styles/occami.css';
+.mc-template-directory { display:grid; gap:12px; min-width:0; }
+.mc-template-row { display:flex; align-items:center; gap:10px; padding:10px; border:1px solid var(--border); border-radius:8px; cursor:pointer; margin-bottom:6px; }
+.mc-template-row.selected { border-color:var(--accent); background:var(--accent-soft); }
+.mc-template-row .row-main { min-width:0; overflow-wrap:anywhere; }
+.mc-template-row .field-help { display:block; }
+.mc-template-pagination { display:flex; flex-wrap:wrap; gap:8px; align-items:center; justify-content:flex-end; }
+.mc-template-pagination > span:first-child { margin-right:auto; }
/* Host differences: no review bar or fake native controls; retained React pages. */
#root, .occami-root { width:100%; height:100%; min-height:0; }
.sr-only {position:absolute!important;width:1px!important;height:1px!important;padding:0!important;margin:-1px!important;overflow:hidden!important;clip:rect(0,0,0,0)!important;white-space:nowrap!important;border:0!important;}
diff --git a/apps/desktop/src/plan-editor.tsx b/apps/desktop/src/plan-editor.tsx
index f0b11146..dbc5e8de 100644
--- a/apps/desktop/src/plan-editor.tsx
+++ b/apps/desktop/src/plan-editor.tsx
@@ -8,7 +8,6 @@ import { AgentProtocolChoice, type ProtocolAdvice } from './features/AgentProtoc
import { contextWindowError, type ContextWindowBounds } from './plan-context-window';
import { DEFAULT_REQUEST_TIMEOUT_MS, requestTimeoutError } from './plan-request-timeout';
import { ProviderIcon } from './ui/ProviderIcon';
-import { connectionName } from './ui/provider-identity';
import { planErrorCode, planErrorMessage } from './plan-editor-errors';
import { ReasoningDialog, type NativeReasoning } from './ui/ReasoningDialog';
import { ModelPicker } from './ui/ModelPicker';
@@ -158,9 +157,9 @@ export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Dr
useEffect(() => {
if (!active) return;
let current = true;
- void invoke<{ sources: { display_name: string; display_template_id?: string | null; connection_identity?: { connection_option_id: string | null }; models: { binding_id: string }[] }[] }>('compute_management_snapshot').then(v => {
+ void invoke<{ sources: { source_id: string; display_name: string; display_template_id?: string | null; connection_identity?: { connection_option_id: string | null }; models: { binding_id: string }[] }[] }>('compute_management_snapshot').then(v => {
if (!current) return;
- setSources(Object.fromEntries(v.sources.flatMap(source => source.models.map(m => [m.binding_id, connectionName(source.connection_identity?.connection_option_id, language, source.display_name)]))));
+ setSources(Object.fromEntries(v.sources.flatMap(source => source.models.map(m => [m.binding_id, v.sources.filter(other => other.display_name === source.display_name).length > 1 ? `${source.display_name} · ${source.source_id.slice(-8)}` : source.display_name]))));
setSourceOptions(Object.fromEntries(v.sources.flatMap(source => source.models.map(m => [m.binding_id, source.display_template_id ?? source.connection_identity?.connection_option_id ?? null]))));
}).catch(() => {});
return () => { current = false; };
diff --git a/apps/desktop/src/product/ModelManagementPage.tsx b/apps/desktop/src/product/ModelManagementPage.tsx
index 16a3f942..c3c3a108 100644
--- a/apps/desktop/src/product/ModelManagementPage.tsx
+++ b/apps/desktop/src/product/ModelManagementPage.tsx
@@ -16,6 +16,7 @@ import type {
ProtectedInputRegistration,
} from '../features/model-connections/types';
import { SubscriptionSignIn } from '../features/subscriptions/SubscriptionSignIn';
+import { AppendConnectionModels } from '../features/models/AppendConnectionModels';
import { Models } from '../features/models/Models';
import {
DeviceScanList,
@@ -196,7 +197,9 @@ export function ModelManagementPage({
const [discoveryError, setDiscoveryError] = useState('');
const [adding, setAdding] = useState(startAdding && trustedAuthority);
const [reconnectingFrom, setReconnectingFrom] = useState<string | null>(null);
- const [addStage, setAddStage] = useState<'choose' | 'api' | 'scan' | 'subscription-login'>('choose');
+ const [addStage, setAddStage] = useState<'choose' | 'api' | 'scan' | 'subscription-login' | 'existing'>('choose');
+ const [appendingSource, setAppendingSource] = useState<ManagedSource | null>(null);
+ const [appendManual, setAppendManual] = useState(false);
const [addNotice, setAddNotice] = useState('');
const [modelNotice, setModelNotice] = useState('');
const [priceTarget, setPriceTarget] = useState<{
@@ -417,6 +420,13 @@ export function ModelManagementPage({
key_edits: [],
validation: selection.validation,
};
+ if (appendingSource) {
+ if (selectedSubscription?.existing_source_id !== appendingSource.source_id) throw { code: 'SOURCE_CHANGED' };
+ change.edit = { action: 'append_models' };
+ change.intent = appendingSource.state === 'disabled' ? 'save_disabled' : 'save_ready';
+ change.selected_model_refs = change.selected_model_refs.filter(ref => !appendingSource.models.some(model => model.model_ref === ref));
+ if (!change.selected_model_refs.length) throw { code: 'MODEL_SELECTION_REQUIRED' };
+ }
const preview = await invoke<SavePreview>('preview_compute_save', { change });
if (!alive.current || subscriptionView.current !== view) return;
handedOffValidations.current.add(validationKey);
@@ -779,10 +789,13 @@ export function ModelManagementPage({
language={language}
mutable={trustedAuthority}
initialDraft={initialDraft.current}
+ existingNames={management.sources.filter(source => source.source_id !== initialDraft.current.existing_source_id).map(source => source.display_name)}
+ savedSource={management.sources.find(source => source.source_id === initialDraft.current.existing_source_id)}
+ appendTo={appendManual ? appendingSource ?? undefined : undefined}
expectedRevisions={management.revisions}
backend={backend}
onBack={() => { setAddStage('choose'); setAddNotice(''); setReconnectingFrom(null); }}
- onCancel={() => { setAdding(false); setReconnectingFrom(null); }}
+ onCancel={() => { setAdding(false); setReconnectingFrom(null); setAppendingSource(null); }}
onSaveAccepted={onOperation}
onSaveResult={(result: ComputeSaveResult) => {
if (modelSaveCompleted(result)) {
@@ -790,9 +803,11 @@ export function ModelManagementPage({
setAdding(false);
setAddStage('choose');
if (reconnectingFrom) setModelNotice(language === 'zh'
- ? '新接入已保存;旧接入和已有路由未改变。请在路由中改选新模型,再停用旧接入。'
- : 'The new connection is saved. The old connection and routes are unchanged. Select the new model in routes, then disable the old connection.');
+ ? '接入配置已保存,原有模型绑定保持不变。'
+ : 'Connection settings saved. Existing model bindings are retained.');
setReconnectingFrom(null);
+ setAppendingSource(null);
+ setAppendManual(false);
requestAnimationFrame(() => addButton.current?.focus());
}
void refreshManagement();
@@ -817,6 +832,8 @@ export function ModelManagementPage({
void requestEditorReplacement('models').then(allowed => {
if (!allowed) return;
setAddNotice('');
+ setAppendingSource(null);
+ setAppendManual(false);
setAddStage('choose');
setAdding(true);
});
@@ -825,11 +842,40 @@ export function ModelManagementPage({
function openConnection(kind: 'known' | 'custom' | 'free') {
if (!trustedAuthority) return;
setReconnectingFrom(null);
+ setAppendingSource(null);
+ setAppendManual(false);
initialDraft.current = newModelConnectionDraft(kind);
setAddNotice('');
setAddStage('api');
}
+ async function appendModels(source: ManagedSource) {
+ if (!trustedAuthority || !await requestEditorReplacement('models')) return;
+ setAppendingSource(source); setAppendManual(false); setAdding(false);
+ if (source.provenance === 'connector_owned') {
+ setRepairingSubscriptionSource(null); setSelectedSubscriptionRef(null);
+ setAddStage('scan'); setAdding(true);
+ try {
+ const result = await invoke<SubscriptionScanResult>('compute_subscriptions');
+ setSubscriptions(result.candidates);
+ const candidate = result.candidates.find(item => item.existing_source_id === source.source_id);
+ if (!candidate) throw { code: 'SUBSCRIPTION_NOT_FOUND' };
+ openSubscription(candidate);
+ } catch (cause) { setSubscriptionError({ code: failureCode(cause), phase: 'scan' }); }
+ }
+ }
+
+ async function loadAppendModels(source: ManagedSource) {
+ const current = await invoke<ManagementSnapshot>('compute_management_snapshot');
+ if (!current.sources.some(item => item.source_id === source.source_id && item.revision === source.revision)) throw { code: 'SOURCE_CHANGED' };
+ const checkId = `append/${crypto.randomUUID()}`;
+ const checked = await invoke<ModelConnectionCheckView>('check_saved_model_connection', { request: {
+ source_id: source.source_id, expected_source_revision: source.revision, edit_revision: 1, check_id: checkId,
+ } });
+ if (!checkMatches(checked, { candidateRef: null, editRevision: 1, checkId }) || checked.reachability === 'transport_failed' || checked.authentication === 'rejected') throw { code: 'MODEL_CONNECTION_FAILED' };
+ return { checked, revisions: current.revisions };
+ }
+
function reconnectSource(source: ManagedSource) {
if (!trustedAuthority || source.provenance !== 'user_configured') return;
const draft = newModelConnectionDraft('custom');
@@ -906,7 +952,7 @@ export function ModelManagementPage({
&& discoverySelections.length);
function toggleSubscriptionModel(modelRef: string) {
- if (!effectiveSubscription || repairingSelectedSubscription) return;
+ if (!effectiveSubscription || repairingSelectedSubscription || appendingSource?.models.some(model => model.model_ref === modelRef)) return;
const next = new Set(selectedSubscriptionModels);
if (next.has(modelRef)) next.delete(modelRef); else next.add(modelRef);
setSubscriptionSelections(current => ({
@@ -950,6 +996,8 @@ export function ModelManagementPage({
}
function closeScan() {
+ setAppendingSource(null);
+ setAppendManual(false);
setAdding(false);
closeSubscriptionView();
requestAnimationFrame(() => addButton.current?.focus());
@@ -1003,7 +1051,7 @@ export function ModelManagementPage({
{connectionForm}
{priceTarget && <PriceEditor
modelName={priceTarget.model.display_name}
- sourceName={priceTarget.source.connection_identity?.product_label || priceTarget.source.display_name}
+ sourceName={priceTarget.source.display_name}
contexts={priceTarget.contexts}
language={language}
writable={priceTarget.writable && trustedAuthority}
@@ -1020,9 +1068,10 @@ export function ModelManagementPage({
onClose={() => { setAdding(false); setAddNotice(''); }}
>
<div className="v3-add-choices">
+ {hasSources && <button className="add-choice" type="button" disabled={!trustedAuthority} onClick={() => setAddStage('existing')}><span className="choice-icon"><UiIcon name="plus" /></span><div><strong>{language === 'zh' ? '向已有接入添加模型' : 'Add models to an existing connection'}</strong><span>{language === 'zh' ? '复用已保存的端点和凭据' : 'Reuse saved endpoints and credentials'}</span></div><UiIcon name="chevronRight" /></button>}
<button data-autofocus className="add-choice" type="button" disabled={!trustedAuthority} onClick={() => openConnection('known')}>
<span className="choice-icon"><UiIcon name="plug" /></span>
- <div><strong>{language === 'zh' ? '添加 API' : 'Add API'}</strong><span>{language === 'zh' ? '选择已支持的服务,填写 Key 后选择模型' : 'Choose a supported service and connect with an API key'}</span></div>
+ <div><strong>{language === 'zh' ? '新建 API 接入' : 'New API connection'}</strong><span>{language === 'zh' ? '从模板开始,使用独立的名称、端点和凭据' : 'Start from a template with a separate name, endpoints and credentials'}</span></div>
<UiIcon name="chevronRight" />
</button>
<button className="add-choice" type="button" disabled={!trustedAuthority} onClick={() => setAddStage('subscription-login')}>
@@ -1042,6 +1091,10 @@ export function ModelManagementPage({
<Disclosure className="oc-advanced" label={language === 'zh' ? '高级接入' : 'Advanced connection'} language={language}><p className="oc-meta">{language === 'zh' ? '使用自己的兼容服务;未知模型需要补充能力信息。' : 'Use a compatible endpoint. Unknown models require capability details.'}</p><button className="btn" type="button" disabled={!trustedAuthority} onClick={() => openConnection('custom')}>{language === 'zh' ? '自定义 API' : 'Custom API'}</button></Disclosure>
{addNotice && <div className="callout" role="status">{addNotice}</div>}
</Dialog>
+ <Dialog open={adding && addStage === 'existing'} title={language === 'zh' ? '选择已有接入' : 'Choose a connection'} closeLabel={language === 'zh' ? '关闭' : 'Close'} onClose={() => setAdding(false)}>
+ <div className="v3-add-choices">{management?.sources.map(source => <button className="add-choice" type="button" key={source.source_id} onClick={() => void appendModels(source)}><div><strong>{source.display_name}</strong><span>{source.connection_identity?.product_label ?? source.provenance} · {source.models.length} {language === 'zh' ? '个模型' : 'models'}</span></div><UiIcon name="chevronRight" /></button>)}</div>
+ </Dialog>
+ {appendingSource && appendingSource.provenance !== 'connector_owned' && !appendManual && <AppendConnectionModels source={appendingSource} language={language} mutable={trustedAuthority} onLoad={loadAppendModels} onPreview={change => invoke<SavePreview>('preview_compute_save', { change })} onApply={applyExisting} onRefresh={refreshManagement} onClose={() => setAppendingSource(null)} onManual={appendingSource.provenance === 'user_configured' ? () => { reconnectSource(appendingSource); setAppendManual(true); } : undefined} />}
<Dialog open={adding && addStage === 'subscription-login'} title={language === 'zh' ? '连接订阅' : 'Connect subscription'} closeLabel={language === 'zh' ? '关闭订阅登录' : 'Close subscription sign-in'} onClose={() => setAdding(false)}>
{adding && addStage === 'subscription-login' && <SubscriptionSignIn language={language} trustedAuthority={trustedAuthority}
onReuseNative={() => { setAddStage('scan'); returnToScanList(); void Promise.all([refreshSubscriptions(), recoverSubscriptionCheck()]); }}
@@ -1079,7 +1132,7 @@ export function ModelManagementPage({
{subscriptionReady && repairingSelectedSubscription
? <p className="oc-meta">{language === 'zh' ? '将保留原有模型、绑定和路由,仅更新当前订阅授权与可执行资格。' : 'Existing models, bindings, and routes will be retained; only current subscription access and execution eligibility will be updated.'}</p>
: subscriptionReady ? subscriptionModels.length
- ? <><p className="oc-meta">{language === 'zh' ? '已读取此账号可见的模型。选择资料完整、可接入路由的模型。' : 'Models visible to this account were loaded. Select models with complete routing data.'}</p><div className="v3-catalog">{subscriptionModels.map(model => <label className="check-row" key={model.model_ref}><input type="checkbox" disabled={!trustedAuthority || (!model.selectable && !selectedSubscriptionModels.has(model.model_ref))} checked={selectedSubscriptionModels.has(model.model_ref)} onChange={() => toggleSubscriptionModel(model.model_ref)} /><div><strong>{model.display_name}</strong>{!model.selectable && <span>{model.missing
+ ? <><p className="oc-meta">{language === 'zh' ? '已读取此账号可见的模型。选择资料完整、可接入路由的模型。' : 'Models visible to this account were loaded. Select models with complete routing data.'}</p><div className="v3-catalog">{subscriptionModels.map(model => <label className="check-row" key={model.model_ref}><input type="checkbox" disabled={!trustedAuthority || Boolean(appendingSource?.models.some(saved => saved.model_ref === model.model_ref)) || (!model.selectable && !selectedSubscriptionModels.has(model.model_ref))} checked={selectedSubscriptionModels.has(model.model_ref)} onChange={() => toggleSubscriptionModel(model.model_ref)} /><div><strong>{model.display_name}</strong>{!model.selectable && <span>{model.missing
? (language === 'zh' ? '已不在当前订阅目录,可取消选择' : 'No longer in the subscription directory; uncheck to remove')
: selectedSubscriptionModels.has(model.model_ref)
? (language === 'zh' ? '当前不可用,可取消选择' : 'Currently unavailable; uncheck to remove')
@@ -1134,6 +1187,7 @@ export function ModelManagementPage({
onRecheck={recheckSavedSource}
onCancelRecheck={checkId => invoke<void>('cancel_model_connection_check', { checkId })}
onReconnect={reconnectSource}
+ onAppend={source => { void appendModels(source); }}
onSourceStateSaved={enabled => setModelNotice(enabled
? language === 'zh' ? '接入已启用。' : 'Connection enabled.'
: language === 'zh' ? '接入已停用。' : 'Connection disabled.')}
diff --git a/apps/desktop/tests/v3/browser/product-shell-scenarios.mjs b/apps/desktop/tests/v3/browser/product-shell-scenarios.mjs
index ca3ddeaa..da6d6df1 100644
--- a/apps/desktop/tests/v3/browser/product-shell-scenarios.mjs
+++ b/apps/desktop/tests/v3/browser/product-shell-scenarios.mjs
@@ -38,10 +38,147 @@ async function routing() {
await until(() => document.querySelector('.plan-identity-fields input'), 'route editor');
}
const scenarios = [
+ scenario('desktop.models.selection-survives-save-refresh', ['model-connections'], 'Renaming a selected connection does not jump back to the previous save result', async () => {
+ let a; let b; let beforeB; let latestChange;
+ await fresh(() => {
+ b = c().management.sources.find(source => source.source_id === 'source/bailian/coding');
+ a = structuredClone(b); a.source_id = 'source/selection-a'; a.display_name = '接入 A';
+ a.models = a.models.map(model => ({ ...model, model_ref: `${model.model_ref}/a`, binding_id: `${model.binding_id}/a` }));
+ c().management.sources = [a, b]; beforeB = JSON.stringify(b);
+ c().handlers.get_compute_save_result = payload => ({ ...c().fixtureResponse('get_compute_save_result', payload), source_id: b.source_id });
+ c().handlers.preview_compute_save = payload => { latestChange = payload.change; return c().fixtureResponse('preview_compute_save', payload); };
+ c().handlers.apply_compute_save = payload => {
+ if (latestChange?.subject.kind === 'saved_source' && latestChange.subject.source_id === a.source_id && latestChange.edit?.action === 'rename') {
+ a.display_name = latestChange.edit.display_name; a.revision += 1;
+ }
+ return c().fixtureResponse('apply_compute_save', payload);
+ };
+ });
+ await click('模型'); await click('添加模型');
+ await until(() => all('button').some(item => item.textContent.includes('新建 API 接入')), 'new connection entry');
+ all('button').find(item => item.textContent.includes('新建 API 接入')).click();
+ await until(() => document.querySelector('[role="dialog"] input[type="password"]'), 'key field');
+ setInput(document.querySelector('[role="dialog"] input[type="password"]'), 'synthetic-selection-key');
+ await click('检查接入');
+ await until(() => all('.model-result-row input[type="checkbox"]').length, 'model choices');
+ all('.model-result-row input[type="checkbox"]')[0].click(); await pause(40);
+ await click('保存接入');
+ await until(() => !document.querySelector('[role="dialog"]') && calls('get_compute_save_result').length, 'completed initial save');
+ await click('按接入');
+ await until(() => document.querySelector('.models-feature .detail-identity h2')?.textContent === b.display_name, 'saved connection focus');
+ all('.models-feature .master-list .list-row').find(row => row.textContent.includes('接入 A')).click(); await pause(40);
+ await click('重命名');
+ await until(() => document.querySelector('[role="dialog"] input'), 'rename field');
+ setInput(document.querySelector('[role="dialog"] input'), '接入 A 已改名');
+ const snapshots = calls('compute_management_snapshot').length;
+ await click('保存名称');
+ await until(() => calls('compute_management_snapshot').length > snapshots && !document.querySelector('[role="dialog"]'), 'rename refresh');
+ assert(document.querySelector('.models-feature .detail-identity h2')?.textContent === '接入 A 已改名', 'Refresh jumped to the previous saved connection');
+ assert(JSON.stringify(b) === beforeB, 'Another connection changed while renaming A');
+ }),
+ scenario('desktop.models.connection-template-directory-layout', ['model-connections'], 'The production stylesheet renders searchable template rows and pagination', async () => {
+ await fresh(); await click('模型'); await click('添加模型');
+ await until(() => all('button').some(item => item.textContent.includes('新建 API 接入')), 'new connection entry');
+ all('button').find(item => item.textContent.includes('新建 API 接入')).click();
+ await until(() => all('.mc-template-row').length > 0, 'template directory');
+ assert(getComputedStyle(document.querySelector('.mc-template-directory')).display === 'grid', 'Production directory layout missing');
+ for (const row of all('.mc-template-row')) {
+ assert(getComputedStyle(row).display === 'flex' && getComputedStyle(row).alignItems === 'center', 'Template row is not aligned');
+ assert(getComputedStyle(row.querySelector('.field-help')).display === 'block', 'Template protocol is not on its own line');
+ }
+ const selected = document.querySelector('.mc-template-row input:checked');
+ assert(selected?.closest('.mc-template-row').classList.contains('selected'), 'Selection styling missing');
+ setInput(document.querySelector('.mc-template-directory input[type="search"]'), '百炼');
+ await until(() => all('.mc-template-row').every(row => row.textContent.includes('百炼')), 'filtered templates');
+ assert(all('.mc-template-row').length > 0, 'Search removed matching templates');
+ assert(getComputedStyle(document.querySelector('.mc-template-pagination')).display === 'flex', 'Pagination layout missing');
+ const close = all('[role="dialog"] button[aria-label="取消添加"]')[0];
+ assert(close, 'Template dialog close control missing');
+ close.click();
+ await until(() => !document.querySelector('[role="dialog"]'), 'closed template dialog');
+ }),
+ scenario('desktop.models.connection-rename', ['model-connections'], 'Rename is scoped to one saved connection without replacing its models or keys', async () => {
+ await fresh(() => { c().management.sources = [c().management.sources.find(source => source.source_id === 'source/bailian/coding')]; });
+ await click('模型'); await click('按接入'); await click('重命名');
+ await until(() => document.querySelector('[role="dialog"] input'), 'rename input');
+ setInput(document.querySelector('[role="dialog"] input'), '团队百炼'); await click('保存名称');
+ await until(() => calls('preview_compute_save').length === 1, 'rename preview');
+ const change = calls('preview_compute_save')[0].payload.change;
+ assert(change.edit.action === 'rename' && change.edit.display_name === '团队百炼', 'Rename intent missing');
+ assert(change.subject.source_id === 'source/bailian/coding' && change.selected_model_refs.length === 0 && change.key_edits.length === 0, 'Rename replaced a model or credential selection');
+ }),
+ scenario('desktop.models.delete-reference-block', ['model-connections'], 'A disabled route reference remains visible and prevents Apply', async () => {
+ await fresh(() => {
+ c().management.sources = [c().management.sources.find(source => source.source_id === 'source/bailian/coding')];
+ const plan = c().desktop.catalog.plans[0]; plan.head.status = 'disabled';
+ c().handlers.preview_compute_save = payload => ({ ...c().fixtureResponse('preview_compute_save', payload), affected_plan_refs: [plan.agent_plan_id] });
+ });
+ await click('模型'); await click('移除模型');
+ await until(() => text().includes('仍被引用,请先调整引用再删除。'), 'reference blocker');
+ assert(text().includes('这是最后一个模型,将一并删除所属接入。'), 'Last-model consequence was hidden');
+ const remove = all('[role="dialog"] button').find(item => item.textContent.trim() === '删除接入');
+ assert(remove?.disabled, 'Referenced connection could be deleted');
+ remove.click(); await pause(50);
+ assert(calls('apply_compute_save').length === 0, 'Disabled button dispatched Apply');
+ assert(calls('preview_compute_save')[0].payload.change.edit.action === 'delete', 'Last model removal did not use explicit delete');
+ const deleteInDialog = () => all('[role="dialog"] button').find(item => item.textContent.trim() === '删除接入');
+ c().handlers.refresh_route_references = () => { throw new Error('publication unavailable'); };
+ await click('更新引用状态');
+ await until(() => text().includes('引用状态暂未更新'), 'failed reference refresh');
+ assert(button('更新引用状态') && !button('更新引用状态').disabled, 'Failed refresh lost its retry entry');
+ assert(deleteInDialog()?.disabled, 'Failed refresh released a reference');
+ c().handlers.refresh_route_references = () => undefined;
+ await click('更新引用状态');
+ await until(() => !document.querySelector('[role="dialog"]'), 'refresh closes stale preview');
+ await click('移除模型');
+ await until(() => text().includes('仍被引用,请先调整引用再删除。'), 'fresh disabled reference');
+ assert(deleteInDialog()?.disabled, 'Checkpoint bypassed a disabled route');
+ assert(calls('preview_compute_save').length === 2, 'Reopen reused an old deletion preview');
+ assert(calls('apply_compute_save').length === 0, 'Reference refresh automatically deleted configuration');
+ // A separately completed publication can release historical references. Its
+ // new deletion preview is still required before the user explicitly deletes.
+ c().handlers.refresh_route_references = () => {
+ c().handlers.preview_compute_save = payload => ({ ...c().fixtureResponse('preview_compute_save', payload), affected_plan_refs: [] });
+ };
+ await click('更新引用状态');
+ await until(() => !document.querySelector('[role="dialog"]'), 'completed historical reference refresh');
+ await click('移除模型');
+ await until(() => deleteInDialog() && !deleteInDialog().disabled, 'new unreferenced preview');
+ assert(calls('apply_compute_save').length === 0, 'Refresh was mistaken for delete consent');
+ }),
+ scenario('desktop.models.append-preserves-existing', ['model-connections'], 'Appending selects only new models and retains a disabled connection', async () => {
+ await fresh(() => {
+ c().management.sources = [c().management.sources.find(source => source.source_id === 'source/bailian/coding')];
+ c().management.sources[0].state = 'disabled';
+ c().handlers.check_saved_model_connection = payload => {
+ const checked = c().fixtureResponse('check_saved_model_connection', payload);
+ checked.candidate.models.push({ ...checked.candidate.models[0], model_ref: 'model-ref/new', upstream_model_id: 'new-model', display_name: 'New model' });
+ return checked;
+ };
+ });
+ await click('模型'); await click('向此接入添加模型');
+ await until(() => all('[role="dialog"] input[type="checkbox"]').length === 2, 'append inventory');
+ const checks = all('[role="dialog"] input[type="checkbox"]');
+ assert(checks[0].disabled && checks[0].checked, 'Existing model was editable as a removal');
+ checks[1].click(); await click('添加 1 个模型');
+ await until(() => calls('preview_compute_save').length === 1, 'append preview');
+ const change = calls('preview_compute_save')[0].payload.change;
+ assert(change.edit.action === 'append_models' && change.intent === 'save_disabled', 'Append lost explicit action or disabled state');
+ assert(JSON.stringify(change.selected_model_refs) === '["model-ref/new"]' && change.key_edits.length === 0, 'Append modified existing model/key selection');
+ }),
+ scenario('desktop.models.remove-only-selected', ['model-connections'], 'Removing one model retains the connection and sends exactly the selected saved model', async () => {
+ await fresh(() => { c().management.sources = [c().management.sources[0]]; });
+ await click('模型'); await click('移除模型');
+ await until(() => all('[role="dialog"] button').some(item => item.textContent.trim() === '移除模型' && !item.disabled), 'remove preview');
+ const change = calls('preview_compute_save')[0].payload.change;
+ assert(change.edit.action === 'remove_models' && change.selected_model_refs.length === 1 && change.key_edits.length === 0, 'Remove scope replaced connection or keys');
+ all('[role="dialog"] button').find(item => item.textContent.trim() === '移除模型').click();
+ await until(() => calls('apply_compute_save').length === 1, 'single remove apply');
+ }),
scenario('desktop.models.tool-check-selection', ['model-connections'], 'A tool check retains the chosen model with its fresh reference without selecting new inventory', async () => {
await fresh(); await click('模型'); await click('添加模型');
- await until(() => all('button').some(item => item.textContent.includes('添加 API')), 'add API entry');
- all('button').find(item => item.textContent.includes('添加 API')).click();
+ await until(() => all('button').some(item => item.textContent.includes('新建 API 接入')), 'add API entry');
+ all('button').find(item => item.textContent.includes('新建 API 接入')).click();
await until(() => document.querySelector('[role="dialog"] input[type="password"]'), 'API key input');
setInput(document.querySelector('[role="dialog"] input[type="password"]'), 'synthetic-tool-check-input');
c().handlers.check_registered_model_connection = payload => {
@@ -254,7 +391,8 @@ const scenarios = [
await until(() => text().includes('用于这些路由'), 'model route references');
assert(refs().some(item => item.textContent.includes('Branch regular model use')), 'Published regular branch model reference is missing');
assert(refs().some(item => item.textContent.includes('Branch upgrade model use')), 'Published upgrade branch model reference is missing');
- assert(!refs().some(item => item.textContent.includes('Disabled branch model use')), 'Disabled route is presented as active model use');
+ assert(refs().some(item => item.textContent.trim() === 'Disabled branch model use(已停用)'), 'Disabled reference is missing or presented without its stopped state');
+ assert(refs().filter(item => item.textContent.includes('Disabled branch model use')).length === 1, 'Disabled reference is duplicated');
await click('Branch regular model use');
await until(() => document.querySelector('.plan-identity-fields input')?.value === 'Branch regular model use', 'referenced route opened');
}),
@@ -516,8 +654,8 @@ const scenarios = [
await until(() => text().includes('接入就绪'), 'readiness status');
assert(text().includes('不代表上游推理或工具调用已验证'), 'Local readiness claims upstream inference verification');
await click('添加模型');
- await until(() => all('button').some(item => item.textContent.includes('添加 API')), 'add API entry');
- all('button').find(item => item.textContent.includes('添加 API')).click();
+ await until(() => all('button').some(item => item.textContent.includes('新建 API 接入')), 'add API entry');
+ all('button').find(item => item.textContent.includes('新建 API 接入')).click();
await until(() => document.querySelector('[role="dialog"] input[type="password"]'), 'API key input');
const key = document.querySelector('[role="dialog"] input[type="password"]');
setInput(key, 'synthetic-input-preserved'); await pause(40);
diff --git a/apps/desktop/tests/v3/browser/scenario-requirements.mjs b/apps/desktop/tests/v3/browser/scenario-requirements.mjs
index e212375a..db0efe4f 100644
--- a/apps/desktop/tests/v3/browser/scenario-requirements.mjs
+++ b/apps/desktop/tests/v3/browser/scenario-requirements.mjs
@@ -49,6 +49,12 @@ export const focusedRequirements = {
};
export const productShellRequired = [
+ 'desktop.models.selection-survives-save-refresh',
+ 'desktop.models.connection-template-directory-layout',
+ 'desktop.models.connection-rename',
+ 'desktop.models.delete-reference-block',
+ 'desktop.models.append-preserves-existing',
+ 'desktop.models.remove-only-selected',
'desktop.home.reactivation-usage',
'desktop.models.tool-check-selection',
'desktop.routing.disabled-header',
diff --git a/apps/desktop/tests/v3/browser/subscription-repair-scenarios.mjs b/apps/desktop/tests/v3/browser/subscription-repair-scenarios.mjs
index e2a69b09..d8498eb5 100644
--- a/apps/desktop/tests/v3/browser/subscription-repair-scenarios.mjs
+++ b/apps/desktop/tests/v3/browser/subscription-repair-scenarios.mjs
@@ -54,6 +54,55 @@ function finishCheck() {
}
const scenarios = [
+ ['managed sign-in repair requires the current source revision and preserves saved membership', async () => {
+ let saved;
+ await fresh(control => {
+ const source = control.management.sources[0];
+ source.display_name = 'Team subscription';
+ source.connection_identity.access_kind = 'subscription';
+ saved = structuredClone(source);
+ control.management.schema = 'hiroute.compute-management-snapshot/v3';
+ control.management.subscription_modes = [{ source_id: source.source_id, source_revision: source.revision - 1, mode: 'cpa_managed' }];
+ const pending = { ...control.pending, existing_source_id: source.source_id, display_name: 'New login account label' };
+ const checked = { ...control.checked, existing_source_id: source.source_id, display_name: pending.display_name, models: [
+ { ...control.checked.models[0], model_ref: source.models[0].model_ref },
+ { ...control.checked.models[0], model_ref: 'model/new-from-login', display_name: 'New login model' },
+ ] };
+ control.subscriptions = [pending];
+ control.handlers.manage_subscription_login = ({ request }) => {
+ assert(request.action === 'list', 'Repair unexpectedly changed a login');
+ return { schema: 'hiroute.subscription-login-result/v1', sessions: request.provider === 'codex'
+ ? [{ provider: 'codex', login_ref: 'login/component-repair', status: 'authorized', candidate: pending.candidate }]
+ : [] };
+ };
+ control.handlers.check_subscription = () => {
+ control.subscriptions = [checked];
+ control.result = { ...control.verified, checked_candidate: checked };
+ return control.result;
+ };
+ });
+ assert(button('重新检查订阅') && !button('重新独立登录'), 'Stale mode revision selected the managed repair flow');
+ c().management.subscription_modes[0].source_revision = saved.revision;
+ c().refresh();
+ await until(() => button('重新独立登录'), 'current managed mode');
+ await click('重新独立登录');
+ await until(() => button('检查并选择模型') && !button('检查并选择模型').disabled, 'authorized managed login');
+ await click('检查并选择模型');
+ await click('检查订阅');
+ await until(() => button('更新订阅'), 'existing connection repair');
+ assert(text().includes('将保留原有模型、绑定和路由'), 'Matching existing_source_id lost repair context');
+ assert(!document.querySelector('.v3-catalog input[type="checkbox"]'), 'Repair exposed model selection changes');
+ await click('更新订阅');
+ await until(() => text().includes('订阅授权已更新'), 'repair saved');
+ const previews = calls('preview_compute_save');
+ assert(previews.length === 1 && calls('apply_compute_save').length === 1, 'Repair was not submitted exactly once');
+ const change = previews[0].payload.change;
+ assert(JSON.stringify(change.selected_model_refs) === JSON.stringify(saved.models.map(model => model.model_ref)), 'Repair replaced saved membership with the new login inventory');
+ assert(change.subject.kind === 'candidate' && JSON.stringify(change.subject.candidate) === JSON.stringify(c().checked.candidate), 'Repair submitted a different candidate or revision');
+ assert(!change.edit && change.key_edits.length === 0, 'Repair submitted a rename or manual credential edit');
+ assert(text().includes(saved.display_name), 'Saved connection name disappeared after repair refresh');
+ // This verifies actual page intent over mock IPC; backend persistence has separate storage/native evidence.
+ }],
['normal inventory, empty selection and duplicate check/save', async () => {
await fresh();
await scan();
@@ -168,17 +217,17 @@ const scenarios = [
['scan empty, runtime unavailable and failed remain distinct', async () => {
await fresh(control => { control.subscriptions = []; control.handlers.compute_scan = () => ({ items: [] }); });
await scan();
- assert(text().includes('没有发现可复用的 Codex 订阅'), 'Successful empty scan missing');
+ assert(text().includes('没有发现可复用的 Codex / Claude Code 订阅'), 'Successful empty scan missing');
await click('完成');
c().handlers.compute_subscriptions = () => ({ discovery_state: 'runtime_unavailable', reason_code: 'subscription_runtime_unavailable', candidates: [] });
await scan();
- assert(text().includes('当前环境暂时无法读取') && !text().includes('没有发现可复用的 Codex 订阅'), 'Runtime absence treated as empty');
+ assert(text().includes('当前环境暂时无法读取') && !text().includes('没有发现可复用的 Codex / Claude Code 订阅'), 'Runtime absence treated as empty');
c().handlers.compute_subscriptions = () => { throw { code: 'DAEMON_UNAVAILABLE' }; };
await click('重新扫描');
- await until(() => text().includes('暂时无法读取本机 Codex 订阅'), 'scan failure');
+ await until(() => text().includes('暂时无法读取本机订阅'), 'scan failure');
delete c().handlers.compute_subscriptions;
await click('重新扫描');
- await until(() => text().includes('没有发现可复用的 Codex 订阅'), 'empty after retry');
+ await until(() => text().includes('没有发现可复用的 Codex / Claude Code 订阅'), 'empty after retry');
}],
['Prepare duplicate and close discard late candidate without cancellation API', async () => {
const late = deferred();
diff --git a/apps/desktop/tests/v3/visual/subscription-repair-active.mjs b/apps/desktop/tests/v3/visual/subscription-repair-active.mjs
index 8823c44b..b370ca2e 100644
--- a/apps/desktop/tests/v3/visual/subscription-repair-active.mjs
+++ b/apps/desktop/tests/v3/visual/subscription-repair-active.mjs
@@ -18,7 +18,7 @@ try {
}
await mkdir(outputRoot, { recursive: true });
await writeFile(path.join(outputRoot, 'subscription-repair-report.json'), `${JSON.stringify(report, null, 2)}\n`);
- if (report.tests !== 15 || report.failed > 0) process.exitCode = 1;
+ if (report.tests !== 16 || report.failed > 0) process.exitCode = 1;
} finally {
client.close();
}
diff --git a/contracts/cli/agent-plan-catalog-query.v2.schema.json b/contracts/cli/agent-plan-catalog-query.v2.schema.json
index 1ea818cc..9dd53772 100644
--- a/contracts/cli/agent-plan-catalog-query.v2.schema.json
+++ b/contracts/cli/agent-plan-catalog-query.v2.schema.json
@@ -45,6 +45,18 @@
"required": [],
"type": "object"
},
+ "checkpoint_change": {
+ "additionalProperties": false,
+ "properties": {
+ "schema": {
+ "const": "hiroute.publication-checkpoint-change/v1"
+ }
+ },
+ "required": [
+ "schema"
+ ],
+ "type": "object"
+ },
"content_change": {
"additionalProperties": false,
"properties": {
diff --git a/contracts/cli/contract-set.v1.json b/contracts/cli/contract-set.v1.json
index 0272ee40..d7d512ef 100644
--- a/contracts/cli/contract-set.v1.json
+++ b/contracts/cli/contract-set.v1.json
@@ -1,10 +1,10 @@
{
- "descriptor_digest": "sha256:febf9a04d9e2721df85c12616dd74f97e68de79191d3eae81da532bd782a7e55",
+ "descriptor_digest": "sha256:a435bc5901bbcaeaf2f41c8c4db15b0a7f967d988aeb544e8f5d2890abc64639",
"files": {
"agent-check-request.v1.schema.json": "sha256:fbd9e9b19282a5ed8c3e30b5ae16538bc01318a70e4bb7c7a55e8e0472553feb",
"agent-launch-descriptor-request.v1.schema.json": "sha256:28f2f9d2d7f9a1618bea0f13383002429bc9e0ff56166cbee86958a245d0fd48",
- "agent-plan-catalog-query.v2.schema.json": "sha256:920dbff3fbd63d670f50960f51b737d09024ab0931db65857e114935b0b20183",
- "coverage-manifest.v1.json": "sha256:482a58242a21800749ac0800ad040aa9d19fe8c3047b323943a82a662b458a07",
+ "agent-plan-catalog-query.v2.schema.json": "sha256:a597b26eac530352f522a05c29a7c8c3a0ee2b553d69d1d911c2b0a44033338c",
+ "coverage-manifest.v1.json": "sha256:0db1cde5b609480819f23b8f96d65f37694fd74b69ea7fa36a268eedd13168b6",
"delegation-cancel-request.v1.schema.json": "sha256:0822c53fc16acfcd618fbef66410939f33f634313389a6df4705f414a468b878",
"delegation-continue-request.v1.schema.json": "sha256:da2f81607f37d154a0fa698a107b37d4b0e9d5a03693dcbcc41e0b7e65db5b93",
"delegation-get-request.v1.schema.json": "sha256:85b29839c1c508018ebe40e4b2bb5c1dce7c3a87c27efa30b196b2d1b6658471",
@@ -16,14 +16,15 @@
"local-control-hello.v2.schema.json": "sha256:169b944fd7d6a6c48e6615e875ec1dfe7b0045e09186312fd2c2b7cc92b56aa6",
"local-control.v2.schema.json": "sha256:4b654de90cd6e333b3953379e5b2e1c5125f1dcbe307b7c7c73f12bb2032d18c",
"machine-envelope.v2.schema.json": "sha256:5a0b47ce1fd80628f760a3da5a88de7dc01f6df83cb6eef47fd4a6c8289070ba",
- "manifest.v1.json": "sha256:492df261163fb9ff7eb11104c53ebdec0d72ab245fa4622ad05ae32d475d406c",
+ "manifest.v1.json": "sha256:a98cee2750c670be1bbbb2cfa132bbd14e13a48f623580d807ecfbc410231d9e",
"operation-cancel-request.v1.schema.json": "sha256:0071cbcf27de3bfb7f6644478fe2b73bb5387ebe33db93629ff5672959e8495f",
"operation-lookup.v1.schema.json": "sha256:0fbaaa15b0e75b4186979bdd856bed0485d55a4bd33a33f3caf3bd92e01a7850",
- "plan-content-change.v2.schema.json": "sha256:5b752e26bc81adfb3ccd1bab98f938a44f7b64059789d33b6f6f278abf1a3ca9",
- "plan-draft-change.v1.schema.json": "sha256:be0b7aff74d2163ae2cbecd05308ef59350938ff434e26c4ba9da3108ee39a24",
- "plan-editor.v2.schema.json": "sha256:8f2547be8bdde8236c4b83c0027e863f7daa4eac5b8d5ab646dec6db67c50e39",
- "plan-lifecycle-change.v1.schema.json": "sha256:c9336293241f2a027c5c9478da25ec5cd70e9cfe0608241fdf85447e37297bc3",
- "planned-manifest.v1.json": "sha256:725ffc35c02647771911050615cc2e65cc68e0f9793ad4cd059362625ccff17c",
+ "plan-content-change.v2.schema.json": "sha256:d07d6595109e50ffc0e253b8cfad578632ebc300e014d45e33f02c446b9d42de",
+ "plan-draft-change.v1.schema.json": "sha256:46366339b9a3689ea0195c641ca9b16820c678641950dd8357db526a07d7bf91",
+ "plan-editor.v2.schema.json": "sha256:9ce9efd5d8117a9ddb6c1b46d16a9b7eb6ec11e4672b5dac8d3893323dd39ffa",
+ "plan-lifecycle-change.v1.schema.json": "sha256:a53203683920280574c0ed8c8f888159c10d5df8949b89af67638116ec374a62",
+ "planned-manifest.v1.json": "sha256:76d35bae7439125404a6d2511dff7728cf6bcde9a894e4241749f18997a9ce82",
+ "publication-checkpoint-change.v1.schema.json": "sha256:4d5a709ba41f529318d5e5c1b1399a2e84c5c51f49527edf927e5824412a795d",
"session-list-query.v1.schema.json": "sha256:1f71a89fc019b59c3499708c0760b694b8cb8532028b56d98702cd3b2721cd44",
"session-lookup.v1.schema.json": "sha256:0c9e0ea31bdde7f720a9a17e8dc175902a20b3fb92abc21ce4bdae9fc3d97587",
"setup-apply-request.v1.schema.json": "sha256:b44377ecb53e609574cd2e1d49624d6bc8e148f7b60a99c2ea9db861e0c2cabd",
diff --git a/contracts/cli/coverage-manifest.v1.json b/contracts/cli/coverage-manifest.v1.json
index cb6600c9..86e392ed 100644
--- a/contracts/cli/coverage-manifest.v1.json
+++ b/contracts/cli/coverage-manifest.v1.json
@@ -1219,7 +1219,7 @@
}
}
],
- "descriptor_digest": "sha256:febf9a04d9e2721df85c12616dd74f97e68de79191d3eae81da532bd782a7e55",
+ "descriptor_digest": "sha256:a435bc5901bbcaeaf2f41c8c4db15b0a7f967d988aeb544e8f5d2890abc64639",
"schema_version": {
"major": 1,
"minor": 0
diff --git a/contracts/cli/manifest.v1.json b/contracts/cli/manifest.v1.json
index 7a54d965..77deeda3 100644
--- a/contracts/cli/manifest.v1.json
+++ b/contracts/cli/manifest.v1.json
@@ -5,7 +5,7 @@
},
"product_contract_revision": "487a807c8dc25cfb24e8b097882cd3bb9716a009",
"proposal_map_revision": "ab4da93cc49c6ec56a01e046230411ff1ca82300",
- "descriptor_digest": "sha256:febf9a04d9e2721df85c12616dd74f97e68de79191d3eae81da532bd782a7e55",
+ "descriptor_digest": "sha256:a435bc5901bbcaeaf2f41c8c4db15b0a7f967d988aeb544e8f5d2890abc64639",
"visibility": "release",
"commands": [
{
@@ -845,7 +845,7 @@
"help": {
"purpose": "Preview a connection identity and registered endpoint change without accepting a Secret.",
"usage": "hiroute compute connection preview --request-stdin --output json",
- "arguments_and_options": "--request-stdin accepts exactly one registered v1 projection, compute-management v2 save, or subscription-check v2 preview request. Preview has no durable side effect and returns the exact digest and revisions required by Apply.",
+ "arguments_and_options": "--request-stdin accepts exactly one registered v1 projection, compute-management v2 save/edit, or subscription-check v2 preview request. The optional edit action is rename (display_name), append_models (checked candidate; preserves existing models), remove_models (saved source; selected refs are removals), or delete (saved source; no selected refs). Omitting edit retains released save semantics. Referenced models, including disabled routes and retained versions, cannot be deleted. Preview has no durable side effect and returns the exact digest and revisions required by Apply.",
"effects": "Stateless Preview: no ID, TTL, Operation, Secret, file, database, publication, or network write.",
"network_and_model_use": "No model use and no non-fixture network access.",
"automation": "Use stable command_id, status, typed data, warnings[].code, and next_actions[].command_id; never parse display text.",
diff --git a/contracts/cli/plan-content-change.v2.schema.json b/contracts/cli/plan-content-change.v2.schema.json
index 8d3aa38c..c7e61144 100644
--- a/contracts/cli/plan-content-change.v2.schema.json
+++ b/contracts/cli/plan-content-change.v2.schema.json
@@ -45,6 +45,18 @@
"required": [],
"type": "object"
},
+ "checkpoint_change": {
+ "additionalProperties": false,
+ "properties": {
+ "schema": {
+ "const": "hiroute.publication-checkpoint-change/v1"
+ }
+ },
+ "required": [
+ "schema"
+ ],
+ "type": "object"
+ },
"content_change": {
"additionalProperties": false,
"properties": {
diff --git a/contracts/cli/plan-draft-change.v1.schema.json b/contracts/cli/plan-draft-change.v1.schema.json
index 6c3cb6ed..35d18043 100644
--- a/contracts/cli/plan-draft-change.v1.schema.json
+++ b/contracts/cli/plan-draft-change.v1.schema.json
@@ -45,6 +45,18 @@
"required": [],
"type": "object"
},
+ "checkpoint_change": {
+ "additionalProperties": false,
+ "properties": {
+ "schema": {
+ "const": "hiroute.publication-checkpoint-change/v1"
+ }
+ },
+ "required": [
+ "schema"
+ ],
+ "type": "object"
+ },
"content_change": {
"additionalProperties": false,
"properties": {
diff --git a/contracts/cli/plan-editor.v2.schema.json b/contracts/cli/plan-editor.v2.schema.json
index 1784df97..62dd9da8 100644
--- a/contracts/cli/plan-editor.v2.schema.json
+++ b/contracts/cli/plan-editor.v2.schema.json
@@ -45,6 +45,18 @@
"required": [],
"type": "object"
},
+ "checkpoint_change": {
+ "additionalProperties": false,
+ "properties": {
+ "schema": {
+ "const": "hiroute.publication-checkpoint-change/v1"
+ }
+ },
+ "required": [
+ "schema"
+ ],
+ "type": "object"
+ },
"content_change": {
"additionalProperties": false,
"properties": {
diff --git a/contracts/cli/plan-lifecycle-change.v1.schema.json b/contracts/cli/plan-lifecycle-change.v1.schema.json
index 405099a4..8888f70c 100644
--- a/contracts/cli/plan-lifecycle-change.v1.schema.json
+++ b/contracts/cli/plan-lifecycle-change.v1.schema.json
@@ -45,6 +45,18 @@
"required": [],
"type": "object"
},
+ "checkpoint_change": {
+ "additionalProperties": false,
+ "properties": {
+ "schema": {
+ "const": "hiroute.publication-checkpoint-change/v1"
+ }
+ },
+ "required": [
+ "schema"
+ ],
+ "type": "object"
+ },
"content_change": {
"additionalProperties": false,
"properties": {
diff --git a/contracts/cli/planned-manifest.v1.json b/contracts/cli/planned-manifest.v1.json
index 7641c136..3557f46b 100644
--- a/contracts/cli/planned-manifest.v1.json
+++ b/contracts/cli/planned-manifest.v1.json
@@ -5,7 +5,7 @@
},
"product_contract_revision": "487a807c8dc25cfb24e8b097882cd3bb9716a009",
"proposal_map_revision": "ab4da93cc49c6ec56a01e046230411ff1ca82300",
- "descriptor_digest": "sha256:febf9a04d9e2721df85c12616dd74f97e68de79191d3eae81da532bd782a7e55",
+ "descriptor_digest": "sha256:a435bc5901bbcaeaf2f41c8c4db15b0a7f967d988aeb544e8f5d2890abc64639",
"visibility": "planned",
"commands": [
{
@@ -1314,7 +1314,7 @@
"help": {
"purpose": "Preview a connection identity and registered endpoint change without accepting a Secret.",
"usage": "hiroute compute connection preview --request-stdin --output json",
- "arguments_and_options": "--request-stdin accepts exactly one registered v1 projection, compute-management v2 save, or subscription-check v2 preview request. Preview has no durable side effect and returns the exact digest and revisions required by Apply.",
+ "arguments_and_options": "--request-stdin accepts exactly one registered v1 projection, compute-management v2 save/edit, or subscription-check v2 preview request. The optional edit action is rename (display_name), append_models (checked candidate; preserves existing models), remove_models (saved source; selected refs are removals), or delete (saved source; no selected refs). Omitting edit retains released save semantics. Referenced models, including disabled routes and retained versions, cannot be deleted. Preview has no durable side effect and returns the exact digest and revisions required by Apply.",
"effects": "Stateless Preview: no ID, TTL, Operation, Secret, file, database, publication, or network write.",
"network_and_model_use": "No model use and no non-fixture network access.",
"automation": "Use stable command_id, status, typed data, warnings[].code, and next_actions[].command_id; never parse display text.",
diff --git a/contracts/cli/publication-checkpoint-change.v1.schema.json b/contracts/cli/publication-checkpoint-change.v1.schema.json
new file mode 100644
index 00000000..6b23ad42
--- /dev/null
+++ b/contracts/cli/publication-checkpoint-change.v1.schema.json
@@ -0,0 +1,995 @@
+{
+ "$defs": {
+ "candidates": {
+ "items": {
+ "$ref": "#/$defs/selection"
+ },
+ "maxItems": 128,
+ "type": "array"
+ },
+ "catalog_query": {
+ "additionalProperties": false,
+ "properties": {
+ "cursor": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "additionalProperties": false,
+ "properties": {
+ "offset": {
+ "minimum": 1,
+ "type": "integer"
+ },
+ "snapshot_digest": {
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": [
+ "snapshot_digest",
+ "offset"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ "limit": {
+ "default": 32,
+ "maximum": 128,
+ "minimum": 1,
+ "type": "integer"
+ }
+ },
+ "required": [],
+ "type": "object"
+ },
+ "checkpoint_change": {
+ "additionalProperties": false,
+ "properties": {
+ "schema": {
+ "const": "hiroute.publication-checkpoint-change/v1"
+ }
+ },
+ "required": [
+ "schema"
+ ],
+ "type": "object"
+ },
+ "content_change": {
+ "additionalProperties": false,
+ "properties": {
+ "consumed_draft": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "additionalProperties": false,
+ "properties": {
+ "draft_id": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "revision": {
+ "minimum": 1,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "draft_id",
+ "revision"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ "editor": {
+ "$ref": "#/$defs/editor"
+ },
+ "schema": {
+ "const": "hiroute.plan-content-change/v2"
+ },
+ "target": {
+ "oneOf": [
+ {
+ "additionalProperties": false,
+ "properties": {
+ "creation_key": {
+ "maxLength": 128,
+ "minLength": 1,
+ "type": "string"
+ },
+ "intent": {
+ "const": "create"
+ }
+ },
+ "required": [
+ "intent",
+ "creation_key"
+ ],
+ "type": "object"
+ },
+ {
+ "additionalProperties": false,
+ "properties": {
+ "expected_head_revision": {
+ "minimum": 1,
+ "type": "integer"
+ },
+ "intent": {
+ "const": "update"
+ },
+ "plan_id": {
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": [
+ "intent",
+ "plan_id",
+ "expected_head_revision"
+ ],
+ "type": "object"
+ }
+ ]
+ }
+ },
+ "required": [
+ "schema",
+ "target",
+ "editor"
+ ],
+ "type": "object"
+ },
+ "draft": {
+ "additionalProperties": false,
+ "properties": {
+ "base_head_revision": {
+ "minimum": 1,
+ "type": "integer"
+ },
+ "draft_id": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "editor": {
+ "$ref": "#/$defs/editor"
+ },
+ "plan_id": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "revision": {
+ "minimum": 1,
+ "type": "integer"
+ },
+ "schema": {
+ "const": "hiroute.plan-draft/v1"
+ },
+ "workspace_id": {
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": [
+ "schema",
+ "workspace_id",
+ "draft_id",
+ "revision",
+ "editor"
+ ],
+ "type": "object"
+ },
+ "draft_change": {
+ "additionalProperties": false,
+ "properties": {
+ "action": {
+ "oneOf": [
+ {
+ "additionalProperties": false,
+ "properties": {
+ "draft": {
+ "$ref": "#/$defs/draft"
+ },
+ "kind": {
+ "const": "save"
+ }
+ },
+ "required": [
+ "kind",
+ "draft"
+ ],
+ "type": "object"
+ },
+ {
+ "additionalProperties": false,
+ "properties": {
+ "kind": {
+ "const": "discard"
+ }
+ },
+ "required": [
+ "kind"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ "draft_id": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "expected_revision": {
+ "minimum": 1,
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
+ "schema": {
+ "const": "hiroute.plan-draft-change/v1"
+ },
+ "workspace_id": {
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": [
+ "schema",
+ "workspace_id",
+ "draft_id",
+ "action"
+ ],
+ "type": "object"
+ },
+ "editor": {
+ "additionalProperties": false,
+ "properties": {
+ "branch_routing": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "additionalProperties": false,
+ "properties": {
+ "branches": {
+ "items": {
+ "additionalProperties": false,
+ "properties": {
+ "candidates": {
+ "$ref": "#/$defs/candidates"
+ },
+ "condition": {
+ "type": "string"
+ },
+ "id": {
+ "maxLength": 128,
+ "minLength": 1,
+ "not": {
+ "const": "smart_saving"
+ },
+ "type": "string"
+ },
+ "judgment": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/$defs/judgment"
+ }
+ ]
+ },
+ "name": {
+ "maxLength": 128,
+ "type": "string"
+ },
+ "primary_candidates": {
+ "$ref": "#/$defs/candidates"
+ }
+ },
+ "required": [
+ "id",
+ "name",
+ "condition",
+ "candidates",
+ "primary_candidates"
+ ],
+ "type": "object"
+ },
+ "maxItems": 16,
+ "type": "array"
+ },
+ "classifier": {
+ "oneOf": [
+ {
+ "additionalProperties": false,
+ "properties": {
+ "kind": {
+ "const": "local_rules"
+ }
+ },
+ "required": [
+ "kind"
+ ],
+ "type": "object"
+ },
+ {
+ "additionalProperties": false,
+ "properties": {
+ "kind": {
+ "const": "decision_service"
+ },
+ "service": {
+ "additionalProperties": false,
+ "properties": {
+ "connection": {
+ "oneOf": [
+ {
+ "additionalProperties": false,
+ "properties": {
+ "auth_header": {
+ "additionalProperties": false,
+ "properties": {
+ "name": {
+ "maxLength": 128,
+ "minLength": 1,
+ "type": "string"
+ },
+ "value_secret_ref": {
+ "maxLength": 256,
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": [
+ "name",
+ "value_secret_ref"
+ ],
+ "type": "object"
+ },
+ "endpoint": {
+ "maxLength": 2048,
+ "type": "string"
+ },
+ "kind": {
+ "const": "system_one"
+ },
+ "model": {
+ "maxLength": 256,
+ "type": "string"
+ },
+ "provider": {
+ "maxLength": 128,
+ "type": "string"
+ },
+ "timeout_ms": {
+ "maximum": 3600000,
+ "minimum": 1,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "kind",
+ "provider",
+ "model",
+ "endpoint",
+ "timeout_ms",
+ "auth_header"
+ ],
+ "type": "object"
+ },
+ {
+ "additionalProperties": false,
+ "properties": {
+ "auth_header": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "additionalProperties": false,
+ "properties": {
+ "name": {
+ "maxLength": 128,
+ "minLength": 1,
+ "type": "string"
+ },
+ "value_secret_ref": {
+ "maxLength": 256,
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": [
+ "name",
+ "value_secret_ref"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ "endpoint": {
+ "maxLength": 2048,
+ "type": "string"
+ },
+ "kind": {
+ "const": "custom"
+ },
+ "timeout_ms": {
+ "maximum": 3600000,
+ "minimum": 1,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "kind",
+ "endpoint",
+ "timeout_ms"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ "id": {
+ "maxLength": 128,
+ "type": "string"
+ },
+ "name": {
+ "maxLength": 128,
+ "type": "string"
+ },
+ "revision": {
+ "minimum": 1,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "id",
+ "revision",
+ "name",
+ "connection"
+ ],
+ "type": "object"
+ }
+ },
+ "required": [
+ "kind",
+ "service"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ "default_branch_id": {
+ "maxLength": 128,
+ "type": "string"
+ },
+ "judgment": {
+ "$ref": "#/$defs/judgment"
+ },
+ "reselect_on_user_message": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "classifier",
+ "branches",
+ "default_branch_id",
+ "judgment",
+ "reselect_on_user_message"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ "candidates": {
+ "$ref": "#/$defs/candidates"
+ },
+ "custom_alias": {
+ "maxLength": 64,
+ "type": "string"
+ },
+ "delegation_enabled": {
+ "type": "boolean"
+ },
+ "display_name": {
+ "maxLength": 128,
+ "type": "string"
+ },
+ "free": {
+ "additionalProperties": false,
+ "properties": {
+ "candidates": {
+ "$ref": "#/$defs/candidates"
+ },
+ "primary": {
+ "$ref": "#/$defs/candidates"
+ },
+ "primary_fallback": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "candidates",
+ "primary",
+ "primary_fallback"
+ ],
+ "type": "object"
+ },
+ "limits": {
+ "additionalProperties": false,
+ "properties": {
+ "attempt_timeout_ms": {
+ "maximum": 3600000,
+ "minimum": 1000,
+ "type": "integer"
+ },
+ "context_window_tokens": {
+ "maximum": 9223372036854775807,
+ "minimum": 1,
+ "type": "integer"
+ },
+ "maximum_attempts": {
+ "maximum": 64,
+ "minimum": 1,
+ "type": "integer"
+ },
+ "request_timeout_ms": {
+ "maximum": 3600000,
+ "minimum": 1000,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "maximum_attempts",
+ "request_timeout_ms",
+ "attempt_timeout_ms"
+ ],
+ "type": "object"
+ },
+ "mode": {
+ "enum": [
+ "fixed_model",
+ "smart_saving",
+ "custom_branches",
+ "free_first"
+ ]
+ },
+ "purpose": {
+ "maxLength": 512,
+ "type": "string"
+ },
+ "requirements": {
+ "additionalProperties": false,
+ "properties": {
+ "minimum_context_tokens": {
+ "maximum": 10000000,
+ "minimum": 0,
+ "type": "integer"
+ },
+ "minimum_output_tokens": {
+ "maximum": 10000000,
+ "minimum": 0,
+ "type": "integer"
+ },
+ "streaming": {
+ "type": "boolean"
+ },
+ "tool": {
+ "type": "boolean"
+ },
+ "vision": {
+ "type": "boolean"
+ }
+ },
+ "required": [],
+ "type": "object"
+ },
+ "schema": {
+ "const": "hiroute.plan-editor/v2"
+ },
+ "smart": {
+ "additionalProperties": false,
+ "properties": {
+ "classifier": {
+ "oneOf": [
+ {
+ "additionalProperties": false,
+ "properties": {
+ "kind": {
+ "const": "local_rules"
+ }
+ },
+ "required": [
+ "kind"
+ ],
+ "type": "object"
+ },
+ {
+ "additionalProperties": false,
+ "properties": {
+ "kind": {
+ "const": "decision_service"
+ },
+ "service": {
+ "additionalProperties": false,
+ "properties": {
+ "connection": {
+ "oneOf": [
+ {
+ "additionalProperties": false,
+ "properties": {
+ "auth_header": {
+ "additionalProperties": false,
+ "properties": {
+ "name": {
+ "maxLength": 128,
+ "minLength": 1,
+ "type": "string"
+ },
+ "value_secret_ref": {
+ "maxLength": 256,
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": [
+ "name",
+ "value_secret_ref"
+ ],
+ "type": "object"
+ },
+ "endpoint": {
+ "maxLength": 2048,
+ "type": "string"
+ },
+ "kind": {
+ "const": "system_one"
+ },
+ "model": {
+ "maxLength": 256,
+ "type": "string"
+ },
+ "provider": {
+ "maxLength": 128,
+ "type": "string"
+ },
+ "timeout_ms": {
+ "maximum": 3600000,
+ "minimum": 1,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "kind",
+ "provider",
+ "model",
+ "endpoint",
+ "timeout_ms",
+ "auth_header"
+ ],
+ "type": "object"
+ },
+ {
+ "additionalProperties": false,
+ "properties": {
+ "auth_header": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "additionalProperties": false,
+ "properties": {
+ "name": {
+ "maxLength": 128,
+ "minLength": 1,
+ "type": "string"
+ },
+ "value_secret_ref": {
+ "maxLength": 256,
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": [
+ "name",
+ "value_secret_ref"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ "endpoint": {
+ "maxLength": 2048,
+ "type": "string"
+ },
+ "kind": {
+ "const": "custom"
+ },
+ "timeout_ms": {
+ "maximum": 3600000,
+ "minimum": 1,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "kind",
+ "endpoint",
+ "timeout_ms"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ "id": {
+ "maxLength": 128,
+ "type": "string"
+ },
+ "name": {
+ "maxLength": 128,
+ "type": "string"
+ },
+ "revision": {
+ "minimum": 1,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "id",
+ "revision",
+ "name",
+ "connection"
+ ],
+ "type": "object"
+ }
+ },
+ "required": [
+ "kind",
+ "service"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ "complex_keywords": {
+ "items": {
+ "maxLength": 64,
+ "type": "string"
+ },
+ "maxItems": 64,
+ "type": "array"
+ },
+ "economy": {
+ "$ref": "#/$defs/candidates"
+ },
+ "judgment": {
+ "$ref": "#/$defs/judgment"
+ },
+ "primary": {
+ "$ref": "#/$defs/candidates"
+ },
+ "reselect_on_user_message": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "economy",
+ "primary",
+ "judgment",
+ "reselect_on_user_message",
+ "classifier",
+ "complex_keywords"
+ ],
+ "type": "object"
+ },
+ "work": {
+ "additionalProperties": false,
+ "properties": {
+ "harness": {
+ "enum": [
+ "codex_cli",
+ "claude_code",
+ "qoder_cli",
+ "pi",
+ "deepseek_harness"
+ ]
+ },
+ "protocol": {
+ "enum": [
+ "responses",
+ "messages"
+ ]
+ }
+ },
+ "required": [
+ "harness",
+ "protocol"
+ ],
+ "type": "object"
+ }
+ },
+ "required": [
+ "schema",
+ "display_name",
+ "purpose",
+ "mode",
+ "candidates",
+ "smart",
+ "free",
+ "delegation_enabled",
+ "requirements",
+ "limits"
+ ],
+ "type": "object"
+ },
+ "judgment": {
+ "additionalProperties": false,
+ "properties": {
+ "competence": {
+ "additionalProperties": false,
+ "properties": {
+ "criteria": {
+ "items": {
+ "type": "string"
+ },
+ "maxItems": 3,
+ "minItems": 3,
+ "type": "array"
+ },
+ "floor_millis": {
+ "maximum": 1000,
+ "minimum": 0,
+ "type": "integer"
+ },
+ "instructions": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "floor_millis",
+ "instructions",
+ "criteria"
+ ],
+ "type": "object"
+ },
+ "degree": {
+ "additionalProperties": false,
+ "properties": {
+ "complex": {
+ "type": "string"
+ },
+ "instructions": {
+ "type": "string"
+ },
+ "simple": {
+ "type": "string"
+ },
+ "simple_threshold_millis": {
+ "maximum": 1000,
+ "minimum": 0,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "simple_threshold_millis",
+ "instructions",
+ "simple",
+ "complex"
+ ],
+ "type": "object"
+ }
+ },
+ "required": [
+ "degree",
+ "competence"
+ ],
+ "type": "object"
+ },
+ "lifecycle_change": {
+ "additionalProperties": false,
+ "properties": {
+ "expected_head_revision": {
+ "minimum": 1,
+ "type": "integer"
+ },
+ "plan_id": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "schema": {
+ "const": "hiroute.plan-lifecycle-change/v1"
+ },
+ "status": {
+ "enum": [
+ "enabled",
+ "disabled",
+ "deleted"
+ ]
+ }
+ },
+ "required": [
+ "schema",
+ "plan_id",
+ "expected_head_revision",
+ "status"
+ ],
+ "type": "object"
+ },
+ "selection": {
+ "additionalProperties": false,
+ "properties": {
+ "binding_id": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "reasoning": {
+ "oneOf": [
+ {
+ "additionalProperties": false,
+ "properties": {
+ "kind": {
+ "const": "profile"
+ },
+ "profile": {
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": [
+ "kind",
+ "profile"
+ ],
+ "type": "object"
+ },
+ {
+ "additionalProperties": false,
+ "properties": {
+ "enabled": {
+ "type": "boolean"
+ },
+ "kind": {
+ "const": "toggle"
+ }
+ },
+ "required": [
+ "kind",
+ "enabled"
+ ],
+ "type": "object"
+ },
+ {
+ "additionalProperties": false,
+ "properties": {
+ "kind": {
+ "const": "budget"
+ },
+ "tokens": {
+ "maximum": 4294967295,
+ "minimum": 1,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "kind",
+ "tokens"
+ ],
+ "type": "object"
+ }
+ ]
+ }
+ },
+ "required": [
+ "binding_id"
+ ],
+ "type": "object"
+ }
+ },
+ "$id": "hiroute://contracts/cli/publication-checkpoint-change.v1.schema.json",
+ "$ref": "#/$defs/checkpoint_change",
+ "$schema": "https://json-schema.org/draft/2020-12/schema"
+}
diff --git a/contracts/compatibility-support.v1.json b/contracts/compatibility-support.v1.json
index 9877f0d8..ab2cae30 100644
--- a/contracts/compatibility-support.v1.json
+++ b/contracts/compatibility-support.v1.json
@@ -294,6 +294,10 @@
"hiroute.protected-apply-grant/v2",
"hiroute.protected-input-result/v1",
"hiroute.protected-input/v1",
+ "hiroute.publication-checkpoint-change/v1",
+ "hiroute.publication-checkpoint-control/v1",
+ "hiroute.publication-checkpoint-effect/v1",
+ "hiroute.publication-checkpoint-preview/v1",
"hiroute.qoder-additional-model/v1",
"hiroute.qoder-borrowed-context-collaboration/v1",
"hiroute.qoder-native-restore/v1",
@@ -566,6 +570,7 @@
"hiroute.compiled-agent-plan",
"hiroute.materialized-route-digest",
"hiroute.plan-content-change",
+ "hiroute.publication-checkpoint",
"hiroute.routing-control-change",
"hiroute.routing-control",
"hiroute.routing-publication-effect",
@@ -577,6 +582,10 @@
"hiroute.compiled-agent-plan/v3",
"hiroute.stable-route/v1",
"hiroute.plan-content-change/v2",
+ "hiroute.publication-checkpoint-change/v1",
+ "hiroute.publication-checkpoint-control/v1",
+ "hiroute.publication-checkpoint-effect/v1",
+ "hiroute.publication-checkpoint-preview/v1",
"hiroute.routing-control/v2",
"hiroute.routing-publication-effect/v2",
"hiroute.stored-plan/v1"
@@ -993,6 +1002,35 @@
}
]
},
+ {
+ "subject": "compute_management_released_lifecycle",
+ "audited_prefixes": [
+ "hiroute.compute-management-change",
+ "hiroute.compute-management-mutation",
+ "hiroute.compute-management-preview",
+ "hiroute.compute-management-source"
+ ],
+ "current_contracts": [
+ "hiroute.compute-management-change/v2",
+ "hiroute.compute-management-mutation/v2",
+ "hiroute.compute-management-preview/v2",
+ "hiroute.compute-management-source/v3"
+ ],
+ "legacy_support": [
+ {
+ "contract": "hiroute.compute-management-mutation/v2",
+ "mode": "frozen_fixture",
+ "owner": "compute-management",
+ "reason": "Freeze the public v0.2.0 d625e653048b2306c88da07826d52027e9891675 production CLI save journal: omitted edit and mandatory desired object must retain canonical bytes, source identity, secret effect binding and accepted preview digest. The fixture uses a local synthetic upstream, not provider credentials. The same v2 identifier remains the current producer and reader in the listed Domain module; only delete adds a null desired value.",
+ "removal_condition": "Remove only when v0.2.0 is no longer a supported source under the release support policy and its frozen recovery regression is explicitly retired. Never regenerate with a current serializer.",
+ "allowed_paths": [
+ "crates/local-storage/tests/fixtures/v0.2.0-compute-operation.json",
+ "crates/local-storage/src/control/compute/management/tests/released_lifecycle.rs",
+ "crates/domain/src/compute/management/mod.rs"
+ ]
+ }
+ ]
+ },
{
"subject": "compute_management_queries",
"audited_prefixes": [
diff --git a/crates/application-api/src/compute_management.rs b/crates/application-api/src/compute_management.rs
index 8edf535d..369c8feb 100644
--- a/crates/application-api/src/compute_management.rs
+++ b/crates/application-api/src/compute_management.rs
@@ -258,6 +258,18 @@ pub struct ComputeManagementChangeV2 {
pub key_edits: Vec<ComputeKeyEditV2>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub validation: Option<ComputeValidationRefV2>,
+ /// Explicit lifecycle intent. Omitted legacy saves retain replacement semantics and bytes.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub edit: Option<ComputeManagementEditV1>,
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
+pub enum ComputeManagementEditV1 {
+ Rename { display_name: String },
+ AppendModels,
+ RemoveModels,
+ Delete,
}
impl ComputeManagementChangeV2 {
@@ -284,6 +296,30 @@ impl ComputeManagementChangeV2 {
if let Some(validation) = &self.validation {
validation.validate_shape()?;
}
+ if let Some(edit) = &self.edit {
+ let saved = matches!(self.subject, ComputeManagementSubjectV2::SavedSource { .. });
+ let valid = match edit {
+ ComputeManagementEditV1::Rename { display_name } => {
+ !display_name.trim().is_empty()
+ && display_name.chars().count() <= 60
+ && !display_name.chars().any(char::is_control)
+ && (!saved || self.selected_model_refs.is_empty())
+ }
+ ComputeManagementEditV1::AppendModels => {
+ !saved && !self.selected_model_refs.is_empty()
+ }
+ ComputeManagementEditV1::RemoveModels => {
+ saved && !self.selected_model_refs.is_empty()
+ }
+ ComputeManagementEditV1::Delete => saved && self.selected_model_refs.is_empty(),
+ };
+ if !valid
+ || (!self.key_edits.is_empty()
+ && (saved || !matches!(edit, ComputeManagementEditV1::Rename { .. })))
+ {
+ return Err(ComputeManagementContractErrorV2::InvalidCandidate);
+ }
+ }
Ok(())
}
}
@@ -629,6 +665,7 @@ mod tests {
#[test]
fn management_change_remains_a_closed_versioned_shape() {
let change = ComputeManagementChangeV2 {
+ edit: None,
schema: COMPUTE_MANAGEMENT_CHANGE_SCHEMA_V2.to_owned(),
subject: ComputeManagementSubjectV2::Candidate {
candidate: candidate(42),
diff --git a/crates/application-api/src/compute_management_view.rs b/crates/application-api/src/compute_management_view.rs
index 200e4dfa..b2e705c1 100644
--- a/crates/application-api/src/compute_management_view.rs
+++ b/crates/application-api/src/compute_management_view.rs
@@ -133,6 +133,10 @@ pub struct ComputeModelPresentationV1 {
#[serde(rename_all = "snake_case")]
pub enum ComputeManagementActionV2 {
Edit,
+ Rename,
+ AppendModels,
+ RemoveModels,
+ Delete,
AddKey,
Recheck,
Reauthorize,
diff --git a/crates/application-api/src/generated.rs b/crates/application-api/src/generated.rs
index 42a3b104..ea8844d7 100644
--- a/crates/application-api/src/generated.rs
+++ b/crates/application-api/src/generated.rs
@@ -555,6 +555,7 @@ mod tests {
"plan-editor.v2.schema.json",
"plan-lifecycle-change.v1.schema.json",
"planned-manifest.v1.json",
+ "publication-checkpoint-change.v1.schema.json",
"session-list-query.v1.schema.json",
"session-lookup.v1.schema.json",
"setup-apply-request.v1.schema.json",
diff --git a/crates/application-api/src/generated/plan_authoring.rs b/crates/application-api/src/generated/plan_authoring.rs
index a4af9165..864a4531 100644
--- a/crates/application-api/src/generated/plan_authoring.rs
+++ b/crates/application-api/src/generated/plan_authoring.rs
@@ -136,6 +136,10 @@ fn definitions() -> Value {
&["schema", "plan_id", "expected_head_revision", "status"],
json!({"schema":{"const":"hiroute.plan-lifecycle-change/v1"},"plan_id":{"type":"string","minLength":1},"expected_head_revision":{"type":"integer","minimum":1},"status":{"enum":["enabled","disabled","deleted"]}}),
);
+ let checkpoint = object(
+ &["schema"],
+ json!({"schema":{"const":"hiroute.publication-checkpoint-change/v1"}}),
+ );
let draft_change = object(
&["schema", "workspace_id", "draft_id", "action"],
json!({"schema":{"const":"hiroute.plan-draft-change/v1"},"workspace_id":{"type":"string","minLength":1},"draft_id":{"type":"string","minLength":1},"expected_revision":{"type":["integer","null"],"minimum":1},"action":{"oneOf":[object(&["kind","draft"],json!({"kind":{"const":"save"},"draft":reference("draft")})),object(&["kind"],json!({"kind":{"const":"discard"}}))]}}),
@@ -145,7 +149,7 @@ fn definitions() -> Value {
json!({"limit":{"type":"integer","minimum":1,"maximum":128,"default":32},
"cursor":{"oneOf":[{"type":"null"},object(&["snapshot_digest","offset"],json!({"snapshot_digest":{"type":"string","minLength":1},"offset":{"type":"integer","minimum":1}}))]}}),
);
- json!({"judgment":judgment,"catalog_query":catalog_query,"selection":selection,"candidates":candidates,"editor":editor,"draft":draft,"content_change":content,"lifecycle_change":lifecycle,"draft_change":draft_change})
+ json!({"judgment":judgment,"catalog_query":catalog_query,"selection":selection,"candidates":candidates,"editor":editor,"draft":draft,"content_change":content,"lifecycle_change":lifecycle,"checkpoint_change":checkpoint,"draft_change":draft_change})
}
pub(super) fn files() -> Vec<(&'static str, String)> {
[
@@ -154,6 +158,7 @@ pub(super) fn files() -> Vec<(&'static str, String)> {
("plan-content-change.v2.schema.json", "content_change"),
("plan-lifecycle-change.v1.schema.json", "lifecycle_change"),
("plan-draft-change.v1.schema.json", "draft_change"),
+ ("publication-checkpoint-change.v1.schema.json", "checkpoint_change"),
].into_iter().map(|(path, name)| (path, pretty_json(&json!({
"$schema":"https://json-schema.org/draft/2020-12/schema", "$id":format!("hiroute://contracts/cli/{path}"),
"$ref":format!("#/$defs/{name}"), "$defs": definitions(),
diff --git a/crates/application-api/src/plan_authoring.rs b/crates/application-api/src/plan_authoring.rs
index 81319678..d72c58b0 100644
--- a/crates/application-api/src/plan_authoring.rs
+++ b/crates/application-api/src/plan_authoring.rs
@@ -2,6 +2,32 @@
use hiroute_domain::*;
use serde::{Deserialize, Serialize};
+pub use hiroute_domain::{PUBLICATION_CHECKPOINT_CHANGE_SCHEMA_V1, PublicationCheckpointChangeV1};
+pub const PUBLICATION_CHECKPOINT_PREVIEW_SCHEMA_V1: &str =
+ "hiroute.publication-checkpoint-preview/v1";
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct PublicationCheckpointPreviewV1 {
+ pub schema: String,
+ pub change_digest: CanonicalDigest,
+ pub expected_revisions: RevisionSetV1,
+ pub before_digest: CanonicalDigest,
+ pub publication_revision: GatewayPublicationRevision,
+}
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct PublicationCheckpointPreviewRequestV1 {
+ pub change: PublicationCheckpointChangeV1,
+}
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct PublicationCheckpointApplyRequestV1 {
+ pub change: PublicationCheckpointChangeV1,
+ pub accept_digest: CanonicalDigest,
+ pub expected_revisions: RevisionSetV1,
+ pub idempotency_key: String,
+}
+
pub const PLAN_CONTENT_CHANGE_SCHEMA_V2: &str = "hiroute.plan-content-change/v2";
pub const PLAN_CONTENT_PREVIEW_SCHEMA_V2: &str = "hiroute.plan-content-preview/v2";
diff --git a/crates/application-api/src/protocol.rs b/crates/application-api/src/protocol.rs
index 523301c8..84c073b0 100644
--- a/crates/application-api/src/protocol.rs
+++ b/crates/application-api/src/protocol.rs
@@ -1128,7 +1128,7 @@ pub(crate) fn command_arguments(command_id: &str) -> String {
"schema.show" => "Required: --command-id <stable-command-id>. Global --output json and --request-id options are supported.".to_owned(),
"setup.apply" => "The setup document is read from --spec-fd. Digest, expected revision, and idempotency key are mandatory. Mutation authority is accepted only from the protected inherited capability channel.".to_owned(),
"agents.check" => "Configuration, native-authentication and collaboration are bounded local checks admitted by the owner-only same-UID transport and make no upstream model call. Live requires --target JSON containing context_id, surface, expected_applied_revision and client_model_ids, --allow-model-call and a separately delivered one-shot capability bound to that target. Targets are forbidden on local checks; provider, credential, prompt and URL overrides are forbidden.".to_owned(),
- "compute.connection.preview" => "--request-stdin accepts exactly one registered v1 projection, compute-management v2 save, or subscription-check v2 preview request. Preview has no durable side effect and returns the exact digest and revisions required by Apply.".to_owned(),
+ "compute.connection.preview" => "--request-stdin accepts exactly one registered v1 projection, compute-management v2 save/edit, or subscription-check v2 preview request. The optional edit action is rename (display_name), append_models (checked candidate; preserves existing models), remove_models (saved source; selected refs are removals), or delete (saved source; no selected refs). Omitting edit retains released save semantics. Referenced models, including disabled routes and retained versions, cannot be deleted. Preview has no durable side effect and returns the exact digest and revisions required by Apply.".to_owned(),
"compute.connection.apply" => "--request-stdin accepts only the exact preview spec, digest, revisions, and a non-empty idempotency key. Same-UID Local Control reproduces the plan; replay uses the original key and changed payloads are rejected.".to_owned(),
"compute.connection.test" => "--request-stdin selects native, registered, discovered, or saved with its strict nested request. Credentials are referenced only through a protected-input candidate; plaintext credential fields are rejected. The explicit probe may contact the configured provider and may consume quota when an inference model is selected.".to_owned(),
"compute.connection.login" => "--request-stdin accepts list/start with provider codex or claude; status/cancel/forget with an exact login_ref; callback with login_ref and input_candidate. Register callback text first with protected-input register --candidate <callback_input_candidate.candidate_ref> --secret-fd <FD>. OAuth codes, tokens, callback URLs and credential paths are rejected in ordinary request JSON. Start returns a browser URL; successful login still requires subscription check, model selection and save.".to_owned(),
diff --git a/crates/application/src/compute_management/mutations.rs b/crates/application/src/compute_management/mutations.rs
index 0fcf4ab2..9d6184bd 100644
--- a/crates/application/src/compute_management/mutations.rs
+++ b/crates/application/src/compute_management/mutations.rs
@@ -22,6 +22,8 @@ use super::{
ComputeCredentialBindingV2,
};
+mod lifecycle;
+
/// A public preview paired with its sealed, non-wire transaction plan.
pub struct ComputeManagementPreparedPreviewV2 {
pub result: ComputeSavePreviewV2,
@@ -119,6 +121,19 @@ where
}
let resolved = self.resolve_subject(&change, &snapshot.sources)?;
+ if maintenance_scope.is_none() && change.edit.is_some() {
+ self.validate_name_edit(&change, &resolved, &snapshot.sources)?;
+ if resolved.candidate.is_none()
+ || matches!(
+ change.edit,
+ Some(hiroute_application_api::ComputeManagementEditV1::AppendModels)
+ )
+ {
+ return self.preview_lifecycle(change, resolved, snapshot.revisions);
+ }
+ } else if maintenance_scope.is_some() && change.edit.is_some() {
+ return Err(ComputeManagementPlanningErrorV2::InvalidChange);
+ }
let current = resolved.current;
if let Some(scope) = maintenance_scope {
let source = current
@@ -213,6 +228,11 @@ where
&desired.additional_native_endpoints,
&desired.credentials,
)?;
+ if let Some(hiroute_application_api::ComputeManagementEditV1::Rename { display_name }) =
+ &change.edit
+ {
+ desired.display_name = display_name.trim().to_owned();
+ }
desired
.validate()
.map_err(|_| ComputeManagementPlanningErrorV2::InvalidCandidate)?;
@@ -228,44 +248,15 @@ where
&& left.materializes_secret == right.materializes_secret
});
- let spec = ChangeSpecV1 {
- schema_version: CHANGE_SPEC_SCHEMA_V1,
- command_id: "compute.connection.apply".into(),
- resource_id: Some(desired.source_id.clone()),
- desired_state: serde_json::to_value(&change)
- .map_err(|_| ComputeManagementPlanningErrorV2::InvalidChange)?,
- };
- let plan = TransactionPlanV1::from_compute_management_planner(
- spec.clone(),
+ self.seal_preview(
+ change,
current.as_ref(),
- desired.clone(),
+ Some(desired),
+ resolved.candidate.map(|facts| facts.candidate),
+ snapshot.revisions,
secret_mutations,
- )
- .map_err(|_| ComputeManagementPlanningErrorV2::InvalidChange)?;
- let accept_digest = CanonicalDigest::of(&(
- "hiroute.compute-management-preview/v2",
- &spec,
- &snapshot.revisions,
- plan.control(),
- plan.secrets(),
- ))
- .map_err(|_| ComputeManagementPlanningErrorV2::InvalidChange)?;
- let changes = preview_changes(current.as_ref(), &desired);
- Ok(ComputeManagementPreparedPreviewV2 {
- result: ComputeSavePreviewV2 {
- candidate: resolved.candidate.map(|facts| facts.candidate),
- validation: change.validation,
- spec,
- accept_digest,
- expected_revisions: snapshot.revisions,
- changes,
- // Plan references are joined by the central routing composition. This local
- // planner never guesses that an absent adapter means an absent reference.
- affected_plan_refs: Vec::new(),
- },
- plan,
discovery_guards,
- })
+ )
}
pub fn prepare_apply(
@@ -279,6 +270,15 @@ where
serde_json::from_value(request.spec.desired_state.clone())
.map_err(|_| ComputeManagementPlanningErrorV2::InvalidChange)?;
let reproduced = self.preview(change)?;
+ if !reproduced.result.affected_plan_refs.is_empty()
+ && reproduced
+ .result
+ .changes
+ .iter()
+ .any(|change| change.action == "remove" && change.resource_kind == "model_binding")
+ {
+ return Err(ComputeManagementPlanningErrorV2::RevisionConflict);
+ }
if reproduced.result.spec != request.spec
|| reproduced.result.accept_digest != request.accept_digest
|| reproduced.result.expected_revisions != request.expected_revisions
@@ -443,7 +443,10 @@ where
source_id: source_id.into(),
revision,
lineage_digest: lineage_digest.clone(),
- display_name: candidate.display_name.clone(),
+ display_name: current.map_or_else(
+ || candidate.display_name.clone(),
+ |source| source.display_name.clone(),
+ ),
provenance,
target: ComputeManagementTargetV2 {
scheme: target.scheme.clone(),
diff --git a/crates/application/src/compute_management/mutations/lifecycle.rs b/crates/application/src/compute_management/mutations/lifecycle.rs
new file mode 100644
index 00000000..3601c42e
--- /dev/null
+++ b/crates/application/src/compute_management/mutations/lifecycle.rs
@@ -0,0 +1,260 @@
+//! Explicit connection lifecycle; legacy saves keep their replacement-selection semantics.
+use super::*;
+use hiroute_application_api::{ComputeManagementEditV1, ComputeSaveChangeViewV2};
+use hiroute_domain::{ComputeManagementSourceV2, RevisionSetV1};
+
+impl<C, R, S, I> ComputeManagementPlanner<'_, C, R, S, I>
+where
+ C: ComputeCandidatePort,
+ R: ComputeManagementRepositoryPort,
+ S: SecretStorePort,
+ I: ProtectedInputPort,
+{
+ pub(super) fn validate_name_edit(
+ &self,
+ change: &ComputeManagementChangeV2,
+ resolved: &ResolvedSubject,
+ sources: &[ComputeManagementSourceV2],
+ ) -> Result<(), ComputeManagementPlanningErrorV2> {
+ if let Some(ComputeManagementEditV1::Rename { display_name }) = &change.edit {
+ let name = display_name.trim();
+ if sources.iter().any(|source| {
+ source.source_id != resolved.source_id && source.display_name.trim() == name
+ }) {
+ return Err(ComputeManagementPlanningErrorV2::InvalidChange);
+ }
+ }
+ Ok(())
+ }
+
+ pub(super) fn preview_lifecycle(
+ &self,
+ change: ComputeManagementChangeV2,
+ resolved: ResolvedSubject,
+ revisions: RevisionSetV1,
+ ) -> Result<ComputeManagementPreparedPreviewV2, ComputeManagementPlanningErrorV2> {
+ let current = resolved
+ .current
+ .as_ref()
+ .ok_or(ComputeManagementPlanningErrorV2::SourceNotFound)?;
+ let mut source = current.clone();
+ source.revision = source
+ .revision
+ .checked_add(1)
+ .ok_or(ComputeManagementPlanningErrorV2::InvalidChange)?;
+ let mut secrets = Vec::new();
+ let mut discovery_guards = Vec::new();
+ let desired = match change
+ .edit
+ .as_ref()
+ .ok_or(ComputeManagementPlanningErrorV2::InvalidChange)?
+ {
+ ComputeManagementEditV1::Rename { display_name } => {
+ source.display_name = display_name.trim().to_owned();
+ Some(source)
+ }
+ ComputeManagementEditV1::RemoveModels => {
+ let selected = select_saved_models(current, &change.selected_model_refs)?;
+ source.models.retain(|model| {
+ !selected
+ .iter()
+ .any(|removed| removed.binding_id == model.binding_id)
+ });
+ if source.models.is_empty() {
+ return Err(ComputeManagementPlanningErrorV2::ModelNotSelectable);
+ }
+ Some(source)
+ }
+ ComputeManagementEditV1::Delete => {
+ for key in &current.credentials {
+ if self.secrets.generation(&key.credential)? != key.credential.generation() {
+ return Err(ComputeManagementPlanningErrorV2::CredentialConflict);
+ }
+ secrets.push(
+ SecretMutationV1::delete(
+ key.credential.clone(),
+ key.credential.generation(),
+ )
+ .map_err(|_| ComputeManagementPlanningErrorV2::InvalidKeyEdit)?,
+ );
+ }
+ None
+ }
+ ComputeManagementEditV1::AppendModels => {
+ let candidate = resolved
+ .candidate
+ .as_ref()
+ .ok_or(ComputeManagementPlanningErrorV2::InvalidCandidate)?;
+ if candidate.existing_source_id.as_deref() != Some(current.source_id.as_str()) {
+ return Err(ComputeManagementPlanningErrorV2::LineageConflict);
+ }
+ ensure_unique_nonempty(&change.selected_model_refs)?;
+ let mut additions = Vec::new();
+ for reference in &change.selected_model_refs {
+ let member = candidate
+ .models
+ .iter()
+ .find(|model| &model.model_ref == reference);
+ if current.models.iter().any(|old| {
+ &old.model_ref == reference
+ || member
+ .is_some_and(|new| new.upstream_model_id == old.upstream_model_id)
+ }) {
+ continue;
+ }
+ member.ok_or(ComputeManagementPlanningErrorV2::ModelNotSelectable)?;
+ additions.push(reference.clone());
+ }
+ if candidate.validation.as_ref() != change.validation.as_ref() {
+ return Err(ComputeManagementPlanningErrorV2::ValidationConflict);
+ }
+ // Validate the checked connection identity even when every selected member already
+ // exists. Append cannot quietly replace the endpoint, credentials or provenance.
+ let target = candidate
+ .target
+ .as_ref()
+ .ok_or(ComputeManagementPlanningErrorV2::InvalidCandidate)?;
+ if target.scheme != current.target.scheme
+ || target.authority != current.target.authority
+ || target.port != current.target.port
+ || target.request_path != current.target.request_path
+ || target.upstream_protocol != current.target.upstream_protocol
+ || target.protocol_profile_id != current.target.protocol_profile_id
+ || target.protocol_profile_revision != current.target.protocol_profile_revision
+ || candidate.authentication.as_ref() != Some(&current.authentication)
+ || candidate.additional_native_endpoints != current.additional_native_endpoints
+ {
+ return Err(ComputeManagementPlanningErrorV2::LineageConflict);
+ }
+ self.materialize_primary_candidate_key(
+ candidate,
+ Some(current),
+ &change,
+ &mut source,
+ &mut secrets,
+ &mut discovery_guards,
+ )?;
+ if !additions.is_empty() {
+ source.models.extend(select_candidate_models(
+ &current.source_id,
+ Some(current),
+ candidate,
+ &additions,
+ change.intent,
+ )?);
+ }
+ source.validation = map_validation(candidate.validation.as_ref());
+ source.last_candidate_ref = candidate.candidate.candidate_ref.clone();
+ source.last_candidate_revision = candidate.candidate.candidate_revision;
+ Some(source)
+ }
+ };
+ if let Some(source) = &desired {
+ source
+ .validate()
+ .map_err(|_| ComputeManagementPlanningErrorV2::InvalidCandidate)?;
+ }
+ self.seal_preview(
+ change,
+ Some(current),
+ desired,
+ resolved
+ .candidate
+ .as_ref()
+ .map(|facts| facts.candidate.clone()),
+ revisions,
+ secrets,
+ discovery_guards,
+ )
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ pub(super) fn seal_preview(
+ &self,
+ change: ComputeManagementChangeV2,
+ current: Option<&ComputeManagementSourceV2>,
+ desired: Option<ComputeManagementSourceV2>,
+ candidate: Option<ComputeCandidateRefV2>,
+ revisions: RevisionSetV1,
+ secrets: Vec<SecretMutationV1>,
+ discovery_guards: Vec<ComputePreparedDiscoveryGuardV1>,
+ ) -> Result<ComputeManagementPreparedPreviewV2, ComputeManagementPlanningErrorV2> {
+ let source = desired
+ .as_ref()
+ .or(current)
+ .ok_or(ComputeManagementPlanningErrorV2::SourceNotFound)?;
+ let changes = if let Some(desired) = &desired {
+ preview_changes(current, desired)
+ } else {
+ let mut changes = vec![ComputeSaveChangeViewV2 {
+ resource_kind: "compute_source".into(),
+ resource_id: source.source_id.clone(),
+ action: "delete".into(),
+ }];
+ changes.extend(source.models.iter().map(|model| ComputeSaveChangeViewV2 {
+ resource_kind: "model_binding".into(),
+ resource_id: model.binding_id.clone(),
+ action: "remove".into(),
+ }));
+ changes.extend(
+ source
+ .credentials
+ .iter()
+ .map(|key| ComputeSaveChangeViewV2 {
+ resource_kind: "credential_key".into(),
+ resource_id: key.key_id.clone(),
+ action: "remove".into(),
+ }),
+ );
+ changes
+ };
+ let removed: Vec<_> = changes
+ .iter()
+ .filter(|change| change.resource_kind == "model_binding" && change.action == "remove")
+ .map(|change| change.resource_id.clone())
+ .collect();
+ let affected_plan_refs = if removed.is_empty() {
+ Vec::new()
+ } else {
+ self.repository
+ .compute_management_references(&self.workspace, &removed)?
+ };
+ let spec = ChangeSpecV1 {
+ schema_version: CHANGE_SPEC_SCHEMA_V1,
+ command_id: "compute.connection.apply".into(),
+ resource_id: Some(source.source_id.clone()),
+ desired_state: serde_json::to_value(&change)
+ .map_err(|_| ComputeManagementPlanningErrorV2::InvalidChange)?,
+ };
+ let plan = TransactionPlanV1::from_compute_management_change(
+ spec.clone(),
+ current,
+ desired,
+ secrets,
+ )
+ .map_err(|_| ComputeManagementPlanningErrorV2::InvalidChange)?;
+ // Keep the released save digest unchanged. The writer re-reads references atomically;
+ // a preview is descriptive and never grants permission to bypass that read.
+ let accept_digest = CanonicalDigest::of(&(
+ "hiroute.compute-management-preview/v2",
+ &spec,
+ &revisions,
+ plan.control(),
+ plan.secrets(),
+ ))
+ .map_err(|_| ComputeManagementPlanningErrorV2::InvalidChange)?;
+ Ok(ComputeManagementPreparedPreviewV2 {
+ result: ComputeSavePreviewV2 {
+ candidate,
+ validation: change.validation,
+ spec,
+ accept_digest,
+ expected_revisions: revisions,
+ changes,
+ affected_plan_refs,
+ },
+ plan,
+ discovery_guards,
+ })
+ }
+}
diff --git a/crates/application/src/compute_management/query.rs b/crates/application/src/compute_management/query.rs
index 30a5b61f..140cd5a4 100644
--- a/crates/application/src/compute_management/query.rs
+++ b/crates/application/src/compute_management/query.rs
@@ -644,7 +644,13 @@ fn provenance_kind(value: &ComputeManagementProvenanceV2) -> ComputeCandidatePro
}
pub(super) fn source_actions(source: &ComputeManagementSourceV2) -> Vec<ComputeManagementActionV2> {
- let mut actions = vec![ComputeManagementActionV2::Edit];
+ let mut actions = vec![
+ ComputeManagementActionV2::Edit,
+ ComputeManagementActionV2::Rename,
+ ComputeManagementActionV2::AppendModels,
+ ComputeManagementActionV2::RemoveModels,
+ ComputeManagementActionV2::Delete,
+ ];
if source.provenance.is_native() {
if !matches!(
source.authentication,
diff --git a/crates/application/src/control/mod.rs b/crates/application/src/control/mod.rs
index 614f9e9c..5419ef29 100644
--- a/crates/application/src/control/mod.rs
+++ b/crates/application/src/control/mod.rs
@@ -538,6 +538,18 @@ pub trait ComputeManagementControlPort: Send + Sync {
}
pub trait RoutingFactsPort: Send + Sync {
+ fn publication_checkpoint_snapshot(
+ &self,
+ _workspace: &WorkspaceId,
+ ) -> Result<
+ (
+ hiroute_domain::PublicationRecordV1,
+ hiroute_domain::RevisionSetV1,
+ ),
+ ControlReadError,
+ > {
+ Err(ControlReadError::Unavailable)
+ }
fn decision_services(
&self,
_workspace: &WorkspaceId,
diff --git a/crates/application/src/control_plane/mod.rs b/crates/application/src/control_plane/mod.rs
index b73226fa..9da4b61d 100644
--- a/crates/application/src/control_plane/mod.rs
+++ b/crates/application/src/control_plane/mod.rs
@@ -4,6 +4,7 @@ mod compute;
mod plan_content;
mod plan_draft;
mod plan_lifecycle;
+mod publication_checkpoint;
pub(crate) mod subscription_login;
use hiroute_application_api::{
@@ -319,6 +320,15 @@ pub(crate) fn dispatch_preview_routing(
service: &ApplicationService,
request: LocalControlRequestV2,
) -> MachineEnvelopeV2<Value> {
+ if request
+ .payload
+ .get("change")
+ .and_then(|c| c.get("schema"))
+ .and_then(Value::as_str)
+ == Some(hiroute_application_api::PUBLICATION_CHECKPOINT_CHANGE_SCHEMA_V1)
+ {
+ return publication_checkpoint::dispatch_preview(service, request);
+ }
if request
.payload
.get("change")
@@ -354,6 +364,15 @@ pub(crate) fn dispatch_apply_routing(
service: &ApplicationService,
request: LocalControlRequestV2,
) -> MachineEnvelopeV2<Value> {
+ if request
+ .payload
+ .get("change")
+ .and_then(|c| c.get("schema"))
+ .and_then(Value::as_str)
+ == Some(hiroute_application_api::PUBLICATION_CHECKPOINT_CHANGE_SCHEMA_V1)
+ {
+ return publication_checkpoint::dispatch_apply(service, request);
+ }
if request
.payload
.get("change")
diff --git a/crates/application/src/control_plane/publication_checkpoint.rs b/crates/application/src/control_plane/publication_checkpoint.rs
new file mode 100644
index 00000000..ff4b6b20
--- /dev/null
+++ b/crates/application/src/control_plane/publication_checkpoint.rs
@@ -0,0 +1,137 @@
+//! Explicit reference refresh preserves current routing authority and uses its normal writer.
+use super::*;
+use crate::control::RoutingFactsPort;
+use hiroute_application_api::*;
+use hiroute_domain::{PublicationRecordV1, TransactionPlanV1, WorkspaceId, checkpoint_publication};
+
+fn preview(
+ port: &dyn RoutingFactsPort,
+ change: &PublicationCheckpointChangeV1,
+) -> Result<(PublicationCheckpointPreviewV1, PublicationRecordV1), ErrorCode> {
+ if change.schema != PUBLICATION_CHECKPOINT_CHANGE_SCHEMA_V1 {
+ return Err(ErrorCode::InvalidArguments);
+ }
+ let (before, revisions) = port
+ .publication_checkpoint_snapshot(&WorkspaceId::default())
+ .map_err(map_control_error)?;
+ let after = checkpoint_publication(&before).map_err(|_| ErrorCode::InvalidArguments)?;
+ let digest = hiroute_domain::CanonicalDigest::of(&(
+ PUBLICATION_CHECKPOINT_PREVIEW_SCHEMA_V1,
+ change,
+ &revisions,
+ &before,
+ &after,
+ ))
+ .map_err(|_| ErrorCode::InvalidArguments)?;
+ Ok((
+ PublicationCheckpointPreviewV1 {
+ schema: PUBLICATION_CHECKPOINT_PREVIEW_SCHEMA_V1.into(),
+ change_digest: digest,
+ expected_revisions: revisions,
+ before_digest: before.digest.clone(),
+ publication_revision: after.publication_revision,
+ },
+ before,
+ ))
+}
+
+pub(super) fn dispatch_preview(
+ service: &ApplicationService,
+ request: LocalControlRequestV2,
+) -> MachineEnvelopeV2<Value> {
+ if request.protected_grant.is_some() {
+ return failed(ErrorCode::CapabilityDenied, request.request_id);
+ }
+ let Some(port) = service.ports.as_ref().and_then(|p| p.routing.as_deref()) else {
+ return failed(ErrorCode::DaemonUnavailable, request.request_id);
+ };
+ let payload: PublicationCheckpointPreviewRequestV1 =
+ match serde_json::from_value(request.payload) {
+ Ok(value) => value,
+ Err(_) => return failed(ErrorCode::InvalidArguments, request.request_id),
+ };
+ match preview(port, &payload.change) {
+ Ok((result, _)) => succeeded(result, request.request_id),
+ Err(error) => failed(error, request.request_id),
+ }
+}
+
+pub(super) fn dispatch_apply(
+ service: &ApplicationService,
+ request: LocalControlRequestV2,
+) -> MachineEnvelopeV2<Value> {
+ if request.protected_grant.is_some() {
+ return failed(ErrorCode::CapabilityDenied, request.request_id);
+ }
+ let Some(ports) = service.ports.as_ref() else {
+ return failed(ErrorCode::DaemonUnavailable, request.request_id);
+ };
+ let (Some(port), Some(mutation)) = (ports.routing.as_ref(), ports.mutation.as_ref()) else {
+ return failed(ErrorCode::DaemonUnavailable, request.request_id);
+ };
+ let payload: PublicationCheckpointApplyRequestV1 = match serde_json::from_value(request.payload)
+ {
+ Ok(value) => value,
+ Err(_) => return failed(ErrorCode::InvalidArguments, request.request_id),
+ };
+ if payload.idempotency_key.is_empty() {
+ return failed(ErrorCode::InvalidArguments, request.request_id);
+ }
+ if let Some(replay) = replay_apply(
+ ports.control.as_ref(),
+ PrincipalKind::InteractiveUser,
+ "ApplyAgentPlanChange",
+ &payload.idempotency_key,
+ &payload.accept_digest,
+ &request.request_id,
+ ) {
+ return replay;
+ }
+ let prepared = (|| {
+ let (reproduced, before) = preview(port.as_ref(), &payload.change)?;
+ if reproduced.change_digest != payload.accept_digest
+ || reproduced.expected_revisions != payload.expected_revisions
+ {
+ return Err(ErrorCode::ChangePreviewStale);
+ }
+ let spec = hiroute_domain::ChangeSpecV1 {
+ schema_version: hiroute_domain::CHANGE_SPEC_SCHEMA_V1,
+ command_id: "routing.apply".into(),
+ resource_id: Some("publication/current".into()),
+ desired_state: serde_json::to_value(&payload.change)
+ .map_err(|_| ErrorCode::InvalidArguments)?,
+ };
+ let plan = TransactionPlanV1::from_publication_checkpoint(spec.clone(), before)
+ .map_err(|_| ErrorCode::InvalidArguments)?;
+ let apply = ApplyRequestV1 {
+ schema_version: CHANGE_SPEC_SCHEMA_V1,
+ spec,
+ accept_digest: payload.accept_digest.clone(),
+ expected_revisions: payload.expected_revisions.clone(),
+ idempotency_key: payload.idempotency_key,
+ apply_capability: None,
+ };
+ let prepared =
+ crate::PreparedTransactionV1::for_setup(apply, payload.accept_digest.clone(), plan)
+ .map_err(|e| e.error_code())?;
+ let port = port.clone();
+ Ok(prepared.with_revalidation(move || {
+ let (current, _) = preview(port.as_ref(), &payload.change)
+ .map_err(|_| crate::TransactionError::ChangePreviewStale)?;
+ if current.change_digest != payload.accept_digest
+ || current.expected_revisions != payload.expected_revisions
+ {
+ return Err(crate::TransactionError::ChangePreviewStale);
+ }
+ Ok(())
+ }))
+ })();
+ let prepared = match prepared {
+ Ok(value) => value,
+ Err(error) => return failed(error, request.request_id),
+ };
+ 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),
+ }
+}
diff --git a/crates/application/src/operations/compute_compensation.rs b/crates/application/src/operations/compute_compensation.rs
new file mode 100644
index 00000000..b33c1b12
--- /dev/null
+++ b/crates/application/src/operations/compute_compensation.rs
@@ -0,0 +1,70 @@
+use super::*;
+use hiroute_domain::{ComputeManagementMutationV2, VerifiedSecretSubjectV1};
+
+impl<'a, C, S, R, E, I> TransactionCoordinator<'a, C, S, R, E, I>
+where
+ C: ControlRepositoryPort
+ + ComputeSourceControlPort
+ + CredentialPoolControlPort
+ + ConnectionOptionAuthorizationPort,
+ S: SecretStorePort,
+ R: RuntimeStatePort,
+ E: ExternalEffectPort,
+ I: ProtectedInputPort,
+{
+ pub(super) fn reconcile_compute_compensation(
+ &self,
+ operation: &OperationV1,
+ ) -> Result<(), TransactionError> {
+ let Some(value) = operation.plan.control().get("compute_management_mutation") else {
+ return Ok(());
+ };
+ let mutation: ComputeManagementMutationV2 = serde_json::from_value(value.clone())
+ .map_err(|_| TransactionError::EffectOwnershipLost)?;
+ let Some(expected) = mutation.expected() else {
+ return Ok(());
+ };
+ let mut references = Vec::new();
+ for secret in operation.plan.secrets() {
+ let Some(key) = expected
+ .credentials
+ .iter()
+ .find(|key| key.key_id == secret.credential().credential_id())
+ else {
+ continue;
+ };
+ let reference = self
+ .secrets
+ .compensated_secret_reference(&operation.operation_id, secret)?
+ .ok_or(TransactionError::EffectMissing)?;
+ let subject = VerifiedSecretSubjectV1::from_authenticated_transport(
+ reference.subject(),
+ reference.owner_scope(),
+ )
+ .map_err(|_| TransactionError::EffectOwnershipLost)?;
+ let destination = reference
+ .allowed_destinations()
+ .iter()
+ .next()
+ .ok_or(TransactionError::EffectMissing)?;
+ let restored = self.secrets.resolve_secret(
+ &subject,
+ &reference,
+ reference.purpose(),
+ destination,
+ reference.generation(),
+ )?;
+ if self.secrets.fingerprint(&restored)? != key.fingerprint {
+ return Err(TransactionError::EffectOwnershipLost);
+ }
+ if reference != key.credential {
+ references.push(reference);
+ }
+ }
+ if !references.is_empty() {
+ self.control
+ .reconcile_compute_compensation(operation, &references)?;
+ }
+ Ok(())
+ }
+}
diff --git a/crates/application/src/operations/mod.rs b/crates/application/src/operations/mod.rs
index 4db6580e..8568fc13 100644
--- a/crates/application/src/operations/mod.rs
+++ b/crates/application/src/operations/mod.rs
@@ -20,6 +20,7 @@ use crate::change::{
};
mod agent_access_grants;
+mod compute_compensation;
mod execution;
mod prepared;
@@ -667,6 +668,7 @@ where
.observe_runtime(&operation.operation_id, mutation)?,
)?;
}
+ self.reconcile_compute_compensation(operation)?;
Ok(())
}
diff --git a/crates/application/src/subscriptions/mod.rs b/crates/application/src/subscriptions/mod.rs
index 4b8525c7..f84df149 100644
--- a/crates/application/src/subscriptions/mod.rs
+++ b/crates/application/src/subscriptions/mod.rs
@@ -265,6 +265,7 @@ pub fn prepare_compute_management_change(
validate_model_selection(candidate, &selected_model_refs, enable)?;
let change = ComputeManagementChangeV2 {
+ edit: None,
schema: COMPUTE_MANAGEMENT_CHANGE_SCHEMA_V2.to_owned(),
subject: ComputeManagementSubjectV2::Candidate {
candidate: candidate.candidate.clone(),
diff --git a/crates/cli/src/control_plane.rs b/crates/cli/src/control_plane.rs
index 1c8af297..357f8cfe 100644
--- a/crates/cli/src/control_plane.rs
+++ b/crates/cli/src/control_plane.rs
@@ -154,6 +154,18 @@ fn routing_request(options: &[String], apply: bool) -> Result<Value, ErrorCode>
let request: T = serde_json::from_value(value).map_err(|_| ErrorCode::InvalidArguments)?;
serde_json::to_value(request).map_err(|_| ErrorCode::Internal)
}
+ if value
+ .get("change")
+ .and_then(|c| c.get("schema"))
+ .and_then(Value::as_str)
+ == Some(hiroute_application_api::PUBLICATION_CHECKPOINT_CHANGE_SCHEMA_V1)
+ {
+ return if apply {
+ typed::<hiroute_application_api::PublicationCheckpointApplyRequestV1>(value)
+ } else {
+ typed::<hiroute_application_api::PublicationCheckpointPreviewRequestV1>(value)
+ };
+ }
if value
.get("change")
.and_then(|c| c.get("schema"))
diff --git a/crates/daemon/src/control/runtime/effects/tests.rs b/crates/daemon/src/control/runtime/effects/tests.rs
index 4241bedc..71e48e20 100644
--- a/crates/daemon/src/control/runtime/effects/tests.rs
+++ b/crates/daemon/src/control/runtime/effects/tests.rs
@@ -25,6 +25,7 @@ use serde_json::json;
use super::*;
+mod checkpoint;
mod publication_validation;
mod service_status;
mod skill_activation;
@@ -45,8 +46,10 @@ fn publication_restart_reconciles_every_persisted_install_window() {
};
use std::sync::Arc;
- for window in 0..5 {
- eprintln!("restart-window {window}: open");
+ for scenario in 0..10 {
+ let is_checkpoint = scenario >= 5;
+ let window = scenario % 5;
+ eprintln!("restart-window {window}, checkpoint={is_checkpoint}: open");
let directory = tempfile::tempdir().unwrap();
fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o700)).unwrap();
let runtime = super::super::ProductionControlRuntime::open_with_release_catalog(
@@ -56,7 +59,7 @@ fn publication_restart_reconciles_every_persisted_install_window() {
.unwrap();
let lkg = directory.path().join("gateway-lkg.json");
let target = Arc::new(GatewayPublicationAdapter::new(Arc::new(
- GatewayPublicationInstaller::open(&lkg).unwrap(),
+ GatewayPublicationInstaller::open_for_product_authority(&lkg).unwrap(),
)));
*runtime.adapter.publication_target.lock().unwrap() = Some(target.clone());
let desired =
@@ -64,12 +67,30 @@ fn publication_restart_reconciles_every_persisted_install_window() {
"../../../../../../e2e/product/fixtures/routing/current-publication.v3.json"
))
.unwrap();
- let (mut operation, intent, record) = routing_operation(
- &runtime.adapter,
- desired,
- None,
- &format!("restart-{window}"),
- );
+ let (mut operation, intent, record) = if is_checkpoint {
+ let prepared = checkpoint::operation(
+ &runtime.adapter,
+ desired,
+ &format!("checkpoint-restart-{window}"),
+ );
+ let before = runtime
+ .adapter
+ .stores_lock()
+ .unwrap()
+ .control()
+ .active_publication(&WorkspaceId::default())
+ .unwrap()
+ .unwrap();
+ target.activate_verified(&before).unwrap();
+ prepared
+ } else {
+ routing_operation(
+ &runtime.adapter,
+ desired,
+ None,
+ &format!("restart-{window}"),
+ )
+ };
let effect = runtime.adapter.apply_external(&operation, &intent).unwrap();
eprintln!("restart-window {window}: initial effect");
operation
@@ -154,8 +175,11 @@ fn publication_restart_reconciles_every_persisted_install_window() {
)
.unwrap();
let target = Arc::new(GatewayPublicationAdapter::new(Arc::new(
- GatewayPublicationInstaller::open(&lkg).unwrap(),
+ GatewayPublicationInstaller::open_for_product_authority(&lkg).unwrap(),
)));
+ // The production role=all entry reconstructs authority from Control, never
+ // from the Gateway cache left by an interrupted installation.
+ assert!(target.is_empty().unwrap());
assert!(RuntimePublicationFeed::pin(target.as_ref()).is_none());
*recovered.adapter.publication_target.lock().unwrap() = Some(target.clone());
recovered.adapter.restore_active_publication().unwrap();
diff --git a/crates/daemon/src/control/runtime/effects/tests/checkpoint.rs b/crates/daemon/src/control/runtime/effects/tests/checkpoint.rs
new file mode 100644
index 00000000..93e71554
--- /dev/null
+++ b/crates/daemon/src/control/runtime/effects/tests/checkpoint.rs
@@ -0,0 +1,186 @@
+use super::*;
+
+fn wire(
+ name: &str,
+ payload: serde_json::Value,
+) -> hiroute_application_api::LocalControlWireRequestV2 {
+ hiroute_application_api::LocalControlWireRequestV2 {
+ schema_version: hiroute_application_api::LOCAL_CONTROL_SCHEMA_V2,
+ request_id: format!("checkpoint-{name}"),
+ operation_id: name.into(),
+ payload,
+ protected_grant: None,
+ }
+}
+
+#[test]
+fn publication_checkpoint_wire_is_installed_cas_bound_replayable_and_recovery_gated() {
+ if crate::test_support::isolated_agent_home(
+ "control::runtime::effects::tests::checkpoint::publication_checkpoint_wire_is_installed_cas_bound_replayable_and_recovery_gated",
+ ) {
+ return;
+ }
+ use crate::control::LocalControlDaemon;
+ use crate::gateway_ports::GatewayPublicationAdapter;
+ use hiroute_application::ApplicationService;
+ use hiroute_gateway::server::publication::GatewayPublicationInstaller;
+ let directory = tempfile::tempdir().unwrap();
+ let runtime = super::super::super::ProductionControlRuntime::open_with_release_catalog(
+ directory.path(),
+ crate::release_catalog::fixture_catalog(),
+ )
+ .unwrap();
+ let workspace = WorkspaceId::default();
+ let publication = GatewayPublicationV1::new(
+ workspace.clone(),
+ GatewayPublicationRevision::new(1).unwrap(),
+ hiroute_domain::AliasRegistryV1::default(),
+ vec![],
+ )
+ .unwrap();
+ let before = PublicationRecordV1::from_publication(workspace.clone(), &publication).unwrap();
+ {
+ let stores = runtime.adapter.stores_lock().unwrap();
+ stores.control().prepare_publication(&before, None).unwrap();
+ stores
+ .control()
+ .mark_publication_active(&workspace, before.publication_revision, &before.digest)
+ .unwrap();
+ }
+ let service = LocalControlDaemon::new(ApplicationService::new(runtime.application_ports()));
+ let change = json!({"schema": hiroute_domain::PUBLICATION_CHECKPOINT_CHANGE_SCHEMA_V1});
+ let preview =
+ || service.dispatch_wire(wire("PreviewAgentPlanChange", json!({"change":change})));
+ assert!(
+ preview().error.is_some(),
+ "A stored publication without verified installation is insufficient"
+ );
+ let target = Arc::new(GatewayPublicationAdapter::new(Arc::new(
+ GatewayPublicationInstaller::open_for_product_authority(
+ directory.path().join("gateway-lkg.json"),
+ )
+ .unwrap(),
+ )));
+ runtime
+ .configure_managed_agent_runtime(
+ "http://127.0.0.1:5837/v1".into(),
+ "/test/hiroute".into(),
+ Some(target),
+ )
+ .unwrap();
+ let ready = preview();
+ assert!(ready.error.is_none(), "{ready:?}");
+ let ready = ready.data.unwrap();
+ let apply = json!({"change":change, "accept_digest":ready["change_digest"], "expected_revisions":ready["expected_revisions"], "idempotency_key":"empty-checkpoint"});
+ let accepted = service.dispatch_wire(wire("ApplyAgentPlanChange", apply.clone()));
+ assert!(accepted.error.is_none(), "{accepted:?}");
+ let accepted = accepted.data.unwrap();
+ assert_eq!(accepted["state"], "succeeded", "{accepted}");
+ let after = {
+ let stores = runtime.adapter.stores_lock().unwrap();
+ let control = stores.control();
+ let after = control.active_publication(&workspace).unwrap().unwrap();
+ assert_eq!(
+ control.last_known_good_publication(&workspace).unwrap(),
+ Some(before.clone())
+ );
+ assert_eq!(after.publication_revision.get(), 2);
+ assert!(after.verify_current().unwrap().plans.is_empty());
+ assert!(after.verify_current().unwrap().grants.is_empty());
+ assert!(control.prepared_publication(&workspace).unwrap().is_none());
+ after
+ };
+ let replay = service.dispatch_wire(wire("ApplyAgentPlanChange", apply.clone()));
+ assert!(replay.error.is_none(), "{replay:?}");
+ assert_eq!(
+ replay.data.unwrap()["operation_id"],
+ accepted["operation_id"]
+ );
+ let mut stale = apply;
+ stale["idempotency_key"] = json!("new-key-stale-preview");
+ assert!(
+ service
+ .dispatch_wire(wire("ApplyAgentPlanChange", stale))
+ .error
+ .is_some()
+ );
+ assert_eq!(
+ runtime
+ .adapter
+ .stores_lock()
+ .unwrap()
+ .control()
+ .active_publication(&workspace)
+ .unwrap(),
+ Some(after.clone())
+ );
+ // Recovery and another prepared publication continue to block a new checkpoint.
+ runtime
+ .adapter
+ .stores_lock()
+ .unwrap()
+ .control()
+ .begin_plan_version_recovery()
+ .unwrap();
+ assert!(preview().error.is_some());
+ runtime
+ .adapter
+ .stores_lock()
+ .unwrap()
+ .control()
+ .reconcile_plan_versions(&workspace, &[], 1)
+ .unwrap();
+ assert!(preview().error.is_none());
+ let competing = hiroute_domain::checkpoint_publication(&after).unwrap();
+ runtime
+ .adapter
+ .stores_lock()
+ .unwrap()
+ .control()
+ .prepare_publication(&competing, Some(after.publication_revision))
+ .unwrap();
+ assert!(preview().error.is_some());
+}
+
+pub(super) fn operation(
+ adapter: &LocalControlAdapter,
+ prior: GatewayPublicationV1,
+ key: &str,
+) -> (OperationV1, ExternalEffectIntentV1, PublicationRecordV1) {
+ let (mut prior, _) = current_publication(prior);
+ prior.publication_revision = GatewayPublicationRevision::new(10).unwrap();
+ let workspace = WorkspaceId::default();
+ let before = PublicationRecordV1::from_publication(workspace.clone(), &prior).unwrap();
+ let revisions = {
+ let stores = adapter.stores_lock().unwrap();
+ stores.control().prepare_publication(&before, None).unwrap();
+ stores
+ .control()
+ .mark_publication_active(&workspace, before.publication_revision, &before.digest)
+ .unwrap();
+ stores.control().current_revisions(&workspace).unwrap()
+ };
+ let plan = TransactionPlanV1::from_publication_checkpoint(ChangeSpecV1 {
+ schema_version: hiroute_domain::CHANGE_SPEC_SCHEMA_V1,
+ command_id: "routing.apply".into(), resource_id: Some("publication/current".into()),
+ desired_state: json!({"schema":hiroute_domain::PUBLICATION_CHECKPOINT_CHANGE_SCHEMA_V1}),
+ }, before).unwrap();
+ let scope = IdempotencyScopeV1::new("interactive-user", "ApplyAgentPlanChange", key).unwrap();
+ let request_digest = CanonicalDigest::of_bytes(key.as_bytes());
+ let operation = OperationV1::new(
+ OperationId::derive(&workspace, &scope, &request_digest),
+ workspace,
+ scope,
+ request_digest,
+ CanonicalDigest::of_bytes(b"checkpoint-accepted"),
+ revisions,
+ plan,
+ )
+ .unwrap();
+ begin_operation_for_test(adapter, &operation);
+ let intent = operation.plan.external()[0].clone();
+ let record = hiroute_domain::routing_publication_record(&intent)
+ .unwrap()
+ .unwrap();
+ (operation, intent, record)
+}
diff --git a/crates/daemon/src/control/runtime/model_connections.rs b/crates/daemon/src/control/runtime/model_connections.rs
index 2460dbee..0c888185 100644
--- a/crates/daemon/src/control/runtime/model_connections.rs
+++ b/crates/daemon/src/control/runtime/model_connections.rs
@@ -652,7 +652,18 @@ impl ComputeManagementControlPort for LocalControlAdapter {
candidate,
validation,
disposition,
- source_id: source.as_ref().map(|source| source.source_id.clone()),
+ source_id: source
+ .as_ref()
+ .map(|source| source.source_id.clone())
+ .or_else(|| {
+ (operation.state == OperationState::Succeeded
+ && matches!(
+ change.edit,
+ Some(hiroute_application_api::ComputeManagementEditV1::Delete)
+ ))
+ .then(|| operation.plan.spec().resource_id.clone())
+ .flatten()
+ }),
bindings: source
.as_ref()
.map(|source| {
diff --git a/crates/daemon/src/control/runtime/model_connections/saved.rs b/crates/daemon/src/control/runtime/model_connections/saved.rs
index f06921b0..b26fdd42 100644
--- a/crates/daemon/src/control/runtime/model_connections/saved.rs
+++ b/crates/daemon/src/control/runtime/model_connections/saved.rs
@@ -169,6 +169,22 @@ impl LocalControlAdapter {
draft.models.push(declaration);
}
}
+ // Offer current same-product declarations for explicit append. These are not
+ // account inventory or verified inference, and never replace saved members.
+ for declaration in super::saved_prefill::registered_product_candidates(
+ catalog.model_metadata(),
+ &base_url,
+ &request_path,
+ draft.protocol,
+ ) {
+ if !draft
+ .models
+ .iter()
+ .any(|model| model.upstream_model_id == declaration.upstream_model_id)
+ {
+ draft.models.push(declaration);
+ }
+ }
draft.trusted_lineage_digest = Some(source.lineage_digest.clone());
Ok(draft)
}
@@ -933,6 +949,13 @@ mod tests {
.unwrap();
assert_eq!(draft.additional_native_endpoints, original_endpoints);
assert_eq!(source.credentials, original_credentials);
+ assert!(
+ draft.models.iter().any(|model| !source
+ .models
+ .iter()
+ .any(|saved| saved.upstream_model_id == model.upstream_model_id)),
+ "saved-source check must retain unselected product candidates for append"
+ );
for (id, vision) in [("deepseek-v4-flash", false), ("deepseek-v4.1-flash", true)] {
let model = draft
.models
diff --git a/crates/daemon/src/control/runtime/model_connections/saved_prefill.rs b/crates/daemon/src/control/runtime/model_connections/saved_prefill.rs
index 079cdf76..a6130718 100644
--- a/crates/daemon/src/control/runtime/model_connections/saved_prefill.rs
+++ b/crates/daemon/src/control/runtime/model_connections/saved_prefill.rs
@@ -5,12 +5,134 @@ use hiroute_domain::{
MetadataTokenStateV1, ModelMetadataCatalogV1, NativeReasoningCapabilityV1, UpstreamProtocol,
};
use hiroute_integrations::{
- NativeCandidateFactBasisV1, NativeCandidateFactValueV1, NativeModelDeclarationV1,
+ NativeCandidateFactBasisV1, NativeCandidateFactValueV1, NativeModelCapabilityDeclarationV1,
+ NativeModelDeclarationV1,
};
const FALLBACK_CONTEXT: u64 = 200_000;
const FALLBACK_OUTPUT: u64 = 32_768;
+pub(super) fn registered_product_candidates(
+ catalog: &ModelMetadataCatalogV1,
+ base_url: &str,
+ request_path: &str,
+ protocol: UpstreamProtocol,
+) -> Vec<NativeModelDeclarationV1> {
+ let protocol_name = match protocol {
+ UpstreamProtocol::ChatCompletions => "openai-chat",
+ UpstreamProtocol::Responses => "openai-responses",
+ UpstreamProtocol::Messages => "anthropic-messages",
+ };
+ let endpoint = format!(
+ "{}/{}",
+ base_url.trim_end_matches('/'),
+ request_path.trim_start_matches('/')
+ );
+ let matches_interface = |interface: &hiroute_domain::MetadataProductInterfaceV1| {
+ interface.protocol == protocol_name
+ && interface
+ .base_url
+ .as_ref()
+ .zip(interface.request_path.as_ref())
+ .is_some_and(|(base, path)| {
+ format!(
+ "{}/{}",
+ base.trim_end_matches('/'),
+ path.trim_start_matches('/')
+ ) == endpoint
+ })
+ };
+ let products: Vec<_> = catalog
+ .access_products
+ .iter()
+ .filter(|product| product.interfaces.iter().any(&matches_interface))
+ .collect();
+ let interfaces: std::collections::BTreeSet<_> = products
+ .iter()
+ .flat_map(|product| {
+ product
+ .interfaces
+ .iter()
+ .filter(|interface| matches_interface(interface))
+ .map(move |interface| {
+ (
+ product.product_key.as_str(),
+ interface.interface_key.as_str(),
+ )
+ })
+ })
+ .collect();
+ let retired: std::collections::BTreeSet<_> = catalog
+ .endpoint_bindings
+ .iter()
+ .filter(|binding| {
+ products
+ .iter()
+ .any(|product| product.product_key == binding.product_key)
+ && matches!(binding.lifecycle.as_deref(), Some("deprecated" | "retired"))
+ })
+ .map(|binding| binding.upstream_model_id.as_str())
+ .collect();
+ let mut ids: std::collections::BTreeSet<String> = products
+ .iter()
+ .flat_map(|product| product.documented_upstream_model_ids.iter().cloned())
+ .collect();
+ ids.extend(
+ catalog
+ .endpoint_bindings
+ .iter()
+ .filter(|binding| {
+ binding
+ .interface_candidates
+ .iter()
+ .any(|key| interfaces.contains(&(binding.product_key.as_str(), key.as_str())))
+ })
+ .map(|binding| binding.upstream_model_id.clone()),
+ );
+ fn unknown<T>() -> NativeCandidateFactValueV1<T> {
+ NativeCandidateFactValueV1 {
+ value: None,
+ basis: NativeCandidateFactBasisV1::Unknown,
+ }
+ }
+ ids.into_iter()
+ .filter(|id| !retired.contains(id.as_str()))
+ .map(|id| {
+ let display_name = matching_binding(catalog, base_url, request_path, protocol, &id)
+ .and_then(|(binding, _)| {
+ catalog
+ .canonical_models
+ .iter()
+ .find(|model| model.model_key == binding.model_key)
+ })
+ .map(|model| model.display_name.clone())
+ .unwrap_or_else(|| id.clone());
+ let mut declaration = NativeModelDeclarationV1 {
+ upstream_model_id: id,
+ display_name,
+ catalog_configuration_id: None,
+ membership: hiroute_application_api::ComputeModelMembershipV2::UserDeclared,
+ capabilities: NativeModelCapabilityDeclarationV1 {
+ tool: unknown(),
+ vision: unknown(),
+ streaming: unknown(),
+ context_tokens: unknown(),
+ max_output_tokens: unknown(),
+ native_reasoning: unknown(),
+ },
+ };
+ fill_unknown_registered_model(
+ &mut declaration,
+ catalog,
+ base_url,
+ request_path,
+ protocol,
+ );
+ declaration
+ })
+ .collect()
+}
+
pub(super) fn fill_unknown_registered_model(
declaration: &mut NativeModelDeclarationV1,
catalog: &ModelMetadataCatalogV1,
@@ -227,3 +349,46 @@ fn fill_unknown<T>(fact: &mut NativeCandidateFactValueV1<T>, value: T) {
};
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn saved_token_plan_append_candidates_are_product_scoped_declarations() {
+ let catalog = crate::release_catalog::current_fixture_catalog();
+ let candidates = registered_product_candidates(
+ catalog.model_metadata(),
+ "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
+ "/chat/completions",
+ UpstreamProtocol::ChatCompletions,
+ );
+ assert!(
+ candidates.len() > 1,
+ "a saved single model must offer other product models"
+ );
+ assert!(
+ candidates
+ .iter()
+ .any(|model| model.upstream_model_id == "qwen3.6-plus")
+ );
+ assert!(
+ candidates
+ .iter()
+ .all(|model| model.catalog_configuration_id.is_none()
+ && model.membership
+ == hiroute_application_api::ComputeModelMembershipV2::UserDeclared
+ && model.capabilities.context_tokens.basis
+ == NativeCandidateFactBasisV1::UserDeclared)
+ );
+ assert!(
+ registered_product_candidates(
+ catalog.model_metadata(),
+ "https://unrelated.example.test/v1",
+ "/chat/completions",
+ UpstreamProtocol::ChatCompletions
+ )
+ .is_empty()
+ );
+ }
+}
diff --git a/crates/daemon/src/control/runtime/routing.rs b/crates/daemon/src/control/runtime/routing.rs
index 77377735..0b8b952b 100644
--- a/crates/daemon/src/control/runtime/routing.rs
+++ b/crates/daemon/src/control/runtime/routing.rs
@@ -19,6 +19,77 @@ mod candidates;
use candidates::CandidateDiagnostics;
impl RoutingFactsPort for LocalControlAdapter {
+ fn publication_checkpoint_snapshot(
+ &self,
+ workspace: &WorkspaceId,
+ ) -> Result<
+ (
+ hiroute_domain::PublicationRecordV1,
+ hiroute_domain::RevisionSetV1,
+ ),
+ ControlReadError,
+ > {
+ let (record, revisions) = {
+ let stores = self.stores_lock().map_err(super::map_port)?;
+ let control = stores.control();
+ control
+ .require_plan_version_recovery_ready(workspace)
+ .map_err(|_| ControlReadError::Unavailable)?;
+ if control
+ .prepared_publication(workspace)
+ .map_err(super::map_port)?
+ .is_some()
+ {
+ return Err(ControlReadError::Unavailable);
+ }
+ (
+ control
+ .active_publication(workspace)
+ .map_err(super::map_port)?
+ .ok_or(ControlReadError::Unavailable)?,
+ control
+ .current_revisions(workspace)
+ .map_err(super::map_port)?,
+ )
+ };
+ record
+ .verify_current()
+ .map_err(|_| ControlReadError::Corrupt)?;
+ if !self
+ .publication_is_installed(&record)
+ .map_err(super::map_port)?
+ {
+ return Err(ControlReadError::Unavailable);
+ }
+ let stores = self.stores_lock().map_err(super::map_port)?;
+ stores
+ .control()
+ .require_plan_version_recovery_ready(workspace)
+ .map_err(|_| ControlReadError::Unavailable)?;
+ if stores
+ .control()
+ .prepared_publication(workspace)
+ .map_err(super::map_port)?
+ .is_some()
+ {
+ return Err(ControlReadError::SnapshotChanged);
+ }
+ if stores
+ .control()
+ .active_publication(workspace)
+ .map_err(super::map_port)?
+ .as_ref()
+ != Some(&record)
+ || stores
+ .control()
+ .current_revisions(workspace)
+ .map_err(super::map_port)?
+ != revisions
+ {
+ return Err(ControlReadError::SnapshotChanged);
+ }
+ Ok((record, revisions))
+ }
fn plan_lifecycle_snapshot(
&self,
workspace: &WorkspaceId,
diff --git a/crates/daemon/src/control/runtime/subscriptions/login.rs b/crates/daemon/src/control/runtime/subscriptions/login.rs
index 724e3855..e0cedf87 100644
--- a/crates/daemon/src/control/runtime/subscriptions/login.rs
+++ b/crates/daemon/src/control/runtime/subscriptions/login.rs
@@ -102,7 +102,29 @@ impl LocalControlAdapter {
"subscription.admission.invalid_plan",
)
})?;
- let source = envelope.compute_management_mutation.desired();
+ let Some(source) = envelope.compute_management_mutation.desired() else {
+ // Forgetting a saved connection does not require or revoke a connector login.
+ return Ok(());
+ };
+ if operation
+ .plan
+ .spec()
+ .desired_state
+ .pointer("/subject/kind")
+ .and_then(serde_json::Value::as_str)
+ == Some("saved_source")
+ && matches!(
+ operation
+ .plan
+ .spec()
+ .desired_state
+ .pointer("/edit/action")
+ .and_then(serde_json::Value::as_str),
+ Some("rename" | "remove_models")
+ )
+ {
+ return Ok(());
+ }
if source.state != MaterializationState::Ready {
return Ok(());
}
@@ -332,6 +354,7 @@ impl LocalControlAdapter {
.current_revisions(&WorkspaceId::default())
.map_err(super::error::map_port)?;
let preview = self.preview_compute_save(ComputeManagementChangeV2 {
+ edit: None,
schema: COMPUTE_MANAGEMENT_CHANGE_SCHEMA_V2.into(),
subject: ComputeManagementSubjectV2::SavedSource {
source_id: source.source_id.clone(),
diff --git a/crates/daemon/src/control/runtime/subscriptions/login_admission_tests.rs b/crates/daemon/src/control/runtime/subscriptions/login_admission_tests.rs
index 63c49eaf..f986acff 100644
--- a/crates/daemon/src/control/runtime/subscriptions/login_admission_tests.rs
+++ b/crates/daemon/src/control/runtime/subscriptions/login_admission_tests.rs
@@ -265,6 +265,7 @@ impl Fixture {
let candidate = checked.checked_candidate.as_ref().unwrap();
self.save_request(
ComputeManagementChangeV2 {
+ edit: None,
schema: COMPUTE_MANAGEMENT_CHANGE_SCHEMA_V2.into(),
subject: ComputeManagementSubjectV2::Candidate {
candidate: candidate.candidate.clone(),
@@ -294,6 +295,7 @@ impl Fixture {
let source = &snapshot.sources[0];
self.save_request(
ComputeManagementChangeV2 {
+ edit: None,
schema: COMPUTE_MANAGEMENT_CHANGE_SCHEMA_V2.into(),
subject: ComputeManagementSubjectV2::SavedSource {
source_id: source.source_id.clone(),
@@ -635,3 +637,47 @@ fn succeeded_replay_after_forget_preserves_disabled_source_without_restart() {
assert_eq!(fixture.spawns(), spawns);
assert!(!fixture.credential_path(&login.login_ref).exists());
}
+
+#[test]
+fn deleting_saved_connection_keeps_managed_login_and_does_not_restart_provider() {
+ if isolated("deleting_saved_connection_keeps_managed_login_and_does_not_restart_provider") {
+ return;
+ }
+ for provider in [
+ SubscriptionLoginProviderV1::Codex,
+ SubscriptionLoginProviderV1::Claude,
+ ] {
+ let fixture = Fixture::new();
+ let login = fixture.authorize(provider);
+ let checked = fixture.check(&login);
+ fixture.save(fixture.candidate_request(&checked, "first-save"));
+ let snapshot = fixture.snapshot();
+ let source = &snapshot.sources[0];
+ let path = fixture.credential_path(&login.login_ref);
+ let before = fs::read(&path).unwrap();
+ let spawns = fixture.spawns();
+ let request = fixture.save_request(
+ ComputeManagementChangeV2 {
+ schema: COMPUTE_MANAGEMENT_CHANGE_SCHEMA_V2.into(),
+ subject: ComputeManagementSubjectV2::SavedSource {
+ source_id: source.source_id.clone(),
+ },
+ expected_revisions: snapshot.revisions,
+ selected_model_refs: Vec::new(),
+ intent: ComputeManagementIntentV2::SaveReady,
+ key_edits: Vec::new(),
+ validation: None,
+ edit: Some(hiroute_application_api::ComputeManagementEditV1::Delete),
+ },
+ "delete-connection",
+ );
+ fixture.save(request);
+ assert!(fixture.snapshot().sources.is_empty());
+ assert_eq!(
+ fs::read(path).unwrap(),
+ before,
+ "connection deletion must preserve the independent login"
+ );
+ assert_eq!(fixture.spawns(), spawns);
+ }
+}
diff --git a/crates/daemon/src/control/runtime/subscriptions/maintenance.rs b/crates/daemon/src/control/runtime/subscriptions/maintenance.rs
index 47ec2faf..3e8431ab 100644
--- a/crates/daemon/src/control/runtime/subscriptions/maintenance.rs
+++ b/crates/daemon/src/control/runtime/subscriptions/maintenance.rs
@@ -523,6 +523,7 @@ impl LocalControlAdapter {
return Err(MaintenanceFailure::RuntimeUnavailable);
}
let change = ComputeManagementChangeV2 {
+ edit: None,
schema: COMPUTE_MANAGEMENT_CHANGE_SCHEMA_V2.to_owned(),
subject: ComputeManagementSubjectV2::Candidate {
candidate: checked_candidate.candidate.clone(),
diff --git a/crates/daemon/tests/discovered_model_product.rs b/crates/daemon/tests/discovered_model_product.rs
index e01176db..32bc4e76 100644
--- a/crates/daemon/tests/discovered_model_product.rs
+++ b/crates/daemon/tests/discovered_model_product.rs
@@ -62,6 +62,7 @@ fn change(
revisions: RevisionSetV1,
) -> ComputeManagementChangeV2 {
ComputeManagementChangeV2 {
+ edit: None,
schema: COMPUTE_MANAGEMENT_CHANGE_SCHEMA_V2.into(),
subject: ComputeManagementSubjectV2::Candidate {
candidate: candidate.candidate.clone(),
diff --git a/crates/daemon/tests/local_worker_platform.rs b/crates/daemon/tests/local_worker_platform.rs
index 12211c02..606ad86b 100644
--- a/crates/daemon/tests/local_worker_platform.rs
+++ b/crates/daemon/tests/local_worker_platform.rs
@@ -446,10 +446,12 @@ async fn local_worker_materials_and_sessions_never_share_ownership() {
0o700
);
let literal = "a path with spaces; $(not-a-command)";
- let output = std::process::Command::new(root.join("native-launcher"))
- .arg(literal)
- .output()
- .unwrap();
+ let output = local_worker_support::materialized_launcher::output_with_file_busy_retry(|| {
+ std::process::Command::new(root.join("native-launcher"))
+ .arg(literal)
+ .output()
+ })
+ .unwrap();
assert!(output.status.success());
assert_eq!(output.stdout, literal.as_bytes());
assert!(
diff --git a/crates/daemon/tests/local_worker_support/materialized_launcher.rs b/crates/daemon/tests/local_worker_support/materialized_launcher.rs
new file mode 100644
index 00000000..3fc9eaa6
--- /dev/null
+++ b/crates/daemon/tests/local_worker_support/materialized_launcher.rs
@@ -0,0 +1,111 @@
+use std::{
+ io,
+ process::Output,
+ time::{Duration, Instant},
+};
+
+pub fn output_with_file_busy_retry(
+ mut output: impl FnMut() -> io::Result<Output>,
+) -> io::Result<Output> {
+ let deadline = Instant::now() + Duration::from_millis(100);
+ loop {
+ match output() {
+ // Execution has not started. A concurrently forked fixture can briefly retain
+ // the freshly materialized script's writer; never retry a child result.
+ Err(error)
+ if error.kind() == io::ErrorKind::ExecutableFileBusy
+ && Instant::now() < deadline =>
+ {
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ result => return result,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ #[cfg(target_os = "linux")]
+ fn held_writer_matches_original_failure_then_runs_launcher_only_once() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let root = super::super::private_tempdir().unwrap();
+ let script = root.path().join("native-launcher");
+ std::fs::write(
+ &script,
+ b"#!/bin/sh\nprintf 'launched\\n' >> \"$0.started\"\nprintf '%s' \"$1\"\n",
+ )
+ .unwrap();
+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o700)).unwrap();
+ let mut writer = Some(
+ std::fs::OpenOptions::new()
+ .write(true)
+ .open(&script)
+ .unwrap(),
+ );
+ let literal = "a path with spaces; $(not-a-command)";
+ let mut attempts = 0;
+ let mut original_error = None;
+ let output = output_with_file_busy_retry(|| {
+ attempts += 1;
+ let result = std::process::Command::new(&script).arg(literal).output();
+ if attempts == 1 {
+ original_error = result.as_ref().err().and_then(io::Error::raw_os_error);
+ // Release only after reproducing the original direct Command failure.
+ // No timed writer thread or successful isolated rerun establishes this proof.
+ drop(writer.take());
+ }
+ result
+ })
+ .unwrap();
+ assert_eq!(original_error, Some(nix::errno::Errno::ETXTBSY as i32));
+ assert!(attempts >= 2);
+ assert!(output.status.success());
+ assert_eq!(output.stdout, literal.as_bytes());
+ assert_eq!(
+ std::fs::read(root.path().join("native-launcher.started")).unwrap(),
+ b"launched\n"
+ );
+ }
+
+ #[test]
+ fn non_file_busy_errors_and_child_failures_are_never_retried() {
+ let mut attempts = 0;
+ let error = output_with_file_busy_retry(|| {
+ attempts += 1;
+ Err(io::Error::from(io::ErrorKind::PermissionDenied))
+ })
+ .unwrap_err();
+ assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
+ assert_eq!(attempts, 1);
+
+ let mut attempts = 0;
+ let output = output_with_file_busy_retry(|| {
+ attempts += 1;
+ std::process::Command::new("/bin/sh")
+ .args(["-c", "printf 'child failure' >&2; exit 7"])
+ .output()
+ })
+ .unwrap();
+ assert_eq!(output.status.code(), Some(7));
+ assert_eq!(output.stderr, b"child failure");
+ assert_eq!(attempts, 1);
+ }
+
+ #[test]
+ fn persistent_file_busy_error_is_bounded_and_returned() {
+ let started = Instant::now();
+ let mut attempts = 0;
+ let error = output_with_file_busy_retry(|| {
+ attempts += 1;
+ Err(io::Error::from(io::ErrorKind::ExecutableFileBusy))
+ })
+ .unwrap_err();
+ assert_eq!(error.kind(), io::ErrorKind::ExecutableFileBusy);
+ assert!(attempts >= 2);
+ assert!(started.elapsed() < Duration::from_secs(1));
+ }
+}
diff --git a/crates/daemon/tests/local_worker_support/mod.rs b/crates/daemon/tests/local_worker_support/mod.rs
index f58118e5..04dc7f86 100644
--- a/crates/daemon/tests/local_worker_support/mod.rs
+++ b/crates/daemon/tests/local_worker_support/mod.rs
@@ -13,6 +13,8 @@ use std::{
use tokio::io::{AsyncBufReadExt, BufReader};
use zeroize::Zeroizing;
+pub mod materialized_launcher;
+
pub fn request(root: &Path, cwd: &Path, nonce: &str, mode: &str) -> WorkerLaunchRequest {
let binary = std::env::current_exe().unwrap();
let execution = WorkerExecutionIntentV1 {
diff --git a/crates/daemon/tests/pre_gateway_compute_routing.rs b/crates/daemon/tests/pre_gateway_compute_routing.rs
index 19c5f5b4..8dd5ca53 100644
--- a/crates/daemon/tests/pre_gateway_compute_routing.rs
+++ b/crates/daemon/tests/pre_gateway_compute_routing.rs
@@ -743,6 +743,7 @@ fn run_discovered_prepare_path(root: &Path) {
assert_eq!(replayed, candidate);
let change = ComputeManagementChangeV2 {
+ edit: None,
schema: COMPUTE_MANAGEMENT_CHANGE_SCHEMA_V2.into(),
subject: ComputeManagementSubjectV2::Candidate {
candidate: candidate.candidate.clone(),
diff --git a/crates/daemon/tests/subscription_management_product.rs b/crates/daemon/tests/subscription_management_product.rs
index 8f3af30f..3619bef2 100644
--- a/crates/daemon/tests/subscription_management_product.rs
+++ b/crates/daemon/tests/subscription_management_product.rs
@@ -433,6 +433,7 @@ async fn hirouted_client_core_subscription_save_snapshot_and_restart_are_closed(
.preview_compute_save(
"subscription-save-preview",
ComputeManagementChangeV2 {
+ edit: None,
schema: COMPUTE_MANAGEMENT_CHANGE_SCHEMA_V2.into(),
subject: ComputeManagementSubjectV2::Candidate {
candidate: checked_candidate.candidate.clone(),
@@ -516,6 +517,7 @@ async fn hirouted_client_core_subscription_save_snapshot_and_restart_are_closed(
.preview_compute_save(
"subscription-save-reuse",
ComputeManagementChangeV2 {
+ edit: None,
schema: COMPUTE_MANAGEMENT_CHANGE_SCHEMA_V2.into(),
subject: ComputeManagementSubjectV2::Candidate {
candidate: checked_candidate.candidate.clone(),
diff --git a/crates/daemon/tests/support/subscription_cache_regression.rs b/crates/daemon/tests/support/subscription_cache_regression.rs
index 26a3dfc1..d1779968 100644
--- a/crates/daemon/tests/support/subscription_cache_regression.rs
+++ b/crates/daemon/tests/support/subscription_cache_regression.rs
@@ -122,6 +122,7 @@ async fn save_checked(
.preview_compute_save(
&format!("{label}-preview"),
ComputeManagementChangeV2 {
+ edit: None,
schema: COMPUTE_MANAGEMENT_CHANGE_SCHEMA_V2.into(),
subject: ComputeManagementSubjectV2::Candidate {
candidate: candidate.candidate.clone(),
@@ -335,6 +336,7 @@ async fn unconsumed_check_expires_when_same_saved_source_revision_changes() {
.preview_compute_save(
"revision-disable-preview",
ComputeManagementChangeV2 {
+ edit: None,
schema: COMPUTE_MANAGEMENT_CHANGE_SCHEMA_V2.into(),
subject: ComputeManagementSubjectV2::SavedSource {
source_id: source.source_id.clone(),
@@ -383,6 +385,7 @@ async fn unconsumed_check_expires_when_same_saved_source_revision_changes() {
.preview_compute_save(
"revision-stale-save",
ComputeManagementChangeV2 {
+ edit: None,
schema: COMPUTE_MANAGEMENT_CHANGE_SCHEMA_V2.into(),
subject: ComputeManagementSubjectV2::Candidate {
candidate: candidate.candidate.clone(),
diff --git a/crates/domain/src/compute/management/mod.rs b/crates/domain/src/compute/management/mod.rs
index e06ae054..5f1498ea 100644
--- a/crates/domain/src/compute/management/mod.rs
+++ b/crates/domain/src/compute/management/mod.rs
@@ -560,7 +560,7 @@ pub struct ComputeManagementMutationV2 {
desired_revision: u64,
desired_digest: CanonicalDigest,
change_spec_digest: CanonicalDigest,
- desired: ComputeManagementSourceV2,
+ desired: Option<ComputeManagementSourceV2>,
}
impl ComputeManagementMutationV2 {
@@ -569,15 +569,35 @@ impl ComputeManagementMutationV2 {
current: Option<&ComputeManagementSourceV2>,
desired: ComputeManagementSourceV2,
) -> Result<Self, ComputeManagementErrorV2> {
+ Self::from_optional_planner(spec, current, Some(desired))
+ }
+
+ pub fn from_optional_planner(
+ spec: &ChangeSpecV1,
+ current: Option<&ComputeManagementSourceV2>,
+ desired: Option<ComputeManagementSourceV2>,
+ ) -> Result<Self, ComputeManagementErrorV2> {
+ let identity = desired
+ .as_ref()
+ .or(current)
+ .ok_or(ComputeManagementErrorV2::InvalidMutation)?;
let mutation = Self {
schema: COMPUTE_MANAGEMENT_MUTATION_SCHEMA_V2.to_owned(),
- transaction: "compare_and_swap".to_owned(),
- source_id: desired.source_id.clone(),
+ transaction: if desired.is_some() {
+ "compare_and_swap"
+ } else {
+ "delete"
+ }
+ .to_owned(),
+ source_id: identity.source_id.clone(),
expected_revision: current.map_or(0, |source| source.revision),
expected_digest: current.map(ComputeManagementSourceV2::digest).transpose()?,
expected: current.cloned(),
- desired_revision: desired.revision,
- desired_digest: desired.digest()?,
+ desired_revision: desired.as_ref().map_or_else(
+ || identity.revision.checked_add(1).unwrap_or(0),
+ |source| source.revision,
+ ),
+ desired_digest: Self::optional_digest(desired.as_ref())?,
change_spec_digest: CanonicalDigest::of(spec)
.map_err(|_| ComputeManagementErrorV2::InvalidDigest)?,
desired,
@@ -588,13 +608,27 @@ impl ComputeManagementMutationV2 {
}
pub fn validate_shape(&self, spec: &ChangeSpecV1) -> Result<(), ComputeManagementErrorV2> {
- self.desired.validate()?;
+ if let Some(desired) = &self.desired {
+ desired.validate()?;
+ if self.transaction != "compare_and_swap"
+ || self.source_id != desired.source_id
+ || self.desired_revision != desired.revision
+ {
+ return Err(ComputeManagementErrorV2::InvalidMutation);
+ }
+ } else if self.transaction != "delete"
+ || self.expected.is_none()
+ || spec
+ .desired_state
+ .pointer("/edit/action")
+ .and_then(serde_json::Value::as_str)
+ != Some("delete")
+ {
+ return Err(ComputeManagementErrorV2::InvalidMutation);
+ }
if self.schema != COMPUTE_MANAGEMENT_MUTATION_SCHEMA_V2
- || self.transaction != "compare_and_swap"
- || self.source_id != self.desired.source_id
- || self.desired_revision != self.desired.revision
|| self.desired_revision != self.expected_revision.checked_add(1).unwrap_or(0)
- || self.desired_digest != self.desired.digest()?
+ || self.desired_digest != Self::optional_digest(self.desired.as_ref())?
|| self.change_spec_digest
!= CanonicalDigest::of(spec).map_err(|_| ComputeManagementErrorV2::InvalidDigest)?
|| spec.command_id != "compute.connection.apply"
@@ -646,8 +680,22 @@ impl ComputeManagementMutationV2 {
self.expected.as_ref()
}
- pub fn desired(&self) -> &ComputeManagementSourceV2 {
- &self.desired
+ pub fn desired(&self) -> Option<&ComputeManagementSourceV2> {
+ self.desired.as_ref()
+ }
+
+ pub fn desired_digest(&self) -> &CanonicalDigest {
+ &self.desired_digest
+ }
+
+ fn optional_digest(
+ source: Option<&ComputeManagementSourceV2>,
+ ) -> Result<CanonicalDigest, ComputeManagementErrorV2> {
+ match source {
+ Some(source) => source.digest(),
+ None => CanonicalDigest::of(&serde_json::Value::Null)
+ .map_err(|_| ComputeManagementErrorV2::InvalidDigest),
+ }
}
}
@@ -674,6 +722,20 @@ pub trait ComputeManagementRepositoryPort {
&self,
workspace: &WorkspaceId,
) -> PortResult<ComputeManagementStoredSnapshotV2>;
+
+ /// Exact binding references, including disabled plans and retained execution versions.
+ /// An adapter without this read cannot authorize removal.
+ fn compute_management_references(
+ &self,
+ workspace: &WorkspaceId,
+ binding_ids: &[String],
+ ) -> PortResult<Vec<String>> {
+ let _ = (workspace, binding_ids);
+ Err(crate::PortError::new(
+ crate::PortErrorCode::Unavailable,
+ "compute.management.references.unavailable",
+ ))
+ }
}
pub fn validate_authentication(
diff --git a/crates/domain/src/lib.rs b/crates/domain/src/lib.rs
index eba618a2..9a7cec51 100644
--- a/crates/domain/src/lib.rs
+++ b/crates/domain/src/lib.rs
@@ -47,15 +47,16 @@ pub use operation::{
ExternalEffectPort, IdempotencyScopeV1, OPERATION_INPUT_SCHEMA, OPERATION_SCHEMA_VERSION,
OperationId, OperationState, OperationStatus, OperationStepKind, OperationStepStatus,
OperationStepV1, OperationV1, OperationValidationError, OwnedEffectKind, OwnedEffectV1,
- PlanContentControlV2, ProtectedApplyCapability, ProtectedSecret, RuntimeMutationV1,
- RuntimeStatePort, SETTINGS_SERVICE_COMPLETION_SCHEMA, SecretFingerprintAlgorithm,
- SecretMutationKind, SecretMutationV1, SecretStorePort, SettingsServiceCompletionV1,
- StoredOperationInputV1, SubscriptionCheckIntentV2, TransactionPlanV1,
- VerifiedApplyAuthorizationV1, VerifiedSecretSubjectV1, WorkerDependencySelectionChangeV1,
- WorkerDependencySelectionRecordV1, agent_connection_publication_record,
- agent_connection_restore_publication_record, decode_subscription_check_intent,
- is_agent_access_grant_effect, is_settings_managed_configuration, is_settings_publication,
- is_subscription_check_effect, routing_publication_record, settings_model_publication_intent,
+ PUBLICATION_CHECKPOINT_CHANGE_SCHEMA_V1, PlanContentControlV2, ProtectedApplyCapability,
+ ProtectedSecret, PublicationCheckpointChangeV1, RuntimeMutationV1, RuntimeStatePort,
+ SETTINGS_SERVICE_COMPLETION_SCHEMA, SecretFingerprintAlgorithm, SecretMutationKind,
+ SecretMutationV1, SecretStorePort, SettingsServiceCompletionV1, StoredOperationInputV1,
+ SubscriptionCheckIntentV2, TransactionPlanV1, VerifiedApplyAuthorizationV1,
+ VerifiedSecretSubjectV1, WorkerDependencySelectionChangeV1, WorkerDependencySelectionRecordV1,
+ agent_connection_publication_record, agent_connection_restore_publication_record,
+ checkpoint_publication, decode_subscription_check_intent, is_agent_access_grant_effect,
+ is_settings_managed_configuration, is_settings_publication, is_subscription_check_effect,
+ routing_publication_record, settings_model_publication_intent,
settings_model_publication_record, valid_user_agent_token, validate_idempotency_key,
validate_settings_model_publication_intent,
};
diff --git a/crates/domain/src/operation/compute_management.rs b/crates/domain/src/operation/compute_management.rs
index 060e16ec..c0e1e597 100644
--- a/crates/domain/src/operation/compute_management.rs
+++ b/crates/domain/src/operation/compute_management.rs
@@ -14,8 +14,18 @@ impl TransactionPlanV1 {
desired: crate::ComputeManagementSourceV2,
secrets: Vec<SecretMutationV1>,
) -> Result<Self, OperationValidationError> {
- let mutation = crate::ComputeManagementMutationV2::from_planner(&spec, current, desired)
- .map_err(|_| OperationValidationError::UnregisteredEffectPlan)?;
+ Self::from_compute_management_change(spec, current, Some(desired), secrets)
+ }
+
+ pub fn from_compute_management_change(
+ spec: ChangeSpecV1,
+ current: Option<&crate::ComputeManagementSourceV2>,
+ desired: Option<crate::ComputeManagementSourceV2>,
+ secrets: Vec<SecretMutationV1>,
+ ) -> Result<Self, OperationValidationError> {
+ let mutation =
+ crate::ComputeManagementMutationV2::from_optional_planner(&spec, current, desired)
+ .map_err(|_| OperationValidationError::UnregisteredEffectPlan)?;
let control = json!({"compute_management_mutation": &mutation});
validate_management_plan(&spec, &control, &secrets, &[], &[])?;
Ok(Self {
@@ -69,14 +79,20 @@ pub(super) fn validate_management_plan(
.unwrap_or_default();
let desired = mutation
.desired()
- .credentials
- .iter()
- .map(|credential| (credential.key_id.as_str(), credential))
- .collect::<BTreeMap<_, _>>();
+ .map(|source| {
+ source
+ .credentials
+ .iter()
+ .map(|credential| (credential.key_id.as_str(), credential))
+ .collect::<BTreeMap<_, _>>()
+ })
+ .unwrap_or_default();
let destinations = mutation
.desired()
- .native_destinations()
- .map_err(|_| OperationValidationError::UnregisteredEffectPlan)?;
+ .map(|source| source.native_destinations())
+ .transpose()
+ .map_err(|_| OperationValidationError::UnregisteredEffectPlan)?
+ .unwrap_or_default();
let mut secret_by_id = BTreeMap::new();
for secret in secrets {
diff --git a/crates/domain/src/operation/mod.rs b/crates/domain/src/operation/mod.rs
index b2692bd6..71c05c68 100644
--- a/crates/domain/src/operation/mod.rs
+++ b/crates/domain/src/operation/mod.rs
@@ -20,8 +20,12 @@ mod agent_config_permission;
mod agent_connection;
mod compute;
mod compute_management;
+mod publication_checkpoint;
mod routing;
mod routing_content;
+pub use publication_checkpoint::{
+ PUBLICATION_CHECKPOINT_CHANGE_SCHEMA_V1, PublicationCheckpointChangeV1, checkpoint_publication,
+};
mod routing_draft;
pub use routing_content::{ConsumedPlanDraftV1, PlanContentControlV2};
mod journal;
@@ -1667,6 +1671,18 @@ pub trait ControlRepositoryPort {
) -> PortResult<EffectReconciliation>;
fn activate_control(&self, effect: &OwnedEffectV1) -> PortResult<OwnedEffectV1>;
fn compensate_control(&self, effect: &OwnedEffectV1) -> PortResult<CompensationOutcome>;
+ /// Converges exact managed-source references after authenticated Secret compensation,
+ /// while this operation still owns the writer. Must be CAS-protected and idempotent.
+ fn reconcile_compute_compensation(
+ &self,
+ _operation: &OperationV1,
+ _references: &[CredentialRefV1],
+ ) -> PortResult<()> {
+ Err(crate::PortError::new(
+ crate::PortErrorCode::Unavailable,
+ "control.compute_compensation.unsupported",
+ ))
+ }
/// Persists a terminal state and releases the durable single-writer claim when safe.
fn finish_operation(&self, operation: &mut OperationV1) -> PortResult<u64>;
/// Persists a non-terminal settings tail and atomically releases this operation's writer
@@ -1739,6 +1755,18 @@ pub trait SecretStorePort {
) -> PortResult<EffectReconciliation>;
fn activate_secret(&self, effect: &OwnedEffectV1) -> PortResult<OwnedEffectV1>;
fn compensate_secret(&self, effect: &OwnedEffectV1) -> PortResult<CompensationOutcome>;
+ /// Proves the currently restored reference using this exact compensated effect.
+ /// Missing/unactivated effects may retain the original generation; a newer owner fails.
+ fn compensated_secret_reference(
+ &self,
+ _operation_id: &OperationId,
+ _mutation: &SecretMutationV1,
+ ) -> PortResult<Option<CredentialRefV1>> {
+ Err(crate::PortError::new(
+ crate::PortErrorCode::Unavailable,
+ "secret.compensation_reference.unsupported",
+ ))
+ }
/// Reads only non-secret metadata for one exact canonical connection. Adapters that have not
/// implemented the dedicated grant store fail closed instead of treating it as a Provider
diff --git a/crates/domain/src/operation/publication_checkpoint.rs b/crates/domain/src/operation/publication_checkpoint.rs
new file mode 100644
index 00000000..46accebb
--- /dev/null
+++ b/crates/domain/src/operation/publication_checkpoint.rs
@@ -0,0 +1,325 @@
+//! Explicit re-publication of identical authority, including an empty workspace.
+use super::*;
+use crate::{GatewayPublicationRevision, PublicationRecordV1};
+
+pub const PUBLICATION_CHECKPOINT_CHANGE_SCHEMA_V1: &str =
+ "hiroute.publication-checkpoint-change/v1";
+const CONTROL_SCHEMA: &str = "hiroute.publication-checkpoint-control/v1";
+const EFFECT_SCHEMA: &str = "hiroute.publication-checkpoint-effect/v1";
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct PublicationCheckpointChangeV1 {
+ pub schema: String,
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+struct CheckpointControl {
+ schema: String,
+ change_spec_digest: CanonicalDigest,
+ before_digest: CanonicalDigest,
+ after_digest: CanonicalDigest,
+}
+
+#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+struct CheckpointEffect {
+ schema: String,
+ change_spec: ChangeSpecV1,
+ control: CheckpointControl,
+ before: PublicationRecordV1,
+ after: PublicationRecordV1,
+}
+
+pub fn checkpoint_publication(
+ before: &PublicationRecordV1,
+) -> Result<PublicationRecordV1, OperationValidationError> {
+ let mut publication = before.verify_current().map_err(|_| invalid())?;
+ publication.publication_revision = GatewayPublicationRevision::new(
+ publication
+ .publication_revision
+ .get()
+ .checked_add(1)
+ .ok_or_else(invalid)?,
+ )
+ .map_err(|_| invalid())?;
+ PublicationRecordV1::from_publication(before.workspace_id.clone(), &publication)
+ .map_err(|_| invalid())
+}
+
+impl TransactionPlanV1 {
+ pub fn from_publication_checkpoint(
+ spec: ChangeSpecV1,
+ before: PublicationRecordV1,
+ ) -> Result<Self, OperationValidationError> {
+ let after = checkpoint_publication(&before)?;
+ let control = CheckpointControl {
+ schema: CONTROL_SCHEMA.into(),
+ change_spec_digest: CanonicalDigest::of(&spec)?,
+ before_digest: before.digest.clone(),
+ after_digest: after.digest.clone(),
+ };
+ let effect = CheckpointEffect {
+ schema: EFFECT_SCHEMA.into(),
+ change_spec: spec.clone(),
+ control: control.clone(),
+ before,
+ after,
+ };
+ validate_effect(&effect)?;
+ Ok(Self {
+ spec,
+ control: crate::canonicalize_json(serde_json::to_value(control)?),
+ credential_pool: None,
+ worker_dependency_selection: None,
+ secrets: vec![],
+ agent_access_grants: vec![],
+ runtime: vec![],
+ external: vec![ExternalEffectIntentV1 {
+ effect_id: "routing-publication".into(),
+ kind: OwnedEffectKind::Publication,
+ target: "publication/current".into(),
+ before_fingerprint: Some(effect.before.digest.clone()),
+ desired: crate::canonicalize_json(serde_json::to_value(effect)?).into(),
+ content_publication: None,
+ desired_mode: 0o644,
+ sensitive: false,
+ }],
+ })
+ }
+}
+
+fn invalid() -> OperationValidationError {
+ OperationValidationError::UnregisteredEffectPlan
+}
+
+fn validate_effect(effect: &CheckpointEffect) -> Result<(), OperationValidationError> {
+ let change: PublicationCheckpointChangeV1 =
+ serde_json::from_value(effect.change_spec.desired_state.clone()).map_err(|_| invalid())?;
+ if effect.schema != EFFECT_SCHEMA
+ || effect.control.schema != CONTROL_SCHEMA
+ || change.schema != PUBLICATION_CHECKPOINT_CHANGE_SCHEMA_V1
+ || effect.change_spec.command_id != "routing.apply"
+ || effect.change_spec.resource_id.as_deref() != Some("publication/current")
+ || effect.control.change_spec_digest != CanonicalDigest::of(&effect.change_spec)?
+ || effect.control.before_digest != effect.before.digest
+ || effect.control.after_digest != effect.after.digest
+ || checkpoint_publication(&effect.before)? != effect.after
+ {
+ return Err(invalid());
+ }
+ Ok(())
+}
+
+pub(super) fn is_control(value: &Value) -> bool {
+ value.get("schema").and_then(Value::as_str) == Some(CONTROL_SCHEMA)
+}
+pub(super) fn is_effect(value: &Value) -> bool {
+ value.get("schema").and_then(Value::as_str) == Some(EFFECT_SCHEMA)
+}
+pub(super) fn validate_external(
+ id: &str,
+ kind: OwnedEffectKind,
+ target: &str,
+ desired: &Value,
+ mode: u32,
+ sensitive: bool,
+) -> Result<(), OperationValidationError> {
+ if id != "routing-publication"
+ || kind != OwnedEffectKind::Publication
+ || target != "publication/current"
+ || mode != 0o644
+ || sensitive
+ {
+ return Err(invalid());
+ }
+ let effect: CheckpointEffect =
+ serde_json::from_value(desired.clone()).map_err(|_| invalid())?;
+ validate_effect(&effect)
+}
+pub(super) fn record(
+ intent: &ExternalEffectIntentV1,
+) -> Result<PublicationRecordV1, OperationValidationError> {
+ validate_external(
+ &intent.effect_id,
+ intent.kind,
+ &intent.target,
+ &intent.desired,
+ intent.desired_mode,
+ intent.sensitive,
+ )?;
+ let effect: CheckpointEffect =
+ serde_json::from_value(intent.desired.as_ref().clone()).map_err(|_| invalid())?;
+ if intent.before_fingerprint.as_ref() != Some(&effect.before.digest) {
+ return Err(invalid());
+ }
+ Ok(effect.after)
+}
+pub(super) fn validate_plan(
+ spec: &ChangeSpecV1,
+ control: &Value,
+ secrets: &[SecretMutationV1],
+ runtime: &[RuntimeMutationV1],
+ external: &[ExternalEffectIntentV1],
+) -> Result<(), OperationValidationError> {
+ if !secrets.is_empty() || !runtime.is_empty() || external.len() != 1 {
+ return Err(invalid());
+ }
+ record(&external[0])?;
+ let effect: CheckpointEffect =
+ serde_json::from_value(external[0].desired.as_ref().clone()).map_err(|_| invalid())?;
+ let control: CheckpointControl =
+ serde_json::from_value(control.clone()).map_err(|_| invalid())?;
+ if effect.change_spec != *spec || effect.control != control {
+ return Err(invalid());
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ fn before() -> PublicationRecordV1 {
+ let publication = crate::GatewayPublicationV1::new(
+ crate::WorkspaceId::default(),
+ GatewayPublicationRevision::new(1).unwrap(),
+ crate::AliasRegistryV1::default(),
+ vec![],
+ )
+ .unwrap();
+ PublicationRecordV1::from_publication(publication.workspace_id.clone(), &publication)
+ .unwrap()
+ }
+ fn plan() -> TransactionPlanV1 {
+ TransactionPlanV1::from_publication_checkpoint(ChangeSpecV1 {
+ schema_version: crate::CHANGE_SPEC_SCHEMA_V1,
+ command_id: "routing.apply".into(), resource_id: Some("publication/current".into()),
+ desired_state: serde_json::json!({"schema":PUBLICATION_CHECKPOINT_CHANGE_SCHEMA_V1}),
+ }, before()).unwrap()
+ }
+ #[test]
+ fn publication_checkpoint_preserves_empty_authority_and_strictly_advances_once() {
+ let plan = plan();
+ let mut expected = before().verify_current().unwrap();
+ expected.publication_revision = GatewayPublicationRevision::new(2).unwrap();
+ assert_eq!(
+ record(&plan.external[0]).unwrap().verify_current().unwrap(),
+ expected
+ );
+ assert!(
+ plan.secrets.is_empty()
+ && plan.runtime.is_empty()
+ && plan.agent_access_grants.is_empty()
+ );
+ validate_plan(&plan.spec, &plan.control, &[], &[], &plan.external).unwrap();
+ let effect = &plan.external[0];
+ let recovered = ExternalEffectIntentV1::from_registered_adapter(
+ effect.effect_id.clone(),
+ effect.kind,
+ effect.target.clone(),
+ effect.before_fingerprint.clone(),
+ effect.desired.as_ref().clone(),
+ effect.desired_mode,
+ effect.sensitive,
+ )
+ .unwrap();
+ assert_eq!(record(&recovered).unwrap(), record(effect).unwrap());
+ }
+ #[test]
+ fn publication_checkpoint_preserves_nonempty_grants_disabled_heads_and_tombstones() {
+ let original: crate::GatewayPublicationV1 = serde_json::from_slice(include_bytes!(
+ "../../../../e2e/product/fixtures/routing/current-publication.v3.json"
+ ))
+ .unwrap();
+ let mut publication = original.into_current().unwrap();
+ assert!(!publication.plans.is_empty());
+ assert!(!publication.grants.is_empty());
+ publication.plan_heads = publication
+ .plans
+ .iter()
+ .map(|compiled| {
+ let version = crate::PlanVersionV1::from_unversioned_compiled_recovery(
+ publication.workspace_id.clone(),
+ compiled.clone(),
+ )
+ .unwrap();
+ crate::PlanHeadV1 {
+ head_revision: version.reference.content_revision,
+ reference: version.reference,
+ model_alias: compiled.model_alias().clone(),
+ status: crate::PlanLifecycleV1::Enabled,
+ }
+ })
+ .collect();
+ let mut disabled = publication.plan_heads[0].clone();
+ disabled.head_revision += 1;
+ disabled.status = crate::PlanLifecycleV1::Disabled;
+ publication = publication
+ .next_with_plan_lifecycle(
+ GatewayPublicationRevision::new(publication.publication_revision.get() + 1)
+ .unwrap(),
+ disabled,
+ )
+ .unwrap();
+ publication
+ .alias_registry
+ .tombstones
+ .insert(crate::ModelAlias::parse("retired-checkpoint-fixture").unwrap());
+ let record =
+ PublicationRecordV1::from_publication(publication.workspace_id.clone(), &publication)
+ .unwrap();
+ let after = checkpoint_publication(&record)
+ .unwrap()
+ .verify_current()
+ .unwrap();
+ publication.publication_revision = after.publication_revision;
+ assert_eq!(after, publication);
+ }
+ #[test]
+ fn publication_checkpoint_rejects_changed_authority_and_forged_ownership() {
+ for field in ["authority", "before", "revision", "spec", "control"] {
+ let mut plan = plan();
+ let mut effect: CheckpointEffect =
+ serde_json::from_value(plan.external[0].desired.as_ref().clone()).unwrap();
+ match field {
+ "authority" => {
+ let mut publication = effect.after.verify_current().unwrap();
+ publication
+ .alias_registry
+ .tombstones
+ .insert(crate::ModelAlias::parse("retired-forged").unwrap());
+ effect.after = PublicationRecordV1::from_publication(
+ publication.workspace_id.clone(),
+ &publication,
+ )
+ .unwrap();
+ effect.control.after_digest = effect.after.digest.clone();
+ }
+ "before" => {
+ plan.external[0].before_fingerprint = Some(CanonicalDigest::of_bytes(b"wrong"))
+ }
+ "revision" => {
+ let mut publication = effect.after.verify_current().unwrap();
+ publication.publication_revision = GatewayPublicationRevision::new(3).unwrap();
+ effect.after = PublicationRecordV1::from_publication(
+ publication.workspace_id.clone(),
+ &publication,
+ )
+ .unwrap();
+ effect.control.after_digest = effect.after.digest.clone();
+ }
+ "spec" => effect.change_spec.desired_state["unexpected"] = serde_json::json!(true),
+ _ => {
+ plan.control["before_digest"] =
+ serde_json::json!(CanonicalDigest::of_bytes(b"wrong"))
+ }
+ }
+ plan.external[0].desired = serde_json::to_value(effect).unwrap().into();
+ assert!(
+ validate_plan(&plan.spec, &plan.control, &[], &[], &plan.external).is_err(),
+ "{field}"
+ );
+ }
+ }
+}
diff --git a/crates/domain/src/operation/routing.rs b/crates/domain/src/operation/routing.rs
index 0b4a7c88..f3c2b157 100644
--- a/crates/domain/src/operation/routing.rs
+++ b/crates/domain/src/operation/routing.rs
@@ -177,6 +177,9 @@ pub fn routing_publication_record(
if intent.effect_id != EFFECT_ID {
return Ok(None);
}
+ if super::publication_checkpoint::is_effect(&intent.desired) {
+ return super::publication_checkpoint::record(intent).map(Some);
+ }
if super::routing_content::is_effect(&intent.desired) {
return super::routing_content::record(intent).map(Some);
}
@@ -209,6 +212,11 @@ pub(super) fn validate_plan(
runtime: &[RuntimeMutationV1],
external: &[ExternalEffectIntentV1],
) -> Result<(), OperationValidationError> {
+ if super::publication_checkpoint::is_control(control) {
+ return super::publication_checkpoint::validate_plan(
+ spec, control, secrets, runtime, external,
+ );
+ }
if super::routing_draft::is_control(control) {
return super::routing_draft::validate_plan(spec, control, secrets, runtime, external);
}
@@ -266,6 +274,16 @@ pub(super) fn validate_external_components(
desired_mode: u32,
sensitive: bool,
) -> Result<(), OperationValidationError> {
+ if super::publication_checkpoint::is_effect(desired) {
+ return super::publication_checkpoint::validate_external(
+ effect_id,
+ kind,
+ target,
+ desired,
+ desired_mode,
+ sensitive,
+ );
+ }
if super::routing_content::is_effect(desired) {
return super::routing_content::validate_external(
effect_id,
diff --git a/crates/gateway/src/core_runtime/response_diagnostics_tests.rs b/crates/gateway/src/core_runtime/response_diagnostics_tests.rs
index d255db96..5a01cf5f 100644
--- a/crates/gateway/src/core_runtime/response_diagnostics_tests.rs
+++ b/crates/gateway/src/core_runtime/response_diagnostics_tests.rs
@@ -29,6 +29,10 @@ use crate::server::test_control::{
write_dial_config,
};
+#[path = "response_diagnostics_tests/capture.rs"]
+mod capture;
+use capture::{assert_capture, create_capture_session, wait_for_captured_request_eof};
+
const CHILD_CASE: &str = "HIROUTE_STREAM_DIAGNOSTIC_CASE";
const CHILD_ROOT: &str = "HIROUTE_STREAM_DIAGNOSTIC_ROOT";
const TOKEN: &str = "SENTINEL_CLIENT_CREDENTIAL";
@@ -84,6 +88,11 @@ fn production_completed_prefix_capture_keeps_formal_attempt_correlation() {
run_child_case("capture_known").unwrap();
}
+#[test]
+fn production_completed_prefix_capture_accepts_usage_before_provider_completion() {
+ run_child_case("capture_known_usage_first").unwrap();
+}
+
#[test]
fn production_prebody_failed_capture_keeps_promoted_attempt_correlation() {
let failures: Vec<_> = ["prebody_capture_invalid_json", "prebody_capture_relay"]
@@ -128,6 +137,7 @@ fn run_child_case(case: &str) -> Result<(), String> {
if matches!(
case,
"capture_known"
+ | "capture_known_usage_first"
| "capture_unknown"
| "prebody_capture_invalid_json"
| "prebody_capture_relay"
@@ -304,7 +314,7 @@ fn sample(case: &str) -> (Vec<u8>, Option<&'static str>, Option<&'static str>, u
None,
1,
),
- "capture_known" => {
+ "capture_known" | "capture_known_usage_first" => {
let mut value = chat(tool(Some(TOOL), "{}"), json!("tool_calls"));
value["usage"] = json!({"prompt_tokens":11,"completion_tokens":7,"total_tokens":18});
(frame(value), None, None, 2)
@@ -321,6 +331,7 @@ fn sample(case: &str) -> (Vec<u8>, Option<&'static str>, Option<&'static str>, u
"invalid_arguments"
| "unknown_metadata"
| "capture_known"
+ | "capture_known_usage_first"
| "capture_unknown"
| "capture_disabled"
) {
@@ -330,6 +341,7 @@ fn sample(case: &str) -> (Vec<u8>, Option<&'static str>, Option<&'static str>, u
}
fn run_case(case: &str, root: &Path) {
+ let facts = Facts::default();
let capture_enabled = std::env::var_os("HIROUTE_PRIVATE_STREAM_CAPTURE").is_some();
if capture_enabled {
create_capture_session(&root.join("capture"));
@@ -359,12 +371,20 @@ fn run_case(case: &str, root: &Path) {
write_dial_config(root, &[&listener]).unwrap();
let peer = listener.try_clone().unwrap();
let sent = wire.clone();
+ let capture_root = capture_enabled.then(|| root.join("capture"));
+ let usage_first = case == "capture_known_usage_first";
+ let upstream_facts = facts.clone();
let upstream = std::thread::spawn(move || {
let (mut stream, _) = peer.accept().unwrap();
stream
.set_read_timeout(Some(Duration::from_secs(10)))
.unwrap();
let request = read_request(&mut stream);
+ if let Some(root) = &capture_root {
+ // Receiving Content-Length bytes does not prove the request reader
+ // has verified EOF. This fixture promises a replayable capture.
+ wait_for_captured_request_eof(root);
+ }
write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", sent.len()).unwrap();
if after_body {
stream.write_all(&sent[..prefix_len]).unwrap();
@@ -373,6 +393,16 @@ fn run_case(case: &str, root: &Path) {
// the first real body unit. This proves the afterbody boundary.
wait_for_body.recv_timeout(Duration::from_secs(3)).unwrap();
let _ = stream.write_all(&sent[prefix_len..]);
+ } else if usage_first {
+ let terminal = b"data: [DONE]\n\n";
+ assert!(sent.ends_with(terminal));
+ let split = sent.len() - terminal.len();
+ stream.write_all(&sent[..split]).unwrap();
+ stream.flush().unwrap();
+ // Deliver the accepted canonical usage before the provider can
+ // complete. This deterministically exercises production deduplication.
+ wait_canonical_usage(&upstream_facts);
+ stream.write_all(&sent[split..]).unwrap();
} else {
let _ = stream.write_all(&sent);
}
@@ -421,7 +451,6 @@ fn run_case(case: &str, root: &Path) {
parent_session_id: None,
level_override: Some(DiagnosticLevel::Debug),
});
- let facts = Facts::default();
let mut sinks = GatewayObservationSinks::discard();
sinks.execution_fact = Arc::new(facts.clone());
let observation =
@@ -480,7 +509,7 @@ fn run_case(case: &str, root: &Path) {
"{}",
String::from_utf8_lossy(&response)
);
- if case == "capture_known" {
+ if matches!(case, "capture_known" | "capture_known_usage_first") {
let response = String::from_utf8_lossy(&response);
assert!(response.contains("\"type\":\"tool_use\""));
assert!(response.contains(&format!("\"name\":\"{TOOL}\"")));
@@ -514,6 +543,14 @@ fn run_case(case: &str, root: &Path) {
// Keep the collector live through Gateway shutdown; request_finished is
// a terminal business fact, not a barrier for every observation producer.
let facts = facts.0.lock().unwrap().clone();
+ if usage_first {
+ assert!(
+ facts.iter().all(|r| {
+ r.pointer("/fact/source").and_then(Value::as_str) != Some("provider_completion")
+ }),
+ "canonical usage must suppress the later duplicate provider completion"
+ );
+ }
if no_credential {
assert!(
!facts.iter().any(
@@ -740,6 +777,25 @@ fn wait_finished(facts: &Facts, failed: bool) {
std::thread::sleep(Duration::from_millis(5));
}
}
+
+fn wait_canonical_usage(facts: &Facts) {
+ let deadline = Instant::now() + Duration::from_secs(5);
+ loop {
+ let records = facts.0.lock().unwrap().clone();
+ if records.iter().any(|r| {
+ r.pointer("/fact/kind").and_then(Value::as_str) == Some("usage_and_cache")
+ && r.pointer("/fact/source").and_then(Value::as_str)
+ == Some("accepted_canonical_model_event")
+ }) {
+ return;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "canonical usage was not delivered"
+ );
+ std::thread::sleep(Duration::from_millis(5));
+ }
+}
fn assert_prebody_relay_business(facts: &[Value]) {
let named = |name| {
facts
@@ -911,133 +967,3 @@ fn wait_replay_clean(root: &Path) {
std::thread::sleep(Duration::from_millis(5));
}
}
-fn create_capture_session(root: &Path) {
- fs::DirBuilder::new().mode(0o700).create(root).unwrap();
- let now = SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .unwrap()
- .as_secs();
- let mut file = fs::OpenOptions::new()
- .create_new(true)
- .write(true)
- .mode(0o600)
- .open(root.join("session.json"))
- .unwrap();
- file.write_all(serde_json::to_string(&json!({"source_sha":"a".repeat(40),"binary_sha256":"b".repeat(64),
- "client":"deterministic-production-listener-fixture","expires_at":now+60,"delete_after":now+120})).unwrap().as_bytes()).unwrap();
-}
-
-fn assert_capture(
- root: &Path,
- upstream: &[u8],
- entity: &[u8],
- reason: Option<&str>,
- diagnostics: &[Value],
- facts: &[Value],
-) {
- let lock = fs::OpenOptions::new()
- .read(true)
- .write(true)
- .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
- .open(root.join("active.lock"))
- .unwrap();
- // The stable inode survives both clean exit and crashes; kernel ownership
- // must be released before cleanup can use this same lock.
- rustix::fs::flock(&lock, rustix::fs::FlockOperation::NonBlockingLockExclusive)
- .expect("writer ownership was not released");
- let files: Vec<_> = fs::read_dir(root)
- .unwrap()
- .map(|e| e.unwrap().path())
- .filter(|p| p.extension().is_some_and(|e| e == "capture"))
- .collect();
- assert_eq!(files.len(), 1);
- let path = &files[0];
- assert_eq!(
- fs::metadata(path).unwrap().permissions().mode() & 0o777,
- 0o600
- );
- let bytes = fs::read(path).unwrap();
- assert!(
- !bytes
- .windows(b"SENTINEL_UPSTREAM_CREDENTIAL".len())
- .any(|w| w == b"SENTINEL_UPSTREAM_CREDENTIAL")
- );
- let mut remaining = bytes.as_slice();
- let mut records = Vec::new();
- while !remaining.is_empty() {
- assert!(remaining.len() >= 9);
- let size = u64::from_le_bytes(remaining[1..9].try_into().unwrap()) as usize;
- assert!(size <= remaining.len() - 9);
- records.push((remaining[0], &remaining[9..9 + size]));
- remaining = &remaining[9 + size..];
- }
- assert_eq!(records.last().unwrap().0, 8);
- assert!(records.iter().any(|r| r.0 == 2));
- let captured = |kind| {
- records
- .iter()
- .filter(|r| r.0 == kind)
- .flat_map(|r| r.1.iter().copied())
- .collect::<Vec<_>>()
- };
- let body_offset = upstream.windows(4).position(|w| w == b"\r\n\r\n").unwrap() + 4;
- assert_eq!(
- captured(1),
- upstream[body_offset..],
- "capture must use actual prepared request reader"
- );
- assert_eq!(
- captured(4),
- entity,
- "ordered read blocks must reproduce the exact entity"
- );
- let context: Value = serde_json::from_slice(records[0].1).unwrap();
- assert_eq!(
- context["request_bytes"],
- (upstream.len() - body_offset) as u64
- );
- assert_eq!(context["profile"]["ingress_protocol"], "messages");
- assert_eq!(
- context["profile"]["capability"]["upstream_protocol"],
- "chat_completions"
- );
- assert!(!context["chat_tools"].is_null());
- assert_eq!(records.iter().filter(|r| r.0 == 7).count(), 1);
- let correlation: Value =
- serde_json::from_slice(records.iter().find(|r| r.0 == 7).unwrap().1).unwrap();
- let attempt = diagnostics
- .iter()
- .find_map(|r| payload(r, "attempt_begin"))
- .unwrap();
- assert_eq!(correlation["request_token"], attempt["request_token"]);
- assert_eq!(correlation["attempt_token"], attempt["attempt_token"]);
- assert_eq!(correlation["attempt_index"], attempt["attempt_index"]);
- assert_eq!(
- correlation["request_id"],
- facts
- .iter()
- .find_map(|r| r.pointer("/correlation/request_id"))
- .unwrap()
- .clone()
- );
- let rt = tokio::runtime::Runtime::new().unwrap();
- for chunks in [0, 1, 4096] {
- let replay = rt
- .block_on(crate::runtime::stream_capture::replay_capture(path, chunks))
- .unwrap();
- assert_eq!(
- replay["decoder"]["result"],
- if reason.is_some() {
- "rejected"
- } else {
- "accepted"
- }
- );
- if let Some(reason) = reason {
- assert_eq!(replay["decoder"]["reason"], reason);
- } else {
- assert_eq!(replay["decoder"]["tool_calls"], 1);
- }
- assert!(!replay.to_string().contains("SENTINEL"));
- }
-}
diff --git a/crates/gateway/src/core_runtime/response_diagnostics_tests/capture.rs b/crates/gateway/src/core_runtime/response_diagnostics_tests/capture.rs
new file mode 100644
index 00000000..2caa0cdb
--- /dev/null
+++ b/crates/gateway/src/core_runtime/response_diagnostics_tests/capture.rs
@@ -0,0 +1,166 @@
+//! Capture readiness and complete offline replay assertions for listener fixtures.
+use super::*;
+
+pub(super) fn wait_for_captured_request_eof(root: &Path) {
+ let deadline = Instant::now() + Duration::from_secs(3);
+ loop {
+ let mut kinds = Vec::new();
+ for entry in fs::read_dir(root).unwrap() {
+ let path = entry.unwrap().path();
+ if path.extension().is_none_or(|ext| ext != "capture") {
+ continue;
+ }
+ let bytes = fs::read(path).unwrap();
+ let mut remaining = bytes.as_slice();
+ // A concurrent writer may leave an incomplete trailing record.
+ while remaining.len() >= 9 {
+ let size = u64::from_le_bytes(remaining[1..9].try_into().unwrap());
+ if size > (remaining.len() - 9) as u64 {
+ break;
+ }
+ kinds.push(remaining[0]);
+ if remaining[0] == 2 {
+ assert_eq!(size, 0);
+ return;
+ }
+ remaining = &remaining[9 + size as usize..];
+ }
+ }
+ assert!(
+ Instant::now() < deadline,
+ "request EOF was not captured: {kinds:?}"
+ );
+ std::thread::sleep(Duration::from_millis(1));
+ }
+}
+
+pub(super) fn create_capture_session(root: &Path) {
+ fs::DirBuilder::new().mode(0o700).create(root).unwrap();
+ let now = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_secs();
+ let mut file = fs::OpenOptions::new()
+ .create_new(true)
+ .write(true)
+ .mode(0o600)
+ .open(root.join("session.json"))
+ .unwrap();
+ file.write_all(serde_json::to_string(&json!({"source_sha":"a".repeat(40),"binary_sha256":"b".repeat(64),
+ "client":"deterministic-production-listener-fixture","expires_at":now+60,"delete_after":now+120})).unwrap().as_bytes()).unwrap();
+}
+
+pub(super) fn assert_capture(
+ root: &Path,
+ upstream: &[u8],
+ entity: &[u8],
+ reason: Option<&str>,
+ diagnostics: &[Value],
+ facts: &[Value],
+) {
+ let lock = fs::OpenOptions::new()
+ .read(true)
+ .write(true)
+ .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
+ .open(root.join("active.lock"))
+ .unwrap();
+ // The stable inode survives both clean exit and crashes; kernel ownership
+ // must be released before cleanup can use this same lock.
+ rustix::fs::flock(&lock, rustix::fs::FlockOperation::NonBlockingLockExclusive)
+ .expect("writer ownership was not released");
+ let files: Vec<_> = fs::read_dir(root)
+ .unwrap()
+ .map(|e| e.unwrap().path())
+ .filter(|p| p.extension().is_some_and(|e| e == "capture"))
+ .collect();
+ assert_eq!(files.len(), 1);
+ let path = &files[0];
+ assert_eq!(
+ fs::metadata(path).unwrap().permissions().mode() & 0o777,
+ 0o600
+ );
+ let bytes = fs::read(path).unwrap();
+ assert!(
+ !bytes
+ .windows(b"SENTINEL_UPSTREAM_CREDENTIAL".len())
+ .any(|w| w == b"SENTINEL_UPSTREAM_CREDENTIAL")
+ );
+ let mut remaining = bytes.as_slice();
+ let mut records = Vec::new();
+ while !remaining.is_empty() {
+ assert!(remaining.len() >= 9);
+ let size = u64::from_le_bytes(remaining[1..9].try_into().unwrap()) as usize;
+ assert!(size <= remaining.len() - 9);
+ records.push((remaining[0], &remaining[9..9 + size]));
+ remaining = &remaining[9 + size..];
+ }
+ assert_eq!(records.last().unwrap().0, 8);
+ assert!(records.iter().any(|r| r.0 == 2));
+ let captured = |kind| {
+ records
+ .iter()
+ .filter(|r| r.0 == kind)
+ .flat_map(|r| r.1.iter().copied())
+ .collect::<Vec<_>>()
+ };
+ let body_offset = upstream.windows(4).position(|w| w == b"\r\n\r\n").unwrap() + 4;
+ assert_eq!(
+ captured(1),
+ upstream[body_offset..],
+ "capture must use actual prepared request reader"
+ );
+ assert_eq!(
+ captured(4),
+ entity,
+ "ordered read blocks must reproduce the exact entity"
+ );
+ let context: Value = serde_json::from_slice(records[0].1).unwrap();
+ assert_eq!(
+ context["request_bytes"],
+ (upstream.len() - body_offset) as u64
+ );
+ assert_eq!(context["profile"]["ingress_protocol"], "messages");
+ assert_eq!(
+ context["profile"]["capability"]["upstream_protocol"],
+ "chat_completions"
+ );
+ assert!(!context["chat_tools"].is_null());
+ assert_eq!(records.iter().filter(|r| r.0 == 7).count(), 1);
+ let correlation: Value =
+ serde_json::from_slice(records.iter().find(|r| r.0 == 7).unwrap().1).unwrap();
+ let attempt = diagnostics
+ .iter()
+ .find_map(|r| payload(r, "attempt_begin"))
+ .unwrap();
+ assert_eq!(correlation["request_token"], attempt["request_token"]);
+ assert_eq!(correlation["attempt_token"], attempt["attempt_token"]);
+ assert_eq!(correlation["attempt_index"], attempt["attempt_index"]);
+ assert_eq!(
+ correlation["request_id"],
+ facts
+ .iter()
+ .find_map(|r| r.pointer("/correlation/request_id"))
+ .unwrap()
+ .clone()
+ );
+ let rt = tokio::runtime::Runtime::new().unwrap();
+ for chunks in [0, 1, 4096] {
+ let replay = rt
+ .block_on(crate::runtime::stream_capture::replay_capture(path, chunks))
+ .unwrap();
+ assert_eq!(
+ replay["decoder"]["result"],
+ if reason.is_some() {
+ "rejected"
+ } else {
+ "accepted"
+ }
+ );
+ if let Some(reason) = reason {
+ assert_eq!(replay["decoder"]["reason"], reason);
+ } else {
+ assert_eq!(replay["decoder"]["tool_calls"], 1);
+ }
+ assert!(!replay.to_string().contains("SENTINEL"));
+ }
+}
diff --git a/crates/gateway/src/runtime/stream_capture/tests.rs b/crates/gateway/src/runtime/stream_capture/tests.rs
index 2d35f335..0096aef3 100644
--- a/crates/gateway/src/runtime/stream_capture/tests.rs
+++ b/crates/gateway/src/runtime/stream_capture/tests.rs
@@ -386,21 +386,25 @@ fn capture_redacts_transport_headers_and_enforces_expiry() {
#[tokio::test]
async fn capture_limits_and_partial_request_cannot_produce_replay_evidence() {
- let root = setup();
- assert!(Capture::open(&root, &profile(), None, MAX_FILE as usize, true).is_err());
- assert!(root.join("active.lock").exists());
- let capture = open_after_capture_release(&root, || {});
- capture.record(1, b"{");
- capture.record(3, &200u16.to_le_bytes());
- capture.failed();
- drop(capture);
- assert_eq!(
- replay_capture(&root.join("attempt-1.capture"), 0)
- .await
- .unwrap_err(),
- "request body capture incomplete"
- );
- fs::remove_dir_all(root).unwrap();
+ // Even all expected bytes are insufficient without the reader's verified
+ // EOF: an early upstream error is allowed to seal an incomplete capture.
+ for request in [b"{".as_slice(), b"{}".as_slice()] {
+ let root = setup();
+ assert!(Capture::open(&root, &profile(), None, MAX_FILE as usize, true).is_err());
+ assert!(root.join("active.lock").exists());
+ let capture = open_after_capture_release(&root, || {});
+ capture.record(1, request);
+ capture.record(3, &200u16.to_le_bytes());
+ capture.failed();
+ drop(capture);
+ assert_eq!(
+ replay_capture(&root.join("attempt-1.capture"), 0)
+ .await
+ .unwrap_err(),
+ "request body capture incomplete"
+ );
+ fs::remove_dir_all(root).unwrap();
+ }
let root = setup();
for _ in 0..MAX_ATTEMPTS {
diff --git a/crates/local-storage/src/control/compute/management.rs b/crates/local-storage/src/control/compute/management.rs
index 7da8cd3f..ef206d95 100644
--- a/crates/local-storage/src/control/compute/management.rs
+++ b/crates/local-storage/src/control/compute/management.rs
@@ -12,6 +12,11 @@ use rusqlite::{OptionalExtension, Transaction, TransactionBehavior, params};
use serde::Deserialize;
use serde_json::Value;
+mod compensation;
+mod references;
+
+pub(in crate::control) use compensation::reconcile as reconcile_compensation;
+
use super::{ControlStore, decode, encode, invalid, port, validate_storage_id};
#[derive(Deserialize)]
@@ -33,14 +38,16 @@ pub(in crate::control) fn stage_control(
mutation
.validate_against(current.as_ref())
.map_err(|_| conflict("compute.management.stage.cas"))?;
+ references::validate_removal(transaction, workspace, &mutation)?;
+ let identity = mutation
+ .desired()
+ .or(mutation.expected())
+ .ok_or_else(|| invalid("compute.management.identity"))?;
let lineage_owner: Option<String> = transaction
.query_row(
"SELECT source_id FROM compute_management_sources
WHERE workspace_id=?1 AND lineage_digest=?2",
- params![
- workspace.as_str(),
- mutation.desired().lineage_digest.as_str()
- ],
+ params![workspace.as_str(), identity.lineage_digest.as_str()],
|row| row.get(0),
)
.optional()
@@ -72,11 +79,7 @@ pub(in crate::control) fn stage_control(
mutation.source_id(),
mutation.expected_revision(),
before_owner,
- mutation
- .desired()
- .digest()
- .map_err(|_| invalid("compute.management.stage.digest"))?
- .as_str(),
+ mutation.desired_digest().as_str(),
],
)
.map_err(|_| port("compute.management.stage.effect"))?;
@@ -101,10 +104,7 @@ pub(in crate::control) fn activate(
)
.optional()
.map_err(|_| port("compute.management.activate.effect"))?;
- let desired_digest = mutation
- .desired()
- .digest()
- .map_err(|_| corrupt("compute.management.activate.digest"))?;
+ let desired_digest = mutation.desired_digest();
if staged
.as_ref()
.is_none_or(|(staged_workspace, source_id, expected_revision, digest)| {
@@ -120,7 +120,17 @@ pub(in crate::control) fn activate(
mutation
.validate_against(current.as_ref())
.map_err(|_| conflict("compute.management.activate.cas"))?;
- write_source(transaction, workspace, mutation.desired(), operation_id)
+ references::validate_removal(transaction, workspace, &mutation)?;
+ if let Some(desired) = mutation.desired() {
+ write_source(transaction, workspace, desired, operation_id)
+ } else {
+ let deleted = transaction.execute("DELETE FROM compute_management_sources WHERE workspace_id=?1 AND source_id=?2 AND revision=?3", params![workspace.as_str(), mutation.source_id(), mutation.expected_revision()])
+ .map_err(|_| port("compute.management.delete"))?;
+ if deleted != 1 {
+ return Err(conflict("compute.management.delete.cas"));
+ }
+ Ok(())
+ }
}
pub(in crate::control) fn current_matches(
@@ -159,8 +169,16 @@ pub(in crate::control) fn current_matches(
)
.optional()
.map_err(|_| port("compute.management.observe"))?;
- let desired = encode(mutation.desired())?;
- Ok(current.is_some_and(|(json, owner)| json == desired && owner == operation_id.as_str()))
+ match mutation.desired() {
+ Some(desired) => {
+ let desired = encode(desired)?;
+ Ok(current
+ .is_some_and(|(json, owner)| json == desired && owner == operation_id.as_str()))
+ }
+ None => {
+ Ok(current.is_none() && deletion_owned(connection, workspace, operation_id.as_str())?)
+ }
+ }
}
pub(in crate::control) fn compensate(
@@ -192,8 +210,14 @@ pub(in crate::control) fn compensate(
)
.optional()
.map_err(|_| port("compute.management.compensate.current"))?;
- let desired = encode(mutation.desired())?;
- if !current.is_some_and(|(json, owner)| json == desired && owner == operation_id) {
+ let owns = match mutation.desired() {
+ Some(desired) => {
+ let desired = encode(desired)?;
+ current.is_some_and(|(json, owner)| json == desired && owner == operation_id)
+ }
+ None => current.is_none() && deletion_owned(transaction, workspace, operation_id)?,
+ };
+ if !owns {
return Ok(false);
}
if let Some(expected) = mutation.expected() {
@@ -223,6 +247,13 @@ pub(in crate::control) fn compensate(
}
impl ComputeManagementRepositoryPort for ControlStore {
+ fn compute_management_references(
+ &self,
+ workspace: &WorkspaceId,
+ binding_ids: &[String],
+ ) -> PortResult<Vec<String>> {
+ references::read(&self.connection.borrow(), workspace, binding_ids)
+ }
fn compute_management_source(
&self,
source_id: &str,
@@ -298,6 +329,17 @@ impl ComputeManagementRepositoryPort for ControlStore {
}
}
+/// Absence alone is never a deletion ownership witness. Reuse the same durable workspace
+/// revision/digest/owner triple as the outer Control effect, including in helper-level recovery.
+fn deletion_owned(
+ connection: &rusqlite::Connection,
+ workspace: &WorkspaceId,
+ operation_id: &str,
+) -> PortResult<bool> {
+ connection.query_row("SELECT EXISTS(SELECT 1 FROM workspace_state w JOIN control_effects e ON e.workspace_id=w.workspace_id WHERE w.workspace_id=?1 AND e.operation_id=?2 AND w.owner_operation_id=e.operation_id AND w.target_revision=e.after_revision AND w.desired_digest=e.after_digest AND e.activated=1 AND e.compensated=0)", params![workspace.as_str(), operation_id], |row| row.get(0))
+ .map_err(|_| port("compute.management.delete.owner"))
+}
+
fn mutation_from_staged(staged_json: &str) -> PortResult<Option<ComputeManagementMutationV2>> {
let mut envelope: Value = serde_json::from_str(staged_json)
.map_err(|_| corrupt("compute.management.stage.decode"))?;
diff --git a/crates/local-storage/src/control/compute/management/compensation.rs b/crates/local-storage/src/control/compute/management/compensation.rs
new file mode 100644
index 00000000..fa1e3d38
--- /dev/null
+++ b/crates/local-storage/src/control/compute/management/compensation.rs
@@ -0,0 +1,137 @@
+//! Single-writer, idempotent convergence of forward Secret compensation references.
+use super::*;
+use hiroute_domain::{CredentialRefV1, OperationState, OperationV1};
+
+pub(in crate::control) fn reconcile(
+ store: &ControlStore,
+ operation: &OperationV1,
+ references: &[CredentialRefV1],
+) -> PortResult<()> {
+ if references.is_empty() {
+ return Ok(());
+ }
+ if !matches!(
+ operation.state,
+ OperationState::RollingBack | OperationState::NeedsAttention
+ ) {
+ return Err(conflict("compute.compensation.state"));
+ }
+ let mutation = mutation_from_control(operation.plan.control())?
+ .ok_or_else(|| invalid("compute.compensation.mutation"))?;
+ let expected = mutation
+ .expected()
+ .ok_or_else(|| invalid("compute.compensation.expected"))?;
+ let mut repaired = expected.clone();
+ let mut seen = std::collections::BTreeSet::new();
+ for reference in references {
+ if !seen.insert(reference.credential_id()) {
+ return Err(invalid("compute.compensation.duplicate"));
+ }
+ let key = repaired
+ .credentials
+ .iter_mut()
+ .find(|key| key.key_id == reference.credential_id())
+ .ok_or_else(|| invalid("compute.compensation.key"))?;
+ let original = &key.credential;
+ let forward = original
+ .generation()
+ .checked_add(2)
+ .ok_or_else(|| conflict("compute.compensation.generation"))?;
+ let exact = CredentialRefV1::new(
+ original.credential_id(),
+ original.owner_scope(),
+ original.subject(),
+ original.purpose(),
+ original.allowed_destinations().iter().cloned(),
+ forward,
+ )
+ .map_err(|_| invalid("compute.compensation.reference"))?;
+ if reference != &exact
+ || !operation
+ .plan
+ .secrets()
+ .iter()
+ .any(|secret| secret.credential() == original)
+ {
+ return Err(conflict("compute.compensation.authority"));
+ }
+ key.credential = reference.clone();
+ }
+ // Skip the possibly activated desired revision as well as the original one.
+ repaired.revision = expected
+ .revision
+ .checked_add(2)
+ .ok_or_else(|| conflict("compute.compensation.revision"))?;
+ repaired
+ .validate()
+ .map_err(|_| invalid("compute.compensation.source"))?;
+ let desired = serde_json::json!({"compute_management_compensation": &repaired});
+ let digest =
+ CanonicalDigest::of(&desired).map_err(|_| invalid("compute.compensation.digest"))?;
+ let mut connection = store.connection.borrow_mut();
+ let transaction = connection
+ .transaction_with_behavior(TransactionBehavior::Immediate)
+ .map_err(|_| port("compute.compensation.begin"))?;
+ let owns: bool = transaction.query_row(
+ "SELECT EXISTS(SELECT 1 FROM writer_claim w JOIN operations o ON o.operation_id=w.operation_id
+ WHERE w.singleton=1 AND w.operation_id=?1 AND o.generation=?2 AND o.accepted_change_digest=?3
+ AND o.state IN ('rolling_back','needs_attention'))",
+ params![operation.operation_id.as_str(), operation.generation, operation.accepted_digest.as_str()], |row| row.get(0))
+ .map_err(|_| port("compute.compensation.writer"))?;
+ if !owns {
+ return Err(conflict("compute.compensation.writer"));
+ }
+ let owner: Option<String> = transaction.query_row(
+ "SELECT m.before_owner_operation_id FROM compute_management_effects m JOIN control_effects e USING(operation_id)
+ WHERE m.operation_id=?1 AND m.workspace_id=?2 AND m.source_id=?3 AND e.compensated=1",
+ params![operation.operation_id.as_str(), operation.workspace_id.as_str(), expected.source_id], |row| row.get(0))
+ .optional().map_err(|_| port("compute.compensation.effect"))?.flatten();
+ let before_owner = owner.ok_or_else(|| conflict("compute.compensation.effect"))?;
+ let current = read_source(&transaction, &operation.workspace_id, &expected.source_id)?
+ .ok_or_else(|| conflict("compute.compensation.missing"))?;
+ let current_owner: String = transaction.query_row(
+ "SELECT owner_operation_id FROM compute_management_sources WHERE workspace_id=?1 AND source_id=?2",
+ params![operation.workspace_id.as_str(), expected.source_id], |row| row.get(0))
+ .map_err(|_| port("compute.compensation.current_owner"))?;
+ // Source and workspace were advanced together. This exact operation-owned row
+ // is the durable receipt if the process stopped before the terminal journal write.
+ if current == repaired && current_owner == operation.operation_id.as_str() {
+ let receipt: bool = transaction.query_row("SELECT EXISTS(SELECT 1 FROM workspace_state w JOIN workspace_revision_heads h USING(workspace_id) WHERE w.workspace_id=?1 AND w.owner_operation_id=?2 AND w.desired_digest=?3 AND w.target_revision=h.revision)",
+ params![operation.workspace_id.as_str(), operation.operation_id.as_str(), digest.as_str()], |row| row.get(0))
+ .map_err(|_| port("compute.compensation.receipt"))?;
+ return if receipt {
+ Ok(())
+ } else {
+ Err(conflict("compute.compensation.receipt"))
+ };
+ }
+ if &current != expected || current_owner != before_owner {
+ return Err(conflict("compute.compensation.cas"));
+ }
+ let revision = super::super::super::read_control_head(&transaction, &operation.workspace_id)?
+ .checked_add(1)
+ .ok_or_else(|| conflict("compute.compensation.workspace_revision"))?;
+ let encoded =
+ encode(&serde_json::json!({"schema":"hiroute.control-desired/v1","value":desired}))?;
+ write_source(
+ &transaction,
+ &operation.workspace_id,
+ &repaired,
+ operation.operation_id.as_str(),
+ )?;
+ let changed = transaction.execute("UPDATE workspace_state SET desired_json=?2,target_revision=?3,desired_digest=?4,owner_operation_id=?5,updated_at=unixepoch() WHERE workspace_id=?1",
+ params![operation.workspace_id.as_str(), encoded, revision, digest.as_str(), operation.operation_id.as_str()])
+ .map_err(|_| port("compute.compensation.workspace"))?;
+ if changed != 1 {
+ return Err(conflict("compute.compensation.workspace"));
+ }
+ transaction
+ .execute(
+ "UPDATE workspace_revision_heads SET revision=?2 WHERE workspace_id=?1",
+ params![operation.workspace_id.as_str(), revision],
+ )
+ .map_err(|_| port("compute.compensation.head"))?;
+ transaction
+ .commit()
+ .map_err(|_| port("compute.compensation.commit"))
+}
diff --git a/crates/local-storage/src/control/compute/management/references.rs b/crates/local-storage/src/control/compute/management/references.rs
new file mode 100644
index 00000000..153874df
--- /dev/null
+++ b/crates/local-storage/src/control/compute/management/references.rs
@@ -0,0 +1,158 @@
+//! Shared binding-reference read used by Preview and by the transactional writer.
+use std::collections::BTreeSet;
+
+use super::*;
+use hiroute_domain::{ComputeManagementMutationV2, PlanDraftV1, PlanVersionV1};
+
+pub(super) fn validate_removal(
+ connection: &rusqlite::Connection,
+ workspace: &WorkspaceId,
+ mutation: &ComputeManagementMutationV2,
+) -> PortResult<()> {
+ let removed: Vec<String> = mutation
+ .expected()
+ .into_iter()
+ .flat_map(|source| &source.models)
+ .filter(|model| {
+ !mutation.desired().is_some_and(|source| {
+ source
+ .models
+ .iter()
+ .any(|kept| kept.binding_id == model.binding_id)
+ })
+ })
+ .map(|model| model.binding_id.clone())
+ .collect();
+ if !read(connection, workspace, &removed)?.is_empty() {
+ return Err(conflict("compute.management.models_in_use"));
+ }
+ Ok(())
+}
+
+pub(super) fn read(
+ connection: &rusqlite::Connection,
+ workspace: &WorkspaceId,
+ bindings: &[String],
+) -> PortResult<Vec<String>> {
+ if bindings.is_empty() {
+ return Ok(Vec::new());
+ }
+ let bindings: BTreeSet<&str> = bindings.iter().map(String::as_str).collect();
+ let has_versions: bool = connection
+ .query_row(
+ "SELECT EXISTS(SELECT 1 FROM plan_versions WHERE workspace_id=?1)",
+ [workspace.as_str()],
+ |row| row.get(0),
+ )
+ .map_err(|_| port("compute.management.references.versions"))?;
+ let recovery: Option<bool> = connection
+ .query_row(
+ "SELECT ready FROM plan_version_recovery WHERE workspace_id=?1",
+ [workspace.as_str()],
+ |row| row.get(0),
+ )
+ .optional()
+ .map_err(|_| port("compute.management.references.recovery"))?;
+ if recovery == Some(false) || (has_versions && recovery != Some(true)) {
+ return Err(conflict("compute.management.references.recovery_required"));
+ }
+ let mut references = BTreeSet::new();
+ // Current heads include disabled plans. Old versions only block while held or preparing;
+ // immutable historical records alone must not make a connection impossible to clean up.
+ let mut statement = connection.prepare("SELECT v.version_json FROM plan_versions v WHERE v.workspace_id=?1 AND (v.state='prepared' OR EXISTS(SELECT 1 FROM plan_heads h WHERE h.workspace_id=v.workspace_id AND h.plan_id=v.plan_id AND json_extract(h.head_json,'$.status') != 'deleted' AND json_extract(h.head_json,'$.reference.content_revision')=v.content_revision) OR EXISTS(SELECT 1 FROM plan_version_holds h WHERE h.workspace_id=v.workspace_id AND h.plan_id=v.plan_id AND h.content_revision=v.content_revision))")
+ .map_err(|_| port("compute.management.references.prepare"))?;
+ let rows = statement
+ .query_map([workspace.as_str()], |row| row.get::<_, String>(0))
+ .map_err(|_| port("compute.management.references.query"))?;
+ for row in rows {
+ let json = row.map_err(|_| port("compute.management.references.row"))?;
+ let version: PlanVersionV1 = decode(&json)?;
+ version
+ .validate()
+ .map_err(|_| corrupt("compute.management.references.version"))?;
+ let value: Value = serde_json::from_str(&json)
+ .map_err(|_| corrupt("compute.management.references.json"))?;
+ if references_binding(&value, &bindings) {
+ references.insert(version.reference.plan_id.as_str().to_owned());
+ }
+ }
+ let mut statement = connection
+ .prepare("SELECT draft_json FROM plan_drafts WHERE workspace_id=?1")
+ .map_err(|_| port("compute.management.references.drafts"))?;
+ for row in statement
+ .query_map([workspace.as_str()], |row| row.get::<_, String>(0))
+ .map_err(|_| port("compute.management.references.drafts"))?
+ {
+ let json = row.map_err(|_| port("compute.management.references.draft"))?;
+ let draft: PlanDraftV1 = decode(&json)?;
+ draft
+ .validate()
+ .map_err(|_| corrupt("compute.management.references.draft"))?;
+ let value: Value = serde_json::from_str(&json)
+ .map_err(|_| corrupt("compute.management.references.json"))?;
+ if references_binding(&value, &bindings) {
+ references.insert(draft.draft_id);
+ }
+ }
+ // Active publications also cover supported unversioned plans, and the installation window
+ // before a newly prepared version receives its product head.
+ let mut statement = connection.prepare("SELECT publication_bytes FROM gateway_publications WHERE workspace_id=?1 AND state IN ('active','prepared','lkg')")
+ .map_err(|_| port("compute.management.references.publications"))?;
+ for row in statement
+ .query_map([workspace.as_str()], |row| row.get::<_, Vec<u8>>(0))
+ .map_err(|_| port("compute.management.references.publications"))?
+ {
+ let bytes = row.map_err(|_| port("compute.management.references.publication"))?;
+ let publication = hiroute_domain::GatewayPublicationV1::decode_persisted(&bytes)
+ .map_err(|_| corrupt("compute.management.references.publication"))?;
+ for plan in publication.plans {
+ let value = serde_json::to_value(&plan)
+ .map_err(|_| corrupt("compute.management.references.publication.plan"))?;
+ if references_binding(&value, &bindings) {
+ references.insert(plan.agent_plan_id().as_str().to_owned());
+ }
+ }
+ }
+ Ok(references.into_iter().collect())
+}
+
+fn references_binding(value: &Value, bindings: &BTreeSet<&str>) -> bool {
+ match value {
+ Value::Object(object) => {
+ object
+ .get("binding_id")
+ .and_then(Value::as_str)
+ .is_some_and(|id| bindings.contains(id))
+ || object
+ .get("quality_anchor_binding_id")
+ .and_then(Value::as_str)
+ .is_some_and(|id| bindings.contains(id))
+ || object
+ .get("automatic_reasoning")
+ .and_then(Value::as_object)
+ .is_some_and(|map| map.keys().any(|id| bindings.contains(id.as_str())))
+ || object
+ .values()
+ .any(|value| references_binding(value, bindings))
+ }
+ Value::Array(values) => values
+ .iter()
+ .any(|value| references_binding(value, bindings)),
+ _ => false,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn automatic_free_pool_configuration_keys_remain_references_without_materialized_candidates() {
+ let binding = "binding/temporarily-unavailable";
+ let config = serde_json::json!({"free_pool":{"automatic_reasoning":{binding:{"kind":"toggle","enabled":true}}}});
+ assert!(references_binding(&config, &BTreeSet::from([binding])));
+ assert!(!references_binding(
+ &config,
+ &BTreeSet::from(["binding/unrelated"])
+ ));
+ }
+}
diff --git a/crates/local-storage/src/control/compute/management/tests.rs b/crates/local-storage/src/control/compute/management/tests.rs
index 2621534d..e3038fa8 100644
--- a/crates/local-storage/src/control/compute/management/tests.rs
+++ b/crates/local-storage/src/control/compute/management/tests.rs
@@ -31,6 +31,11 @@ use hiroute_domain::{
use super::super::super::ControlStore;
use crate::{LocalSecretStore, LocalStorageSet, RuntimeStore};
+mod compensation_guards;
+mod lifecycle;
+mod recovery;
+mod released_lifecycle;
+mod removal_guards;
mod runtime_leases;
mod subscription_selection;
@@ -321,6 +326,7 @@ fn discovery_change(
revisions: hiroute_domain::RevisionSetV1,
) -> ComputeManagementChangeV2 {
ComputeManagementChangeV2 {
+ edit: None,
schema: "hiroute.compute-management-change/v2".into(),
subject: ComputeManagementSubjectV2::Candidate {
candidate: facts.candidate.clone(),
@@ -387,6 +393,7 @@ fn populate_saved_source(
.revisions;
let preview = planner
.preview(ComputeManagementChangeV2 {
+ edit: None,
schema: "hiroute.compute-management-change/v2".into(),
subject: ComputeManagementSubjectV2::Candidate {
candidate: facts.candidate.clone(),
@@ -440,6 +447,7 @@ fn populate_saved_source(
registry.register_compute_candidate(second.clone()).unwrap();
let second_preview = planner
.preview(ComputeManagementChangeV2 {
+ edit: None,
schema: "hiroute.compute-management-change/v2".into(),
subject: ComputeManagementSubjectV2::SavedSource {
source_id: source.source_id.clone(),
@@ -478,6 +486,7 @@ fn populate_saved_source(
.unwrap();
let combination_preview = planner
.preview(ComputeManagementChangeV2 {
+ edit: None,
schema: "hiroute.compute-management-change/v2".into(),
subject: ComputeManagementSubjectV2::SavedSource {
source_id: second_source.source_id.clone(),
@@ -603,6 +612,7 @@ fn editing_source_adds_endpoint_without_reentering_or_copying_the_saved_key() {
.unwrap();
let preview = planner
.preview(ComputeManagementChangeV2 {
+ edit: None,
schema: "hiroute.compute-management-change/v2".into(),
subject: ComputeManagementSubjectV2::Candidate {
candidate: first.candidate,
@@ -663,6 +673,7 @@ fn editing_source_adds_endpoint_without_reentering_or_copying_the_saved_key() {
registry.register_compute_candidate(edited.clone()).unwrap();
let preview = planner
.preview(ComputeManagementChangeV2 {
+ edit: None,
schema: "hiroute.compute-management-change/v2".into(),
subject: ComputeManagementSubjectV2::Candidate {
candidate: edited.candidate,
@@ -939,4 +950,104 @@ fn reimport_of_saved_native_source_still_rejects_changed_discovery_without_key_e
assert_eq!(snapshot().revisions, before.revisions);
}
+#[test]
+fn append_of_saved_native_source_revalidates_discovery_at_preview_and_admission() {
+ let directory = tempdir().unwrap();
+ let stores = LocalStorageSet::open_for_daemon_startup(directory.path()).unwrap();
+ let workspace = WorkspaceId::default();
+ let registry = TrustedComputeCandidateRegistry::new();
+ let evidence = CanonicalDigest::of_bytes(b"static-native-source/v1");
+ let mut facts = discovered_candidate(evidence.clone());
+ facts.provenance = ComputeCandidateProvenanceV2::UserConfigured {
+ configuration_revision: 1,
+ evidence_digest: facts.evidence_digest.clone(),
+ };
+ registry.register_compute_candidate(facts.clone()).unwrap();
+ let input = DiscoveryProtectedInput::new(evidence);
+ let planner =
+ ComputeManagementPlanner::new(&registry, stores.control(), stores.secrets(), &input);
+ let runtime = TransactionRuntime::default();
+ let external = NoExternal;
+ let coordinator = TransactionCoordinator::new(
+ stores.control(),
+ stores.secrets(),
+ stores.runtime(),
+ &external,
+ &input,
+ &runtime,
+ );
+ coordinator.reconcile_startup_and_open().unwrap();
+ let snapshot = || {
+ hiroute_domain::ComputeManagementRepositoryPort::compute_management_snapshot(
+ stores.control(),
+ &workspace,
+ )
+ .unwrap()
+ };
+ let first = planner
+ .preview(discovery_change(&facts, snapshot().revisions))
+ .unwrap();
+ apply_preview(
+ &stores,
+ &planner,
+ &coordinator,
+ &workspace,
+ first,
+ "native-source-first-save",
+ );
+ let before = snapshot();
+ // A no-key-edit reimport with the same evidence remains a valid product save.
+ let repeat = planner
+ .preview(discovery_change(&facts, before.revisions))
+ .unwrap();
+ apply_preview(
+ &stores,
+ &planner,
+ &coordinator,
+ &workspace,
+ repeat,
+ "native-source-unchanged-reimport",
+ );
+ assert_eq!(
+ snapshot().sources[0].credentials,
+ before.sources[0].credentials
+ );
+ let before = snapshot();
+ let mut refreshed_facts = facts.clone();
+ refreshed_facts.existing_source_id = Some(before.sources[0].source_id.clone());
+ refreshed_facts.candidate.candidate_revision += 1;
+ registry
+ .register_compute_candidate(refreshed_facts.clone())
+ .unwrap();
+ let mut change = discovery_change(&refreshed_facts, before.revisions.clone());
+ change.edit = Some(hiroute_application_api::ComputeManagementEditV1::AppendModels);
+ let preview = planner.preview(change.clone()).unwrap();
+ let request = ComputeConnectionApplyRequestV1 {
+ spec: preview.result.spec,
+ accept_digest: preview.result.accept_digest,
+ expected_revisions: preview.result.expected_revisions,
+ idempotency_key: "native-source-reimport".into(),
+ };
+ let prepared = planner.prepare_apply(request.clone()).unwrap();
+ input.evidence_valid.store(false, Ordering::Release);
+ assert!(matches!(
+ planner.preview(change),
+ Err(ComputeManagementPlanningErrorV2::PreviewStale)
+ ));
+ assert!(matches!(
+ planner.prepare_apply(request),
+ Err(ComputeManagementPlanningErrorV2::PreviewStale)
+ ));
+ assert!(matches!(
+ coordinator.accept_prepared(
+ &workspace,
+ &VerifiedPrincipal::for_local_control(),
+ prepared
+ ),
+ Err(TransactionError::ChangePreviewStale)
+ ));
+ assert_eq!(snapshot().sources, before.sources);
+ assert_eq!(snapshot().revisions, before.revisions);
+}
+
mod disabled;
diff --git a/crates/local-storage/src/control/compute/management/tests/compensation_guards.rs b/crates/local-storage/src/control/compute/management/tests/compensation_guards.rs
new file mode 100644
index 00000000..0d94d873
--- /dev/null
+++ b/crates/local-storage/src/control/compute/management/tests/compensation_guards.rs
@@ -0,0 +1,105 @@
+//! Fail-closed checks at the real rollback receipt left before its terminal write.
+use super::*;
+use hiroute_domain::ComputeManagementSourceV2;
+
+fn snapshot(stores: &LocalStorageSet) -> Vec<Vec<String>> {
+ stores.control().with_connection(|connection| {
+ [
+ "SELECT source_json,owner_operation_id,CAST(revision AS TEXT) FROM compute_management_sources ORDER BY source_id",
+ "SELECT desired_json,desired_digest,owner_operation_id,CAST(target_revision AS TEXT) FROM workspace_state ORDER BY workspace_id",
+ "SELECT CAST(revision AS TEXT) FROM workspace_revision_heads ORDER BY workspace_id",
+ ].into_iter().flat_map(|sql| {
+ let mut statement = connection.prepare(sql).unwrap();
+ let columns = statement.column_count();
+ statement.query_map([], |row| {
+ (0..columns).map(|index| row.get::<_, String>(index)).collect()
+ }).unwrap().collect::<Result<Vec<Vec<String>>, _>>().unwrap()
+ }).collect()
+ })
+}
+
+pub(super) fn assert_compensation_owner_and_receipt_guards(
+ stores: &LocalStorageSet,
+ operation_id: &hiroute_domain::OperationId,
+ before: &ComputeManagementSourceV2,
+ restored: &ComputeManagementSourceV2,
+) {
+ let operation = stores
+ .control()
+ .load_operation(operation_id)
+ .unwrap()
+ .unwrap();
+ let references: Vec<_> = restored
+ .credentials
+ .iter()
+ .map(|key| key.credential.clone())
+ .collect();
+ let healthy = snapshot(stores);
+ let before_owner: String = stores.control().with_connection(|connection| {
+ connection.query_row("SELECT before_owner_operation_id FROM compute_management_effects WHERE operation_id=?1", [operation_id.as_str()], |row| row.get(0)).unwrap()
+ });
+ assert_ne!(before_owner, operation_id.as_str());
+ let restore = || {
+ stores.control().with_connection(|connection| {
+ connection.execute("UPDATE compute_management_sources SET source_json=?1,owner_operation_id=?2,revision=?3", rusqlite::params![healthy[0][0], healthy[0][1], healthy[0][2]]).unwrap();
+ connection.execute("UPDATE workspace_state SET desired_json=?1,desired_digest=?2,owner_operation_id=?3,target_revision=?4", rusqlite::params![healthy[1][0], healthy[1][1], healthy[1][2], healthy[1][3]]).unwrap();
+ connection.execute("UPDATE workspace_revision_heads SET revision=?1", rusqlite::params![healthy[2][0]]).unwrap();
+ })
+ };
+
+ // Exact original source bytes alone cannot authorize repair after its owner changed.
+ stores.control().with_connection(|connection| {
+ connection.execute("UPDATE compute_management_sources SET source_json=?1,revision=?2,owner_operation_id=?3", rusqlite::params![super::super::encode(before).unwrap(), before.revision, operation_id.as_str()]).unwrap();
+ });
+ let foreign = snapshot(stores);
+ let error = stores
+ .control()
+ .reconcile_compute_compensation(&operation, &references)
+ .unwrap_err();
+ assert_eq!(
+ error,
+ PortError::new(PortErrorCode::Conflict, "compute.compensation.cas")
+ );
+ assert_eq!(snapshot(stores), foreign);
+ restore();
+
+ for field in ["owner", "digest", "head"] {
+ stores.control().with_connection(|connection| match field {
+ "owner" => connection
+ .execute(
+ "UPDATE workspace_state SET owner_operation_id=?1",
+ [&before_owner],
+ )
+ .unwrap(),
+ "digest" => connection
+ .execute(
+ "UPDATE workspace_state SET desired_digest='corrupt-receipt'",
+ [],
+ )
+ .unwrap(),
+ _ => connection
+ .execute(
+ "UPDATE workspace_revision_heads SET revision=revision+1",
+ [],
+ )
+ .unwrap(),
+ });
+ let corrupted = snapshot(stores);
+ let error = stores
+ .control()
+ .reconcile_compute_compensation(&operation, &references)
+ .unwrap_err();
+ assert_eq!(
+ error,
+ PortError::new(PortErrorCode::Conflict, "compute.compensation.receipt")
+ );
+ assert_eq!(snapshot(stores), corrupted);
+ restore();
+ }
+ // Restoring the fixture allows the unchanged receipt to replay without another revision.
+ stores
+ .control()
+ .reconcile_compute_compensation(&operation, &references)
+ .unwrap();
+ assert_eq!(snapshot(stores), healthy);
+}
diff --git a/crates/local-storage/src/control/compute/management/tests/disabled.rs b/crates/local-storage/src/control/compute/management/tests/disabled.rs
index 45c66cb4..5aafc3f0 100644
--- a/crates/local-storage/src/control/compute/management/tests/disabled.rs
+++ b/crates/local-storage/src/control/compute/management/tests/disabled.rs
@@ -56,6 +56,7 @@ fn pending_credential_disabled_save_uses_only_the_current_candidate_revision() {
.unwrap()
.revisions;
let change = |candidate: ComputeCandidateRefV2, intent| ComputeManagementChangeV2 {
+ edit: None,
schema: "hiroute.compute-management-change/v2".into(),
subject: ComputeManagementSubjectV2::Candidate { candidate },
expected_revisions: revisions.clone(),
@@ -156,6 +157,7 @@ fn failed_connection_can_save_disabled_user_declared_models_but_not_ready() {
.unwrap()
.revisions;
let change = |intent| ComputeManagementChangeV2 {
+ edit: None,
schema: "hiroute.compute-management-change/v2".into(),
subject: ComputeManagementSubjectV2::Candidate {
candidate: facts.candidate.clone(),
diff --git a/crates/local-storage/src/control/compute/management/tests/lifecycle.rs b/crates/local-storage/src/control/compute/management/tests/lifecycle.rs
new file mode 100644
index 00000000..ee5ab3c2
--- /dev/null
+++ b/crates/local-storage/src/control/compute/management/tests/lifecycle.rs
@@ -0,0 +1,317 @@
+use super::*;
+use hiroute_application_api::ComputeManagementEditV1;
+use hiroute_domain::{ComputeManagementRepositoryPort, ComputeManagementSourceV2};
+
+pub(super) fn saved(stores: &LocalStorageSet) -> ComputeManagementSourceV2 {
+ stores
+ .control()
+ .compute_management_snapshot(&WorkspaceId::default())
+ .unwrap()
+ .sources
+ .remove(0)
+}
+
+pub(super) fn edit(
+ stores: &LocalStorageSet,
+ source: &ComputeManagementSourceV2,
+ action: ComputeManagementEditV1,
+ selected: &[&str],
+) -> ComputeManagementChangeV2 {
+ ComputeManagementChangeV2 {
+ schema: "hiroute.compute-management-change/v2".into(),
+ subject: ComputeManagementSubjectV2::SavedSource {
+ source_id: source.source_id.clone(),
+ },
+ expected_revisions: stores
+ .control()
+ .compute_management_snapshot(&WorkspaceId::default())
+ .unwrap()
+ .revisions,
+ selected_model_refs: selected.iter().map(|value| (*value).into()).collect(),
+ intent: ComputeManagementIntentV2::SaveReady,
+ key_edits: Vec::new(),
+ validation: None,
+ edit: Some(action),
+ }
+}
+
+pub(super) fn execute(
+ stores: &LocalStorageSet,
+ registry: &TrustedComputeCandidateRegistry,
+ change: ComputeManagementChangeV2,
+ key: &str,
+) {
+ let input = ProtectedInput;
+ let planner =
+ ComputeManagementPlanner::new(registry, stores.control(), stores.secrets(), &input);
+ let runtime = TransactionRuntime::default();
+ let external = NoExternal;
+ let coordinator = TransactionCoordinator::new(
+ stores.control(),
+ stores.secrets(),
+ stores.runtime(),
+ &external,
+ &input,
+ &runtime,
+ );
+ coordinator.reconcile_startup_and_open().unwrap();
+ let preview = planner
+ .preview(change)
+ .unwrap_or_else(|error| panic!("{key} preview failed: {error:?}"));
+ apply_preview(
+ stores,
+ &planner,
+ &coordinator,
+ &WorkspaceId::default(),
+ preview,
+ key,
+ );
+}
+
+#[test]
+fn rename_remove_delete_preserve_binding_and_clean_only_owned_credentials_after_restart() {
+ let directory = tempdir().unwrap();
+ populate_saved_source(directory.path(), &WorkspaceId::default());
+ let stores = LocalStorageSet::open_for_daemon_startup(directory.path()).unwrap();
+ let registry = TrustedComputeCandidateRegistry::new();
+ let before = saved(&stores);
+ execute(
+ &stores,
+ &registry,
+ edit(
+ &stores,
+ &before,
+ ComputeManagementEditV1::Rename {
+ display_name: "Bailian · team".into(),
+ },
+ &[],
+ ),
+ "rename",
+ );
+ let named = saved(&stores);
+ assert_eq!(named.display_name, "Bailian · team");
+ assert_eq!(named.models, before.models);
+ assert_eq!(named.credentials, before.credentials);
+ assert_eq!(named.source_id, before.source_id);
+ execute(
+ &stores,
+ &registry,
+ edit(
+ &stores,
+ &named,
+ ComputeManagementEditV1::RemoveModels,
+ &[&named.models[0].model_ref],
+ ),
+ "remove",
+ );
+ let kept = saved(&stores);
+ assert_eq!(kept.models, vec![named.models[1].clone()]);
+ assert_eq!(kept.credentials, before.credentials);
+ let input = ProtectedInput;
+ let planner =
+ ComputeManagementPlanner::new(&registry, stores.control(), stores.secrets(), &input);
+ assert!(
+ planner
+ .preview(edit(
+ &stores,
+ &kept,
+ ComputeManagementEditV1::RemoveModels,
+ &[&kept.models[0].model_ref]
+ ))
+ .is_err(),
+ "last model requires explicit connection deletion"
+ );
+ execute(
+ &stores,
+ &registry,
+ edit(&stores, &kept, ComputeManagementEditV1::Delete, &[]),
+ "delete",
+ );
+ assert!(
+ stores
+ .control()
+ .compute_management_snapshot(&WorkspaceId::default())
+ .unwrap()
+ .sources
+ .is_empty()
+ );
+ for key in &kept.credentials {
+ assert_owned_secret_deleted(&stores, &key.credential);
+ }
+ drop(stores);
+ let reopened = LocalStorageSet::open_for_daemon_startup(directory.path()).unwrap();
+ assert!(
+ reopened
+ .control()
+ .compute_management_source(&before.source_id)
+ .unwrap()
+ .is_none()
+ );
+}
+
+#[test]
+fn explicit_append_preserves_disabled_source_old_model_facts_and_key() {
+ let directory = tempdir().unwrap();
+ populate_saved_source(directory.path(), &WorkspaceId::default());
+ let stores = LocalStorageSet::open_for_daemon_startup(directory.path()).unwrap();
+ let registry = TrustedComputeCandidateRegistry::new();
+ let original = saved(&stores);
+ let mut disable = edit(&stores, &original, ComputeManagementEditV1::Delete, &[]);
+ disable.edit = None;
+ disable.intent = ComputeManagementIntentV2::SaveDisabled;
+ disable.selected_model_refs = original
+ .models
+ .iter()
+ .map(|model| model.model_ref.clone())
+ .collect();
+ execute(&stores, &registry, disable, "disable");
+ let current = saved(&stores);
+ let mut facts = candidate("candidate/append", "slot/primary");
+ facts.existing_source_id = Some(current.source_id.clone());
+ let mut extra = facts.models[0].clone();
+ extra.model_ref = "model/third".into();
+ extra.upstream_model_id = "third-upstream".into();
+ extra.display_name = "Third model".into();
+ facts.models = vec![extra];
+ registry.register_compute_candidate(facts.clone()).unwrap();
+ let mut change = edit(
+ &stores,
+ &current,
+ ComputeManagementEditV1::AppendModels,
+ &["model/third"],
+ );
+ change.subject = ComputeManagementSubjectV2::Candidate {
+ candidate: facts.candidate.clone(),
+ };
+ execute(&stores, &registry, change, "append");
+ let added = saved(&stores);
+ assert_eq!(added.state, MaterializationState::Disabled);
+ assert_eq!(&added.models[..current.models.len()], &current.models);
+ assert_eq!(added.models.len(), current.models.len() + 1);
+ assert_eq!(added.credentials, current.credentials);
+ assert_eq!(added.display_name, current.display_name);
+ assert_eq!(added.source_id, current.source_id);
+}
+
+#[test]
+fn stale_saved_edit_cannot_recreate_deleted_connection() {
+ let directory = tempdir().unwrap();
+ populate_saved_source(directory.path(), &WorkspaceId::default());
+ let stores = LocalStorageSet::open_for_daemon_startup(directory.path()).unwrap();
+ let registry = TrustedComputeCandidateRegistry::new();
+ let source = saved(&stores);
+ let old = edit(
+ &stores,
+ &source,
+ ComputeManagementEditV1::Rename {
+ display_name: "Old page".into(),
+ },
+ &[],
+ );
+ execute(
+ &stores,
+ &registry,
+ edit(&stores, &source, ComputeManagementEditV1::Delete, &[]),
+ "delete",
+ );
+ let input = ProtectedInput;
+ let planner =
+ ComputeManagementPlanner::new(&registry, stores.control(), stores.secrets(), &input);
+ assert!(planner.preview(old.clone()).is_err());
+ let mut refreshed = old;
+ refreshed.expected_revisions = stores
+ .control()
+ .compute_management_snapshot(&WorkspaceId::default())
+ .unwrap()
+ .revisions;
+ assert!(planner.preview(refreshed).is_err());
+}
+
+#[test]
+fn two_independent_connections_with_same_key_keep_distinct_owners_after_one_is_deleted() {
+ let root = tempdir().unwrap();
+ let stores = LocalStorageSet::open_for_daemon_startup(root.path()).unwrap();
+ let registry = TrustedComputeCandidateRegistry::new();
+ for number in 1..=2 {
+ let mut facts = candidate(&format!("candidate/independent-{number}"), "slot/primary");
+ facts.lineage_ref = format!("lineage/independent-{number}");
+ registry.register_compute_candidate(facts.clone()).unwrap();
+ execute(
+ &stores,
+ &registry,
+ ComputeManagementChangeV2 {
+ schema: "hiroute.compute-management-change/v2".into(),
+ subject: ComputeManagementSubjectV2::Candidate {
+ candidate: facts.candidate,
+ },
+ expected_revisions: stores
+ .control()
+ .compute_management_snapshot(&WorkspaceId::default())
+ .unwrap()
+ .revisions,
+ selected_model_refs: vec!["model/one".into()],
+ intent: ComputeManagementIntentV2::SaveReady,
+ key_edits: Vec::new(),
+ validation: None,
+ edit: Some(ComputeManagementEditV1::Rename {
+ display_name: format!("API {number}"),
+ }),
+ },
+ &format!("create-{number}"),
+ );
+ }
+ let mut sources = stores
+ .control()
+ .compute_management_snapshot(&WorkspaceId::default())
+ .unwrap()
+ .sources;
+ sources.sort_by(|a, b| a.display_name.cmp(&b.display_name));
+ let (first, second) = (&sources[0], &sources[1]);
+ assert_ne!(first.source_id, second.source_id);
+ assert_ne!(first.models[0].binding_id, second.models[0].binding_id);
+ assert_ne!(
+ first.credentials[0].credential.owner_scope(),
+ second.credentials[0].credential.owner_scope()
+ );
+ assert_ne!(first.credentials[0].key_id, second.credentials[0].key_id);
+ execute(
+ &stores,
+ &registry,
+ edit(&stores, first, ComputeManagementEditV1::Delete, &[]),
+ "delete-one",
+ );
+ assert_eq!(saved(&stores), *second);
+ assert_owned_secret_deleted(&stores, &first.credentials[0].credential);
+ assert_eq!(
+ stores
+ .secrets()
+ .generation(&second.credentials[0].credential)
+ .unwrap(),
+ second.credentials[0].credential.generation()
+ );
+}
+
+fn assert_owned_secret_deleted(
+ stores: &LocalStorageSet,
+ credential: &hiroute_domain::CredentialRefV1,
+) {
+ // A delete advances the durable generation/absence witness; resetting it to zero
+ // would permit stale credential references to regain authority after recreation.
+ assert_eq!(
+ stores.secrets().generation(credential).unwrap(),
+ credential.generation() + 1
+ );
+ let present: bool = stores.secrets().with_connection(|connection| {
+ connection
+ .query_row(
+ "SELECT EXISTS(SELECT 1 FROM secret_entries WHERE credential_id=?1)",
+ [credential.credential_id()],
+ |row| row.get(0),
+ )
+ .unwrap()
+ });
+ assert!(
+ !present,
+ "deleted connection must no longer retain a live secret entry"
+ );
+}
diff --git a/crates/local-storage/src/control/compute/management/tests/recovery.rs b/crates/local-storage/src/control/compute/management/tests/recovery.rs
new file mode 100644
index 00000000..d5a17fef
--- /dev/null
+++ b/crates/local-storage/src/control/compute/management/tests/recovery.rs
@@ -0,0 +1,497 @@
+//! Real coordinator and three stores; SQLite faults are limited to exact deletion checkpoints.
+use super::lifecycle::{edit, saved};
+use super::*;
+use hiroute_application_api::ComputeManagementEditV1;
+use hiroute_domain::{
+ ComputeManagementRepositoryPort, ComputeManagementSourceV2, VerifiedSecretSubjectV1,
+};
+
+fn assert_credentials_restored(stores: &LocalStorageSet, source: &ComputeManagementSourceV2) {
+ for key in &source.credentials {
+ let credential = &key.credential;
+ let subject = VerifiedSecretSubjectV1::from_authenticated_transport(
+ credential.subject(),
+ credential.owner_scope(),
+ )
+ .unwrap();
+ let secret = stores
+ .secrets()
+ .resolve_secret(
+ &subject,
+ credential,
+ credential.purpose(),
+ credential.allowed_destinations().iter().next().unwrap(),
+ credential.generation(),
+ )
+ .unwrap();
+ assert_eq!(
+ stores.secrets().fingerprint(&secret).unwrap(),
+ key.fingerprint
+ );
+ }
+}
+
+#[test]
+fn compute_delete_failure_after_secret_activation_rolls_back_all_stores_and_survives_restart() {
+ for (terminal_failure, blocked_secret) in [
+ (false, None),
+ (true, None),
+ (false, Some(0)),
+ (false, Some(1)),
+ ] {
+ let root = tempdir().unwrap();
+ populate_saved_source(root.path(), &WorkspaceId::default());
+ let before;
+ let restored;
+ let restored_revisions;
+ let operation_id;
+ {
+ let stores = LocalStorageSet::open_for_daemon_startup(root.path()).unwrap();
+ before = saved(&stores);
+ let registry = TrustedComputeCandidateRegistry::new();
+ let input = ProtectedInput;
+ let planner = ComputeManagementPlanner::new(
+ &registry,
+ stores.control(),
+ stores.secrets(),
+ &input,
+ );
+ let preview = planner
+ .preview(edit(&stores, &before, ComputeManagementEditV1::Delete, &[]))
+ .unwrap();
+ let runtime = TransactionRuntime::default();
+ let external = NoExternal;
+ let coordinator = TransactionCoordinator::new(
+ stores.control(),
+ stores.secrets(),
+ stores.runtime(),
+ &external,
+ &input,
+ &runtime,
+ );
+ coordinator.reconcile_startup_and_open().unwrap();
+ let prepared = planner
+ .prepare_apply(ComputeConnectionApplyRequestV1 {
+ spec: preview.result.spec,
+ accept_digest: preview.result.accept_digest,
+ expected_revisions: preview.result.expected_revisions,
+ idempotency_key: "delete-rollback".into(),
+ })
+ .unwrap();
+ let accepted = coordinator
+ .accept_prepared(
+ &WorkspaceId::default(),
+ &VerifiedPrincipal::for_local_control(),
+ prepared,
+ )
+ .unwrap();
+ operation_id = accepted.operation().operation_id.clone();
+ let secrets = accepted.operation().plan.secrets();
+ assert_eq!(secrets.len(), 2);
+ let activated: Vec<_> = secrets
+ .iter()
+ .take(blocked_secret.unwrap_or(secrets.len()))
+ .map(|secret| secret.credential().credential_id().to_owned())
+ .collect();
+ if let Some(index) = blocked_secret {
+ let blocked = secrets[index].credential().credential_id();
+ assert!(!blocked.contains('\''));
+ stores.secrets().with_connection(|connection| connection.execute_batch(&format!("CREATE TRIGGER fail_secret_delete BEFORE DELETE ON secret_entries WHEN OLD.credential_id='{blocked}' BEGIN SELECT RAISE(ABORT, 'fixture_secret_delete_failure'); END;")).unwrap());
+ }
+ // Activation deletes Secret entries before trying the Control row. Failure here
+ // exercises real coordinator compensation of already-activated credential deletes.
+ stores.control().with_connection(|connection| connection.execute_batch(
+ "CREATE TRIGGER fail_connection_delete BEFORE DELETE ON compute_management_sources BEGIN SELECT RAISE(ABORT, 'fixture_delete_failure'); END;").unwrap());
+ if terminal_failure {
+ stores.control().with_connection(|connection| connection.execute_batch("CREATE TRIGGER fail_rollback_terminal BEFORE UPDATE OF state ON operations WHEN NEW.state='rolled_back' BEGIN SELECT RAISE(ABORT, 'fixture_rollback_terminal'); END;").unwrap());
+ assert!(coordinator.run(&operation_id).is_err());
+ } else {
+ let completed = coordinator.run(&operation_id).unwrap();
+ assert_eq!(completed.state, OperationState::RolledBack);
+ }
+ restored = saved(&stores);
+ let mut expected = before.clone();
+ if !activated.is_empty() {
+ expected.revision += 2;
+ }
+ for key in &mut expected.credentials {
+ if !activated.contains(&key.key_id) {
+ continue;
+ }
+ let credential = &key.credential;
+ key.credential = hiroute_domain::CredentialRefV1::new(
+ credential.credential_id(),
+ credential.owner_scope(),
+ credential.subject(),
+ credential.purpose(),
+ credential.allowed_destinations().iter().cloned(),
+ credential.generation() + 2,
+ )
+ .unwrap();
+ }
+ assert_eq!(restored, expected);
+ if terminal_failure {
+ super::compensation_guards::assert_compensation_owner_and_receipt_guards(
+ &stores,
+ &operation_id,
+ &before,
+ &restored,
+ );
+ }
+ assert_credentials_restored(&stores, &restored);
+ for key in &before.credentials {
+ let credential = &key.credential;
+ let subject = VerifiedSecretSubjectV1::from_authenticated_transport(
+ credential.subject(),
+ credential.owner_scope(),
+ )
+ .unwrap();
+ assert_eq!(
+ stores
+ .secrets()
+ .resolve_secret(
+ &subject,
+ credential,
+ credential.purpose(),
+ credential.allowed_destinations().iter().next().unwrap(),
+ credential.generation()
+ )
+ .is_err(),
+ activated.contains(&key.key_id)
+ );
+ }
+ let lease = stores
+ .lease_native_credential_exact(&super::runtime_leases::frozen_request(
+ &restored, 0, 0,
+ ))
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ lease.generation(),
+ restored.credentials[0].credential.generation()
+ );
+ restored_revisions = stores
+ .control()
+ .current_revisions(&WorkspaceId::default())
+ .unwrap();
+ stores.secrets().with_connection(|connection| {
+ connection
+ .execute_batch("DROP TRIGGER IF EXISTS fail_secret_delete;")
+ .unwrap()
+ });
+ stores.control().with_connection(|connection| {
+ connection
+ .execute_batch("DROP TRIGGER fail_connection_delete; DROP TRIGGER IF EXISTS fail_rollback_terminal;")
+ .unwrap()
+ });
+ }
+ let stores = LocalStorageSet::open_for_daemon_startup(root.path()).unwrap();
+ let runtime = TransactionRuntime::default();
+ let external = NoExternal;
+ let input = ProtectedInput;
+ let coordinator = TransactionCoordinator::new(
+ stores.control(),
+ stores.secrets(),
+ stores.runtime(),
+ &external,
+ &input,
+ &runtime,
+ );
+ coordinator.reconcile_startup_and_open().unwrap();
+ assert_eq!(
+ stores
+ .control()
+ .load_operation(&operation_id)
+ .unwrap()
+ .unwrap()
+ .state,
+ OperationState::RolledBack
+ );
+ assert_eq!(saved(&stores), restored);
+ assert_credentials_restored(&stores, &restored);
+ assert_eq!(
+ stores
+ .control()
+ .current_revisions(&WorkspaceId::default())
+ .unwrap(),
+ restored_revisions
+ );
+ coordinator.reconcile_startup_and_open().unwrap();
+ assert_eq!(
+ stores
+ .control()
+ .current_revisions(&WorkspaceId::default())
+ .unwrap(),
+ restored_revisions
+ );
+ }
+}
+
+#[test]
+fn compute_key_edit_rollback_preserves_authority_and_restores_forward_references() {
+ for action in ["replace", "remove", "rebind"] {
+ let root = tempdir().unwrap();
+ populate_saved_source(root.path(), &WorkspaceId::default());
+ let stores = LocalStorageSet::open_for_daemon_startup(root.path()).unwrap();
+ let before = saved(&stores);
+ let registry = TrustedComputeCandidateRegistry::new();
+ let mut change = edit(&stores, &before, ComputeManagementEditV1::Delete, &[]);
+ change.edit = None;
+ change.selected_model_refs = before
+ .models
+ .iter()
+ .map(|model| model.model_ref.clone())
+ .collect();
+ // Removing the disabled spare key is a valid ready save; removing the only
+ // enabled key must instead be rejected by the planner before any effects.
+ let key = &before.credentials[usize::from(action == "remove")];
+ match action {
+ "replace" => {
+ let replacement = candidate("candidate/rollback-replace", "slot/primary");
+ registry
+ .register_compute_candidate(replacement.clone())
+ .unwrap();
+ change.key_edits.push(ComputeKeyEditV2::Replace {
+ key_id: key.key_id.clone(),
+ expected_generation: key.credential.generation(),
+ input_candidate: replacement.candidate,
+ });
+ }
+ "remove" => change.key_edits.push(ComputeKeyEditV2::Remove {
+ key_id: key.key_id.clone(),
+ expected_generation: key.credential.generation(),
+ }),
+ _ => {
+ let mut edited = candidate("candidate/rollback-endpoint", "slot/unused");
+ edited.existing_source_id = Some(before.source_id.clone());
+ edited.trusted_lineage_digest = Some(before.lineage_digest.clone());
+ edited.credential_binding = ComputeCredentialBindingV2::NativeSaved {
+ credential_id: key.key_id.clone(),
+ expected_generation: key.credential.generation(),
+ };
+ let mut target = before.target.clone();
+ target.authority = "rollback-messages.example.test".into();
+ target.request_path = "/v1/messages".into();
+ target.upstream_protocol = UpstreamProtocol::Messages;
+ target.protocol_profile_id = "profile/messages".into();
+ edited
+ .additional_native_endpoints
+ .push(hiroute_domain::ComputeNativeEndpointV3 {
+ target,
+ authentication: GatewayAuthenticationSemanticsV1::ApiKeyHeader {
+ header: "x-api-key".into(),
+ },
+ recheck: None,
+ });
+ registry.register_compute_candidate(edited.clone()).unwrap();
+ change.selected_model_refs = edited
+ .models
+ .iter()
+ .map(|model| model.model_ref.clone())
+ .collect();
+ change.subject = ComputeManagementSubjectV2::Candidate {
+ candidate: edited.candidate,
+ };
+ }
+ }
+ let input = ProtectedInput;
+ let planner =
+ ComputeManagementPlanner::new(&registry, stores.control(), stores.secrets(), &input);
+ let preview = planner
+ .preview(change)
+ .unwrap_or_else(|error| panic!("{action} preview: {error:?}"));
+ let runtime = TransactionRuntime::default();
+ let external = NoExternal;
+ let coordinator = TransactionCoordinator::new(
+ stores.control(),
+ stores.secrets(),
+ stores.runtime(),
+ &external,
+ &input,
+ &runtime,
+ );
+ coordinator.reconcile_startup_and_open().unwrap();
+ let prepared = planner
+ .prepare_apply(ComputeConnectionApplyRequestV1 {
+ spec: preview.result.spec,
+ accept_digest: preview.result.accept_digest,
+ expected_revisions: preview.result.expected_revisions,
+ idempotency_key: format!("rollback-{action}"),
+ })
+ .unwrap();
+ let accepted = coordinator
+ .accept_prepared(
+ &WorkspaceId::default(),
+ &VerifiedPrincipal::for_local_control(),
+ prepared,
+ )
+ .unwrap();
+ let secrets = accepted.operation().plan.secrets();
+ assert_eq!(secrets.len(), if action == "rebind" { 2 } else { 1 });
+ let expected_kind = match action {
+ "replace" => hiroute_domain::SecretMutationKind::Upsert,
+ "remove" => hiroute_domain::SecretMutationKind::Delete,
+ _ => hiroute_domain::SecretMutationKind::Rebind,
+ };
+ assert!(secrets.iter().all(|secret| secret.kind() == expected_kind));
+ // Fail the desired activation, while allowing the distinct forward compensation revision.
+ stores.control().with_connection(|connection| connection.execute_batch(&format!("CREATE TRIGGER fail_source_edit BEFORE UPDATE ON compute_management_sources WHEN NEW.revision={} BEGIN SELECT RAISE(ABORT, 'fixture_source_edit'); END;", before.revision + 1)).unwrap());
+ assert_eq!(
+ coordinator
+ .run(&accepted.operation().operation_id)
+ .unwrap()
+ .state,
+ OperationState::RolledBack,
+ "{action}"
+ );
+ let restored = saved(&stores);
+ let mut expected = before.clone();
+ expected.revision += 2;
+ for key in &mut expected.credentials {
+ if !secrets
+ .iter()
+ .any(|secret| secret.credential().credential_id() == key.key_id)
+ {
+ continue;
+ }
+ let credential = &key.credential;
+ key.credential = hiroute_domain::CredentialRefV1::new(
+ credential.credential_id(),
+ credential.owner_scope(),
+ credential.subject(),
+ credential.purpose(),
+ credential.allowed_destinations().iter().cloned(),
+ credential.generation() + 2,
+ )
+ .unwrap();
+ }
+ assert_eq!(restored, expected, "{action}");
+ assert_credentials_restored(&stores, &restored);
+ assert!(
+ stores
+ .lease_native_credential_exact(&super::runtime_leases::frozen_request(
+ &restored, 0, 0
+ ))
+ .unwrap()
+ .is_some(),
+ "{action}"
+ );
+ }
+}
+
+#[test]
+fn compute_delete_activated_before_terminal_journal_failure_completes_once_on_startup() {
+ let root = tempdir().unwrap();
+ populate_saved_source(root.path(), &WorkspaceId::default());
+ let before;
+ let operation_id;
+ {
+ let stores = LocalStorageSet::open_for_daemon_startup(root.path()).unwrap();
+ before = saved(&stores);
+ let registry = TrustedComputeCandidateRegistry::new();
+ let input = ProtectedInput;
+ let planner =
+ ComputeManagementPlanner::new(&registry, stores.control(), stores.secrets(), &input);
+ let preview = planner
+ .preview(edit(&stores, &before, ComputeManagementEditV1::Delete, &[]))
+ .unwrap();
+ let runtime = TransactionRuntime::default();
+ let external = NoExternal;
+ let coordinator = TransactionCoordinator::new(
+ stores.control(),
+ stores.secrets(),
+ stores.runtime(),
+ &external,
+ &input,
+ &runtime,
+ );
+ coordinator.reconcile_startup_and_open().unwrap();
+ let prepared = planner
+ .prepare_apply(ComputeConnectionApplyRequestV1 {
+ spec: preview.result.spec,
+ accept_digest: preview.result.accept_digest,
+ expected_revisions: preview.result.expected_revisions,
+ idempotency_key: "delete-recovery".into(),
+ })
+ .unwrap();
+ let accepted = coordinator
+ .accept_prepared(
+ &WorkspaceId::default(),
+ &VerifiedPrincipal::for_local_control(),
+ prepared,
+ )
+ .unwrap();
+ operation_id = accepted.operation().operation_id.clone();
+ stores.control().with_connection(|connection| connection.execute_batch(
+ "CREATE TRIGGER fail_delete_terminal BEFORE UPDATE OF state ON operations WHEN NEW.state='succeeded' BEGIN SELECT RAISE(ABORT, 'fixture_terminal_failure'); END;").unwrap());
+ assert!(coordinator.run(&operation_id).is_err());
+ assert!(
+ stores
+ .control()
+ .compute_management_source(&before.source_id)
+ .unwrap()
+ .is_none()
+ );
+ stores.control().with_connection(|connection| {
+ connection
+ .execute_batch("DROP TRIGGER fail_delete_terminal;")
+ .unwrap()
+ });
+ }
+ let stores = LocalStorageSet::open_for_daemon_startup(root.path()).unwrap();
+ let runtime = TransactionRuntime::default();
+ let external = NoExternal;
+ let input = ProtectedInput;
+ let coordinator = TransactionCoordinator::new(
+ stores.control(),
+ stores.secrets(),
+ stores.runtime(),
+ &external,
+ &input,
+ &runtime,
+ );
+ coordinator.reconcile_startup_and_open().unwrap();
+ assert_eq!(
+ stores
+ .control()
+ .load_operation(&operation_id)
+ .unwrap()
+ .unwrap()
+ .state,
+ OperationState::Succeeded
+ );
+ assert!(
+ stores
+ .control()
+ .compute_management_source(&before.source_id)
+ .unwrap()
+ .is_none()
+ );
+ for key in &before.credentials {
+ assert_eq!(
+ stores.secrets().generation(&key.credential).unwrap(),
+ key.credential.generation() + 1
+ );
+ assert!(!stores.secrets().with_connection(|connection| {
+ connection
+ .query_row(
+ "SELECT EXISTS(SELECT 1 FROM secret_entries WHERE credential_id=?1)",
+ [&key.key_id],
+ |row| row.get::<_, bool>(0),
+ )
+ .unwrap()
+ }));
+ }
+ let revisions = stores
+ .control()
+ .current_revisions(&WorkspaceId::default())
+ .unwrap();
+ coordinator.reconcile_startup_and_open().unwrap();
+ assert_eq!(
+ stores
+ .control()
+ .current_revisions(&WorkspaceId::default())
+ .unwrap(),
+ revisions
+ );
+}
diff --git a/crates/local-storage/src/control/compute/management/tests/released_lifecycle.rs b/crates/local-storage/src/control/compute/management/tests/released_lifecycle.rs
new file mode 100644
index 00000000..676c59f8
--- /dev/null
+++ b/crates/local-storage/src/control/compute/management/tests/released_lifecycle.rs
@@ -0,0 +1,60 @@
+//! Actual released CLI -> daemon bytes, captured without the current serializer.
+//! Producer: public v0.2.0, d625e653048b2306c88da07826d52027e9891675.
+use super::*;
+
+#[test]
+fn compute_released_save_omits_edit_and_preserves_journal_control_and_accept_digest() {
+ let raw = include_str!(concat!(
+ env!("CARGO_MANIFEST_DIR"),
+ "/tests/fixtures/v0.2.0-compute-operation.json"
+ ));
+ assert_eq!(
+ CanonicalDigest::of_bytes(raw.as_bytes()).as_str(),
+ "sha256:36a7ba3deb41a15a88cc6af76bba399b132b8cce07a4648d2168cf573426483c"
+ );
+ let mut original: serde_json::Value = serde_json::from_str(raw).unwrap();
+ let operation = crate::control::decode_operation(&Default::default(), raw).unwrap();
+ // The released journal explicitly stores a null optional error. The current
+ // Operation writer omits None; this predates the connection edit contract.
+ assert!(original["safe_error_code"].is_null());
+ original.as_object_mut().unwrap().remove("safe_error_code");
+ assert_eq!(serde_json::to_value(&operation).unwrap(), original);
+ let spec = operation.plan.spec();
+ let change: ComputeManagementChangeV2 =
+ serde_json::from_value(spec.desired_state.clone()).unwrap();
+ change.validate_shape().unwrap();
+ assert!(change.edit.is_none());
+ assert_eq!(serde_json::to_value(change).unwrap(), spec.desired_state);
+ let mutation: hiroute_domain::ComputeManagementMutationV2 =
+ serde_json::from_value(operation.plan.control()["compute_management_mutation"].clone())
+ .unwrap();
+ mutation.validate_shape(spec).unwrap();
+ assert!(mutation.desired().is_some());
+ assert_eq!(
+ serde_json::to_value(&mutation).unwrap(),
+ operation.plan.control()["compute_management_mutation"]
+ );
+ assert_eq!(
+ mutation.desired().unwrap().digest().unwrap(),
+ *mutation.desired_digest()
+ );
+ let accepted = CanonicalDigest::of(&(
+ "hiroute.compute-management-preview/v2",
+ spec,
+ &operation.expected_revisions,
+ operation.plan.control(),
+ operation.plan.secrets(),
+ ))
+ .unwrap();
+ assert_eq!(accepted, operation.accepted_digest);
+ assert_eq!(
+ accepted.as_str(),
+ "sha256:1c55a5e135365f9e40fc739446d253ad367696a372b061c86cf13c883c3ce461"
+ );
+ assert_eq!(
+ mutation.source_id(),
+ "source/managed-c71f3083486a232251e0c7f1"
+ );
+ assert_eq!(mutation.desired().unwrap().models.len(), 2);
+ assert_eq!(mutation.desired().unwrap().credentials.len(), 1);
+}
diff --git a/crates/local-storage/src/control/compute/management/tests/removal_guards.rs b/crates/local-storage/src/control/compute/management/tests/removal_guards.rs
new file mode 100644
index 00000000..705fac08
--- /dev/null
+++ b/crates/local-storage/src/control/compute/management/tests/removal_guards.rs
@@ -0,0 +1,210 @@
+//! Exercise the real Control effect boundary, including a reference arriving after preview.
+use super::lifecycle::{edit, saved};
+use super::*;
+use hiroute_application_api::ComputeManagementEditV1;
+use hiroute_domain::{
+ ComputeManagementRepositoryPort, OperationId, PlanDraftV1, TransactionPlanV1,
+};
+
+fn referencing_draft(binding: &str) -> PlanDraftV1 {
+ serde_json::from_value(serde_json::json!({
+ "schema":"hiroute.plan-draft/v1", "workspace_id":WorkspaceId::DEFAULT,
+ "draft_id":"draft/model-removal", "revision":1,
+ "editor":{"schema":"hiroute.plan-editor/v2", "display_name":"Using a model", "purpose":"",
+ "mode":"fixed_model", "candidates":[{"binding_id":binding}],
+ "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":{},"limits":{"maximum_attempts":6,"request_timeout_ms":60000,"attempt_timeout_ms":30000}}
+ })).unwrap()
+}
+
+#[test]
+fn reference_added_after_preview_blocks_stage_and_added_after_stage_blocks_activation() {
+ let root = tempdir().unwrap();
+ populate_saved_source(root.path(), &WorkspaceId::default());
+ let stores = LocalStorageSet::open_for_daemon_startup(root.path()).unwrap();
+ let source = saved(&stores);
+ let registry = TrustedComputeCandidateRegistry::new();
+ let input = ProtectedInput;
+ let planner =
+ ComputeManagementPlanner::new(&registry, stores.control(), stores.secrets(), &input);
+ let preview = planner
+ .preview(edit(&stores, &source, ComputeManagementEditV1::Delete, &[]))
+ .unwrap();
+ let workspace = WorkspaceId::default();
+ let operation = OperationId::parse("op_55555555555555555555555555555555").unwrap();
+ seed_operation(&stores, &operation, preview.plan());
+ let draft = referencing_draft(&source.models[0].binding_id);
+ stores.control().save_plan_draft(&draft, None).unwrap();
+ let referenced = planner
+ .preview(edit(&stores, &source, ComputeManagementEditV1::Delete, &[]))
+ .unwrap();
+ assert_eq!(
+ referenced.result.affected_plan_refs,
+ vec![draft.draft_id.clone()]
+ );
+ assert!(
+ planner
+ .prepare_apply(ComputeConnectionApplyRequestV1 {
+ spec: preview.result.spec.clone(),
+ accept_digest: preview.result.accept_digest.clone(),
+ expected_revisions: preview.result.expected_revisions.clone(),
+ idempotency_key: "delete-stale".into()
+ })
+ .is_err()
+ );
+ assert!(
+ stores
+ .control()
+ .apply_control(
+ &operation,
+ &workspace,
+ preview.result.expected_revisions.target,
+ preview.plan().control()
+ )
+ .is_err()
+ );
+ stores
+ .control()
+ .discard_plan_draft(&workspace, &draft.draft_id, 1)
+ .unwrap();
+ let staged = stores
+ .control()
+ .apply_control(
+ &operation,
+ &workspace,
+ preview.result.expected_revisions.target,
+ preview.plan().control(),
+ )
+ .unwrap();
+ stores.control().save_plan_draft(&draft, None).unwrap();
+ assert!(stores.control().activate_control(&staged).is_err());
+ assert_eq!(saved(&stores), source);
+}
+
+#[test]
+fn deleted_source_compensation_restores_exact_bytes_but_cannot_win_after_later_create_delete() {
+ let root = tempdir().unwrap();
+ populate_saved_source(root.path(), &WorkspaceId::default());
+ let stores = LocalStorageSet::open_for_daemon_startup(root.path()).unwrap();
+ let source = saved(&stores);
+ let registry = TrustedComputeCandidateRegistry::new();
+ let input = ProtectedInput;
+ let planner =
+ ComputeManagementPlanner::new(&registry, stores.control(), stores.secrets(), &input);
+ let workspace = WorkspaceId::default();
+ let stage = |plan: &TransactionPlanV1, id: &str| {
+ let revision = stores
+ .control()
+ .current_revisions(&workspace)
+ .unwrap()
+ .target;
+ let operation = OperationId::parse(id).unwrap();
+ seed_operation(&stores, &operation, plan);
+ let effect = stores
+ .control()
+ .apply_control(&operation, &workspace, revision, plan.control())
+ .unwrap();
+ stores.control().activate_control(&effect).unwrap();
+ effect
+ };
+ let deletion = planner
+ .preview(edit(&stores, &source, ComputeManagementEditV1::Delete, &[]))
+ .unwrap();
+ let effect = stage(deletion.plan(), "op_11111111111111111111111111111111");
+ assert!(
+ stores
+ .control()
+ .compute_management_source(&source.source_id)
+ .unwrap()
+ .is_none()
+ );
+ assert_eq!(
+ stores.control().compensate_control(&effect).unwrap(),
+ CompensationOutcome::Compensated
+ );
+ assert_eq!(saved(&stores), source);
+ let deletion = planner
+ .preview(edit(&stores, &source, ComputeManagementEditV1::Delete, &[]))
+ .unwrap();
+ let old_effect = stage(deletion.plan(), "op_22222222222222222222222222222222");
+ // Same lineage can be imported again. Its later delete must never give the old delete
+ // ownership merely because both operations leave the source row absent.
+ let mut recreated = source.clone();
+ recreated.revision = 1;
+ recreated.credentials.clear();
+ recreated.state = MaterializationState::NeedsCredential;
+ let spec = hiroute_domain::ChangeSpecV1 {
+ schema_version: hiroute_domain::CHANGE_SPEC_SCHEMA_V1,
+ command_id: "compute.connection.apply".into(),
+ resource_id: Some(source.source_id.clone()),
+ desired_state: serde_json::to_value(ComputeManagementChangeV2 {
+ schema: "hiroute.compute-management-change/v2".into(),
+ subject: ComputeManagementSubjectV2::Candidate {
+ candidate: candidate("candidate/new-owner", "slot/primary").candidate,
+ },
+ expected_revisions: stores.control().current_revisions(&workspace).unwrap(),
+ selected_model_refs: recreated
+ .models
+ .iter()
+ .map(|model| model.model_ref.clone())
+ .collect(),
+ intent: ComputeManagementIntentV2::SaveReady,
+ key_edits: Vec::new(),
+ validation: None,
+ edit: None,
+ })
+ .unwrap(),
+ };
+ let creation = TransactionPlanV1::from_compute_management_change(
+ spec,
+ None,
+ Some(recreated.clone()),
+ Vec::new(),
+ )
+ .unwrap();
+ stage(&creation, "op_33333333333333333333333333333333");
+ let deletion = planner
+ .preview(edit(
+ &stores,
+ &recreated,
+ ComputeManagementEditV1::Delete,
+ &[],
+ ))
+ .unwrap();
+ stage(deletion.plan(), "op_44444444444444444444444444444444");
+ assert_eq!(
+ stores.control().compensate_control(&old_effect).unwrap(),
+ CompensationOutcome::OwnershipLost
+ );
+ assert!(
+ stores
+ .control()
+ .compute_management_source(&source.source_id)
+ .unwrap()
+ .is_none()
+ );
+}
+
+fn seed_operation(stores: &LocalStorageSet, id: &OperationId, plan: &TransactionPlanV1) {
+ // This is a storage effect interleaving test, not coordinator admission evidence.
+ // Keep a well-formed parent journal so the management effect's FK is exercised.
+ let digest = CanonicalDigest::of_bytes(id.as_str().as_bytes());
+ let operation = OperationV1::new(
+ id.clone(),
+ WorkspaceId::default(),
+ hiroute_domain::IdempotencyScopeV1::new("local-control", "ApplyComputeSave", id.as_str())
+ .unwrap(),
+ digest.clone(),
+ digest.clone(),
+ stores
+ .control()
+ .current_revisions(&WorkspaceId::default())
+ .unwrap(),
+ plan.clone(),
+ )
+ .unwrap();
+ stores.control().with_connection(|connection| connection.execute(
+ "INSERT INTO operations(operation_id,workspace_id,principal,operation_kind,idempotency_key,request_digest,accepted_change_digest,state,generation,operation_json,created_at,updated_at) VALUES(?1,?2,'local-control','ApplyComputeSave',?1,?3,?3,'accepted',1,?4,1,1)",
+ rusqlite::params![id.as_str(),WorkspaceId::DEFAULT,digest.as_str(),serde_json::to_string(&operation).unwrap()]).unwrap());
+}
diff --git a/crates/local-storage/src/control/compute/management/tests/runtime_leases.rs b/crates/local-storage/src/control/compute/management/tests/runtime_leases.rs
index 6c774a11..66ba7a0a 100644
--- a/crates/local-storage/src/control/compute/management/tests/runtime_leases.rs
+++ b/crates/local-storage/src/control/compute/management/tests/runtime_leases.rs
@@ -23,6 +23,7 @@ fn save(
ComputeManagementPlanner::new(registry, stores.control(), stores.secrets(), &input);
let preview = planner
.preview(ComputeManagementChangeV2 {
+ edit: None,
schema: "hiroute.compute-management-change/v2".into(),
subject,
expected_revisions: snapshot.revisions,
@@ -52,7 +53,7 @@ fn save(
.remove(0)
}
-fn frozen_request(
+pub(super) fn frozen_request(
source: &ComputeManagementSourceV2,
model: usize,
credential: usize,
diff --git a/crates/local-storage/src/control/compute/management/tests/subscription_selection.rs b/crates/local-storage/src/control/compute/management/tests/subscription_selection.rs
index b5ca59e8..dd50b68a 100644
--- a/crates/local-storage/src/control/compute/management/tests/subscription_selection.rs
+++ b/crates/local-storage/src/control/compute/management/tests/subscription_selection.rs
@@ -47,6 +47,7 @@ fn change(
selected: &[&str],
) -> ComputeManagementChangeV2 {
ComputeManagementChangeV2 {
+ edit: None,
schema: "hiroute.compute-management-change/v2".into(),
subject: ComputeManagementSubjectV2::Candidate {
candidate: facts.candidate.clone(),
@@ -63,13 +64,12 @@ fn change(
}
}
-fn save(
+fn register_verified_subscription(
stores: &LocalStorageSet,
registry: &TrustedComputeCandidateRegistry,
facts: &ComputeCandidateFactsV2,
- selected: &[&str],
key: &str,
-) -> hiroute_domain::ComputeManagementSourceV2 {
+) {
// This storage test starts at verified subscription facts. Admission still uses
// the real durable handoff and transaction; the daemon tests cover the check.
let validation = facts.validation.as_ref().unwrap();
@@ -100,6 +100,16 @@ fn save(
.unwrap();
});
registry.register_compute_candidate(facts.clone()).unwrap();
+}
+
+fn save(
+ stores: &LocalStorageSet,
+ registry: &TrustedComputeCandidateRegistry,
+ facts: &ComputeCandidateFactsV2,
+ selected: &[&str],
+ key: &str,
+) -> hiroute_domain::ComputeManagementSourceV2 {
+ register_verified_subscription(stores, registry, facts, key);
let input = ProtectedInput;
let planner =
ComputeManagementPlanner::new(registry, stores.control(), stores.secrets(), &input);
@@ -407,3 +417,243 @@ fn subscription_recheck_and_background_refresh_retain_membership_when_rights_cha
.is_empty()
);
}
+
+#[test]
+fn removed_subscription_cannot_be_resurrected_by_late_maintenance_or_checked_candidate() {
+ let root = tempdir().unwrap();
+ let stores = LocalStorageSet::open_for_daemon_startup(root.path()).unwrap();
+ let registry = TrustedComputeCandidateRegistry::new();
+ let source = save(
+ &stores,
+ &registry,
+ &subscription("candidate/first"),
+ &["model/one"],
+ "first",
+ );
+ let mut checked = subscription("candidate/late");
+ checked.existing_source_id = Some(source.source_id.clone());
+ registry
+ .register_compute_candidate(checked.clone())
+ .unwrap();
+ let old = change(&stores, &checked, &["model/one"]);
+ // Native login files belong to the connector. Management deletion has only Control
+ // and owned Secret effects; it has no External or Runtime mutation authority.
+ let input = ProtectedInput;
+ let planner =
+ ComputeManagementPlanner::new(&registry, stores.control(), stores.secrets(), &input);
+ let deletion = super::lifecycle::edit(
+ &stores,
+ &source,
+ hiroute_application_api::ComputeManagementEditV1::Delete,
+ &[],
+ );
+ let preview = planner.preview(deletion.clone()).unwrap();
+ assert!(preview.plan().secrets().is_empty());
+ assert!(preview.plan().external().is_empty());
+ assert!(preview.plan().runtime().is_empty());
+ super::lifecycle::execute(&stores, &registry, deletion, "delete-subscription");
+ let scope = ComputeSubscriptionMaintenanceScopeV1 {
+ source_id: source.source_id,
+ expected_source_revision: source.revision,
+ };
+ assert!(planner.preview(old).is_err());
+ let refreshed = change(&stores, &checked, &["model/one"]);
+ assert!(matches!(
+ planner.preview(refreshed.clone()),
+ Err(ComputeManagementPlanningErrorV2::SourceNotFound)
+ ));
+ assert!(
+ planner
+ .preview_subscription_maintenance(refreshed, &scope)
+ .is_err()
+ );
+ assert!(
+ stores
+ .control()
+ .compute_management_snapshot(&WorkspaceId::default())
+ .unwrap()
+ .sources
+ .is_empty()
+ );
+}
+
+#[test]
+fn subscription_v3_mode_tracks_lifecycle_revisions_and_never_revives_after_delete() {
+ use super::lifecycle::{edit, execute, saved};
+ use hiroute_application::compute_management::{
+ query_compute_management, query_compute_management_v3,
+ };
+ use hiroute_application_api::{
+ ComputeManagementEditV1, ComputeManagementQueryV2, ComputeSubscriptionModeV1,
+ };
+
+ for managed in [false, true] {
+ let root = tempdir().unwrap();
+ let stores = LocalStorageSet::open_for_daemon_startup(root.path()).unwrap();
+ let registry = TrustedComputeCandidateRegistry::new();
+ let expected = if managed {
+ ComputeSubscriptionModeV1::CpaManaged
+ } else {
+ ComputeSubscriptionModeV1::NativeBorrowed
+ };
+ let facts_for = |label: &str| {
+ let mode = if managed { "managed/" } else { "" };
+ let mut facts = subscription(&format!("candidate/cpa/codex/{mode}{label}"));
+ facts.provenance = ComputeCandidateProvenanceV2::ConnectorOwned {
+ connector_id: "connector.cpa.codex".into(),
+ account_ref: "account/subscription".into(),
+ };
+ facts
+ };
+ let assert_mode = |source: &hiroute_domain::ComputeManagementSourceV2| {
+ let query = ComputeManagementQueryV2::default();
+ let v3 = query_compute_management_v3(
+ stores.control(),
+ stores.runtime(),
+ &WorkspaceId::default(),
+ &query,
+ None,
+ )
+ .unwrap();
+ assert_eq!(v3.subscription_modes.len(), 1);
+ let mode = &v3.subscription_modes[0];
+ assert_eq!(mode.source_id, source.source_id);
+ assert_eq!(mode.source_revision, source.revision);
+ assert_eq!(mode.mode, expected);
+ let v2 = query_compute_management(
+ stores.control(),
+ stores.runtime(),
+ &WorkspaceId::default(),
+ &query,
+ )
+ .unwrap();
+ assert_eq!(v3.into_v2(), v2);
+ assert!(
+ serde_json::to_value(v2)
+ .unwrap()
+ .get("subscription_modes")
+ .is_none()
+ );
+ };
+ let original = save(
+ &stores,
+ &registry,
+ &facts_for("first"),
+ &["model/one"],
+ "first-mode",
+ );
+ assert_mode(&original);
+ execute(
+ &stores,
+ &registry,
+ edit(
+ &stores,
+ &original,
+ ComputeManagementEditV1::Rename {
+ display_name: "Subscription team".into(),
+ },
+ &[],
+ ),
+ "rename-mode",
+ );
+ let named = saved(&stores);
+ assert_eq!(named.display_name, "Subscription team");
+ assert!(named.revision > original.revision);
+ assert_eq!(named.source_id, original.source_id);
+ assert_eq!(named.models, original.models);
+ assert_mode(&named);
+
+ // These are verified-check storage fixtures, not native OAuth or inference evidence.
+ let mut latest_validation = facts_for("first").validation;
+ for (label, model_ref, upstream, disabled) in [
+ ("ready-append", "model/two", "upstream-two", false),
+ ("disabled-append", "model/three", "upstream-three", true),
+ ] {
+ let before = saved(&stores);
+ if disabled {
+ let mut disable = edit(&stores, &before, ComputeManagementEditV1::Delete, &[]);
+ disable.edit = None;
+ disable.intent = ComputeManagementIntentV2::SaveDisabled;
+ disable.validation = latest_validation.clone();
+ disable.selected_model_refs =
+ before.models.iter().map(|m| m.model_ref.clone()).collect();
+ execute(&stores, &registry, disable, "disable-mode");
+ }
+ let before = saved(&stores);
+ assert_mode(&before);
+ let mut facts = facts_for(label);
+ facts.existing_source_id = Some(before.source_id.clone());
+ let mut extra = facts.models[0].clone();
+ extra.model_ref = model_ref.into();
+ extra.upstream_model_id = upstream.into();
+ facts.models.retain(|model| model.model_ref != model_ref);
+ facts.models.push(extra);
+ register_verified_subscription(&stores, &registry, &facts, label);
+ latest_validation = facts.validation.clone();
+ let mut append = change(&stores, &facts, &[model_ref]);
+ append.edit = Some(ComputeManagementEditV1::AppendModels);
+ execute(&stores, &registry, append, label);
+ let after = saved(&stores);
+ assert_eq!(after.source_id, before.source_id);
+ assert_eq!(after.display_name, named.display_name);
+ assert_eq!(after.state, before.state);
+ assert_eq!(after.credentials, before.credentials);
+ assert_eq!(&after.models[..before.models.len()], &before.models);
+ assert_eq!(after.models.len(), before.models.len() + 1);
+ assert_mode(&after);
+ }
+ let disabled = saved(&stores);
+ assert_eq!(disabled.state, MaterializationState::Disabled);
+ let mut late = facts_for("late-maintenance");
+ late.existing_source_id = Some(disabled.source_id.clone());
+ register_verified_subscription(&stores, &registry, &late, "late-mode");
+ let scope = ComputeSubscriptionMaintenanceScopeV1 {
+ source_id: disabled.source_id.clone(),
+ expected_source_revision: disabled.revision,
+ };
+ let input = ProtectedInput;
+ let planner =
+ ComputeManagementPlanner::new(&registry, stores.control(), stores.secrets(), &input);
+ assert!(matches!(
+ planner
+ .preview_subscription_maintenance(change(&stores, &late, &["model/one"]), &scope),
+ Err(ComputeManagementPlanningErrorV2::RevisionConflict)
+ ));
+ assert_eq!(saved(&stores), disabled);
+ let captured = change(&stores, &late, &["model/one"]);
+ execute(
+ &stores,
+ &registry,
+ edit(&stores, &disabled, ComputeManagementEditV1::Delete, &[]),
+ "delete-mode",
+ );
+ assert!(planner.preview(captured).is_err());
+ assert!(matches!(
+ planner
+ .preview_subscription_maintenance(change(&stores, &late, &["model/one"]), &scope),
+ Err(ComputeManagementPlanningErrorV2::SourceNotFound)
+ ));
+ let v3 = query_compute_management_v3(
+ stores.control(),
+ stores.runtime(),
+ &WorkspaceId::default(),
+ &ComputeManagementQueryV2::default(),
+ None,
+ )
+ .unwrap();
+ assert!(v3.sources.is_empty());
+ assert!(v3.subscription_modes.is_empty());
+ drop(stores);
+ let reopened = LocalStorageSet::open_for_daemon_startup(root.path()).unwrap();
+ let v3 = query_compute_management_v3(
+ reopened.control(),
+ reopened.runtime(),
+ &WorkspaceId::default(),
+ &ComputeManagementQueryV2::default(),
+ None,
+ )
+ .unwrap();
+ assert!(v3.sources.is_empty());
+ assert!(v3.subscription_modes.is_empty());
+ }
+}
diff --git a/crates/local-storage/src/control/mod.rs b/crates/local-storage/src/control/mod.rs
index eb17f5aa..9d7752c7 100644
--- a/crates/local-storage/src/control/mod.rs
+++ b/crates/local-storage/src/control/mod.rs
@@ -1456,6 +1456,14 @@ impl ControlRepositoryPort for ControlStore {
Ok(CompensationOutcome::Compensated)
}
+ fn reconcile_compute_compensation(
+ &self,
+ operation: &OperationV1,
+ references: &[hiroute_domain::CredentialRefV1],
+ ) -> PortResult<()> {
+ compute::management::reconcile_compensation(self, operation, references)
+ }
+
fn finish_operation(&self, operation: &mut OperationV1) -> PortResult<u64> {
if !operation.state.is_terminal() {
return Err(port(
diff --git a/crates/local-storage/src/control/plans/holds.rs b/crates/local-storage/src/control/plans/holds.rs
index 05cde51b..9c5cc082 100644
--- a/crates/local-storage/src/control/plans/holds.rs
+++ b/crates/local-storage/src/control/plans/holds.rs
@@ -3,6 +3,12 @@ use hiroute_domain::{VersionOwnerRefV1, VersionReservationV1};
use std::collections::BTreeSet;
impl ControlStore {
+ pub fn require_plan_version_recovery_ready(
+ &self,
+ workspace: &WorkspaceId,
+ ) -> Result<(), PlanVersionError> {
+ require_ready(&self.connection.borrow(), workspace)
+ }
/// Lifecycle deletion considers every revision, including old continuation holds and
/// prepared content. An unfinished recovery cannot prove that no owner remains.
pub fn plan_has_retained_versions(
diff --git a/crates/local-storage/src/control/plans/tests.rs b/crates/local-storage/src/control/plans/tests.rs
index 9b688ce9..68d93769 100644
--- a/crates/local-storage/src/control/plans/tests.rs
+++ b/crates/local-storage/src/control/plans/tests.rs
@@ -246,3 +246,134 @@ fn crash_reservation_without_runtime_acceptance_is_reclaimed_only_after_expiry_a
.reclaim_plan_version(&version.reference)
.unwrap();
}
+
+#[test]
+fn compute_removal_references_include_disabled_heads_and_continuations_but_not_unheld_history() {
+ let root = tempdir().unwrap();
+ let stores = crate::LocalStorageSet::open_for_daemon_startup(root.path()).unwrap();
+ let store = stores.control();
+ let version = version();
+ let workspace = WorkspaceId::default();
+ let bindings = vec![
+ version.compiled.body.materialized.attempt_owned.groups[0].candidates[0]
+ .binding_id
+ .clone(),
+ ];
+ seed(store, &version);
+ assert!(
+ store
+ .compute_management_references(&workspace, &bindings)
+ .is_err(),
+ "unreconciled recovery fails closed"
+ );
+ store.reconcile_plan_versions(&workspace, &[], 1).unwrap();
+ assert!(
+ store
+ .compute_management_references(&workspace, &bindings)
+ .unwrap()
+ .is_empty()
+ );
+ let mut head = PlanHeadV1 {
+ reference: version.reference.clone(),
+ head_revision: version.reference.content_revision,
+ model_alias: version.compiled.model_alias().clone(),
+ status: PlanLifecycleV1::Disabled,
+ };
+ let save_head = |head: &PlanHeadV1| {
+ store.connection.borrow().execute(
+ "INSERT OR REPLACE INTO plan_heads(workspace_id,plan_id,head_revision,head_json) VALUES(?1,?2,?3,?4)",
+ params![workspace.as_str(), version.reference.plan_id.as_str(), head.head_revision, encode(head).unwrap()]).unwrap()
+ };
+ save_head(&head);
+ assert_eq!(
+ store
+ .compute_management_references(&workspace, &bindings)
+ .unwrap(),
+ vec![version.reference.plan_id.as_str()]
+ );
+ head.status = PlanLifecycleV1::Deleted;
+ save_head(&head);
+ assert!(
+ store
+ .compute_management_references(&workspace, &bindings)
+ .unwrap()
+ .is_empty()
+ );
+ let mut hold = reservation(&version, "task/continuation");
+ hold.owner.kind = VersionOwnerKindV1::Task;
+ hold.owner.purpose = VersionOwnerPurposeV1::Continuation;
+ store.acquire_exact_plan_version(&hold).unwrap();
+ assert_eq!(
+ store
+ .compute_management_references(&workspace, &bindings)
+ .unwrap(),
+ vec![version.reference.plan_id.as_str()]
+ );
+ store.release_plan_version(&workspace, &hold.owner).unwrap();
+ assert!(
+ store
+ .compute_management_references(&workspace, &bindings)
+ .unwrap()
+ .is_empty()
+ );
+ store
+ .connection
+ .borrow()
+ .execute("UPDATE plan_versions SET state='prepared'", [])
+ .unwrap();
+ assert_eq!(
+ store
+ .compute_management_references(&workspace, &bindings)
+ .unwrap(),
+ vec![version.reference.plan_id.as_str()]
+ );
+}
+
+#[test]
+fn compute_references_decode_production_publication_bytes_and_protect_recovery_lkg() {
+ let root = tempdir().unwrap();
+ let stores = crate::LocalStorageSet::open_for_daemon_startup(root.path()).unwrap();
+ let store = stores.control();
+ let workspace = WorkspaceId::default();
+ let publication: GatewayPublicationV1 = serde_json::from_str(include_str!(
+ "../../../../../e2e/product/fixtures/routing/current-publication.v3.json"
+ ))
+ .unwrap();
+ let plan = publication
+ .plans
+ .iter()
+ .find(|plan| plan.agent_plan_id().as_str() == "plan/custom")
+ .unwrap();
+ let bindings = vec![
+ plan.body.materialized.attempt_owned.groups[0].candidates[0]
+ .binding_id
+ .clone(),
+ ];
+ let bytes = publication.canonical_bytes().unwrap();
+ store.connection.borrow().execute("INSERT INTO gateway_publications(workspace_id,publication_revision,digest,publication_bytes,state,created_at,updated_at) VALUES(?1,1,?2,?3,'active',1,1)", params![workspace.as_str(),CanonicalDigest::of_bytes(&bytes).as_str(),bytes]).unwrap();
+ for state in ["active", "prepared", "lkg"] {
+ store
+ .connection
+ .borrow()
+ .execute("UPDATE gateway_publications SET state=?1", [state])
+ .unwrap();
+ assert!(
+ store
+ .compute_management_references(&workspace, &bindings)
+ .unwrap()
+ .contains(&"plan/custom".to_owned()),
+ "{state}"
+ );
+ }
+ store
+ .connection
+ .borrow()
+ .execute("UPDATE gateway_publications SET state='historical'", [])
+ .unwrap();
+ assert!(
+ store
+ .compute_management_references(&workspace, &bindings)
+ .unwrap()
+ .is_empty()
+ );
+}
diff --git a/crates/local-storage/src/secrets/compensation.rs b/crates/local-storage/src/secrets/compensation.rs
new file mode 100644
index 00000000..92060fee
--- /dev/null
+++ b/crates/local-storage/src/secrets/compensation.rs
@@ -0,0 +1,101 @@
+//! Authenticated proof of the current reference after an exact owned compensation.
+use super::*;
+
+pub(super) fn restored_reference(
+ store: &LocalSecretStore,
+ operation: &OperationId,
+ mutation: &SecretMutationV1,
+) -> PortResult<Option<CredentialRefV1>> {
+ let connection = store.connection.borrow();
+ let original = mutation.credential();
+ let record = read_effect(&connection, operation.as_str(), original.credential_id())?;
+ let Some(record) = record else {
+ // A failure before staging did not mutate this key. Authenticate the exact
+ // original reference; never follow a newer generation just because it exists.
+ let Some(row) = read_entry(&connection, original.credential_id())? else {
+ return Ok(None);
+ };
+ store.validate_reference(original, &row)?;
+ if row.generation != original.generation()
+ || read_head(&connection, original.credential_id())? != row.generation
+ {
+ return Err(port(
+ PortErrorCode::Conflict,
+ "secret.compensation_reference.unstaged",
+ ));
+ }
+ store.authenticate_row(&row)?;
+ return Ok(Some(original.clone()));
+ };
+ if !record.compensated
+ || record.owner_scope != original.owner_scope()
+ || record.before_generation != mutation.expected_generation()
+ || record.after_exists != (mutation.kind() != SecretMutationKind::Delete)
+ {
+ return Err(port(
+ PortErrorCode::Conflict,
+ "secret.compensation_reference.effect",
+ ));
+ }
+ if !record.before_exists {
+ return Ok(None);
+ }
+ store.authenticate_before(&record)?;
+ store.authenticate_staged(&record)?;
+ let generation = if record.activated {
+ record.after_generation.checked_add(1).ok_or_else(|| {
+ port(
+ PortErrorCode::Conflict,
+ "secret.compensation_reference.overflow",
+ )
+ })?
+ } else {
+ record.before_generation
+ };
+ let before = record
+ .before_row(generation, operation.as_str())?
+ .ok_or_else(|| {
+ port(
+ PortErrorCode::Corrupt,
+ "secret.compensation_reference.before",
+ )
+ })?;
+ let reference = CredentialRefV1::new(
+ &before.credential_id,
+ &before.owner_scope,
+ &before.subject,
+ &before.purpose,
+ parse_destinations(&before.allowed_destinations_json)?,
+ generation,
+ )
+ .map_err(|_| {
+ port(
+ PortErrorCode::Corrupt,
+ "secret.compensation_reference.authority",
+ )
+ })?;
+ let row = read_entry(&connection, original.credential_id())?.ok_or_else(|| {
+ port(
+ PortErrorCode::NotFound,
+ "secret.compensation_reference.missing",
+ )
+ })?;
+ store.validate_reference(&reference, &row)?;
+ if row.generation != generation
+ || read_head(&connection, original.credential_id())? != generation
+ || row.fingerprint != before.fingerprint
+ || row.owner_operation_id
+ != if record.activated {
+ operation.as_str()
+ } else {
+ before.owner_operation_id.as_str()
+ }
+ {
+ return Err(port(
+ PortErrorCode::Conflict,
+ "secret.compensation_reference.owner",
+ ));
+ }
+ store.authenticate_row(&row)?;
+ Ok(Some(reference))
+}
diff --git a/crates/local-storage/src/secrets/delete_recovery_tests.rs b/crates/local-storage/src/secrets/delete_recovery_tests.rs
new file mode 100644
index 00000000..e2792cc7
--- /dev/null
+++ b/crates/local-storage/src/secrets/delete_recovery_tests.rs
@@ -0,0 +1,132 @@
+use super::*;
+
+fn reference(generation: u64) -> CredentialRefV1 {
+ CredentialRefV1::new(
+ "delete-key",
+ "delete-owner",
+ "hirouted",
+ "provider-auth",
+ ["provider-api".to_owned()],
+ generation,
+ )
+ .unwrap()
+}
+
+fn operation(value: char) -> OperationId {
+ OperationId::parse(format!("op_{}", value.to_string().repeat(32))).unwrap()
+}
+
+fn open(root: &Path) -> Result<LocalSecretStore, LocalStorageError> {
+ LocalSecretStore::open(
+ &crate::test_storage_authority(),
+ root.join("secrets.db"),
+ root.join("master-key"),
+ root.join("backups"),
+ )
+}
+
+#[test]
+fn compute_delete_secret_journal_reopens_when_staged_activated_or_compensated() {
+ for phase in 0..3 {
+ let directory = crate::test_tempdir().unwrap();
+ let root = directory.path().join("data");
+ let store = open(&root).unwrap();
+ let secret = ProtectedSecret::new(b"delete-recovery-fixture".to_vec()).unwrap();
+ let save = SecretMutationV1::upsert(
+ reference(0),
+ 0,
+ "input",
+ Some(store.fingerprint(&secret).unwrap()),
+ )
+ .unwrap();
+ let saved = store
+ .apply_secret(&operation('1'), &save, Some(&secret))
+ .unwrap();
+ store.activate_secret(&saved).unwrap();
+ let delete = SecretMutationV1::delete(reference(1), 1).unwrap();
+ let effect = store.apply_secret(&operation('2'), &delete, None).unwrap();
+ if phase > 0 {
+ store.activate_secret(&effect).unwrap();
+ }
+ if phase == 2 {
+ store.compensate_secret(&effect).unwrap();
+ }
+ drop(store);
+ let reopened = open(&root).expect("metadata-only delete journal must reopen");
+ let observed = reopened.observe_secret(&operation('2'), &delete).unwrap();
+ match phase {
+ 0 => assert!(matches!(observed, EffectReconciliation::Staged(_))),
+ 1 => assert!(matches!(observed, EffectReconciliation::Applied(_))),
+ _ => assert!(matches!(observed, EffectReconciliation::Missing)),
+ }
+ assert_eq!(
+ read_entry(&reopened.connection.borrow(), "delete-key")
+ .unwrap()
+ .is_some(),
+ phase != 1
+ );
+ if phase == 2 {
+ let restored = reopened
+ .compensated_secret_reference(&operation('2'), &delete)
+ .unwrap()
+ .unwrap();
+ assert_eq!(restored, reference(3));
+ let replacement = SecretMutationV1::upsert(
+ restored,
+ 3,
+ "input",
+ Some(reopened.fingerprint(&secret).unwrap()),
+ )
+ .unwrap();
+ let newer = reopened
+ .apply_secret(&operation('4'), &replacement, Some(&secret))
+ .unwrap();
+ reopened.activate_secret(&newer).unwrap();
+ assert!(
+ reopened
+ .compensated_secret_reference(&operation('2'), &delete)
+ .is_err(),
+ "same value under a newer owner must not prove old compensation"
+ );
+ assert_eq!(reopened.generation(&reference(4)).unwrap(), 4);
+ }
+ }
+}
+
+#[test]
+fn compute_delete_secret_journal_with_unexpected_or_corrupt_ciphertext_stays_locked() {
+ for column in [
+ "staged_ciphertext",
+ "staged_nonce",
+ "before_ciphertext",
+ "before_nonce",
+ ] {
+ let directory = crate::test_tempdir().unwrap();
+ let root = directory.path().join("data");
+ let store = open(&root).unwrap();
+ let secret = ProtectedSecret::new(b"delete-authentication-fixture".to_vec()).unwrap();
+ let save = SecretMutationV1::upsert(
+ reference(0),
+ 0,
+ "input",
+ Some(store.fingerprint(&secret).unwrap()),
+ )
+ .unwrap();
+ let saved = store
+ .apply_secret(&operation('1'), &save, Some(&secret))
+ .unwrap();
+ store.activate_secret(&saved).unwrap();
+ let delete = SecretMutationV1::delete(reference(1), 1).unwrap();
+ store.apply_secret(&operation('3'), &delete, None).unwrap();
+ store
+ .connection
+ .borrow()
+ .execute(
+ &format!("UPDATE secret_effects SET {column}=X'00' WHERE operation_id=?1"),
+ [operation('3').as_str()],
+ )
+ .unwrap();
+ drop(store);
+ assert!(matches!(open(&root), Err(LocalStorageError::Locked)));
+ }
+}
diff --git a/crates/local-storage/src/secrets/mod.rs b/crates/local-storage/src/secrets/mod.rs
index 81858d1c..b2fe18d0 100644
--- a/crates/local-storage/src/secrets/mod.rs
+++ b/crates/local-storage/src/secrets/mod.rs
@@ -29,6 +29,7 @@ use crate::{DaemonStorageAuthority, LocalStorageError};
mod collaboration_bootstrap;
#[path = "../agents/collaboration_credentials.rs"]
mod collaboration_credentials;
+mod compensation;
mod grant;
pub(crate) use grant::integrity::validate as validate_stable_grants;
#[cfg(test)]
@@ -312,6 +313,13 @@ fn has_backup_evidence(
}
impl SecretStorePort for LocalSecretStore {
+ fn compensated_secret_reference(
+ &self,
+ operation_id: &OperationId,
+ mutation: &SecretMutationV1,
+ ) -> PortResult<Option<CredentialRefV1>> {
+ compensation::restored_reference(self, operation_id, mutation)
+ }
fn generation(&self, credential: &CredentialRefV1) -> PortResult<u64> {
let connection = self.connection.borrow();
if let Some(row) = read_entry(&connection, credential.credential_id())? {
@@ -767,11 +775,18 @@ impl SecretStorePort for LocalSecretStore {
self.encrypt(&credential, &before.kind, restored_generation, &plaintext)?;
transaction
.execute(
- "UPDATE secret_entries SET owner_scope = ?2, kind = ?3, ciphertext = ?4,
- nonce = ?5, aad_schema = ?6, key_version = ?7, fingerprint = ?8,
- generation = ?9, owner_operation_id = ?10, subject = ?11,
- purpose = ?12, allowed_destinations_json = ?13, updated_at = unixepoch()
- WHERE credential_id = ?1",
+ "INSERT INTO secret_entries (credential_id, owner_scope, kind, ciphertext,
+ nonce, aad_schema, key_version, fingerprint, generation, owner_operation_id,
+ subject, purpose, allowed_destinations_json, created_at, updated_at)
+ VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,unixepoch(),unixepoch())
+ ON CONFLICT(credential_id) DO UPDATE SET
+ owner_scope=excluded.owner_scope, kind=excluded.kind,
+ ciphertext=excluded.ciphertext, nonce=excluded.nonce,
+ aad_schema=excluded.aad_schema, key_version=excluded.key_version,
+ fingerprint=excluded.fingerprint, generation=excluded.generation,
+ owner_operation_id=excluded.owner_operation_id, subject=excluded.subject,
+ purpose=excluded.purpose, allowed_destinations_json=excluded.allowed_destinations_json,
+ updated_at=excluded.updated_at",
params![
credential_id,
&before.owner_scope,
@@ -1216,6 +1231,14 @@ fn migrate_legacy_secret_aad(
));
}
}
+ // Delete producers retain format metadata, but never a staged secret.
+ // The before image above still needs authentication for compensation.
+ if !record.after_exists {
+ if record.staged_ciphertext.is_some() || record.staged_nonce.is_some() {
+ return Err(LocalStorageError::Locked);
+ }
+ continue;
+ }
let staged_present = record.staged_ciphertext.is_some()
|| record.staged_nonce.is_some()
|| record.staged_aad_schema.is_some()
@@ -1872,6 +1895,9 @@ fn port(code: PortErrorCode, context: &'static str) -> PortError {
PortError::new(code, context)
}
+#[cfg(test)]
+mod delete_recovery_tests;
+
#[cfg(test)]
mod tests {
use crate::test_tempdir as tempdir;
diff --git a/crates/local-storage/tests/fixtures/v0.2.0-compute-operation.json b/crates/local-storage/tests/fixtures/v0.2.0-compute-operation.json
new file mode 100644
index 00000000..fa2b0765
--- /dev/null
+++ b/crates/local-storage/tests/fixtures/v0.2.0-compute-operation.json
@@ -0,0 +1 @@
+{"schema_version":2,"operation_id":"op_207cf88f9270489ae320c738859e0a4c","workspace_id":"personal/default","idempotency":{"principal":"interactive-user","operation_kind":"ApplyComputeSave","key":"released-producer-save"},"request_digest":"sha256:492cca3897caef3b3c7f7b9c37119eb6c0d5e4a9332a625cf2560e6f9a05b064","accepted_digest":"sha256:1c55a5e135365f9e40fc739446d253ad367696a372b061c86cf13c883c3ce461","expected_revisions":{"target":0,"dependencies":{"release.model_data":1,"release.registry":1}},"plan":{"control":{"compute_management_mutation":{"change_spec_digest":"sha256:9a702208daaf96eee8af74069021723e8c4e4c491d7ebed77e4f4e046a16e944","desired":{"authentication":{"kind":"bearer"},"credentials":[{"credential":{"allowed_destinations":["compute-target/7eac3ccdfab2191651c0bacdc966022e"],"credential_id":"credential/managed-b090d3254c68d9383f54f38d","generation":1,"owner_scope":"source/source/managed-c71f3083486a232251e0c7f1","purpose":"provider-auth","subject":"hirouted"},"enabled":true,"fingerprint":"sha256:6239b41892f03e1976750a4f90aa047bd485a3b6869c127ea5299778a79db4ab","key_id":"credential/managed-b090d3254c68d9383f54f38d","ordinal":0}],"display_name":"Released Native Fixture","last_candidate_ref":"candidate/native/released-producer","last_candidate_revision":1,"lineage_digest":"sha256:c71f3083486a232251e0c7f1972e1cd5b2060b5d0382560a4306729fed93eeb1","models":[{"binding_id":"binding/managed-694fdb6d6b86407247c323ef","capabilities":{"context_tokens":{"basis":"user_declared","value":32768},"max_output_tokens":{"basis":"user_declared","value":4096},"native_reasoning":{"basis":"user_declared","value":{"kind":"fixed","profile":"provider-default"}},"streaming":{"basis":"user_declared","value":true},"tool":{"basis":"user_declared","value":true},"vision":{"basis":"user_declared","value":false}},"capability_evidence_digest":"sha256:fcf0f1555fb19424b7ba2943ea2ffe6ff56b40214c5714490df9ef82b6fee835","display_name":"released-model-a","execution_eligible":true,"membership":"user_declared","model_ref":"model/sha256:01b2de689c95bdeeffd1079651361fc3a40adf380e7346bf24a56b7b7e80606d","revision":1,"upstream_model_id":"released-model-a"},{"binding_id":"binding/managed-48ab70c9b4adb37c2a6c2079","capabilities":{"context_tokens":{"basis":"user_declared","value":32768},"max_output_tokens":{"basis":"user_declared","value":4096},"native_reasoning":{"basis":"user_declared","value":{"kind":"fixed","profile":"provider-default"}},"streaming":{"basis":"user_declared","value":true},"tool":{"basis":"user_declared","value":true},"vision":{"basis":"user_declared","value":false}},"capability_evidence_digest":"sha256:fef35f5fca408d30bc41b7cdc936d8edf2ccd99e0c8aa40d5cf90a49ba69c710","display_name":"released-model-b","execution_eligible":true,"membership":"user_declared","model_ref":"model/sha256:499ff25fe5fded202dc225ba6ecb80cde0a6dd60d71d59b13b2536824ae6fcdc","revision":1,"upstream_model_id":"released-model-b"}],"native_recheck":{"inventory_path":"/v1/models","protocol_header_semantics":{"content_type":"application/json","forbidden_forward_headers":["authorization","x-api-key"],"required_headers":[]}},"provenance":{"configuration_revision":1,"evidence_digest":"sha256:b67bb2abc71cae77ca46f11497f8ca9afe5720572efff6c46151e61facd4ceca","kind":"user_configured"},"revision":1,"schema":"hiroute.compute-management-source/v3","source_id":"source/managed-c71f3083486a232251e0c7f1","state":"ready","target":{"authority":"127.0.0.1","port":41949,"protocol_profile_id":"profile/custom/responses","protocol_profile_revision":1,"request_path":"/v1/responses","scheme":"http","upstream_protocol":"responses"}},"desired_digest":"sha256:517cee917dd8cffaa12600fbdb4f2cc8824df4c539f8ba79977de0964f361d8b","desired_revision":1,"expected_revision":0,"schema":"hiroute.compute-management-mutation/v2","source_id":"source/managed-c71f3083486a232251e0c7f1","transaction":"compare_and_swap"}},"credential_pool":null,"external":[],"runtime":[],"schema":"hiroute.operation-input/v1","secrets":[{"credential":{"allowed_destinations":["compute-target/7eac3ccdfab2191651c0bacdc966022e"],"credential_id":"credential/managed-b090d3254c68d9383f54f38d","generation":0,"owner_scope":"source/source/managed-c71f3083486a232251e0c7f1","purpose":"provider-auth","subject":"hirouted"},"expected_generation":0,"fingerprint":"sha256:6239b41892f03e1976750a4f90aa047bd485a3b6869c127ea5299778a79db4ab","fingerprint_algorithm":"hmac_sha256_v1","input_slot":"candidate/native/released-producer","kind":"upsert","new_allowed_destinations":null}],"spec":{"command_id":"compute.connection.apply","desired_state":{"expected_revisions":{"dependencies":{"release.model_data":1,"release.registry":1},"target":0},"intent":"save_ready","schema":"hiroute.compute-management-change/v2","selected_model_refs":["model/sha256:01b2de689c95bdeeffd1079651361fc3a40adf380e7346bf24a56b7b7e80606d","model/sha256:499ff25fe5fded202dc225ba6ecb80cde0a6dd60d71d59b13b2536824ae6fcdc"],"subject":{"candidate":{"candidate_ref":"candidate/native/released-producer","candidate_revision":1},"kind":"candidate"}},"resource_id":"source/managed-c71f3083486a232251e0c7f1","schema_version":{"major":1,"minor":0}},"worker_dependency_selection":null},"state":"succeeded","generation":15,"steps":[{"sequence":0,"kind":"prepare","deterministic_input_digest":"sha256:b702ec088acb2cef5d5302f43d07295186d65e28d6220be6b114587e19bdfc27","status":"applied","attempts":1,"effects":[],"terminal_result":"applied"},{"sequence":1,"kind":"apply_secrets","deterministic_input_digest":"sha256:f9f1a926f1555620751517116a9a16891daa5d7d0a305626cb3fdf9d667874c2","status":"applied","attempts":1,"effects":[{"effect_id":"secret:credential/managed-b090d3254c68d9383f54f38d","kind":"secret","target":"credential/managed-b090d3254c68d9383f54f38d","after_fingerprint":"sha256:6239b41892f03e1976750a4f90aa047bd485a3b6869c127ea5299778a79db4ab","compensation":{"schema":"hiroute.secret-compensation/v1","operation_id":"op_207cf88f9270489ae320c738859e0a4c","credential_id":"credential/managed-b090d3254c68d9383f54f38d","owner_scope":"source/source/managed-c71f3083486a232251e0c7f1","after_exists":true,"after_generation":1}}],"terminal_result":"applied"},{"sequence":2,"kind":"materialize_sources","deterministic_input_digest":"sha256:f38ac13164c752156764dcf876e05031b653972bd094630cb01deb097b8e7f3d","status":"applied","attempts":1,"effects":[{"effect_id":"control:personal/default","kind":"control","target":"personal/default","after_fingerprint":"sha256:f2a683f6678652d4ab7a50f1194740ee1bb9a683709c9d92ee925037879f7e96","compensation":{"schema":"hiroute.control-compensation/v1","operation_id":"op_207cf88f9270489ae320c738859e0a4c","after_revision":1}}],"terminal_result":"applied"},{"sequence":3,"kind":"compile_publication","deterministic_input_digest":"sha256:c9171635fed9ca419452391118a4de7a2afe2190f23346129db8cd0fad57e365","status":"applied","attempts":1,"effects":[],"terminal_result":"applied"},{"sequence":4,"kind":"apply_agent_artifacts","deterministic_input_digest":"sha256:5ac4612884ca3ffb3894cdd5bfa06ddfa853f083ca2bdf5605db6cc1f6922b51","status":"applied","attempts":1,"effects":[],"terminal_result":"applied"},{"sequence":5,"kind":"activate","deterministic_input_digest":"sha256:e522a4f844eb520088412ae184c9dc4b0cc2c8ca509e02b8c269b8eda7c1ae8b","status":"applied","attempts":1,"effects":[],"terminal_result":"applied"}],"safe_error_code":null}
\ No newline at end of file
diff --git a/docs/code-map/architecture.md b/docs/code-map/architecture.md
index 80fa9dff..ab18d457 100644
--- a/docs/code-map/architecture.md
+++ b/docs/code-map/architecture.md
@@ -36,6 +36,7 @@ The name must fit any runtime root that supports `hiroute/control.sock`, includi
| --- | --- | --- |
| Discover a native source without executing it | [Native model connections](../../crates/integrations/src/model_connections), [Pi reader](../../crates/integrations/src/agents/pi_sources.rs), [DSH reader](../../crates/integrations/src/agents/dsh_sources.rs) | Static declarations and supported credential references only; OAuth/helpers are not executed by discovery |
| Display, prepare and save the selected source | [Safe Desktop projection](../../apps/desktop/src-tauri/src/bridge/model_connection_web.rs), [daemon preparation](../../crates/daemon/src/control/runtime/model_connections/pi_discovered.rs) | Provider/model identity remains visible; privileged scan material stays private; source changes invalidate the prepared candidate |
+| Rename a connection, append models or remove saved configuration | [Shared lifecycle planner](../../crates/application/src/compute_management/mutations/lifecycle.rs), [transactional reference guards](../../crates/local-storage/src/control/compute/management/references.rs), [Desktop lifecycle dialog](../../apps/desktop/src/features/models/ConnectionLifecycleDialog.tsx) | Templates do not own credentials. Explicit append preserves saved members; enabled/disabled routes and retained recovery versions block removal. Removing the last model requires explicit connection deletion; owned secrets follow the same recoverable operation. |
| Connect a native Codex or Claude subscription | [Source discovery](../../crates/integrations/src/agents/subscription_sources.rs), [credential adapters](../../crates/cpa-bridge/src), [shared lifecycle](../../crates/daemon/src/control/runtime/subscriptions.rs), [provider runtimes](../../crates/cpa-bridge/src/runtime_set.rs) | Native clients retain refresh authority; only access leases enter isolated CPA instances. Claude Keychain interaction is limited to an explicit check; discovery reads metadata only. Codex borrowing reads file storage only and rejects a configured non-file store even if stale auth.json remains. |
| Sign in independently to a Codex or Claude subscription | [Shared login control](../../crates/application/src/control_plane/subscription_login.rs), [protected lifecycle](../../crates/daemon/src/control/runtime/subscriptions/login.rs), [private sessions](../../crates/cpa-bridge/src/managed_sessions.rs), [Desktop sign-in](../../apps/desktop/src/features/subscriptions/SubscriptionSignIn.tsx) | CPA owns the new authorization and refresh; login is separate from Check/Save and routing. Daemon maintenance owns pending completion/expiry, and saved revisions own runtime selection. [The pinned CPA adapter](../../vendor/cpa/README.md) explains refresh ownership and request recovery. |
| Lease a subscription credential without blocking Gateway workers | [Async adapter](../../crates/daemon/src/gateway_ports/credential/cpa.rs), [request budget](../../crates/cpa-bridge/src/request_context.rs), [admission and observations](../../crates/cpa-bridge/src/runtime/admission.rs), [Claude identity resolution](../../crates/cpa-bridge/src/claude_profile.rs) | Bounded provider executors own compatibility I/O. Short admission updates revoke before lifecycle work; identity lookup runs outside the lifecycle owner. Cancellation and saved revisions guard later publication. Follow [concurrency regressions](../../crates/cpa-bridge/src/runtime/tests/request_io.rs) for races with disable, replacement and delayed I/O. |
@@ -64,6 +65,8 @@ Scan → Prepare → Save → restart → native use, including stale-source rej
| Agent settings | Configure/Edit seals service state before the file tail. Ordinary Disable conditionally restores files before withdrawing grants; conflicts preserve foreign edits and require the appropriate fresh operation or exact retry. | [Transaction](../../crates/application/src/agent_connection/settings/transaction.rs), [ordering tests](../../crates/application/src/operations/tests/settings_tail.rs) |
| Native target registration | An unused discovered target is not access authority or a global startup dependency. Actual access and accepted-operation recovery retain path identity and safe-write checks; OS I/O determines accessibility. | [Registration tests](../../crates/local-storage/src/agents/native_registration_tests.rs), [startup journey](../../crates/daemon/tests/publication_process.rs) |
| Operation journal | Domain checkpoints and stored journals agree before publication or native effects; immutable plan bytes and generation/identity guards remain authoritative. JSON member ordering is distinct from a content change. | [Checkpoint](../../crates/domain/src/operation/journal.rs), [verification](../../crates/local-storage/src/control/journal.rs), [transaction guards](../../crates/local-storage/src/control/transaction_v2_tests.rs) |
+| Managed credential rollback | Authenticate the exact compensated Secret before converging source references under the same writer. Forward generations and source/workspace revisions reject stale authority; the atomic receipt makes restart idempotent. | [Coordinator](../../crates/application/src/operations/compute_compensation.rs), [Secret proof](../../crates/local-storage/src/secrets/compensation.rs), [Control receipt](../../crates/local-storage/src/control/compute/management/compensation.rs) |
+| Reference refresh | A checkpoint copies verified installed routing authority at the next revision through the normal publication writer. Preview pins revisions and content; disabled routes, drafts and held versions remain deletion blockers. | [Strict checkpoint](../../crates/domain/src/operation/publication_checkpoint.rs), [shared entry](../../crates/application/src/control_plane/publication_checkpoint.rs), [installed-state facts](../../crates/daemon/src/control/runtime/routing.rs) |
| Profile deletion | Untouched proof binds the current store instance and exact marker; a stage directory alone cannot prove deletion never began. | [Profile lifecycle](../../crates/daemon/src/control/runtime/settings_profile_tests.rs) |
| Worker/content lifetime | Result completion, process stop, body availability and permission to Continue are separate facts; cleanup requires exact ownership. | [Worker map](worker-context.md#state-and-lifetime), [managed-text contract](../../crates/observation/src/managed_text/README.md) |
| Recovery and compatibility | Current producers have one ingestion contract. Registered legacy revoke tails retain their own ordering; frozen fixtures alone do not establish production upgrade support. | [Startup admission](../../crates/local-storage/src/migrations/startup_format.rs), [legacy-tail tests](../../crates/daemon/src/control/runtime/settings_profile_legacy_tests.rs), [compatibility registry](../../contracts/compatibility-support.v1.json) |
diff --git a/docs/standalone-cli.md b/docs/standalone-cli.md
index 2283a62a..d27ff243 100644
--- a/docs/standalone-cli.md
+++ b/docs/standalone-cli.md
@@ -298,6 +298,50 @@ hiroute operations find --request-stdin --output json < operation-find.json
The same key and content returns the original Operation. The same key with different content
is rejected deterministically and never writes twice.
+## Rename, append or remove saved connections
+
+Use the same `compute connection preview` / `apply` sequence with the optional
+`change.edit` field. Omit `edit` to keep the existing save behavior. Read current
+`compute list` revisions before preview; pass its returned request unchanged to apply.
+
+| `edit` | Subject | `selected_model_refs` |
+| --- | --- | --- |
+| `{"action":"rename","display_name":"Team API"}` | Saved source | Empty |
+| `{"action":"append_models"}` | Freshly checked candidate for the existing source | Models to add |
+| `{"action":"remove_models"}` | Saved source | Models to remove |
+| `{"action":"delete"}` | Saved source | Empty |
+
+A saved-source subject is `{"kind":"saved_source","source_id":"SOURCE_ID"}`.
+Keep `key_edits` empty for these saved-source edits and append. Names must be distinct,
+nonempty and at most 60 characters. A new candidate save can also carry the rename
+edit to name its independent connection; its normal protected key input is still required.
+Each independently created connection owns its endpoints and credentials, even when it
+starts from the same provider template or uses the same literal key.
+
+Append preserves existing model records, bindings, credentials and enabled state.
+Removing the last model requires explicit `delete`; deleting a connection also cleans
+its HiRoute-owned credentials, while preserving subscription sign-ins and usage history.
+`affected_plan_refs` lists blockers in the preview: disabled routes, saved drafts,
+and retained execution or recovery versions also prevent removal. Apply rechecks
+references, so a new reference after preview can still reject the operation.
+
+After deleting a route or moving its models, the previous publication may still retain
+references. Refresh them through the normal routing publication transaction:
+
+```json
+{"change":{"schema":"hiroute.publication-checkpoint-change/v1"}}
+```
+
+Pass this request to `routing preview --request-stdin --output json`. Submit the same
+`change`, the returned `change_digest` as `accept_digest`, `expected_revisions`, and a
+new `idempotency_key` to `routing apply --request-stdin --output json`. Wait for its
+Operation to reach `succeeded`, then obtain a fresh connection deletion preview.
+An uncertain response requires observing or replaying that same Operation/key.
+This publishes an unchanged copy of the installed routing configuration at the next
+revision, including an empty configuration; it does not create routes or grant access.
+Disabled routes, drafts and retained execution versions still block removal.
+Desktop exposes this action as **Update references** in the blocked deletion dialog.
+
## Discover and save a subscription source
```sh
diff --git a/docs/standalone-cli.zh-CN.md b/docs/standalone-cli.zh-CN.md
index 86e3a809..7be3ce51 100644
--- a/docs/standalone-cli.zh-CN.md
+++ b/docs/standalone-cli.zh-CN.md
@@ -717,3 +717,41 @@ hiroute decision services test --request-stdin --output json < decision-test-req
保存后运行 `hiroute service restart --output json` 应用;重启可能中断正在执行的任务和请求。
手动代理作用于全部受管订阅及 Claude 订阅检查,不作用于 Worker 工具或 Native API。
不支持 URL 用户名密码、PAC 或 ALL_PROXY。配置已应用不等于订阅可用;仍需检查订阅和真实推理。
+
+
+## 接入改名、追加与删除
+
+继续使用 `compute connection preview` 和 `compute connection apply`,在
+`change` 中增加可选 `edit`;不填写时保持原有保存语义。先读取 `compute list`
+的最新 revisions,再预览,并将返回的 spec、digest、revisions 原样提交。
+
+| `edit` | subject | selected_model_refs |
+| --- | --- | --- |
+| `{"action":"rename","display_name":"团队 API"}` | saved_source | 空数组 |
+| `{"action":"append_models"}` | 对已有接入重新检查得到的 candidate | 要追加的模型 |
+| `{"action":"remove_models"}` | saved_source | 要移除的模型 |
+| `{"action":"delete"}` | saved_source | 空数组 |
+
+saved_source 的完整形式为 `{"kind":"saved_source","source_id":"SOURCE_ID"}`。
+上述已有接入操作和追加操作的 `key_edits` 为空。名称需与其他接入区分,长度为
+1–60 个字符。新建 candidate 保存也可带 rename edit 指定名称,并按原有流程
+提交受保护凭据。同一供应商模板创建的不同接入分别拥有端点、凭据和模型。
+
+追加保留已有模型、绑定、凭据和启停状态。移除最后一个模型需明确使用 delete;
+删除接入会清理其在 HiRoute 中拥有的凭据,保留订阅登录和历史记录。
+预览的 `affected_plan_refs` 返回阻止删除的引用,包括停用路由、保存的草稿以及
+仍保留的执行或恢复版本。应用阶段会重新检查,预览后新增引用也会阻止删除。
+
+删除路由或调整其模型后,上一份发布可能仍保留引用。可通过正常路由发布流程更新:
+
+```json
+{"change":{"schema":"hiroute.publication-checkpoint-change/v1"}}
+```
+
+将此请求传给 `routing preview --request-stdin --output json`,再将相同 `change`、
+返回的 `change_digest`(作为 `accept_digest`)、`expected_revisions` 和新的
+`idempotency_key` 传给 `routing apply --request-stdin --output json`。等待 Operation
+达到 `succeeded` 后,重新预览接入删除;响应不确定时应观察或重放原 Operation/key。
+此操作仅将已安装的路由配置原样发布到下一版本,支持空配置,不创建路由或新增授权。
+停用路由、草稿和仍保留的执行版本继续阻止删除。Desktop 在删除受阻窗口提供
+“更新引用状态”,完成后再次打开删除窗口检查。
diff --git a/e2e/product/schema/contract-set.v1.json b/e2e/product/schema/contract-set.v1.json
index 6588408b..0028b749 100644
--- a/e2e/product/schema/contract-set.v1.json
+++ b/e2e/product/schema/contract-set.v1.json
@@ -1,10 +1,10 @@
{
- "descriptor_digest": "sha256:febf9a04d9e2721df85c12616dd74f97e68de79191d3eae81da532bd782a7e55",
+ "descriptor_digest": "sha256:a435bc5901bbcaeaf2f41c8c4db15b0a7f967d988aeb544e8f5d2890abc64639",
"files": {
"dependency-gate.v1.json": "sha256:b8ac81155266dca921f159d1cfabec6605f2e4bab0320ad6b23a3dbee51e6fa1",
"product-action.v1.schema.json": "sha256:faf815b27fd292e564a7d51de20c5a2825abbe710315a2364a9932ae3b5e4b7e",
"product-oracle-evidence.v1.schema.json": "sha256:faab6582bf3fba307b0f9f2949c51726409a209b0fa62e847114e0c6301038c6",
- "product-oracle-manifest.v1.json": "sha256:e8b1b7ed8834eab106bf465b3a76929081c712d256b2c454580b3a45a2a89924",
+ "product-oracle-manifest.v1.json": "sha256:bbcdce63841053bba9567ae2514bba228d9685328438c9a31ecf10e883ba57e2",
"product-result.v1.schema.json": "sha256:72fc76be77572e40eed7516754911b45fdc9d55a8c089ba74c21427a33809def"
},
"schema_version": {
diff --git a/e2e/product/schema/product-oracle-manifest.v1.json b/e2e/product/schema/product-oracle-manifest.v1.json
index aef5d2b9..8c863c7b 100644
--- a/e2e/product/schema/product-oracle-manifest.v1.json
+++ b/e2e/product/schema/product-oracle-manifest.v1.json
@@ -1,5 +1,5 @@
{
- "descriptor_digest": "sha256:febf9a04d9e2721df85c12616dd74f97e68de79191d3eae81da532bd782a7e55",
+ "descriptor_digest": "sha256:a435bc5901bbcaeaf2f41c8c4db15b0a7f967d988aeb544e8f5d2890abc64639",
"expected_red_reasons": [],
"planned_commands": [
"schema.list",
diff --git a/scripts/local-rust.py b/scripts/local-rust.py
index 4bc01c0f..e5d951b1 100644
--- a/scripts/local-rust.py
+++ b/scripts/local-rust.py
@@ -107,14 +107,14 @@ class Store:
remote.save(path, row)
@contextlib.contextmanager
- def locked(self, checkout):
- # The runner and cleanup use the same lock; cleanup never waits on an active build.
+ def locked(self, checkout, *, wait=False):
+ # Only an explicitly queued run waits; cleanup always uses the default fast failure.
key = hashlib.sha256(str(checkout).encode()).hexdigest()
with contextlib.ExitStack() as stack:
handles = []
for path in (self.global_lock, self.root / "locks" / (key + ".lock")):
handle = stack.enter_context(path.open("a"))
- remote.fcntl.flock(handle, remote.fcntl.LOCK_EX | remote.fcntl.LOCK_NB)
+ remote.fcntl.flock(handle, remote.fcntl.LOCK_EX | (0 if wait else remote.fcntl.LOCK_NB))
handles.append(handle)
yield handles
@@ -135,6 +135,16 @@ class Store:
if any(not p.startswith("target/") for p in ignored.splitlines()):
raise ValueError("Ignored files outside target retained")
target = checkout / "target"
+ # Lock admission can fail before Cargo creates a target. Only a managed,
+ # never-started run without recorded target identities may use this path.
+ # A later-created target (including a dangling link) still fails closed.
+ if (row["kind"] == "managed" and row.get("process_exit") is None
+ and not row.get("command_started_at")
+ and "target_identity" not in row and "debug_identity" not in row
+ and not os.path.lexists(target)):
+ if git(checkout, "ls-files", "target"):
+ raise ValueError("Target contains tracked files")
+ return checkout, target / "debug"
identity(target)
if target.resolve() != target or identity(target) != row["target_identity"]:
raise ValueError("Target was replaced")
@@ -189,7 +199,8 @@ class Store:
raise ValueError("Candidate changed; preview again")
if row["kind"] == "managed":
# Preserve all non-debug target artifacts before removing this disposable tree.
- self.export_target(row)
+ if os.path.lexists(checkout / "target"):
+ self.export_target(row)
remote.command(["git", "-C", row["repo"], "worktree", "remove", "--force", str(checkout)])
else:
shutil.rmtree(debug) # Never remove a developer worktree or its release/evidence.
@@ -283,7 +294,8 @@ def run(store, args, prepare=None, on_record=None):
row = dict(id=key, kind="managed", repo=str(repo), checkout=str(checkout), sha=args.sha,
command=cargo, status="preparing", keep=args.keep, evidence_saved=False,
process_exit=None, scenario="unassessed", candidate_source=source,
- build_jobs=jobs, platform=sys.platform, architecture=platform.machine(),
+ build_jobs=jobs, wait_for_lock=getattr(args, "wait_for_lock", False),
+ platform=sys.platform, architecture=platform.machine(),
submitted_at=time.time(), **feedback)
row["executor_sha256"] = {
name: hashlib.sha256(Path(__file__).with_name(name).read_bytes()).hexdigest()
@@ -324,8 +336,11 @@ def run(store, args, prepare=None, on_record=None):
}
before = remote.stats(store.record_path(key).parent, "cache-before", server_env)
row["queued_at"] = time.time()
- with store.locked(checkout) as handles:
+ store.save(row)
+ with store.locked(checkout, wait=row["wait_for_lock"]) as handles:
row["capacity_acquired_at"] = time.time()
+ if row["wait_for_lock"] and shutil.disk_usage(store.root).free < 30 * GIB:
+ raise ValueError("Less than 30 GiB free after waiting; build not started")
info = private_temp()
row["temporary_directory"] = info
env["TMPDIR"] = info["path"]
@@ -385,6 +400,8 @@ def main():
p.add_argument("--sha", required=True)
p.add_argument("--source", choices=("origin", "local"), default="origin")
p.add_argument("--jobs", type=int, default=2)
+ p.add_argument("--wait-for-lock", action="store_true",
+ help="Wait on the existing exclusive host/checkout locks before starting Cargo")
p.add_argument("--keep", action="store_true")
p.add_argument("--cargo-only", action="store_true", help="Assert pure Cargo check: no external scenario verdict or unique debug artifacts")
p.add_argument("--timeout", type=int, default=3600)
diff --git a/scripts/private-stream-capture.py b/scripts/private-stream-capture.py
index b69d1785..f6c0e3cc 100644
--- a/scripts/private-stream-capture.py
+++ b/scripts/private-stream-capture.py
@@ -15,6 +15,7 @@ import shutil
import signal
import stat
import subprocess
+import sys
import time
GROUP_STOP_GRACE_SECONDS = 5
@@ -46,15 +47,63 @@ def create_session(root, source_sha, binary, client, seconds):
return session
-def stop(child):
+def darwin_group_contains_only_leader(pid):
+ if sys.platform != "darwin":
+ return False
+ import ctypes
+ libc = ctypes.CDLL(None, use_errno=True)
+ libc.sysctl.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.c_uint, ctypes.c_void_p,
+ ctypes.POINTER(ctypes.c_size_t), ctypes.c_void_p, ctypes.c_size_t]
+ libc.sysctl.restype = ctypes.c_int
+
+ def snapshot(selector):
+ # Darwin sys/sysctl.h: CTL_KERN=1, KERN_PROC=14, PID=1, PGRP=2.
+ # Compare the opaque records instead of depending on kinfo_proc layout.
+ mib = (ctypes.c_int * 4)(1, 14, selector, pid)
+ size = ctypes.c_size_t()
+ if libc.sysctl(mib, 4, None, ctypes.byref(size), None, 0) != 0:
+ return None
+ if not 0 < size.value <= 16 * 1024 * 1024:
+ return None
+ buffer = ctypes.create_string_buffer(size.value)
+ if libc.sysctl(mib, 4, buffer, ctypes.byref(size), None, 0) != 0:
+ return None
+ return buffer.raw[:size.value]
+
+ leader = snapshot(1)
+ return bool(leader) and snapshot(2) == leader
+
+
+def signal_owned_group(child, sig, created_isolated_session):
+ try:
+ os.killpg(child.pid, sig)
+ except ProcessLookupError:
+ pass
+ except PermissionError:
+ # Darwin returns EPERM for a group containing only an unsignalable
+ # zombie. Any additional member or unavailable kernel proof fails closed.
+ if not (created_isolated_session and candidate_exited(child)
+ and darwin_group_contains_only_leader(child.pid)):
+ raise
+
+
+def stop(child, *, created_isolated_session=False):
if child.returncode is not None:
raise ValueError("candidate leader was reaped before process-group cleanup")
- if os.getpgid(child.pid) != child.pid or os.getsid(child.pid) != child.pid:
- raise ValueError("candidate does not own its isolated session/process group")
+ try:
+ if os.getpgid(child.pid) != child.pid or os.getsid(child.pid) != child.pid:
+ raise ValueError("candidate does not own its isolated session/process group")
+ except ProcessLookupError:
+ # macOS may hide a zombie's PGID/SID before waitpid reaps it. Popen's
+ # successful start_new_session establishes this ID; WNOWAIT proves the
+ # leader still anchors it against reuse. Never infer ownership from a
+ # missing process alone.
+ if not created_isolated_session or not candidate_exited(child):
+ raise
# The waitable leader anchors this group ID even when it has already
# exited. A descendant may still own capture files or ignore SIGTERM.
try:
- os.killpg(child.pid, signal.SIGTERM)
+ signal_owned_group(child, signal.SIGTERM, created_isolated_session)
deadline = time.monotonic() + GROUP_STOP_GRACE_SECONDS
while time.monotonic() < deadline:
time.sleep(min(0.02, max(0, deadline - time.monotonic())))
@@ -62,9 +111,7 @@ def stop(child):
# Graceful termination of the retention owner can interrupt the grace
# wait. It must still stop descendants before attempting raw cleanup.
try:
- os.killpg(child.pid, signal.SIGKILL)
- except ProcessLookupError:
- pass
+ signal_owned_group(child, signal.SIGKILL, created_isolated_session)
finally:
child.wait(timeout=5)
@@ -186,7 +233,7 @@ def supervise_candidate(args, root, binary, command, source, report):
time.sleep(0.02)
finally:
if child is not None:
- stop(child)
+ stop(child, created_isolated_session=True)
report({"stop_reason": reason, "process_exit": child.returncode if child else None,
"scenario": "unassessed", "retention_seconds": 86400})
diff --git a/scripts/test-local-rust.py b/scripts/test-local-rust.py
index 941e873d..2b69793f 100644
--- a/scripts/test-local-rust.py
+++ b/scripts/test-local-rust.py
@@ -4,6 +4,8 @@ import importlib.util
import json
import os
from pathlib import Path
+import select
+import signal
import subprocess
import tempfile
import time
@@ -66,6 +68,51 @@ class Cleanup(unittest.TestCase):
self.assertEqual(before, self.store.record_path(row['id']).read_bytes())
self.assertTrue((self.repo / 'target/debug/binary').exists())
+ def targetless_admission(self):
+ row = self.managed()
+ m.shutil.rmtree(Path(row['checkout']) / 'target')
+ row.pop('target_identity')
+ row.pop('debug_identity')
+ row['process_exit'] = None
+ self.store.save(row)
+ return row
+
+ def test_targetless_admission_cleanup_preserves_run_evidence(self):
+ row = self.targetless_admission()
+ report = self.store.record_path(row['id']).parent / 'validation-report.json'
+ report.write_text('{"scenario":"not_executed"}')
+ candidate = self.store.preview_one(row)
+ self.assertEqual(candidate['state'], 'candidate')
+ self.assertEqual(candidate['bytes'], 0)
+ self.store.apply(row['id'], candidate['token'])
+ self.assertFalse(Path(row['checkout']).exists())
+ self.assertTrue(self.store.load(row['id'])['removed'])
+ self.assertIsNone(self.store.load(row['id'])['process_exit'])
+ self.assertEqual(json.loads(report.read_text())['scenario'], 'not_executed')
+
+ def test_targetless_admission_rejects_later_target_and_dangling_link(self):
+ row = self.targetless_admission()
+ candidate = self.store.preview_one(row)
+ target = Path(row['checkout']) / 'target'
+ for linked in (False, True):
+ if linked:
+ target.symlink_to(self.base / 'missing', target_is_directory=True)
+ else:
+ target.mkdir()
+ with self.assertRaises((ValueError, KeyError)):
+ self.store.apply(row['id'], candidate['token'])
+ if linked:
+ target.unlink()
+ else:
+ target.rmdir()
+ self.assertTrue(Path(row['checkout']).exists())
+
+ def test_missing_target_after_started_or_attested_run_stays_protected(self):
+ row = self.targetless_admission()
+ for extra in ({'command_started_at': 1}, {'process_exit': 1},
+ {'target_identity': [1, 2]}, {'debug_identity': [1, 3]}):
+ self.assertEqual(self.store.preview_one(dict(row, **extra))['state'], 'skipped')
+
def test_developer_cleanup_preserves_dirty_source_evidence_and_branch(self):
row = self.developer()
(self.repo / 'source').write_text('uncommitted')
@@ -96,6 +143,275 @@ class Cleanup(unittest.TestCase):
child.communicate('done')
self.assertEqual(child.returncode, 0)
+ def child(self, code, *arguments, env=None):
+ process = subprocess.Popen([m.sys.executable, '-c', code, *map(str, arguments)],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE, text=True, env=env)
+ def reap():
+ if process.poll() is None:
+ process.kill()
+ process.communicate(timeout=5)
+ self.addCleanup(reap)
+ return process
+
+ def ready(self, process):
+ self.assertTrue(select.select([process.stdout], [], [], 5)[0], 'child readiness timed out')
+ # Read only the readiness line; TextIO.readline could prefetch the final
+ # JSON that communicate() must later read from a fast nonblocking child.
+ line = b''
+ while not line.endswith(b'\n'):
+ value = os.read(process.stdout.fileno(), 1)
+ self.assertTrue(value, 'child exited before readiness')
+ line += value
+ self.assertEqual(line, b'ready\n')
+
+ def hold_lock(self, path):
+ child = self.child('import fcntl,sys; f=open(sys.argv[1],"a"); '
+ 'fcntl.flock(f,fcntl.LOCK_EX); print("ready",flush=True); sys.stdin.read()', path)
+ self.ready(child)
+ return child
+
+ def queued_run(self, wait_for_lock=None, available_bytes=60 * m.GIB):
+ # Only Git, child processes and flock are real; these private compiler tools
+ # record invocations instead of compiling Rust or touching the host's locks.
+ binary = self.base / 'queued-bin'
+ binary.mkdir()
+ calls = self.base / 'compiler-calls.jsonl'
+ cargo = binary / 'cargo'
+ cargo.write_text('#!' + m.sys.executable + '\n'
+ 'import json,pathlib,sys\n'
+ f'with pathlib.Path({str(calls)!r}).open("a") as out:\n'
+ ' out.write(json.dumps(sys.argv[1:])+"\\n")\n'
+ 'target=pathlib.Path.cwd()/"target"\n'
+ 'if sys.argv[1]=="metadata":\n'
+ ' print(json.dumps({"target_directory":str(target)}))\n'
+ 'elif sys.argv[1]=="--version":\n'
+ ' print("cargo fixture")\n'
+ 'else:\n'
+ ' (target/"debug").mkdir(parents=True)\n'
+ ' print("test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out")\n')
+ cargo.chmod(0o700)
+ for name in ('rustc', 'sccache'):
+ tool = binary / name
+ tool.write_text('#!/bin/sh\nexit 0\n')
+ tool.chmod(0o700)
+ space = self.base / 'available-bytes'
+ space.write_text(str(available_bytes))
+ args = dict(repo=str(self.repo), ref=m.git(self.repo, 'symbolic-ref', 'HEAD'),
+ sha=m.git(self.repo, 'rev-parse', 'HEAD'), command=['cargo', 'test'],
+ keep=True, cargo_only=True, timeout=5, source='local', jobs=2)
+ if wait_for_lock is not None:
+ args['wait_for_lock'] = wait_for_lock
+ code = '''import importlib.util,json,sys,types
+from pathlib import Path
+sys.dont_write_bytecode=True
+spec=importlib.util.spec_from_file_location('queued_local',sys.argv[1])
+module=importlib.util.module_from_spec(spec)
+spec.loader.exec_module(module)
+store=module.Store(sys.argv[2],sys.argv[3])
+store.ensure_space=lambda: None
+store.gc=lambda *a,**k: (_ for _ in ()).throw(AssertionError('GC must not run inside the acquired lock'))
+module.remote.stats=lambda *a,**k: {'cache_hits':1}
+module.shutil.disk_usage=lambda path: types.SimpleNamespace(free=int(Path(sys.argv[4]).read_text()))
+flock=module.remote.fcntl.flock
+first=True
+def observed_flock(handle,flags):
+ global first
+ if first:
+ first=False
+ print('ready',flush=True)
+ return flock(handle,flags)
+module.remote.fcntl.flock=observed_flock
+result=module.run(store,types.SimpleNamespace(**json.loads(sys.argv[5])))
+print(json.dumps(result),flush=True)
+'''
+ env = dict(os.environ, PATH=str(binary) + os.pathsep + os.environ['PATH'])
+ child = self.child(code, m.__file__, self.store.root, self.store.global_lock,
+ space, json.dumps(args), env=env)
+ self.ready(child)
+ return child, calls, space
+
+ def run_result(self, child):
+ output, error = child.communicate(timeout=5)
+ self.assertEqual(child.returncode, 0, error)
+ row = json.loads(output)
+ if row.get('temporary_directory'):
+ self.addCleanup(m.remote.cleanup_temp_directory, row['temporary_directory'])
+ return row
+
+ def waiting_record(self, child, calls, require_queue=True):
+ with self.assertRaises(subprocess.TimeoutExpired):
+ child.wait(timeout=0.15)
+ self.assertFalse(calls.exists(), 'compiler tools entered before capacity was acquired')
+ records = list((self.store.root / 'runs').glob('*/result.json'))
+ self.assertEqual(len(records), 1)
+ row = json.loads(records[0].read_text())
+ self.assertTrue(row['wait_for_lock'])
+ if require_queue:
+ self.assertIn('queued_at', row)
+ self.assertLessEqual(row['checkout_finished_at'], row['queued_at'])
+ self.assertNotIn('capacity_acquired_at', row)
+ self.assertNotIn('command_started_at', row)
+ return row
+
+ def test_waiting_run_executes_once_after_child_releases_lock(self):
+ holder = self.hold_lock(self.store.global_lock)
+ child, calls, _ = self.queued_run(wait_for_lock=True, available_bytes=30 * m.GIB)
+ queued = self.waiting_record(child, calls)
+ released_at = time.time()
+ holder.communicate('release', timeout=5)
+ row = self.run_result(child)
+ self.assertEqual(row['scenario'], 'green', row)
+ self.assertEqual(row['process_exit'], 0)
+ self.assertEqual(row['queued_at'], queued['queued_at'])
+ self.assertGreaterEqual(row['capacity_acquired_at'], released_at)
+ self.assertLessEqual(row['capacity_acquired_at'], row['command_started_at'])
+ self.assertLessEqual(row['command_started_at'], row['command_finished_at'])
+ self.assertEqual([json.loads(line) for line in calls.read_text().splitlines()].count(['test']), 1)
+ saved = self.store.load(row['id'])
+ self.assertTrue(saved['wait_for_lock'])
+ self.assertEqual(saved['queued_at'], row['queued_at'])
+ with self.store.locked(row['checkout']):
+ pass
+
+ def test_default_run_refuses_busy_lock_without_execution(self):
+ holder = self.hold_lock(self.store.global_lock)
+ child, calls, _ = self.queued_run()
+ row = self.run_result(child)
+ self.assertFalse(row['wait_for_lock'])
+ self.assertEqual(row['scenario'], 'red')
+ self.assertIsNone(row['process_exit'])
+ self.assertIn('temporarily unavailable', row['error'])
+ self.assertNotIn('capacity_acquired_at', row)
+ self.assertFalse(calls.exists())
+ self.assertIsNone(holder.poll(), 'the test must leave the competing owner active')
+
+ def test_interrupted_waiting_run_has_no_execution_or_lock_leak(self):
+ holder = self.hold_lock(self.store.global_lock)
+ child, calls, _ = self.queued_run(wait_for_lock=True)
+ self.waiting_record(child, calls, require_queue=False)
+ child.send_signal(signal.SIGINT)
+ row = self.run_result(child)
+ self.assertEqual(row['scenario'], 'red')
+ self.assertIsNone(row['process_exit'])
+ self.assertNotIn('capacity_acquired_at', row)
+ self.assertFalse(calls.exists())
+ holder.communicate('release', timeout=5)
+ with self.store.locked(row['checkout']):
+ pass
+
+ def waiting_store(self):
+ checkout_lock = self.store.root / 'locks' / (m.hashlib.sha256(str(self.repo).encode()).hexdigest() + '.lock')
+ holder = self.hold_lock(checkout_lock)
+ code = '''import importlib.util,sys
+spec=importlib.util.spec_from_file_location('waiting_local',sys.argv[1])
+module=importlib.util.module_from_spec(spec)
+spec.loader.exec_module(module)
+store=module.Store(sys.argv[2],sys.argv[3])
+flock=module.remote.fcntl.flock
+count=0
+def observed_flock(handle,flags):
+ global count
+ count+=1
+ if count==2: print('ready',flush=True)
+ return flock(handle,flags)
+module.remote.fcntl.flock=observed_flock
+with store.locked(sys.argv[4],wait=True): print('entered',flush=True)
+'''
+ child = self.child(code, m.__file__, self.store.root, self.store.global_lock, self.repo)
+ self.ready(child)
+ return holder, child
+
+ def test_waiting_store_enters_once_after_checkout_child_releases_lock(self):
+ holder, child = self.waiting_store()
+ with self.assertRaises(subprocess.TimeoutExpired):
+ child.wait(timeout=0.15)
+ holder.communicate('release', timeout=5)
+ output, error = child.communicate(timeout=5)
+ self.assertEqual(child.returncode, 0, error)
+ self.assertEqual(output.splitlines(), ['entered'])
+ with self.store.locked(self.repo):
+ pass
+
+ def test_waiting_store_holds_global_until_checkout_and_releases_on_termination(self):
+ holder, child = self.waiting_store()
+ with self.assertRaises(subprocess.TimeoutExpired):
+ child.wait(timeout=0.15)
+ with self.assertRaises(BlockingIOError):
+ with self.store.locked(self.base / 'other-checkout'):
+ self.fail('global lock was released while waiting on the checkout lock')
+ child.terminate()
+ output, _ = child.communicate(timeout=5)
+ self.assertEqual(child.returncode, -signal.SIGTERM)
+ self.assertNotIn('entered', output)
+ with self.store.locked(self.base / 'other-checkout'):
+ pass
+ holder.communicate('release', timeout=5)
+ with self.store.locked(self.repo):
+ pass
+
+ def test_cleanup_still_refuses_busy_child_lock_without_waiting(self):
+ row = self.developer()
+ token = self.store.preview_one(row)['token']
+ holder = self.hold_lock(self.store.global_lock)
+ code = '''import importlib.util,json,sys
+spec=importlib.util.spec_from_file_location('cleanup_local',sys.argv[1])
+module=importlib.util.module_from_spec(spec)
+spec.loader.exec_module(module)
+store=module.Store(sys.argv[2],sys.argv[3])
+row=store.load(sys.argv[4])
+preview=store.preview_one(row)
+try: store.apply(row['id'],sys.argv[5])
+except BlockingIOError: rejected=True
+else: rejected=False
+print(json.dumps({'preview':preview['state'],'apply_rejected':rejected}))
+'''
+ child = self.child(code, m.__file__, self.store.root, self.store.global_lock, row['id'], token)
+ output, error = child.communicate(timeout=2)
+ self.assertEqual(child.returncode, 0, error)
+ self.assertEqual(json.loads(output), {'preview': 'skipped', 'apply_rejected': True})
+ self.assertIsNone(holder.poll())
+ self.assertTrue((self.repo / 'target/debug/binary').exists())
+
+ def test_waiting_run_rechecks_capacity_without_gc_before_compiler(self):
+ holder = self.hold_lock(self.store.global_lock)
+ child, calls, space = self.queued_run(wait_for_lock=True)
+ self.waiting_record(child, calls, require_queue=False)
+ space.write_text(str(30 * m.GIB - 1))
+ holder.communicate('release', timeout=5)
+ row = self.run_result(child)
+ self.assertEqual(row['scenario'], 'red')
+ self.assertIn('Less than 30 GiB free after waiting', row['error'])
+ self.assertIsNone(row['process_exit'])
+ self.assertIn('capacity_acquired_at', row)
+ self.assertNotIn('command_started_at', row)
+ self.assertNotIn('temporary_directory', row)
+ self.assertFalse(calls.exists())
+ with self.store.locked(row['checkout']):
+ pass
+
+ def test_default_run_does_not_add_a_second_capacity_check(self):
+ # Preflight is stubbed in this compiler fixture. Only wait mode adds the
+ # new capacity check after flock; the original default stays compatible.
+ child, calls, _ = self.queued_run(available_bytes=0)
+ row = self.run_result(child)
+ self.assertFalse(row['wait_for_lock'])
+ self.assertEqual(row['scenario'], 'green', row)
+ self.assertTrue(calls.exists())
+
+ def test_local_cli_parses_explicit_wait_and_preserves_default(self):
+ for enabled in (False, True):
+ argv = ['local-rust.py', 'run', '--ref', 'refs/heads/test', '--sha', 'a' * 40]
+ if enabled:
+ argv.append('--wait-for-lock')
+ argv += ['--', 'cargo', 'test']
+ with self.subTest(wait=enabled), patch.object(m.sys, 'argv', argv), \
+ patch.object(m, 'Store', return_value=self.store), \
+ patch.object(m, 'run', return_value={'scenario': 'green'}) as run, \
+ patch('builtins.print'):
+ self.assertEqual(m.main(), 0)
+ self.assertEqual(run.call_args.args[1].wait_for_lock, enabled)
+
def test_keep_and_missing_evidence_are_protected(self):
row = self.managed()
for field, value in [('keep', True), ('evidence_saved', False), ('status', 'running')]:
diff --git a/scripts/test-private-stream-capture.py b/scripts/test-private-stream-capture.py
index 30aad841..18bb74e7 100644
--- a/scripts/test-private-stream-capture.py
+++ b/scripts/test-private-stream-capture.py
@@ -120,6 +120,9 @@ class CaptureSessionTest(unittest.TestCase):
try:
self.assertTrue((root / "raw.capture").exists())
if early_stop:
+ time.sleep(0.2)
+ self.assertTrue((root / "raw.capture").exists(),
+ "normal candidate exit must retain the sealed sample")
os.kill(owner, signal.SIGTERM)
deadline = time.monotonic() + 5
while root.exists() and time.monotonic() < deadline:
@@ -323,6 +326,51 @@ while True:
child.kill()
child.wait(timeout=5)
+ @unittest.skipUnless(hasattr(os, "WNOWAIT"), "requires non-reaping waitid")
+ def test_exited_owned_leader_can_be_stopped_when_macos_hides_group_identity(self):
+ child = subprocess.Popen([sys.executable, "-c", "pass"], start_new_session=True)
+ try:
+ deadline = time.monotonic() + 5
+ while not capture.candidate_exited(child) and time.monotonic() < deadline:
+ time.sleep(0.01)
+ self.assertTrue(capture.candidate_exited(child))
+ with patch.object(capture.os, "getpgid", side_effect=ProcessLookupError), \
+ patch.object(capture, "GROUP_STOP_GRACE_SECONDS", 0):
+ capture.stop(child, created_isolated_session=True)
+ self.assertEqual(child.returncode, 0)
+ finally:
+ if child.returncode is None:
+ child.kill()
+ child.wait(timeout=5)
+
+ @unittest.skipUnless(hasattr(os, "WNOWAIT"), "requires non-reaping waitid")
+ def test_missing_group_identity_does_not_authorize_signalling_a_live_child(self):
+ child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"],
+ start_new_session=True)
+ try:
+ with patch.object(capture.os, "getpgid", side_effect=ProcessLookupError), \
+ patch.object(capture.os, "killpg") as kill_group:
+ with self.assertRaises(ProcessLookupError):
+ capture.stop(child, created_isolated_session=True)
+ kill_group.assert_not_called()
+ self.assertIsNone(child.poll())
+ finally:
+ child.kill()
+ child.wait(timeout=5)
+
+ def test_group_permission_error_requires_kernel_proof_of_only_waitable_leader(self):
+ child = SimpleNamespace(pid=123, returncode=None)
+ with patch.object(capture.os, "killpg", side_effect=PermissionError), \
+ patch.object(capture, "candidate_exited", return_value=True), \
+ patch.object(capture, "darwin_group_contains_only_leader", return_value=False):
+ with self.assertRaises(PermissionError):
+ capture.signal_owned_group(child, signal.SIGKILL, True)
+ with patch.object(capture.os, "killpg", side_effect=PermissionError), \
+ patch.object(capture, "candidate_exited", return_value=True), \
+ patch.object(capture, "darwin_group_contains_only_leader", return_value=True):
+ with self.assertRaises(PermissionError):
+ capture.signal_owned_group(child, signal.SIGKILL, False)
+
def test_private_writer_does_not_follow_or_overwrite(self):
with tempfile.TemporaryDirectory() as parent:
target = Path(parent) / "target"
diff --git a/scripts/test-validation.py b/scripts/test-validation.py
index ca028813..9ee45d44 100644
--- a/scripts/test-validation.py
+++ b/scripts/test-validation.py
@@ -226,6 +226,44 @@ pilot.record('build:' + sys.argv[1])
self.assertEqual(argv[argv.index('--source') + 1], 'local')
self.assertEqual(argv[argv.index('--jobs') + 1], '3')
+ def test_real_validation_cli_forwards_wait_policy_before_cargo_boundary(self):
+ scripts = self.root / 'scripts'
+ scripts.mkdir()
+ (scripts / 'local-rust.py').write_text('import json,sys\nprint(json.dumps(sys.argv[1:]))\n')
+ self.write({'backend': {'transport': 'local', 'repo': str(self.root), 'jobs': 3}})
+ for enabled in (False, True):
+ arguments = ['run', '--ref', 'refs/heads/test', '--sha', 'a' * 40]
+ if enabled:
+ arguments.append('--wait-for-lock')
+ arguments += ['--', 'cargo', 'test', '--locked']
+ with self.subTest(wait=enabled):
+ result = subprocess.run([sys.executable, str(Path(m.__file__)),
+ '--config', str(self.config), 'backend', *arguments],
+ capture_output=True, text=True, timeout=5)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ forwarded = json.loads(result.stdout)
+ boundary = forwarded.index('--')
+ self.assertEqual(forwarded.count('--wait-for-lock'), int(enabled))
+ self.assertEqual('--wait-for-lock' in forwarded[:boundary], enabled)
+ self.assertEqual(forwarded[boundary + 1:], ['cargo', 'test', '--locked'])
+ self.assertEqual(forwarded[forwarded.index('--source') + 1], 'local')
+ self.assertEqual(forwarded[forwarded.index('--jobs') + 1], '3')
+ self.assertIn('--cargo-only', forwarded[:boundary])
+
+ def test_mac_desktop_forwards_wait_policy_without_backend_defaults(self):
+ arguments = ['run', '--ref', 'refs/heads/test', '--sha', 'a' * 40,
+ '--wait-for-lock', '--', 'cargo', 'check']
+ payload = self.payload('desktop', arguments)
+ payload.update(name='desktop', target={'transport': 'ssh'})
+ with patch.object(host.sys, 'platform', 'darwin'), \
+ patch.object(host.subprocess, 'run', return_value=subprocess.CompletedProcess([], 0)) as call:
+ self.assertEqual(host.execute(payload), 0)
+ forwarded = call.call_args.args[0]
+ self.assertEqual(forwarded.count('--wait-for-lock'), 1)
+ self.assertLess(forwarded.index('--wait-for-lock'), forwarded.index('--'))
+ self.assertNotIn('--cargo-only', forwarded)
+ self.assertNotIn('--source', forwarded)
+
def test_mac_desktop_keeps_original_runner_options_and_unassessed_exit(self):
p = self.payload('desktop')
p.update(name='desktop', target={'transport': 'ssh'})
diff --git a/tools/e2e-harness/tests/p0_gateway_runtime.rs b/tools/e2e-harness/tests/p0_gateway_runtime.rs
index e1c804ce..f3320539 100644
--- a/tools/e2e-harness/tests/p0_gateway_runtime.rs
+++ b/tools/e2e-harness/tests/p0_gateway_runtime.rs
@@ -41,12 +41,12 @@ mod reasoning;
#[path = "p0_gateway_runtime/accepted_history.rs"]
mod accepted_history;
-#[path = "p0_gateway_runtime/nonstream_terminal.rs"]
-mod nonstream_terminal;
-
#[path = "p0_gateway_runtime/responses_options.rs"]
mod responses_options;
+#[path = "p0_gateway_runtime/nonstream_terminal.rs"]
+mod nonstream_terminal;
+
#[test]
fn fixed_requests_retry_only_same_source_keys_and_never_enter_an_allowed_plan() {
for (status, error) in [(401, AUTH_ERROR), (403, AUTH_ERROR), (429, QUOTA_ERROR)] {