Skip to content
Python

feat(memhub-cli): --user-id for memory commands, connect a Hermes profile

alvinfei0ff4538f3646
diff --git a/memhub/apps/cli/src/cli.ts b/memhub/apps/cli/src/cli.ts
index 39db94c..54ec50f 100644
--- a/memhub/apps/cli/src/cli.ts
+++ b/memhub/apps/cli/src/cli.ts
@@ -190,8 +190,10 @@ import {
} from "./managed-cli-link.js";
import {
addMemory,
+ DEFAULT_USER_ID,
isMemoryId,
isRequestId,
+ isUserId,
MEMORY_KINDS,
MEMORY_SCENES,
MEMORY_VARIANTS,
@@ -209,6 +211,7 @@ import {
renderMemoryAddText,
renderMemoryDetailText,
renderMemoryPageText,
+ userIdParameters,
validMemoryText,
} from "./memory-report.js";
import {
@@ -538,6 +541,23 @@ async function runCommand(
environment = { ...environment, ONE_MEMORY_DATA_DIR: lifted.dataDir };
}
}
+ // `--user-id <id>` is global to the memory commands: it names whose
+ // memories are read or written. It is lifted before dispatch so each
+ // command's own parser keeps seeing exactly the arguments it always did.
+ // `sources connect` gives the flag its own meaning and parses it itself.
+ let userId: string | undefined;
+ if (USER_ID_COMMANDS.has(arguments_[0] ?? "")) {
+ const lifted = liftUserIdOption(arguments_);
+ if (lifted === null) {
+ return reject(
+ findCommand(arguments_[0] ?? ""),
+ asJson,
+ "--user-id 无效:只能是 1–64 位字母、数字、点、下划线或连字符。",
+ );
+ }
+ arguments_ = lifted.arguments_;
+ userId = lifted.userId;
+ }
environment = await environmentWithManagedDataDir(environment);
const command = arguments_[0];
if (command === undefined) return reject(undefined, asJson, "缺少命令。");
@@ -776,9 +796,11 @@ async function runCommand(
const attachment = await attachToRuntimeOrNull(environment);
if (attachment === null) return runtimeUnavailable(descriptor, asJson);
if (parsed.kind === "status") {
- const receipt = await readMemoryWrite(attachment, parsed.id).catch(
- () => undefined,
- );
+ const receipt = await readMemoryWrite(
+ attachment,
+ parsed.id,
+ userId,
+ ).catch(() => undefined);
if (receipt === undefined) {
return emitFailure(asJson, "write status", "memory_write_read_failed");
}
@@ -812,6 +834,7 @@ async function runCommand(
? {}
: { memory_at: parsed.memory_at }),
...(parsed.priority === undefined ? {} : { priority: parsed.priority }),
+ ...(userId === undefined ? {} : { user_id: userId }),
});
if (outcome.state !== "accepted") {
emit(
@@ -1585,6 +1608,7 @@ async function runCommand(
limit: parsed.limit,
character_budget: parsed.characterBudget,
timeout_ms: parsed.timeoutMs,
+ ...userIdParameters(userId),
})
: ({
schema_version: 2,
@@ -1783,6 +1807,16 @@ async function runCommand(
}
if (named === "sources" && arguments_[1] !== "list") {
const parsed = parseSourcesCommand(arguments_.slice(1));
+ if (
+ !parsed &&
+ arguments_.some((item) => item === "--user-id" || item === "--root")
+ ) {
+ return reject(
+ descriptor,
+ asJson,
+ "--user-id 和 --root 只能用于接入单个 hermes 来源(Hermes profile),用户 ID 只能是 1–64 位字母、数字、点、下划线或连字符。",
+ );
+ }
if (!parsed) return usage();
if (parsed.kind === "receipt") {
const connected = await connectRuntime(environment);
@@ -2007,7 +2041,11 @@ async function runCommand(
);
return connected.exitCode;
}
- const outcome = await connected.reader<unknown>("/api/v2/user-profile");
+ const profileUser = userIdParameters(userId);
+ const outcome =
+ profileUser.user_id === undefined
+ ? await connected.reader<unknown>("/api/v2/user-profile")
+ : await connected.reader<unknown>("/api/v2/user-profile", profileUser);
const value =
outcome.state === "ok"
? (outcome.data as {
@@ -2112,7 +2150,7 @@ async function runCommand(
}
const { reader, operations } = connected;
if (parsed.kind === "list") {
- const document = await readMemoryPage(reader, parsed.query);
+ const document = await readMemoryPage(reader, parsed.query, userId);
emit(
asJson
? `${JSON.stringify(document)}\n`
@@ -2125,6 +2163,7 @@ async function runCommand(
reader,
parsed.memoryId,
parsed.namespace,
+ userId,
);
emit(
asJson
@@ -2136,8 +2175,8 @@ async function runCommand(
if (parsed.kind === "add" || parsed.kind === "add-status") {
const document =
parsed.kind === "add"
- ? await addMemory(operations, text ?? "", parsed.requestId)
- : await readMemoryAddStatus(reader, parsed.requestId);
+ ? await addMemory(operations, text ?? "", parsed.requestId, userId)
+ : await readMemoryAddStatus(reader, parsed.requestId, userId);
emit(
asJson
? `${JSON.stringify(document)}\n`
@@ -2152,9 +2191,13 @@ async function runCommand(
content: text,
...namespaceParameters(parsed.namespace),
...(parsed.task === undefined ? {} : { task: parsed.task }),
+ ...userIdParameters(userId),
})
: await operations.delete<unknown>(
- withQuery(memoryPath, namespaceParameters(parsed.namespace)),
+ withQuery(memoryPath, {
+ ...namespaceParameters(parsed.namespace),
+ ...userIdParameters(userId),
+ }),
);
const document = {
schema_version: 2,
@@ -3678,13 +3721,21 @@ async function connectSources(
asJson,
);
}
- if (parsed.importHistory) {
+ // Another user's Hermes profile is granted and imported in one connect
+ // request: only that request can carry a user and a root.
+ if (
+ parsed.importHistory ||
+ parsed.userId !== undefined ||
+ parsed.root !== undefined
+ ) {
const document = await connectSourcesWithImport(reader, operations, {
sourceIds: parsed.sourceIds,
confirmOverrides: parsed.confirmOverrides,
...(parsed.requestId === undefined
? {}
: { requestId: parsed.requestId }),
+ ...(parsed.userId === undefined ? {} : { userId: parsed.userId }),
+ ...(parsed.root === undefined ? {} : { root: parsed.root }),
});
emitFlowDocument(document, asJson);
return flowExitCode(document);
@@ -5134,14 +5185,23 @@ type SourcesCommand =
importHistory: boolean;
confirmOverrides: boolean;
requestId?: string;
+ /** `--user-id`: whose grant (Hermes only). Absent for `local`. */
+ userId?: string;
+ /** `--root`: an absolute root other than the candidate (Hermes only). */
+ root?: string;
}
| { kind: "all"; importHistory: boolean; confirmOverrides: boolean }
| { kind: "receipt"; requestId: string };
const SOURCE_ID_SHAPE = /^[a-z0-9][a-z0-9-]{0,127}$/;
+/** Only Hermes keeps one history per profile, so only Hermes may be
+ * connected for another user or from another root. */
+const MULTI_USER_SOURCES = new Set(["hermes"]);
+
/** `sources connect <id> [<id> ...] | --all-detected [--import]
- * [--confirm-overrides] [--request-id <uuid>]` and `sources receipt <id>`.
+ * [--confirm-overrides] [--request-id <uuid>]
+ * [--user-id <id>] [--root <path>]` and `sources receipt <id>`.
*
* Sources may be named positionally or with repeated `--source` (the old
* `init --source` spelling is rewritten to this command). */
@@ -5157,6 +5217,8 @@ function parseSourcesCommand(rest: readonly string[]): SourcesCommand | null {
const sourceIds: string[] = [];
const switches = new Set<string>();
let requestId: string | undefined;
+ let userId: string | undefined;
+ let root: string | undefined;
for (let index = 1; index < tokens.length; index += 1) {
const token = tokens[index];
if (["--import", "--confirm-overrides", "--all-detected"].includes(token)) {
@@ -5164,6 +5226,21 @@ function parseSourcesCommand(rest: readonly string[]): SourcesCommand | null {
switches.add(token);
continue;
}
+ if (token === "--user-id" || token === "--root") {
+ const value = tokens[index + 1];
+ if (value === undefined || value.startsWith("--")) return null;
+ if (token === "--user-id") {
+ if (userId !== undefined || !isUserId(value)) return null;
+ userId = value;
+ } else {
+ if (root !== undefined) return null;
+ const expanded = expandRootPath(value);
+ if (expanded === null) return null;
+ root = expanded;
+ }
+ index += 1;
+ continue;
+ }
if (token === "--source" || token === "--request-id") {
const value = tokens[index + 1];
if (value === undefined || value.startsWith("--")) return null;
@@ -5187,10 +5264,23 @@ function parseSourcesCommand(rest: readonly string[]): SourcesCommand | null {
const confirmOverrides = switches.has("--confirm-overrides");
if (
requestId !== undefined &&
- (!OPERATION_ID.test(requestId) || !importHistory)
+ (!OPERATION_ID.test(requestId) ||
+ !(importHistory || userId !== undefined || root !== undefined))
) {
return null;
}
+ // `--user-id local` is the default and changes nothing.
+ if (userId === DEFAULT_USER_ID) userId = undefined;
+ if (userId !== undefined || root !== undefined) {
+ // One Hermes profile per connect: the user and root name one grant.
+ if (
+ switches.has("--all-detected") ||
+ sourceIds.length !== 1 ||
+ !MULTI_USER_SOURCES.has(sourceIds[0])
+ ) {
+ return null;
+ }
+ }
if (switches.has("--all-detected")) {
// One names exact sources, the other means "whatever is detected".
if (sourceIds.length > 0 || requestId !== undefined) return null;
@@ -5203,9 +5293,24 @@ function parseSourcesCommand(rest: readonly string[]): SourcesCommand | null {
importHistory,
confirmOverrides,
...(requestId === undefined ? {} : { requestId }),
+ ...(userId === undefined ? {} : { userId }),
+ ...(root === undefined ? {} : { root }),
};
}
+/** `--root` as an absolute path: a leading `~` is the home directory, a
+ * relative path is taken from the working directory. Core expands nothing. */
+function expandRootPath(value: string): string | null {
+ if (value.length === 0 || /[\0\r\n]/.test(value)) return null;
+ const expanded =
+ value === "~"
+ ? os.homedir()
+ : value.startsWith("~/")
+ ? path.join(os.homedir(), value.slice(2))
+ : value;
+ return path.resolve(expanded);
+}
+
function parseGraphWidthCommand(
rest: readonly string[],
): { decision: GraphWidthDecision; confirmed: boolean } | null {
@@ -6599,6 +6704,30 @@ const OWN_DATA_DIR_COMMANDS = new Set([
/** Remove one `--data-dir <absolute path>` from argv; null when it is
* repeated, missing its value, or not an absolute path. */
+/** Memory commands that honour the global `--user-id`. */
+const USER_ID_COMMANDS = new Set(["memories", "recall", "profile", "write"]);
+
+/**
+ * Take `--user-id <id>` out of the arguments. The default user (`local`) is
+ * returned as undefined, so a default request names no user at all and stays
+ * byte-identical to one sent before multi-user support.
+ */
+function liftUserIdOption(
+ arguments_: readonly string[],
+): { arguments_: string[]; userId?: string } | null {
+ const index = arguments_.indexOf("--user-id");
+ if (index === -1) return { arguments_: [...arguments_] };
+ if (arguments_.indexOf("--user-id", index + 1) !== -1) return null;
+ const value = arguments_[index + 1];
+ if (value === undefined || value.startsWith("--") || !isUserId(value)) {
+ return null;
+ }
+ return {
+ arguments_: [...arguments_.slice(0, index), ...arguments_.slice(index + 2)],
+ ...(value === DEFAULT_USER_ID ? {} : { userId: value }),
+ };
+}
+
function liftDataDirOption(
arguments_: readonly string[],
): { arguments_: string[]; dataDir?: string } | null {
diff --git a/memhub/apps/cli/src/command-catalog.ts b/memhub/apps/cli/src/command-catalog.ts
index e73cf63..1929ba8 100644
--- a/memhub/apps/cli/src/command-catalog.ts
+++ b/memhub/apps/cli/src/command-catalog.ts
@@ -68,6 +68,12 @@ const JSON_OPTION: CommandOption = {
flag: "--json",
summary: "以 JSON 输出到 stdout,供脚本与 Agent 消费。",
};
+/** Global to the memory commands: whose memories are read or written. */
+const USER_ID_OPTION: CommandOption = {
+ flag: "--user-id <id>",
+ summary:
+ "读写哪个用户的记忆,默认 local(App 用的就是 local)。1–64 位字母、数字、点、下划线或连字符;其他用户的记忆来自用 sources connect hermes --user-id 接入的 Hermes profile。",
+};
const WATCH_OPTION: CommandOption = {
flag: "--watch",
summary: "串行持续刷新;Ctrl-C 只停止观察,不停止 Runtime。",
@@ -252,15 +258,25 @@ export const COMMANDS: readonly CommandDescriptor[] = [
{
name: "sources",
summary:
- "列出来源,直接接入来源,或按 request id 查接入回执。connect 不加 --import 只授权(处理保持冻结:不导入历史、不扫描新会话);加 --import 同时导入历史并开启持续同步,返回 request id。目录来自环境变量覆盖的来源必须加 --confirm-overrides。",
+ "列出来源,直接接入来源,或按 request id 查接入回执。connect 不加 --import 只授权(处理保持冻结:不导入历史、不扫描新会话);加 --import 同时导入历史并开启持续同步,返回 request id。目录来自环境变量覆盖的来源必须加 --confirm-overrides。Hermes 的每个 profile 是一个独立用户:用 --user-id 和 --root 接入,授权并导入历史(会自动排除 ~/.hermes/profiles/**,各用户互不读取)。",
usage:
- "memhub sources list [--json]\n memhub sources connect <id> [<id> ...] [--import] [--confirm-overrides] [--request-id <uuid>] [--json]\n memhub sources connect --all-detected [--import] [--confirm-overrides] [--json]\n memhub sources receipt <request-id> [--json]",
+ "memhub sources list [--json]\n memhub sources connect <id> [<id> ...] [--import] [--confirm-overrides] [--request-id <uuid>] [--json]\n memhub sources connect hermes --user-id <id> --root <path> [--import] [--request-id <uuid>] [--json]\n memhub sources connect --all-detected [--import] [--confirm-overrides] [--json]\n memhub sources receipt <request-id> [--json]",
options: [
{
flag: "--import",
summary:
"接入后立即导入历史会话并开启持续同步;不加时只授权,处理保持冻结。",
},
+ {
+ flag: "--user-id <id>",
+ summary:
+ "只用于 hermes:这条接入属于哪个用户(默认 local)。和 --root 一起接入一个 Hermes profile,例如 --user-id wife --root ~/.hermes/profiles/wife;其他来源只能是 local。",
+ },
+ {
+ flag: "--root <path>",
+ summary:
+ "只用于 hermes:读取的根目录(~ 会展开为主目录)。默认是 Hermes 自己的目录 ~/.hermes。",
+ },
{
flag: "--all-detected",
summary:
@@ -373,7 +389,7 @@ export const COMMANDS: readonly CommandDescriptor[] = [
summary:
"列出、搜索、查看、添加、修改或物理删除记忆(对话、工作、编码三个场景)。add 和 App 的「添加记忆」是同一个入口;delete 不可逆,需 --yes。",
usage:
- "memhub memories list [--scene <all|chat|working|coding>] [--source <id>] [--query <text>] [--status <state>] [--offset <n>] [--limit <n>] [--json]\n memhub memories show <memory-id> [--kind <kind>] [--variant <variant>] [--json]\n memhub memories add <text> [--request-id <uuid>] [--json]\n memhub memories add --content-file <path> [--request-id <uuid>] [--json]\n memhub memories add-status <request-id> [--json]\n memhub memories update <memory-id> --content-file <path> [--kind <kind>] [--variant <variant>] [--task <text>] [--json]\n memhub memories delete <memory-id> [--kind <kind>] [--variant <variant>] [--yes] [--json]",
+ "memhub memories list [--scene <all|chat|working|coding>] [--source <id>] [--query <text>] [--status <state>] [--offset <n>] [--limit <n>] [--user-id <id>] [--json]\n memhub memories show <memory-id> [--kind <kind>] [--variant <variant>] [--user-id <id>] [--json]\n memhub memories add <text> [--request-id <uuid>] [--user-id <id>] [--json]\n memhub memories add --content-file <path> [--request-id <uuid>] [--user-id <id>] [--json]\n memhub memories add-status <request-id> [--user-id <id>] [--json]\n memhub memories update <memory-id> --content-file <path> [--kind <kind>] [--variant <variant>] [--task <text>] [--user-id <id>] [--json]\n memhub memories delete <memory-id> [--kind <kind>] [--variant <variant>] [--yes] [--user-id <id>] [--json]",
options: [
{
flag: "--scene <all|chat|working|coding>",
@@ -411,6 +427,7 @@ export const COMMANDS: readonly CommandDescriptor[] = [
"add 的幂等键;用同一个 id 重试只会读回第一次的结果,不会重复添加。不给时自动生成并输出。",
},
DESTRUCTIVE_CONFIRM_OPTION,
+ USER_ID_OPTION,
JSON_OPTION,
],
exit_codes: RUNTIME_EXITS,
@@ -418,8 +435,8 @@ export const COMMANDS: readonly CommandDescriptor[] = [
{
name: "profile",
summary: "读取 SDK 组装后的用户长期画像(L0 + 已启用的长期画像补充)。",
- usage: "memhub profile [--json]",
- options: [JSON_OPTION],
+ usage: "memhub profile [--user-id <id>] [--json]",
+ options: [USER_ID_OPTION, JSON_OPTION],
exit_codes: RUNTIME_EXITS,
},
{
@@ -475,7 +492,7 @@ export const COMMANDS: readonly CommandDescriptor[] = [
summary:
"从原始对话与已沉淀记忆统一检索上下文;本地只读,不调用模型、不触发补索引。文本输出标明每条是「原始对话摘录」还是「记忆」(JSON 里是 kind: raw|memory)。",
usage:
- "memhub recall <query> [--kind <raw|memory>] [--source <id>] [--limit <n>] [--character-budget <n>] [--timeout-ms <n>] [--json]\n memhub recall --query-file <path> [...]\n memhub recall --stdin [...]",
+ "memhub recall <query> [--kind <raw|memory>] [--source <id>] [--limit <n>] [--character-budget <n>] [--timeout-ms <n>] [--user-id <id>] [--json]\n memhub recall --query-file <path> [...]\n memhub recall --stdin [...]",
options: [
{
flag: "--query-file <path>",
@@ -502,6 +519,7 @@ export const COMMANDS: readonly CommandDescriptor[] = [
flag: "--timeout-ms <n>",
summary: "Core 查询时限 50..30000 毫秒,默认 2000。",
},
+ USER_ID_OPTION,
JSON_OPTION,
],
exit_codes: RUNTIME_EXITS,
@@ -650,7 +668,7 @@ export const COMMANDS: readonly CommandDescriptor[] = [
summary:
"提交一段 OpenAI 格式的对话(messages)到写入队列,异步加工成记忆;或按 request id 查询状态。request id 是幂等键:不给时自动生成并输出,重试请带上同一个。新增一条结论式记忆请用 memories add。",
usage:
- "memhub write submit --messages-file <path> --session <id> [--source <id>] [--request-id <id>] [--memory-at <RFC3339>] [--live] [--json]\n memhub write status <request-id> [--json]",
+ "memhub write submit --messages-file <path> --session <id> [--source <id>] [--request-id <id>] [--memory-at <RFC3339>] [--live] [--user-id <id>] [--json]\n memhub write status <request-id> [--user-id <id>] [--json]",
options: [
{
flag: "--messages-file <path>",
@@ -666,6 +684,7 @@ export const COMMANDS: readonly CommandDescriptor[] = [
},
{ flag: "--memory-at <RFC3339>", summary: "对话发生时间,必须带时区。" },
{ flag: "--live", summary: "优先处理。" },
+ USER_ID_OPTION,
JSON_OPTION,
],
exit_codes: RUNTIME_EXITS,
diff --git a/memhub/apps/cli/src/context-search.ts b/memhub/apps/cli/src/context-search.ts
index 8a47888..76cabce 100644
--- a/memhub/apps/cli/src/context-search.ts
+++ b/memhub/apps/cli/src/context-search.ts
@@ -10,6 +10,8 @@ export interface ContextSearchInput {
limit: number;
character_budget: number;
timeout_ms: number;
+ /** Whose memories to search. Omitted for the default user (`local`). */
+ user_id?: string;
}
/** The CLI's JSON document mirrors Core's SDK-native context schema v2. */
diff --git a/memhub/apps/cli/src/core-client.ts b/memhub/apps/cli/src/core-client.ts
index c47e4cb..dbc846e 100644
--- a/memhub/apps/cli/src/core-client.ts
+++ b/memhub/apps/cli/src/core-client.ts
@@ -12,6 +12,7 @@ const READ_ONLY_PATHS = [
"/api/v1/live-sync",
"/api/v1/memory-processing",
"/api/v1/model-profiles",
+ "/api/v1/source-grants",
"/api/v1/sources",
"/api/v2/home-summary",
"/api/v2/memory-library",
@@ -310,6 +311,8 @@ export async function submitMemoryWrite(
messages: readonly OpenAIMessage[];
memory_at?: string;
priority?: "live" | "normal";
+ /** Whose memory this is. Omitted for the default user (`local`). */
+ user_id?: string;
},
): Promise<MemoryWriteOutcome> {
let response: { status: number; data: unknown };
@@ -327,6 +330,9 @@ export async function submitMemoryWrite(
...(request.priority === undefined
? {}
: { priority: request.priority }),
+ ...(request.user_id === undefined || request.user_id === "local"
+ ? {}
+ : { user_id: request.user_id }),
},
{
headers: { Authorization: `Bearer ${attachment.apiToken}` },
@@ -469,11 +475,16 @@ export async function deleteModelProfile(
export async function readMemoryWrite(
attachment: RuntimeAttachmentLike,
requestId: string,
+ /** A receipt belongs to the user that submitted it; omit for `local`. */
+ userId?: string,
): Promise<MemoryWriteReceipt | null> {
try {
const response = await axios.get<MemoryWriteReceipt>(
`${baseUrlOf(attachment)}/api/v2/memory-writes/${encodeURIComponent(requestId)}`,
{
+ ...(userId === undefined || userId === "local"
+ ? {}
+ : { params: { user_id: userId } }),
headers: { Authorization: `Bearer ${attachment.apiToken}` },
timeout: 10_000,
proxy: false,
diff --git a/memhub/apps/cli/src/core-operations.ts b/memhub/apps/cli/src/core-operations.ts
index 7fa078b..867db38 100644
--- a/memhub/apps/cli/src/core-operations.ts
+++ b/memhub/apps/cli/src/core-operations.ts
@@ -6,9 +6,10 @@ const WRITE_PATHS = [
] as const;
/** `POST /api/v2/memories` adds one memory (the app's 添加记忆). */
const MEMORY_ADD_PATH = "/api/v2/memories";
-/** One SDK memory; delete names its namespace in the query string. */
+/** One SDK memory; delete names its namespace, and a non-default user, in
+ * the query string. */
const SDK_MEMORY_PATH =
- /^\/api\/v2\/memories\/[A-Za-z0-9][\w.-]{0,127}(?:\?kind=(?:chat|experience|fact)(?:&variant=(?:working|coding))?)?$/;
+ /^\/api\/v2\/memories\/[A-Za-z0-9][\w.-]{0,127}(?:\?(?:kind=(?:chat|experience|fact)(?:&variant=(?:working|coding))?(?:&user_id=[A-Za-z0-9._-]{1,64})?|user_id=[A-Za-z0-9._-]{1,64}))?$/;
const MODEL_PROBE_PATH =
/^\/api\/v1\/model-profiles\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/probe$/;
const MODEL_PROFILE_PATH =
diff --git a/memhub/apps/cli/src/headless-flows.ts b/memhub/apps/cli/src/headless-flows.ts
index 03a6bb9..162021f 100644
--- a/memhub/apps/cli/src/headless-flows.ts
+++ b/memhub/apps/cli/src/headless-flows.ts
@@ -110,9 +110,18 @@ export async function connectSourcesWithImport(
sourceIds: readonly string[];
confirmOverrides: boolean;
requestId?: string;
+ /** Whose grant this is. Omitted for the default user (`local`). */
+ userId?: string;
+ /** An absolute root other than the source's candidate (a Hermes
+ * profile). Core reads its identity itself, so the source's candidate
+ * root id and revision are not sent for it. */
+ root?: string;
},
): Promise<FlowDocument> {
const sourceIds = input.sourceIds;
+ // A second user's grant is not a first run, and a custom root has no
+ // candidate the app showed: both are a plain connect.
+ const profile = input.root !== undefined || input.userId !== undefined;
if (
sourceIds.length < 1 ||
sourceIds.length > 32 ||
@@ -134,9 +143,14 @@ export async function connectSourcesWithImport(
return invalid("source_unavailable");
}
const items = selected.map(([candidate]) => candidate);
- const needsOverride = items
- .filter((item) => item.requires_override_confirmation)
- .map((item) => item.source_id);
+ // A custom root is the caller's own choice, not the environment override
+ // the confirmation exists for.
+ const needsOverride =
+ input.root !== undefined
+ ? []
+ : items
+ .filter((item) => item.requires_override_confirmation)
+ .map((item) => item.source_id);
if (needsOverride.length > 0 && !input.confirmOverrides) {
return {
schema_version: 1,
@@ -154,18 +168,22 @@ export async function connectSourcesWithImport(
request = buildSourceImportRequest({
sourceIds: [...sourceIds],
sourceRoots: Object.fromEntries(
- items.map((item) => [item.source_id, item.candidate_root_id]),
+ items.flatMap((item) =>
+ input.root === undefined
+ ? [[item.source_id, item.candidate_root_id]]
+ : [],
+ ),
),
sourceCandidateRevisions: Object.fromEntries(
items.flatMap((item) =>
- item.candidate_revision === undefined
+ item.candidate_revision === undefined || input.root !== undefined
? []
: [[item.source_id, item.candidate_revision]],
),
),
confirmEnvironmentOverrides: needsOverride.length > 0,
fullRescan: false,
- onboarding: true,
+ onboarding: !profile,
enableSync: true,
requestId,
});
@@ -175,7 +193,11 @@ export async function connectSourcesWithImport(
}
throw error;
}
- const result = await operations.post<unknown>(request.path, request.body);
+ const result = await operations.post<unknown>(request.path, {
+ ...request.body,
+ ...(input.userId === undefined ? {} : { user_id: input.userId }),
+ ...(input.root === undefined ? {} : { root: input.root }),
+ });
if (result.state === "rejected") {
return rejected(requestId, result.code);
}
diff --git a/memhub/apps/cli/src/memory-report.ts b/memhub/apps/cli/src/memory-report.ts
index 20263bc..1a41ed0 100644
--- a/memhub/apps/cli/src/memory-report.ts
+++ b/memhub/apps/cli/src/memory-report.ts
@@ -14,6 +14,25 @@ import { type CoreReader, RESERVED_MEMORY_SEGMENTS } from "./core-client.js";
import type { CoreOperations } from "./core-operations.js";
import { PRODUCT } from "./version.js";
+/** A MemHub user id, the same shape Core accepts. `local` is the default. */
+const USER_ID = /^[A-Za-z0-9._-]{1,64}$/;
+export const DEFAULT_USER_ID = "local";
+
+export function isUserId(value: string): boolean {
+ return USER_ID.test(value);
+}
+
+/**
+ * The `user_id` to send, or nothing. The default user is never named on the
+ * wire, so a request without `--user-id` stays exactly what it was before
+ * multi-user support and still works against an older Core.
+ */
+export function userIdParameters(userId?: string): { user_id?: string } {
+ return userId === undefined || userId === DEFAULT_USER_ID
+ ? {}
+ : { user_id: userId };
+}
+
/** Output budget: a long memory is shortened visibly, never dropped silently. */
const CONTENT_BUDGET = 240;
@@ -101,10 +120,12 @@ export interface MemoryDetailDocument {
export async function readMemoryPage(
reader: CoreReader,
query: MemoryQuery,
+ userId?: string,
): Promise<MemoryPageDocument> {
const parameters: Record<string, string | number> = {
offset: query.offset,
limit: query.limit,
+ ...userIdParameters(userId),
};
if (query.status !== undefined) parameters.statuses = query.status;
if (query.source !== undefined) parameters.source = query.source;
@@ -156,8 +177,12 @@ export async function readMemoryDetail(
reader: CoreReader,
memoryId: string,
namespace: MemoryNamespace = {},
+ userId?: string,
): Promise<MemoryDetailDocument> {
- const parameters = namespaceParameters(namespace);
+ const parameters = {
+ ...namespaceParameters(namespace),
+ ...userIdParameters(userId),
+ };
const outcome = await reader<unknown>(
`/api/v2/memories/${memoryId}`,
Object.keys(parameters).length > 0 ? parameters : undefined,
@@ -236,6 +261,7 @@ export async function addMemory(
operations: CoreOperations,
text: string,
requestId: string = randomUUID(),
+ userId?: string,
): Promise<MemoryAddDocument> {
const base = {
schema_version: 2 as const,
@@ -259,7 +285,10 @@ export async function addMemory(
}
throw error;
}
- const result = await operations.post<unknown>(request.path, request.body);
+ const result = await operations.post<unknown>(request.path, {
+ ...request.body,
+ ...userIdParameters(userId),
+ });
if (result.state !== "committed") {
return { ...base, state: result.state, code: result.code };
}
@@ -273,6 +302,7 @@ export async function addMemory(
export async function readMemoryAddStatus(
reader: CoreReader,
requestId: string,
+ userId?: string,
): Promise<MemoryAddDocument> {
const base = {
schema_version: 2 as const,
@@ -283,7 +313,11 @@ export async function readMemoryAddStatus(
if (!UUID.test(requestId)) {
return { ...base, state: "invalid", code: "invalid_request_id" };
}
- const outcome = await reader<unknown>(memoryAddStatusPath(requestId));
+ const user = userIdParameters(userId);
+ const outcome =
+ user.user_id === undefined
+ ? await reader<unknown>(memoryAddStatusPath(requestId))
+ : await reader<unknown>(memoryAddStatusPath(requestId), user);
if (outcome.state === "not_found") {
return { ...base, state: "not_found", code: "memory_add_not_found" };
}
diff --git a/memhub/apps/cli/src/source-progress-report.ts b/memhub/apps/cli/src/source-progress-report.ts
index ee20af2..5fe95d0 100644
--- a/memhub/apps/cli/src/source-progress-report.ts
+++ b/memhub/apps/cli/src/source-progress-report.ts
@@ -38,6 +38,21 @@ export interface SourcesDocument {
state: ReadState["state"];
code?: string;
sources: Array<Record<string, unknown>>;
+ /** Every grant of every user (`GET /api/v1/source-grants`). Absent when
+ * Core is too old to list them; `sources` is the default user's view. */
+ grants?: SourceGrant[];
+}
+
+/** One source grant. Only Hermes has grants for users other than `local`,
+ * one per Hermes profile root. */
+export interface SourceGrant {
+ user_id: string;
+ source_id: string;
+ root_label: string | null;
+ root_path: string | null;
+ authorized: boolean;
+ revoked_at: string | null;
+ sync_enabled: boolean;
}
export interface SyncDocument {
@@ -86,14 +101,66 @@ export async function readSources(
sources: [],
};
}
+ const grants = await readSourceGrants(reader);
return {
schema_version: SCHEMA_VERSION,
product: PRODUCT,
state: "ok",
- sources: result.data.map(projectSource),
+ // `/api/v1/sources` is the default user's view of every source.
+ sources: result.data.map((source) => ({
+ ...projectSource(source),
+ user_id: "local",
+ })),
+ ...(grants === null ? {} : { grants }),
};
}
+/** The grants of every user, or null when Core cannot list them (an older
+ * Core answers 404): the source list is then shown as before. */
+async function readSourceGrants(
+ reader: CoreReader,
+): Promise<SourceGrant[] | null> {
+ let outcome: ReadOutcome<unknown>;
+ try {
+ outcome = await reader<unknown>("/api/v1/source-grants");
+ } catch {
+ return null;
+ }
+ if (outcome.state !== "ok") return null;
+ const value = outcome.data;
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
+ const items = (value as { grants?: unknown }).grants;
+ if (!Array.isArray(items)) return null;
+ const grants: SourceGrant[] = [];
+ const text = (candidate: unknown): string | null =>
+ typeof candidate === "string" && candidate.length <= 4096
+ ? candidate
+ : null;
+ for (const item of items) {
+ if (!item || typeof item !== "object" || Array.isArray(item)) return null;
+ const grant = item as Record<string, unknown>;
+ if (
+ typeof grant.user_id !== "string" ||
+ !/^[A-Za-z0-9._-]{1,64}$/.test(grant.user_id) ||
+ typeof grant.source_id !== "string" ||
+ !/^[a-z0-9][a-z0-9-]{0,127}$/.test(grant.source_id) ||
+ typeof grant.authorized !== "boolean"
+ ) {
+ return null;
+ }
+ grants.push({
+ user_id: grant.user_id,
+ source_id: grant.source_id,
+ root_label: text(grant.root_label),
+ root_path: text(grant.root_path),
+ authorized: grant.authorized,
+ revoked_at: text(grant.revoked_at),
+ sync_enabled: grant.sync_enabled === true,
+ });
+ }
+ return grants;
+}
+
export async function readSync(reader: CoreReader): Promise<SyncDocument> {
const result = validated(
await reader<unknown>("/api/v1/live-sync"),
@@ -231,6 +298,22 @@ export function renderSourcesText(document: SourcesDocument): string {
);
}
if (document.sources.length === 0) lines.push("(没有来源)");
+ // The list above is the default user's (`local`). Another user's grant,
+ // a Hermes profile, is listed with its user so it is not mistaken for it.
+ const others = (document.grants ?? []).filter(
+ (grant) => grant.user_id !== "local",
+ );
+ if (others.length > 0) {
+ lines.push("其他用户的连接:");
+ for (const grant of others) {
+ const name =
+ document.sources.find((source) => source.source_id === grant.source_id)
+ ?.display_name ?? grant.source_id;
+ lines.push(
+ `- ${name}(用户 ${grant.user_id}):${grant.authorized ? "已连接" : grant.revoked_at ? "已撤销" : "未连接"};处理${grant.sync_enabled ? "已开启" : "已冻结"}${grant.root_path ? `;目录 ${grant.root_path}` : ""}`,
+ );
+ }
+ }
lines.push("");
return lines.join("\n");
}
diff --git a/memhub/apps/cli/src/source-progress.test.ts b/memhub/apps/cli/src/source-progress.test.ts
index 35136c0..9c1e804 100644
--- a/memhub/apps/cli/src/source-progress.test.ts
+++ b/memhub/apps/cli/src/source-progress.test.ts
@@ -179,12 +179,72 @@ describe("CLI-07/10 source and synchronization reads", () => {
sync_enabled: true,
sync_completeness: "additions_only",
});
- expect(requestedPaths()).toEqual(["/api/v1/sources"]);
+ // The grants list answers 404 here, as an older Core does: the source
+ // list is shown as before, every row the default user's.
+ expect(report.sources[0].user_id).toBe("local");
+ expect(report.grants).toBeUndefined();
+ expect(requestedPaths()).toEqual([
+ "/api/v1/sources",
+ "/api/v1/source-grants",
+ ]);
expect(requestedPaths().some((path) => path.includes("detect"))).toBe(
false,
);
});
+ it("shows every user's grant, a Hermes profile with its user", async () => {
+ const grants = {
+ schema_version: 1,
+ grants: [
+ {
+ user_id: "local",
+ source_id: "codex",
+ root_label: ".codex",
+ root_path: "/home/synthetic/.codex",
+ authorized: true,
+ revoked_at: null,
+ sync_enabled: true,
+ },
+ {
+ user_id: "wife",
+ source_id: "hermes",
+ root_label: "wife",
+ root_path: "/home/synthetic/.hermes/profiles/wife",
+ authorized: true,
+ revoked_at: null,
+ sync_enabled: true,
+ },
+ ],
+ };
+ transport.get.mockImplementation(async (url: string) =>
+ url === "/api/v1/source-grants"
+ ? { status: 200, data: grants }
+ : (RESPONSES.get(url) ?? { status: 404, data: {} }),
+ );
+ let streams = captureStreams();
+ try {
+ expect(await run(["sources", "list", "--json"], {})).toBe(0);
+ } finally {
+ streams.restore();
+ }
+ const report = JSON.parse(streams.stdout());
+ expect(report.grants).toEqual(grants.grants);
+ expect(report.sources[0]).toMatchObject({
+ source_id: "codex",
+ user_id: "local",
+ });
+ streams = captureStreams();
+ try {
+ expect(await run(["sources", "list"], {})).toBe(0);
+ } finally {
+ streams.restore();
+ }
+ expect(streams.stdout()).toContain("其他用户的连接:");
+ expect(streams.stdout()).toContain(
+ "hermes(用户 wife):已连接;处理已开启;目录 /home/synthetic/.hermes/profiles/wife",
+ );
+ });
+
it("keeps degraded synchronization distinct and prints its error code", async () => {
const streams = captureStreams();
try {
@@ -552,6 +612,7 @@ describe("CLI-19 progress and issue reads", () => {
requestedPaths().every((path) =>
[
"/api/v1/sources",
+ "/api/v1/source-grants",
"/api/v1/live-sync",
"/api/v1/import-jobs",
"/api/v1/memory-processing",
diff --git a/memhub/apps/cli/src/user-id-cli.test.ts b/memhub/apps/cli/src/user-id-cli.test.ts
new file mode 100644
index 0000000..dededdf
--- /dev/null
+++ b/memhub/apps/cli/src/user-id-cli.test.ts
@@ -0,0 +1,405 @@
+import { mkdtemp, writeFile } from "node:fs/promises";
+import os, { tmpdir } from "node:os";
+import path from "node:path";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { run } from "./cli.js";
+
+const transport = vi.hoisted(() => ({
+ get: vi.fn(),
+ post: vi.fn(),
+ put: vi.fn(),
+ patch: vi.fn(),
+ delete: vi.fn(),
+}));
+const direct = vi.hoisted(() => ({ get: vi.fn(), post: vi.fn() }));
+vi.mock("axios", () => ({
+ default: {
+ create: vi.fn(() => transport),
+ get: direct.get,
+ post: direct.post,
+ 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 REQUEST = "33333333-3333-4333-8333-333333333333";
+const HERMES = {
+ source_id: "hermes",
+ display_name: "Hermes",
+ storage_kinds: ["sqlite"],
+ available: true,
+ authorized: true,
+ detected: null,
+ root_label: ".hermes",
+ candidate_path: "~/.hermes",
+ candidate_kind: "default",
+ candidate_revision: 0,
+ candidate_root_id: "hermes-root-identity",
+ imported_messages: 0,
+ imported_conversations: 0,
+ capabilities: {
+ historical_import: "implemented",
+ incremental_import: "implemented",
+ live_sync: "implemented",
+ recall: "implemented",
+ installer: "not_implemented",
+ verification: "fixture_only",
+ },
+ sync_completeness: "additions_only",
+ location_state: "found",
+};
+const CODEX = {
+ ...HERMES,
+ source_id: "codex",
+ display_name: "Codex",
+ candidate_root_id: "codex-root-identity",
+};
+
+function addReceipt() {
+ return {
+ evidence_id: "44444444-4444-4444-8444-444444444444",
+ text: "Prefers tea",
+ scope: "all-apps",
+ created_at: "2026-10-27T00:00:00Z",
+ state: "pending",
+ task_id: null,
+ memory_ids: [],
+ error: null,
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ for (const method of [
+ ...Object.values(transport),
+ ...Object.values(direct),
+ ]) {
+ 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) => {
+ if (url === "/api/v1/sources") {
+ return { status: 200, data: [HERMES, CODEX] };
+ }
+ if (url === "/api/v2/user-profile") {
+ return {
+ status: 200,
+ data: { request_id: "r-1", profile: null, elapsed_ms: 1 },
+ };
+ }
+ return { status: 404, data: {} };
+ });
+ transport.post.mockImplementation(
+ async (url: string, body: Record<string, unknown>) =>
+ url === "/api/v1/sources/connect"
+ ? {
+ status: 200,
+ data: {
+ request_id: body.request_id,
+ accepted_source_ids: ["hermes"],
+ failed_sources: {},
+ jobs: [],
+ },
+ }
+ : url === "/api/v2/memories"
+ ? { status: 201, data: addReceipt() }
+ : { status: 404, data: {} },
+ );
+ transport.put.mockResolvedValue({ status: 200, data: {} });
+ transport.delete.mockResolvedValue({ status: 204, data: "" });
+ direct.post.mockResolvedValue({
+ status: 202,
+ data: {
+ request_id: REQUEST,
+ state: "accepted",
+ created_at: "T1",
+ updated_at: "T1",
+ },
+ });
+ direct.get.mockResolvedValue({
+ data: {
+ request_id: REQUEST,
+ state: "accepted",
+ created_at: "T1",
+ updated_at: "T1",
+ },
+ });
+});
+
+describe("--user-id on the memory commands", () => {
+ it("passes the user as a query parameter to memory reads and deletes", async () => {
+ await capturedRun(["memories", "list", "--user-id", "wife", "--json"]);
+ expect(transport.get).toHaveBeenCalledWith("/api/v2/memory-library", {
+ params: { offset: 0, limit: 100, user_id: "wife" },
+ });
+ // Global: the flag may come before the subcommand too.
+ await capturedRun(["memories", "--user-id", "wife", "show", "m-1"]);
+ expect(transport.get).toHaveBeenCalledWith("/api/v2/memories/m-1", {
+ params: { user_id: "wife" },
+ });
+ await capturedRun(["memories", "add-status", REQUEST, "--user-id", "wife"]);
+ expect(transport.get).toHaveBeenCalledWith(
+ `/api/v2/memories/additions/${REQUEST}`,
+ { params: { user_id: "wife" } },
+ );
+ await capturedRun(["profile", "--user-id", "wife", "--json"]);
+ expect(transport.get).toHaveBeenCalledWith("/api/v2/user-profile", {
+ params: { user_id: "wife" },
+ });
+ await capturedRun([
+ "memories",
+ "delete",
+ "fact-1",
+ "--kind",
+ "fact",
+ "--yes",
+ "--user-id",
+ "wife",
+ ]);
+ expect(transport.delete).toHaveBeenCalledWith(
+ "/api/v2/memories/fact-1?kind=fact&user_id=wife",
+ undefined,
+ );
+ await capturedRun([
+ "memories",
+ "delete",
+ "m-1",
+ "--yes",
+ "--user-id",
+ "wife",
+ ]);
+ expect(transport.delete).toHaveBeenCalledWith(
+ "/api/v2/memories/m-1?user_id=wife",
+ undefined,
+ );
+ await capturedRun(["write", "status", REQUEST, "--user-id", "wife"]);
+ expect(direct.get.mock.calls[0][0]).toBe(
+ `http://127.0.0.1:8765/api/v2/memory-writes/${REQUEST}`,
+ );
+ expect(direct.get.mock.calls[0][1].params).toEqual({ user_id: "wife" });
+ });
+
+ it("passes the user in the body of memory writes and searches", async () => {
+ await capturedRun(["memories", "add", "Prefers tea", "--user-id", "wife"]);
+ expect(transport.post.mock.calls[0][0]).toBe("/api/v2/memories");
+ expect(transport.post.mock.calls[0][1]).toMatchObject({
+ text: "Prefers tea",
+ scope: "all-apps",
+ user_id: "wife",
+ });
+ const directory = await mkdtemp(path.join(tmpdir(), "om-user-id-"));
+ const content = path.join(directory, "content.txt");
+ await writeFile(content, "Prefers green tea\n");
+ await capturedRun([
+ "memories",
+ "update",
+ "m-1",
+ "--content-file",
+ content,
+ "--user-id",
+ "wife",
+ ]);
+ expect(transport.put.mock.calls[0][0]).toBe("/api/v2/memories/m-1");
+ expect(transport.put.mock.calls[0][1]).toMatchObject({ user_id: "wife" });
+ await capturedRun(["recall", "tea", "--user-id", "wife", "--json"]);
+ const search = transport.post.mock.calls.find(
+ ([url]) => url === "/api/v2/context/search",
+ );
+ expect(search?.[1]).toMatchObject({ query: "tea", user_id: "wife" });
+ const messages = path.join(directory, "messages.json");
+ await writeFile(
+ messages,
+ JSON.stringify([{ role: "user", content: "I like tea" }]),
+ );
+ await capturedRun([
+ "write",
+ "submit",
+ "--messages-file",
+ messages,
+ "--session",
+ "s-1",
+ "--user-id",
+ "wife",
+ ]);
+ expect(direct.post.mock.calls[0][0]).toBe(
+ "http://127.0.0.1:8765/api/v2/memory-writes",
+ );
+ expect(direct.post.mock.calls[0][1]).toMatchObject({
+ session_id: "s-1",
+ user_id: "wife",
+ });
+ });
+
+ it("names no user by default or for --user-id local", async () => {
+ for (const extra of [[], ["--user-id", "local"]]) {
+ transport.get.mockClear();
+ transport.post.mockClear();
+ await capturedRun(["memories", "list", ...extra, "--json"]);
+ expect(transport.get).toHaveBeenCalledWith("/api/v2/memory-library", {
+ params: { offset: 0, limit: 100 },
+ });
+ await capturedRun(["profile", ...extra]);
+ expect(transport.get).toHaveBeenCalledWith(
+ "/api/v2/user-profile",
+ undefined,
+ );
+ await capturedRun(["memories", "add", "Prefers tea", ...extra]);
+ expect(transport.post.mock.calls[0][1]).not.toHaveProperty("user_id");
+ await capturedRun(["recall", "tea", ...extra, "--json"]);
+ const search = transport.post.mock.calls.find(
+ ([url]) => url === "/api/v2/context/search",
+ );
+ expect(search?.[1]).not.toHaveProperty("user_id");
+ }
+ });
+
+ it("refuses a malformed user id before contacting Core", async () => {
+ for (const value of ["bad:id", "", "x".repeat(65), "a b", "--json"]) {
+ const result = await capturedRun([
+ "memories",
+ "list",
+ "--user-id",
+ value,
+ ]);
+ expect(result.code).toBe(2);
+ }
+ expect(
+ (await capturedRun(["profile", "--user-id", "a", "--user-id", "b"])).code,
+ ).toBe(2);
+ expect((await capturedRun(["recall", "tea", "--user-id"])).code).toBe(2);
+ expect(transport.get).not.toHaveBeenCalled();
+ expect(transport.post).not.toHaveBeenCalled();
+ });
+});
+
+describe("sources connect for a Hermes profile", () => {
+ it("connects hermes for another user from its own root", async () => {
+ const result = await capturedRun([
+ "sources",
+ "connect",
+ "hermes",
+ "--user-id",
+ "wife",
+ "--root",
+ "~/.hermes/profiles/wife",
+ "--json",
+ ]);
+ expect(result.code).toBe(0);
+ expect(transport.post).toHaveBeenCalledTimes(1);
+ const [url, body] = transport.post.mock.calls[0];
+ expect(url).toBe("/api/v1/sources/connect");
+ expect(body).toMatchObject({
+ source_ids: ["hermes"],
+ // Core reads the custom root's identity itself.
+ source_roots: {},
+ source_candidate_revisions: {},
+ onboarding: false,
+ user_id: "wife",
+ root: path.join(os.homedir(), ".hermes/profiles/wife"),
+ });
+ });
+
+ it("keeps a plain connect unchanged and accepts --import with a profile", async () => {
+ await capturedRun(["sources", "connect", "hermes", "--import", "--json"]);
+ const plain = transport.post.mock.calls[0][1];
+ expect(plain).not.toHaveProperty("user_id");
+ expect(plain).not.toHaveProperty("root");
+ expect(plain).toMatchObject({
+ source_roots: { hermes: "hermes-root-identity" },
+ onboarding: true,
+ });
+ transport.post.mockClear();
+ const result = await capturedRun([
+ "sources",
+ "connect",
+ "hermes",
+ "--import",
+ "--user-id",
+ "wife",
+ "--root",
+ "/profiles/wife",
+ "--request-id",
+ REQUEST,
+ "--json",
+ ]);
+ expect(result.code).toBe(0);
+ expect(transport.post.mock.calls[0][1]).toMatchObject({
+ request_id: REQUEST,
+ user_id: "wife",
+ root: "/profiles/wife",
+ });
+ });
+
+ it("refuses --user-id and --root for any source but hermes", async () => {
+ for (const argv of [
+ ["sources", "connect", "codex", "--user-id", "wife"],
+ ["sources", "connect", "codex", "--root", "/somewhere", "--import"],
+ ["sources", "connect", "hermes", "codex", "--user-id", "wife"],
+ ["sources", "connect", "--all-detected", "--user-id", "wife"],
+ ["sources", "connect", "hermes", "--user-id", "bad:id"],
+ ]) {
+ const result = await capturedRun(argv);
+ expect(result.code).toBe(2);
+ expect(result.stderr).toContain("hermes");
+ }
+ expect(transport.post).not.toHaveBeenCalled();
+ });
+});
+
+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/docs/cli/EXPERIENCE.md b/memhub/docs/cli/EXPERIENCE.md
index 383ffca..09c024a 100644
--- a/memhub/docs/cli/EXPERIENCE.md
+++ b/memhub/docs/cli/EXPERIENCE.md
@@ -53,6 +53,26 @@ node apps/cli/dist/one-memory.cjs sources connect --all-detected --import
(如 `DSH_HOME`)的来源必须加 `--confirm-overrides`,否则被拒绝(或在
`--all-detected` 时跳过并列出)。用同一个 `--request-id <uuid>` 重试不会重复导入。
+### 接入 Hermes 的另一个 profile(多用户)
+
+一个 Runtime 可以给多个用户记忆。**用户由读的是哪个目录决定**,不看会话或平台账号:
+`~/.hermes/state.db` 属于默认用户 `local`,`~/.hermes/profiles/<name>/state.db` 是另一个用户。
+
+```bash
+# 把 wife 这个 Hermes profile 接成用户 wife:授权 + 导入历史,一步完成
+node apps/cli/dist/one-memory.cjs sources connect hermes --user-id wife --root ~/.hermes/profiles/wife
+# 也可以显式加 --import,效果相同;可带 --request-id <uuid> 幂等重试
+node apps/cli/dist/one-memory.cjs sources connect hermes --user-id wife --root ~/.hermes/profiles/wife --import --json
+
+# 列出来源;其他用户的连接单独列在「其他用户的连接」下,--json 里在 grants 字段
+node apps/cli/dist/one-memory.cjs sources list
+```
+
+- 只有 `hermes` 能带 `--user-id`(非 `local`)或 `--root`;其他来源带了会退 2,什么都不发。
+- `--root` 里的 `~` 由 CLI 展开为主目录,相对路径按当前目录解析成绝对路径。
+- 扫描 `~/.hermes` 时会排除 `profiles/**`,所以 `local` 不会读到 wife 的 `state.db`。
+- App 不变:它只读写 `local`,其他来源也都固定是 `local`。
+
## 3. 看导入进度
```bash
@@ -105,6 +125,23 @@ node apps/cli/dist/one-memory.cjs write status <request_id> --json
两条都返回 request id;它是幂等键,结果未知时用**同一个** `--request-id` 重试不会重复写入。
+### 按用户读写(`--user-id`)
+
+记忆命令都接受全局 `--user-id <id>`(默认 `local`,即 App 看到的那份):
+`memories list/show/add/add-status/update/delete`、`recall`、`profile`、`write submit/status`。
+
+```bash
+node apps/cli/dist/one-memory.cjs memories list --user-id wife --json
+node apps/cli/dist/one-memory.cjs memories add "我更喜欢喝绿茶" --user-id wife
+node apps/cli/dist/one-memory.cjs recall "喝什么茶" --user-id wife
+node apps/cli/dist/one-memory.cjs profile --user-id wife
+node apps/cli/dist/one-memory.cjs write status <request_id> --user-id wife
+```
+
+- 用户 ID 只能是 1–64 位字母、数字、`.`、`_`、`-`;其他写法退 2,不连 Runtime。
+- 不带 `--user-id`(或写 `--user-id local`)时请求里不出现 `user_id`,和以前完全一样。
+- 用户之间互相隔离:读、改、删另一个用户的记忆 ID 返回「未找到」;write 的 request id 也只属于提交它的用户。
+
## 8. 召回(recall)
`recall` 两条路径(raw / memory)此前已真机验证。文本输出会标明每条是「原始对话摘录」