Skip to content
Python

feat(memhub-cli): embedding switch commands and the App contract

alvinfeif38c370fbd87
diff --git a/memhub/apps/cli/src/cli.ts b/memhub/apps/cli/src/cli.ts
index fb99613..042ce9a 100644
--- a/memhub/apps/cli/src/cli.ts
+++ b/memhub/apps/cli/src/cli.ts
@@ -122,6 +122,14 @@ import {
doctorExitCode,
renderDoctorText,
} from "./doctor-report.js";
+import {
+ activateWithEmbeddingSwitch,
+ cleanupSpace,
+ listSpaces,
+ type SwitchIo,
+ switchCancel,
+ switchStatus,
+} from "./embedding-switch-flow.js";
import {
EXIT_FAILED,
EXIT_OK,
@@ -248,7 +256,6 @@ import {
renderModelReportText,
} from "./model-report.js";
import {
- activateModelProfile,
editModelProfile,
type ModelWriteDocument,
modelWriteExitCode,
@@ -1703,6 +1710,18 @@ async function runCommand(
);
if (apiKey === undefined) return usage();
}
+ if (
+ parsed.kind === "spaces" &&
+ parsed.cleanup !== undefined &&
+ !parsed.confirmed
+ ) {
+ return emitConfirmPreview(asJson, {
+ command: "models spaces",
+ target: parsed.cleanup,
+ effect: `删除已停用的向量空间 ${parsed.cleanup}(不可恢复;正在使用的空间不能删除)`,
+ retry: `${PRODUCT} models spaces --cleanup ${parsed.cleanup} --yes`,
+ });
+ }
if (parsed.kind === "remove" && !parsed.confirmed) {
return emitConfirmPreview(asJson, {
command: "models remove",
@@ -1725,6 +1744,50 @@ async function runCommand(
return connected.exitCode;
}
const { reader, operations } = connected;
+ // Ctrl-C while following a switch stops watching, never the switch.
+ const interrupt = new AbortController();
+ const switchIo: SwitchIo = {
+ reader,
+ operations,
+ emit: (text) => {
+ emit(text);
+ },
+ asJson,
+ interactive:
+ !asJson && (controls.stdinIsTTY ?? process.stdin.isTTY) === true,
+ confirm: async (question) => {
+ const prompter =
+ controls.wizardPrompter ?? (await createTerminalPrompter());
+ try {
+ return /^(y|yes)$/i.test((await prompter.ask(question)).trim());
+ } finally {
+ if ("close" in prompter && typeof prompter.close === "function") {
+ prompter.close();
+ }
+ }
+ },
+ ...(controls.watchWait ? { wait: controls.watchWait } : {}),
+ signal: controls.watchSignal ?? interrupt.signal,
+ };
+ const withInterrupt = async (run: () => Promise<number>) => {
+ const onInterrupt = () => interrupt.abort();
+ process.once("SIGINT", onInterrupt);
+ try {
+ return await run();
+ } finally {
+ process.removeListener("SIGINT", onInterrupt);
+ }
+ };
+ if (parsed.kind === "switch") {
+ return parsed.action === "status"
+ ? await switchStatus(switchIo)
+ : await switchCancel(switchIo);
+ }
+ if (parsed.kind === "spaces") {
+ return parsed.cleanup === undefined
+ ? await listSpaces(switchIo)
+ : await cleanupSpace(parsed.cleanup, switchIo);
+ }
if (parsed.kind === "add") {
const created = await createModelProfile(
config,
@@ -1739,33 +1802,66 @@ async function runCommand(
emitFlowDocument(created, asJson);
return flowExitCode(created);
}
- const activated = await activateModelProfile(
- String(created.receipt.profile_id),
+ // Core activates only a probed profile: probe first, then the same
+ // path as `models activate`, so an embedding change shows its plan.
+ const profileId = String(created.receipt.profile_id);
+ const probe = await probeUntilSettled(
+ reader,
operations,
+ profileId,
+ controls.watchWait,
);
- const document = {
- ...created,
- activation:
- activated.state === "committed"
- ? { state: "committed" }
- : { state: activated.state, code: activated.code },
- };
+ const probed =
+ probe.state === "completed" &&
+ Boolean(
+ (
+ (probe.receipt.result as Record<string, unknown> | undefined)
+ ?.capabilities as Record<string, unknown> | undefined
+ )?.embedding_available,
+ );
emit(
asJson
- ? `${JSON.stringify(document)}\n`
+ ? `${JSON.stringify({
+ ...created,
+ probe: {
+ state: probe.state,
+ ...("operation_id" in probe && probe.operation_id
+ ? { operation_id: probe.operation_id }
+ : {}),
+ ...("code" in probe ? { code: probe.code } : {}),
+ },
+ })}\n`
: `${renderFlowText(created)}${
- activated.state === "committed"
- ? "已设为当前使用的模型配置。\n"
- : `设为当前使用未完成:${activated.state}(${activated.code})\n`
+ probed
+ ? "探测通过。\n"
+ : `探测未通过(${"code" in probe ? probe.code : probe.state}),没有设为当前使用;用 ${PRODUCT} models test ${profileId} 查看原因。\n`
}`,
);
- return activated.state === "committed" ? EXIT_OK : EXIT_FAILED;
+ if (!probed) return EXIT_FAILED;
+ return await withInterrupt(() =>
+ activateWithEmbeddingSwitch(
+ profileId,
+ { confirmed: parsed.confirmed, follow: parsed.follow },
+ switchIo,
+ ),
+ );
}
- if (parsed.kind === "edit" || parsed.kind === "activate") {
- const document =
- parsed.kind === "edit"
- ? await editModelProfile(parsed.profileId, config, apiKey, operations)
- : await activateModelProfile(parsed.profileId, operations);
+ if (parsed.kind === "activate") {
+ return await withInterrupt(() =>
+ activateWithEmbeddingSwitch(
+ parsed.profileId,
+ { confirmed: parsed.confirmed, follow: parsed.follow },
+ switchIo,
+ ),
+ );
+ }
+ if (parsed.kind === "edit") {
+ const document = await editModelProfile(
+ parsed.profileId,
+ config,
+ apiKey,
+ operations,
+ );
emitModelWriteDocument(document, asJson);
return modelWriteExitCode(document);
}
@@ -5289,6 +5385,8 @@ type ModelsCommand =
configFile: string;
apiKeyFile?: string;
activate: boolean;
+ confirmed: boolean;
+ follow?: boolean;
}
| {
kind: "edit";
@@ -5296,7 +5394,14 @@ type ModelsCommand =
configFile: string;
apiKeyFile?: string;
}
- | { kind: "activate"; profileId: string }
+ | {
+ kind: "activate";
+ profileId: string;
+ confirmed: boolean;
+ follow?: boolean;
+ }
+ | { kind: "switch"; action: "status" | "cancel" }
+ | { kind: "spaces"; cleanup?: string; confirmed: boolean }
| { kind: "test"; profileId: string }
| { kind: "receipt"; operationId: string }
| { kind: "remove"; profileId: string; confirmed: boolean };
@@ -5337,16 +5442,46 @@ function parseModelsCommand(rest: readonly string[]): ModelsCommand | null {
const flags = readFlags(
tokens.slice(1),
["--config-file", "--api-key-file"],
- ["--activate"],
+ ["--activate", "--yes", "--wait", "--no-wait"],
);
const configFile = flags?.values.get("--config-file");
if (!flags || configFile === undefined) return null;
+ const follow = followFlag(flags.switches);
+ if (follow === null) return null;
+ const activate = flags.switches.has("--activate");
+ // The switch flags only mean something when the add also activates.
+ if (
+ !activate &&
+ ["--yes", "--wait", "--no-wait"].some((flag) => flags.switches.has(flag))
+ ) {
+ return null;
+ }
const apiKeyFile = flags.values.get("--api-key-file");
return {
kind: "add",
configFile,
...(apiKeyFile === undefined ? {} : { apiKeyFile }),
- activate: flags.switches.has("--activate"),
+ activate,
+ confirmed: flags.switches.has("--yes"),
+ ...(follow === undefined ? {} : { follow }),
+ };
+ }
+ if (action === "switch") {
+ if (tokens.length !== 2 || (target !== "status" && target !== "cancel")) {
+ return null;
+ }
+ return { kind: "switch", action: target };
+ }
+ if (action === "spaces") {
+ const flags = readFlags(tokens.slice(1), ["--cleanup"], ["--yes"]);
+ if (!flags) return null;
+ const cleanup = flags.values.get("--cleanup");
+ if (cleanup === undefined && flags.switches.has("--yes")) return null;
+ if (cleanup !== undefined && !OPERATION_ID.test(cleanup)) return null;
+ return {
+ kind: "spaces",
+ ...(cleanup === undefined ? {} : { cleanup }),
+ confirmed: flags.switches.has("--yes"),
};
}
if (target === undefined || !OPERATION_ID.test(target)) return null;
@@ -5367,8 +5502,21 @@ function parseModelsCommand(rest: readonly string[]): ModelsCommand | null {
};
}
if (action === "activate") {
- const flags = readFlags(tokens.slice(2), [], ["--confirm", "--yes"]);
- return flags ? { kind: "activate", profileId: target } : null;
+ const flags = readFlags(
+ tokens.slice(2),
+ [],
+ ["--confirm", "--yes", "--wait", "--no-wait"],
+ );
+ if (!flags) return null;
+ const follow = followFlag(flags.switches);
+ if (follow === null) return null;
+ return {
+ kind: "activate",
+ profileId: target,
+ // `--confirm` stays the hidden alias of `--yes`.
+ confirmed: flags.switches.has("--yes") || flags.switches.has("--confirm"),
+ ...(follow === undefined ? {} : { follow }),
+ };
}
if (action === "test") {
return tokens.length === 2 ? { kind: "test", profileId: target } : null;
@@ -5391,6 +5539,35 @@ function parseModelsCommand(rest: readonly string[]): ModelsCommand | null {
return null;
}
+/** `--wait` / `--no-wait`: undefined when neither, null when both. */
+function followFlag(switches: ReadonlySet<string>): boolean | undefined | null {
+ const wait = switches.has("--wait");
+ const noWait = switches.has("--no-wait");
+ if (wait && noWait) return null;
+ return wait ? true : noWait ? false : undefined;
+}
+
+/** Start a probe and read its receipt until it settles (about two minutes). */
+async function probeUntilSettled(
+ reader: CoreReader,
+ operations: CoreOperations,
+ profileId: string,
+ wait?: (milliseconds: number, signal: AbortSignal) => Promise<void>,
+): Promise<ModelProbeFlowDocument> {
+ let document = await startModelProbe(reader, operations, profileId);
+ const pause =
+ wait ??
+ ((milliseconds: number) =>
+ new Promise<void>((resolve) => setTimeout(resolve, milliseconds)));
+ const signal = new AbortController().signal;
+ for (let attempt = 0; attempt < 120; attempt += 1) {
+ if (document.state !== "pending" || !document.operation_id) break;
+ await pause(1_000, signal);
+ document = await readModelProbeReceipt(reader, document.operation_id);
+ }
+ return document;
+}
+
type SourcesCommand =
| {
kind: "ids";
diff --git a/memhub/apps/cli/src/command-catalog.ts b/memhub/apps/cli/src/command-catalog.ts
index 4ef86f9..472c0d0 100644
--- a/memhub/apps/cli/src/command-catalog.ts
+++ b/memhub/apps/cli/src/command-catalog.ts
@@ -361,9 +361,9 @@ export const COMMANDS: readonly CommandDescriptor[] = [
{
name: "models",
summary:
- "管理生成模型配置。add/test 直接提交并返回操作 ID(异步,用 receipt 查结果);edit/activate 直接执行;remove 不可逆,需 --yes。<profile-id>/<operation-id> 都是 UUID;脚本模式的凭据只从受控文件读取。",
+ "管理生成模型配置。add/test 直接提交并返回操作 ID(异步,用 receipt 查结果);edit 直接执行;activate 换了向量模型(模型或维度)时先显示切换计划,需 --yes 确认后重新生成全部向量,switch 查看或取消、spaces 查看或清理旧向量数据;remove 不可逆,需 --yes。<profile-id>/<operation-id> 都是 UUID;脚本模式的凭据只从受控文件读取。",
usage:
- "memhub models list [--json]\n memhub models show <profile-id> [--json]\n memhub models add --config-file <path> [--api-key-file <path>] [--activate] [--json]\n memhub models test <profile-id> [--json]\n memhub models receipt <operation-id> [--json]\n memhub models edit <profile-id> --config-file <path> [--api-key-file <path>] [--json]\n memhub models activate <profile-id> [--json]\n memhub models remove <profile-id> [--yes] [--json]",
+ "memhub models list [--json]\n memhub models show <profile-id> [--json]\n memhub models add --config-file <path> [--api-key-file <path>] [--activate [--yes] [--wait|--no-wait]] [--json]\n memhub models test <profile-id> [--json]\n memhub models receipt <operation-id> [--json]\n memhub models edit <profile-id> --config-file <path> [--api-key-file <path>] [--json]\n memhub models activate <profile-id> [--yes] [--wait|--no-wait] [--json]\n memhub models switch <status|cancel> [--json]\n memhub models spaces [--cleanup <space-id> --yes] [--json]\n memhub models remove <profile-id> [--yes] [--json]",
alternative_usage: "memhub models setup",
options: [
{
@@ -377,7 +377,17 @@ export const COMMANDS: readonly CommandDescriptor[] = [
},
{
flag: "--activate",
- summary: "add 成功后把新配置设为当前使用。",
+ summary:
+ "add 成功后先探测,再按 activate 的规则设为当前使用(向量模型变化时同样要确认切换)。",
+ },
+ {
+ flag: "--wait | --no-wait",
+ summary:
+ "activate 开始向量模型切换后是否跟随进度;终端里默认跟随,Ctrl-C 只停止显示。",
+ },
+ {
+ flag: "--cleanup <space-id>",
+ summary: "spaces:立即删除一个已停用的向量空间(不可恢复,需 --yes)。",
},
DESTRUCTIVE_CONFIRM_OPTION,
JSON_OPTION,
diff --git a/memhub/apps/cli/src/command-contract.test.ts b/memhub/apps/cli/src/command-contract.test.ts
index f3f7263..712679f 100644
--- a/memhub/apps/cli/src/command-contract.test.ts
+++ b/memhub/apps/cli/src/command-contract.test.ts
@@ -635,6 +635,8 @@ describe("documented commands", () => {
"receipt",
"edit",
"activate",
+ "switch",
+ "spaces",
"remove",
],
// Source processing is one Freeze/Thaw switch under `sync`; the obsolete
diff --git a/memhub/apps/cli/src/context-search.ts b/memhub/apps/cli/src/context-search.ts
index 76cabce..92cdf45 100644
--- a/memhub/apps/cli/src/context-search.ts
+++ b/memhub/apps/cli/src/context-search.ts
@@ -97,7 +97,12 @@ export function contextExitCode(document: ContextSearchDocument): number {
}
export function renderContextText(document: ContextSearchDocument): string {
- if (document.state === "unavailable") return "暂时无法查记忆,请稍后重试。\n";
+ if (document.state === "unavailable") {
+ // No lexical fallback: without the embedding service nothing is searched.
+ return document.code === "embedding_unavailable"
+ ? "向量服务不可用,无法检索;请检查向量模型配置。\n"
+ : "暂时无法查记忆,请稍后重试。\n";
+ }
if (document.state === "denied") return "当前应用没有查记忆权限。\n";
if (document.state === "invalid") return "查记忆返回了无法识别的结果。\n";
if (document.state === "rejected") {
diff --git a/memhub/apps/cli/src/core-client.ts b/memhub/apps/cli/src/core-client.ts
index 6c47c05..39a1d45 100644
--- a/memhub/apps/cli/src/core-client.ts
+++ b/memhub/apps/cli/src/core-client.ts
@@ -8,6 +8,9 @@ import axios from "axios";
*/
const READ_ONLY_PATHS = [
"/api/v1/call-events",
+ // Read-only: the registry plus a scan of the vector store's collection names.
+ "/api/v1/embedding-spaces",
+ "/api/v1/embedding-switches/current",
"/api/v1/import-jobs",
"/api/v1/live-sync",
"/api/v1/memory-processing",
@@ -163,10 +166,23 @@ export function createCoreReader(attachment: {
code: detailCode(response.data, response.status),
};
}
- return { state: "unavailable" as const, code: `http_${response.status}` };
+ return {
+ state: "unavailable" as const,
+ code: unavailableCode(response.data, response.status),
+ };
};
}
+/** A 503 that names `embedding_unavailable` keeps it: the search could not
+ * embed its query, which needs another fix than "try again later". */
+function unavailableCode(value: unknown, status: number): string {
+ return status === 503 && detailCode(value, status) === EMBEDDING_UNAVAILABLE
+ ? EMBEDDING_UNAVAILABLE
+ : `http_${status}`;
+}
+
+export const EMBEDDING_UNAVAILABLE = "embedding_unavailable";
+
/** Core's stable `detail` code when it sent one, else the bare status. */
function detailCode(value: unknown, status: number): string {
const detail =
@@ -218,7 +234,10 @@ export function createCoreContextQuery(attachment: {
if (response.status === 404) {
return { state: "not_found" as const, code: "http_404" };
}
- return { state: "unavailable" as const, code: `http_${response.status}` };
+ return {
+ state: "unavailable" as const,
+ code: unavailableCode(response.data, response.status),
+ };
};
}
diff --git a/memhub/apps/cli/src/core-operations.ts b/memhub/apps/cli/src/core-operations.ts
index f6d35de..dd7fb6a 100644
--- a/memhub/apps/cli/src/core-operations.ts
+++ b/memhub/apps/cli/src/core-operations.ts
@@ -32,11 +32,26 @@ const MEMORY_MODE_PATH = "/api/v1/settings/memory-mode";
/** `memhub settings features set|reset` sets the SDK features. */
const MEMORY_FEATURES_PATH = "/api/v1/settings/memory-features";
const ONBOARDING_COMPLETE_PATH = "/api/v1/onboarding/complete";
+const EMBEDDING_SWITCH_PATHS = [
+ "/api/v1/embedding-switches",
+ "/api/v1/embedding-switches/plan",
+] as const;
+const EMBEDDING_SWITCH_CANCEL =
+ /^\/api\/v1\/embedding-switches\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/cancel$/;
+const EMBEDDING_SPACE_PATH =
+ /^\/api\/v1\/embedding-spaces\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const MAX_BYTES = 4 * 1024 * 1024;
export type OperationOutcome<T> =
| { state: "committed"; data: T }
- | { state: "rejected"; code: string; http_status: number }
+ | {
+ state: "rejected";
+ code: string;
+ http_status: number;
+ /** Core's refusal body, when it carries more than the code (a switch
+ * plan rides along with `embedding_switch_required`). */
+ body?: unknown;
+ }
| { state: "unknown"; code: string };
export interface CoreOperations {
@@ -104,6 +119,8 @@ export function createCoreOperations(attachment: {
path !== GRAPH_WIDTH_PATH &&
path !== EVOLVE_PATH &&
path !== ONBOARDING_COMPLETE_PATH &&
+ !(EMBEDDING_SWITCH_PATHS as readonly string[]).includes(path) &&
+ !EMBEDDING_SWITCH_CANCEL.test(path) &&
!MODEL_PROFILE_ACTIVATE.test(path)
) {
throw new Error("core_operation_path_not_allowed");
@@ -121,11 +138,18 @@ export function createCoreOperations(attachment: {
if (response.status >= 200 && response.status < 300) {
return { state: "committed", data: response.data as T };
}
- if (response.status >= 400 && response.status < 500) {
+ if (
+ (response.status >= 400 && response.status < 500) ||
+ // Core answers a refusal it can name with 503 (`sdk_reembed_unavailable`)
+ // or 507 (`insufficient_disk_space`) on the switch routes.
+ ([503, 507].includes(response.status) &&
+ (EMBEDDING_SWITCH_PATHS as readonly string[]).includes(path))
+ ) {
return {
state: "rejected",
code: safeErrorCode(response.data, response.status),
http_status: response.status,
+ body: response.data,
};
}
return {
@@ -204,7 +228,11 @@ export function createCoreOperations(attachment: {
};
},
async delete<T>(path: string, signal?: AbortSignal) {
- if (!SDK_MEMORY_PATH.test(path) && !MODEL_PROFILE_PATH.test(path)) {
+ if (
+ !SDK_MEMORY_PATH.test(path) &&
+ !MODEL_PROFILE_PATH.test(path) &&
+ !EMBEDDING_SPACE_PATH.test(path)
+ ) {
throw new Error("core_operation_path_not_allowed");
}
let response: { status: number; data: unknown };
diff --git a/memhub/apps/cli/src/embedding-switch-cli.test.ts b/memhub/apps/cli/src/embedding-switch-cli.test.ts
new file mode 100644
index 0000000..4a4a06f
--- /dev/null
+++ b/memhub/apps/cli/src/embedding-switch-cli.test.ts
@@ -0,0 +1,488 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { run } from "./cli.js";
+import { renderContextText } from "./context-search.js";
+import { describeEmbeddingSwitchSummary } from "./embedding-switch-flow.js";
+import { composeStatusReport, renderStatusText } from "./status-report.js";
+
+const transport = vi.hoisted(() => ({
+ get: vi.fn(),
+ post: vi.fn(),
+ put: vi.fn(),
+ patch: vi.fn(),
+ delete: vi.fn(),
+}));
+vi.mock("axios", () => ({
+ default: { create: vi.fn(() => transport), get: vi.fn() },
+}));
+
+const runtime = vi.hoisted(() => ({
+ inspectRuntimeStatus: vi.fn(),
+ discoverRuntimeAttachment: vi.fn(),
+}));
+vi.mock("@one-memory/runtime-control", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@one-memory/runtime-control")>()),
+ ...runtime,
+}));
+
+const PROFILE = "44444444-4444-4444-8444-444444444444";
+const JOB = "55555555-5555-4555-8555-555555555555";
+const SPACE = "66666666-6666-4666-8666-666666666666";
+
+function plan(overrides: Record<string, unknown> = {}) {
+ return {
+ needed: true,
+ reason: "embedding_identity_changed",
+ plan_token: "token-1",
+ source: {
+ space_id: "77777777-7777-4777-8777-777777777777",
+ model: "bge-small-zh-v1.5",
+ dims: 512,
+ collection_base: "memhub_aaaaaaaaaaaaaaaa",
+ vectors: 12480,
+ },
+ target: {
+ space_id: null,
+ model: "text-embedding-v3",
+ dims: 1024,
+ collection_base: "",
+ },
+ target_profile_id: PROFILE,
+ target_revision: 5,
+ target_provider_kind: "openai_compatible",
+ target_local: false,
+ sources: [],
+ total_vectors: 12480,
+ users: 2,
+ graph_vectors: null,
+ estimate_s: 120,
+ requests: 195,
+ disk_bytes_needed: 70 * 1024 * 1024,
+ disk_bytes_free: 10 * 1024 * 1024 * 1024,
+ retention_days: 14,
+ blockers: [],
+ ...overrides,
+ };
+}
+
+function job(
+ state: string,
+ percent: number,
+ extra: Record<string, unknown> = {},
+) {
+ return {
+ job_id: JOB,
+ kind: "switch",
+ state,
+ source: plan().source,
+ target: { ...plan().target, space_id: SPACE },
+ stray_space_ids: [],
+ target_profile_id: PROFILE,
+ target_revision: 5,
+ requested_by: "cli",
+ progress: {
+ phase: state === "reembedding" ? "vectors" : "prepare",
+ done: Math.round((12480 * percent) / 100),
+ total: 12480,
+ percent,
+ eta_s: 60,
+ },
+ cancel_requested: false,
+ error_code: null,
+ attempt: 1,
+ created_at: "T1",
+ updated_at: "T1",
+ finished_at: state === "done" ? "T2" : null,
+ ...extra,
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ for (const method of Object.values(transport)) method.mockReset();
+ runtime.inspectRuntimeStatus.mockResolvedValue({
+ state: "running",
+ code: "runtime_verified",
+ instanceId: "instance-1",
+ host: "127.0.0.1",
+ port: 8765,
+ version: "1.2.3",
+ });
+ runtime.discoverRuntimeAttachment.mockResolvedValue({
+ instanceId: "instance-1",
+ apiToken: "synthetic-runtime-token",
+ host: "127.0.0.1",
+ port: 8765,
+ servicePid: 4242,
+ health: {
+ status: "ok",
+ service: "one-memory-core",
+ version: "1.2.3",
+ instance_id: "instance-1",
+ },
+ });
+});
+
+describe("models activate with an embedding change", () => {
+ it("prints the plan and exits 2 without --yes on a non-terminal", async () => {
+ transport.post.mockImplementation(async (url: string) =>
+ url === "/api/v1/embedding-switches/plan"
+ ? { status: 200, data: plan() }
+ : { status: 404, data: {} },
+ );
+ const result = await capturedRun(["models", "activate", PROFILE]);
+ expect(result.code).toBe(2);
+ expect(result.stdout).toContain("将更换向量模型");
+ expect(result.stdout).toContain("bge-small-zh-v1.5(512 维)");
+ expect(result.stdout).toContain("text-embedding-v3(1024 维)");
+ expect(result.stdout).toContain("12,480");
+ expect(result.stdout).toContain("重新运行并加上 --yes 以确认");
+ expect(transport.post.mock.calls.map(([url]) => url)).toEqual([
+ "/api/v1/embedding-switches/plan",
+ ]);
+ });
+
+ it("starts the switch with --yes and emits JSON progress lines", async () => {
+ transport.post.mockImplementation(async (url: string) => {
+ if (url === "/api/v1/embedding-switches/plan") {
+ return { status: 200, data: plan() };
+ }
+ if (url === "/api/v1/embedding-switches") {
+ return { status: 202, data: job("preparing", 0) };
+ }
+ return { status: 404, data: {} };
+ });
+ const answers = [
+ {
+ phase: "running",
+ writes_paused: true,
+ job: job("reembedding", 50),
+ last_finished: null,
+ },
+ {
+ phase: "idle",
+ writes_paused: false,
+ job: null,
+ last_finished: job("done", 100),
+ },
+ ];
+ transport.get.mockImplementation(async (url: string) =>
+ url === "/api/v1/embedding-switches/current"
+ ? { status: 200, data: { schema_version: 1, ...answers.shift() } }
+ : { status: 404, data: {} },
+ );
+ const result = await capturedRun(
+ ["models", "activate", PROFILE, "--yes", "--wait", "--json"],
+ { watchWait: async () => undefined },
+ );
+ expect(result.code).toBe(0);
+ const lines = result.stdout
+ .trim()
+ .split("\n")
+ .map((line) => JSON.parse(line));
+ expect(lines.map((line) => line.state)).toEqual([
+ "preparing",
+ "reembedding",
+ "done",
+ "done",
+ ]);
+ expect(lines[1]).toMatchObject({ percent: 50, job_id: JOB });
+ expect(lines.at(-1)).toMatchObject({ result: "switched" });
+ expect(transport.post).toHaveBeenCalledWith(
+ "/api/v1/embedding-switches",
+ {
+ profile_id: PROFILE,
+ expected_revision: 5,
+ plan_token: "token-1",
+ requested_by: "cli",
+ },
+ undefined,
+ );
+ });
+
+ it("refuses a plan with blockers and starts nothing", async () => {
+ transport.post.mockResolvedValue({
+ status: 200,
+ data: plan({ blockers: ["sdk_reembed_unavailable"] }),
+ });
+ const result = await capturedRun([
+ "models",
+ "activate",
+ PROFILE,
+ "--yes",
+ "--json",
+ ]);
+ expect(result.code).toBe(1);
+ expect(JSON.parse(result.stdout)).toMatchObject({
+ state: "blocked",
+ code: "sdk_reembed_unavailable",
+ });
+ expect(transport.post).toHaveBeenCalledTimes(1);
+ });
+
+ it("says nothing is re-embedded when only generation changed", async () => {
+ transport.post.mockImplementation(async (url: string) =>
+ url === "/api/v1/embedding-switches/plan"
+ ? {
+ status: 200,
+ data: plan({ needed: false, reason: "same_embedding" }),
+ }
+ : { status: 200, data: profileResponse() },
+ );
+ const result = await capturedRun(["models", "activate", PROFILE]);
+ expect(result.code).toBe(0);
+ expect(result.stdout).toContain("向量模型未变化,无需重新生成向量。");
+ });
+
+ it("reads the plan carried by a 409 embedding_switch_required", async () => {
+ transport.post.mockImplementation(async (url: string) =>
+ url.endsWith("/activate")
+ ? {
+ status: 409,
+ data: { detail: "embedding_switch_required", plan: plan() },
+ }
+ : { status: 404, data: { detail: "Not Found" } },
+ );
+ const result = await capturedRun(["models", "activate", PROFILE, "--json"]);
+ expect(result.code).toBe(2);
+ expect(JSON.parse(result.stdout)).toMatchObject({
+ state: "confirmation_required",
+ code: "embedding_switch_required",
+ });
+ });
+});
+
+describe("models switch and spaces", () => {
+ it("reports no switch, then cancels the running one", async () => {
+ transport.get.mockResolvedValueOnce({
+ status: 200,
+ data: {
+ schema_version: 1,
+ phase: "idle",
+ writes_paused: false,
+ job: null,
+ last_finished: null,
+ },
+ });
+ const idle = await capturedRun(["models", "switch", "status"]);
+ expect(idle.code).toBe(0);
+ expect(idle.stdout).toContain("没有进行中的向量模型切换");
+
+ transport.get.mockResolvedValueOnce({
+ status: 200,
+ data: {
+ schema_version: 1,
+ phase: "running",
+ writes_paused: true,
+ job: job("reembedding", 20),
+ last_finished: null,
+ },
+ });
+ transport.post.mockResolvedValue({
+ status: 200,
+ data: job("reembedding", 20, { cancel_requested: true }),
+ });
+ const cancelled = await capturedRun([
+ "models",
+ "switch",
+ "cancel",
+ "--json",
+ ]);
+ expect(cancelled.code).toBe(0);
+ expect(transport.post).toHaveBeenCalledWith(
+ `/api/v1/embedding-switches/${JOB}/cancel`,
+ {},
+ undefined,
+ );
+ expect(JSON.parse(cancelled.stdout)).toMatchObject({
+ cancel_requested: true,
+ });
+ });
+
+ it("lists spaces and needs --yes before cleaning one up", async () => {
+ transport.get.mockResolvedValue({
+ status: 200,
+ data: {
+ schema_version: 1,
+ live_space_id: "x",
+ spaces: [
+ {
+ space_id: SPACE,
+ state: "retired",
+ model: "bge-small-zh-v1.5",
+ dims: 512,
+ vectors: 10,
+ keep_until: "2026-11-15T00:00:00+00:00",
+ },
+ {
+ space_id: "88888888-8888-4888-8888-888888888888",
+ state: "dropped",
+ model: "m",
+ dims: 8,
+ },
+ ],
+ scanned: [],
+ scan_error: null,
+ },
+ });
+ const listed = await capturedRun(["models", "spaces"]);
+ expect(listed.code).toBe(0);
+ expect(listed.stdout).toContain("已停用");
+ expect(listed.stdout).toContain("保留到 2026-11-15");
+ expect(listed.stdout).not.toContain("88888888");
+
+ const preview = await capturedRun(["models", "spaces", "--cleanup", SPACE]);
+ expect(preview.code).toBe(0);
+ expect(preview.stdout).toContain("--yes");
+ expect(transport.delete).not.toHaveBeenCalled();
+
+ transport.delete.mockResolvedValue({
+ status: 200,
+ data: { schema_version: 1 },
+ });
+ const dropped = await capturedRun([
+ "models",
+ "spaces",
+ "--cleanup",
+ SPACE,
+ "--yes",
+ ]);
+ expect(dropped.code).toBe(0);
+ expect(transport.delete).toHaveBeenCalledWith(
+ `/api/v1/embedding-spaces/${SPACE}`,
+ undefined,
+ );
+ });
+});
+
+describe("status and search wording", () => {
+ it("shows the switch line in memhub status", async () => {
+ const reader = async (path: string) =>
+ path === "/api/v1/memory-processing"
+ ? {
+ state: "ok" as const,
+ data: {
+ pending: 3,
+ fresh_pending: 1,
+ backlog_pending: 2,
+ outside_window_pending: 0,
+ running: 0,
+ waiting_for_model: 0,
+ completed: 9,
+ failed: 0,
+ embedding_switch: {
+ job_id: JOB,
+ kind: "switch",
+ state: "reembedding",
+ percent: 50,
+ eta_s: 60,
+ },
+ },
+ }
+ : { state: "unavailable" as const, code: "http_503" };
+ const report = await composeStatusReport({
+ dataDir: "/synthetic/data",
+ runtime: {
+ state: "running",
+ code: "runtime_verified",
+ instanceId: "instance-1",
+ host: "127.0.0.1",
+ port: 8765,
+ } as never,
+ background: null,
+ reader: reader as never,
+ });
+ const text = renderStatusText(report, "MemHub");
+ expect(text).toContain("向量模型:切换中 50%,记忆整理已暂停");
+ expect(
+ describeEmbeddingSwitchSummary({
+ kind: "merge",
+ state: "reembedding",
+ percent: 30,
+ }),
+ ).toBe("正在合并旧向量数据 30%,记忆整理已暂停");
+ expect(
+ describeEmbeddingSwitchSummary({
+ kind: "merge",
+ state: "scanning",
+ percent: 0,
+ }),
+ ).toBe("正在检查向量数据…");
+ });
+
+ it("names an unavailable embedding service instead of 'try later'", () => {
+ expect(
+ renderContextText({
+ schema_version: 2,
+ product: "memhub",
+ state: "unavailable",
+ code: "embedding_unavailable",
+ items: [],
+ }),
+ ).toContain("向量服务不可用");
+ });
+});
+
+function profileResponse() {
+ return {
+ profile_id: PROFILE,
+ name: "Synthetic",
+ provider_kind: "openai_compatible",
+ base_url: "https://example.invalid/v1",
+ model: "synthetic-model-2",
+ embedding_model: "text-embedding-v3",
+ embedding_provider_kind: "openai_compatible",
+ embedding_base_url: "https://example.invalid/v1",
+ embedding_dimensions: 1024,
+ has_api_key: true,
+ credential_state: "available",
+ timeout_seconds: 30,
+ max_concurrency: 1,
+ context_window: null,
+ disable_thinking: true,
+ capabilities: {
+ endpoint_reachable: true,
+ model_available: true,
+ structured_output: true,
+ embedding_available: true,
+ },
+ revision: 5,
+ is_active: true,
+ created_at: "2026-09-19T00:00:00Z",
+ updated_at: "2026-09-19T00:00:00Z",
+ };
+}
+
+async function capturedRun(
+ arguments_: string[],
+ controls: Parameters<typeof run>[2] = {},
+) {
+ let stdout = "";
+ let stderr = "";
+ const stdoutSpy = vi
+ .spyOn(process.stdout, "write")
+ .mockImplementation((chunk) => {
+ stdout += String(chunk);
+ return true;
+ });
+ const stderrSpy = vi
+ .spyOn(process.stderr, "write")
+ .mockImplementation((chunk) => {
+ stderr += String(chunk);
+ return true;
+ });
+ try {
+ return {
+ code: await run(
+ arguments_,
+ { ONE_MEMORY_DATA_DIR: "/synthetic/data" },
+ { stdinIsTTY: false, ...controls },
+ ),
+ stdout,
+ stderr,
+ };
+ } finally {
+ stdoutSpy.mockRestore();
+ stderrSpy.mockRestore();
+ }
+}
diff --git a/memhub/apps/cli/src/embedding-switch-flow.ts b/memhub/apps/cli/src/embedding-switch-flow.ts
new file mode 100644
index 0000000..154bfef
--- /dev/null
+++ b/memhub/apps/cli/src/embedding-switch-flow.ts
@@ -0,0 +1,847 @@
+/**
+ * Switching the embedding model from the CLI: `models activate` when the
+ * embedding changes, `models switch status|cancel`, `models spaces`.
+ *
+ * Core owns every decision (`/api/v1/embedding-switches*`, contract
+ * `docs/contracts/embedding-switch-v1.md`). A change of embedding model or
+ * width is never applied by activation alone: Core plans a switch, the user
+ * confirms it, Core re-embeds every memory into a new space and only then
+ * makes it live. The CLI shows the plan, asks, starts the job and follows it.
+ */
+
+import type { CoreReader } from "./core-client.js";
+import type {
+ CoreDeleteOperations,
+ CoreOperations,
+ OperationOutcome,
+} from "./core-operations.js";
+import { EXIT_FAILED, EXIT_OK, EXIT_USAGE } from "./exit-codes.js";
+import {
+ activateModelProfile,
+ type ModelWriteDocument,
+ modelProfileResult,
+ renderModelWriteText,
+} from "./model-write-flows.js";
+import { PRODUCT } from "./version.js";
+
+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+const CODE = /^[a-z0-9_.:-]{1,128}$/;
+const TERMINAL = new Set(["done", "rolled_back"]);
+const POLL_MS = 1_000;
+
+export interface SpaceSummary {
+ space_id: string | null;
+ model: string | null;
+ dims: number | null;
+ collection_base: string;
+ vectors?: number | null;
+}
+
+export interface EmbeddingSwitchPlan {
+ needed: boolean;
+ reason: string;
+ plan_token: string;
+ source: SpaceSummary;
+ target: SpaceSummary;
+ target_profile_id: string;
+ target_revision: number;
+ target_provider_kind: string;
+ target_local: boolean;
+ total_vectors: number;
+ users: number | null;
+ graph_vectors: number | null;
+ estimate_s: number | null;
+ requests: number | null;
+ disk_bytes_needed: number;
+ disk_bytes_free: number | null;
+ retention_days: number;
+ blockers: string[];
+}
+
+export interface SwitchProgress {
+ phase: string;
+ done: number;
+ total: number;
+ percent: number;
+ eta_s: number | null;
+}
+
+export interface EmbeddingSwitchJob {
+ job_id: string;
+ kind: "switch" | "merge";
+ state: string;
+ source: SpaceSummary;
+ target: SpaceSummary;
+ progress: SwitchProgress;
+ cancel_requested: boolean;
+ error_code: string | null;
+ finished_at: string | null;
+}
+
+export interface SwitchCurrent {
+ phase: "idle" | "scanning" | "running";
+ writes_paused: boolean;
+ job: EmbeddingSwitchJob | null;
+ last_finished: EmbeddingSwitchJob | null;
+}
+
+export interface SwitchIo {
+ reader: CoreReader;
+ operations: CoreOperations & CoreDeleteOperations;
+ emit: (text: string) => void;
+ asJson: boolean;
+ /** A terminal is attached: may prompt, and follows progress by default. */
+ interactive: boolean;
+ confirm?: (question: string) => Promise<boolean>;
+ wait?: (milliseconds: number, signal: AbortSignal) => Promise<void>;
+ signal?: AbortSignal;
+}
+
+export interface ActivateOptions {
+ confirmed: boolean;
+ /** `--wait` / `--no-wait`; undefined follows on a terminal only. */
+ follow?: boolean;
+}
+
+// ---------------------------------------------------------------------------
+// Parsing: bounded projections of Core's answers, never passthrough.
+// ---------------------------------------------------------------------------
+
+function record(value: unknown): Record<string, unknown> | null {
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : null;
+}
+
+function int(value: unknown): number | null {
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0
+ ? value
+ : null;
+}
+
+function str(value: unknown, max = 256): string | null {
+ return typeof value === "string" && value.length <= max ? value : null;
+}
+
+function space(value: unknown): SpaceSummary | null {
+ const item = record(value);
+ if (!item) return null;
+ return {
+ space_id: str(item.space_id, 64),
+ model: str(item.model),
+ dims: int(item.dims),
+ collection_base: str(item.collection_base) ?? "",
+ vectors: int(item.vectors),
+ };
+}
+
+export function parsePlan(value: unknown): EmbeddingSwitchPlan | null {
+ const plan = record(value);
+ if (!plan || typeof plan.needed !== "boolean") return null;
+ const source = space(plan.source);
+ const target = space(plan.target);
+ const token = str(plan.plan_token, 128);
+ const profile = str(plan.target_profile_id, 128);
+ const revision = int(plan.target_revision);
+ if (!source || !target || !token || !profile || revision === null) {
+ return null;
+ }
+ const blockers = Array.isArray(plan.blockers)
+ ? plan.blockers.filter(
+ (item): item is string => typeof item === "string" && CODE.test(item),
+ )
+ : [];
+ return {
+ needed: plan.needed,
+ reason: str(plan.reason, 64) ?? "",
+ plan_token: token,
+ source,
+ target,
+ target_profile_id: profile,
+ target_revision: revision,
+ target_provider_kind: str(plan.target_provider_kind, 64) ?? "",
+ target_local: plan.target_local === true,
+ total_vectors: int(plan.total_vectors) ?? 0,
+ users: int(plan.users),
+ graph_vectors: int(plan.graph_vectors),
+ estimate_s: int(plan.estimate_s),
+ requests: int(plan.requests),
+ disk_bytes_needed: int(plan.disk_bytes_needed) ?? 0,
+ disk_bytes_free: int(plan.disk_bytes_free),
+ retention_days: int(plan.retention_days) ?? 14,
+ blockers,
+ };
+}
+
+export function parseJob(value: unknown): EmbeddingSwitchJob | null {
+ const job = record(value);
+ if (!job) return null;
+ const jobId = str(job.job_id, 64);
+ const state = str(job.state, 32);
+ const source = space(job.source);
+ const target = space(job.target);
+ const progress = record(job.progress) ?? {};
+ if (!jobId || !state || !source || !target) return null;
+ if (job.kind !== "switch" && job.kind !== "merge") return null;
+ const percent =
+ typeof progress.percent === "number" && Number.isFinite(progress.percent)
+ ? Math.min(100, Math.max(0, progress.percent))
+ : 0;
+ return {
+ job_id: jobId,
+ kind: job.kind,
+ state,
+ source,
+ target,
+ progress: {
+ phase: str(progress.phase, 32) ?? "prepare",
+ done: int(progress.done) ?? 0,
+ total: int(progress.total) ?? 0,
+ percent,
+ eta_s: int(progress.eta_s),
+ },
+ cancel_requested: job.cancel_requested === true,
+ error_code:
+ typeof job.error_code === "string" && CODE.test(job.error_code)
+ ? job.error_code
+ : null,
+ finished_at: str(job.finished_at, 64),
+ };
+}
+
+export function parseCurrent(value: unknown): SwitchCurrent | null {
+ const current = record(value);
+ if (!current) return null;
+ const phase = current.phase;
+ if (phase !== "idle" && phase !== "scanning" && phase !== "running") {
+ return null;
+ }
+ return {
+ phase,
+ writes_paused: current.writes_paused === true,
+ job: current.job == null ? null : parseJob(current.job),
+ last_finished:
+ current.last_finished == null ? null : parseJob(current.last_finished),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Wording
+// ---------------------------------------------------------------------------
+
+const BLOCKER_TEXT: Record<string, string> = {
+ embedding_switch_running: "上一次向量模型切换还在进行,请等待完成或先取消。",
+ embedding_probe_required: "新配置还没有通过探测;先运行 memhub models test。",
+ sdk_reembed_unavailable:
+ "当前运行时的 SDK 不支持重新生成向量,请先升级 MemHub。",
+ embedding_switch_requires_migration:
+ "还有旧版本的向量数据没有迁移完,请先完成升级迁移。",
+ embedding_dimensions_unknown:
+ "新配置的向量维度未知;先探测或在配置里写明 embedding_dimensions。",
+ insufficient_disk_space: "磁盘空间不足,无法容纳新旧两份向量数据。",
+};
+
+const FAILURE_TEXT: Record<string, string> = {
+ writes_did_not_drain: "等待正在进行的记忆整理结束超时",
+ embedding_service_failed: "向量服务连续请求失败",
+ embedding_dimensions_mismatch: "向量服务返回的维度与探测到的不一致",
+ embedding_verification_failed: "新向量没有通过校验",
+ target_profile_changed: "切换期间目标配置被修改",
+ embedding_switch_cancelled: "已取消",
+ model_secret_unavailable: "读不到向量服务的 API Key",
+ secure_storage_unavailable: "系统钥匙串不可用",
+ embedding_switch_clients_busy: "记忆图谱一直被占用,无法重新生成",
+};
+
+const STATE_TEXT: Record<string, string> = {
+ preparing: "准备中(等待记忆整理暂停)",
+ reembedding: "重新生成向量",
+ verifying: "校验新向量",
+ committing: "正式切换",
+ failed: "正在回滚",
+ done: "已完成",
+ rolled_back: "已回滚",
+};
+
+export function blockerText(code: string): string {
+ return BLOCKER_TEXT[code] ?? code;
+}
+
+function spaceLabel(item: SpaceSummary, local?: boolean): string {
+ const dims = item.dims === null ? "维度未知" : `${item.dims} 维`;
+ return `${item.model ?? "未知模型"}(${dims}${local ? ",本地" : ""})`;
+}
+
+function duration(seconds: number | null): string {
+ if (seconds === null) return "未知";
+ if (seconds < 60) return `${Math.max(1, seconds)} 秒`;
+ return `${Math.round(seconds / 60)} 分钟`;
+}
+
+function megabytes(bytes: number | null): string {
+ return bytes === null ? "未知" : `${Math.ceil(bytes / (1024 * 1024))} MB`;
+}
+
+export function renderPlanText(plan: EmbeddingSwitchPlan): string {
+ const lines = [
+ `将更换向量模型:${spaceLabel(plan.source)} → ${spaceLabel(plan.target, plan.target_local)}`,
+ `需要用新模型重新生成 ${plan.total_vectors.toLocaleString("en-US")} 条向量` +
+ `${plan.users === null ? "" : `(${plan.users} 个用户)`}` +
+ `,预计约 ${duration(plan.estimate_s)}` +
+ `${plan.requests === null ? ",在本机计算,不产生费用" : `,约 ${plan.requests} 次请求`}` +
+ `,额外磁盘约 ${megabytes(plan.disk_bytes_needed)}。`,
+ ];
+ if (plan.graph_vectors) {
+ lines.push(`记忆图谱另有 ${plan.graph_vectors} 条向量一并重新生成。`);
+ }
+ if (
+ plan.source.dims !== null &&
+ plan.source.dims === plan.target.dims &&
+ plan.source.model !== plan.target.model
+ ) {
+ lines.push("新旧模型维度相同,但向量不能通用,仍需重新生成。");
+ }
+ lines.push(
+ "切换期间记忆整理暂停,检索继续使用旧模型;完成并校验通过后才会生效。",
+ `旧的向量数据保留 ${plan.retention_days} 天,可用 memhub models spaces 清理。`,
+ );
+ for (const blocker of plan.blockers) {
+ lines.push(`无法开始:${blockerText(blocker)}`);
+ }
+ return `${lines.join("\n")}\n`;
+}
+
+export function renderProgressLine(job: EmbeddingSwitchJob): string {
+ const what = job.kind === "merge" ? "正在合并旧向量数据" : "正在切换向量模型";
+ const state = STATE_TEXT[job.state] ?? job.state;
+ if (job.state === "reembedding" && job.progress.total > 0) {
+ const eta =
+ job.progress.eta_s === null
+ ? ""
+ : ` 预计还需 ${duration(job.progress.eta_s)}`;
+ return `${what}:${state} ${job.progress.done.toLocaleString("en-US")}/${job.progress.total.toLocaleString("en-US")} ${Math.floor(job.progress.percent)}%${eta}`;
+ }
+ return `${what}:${state}`;
+}
+
+export function renderOutcomeText(job: EmbeddingSwitchJob): string {
+ if (job.state === "done") {
+ return job.kind === "merge"
+ ? "旧向量数据已合并,记忆整理已恢复。\n"
+ : `已切换到 ${job.target.model ?? "新模型"}。\n`;
+ }
+ const code = job.error_code ?? "embedding_switch_failed";
+ if (code === "embedding_switch_cancelled") {
+ return `已取消切换,继续使用 ${job.source.model ?? "旧模型"}。\n`;
+ }
+ return `切换未完成,已恢复使用 ${job.source.model ?? "旧模型"},数据未受影响。原因:${FAILURE_TEXT[code] ?? code}(${code})\n`;
+}
+
+/** One line for `memhub status`, from `memory-processing.embedding_switch`. */
+export function describeEmbeddingSwitchSummary(value: unknown): string | null {
+ const summary = record(value);
+ if (!summary) return null;
+ const percent =
+ typeof summary.percent === "number" && Number.isFinite(summary.percent)
+ ? Math.floor(summary.percent)
+ : 0;
+ if (summary.state === "scanning") return "正在检查向量数据…";
+ if (summary.kind === "merge") {
+ return `正在合并旧向量数据 ${percent}%,记忆整理已暂停`;
+ }
+ if (summary.state === "failed") return "切换未完成,正在恢复旧向量模型";
+ return `切换中 ${percent}%,记忆整理已暂停`;
+}
+
+// ---------------------------------------------------------------------------
+// Flows
+// ---------------------------------------------------------------------------
+
+function document(
+ command: string,
+ fields: Record<string, unknown>,
+): Record<string, unknown> {
+ return { schema_version: 1, product: PRODUCT, command, ...fields };
+}
+
+function emitDocument(io: SwitchIo, value: Record<string, unknown>): void {
+ io.emit(`${JSON.stringify(value)}\n`);
+}
+
+async function requestPlan(
+ profileId: string,
+ io: SwitchIo,
+): Promise<
+ | { state: "plan"; plan: EmbeddingSwitchPlan }
+ | { state: "unsupported" }
+ | { state: "failed"; code: string }
+> {
+ const outcome = await io.operations.post<unknown>(
+ "/api/v1/embedding-switches/plan",
+ { profile_id: profileId },
+ );
+ if (outcome.state === "committed") {
+ const plan = parsePlan(outcome.data);
+ // Not a plan: activation itself still refuses an embedding change.
+ return plan ? { state: "plan", plan } : { state: "unsupported" };
+ }
+ if (outcome.state === "rejected") {
+ // A Core before the registry has no plan route: activation as before.
+ if (outcome.http_status === 404 && outcome.code === "http_404") {
+ return { state: "unsupported" };
+ }
+ const plan = parsePlan(record(outcome.body)?.plan);
+ if (plan) return { state: "plan", plan };
+ return { state: "failed", code: outcome.code };
+ }
+ return { state: "failed", code: outcome.code };
+}
+
+function emitActivation(io: SwitchIo, result: ModelWriteDocument): number {
+ io.emit(
+ io.asJson ? `${JSON.stringify(result)}\n` : renderModelWriteText(result),
+ );
+ return result.state === "committed" ? EXIT_OK : EXIT_FAILED;
+}
+
+/**
+ * `memhub models activate <id> [--yes] [--wait|--no-wait] [--json]`.
+ *
+ * Asks Core for the plan first. No embedding change: activate as before.
+ * An embedding change: show the plan, confirm (`--yes`, or a prompt on a
+ * terminal; exit 2 otherwise), start the switch and follow it.
+ */
+export async function activateWithEmbeddingSwitch(
+ profileId: string,
+ options: ActivateOptions,
+ io: SwitchIo,
+): Promise<number> {
+ if (!UUID.test(profileId)) {
+ return emitActivation(
+ io,
+ await activateModelProfile(profileId, io.operations),
+ );
+ }
+ const planned = await requestPlan(profileId, io);
+ if (planned.state === "unsupported") {
+ const activated = await activateOrPlan(profileId, io);
+ return activated.state === "plan"
+ ? confirmAndSwitch(activated.plan, options, io)
+ : emitActivation(io, activated.result);
+ }
+ if (planned.state === "failed") {
+ return reject(io, "models activate", planned.code);
+ }
+ const plan = planned.plan;
+ if (!plan.needed) {
+ if (!io.asJson && plan.reason === "same_embedding") {
+ io.emit("向量模型未变化,无需重新生成向量。\n");
+ }
+ const activated = await activateOrPlan(profileId, io);
+ if (activated.state === "plan") {
+ return confirmAndSwitch(activated.plan, options, io);
+ }
+ return emitActivation(io, activated.result);
+ }
+ return confirmAndSwitch(plan, options, io);
+}
+
+async function activateOrPlan(
+ profileId: string,
+ io: SwitchIo,
+): Promise<
+ | { state: "plan"; plan: EmbeddingSwitchPlan }
+ | { state: "activated"; result: ModelWriteDocument }
+> {
+ const result: OperationOutcome<unknown> = await io.operations.post<unknown>(
+ `/api/v1/model-profiles/${encodeURIComponent(profileId)}/activate`,
+ {},
+ );
+ if (
+ result.state === "rejected" &&
+ result.code === "embedding_switch_required"
+ ) {
+ const plan = parsePlan(record(result.body)?.plan);
+ if (plan) return { state: "plan", plan };
+ }
+ return { state: "activated", result: modelProfileResult(profileId, result) };
+}
+
+function reject(io: SwitchIo, command: string, code: string): number {
+ if (io.asJson) {
+ emitDocument(io, document(command, { state: "rejected", code }));
+ } else {
+ io.emit(`${command} 未完成:${blockerText(code)}(${code})\n`);
+ }
+ return EXIT_FAILED;
+}
+
+async function confirmAndSwitch(
+ plan: EmbeddingSwitchPlan,
+ options: ActivateOptions,
+ io: SwitchIo,
+): Promise<number> {
+ if (plan.blockers.length > 0) {
+ if (io.asJson) {
+ emitDocument(
+ io,
+ document("models activate", {
+ state: "blocked",
+ code: plan.blockers[0],
+ plan,
+ }),
+ );
+ } else {
+ io.emit(renderPlanText(plan));
+ }
+ return EXIT_FAILED;
+ }
+ if (!options.confirmed) {
+ const ask = io.interactive && !io.asJson ? io.confirm : undefined;
+ if (ask === undefined) {
+ if (io.asJson) {
+ emitDocument(
+ io,
+ document("models activate", {
+ state: "confirmation_required",
+ code: "embedding_switch_required",
+ plan,
+ next_step: `${PRODUCT} models activate ${plan.target_profile_id} --yes`,
+ }),
+ );
+ } else {
+ io.emit(`${renderPlanText(plan)}重新运行并加上 --yes 以确认\n`);
+ }
+ return EXIT_USAGE;
+ }
+ io.emit(renderPlanText(plan));
+ if (!(await ask("继续?[y/N] "))) {
+ io.emit("未开始切换,仍在使用原来的向量模型。\n");
+ return EXIT_OK;
+ }
+ }
+ const started = await io.operations.post<unknown>(
+ "/api/v1/embedding-switches",
+ {
+ profile_id: plan.target_profile_id,
+ expected_revision: plan.target_revision,
+ plan_token: plan.plan_token,
+ requested_by: "cli",
+ },
+ );
+ if (started.state !== "committed") {
+ return reject(io, "models activate", started.code);
+ }
+ const job = parseJob(started.data);
+ if (!job) return reject(io, "models activate", "embedding_switch_invalid");
+ const follow = options.follow ?? io.interactive;
+ if (!follow) {
+ if (io.asJson) {
+ emitDocument(io, document("models activate", progressFields(job)));
+ } else {
+ io.emit(
+ `已开始切换向量模型(${job.job_id})。用 memhub models switch status 查看进度。\n`,
+ );
+ }
+ return EXIT_OK;
+ }
+ return followJob(job, io, "models activate");
+}
+
+function progressFields(job: EmbeddingSwitchJob): Record<string, unknown> {
+ return {
+ state: job.state,
+ job_id: job.job_id,
+ kind: job.kind,
+ phase: job.progress.phase,
+ percent: job.progress.percent,
+ done: job.progress.done,
+ total: job.progress.total,
+ eta_s: job.progress.eta_s,
+ ...(job.error_code ? { code: job.error_code } : {}),
+ };
+}
+
+async function readCurrent(io: SwitchIo): Promise<SwitchCurrent | null> {
+ const outcome = await io.reader<unknown>(
+ "/api/v1/embedding-switches/current",
+ );
+ return outcome.state === "ok" ? parseCurrent(outcome.data) : null;
+}
+
+/** Poll `current` until the job ends or the user stops watching. */
+async function followJob(
+ started: EmbeddingSwitchJob,
+ io: SwitchIo,
+ command: string,
+): Promise<number> {
+ const wait = io.wait ?? defaultWait;
+ const signal = io.signal ?? new AbortController().signal;
+ let last = "";
+ let job = started;
+ const show = (value: EmbeddingSwitchJob) => {
+ const line = io.asJson
+ ? JSON.stringify(document(command, progressFields(value)))
+ : renderProgressLine(value);
+ if (line !== last) {
+ io.emit(`${line}\n`);
+ last = line;
+ }
+ };
+ show(job);
+ if (!io.asJson) {
+ io.emit(
+ "(Ctrl-C 只停止显示;用 `memhub models switch cancel` 取消切换)\n",
+ );
+ }
+ while (!TERMINAL.has(job.state)) {
+ try {
+ await wait(POLL_MS, signal);
+ } catch {
+ // Aborted below.
+ }
+ if (signal.aborted) {
+ if (!io.asJson) {
+ io.emit(
+ "已停止显示进度;切换仍在后台进行。用 `memhub models switch cancel` 取消。\n",
+ );
+ }
+ return EXIT_OK;
+ }
+ const current = await readCurrent(io);
+ if (current === null) continue;
+ const next =
+ current.job?.job_id === job.job_id
+ ? current.job
+ : current.last_finished?.job_id === job.job_id
+ ? current.last_finished
+ : null;
+ if (next === null) continue;
+ job = next;
+ show(job);
+ }
+ if (io.asJson) {
+ emitDocument(
+ io,
+ document(command, {
+ ...progressFields(job),
+ result: job.state === "done" ? "switched" : "rolled_back",
+ }),
+ );
+ } else {
+ io.emit(renderOutcomeText(job));
+ }
+ return job.state === "done" ? EXIT_OK : EXIT_FAILED;
+}
+
+function defaultWait(milliseconds: number, signal: AbortSignal): Promise<void> {
+ return new Promise((resolve, reject) => {
+ if (signal.aborted) {
+ reject(new Error("aborted"));
+ return;
+ }
+ const timer = setTimeout(() => {
+ signal.removeEventListener("abort", onAbort);
+ resolve();
+ }, milliseconds);
+ const onAbort = () => {
+ clearTimeout(timer);
+ reject(new Error("aborted"));
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ });
+}
+
+/** `memhub models switch status [--json]`. */
+export async function switchStatus(io: SwitchIo): Promise<number> {
+ const outcome = await io.reader<unknown>(
+ "/api/v1/embedding-switches/current",
+ );
+ if (outcome.state !== "ok")
+ return reject(io, "models switch status", outcome.code);
+ const current = parseCurrent(outcome.data);
+ if (!current) {
+ return reject(io, "models switch status", "embedding_switch_invalid");
+ }
+ if (io.asJson) {
+ emitDocument(
+ io,
+ document("models switch status", {
+ state: current.phase,
+ writes_paused: current.writes_paused,
+ job: current.job ? progressFields(current.job) : null,
+ last_finished: current.last_finished
+ ? progressFields(current.last_finished)
+ : null,
+ }),
+ );
+ return EXIT_OK;
+ }
+ if (current.job) {
+ io.emit(
+ `${renderProgressLine(current.job)}\n记忆整理已暂停,检索不受影响。\n`,
+ );
+ } else if (current.phase === "scanning") {
+ io.emit("正在检查向量数据…\n");
+ } else if (current.last_finished) {
+ io.emit(
+ `没有进行中的向量模型切换。上一次:${renderOutcomeText(current.last_finished)}`,
+ );
+ } else {
+ io.emit("没有进行中的向量模型切换。\n");
+ }
+ return EXIT_OK;
+}
+
+/** `memhub models switch cancel [--json]`: cancel the running job, if any. */
+export async function switchCancel(io: SwitchIo): Promise<number> {
+ const current = await readCurrent(io);
+ if (current === null) {
+ return reject(io, "models switch cancel", "embedding_switch_unavailable");
+ }
+ if (!current.job) {
+ return reject(io, "models switch cancel", "embedding_switch_not_found");
+ }
+ const outcome = await io.operations.post<unknown>(
+ `/api/v1/embedding-switches/${current.job.job_id}/cancel`,
+ {},
+ );
+ if (outcome.state !== "committed") {
+ return reject(io, "models switch cancel", outcome.code);
+ }
+ const job = parseJob(outcome.data) ?? current.job;
+ if (io.asJson) {
+ emitDocument(
+ io,
+ document("models switch cancel", {
+ ...progressFields(job),
+ cancel_requested: true,
+ }),
+ );
+ } else {
+ io.emit("已请求取消;当前批次完成后回滚,继续使用原来的向量模型。\n");
+ }
+ return EXIT_OK;
+}
+
+interface SpaceRow {
+ space_id: string;
+ state: string;
+ model: string | null;
+ dims: number | null;
+ vectors: number | null;
+ keep_until: string | null;
+}
+
+function spaceRows(value: unknown): SpaceRow[] | null {
+ const body = record(value);
+ if (!body || !Array.isArray(body.spaces)) return null;
+ const rows: SpaceRow[] = [];
+ for (const item of body.spaces) {
+ const row = record(item);
+ const spaceId = str(row?.space_id, 64);
+ const state = str(row?.state, 16);
+ if (!row || !spaceId || !state) return null;
+ if (state === "dropped") continue;
+ rows.push({
+ space_id: spaceId,
+ state,
+ model: str(row.model),
+ dims: int(row.dims) ?? int(row.name_dims),
+ vectors: int(row.vectors),
+ keep_until: str(row.keep_until, 64),
+ });
+ }
+ return rows;
+}
+
+const SPACE_STATE: Record<string, string> = {
+ live: "使用中",
+ building: "正在生成",
+ stray: "待合并",
+ retired: "已停用",
+};
+
+/** `memhub models spaces [--json]`. */
+export async function listSpaces(io: SwitchIo): Promise<number> {
+ const outcome = await io.reader<unknown>("/api/v1/embedding-spaces");
+ if (outcome.state !== "ok") return reject(io, "models spaces", outcome.code);
+ const rows = spaceRows(outcome.data);
+ if (!rows) return reject(io, "models spaces", "embedding_spaces_invalid");
+ const body = record(outcome.data) ?? {};
+ const unregistered = Array.isArray(body.scanned)
+ ? body.scanned
+ .map(record)
+ .filter(
+ (item): item is Record<string, unknown> =>
+ item !== null && item.state === "unregistered",
+ )
+ .map((item) => ({
+ collection_base: str(item.collection_base) ?? "",
+ vectors: int(item.vectors) ?? 0,
+ }))
+ : [];
+ if (io.asJson) {
+ emitDocument(
+ io,
+ document("models spaces", {
+ state: "ok",
+ spaces: rows,
+ unregistered,
+ scan_error:
+ typeof body.scan_error === "string" && CODE.test(body.scan_error)
+ ? body.scan_error
+ : null,
+ }),
+ );
+ return EXIT_OK;
+ }
+ const lines = ["向量空间:"];
+ for (const row of rows) {
+ const dims = row.dims === null ? "维度未知" : `${row.dims} 维`;
+ const keep =
+ row.state === "retired" && row.keep_until
+ ? `,保留到 ${row.keep_until.slice(0, 10)}`
+ : "";
+ lines.push(
+ ` ${row.space_id} ${SPACE_STATE[row.state] ?? row.state} ${row.model ?? "未知模型"}(${dims}) ${row.vectors ?? "?"} 条${keep}`,
+ );
+ }
+ for (const item of unregistered) {
+ lines.push(
+ ` (未登记)${item.collection_base} ${item.vectors} 条,下次启动时合并`,
+ );
+ }
+ if (rows.some((row) => row.state === "retired")) {
+ lines.push(
+ "清理已停用的空间:memhub models spaces --cleanup <space-id> --yes",
+ );
+ }
+ io.emit(`${lines.join("\n")}\n`);
+ return EXIT_OK;
+}
+
+/** `memhub models spaces --cleanup <space-id> --yes`: drop a retired space now. */
+export async function cleanupSpace(
+ spaceId: string,
+ io: SwitchIo,
+): Promise<number> {
+ if (!UUID.test(spaceId)) {
+ return reject(io, "models spaces", "embedding_space_not_found");
+ }
+ const outcome = await io.operations.delete<unknown>(
+ `/api/v1/embedding-spaces/${spaceId}`,
+ );
+ if (outcome.state !== "committed") {
+ return reject(io, "models spaces", outcome.code);
+ }
+ if (io.asJson) {
+ emitDocument(
+ io,
+ document("models spaces", { state: "dropped", space_id: spaceId }),
+ );
+ } else {
+ io.emit(`已清理旧向量数据:${spaceId}\n`);
+ }
+ return EXIT_OK;
+}
diff --git a/memhub/apps/cli/src/headless-flows.test.ts b/memhub/apps/cli/src/headless-flows.test.ts
index 7e9c47c..c6f8a57 100644
--- a/memhub/apps/cli/src/headless-flows.test.ts
+++ b/memhub/apps/cli/src/headless-flows.test.ts
@@ -510,15 +510,98 @@ describe("models add", () => {
expect(result.stdout + result.stderr).not.toContain("SYNTHETIC_LOOSE_KEY");
});
- it("activates the new profile with --activate", async () => {
+ it("probes the new profile before activating it with --activate", async () => {
const configFile = await modelConfigFile();
- transport.post.mockImplementation(async (url: string) =>
- url === "/api/v1/model-profiles"
- ? { status: 200, data: PROFILE }
- : url === "/api/v1/model-profiles/profile-1/activate"
- ? { status: 200, data: { ...PROFILE, is_active: true } }
- : { status: 404, data: {} },
+ let probeId: string | undefined;
+ transport.get.mockImplementation(async (url: string) => {
+ if (url === "/api/v1/model-profiles") {
+ return { status: 200, data: [PROBE_PROFILE] };
+ }
+ const match = /^\/api\/v1\/model-probe-operations\/(.+)$/.exec(url);
+ if (match) {
+ return {
+ status: 200,
+ data:
+ probeId === undefined
+ ? probeNotFound(match[1])
+ : probeReceiptPassing(match[1]),
+ };
+ }
+ return { status: 404, data: {} };
+ });
+ transport.post.mockImplementation(async (url: string, body: unknown) => {
+ if (url === "/api/v1/model-profiles") {
+ return { status: 200, data: PROBE_PROFILE };
+ }
+ if (url === `/api/v1/model-profiles/${PROBE_PROFILE.profile_id}/probe`) {
+ probeId = (body as { operation_id: string }).operation_id;
+ return { status: 200, data: probePending(probeId) };
+ }
+ if (url === "/api/v1/embedding-switches/plan") {
+ return { status: 200, data: samePlan() };
+ }
+ if (
+ url === `/api/v1/model-profiles/${PROBE_PROFILE.profile_id}/activate`
+ ) {
+ return {
+ status: 200,
+ data: {
+ ...PROBE_PROFILE,
+ is_active: true,
+ embedding_model: "synthetic-embedding",
+ },
+ };
+ }
+ return { status: 404, data: {} };
+ });
+ const result = await capturedRun(
+ ["models", "add", "--config-file", configFile, "--activate", "--json"],
+ { watchWait: async () => undefined },
);
+ expect(result.code).toBe(0);
+ const lines = result.stdout
+ .trim()
+ .split("\n")
+ .map((line) => JSON.parse(line));
+ expect(lines[0].probe).toMatchObject({ state: "completed" });
+ expect(lines.at(-1)).toMatchObject({ state: "committed" });
+ expect(transport.post.mock.calls.map(([url]) => url)).toEqual([
+ "/api/v1/model-profiles",
+ `/api/v1/model-profiles/${PROBE_PROFILE.profile_id}/probe`,
+ "/api/v1/embedding-switches/plan",
+ `/api/v1/model-profiles/${PROBE_PROFILE.profile_id}/activate`,
+ ]);
+ });
+
+ it("does not activate a profile whose probe fails", async () => {
+ const configFile = await modelConfigFile();
+ let probeId: string | undefined;
+ transport.get.mockImplementation(async (url: string) => {
+ if (url === "/api/v1/model-profiles") {
+ return { status: 200, data: [PROBE_PROFILE] };
+ }
+ const match = /^\/api\/v1\/model-probe-operations\/(.+)$/.exec(url);
+ if (match) {
+ return {
+ status: 200,
+ data:
+ probeId === undefined
+ ? probeNotFound(match[1])
+ : probeReceipt(match[1]),
+ };
+ }
+ return { status: 404, data: {} };
+ });
+ transport.post.mockImplementation(async (url: string, body: unknown) => {
+ if (url === "/api/v1/model-profiles") {
+ return { status: 200, data: PROBE_PROFILE };
+ }
+ if (url.endsWith("/probe")) {
+ probeId = (body as { operation_id: string }).operation_id;
+ return { status: 200, data: probeReceipt(probeId) };
+ }
+ return { status: 404, data: {} };
+ });
const result = await capturedRun([
"models",
"add",
@@ -527,14 +610,12 @@ describe("models add", () => {
"--activate",
"--json",
]);
- expect(result.code).toBe(0);
- expect(JSON.parse(result.stdout).activation).toEqual({
- state: "committed",
- });
- expect(transport.post.mock.calls.map(([url]) => url)).toEqual([
- "/api/v1/model-profiles",
- "/api/v1/model-profiles/profile-1/activate",
- ]);
+ expect(result.code).toBe(1);
+ expect(
+ transport.post.mock.calls.some(([url]) =>
+ String(url).endsWith("/activate"),
+ ),
+ ).toBe(false);
});
it("recovers an unknown create through its operation receipt", async () => {
@@ -752,6 +833,54 @@ function probePending(operationId: string) {
};
}
+function samePlan() {
+ const space = {
+ space_id: null,
+ model: "synthetic-embedding",
+ dims: 8,
+ collection_base: "",
+ };
+ return {
+ needed: false,
+ reason: "same_embedding",
+ plan_token: "token-1",
+ source: space,
+ target: space,
+ target_profile_id: PROBE_PROFILE.profile_id,
+ target_revision: 3,
+ target_provider_kind: "openai_compatible",
+ target_local: false,
+ blockers: [],
+ };
+}
+
+function probeReceiptPassing(operationId: string) {
+ const receipt = probeReceipt(operationId);
+ return {
+ ...receipt,
+ result: {
+ ...receipt.result,
+ stages: [
+ {
+ stage: "embedding",
+ ok: true,
+ code: "ok",
+ latency_ms: 1,
+ embedding_dimensions: 8,
+ },
+ ],
+ capabilities: {
+ endpoint_reachable: true,
+ model_available: true,
+ structured_output: true,
+ embedding_available: true,
+ },
+ embedding_width: 8,
+ embedding_switch_required: false,
+ },
+ };
+}
+
function probeNotFound(operationId: string) {
return {
schema_version: 1,
@@ -819,7 +948,10 @@ function importJob() {
};
}
-async function capturedRun(argv: string[]) {
+async function capturedRun(
+ argv: string[],
+ controls: Parameters<typeof run>[2] = {},
+) {
let stdout = "";
let stderr = "";
const originalOut = process.stdout.write;
@@ -833,7 +965,7 @@ async function capturedRun(argv: string[]) {
return true;
}) as typeof process.stderr.write;
try {
- const code = await run(argv, {});
+ const code = await run(argv, {}, controls);
return { code, stdout, stderr };
} finally {
process.stdout.write = originalOut;
diff --git a/memhub/apps/cli/src/memory-report.ts b/memhub/apps/cli/src/memory-report.ts
index 1a41ed0..c6252c3 100644
--- a/memhub/apps/cli/src/memory-report.ts
+++ b/memhub/apps/cli/src/memory-report.ts
@@ -372,6 +372,9 @@ export function renderMemoryAddText(document: MemoryAddDocument): string {
export function renderMemoryPageText(document: MemoryPageDocument): string {
const page = document.page;
if (page.state !== "ok") {
+ if (page.state === "unavailable" && page.code === "embedding_unavailable") {
+ return "向量服务不可用,无法检索;请检查向量模型配置。\n";
+ }
if (page.state === "unavailable") {
return "后台正忙,记忆列表这次没查完,不代表没有记忆,请稍后再试\n";
}
diff --git a/memhub/apps/cli/src/model-probe-flow.ts b/memhub/apps/cli/src/model-probe-flow.ts
index ccd4358..a0a5e3e 100644
--- a/memhub/apps/cli/src/model-probe-flow.ts
+++ b/memhub/apps/cli/src/model-probe-flow.ts
@@ -22,6 +22,10 @@ const RESULT_KEYS = new Set([
"stages",
"capabilities",
]);
+const OPTIONAL_RESULT_KEYS = [
+ "embedding_width",
+ "embedding_switch_required",
+] as const;
const STAGE_KEYS = new Set([
"stage",
"ok",
@@ -272,9 +276,34 @@ function validateResult(
inputRevision: number,
): Record<string, unknown> | null {
const result = record(value);
+ // A Core with the embedding registry adds what the embedding stage measured
+ // and whether using it needs an embedding switch; older Cores send neither.
+ const optional = Object.fromEntries(
+ OPTIONAL_RESULT_KEYS.filter((key) => key in (result ?? {})).map((key) => [
+ key,
+ result?.[key],
+ ]),
+ );
+ const required = result
+ ? Object.fromEntries(
+ Object.entries(result).filter(
+ ([key]) => !(OPTIONAL_RESULT_KEYS as readonly string[]).includes(key),
+ ),
+ )
+ : null;
if (
!result ||
- !exactKeys(result, RESULT_KEYS) ||
+ !required ||
+ !exactKeys(required, RESULT_KEYS) ||
+ !(
+ optional.embedding_width === undefined ||
+ optional.embedding_width === null ||
+ positiveInteger(optional.embedding_width)
+ ) ||
+ !(
+ optional.embedding_switch_required === undefined ||
+ typeof optional.embedding_switch_required === "boolean"
+ ) ||
result.profile_id !== profileId ||
result.input_profile_revision !== inputRevision ||
!positiveInteger(result.profile_revision) ||
diff --git a/memhub/apps/cli/src/model-write-flows.ts b/memhub/apps/cli/src/model-write-flows.ts
index 5f1df02..21d5832 100644
--- a/memhub/apps/cli/src/model-write-flows.ts
+++ b/memhub/apps/cli/src/model-write-flows.ts
@@ -117,7 +117,7 @@ export async function editModelProfile(
return modelProfileResult(profileId, result);
}
-function modelProfileResult(
+export function modelProfileResult(
operationId: string,
result:
| Awaited<ReturnType<CoreOperations["post"]>>
diff --git a/memhub/apps/cli/src/status-report.ts b/memhub/apps/cli/src/status-report.ts
index 660c11a..25b1350 100644
--- a/memhub/apps/cli/src/status-report.ts
+++ b/memhub/apps/cli/src/status-report.ts
@@ -18,6 +18,7 @@ import {
validateProcessing,
validateSources,
} from "./core-responses.js";
+import { describeEmbeddingSwitchSummary } from "./embedding-switch-flow.js";
import { PRODUCT } from "./version.js";
const MIGRATION_ISSUES_URL =
@@ -306,6 +307,10 @@ export function renderStatusText(
);
}
if (report.pipeline) lines.push(`记忆模式:${pipelineLine(report.pipeline)}`);
+ const embeddingSwitch = describeEmbeddingSwitchSummary(
+ report.sections.processing?.embedding_switch,
+ );
+ if (embeddingSwitch !== null) lines.push(`向量模型:${embeddingSwitch}`);
if (report.summary.state === "partial") {
const notes = [
report.summary.degraded.length > 0
@@ -365,7 +370,10 @@ function sectionLine(section: Section | undefined): string {
if (section.state === "not_checked") return "未检查";
if (section.state !== "ok") return "暂时不可用,请稍后重试";
return Object.entries(section)
- .filter(([key]) => key !== "state" && key !== "code")
+ .filter(
+ ([key]) =>
+ key !== "state" && key !== "code" && key !== "embedding_switch",
+ )
.map(([key, value]) => `${fieldLabel(key)} ${formatValue(value)}`)
.join(" ");
}
@@ -481,9 +489,30 @@ function describeProcessing(
reason: block.reason,
count: block.count,
})),
+ ...embeddingSwitchField(summary),
};
}
+/** The running switch or merge, projected; absent when none runs. */
+function embeddingSwitchField(
+ summary: MemoryProcessingSummary,
+): Record<string, unknown> {
+ const value = (summary as unknown as Record<string, unknown>)
+ .embedding_switch;
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
+ const item = value as Record<string, unknown>;
+ const kind = item.kind === "merge" ? "merge" : "switch";
+ const state =
+ typeof item.state === "string" && /^[a-z_]{1,32}$/.test(item.state)
+ ? item.state
+ : "unknown";
+ const percent =
+ typeof item.percent === "number" && Number.isFinite(item.percent)
+ ? Math.min(100, Math.max(0, item.percent))
+ : 0;
+ return { embedding_switch: { kind, state, percent } };
+}
+
/** Projection, not passthrough: a Core that leaks a key must not make us leak. */
function describeModel(profiles: ModelProfile[]): Record<string, unknown> {
const active = profiles.find((profile) => profile.is_active);
diff --git a/memhub/docs/contracts/embedding-switch-v1.md b/memhub/docs/contracts/embedding-switch-v1.md
new file mode 100644
index 0000000..ac9a76c
--- /dev/null
+++ b/memhub/docs/contracts/embedding-switch-v1.md
@@ -0,0 +1,332 @@
+# Embedding Switch v1
+
+Updated: 2026-11-01.
+
+This contract is what the App and the CLI build on to change the embedding
+model without losing a memory, and to fold in vector data an earlier build left
+in another embedding space. Core owns every decision; clients plan, confirm,
+start, follow and cancel. Core implementation: `embedding_switch.py`,
+`embedding_switch_routes.py`, `embedding_spaces.py`.
+
+## 1. Rules
+
+1. **Identity is model name + dimension.** Two profiles with the same
+ embedding model and the same width share an embedding space, whatever the
+ provider or endpoint. Changing only the endpoint, provider, key or anything
+ about generation never re-embeds.
+2. **Activation never changes the space by itself.** A profile whose embedding
+ identity differs from the live space's needs a *switch*:
+ `POST /api/v1/model-profiles/{id}/activate` answers
+ `409 embedding_switch_required` with the plan. Exception: a home with no
+ vector at all (no collection holds a record, no graph, no write in flight)
+ activates directly; nothing has to be carried over.
+3. **A switch re-embeds every vector of every user** (all layers, raw included,
+ coding keys, working facts, entities; and in ultra mode the graph) from the
+ stored text into a new space, verifies it, then commits in one SQLite
+ transaction: the new space live, the old one retired, the target profile
+ active. Nothing is renamed at commit.
+4. **Reads keep serving the old space until the commit.** Recall, library,
+ search and context results do not change while a switch runs.
+5. **Model writes pause; intake keeps queueing.** From the moment a job exists
+ until it is `done` or `rolled_back`, no conversation is turned into memory
+ and direct edits/deletes answer `409 embedding_switch_in_progress`. Imports,
+ live sync, manual adds and `/api/v2/memory-writes` still queue; the queue
+ sediments into the new space after the commit.
+6. **Failure or cancel keeps the old model.** The source space is never
+ written. A failed or cancelled job drops what it built and ends
+ `rolled_back`; the old profile stays active.
+7. **Startup scan and merge.** On every Core start, before model writes resume,
+ Core scans the vector store. A non-empty space that is neither live nor
+ known to the registry (*stray*: an earlier build wrote one collection and
+ read another) is merged: its ids missing from the live space are
+ re-embedded into the live space with the live embedder. The live space's
+ records win. A merged stray is retired. A stray with nothing missing is
+ retired at once, without a job. The same fold-in runs inside every switch.
+8. **Retired spaces are kept 14 days**, then dropped by a daily sweep, or
+ earlier with `DELETE /api/v1/embedding-spaces/{id}`. A retired space is
+ never folded back in: its records are already live, and folding it in again
+ would bring back memories deleted since.
+9. **Restarts resume.** A job is persisted with a heartbeat. Quitting the App,
+ a crash, a reboot or an App update installing a new build mid-switch: the
+ next serving Core resumes the job from its state. The upgrade migration
+ (`sdk-migrate`) never touches the switch tables; `sdk-migration-status`
+ reports an open job as `embedding_switch` and does not block on it.
+10. **Ultra graph.** With the graph store enabled the switch builds a new graph
+ at the target width. While it does, every SDK client is closed briefly, so
+ reads wait for that step.
+
+## 2. Space registry
+
+`GET /api/v1/embedding-spaces` lists `spaces[]` (registry rows) and
+`scanned[]` (what the vector store holds).
+
+| Field | Meaning |
+|---|---|
+| `space_id` | uuid |
+| `state` | `live` · `building` (a switch target) · `stray` (found by the scan, waiting to be merged) · `retired` · `dropped` |
+| `model`, `dims` | embedding identity; `model` is null for a stray, `dims` null until measured |
+| `name_dims` | the width the collection names carry; null for an "auto" space (old name kept) |
+| `collection_base` | physical base; existing homes keep their pre-registry name byte for byte |
+| `graph_dir` | graph directory of the space (`graph` for the first) |
+| `vectors` | count at the last scan (display only) |
+| `live_since`, `retired_at`, `keep_until`, `dropped_at` | ISO 8601 timestamps; `keep_until = retired_at + 14 days` |
+
+`scanned[]` entries: `collection_base`, `name_dims`, `width`, `vectors`,
+`counts` (per role), `space_id` and `state` (`unregistered` when no row names
+it). `scanned` is null with `scan_error` set when the scan could not run (for
+example `sdk_reembed_unavailable` on an SDK older than 2.0.10).
+
+## 3. Endpoints
+
+All routes need the local API token (or a valid UI session). Errors keep
+Core's shape `{"detail": "<code>"}`; a refusal that computed a plan adds
+`"plan": {...}`.
+
+| Method and path | Request | Success | Purpose |
+|---|---|---|---|
+| `POST /api/v1/embedding-switches/plan` | `{profile_id, expected_revision?}` | 200 plan | No side effects. |
+| `POST /api/v1/embedding-switches` | `{profile_id, expected_revision, plan_token, requested_by: "app"\|"cli"}` | 202 job | Start a switch. A stale `plan_token` is refused. |
+| `GET /api/v1/embedding-switches/current` | — | 200 current | Poll while a dialog, banner or loading screen shows it (1 s). `Cache-Control: no-store`. |
+| `GET /api/v1/embedding-switches/{job_id}` | — | 200 job | One job. |
+| `POST /api/v1/embedding-switches/{job_id}/cancel` | — | 200 job | Sets `cancel_requested`; honoured at the next batch. |
+| `GET /api/v1/embedding-spaces` | — | 200 | Registry + scan. |
+| `DELETE /api/v1/embedding-spaces/{space_id}` | — | 200 `{space}` | Drop a **retired** space now. |
+| `POST /api/v1/model-profiles/{id}/activate` | — | 200 profile | **Changed**: see §1 rule 2. |
+| `GET /api/v1/memory-processing`, `GET /api/v1/health` | — | — | New field `embedding_switch` (§4.1). |
+
+### 3.1 Plan
+
+```json
+{
+ "needed": true,
+ "reason": "embedding_identity_changed | same_embedding | empty_home",
+ "plan_token": "…",
+ "source": {"space_id": "…", "model": "bge-small-zh-v1.5", "dims": 512, "collection_base": "memhub_…", "vectors": 12480},
+ "target": {"space_id": null, "model": "text-embedding-v3", "dims": 1024, "collection_base": ""},
+ "target_profile_id": "…", "target_revision": 5,
+ "target_provider_kind": "openai_compatible", "target_local": false,
+ "sources": [{"space_id": "…", "collection_base": "…", "dims": 512, "vectors": 12480, "unmerged": null}],
+ "total_vectors": 12480, "users": 2, "graph_vectors": null,
+ "estimate_s": 63, "requests": 195,
+ "disk_bytes_needed": 73400320, "disk_bytes_free": 101234567890,
+ "retention_days": 14,
+ "blockers": []
+}
+```
+
+- `needed: false` with `same_embedding`: activate as before (generation-only
+ change, or the same model and width at another endpoint).
+- `needed: false` with `empty_home`: activate; Core moves the space in the same
+ transaction.
+- `sources[0]` is the live space; further entries are strays folded in
+ (`unmerged` = their record count). `users` counts distinct `user_id`s.
+- `requests` is null for a local target (no cost). `estimate_s` is a rough
+ guide (local ≈ 60 vectors/s, remote ≈ 200 vectors/s).
+- A non-empty `blockers` means the switch cannot start (§5.1).
+
+### 3.2 Job
+
+```json
+{
+ "job_id": "…", "kind": "switch | merge",
+ "state": "preparing | reembedding | verifying | committing | done | failed | rolled_back",
+ "source": {…space summary…}, "target": {…space summary…},
+ "stray_space_ids": [], "target_profile_id": "…", "target_revision": 5,
+ "requested_by": "app | cli | startup",
+ "progress": {
+ "phase": "prepare | vectors | graph | verify | commit | rollback | done",
+ "done": 6240, "total": 12480, "percent": 50.0,
+ "embedded": 6240, "reused": 0, "kept": 0,
+ "role": "memory", "source_index": 1, "sources": 1,
+ "rate_per_s": 180.2, "eta_s": 35, "updated_at": "…"
+ },
+ "cancel_requested": false, "error_code": null, "attempt": 1,
+ "created_at": "…", "updated_at": "…", "finished_at": null
+}
+```
+
+| State | Meaning | Writes |
+|---|---|---|
+| `preparing` | Gate closed; waiting (≤ 10 min) for model writes already past their claim | paused |
+| `reembedding` | Vectors (then graph) re-embedded; `progress` advances | paused |
+| `verifying` | Ids, documents, metadata, widths and per-user counts compared | paused |
+| `committing` | The single SQLite transaction | paused |
+| `done` | Terminal. New space live (switch) or strays retired (merge) | resume |
+| `failed` | **Rollback in progress** (not terminal): dropping the partial target | paused |
+| `rolled_back` | Terminal. Old space and profile unchanged; `error_code` says why | resume |
+
+`kind: "merge"` jobs come from the startup scan (`requested_by: "startup"`);
+their target is the live space. Cancel is accepted in `preparing`,
+`reembedding` and `verifying`.
+
+### 3.3 Current
+
+```json
+{
+ "schema_version": 1,
+ "phase": "idle | scanning | running",
+ "writes_paused": true,
+ "scan_state": "pending | scanning | done | failed | unavailable",
+ "scan_error": null,
+ "job": {…job…} ,
+ "last_finished": {…job…}
+}
+```
+
+`job` is the open job or null; `last_finished` the most recent terminal job,
+so a client can show the outcome after it ends.
+
+### 3.4 Probe
+
+The probe result shape is unchanged. What changed is what the probe records:
+
+- On the profile that fills the live space (the active one, or the one the
+ space was built with), a measured width that differs from the space's width
+ is **never** recorded. Recording it used to move writes to new, empty
+ collections silently (B2).
+- A measured width equal to the width the space already stores is a
+ *relabel*: it is recorded, and no collection name changes. An "auto" space
+ whose width was never recorded takes the measured width when Chroma stores
+ the same width, or when it stores nothing yet.
+- Every other profile records what it measured, as before.
+
+A probe never tells the App that a switch is needed. The App learns that only
+from `POST /api/v1/embedding-switches/plan` (`needed: true`), or from the body
+of a `409 embedding_switch_required` answer to activate.
+
+## 4. Summary fields
+
+### 4.1 `embedding_switch`
+
+On `/api/v1/memory-processing` and `/api/v1/health`:
+`{"job_id": "…", "kind": "switch|merge", "state": "<job state>", "percent": 50.0, "eta_s": 35}`,
+or `{"kind": "merge", "state": "scanning", "percent": 0.0, "eta_s": null}` during
+the startup scan, or null.
+
+## 5. Error codes
+
+### 5.1 Refusals
+
+| Code | HTTP | When |
+|---|---|---|
+| `embedding_switch_required` | 409 (+ `plan`) | activate with another embedding on a non-empty home |
+| `embedding_switch_running` | 409 | activate / start / embedding edit of the active or target profile while a job is open |
+| `embedding_switch_plan_stale` | 409 (+ `plan`) | `plan_token` no longer matches (data or live space changed) |
+| `embedding_switch_not_needed` | 409 (+ `plan`) | start with the same identity, or on an empty home (activate instead) |
+| `embedding_switch_in_progress` | 409 | memory edit/delete, `POST /api/v1/graph-width` while writes are paused |
+| `embedding_switch_not_cancellable` | 409 | cancel in `committing` or later |
+| `embedding_switch_not_found` | 404 | unknown job, or cancel with no open job |
+| `embedding_space_not_found` | 404 | unknown or already dropped space |
+| `embedding_space_not_retired` | 409 | delete of a live, building or stray space |
+| `embedding_space_in_use` | 409 | delete of a space an SDK client still holds open; retry later |
+| `embedding_probe_required` | 409 (blocker) | target not probed at this revision (activate answers `model_profile_probe_required`) |
+| `embedding_dimensions_unknown` | 409 (blocker) | target width unknown; probe it or declare `embedding_dimensions` |
+| `embedding_switch_requires_migration` | 409 (blocker) | legacy `one_memory_*` collections still wait for `sdk-migrate` |
+| `sdk_reembed_unavailable` | 503 (blocker) | installed SDK has no re-embed module (before hy-memory 2.0.10) |
+| `insufficient_disk_space` | 507 (blocker) | free disk < 1.5 × estimated target size + 200 MB |
+| `model_profile_not_found` | 404 | unknown profile |
+| `model_profile_conflict` | 409 | `expected_revision` stale |
+| `embedding_unavailable` | 503 | search, recall, context, library search or ask could not embed the query (remote embedding down). No lexical fallback. |
+
+### 5.2 Job failure codes (`error_code` on a `rolled_back` job)
+
+| Code | Meaning |
+|---|---|
+| `writes_did_not_drain` | in-flight model writes did not finish within 10 minutes |
+| `embedding_service_failed` | the embedding service kept failing after retries |
+| `embedding_dimensions_mismatch` | the service returned another width than probed |
+| `embedding_verification_failed` | the copy did not verify (missing/changed ids, widths, per-user counts, graph) |
+| `target_profile_changed` | the target profile was edited during the switch |
+| `embedding_switch_cancelled` | cancelled by the user |
+| `model_secret_unavailable` | the embedding API key could not be read |
+| `secure_storage_unavailable` | the system keychain was unavailable |
+| `embedding_switch_clients_busy` | SDK clients stayed busy; the graph could not be copied |
+
+## 6. App guidance
+
+### 6.1 Setup flow (`finishSetup`)
+
+probe → `POST /embedding-switches/plan` → `needed: false`: activate as today →
+`needed: true`: show the confirmation dialog; on confirm
+`POST /embedding-switches` with the plan's `plan_token`. The active profile does
+not change until the job is `done`. Persist `embedding_base_url` explicitly
+for remote embeddings. Handle `409 embedding_switch_required` from activate
+the same way (the plan is in the body).
+
+### 6.2 Loading screen (startup merge)
+
+Core is already ready and serving reads when the App's loading phase starts.
+Poll `GET /api/v1/embedding-switches/current` (or `/api/v1/health` →
+`embedding_switch`) every second. While `phase` is `scanning`, or `job.kind` is
+`merge` and not terminal, show the line below with `progress.percent`. The App
+may enter the home before the merge ends (reads work); then show the banner
+(§6.4) instead.
+
+| | Copy |
+|---|---|
+| zh | 正在检查向量数据… / 正在合并旧版本留下的向量数据 {p}%,完成前暂不整理新记忆。 |
+| en | Checking vector data… / Merging vector data left by an earlier version: {p}%. New memories are processed once this finishes. |
+| es | Comprobando los datos vectoriales… / Fusionando datos vectoriales de una versión anterior: {p} %. Los recuerdos nuevos se procesarán al terminar. |
+
+### 6.3 Confirmation dialog
+
+| | Copy |
+|---|---|
+| zh | **更换向量模型** 你把向量模型从 **{旧模型}({旧维度} 维)** 换成了 **{新模型}({新维度} 维)**。不同的向量模型无法互相检索。为了让已有记忆在新模型下仍能被找到,MemHub 会用新模型为全部记忆重新生成向量:共 **{N} 条向量**({用户数} 个用户),预计耗时 **约 {T}**({本地:在本机计算,不产生费用 / 远程:将调用 {endpoint},约 {请求数} 次请求,可能产生费用}),需要额外磁盘空间约 **{X} MB**。切换期间:新的对话会照常记录,但暂不整理成记忆,切换完成后自动补上;检索和记忆库继续使用旧模型;暂时无法编辑或删除记忆。全部完成并校验通过后才会正式切换。中途失败或取消,会保持使用旧模型,不丢失任何数据。旧的向量数据会保留 14 天。[取消] [开始切换] |
+| en | **Change embedding model** You changed the embedding model from **{old} ({oldDims}-d)** to **{new} ({newDims}-d)**. Vectors from different models cannot search each other, so MemHub will re-create the vectors of all memories with the new model: **{N} vectors** ({users} users), about **{T}** ({local: computed on this Mac, free / remote: calls {endpoint}, about {requests} requests, may cost money}), about **{X} MB** of extra disk. During the switch new conversations are still recorded but not turned into memories until it finishes; search and the library keep using the old model; memories cannot be edited or deleted. The switch takes effect only after everything is verified. If it fails or you cancel, the old model stays and no data is lost. Old vectors are kept for 14 days. [Cancel] [Start switch] |
+| es | **Cambiar el modelo de embeddings** Cambiaste el modelo de **{old} ({oldDims} d)** a **{new} ({newDims} d)**. Los vectores de modelos distintos no se pueden buscar entre sí, así que MemHub regenerará los vectores de todos los recuerdos con el nuevo modelo: **{N} vectores** ({users} usuarios), unos **{T}** ({local: se calcula en este equipo, sin coste / remoto: llama a {endpoint}, unas {requests} solicitudes, puede tener coste}), unos **{X} MB** de disco adicional. Durante el cambio las conversaciones nuevas se registran pero no se convierten en recuerdos hasta terminar; la búsqueda y la biblioteca siguen usando el modelo anterior; no se pueden editar ni borrar recuerdos. El cambio solo se aplica tras verificarlo todo. Si falla o lo cancelas, se mantiene el modelo anterior sin perder datos. Los vectores anteriores se guardan 14 días. [Cancelar] [Iniciar cambio] |
+
+Extra lines: same width (`source.dims == target.dims`) — zh 新旧模型维度相同,但向量不能通用,仍需重新生成。/ en Both models have the same width, but their vectors are not interchangeable, so they still have to be re-created. / es Ambos modelos tienen la misma dimensión, pero sus vectores no son intercambiables y hay que regenerarlos. Builtin target (`target_local`) — zh 将使用内置模型 bge-small-zh-v1.5,在本机计算,不产生费用。/ en Uses the built-in model bge-small-zh-v1.5, computed on this Mac at no cost. / es Usa el modelo integrado bge-small-zh-v1.5, calculado en este equipo sin coste. Strays in `sources` — zh 另外会合并旧版本留下的 {M} 条向量。/ en Also merges {M} vectors left by an earlier version. / es También fusiona {M} vectores de una versión anterior. Blockers disable [Start] and show §5.1 text.
+
+### 6.4 Progress banner and card
+
+| State | zh | en | es |
+|---|---|---|---|
+| preparing | 正在准备切换向量模型,等待正在进行的记忆整理结束… | Preparing to switch the embedding model, waiting for memory processing in progress… | Preparando el cambio de modelo, esperando a que termine el procesamiento en curso… |
+| reembedding | 正在切换向量模型:重新生成向量 {done}/{total}({p}%),预计还需 {eta}。记忆整理已暂停,检索不受影响。[取消切换] | Switching embedding model: re-creating vectors {done}/{total} ({p}%), about {eta} left. Memory processing is paused; search is unaffected. [Cancel] | Cambiando el modelo: regenerando vectores {done}/{total} ({p} %), faltan unos {eta}. El procesamiento está en pausa; la búsqueda no se ve afectada. [Cancelar] |
+| verifying / committing | 正在校验新向量… | Verifying the new vectors… | Verificando los vectores nuevos… |
+| done (switch) | 已切换到 {新模型}。暂停期间的对话正在整理成记忆。[清理旧向量数据] | Switched to {new}. Conversations from the pause are being processed now. [Clean up old vectors] | Cambiado a {new}. Las conversaciones de la pausa se están procesando. [Limpiar vectores antiguos] |
+| done (merge) | 旧向量数据已合并。 | Old vector data merged. | Datos vectoriales antiguos fusionados. |
+| failed | 切换未完成,正在恢复旧向量模型… | The switch did not finish; restoring the previous model… | El cambio no terminó; restaurando el modelo anterior… |
+| rolled_back | 切换未完成,已恢复使用 {旧模型},数据未受影响。原因:{reason} [重试] [查看日志] | The switch did not finish; {old} is in use again and no data was affected. Reason: {reason} [Retry] [View log] | El cambio no terminó; se vuelve a usar {old} sin afectar a los datos. Motivo: {reason} [Reintentar] [Ver registro] |
+| rolled_back + `embedding_switch_cancelled` | 已取消切换,继续使用 {旧模型}。 | Switch cancelled; still using {old}. | Cambio cancelado; se sigue usando {old}. |
+
+Retry = plan again and start a new job. "Clean up" calls
+`DELETE /api/v1/embedding-spaces/{source.space_id}` (show `vectors`).
+
+`{reason}` per §5.2:
+
+| Code | zh | en | es |
+|---|---|---|---|
+| writes_did_not_drain | 等待正在进行的记忆整理结束超时 | Timed out waiting for memory processing to finish | Se agotó la espera del procesamiento en curso |
+| embedding_service_failed | 向量服务连续请求失败 | The embedding service kept failing | El servicio de embeddings falló repetidamente |
+| embedding_dimensions_mismatch | 向量服务返回的维度与探测到的不一致 | The service returned another vector width than probed | El servicio devolvió otra dimensión que la detectada |
+| embedding_verification_failed | 新向量没有通过校验 | The new vectors did not verify | Los vectores nuevos no superaron la verificación |
+| target_profile_changed | 切换期间目标配置被修改 | The target profile was edited during the switch | El perfil de destino se modificó durante el cambio |
+| model_secret_unavailable | 读不到向量服务的 API Key | The embedding API key could not be read | No se pudo leer la clave API de embeddings |
+| secure_storage_unavailable | 系统钥匙串不可用 | The system keychain is unavailable | El llavero del sistema no está disponible |
+| embedding_switch_clients_busy | 记忆图谱一直被占用 | The memory graph stayed busy | El grafo de memoria siguió ocupado |
+
+Blocked actions while writes are paused (`409 embedding_switch_in_progress`
+/ `embedding_switch_running`): zh 正在切换向量模型,暂时无法修改记忆,请在切换完成后再试。/ 上一次向量模型切换还在进行,请等待完成或先取消。 en The embedding model is being switched; memories can be edited again once it finishes. / A previous switch is still running; wait for it or cancel it first. es Se está cambiando el modelo de embeddings; podrás editar recuerdos al terminar. / Aún hay un cambio en curso; espera o cancélalo primero.
+
+### 6.5 `embedding_unavailable` toast
+
+Any search/recall/context route answering `503 {"detail": "embedding_unavailable"}`:
+show a top-right toast (do not show an empty result list).
+
+| | Copy |
+|---|---|
+| zh | 向量服务暂时不可用,无法检索记忆。请检查向量模型的服务地址和 API Key。 |
+| en | The embedding service is unavailable, so memories cannot be searched. Check the embedding model's endpoint and API key. |
+| es | El servicio de embeddings no está disponible y no se pueden buscar recuerdos. Revisa la dirección del servicio y la clave API del modelo de embeddings. |
+
+## 7. CLI
+
+`memhub models activate <id> [--yes] [--wait|--no-wait] [--json]` shows the
+plan; without `--yes` it prompts on a terminal and exits 2 otherwise; with
+`--yes` it starts the switch and follows it (default on a terminal; `--json`
+emits one JSON line per progress change, then a result line). Ctrl-C only
+stops watching. `memhub models add … --activate` probes first, then the same
+path. `memhub models switch status|cancel`, `memhub models spaces
+[--cleanup <space-id> --yes]`, and a `向量模型:…` line in `memhub status`.