Skip to content
Python

feat(memhub): configurable SDK retrieval and extraction features

alvinfei3742b3e45312
diff --git a/memhub/apps/cli/src/cli.ts b/memhub/apps/cli/src/cli.ts
index 2c07f9d..fb99613 100644
--- a/memhub/apps/cli/src/cli.ts
+++ b/memhub/apps/cli/src/cli.ts
@@ -188,6 +188,13 @@ import {
removeManagedCliLink,
rollbackManagedCliLink,
} from "./managed-cli-link.js";
+import {
+ type FeaturesDocument,
+ featuresExitCode,
+ parseFeaturesCommand,
+ renderFeaturesText,
+ runFeaturesCommand,
+} from "./memory-features-flow.js";
import {
type EvolveDocument,
evolveExitCode,
@@ -2242,6 +2249,40 @@ async function runCommand(
);
return outcome.state === "committed" ? EXIT_OK : EXIT_FAILED;
}
+ if (
+ named === "settings" &&
+ arguments_.slice(1).find((value) => value !== "--json") === "features"
+ ) {
+ const parsed = parseFeaturesCommand(
+ arguments_
+ .slice(1)
+ .filter((value, index, all) => index !== all.indexOf("features")),
+ );
+ if (!parsed) return usage();
+ const connected = await connectRuntime(environment);
+ if (!connected.ok) {
+ const document: FeaturesDocument = {
+ schema_version: 1,
+ product: PRODUCT,
+ command: "settings features",
+ state: "unavailable",
+ code: connected.code,
+ };
+ emit(
+ asJson ? `${JSON.stringify(document)}\n` : renderFeaturesText(document),
+ );
+ return connected.exitCode;
+ }
+ const document = await runFeaturesCommand(
+ parsed,
+ connected.reader,
+ connected.operations,
+ );
+ emit(
+ asJson ? `${JSON.stringify(document)}\n` : renderFeaturesText(document),
+ );
+ return featuresExitCode(document);
+ }
if (named === "settings") {
const parsed = parseSettingsCommand(arguments_.slice(1));
if (!parsed) return usage();
diff --git a/memhub/apps/cli/src/command-catalog.ts b/memhub/apps/cli/src/command-catalog.ts
index 77258db..4ef86f9 100644
--- a/memhub/apps/cli/src/command-catalog.ts
+++ b/memhub/apps/cli/src/command-catalog.ts
@@ -451,13 +451,26 @@ export const COMMANDS: readonly CommandDescriptor[] = [
{
name: "settings",
summary:
- "查看或切换记忆模式(lite / pro / ultra)。lite 不调用模型,只在原始对话里检索;pro 由模型提取记忆(System 1);ultra 在 pro 之上每晚自动进化(System 2,使用知识图谱)。任何模式都保留全部原始对话。切换不迁移数据:已处理的不会重做,排队中的和新的按新模式处理;需 --yes,不加时只显示计划。环境变量 ONE_MEMORY_GRAPH_STORE 会强制 ultra。",
- usage: "memhub settings mode [lite|pro|ultra] [--yes] [--json]",
+ "查看或切换记忆模式(lite / pro / ultra)。lite 不调用模型,只在原始对话里检索;pro 由模型提取记忆(System 1);ultra 在 pro 之上每晚自动进化(System 2,使用知识图谱)。任何模式都保留全部原始对话。切换不迁移数据:已处理的不会重做,排队中的和新的按新模式处理;需 --yes,不加时只显示计划。环境变量 ONE_MEMORY_GRAPH_STORE 会强制 ultra。settings features 查看或开关 SDK 的可选检索与提取功能(全局设置,默认全部保持 SDK 默认值):graph_rerank 图谱重排(仅 ultra)、same_series_timeline 同系列时间线(需 graph_rerank)、episode_recall 片段召回(pro / ultra,需先开 session_episodes 写入片段)、session_episodes 片段写入、episode_summary 片段摘要(每个片段一次模型调用)、intention 意图提取(默认开)、few_shot 提取示例;set 需 --yes,不加时只显示计划;reset 恢复默认值。",
+ usage:
+ "memhub settings mode [lite|pro|ultra] [--yes] [--json]\n" +
+ " memhub settings features [--json]\n" +
+ " memhub settings features set <name>=<true|false> [...] [--yes] [--json]\n" +
+ " memhub settings features reset [<name> ...] [--json]",
options: [
{
flag: "mode [lite|pro|ultra]",
summary: "不带模式只显示当前模式;带模式时先显示切换计划。",
},
+ {
+ flag: "features set <name>=<true|false>",
+ summary:
+ "开关一个或多个 SDK 功能;功能在当前模式下不生效时会注明原因(例如 graph_rerank 需要 ultra)。",
+ },
+ {
+ flag: "features reset [<name> ...]",
+ summary: "把指定功能(不写则全部)恢复为 SDK 默认值。",
+ },
CONFIRM_OPTION,
JSON_OPTION,
],
diff --git a/memhub/apps/cli/src/core-client.ts b/memhub/apps/cli/src/core-client.ts
index 81aa522..6c47c05 100644
--- a/memhub/apps/cli/src/core-client.ts
+++ b/memhub/apps/cli/src/core-client.ts
@@ -19,6 +19,7 @@ const READ_ONLY_PATHS = [
"/api/v2/user-profile",
"/api/v2/user-profile/versions",
"/api/v1/settings/memory-mode",
+ "/api/v1/settings/memory-features",
"/api/v2/evolve",
] as const;
/** One evolve run's receipt (`memhub evolve --wait`). */
diff --git a/memhub/apps/cli/src/core-operations.ts b/memhub/apps/cli/src/core-operations.ts
index 035df49..f6d35de 100644
--- a/memhub/apps/cli/src/core-operations.ts
+++ b/memhub/apps/cli/src/core-operations.ts
@@ -29,6 +29,8 @@ const GRAPH_WIDTH_PATH = "/api/v1/graph-width";
/** `memhub evolve` starts a run; `memhub settings mode <m> --yes` sets the mode. */
const EVOLVE_PATH = "/api/v2/evolve";
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 MAX_BYTES = 4 * 1024 * 1024;
@@ -138,6 +140,7 @@ export function createCoreOperations(attachment: {
) {
if (
path !== MEMORY_MODE_PATH &&
+ path !== MEMORY_FEATURES_PATH &&
(!SDK_MEMORY_PATH.test(path) || path.includes("?"))
) {
throw new Error("core_operation_path_not_allowed");
diff --git a/memhub/apps/cli/src/memory-features-cli.test.ts b/memhub/apps/cli/src/memory-features-cli.test.ts
new file mode 100644
index 0000000..7030ab3
--- /dev/null
+++ b/memhub/apps/cli/src/memory-features-cli.test.ts
@@ -0,0 +1,318 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { run } from "./cli.js";
+import { parseFeaturesCommand } from "./memory-features-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(),
+ post: vi.fn(),
+ isAxiosError: () => false,
+ },
+}));
+
+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 DEFAULTS: Record<string, boolean> = {
+ graph_rerank: false,
+ same_series_timeline: false,
+ episode_recall: false,
+ session_episodes: false,
+ episode_summary: false,
+ intention: true,
+ few_shot: false,
+};
+
+function featuresState(
+ configured: Record<string, boolean> = {},
+ mode = "pro",
+ extra: Record<string, unknown> = {},
+) {
+ const nonDefault: Record<string, boolean> = {};
+ const features = Object.entries(DEFAULTS).map(([name, fallback]) => {
+ const enabled = configured[name] ?? fallback;
+ if (enabled !== fallback) nonDefault[name] = enabled;
+ const needsUltra = name === "graph_rerank";
+ const reason = !enabled
+ ? "disabled"
+ : needsUltra && mode !== "ultra"
+ ? "requires_ultra"
+ : null;
+ return {
+ name,
+ enabled,
+ configured: name in configured ? configured[name] : null,
+ default: fallback,
+ active: reason === null,
+ reason,
+ side: "read",
+ requires_mode: needsUltra ? "ultra" : "pro",
+ requires_feature: null,
+ cost: "none",
+ sdk_field: `recall.${name}`,
+ env: `MEMORY_${name.toUpperCase()}`,
+ description: name,
+ };
+ });
+ return { mode, features, non_default: nonDefault, ...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",
+ },
+ });
+ transport.get.mockImplementation(async (url: string) =>
+ url === "/api/v1/settings/memory-features"
+ ? { status: 200, data: featuresState() }
+ : { status: 404, data: {} },
+ );
+});
+
+describe("memhub settings features", () => {
+ it("lists every feature with its value and whether it acts", async () => {
+ const result = await capturedRun(["settings", "features", "--json"]);
+ expect(result.code).toBe(0);
+ const json = JSON.parse(result.stdout);
+ expect(json.state).toBe("ok");
+ expect(json.features.features).toHaveLength(7);
+ expect(transport.put).not.toHaveBeenCalled();
+ const text = (await capturedRun(["settings", "features"])).stdout;
+ expect(text).toContain("graph_rerank:关(默认)");
+ expect(text).toContain("intention:开(默认)");
+ expect(text).toContain("先开启 session_episodes");
+ });
+
+ it("prints the plan and changes nothing without --yes", async () => {
+ const result = await capturedRun([
+ "settings",
+ "features",
+ "set",
+ "graph_rerank=true",
+ "episode_recall=true",
+ ]);
+ expect(result.code).toBe(0);
+ expect(transport.put).not.toHaveBeenCalled();
+ expect(result.stdout).toContain(
+ "memhub settings features set graph_rerank=true episode_recall=true --yes",
+ );
+ });
+
+ it("sets features with --yes and reports the ones inactive in this mode", async () => {
+ transport.put.mockResolvedValue({
+ status: 200,
+ data: featuresState({ graph_rerank: true, episode_recall: true }, "pro", {
+ changed: ["graph_rerank", "episode_recall"],
+ }),
+ });
+ const result = await capturedRun([
+ "settings",
+ "features",
+ "set",
+ "graph_rerank=true",
+ "episode_recall=true",
+ "--yes",
+ ]);
+ expect(result.code).toBe(0);
+ expect(transport.put).toHaveBeenCalledWith(
+ "/api/v1/settings/memory-features",
+ { graph_rerank: true, episode_recall: true },
+ undefined,
+ );
+ expect(result.stdout).toContain("已更新:graph_rerank、episode_recall");
+ expect(result.stdout).toContain(
+ "graph_rerank:开(已设置,当前模式下不生效(需要 ultra))",
+ );
+ });
+
+ it("does nothing when the values are already set", async () => {
+ transport.get.mockResolvedValue({
+ status: 200,
+ data: featuresState({ few_shot: true }),
+ });
+ const result = await capturedRun([
+ "settings",
+ "features",
+ "set",
+ "few_shot=true",
+ "--yes",
+ ]);
+ expect(result.code).toBe(0);
+ expect(result.stdout).toContain("没有需要改动的设置");
+ expect(transport.put).not.toHaveBeenCalled();
+ });
+
+ it("resets the named features, or every set one, to the default", async () => {
+ transport.get.mockResolvedValue({
+ status: 200,
+ data: featuresState({ few_shot: true, intention: false }),
+ });
+ transport.put.mockResolvedValue({
+ status: 200,
+ data: featuresState({}, "pro", { changed: ["intention", "few_shot"] }),
+ });
+ expect(
+ (await capturedRun(["settings", "features", "reset", "few_shot"])).code,
+ ).toBe(0);
+ expect(transport.put).toHaveBeenLastCalledWith(
+ "/api/v1/settings/memory-features",
+ { few_shot: null },
+ undefined,
+ );
+ const all = await capturedRun(["settings", "features", "reset", "--json"]);
+ expect(JSON.parse(all.stdout).state).toBe("committed");
+ expect(transport.put).toHaveBeenLastCalledWith(
+ "/api/v1/settings/memory-features",
+ { intention: null, few_shot: null },
+ undefined,
+ );
+ });
+
+ it("refuses unknown names and malformed values before the Runtime", async () => {
+ for (const bad of [
+ ["settings", "features", "set"],
+ ["settings", "features", "set", "local_rerank=true"],
+ ["settings", "features", "set", "graph_rerank=yes"],
+ ["settings", "features", "set", "graph_rerank"],
+ ["settings", "features", "set", "few_shot=true", "few_shot=false"],
+ ["settings", "features", "reset", "nope"],
+ ["settings", "features", "toggle"],
+ ]) {
+ const result = await capturedRun(bad);
+ expect(result.code, bad.join(" ")).toBe(2);
+ }
+ expect(transport.put).not.toHaveBeenCalled();
+ });
+
+ it("surfaces a 422 from the Runtime as rejected", async () => {
+ transport.put.mockResolvedValue({
+ status: 422,
+ data: { detail: "invalid_request" },
+ });
+ const result = await capturedRun([
+ "settings",
+ "features",
+ "set",
+ "few_shot=true",
+ "--yes",
+ "--json",
+ ]);
+ expect(result.code).toBe(1);
+ expect(JSON.parse(result.stdout).state).toBe("rejected");
+ });
+
+ it("parses the forms the help shows", () => {
+ expect(parseFeaturesCommand([])).toEqual({ kind: "show" });
+ expect(parseFeaturesCommand(["set", "intention=false", "--yes"])).toEqual({
+ kind: "set",
+ values: { intention: false },
+ confirmed: true,
+ });
+ expect(parseFeaturesCommand(["reset"])).toEqual({
+ kind: "reset",
+ names: [],
+ });
+ });
+});
+
+describe("status pipeline features", () => {
+ it("shows the features that differ from the defaults", async () => {
+ const processing = {
+ pending: 0,
+ fresh_pending: 0,
+ backlog_pending: 0,
+ outside_window_pending: 0,
+ running: 0,
+ waiting_for_model: 0,
+ completed: 3,
+ failed: 0,
+ blocked_stages: [],
+ pipeline: {
+ mode: "pro",
+ configured_mode: "pro",
+ forced_by_env: false,
+ last_evolve_at: null,
+ graph_build: { state: "idle", users: {} },
+ evolve: { mode: "pro", schedule: null, running: [], users: {} },
+ features: { episode_recall: true, intention: false },
+ },
+ };
+ const report = await composeStatusReport({
+ dataDir: "/tmp/isolated",
+ runtime: { state: "running", code: "ok", host: "127.0.0.1", port: 1 },
+ background: null,
+ reader: (async (path: string) =>
+ path === "/api/v1/memory-processing"
+ ? { state: "ok", data: processing }
+ : { state: "unavailable", code: "x" }) as never,
+ });
+ expect(report.pipeline?.features).toEqual({
+ episode_recall: true,
+ intention: false,
+ });
+ const text = renderStatusText(report, "MemHub");
+ expect(text).toContain("SDK 功能:episode_recall=开、intention=关");
+ });
+});
+
+async function capturedRun(arguments_: string[]) {
+ 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" }),
+ stdout,
+ stderr,
+ };
+ } finally {
+ stdoutSpy.mockRestore();
+ stderrSpy.mockRestore();
+ }
+}
diff --git a/memhub/apps/cli/src/memory-features-flow.ts b/memhub/apps/cli/src/memory-features-flow.ts
new file mode 100644
index 0000000..230fe34
--- /dev/null
+++ b/memhub/apps/cli/src/memory-features-flow.ts
@@ -0,0 +1,273 @@
+/**
+ * `memhub settings features [set <name>=<true|false> ... | reset [<name> ...]]`.
+ *
+ * The SDK's optional retrieval and extraction features (graph rerank, episode
+ * recall, the episode write side, intention, few-shot). One global setting in
+ * the Runtime; an unset feature keeps the SDK default, so an install nobody
+ * touched behaves as before. `set` prints its plan first and needs `--yes`,
+ * like `settings mode`, because some features spend model calls; `reset`
+ * only returns features to their defaults and applies at once.
+ */
+
+import type { CoreReader } from "./core-client.js";
+import type { CorePutOperations } from "./core-operations.js";
+import { PRODUCT } from "./version.js";
+
+export const MEMORY_FEATURES = [
+ "graph_rerank",
+ "same_series_timeline",
+ "episode_recall",
+ "session_episodes",
+ "episode_summary",
+ "intention",
+ "few_shot",
+] as const;
+export type MemoryFeature = (typeof MEMORY_FEATURES)[number];
+
+const FEATURE_LABEL: Record<MemoryFeature, string> = {
+ graph_rerank: "图谱重排(沿知识图谱的边传播支持度;仅 ultra)",
+ same_series_timeline:
+ "同系列时间线(同一系列的记忆按时间放在一起;需图谱重排)",
+ episode_recall:
+ "片段召回(补入同一片段的记忆并多通道打分;pro / ultra,需片段写入)",
+ session_episodes: "片段写入(同一会话提取的记忆归入同一片段)",
+ episode_summary: "片段摘要(片段结束时总结一次;每个片段一次模型调用)",
+ intention: "意图提取(随事实一起提取用户的计划与意图)",
+ few_shot: "提取示例(在提取提示里附上示例;不加调用,输入更长)",
+};
+
+const REASON_TEXT: Record<string, string> = {
+ disabled: "未开启",
+ requires_pro: "lite 模式下不生效(需要 pro 或 ultra)",
+ requires_ultra: "当前模式下不生效(需要 ultra)",
+ requires_graph_rerank: "需要先开启并生效 graph_rerank",
+};
+
+export type FeaturesCommand =
+ | { kind: "show" }
+ | {
+ kind: "set";
+ values: Partial<Record<MemoryFeature, boolean>>;
+ confirmed: boolean;
+ }
+ | { kind: "reset"; names: MemoryFeature[] };
+
+function isFeature(value: string): value is MemoryFeature {
+ return (MEMORY_FEATURES as readonly string[]).includes(value);
+}
+
+/** Arguments after `settings features`; null = usage. */
+export function parseFeaturesCommand(
+ values: readonly string[],
+): FeaturesCommand | null {
+ const rest = values.filter((value) => value !== "--json");
+ if (rest.length === 0) return { kind: "show" };
+ const [verb, ...tail] = rest;
+ const yes = tail.filter((value) => value === "--yes").length;
+ if (yes > 1) return null;
+ const positional = tail.filter((value) => value !== "--yes");
+ if (verb === "set") {
+ if (positional.length === 0) return null;
+ const parsed: Partial<Record<MemoryFeature, boolean>> = {};
+ for (const item of positional) {
+ const match = /^([a-z_]+)=(true|false)$/.exec(item);
+ if (!match || !isFeature(match[1]) || match[1] in parsed) return null;
+ parsed[match[1]] = match[2] === "true";
+ }
+ return { kind: "set", values: parsed, confirmed: yes === 1 };
+ }
+ if (verb === "reset") {
+ if (new Set(positional).size !== positional.length) return null;
+ if (!positional.every(isFeature)) return null;
+ return { kind: "reset", names: positional as MemoryFeature[] };
+ }
+ return null;
+}
+
+export interface FeatureState {
+ name: MemoryFeature;
+ enabled: boolean;
+ configured: boolean | null;
+ default: boolean;
+ active: boolean;
+ reason: string | null;
+ cost: string;
+ requires_mode: string;
+ description: string;
+}
+
+export interface FeaturesState {
+ mode: string;
+ features: FeatureState[];
+ non_default: Partial<Record<MemoryFeature, boolean>>;
+ changed?: MemoryFeature[];
+}
+
+function featuresState(value: unknown): FeaturesState | null {
+ if (!value || typeof value !== "object") return null;
+ const item = value as Record<string, unknown>;
+ if (
+ typeof item.mode !== "string" ||
+ !Array.isArray(item.features) ||
+ !item.non_default ||
+ typeof item.non_default !== "object"
+ ) {
+ return null;
+ }
+ for (const feature of item.features) {
+ if (
+ !feature ||
+ typeof feature !== "object" ||
+ typeof (feature as FeatureState).name !== "string" ||
+ typeof (feature as FeatureState).enabled !== "boolean" ||
+ typeof (feature as FeatureState).active !== "boolean"
+ ) {
+ return null;
+ }
+ }
+ return item as unknown as FeaturesState;
+}
+
+export type FeaturesDocument = {
+ schema_version: 1;
+ product: string;
+ command: "settings features";
+} & (
+ | { state: "ok"; features: FeaturesState }
+ | {
+ state: "preview";
+ features: FeaturesState;
+ target: Partial<Record<MemoryFeature, boolean>>;
+ applied: false;
+ next_step: string;
+ }
+ | { state: "unchanged"; features: FeaturesState }
+ | { state: "committed"; features: FeaturesState; changed: MemoryFeature[] }
+ | { state: "rejected" | "unknown" | "unavailable"; code: string }
+);
+
+const BASE = {
+ schema_version: 1 as const,
+ product: PRODUCT,
+ command: "settings features" as const,
+};
+
+const PATH = "/api/v1/settings/memory-features";
+
+export async function runFeaturesCommand(
+ command: FeaturesCommand,
+ reader: CoreReader,
+ operations: CorePutOperations,
+): Promise<FeaturesDocument> {
+ const read = await reader<unknown>(PATH);
+ if (read.state !== "ok") {
+ return { ...BASE, state: "unavailable", code: read.code };
+ }
+ const current = featuresState(read.data);
+ if (current === null) {
+ return { ...BASE, state: "unavailable", code: "response_invalid" };
+ }
+ if (command.kind === "show") {
+ return { ...BASE, state: "ok", features: current };
+ }
+ let body: Record<string, unknown>;
+ if (command.kind === "set") {
+ const configured = new Map(
+ current.features.map((feature) => [feature.name, feature.configured]),
+ );
+ const differs = Object.entries(command.values).some(
+ ([name, value]) => configured.get(name as MemoryFeature) !== value,
+ );
+ if (!differs) return { ...BASE, state: "unchanged", features: current };
+ if (!command.confirmed) {
+ const pairs = Object.entries(command.values)
+ .map(([name, value]) => `${name}=${value}`)
+ .join(" ");
+ return {
+ ...BASE,
+ state: "preview",
+ features: current,
+ target: command.values,
+ applied: false,
+ next_step: `${PRODUCT} settings features set ${pairs} --yes`,
+ };
+ }
+ body = { ...command.values };
+ } else {
+ const names =
+ command.names.length > 0
+ ? command.names
+ : current.features
+ .filter((feature) => feature.configured !== null)
+ .map((feature) => feature.name);
+ if (
+ names.every(
+ (name) =>
+ current.features.find((feature) => feature.name === name)
+ ?.configured === null,
+ )
+ ) {
+ return { ...BASE, state: "unchanged", features: current };
+ }
+ body = Object.fromEntries(names.map((name) => [name, null]));
+ }
+ const result = await operations.put<unknown>(PATH, body);
+ if (result.state !== "committed") {
+ return { ...BASE, state: result.state, code: result.code };
+ }
+ const changed = featuresState(result.data);
+ if (changed === null) {
+ return { ...BASE, state: "unknown", code: "response_invalid" };
+ }
+ return {
+ ...BASE,
+ state: "committed",
+ features: changed,
+ changed: changed.changed ?? [],
+ };
+}
+
+export function featuresExitCode(document: FeaturesDocument): number {
+ return ["ok", "preview", "unchanged", "committed"].includes(document.state)
+ ? 0
+ : 1;
+}
+
+function featureLine(feature: FeatureState): string {
+ const label = FEATURE_LABEL[feature.name] ?? feature.name;
+ const value = feature.enabled ? "开" : "关";
+ const origin = feature.configured === null ? "默认" : "已设置";
+ const activity =
+ feature.enabled && !feature.active && feature.reason
+ ? `,${REASON_TEXT[feature.reason] ?? feature.reason}`
+ : "";
+ return `${feature.name}:${value}(${origin}${activity})— ${label}`;
+}
+
+export function renderFeaturesText(document: FeaturesDocument): string {
+ if ("code" in document) {
+ return `SDK 功能未能${document.state === "unavailable" ? "读取" : "修改"}:${document.code}\n`;
+ }
+ const state = document.features;
+ const lines = [`当前模式:${state.mode}`];
+ for (const feature of state.features) lines.push(featureLine(feature));
+ lines.push(
+ "片段召回(episode_recall)只对带片段的记忆有用:先开启 session_episodes,之后提取的记忆才会带片段。",
+ );
+ if (document.state === "unchanged") lines.push("没有需要改动的设置。");
+ if (document.state === "preview") {
+ lines.push("将设置:");
+ for (const [name, value] of Object.entries(document.target)) {
+ lines.push(`- ${name} = ${value ? "开" : "关"}`);
+ }
+ lines.push(`未执行任何改动。确认后运行:${document.next_step}`);
+ }
+ if (document.state === "committed") {
+ lines.push(
+ document.changed.length > 0
+ ? `已更新:${document.changed.join("、")}。正在进行的写入按原设置完成,之后的写入和检索使用新设置。`
+ : "已保存,生效的值没有变化。",
+ );
+ }
+ return `${lines.join("\n")}\n`;
+}
diff --git a/memhub/apps/cli/src/status-report.ts b/memhub/apps/cli/src/status-report.ts
index 4833f33..660c11a 100644
--- a/memhub/apps/cli/src/status-report.ts
+++ b/memhub/apps/cli/src/status-report.ts
@@ -83,6 +83,8 @@ export interface PipelineSummary {
}
>;
graph_build: string | null;
+ /** SDK features (`memory_features`) whose value differs from the default. */
+ features: Record<string, boolean>;
}
const MODES = new Set(["lite", "pro", "ultra"]);
@@ -127,6 +129,14 @@ export function describePipeline(value: unknown): PipelineSummary | null {
};
}
}
+ const features: Record<string, boolean> = {};
+ if (item.features && typeof item.features === "object") {
+ for (const [name, value] of Object.entries(
+ item.features as Record<string, unknown>,
+ )) {
+ if (typeof value === "boolean") features[name] = value;
+ }
+ }
const graph =
item.graph_build && typeof item.graph_build === "object"
? (item.graph_build as Record<string, unknown>)
@@ -146,6 +156,7 @@ export function describePipeline(value: unknown): PipelineSummary | null {
evolve_running: Array.isArray(evolve.running) ? evolve.running.length : 0,
evolve_users: users,
graph_build: typeof graph.state === "string" ? graph.state : null,
+ features,
};
}
@@ -329,6 +340,14 @@ export function pipelineLine(pipeline: PipelineSummary): string {
if (pipeline.evolve_running > 0)
parts.push(`,进行中 ${pipeline.evolve_running}`);
}
+ const changed = Object.entries(pipeline.features);
+ if (changed.length > 0) {
+ parts.push(
+ `;SDK 功能:${changed
+ .map(([name, value]) => `${name}=${value ? "开" : "关"}`)
+ .join("、")}`,
+ );
+ }
return parts.join("");
}
diff --git a/memhub/apps/core/src/one_memory/api.py b/memhub/apps/core/src/one_memory/api.py
index ed959fa..5c396ba 100644
--- a/memhub/apps/core/src/one_memory/api.py
+++ b/memhub/apps/core/src/one_memory/api.py
@@ -104,6 +104,7 @@ from one_memory.hy_sdk_runtime import (
close_all_shared_runtimes,
hold_stores_offline,
release_stores,
+ sdk_feature_defaults,
sdk_relevance_floor,
)
from one_memory.hy_sdk_types import (
@@ -192,6 +193,18 @@ from one_memory.memory_evolution import (
MemoryGraphBackfill,
UserEvolveState,
)
+from one_memory.memory_features import (
+ FEATURES,
+ FeatureCost,
+ FeatureOverrides,
+ FeatureReason,
+ FeatureSide,
+ MemoryFeatureName,
+ MemoryFeatures,
+ effective_features,
+ feature_activity,
+ non_default_features,
+)
from one_memory.memory_governance import (
MemoryGovernanceStore,
)
@@ -732,6 +745,52 @@ class PipelineStatus(BaseModel):
#: Newest finished run across users, for a one-line status.
last_evolve_at: datetime | None = None
graph_build: GraphBuildState
+ #: The SDK features (`memory_features`) whose value differs from the SDK
+ #: default; empty while every feature is at its default.
+ features: dict[MemoryFeatureName, bool] = Field(default_factory=dict)
+
+
+class MemoryFeatureState(BaseModel):
+ """One feature in `GET /api/v1/settings/memory-features`."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ name: MemoryFeatureName
+ #: What clients are built with: `configured`, else `default`.
+ enabled: bool
+ #: What a person set; null = not set, the SDK default applies.
+ configured: bool | None
+ #: The SDK default (its code default, or its own env var when set).
+ default: bool
+ #: Whether it acts in the current mode; `reason` says why not.
+ active: bool
+ reason: FeatureReason | None
+ side: FeatureSide
+ requires_mode: Literal["pro", "ultra"]
+ requires_feature: MemoryFeatureName | None
+ cost: FeatureCost
+ #: The `MemoryConfig` field it sets, and the SDK's own env var for it.
+ sdk_field: str
+ env: str
+ description: str
+
+
+class MemoryFeaturesState(BaseModel):
+ """`GET /api/v1/settings/memory-features`."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ mode: MemoryMode
+ features: tuple[MemoryFeatureState, ...]
+ #: Same as `pipeline.features`: the values that differ from the defaults.
+ non_default: dict[MemoryFeatureName, bool]
+
+
+class MemoryFeaturesChange(MemoryFeaturesState):
+ """`PUT /api/v1/settings/memory-features`: the new state and what changed."""
+
+ #: Features whose value changed; empty = nothing rebuilt.
+ changed: tuple[MemoryFeatureName, ...] = ()
def memory_mode_effects(
@@ -1220,6 +1279,7 @@ def create_app(
),
sedimentation_enabled=lambda: _config_store(app).sedimentation_enabled(),
memory_mode=lambda: _memory_mode(app),
+ memory_features=lambda: _memory_features(app),
)
app.state.sdk_memory_runtime = SdkMemoryRuntime(
coordinator=app.state.sdk_write_coordinator,
@@ -4296,6 +4356,58 @@ def create_app(
effects=memory_mode_effects(previous_effective, effective, graph_backfill=backfill),
)
+ @app.get(
+ "/api/v1/settings/memory-features",
+ response_model=MemoryFeaturesState,
+ dependencies=strict,
+ )
+ def get_memory_features() -> MemoryFeaturesState:
+ """The SDK retrieval and extraction features: value, default, active in this mode."""
+ return _memory_features_state(app)
+
+ @app.put(
+ "/api/v1/settings/memory-features",
+ response_model=MemoryFeaturesChange,
+ dependencies=strict,
+ )
+ async def put_memory_features(request: MemoryFeatures) -> MemoryFeaturesChange:
+ """Turn SDK features on or off; one global setting, not per user.
+
+ A key sets that feature, null resets it to the SDK default, an absent
+ key is left as it is; an unknown key or a non-boolean is 422. A
+ change rebuilds the SDK clients like a mode change: a write in flight
+ finishes with the old features, the next job and search use the new
+ ones. Nothing stored is migrated and no collection is renamed. See
+ docs/contracts/memory-features-v1.md.
+ """
+ store = _config_store(app)
+ async with app.state.memory_mode_lock:
+ defaults = await asyncio.to_thread(sdk_feature_defaults)
+ previous = _memory_features(app)
+ updated = store.memory_features().merged(request)
+ if updated != store.memory_features():
+ await asyncio.to_thread(store.set_memory_features, updated)
+ current = _memory_features(app)
+ before = effective_features(previous, defaults)
+ after = effective_features(current, defaults)
+ changed = tuple(spec.name for spec in FEATURES if before[spec.name] != after[spec.name])
+ if current != previous:
+ # Even a reset to the default value rebuilds: the client then
+ # carries no override at all, byte for byte the default config.
+ await app.state.sdk_write_coordinator.retire_stale_handles()
+ # Reads rebuild on their next request (`ActiveProfileReadHandle`).
+ diagnostic_event(
+ level="info",
+ component="memory.features",
+ event="memory_features.changed",
+ outcome="succeeded",
+ details={"changed": list(changed), "set": [name for name, _ in current]},
+ )
+ return MemoryFeaturesChange(
+ **_memory_features_state(app, defaults).model_dump(),
+ changed=changed,
+ )
+
@app.get(
"/api/v1/settings/evolve-schedule",
response_model=EvolveSchedule,
@@ -5648,13 +5760,14 @@ def _sdk_client_handle(app: FastAPI) -> SdkClientHandle:
handle = cast(SdkClientHandle | None, app.state.sdk_client_handle)
if handle is None:
# Reads open the embedding space writes fill: the active profile's,
- # the built-in one only when none is active (#242). A profile or a
- # memory-mode change rebuilds the client.
+ # the built-in one only when none is active (#242). A profile, a
+ # memory-mode or a feature change rebuilds the client.
handle = ActiveProfileReadHandle(
profiles=_model_profile_store(app),
secrets=_secret_store(app),
data_dir=cast(Settings, app.state.settings).data_dir,
memory_mode=lambda: _memory_mode(app),
+ features=lambda: _memory_features(app),
)
app.state.sdk_client_handle = handle
return handle
@@ -5691,6 +5804,47 @@ def _evolve_overview(app: FastAPI) -> EvolveOverview:
)
+def _memory_features(app: FastAPI) -> FeatureOverrides:
+ """The SDK features a person set, as the key every SDK client is built with."""
+ store = getattr(app.state, "config_store", None)
+ return store.memory_features().overrides() if store is not None else ()
+
+
+def _memory_features_state(
+ app: FastAPI, defaults: dict[str, bool] | None = None
+) -> MemoryFeaturesState:
+ defaults = sdk_feature_defaults() if defaults is None else defaults
+ overrides = _memory_features(app)
+ configured = dict(overrides)
+ effective = effective_features(overrides, defaults)
+ mode = _memory_mode(app)
+ features = []
+ for spec in FEATURES:
+ reason = feature_activity(spec.name, effective, mode)
+ features.append(
+ MemoryFeatureState(
+ name=spec.name,
+ enabled=effective[spec.name],
+ configured=configured.get(spec.name),
+ default=defaults[spec.name],
+ active=reason is None,
+ reason=reason,
+ side=spec.side,
+ requires_mode=spec.requires_mode,
+ requires_feature=spec.requires_feature,
+ cost=spec.cost,
+ sdk_field=spec.sdk_field,
+ env=spec.env,
+ description=spec.description,
+ )
+ )
+ return MemoryFeaturesState(
+ mode=mode,
+ features=tuple(features),
+ non_default=cast(dict[MemoryFeatureName, bool], non_default_features(overrides, defaults)),
+ )
+
+
def _pipeline_status(app: FastAPI) -> PipelineStatus | None:
"""R10's `pipeline`, or None before the evolve state exists (legacy tests)."""
if getattr(app.state, "evolve_state_store", None) is None:
@@ -5707,6 +5861,10 @@ def _pipeline_status(app: FastAPI) -> PipelineStatus | None:
evolve=overview,
last_evolve_at=max(finished, default=None),
graph_build=state.graph_build,
+ features=cast(
+ dict[MemoryFeatureName, bool],
+ non_default_features(_memory_features(app), sdk_feature_defaults()),
+ ),
)
diff --git a/memhub/apps/core/src/one_memory/hy_sdk_runtime.py b/memhub/apps/core/src/one_memory/hy_sdk_runtime.py
index 48f7490..84f5ecb 100644
--- a/memhub/apps/core/src/one_memory/hy_sdk_runtime.py
+++ b/memhub/apps/core/src/one_memory/hy_sdk_runtime.py
@@ -11,7 +11,7 @@ import asyncio
import hashlib
import os
import threading
-from collections.abc import Callable, Coroutine
+from collections.abc import Callable, Coroutine, Iterable, Mapping
from dataclasses import dataclass
from pathlib import Path
from typing import Any, ClassVar
@@ -37,6 +37,12 @@ from one_memory.hy_graph_admin import (
from one_memory.hy_sdk_types import HySdkRuntimeError
from one_memory.local_embedding import LocalEmbedder
from one_memory.log_file import confine_hy_sdk_logging
+from one_memory.memory_features import (
+ FEATURES,
+ FEATURES_BY_NAME,
+ FeatureOverrides,
+ feature_overrides,
+)
from one_memory.model_profiles import (
ModelProfileSnapshot,
ProviderKind,
@@ -171,6 +177,7 @@ class SdkClientHandle:
data_dir: Path,
http_transport_factory: Callable[[], Any] | None = None,
mode: str | None = None,
+ features: FeatureOverrides = (),
) -> None:
self._profile = profile
self._api_key = api_key
@@ -178,6 +185,8 @@ class SdkClientHandle:
self._http_transport_factory = http_transport_factory
#: The SDK mode this handle's client is built with, fixed for its life.
self.mode = mode or effective_memory_mode()
+ #: The SDK features set on its config (`memory_features`), fixed likewise.
+ self.features = features
self._lease: ClientLease | None = None
self._lock = asyncio.Lock()
@@ -193,6 +202,7 @@ class SdkClientHandle:
data_dir=self._data_dir,
http_transport_factory=self._http_transport_factory,
mode=self.mode,
+ features=self.features,
)
return self._lease.client
@@ -259,13 +269,48 @@ def sdk_relevance_floor() -> float:
return min(1.0, max(0.0, value))
+def sdk_feature_defaults() -> dict[str, bool]:
+ """Each `memory_features` feature's SDK default, as a fresh config has it.
+
+ That is the SDK's code default unless the process environment sets the
+ SDK's own variable (`FeatureSpec.env`), exactly what an unset feature
+ leaves on a client.
+ """
+ config = MemoryConfig()
+ return {
+ spec.name: bool(getattr(getattr(config, spec.section), spec.field)) for spec in FEATURES
+ }
+
+
+def apply_sdk_features(
+ config: MemoryConfig, features: Mapping[str, bool] | Iterable[tuple[str, bool]]
+) -> MemoryConfig:
+ """Set each feature a person chose on its `MemoryConfig` field.
+
+ Every exposed feature is a config field the SDK reads from the config at
+ call time, never from `os.environ`, so this is per client and
+ deterministic. Nothing here touches `vector_store`, so the collection
+ identity never depends on a feature.
+ """
+ values = dict(features.items() if isinstance(features, Mapping) else features)
+ for name, value in feature_overrides(values):
+ spec = FEATURES_BY_NAME[name]
+ setattr(getattr(config, spec.section), spec.field, value)
+ return config
+
+
def build_sdk_config(
profile: ModelProfileSnapshot,
*,
api_key: str | None,
data_dir: Path,
+ features: Mapping[str, bool] | Iterable[tuple[str, bool]] = (),
) -> MemoryConfig:
- """Map a model snapshot to SDK models, endpoints, backends, and local paths."""
+ """Map a model snapshot to SDK models, endpoints, backends, and local paths.
+
+ `features` (`memory_features`) are set on top; with none the config is
+ exactly what it was before the setting existed.
+ """
generation_endpoint, generation_key = _generation_access(profile, api_key)
embedding_provider = profile.embedding_provider_kind or profile.provider_kind
embedding_service_is_local = embedding_provider is ProviderKind.LOCAL_ONNX
@@ -311,7 +356,7 @@ def build_sdk_config(
if thinking_off:
llm["extra_body"] = thinking_off
- return MemoryConfig.from_dict(
+ config = MemoryConfig.from_dict(
{
"llm": llm,
"embedder": {
@@ -348,6 +393,7 @@ def build_sdk_config(
"coding": {"db_path": str(root / "coding.sqlite3")},
}
)
+ return apply_sdk_features(config, features)
def acquire_client(
@@ -357,11 +403,14 @@ def acquire_client(
data_dir: Path,
http_transport_factory: Callable[[], Any] | None = None,
mode: str | None = None,
+ features: FeatureOverrides = (),
) -> ClientLease:
"""Construct a public SDK client and return its explicit runtime lease.
`mode` is the SDK pipeline mode (lite / pro / ultra); None keeps the
pre-setting default (ultra when `ONE_MEMORY_GRAPH_STORE` is set, else pro).
+ `features` are the `memory_features` set on its config; none keeps every
+ SDK default.
Waits while `hold_stores_offline` holds this home's stores.
"""
key = data_dir.resolve()
@@ -376,6 +425,7 @@ def acquire_client(
data_dir=data_dir,
http_transport_factory=http_transport_factory,
mode=mode or effective_memory_mode(),
+ features=features,
)
finally:
with _STORE_GATE:
@@ -415,8 +465,9 @@ def _acquire_client(
data_dir: Path,
http_transport_factory: Callable[[], Any] | None,
mode: str = "pro",
+ features: FeatureOverrides = (),
) -> ClientLease:
- config = build_sdk_config(profile, api_key=api_key, data_dir=data_dir)
+ config = build_sdk_config(profile, api_key=api_key, data_dir=data_dir, features=features)
config.http_transport_factory = http_transport_factory
mismatch = inspect_graph_width_mismatch(config)
if mismatch is not None:
diff --git a/memhub/apps/core/src/one_memory/memory_features.py b/memhub/apps/core/src/one_memory/memory_features.py
new file mode 100644
index 0000000..a8c0727
--- /dev/null
+++ b/memhub/apps/core/src/one_memory/memory_features.py
@@ -0,0 +1,262 @@
+"""SDK retrieval and extraction features a person may turn on or off.
+
+MemHub hard-codes none of these. Each is one `MemoryConfig` field that the SDK
+reads from its config object (never from `os.environ` at call time), so
+`hy_sdk_runtime.build_sdk_config` sets it per client and a client's features
+are fixed for its life, like its mode. An unset feature keeps the SDK default,
+so with nothing set the SDK config is byte for byte what it was before this
+setting existed.
+
+The setting is one global document in `config.json` (`memory_features`),
+beside `memory_mode`; management stays global, not per user. A change
+rebuilds the SDK handles the way a mode change does (#218 use count).
+
+What is deliberately left out, and why, is in
+docs/contracts/memory-features-v1.md. In short: flags the SDK reads straight
+from the process environment (the System 2 schema dedup/compaction lane, the
+balanced-catalog and specific-supplement lanes, the hybrid reader's
+`MEMORY_HYBRID_V2_*` knobs) cannot be scoped to one client; flags MemHub never
+exercises (query rewrite needs `queries=[...]`, session narratives need
+`finalize_session`); flags that are dangerous or internal (graph write, local
+cross-encoder download, access write-back); and everything MemHub already
+controls elsewhere (pipeline log, trace, memory operations, telemetry, mode).
+
+No SDK import here: only `hy_sdk_runtime` and `hy_sdk_migration` import it.
+`config_state` imports this module, so it imports nothing from there.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from dataclasses import dataclass
+from typing import Literal
+
+from pydantic import BaseModel, ConfigDict, StrictBool
+
+MemoryFeatureName = Literal[
+ "graph_rerank",
+ "same_series_timeline",
+ "episode_recall",
+ "session_episodes",
+ "episode_summary",
+ "intention",
+ "few_shot",
+]
+#: Read features change search; write features change what extraction stores.
+FeatureSide = Literal["read", "write"]
+#: none: no extra call. extra_query: one more store query per search.
+#: llm_call: extra generation-model calls. prompt_tokens: no extra call, but
+#: a longer extraction prompt.
+FeatureCost = Literal["none", "extra_query", "llm_call", "prompt_tokens"]
+#: Why an enabled feature does nothing right now (`active: false`).
+FeatureReason = Literal["disabled", "requires_pro", "requires_ultra", "requires_graph_rerank"]
+#: A client's features as a hashable key: sorted (name, value) pairs, set ones only.
+type FeatureOverrides = tuple[tuple[str, bool], ...]
+
+_MODE_RANK: dict[str, int] = {"lite": 0, "pro": 1, "ultra": 2}
+
+
+@dataclass(frozen=True)
+class FeatureSpec:
+ name: MemoryFeatureName
+ #: `MemoryConfig` section and field the value is written to.
+ section: Literal["graph_store", "recall", "llm"]
+ field: str
+ #: The SDK's own env var for the same field; only its default comes from it.
+ env: str
+ side: FeatureSide
+ #: Lowest mode the feature acts in.
+ requires_mode: Literal["pro", "ultra"]
+ #: Another feature that must be active for this one to act.
+ requires_feature: MemoryFeatureName | None
+ cost: FeatureCost
+ description: str
+
+ @property
+ def sdk_field(self) -> str:
+ return f"{self.section}.{self.field}"
+
+
+FEATURES: tuple[FeatureSpec, ...] = (
+ FeatureSpec(
+ name="graph_rerank",
+ section="graph_store",
+ field="graph_rerank_enabled",
+ env="MEMORY_GRAPH_RERANK_ENABLED",
+ side="read",
+ requires_mode="ultra",
+ requires_feature=None,
+ cost="extra_query",
+ description=(
+ "Usage A: propagate support over knowledge-graph edges inside the "
+ "recall pool, so memories linked to strong hits rank higher. Needs "
+ "the graph store (ultra). No model call; one graph query per search."
+ ),
+ ),
+ FeatureSpec(
+ name="same_series_timeline",
+ section="recall",
+ field="same_series_timeline_enabled",
+ env="MEMORY_SAME_SERIES_TIMELINE_ENABLED",
+ side="read",
+ requires_mode="ultra",
+ requires_feature="graph_rerank",
+ cost="none",
+ description=(
+ "Keep memories joined by a same-series graph edge together, in time "
+ "order, in the results. Uses the edges graph rerank reads, so it "
+ "needs graph_rerank (ultra). No model call."
+ ),
+ ),
+ FeatureSpec(
+ name="episode_recall",
+ section="recall",
+ field="episode_recall_enabled",
+ env="MEMORY_EPISODE_RECALL_ENABLED",
+ side="read",
+ requires_mode="pro",
+ requires_feature=None,
+ cost="extra_query",
+ description=(
+ "Usage B: pull in memories from the same episode as a hit and score "
+ "them on tag-keyword overlap, content overlap and time affinity. No "
+ "graph needed (pro or ultra). No model call; one store query per "
+ "search. Helps only memories that carry an episode_id."
+ ),
+ ),
+ FeatureSpec(
+ name="session_episodes",
+ section="recall",
+ field="session_episode_enabled",
+ env="MEMORY_SESSION_EPISODE_ENABLED",
+ side="write",
+ requires_mode="pro",
+ requires_feature=None,
+ cost="none",
+ description=(
+ "Episode write side: memories extracted from one conversation share "
+ "one stable episode_id, instead of the default rule (a new episode "
+ "after 30 minutes idle or 50 memories). No model call."
+ ),
+ ),
+ FeatureSpec(
+ name="episode_summary",
+ section="recall",
+ field="episode_summary_enabled",
+ env="MEMORY_EPISODE_SUMMARY_ENABLED",
+ side="write",
+ requires_mode="pro",
+ requires_feature=None,
+ cost="llm_call",
+ description=(
+ "When an episode closes (the idle-gap rule), summarize it once into "
+ "an episode memory. One model call per closed episode of 3 or more "
+ "memories."
+ ),
+ ),
+ FeatureSpec(
+ name="intention",
+ section="llm",
+ field="enable_intention",
+ env="MEMORY_ENABLE_INTENTION",
+ side="write",
+ requires_mode="pro",
+ requires_feature=None,
+ cost="none",
+ description=(
+ "Extract the user's stated plans and intentions (L7) along with "
+ "facts. On by default; off drops them from the extraction prompt. "
+ "No extra call."
+ ),
+ ),
+ FeatureSpec(
+ name="few_shot",
+ section="llm",
+ field="few_shot_enabled",
+ env="MEMORY_FEW_SHOT_ENABLED",
+ side="write",
+ requires_mode="pro",
+ requires_feature=None,
+ cost="prompt_tokens",
+ description=(
+ "Append worked examples to the extraction and reconcile prompts. "
+ "Can help a weaker model; no extra call, but every extraction "
+ "sends more input tokens."
+ ),
+ ),
+)
+FEATURE_NAMES: tuple[MemoryFeatureName, ...] = tuple(spec.name for spec in FEATURES)
+FEATURES_BY_NAME: dict[str, FeatureSpec] = {spec.name: spec for spec in FEATURES}
+
+
+class MemoryFeatures(BaseModel):
+ """`config.json` `memory_features`, and the `PUT` body.
+
+ Every key is optional; absent (or null) means the SDK default. In a `PUT`
+ an absent key is left as it is and null resets it. Unknown keys and
+ non-boolean values are refused (422).
+ """
+
+ model_config = ConfigDict(frozen=True, extra="forbid", strict=True)
+
+ graph_rerank: StrictBool | None = None
+ same_series_timeline: StrictBool | None = None
+ episode_recall: StrictBool | None = None
+ session_episodes: StrictBool | None = None
+ episode_summary: StrictBool | None = None
+ intention: StrictBool | None = None
+ few_shot: StrictBool | None = None
+
+ def overrides(self) -> FeatureOverrides:
+ """The features a person set, as the client key."""
+ return feature_overrides(
+ {name: value for name, value in self.model_dump().items() if value is not None}
+ )
+
+ def merged(self, update: MemoryFeatures) -> MemoryFeatures:
+ """This document with the keys `update` names: a value sets, null resets."""
+ values = self.model_dump()
+ for name in update.model_fields_set:
+ values[name] = getattr(update, name)
+ return MemoryFeatures(**{key: value for key, value in values.items() if value is not None})
+
+
+def feature_overrides(values: Mapping[str, bool]) -> FeatureOverrides:
+ unknown = set(values) - set(FEATURES_BY_NAME)
+ if unknown:
+ raise ValueError("unknown_memory_feature")
+ return tuple(sorted((name, bool(value)) for name, value in values.items()))
+
+
+def effective_features(
+ overrides: FeatureOverrides, defaults: Mapping[str, bool]
+) -> dict[str, bool]:
+ """Every feature's value: what a person set, else the SDK default."""
+ values: dict[str, bool] = {spec.name: bool(defaults.get(spec.name, False)) for spec in FEATURES}
+ values.update(dict(overrides))
+ return values
+
+
+def feature_activity(name: str, effective: Mapping[str, bool], mode: str) -> FeatureReason | None:
+ """None when the feature acts in this mode; else why it does not."""
+ spec = FEATURES_BY_NAME[name]
+ if not effective.get(name, False):
+ return "disabled"
+ if _MODE_RANK.get(mode, 0) < _MODE_RANK[spec.requires_mode]:
+ return "requires_ultra" if spec.requires_mode == "ultra" else "requires_pro"
+ if spec.requires_feature is not None and (
+ feature_activity(spec.requires_feature, effective, mode) is not None
+ ):
+ return "requires_graph_rerank"
+ return None
+
+
+def non_default_features(
+ overrides: FeatureOverrides, defaults: Mapping[str, bool]
+) -> dict[str, bool]:
+ """The features whose value differs from the SDK default, for status."""
+ return {
+ name: value
+ for name, value in effective_features(overrides, defaults).items()
+ if value != bool(defaults.get(name, False))
+ }
diff --git a/memhub/apps/core/src/one_memory/memory_server/config_state.py b/memhub/apps/core/src/one_memory/memory_server/config_state.py
index 3f7419e..3340d62 100644
--- a/memhub/apps/core/src/one_memory/memory_server/config_state.py
+++ b/memhub/apps/core/src/one_memory/memory_server/config_state.py
@@ -17,6 +17,7 @@ from typing import Literal
from pydantic import BaseModel, ConfigDict, Field, StrictBool, field_validator
+from one_memory.memory_features import MemoryFeatures
from one_memory.memory_queue import ExtractionWindowPreset
_SOURCE_ID = re.compile(r"^[a-z0-9][a-z0-9-]{0,127}$")
@@ -69,6 +70,9 @@ class ConfigDocument(BaseModel):
#: still forces ultra over it; see `hy_graph_admin.effective_memory_mode`.
memory_mode: MemoryMode = "pro"
evolve_schedule: EvolveSchedule = Field(default_factory=EvolveSchedule)
+ #: SDK retrieval and extraction features a person set; an unset one keeps
+ #: the SDK default. See `one_memory.memory_features`.
+ memory_features: MemoryFeatures = Field(default_factory=MemoryFeatures)
@field_validator("sources")
@classmethod
@@ -91,7 +95,7 @@ class ConfigFileError(RuntimeError):
pass
-_WRITTEN_WHEN_SET = frozenset({"memory_mode", "evolve_schedule"})
+_WRITTEN_WHEN_SET = frozenset({"memory_mode", "evolve_schedule", "memory_features"})
class ConfigStore:
@@ -166,6 +170,19 @@ class ConfigStore:
self._document = updated
return updated
+ def memory_features(self) -> MemoryFeatures:
+ with self._lock:
+ return self._document.memory_features
+
+ def set_memory_features(self, features: MemoryFeatures) -> ConfigDocument:
+ if not isinstance(features, MemoryFeatures):
+ raise ValueError("invalid_memory_features")
+ with self._lock:
+ updated = self._document.model_copy(update={"memory_features": features})
+ self._write(updated)
+ self._document = updated
+ return updated
+
def migrate_extraction_window_preset(self, preset: ExtractionWindowPreset) -> ConfigDocument:
"""Adopt the legacy SQL value only when config.json has no value."""
if not isinstance(preset, ExtractionWindowPreset):
@@ -214,9 +231,13 @@ class ConfigStore:
# Settings added after 1.0.5 are written only once a person chose
# them, so an untouched install's file stays what older builds read.
unset = {name for name in _WRITTEN_WHEN_SET if name not in document.model_fields_set}
+ values = document.model_dump(mode="json", exclude=unset)
+ if "memory_features" in values:
+ # Only the features a person set; an absent one is the SDK default.
+ values["memory_features"] = document.memory_features.model_dump(exclude_none=True)
payload = (
json.dumps(
- document.model_dump(mode="json", exclude=unset),
+ values,
ensure_ascii=False,
indent=2,
sort_keys=True,
diff --git a/memhub/apps/core/src/one_memory/sdk_read_handle.py b/memhub/apps/core/src/one_memory/sdk_read_handle.py
index e9d13fb..016504c 100644
--- a/memhub/apps/core/src/one_memory/sdk_read_handle.py
+++ b/memhub/apps/core/src/one_memory/sdk_read_handle.py
@@ -12,8 +12,9 @@ is closed once no task still uses it, as `SdkWriteCoordinator` does for writes
HTTP request, one retention pass).
The memory mode (lite / pro / ultra) is fixed per SDK client, so a mode change
-rebuilds and retires the same way: handles are keyed by (profile, mode). The
-mode never names a collection; it is a separate client parameter.
+rebuilds and retires the same way, and so do the SDK features
+(`memory_features`): handles are keyed by (profile, mode, features). Neither
+mode nor features names a collection; both are separate client parameters.
"""
from __future__ import annotations
@@ -31,6 +32,7 @@ from one_memory.hy_sdk_runtime import (
retrieval_view,
)
from one_memory.hy_sdk_types import HySdkRuntimeError
+from one_memory.memory_features import FeatureOverrides
from one_memory.model_profiles import ModelProfileStore, ProviderKind
from one_memory.secrets import SecretStore, SecretStoreUnavailableError
@@ -47,13 +49,15 @@ class ActiveProfileReadHandle(SdkClientHandle):
secrets: SecretStore,
data_dir: Path,
memory_mode: Callable[[], str] = effective_memory_mode,
+ features: Callable[[], FeatureOverrides] = lambda: (),
) -> None:
super().__init__(builtin_retrieval_snapshot(), api_key=None, data_dir=data_dir)
self.profiles = profiles
self.secrets = secrets
self.data_dir = data_dir
self.memory_mode = memory_mode
- self._handles: dict[tuple[str, int, str], SdkClientHandle] = {}
+ self.current_features = features
+ self._handles: dict[tuple[str, int, str, FeatureOverrides], SdkClientHandle] = {}
#: Tasks in flight per handle; a retired handle closes at zero.
self._uses: dict[SdkClientHandle, int] = {}
self._retired: set[SdkClientHandle] = set()
@@ -62,7 +66,7 @@ class ActiveProfileReadHandle(SdkClientHandle):
async def client(self) -> Any:
profile = await asyncio.to_thread(self.profiles.active_identity) or _BUILTIN
- identity = (*profile, self.memory_mode())
+ identity = (*profile, self.memory_mode(), self.current_features())
async with self._handle_lock:
handle = self._handles.get(identity)
if handle is None:
@@ -104,12 +108,16 @@ class ActiveProfileReadHandle(SdkClientHandle):
self._closing.add(closing)
closing.add_done_callback(self._closing.discard)
- def _build(self, key: tuple[str, int, str]) -> SdkClientHandle:
- profile_id, revision, mode = key
+ def _build(self, key: tuple[str, int, str, FeatureOverrides]) -> SdkClientHandle:
+ profile_id, revision, mode, features = key
identity = (profile_id, revision)
if identity == _BUILTIN:
return SdkClientHandle(
- builtin_retrieval_snapshot(), api_key=None, data_dir=self.data_dir, mode=mode
+ builtin_retrieval_snapshot(),
+ api_key=None,
+ data_dir=self.data_dir,
+ mode=mode,
+ features=features,
)
profile = self.profiles.snapshot(*identity)
view = retrieval_view(profile)
@@ -122,4 +130,6 @@ class ActiveProfileReadHandle(SdkClientHandle):
raise HySdkRuntimeError("secure_storage_unavailable") from None
if secret is None:
raise HySdkRuntimeError("model_secret_unavailable")
- return SdkClientHandle(view, api_key=secret, data_dir=self.data_dir, mode=mode)
+ return SdkClientHandle(
+ view, api_key=secret, data_dir=self.data_dir, mode=mode, features=features
+ )
diff --git a/memhub/apps/core/src/one_memory/sdk_write_processor.py b/memhub/apps/core/src/one_memory/sdk_write_processor.py
index ca98bf7..b345be1 100644
--- a/memhub/apps/core/src/one_memory/sdk_write_processor.py
+++ b/memhub/apps/core/src/one_memory/sdk_write_processor.py
@@ -13,6 +13,7 @@ from one_memory.hy_graph_admin import effective_memory_mode
from one_memory.hy_sdk_runtime import SdkClientHandle, builtin_retrieval_snapshot
from one_memory.imports.models import EvidenceContentKind, EvidenceOrigin, EvidenceRecord
from one_memory.input_sanitization import sanitize_model_input
+from one_memory.memory_features import FeatureOverrides
from one_memory.model_profiles import ModelProfileSnapshot, ModelProfileStore
from one_memory.secrets import SecretStore, SecretStoreUnavailableError
@@ -146,8 +147,9 @@ class SdkWriteCoordinator:
the SharedRuntime closed mid-`add`, the job failed with AttributeError
after HY was invoked, and it was left `unknown`.
- Handles are keyed by profile and memory mode, so a mode change retires
- handles the same way. In lite no generation model is needed: without an
+ Handles are keyed by profile, memory mode and the SDK features
+ (`memory_features`), so a mode or feature change retires handles the same
+ way. In lite no generation model is needed: without an
active profile the built-in local embedder writes raw turns.
`exclusive_for_evolve(user_id)` keeps evolve and that user's writes
@@ -165,6 +167,7 @@ class SdkWriteCoordinator:
transport_factory: Callable[[ModelProfileSnapshot], Callable[[], Any] | None],
sedimentation_enabled: Callable[[], bool],
memory_mode: Callable[[], str] = effective_memory_mode,
+ memory_features: Callable[[], FeatureOverrides] = lambda: (),
) -> None:
self.profiles = profiles
self.secrets = secrets
@@ -172,7 +175,8 @@ class SdkWriteCoordinator:
self.transport_factory = transport_factory
self.sedimentation_enabled = sedimentation_enabled
self.memory_mode = memory_mode
- self._handles: dict[tuple[str, int, str], SdkClientHandle] = {}
+ self.memory_features = memory_features
+ self._handles: dict[tuple[str, int, str, FeatureOverrides], SdkClientHandle] = {}
#: Users evolve (or the graph backfill) is running for, the writes in
#: flight per user, and one exclusive run per user at a time. Writes
#: of one user still run side by side; only evolve waits for them.
@@ -217,15 +221,16 @@ class SdkWriteCoordinator:
async with self._writes_idle:
self._writes_idle.notify_all()
- async def retire_stale_modes(self) -> None:
- """After a mode change: retire handles of other modes, closing the idle ones.
+ async def retire_stale_handles(self) -> None:
+ """After a mode or feature change: retire handles built otherwise.
- A handle still writing is closed when its last use ends (#218), so a
- write that started in the old mode finishes in it.
+ The idle ones close now. A handle still writing is closed when its
+ last use ends (#218), so a write that started in the old mode, or
+ with the old features, finishes in it.
"""
- mode = self.memory_mode()
+ build = (self.memory_mode(), self.memory_features())
async with self._lock:
- stale = {key: handle for key, handle in self._handles.items() if key[2] != mode}
+ stale = {key: handle for key, handle in self._handles.items() if key[2:] != build}
for key in stale:
del self._handles[key]
self._retired.update(stale.values())
@@ -233,6 +238,9 @@ class SdkWriteCoordinator:
self._retired -= unused
await asyncio.gather(*(value.close() for value in unused))
+ #: The name #253 introduced; a mode change is one kind of rebuild.
+ retire_stale_modes = retire_stale_handles
+
def evolving(self, user_id: str) -> bool:
"""Whether evolve holds this user, so their queued writes should wait."""
return user_id in self._evolving
@@ -280,10 +288,11 @@ class SdkWriteCoordinator:
async def _active_handle(self) -> AsyncIterator[SdkClientHandle]:
"""Use the active profile's handle; retire the others, closing the unused."""
mode = self.memory_mode()
+ features = self.memory_features()
profile_identity, profile, secret = await asyncio.to_thread(
self._read_active_credentials, mode
)
- identity = (*profile_identity, mode)
+ identity = (*profile_identity, mode, features)
async with self._lock:
handle = self._handles.get(identity)
if handle is None:
@@ -293,6 +302,7 @@ class SdkWriteCoordinator:
data_dir=self.data_dir,
http_transport_factory=self.transport_factory(profile),
mode=mode,
+ features=features,
)
self._handles[identity] = handle
self._retired.update(value for key, value in self._handles.items() if key != identity)
diff --git a/memhub/apps/core/tests/TEST_INDEX.md b/memhub/apps/core/tests/TEST_INDEX.md
index e4adde4..719e2ed 100644
--- a/memhub/apps/core/tests/TEST_INDEX.md
+++ b/memhub/apps/core/tests/TEST_INDEX.md
@@ -159,6 +159,7 @@
| `test_memory_citation_query_plan.py` | `contract` | Correlated citation checks must look links up by memory, not scan by 'active'. |
| `test_memory_content_import.py` | `integration` | 覆盖 existing memory preview keeps unknown author and exact original、invalid existing memory records never leave a partial upload、memory content requires explicit mode and rejects vendor guessing 等 5 个场景。 |
| `test_memory_evidence_freshness.py` | `contract` | 新鲜度拆除后:读路径恒为 current;证据修订 / 畸形 proof / segment ref 不再藏记忆或 503。 |
+| `test_memory_features.py` | `contract` | The SDK retrieval and extraction features MemHub lets a person turn on. |
| `test_memory_freshness_integration_review.py` | `integration` | Independent synthetic read-path review; no lifespan, model or user database. |
| `test_memory_library_all_scenes.py` | `integration` | The v2 memory library across chat, working and coding memories. |
| `test_memory_mode_and_evolve.py` | `contract` | The memory mode (lite / pro / ultra), evolve and its nightly schedule. |
@@ -313,4 +314,4 @@
| `test_workspace_recall.py` | `contract` | Workspace memories were unreachable from every host; these pin the way in. |
| `test_write_queue_lease_renewal.py` | `contract` | Rule 8: a lease must outlive the work it covers, and be renewed while it runs. |
-共 308 个测试文件。
+共 309 个测试文件。
diff --git a/memhub/apps/core/tests/core_test_classification.py b/memhub/apps/core/tests/core_test_classification.py
index 226e871..13c1228 100644
--- a/memhub/apps/core/tests/core_test_classification.py
+++ b/memhub/apps/core/tests/core_test_classification.py
@@ -14,8 +14,8 @@ from pathlib import Path
import pytest
PRIMARY_MARKERS = ("unit", "contract", "integration", "performance", "live")
-EXPECTED_TEST_FILE_COUNT = 308
-EXPECTED_TEST_FILES_SHA256 = "3aadf5953e41c01d4b60469f47242c00d2acef3c42550aa017255e31d216b589"
+EXPECTED_TEST_FILE_COUNT = 309
+EXPECTED_TEST_FILES_SHA256 = "a7d6ed33175f618d2d40f401d447a5553e1347ffd51dd878370c0fc84d13396d"
# Pure transformations, validation models, parity checks and state machines.
# This list is intentionally small: uncertain files default to contract.
diff --git a/memhub/apps/core/tests/test_core_ready_before_recovery.py b/memhub/apps/core/tests/test_core_ready_before_recovery.py
index b324116..b0c3991 100644
--- a/memhub/apps/core/tests/test_core_ready_before_recovery.py
+++ b/memhub/apps/core/tests/test_core_ready_before_recovery.py
@@ -164,7 +164,7 @@ def test_metadata_repair_never_overlaps_an_sdk_client(tmp_path, monkeypatch):
events.append("repair_finished")
return MetadataRepairResult(None, 0, 0, 0)
- def open_client(profile, *, api_key, data_dir, http_transport_factory, mode="pro"):
+ def open_client(profile, *, api_key, data_dir, http_transport_factory, mode="pro", features=()):
events.append("client_opened")
return ClientLease(object(), data_dir.resolve())
diff --git a/memhub/apps/core/tests/test_memory_features.py b/memhub/apps/core/tests/test_memory_features.py
new file mode 100644
index 0000000..47abae4
--- /dev/null
+++ b/memhub/apps/core/tests/test_memory_features.py
@@ -0,0 +1,499 @@
+"""The SDK retrieval and extraction features MemHub lets a person turn on.
+
+Graph rerank (usage A), episode recall (usage B), the episode write side and
+the extraction switches are `MemoryConfig` fields. MemHub hard-codes none of
+them: one global `memory_features` document sets them per client in
+`build_sdk_config`, an unset one keeps the SDK default (so nothing set is the
+config of before, byte for byte), and a change rebuilds the handles the way a
+mode change does. A feature never touches the vector collection identity.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import dataclasses
+import json
+from contextlib import asynccontextmanager
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from httpx import ASGITransport, AsyncClient
+from pydantic import SecretStr, ValidationError
+
+from one_memory import hy_sdk_runtime, sdk_write_processor
+from one_memory.api import create_app
+from one_memory.config import Settings
+from one_memory.memory_features import (
+ FEATURE_NAMES,
+ FEATURES,
+ FEATURES_BY_NAME,
+ MemoryFeatures,
+ effective_features,
+ feature_activity,
+)
+from one_memory.memory_server.config_state import ConfigStore
+from one_memory.model_profiles import ModelProfileSnapshot, ProviderKind
+from one_memory.secrets import InMemorySecretStore
+
+TOKEN = "memory-features-test"
+
+#: What MemHub ran with before the setting existed, on a clean environment.
+TODAY = {
+ "graph_rerank": False,
+ "same_series_timeline": False,
+ "episode_recall": False,
+ "session_episodes": False,
+ "episode_summary": False,
+ "intention": True,
+ "few_shot": False,
+}
+
+
[email protected](autouse=True)
+def _clean_sdk_env(monkeypatch):
+ """The SDK's own env vars feed its defaults; tests start without them."""
+ for spec in FEATURES:
+ monkeypatch.delenv(spec.env, raising=False)
+ monkeypatch.delenv("ONE_MEMORY_GRAPH_STORE", raising=False)
+
+
+def _remote_profile() -> ModelProfileSnapshot:
+ return ModelProfileSnapshot(
+ profile_id="remote",
+ revision=3,
+ provider_kind=ProviderKind.OPENAI_COMPATIBLE,
+ base_url="https://models.example.test/v1",
+ model="chat-model",
+ embedding_provider_kind=ProviderKind.OPENAI_COMPATIBLE,
+ embedding_model="embed-model",
+ embedding_dimensions=1024,
+ timeout_seconds=60,
+ max_concurrency=1,
+ context_window=None,
+ has_api_key=True,
+ # Since #255 the embedding endpoint is its own field, never inherited.
+ embedding_base_url="https://models.example.test/v1",
+ )
+
+
+PROFILES = (hy_sdk_runtime.builtin_retrieval_snapshot(), _remote_profile())
+
+
+def _config(tmp_path: Path, profile: ModelProfileSnapshot, features=()):
+ return hy_sdk_runtime.build_sdk_config(
+ profile, api_key="secret-key", data_dir=tmp_path, features=features
+ )
+
+
+def _field(config, name: str) -> bool:
+ spec = FEATURES_BY_NAME[name]
+ return getattr(getattr(config, spec.section), spec.field)
+
+
+# --- the catalog and the document ------------------------------------------
+
+
+def test_the_document_names_exactly_the_catalog() -> None:
+ assert tuple(MemoryFeatures.model_fields) == FEATURE_NAMES
+ assert set(TODAY) == set(FEATURE_NAMES)
+ # Each feature is a MemoryConfig field the SDK has; no env var is written.
+ defaults = hy_sdk_runtime.sdk_feature_defaults()
+ assert set(defaults) == set(FEATURE_NAMES)
+
+
+def test_the_defaults_are_todays_behaviour() -> None:
+ assert hy_sdk_runtime.sdk_feature_defaults() == TODAY
+ assert MemoryFeatures().overrides() == ()
+ assert effective_features((), TODAY) == TODAY
+
+
+def test_the_sdk_env_var_still_moves_the_default_of_an_unset_feature(monkeypatch) -> None:
+ monkeypatch.setenv("MEMORY_EPISODE_RECALL_ENABLED", "true")
+ assert hy_sdk_runtime.sdk_feature_defaults()["episode_recall"] is True
+
+
+def test_unknown_or_non_boolean_values_are_refused() -> None:
+ with pytest.raises(ValidationError):
+ MemoryFeatures.model_validate({"graph_rerank": True, "local_rerank": True})
+ with pytest.raises(ValidationError):
+ MemoryFeatures.model_validate({"graph_rerank": "true"})
+ with pytest.raises(ValidationError):
+ MemoryFeatures.model_validate({"graph_rerank": 1})
+ with pytest.raises(ValueError, match="unknown_memory_feature"):
+ hy_sdk_runtime.build_sdk_config(
+ PROFILES[0], api_key=None, data_dir=Path("/tmp/unused"), features={"nope": True}
+ )
+
+
+def test_merge_sets_resets_and_leaves_absent_keys_alone() -> None:
+ saved = MemoryFeatures(graph_rerank=True, few_shot=True)
+ update = MemoryFeatures.model_validate({"few_shot": None, "episode_recall": True})
+ merged = saved.merged(update)
+ assert merged.overrides() == (("episode_recall", True), ("graph_rerank", True))
+ assert saved.merged(MemoryFeatures()) == saved
+
+
+def test_the_setting_persists_and_an_untouched_install_writes_none(tmp_path) -> None:
+ store = ConfigStore(tmp_path)
+ store.set_sync("cursor", True)
+ assert "memory_features" not in json.loads((tmp_path / "config.json").read_text())
+ store.set_memory_features(MemoryFeatures(graph_rerank=True, intention=False))
+ saved = json.loads((tmp_path / "config.json").read_text())
+ # Only what a person set; an absent key is the SDK default.
+ assert saved["memory_features"] == {"graph_rerank": True, "intention": False}
+ assert ConfigStore(tmp_path).memory_features().overrides() == (
+ ("graph_rerank", True),
+ ("intention", False),
+ )
+ (tmp_path / "config.json").write_text(json.dumps({"memory_features": {"bogus": True}}))
+ with pytest.raises(Exception, match="config_invalid"):
+ ConfigStore(tmp_path)
+
+
+# --- how settings reach the SDK ----------------------------------------------
+
+
[email protected]("profile", PROFILES, ids=("builtin", "remote"))
+def test_each_feature_reaches_the_built_memory_config(tmp_path, profile) -> None:
+ for spec in FEATURES:
+ flipped = not TODAY[spec.name]
+ config = _config(tmp_path, profile, {spec.name: flipped})
+ assert _field(config, spec.name) is flipped, spec.name
+ for other in FEATURES:
+ if other.name != spec.name:
+ assert _field(config, other.name) is TODAY[other.name], (spec.name, other.name)
+
+
[email protected]("profile", PROFILES, ids=("builtin", "remote"))
+def test_nothing_set_is_the_config_of_before_byte_for_byte(tmp_path, profile) -> None:
+ before = repr(dataclasses.asdict(_config(tmp_path, profile)))
+ assert repr(dataclasses.asdict(_config(tmp_path, profile, ()))) == before
+ assert repr(dataclasses.asdict(_config(tmp_path, profile, {}))) == before
+ # Setting every feature to its default value changes nothing either.
+ assert repr(dataclasses.asdict(_config(tmp_path, profile, TODAY))) == before
+
+
[email protected]("profile", PROFILES, ids=("builtin", "remote"))
+def test_features_never_change_the_collection_identity(tmp_path, profile) -> None:
+ def identity(config):
+ return (
+ dataclasses.asdict(config.vector_store),
+ config.embedder.model,
+ config.embedder.embedding_dims,
+ config.graph_store.db_path,
+ config.cache.db_path,
+ )
+
+ baseline = identity(_config(tmp_path, profile))
+ for values in (
+ {name: True for name in FEATURE_NAMES},
+ {name: False for name in FEATURE_NAMES},
+ {"graph_rerank": True, "episode_recall": True},
+ ):
+ assert identity(_config(tmp_path, profile, values)) == baseline
+
+
+def test_acquire_client_builds_the_client_with_the_features(tmp_path, monkeypatch) -> None:
+ built: list[tuple[str, bool, bool]] = []
+
+ class Client:
+ def __init__(self, *, config, mode, runtime, embedding_service):
+ built.append(
+ (
+ mode,
+ config.graph_store.graph_rerank_enabled,
+ config.recall.episode_recall_enabled,
+ )
+ )
+
+ def close(self):
+ return None
+
+ monkeypatch.setattr(hy_sdk_runtime, "HyMemoryClient", Client)
+ monkeypatch.setattr(hy_sdk_runtime, "_acquire_runtime", lambda config, key: object())
+ monkeypatch.setattr(hy_sdk_runtime, "_release_runtime", lambda key: None)
+ monkeypatch.setattr(hy_sdk_runtime, "inspect_graph_width_mismatch", lambda config: None)
+ profile = hy_sdk_runtime.builtin_retrieval_snapshot()
+ hy_sdk_runtime.acquire_client(profile, api_key=None, data_dir=tmp_path, mode="pro").close()
+ hy_sdk_runtime.acquire_client(
+ profile,
+ api_key=None,
+ data_dir=tmp_path,
+ mode="ultra",
+ features=(("episode_recall", True), ("graph_rerank", True)),
+ ).close()
+ assert built == [("pro", False, False), ("ultra", True, True)]
+
+
+# --- active in the current mode ---------------------------------------------
+
+
+def test_a_feature_needing_a_higher_mode_is_reported_inactive() -> None:
+ on = effective_features((("graph_rerank", True), ("episode_recall", True)), TODAY)
+ assert feature_activity("graph_rerank", on, "pro") == "requires_ultra"
+ assert feature_activity("graph_rerank", on, "ultra") is None
+ # Usage B needs no graph: it acts in pro, not in lite (nothing extracted).
+ assert feature_activity("episode_recall", on, "pro") is None
+ assert feature_activity("episode_recall", on, "lite") == "requires_pro"
+ assert feature_activity("intention", TODAY, "lite") == "requires_pro"
+ assert feature_activity("few_shot", TODAY, "ultra") == "disabled"
+ series = effective_features((("same_series_timeline", True),), TODAY)
+ assert feature_activity("same_series_timeline", series, "ultra") == "requires_graph_rerank"
+ series = effective_features((("same_series_timeline", True), ("graph_rerank", True)), TODAY)
+ assert feature_activity("same_series_timeline", series, "pro") == "requires_ultra"
+ assert feature_activity("same_series_timeline", series, "ultra") is None
+
+
+# --- rebuilding handles -------------------------------------------------------
+
+
+class _FakeHandle:
+ def __init__(self, mode: str, features=(), profile_id: str = "p") -> None:
+ self.mode = mode
+ self.features = features
+ self.profile_id = profile_id
+ self.closed = False
+
+ async def client(self):
+ return self
+
+ async def close(self):
+ self.closed = True
+
+
+def test_the_read_handle_rebuilds_its_client_when_the_features_change(
+ monkeypatch, tmp_path
+) -> None:
+ """Reads follow the active profile (#255), the mode and the features."""
+ from one_memory import sdk_read_handle
+
+ features = [()]
+ made: list[_FakeHandle] = []
+
+ def handle_for(profile, *, api_key, data_dir, mode=None, features=()):
+ handle = _FakeHandle(mode or "pro", features, profile.profile_id)
+ made.append(handle)
+ return handle
+
+ monkeypatch.setattr(sdk_read_handle, "SdkClientHandle", handle_for)
+
+ class _NoProfile:
+ def active_identity(self):
+ return None
+
+ reads = sdk_read_handle.ActiveProfileReadHandle(
+ profiles=_NoProfile(), # type: ignore[arg-type]
+ secrets=None, # type: ignore[arg-type]
+ data_dir=tmp_path,
+ memory_mode=lambda: "pro",
+ features=lambda: features[0],
+ )
+ hold = asyncio.Event()
+ holding = asyncio.Event()
+
+ async def read():
+ return await reads.client()
+
+ async def slow_read():
+ client = await reads.client()
+ holding.set()
+ await hold.wait()
+ return client
+
+ async def scenario():
+ in_flight = asyncio.create_task(slow_read())
+ await asyncio.wait_for(holding.wait(), 5)
+ old = made[0]
+ assert (await asyncio.create_task(read())) is old
+ features[0] = (("episode_recall", True),)
+ try:
+ fresh = await asyncio.create_task(read())
+ assert fresh.features == (("episode_recall", True),) and fresh.mode == "pro"
+ # A read that took the old client is still using it.
+ assert not old.closed
+ finally:
+ hold.set()
+ await in_flight
+ for _ in range(10):
+ await asyncio.sleep(0)
+ assert old.closed and not fresh.closed
+ await reads.close()
+ assert fresh.closed
+
+ asyncio.run(scenario())
+
+
+class _Profiles:
+ def active_identity(self):
+ return ("profile-a", 1)
+
+ def snapshot(self, profile_id, revision):
+ return SimpleNamespace(profile_id=profile_id, has_api_key=False)
+
+ def resolve_snapshot_secret(self, profile_id, revision, secrets):
+ return None
+
+
+def test_a_feature_change_keeps_a_busy_write_handle_until_its_write_ends(monkeypatch) -> None:
+ features = [()]
+ opened: list[_FakeHandle] = []
+
+ def handle(profile, **kwargs):
+ value = _FakeHandle(kwargs["mode"], kwargs["features"], profile.profile_id)
+ opened.append(value)
+ return value
+
+ monkeypatch.setattr(sdk_write_processor, "SdkClientHandle", handle)
+ coordinator = sdk_write_processor.SdkWriteCoordinator(
+ profiles=_Profiles(), # type: ignore[arg-type]
+ secrets=None, # type: ignore[arg-type]
+ data_dir=None,
+ transport_factory=lambda _profile: None,
+ sedimentation_enabled=lambda: True,
+ memory_mode=lambda: "pro",
+ memory_features=lambda: features[0],
+ )
+
+ async def scenario():
+ async with coordinator.use_client() as client:
+ assert client.features == ()
+ features[0] = (("few_shot", True),)
+ await coordinator.retire_stale_handles()
+ # In flight: it finishes with the features it started with (#218).
+ assert not opened[0].closed
+ assert opened[0].closed
+ async with coordinator.use_client() as client:
+ assert client.features == (("few_shot", True),)
+ features[0] = ()
+ await coordinator.retire_stale_handles()
+ assert opened[1].closed
+ await coordinator.close()
+
+ asyncio.run(scenario())
+
+
+# --- the HTTP surface -----------------------------------------------------------
+
+
+def application(tmp_path: Path):
+ settings = Settings(
+ data_dir=tmp_path / "data",
+ source_home=tmp_path,
+ api_token=SecretStr(TOKEN),
+ imports_enabled=False,
+ automatic_memory_processing=False,
+ live_sync_enabled=False,
+ )
+ return create_app(settings, secret_store=InMemorySecretStore())
+
+
+def run_app(tmp_path, monkeypatch, scenario) -> None:
+ async def main() -> None:
+ app = application(tmp_path)
+
+ @asynccontextmanager
+ async def write_client():
+ yield SimpleNamespace()
+
+ async with app.router.lifespan_context(app):
+ monkeypatch.setattr(app.state.sdk_write_coordinator, "use_client", write_client)
+ async with AsyncClient(
+ transport=ASGITransport(app=app),
+ base_url="http://test",
+ headers={"Authorization": f"Bearer {TOKEN}"},
+ ) as client:
+ await scenario(app, client)
+
+ asyncio.run(main())
+
+
+def _by_name(body) -> dict[str, dict]:
+ return {item["name"]: item for item in body["features"]}
+
+
+def test_features_api_get_put_reset_and_status(tmp_path, monkeypatch) -> None:
+ async def scenario(app, client):
+ current = (await client.get("/api/v1/settings/memory-features")).json()
+ assert current["mode"] == "pro" and current["non_default"] == {}
+ listed = _by_name(current)
+ assert list(listed) == list(FEATURE_NAMES)
+ assert {name: item["enabled"] for name, item in listed.items()} == TODAY
+ assert all(item["configured"] is None for item in listed.values())
+ rerank = listed["graph_rerank"]
+ assert rerank["default"] is False and rerank["active"] is False
+ assert rerank["reason"] == "disabled" and rerank["requires_mode"] == "ultra"
+ assert rerank["sdk_field"] == "graph_store.graph_rerank_enabled"
+ assert rerank["env"] == "MEMORY_GRAPH_RERANK_ENABLED"
+ assert listed["intention"]["active"] is True
+ assert listed["episode_summary"]["cost"] == "llm_call"
+ reads = app.state.sdk_client_handle
+ # The read handle is keyed by (profile, mode, features): what it
+ # builds next is what these return.
+ assert reads.current_features() == ()
+
+ changed = await client.put(
+ "/api/v1/settings/memory-features",
+ json={"graph_rerank": True, "episode_recall": True},
+ )
+ assert changed.status_code == 200, changed.text
+ body = changed.json()
+ assert body["changed"] == ["graph_rerank", "episode_recall"]
+ listed = _by_name(body)
+ # Enabled but the graph store is ultra only: reported, not hidden.
+ assert listed["graph_rerank"]["enabled"] is True
+ assert listed["graph_rerank"]["active"] is False
+ assert listed["graph_rerank"]["reason"] == "requires_ultra"
+ assert listed["episode_recall"]["active"] is True
+ assert body["non_default"] == {"graph_rerank": True, "episode_recall": True}
+ # The handles were rebuilt with the new features.
+ expected = (("episode_recall", True), ("graph_rerank", True))
+ assert app.state.sdk_write_coordinator.memory_features() == expected
+ assert reads.current_features() == expected
+ assert reads.memory_mode() == "pro"
+
+ processing = (await client.get("/api/v1/memory-processing")).json()
+ assert processing["pipeline"]["features"] == {
+ "graph_rerank": True,
+ "episode_recall": True,
+ }
+
+ await client.put("/api/v1/settings/memory-mode", json={"mode": "ultra"})
+ await app.state.memory_graph_backfill.wait()
+ ultra = _by_name((await client.get("/api/v1/settings/memory-features")).json())
+ assert ultra["graph_rerank"]["active"] is True
+ assert ultra["graph_rerank"]["reason"] is None
+
+ again = (
+ await client.put("/api/v1/settings/memory-features", json={"graph_rerank": True})
+ ).json()
+ assert again["changed"] == []
+ assert reads.current_features() == expected
+
+ reset = (
+ await client.put(
+ "/api/v1/settings/memory-features",
+ json={"graph_rerank": None, "episode_recall": None},
+ )
+ ).json()
+ assert reset["changed"] == ["graph_rerank", "episode_recall"]
+ assert reset["non_default"] == {}
+ assert reads.current_features() == ()
+ saved = json.loads((tmp_path / "data" / "config.json").read_text())
+ assert saved["memory_features"] == {}
+
+ for bad in (
+ {"local_rerank": True},
+ {"graph_rerank": "true"},
+ {"graph_rerank": 1},
+ {"features": {"graph_rerank": True}},
+ ):
+ response = await client.put("/api/v1/settings/memory-features", json=bad)
+ assert response.status_code == 422, bad
+ assert (
+ await client.get("/api/v1/settings/memory-features", params={"user_id": "x"})
+ ).status_code == 422
+ assert (await client.get("/api/v1/settings/memory-features")).json()["non_default"] == {}
+
+ run_app(tmp_path, monkeypatch, scenario)
diff --git a/memhub/apps/core/tests/test_memory_mode_and_evolve.py b/memhub/apps/core/tests/test_memory_mode_and_evolve.py
index b84c102..30a2ecd 100644
--- a/memhub/apps/core/tests/test_memory_mode_and_evolve.py
+++ b/memhub/apps/core/tests/test_memory_mode_and_evolve.py
@@ -108,7 +108,7 @@ def test_the_read_handle_rebuilds_on_a_mode_or_profile_change(monkeypatch, tmp_p
modes = ["pro"]
made: list[_FakeHandle] = []
- def handle_for(profile, *, api_key, data_dir, mode=None):
+ def handle_for(profile, *, api_key, data_dir, mode=None, features=()):
handle = _FakeHandle(mode or "pro", profile.profile_id)
made.append(handle)
return handle
diff --git a/memhub/apps/core/tests/test_search_without_profile.py b/memhub/apps/core/tests/test_search_without_profile.py
index ae45adc..c713e59 100644
--- a/memhub/apps/core/tests/test_search_without_profile.py
+++ b/memhub/apps/core/tests/test_search_without_profile.py
@@ -140,7 +140,9 @@ class _Recorder:
self.opened: list[tuple[str, int | None, str | None]] = []
self.closed: list[str] = []
- def __call__(self, profile, *, api_key, data_dir, http_transport_factory=None, mode="pro"):
+ def __call__(
+ self, profile, *, api_key, data_dir, http_transport_factory=None, mode="pro", features=()
+ ):
from one_memory.hy_sdk_runtime import build_sdk_config
config = build_sdk_config(profile, api_key=api_key, data_dir=data_dir)
diff --git a/memhub/docs/ARCHITECTURE.md b/memhub/docs/ARCHITECTURE.md
index a514655..40a68b9 100644
--- a/memhub/docs/ARCHITECTURE.md
+++ b/memhub/docs/ARCHITECTURE.md
@@ -130,7 +130,7 @@ This exception does not extend to VDB, Coding, prompt, reconcile, or lifecycle.
- Storage backends:仅 SDK config/env(Chroma/FAISS/Qdrant、Kuzu/Neo4j、cache/history sqlite|mysql、coding sqlite 等)。
- Queue:pending `memory_write_jobs` 只表示尚未调用 SDK 的待处理请求,因此没有 SDK raw/memory ID。worker 单次调用 SDK `add()`;SDK 内部完成 raw 写入与 extraction/reconciliation,成功后 MemHub 仅将返回的 raw ID / memory IDs 记作 job outcome。
-- Raw retention:MemHub 不删除任何 SDK L1 raw,任何模式都全部保留(SDK 自身也不删 raw);每个完整 turn 只保存真人 user 与 assistant,tool 不进入 raw。记忆模式(lite / pro / ultra)与 evolve 见 `docs/contracts/memory-mode-evolve-v1.md`。
+- Raw retention:MemHub 不删除任何 SDK L1 raw,任何模式都全部保留(SDK 自身也不删 raw);每个完整 turn 只保存真人 user 与 assistant,tool 不进入 raw。记忆模式(lite / pro / ultra)与 evolve 见 `docs/contracts/memory-mode-evolve-v1.md`;SDK 可选检索与提取功能(graph rerank、episode recall 等,全局设置,默认保持 SDK 默认值)见 `docs/contracts/memory-features-v1.md`。
- Recall:Host Bridge / Core 先做宿主安装凭据与 tool grant,再调 **SDK search/get**。当前产品没有逐 memory 的 A-harness→B-harness 可见性开关,默认允许跨 harness 搜索;未来若增加来源限制,直接透传 SDK `source` / `include_sources` / `exclude_sources`,不在 MemHub 建 memory ACL。
- Context wire:cutover marker 提交前只使用 legacy Context v1;提交后 Host Bridge 只使用 SDK-native Context v2。两种 schema 原样校验、原样返回,不把 SDK item 补造成 v1 的 `revision`、`evidence_ids`、`paths` 或 `adoption`,已选择的 v2 路径失败时也不回退 legacy 权威。
- Ask wire:marker 前保留 Governance Ask v1;marker 后 Web / Host Bridge 只调用 SDK Ask v2。v2 的引用只含 SDK 原生 `memory_id/content/layer/status/source/gmt_created`,生成过程中重复 `get` 校验同一 SDK 快照,不补造 revision、Evidence 或 scopes,SDK 失败不回退 v1。
diff --git a/memhub/docs/cli/EXPERIENCE.md b/memhub/docs/cli/EXPERIENCE.md
index b57bd7f..b7cb08a 100644
--- a/memhub/docs/cli/EXPERIENCE.md
+++ b/memhub/docs/cli/EXPERIENCE.md
@@ -166,6 +166,24 @@ node apps/cli/dist/one-memory.cjs evolve --user-id wife --wait # 立即进化
- `status --json` 与 `progress --json` 输出 `pipeline.mode`、每晚进化时间和每个用户的上次进化。
- 契约见 `docs/contracts/memory-mode-evolve-v1.md`。
+### SDK 可选功能(`settings features`)
+
+```bash
+node apps/cli/dist/one-memory.cjs settings features # 列出全部功能、默认值、当前模式下是否生效
+node apps/cli/dist/one-memory.cjs settings features set episode_recall=true session_episodes=true # 只显示计划
+node apps/cli/dist/one-memory.cjs settings features set episode_recall=true session_episodes=true --yes # 生效
+node apps/cli/dist/one-memory.cjs settings features reset episode_recall # 恢复默认
+node apps/cli/dist/one-memory.cjs settings features reset # 全部恢复默认
+```
+
+- 全局设置,不分用户;没设置的功能保持 SDK 默认值,什么都不设时与以前完全一样(App 不变)。
+- 可设:`graph_rerank`(图谱重排,仅 ultra)、`same_series_timeline`(需 graph_rerank)、`episode_recall`(片段召回,pro 即可)、`session_episodes`(片段写入)、`episode_summary`(片段摘要,每个片段一次模型调用)、`intention`(默认开)、`few_shot`。
+- 片段召回只对带片段的记忆有用:同时开 `session_episodes`,之后提取的记忆才按会话归入片段。
+- 在当前模式下不生效的功能照样保存,并注明原因(如 `graph_rerank` 在 pro 下「需要 ultra」)。
+- 修改会重建 SDK 客户端:正在写的一批按旧设置写完,之后的写入和检索用新设置;不迁移数据,不改集合名。
+- `status --json` / `progress --json` 的 `pipeline.features` 列出与默认值不同的功能。
+- 契约见 `docs/contracts/memory-features-v1.md`。
+
## 8. 召回(recall)
`recall` 两条路径(raw / memory)此前已真机验证。文本输出会标明每条是「原始对话摘录」
diff --git a/memhub/docs/contracts/memory-features-v1.md b/memhub/docs/contracts/memory-features-v1.md
new file mode 100644
index 0000000..4add86e
--- /dev/null
+++ b/memhub/docs/contracts/memory-features-v1.md
@@ -0,0 +1,226 @@
+# SDK retrieval and extraction features v1
+
+Status: Core + CLI implemented. Stacks on the memory-mode contract
+(`memory-mode-evolve-v1.md`). The App keeps today's behaviour and has no
+control for this yet; the copy in section 9 is there if it adds one.
+
+MemHub hard-codes none of the SDK's optional features. A person can turn the
+ones below on or off through the CLI or the API. Nobody has to: an unset
+feature keeps the SDK default, and with nothing set the SDK config is byte for
+byte what MemHub built before this setting existed.
+
+All routes need the Runtime bearer token. Unknown query parameters and body
+fields answer `422 {"detail": "request_validation_failed"}`, like every other
+settings route. The setting is global, like the memory mode: it applies to
+every user's SDK client and takes no `user_id`.
+
+## 1. Inventory
+
+These are the hy-memory flags (`hy_memory/config.py` and the modules that read
+the environment directly) that change retrieval or extraction quality. Cost:
+"none" means no extra call; "query" means one more local store query per
+search; "LLM" means extra generation-model calls; "tokens" means a longer
+prompt and no extra call.
+
+### Exposed
+
+| Name | SDK field (env) | Default | Mode | Cost |
+|---|---|---|---|---|
+| `graph_rerank` | `graph_store.graph_rerank_enabled` (`MEMORY_GRAPH_RERANK_ENABLED`) | off | ultra (graph store) | query (graph edges) |
+| `same_series_timeline` | `recall.same_series_timeline_enabled` (`MEMORY_SAME_SERIES_TIMELINE_ENABLED`) | off | ultra + `graph_rerank` | none |
+| `episode_recall` | `recall.episode_recall_enabled` (`MEMORY_EPISODE_RECALL_ENABLED`) | off | pro or ultra; no graph | query (episode members) |
+| `session_episodes` | `recall.session_episode_enabled` (`MEMORY_SESSION_EPISODE_ENABLED`) | off | pro or ultra | none |
+| `episode_summary` | `recall.episode_summary_enabled` (`MEMORY_EPISODE_SUMMARY_ENABLED`) | off | pro or ultra | LLM: one call per closed episode of 3+ memories |
+| `intention` | `llm.enable_intention` (`MEMORY_ENABLE_INTENTION`) | **on** | pro or ultra | none (off shortens the prompt) |
+| `few_shot` | `llm.few_shot_enabled` (`MEMORY_FEW_SHOT_ENABLED`) | off | pro or ultra | tokens (extraction and reconcile) |
+
+- **Graph rerank (usage A).** It propagates support over the graph edges
+ inside the recall pool (`reader_base._apply_graph_rerank`). It needs a graph
+ store, which MemHub opens only in ultra. In pro and lite it is reported
+ `active: false, reason: "requires_ultra"`.
+- **Episode recall (usage B).** It adds memories from the same episode as a
+ hit and scores them on three channels: tag-keyword overlap, content overlap
+ and temporal affinity. It needs no graph, so it works in pro (issue #121).
+ It helps only memories that carry an `episode_id`.
+ - Memories that System 1 adds through reconcile get an idle-gap
+ `episode_id` whenever the SDK cache is available, which MemHub's SQLite
+ cache is. A new episode starts after 30 minutes idle or 50 memories.
+ - `session_episodes` replaces that with one stable episode per conversation.
+ - Memories stored before the change keep the id they had.
+ - Raw turns from lite, and notes written before episodes existed, carry none.
+- **Episode write side.** `session_episodes` and `episode_summary` are the
+ write half of episodes, and both are off by default. Usage B only helps once
+ episodes are being written. The SDK's session narrative (L3, `finalize_session`)
+ is a separate feature and is not exposed (section 2).
+- **`intention`** is the only feature that is on by default. Turning it off
+ stops L7 intention memories from being extracted.
+
+### Left out, and why
+
+| Flag(s) | Why it is not exposed |
+|---|---|
+| `recall.entity_store_enabled` (`MEMORY_ENTITY_STORE_ENABLED`) | Entity extraction needs spaCy and `en_core_web_sm`, which MemHub does not ship, so it would silently do nothing. It also writes a new `{collection}_entities` collection, and MemHub's collection identity has to stay fixed. |
+| `llm.enable_query_rewrite` (`MEMORY_ENABLE_QUERY_REWRITE`) | It only affects default-mode searches that pass `queries=[...]`, and MemHub never sends that. Per-request rewrite already exists as `search_mode: "agentic"` (#252). |
+| `session_episode_context_enabled`, `dynamic_episode_enabled`, `series_episode_enabled`, `episode_capsule_context_enabled`, `episode_member_expansion_enabled` | They read or write the L3 session narrative that `finalize_session` builds, and MemHub never calls it. When dynamic or series finalize fails, the SDK fails the write with a non-retryable 409 partial result, which would leave MemHub jobs `unknown`. |
+| `local_rerank_enabled` (+ model / device) | It downloads a cross-encoder model on first use. That is a network fetch MemHub's packaged, offline runtime and zero-collection rules do not allow. |
+| `strength_enabled`, `access_tracking_enabled` | They write access counts back to memory rows on every search: a read that mutates. Internal. |
+| `structure_metadata_enabled`, `retrieval_clauses_*`, `supplemental_propositions_enabled`, `hierarchy_bundle_*`, `multi_seed_bundle_*`, `tag_index_nominee_*`, `dynamic_entity_tag_embed_enabled` | Experimental retrieval lanes, each with many tuning parameters. The SDK marks them as still under gray validation, and some depend on System 2 output. Internal tuning, not a person's choice. |
+| `graph_store.memory_graph_write`, `path_enabled` (default on) | Turning them off breaks graph rerank and evolve. Dangerous. |
+| `hierarchy_topic_write`, `temporal_spine`, `topic_summary_enabled` | Experimental graph write lanes ("stage 5"); topic summary also costs LLM calls. Not validated for users. |
+| Schema lane and catalog / supplement (`MEMORY_EVOLING_SCHEMA_DEDUP_ENABLED`, `MEMORY_EVOLING_SCHEMA_COMPACTION_ENABLED`, `MEMORY_EVOLING_BALANCED_CATALOG_ENABLED`, `MEMORY_EVOLING_SPECIFIC_SUPPLEMENT_ENABLED`, `MEMORY_USER_PROFILE_*`, `MEMORY_HYBRID_V2_*_L0_ENABLED`) | The SDK reads them from `os.environ`, not from `MemoryConfig`. Some are read once at import (`system2_tools`), others on each call for the whole process. They cannot be scoped to one client, and setting them in Core's environment would need a restart and would leak into every client. Section 3. |
+| The hybrid reader's env knobs (`MEMORY_HYBRID_V2_*`, `MEMORY_TOPIC_*_ENABLED`, `MEMORY_*_BUNDLE_ENABLED`, `MEMORY_RERANK_*`) | Same reason: read from the process environment on each search. |
+| `RECONCILE_ENABLED`, `SWEEPER_ENABLED`, `MEMORY_CROSS_DOMAIN_ENABLE` | Read at import time. Turning reconcile off stores every extraction without dedup. Dangerous. |
+| `coding.chain_block_enabled`, `coding.verbatim_fallback_enabled` | Coding-scene options. The verbatim fallback stores assistant and tool traces as facts. |
+| `MEMORY_ENABLE_GRAPH` (graph in pro) | That is the memory mode's job (`settings mode`). |
+| `MEMORY_LOG_LLM_CONTENT`, pipeline log, trace, memory operations, metrics / telemetry | Diagnostics. MemHub controls them elsewhere (`diagnostic-logging.md`). |
+
+## 2. The setting
+
+`config.json` gains an optional `memory_features` object next to
+`memory_mode`. It is written only once a person sets a feature, and then it
+holds only the features they set:
+
+```json
+{"memory_mode": "pro", "memory_features": {"episode_recall": true, "session_episodes": true}}
+```
+
+The values are strict booleans and unknown keys are refused, so a hand-edited
+file with an unknown feature fails to load (`config_invalid`), like any other
+malformed setting.
+
+## 3. How a setting reaches the SDK
+
+- Every exposed feature is a `MemoryConfig` field that the SDK reads from the
+ config object when it is called. None of them is read from `os.environ` at
+ call time.
+- `hy_sdk_runtime.build_sdk_config(..., features=...)` sets those fields on
+ each client's config after `MemoryConfig.from_dict`. The result is
+ deterministic per client.
+- The SDK's own env vars (the second column of the table) still decide the
+ default of a feature nobody set. That is exactly what happened before the
+ setting existed. A setting always wins over the env var.
+- MemHub writes no env var. The flags the SDK reads straight from the
+ environment are the ones left out above.
+- Each client's features are fixed when it is built, like its mode. Both the
+ write handles (`SdkWriteCoordinator`) and the read handle
+ (`ActiveProfileReadHandle`) are keyed by (profile, revision, mode,
+ features).
+- A change runs `retire_stale_handles`, the #218 use count. An idle write
+ handle closes at once, and a write in flight finishes with the features it
+ started with. The next read builds a client with the new key. The old read
+ client closes once no request still uses it.
+- Nothing stored is migrated. A feature never touches `vector_store`, the
+ embedder or any store path, so the collection identity is the same with any
+ features (tested).
+
+## 4. `GET /api/v1/settings/memory-features`
+
+```json
+{
+ "mode": "pro",
+ "features": [
+ {
+ "name": "graph_rerank",
+ "enabled": true,
+ "configured": true,
+ "default": false,
+ "active": false,
+ "reason": "requires_ultra",
+ "side": "read",
+ "requires_mode": "ultra",
+ "requires_feature": null,
+ "cost": "extra_query",
+ "sdk_field": "graph_store.graph_rerank_enabled",
+ "env": "MEMORY_GRAPH_RERANK_ENABLED",
+ "description": "Usage A: propagate support over knowledge-graph edges ..."
+ }
+ ],
+ "non_default": {"graph_rerank": true}
+}
+```
+
+- `enabled` is what clients are built with: `configured` if set, else `default`.
+- `configured` is null when unset.
+- `default` is the SDK default: its code default, or its own env var when set.
+- `active` is false with a `reason` when the feature does nothing right now.
+ The reason is one of `disabled`, `requires_pro` (lite), `requires_ultra`, or
+ `requires_graph_rerank` (for `same_series_timeline`).
+- `cost` is one of `none`, `extra_query`, `llm_call`, `prompt_tokens`.
+- `features` always lists every feature, in the table's order.
+
+## 5. `PUT /api/v1/settings/memory-features`
+
+The body has any of the feature names as keys:
+
+- `true` or `false` sets that feature.
+- `null` resets it to the default.
+- An absent key is left as it is.
+- Anything else answers `422`, including a non-boolean, `"true"`, `1`, or an
+ unknown name.
+
+```json
+{"graph_rerank": true, "episode_recall": true, "few_shot": null}
+```
+
+The answer is the state of section 4, plus `changed`: the features whose
+effective value changed, in the table's order. When the set of configured
+features changes, the SDK clients are rebuilt (section 3). That includes a
+reset to a value equal to the default, after which the client carries no
+override at all.
+
+## 6. Status
+
+`pipeline` in `GET /api/v1/memory-processing` (memory-mode contract §7) gains
+`features`, which lists the features whose effective value differs from the
+default. It is `{}` while every feature is at its default:
+
+```json
+{"pipeline": {"mode": "pro", "...": "...", "features": {"episode_recall": true, "intention": false}}}
+```
+
+`memhub status --json` and `memhub progress --json` carry it as
+`pipeline.features`. The text status appends `;SDK 功能:episode_recall=开、…`
+to the memory-mode line.
+
+## 7. CLI
+
+```bash
+memhub settings features # list them
+memhub settings features set episode_recall=true session_episodes=true # plan only
+memhub settings features set episode_recall=true session_episodes=true --yes
+memhub settings features reset few_shot # back to the default
+memhub settings features reset # every set feature
+```
+
+`set` prints its plan and needs `--yes`, like `settings mode`, because some
+features spend model calls. `reset` only returns features to their defaults,
+so it applies at once. Unknown names or values other than `true` / `false` are
+a usage error (exit 2) before the Runtime is asked.
+
+## 8. Rules kept
+
+- Global management, as for the mode: no `user_id`; reads stay scoped per
+ user as before.
+- Strict parameters: unknown body fields and query parameters answer 422.
+- The mode semantics of #253 are unchanged. A feature needing a higher mode is
+ stored and reported inactive; it is not refused.
+
+## 9. Copy the UI can reuse
+
+| Key | zh-CN | en | es |
+|---|---|---|---|
+| title | 高级检索与提取 | Advanced retrieval and extraction | Recuperación y extracción avanzadas |
+| graph_rerank | 图谱重排:沿知识图谱的关联提升相关记忆的排名(仅 ultra)。 | Graph rerank: ranks memories higher when the knowledge graph links them to strong matches (ultra only). | Reordenación por grafo: sube en la lista las memorias que el grafo de conocimiento relaciona con buenas coincidencias (solo ultra). |
+| same_series_timeline | 同系列时间线:同一系列的记忆按时间放在一起(需图谱重排)。 | Same-series timeline: keeps memories of one series together in time order (needs graph rerank). | Línea temporal de la serie: mantiene juntas y en orden temporal las memorias de una misma serie (requiere la reordenación por grafo). |
+| episode_recall | 片段召回:补入与命中记忆同一片段的记忆,并按标签、内容和时间打分。 | Episode recall: adds memories from the same episode as a match and scores them by tags, content and time. | Recuperación por episodio: añade memorias del mismo episodio que una coincidencia y las puntúa por etiquetas, contenido y tiempo. |
+| session_episodes | 片段写入:同一会话中提取的记忆归入同一片段。 | Episodes per conversation: memories extracted from one conversation share one episode. | Episodios por conversación: las memorias extraídas de una conversación comparten un episodio. |
+| episode_summary | 片段摘要:片段结束时总结一次(每个片段一次模型调用)。 | Episode summaries: each finished episode is summarized once (one model call per episode). | Resúmenes de episodio: cada episodio terminado se resume una vez (una llamada al modelo por episodio). |
+| intention | 意图提取:随事实一起记住你提到的计划和意图。 | Intentions: remembers the plans and intentions you mention, along with facts. | Intenciones: recuerda los planes e intenciones que mencionas, junto con los hechos. |
+| few_shot | 提取示例:在提取提示中加入示例,可帮助较弱的模型(输入更长)。 | Extraction examples: adds examples to the extraction prompt, which can help a weaker model (longer input). | Ejemplos de extracción: añade ejemplos a la instrucción de extracción, lo que puede ayudar a un modelo más débil (entrada más larga). |
+| default | 默认 | Default | Predeterminado |
+| requires_ultra | 当前模式下不生效,需要 ultra。 | Has no effect in this mode; needs ultra. | No tiene efecto en este modo; requiere ultra. |
+| requires_pro | lite 模式下不生效。 | Has no effect in lite. | No tiene efecto en lite. |
+| requires_graph_rerank | 需要先开启图谱重排。 | Turn on graph rerank first. | Activa primero la reordenación por grafo. |
+| episodes_hint | 片段召回只对带片段的记忆有用;开启片段写入后,新提取的记忆才会按会话归入片段。 | Episode recall only helps memories that belong to an episode; with episodes per conversation on, new memories are grouped by conversation. | La recuperación por episodio solo ayuda a las memorias que pertenecen a un episodio; con los episodios por conversación activados, las memorias nuevas se agrupan por conversación. |
+| cost_llm | 会增加模型调用 | Uses extra model calls | Usa llamadas adicionales al modelo |
+| applied | 正在进行的写入按原设置完成,之后的写入和检索使用新设置。 | A write in progress finishes with the old settings; later writes and searches use the new ones. | Una escritura en curso termina con la configuración anterior; las siguientes escrituras y búsquedas usan la nueva. |
diff --git a/memhub/docs/contracts/memory-mode-evolve-v1.md b/memhub/docs/contracts/memory-mode-evolve-v1.md
index 5e09d3e..e8113b4 100644
--- a/memhub/docs/contracts/memory-mode-evolve-v1.md
+++ b/memhub/docs/contracts/memory-mode-evolve-v1.md
@@ -285,11 +285,15 @@ A user is kept when `memory_stats` reports any memory or fact for them.
"forced_by_env": false,
"evolve": {"...": "the overview of section 5"},
"last_evolve_at": "2026-11-01T03:00:00Z",
- "graph_build": {"...": "as in section 3"}
+ "graph_build": {"...": "as in section 3"},
+ "features": {}
}
}
```
+`features` lists the SDK features whose value differs from the default (empty
+while every feature is at its default); see `memory-features-v1.md`.
+
`memhub status --json` adds a top-level projection of it:
```json
@@ -304,7 +308,8 @@ A user is kept when `memory_stats` reports any memory or fact for them.
"evolve_users": {
"local": {"last_run_at": "...", "last_error": null, "state": "succeeded"}
},
- "graph_build": "succeeded"
+ "graph_build": "succeeded",
+ "features": {}
}
}
```
@@ -319,8 +324,14 @@ memhub settings mode # show the current mode
memhub settings mode lite # print the plan, change nothing
memhub settings mode lite --yes # switch
memhub evolve [--user-id <id>] [--agent-id <id>] [--max-batches <n>] [--wait] [--json]
+memhub settings features [set <name>=<true|false> ... [--yes] | reset [<name> ...]]
```
+The SDK's optional retrieval and extraction features (graph rerank, episode
+recall, the episode write side, …) are a second global setting beside the
+mode. A change rebuilds the SDK handles the same way. Contract:
+`memory-features-v1.md`.
+
## 9. Copy the UI can reuse
| Key | zh-CN | en | es |