@sparkelf/dsh-knowledge-base 0.6.2 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1852,17 +1852,17 @@ const NODE_TYPES$1 = [
1852
1852
  "decision",
1853
1853
  "topic"
1854
1854
  ];
1855
- const AUTHORITIES$2 = [
1855
+ const AUTHORITIES$3 = [
1856
1856
  "canonical",
1857
1857
  "advisory",
1858
1858
  "redline"
1859
1859
  ];
1860
- const ORIGINS$2 = [
1860
+ const ORIGINS$3 = [
1861
1861
  "human",
1862
1862
  "ai",
1863
1863
  "mixed"
1864
1864
  ];
1865
- const REVIEW_STATUSES$2 = [
1865
+ const REVIEW_STATUSES$3 = [
1866
1866
  "draft",
1867
1867
  "reviewed",
1868
1868
  "approved"
@@ -2196,10 +2196,10 @@ const parseFrontMatter$1 = (source, options) => {
2196
2196
  else title = options.titleFallback;
2197
2197
  }
2198
2198
  const type = enumValue(entries.get("type"), NODE_TYPES$1, DEFAULT_NODE_TYPE, "type", errors);
2199
- const authority = enumValue(entries.get("authority"), AUTHORITIES$2, DEFAULT_AUTHORITY, "authority", errors);
2199
+ const authority = enumValue(entries.get("authority"), AUTHORITIES$3, DEFAULT_AUTHORITY, "authority", errors);
2200
2200
  const internalizable = booleanValue(entries.get("internalizable"), true, "internalizable", errors);
2201
- const origin = enumValue(entries.get("origin"), ORIGINS$2, DEFAULT_ORIGIN, "origin", errors);
2202
- const reviewStatus = enumValue(entries.get("reviewStatus"), REVIEW_STATUSES$2, DEFAULT_REVIEW_STATUS, "reviewStatus", errors);
2201
+ const origin = enumValue(entries.get("origin"), ORIGINS$3, DEFAULT_ORIGIN, "origin", errors);
2202
+ const reviewStatus = enumValue(entries.get("reviewStatus"), REVIEW_STATUSES$3, DEFAULT_REVIEW_STATUS, "reviewStatus", errors);
2203
2203
  const tags = stringArrayValue(entries.get("tags"), [], "tags", errors);
2204
2204
  const sourceRefs = stringArrayValue(entries.get("sourceRefs"), [], "sourceRefs", errors);
2205
2205
  if (errors.length > 0 || id === void 0 || title === void 0) return {
@@ -2492,10 +2492,10 @@ const parseEdgeFrontMatter = (source, edgeId) => {
2492
2492
  const { entries, errors } = parseFrontMatterLines(block.lines);
2493
2493
  const id = scalarString(entries.get("id"), "id", errors) ?? edgeId;
2494
2494
  const title = scalarString(entries.get("title"), "title", errors) ?? id;
2495
- const authority = enumValue(entries.get("authority"), AUTHORITIES$2, DEFAULT_AUTHORITY, "authority", errors);
2495
+ const authority = enumValue(entries.get("authority"), AUTHORITIES$3, DEFAULT_AUTHORITY, "authority", errors);
2496
2496
  const internalizable = booleanValue(entries.get("internalizable"), true, "internalizable", errors);
2497
- const origin = enumValue(entries.get("origin"), ORIGINS$2, DEFAULT_ORIGIN, "origin", errors);
2498
- const reviewStatus = enumValue(entries.get("reviewStatus"), REVIEW_STATUSES$2, DEFAULT_REVIEW_STATUS, "reviewStatus", errors);
2497
+ const origin = enumValue(entries.get("origin"), ORIGINS$3, DEFAULT_ORIGIN, "origin", errors);
2498
+ const reviewStatus = enumValue(entries.get("reviewStatus"), REVIEW_STATUSES$3, DEFAULT_REVIEW_STATUS, "reviewStatus", errors);
2499
2499
  const tags = stringArrayValue(entries.get("tags"), [], "tags", errors);
2500
2500
  const sourceRefs = stringArrayValue(entries.get("sourceRefs"), [], "sourceRefs", errors);
2501
2501
  const relationType = scalarString(entries.get("type"), "type", errors);
@@ -9421,17 +9421,17 @@ const NODE_TYPES = [
9421
9421
  "decision",
9422
9422
  "topic"
9423
9423
  ];
9424
- const AUTHORITIES$1 = [
9424
+ const AUTHORITIES$2 = [
9425
9425
  "canonical",
9426
9426
  "advisory",
9427
9427
  "redline"
9428
9428
  ];
9429
- const ORIGINS$1 = [
9429
+ const ORIGINS$2 = [
9430
9430
  "human",
9431
9431
  "ai",
9432
9432
  "mixed"
9433
9433
  ];
9434
- const REVIEW_STATUSES$1 = [
9434
+ const REVIEW_STATUSES$2 = [
9435
9435
  "draft",
9436
9436
  "reviewed",
9437
9437
  "approved"
@@ -9959,10 +9959,10 @@ function parseEdgeDocument(source, edge, docPath) {
9959
9959
  else internalizable = internalizableRaw === "true";
9960
9960
  }
9961
9961
  attributes.title = readText("title") ?? edge.id;
9962
- attributes.authority = readEnum("authority", AUTHORITIES$1, "advisory");
9962
+ attributes.authority = readEnum("authority", AUTHORITIES$2, "advisory");
9963
9963
  attributes.internalizable = internalizable;
9964
- attributes.origin = readEnum("origin", ORIGINS$1, "human");
9965
- attributes.reviewStatus = readEnum("reviewStatus", REVIEW_STATUSES$1, "draft");
9964
+ attributes.origin = readEnum("origin", ORIGINS$2, "human");
9965
+ attributes.reviewStatus = readEnum("reviewStatus", REVIEW_STATUSES$2, "draft");
9966
9966
  attributes.tags = readArray("tags") ?? [];
9967
9967
  attributes.sourceRefs = readArray("sourceRefs") ?? [];
9968
9968
  if (documentId !== void 0) attributes.documentId = documentId;
@@ -10791,9 +10791,9 @@ function parseOverviewLink(value) {
10791
10791
  const authority = value.authority;
10792
10792
  const origin = value.origin;
10793
10793
  const reviewStatus = value.reviewStatus;
10794
- if (!AUTHORITIES$1.includes(authority)) return void 0;
10795
- if (!ORIGINS$1.includes(origin)) return void 0;
10796
- if (!REVIEW_STATUSES$1.includes(reviewStatus)) return void 0;
10794
+ if (!AUTHORITIES$2.includes(authority)) return void 0;
10795
+ if (!ORIGINS$2.includes(origin)) return void 0;
10796
+ if (!REVIEW_STATUSES$2.includes(reviewStatus)) return void 0;
10797
10797
  const tags = Array.isArray(value.tags) && value.tags.every((item) => typeof item === "string") ? value.tags.map((item) => item.trim()).filter((item) => item !== "") : [];
10798
10798
  const sourceRefs = Array.isArray(value.sourceRefs) && value.sourceRefs.every((item) => typeof item === "string") ? value.sourceRefs.map((item) => item.trim()).filter((item) => item !== "") : [];
10799
10799
  const title = typeof value.title === "string" && value.title.trim() !== "" ? value.title.trim() : void 0;
@@ -11308,10 +11308,10 @@ async function addOverviewEdge(host, graphs, overview, args) {
11308
11308
  to,
11309
11309
  type,
11310
11310
  ...args.title === void 0 || args.title.trim() === "" ? {} : { title: args.title.trim() },
11311
- authority: enumArg(args.authority, AUTHORITIES$1, "authority") ?? "advisory",
11311
+ authority: enumArg(args.authority, AUTHORITIES$2, "authority") ?? "advisory",
11312
11312
  internalizable: booleanArg(args.internalizable, "internalizable") ?? true,
11313
- origin: enumArg(args.origin, ORIGINS$1, "origin") ?? "human",
11314
- reviewStatus: enumArg(args.reviewStatus, REVIEW_STATUSES$1, "reviewStatus") ?? "draft",
11313
+ origin: enumArg(args.origin, ORIGINS$2, "origin") ?? "human",
11314
+ reviewStatus: enumArg(args.reviewStatus, REVIEW_STATUSES$2, "reviewStatus") ?? "draft",
11315
11315
  tags: stringListArg(args.tags, "tags") ?? [],
11316
11316
  sourceRefs: stringListArg(args.sourceRefs, "sourceRefs") ?? [],
11317
11317
  ...args.body === void 0 || args.body.trim() === "" ? {} : { body: args.body },
@@ -11710,10 +11710,10 @@ async function addToGraphJson(host, graph, store, args) {
11710
11710
  id,
11711
11711
  type: enumArg(args.type, NODE_TYPES, "type") ?? "fact",
11712
11712
  title,
11713
- authority: enumArg(args.authority, AUTHORITIES$1, "authority") ?? "advisory",
11713
+ authority: enumArg(args.authority, AUTHORITIES$2, "authority") ?? "advisory",
11714
11714
  internalizable: booleanArg(args.internalizable, "internalizable") ?? true,
11715
- origin: enumArg(args.origin, ORIGINS$1, "origin") ?? "human",
11716
- reviewStatus: enumArg(args.reviewStatus, REVIEW_STATUSES$1, "reviewStatus") ?? "draft",
11715
+ origin: enumArg(args.origin, ORIGINS$2, "origin") ?? "human",
11716
+ reviewStatus: enumArg(args.reviewStatus, REVIEW_STATUSES$2, "reviewStatus") ?? "draft",
11717
11717
  tags: stringListArg(args.tags, "tags") ?? [],
11718
11718
  sourceRefs: stringListArg(args.sourceRefs, "sourceRefs") ?? []
11719
11719
  }, body);
@@ -11781,10 +11781,10 @@ async function addToGraphJson(host, graph, store, args) {
11781
11781
  for (const endpoint of [from, to]) if (!state.nodes.some((node) => node.id === endpoint)) throw new KnowledgeToolError("not-found", "edge endpoint is not a node in this graph: " + endpoint, endpoint);
11782
11782
  const type = (args.type ?? "").trim();
11783
11783
  if (type === "") throw new KnowledgeToolError("invalid", "type (the relation label) is required for an edge", id);
11784
- const authority = enumArg(args.authority, AUTHORITIES$1, "authority") ?? "advisory";
11784
+ const authority = enumArg(args.authority, AUTHORITIES$2, "authority") ?? "advisory";
11785
11785
  const internalizable = booleanArg(args.internalizable, "internalizable") ?? true;
11786
- const origin = enumArg(args.origin, ORIGINS$1, "origin") ?? "human";
11787
- const reviewStatus = enumArg(args.reviewStatus, REVIEW_STATUSES$1, "reviewStatus") ?? "draft";
11786
+ const origin = enumArg(args.origin, ORIGINS$2, "origin") ?? "human";
11787
+ const reviewStatus = enumArg(args.reviewStatus, REVIEW_STATUSES$2, "reviewStatus") ?? "draft";
11788
11788
  const title = (args.title ?? "").trim();
11789
11789
  const wantsDoc = body.trim() !== "" || args.authority !== void 0 || args.internalizable !== void 0 || args.origin !== void 0 || args.reviewStatus !== void 0 || args.tags !== void 0 || args.sourceRefs !== void 0 || title !== "";
11790
11790
  const docPath = edgeDocPath(store.graphId, id);
@@ -11939,10 +11939,10 @@ async function setOnGraphJson(host, graph, store, args) {
11939
11939
  if (unsupported.length > 0) throw new KnowledgeToolError("invalid", "a graph-json node has no card fields to edit (" + unsupported.join(", ") + "); pass title/type/authority/internalizable/origin/reviewStatus/tags/sourceRefs", node.id);
11940
11940
  if (node.missing) throw new KnowledgeToolError("not-found", "the node document is missing; add it first", node.path);
11941
11941
  const type = enumArg(args.type, NODE_TYPES, "type") ?? node.type;
11942
- const authority = enumArg(args.authority, AUTHORITIES$1, "authority") ?? node.authority;
11942
+ const authority = enumArg(args.authority, AUTHORITIES$2, "authority") ?? node.authority;
11943
11943
  const internalizable = booleanArg(args.internalizable, "internalizable") ?? node.internalizable;
11944
- const origin = enumArg(args.origin, ORIGINS$1, "origin") ?? node.origin;
11945
- const reviewStatus = enumArg(args.reviewStatus, REVIEW_STATUSES$1, "reviewStatus") ?? node.reviewStatus;
11944
+ const origin = enumArg(args.origin, ORIGINS$2, "origin") ?? node.origin;
11945
+ const reviewStatus = enumArg(args.reviewStatus, REVIEW_STATUSES$2, "reviewStatus") ?? node.reviewStatus;
11946
11946
  const tags = stringListArg(args.tags, "tags") ?? node.tags;
11947
11947
  const sourceRefs = stringListArg(args.sourceRefs, "sourceRefs") ?? node.sourceRefs;
11948
11948
  const title = (args.title ?? node.title).trim();
@@ -12038,7 +12038,7 @@ async function setOnGraphJson(host, graph, store, args) {
12038
12038
  if (unsupported.length > 0) throw new KnowledgeToolError("invalid", "a graph-json edge only supports type, authority, internalizable and a relation-document body (got " + unsupported.join(", ") + ")", edge.id);
12039
12039
  const type = (args.type ?? edge.type).trim();
12040
12040
  if (type === "") throw new KnowledgeToolError("invalid", "type must not be empty", edge.id);
12041
- const authority = enumArg(args.authority, AUTHORITIES$1, "authority") ?? edge.authority;
12041
+ const authority = enumArg(args.authority, AUTHORITIES$2, "authority") ?? edge.authority;
12042
12042
  const internalizable = booleanArg(args.internalizable, "internalizable") ?? edge.internalizable;
12043
12043
  const body = args.body;
12044
12044
  const changed = [];
@@ -12948,14 +12948,14 @@ function isSummaryDocumentPath(relPath) {
12948
12948
  const isSkippedDirectoryName = (name) => name.startsWith(".") || SKIPPED_DIRECTORIES.has(name);
12949
12949
  /** A hidden file is tool state (`.DS_Store`, editor swap files), not a document. */
12950
12950
  const isHiddenFileName = (name) => name.startsWith(".");
12951
- const isSafeDocumentPath = (value) => {
12951
+ const isSafeDocumentPath$1 = (value) => {
12952
12952
  if (value === "" || value.includes("\0") || value.includes("\\")) return false;
12953
12953
  if (value.startsWith("/") || /^[A-Za-z]:\//u.test(value)) return false;
12954
12954
  return value.split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..");
12955
12955
  };
12956
12956
  const assertSafeDocumentPaths = (values, field) => {
12957
12957
  const unique = [...new Set(values)];
12958
- for (const value of unique) if (!isSafeDocumentPath(value)) throw new Error(`${field} contains an unsafe relative path: ${JSON.stringify(value)}`);
12958
+ for (const value of unique) if (!isSafeDocumentPath$1(value)) throw new Error(`${field} contains an unsafe relative path: ${JSON.stringify(value)}`);
12959
12959
  return unique.sort(compareText$2);
12960
12960
  };
12961
12961
  /**
@@ -13118,7 +13118,7 @@ async function refreshDirtySummaries(input) {
13118
13118
  for (const directory of input.changeSet.dirtyDirectories ?? []) {
13119
13119
  const normalized = directory.replaceAll("\\", "/").replace(/\/+$/u, "");
13120
13120
  if (normalized === "") continue;
13121
- if (!isSafeDocumentPath(normalized)) throw new Error(`changeSet.dirtyDirectories contains an unsafe relative path: ${JSON.stringify(directory)}`);
13121
+ if (!isSafeDocumentPath$1(normalized)) throw new Error(`changeSet.dirtyDirectories contains an unsafe relative path: ${JSON.stringify(directory)}`);
13122
13122
  dirtyDirectories.add(normalized);
13123
13123
  }
13124
13124
  const directories = [];
@@ -16104,1689 +16104,1928 @@ function eligibleForDepartment(scope, departmentCode) {
16104
16104
  return scope.slice(11) === departmentCode;
16105
16105
  }
16106
16106
  //#endregion
16107
- //#region src/memoryContext.ts
16107
+ //#region src/memoryPromotion.ts
16108
16108
  /**
16109
- * Runtime memory context: what the model may see from one user's personal graph.
16109
+ * Promotion of a personal memory or SOP into department/global memory.
16110
16110
  *
16111
- * The personal graph is a projection, not a second copy:
16111
+ * Personal memory is private by construction. Sharing it with a department or the
16112
+ * whole platform is not a copy the guardian makes on its own: it is a product
16113
+ * decision that needs a second pair of eyes (design §17.4, §21.2, §22). This module
16114
+ * owns that decision and its audit trail:
16112
16115
  *
16113
- * - a `subscribe` binding is resolved LIVE from the current department/global
16114
- * graph. The resolver reads the document body from disk on every call and
16115
- * prefers the live frontmatter, so a published change reaches the model
16116
- * without waiting for the guardian or for a binding refresh;
16117
- * - an `internalize` binding is read from the user's own branch at
16118
- * `<usersRoot>/<userId>/memory/<graphId>/<sourceId>.md`. That branch does not
16119
- * follow the source; `stale` / `revoked` come from the binding so the runtime
16120
- * can down-rank or hide it;
16121
- * - visibility is decided per graph through `canViewGraph`. A graph, node or
16122
- * edge the viewer cannot see is omitted, never partially projected;
16123
- * - redlines are marked `nonOverridable` with an explicit marker. The character
16124
- * budget drops advisory material first and never drops a redline.
16116
+ * - a promotion is a durable record with a **pending → approved | rejected**
16117
+ * lifecycle; a rejected or approved record is never silently rewritten;
16118
+ * - only a caller who already holds review authority for the target scope may
16119
+ * create or decide one — `kb:config:manage` for global, the department review
16120
+ * scope for `department:<code>`;
16121
+ * - a request can never be approved by the person who made it. An administrator
16122
+ * who wants their own memory shared uses the explicit `confirm` path, which is a
16123
+ * different, separately-audited action;
16124
+ * - only `privacy: normal` content is promotable. `private`, `sensitive` and
16125
+ * `secret` memories are refused rather than downgraded, because a promotion is
16126
+ * an irreversible widening of who can read them;
16127
+ * - approval writes a real shared memory document and a graph node under the
16128
+ * target scope, so the existing knowledge-base permissions (not this module)
16129
+ * decide who can read it.
16125
16130
  *
16126
- * Ordering is deterministic (priority tier, graph id, source type, source id),
16127
- * so two identical inputs produce the same prompt prefix.
16131
+ * The store is product metadata (a review queue), not knowledge content: it lives
16132
+ * beside the per-user binding state, never inside a document tree, and holds one
16133
+ * JSON file committed by atomic rename.
16128
16134
  *
16129
- * @module @sparkelf/dsh-knowledge-base/memory-context
16135
+ * @module @sparkelf/dsh-knowledge-base/memory-promotion
16130
16136
  */
16131
- /** Default prompt budget for the resolved context. */
16132
- const DEFAULT_MEMORY_CONTEXT_MAX_CHARS = 8e3;
16133
- /** Marker the runtime must treat as above personal memory and preferences. */
16134
- const SYSTEM_POLICY_MARKER = "system policy overrides personal memory";
16135
- /** The fixed per-entry metadata overhead included in `chars`. */
16136
- const ENTRY_METADATA_CHARS = 32;
16137
- const AUTHORITY_RANK = {
16138
- advisory: 0,
16139
- canonical: 1,
16140
- redline: 2
16137
+ /** Graph id that owns promoted department/global memory inside one scope. */
16138
+ const SHARED_MEMORY_GRAPH_ID = "shared-memory";
16139
+ /** Folder (relative to the scope root) that holds one document per promotion. */
16140
+ const SHARED_MEMORY_FOLDER = "记忆共享";
16141
+ /** Display name per graph scope. */
16142
+ function sharedMemoryGraphName(scope) {
16143
+ return scope === "global" ? "全局共享记忆" : "部门共享记忆";
16144
+ }
16145
+ /** A structured refusal the route maps to a status code. */
16146
+ var MemoryPromotionError = class extends Error {
16147
+ code;
16148
+ name = "MemoryPromotionError";
16149
+ constructor(code, message) {
16150
+ super(message);
16151
+ this.code = code;
16152
+ }
16141
16153
  };
16142
- const AUTHORITIES = [
16143
- "canonical",
16144
- "advisory",
16145
- "redline"
16146
- ];
16147
- const ORIGINS = [
16148
- "human",
16149
- "ai",
16150
- "mixed"
16151
- ];
16152
- const REVIEW_STATUSES = [
16153
- "draft",
16154
- "reviewed",
16155
- "approved"
16156
- ];
16157
- /**
16158
- * Adapt a loaded graph manifest to the visibility descriptor `canViewGraph`
16159
- * expects. `scope` is the machine scope (`global`, `department:<code>`,
16160
- * `personal:<uid>`); `owner` is the private-graph owner when present.
16161
- */
16162
- function graphScopeDescriptor(manifest) {
16163
- const scope = manifest.scope ?? "";
16164
- const departmentPrefix = "department:";
16165
- const personalPrefix = "personal:";
16166
- const departmentCode = scope.startsWith(departmentPrefix) ? scope.slice(11) : void 0;
16167
- const ownerId = manifest.visibility === "private" ? manifest.owner ?? (scope.startsWith(personalPrefix) ? scope.slice(9) : void 0) : void 0;
16154
+ /** The submitter may request a promotion only inside a scope they can review. */
16155
+ function decidePromotionScope(reviewer, scope, departmentCode) {
16156
+ if (scope === "global") {
16157
+ if (!reviewer.isGlobalAdmin || !reviewer.canManageConfig) return {
16158
+ ok: false,
16159
+ code: "forbidden",
16160
+ message: "只有管理员/超级管理员可以把记忆晋升到全局。"
16161
+ };
16162
+ return { ok: true };
16163
+ }
16164
+ const code = (departmentCode ?? reviewer.departmentCode ?? "").trim();
16165
+ if (code === "") return {
16166
+ ok: false,
16167
+ code: "invalid",
16168
+ message: "晋升到部门必须指定部门。"
16169
+ };
16170
+ if (reviewer.departmentCode === void 0 || code !== reviewer.departmentCode) return {
16171
+ ok: false,
16172
+ code: "forbidden",
16173
+ message: "只能晋升到当前账号所属部门。"
16174
+ };
16175
+ if (!reviewer.isGlobalAdmin && !reviewer.reviewDepartments.includes(code)) return {
16176
+ ok: false,
16177
+ code: "forbidden",
16178
+ message: "只能晋升到本部门管理范围内的记忆。"
16179
+ };
16168
16180
  return {
16169
- visibility: manifest.visibility,
16170
- ownerId,
16171
- departmentCode
16181
+ ok: true,
16182
+ departmentCode: code,
16183
+ departmentPath: reviewer.departmentPathCodes !== void 0 && reviewer.departmentPathCodes.length > 0 ? [...reviewer.departmentPathCodes] : [code]
16172
16184
  };
16173
16185
  }
16186
+ /** Whether one reviewer may decide a promotion aimed at its target scope. */
16187
+ function canReviewPromotion(reviewer, target) {
16188
+ if (target.scope === "global") return reviewer.isGlobalAdmin;
16189
+ const code = target.departmentCode ?? "";
16190
+ if (code === "") return false;
16191
+ return reviewer.isGlobalAdmin || reviewer.reviewDepartments.includes(code);
16192
+ }
16174
16193
  /**
16175
- * Resolve the caller's personal memory context.
16194
+ * Whether one approved promotion is visible to a viewer.
16176
16195
  *
16177
- * @param input - viewer, roots, user id, loaded graphs and optional budget.
16178
- * @returns Priority-ordered entries, budget drops and redline counters.
16196
+ * A department promotion is visible to the viewer whose organization path contains
16197
+ * that department (own department and its ancestors) or whose data scope names it.
16198
+ * The source owner always keeps seeing their own approved memory.
16179
16199
  */
16180
- async function resolveMemoryContext(input) {
16181
- const maxChars = normalizeMaxChars(input.maxChars);
16182
- const graphById = /* @__PURE__ */ new Map();
16183
- for (const graph of input.graphs) if (!graphById.has(graph.manifest.id)) graphById.set(graph.manifest.id, graph);
16184
- const bindings = input.bindings ?? await new BindingStore(input.usersRoot).list(input.userId);
16185
- const entries = [];
16186
- const bindingIds = /* @__PURE__ */ new Set();
16187
- const bindingContent = /* @__PURE__ */ new Set();
16188
- for (const binding of bindings) {
16189
- if (binding.userId !== input.userId) continue;
16190
- if (binding.mode !== "subscribe" && binding.mode !== "internalize") continue;
16191
- const graph = graphById.get(binding.graphId);
16192
- if (graph === void 0) continue;
16193
- if (!canViewGraph(input.viewer, graphScopeDescriptor(graph.manifest))) continue;
16194
- const entry = binding.mode === "subscribe" ? await resolveSubscribedEntry(binding, graph) : await resolveInternalizedEntry(binding, graph, input.usersRoot);
16195
- if (entry === void 0) continue;
16196
- entries.push(entry);
16197
- bindingIds.add(entry.sourceId);
16198
- bindingContent.add(contentFingerprint(entry.title, entry.body));
16200
+ function isPromotionVisibleTo(record, viewer) {
16201
+ if (record.target.scope === "global") return true;
16202
+ if (record.source.userId === viewer.userId) return true;
16203
+ if (viewer.isGlobalAdmin) return true;
16204
+ const code = record.target.departmentCode ?? "";
16205
+ if (code === "") return false;
16206
+ if (viewer.departmentCode === code) return true;
16207
+ if (viewer.departmentPathCodes?.includes(code) === true) return true;
16208
+ if (viewer.visibleDepartmentCodes?.includes(code) === true) return true;
16209
+ return viewer.reviewDepartments.includes(code);
16210
+ }
16211
+ /**
16212
+ * The scope root one target writes under, WITHOUT a trailing slash.
16213
+ *
16214
+ * DataOps grants are matched against this exact resource id (a trailing slash is a
16215
+ * different id and matches nothing), so every permission question must use this
16216
+ * spelling. Directory joining adds the slash separately.
16217
+ */
16218
+ function targetScopeRoot(target) {
16219
+ if (target.scope === "global") return "global";
16220
+ return "department/" + (target.departmentPath !== void 0 && target.departmentPath.length > 0 ? target.departmentPath : target.departmentCode === void 0 ? [] : [target.departmentCode]).join("/");
16221
+ }
16222
+ /** The scope-relative prefix one target writes under (`global/`, `department/A/B/`). */
16223
+ function targetScopePrefix(target) {
16224
+ return targetScopeRoot(target) + "/";
16225
+ }
16226
+ /** Where the review queue lives for one deployment's per-user memory root. */
16227
+ function promotionStorePath(memoryUsersRoot) {
16228
+ return join(dirname(resolve(memoryUsersRoot)), "promotions.json");
16229
+ }
16230
+ /** Map a stored memory type onto the graph's smaller node vocabulary. */
16231
+ function sharedNodeTypeOf(type) {
16232
+ switch (type) {
16233
+ case "preference": return "topic";
16234
+ case "pitfall": return "case";
16235
+ case "episodic": return "case";
16236
+ case "fact": return "fact";
16237
+ case "sop": return "procedure";
16199
16238
  }
16200
- const personalMemoryRoot = input.personalMemoryRoot?.trim() ?? "";
16201
- if (personalMemoryRoot !== "") entries.push(...await resolvePersonalMemoryEntries(personalMemoryRoot, bindingIds, bindingContent));
16202
- entries.sort(compareEntries);
16203
- const selected = [];
16204
- const dropped = [];
16205
- let charCount = 0;
16206
- for (const entry of entries) {
16207
- if (!(entry.nonOverridable || entry.authority === "redline") && charCount + entry.chars > maxChars) {
16208
- dropped.push({
16209
- graphId: entry.graphId,
16210
- sourceType: entry.sourceType,
16211
- sourceId: entry.sourceId,
16212
- mode: entry.mode,
16213
- chars: entry.chars,
16214
- reason: "budget"
16215
- });
16216
- continue;
16239
+ }
16240
+ /** The text a promotion copies into the shared document. */
16241
+ function promotionContentOf(entry) {
16242
+ switch (entry.type) {
16243
+ case "preference": return entry.value;
16244
+ case "pitfall": return [
16245
+ "现象:" + entry.errorSignature,
16246
+ "原因:" + entry.context,
16247
+ "解决:" + entry.solution
16248
+ ].join("\n\n");
16249
+ case "episodic": return entry.summary;
16250
+ case "fact": return entry.statement;
16251
+ case "sop": {
16252
+ const parts = ["触发条件:" + entry.trigger, entry.steps.map((step, index) => `${String(index + 1)}. ${step}`).join("\n")];
16253
+ if (entry.successCriteria !== void 0 && entry.successCriteria.length > 0) parts.push(entry.successCriteria.map((item) => "- " + item).join("\n"));
16254
+ return parts.join("\n\n");
16217
16255
  }
16218
- selected.push(entry);
16219
- charCount += entry.chars;
16220
16256
  }
16221
- const redlineCount = selected.filter((entry) => entry.nonOverridable).length;
16222
- const personalCount = selected.filter((entry) => entry.mode === "personal").length;
16223
- return {
16224
- userId: input.userId,
16225
- entries: selected,
16226
- dropped,
16227
- charCount,
16228
- maxChars,
16229
- redlineCount,
16230
- personalCount,
16231
- systemPolicy: redlineCount > 0 ? SYSTEM_POLICY_MARKER : ""
16232
- };
16233
16257
  }
16234
- /** Render a resolved context for a model-facing text tool result. */
16235
- function renderMemoryContextMarkdown(result) {
16236
- const lines = [
16237
- `# Memory context (${result.userId})`,
16238
- "",
16239
- `- entries: ${result.entries.length}; chars: ${result.charCount}/${result.maxChars}; redlines: ${result.redlineCount}; personal: ${result.personalCount}`
16240
- ];
16241
- if (result.systemPolicy !== "") lines.push(`- ${result.systemPolicy}`);
16242
- for (const entry of result.entries) {
16243
- const marker = entry.nonOverridable ? "[REDLINE] " : entry.mode === "personal" ? "[PERSONAL] " : "";
16244
- lines.push("", `## ${marker}${entry.title}`, "");
16245
- if (entry.mode === "personal") {
16246
- lines.push(`- mode: personal; type: ${entry.type}; privacy: ${entry.privacy ?? "private"}`);
16247
- if (entry.path !== void 0) lines.push(`- path: ${entry.path}`);
16248
- } else {
16249
- lines.push(`- mode: ${entry.mode}; source: ${entry.sourceType} \`${entry.sourceId}\` in graph \`${entry.graphId}\``);
16250
- lines.push(`- status: ${entry.status}; authority: ${entry.authority}; origin: ${entry.origin}; review: ${entry.reviewStatus}`);
16251
- lines.push(`- source version: ${entry.sourceVersion}${entry.sourceCommit === void 0 ? "" : ` (${entry.sourceCommit})`}`);
16252
- if (entry.path !== void 0) lines.push(`- path: ${entry.path}`);
16253
- if (entry.from !== void 0 && entry.to !== void 0) lines.push(`- relation: ${entry.from} -> ${entry.to}`);
16254
- }
16255
- if (entry.nonOverridable) lines.push(`- ${SYSTEM_POLICY_MARKER}`);
16256
- lines.push("", entry.body);
16257
- }
16258
- if (result.dropped.length > 0) {
16259
- lines.push("", "## Dropped by budget");
16260
- for (const drop of result.dropped) lines.push(`- ${drop.mode} ${drop.sourceType} \`${drop.sourceId}\` in graph \`${drop.graphId}\` (${drop.chars} chars)`);
16258
+ /** The short title a shared row shows; mirrors the personal page's rules. */
16259
+ function promotionTitleOf(entry) {
16260
+ if (typeof entry.displayTitle === "string" && entry.displayTitle.trim() !== "") return clipTitle(entry.displayTitle.trim());
16261
+ switch (entry.type) {
16262
+ case "preference": return looksTechnical(entry.value) ? "偏好记录" : clipTitle(entry.value);
16263
+ case "pitfall": return looksTechnical(entry.errorSignature) ? "踩坑记录" : clipTitle(entry.errorSignature);
16264
+ case "episodic":
16265
+ if (entry.tags?.includes("SOP评估")) return "方法评估";
16266
+ if (entry.tags?.includes("SOP晋升")) return "方法晋升";
16267
+ if (entry.tags?.includes("idle")) return "空闲触发";
16268
+ if (entry.tags?.includes("compaction")) return "压缩触发";
16269
+ if (entry.tags?.includes("dream")) return "记忆整理";
16270
+ return "情景记录";
16271
+ case "fact": return looksTechnical(entry.key) ? "事实记录" : clipTitle(entry.key);
16272
+ case "sop": return clipTitle(entry.title);
16261
16273
  }
16262
- return `${lines.join("\n")}\n`;
16263
16274
  }
16264
- async function resolveSubscribedEntry(binding, graph) {
16265
- const graphId = graph.manifest.id;
16266
- const sourceVersion = graph.manifest.version;
16267
- const sourceCommit = graphCommit(graph) ?? binding.sourceCommit;
16268
- if (binding.sourceType === "node") {
16269
- const node = graph.nodes.find((candidate) => candidate.id === binding.sourceId);
16270
- if (node === void 0 || node.missing) return void 0;
16271
- const document = await readGraphDocument(graph.root, node.path);
16272
- if (document === void 0) return void 0;
16273
- const live = readDocumentAttributes(document.frontMatter);
16274
- const title = live.title ?? node.title ?? node.id;
16275
- const body = document.body.trim();
16276
- return finalizeEntry({
16277
- mode: "subscribe",
16278
- graphId,
16279
- sourceType: "node",
16280
- sourceId: node.id,
16281
- title,
16282
- type: live.type ?? node.type,
16283
- authority: live.authority ?? node.authority,
16284
- origin: live.origin ?? node.origin,
16285
- reviewStatus: live.reviewStatus ?? node.reviewStatus,
16286
- status: binding.status,
16287
- sourceVersion,
16288
- ...sourceCommit === void 0 ? {} : { sourceCommit },
16289
- path: node.path,
16290
- body
16291
- });
16292
- }
16293
- const edge = graph.edges.find((candidate) => candidate.id === binding.sourceId);
16294
- if (edge === void 0 || edge.missing) return void 0;
16295
- const from = graph.nodes.find((node) => node.id === edge.from);
16296
- const to = graph.nodes.find((node) => node.id === edge.to);
16297
- if (from === void 0 || to === void 0) return void 0;
16298
- const document = await readGraphDocument(graph.root, edge.docPath);
16299
- if (document === void 0) return void 0;
16300
- const live = readDocumentAttributes(document.frontMatter);
16301
- const authority = strictestAuthority(live.authority ?? edge.authority, from.authority, to.authority);
16302
- const body = document.body.trim();
16303
- return finalizeEntry({
16304
- mode: "subscribe",
16305
- graphId,
16306
- sourceType: "edge",
16307
- sourceId: edge.id,
16308
- title: live.title ?? edge.title ?? edge.id,
16309
- type: live.type ?? edge.type,
16310
- authority,
16311
- origin: live.origin ?? edge.origin,
16312
- reviewStatus: live.reviewStatus ?? edge.reviewStatus,
16313
- status: binding.status,
16314
- sourceVersion,
16315
- ...sourceCommit === void 0 ? {} : { sourceCommit },
16316
- ...edge.docPath === void 0 ? {} : { path: edge.docPath },
16317
- from: edge.from,
16318
- to: edge.to,
16319
- body
16320
- });
16275
+ /** Whitespace-collapsed, bounded title; never a technical identifier on its own. */
16276
+ function clipTitle(value) {
16277
+ const clean = value.replace(/\s+/gu, " ").trim();
16278
+ return clean.length <= 40 ? clean : `${clean.slice(0, 39)}…`;
16321
16279
  }
16322
- async function resolveInternalizedEntry(binding, graph, usersRoot) {
16323
- let source;
16280
+ /** A technical token that should not be the first thing a reader sees in a row. */
16281
+ function looksTechnical(value) {
16282
+ if (/[\\/]|session-|kb_[a-z]|\.md\b|\bSOP\b|[a-z]+_[a-z]+/iu.test(value)) return true;
16283
+ return value.trim().length > 12 && /^[a-z0-9._-]+$/u.test(value.trim());
16284
+ }
16285
+ const EMPTY_STORE = {
16286
+ version: 1,
16287
+ promotions: []
16288
+ };
16289
+ const writeQueues = /* @__PURE__ */ new Map();
16290
+ /** Serialize mutations of one store path so two requests cannot overwrite each other. */
16291
+ function serialize(path, operation) {
16292
+ const next = (writeQueues.get(path) ?? Promise.resolve()).then(operation, operation);
16293
+ writeQueues.set(path, next.then(() => void 0, () => void 0));
16294
+ return next;
16295
+ }
16296
+ /** Read the queue, treating absence as empty and quarantining corrupt JSON. */
16297
+ async function readPromotionStore(path) {
16298
+ let raw;
16324
16299
  try {
16325
- source = await readFile(memoryFilePath(usersRoot, binding.userId, binding.graphId, binding.sourceId), "utf8");
16326
- } catch {
16327
- return;
16300
+ raw = await readFile(path, "utf8");
16301
+ } catch (error) {
16302
+ if (error.code === "ENOENT") return EMPTY_STORE;
16303
+ throw new MemoryPromotionError("io", `could not read ${path}: ${String(error)}`);
16328
16304
  }
16329
- const document = splitFrontMatter(source);
16330
- const local = readDocumentAttributes(document.frontMatter);
16331
- const current = currentSourcePolicy(binding, graph);
16332
- const authority = strictestAuthority(local.authority ?? "advisory", current.authority);
16333
- const body = document.body.trim();
16334
- return finalizeEntry({
16335
- mode: "internalize",
16336
- graphId: binding.graphId,
16337
- sourceType: binding.sourceType,
16338
- sourceId: binding.sourceId,
16339
- title: local.title ?? current.title ?? binding.sourceId,
16340
- type: local.type ?? current.type,
16341
- authority,
16342
- origin: local.origin ?? current.origin,
16343
- reviewStatus: local.reviewStatus ?? current.reviewStatus,
16344
- status: binding.status,
16345
- sourceVersion: binding.sourceVersion,
16346
- ...binding.sourceCommit === void 0 ? {} : { sourceCommit: binding.sourceCommit },
16347
- path: binding.localPath ?? `memory/${binding.graphId}/${binding.sourceId}.md`,
16348
- ...current.from === void 0 ? {} : { from: current.from },
16349
- ...current.to === void 0 ? {} : { to: current.to },
16350
- body,
16351
- nonOverridable: current.authority === "redline"
16352
- });
16353
- }
16354
- /**
16355
- * Privacy levels that may enter a model-facing context.
16356
- *
16357
- * The resolver only reads the caller's own root, so `normal` and `private` stay
16358
- * owner-scoped. `sensitive` is deliberately excluded: the design says owner-only
16359
- * *and* redacted in logs/telemetry, and a tool result is part of the session
16360
- * transcript. `secret` is a credential pointer, not memory content; the model
16361
- * does not need it. Both remain readable on the memory page.
16362
- */
16363
- const CONTEXT_PRIVACY = /* @__PURE__ */ new Set(["normal", "private"]);
16364
- /**
16365
- * Resolve the caller's current `MemoryStore` entries as advisory context.
16366
- *
16367
- * Current aggregate snapshots and SOPs are the effective memory; daily-log
16368
- * entries are included as episodic history but rank below the aggregates. An
16369
- * entry that another entry `supersedes` is historical and is skipped, as is an
16370
- * entry already represented by a binding.
16371
- *
16372
- * @param memoryRoot - the caller's own `<scope>/个人记忆图谱` directory.
16373
- * @param bindingIds - source ids already resolved from bindings.
16374
- * @param bindingContent - title+body fingerprints already resolved from bindings.
16375
- */
16376
- async function resolvePersonalMemoryEntries(memoryRoot, bindingIds, bindingContent) {
16377
- const store = new MemoryStore(memoryRoot);
16378
- let listed;
16379
16305
  try {
16380
- listed = await store.listEntries();
16306
+ const parsed = JSON.parse(raw);
16307
+ if (parsed === null || typeof parsed !== "object") throw new Error("not an object");
16308
+ const candidate = parsed;
16309
+ if (candidate.version !== 1 || !Array.isArray(candidate.promotions)) throw new Error("wrong shape");
16310
+ return {
16311
+ version: 1,
16312
+ promotions: candidate.promotions
16313
+ };
16381
16314
  } catch {
16382
- return [];
16383
- }
16384
- const superseded = /* @__PURE__ */ new Set();
16385
- for (const entry of listed) if (entry.supersedes !== void 0 && entry.supersedes !== "") superseded.add(entry.supersedes);
16386
- const seenIds = new Set(bindingIds);
16387
- const seenContent = new Set(bindingContent);
16388
- const entries = [];
16389
- for (const entry of listed) {
16390
- if (superseded.has(entry.id)) continue;
16391
- if (!CONTEXT_PRIVACY.has(entry.privacy)) continue;
16392
- if (entry.type === "sop" && (entry.status === "dropped" || entry.status === "promoted")) continue;
16393
- const title = memoryEntryTitle(entry);
16394
- const body = personalEntryBody(entry);
16395
- if (title.trim() === "" || body.trim() === "") continue;
16396
- const fingerprint = contentFingerprint(title, body);
16397
- if (seenIds.has(entry.id) || seenContent.has(fingerprint)) continue;
16398
- seenIds.add(entry.id);
16399
- seenContent.add(fingerprint);
16400
- entries.push(finalizePersonalEntry(entry, title, body));
16315
+ await rename(path, `${path}.corrupt-${String(Date.now())}`).catch(() => void 0);
16316
+ return EMPTY_STORE;
16401
16317
  }
16402
- return entries;
16403
16318
  }
16404
- /** Map one store entry to the context shape; personal memory is always advisory. */
16405
- function finalizePersonalEntry(entry, title, body) {
16319
+ /** Commit the queue atomically. */
16320
+ async function writePromotionStore(path, store) {
16321
+ await writeFileAtomic(path, JSON.stringify(store, null, 2) + "\n");
16322
+ }
16323
+ /** Read every promotion, oldest first. */
16324
+ async function listPromotionRecords(path) {
16325
+ return (await readPromotionStore(path)).promotions;
16326
+ }
16327
+ const MAX_TITLE = 200;
16328
+ const MAX_CONTENT = 2e4;
16329
+ /** Reject a request that cannot be shared safely or written to a graph. */
16330
+ function normalizePromotionDraft(draft) {
16331
+ if (draft.source.privacy !== "normal") throw new MemoryPromotionError("privacy", "只有隐私为「普通」的记忆可以晋升;仅自己、敏感和凭据引用不会被共享。");
16332
+ const title = draft.source.title.trim();
16333
+ if (title === "" || title.length > MAX_TITLE) throw new MemoryPromotionError("invalid", `a promotion title must be 1–${String(MAX_TITLE)} characters`);
16334
+ const content = draft.source.content.trim();
16335
+ if (content === "" || content.length > MAX_CONTENT) throw new MemoryPromotionError("invalid", `a promotion body must be 1–${String(MAX_CONTENT)} characters`);
16336
+ if (draft.target.scope === "department" && (draft.target.departmentCode ?? "").trim() === "") throw new MemoryPromotionError("invalid", "a department promotion needs a department code");
16406
16337
  return {
16407
- mode: "personal",
16408
- graphId: PERSONAL_MEMORY_GRAPH_ID,
16409
- sourceType: "entry",
16410
- sourceId: entry.id,
16411
- title,
16412
- type: entry.type,
16413
- authority: "advisory",
16414
- origin: entry.origin === "explicit" ? "mixed" : "ai",
16415
- reviewStatus: "draft",
16416
- status: "active",
16417
- sourceVersion: entry.type === "sop" ? entry.version : 1,
16418
- path: entry.path,
16419
- privacy: entry.privacy,
16420
- updatedAt: memoryEntryUpdatedAt(entry),
16421
- body,
16422
- nonOverridable: false,
16423
- chars: title.length + body.length + ENTRY_METADATA_CHARS
16338
+ source: {
16339
+ ...draft.source,
16340
+ title,
16341
+ content
16342
+ },
16343
+ target: draft.target
16424
16344
  };
16425
16345
  }
16426
- /**
16427
- * Model-facing body for one entry.
16428
- *
16429
- * Only user content is rendered: `sourceSession`, `evidence`, `credentialRef`
16430
- * and other internal pointers are deliberately absent.
16431
- */
16432
- function personalEntryBody(entry) {
16433
- const content = memoryEntryContent(entry).trim();
16434
- switch (entry.type) {
16435
- case "preference": {
16436
- const lines = [];
16437
- if (entry.app !== void 0 && entry.app !== "") lines.push(`app: ${entry.app}`);
16438
- lines.push(`topic: ${entry.topic}`, content);
16439
- return lines.join("\n");
16440
- }
16441
- case "pitfall": {
16442
- const lines = [
16443
- `error: ${entry.errorSignature}`,
16444
- `context: ${entry.context}`,
16445
- `solution: ${content}`
16446
- ];
16447
- if (entry.appliesTo !== void 0 && entry.appliesTo.length > 0) lines.push(`applies to: ${entry.appliesTo.join(", ")}`);
16448
- return lines.join("\n");
16449
- }
16450
- case "fact": {
16451
- const lines = [];
16452
- if (entry.scope !== void 0 && entry.scope !== "") lines.push(`scope: ${entry.scope}`);
16453
- lines.push(`key: ${entry.key}`, `statement: ${content}`);
16454
- return lines.join("\n");
16455
- }
16456
- case "episodic": {
16457
- const lines = [`summary: ${content}`];
16458
- if (entry.request !== void 0 && entry.request !== "") lines.push(`request: ${entry.request}`);
16459
- if (entry.outcome !== void 0 && entry.outcome !== "") lines.push(`outcome: ${entry.outcome}`);
16460
- return lines.join("\n");
16461
- }
16462
- case "sop": {
16463
- const lines = [
16464
- `status: ${entry.status}; version: ${String(entry.version)}`,
16465
- `trigger: ${entry.trigger}`,
16466
- "steps:",
16467
- content
16468
- ];
16469
- if (entry.successCriteria !== void 0 && entry.successCriteria.length > 0) lines.push("success criteria:", ...entry.successCriteria.map((item) => `- ${item}`));
16470
- if (entry.tools !== void 0 && entry.tools.length > 0) lines.push(`tools: ${entry.tools.join(", ")}`);
16471
- return lines.join("\n");
16472
- }
16473
- }
16474
- }
16475
- /** Identity of content used to avoid injecting the same memory twice. */
16476
- function contentFingerprint(title, body) {
16477
- const normalize = (value) => value.replace(/\s+/gu, " ").trim();
16478
- return `${normalize(title)}\u0000${normalize(body)}`;
16479
- }
16480
- /** Current graph-side policy for a binding's source; absent source falls back to advisory. */
16481
- function currentSourcePolicy(binding, graph) {
16482
- if (binding.sourceType === "node") {
16483
- const node = graph.nodes.find((candidate) => candidate.id === binding.sourceId);
16484
- if (node === void 0) return {
16485
- authority: "advisory",
16486
- type: "fact",
16487
- origin: "human",
16488
- reviewStatus: "draft"
16346
+ /** Create one pending request, or return the identical pending one. */
16347
+ async function createPromotionRequest(path, draft, actor, now = () => /* @__PURE__ */ new Date()) {
16348
+ const normalized = normalizePromotionDraft(draft);
16349
+ return serialize(path, async () => {
16350
+ const store = await readPromotionStore(path);
16351
+ const duplicate = store.promotions.find((item) => item.status === "pending" && item.source.userId === normalized.source.userId && item.source.memoryId === normalized.source.memoryId && item.target.scope === normalized.target.scope && (item.target.departmentCode ?? "") === (normalized.target.departmentCode ?? ""));
16352
+ if (duplicate !== void 0) return {
16353
+ record: duplicate,
16354
+ duplicate: true
16355
+ };
16356
+ const at = now().toISOString();
16357
+ const id = "mp-" + randomUUID();
16358
+ const record = {
16359
+ id,
16360
+ status: "pending",
16361
+ source: normalized.source,
16362
+ target: {
16363
+ ...normalized.target,
16364
+ docPath: `${SHARED_MEMORY_FOLDER}/${id}.md`
16365
+ },
16366
+ requestedBy: actor,
16367
+ requestedAt: at,
16368
+ confirmed: false,
16369
+ audit: [{
16370
+ at,
16371
+ actorId: actor.id,
16372
+ actorName: actor.name,
16373
+ action: "requested",
16374
+ detail: {
16375
+ scope: normalized.target.scope,
16376
+ ...normalized.target.departmentCode === void 0 ? {} : { departmentCode: normalized.target.departmentCode },
16377
+ targetGraph: normalized.target.graphId,
16378
+ memoryId: normalized.source.memoryId
16379
+ }
16380
+ }]
16489
16381
  };
16382
+ await writePromotionStore(path, {
16383
+ version: 1,
16384
+ promotions: [...store.promotions, record]
16385
+ });
16490
16386
  return {
16491
- authority: node.authority,
16492
- title: node.title,
16493
- type: node.type,
16494
- origin: node.origin,
16495
- reviewStatus: node.reviewStatus
16387
+ record,
16388
+ duplicate: false
16496
16389
  };
16497
- }
16498
- const edge = graph.edges.find((candidate) => candidate.id === binding.sourceId);
16499
- if (edge === void 0) return {
16500
- authority: "advisory",
16501
- type: "relates_to",
16502
- origin: "human",
16503
- reviewStatus: "draft"
16504
- };
16505
- const from = graph.nodes.find((node) => node.id === edge.from);
16506
- const to = graph.nodes.find((node) => node.id === edge.to);
16507
- return {
16508
- authority: strictestAuthority(edge.authority, from?.authority, to?.authority),
16509
- title: edge.title,
16510
- type: edge.type,
16511
- origin: edge.origin,
16512
- reviewStatus: edge.reviewStatus,
16513
- from: edge.from,
16514
- to: edge.to
16515
- };
16390
+ });
16516
16391
  }
16517
- function finalizeEntry(input) {
16518
- const nonOverridable = input.nonOverridable ?? input.authority === "redline";
16519
- return {
16520
- ...input,
16521
- nonOverridable,
16522
- ...nonOverridable ? { policyNote: SYSTEM_POLICY_MARKER } : {},
16523
- chars: input.title.length + input.body.length + ENTRY_METADATA_CHARS
16524
- };
16392
+ /** Load one promotion by id. */
16393
+ async function getPromotionRecord(path, id) {
16394
+ return (await readPromotionStore(path)).promotions.find((item) => item.id === id);
16525
16395
  }
16526
- /** Read a graph-relative document body and frontmatter; missing bodies fail closed. */
16527
- async function readGraphDocument(root, relPath) {
16528
- if (relPath === void 0 || relPath === "") return {
16529
- frontMatter: null,
16530
- body: ""
16531
- };
16532
- const candidates = [];
16533
- if (isAbsolute(relPath)) candidates.push(relPath);
16534
- else {
16535
- if (relPath.split("/").some((segment) => segment === ".." || segment === "")) return void 0;
16536
- candidates.push(join(root, relPath));
16537
- candidates.push(join(root, "..", "..", relPath));
16538
- }
16539
- for (const candidate of candidates) try {
16540
- return splitFrontMatter(await readFile(candidate, "utf8"));
16541
- } catch {}
16396
+ /** Mark one pending promotion approved after its shared document is on disk. */
16397
+ async function markPromotionApproved(path, id, reviewer, appliedPath, options, now = () => /* @__PURE__ */ new Date()) {
16398
+ return serialize(path, async () => {
16399
+ const store = await readPromotionStore(path);
16400
+ const record = store.promotions.find((item) => item.id === id);
16401
+ if (record === void 0) throw new MemoryPromotionError("not-found", `no promotion with id ${id}`);
16402
+ if (record.status !== "pending") throw new MemoryPromotionError("conflict", `promotion ${id} is already ${record.status}`);
16403
+ const at = now().toISOString();
16404
+ const next = {
16405
+ ...record,
16406
+ status: "approved",
16407
+ reviewedBy: reviewer,
16408
+ reviewedAt: at,
16409
+ confirmed: options.confirmed,
16410
+ appliedAt: at,
16411
+ ...options.note === void 0 || options.note.trim() === "" ? {} : { reviewNote: options.note.trim() },
16412
+ audit: [...record.audit, {
16413
+ at,
16414
+ actorId: reviewer.id,
16415
+ actorName: reviewer.name,
16416
+ action: options.confirmed ? "confirmed" : "approved",
16417
+ detail: {
16418
+ appliedPath,
16419
+ scope: record.target.scope
16420
+ }
16421
+ }]
16422
+ };
16423
+ await writePromotionStore(path, {
16424
+ version: 1,
16425
+ promotions: store.promotions.map((item) => item.id === id ? next : item)
16426
+ });
16427
+ return next;
16428
+ });
16542
16429
  }
16543
- /** Parse the attributes the runtime injection reads, tolerating extra keys. */
16544
- function readDocumentAttributes(frontMatter) {
16545
- if (frontMatter === null || frontMatter.trim() === "") return {};
16546
- const record = parseSimpleYaml(frontMatter);
16547
- const text = (key) => {
16548
- const value = record[key];
16549
- return typeof value === "string" && value !== "" ? value : void 0;
16550
- };
16551
- const authority = text("authority");
16552
- const origin = text("origin");
16553
- const reviewStatus = text("reviewStatus");
16554
- return {
16555
- ...text("title") === void 0 ? {} : { title: text("title") },
16556
- ...text("type") === void 0 ? {} : { type: text("type") },
16557
- ...authority !== void 0 && AUTHORITIES.includes(authority) ? { authority } : {},
16558
- ...origin !== void 0 && ORIGINS.includes(origin) ? { origin } : {},
16559
- ...reviewStatus !== void 0 && REVIEW_STATUSES.includes(reviewStatus) ? { reviewStatus } : {}
16560
- };
16430
+ /** Mark one pending promotion rejected, keeping the reason. */
16431
+ async function markPromotionRejected(path, id, reviewer, note, now = () => /* @__PURE__ */ new Date()) {
16432
+ return serialize(path, async () => {
16433
+ const store = await readPromotionStore(path);
16434
+ const record = store.promotions.find((item) => item.id === id);
16435
+ if (record === void 0) throw new MemoryPromotionError("not-found", `no promotion with id ${id}`);
16436
+ if (record.status !== "pending") throw new MemoryPromotionError("conflict", `promotion ${id} is already ${record.status}`);
16437
+ const at = now().toISOString();
16438
+ const next = {
16439
+ ...record,
16440
+ status: "rejected",
16441
+ reviewedBy: reviewer,
16442
+ reviewedAt: at,
16443
+ ...note === void 0 || note.trim() === "" ? {} : { reviewNote: note.trim() },
16444
+ audit: [...record.audit, {
16445
+ at,
16446
+ actorId: reviewer.id,
16447
+ actorName: reviewer.name,
16448
+ action: "rejected",
16449
+ ...note === void 0 || note.trim() === "" ? {} : { detail: { note: note.trim() } }
16450
+ }]
16451
+ };
16452
+ await writePromotionStore(path, {
16453
+ version: 1,
16454
+ promotions: store.promotions.map((item) => item.id === id ? next : item)
16455
+ });
16456
+ return next;
16457
+ });
16561
16458
  }
16562
- /**
16563
- * Priority tiers: redline, canonical, advisory proxies, personal effective
16564
- * memory, personal episodic history, advisory internalized.
16565
- *
16566
- * Department/global canonical and advisory sources outrank personal memory so a
16567
- * department rule or definition wins a conflict. Advisory internalized branches
16568
- * are still the first thing a prompt budget gives up; raw episodic history is
16569
- * next. A redline is never dropped.
16570
- */
16571
- function entryTier(entry) {
16572
- if (entry.nonOverridable || entry.authority === "redline") return 0;
16573
- if (entry.authority === "canonical") return 1;
16574
- if (entry.mode === "subscribe") return 2;
16575
- if (entry.mode === "personal") return entry.type === "episodic" ? 4 : 3;
16576
- return 5;
16459
+ /** Quote a value for the hand-written YAML front matter. */
16460
+ function yamlQuoted(value) {
16461
+ return JSON.stringify(value.replace(/\s+/gu, " ").trim());
16577
16462
  }
16578
- function compareEntries(left, right) {
16579
- const tier = entryTier(left) - entryTier(right);
16580
- if (tier !== 0) return tier;
16581
- if (left.mode === "personal" && right.mode === "personal") {
16582
- const type = personalTypeRank(left.type) - personalTypeRank(right.type);
16583
- if (type !== 0) return type;
16584
- const updated = compareText(right.updatedAt ?? "", left.updatedAt ?? "");
16585
- if (updated !== 0) return updated;
16586
- return compareText(left.sourceId, right.sourceId);
16587
- }
16588
- const graph = compareText(left.graphId, right.graphId);
16589
- if (graph !== 0) return graph;
16590
- const type = sourceTypeRank(left.sourceType) - sourceTypeRank(right.sourceType);
16591
- if (type !== 0) return type;
16592
- return compareText(left.sourceId, right.sourceId);
16463
+ /** Compose the shared document: front matter for the graph loader, then the body. */
16464
+ function renderSharedMemoryDocument(record, now) {
16465
+ const tags = record.target.scope === "global" ? ["记忆", "全局共享"] : ["记忆", "部门共享"];
16466
+ return [
16467
+ "---",
16468
+ `id: mem-${record.id}`,
16469
+ `type: ${sharedNodeTypeOf(record.source.memoryType)}`,
16470
+ `title: ${yamlQuoted(record.source.title)}`,
16471
+ "authority: advisory",
16472
+ "internalizable: true",
16473
+ "origin: human",
16474
+ "reviewStatus: approved",
16475
+ `tags: [${tags.join(", ")}]`,
16476
+ `promotedAt: ${now}`,
16477
+ `promotionId: ${record.id}`,
16478
+ `scope: ${record.target.scope === "global" ? "global" : "department:" + (record.target.departmentCode ?? "")}`,
16479
+ "---",
16480
+ "",
16481
+ `# ${record.source.title}`,
16482
+ "",
16483
+ record.source.content,
16484
+ "",
16485
+ "---",
16486
+ "",
16487
+ `由 ${record.reviewedBy?.name ?? record.requestedBy.name} 于 ${now} 审核晋升。`,
16488
+ ""
16489
+ ].join("\n");
16593
16490
  }
16594
- /** Current effective memory first; raw episodic history last. */
16595
- function personalTypeRank(type) {
16596
- switch (type) {
16597
- case "preference": return 0;
16598
- case "pitfall": return 1;
16599
- case "fact": return 2;
16600
- case "sop": return 3;
16601
- case "episodic": return 4;
16602
- default: return 5;
16491
+ const isRecord$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
16492
+ /** Read one shared graph, returning undefined when it has not been created yet. */
16493
+ async function readSharedGraph(graphPath) {
16494
+ let raw;
16495
+ try {
16496
+ raw = await readFile(graphPath, "utf8");
16497
+ } catch (error) {
16498
+ if (error.code === "ENOENT") return void 0;
16499
+ throw new MemoryPromotionError("io", `could not read ${graphPath}: ${String(error)}`);
16500
+ }
16501
+ try {
16502
+ const parsed = JSON.parse(raw);
16503
+ if (!isRecord$2(parsed) || parsed.schemaVersion !== 1 || !Array.isArray(parsed.nodes)) throw new Error("wrong shape");
16504
+ return parsed;
16505
+ } catch {
16506
+ throw new MemoryPromotionError("invalid-graph", `shared memory graph is not readable: ${graphPath}`);
16603
16507
  }
16604
16508
  }
16605
- function sourceTypeRank(sourceType) {
16606
- if (sourceType === "node") return 0;
16607
- if (sourceType === "entry") return 1;
16608
- return 2;
16609
- }
16610
- function compareText(left, right) {
16611
- return left < right ? -1 : left > right ? 1 : 0;
16612
- }
16613
- function normalizeMaxChars(value) {
16614
- if (value === void 0 || !Number.isFinite(value)) return DEFAULT_MEMORY_CONTEXT_MAX_CHARS;
16615
- return Math.max(0, Math.floor(value));
16616
- }
16617
- function strictestAuthority(...values) {
16618
- let authority = "advisory";
16619
- for (const value of values) if (value !== void 0 && AUTHORITY_RANK[value] > AUTHORITY_RANK[authority]) authority = value;
16620
- return authority;
16509
+ /** Compose a fresh manifest for one target scope. */
16510
+ function newSharedGraph(record, now) {
16511
+ return {
16512
+ schemaVersion: 1,
16513
+ id: SHARED_MEMORY_GRAPH_ID,
16514
+ name: sharedMemoryGraphName(record.target.scope),
16515
+ description: record.target.scope === "global" ? "经审核晋升到全局的共享记忆;只读展示。" : "经审核晋升到本部门的共享记忆;只读展示。",
16516
+ scope: record.target.scope === "global" ? "global" : "department:" + (record.target.departmentCode ?? ""),
16517
+ version: 1,
16518
+ status: "published",
16519
+ owner: record.reviewedBy?.id ?? record.requestedBy.id,
16520
+ createdAt: now,
16521
+ updatedAt: now,
16522
+ publishedAt: now,
16523
+ tags: ["记忆", "共享"],
16524
+ visibility: record.target.scope,
16525
+ defaultView: {
16526
+ layout: "hierarchy",
16527
+ direction: "TB"
16528
+ },
16529
+ topics: [],
16530
+ nodes: [],
16531
+ edges: []
16532
+ };
16621
16533
  }
16622
- function graphCommit(graph) {
16623
- const withCommit = graph;
16624
- if (typeof withCommit.commit === "string" && withCommit.commit !== "") return withCommit.commit;
16625
- const manifest = graph.manifest;
16626
- if (typeof manifest.commit === "string" && manifest.commit !== "") return manifest.commit;
16627
- if (typeof manifest.sourceCommit === "string" && manifest.sourceCommit !== "") return manifest.sourceCommit;
16534
+ /**
16535
+ * Write an approved promotion into the target scope and register it in the shared
16536
+ * memory graph.
16537
+ *
16538
+ * The document is written first and the manifest second: if the manifest write
16539
+ * fails, the next approval retries both and the orphan document is harmless (it is
16540
+ * not referenced). The reverse order would publish a broken node.
16541
+ */
16542
+ async function applyPromotionToSharedMemory(input) {
16543
+ const { record, scopeRoot } = input;
16544
+ const now = input.now ?? (/* @__PURE__ */ new Date()).toISOString();
16545
+ if (record.status !== "pending") throw new MemoryPromotionError("conflict", `promotion ${record.id} is already ${record.status}`);
16546
+ const docRelPath = `${SHARED_MEMORY_FOLDER}/${record.id}.md`;
16547
+ if (record.target.docPath !== docRelPath) throw new MemoryPromotionError("invalid", "the stored promotion path does not match its id");
16548
+ const docPath = join(scopeRoot, SHARED_MEMORY_FOLDER, `${record.id}.md`);
16549
+ const graphPath = join(scopeRoot, ".graphs", SHARED_MEMORY_GRAPH_ID, "graph.json");
16550
+ await writeFileAtomic(docPath, renderSharedMemoryDocument(record, now));
16551
+ await serialize(graphPath, async () => {
16552
+ const existing = await readSharedGraph(graphPath);
16553
+ const manifest = existing === void 0 ? newSharedGraph(record, now) : {
16554
+ ...existing,
16555
+ version: (Number.isFinite(existing.version) ? existing.version : 0) + 1,
16556
+ updatedAt: now,
16557
+ publishedAt: now,
16558
+ status: "published",
16559
+ visibility: record.target.scope,
16560
+ scope: record.target.scope === "global" ? "global" : "department:" + (record.target.departmentCode ?? ""),
16561
+ tags: [.../* @__PURE__ */ new Set([
16562
+ ...existing.tags ?? [],
16563
+ "记忆",
16564
+ "共享"
16565
+ ])]
16566
+ };
16567
+ const nodeId = "mem-" + record.id;
16568
+ if (!manifest.nodes.some((node) => node.id === nodeId || node.path === docRelPath)) manifest.nodes = [...manifest.nodes, {
16569
+ id: nodeId,
16570
+ path: docRelPath
16571
+ }];
16572
+ await writeFileAtomic(graphPath, JSON.stringify(manifest, null, 2) + "\n");
16573
+ });
16574
+ return {
16575
+ docPath,
16576
+ graphPath,
16577
+ graphId: SHARED_MEMORY_GRAPH_ID
16578
+ };
16628
16579
  }
16629
16580
  //#endregion
16630
- //#region src/memoryTools.ts
16581
+ //#region src/memoryShared.ts
16631
16582
  /**
16632
- * Model-facing runtime memory tools: `memory_context` and `memory_guardian_run`.
16583
+ * Department/global shared memory for the runtime context.
16633
16584
  *
16634
- * `memory_context` is read-only. It resolves the caller's personal binding
16635
- * projection through {@link resolveMemoryContext}: live proxies for subscribed
16636
- * sources, the user's own branch for internalized sources, the current entries
16637
- * of the user's own `MemoryStore`, redlines marked non-overridable, and a
16638
- * deterministic budget. It never writes.
16585
+ * A promotion (design §17.4, §22) writes one approved document under
16586
+ * `<scope>/记忆共享/<promotion-id>.md` and registers it in
16587
+ * `<scope>/.graphs/shared-memory/graph.json`. Those documents have no personal
16588
+ * binding: the user never subscribed, the department published. The runtime
16589
+ * therefore reads the shared graph directly and treats each node as advisory
16590
+ * department/global context.
16639
16591
  *
16640
- * `memory_guardian_run` is the manual trigger for the guardian pass. It is a
16641
- * maintenance action, not a read: it refreshes `sourceVersion`/`sourceCommit`,
16642
- * resolves pending bindings, performs requested internalizations and revokes
16643
- * branches whose source became redline. It is denied unless the Host reports the
16644
- * `kb:config:manage` capability, and it only touches the caller's own bindings
16645
- * root (`userIds: [caller.userId]`) plus graphs the caller may manage. The
16646
- * scheduled guardian job remains the normal path; this tool exists for
16647
- * operators and for a deployment without a scheduler.
16592
+ * Two boundaries keep that read safe:
16648
16593
  *
16649
- * Both tools take the same injected host seam as the other knowledge tools: no
16650
- * global config, no ambient session. The caller's viewer is resolved once per
16651
- * call, and the backend remains the final authority for anything the tools then
16652
- * read or write.
16594
+ * - the caller's scope roots are composed from the authenticated department
16595
+ * chain (`global` plus `department/<chain>`), never from a graph id supplied by
16596
+ * the browser. A graph in another department is never opened;
16597
+ * - `canViewGraph` still decides whether the manifest is readable, and the Host
16598
+ * asks DataOps `canRead` for the scope root before the graph is loaded. The
16599
+ * resolver re-checks visibility per graph, so a caller cannot be handed a
16600
+ * graph and read a name it was not granted.
16653
16601
  *
16654
- * @module @sparkelf/dsh-knowledge-base/memory-tools
16602
+ * Only `normal` / `private` shared documents enter a model-facing context.
16603
+ * `sensitive` / `secret` stay on the memory page, mirroring the personal rule in
16604
+ * §15.2. Promotions only ever copy `normal` content, so this is a fail-closed
16605
+ * guard for hand-written or future documents rather than the normal path.
16606
+ *
16607
+ * @module @sparkelf/dsh-knowledge-base/memory-shared
16655
16608
  */
16656
- const ZERO_GUARDIAN_RESULT = {
16657
- createdPending: 0,
16658
- subscribed: 0,
16659
- internalized: 0,
16660
- rejectedRedline: 0,
16661
- upstreamUpdates: 0,
16662
- revoked: 0
16663
- };
16664
16609
  /**
16665
- * Canonical output renderer shared by the tools: prefer the `rendered` text the
16666
- * tool prepared (markdown or JSON), fall back to pretty JSON.
16610
+ * The shared-memory scope roots a caller may own content under.
16611
+ *
16612
+ * `global` is always a candidate (subject to `canRead`); the department root is
16613
+ * the caller's own organization chain, never a sibling. Order is global first,
16614
+ * then department, so the rendered context is deterministic.
16615
+ *
16616
+ * @param caller - the authenticated caller's department projection.
16617
+ * @returns Scope roots in a stable order.
16667
16618
  */
16668
- const textOutput$1 = {
16669
- schema: {
16670
- type: "object",
16671
- additionalProperties: true
16672
- },
16673
- render: (_args, value) => {
16674
- const record = value;
16675
- return [{
16676
- type: "text",
16677
- text: record !== null && typeof record?.rendered === "string" ? record.rendered : JSON.stringify(value, null, 2)
16678
- }];
16679
- }
16680
- };
16681
- const run$2 = async (operation) => {
16682
- try {
16683
- return await operation();
16684
- } catch (error) {
16685
- throw asKnowledgeToolError(error);
16686
- }
16687
- };
16688
- /** Build the read-only `memory_context` tool. */
16689
- function createMemoryContextTool(host) {
16690
- return defineTool({
16691
- name: "memory_context",
16692
- description: "Read the caller's personal memory context. Returns the caller's own remembered preferences, pitfalls, facts, methods and recent episodic memory from the memory store, plus live proxies for subscribed department/global memory sources, the caller's own internalized branches (marked stale/revoked when they diverged), and redline policy entries marked nonOverridable. Permission-denied graphs are omitted and other users' memory is never read. Ordering is deterministic and a character budget drops personal/history and advisory internalized memory before canonical or redline entries; redlines are never dropped. Read-only: this tool never writes bindings or documents.",
16693
- parameters: {
16694
- format: {
16695
- type: "string",
16696
- description: "markdown (default) or json."
16697
- },
16698
- maxChars: {
16699
- type: "number",
16700
- description: `Prompt budget in characters; default ${DEFAULT_MEMORY_CONTEXT_MAX_CHARS}.`
16701
- }
16702
- },
16703
- output: textOutput$1,
16704
- execute: async (args) => run$2(async () => {
16705
- const viewer = await host.resolveCaller();
16706
- const enabled = host.isMemoryEnabled === void 0 ? true : await host.isMemoryEnabled(viewer);
16707
- const allGraphs = await host.loadGraphs(viewer);
16708
- const graphs = enabled ? allGraphs : allGraphs.filter((graph) => {
16709
- const scope = graph.manifest.scope ?? "";
16710
- return scope !== "personal" && !scope.startsWith("personal:");
16711
- });
16712
- const personalMemoryRoot = enabled ? host.personalMemoryRoot?.(viewer) : void 0;
16713
- const context = await resolveMemoryContext({
16714
- viewer,
16715
- usersRoot: host.usersRoot,
16716
- userId: viewer.userId,
16717
- graphs,
16718
- ...enabled ? {} : { bindings: [] },
16719
- ...personalMemoryRoot === void 0 ? {} : { personalMemoryRoot },
16720
- ...args.maxChars === void 0 ? {} : { maxChars: args.maxChars }
16721
- });
16722
- const format = args.format === "json" ? "json" : "markdown";
16723
- return {
16724
- ok: true,
16725
- format,
16726
- rendered: format === "json" ? JSON.stringify({
16727
- ...context,
16728
- ...enabled ? {} : { paused: true }
16729
- }, null, 2) : (enabled ? "" : "Personal memory is paused. Personal memories are not used; department/global policy and redlines still apply.\n\n") + renderMemoryContextMarkdown(context),
16730
- context,
16731
- ...enabled ? {} : { paused: true }
16732
- };
16733
- })
16734
- });
16735
- }
16736
- /** Build the manage-gated `memory_guardian_run` tool. */
16737
- function createMemoryGuardianRunTool(host) {
16738
- return defineTool({
16739
- name: "memory_guardian_run",
16740
- description: "Run the personal memory guardian pass for the caller. It discovers new graph nodes/edges, resolves pending bindings, performs requested internalizations, refreshes sourceVersion/sourceCommit and revokes internalized branches whose source became redline. It writes only under the caller's bindings/memory root and only for graphs the caller may manage. Requires the kb:config:manage capability; the scheduled guardian job is the normal trigger, this tool is the manual operator path.",
16741
- parameters: {},
16742
- output: textOutput$1,
16743
- execute: async () => run$2(async () => {
16744
- const viewer = await host.resolveCaller();
16745
- if (viewer.userId.trim() === "") throw new KnowledgeToolError("unauthorized", "an authenticated caller is required");
16746
- if (!await host.canManage(viewer)) throw new KnowledgeToolError("forbidden", "memory_guardian_run requires the kb:config:manage capability");
16747
- const manageable = (await host.loadGraphs(viewer)).filter((graph) => canManageGraph(viewer, graphScopeDescriptor(graph.manifest)));
16748
- const runAt = (/* @__PURE__ */ new Date()).toISOString();
16749
- const results = [];
16750
- const totals = { ...ZERO_GUARDIAN_RESULT };
16751
- for (const graph of manageable) {
16752
- const result = await runGuardianPass({
16753
- graph,
16754
- usersRoot: host.usersRoot,
16755
- userIds: [viewer.userId],
16756
- ...viewer.departmentCode === void 0 ? {} : { departmentCode: viewer.departmentCode },
16757
- now: runAt
16758
- });
16759
- results.push({
16760
- graphId: graph.manifest.id,
16761
- ...result
16762
- });
16763
- totals.createdPending += result.createdPending;
16764
- totals.subscribed += result.subscribed;
16765
- totals.internalized += result.internalized;
16766
- totals.rejectedRedline += result.rejectedRedline;
16767
- totals.upstreamUpdates += result.upstreamUpdates;
16768
- totals.revoked += result.revoked;
16769
- }
16770
- const response = {
16771
- ok: true,
16772
- userId: viewer.userId,
16773
- runAt,
16774
- graphs: results,
16775
- totals
16776
- };
16777
- if (manageable.length === 0) response.note = "no readable graph is manageable for this caller; nothing was run";
16778
- return {
16779
- ...response,
16780
- rendered: JSON.stringify(response, null, 2)
16781
- };
16782
- })
16619
+ function sharedMemoryScopeRoots(caller) {
16620
+ const roots = [{
16621
+ scope: "global",
16622
+ relPath: "global"
16623
+ }];
16624
+ const rawCodes = caller.departmentPathCodes !== void 0 && caller.departmentPathCodes.length > 0 ? [...caller.departmentPathCodes] : caller.departmentCode === void 0 || caller.departmentCode === "" ? [] : [caller.departmentCode];
16625
+ const codes = [];
16626
+ for (const value of rawCodes) {
16627
+ const code = typeof value === "string" ? value.trim() : "";
16628
+ if (code === "" || code === "." || code === ".." || code.includes("/") || code.includes("\\")) break;
16629
+ codes.push(code);
16630
+ }
16631
+ if (codes.length > 0) roots.push({
16632
+ scope: "department",
16633
+ relPath: "department/" + codes.join("/"),
16634
+ departmentCode: codes[codes.length - 1]
16783
16635
  });
16636
+ return roots;
16784
16637
  }
16638
+ const AUTHORITIES$1 = [
16639
+ "canonical",
16640
+ "advisory",
16641
+ "redline"
16642
+ ];
16643
+ const ORIGINS$1 = [
16644
+ "human",
16645
+ "ai",
16646
+ "mixed"
16647
+ ];
16648
+ const REVIEW_STATUSES$1 = [
16649
+ "draft",
16650
+ "reviewed",
16651
+ "approved"
16652
+ ];
16653
+ const PRIVACY = PRIVACY_VALUES;
16785
16654
  /**
16786
- * Build both runtime memory tools.
16655
+ * Privacy levels a shared document may enter a model-facing context with.
16787
16656
  *
16788
- * @param host - the injected caller/graph/root seam.
16789
- * @returns Tool definitions for the disclosure coordinator.
16657
+ * `normal` and `private` are owner/scope-scoped; `sensitive` is redacted in logs
16658
+ * and telemetry, and a tool result is part of the transcript; `secret` is only a
16659
+ * credential pointer. Both are skipped, exactly like personal memory.
16790
16660
  */
16791
- function createMemoryTools(host) {
16792
- return [createMemoryContextTool(host), createMemoryGuardianRunTool(host)];
16793
- }
16794
- //#endregion
16795
- //#region src/memoryGraphBootstrap.ts
16661
+ const CONTEXT_PRIVACY$1 = /* @__PURE__ */ new Set(["normal", "private"]);
16796
16662
  /**
16797
- * Ensure the personal memory graph exists.
16798
- *
16799
- * The graph tab is a catalogue of `.graphs/<id>/graph.json` manifests. A user
16800
- * with no subscriptions yet has no personal graph at all, which reads as "the
16801
- * memory feature is missing" rather than "there is nothing in it". This creates
16802
- * an empty, private, published manifest for the caller once; it is the stable
16803
- * home the guardian will later fill with subscription proxies and internalized
16804
- * branches.
16805
- *
16806
- * Writing is deliberately best-effort at the call site: a read-only mount must
16807
- * keep the graph tab usable, so a failed bootstrap is not an error for the route.
16663
+ * The body without the promotion audit footer.
16808
16664
  *
16809
- * @module @sparkelf/dsh-knowledge-base/memory-graph-bootstrap
16665
+ * Every promotion ends with `---` and `由 … 于 … 审核晋升。`, which is provenance,
16666
+ * not memory content. The audit trail stays in the document; the model sees the
16667
+ * statement only. Dropping it here also lets two re-promotions of the same
16668
+ * statement dedupe by title + body instead of appearing once per timestamp.
16810
16669
  */
16811
- /** Stable graph id for the caller's personal memory graph. */
16812
- const PERSONAL_MEMORY_GRAPH_ID$1 = "personal-memory";
16813
- /** Display name shown in the graph tree. */
16814
- const PERSONAL_MEMORY_GRAPH_NAME = "个人记忆图谱";
16815
- /** One safe path segment, or undefined when it cannot be used as a file/dir name. */
16816
- function safeSegment(value) {
16817
- if (value === "" || value === "." || value === "..") return void 0;
16818
- if (value.includes("/") || value.includes("\\") || value.includes("\0")) return void 0;
16819
- return value;
16670
+ function sharedBodyOf(body) {
16671
+ return body.replace(/\n-{3,}\n+由[^\n]*审核晋升。\s*$/u, "").trim();
16820
16672
  }
16821
- /** The manifest a fresh personal memory graph holds. */
16822
- function emptyPersonalMemoryManifest(userId, now) {
16673
+ /** Read the attributes the shared injection reads, tolerating unknown keys. */
16674
+ function readDocumentAttributes$1(frontMatter) {
16675
+ if (frontMatter === null || frontMatter.trim() === "") return {};
16676
+ const record = parseSimpleYaml(frontMatter);
16677
+ const text = (key) => {
16678
+ const value = record[key];
16679
+ return typeof value === "string" && value !== "" ? value : void 0;
16680
+ };
16681
+ const authority = text("authority");
16682
+ const origin = text("origin");
16683
+ const reviewStatus = text("reviewStatus");
16684
+ const privacy = text("privacy");
16823
16685
  return {
16824
- schemaVersion: 1,
16825
- id: PERSONAL_MEMORY_GRAPH_ID$1,
16826
- name: PERSONAL_MEMORY_GRAPH_NAME,
16827
- description: "个人订阅代理与内化记忆的默认图谱;尚未订阅或内化任何部门节点。",
16828
- scope: "personal:" + userId,
16829
- version: 1,
16830
- status: "published",
16831
- owner: userId,
16832
- createdAt: now,
16833
- updatedAt: now,
16834
- publishedAt: now,
16835
- tags: ["记忆"],
16836
- visibility: "private",
16837
- defaultView: {
16838
- layout: "hierarchy",
16839
- direction: "TB"
16840
- },
16841
- topics: [],
16842
- nodes: [],
16843
- edges: []
16686
+ ...text("title") === void 0 ? {} : { title: text("title") },
16687
+ ...text("type") === void 0 ? {} : { type: text("type") },
16688
+ ...authority !== void 0 && AUTHORITIES$1.includes(authority) ? { authority } : {},
16689
+ ...origin !== void 0 && ORIGINS$1.includes(origin) ? { origin } : {},
16690
+ ...reviewStatus !== void 0 && REVIEW_STATUSES$1.includes(reviewStatus) ? { reviewStatus } : {},
16691
+ ...privacy !== void 0 && PRIVACY.includes(privacy) ? { privacy } : {}
16844
16692
  };
16845
16693
  }
16846
- /** Whether one path is a regular file. */
16847
- async function isFile$1(path) {
16848
- try {
16849
- return (await stat(path)).isFile();
16850
- } catch {
16851
- return false;
16852
- }
16694
+ /** A document path that stays inside the scope root. */
16695
+ function isSafeDocumentPath(relPath) {
16696
+ if (relPath === "" || isAbsolute(relPath)) return false;
16697
+ return !relPath.split("/").some((segment) => segment === "" || segment === ".." || segment === ".");
16853
16698
  }
16854
16699
  /**
16855
- * Create `<scopeRoot>/.graphs/personal-memory/graph.json` when it is absent.
16700
+ * Read every injectable node of one shared-memory graph.
16856
16701
  *
16857
- * @param options.scopeRoot - absolute personal scope root (`<actualRoot>/personal/<uid>`).
16858
- * @param options.userId - stable caller id; also the manifest owner.
16859
- * @param options.now - injectable clock for tests.
16860
- * @returns whether the manifest was created and its absolute path.
16702
+ * A missing or unreadable document is skipped (fail soft): one broken promotion
16703
+ * must not hide a redline or fail the whole context. A graph that is not the
16704
+ * shared-memory graph, or whose manifest scope is neither `global` nor
16705
+ * `department:<code>`, contributes nothing.
16706
+ *
16707
+ * @param graph - the loaded graph; its `root` must be the scope root.
16708
+ * @returns Candidates in manifest node order, already privacy-filtered.
16861
16709
  */
16862
- async function ensurePersonalMemoryGraph(options) {
16863
- const userId = safeSegment(options.userId);
16864
- if (userId === void 0) throw new Error("memory-graph: unsafe userId");
16865
- const graphId = safeSegment(PERSONAL_MEMORY_GRAPH_ID$1);
16866
- if (graphId === void 0) throw new Error("memory-graph: unsafe graph id");
16867
- const directory = join(options.scopeRoot, ".graphs", graphId);
16868
- const path = join(directory, "graph.json");
16869
- if (await isFile$1(path)) return {
16870
- created: false,
16871
- path
16872
- };
16873
- const manifest = emptyPersonalMemoryManifest(userId, options.now ?? (/* @__PURE__ */ new Date()).toISOString());
16874
- await mkdir(directory, { recursive: true });
16875
- const temporary = join(directory, ".graph.json." + String(process.pid) + ".tmp");
16876
- await writeFile(temporary, JSON.stringify(manifest, null, 2) + "\n", "utf8");
16877
- await rename(temporary, path);
16878
- return {
16879
- created: true,
16880
- path
16881
- };
16710
+ async function readSharedMemoryCandidates(graph) {
16711
+ if (graph.manifest.id !== "shared-memory") return [];
16712
+ const scope = graph.manifest.scope ?? "";
16713
+ if (scope !== "global" && !scope.startsWith("department:")) return [];
16714
+ const version = Number.isFinite(graph.manifest.version) ? graph.manifest.version : 1;
16715
+ const candidates = [];
16716
+ for (const node of graph.nodes) {
16717
+ if (node.missing) continue;
16718
+ if (!isSafeDocumentPath(node.path)) continue;
16719
+ let text;
16720
+ try {
16721
+ text = await readFile(join(graph.root, node.path), "utf8");
16722
+ } catch {
16723
+ continue;
16724
+ }
16725
+ const document = splitFrontMatter(text);
16726
+ const live = readDocumentAttributes$1(document.frontMatter);
16727
+ const privacy = live.privacy ?? "normal";
16728
+ if (!CONTEXT_PRIVACY$1.has(privacy)) continue;
16729
+ const reviewStatus = live.reviewStatus ?? node.reviewStatus ?? "draft";
16730
+ if (reviewStatus === "draft") continue;
16731
+ const body = sharedBodyOf(document.body);
16732
+ if (body === "") continue;
16733
+ const title = (live.title ?? node.title ?? node.id).trim();
16734
+ if (title === "") continue;
16735
+ candidates.push({
16736
+ id: node.id,
16737
+ title,
16738
+ type: live.type ?? node.type,
16739
+ authority: live.authority ?? node.authority ?? "advisory",
16740
+ origin: live.origin ?? node.origin ?? "human",
16741
+ reviewStatus,
16742
+ privacy,
16743
+ path: node.path,
16744
+ scope,
16745
+ status: "active",
16746
+ version,
16747
+ body
16748
+ });
16749
+ }
16750
+ return candidates;
16882
16751
  }
16883
16752
  //#endregion
16884
- //#region src/memorySettings.ts
16753
+ //#region src/memoryContext.ts
16885
16754
  /**
16886
- * Per-user memory settings: whether personal memory learning is enabled and how
16887
- * often the guardian consolidates what it learned.
16888
- *
16889
- * The product rule (design §22.2) is deliberately conservative:
16755
+ * Runtime memory context: what the model may see from one user's personal graph.
16890
16756
  *
16891
- * - a new user is **paused** (`memoryEnabled: false`), so no extraction starts
16892
- * until the user explicitly confirms the enable dialog;
16893
- * - an administrator or super administrator (a holder of the configured DataOps
16894
- * permission, by default `kb:config:manage`) starts **enabled** on the first
16895
- * read when no settings file exists yet. The global default is never flipped:
16896
- * the administrator decision is injected through {@link MemorySettingsDefaultPolicy},
16897
- * and an explicit `false` written by that administrator always wins;
16898
- * - the switch is per user, not per session, and survives restarts;
16899
- * - the file is local state under `<usersRoot>/<userId>/settings.json`, never
16900
- * knowledge content and never Git content;
16901
- * - a missing or unreadable file is a valid "paused" answer, not an error. Only
16902
- * a filesystem permission failure is surfaced.
16757
+ * The personal graph is a projection, not a second copy:
16903
16758
  *
16904
- * The persisted shape is version 2 (`memoryEnabled` + `consolidationIntervalMinutes`).
16905
- * Version 1 files (only `memoryEnabled`, or even a hand-written bare boolean) are
16906
- * still read: a missing interval falls back to 60 minutes, and a malformed
16907
- * interval never turns a remembered enable/disable decision into a different one.
16759
+ * - a `subscribe` binding is resolved LIVE from the current department/global
16760
+ * graph. The resolver reads the document body from disk on every call and
16761
+ * prefers the live frontmatter, so a published change reaches the model
16762
+ * without waiting for the guardian or for a binding refresh;
16763
+ * - an `internalize` binding is read from the user's own branch at
16764
+ * `<usersRoot>/<userId>/memory/<graphId>/<sourceId>.md`. That branch does not
16765
+ * follow the source; `stale` / `revoked` come from the binding so the runtime
16766
+ * can down-rank or hide it;
16767
+ * - visibility is decided per graph through `canViewGraph`. A graph, node or
16768
+ * edge the viewer cannot see is omitted, never partially projected;
16769
+ * - approved department/global shared memory (`记忆共享/` + `shared-memory`
16770
+ * graph) is read directly. It needs no binding; it stays advisory and yields
16771
+ * to redline/canonical entries;
16772
+ * - redlines are marked `nonOverridable` with an explicit marker. The character
16773
+ * budget drops advisory material first and never drops a redline;
16774
+ * - pausing personal memory removes the caller's own store and internalized
16775
+ * branches, not department/global policy or shared memory.
16908
16776
  *
16909
- * The route/UI layer reads `read()` or `isEnabled()` and writes through
16910
- * `save()`; every write is atomic (tmp + rename) and persists both fields in one
16911
- * rename so a page save can never leave the switch and the interval disagreeing.
16777
+ * Ordering is deterministic (priority tier, graph id, source type, source id),
16778
+ * so two identical inputs produce the same prompt prefix.
16912
16779
  *
16913
- * @module @sparkelf/dsh-knowledge-base/memory-settings
16780
+ * @module @sparkelf/dsh-knowledge-base/memory-context
16914
16781
  */
16915
- /** File name inside one user's directory. */
16916
- const MEMORY_SETTINGS_FILE = "settings.json";
16917
- /** Longest allowed consolidation interval, in minutes. */
16918
- const MEMORY_CONSOLIDATION_INTERVAL_MAX = 1440;
16919
- /** The paused default for a user who has never confirmed the enable dialog. */
16920
- const DEFAULT_MEMORY_SETTINGS = Object.freeze({
16921
- version: 2,
16922
- memoryEnabled: false,
16923
- consolidationIntervalMinutes: 60
16924
- });
16925
- /** A malformed interval or write patch; the route maps this to HTTP 400. */
16926
- var MemorySettingsError = class extends Error {
16927
- code;
16928
- name = "MemorySettingsError";
16929
- constructor(code, message) {
16930
- super(message);
16931
- this.code = code;
16932
- }
16782
+ /** Default prompt budget for the resolved context. */
16783
+ const DEFAULT_MEMORY_CONTEXT_MAX_CHARS = 8e3;
16784
+ /** Marker the runtime must treat as above personal memory and preferences. */
16785
+ const SYSTEM_POLICY_MARKER = "system policy overrides personal memory";
16786
+ /** The fixed per-entry metadata overhead included in `chars`. */
16787
+ const ENTRY_METADATA_CHARS = 32;
16788
+ const AUTHORITY_RANK = {
16789
+ advisory: 0,
16790
+ canonical: 1,
16791
+ redline: 2
16933
16792
  };
16793
+ const AUTHORITIES = [
16794
+ "canonical",
16795
+ "advisory",
16796
+ "redline"
16797
+ ];
16798
+ const ORIGINS = [
16799
+ "human",
16800
+ "ai",
16801
+ "mixed"
16802
+ ];
16803
+ const REVIEW_STATUSES = [
16804
+ "draft",
16805
+ "reviewed",
16806
+ "approved"
16807
+ ];
16934
16808
  /**
16935
- * Validate one consolidation interval.
16936
- *
16937
- * The guard is strict on purpose: a fractional value or a value outside
16938
- * 15–1440 is a client bug, not a number to clamp silently. The route turns this
16939
- * error into a 400 so the page can show the allowed range.
16940
- *
16941
- * @param value - raw value from an API body or a hand-edited file.
16942
- * @returns the accepted integer.
16943
- * @throws {MemorySettingsError} when the value is not an integer in range.
16809
+ * Adapt a loaded graph manifest to the visibility descriptor `canViewGraph`
16810
+ * expects. `scope` is the machine scope (`global`, `department:<code>`,
16811
+ * `personal:<uid>`); `owner` is the private-graph owner when present.
16944
16812
  */
16945
- function normalizeConsolidationInterval(value) {
16946
- if (typeof value !== "number" || !Number.isInteger(value)) throw new MemorySettingsError("invalid-interval", "consolidationIntervalMinutes must be an integer");
16947
- if (value < 15 || value > 1440) throw new MemorySettingsError("invalid-interval", `consolidationIntervalMinutes must be between ${String(15)} and ${String(MEMORY_CONSOLIDATION_INTERVAL_MAX)}`);
16948
- return value;
16949
- }
16950
- /** Read a stored interval leniently: an invalid legacy value falls back to 60. */
16951
- function readStoredInterval(value) {
16952
- try {
16953
- return normalizeConsolidationInterval(value);
16954
- } catch {
16955
- return 60;
16956
- }
16813
+ function graphScopeDescriptor(manifest) {
16814
+ const scope = manifest.scope ?? "";
16815
+ const departmentPrefix = "department:";
16816
+ const personalPrefix = "personal:";
16817
+ const departmentCode = scope.startsWith(departmentPrefix) ? scope.slice(11) : void 0;
16818
+ const ownerId = manifest.visibility === "private" ? manifest.owner ?? (scope.startsWith(personalPrefix) ? scope.slice(9) : void 0) : void 0;
16819
+ return {
16820
+ visibility: manifest.visibility,
16821
+ ownerId,
16822
+ departmentCode
16823
+ };
16957
16824
  }
16958
16825
  /**
16959
- * Atomic settings store over `<usersRoot>/<userId>/settings.json`.
16826
+ * Resolve the caller's personal memory context.
16960
16827
  *
16961
- * `read()` tolerates a corrupt file by returning the paused default; the next
16962
- * write rewrites it. This keeps the memory page usable after a partial write or
16963
- * a hand-edited file instead of failing the whole route.
16828
+ * @param input - viewer, roots, user id, loaded graphs and optional budget.
16829
+ * @returns Priority-ordered entries, budget drops and redline counters.
16964
16830
  */
16965
- var MemorySettingsStore = class {
16966
- usersRoot;
16967
- defaultPolicy;
16968
- constructor(usersRoot, defaultPolicy) {
16969
- if (typeof usersRoot !== "string" || usersRoot.trim() === "") throw new Error("memory-settings: usersRoot must be a non-empty path");
16970
- this.usersRoot = usersRoot;
16971
- this.defaultPolicy = defaultPolicy;
16972
- }
16973
- /** Absolute settings file for one user. */
16974
- filePath(userId) {
16975
- assertPathSegment(userId, "userId");
16976
- return join(this.usersRoot, userId, MEMORY_SETTINGS_FILE);
16831
+ async function resolveMemoryContext(input) {
16832
+ const maxChars = normalizeMaxChars(input.maxChars);
16833
+ const graphById = /* @__PURE__ */ new Map();
16834
+ for (const graph of input.graphs) if (!graphById.has(graph.manifest.id)) graphById.set(graph.manifest.id, graph);
16835
+ const bindings = input.bindings ?? await new BindingStore(input.usersRoot).list(input.userId);
16836
+ const entries = [];
16837
+ const bindingIds = /* @__PURE__ */ new Set();
16838
+ const bindingContent = /* @__PURE__ */ new Set();
16839
+ const paused = input.paused === true;
16840
+ for (const binding of bindings) {
16841
+ if (binding.userId !== input.userId) continue;
16842
+ if (binding.mode !== "subscribe" && binding.mode !== "internalize") continue;
16843
+ if (paused && binding.mode === "internalize") continue;
16844
+ const graph = graphById.get(binding.graphId);
16845
+ if (graph === void 0) continue;
16846
+ if (!canViewGraph(input.viewer, graphScopeDescriptor(graph.manifest))) continue;
16847
+ const entry = binding.mode === "subscribe" ? await resolveSubscribedEntry(binding, graph) : await resolveInternalizedEntry(binding, graph, input.usersRoot);
16848
+ if (entry === void 0) continue;
16849
+ entries.push(entry);
16850
+ bindingIds.add(entry.sourceId);
16851
+ bindingContent.add(contentFingerprint(entry.title, entry.body));
16977
16852
  }
16978
- /** The first-read default for one user, from the injected policy. */
16979
- async defaultFor(userId, options) {
16980
- if (options.defaultEnabled !== void 0) return {
16981
- ...DEFAULT_MEMORY_SETTINGS,
16982
- memoryEnabled: options.defaultEnabled === true
16983
- };
16984
- if (this.defaultPolicy === void 0) return { ...DEFAULT_MEMORY_SETTINGS };
16985
- try {
16986
- return {
16987
- ...DEFAULT_MEMORY_SETTINGS,
16988
- memoryEnabled: await this.defaultPolicy.memoryEnabled(userId) === true
16989
- };
16990
- } catch {
16991
- return { ...DEFAULT_MEMORY_SETTINGS };
16853
+ const seenSharedGraphs = /* @__PURE__ */ new Set();
16854
+ for (const graph of input.graphs) {
16855
+ const graphKey = `${graph.manifest.scope ?? ""}\u0000${graph.root}`;
16856
+ if (seenSharedGraphs.has(graphKey)) continue;
16857
+ if (!canViewGraph(input.viewer, graphScopeDescriptor(graph.manifest))) continue;
16858
+ const candidates = await readSharedMemoryCandidates(graph);
16859
+ if (candidates.length === 0) continue;
16860
+ seenSharedGraphs.add(graphKey);
16861
+ for (const candidate of candidates) {
16862
+ const fingerprint = contentFingerprint(candidate.title, candidate.body);
16863
+ if (bindingIds.has(candidate.id) || bindingContent.has(fingerprint)) continue;
16864
+ bindingIds.add(candidate.id);
16865
+ bindingContent.add(fingerprint);
16866
+ entries.push(finalizeSharedEntry(candidate));
16992
16867
  }
16993
16868
  }
16994
- /**
16995
- * Read one user's settings.
16996
- *
16997
- * Missing content uses {@link MemorySettingsReadOptions.defaultEnabled} or the
16998
- * injected policy. Malformed content stays paused even for an administrator:
16999
- * a corrupt file is not evidence that the administrator opted in. A file with
17000
- * a boolean `memoryEnabled` is accepted even if `version`/the interval is
17001
- * missing, so old settings files keep their explicit choice.
17002
- */
17003
- async read(userId, options = {}) {
17004
- let source;
17005
- try {
17006
- source = await readFile(this.filePath(userId), "utf8");
17007
- } catch (error) {
17008
- if (isErrno$1(error, "ENOENT") || isErrno$1(error, "ENOTDIR")) return this.defaultFor(userId, options);
17009
- throw error;
17010
- }
17011
- let parsed;
17012
- try {
17013
- parsed = JSON.parse(source);
17014
- } catch {
17015
- return { ...DEFAULT_MEMORY_SETTINGS };
16869
+ const personalMemoryRoot = input.personalMemoryRoot?.trim() ?? "";
16870
+ if (!paused && personalMemoryRoot !== "") entries.push(...await resolvePersonalMemoryEntries(personalMemoryRoot, bindingIds, bindingContent));
16871
+ entries.sort(compareEntries);
16872
+ const selected = [];
16873
+ const dropped = [];
16874
+ let charCount = 0;
16875
+ for (const entry of entries) {
16876
+ if (!(entry.nonOverridable || entry.authority === "redline") && charCount + entry.chars > maxChars) {
16877
+ dropped.push({
16878
+ graphId: entry.graphId,
16879
+ sourceType: entry.sourceType,
16880
+ sourceId: entry.sourceId,
16881
+ mode: entry.mode,
16882
+ chars: entry.chars,
16883
+ reason: "budget"
16884
+ });
16885
+ continue;
17016
16886
  }
17017
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return { ...DEFAULT_MEMORY_SETTINGS };
17018
- const memoryEnabled = parsed.memoryEnabled;
17019
- if (typeof memoryEnabled !== "boolean") return { ...DEFAULT_MEMORY_SETTINGS };
17020
- return {
17021
- version: 2,
17022
- memoryEnabled,
17023
- consolidationIntervalMinutes: readStoredInterval(parsed.consolidationIntervalMinutes)
17024
- };
17025
- }
17026
- /** Whether learning is enabled for this user (default `false`). */
17027
- async isEnabled(userId, options = {}) {
17028
- return (await this.read(userId, options)).memoryEnabled;
17029
- }
17030
- /**
17031
- * Persist a partial settings change in one atomic write.
17032
- *
17033
- * The current value is read first so a page that saves only the interval
17034
- * cannot accidentally pause memory (nor enable it). An explicit boolean in
17035
- * the patch always wins; an absent field is preserved.
17036
- *
17037
- * @returns the normalized settings actually written.
17038
- */
17039
- async save(userId, patch, options = {}) {
17040
- if (patch.memoryEnabled === void 0 && patch.consolidationIntervalMinutes === void 0) throw new MemorySettingsError("invalid-settings", "at least one memory setting must be supplied");
17041
- if (patch.memoryEnabled !== void 0 && typeof patch.memoryEnabled !== "boolean") throw new MemorySettingsError("invalid-settings", "memoryEnabled must be a boolean");
17042
- const interval = patch.consolidationIntervalMinutes === void 0 ? void 0 : normalizeConsolidationInterval(patch.consolidationIntervalMinutes);
17043
- const current = await this.read(userId, options);
17044
- const settings = {
17045
- version: 2,
17046
- memoryEnabled: patch.memoryEnabled ?? current.memoryEnabled,
17047
- consolidationIntervalMinutes: interval ?? current.consolidationIntervalMinutes
17048
- };
17049
- await writeFileAtomic(this.filePath(userId), `${JSON.stringify(settings, null, 2)}\n`, { mode: 384 });
17050
- return settings;
17051
- }
17052
- /**
17053
- * Persist the enable/pause switch atomically, preserving the interval.
17054
- *
17055
- * @returns the normalized settings actually written.
17056
- */
17057
- async setEnabled(userId, enabled, options = {}) {
17058
- if (typeof enabled !== "boolean") throw new MemorySettingsError("invalid-settings", "memoryEnabled must be a boolean");
17059
- return this.save(userId, { memoryEnabled: enabled }, options);
17060
- }
17061
- /** Persist one interval while preserving the switch. */
17062
- async setConsolidationInterval(userId, minutes, options = {}) {
17063
- return this.save(userId, { consolidationIntervalMinutes: minutes }, options);
17064
- }
17065
- };
17066
- function isErrno$1(error, code) {
17067
- return typeof error === "object" && error !== null && "code" in error && error.code === code;
17068
- }
17069
- //#endregion
17070
- //#region src/memoryRoutes.ts
17071
- const PATCH_FIELDS = /* @__PURE__ */ new Set([
17072
- "title",
17073
- "content",
17074
- "value",
17075
- "statement",
17076
- "solution",
17077
- "steps",
17078
- "privacy"
17079
- ]);
17080
- /** Which single field `content` corrects, per memory type. SOP uses `steps`. */
17081
- const CONTENT_FIELD = {
17082
- preference: "value",
17083
- pitfall: "solution",
17084
- episodic: "summary",
17085
- fact: "statement"
17086
- };
17087
- const isRecord$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
17088
- const messageOf$1 = (error) => error instanceof Error ? error.message : String(error);
17089
- const ok$1 = (body) => ({
17090
- status: 200,
17091
- body
17092
- });
17093
- const fail$1 = (status, error, code, extra) => ({
17094
- status,
17095
- body: {
17096
- error,
17097
- ...code === void 0 ? {} : { code },
17098
- ...extra
16887
+ selected.push(entry);
16888
+ charCount += entry.chars;
17099
16889
  }
17100
- });
17101
- /** The settings shape the page reads; bounds travel with the value so the UI never guesses. */
17102
- function settingsPayload(settings) {
16890
+ const redlineCount = selected.filter((entry) => entry.nonOverridable).length;
16891
+ const personalCount = selected.filter((entry) => entry.mode === "personal").length;
16892
+ const sharedCount = selected.filter((entry) => entry.mode === "shared").length;
17103
16893
  return {
17104
- enabled: settings.memoryEnabled,
17105
- consolidationIntervalMinutes: settings.consolidationIntervalMinutes,
17106
- intervalMin: 15,
17107
- intervalMax: MEMORY_CONSOLIDATION_INTERVAL_MAX,
17108
- intervalDefault: 60
16894
+ userId: input.userId,
16895
+ entries: selected,
16896
+ dropped,
16897
+ charCount,
16898
+ maxChars,
16899
+ redlineCount,
16900
+ personalCount,
16901
+ sharedCount,
16902
+ systemPolicy: redlineCount > 0 ? SYSTEM_POLICY_MARKER : ""
17109
16903
  };
17110
16904
  }
17111
- /** Options for a settings read that already knows the caller's first-read default. */
17112
- function readOptions(defaultEnabled) {
17113
- return defaultEnabled === void 0 ? {} : { defaultEnabled };
16905
+ /** Render a resolved context for a model-facing text tool result. */
16906
+ function renderMemoryContextMarkdown(result) {
16907
+ const lines = [
16908
+ `# Memory context (${result.userId})`,
16909
+ "",
16910
+ `- entries: ${result.entries.length}; chars: ${result.charCount}/${result.maxChars}; redlines: ${result.redlineCount}; personal: ${result.personalCount}; shared: ${result.sharedCount}`
16911
+ ];
16912
+ if (result.systemPolicy !== "") lines.push(`- ${result.systemPolicy}`);
16913
+ for (const entry of result.entries) {
16914
+ const marker = entry.nonOverridable ? "[REDLINE] " : entry.mode === "personal" ? "[PERSONAL] " : entry.mode === "shared" ? "[SHARED] " : "";
16915
+ lines.push("", `## ${marker}${entry.title}`, "");
16916
+ if (entry.mode === "personal") {
16917
+ lines.push(`- mode: personal; type: ${entry.type}; privacy: ${entry.privacy ?? "private"}`);
16918
+ if (entry.path !== void 0) lines.push(`- path: ${entry.path}`);
16919
+ } else if (entry.mode === "shared") {
16920
+ lines.push(`- mode: shared; scope: ${entry.scope ?? "department"}; type: ${entry.type}; privacy: ${entry.privacy ?? "normal"}`);
16921
+ lines.push(`- authority: ${entry.authority}; origin: ${entry.origin}; review: ${entry.reviewStatus}; source version: ${entry.sourceVersion}`);
16922
+ if (entry.path !== void 0) lines.push(`- path: ${entry.path}`);
16923
+ } else {
16924
+ lines.push(`- mode: ${entry.mode}; source: ${entry.sourceType} \`${entry.sourceId}\` in graph \`${entry.graphId}\``);
16925
+ lines.push(`- status: ${entry.status}; authority: ${entry.authority}; origin: ${entry.origin}; review: ${entry.reviewStatus}`);
16926
+ lines.push(`- source version: ${entry.sourceVersion}${entry.sourceCommit === void 0 ? "" : ` (${entry.sourceCommit})`}`);
16927
+ if (entry.path !== void 0) lines.push(`- path: ${entry.path}`);
16928
+ if (entry.from !== void 0 && entry.to !== void 0) lines.push(`- relation: ${entry.from} -> ${entry.to}`);
16929
+ }
16930
+ if (entry.nonOverridable) lines.push(`- ${SYSTEM_POLICY_MARKER}`);
16931
+ lines.push("", entry.body);
16932
+ }
16933
+ if (result.dropped.length > 0) {
16934
+ lines.push("", "## Dropped by budget");
16935
+ for (const drop of result.dropped) lines.push(`- ${drop.mode} ${drop.sourceType} \`${drop.sourceId}\` in graph \`${drop.graphId}\` (${drop.chars} chars)`);
16936
+ }
16937
+ return `${lines.join("\n")}\n`;
17114
16938
  }
17115
- /** Whitelist the list row so an internal field can never leak by spread. */
17116
- function listRow(entry) {
17117
- return {
17118
- id: entry.id,
17119
- type: entry.type,
17120
- title: memoryEntryTitle(entry),
17121
- sourceLabel: memoryEntrySourceLabel(entry),
17122
- sourceTime: memoryEntrySourceTime(entry),
16939
+ async function resolveSubscribedEntry(binding, graph) {
16940
+ const graphId = graph.manifest.id;
16941
+ const sourceVersion = graph.manifest.version;
16942
+ const sourceCommit = graphCommit(graph) ?? binding.sourceCommit;
16943
+ if (binding.sourceType === "node") {
16944
+ const node = graph.nodes.find((candidate) => candidate.id === binding.sourceId);
16945
+ if (node === void 0 || node.missing) return void 0;
16946
+ const document = await readGraphDocument(graph.root, node.path);
16947
+ if (document === void 0) return void 0;
16948
+ const live = readDocumentAttributes(document.frontMatter);
16949
+ const title = live.title ?? node.title ?? node.id;
16950
+ const body = document.body.trim();
16951
+ return finalizeEntry({
16952
+ mode: "subscribe",
16953
+ graphId,
16954
+ sourceType: "node",
16955
+ sourceId: node.id,
16956
+ title,
16957
+ type: live.type ?? node.type,
16958
+ authority: live.authority ?? node.authority,
16959
+ origin: live.origin ?? node.origin,
16960
+ reviewStatus: live.reviewStatus ?? node.reviewStatus,
16961
+ status: binding.status,
16962
+ sourceVersion,
16963
+ ...sourceCommit === void 0 ? {} : { sourceCommit },
16964
+ path: node.path,
16965
+ body
16966
+ });
16967
+ }
16968
+ const edge = graph.edges.find((candidate) => candidate.id === binding.sourceId);
16969
+ if (edge === void 0 || edge.missing) return void 0;
16970
+ const from = graph.nodes.find((node) => node.id === edge.from);
16971
+ const to = graph.nodes.find((node) => node.id === edge.to);
16972
+ if (from === void 0 || to === void 0) return void 0;
16973
+ const document = await readGraphDocument(graph.root, edge.docPath);
16974
+ if (document === void 0) return void 0;
16975
+ const live = readDocumentAttributes(document.frontMatter);
16976
+ const authority = strictestAuthority(live.authority ?? edge.authority, from.authority, to.authority);
16977
+ const body = document.body.trim();
16978
+ return finalizeEntry({
16979
+ mode: "subscribe",
16980
+ graphId,
16981
+ sourceType: "edge",
16982
+ sourceId: edge.id,
16983
+ title: live.title ?? edge.title ?? edge.id,
16984
+ type: live.type ?? edge.type,
16985
+ authority,
16986
+ origin: live.origin ?? edge.origin,
16987
+ reviewStatus: live.reviewStatus ?? edge.reviewStatus,
16988
+ status: binding.status,
16989
+ sourceVersion,
16990
+ ...sourceCommit === void 0 ? {} : { sourceCommit },
16991
+ ...edge.docPath === void 0 ? {} : { path: edge.docPath },
16992
+ from: edge.from,
16993
+ to: edge.to,
16994
+ body
16995
+ });
16996
+ }
16997
+ async function resolveInternalizedEntry(binding, graph, usersRoot) {
16998
+ let source;
16999
+ try {
17000
+ source = await readFile(memoryFilePath(usersRoot, binding.userId, binding.graphId, binding.sourceId), "utf8");
17001
+ } catch {
17002
+ return;
17003
+ }
17004
+ const document = splitFrontMatter(source);
17005
+ const local = readDocumentAttributes(document.frontMatter);
17006
+ const current = currentSourcePolicy(binding, graph);
17007
+ const authority = strictestAuthority(local.authority ?? "advisory", current.authority);
17008
+ const body = document.body.trim();
17009
+ return finalizeEntry({
17010
+ mode: "internalize",
17011
+ graphId: binding.graphId,
17012
+ sourceType: binding.sourceType,
17013
+ sourceId: binding.sourceId,
17014
+ title: local.title ?? current.title ?? binding.sourceId,
17015
+ type: local.type ?? current.type,
17016
+ authority,
17017
+ origin: local.origin ?? current.origin,
17018
+ reviewStatus: local.reviewStatus ?? current.reviewStatus,
17019
+ status: binding.status,
17020
+ sourceVersion: binding.sourceVersion,
17021
+ ...binding.sourceCommit === void 0 ? {} : { sourceCommit: binding.sourceCommit },
17022
+ path: binding.localPath ?? `memory/${binding.graphId}/${binding.sourceId}.md`,
17023
+ ...current.from === void 0 ? {} : { from: current.from },
17024
+ ...current.to === void 0 ? {} : { to: current.to },
17025
+ body,
17026
+ nonOverridable: current.authority === "redline"
17027
+ });
17028
+ }
17029
+ /**
17030
+ * Privacy levels that may enter a model-facing context.
17031
+ *
17032
+ * The resolver only reads the caller's own root, so `normal` and `private` stay
17033
+ * owner-scoped. `sensitive` is deliberately excluded: the design says owner-only
17034
+ * *and* redacted in logs/telemetry, and a tool result is part of the session
17035
+ * transcript. `secret` is a credential pointer, not memory content; the model
17036
+ * does not need it. Both remain readable on the memory page.
17037
+ */
17038
+ const CONTEXT_PRIVACY = /* @__PURE__ */ new Set(["normal", "private"]);
17039
+ /**
17040
+ * Resolve the caller's current `MemoryStore` entries as advisory context.
17041
+ *
17042
+ * Current aggregate snapshots and SOPs are the effective memory; daily-log
17043
+ * entries are included as episodic history but rank below the aggregates. An
17044
+ * entry that another entry `supersedes` is historical and is skipped, as is an
17045
+ * entry already represented by a binding.
17046
+ *
17047
+ * @param memoryRoot - the caller's own `<scope>/个人记忆图谱` directory.
17048
+ * @param bindingIds - source ids already resolved from bindings.
17049
+ * @param bindingContent - title+body fingerprints already resolved from bindings.
17050
+ */
17051
+ async function resolvePersonalMemoryEntries(memoryRoot, bindingIds, bindingContent) {
17052
+ const store = new MemoryStore(memoryRoot);
17053
+ let listed;
17054
+ try {
17055
+ listed = await store.listEntries();
17056
+ } catch {
17057
+ return [];
17058
+ }
17059
+ const superseded = /* @__PURE__ */ new Set();
17060
+ for (const entry of listed) if (entry.supersedes !== void 0 && entry.supersedes !== "") superseded.add(entry.supersedes);
17061
+ const seenIds = new Set(bindingIds);
17062
+ const seenContent = new Set(bindingContent);
17063
+ const entries = [];
17064
+ for (const entry of listed) {
17065
+ if (superseded.has(entry.id)) continue;
17066
+ if (!CONTEXT_PRIVACY.has(entry.privacy)) continue;
17067
+ if (entry.type === "sop" && (entry.status === "dropped" || entry.status === "promoted")) continue;
17068
+ const title = memoryEntryTitle(entry);
17069
+ const body = personalEntryBody(entry);
17070
+ if (title.trim() === "" || body.trim() === "") continue;
17071
+ const fingerprint = contentFingerprint(title, body);
17072
+ if (seenIds.has(entry.id) || seenContent.has(fingerprint)) continue;
17073
+ seenIds.add(entry.id);
17074
+ seenContent.add(fingerprint);
17075
+ entries.push(finalizePersonalEntry(entry, title, body));
17076
+ }
17077
+ return entries;
17078
+ }
17079
+ /** Map one store entry to the context shape; personal memory is always advisory. */
17080
+ function finalizePersonalEntry(entry, title, body) {
17081
+ return {
17082
+ mode: "personal",
17083
+ graphId: PERSONAL_MEMORY_GRAPH_ID,
17084
+ sourceType: "entry",
17085
+ sourceId: entry.id,
17086
+ title,
17087
+ type: entry.type,
17088
+ authority: "advisory",
17089
+ origin: entry.origin === "explicit" ? "mixed" : "ai",
17090
+ reviewStatus: "draft",
17091
+ status: "active",
17092
+ sourceVersion: entry.type === "sop" ? entry.version : 1,
17093
+ path: entry.path,
17123
17094
  privacy: entry.privacy,
17124
17095
  updatedAt: memoryEntryUpdatedAt(entry),
17125
- path: entry.path
17096
+ body,
17097
+ nonOverridable: false,
17098
+ chars: title.length + body.length + ENTRY_METADATA_CHARS
17126
17099
  };
17127
17100
  }
17128
- function entryPayload(entry) {
17101
+ /** Map one shared document to the context shape; the document keeps its authority. */
17102
+ function finalizeSharedEntry(candidate) {
17129
17103
  return {
17130
- entry,
17131
- title: memoryEntryTitle(entry),
17132
- content: memoryEntryContent(entry),
17133
- source: {
17134
- label: memoryEntrySourceLabel(entry),
17135
- at: memoryEntrySourceTime(entry),
17136
- ...entry.sourceSeqs === void 0 ? {} : { eventSeqs: entry.sourceSeqs },
17137
- ...entry.sourceSession === void 0 ? {} : { sessionId: entry.sourceSession }
17138
- }
17104
+ mode: "shared",
17105
+ graphId: SHARED_MEMORY_GRAPH_ID,
17106
+ sourceType: "node",
17107
+ sourceId: candidate.id,
17108
+ title: candidate.title,
17109
+ type: candidate.type,
17110
+ authority: candidate.authority,
17111
+ origin: candidate.origin,
17112
+ reviewStatus: candidate.reviewStatus,
17113
+ status: "active",
17114
+ sourceVersion: candidate.version,
17115
+ path: candidate.path,
17116
+ privacy: candidate.privacy,
17117
+ scope: candidate.scope,
17118
+ body: candidate.body,
17119
+ nonOverridable: candidate.authority === "redline",
17120
+ ...candidate.authority === "redline" ? { policyNote: SYSTEM_POLICY_MARKER } : {},
17121
+ chars: candidate.title.length + candidate.body.length + ENTRY_METADATA_CHARS
17139
17122
  };
17140
17123
  }
17141
- /** Ids are opaque but must never become a path or a directory traversal. */
17142
- function readEntryId(body) {
17143
- const id = typeof body.id === "string" ? body.id.trim() : "";
17144
- if (id === "" || id.length > 200 || /[\s/\\\u0000]/u.test(id)) return void 0;
17145
- return id;
17146
- }
17147
- const readNonEmptyString = (value) => typeof value === "string" && value.trim() !== "" ? value : void 0;
17148
- /** Extract and validate the patch, translating the generic `content` alias. */
17149
- function readUpdatePatch(body, entry) {
17150
- if (Object.prototype.hasOwnProperty.call(body, "userId")) return { error: fail$1(400, "userId must not be supplied; the caller is resolved from the request", "invalid") };
17151
- const hasPatchObject = Object.prototype.hasOwnProperty.call(body, "patch");
17152
- if (hasPatchObject && !isRecord$2(body.patch)) return { error: fail$1(400, "patch must be an object", "invalid") };
17153
- const source = hasPatchObject ? body.patch : body;
17154
- if (hasPatchObject) {
17155
- const extra = Object.keys(body).filter((key) => key !== "id" && key !== "patch");
17156
- if (extra.length > 0) return { error: fail$1(400, `unsupported update field(s): ${extra.join(", ")}`, "invalid") };
17157
- } else {
17158
- const extra = Object.keys(body).filter((key) => key !== "id" && !PATCH_FIELDS.has(key));
17159
- if (extra.length > 0) return { error: fail$1(400, `unsupported update field(s): ${extra.join(", ")}`, "invalid") };
17160
- }
17161
- if (Object.prototype.hasOwnProperty.call(source, "userId")) return { error: fail$1(400, "userId must not be supplied; the caller is resolved from the request", "invalid") };
17162
- const unknown = Object.keys(source).filter((key) => !PATCH_FIELDS.has(key) && (hasPatchObject || key !== "id"));
17163
- if (unknown.length > 0) return { error: fail$1(400, `unsupported update field(s): ${unknown.join(", ")}`, "invalid") };
17164
- const patch = {};
17165
- if (source.title !== void 0) {
17166
- const title = readNonEmptyString(source.title);
17167
- if (title === void 0) return { error: fail$1(400, "title must be a non-empty string", "invalid") };
17168
- patch.title = title;
17124
+ /**
17125
+ * Model-facing body for one entry.
17126
+ *
17127
+ * Only user content is rendered: `sourceSession`, `evidence`, `credentialRef`
17128
+ * and other internal pointers are deliberately absent.
17129
+ */
17130
+ function personalEntryBody(entry) {
17131
+ const content = memoryEntryContent(entry).trim();
17132
+ switch (entry.type) {
17133
+ case "preference": {
17134
+ const lines = [];
17135
+ if (entry.app !== void 0 && entry.app !== "") lines.push(`app: ${entry.app}`);
17136
+ lines.push(`topic: ${entry.topic}`, content);
17137
+ return lines.join("\n");
17138
+ }
17139
+ case "pitfall": {
17140
+ const lines = [
17141
+ `error: ${entry.errorSignature}`,
17142
+ `context: ${entry.context}`,
17143
+ `solution: ${content}`
17144
+ ];
17145
+ if (entry.appliesTo !== void 0 && entry.appliesTo.length > 0) lines.push(`applies to: ${entry.appliesTo.join(", ")}`);
17146
+ return lines.join("\n");
17147
+ }
17148
+ case "fact": {
17149
+ const lines = [];
17150
+ if (entry.scope !== void 0 && entry.scope !== "") lines.push(`scope: ${entry.scope}`);
17151
+ lines.push(`key: ${entry.key}`, `statement: ${content}`);
17152
+ return lines.join("\n");
17153
+ }
17154
+ case "episodic": {
17155
+ const lines = [`summary: ${content}`];
17156
+ if (entry.request !== void 0 && entry.request !== "") lines.push(`request: ${entry.request}`);
17157
+ if (entry.outcome !== void 0 && entry.outcome !== "") lines.push(`outcome: ${entry.outcome}`);
17158
+ return lines.join("\n");
17159
+ }
17160
+ case "sop": {
17161
+ const lines = [
17162
+ `status: ${entry.status}; version: ${String(entry.version)}`,
17163
+ `trigger: ${entry.trigger}`,
17164
+ "steps:",
17165
+ content
17166
+ ];
17167
+ if (entry.successCriteria !== void 0 && entry.successCriteria.length > 0) lines.push("success criteria:", ...entry.successCriteria.map((item) => `- ${item}`));
17168
+ if (entry.tools !== void 0 && entry.tools.length > 0) lines.push(`tools: ${entry.tools.join(", ")}`);
17169
+ return lines.join("\n");
17170
+ }
17169
17171
  }
17170
- if (source.content !== void 0) {
17171
- const content = readNonEmptyString(source.content);
17172
- if (content === void 0) return { error: fail$1(400, "content must be a non-empty string", "invalid") };
17173
- const field = CONTENT_FIELD[entry.type];
17174
- if (field === void 0) return { error: fail$1(400, `content cannot be edited on a ${entry.type} entry; edit title or steps`, "invalid") };
17175
- if (source[field] !== void 0) return { error: fail$1(400, `content conflicts with ${String(field)}`, "invalid") };
17176
- patch[String(field)] = content;
17172
+ }
17173
+ /** Identity of content used to avoid injecting the same memory twice. */
17174
+ function contentFingerprint(title, body) {
17175
+ const normalize = (value) => value.replace(/\s+/gu, " ").trim();
17176
+ return `${normalize(title)}\u0000${normalize(body)}`;
17177
+ }
17178
+ /** Current graph-side policy for a binding's source; absent source falls back to advisory. */
17179
+ function currentSourcePolicy(binding, graph) {
17180
+ if (binding.sourceType === "node") {
17181
+ const node = graph.nodes.find((candidate) => candidate.id === binding.sourceId);
17182
+ if (node === void 0) return {
17183
+ authority: "advisory",
17184
+ type: "fact",
17185
+ origin: "human",
17186
+ reviewStatus: "draft"
17187
+ };
17188
+ return {
17189
+ authority: node.authority,
17190
+ title: node.title,
17191
+ type: node.type,
17192
+ origin: node.origin,
17193
+ reviewStatus: node.reviewStatus
17194
+ };
17177
17195
  }
17178
- if (source.value !== void 0) {
17179
- const value = readNonEmptyString(source.value);
17180
- if (value === void 0) return { error: fail$1(400, "value must be a non-empty string", "invalid") };
17181
- patch.value = value;
17196
+ const edge = graph.edges.find((candidate) => candidate.id === binding.sourceId);
17197
+ if (edge === void 0) return {
17198
+ authority: "advisory",
17199
+ type: "relates_to",
17200
+ origin: "human",
17201
+ reviewStatus: "draft"
17202
+ };
17203
+ const from = graph.nodes.find((node) => node.id === edge.from);
17204
+ const to = graph.nodes.find((node) => node.id === edge.to);
17205
+ return {
17206
+ authority: strictestAuthority(edge.authority, from?.authority, to?.authority),
17207
+ title: edge.title,
17208
+ type: edge.type,
17209
+ origin: edge.origin,
17210
+ reviewStatus: edge.reviewStatus,
17211
+ from: edge.from,
17212
+ to: edge.to
17213
+ };
17214
+ }
17215
+ function finalizeEntry(input) {
17216
+ const nonOverridable = input.nonOverridable ?? input.authority === "redline";
17217
+ return {
17218
+ ...input,
17219
+ nonOverridable,
17220
+ ...nonOverridable ? { policyNote: SYSTEM_POLICY_MARKER } : {},
17221
+ chars: input.title.length + input.body.length + ENTRY_METADATA_CHARS
17222
+ };
17223
+ }
17224
+ /** Read a graph-relative document body and frontmatter; missing bodies fail closed. */
17225
+ async function readGraphDocument(root, relPath) {
17226
+ if (relPath === void 0 || relPath === "") return {
17227
+ frontMatter: null,
17228
+ body: ""
17229
+ };
17230
+ const candidates = [];
17231
+ if (isAbsolute(relPath)) candidates.push(relPath);
17232
+ else {
17233
+ if (relPath.split("/").some((segment) => segment === ".." || segment === "")) return void 0;
17234
+ candidates.push(join(root, relPath));
17235
+ candidates.push(join(root, "..", "..", relPath));
17182
17236
  }
17183
- if (source.statement !== void 0) {
17184
- const statement = readNonEmptyString(source.statement);
17185
- if (statement === void 0) return { error: fail$1(400, "statement must be a non-empty string", "invalid") };
17186
- patch.statement = statement;
17237
+ for (const candidate of candidates) try {
17238
+ return splitFrontMatter(await readFile(candidate, "utf8"));
17239
+ } catch {}
17240
+ }
17241
+ /** Parse the attributes the runtime injection reads, tolerating extra keys. */
17242
+ function readDocumentAttributes(frontMatter) {
17243
+ if (frontMatter === null || frontMatter.trim() === "") return {};
17244
+ const record = parseSimpleYaml(frontMatter);
17245
+ const text = (key) => {
17246
+ const value = record[key];
17247
+ return typeof value === "string" && value !== "" ? value : void 0;
17248
+ };
17249
+ const authority = text("authority");
17250
+ const origin = text("origin");
17251
+ const reviewStatus = text("reviewStatus");
17252
+ return {
17253
+ ...text("title") === void 0 ? {} : { title: text("title") },
17254
+ ...text("type") === void 0 ? {} : { type: text("type") },
17255
+ ...authority !== void 0 && AUTHORITIES.includes(authority) ? { authority } : {},
17256
+ ...origin !== void 0 && ORIGINS.includes(origin) ? { origin } : {},
17257
+ ...reviewStatus !== void 0 && REVIEW_STATUSES.includes(reviewStatus) ? { reviewStatus } : {}
17258
+ };
17259
+ }
17260
+ /**
17261
+ * Priority tiers: redline, canonical, advisory proxies, personal effective
17262
+ * memory, shared advisory + personal episodic history, advisory internalized.
17263
+ *
17264
+ * Department/global canonical and advisory sources outrank personal memory so a
17265
+ * department rule or definition wins a conflict. Shared memory is published for
17266
+ * the whole scope but has no subscription and stays advisory; it ranks beside
17267
+ * raw personal episodic history and is one of the first tiers a tight prompt
17268
+ * budget gives up. A redline is never dropped.
17269
+ */
17270
+ function entryTier(entry) {
17271
+ if (entry.nonOverridable || entry.authority === "redline") return 0;
17272
+ if (entry.authority === "canonical") return 1;
17273
+ if (entry.mode === "subscribe") return 2;
17274
+ if (entry.mode === "personal") return entry.type === "episodic" ? 4 : 3;
17275
+ if (entry.mode === "shared") return 4;
17276
+ return 5;
17277
+ }
17278
+ /**
17279
+ * Inside the shared/episodic tier, keep curated department context before raw
17280
+ * personal history, so a budget that fits only one still keeps the published one.
17281
+ */
17282
+ function sharedTierRank(entry) {
17283
+ return entry.mode === "shared" ? 0 : 1;
17284
+ }
17285
+ function compareEntries(left, right) {
17286
+ const leftTier = entryTier(left);
17287
+ const tier = leftTier - entryTier(right);
17288
+ if (tier !== 0) return tier;
17289
+ if (leftTier === 4) {
17290
+ const rank = sharedTierRank(left) - sharedTierRank(right);
17291
+ if (rank !== 0) return rank;
17187
17292
  }
17188
- if (source.solution !== void 0) {
17189
- const solution = readNonEmptyString(source.solution);
17190
- if (solution === void 0) return { error: fail$1(400, "solution must be a non-empty string", "invalid") };
17191
- patch.solution = solution;
17293
+ if (left.mode === "personal" && right.mode === "personal") {
17294
+ const type = personalTypeRank(left.type) - personalTypeRank(right.type);
17295
+ if (type !== 0) return type;
17296
+ const updated = compareText(right.updatedAt ?? "", left.updatedAt ?? "");
17297
+ if (updated !== 0) return updated;
17298
+ return compareText(left.sourceId, right.sourceId);
17192
17299
  }
17193
- if (source.steps !== void 0) {
17194
- const steps = source.steps;
17195
- if (!Array.isArray(steps) || steps.length === 0 || steps.some((step) => typeof step !== "string" || step.trim() === "")) return { error: fail$1(400, "steps must be a non-empty array of non-empty strings", "invalid") };
17196
- patch.steps = steps;
17300
+ const graph = compareText(left.graphId, right.graphId);
17301
+ if (graph !== 0) return graph;
17302
+ const type = sourceTypeRank(left.sourceType) - sourceTypeRank(right.sourceType);
17303
+ if (type !== 0) return type;
17304
+ return compareText(left.sourceId, right.sourceId);
17305
+ }
17306
+ /** Current effective memory first; raw episodic history last. */
17307
+ function personalTypeRank(type) {
17308
+ switch (type) {
17309
+ case "preference": return 0;
17310
+ case "pitfall": return 1;
17311
+ case "fact": return 2;
17312
+ case "sop": return 3;
17313
+ case "episodic": return 4;
17314
+ default: return 5;
17197
17315
  }
17198
- if (source.privacy !== void 0) {
17199
- if (!isPrivacy(source.privacy)) return { error: fail$1(400, "privacy must be normal, private, sensitive or secret", "invalid") };
17200
- patch.privacy = source.privacy;
17316
+ }
17317
+ function sourceTypeRank(sourceType) {
17318
+ if (sourceType === "node") return 0;
17319
+ if (sourceType === "entry") return 1;
17320
+ return 2;
17321
+ }
17322
+ function compareText(left, right) {
17323
+ return left < right ? -1 : left > right ? 1 : 0;
17324
+ }
17325
+ function normalizeMaxChars(value) {
17326
+ if (value === void 0 || !Number.isFinite(value)) return DEFAULT_MEMORY_CONTEXT_MAX_CHARS;
17327
+ return Math.max(0, Math.floor(value));
17328
+ }
17329
+ function strictestAuthority(...values) {
17330
+ let authority = "advisory";
17331
+ for (const value of values) if (value !== void 0 && AUTHORITY_RANK[value] > AUTHORITY_RANK[authority]) authority = value;
17332
+ return authority;
17333
+ }
17334
+ function graphCommit(graph) {
17335
+ const withCommit = graph;
17336
+ if (typeof withCommit.commit === "string" && withCommit.commit !== "") return withCommit.commit;
17337
+ const manifest = graph.manifest;
17338
+ if (typeof manifest.commit === "string" && manifest.commit !== "") return manifest.commit;
17339
+ if (typeof manifest.sourceCommit === "string" && manifest.sourceCommit !== "") return manifest.sourceCommit;
17340
+ }
17341
+ //#endregion
17342
+ //#region src/memoryTools.ts
17343
+ /**
17344
+ * Model-facing runtime memory tools: `memory_context` and `memory_guardian_run`.
17345
+ *
17346
+ * `memory_context` is read-only. It resolves the caller's personal binding
17347
+ * projection through {@link resolveMemoryContext}: live proxies for subscribed
17348
+ * sources, the user's own branch for internalized sources, the current entries
17349
+ * of the user's own `MemoryStore`, redlines marked non-overridable, and a
17350
+ * deterministic budget. It never writes.
17351
+ *
17352
+ * `memory_guardian_run` is the manual trigger for the guardian pass. It is a
17353
+ * maintenance action, not a read: it refreshes `sourceVersion`/`sourceCommit`,
17354
+ * resolves pending bindings, performs requested internalizations and revokes
17355
+ * branches whose source became redline. It is denied unless the Host reports the
17356
+ * `kb:config:manage` capability, and it only touches the caller's own bindings
17357
+ * root (`userIds: [caller.userId]`) plus graphs the caller may manage. The
17358
+ * scheduled guardian job remains the normal path; this tool exists for
17359
+ * operators and for a deployment without a scheduler.
17360
+ *
17361
+ * Both tools take the same injected host seam as the other knowledge tools: no
17362
+ * global config, no ambient session. The caller's viewer is resolved once per
17363
+ * call, and the backend remains the final authority for anything the tools then
17364
+ * read or write.
17365
+ *
17366
+ * @module @sparkelf/dsh-knowledge-base/memory-tools
17367
+ */
17368
+ const ZERO_GUARDIAN_RESULT = {
17369
+ createdPending: 0,
17370
+ subscribed: 0,
17371
+ internalized: 0,
17372
+ rejectedRedline: 0,
17373
+ upstreamUpdates: 0,
17374
+ revoked: 0
17375
+ };
17376
+ /**
17377
+ * Canonical output renderer shared by the tools: prefer the `rendered` text the
17378
+ * tool prepared (markdown or JSON), fall back to pretty JSON.
17379
+ */
17380
+ const textOutput$1 = {
17381
+ schema: {
17382
+ type: "object",
17383
+ additionalProperties: true
17384
+ },
17385
+ render: (_args, value) => {
17386
+ const record = value;
17387
+ return [{
17388
+ type: "text",
17389
+ text: record !== null && typeof record?.rendered === "string" ? record.rendered : JSON.stringify(value, null, 2)
17390
+ }];
17201
17391
  }
17202
- return { patch };
17392
+ };
17393
+ const run$2 = async (operation) => {
17394
+ try {
17395
+ return await operation();
17396
+ } catch (error) {
17397
+ throw asKnowledgeToolError(error);
17398
+ }
17399
+ };
17400
+ /** Build the read-only `memory_context` tool. */
17401
+ function createMemoryContextTool(host) {
17402
+ return defineTool({
17403
+ name: "memory_context",
17404
+ description: "Read the caller's memory context. Returns the caller's own remembered preferences, pitfalls, facts, methods and recent episodic memory from the memory store, approved department/global shared memory published for the caller's department (privacy normal/private only), live proxies for subscribed department/global memory sources, the caller's own internalized branches (marked stale/revoked when they diverged), and redline policy entries marked nonOverridable. Permission-denied graphs are omitted and other users' memory or other departments' shared memory is never read. Ordering is deterministic and a character budget drops shared/advisory and personal history before canonical or redline entries; redlines are never dropped. When personal memory is paused, personal entries and internalized copies are omitted but department/global policy, shared memory and redlines still apply. Read-only: this tool never writes bindings or documents.",
17405
+ parameters: {
17406
+ format: {
17407
+ type: "string",
17408
+ description: "markdown (default) or json."
17409
+ },
17410
+ maxChars: {
17411
+ type: "number",
17412
+ description: `Prompt budget in characters; default ${DEFAULT_MEMORY_CONTEXT_MAX_CHARS}.`
17413
+ }
17414
+ },
17415
+ output: textOutput$1,
17416
+ execute: async (args) => run$2(async () => {
17417
+ const viewer = await host.resolveCaller();
17418
+ const enabled = host.isMemoryEnabled === void 0 ? true : await host.isMemoryEnabled(viewer);
17419
+ const allGraphs = await host.loadGraphs(viewer);
17420
+ const sharedGraphs = host.loadSharedGraphs === void 0 ? [] : await host.loadSharedGraphs(viewer).catch(() => []);
17421
+ const graphs = enabled ? [...allGraphs, ...sharedGraphs] : [...allGraphs.filter((graph) => {
17422
+ const scope = graph.manifest.scope ?? "";
17423
+ return scope !== "personal" && !scope.startsWith("personal:");
17424
+ }), ...sharedGraphs];
17425
+ const personalMemoryRoot = enabled ? host.personalMemoryRoot?.(viewer) : void 0;
17426
+ const context = await resolveMemoryContext({
17427
+ viewer,
17428
+ usersRoot: host.usersRoot,
17429
+ userId: viewer.userId,
17430
+ graphs,
17431
+ ...enabled ? {} : { paused: true },
17432
+ ...personalMemoryRoot === void 0 ? {} : { personalMemoryRoot },
17433
+ ...args.maxChars === void 0 ? {} : { maxChars: args.maxChars }
17434
+ });
17435
+ const format = args.format === "json" ? "json" : "markdown";
17436
+ return {
17437
+ ok: true,
17438
+ format,
17439
+ rendered: format === "json" ? JSON.stringify({
17440
+ ...context,
17441
+ ...enabled ? {} : { paused: true }
17442
+ }, null, 2) : (enabled ? "" : "Personal memory is paused. Personal memories are not used; department/global policy and redlines still apply.\n\n") + renderMemoryContextMarkdown(context),
17443
+ context,
17444
+ ...enabled ? {} : { paused: true }
17445
+ };
17446
+ })
17447
+ });
17448
+ }
17449
+ /** Build the manage-gated `memory_guardian_run` tool. */
17450
+ function createMemoryGuardianRunTool(host) {
17451
+ return defineTool({
17452
+ name: "memory_guardian_run",
17453
+ description: "Run the personal memory guardian pass for the caller. It discovers new graph nodes/edges, resolves pending bindings, performs requested internalizations, refreshes sourceVersion/sourceCommit and revokes internalized branches whose source became redline. It writes only under the caller's bindings/memory root and only for graphs the caller may manage. Requires the kb:config:manage capability; the scheduled guardian job is the normal trigger, this tool is the manual operator path.",
17454
+ parameters: {},
17455
+ output: textOutput$1,
17456
+ execute: async () => run$2(async () => {
17457
+ const viewer = await host.resolveCaller();
17458
+ if (viewer.userId.trim() === "") throw new KnowledgeToolError("unauthorized", "an authenticated caller is required");
17459
+ if (!await host.canManage(viewer)) throw new KnowledgeToolError("forbidden", "memory_guardian_run requires the kb:config:manage capability");
17460
+ const manageable = (await host.loadGraphs(viewer)).filter((graph) => canManageGraph(viewer, graphScopeDescriptor(graph.manifest)));
17461
+ const runAt = (/* @__PURE__ */ new Date()).toISOString();
17462
+ const results = [];
17463
+ const totals = { ...ZERO_GUARDIAN_RESULT };
17464
+ for (const graph of manageable) {
17465
+ const result = await runGuardianPass({
17466
+ graph,
17467
+ usersRoot: host.usersRoot,
17468
+ userIds: [viewer.userId],
17469
+ ...viewer.departmentCode === void 0 ? {} : { departmentCode: viewer.departmentCode },
17470
+ now: runAt
17471
+ });
17472
+ results.push({
17473
+ graphId: graph.manifest.id,
17474
+ ...result
17475
+ });
17476
+ totals.createdPending += result.createdPending;
17477
+ totals.subscribed += result.subscribed;
17478
+ totals.internalized += result.internalized;
17479
+ totals.rejectedRedline += result.rejectedRedline;
17480
+ totals.upstreamUpdates += result.upstreamUpdates;
17481
+ totals.revoked += result.revoked;
17482
+ }
17483
+ const response = {
17484
+ ok: true,
17485
+ userId: viewer.userId,
17486
+ runAt,
17487
+ graphs: results,
17488
+ totals
17489
+ };
17490
+ if (manageable.length === 0) response.note = "no readable graph is manageable for this caller; nothing was run";
17491
+ return {
17492
+ ...response,
17493
+ rendered: JSON.stringify(response, null, 2)
17494
+ };
17495
+ })
17496
+ });
17203
17497
  }
17204
- /** Extract and validate the settings write, translating `enabled` to the stored field. */
17205
- function readSettingsPatch(body, options) {
17206
- if (Object.prototype.hasOwnProperty.call(body, "userId")) return { error: fail$1(400, "userId must not be supplied; the caller is resolved from the request", "invalid") };
17207
- const unknown = Object.keys(body).filter((key) => key !== "enabled" && key !== "consolidationIntervalMinutes");
17208
- if (unknown.length > 0) return { error: fail$1(400, `unsupported settings field(s): ${unknown.join(", ")}`, "invalid") };
17209
- if (options.requireEnabled && body.enabled === void 0) return { error: fail$1(400, "enabled must be a boolean", "invalid") };
17210
- const patch = {};
17211
- if (body.enabled !== void 0) {
17212
- if (typeof body.enabled !== "boolean") return { error: fail$1(400, "enabled must be a boolean", "invalid") };
17213
- patch.memoryEnabled = body.enabled;
17214
- }
17215
- if (body.consolidationIntervalMinutes !== void 0) try {
17216
- patch.consolidationIntervalMinutes = normalizeConsolidationInterval(body.consolidationIntervalMinutes);
17217
- } catch (error) {
17218
- if (error instanceof MemorySettingsError) return { error: fail$1(400, error.message, error.code, {
17219
- min: 15,
17220
- max: MEMORY_CONSOLIDATION_INTERVAL_MAX
17221
- }) };
17222
- throw error;
17223
- }
17224
- if (patch.memoryEnabled === void 0 && patch.consolidationIntervalMinutes === void 0) return { error: fail$1(400, "at least one memory setting must be supplied", "invalid") };
17225
- return { patch };
17498
+ /**
17499
+ * Build both runtime memory tools.
17500
+ *
17501
+ * @param host - the injected caller/graph/root seam.
17502
+ * @returns Tool definitions for the disclosure coordinator.
17503
+ */
17504
+ function createMemoryTools(host) {
17505
+ return [createMemoryContextTool(host), createMemoryGuardianRunTool(host)];
17226
17506
  }
17227
- /** Reconcile the personal-memory graph; a derived failure must not undo the write. */
17228
- async function syncGraph(graphWriter) {
17229
- try {
17230
- await graphWriter.syncAll();
17231
- return;
17232
- } catch (error) {
17233
- return messageOf$1(error);
17234
- }
17507
+ //#endregion
17508
+ //#region src/memoryGraphBootstrap.ts
17509
+ /**
17510
+ * Ensure the personal memory graph exists.
17511
+ *
17512
+ * The graph tab is a catalogue of `.graphs/<id>/graph.json` manifests. A user
17513
+ * with no subscriptions yet has no personal graph at all, which reads as "the
17514
+ * memory feature is missing" rather than "there is nothing in it". This creates
17515
+ * an empty, private, published manifest for the caller once; it is the stable
17516
+ * home the guardian will later fill with subscription proxies and internalized
17517
+ * branches.
17518
+ *
17519
+ * Writing is deliberately best-effort at the call site: a read-only mount must
17520
+ * keep the graph tab usable, so a failed bootstrap is not an error for the route.
17521
+ *
17522
+ * @module @sparkelf/dsh-knowledge-base/memory-graph-bootstrap
17523
+ */
17524
+ /** Stable graph id for the caller's personal memory graph. */
17525
+ const PERSONAL_MEMORY_GRAPH_ID$1 = "personal-memory";
17526
+ /** Display name shown in the graph tree. */
17527
+ const PERSONAL_MEMORY_GRAPH_NAME = "个人记忆图谱";
17528
+ /** One safe path segment, or undefined when it cannot be used as a file/dir name. */
17529
+ function safeSegment(value) {
17530
+ if (value === "" || value === "." || value === "..") return void 0;
17531
+ if (value.includes("/") || value.includes("\\") || value.includes("\0")) return void 0;
17532
+ return value;
17235
17533
  }
17236
- /** Map a store/validation failure to an actionable status; unknown errors escape. */
17237
- function failureOf$1(error) {
17238
- if (error instanceof MemorySettingsError) return fail$1(400, error.message, error.code);
17239
- if (error instanceof MemoryValidationError) return fail$1(400, error.message, "invalid-memory", { issues: error.issues });
17240
- if (error instanceof MemoryStoreError) {
17241
- const status = error.code === "not-found" || error.code === "sop-not-found" ? 404 : error.code === "invalid-memory-file" || error.code === "duplicate-id" || error.code === "duplicate-key" || error.code === "sop-exists" || error.code === "sop-terminal" ? 409 : 400;
17242
- return fail$1(status, error.message, error.code);
17534
+ /** The manifest a fresh personal memory graph holds. */
17535
+ function emptyPersonalMemoryManifest(userId, now) {
17536
+ return {
17537
+ schemaVersion: 1,
17538
+ id: PERSONAL_MEMORY_GRAPH_ID$1,
17539
+ name: PERSONAL_MEMORY_GRAPH_NAME,
17540
+ description: "个人订阅代理与内化记忆的默认图谱;尚未订阅或内化任何部门节点。",
17541
+ scope: "personal:" + userId,
17542
+ version: 1,
17543
+ status: "published",
17544
+ owner: userId,
17545
+ createdAt: now,
17546
+ updatedAt: now,
17547
+ publishedAt: now,
17548
+ tags: ["记忆"],
17549
+ visibility: "private",
17550
+ defaultView: {
17551
+ layout: "hierarchy",
17552
+ direction: "TB"
17553
+ },
17554
+ topics: [],
17555
+ nodes: [],
17556
+ edges: []
17557
+ };
17558
+ }
17559
+ /** Whether one path is a regular file. */
17560
+ async function isFile$1(path) {
17561
+ try {
17562
+ return (await stat(path)).isFile();
17563
+ } catch {
17564
+ return false;
17243
17565
  }
17244
- throw error;
17245
17566
  }
17246
17567
  /**
17247
- * Handle one memory-management method.
17568
+ * Create `<scopeRoot>/.graphs/personal-memory/graph.json` when it is absent.
17248
17569
  *
17249
- * The caller's identity is already resolved by the route; this function validates
17250
- * it once more before touching the filesystem and never accepts a body-supplied
17251
- * user id. Expected failures return a status/body; unexpected failures throw so the
17252
- * route's outer `try` reports a real 500 instead of a misleading 400.
17570
+ * @param options.scopeRoot - absolute personal scope root (`<actualRoot>/personal/<uid>`).
17571
+ * @param options.userId - stable caller id; also the manifest owner.
17572
+ * @param options.now - injectable clock for tests.
17573
+ * @returns whether the manifest was created and its absolute path.
17253
17574
  */
17254
- async function handleMemoryRoute(input) {
17255
- const { method, caller, store, settings, graphWriter } = input;
17256
- if (!isSafeUserId(caller.userId)) return fail$1(403, "unsafe caller id; memory is scoped to the authenticated user", "forbidden");
17257
- const body = isRecord$2(input.body) ? input.body : {};
17258
- try {
17259
- switch (method) {
17260
- case "memory.list": {
17261
- const [settingsState, entries] = await Promise.all([settings.read(caller.userId, readOptions(input.defaultEnabled)), store.listEntries()]);
17262
- return ok$1({
17263
- enabled: settingsState.memoryEnabled,
17264
- entries: entries.map(listRow)
17265
- });
17266
- }
17267
- case "memory.get": {
17268
- const id = readEntryId(body);
17269
- if (id === void 0) return fail$1(400, "a safe entry id is required", "invalid");
17270
- const entry = await store.getEntry(id);
17271
- if (entry === void 0) return fail$1(404, "memory entry not found", "not-found");
17272
- return ok$1(entryPayload(entry));
17273
- }
17274
- case "memory.update": {
17275
- const id = readEntryId(body);
17276
- if (id === void 0) return fail$1(400, "a safe entry id is required", "invalid");
17277
- const entry = await store.getEntry(id);
17278
- if (entry === void 0) return fail$1(404, "memory entry not found", "not-found");
17279
- const built = readUpdatePatch(body, entry);
17280
- if ("error" in built) return built.error;
17281
- const updated = await store.updateEntry(id, built.patch);
17282
- const graphSyncWarning = await syncGraph(graphWriter);
17283
- return ok$1({
17284
- ...entryPayload(updated),
17285
- ...graphSyncWarning === void 0 ? {} : { graphSyncWarning }
17286
- });
17287
- }
17288
- case "memory.forget": {
17289
- const id = readEntryId(body);
17290
- if (id === void 0) return fail$1(400, "a safe entry id is required", "invalid");
17291
- const forgotten = await store.forgetEntry(id);
17292
- const graphSyncWarning = forgotten.removed ? await syncGraph(graphWriter) : void 0;
17293
- return ok$1({
17294
- ...forgotten,
17295
- ...graphSyncWarning === void 0 ? {} : { graphSyncWarning }
17296
- });
17297
- }
17298
- case "memory.settings": return ok$1(settingsPayload(await settings.read(caller.userId, readOptions(input.defaultEnabled))));
17299
- case "memory.set-enabled": {
17300
- const built = readSettingsPatch(body, { requireEnabled: true });
17301
- if ("error" in built) return built.error;
17302
- const next = await settings.save(caller.userId, built.patch, readOptions(input.defaultEnabled));
17303
- return ok$1(settingsPayload(next));
17304
- }
17305
- case "memory.save-settings": {
17306
- const built = readSettingsPatch(body, { requireEnabled: false });
17307
- if ("error" in built) return built.error;
17308
- const next = await settings.save(caller.userId, built.patch, readOptions(input.defaultEnabled));
17309
- return ok$1(settingsPayload(next));
17310
- }
17311
- default: return fail$1(404, `unknown memory method: ${method}`, "not-found");
17312
- }
17313
- } catch (error) {
17314
- return failureOf$1(error);
17315
- }
17575
+ async function ensurePersonalMemoryGraph(options) {
17576
+ const userId = safeSegment(options.userId);
17577
+ if (userId === void 0) throw new Error("memory-graph: unsafe userId");
17578
+ const graphId = safeSegment(PERSONAL_MEMORY_GRAPH_ID$1);
17579
+ if (graphId === void 0) throw new Error("memory-graph: unsafe graph id");
17580
+ const directory = join(options.scopeRoot, ".graphs", graphId);
17581
+ const path = join(directory, "graph.json");
17582
+ if (await isFile$1(path)) return {
17583
+ created: false,
17584
+ path
17585
+ };
17586
+ const manifest = emptyPersonalMemoryManifest(userId, options.now ?? (/* @__PURE__ */ new Date()).toISOString());
17587
+ await mkdir(directory, { recursive: true });
17588
+ const temporary = join(directory, ".graph.json." + String(process.pid) + ".tmp");
17589
+ await writeFile(temporary, JSON.stringify(manifest, null, 2) + "\n", "utf8");
17590
+ await rename(temporary, path);
17591
+ return {
17592
+ created: true,
17593
+ path
17594
+ };
17316
17595
  }
17317
17596
  //#endregion
17318
- //#region src/memoryPromotion.ts
17597
+ //#region src/memorySettings.ts
17319
17598
  /**
17320
- * Promotion of a personal memory or SOP into department/global memory.
17599
+ * Per-user memory settings: whether personal memory learning is enabled and how
17600
+ * often the guardian consolidates what it learned.
17321
17601
  *
17322
- * Personal memory is private by construction. Sharing it with a department or the
17323
- * whole platform is not a copy the guardian makes on its own: it is a product
17324
- * decision that needs a second pair of eyes (design §17.4, §21.2, §22). This module
17325
- * owns that decision and its audit trail:
17602
+ * The product rule (design §22.2) is deliberately conservative:
17326
17603
  *
17327
- * - a promotion is a durable record with a **pending → approved | rejected**
17328
- * lifecycle; a rejected or approved record is never silently rewritten;
17329
- * - only a caller who already holds review authority for the target scope may
17330
- * create or decide one — `kb:config:manage` for global, the department review
17331
- * scope for `department:<code>`;
17332
- * - a request can never be approved by the person who made it. An administrator
17333
- * who wants their own memory shared uses the explicit `confirm` path, which is a
17334
- * different, separately-audited action;
17335
- * - only `privacy: normal` content is promotable. `private`, `sensitive` and
17336
- * `secret` memories are refused rather than downgraded, because a promotion is
17337
- * an irreversible widening of who can read them;
17338
- * - approval writes a real shared memory document and a graph node under the
17339
- * target scope, so the existing knowledge-base permissions (not this module)
17340
- * decide who can read it.
17604
+ * - a new user is **paused** (`memoryEnabled: false`), so no extraction starts
17605
+ * until the user explicitly confirms the enable dialog;
17606
+ * - an administrator or super administrator (a holder of the configured DataOps
17607
+ * permission, by default `kb:config:manage`) starts **enabled** on the first
17608
+ * read when no settings file exists yet. The global default is never flipped:
17609
+ * the administrator decision is injected through {@link MemorySettingsDefaultPolicy},
17610
+ * and an explicit `false` written by that administrator always wins;
17611
+ * - the switch is per user, not per session, and survives restarts;
17612
+ * - the file is local state under `<usersRoot>/<userId>/settings.json`, never
17613
+ * knowledge content and never Git content;
17614
+ * - a missing or unreadable file is a valid "paused" answer, not an error. Only
17615
+ * a filesystem permission failure is surfaced.
17341
17616
  *
17342
- * The store is product metadata (a review queue), not knowledge content: it lives
17343
- * beside the per-user binding state, never inside a document tree, and holds one
17344
- * JSON file committed by atomic rename.
17617
+ * The persisted shape is version 2 (`memoryEnabled` + `consolidationIntervalMinutes`).
17618
+ * Version 1 files (only `memoryEnabled`, or even a hand-written bare boolean) are
17619
+ * still read: a missing interval falls back to 60 minutes, and a malformed
17620
+ * interval never turns a remembered enable/disable decision into a different one.
17345
17621
  *
17346
- * @module @sparkelf/dsh-knowledge-base/memory-promotion
17347
- */
17348
- /** Graph id that owns promoted department/global memory inside one scope. */
17349
- const SHARED_MEMORY_GRAPH_ID = "shared-memory";
17350
- /** Folder (relative to the scope root) that holds one document per promotion. */
17351
- const SHARED_MEMORY_FOLDER = "记忆共享";
17352
- /** Display name per graph scope. */
17353
- function sharedMemoryGraphName(scope) {
17354
- return scope === "global" ? "全局共享记忆" : "部门共享记忆";
17355
- }
17356
- /** A structured refusal the route maps to a status code. */
17357
- var MemoryPromotionError = class extends Error {
17622
+ * The route/UI layer reads `read()` or `isEnabled()` and writes through
17623
+ * `save()`; every write is atomic (tmp + rename) and persists both fields in one
17624
+ * rename so a page save can never leave the switch and the interval disagreeing.
17625
+ *
17626
+ * @module @sparkelf/dsh-knowledge-base/memory-settings
17627
+ */
17628
+ /** File name inside one user's directory. */
17629
+ const MEMORY_SETTINGS_FILE = "settings.json";
17630
+ /** Longest allowed consolidation interval, in minutes. */
17631
+ const MEMORY_CONSOLIDATION_INTERVAL_MAX = 1440;
17632
+ /** The paused default for a user who has never confirmed the enable dialog. */
17633
+ const DEFAULT_MEMORY_SETTINGS = Object.freeze({
17634
+ version: 2,
17635
+ memoryEnabled: false,
17636
+ consolidationIntervalMinutes: 60
17637
+ });
17638
+ /** A malformed interval or write patch; the route maps this to HTTP 400. */
17639
+ var MemorySettingsError = class extends Error {
17358
17640
  code;
17359
- name = "MemoryPromotionError";
17641
+ name = "MemorySettingsError";
17360
17642
  constructor(code, message) {
17361
17643
  super(message);
17362
17644
  this.code = code;
17363
17645
  }
17364
17646
  };
17365
- /** The submitter may request a promotion only inside a scope they can review. */
17366
- function decidePromotionScope(reviewer, scope, departmentCode) {
17367
- if (scope === "global") {
17368
- if (!reviewer.isGlobalAdmin || !reviewer.canManageConfig) return {
17369
- ok: false,
17370
- code: "forbidden",
17371
- message: "只有管理员/超级管理员可以把记忆晋升到全局。"
17372
- };
17373
- return { ok: true };
17374
- }
17375
- const code = (departmentCode ?? reviewer.departmentCode ?? "").trim();
17376
- if (code === "") return {
17377
- ok: false,
17378
- code: "invalid",
17379
- message: "晋升到部门必须指定部门。"
17380
- };
17381
- if (reviewer.departmentCode === void 0 || code !== reviewer.departmentCode) return {
17382
- ok: false,
17383
- code: "forbidden",
17384
- message: "只能晋升到当前账号所属部门。"
17385
- };
17386
- if (!reviewer.isGlobalAdmin && !reviewer.reviewDepartments.includes(code)) return {
17387
- ok: false,
17388
- code: "forbidden",
17389
- message: "只能晋升到本部门管理范围内的记忆。"
17390
- };
17391
- return {
17392
- ok: true,
17393
- departmentCode: code,
17394
- departmentPath: reviewer.departmentPathCodes !== void 0 && reviewer.departmentPathCodes.length > 0 ? [...reviewer.departmentPathCodes] : [code]
17395
- };
17396
- }
17397
- /** Whether one reviewer may decide a promotion aimed at its target scope. */
17398
- function canReviewPromotion(reviewer, target) {
17399
- if (target.scope === "global") return reviewer.isGlobalAdmin;
17400
- const code = target.departmentCode ?? "";
17401
- if (code === "") return false;
17402
- return reviewer.isGlobalAdmin || reviewer.reviewDepartments.includes(code);
17403
- }
17404
17647
  /**
17405
- * Whether one approved promotion is visible to a viewer.
17648
+ * Validate one consolidation interval.
17406
17649
  *
17407
- * A department promotion is visible to the viewer whose organization path contains
17408
- * that department (own department and its ancestors) or whose data scope names it.
17409
- * The source owner always keeps seeing their own approved memory.
17650
+ * The guard is strict on purpose: a fractional value or a value outside
17651
+ * 15–1440 is a client bug, not a number to clamp silently. The route turns this
17652
+ * error into a 400 so the page can show the allowed range.
17653
+ *
17654
+ * @param value - raw value from an API body or a hand-edited file.
17655
+ * @returns the accepted integer.
17656
+ * @throws {MemorySettingsError} when the value is not an integer in range.
17410
17657
  */
17411
- function isPromotionVisibleTo(record, viewer) {
17412
- if (record.target.scope === "global") return true;
17413
- if (record.source.userId === viewer.userId) return true;
17414
- if (viewer.isGlobalAdmin) return true;
17415
- const code = record.target.departmentCode ?? "";
17416
- if (code === "") return false;
17417
- if (viewer.departmentCode === code) return true;
17418
- if (viewer.departmentPathCodes?.includes(code) === true) return true;
17419
- if (viewer.visibleDepartmentCodes?.includes(code) === true) return true;
17420
- return viewer.reviewDepartments.includes(code);
17658
+ function normalizeConsolidationInterval(value) {
17659
+ if (typeof value !== "number" || !Number.isInteger(value)) throw new MemorySettingsError("invalid-interval", "consolidationIntervalMinutes must be an integer");
17660
+ if (value < 15 || value > 1440) throw new MemorySettingsError("invalid-interval", `consolidationIntervalMinutes must be between ${String(15)} and ${String(MEMORY_CONSOLIDATION_INTERVAL_MAX)}`);
17661
+ return value;
17662
+ }
17663
+ /** Read a stored interval leniently: an invalid legacy value falls back to 60. */
17664
+ function readStoredInterval(value) {
17665
+ try {
17666
+ return normalizeConsolidationInterval(value);
17667
+ } catch {
17668
+ return 60;
17669
+ }
17421
17670
  }
17422
17671
  /**
17423
- * The scope root one target writes under, WITHOUT a trailing slash.
17672
+ * Atomic settings store over `<usersRoot>/<userId>/settings.json`.
17424
17673
  *
17425
- * DataOps grants are matched against this exact resource id (a trailing slash is a
17426
- * different id and matches nothing), so every permission question must use this
17427
- * spelling. Directory joining adds the slash separately.
17674
+ * `read()` tolerates a corrupt file by returning the paused default; the next
17675
+ * write rewrites it. This keeps the memory page usable after a partial write or
17676
+ * a hand-edited file instead of failing the whole route.
17428
17677
  */
17429
- function targetScopeRoot(target) {
17430
- if (target.scope === "global") return "global";
17431
- return "department/" + (target.departmentPath !== void 0 && target.departmentPath.length > 0 ? target.departmentPath : target.departmentCode === void 0 ? [] : [target.departmentCode]).join("/");
17432
- }
17433
- /** The scope-relative prefix one target writes under (`global/`, `department/A/B/`). */
17434
- function targetScopePrefix(target) {
17435
- return targetScopeRoot(target) + "/";
17436
- }
17437
- /** Where the review queue lives for one deployment's per-user memory root. */
17438
- function promotionStorePath(memoryUsersRoot) {
17439
- return join(dirname(resolve(memoryUsersRoot)), "promotions.json");
17440
- }
17441
- /** Map a stored memory type onto the graph's smaller node vocabulary. */
17442
- function sharedNodeTypeOf(type) {
17443
- switch (type) {
17444
- case "preference": return "topic";
17445
- case "pitfall": return "case";
17446
- case "episodic": return "case";
17447
- case "fact": return "fact";
17448
- case "sop": return "procedure";
17678
+ var MemorySettingsStore = class {
17679
+ usersRoot;
17680
+ defaultPolicy;
17681
+ constructor(usersRoot, defaultPolicy) {
17682
+ if (typeof usersRoot !== "string" || usersRoot.trim() === "") throw new Error("memory-settings: usersRoot must be a non-empty path");
17683
+ this.usersRoot = usersRoot;
17684
+ this.defaultPolicy = defaultPolicy;
17449
17685
  }
17450
- }
17451
- /** The text a promotion copies into the shared document. */
17452
- function promotionContentOf(entry) {
17453
- switch (entry.type) {
17454
- case "preference": return entry.value;
17455
- case "pitfall": return [
17456
- "现象:" + entry.errorSignature,
17457
- "原因:" + entry.context,
17458
- "解决:" + entry.solution
17459
- ].join("\n\n");
17460
- case "episodic": return entry.summary;
17461
- case "fact": return entry.statement;
17462
- case "sop": {
17463
- const parts = ["触发条件:" + entry.trigger, entry.steps.map((step, index) => `${String(index + 1)}. ${step}`).join("\n")];
17464
- if (entry.successCriteria !== void 0 && entry.successCriteria.length > 0) parts.push(entry.successCriteria.map((item) => "- " + item).join("\n"));
17465
- return parts.join("\n\n");
17686
+ /** Absolute settings file for one user. */
17687
+ filePath(userId) {
17688
+ assertPathSegment(userId, "userId");
17689
+ return join(this.usersRoot, userId, MEMORY_SETTINGS_FILE);
17690
+ }
17691
+ /** The first-read default for one user, from the injected policy. */
17692
+ async defaultFor(userId, options) {
17693
+ if (options.defaultEnabled !== void 0) return {
17694
+ ...DEFAULT_MEMORY_SETTINGS,
17695
+ memoryEnabled: options.defaultEnabled === true
17696
+ };
17697
+ if (this.defaultPolicy === void 0) return { ...DEFAULT_MEMORY_SETTINGS };
17698
+ try {
17699
+ return {
17700
+ ...DEFAULT_MEMORY_SETTINGS,
17701
+ memoryEnabled: await this.defaultPolicy.memoryEnabled(userId) === true
17702
+ };
17703
+ } catch {
17704
+ return { ...DEFAULT_MEMORY_SETTINGS };
17466
17705
  }
17467
17706
  }
17468
- }
17469
- /** The short title a shared row shows; mirrors the personal page's rules. */
17470
- function promotionTitleOf(entry) {
17471
- if (typeof entry.displayTitle === "string" && entry.displayTitle.trim() !== "") return clipTitle(entry.displayTitle.trim());
17472
- switch (entry.type) {
17473
- case "preference": return looksTechnical(entry.value) ? "偏好记录" : clipTitle(entry.value);
17474
- case "pitfall": return looksTechnical(entry.errorSignature) ? "踩坑记录" : clipTitle(entry.errorSignature);
17475
- case "episodic":
17476
- if (entry.tags?.includes("SOP评估")) return "方法评估";
17477
- if (entry.tags?.includes("SOP晋升")) return "方法晋升";
17478
- if (entry.tags?.includes("idle")) return "空闲触发";
17479
- if (entry.tags?.includes("compaction")) return "压缩触发";
17480
- if (entry.tags?.includes("dream")) return "记忆整理";
17481
- return "情景记录";
17482
- case "fact": return looksTechnical(entry.key) ? "事实记录" : clipTitle(entry.key);
17483
- case "sop": return clipTitle(entry.title);
17707
+ /**
17708
+ * Read one user's settings.
17709
+ *
17710
+ * Missing content uses {@link MemorySettingsReadOptions.defaultEnabled} or the
17711
+ * injected policy. Malformed content stays paused even for an administrator:
17712
+ * a corrupt file is not evidence that the administrator opted in. A file with
17713
+ * a boolean `memoryEnabled` is accepted even if `version`/the interval is
17714
+ * missing, so old settings files keep their explicit choice.
17715
+ */
17716
+ async read(userId, options = {}) {
17717
+ let source;
17718
+ try {
17719
+ source = await readFile(this.filePath(userId), "utf8");
17720
+ } catch (error) {
17721
+ if (isErrno$1(error, "ENOENT") || isErrno$1(error, "ENOTDIR")) return this.defaultFor(userId, options);
17722
+ throw error;
17723
+ }
17724
+ let parsed;
17725
+ try {
17726
+ parsed = JSON.parse(source);
17727
+ } catch {
17728
+ return { ...DEFAULT_MEMORY_SETTINGS };
17729
+ }
17730
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return { ...DEFAULT_MEMORY_SETTINGS };
17731
+ const memoryEnabled = parsed.memoryEnabled;
17732
+ if (typeof memoryEnabled !== "boolean") return { ...DEFAULT_MEMORY_SETTINGS };
17733
+ return {
17734
+ version: 2,
17735
+ memoryEnabled,
17736
+ consolidationIntervalMinutes: readStoredInterval(parsed.consolidationIntervalMinutes)
17737
+ };
17484
17738
  }
17485
- }
17486
- /** Whitespace-collapsed, bounded title; never a technical identifier on its own. */
17487
- function clipTitle(value) {
17488
- const clean = value.replace(/\s+/gu, " ").trim();
17489
- return clean.length <= 40 ? clean : `${clean.slice(0, 39)}…`;
17490
- }
17491
- /** A technical token that should not be the first thing a reader sees in a row. */
17492
- function looksTechnical(value) {
17493
- if (/[\\/]|session-|kb_[a-z]|\.md\b|\bSOP\b|[a-z]+_[a-z]+/iu.test(value)) return true;
17494
- return value.trim().length > 12 && /^[a-z0-9._-]+$/u.test(value.trim());
17495
- }
17496
- const EMPTY_STORE = {
17497
- version: 1,
17498
- promotions: []
17499
- };
17500
- const writeQueues = /* @__PURE__ */ new Map();
17501
- /** Serialize mutations of one store path so two requests cannot overwrite each other. */
17502
- function serialize(path, operation) {
17503
- const next = (writeQueues.get(path) ?? Promise.resolve()).then(operation, operation);
17504
- writeQueues.set(path, next.then(() => void 0, () => void 0));
17505
- return next;
17506
- }
17507
- /** Read the queue, treating absence as empty and quarantining corrupt JSON. */
17508
- async function readPromotionStore(path) {
17509
- let raw;
17510
- try {
17511
- raw = await readFile(path, "utf8");
17512
- } catch (error) {
17513
- if (error.code === "ENOENT") return EMPTY_STORE;
17514
- throw new MemoryPromotionError("io", `could not read ${path}: ${String(error)}`);
17739
+ /** Whether learning is enabled for this user (default `false`). */
17740
+ async isEnabled(userId, options = {}) {
17741
+ return (await this.read(userId, options)).memoryEnabled;
17515
17742
  }
17516
- try {
17517
- const parsed = JSON.parse(raw);
17518
- if (parsed === null || typeof parsed !== "object") throw new Error("not an object");
17519
- const candidate = parsed;
17520
- if (candidate.version !== 1 || !Array.isArray(candidate.promotions)) throw new Error("wrong shape");
17521
- return {
17522
- version: 1,
17523
- promotions: candidate.promotions
17743
+ /**
17744
+ * Persist a partial settings change in one atomic write.
17745
+ *
17746
+ * The current value is read first so a page that saves only the interval
17747
+ * cannot accidentally pause memory (nor enable it). An explicit boolean in
17748
+ * the patch always wins; an absent field is preserved.
17749
+ *
17750
+ * @returns the normalized settings actually written.
17751
+ */
17752
+ async save(userId, patch, options = {}) {
17753
+ if (patch.memoryEnabled === void 0 && patch.consolidationIntervalMinutes === void 0) throw new MemorySettingsError("invalid-settings", "at least one memory setting must be supplied");
17754
+ if (patch.memoryEnabled !== void 0 && typeof patch.memoryEnabled !== "boolean") throw new MemorySettingsError("invalid-settings", "memoryEnabled must be a boolean");
17755
+ const interval = patch.consolidationIntervalMinutes === void 0 ? void 0 : normalizeConsolidationInterval(patch.consolidationIntervalMinutes);
17756
+ const current = await this.read(userId, options);
17757
+ const settings = {
17758
+ version: 2,
17759
+ memoryEnabled: patch.memoryEnabled ?? current.memoryEnabled,
17760
+ consolidationIntervalMinutes: interval ?? current.consolidationIntervalMinutes
17524
17761
  };
17525
- } catch {
17526
- await rename(path, `${path}.corrupt-${String(Date.now())}`).catch(() => void 0);
17527
- return EMPTY_STORE;
17762
+ await writeFileAtomic(this.filePath(userId), `${JSON.stringify(settings, null, 2)}\n`, { mode: 384 });
17763
+ return settings;
17528
17764
  }
17765
+ /**
17766
+ * Persist the enable/pause switch atomically, preserving the interval.
17767
+ *
17768
+ * @returns the normalized settings actually written.
17769
+ */
17770
+ async setEnabled(userId, enabled, options = {}) {
17771
+ if (typeof enabled !== "boolean") throw new MemorySettingsError("invalid-settings", "memoryEnabled must be a boolean");
17772
+ return this.save(userId, { memoryEnabled: enabled }, options);
17773
+ }
17774
+ /** Persist one interval while preserving the switch. */
17775
+ async setConsolidationInterval(userId, minutes, options = {}) {
17776
+ return this.save(userId, { consolidationIntervalMinutes: minutes }, options);
17777
+ }
17778
+ };
17779
+ function isErrno$1(error, code) {
17780
+ return typeof error === "object" && error !== null && "code" in error && error.code === code;
17529
17781
  }
17530
- /** Commit the queue atomically. */
17531
- async function writePromotionStore(path, store) {
17532
- await writeFileAtomic(path, JSON.stringify(store, null, 2) + "\n");
17533
- }
17534
- /** Read every promotion, oldest first. */
17535
- async function listPromotionRecords(path) {
17536
- return (await readPromotionStore(path)).promotions;
17537
- }
17538
- const MAX_TITLE = 200;
17539
- const MAX_CONTENT = 2e4;
17540
- /** Reject a request that cannot be shared safely or written to a graph. */
17541
- function normalizePromotionDraft(draft) {
17542
- if (draft.source.privacy !== "normal") throw new MemoryPromotionError("privacy", "只有隐私为「普通」的记忆可以晋升;仅自己、敏感和凭据引用不会被共享。");
17543
- const title = draft.source.title.trim();
17544
- if (title === "" || title.length > MAX_TITLE) throw new MemoryPromotionError("invalid", `a promotion title must be 1–${String(MAX_TITLE)} characters`);
17545
- const content = draft.source.content.trim();
17546
- if (content === "" || content.length > MAX_CONTENT) throw new MemoryPromotionError("invalid", `a promotion body must be 1–${String(MAX_CONTENT)} characters`);
17547
- if (draft.target.scope === "department" && (draft.target.departmentCode ?? "").trim() === "") throw new MemoryPromotionError("invalid", "a department promotion needs a department code");
17782
+ //#endregion
17783
+ //#region src/memoryRoutes.ts
17784
+ const PATCH_FIELDS = /* @__PURE__ */ new Set([
17785
+ "title",
17786
+ "content",
17787
+ "value",
17788
+ "statement",
17789
+ "solution",
17790
+ "steps",
17791
+ "privacy"
17792
+ ]);
17793
+ /** Which single field `content` corrects, per memory type. SOP uses `steps`. */
17794
+ const CONTENT_FIELD = {
17795
+ preference: "value",
17796
+ pitfall: "solution",
17797
+ episodic: "summary",
17798
+ fact: "statement"
17799
+ };
17800
+ const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
17801
+ const messageOf$1 = (error) => error instanceof Error ? error.message : String(error);
17802
+ const ok$1 = (body) => ({
17803
+ status: 200,
17804
+ body
17805
+ });
17806
+ const fail$1 = (status, error, code, extra) => ({
17807
+ status,
17808
+ body: {
17809
+ error,
17810
+ ...code === void 0 ? {} : { code },
17811
+ ...extra
17812
+ }
17813
+ });
17814
+ /** The settings shape the page reads; bounds travel with the value so the UI never guesses. */
17815
+ function settingsPayload(settings) {
17548
17816
  return {
17549
- source: {
17550
- ...draft.source,
17551
- title,
17552
- content
17553
- },
17554
- target: draft.target
17817
+ enabled: settings.memoryEnabled,
17818
+ consolidationIntervalMinutes: settings.consolidationIntervalMinutes,
17819
+ intervalMin: 15,
17820
+ intervalMax: MEMORY_CONSOLIDATION_INTERVAL_MAX,
17821
+ intervalDefault: 60
17555
17822
  };
17556
17823
  }
17557
- /** Create one pending request, or return the identical pending one. */
17558
- async function createPromotionRequest(path, draft, actor, now = () => /* @__PURE__ */ new Date()) {
17559
- const normalized = normalizePromotionDraft(draft);
17560
- return serialize(path, async () => {
17561
- const store = await readPromotionStore(path);
17562
- const duplicate = store.promotions.find((item) => item.status === "pending" && item.source.userId === normalized.source.userId && item.source.memoryId === normalized.source.memoryId && item.target.scope === normalized.target.scope && (item.target.departmentCode ?? "") === (normalized.target.departmentCode ?? ""));
17563
- if (duplicate !== void 0) return {
17564
- record: duplicate,
17565
- duplicate: true
17566
- };
17567
- const at = now().toISOString();
17568
- const id = "mp-" + randomUUID();
17569
- const record = {
17570
- id,
17571
- status: "pending",
17572
- source: normalized.source,
17573
- target: {
17574
- ...normalized.target,
17575
- docPath: `${SHARED_MEMORY_FOLDER}/${id}.md`
17576
- },
17577
- requestedBy: actor,
17578
- requestedAt: at,
17579
- confirmed: false,
17580
- audit: [{
17581
- at,
17582
- actorId: actor.id,
17583
- actorName: actor.name,
17584
- action: "requested",
17585
- detail: {
17586
- scope: normalized.target.scope,
17587
- ...normalized.target.departmentCode === void 0 ? {} : { departmentCode: normalized.target.departmentCode },
17588
- targetGraph: normalized.target.graphId,
17589
- memoryId: normalized.source.memoryId
17590
- }
17591
- }]
17592
- };
17593
- await writePromotionStore(path, {
17594
- version: 1,
17595
- promotions: [...store.promotions, record]
17596
- });
17597
- return {
17598
- record,
17599
- duplicate: false
17600
- };
17601
- });
17602
- }
17603
- /** Load one promotion by id. */
17604
- async function getPromotionRecord(path, id) {
17605
- return (await readPromotionStore(path)).promotions.find((item) => item.id === id);
17606
- }
17607
- /** Mark one pending promotion approved after its shared document is on disk. */
17608
- async function markPromotionApproved(path, id, reviewer, appliedPath, options, now = () => /* @__PURE__ */ new Date()) {
17609
- return serialize(path, async () => {
17610
- const store = await readPromotionStore(path);
17611
- const record = store.promotions.find((item) => item.id === id);
17612
- if (record === void 0) throw new MemoryPromotionError("not-found", `no promotion with id ${id}`);
17613
- if (record.status !== "pending") throw new MemoryPromotionError("conflict", `promotion ${id} is already ${record.status}`);
17614
- const at = now().toISOString();
17615
- const next = {
17616
- ...record,
17617
- status: "approved",
17618
- reviewedBy: reviewer,
17619
- reviewedAt: at,
17620
- confirmed: options.confirmed,
17621
- appliedAt: at,
17622
- ...options.note === void 0 || options.note.trim() === "" ? {} : { reviewNote: options.note.trim() },
17623
- audit: [...record.audit, {
17624
- at,
17625
- actorId: reviewer.id,
17626
- actorName: reviewer.name,
17627
- action: options.confirmed ? "confirmed" : "approved",
17628
- detail: {
17629
- appliedPath,
17630
- scope: record.target.scope
17631
- }
17632
- }]
17633
- };
17634
- await writePromotionStore(path, {
17635
- version: 1,
17636
- promotions: store.promotions.map((item) => item.id === id ? next : item)
17637
- });
17638
- return next;
17639
- });
17640
- }
17641
- /** Mark one pending promotion rejected, keeping the reason. */
17642
- async function markPromotionRejected(path, id, reviewer, note, now = () => /* @__PURE__ */ new Date()) {
17643
- return serialize(path, async () => {
17644
- const store = await readPromotionStore(path);
17645
- const record = store.promotions.find((item) => item.id === id);
17646
- if (record === void 0) throw new MemoryPromotionError("not-found", `no promotion with id ${id}`);
17647
- if (record.status !== "pending") throw new MemoryPromotionError("conflict", `promotion ${id} is already ${record.status}`);
17648
- const at = now().toISOString();
17649
- const next = {
17650
- ...record,
17651
- status: "rejected",
17652
- reviewedBy: reviewer,
17653
- reviewedAt: at,
17654
- ...note === void 0 || note.trim() === "" ? {} : { reviewNote: note.trim() },
17655
- audit: [...record.audit, {
17656
- at,
17657
- actorId: reviewer.id,
17658
- actorName: reviewer.name,
17659
- action: "rejected",
17660
- ...note === void 0 || note.trim() === "" ? {} : { detail: { note: note.trim() } }
17661
- }]
17662
- };
17663
- await writePromotionStore(path, {
17664
- version: 1,
17665
- promotions: store.promotions.map((item) => item.id === id ? next : item)
17666
- });
17667
- return next;
17668
- });
17824
+ /** Options for a settings read that already knows the caller's first-read default. */
17825
+ function readOptions(defaultEnabled) {
17826
+ return defaultEnabled === void 0 ? {} : { defaultEnabled };
17669
17827
  }
17670
- /** Quote a value for the hand-written YAML front matter. */
17671
- function yamlQuoted(value) {
17672
- return JSON.stringify(value.replace(/\s+/gu, " ").trim());
17828
+ /** Whitelist the list row so an internal field can never leak by spread. */
17829
+ function listRow(entry) {
17830
+ return {
17831
+ id: entry.id,
17832
+ type: entry.type,
17833
+ title: memoryEntryTitle(entry),
17834
+ sourceLabel: memoryEntrySourceLabel(entry),
17835
+ sourceTime: memoryEntrySourceTime(entry),
17836
+ privacy: entry.privacy,
17837
+ updatedAt: memoryEntryUpdatedAt(entry),
17838
+ path: entry.path
17839
+ };
17673
17840
  }
17674
- /** Compose the shared document: front matter for the graph loader, then the body. */
17675
- function renderSharedMemoryDocument(record, now) {
17676
- const tags = record.target.scope === "global" ? ["记忆", "全局共享"] : ["记忆", "部门共享"];
17677
- return [
17678
- "---",
17679
- `id: mem-${record.id}`,
17680
- `type: ${sharedNodeTypeOf(record.source.memoryType)}`,
17681
- `title: ${yamlQuoted(record.source.title)}`,
17682
- "authority: advisory",
17683
- "internalizable: true",
17684
- "origin: human",
17685
- "reviewStatus: approved",
17686
- `tags: [${tags.join(", ")}]`,
17687
- `promotedAt: ${now}`,
17688
- `promotionId: ${record.id}`,
17689
- `scope: ${record.target.scope === "global" ? "global" : "department:" + (record.target.departmentCode ?? "")}`,
17690
- "---",
17691
- "",
17692
- `# ${record.source.title}`,
17693
- "",
17694
- record.source.content,
17695
- "",
17696
- "---",
17697
- "",
17698
- `由 ${record.reviewedBy?.name ?? record.requestedBy.name} 于 ${now} 审核晋升。`,
17699
- ""
17700
- ].join("\n");
17841
+ function entryPayload(entry) {
17842
+ return {
17843
+ entry,
17844
+ title: memoryEntryTitle(entry),
17845
+ content: memoryEntryContent(entry),
17846
+ source: {
17847
+ label: memoryEntrySourceLabel(entry),
17848
+ at: memoryEntrySourceTime(entry),
17849
+ ...entry.sourceSeqs === void 0 ? {} : { eventSeqs: entry.sourceSeqs },
17850
+ ...entry.sourceSession === void 0 ? {} : { sessionId: entry.sourceSession }
17851
+ }
17852
+ };
17701
17853
  }
17702
- const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
17703
- /** Read one shared graph, returning undefined when it has not been created yet. */
17704
- async function readSharedGraph(graphPath) {
17705
- let raw;
17706
- try {
17707
- raw = await readFile(graphPath, "utf8");
17854
+ /** Ids are opaque but must never become a path or a directory traversal. */
17855
+ function readEntryId(body) {
17856
+ const id = typeof body.id === "string" ? body.id.trim() : "";
17857
+ if (id === "" || id.length > 200 || /[\s/\\\u0000]/u.test(id)) return void 0;
17858
+ return id;
17859
+ }
17860
+ const readNonEmptyString = (value) => typeof value === "string" && value.trim() !== "" ? value : void 0;
17861
+ /** Extract and validate the patch, translating the generic `content` alias. */
17862
+ function readUpdatePatch(body, entry) {
17863
+ if (Object.prototype.hasOwnProperty.call(body, "userId")) return { error: fail$1(400, "userId must not be supplied; the caller is resolved from the request", "invalid") };
17864
+ const hasPatchObject = Object.prototype.hasOwnProperty.call(body, "patch");
17865
+ if (hasPatchObject && !isRecord$1(body.patch)) return { error: fail$1(400, "patch must be an object", "invalid") };
17866
+ const source = hasPatchObject ? body.patch : body;
17867
+ if (hasPatchObject) {
17868
+ const extra = Object.keys(body).filter((key) => key !== "id" && key !== "patch");
17869
+ if (extra.length > 0) return { error: fail$1(400, `unsupported update field(s): ${extra.join(", ")}`, "invalid") };
17870
+ } else {
17871
+ const extra = Object.keys(body).filter((key) => key !== "id" && !PATCH_FIELDS.has(key));
17872
+ if (extra.length > 0) return { error: fail$1(400, `unsupported update field(s): ${extra.join(", ")}`, "invalid") };
17873
+ }
17874
+ if (Object.prototype.hasOwnProperty.call(source, "userId")) return { error: fail$1(400, "userId must not be supplied; the caller is resolved from the request", "invalid") };
17875
+ const unknown = Object.keys(source).filter((key) => !PATCH_FIELDS.has(key) && (hasPatchObject || key !== "id"));
17876
+ if (unknown.length > 0) return { error: fail$1(400, `unsupported update field(s): ${unknown.join(", ")}`, "invalid") };
17877
+ const patch = {};
17878
+ if (source.title !== void 0) {
17879
+ const title = readNonEmptyString(source.title);
17880
+ if (title === void 0) return { error: fail$1(400, "title must be a non-empty string", "invalid") };
17881
+ patch.title = title;
17882
+ }
17883
+ if (source.content !== void 0) {
17884
+ const content = readNonEmptyString(source.content);
17885
+ if (content === void 0) return { error: fail$1(400, "content must be a non-empty string", "invalid") };
17886
+ const field = CONTENT_FIELD[entry.type];
17887
+ if (field === void 0) return { error: fail$1(400, `content cannot be edited on a ${entry.type} entry; edit title or steps`, "invalid") };
17888
+ if (source[field] !== void 0) return { error: fail$1(400, `content conflicts with ${String(field)}`, "invalid") };
17889
+ patch[String(field)] = content;
17890
+ }
17891
+ if (source.value !== void 0) {
17892
+ const value = readNonEmptyString(source.value);
17893
+ if (value === void 0) return { error: fail$1(400, "value must be a non-empty string", "invalid") };
17894
+ patch.value = value;
17895
+ }
17896
+ if (source.statement !== void 0) {
17897
+ const statement = readNonEmptyString(source.statement);
17898
+ if (statement === void 0) return { error: fail$1(400, "statement must be a non-empty string", "invalid") };
17899
+ patch.statement = statement;
17900
+ }
17901
+ if (source.solution !== void 0) {
17902
+ const solution = readNonEmptyString(source.solution);
17903
+ if (solution === void 0) return { error: fail$1(400, "solution must be a non-empty string", "invalid") };
17904
+ patch.solution = solution;
17905
+ }
17906
+ if (source.steps !== void 0) {
17907
+ const steps = source.steps;
17908
+ if (!Array.isArray(steps) || steps.length === 0 || steps.some((step) => typeof step !== "string" || step.trim() === "")) return { error: fail$1(400, "steps must be a non-empty array of non-empty strings", "invalid") };
17909
+ patch.steps = steps;
17910
+ }
17911
+ if (source.privacy !== void 0) {
17912
+ if (!isPrivacy(source.privacy)) return { error: fail$1(400, "privacy must be normal, private, sensitive or secret", "invalid") };
17913
+ patch.privacy = source.privacy;
17914
+ }
17915
+ return { patch };
17916
+ }
17917
+ /** Extract and validate the settings write, translating `enabled` to the stored field. */
17918
+ function readSettingsPatch(body, options) {
17919
+ if (Object.prototype.hasOwnProperty.call(body, "userId")) return { error: fail$1(400, "userId must not be supplied; the caller is resolved from the request", "invalid") };
17920
+ const unknown = Object.keys(body).filter((key) => key !== "enabled" && key !== "consolidationIntervalMinutes");
17921
+ if (unknown.length > 0) return { error: fail$1(400, `unsupported settings field(s): ${unknown.join(", ")}`, "invalid") };
17922
+ if (options.requireEnabled && body.enabled === void 0) return { error: fail$1(400, "enabled must be a boolean", "invalid") };
17923
+ const patch = {};
17924
+ if (body.enabled !== void 0) {
17925
+ if (typeof body.enabled !== "boolean") return { error: fail$1(400, "enabled must be a boolean", "invalid") };
17926
+ patch.memoryEnabled = body.enabled;
17927
+ }
17928
+ if (body.consolidationIntervalMinutes !== void 0) try {
17929
+ patch.consolidationIntervalMinutes = normalizeConsolidationInterval(body.consolidationIntervalMinutes);
17708
17930
  } catch (error) {
17709
- if (error.code === "ENOENT") return void 0;
17710
- throw new MemoryPromotionError("io", `could not read ${graphPath}: ${String(error)}`);
17931
+ if (error instanceof MemorySettingsError) return { error: fail$1(400, error.message, error.code, {
17932
+ min: 15,
17933
+ max: MEMORY_CONSOLIDATION_INTERVAL_MAX
17934
+ }) };
17935
+ throw error;
17711
17936
  }
17937
+ if (patch.memoryEnabled === void 0 && patch.consolidationIntervalMinutes === void 0) return { error: fail$1(400, "at least one memory setting must be supplied", "invalid") };
17938
+ return { patch };
17939
+ }
17940
+ /** Reconcile the personal-memory graph; a derived failure must not undo the write. */
17941
+ async function syncGraph(graphWriter) {
17712
17942
  try {
17713
- const parsed = JSON.parse(raw);
17714
- if (!isRecord$1(parsed) || parsed.schemaVersion !== 1 || !Array.isArray(parsed.nodes)) throw new Error("wrong shape");
17715
- return parsed;
17716
- } catch {
17717
- throw new MemoryPromotionError("invalid-graph", `shared memory graph is not readable: ${graphPath}`);
17943
+ await graphWriter.syncAll();
17944
+ return;
17945
+ } catch (error) {
17946
+ return messageOf$1(error);
17718
17947
  }
17719
17948
  }
17720
- /** Compose a fresh manifest for one target scope. */
17721
- function newSharedGraph(record, now) {
17722
- return {
17723
- schemaVersion: 1,
17724
- id: SHARED_MEMORY_GRAPH_ID,
17725
- name: sharedMemoryGraphName(record.target.scope),
17726
- description: record.target.scope === "global" ? "经审核晋升到全局的共享记忆;只读展示。" : "经审核晋升到本部门的共享记忆;只读展示。",
17727
- scope: record.target.scope === "global" ? "global" : "department:" + (record.target.departmentCode ?? ""),
17728
- version: 1,
17729
- status: "published",
17730
- owner: record.reviewedBy?.id ?? record.requestedBy.id,
17731
- createdAt: now,
17732
- updatedAt: now,
17733
- publishedAt: now,
17734
- tags: ["记忆", "共享"],
17735
- visibility: record.target.scope,
17736
- defaultView: {
17737
- layout: "hierarchy",
17738
- direction: "TB"
17739
- },
17740
- topics: [],
17741
- nodes: [],
17742
- edges: []
17743
- };
17949
+ /** Map a store/validation failure to an actionable status; unknown errors escape. */
17950
+ function failureOf$1(error) {
17951
+ if (error instanceof MemorySettingsError) return fail$1(400, error.message, error.code);
17952
+ if (error instanceof MemoryValidationError) return fail$1(400, error.message, "invalid-memory", { issues: error.issues });
17953
+ if (error instanceof MemoryStoreError) {
17954
+ const status = error.code === "not-found" || error.code === "sop-not-found" ? 404 : error.code === "invalid-memory-file" || error.code === "duplicate-id" || error.code === "duplicate-key" || error.code === "sop-exists" || error.code === "sop-terminal" ? 409 : 400;
17955
+ return fail$1(status, error.message, error.code);
17956
+ }
17957
+ throw error;
17744
17958
  }
17745
17959
  /**
17746
- * Write an approved promotion into the target scope and register it in the shared
17747
- * memory graph.
17960
+ * Handle one memory-management method.
17748
17961
  *
17749
- * The document is written first and the manifest second: if the manifest write
17750
- * fails, the next approval retries both and the orphan document is harmless (it is
17751
- * not referenced). The reverse order would publish a broken node.
17962
+ * The caller's identity is already resolved by the route; this function validates
17963
+ * it once more before touching the filesystem and never accepts a body-supplied
17964
+ * user id. Expected failures return a status/body; unexpected failures throw so the
17965
+ * route's outer `try` reports a real 500 instead of a misleading 400.
17752
17966
  */
17753
- async function applyPromotionToSharedMemory(input) {
17754
- const { record, scopeRoot } = input;
17755
- const now = input.now ?? (/* @__PURE__ */ new Date()).toISOString();
17756
- if (record.status !== "pending") throw new MemoryPromotionError("conflict", `promotion ${record.id} is already ${record.status}`);
17757
- const docRelPath = `${SHARED_MEMORY_FOLDER}/${record.id}.md`;
17758
- if (record.target.docPath !== docRelPath) throw new MemoryPromotionError("invalid", "the stored promotion path does not match its id");
17759
- const docPath = join(scopeRoot, SHARED_MEMORY_FOLDER, `${record.id}.md`);
17760
- const graphPath = join(scopeRoot, ".graphs", SHARED_MEMORY_GRAPH_ID, "graph.json");
17761
- await writeFileAtomic(docPath, renderSharedMemoryDocument(record, now));
17762
- await serialize(graphPath, async () => {
17763
- const existing = await readSharedGraph(graphPath);
17764
- const manifest = existing === void 0 ? newSharedGraph(record, now) : {
17765
- ...existing,
17766
- version: (Number.isFinite(existing.version) ? existing.version : 0) + 1,
17767
- updatedAt: now,
17768
- publishedAt: now,
17769
- status: "published",
17770
- visibility: record.target.scope,
17771
- scope: record.target.scope === "global" ? "global" : "department:" + (record.target.departmentCode ?? ""),
17772
- tags: [.../* @__PURE__ */ new Set([
17773
- ...existing.tags ?? [],
17774
- "记忆",
17775
- "共享"
17776
- ])]
17777
- };
17778
- const nodeId = "mem-" + record.id;
17779
- if (!manifest.nodes.some((node) => node.id === nodeId || node.path === docRelPath)) manifest.nodes = [...manifest.nodes, {
17780
- id: nodeId,
17781
- path: docRelPath
17782
- }];
17783
- await writeFileAtomic(graphPath, JSON.stringify(manifest, null, 2) + "\n");
17784
- });
17785
- return {
17786
- docPath,
17787
- graphPath,
17788
- graphId: SHARED_MEMORY_GRAPH_ID
17789
- };
17967
+ async function handleMemoryRoute(input) {
17968
+ const { method, caller, store, settings, graphWriter } = input;
17969
+ if (!isSafeUserId(caller.userId)) return fail$1(403, "unsafe caller id; memory is scoped to the authenticated user", "forbidden");
17970
+ const body = isRecord$1(input.body) ? input.body : {};
17971
+ try {
17972
+ switch (method) {
17973
+ case "memory.list": {
17974
+ const [settingsState, entries] = await Promise.all([settings.read(caller.userId, readOptions(input.defaultEnabled)), store.listEntries()]);
17975
+ return ok$1({
17976
+ enabled: settingsState.memoryEnabled,
17977
+ entries: entries.map(listRow)
17978
+ });
17979
+ }
17980
+ case "memory.get": {
17981
+ const id = readEntryId(body);
17982
+ if (id === void 0) return fail$1(400, "a safe entry id is required", "invalid");
17983
+ const entry = await store.getEntry(id);
17984
+ if (entry === void 0) return fail$1(404, "memory entry not found", "not-found");
17985
+ return ok$1(entryPayload(entry));
17986
+ }
17987
+ case "memory.update": {
17988
+ const id = readEntryId(body);
17989
+ if (id === void 0) return fail$1(400, "a safe entry id is required", "invalid");
17990
+ const entry = await store.getEntry(id);
17991
+ if (entry === void 0) return fail$1(404, "memory entry not found", "not-found");
17992
+ const built = readUpdatePatch(body, entry);
17993
+ if ("error" in built) return built.error;
17994
+ const updated = await store.updateEntry(id, built.patch);
17995
+ const graphSyncWarning = await syncGraph(graphWriter);
17996
+ return ok$1({
17997
+ ...entryPayload(updated),
17998
+ ...graphSyncWarning === void 0 ? {} : { graphSyncWarning }
17999
+ });
18000
+ }
18001
+ case "memory.forget": {
18002
+ const id = readEntryId(body);
18003
+ if (id === void 0) return fail$1(400, "a safe entry id is required", "invalid");
18004
+ const forgotten = await store.forgetEntry(id);
18005
+ const graphSyncWarning = forgotten.removed ? await syncGraph(graphWriter) : void 0;
18006
+ return ok$1({
18007
+ ...forgotten,
18008
+ ...graphSyncWarning === void 0 ? {} : { graphSyncWarning }
18009
+ });
18010
+ }
18011
+ case "memory.settings": return ok$1(settingsPayload(await settings.read(caller.userId, readOptions(input.defaultEnabled))));
18012
+ case "memory.set-enabled": {
18013
+ const built = readSettingsPatch(body, { requireEnabled: true });
18014
+ if ("error" in built) return built.error;
18015
+ const next = await settings.save(caller.userId, built.patch, readOptions(input.defaultEnabled));
18016
+ return ok$1(settingsPayload(next));
18017
+ }
18018
+ case "memory.save-settings": {
18019
+ const built = readSettingsPatch(body, { requireEnabled: false });
18020
+ if ("error" in built) return built.error;
18021
+ const next = await settings.save(caller.userId, built.patch, readOptions(input.defaultEnabled));
18022
+ return ok$1(settingsPayload(next));
18023
+ }
18024
+ default: return fail$1(404, `unknown memory method: ${method}`, "not-found");
18025
+ }
18026
+ } catch (error) {
18027
+ return failureOf$1(error);
18028
+ }
17790
18029
  }
17791
18030
  //#endregion
17792
18031
  //#region src/memoryPromotionRoutes.ts
@@ -28151,6 +28390,29 @@ function apply(ctx, deploymentConfig) {
28151
28390
  if (!isSafeUserId(userId)) throw new KnowledgeToolError("forbidden", "unsafe caller id");
28152
28391
  return join(localConfig(config).actualRoot, "personal", userId);
28153
28392
  };
28393
+ /**
28394
+ * Load the department/global shared-memory graphs the caller may read.
28395
+ *
28396
+ * A promotion writes `<scope>/记忆共享/<id>.md` and
28397
+ * `<scope>/.graphs/shared-memory/graph.json` beside the `知识图谱` folder, so the
28398
+ * ordinary graph-tab loader never sees it. The scope list is the caller's own
28399
+ * department chain plus `global` — never a sibling department — and DataOps
28400
+ * `canRead` is asked once for each scope root, the same gate `memory.shared`
28401
+ * uses. An absent graph or an unreadable manifest is normal and skips the scope.
28402
+ */
28403
+ const loadSharedMemoryGraphs = async () => {
28404
+ const caller = await fetchCaller(host, config);
28405
+ if (!isSafeUserId(caller.userId)) throw new KnowledgeToolError("forbidden", "unsafe caller id");
28406
+ const actualRoot = localConfig(config).actualRoot;
28407
+ const graphs = [];
28408
+ for (const scope of sharedMemoryScopeRoots(caller)) {
28409
+ if (!await canReadPath(host, config, scope.relPath)) continue;
28410
+ try {
28411
+ graphs.push(await loadGraph(join(actualRoot, scope.relPath), SHARED_MEMORY_GRAPH_ID));
28412
+ } catch {}
28413
+ }
28414
+ return graphs;
28415
+ };
28154
28416
  const memoryToolHost = {
28155
28417
  resolveCaller: async () => {
28156
28418
  const caller = await managementHost.context();
@@ -28173,6 +28435,7 @@ function apply(ctx, deploymentConfig) {
28173
28435
  const roots = await knowledgeGraphScopeRoots(host, config, caller);
28174
28436
  return (await loadGraphJsonScopeSets(host, config, roots, caller.userId)).flatMap((set) => set.graphs);
28175
28437
  },
28438
+ loadSharedGraphs: async () => loadSharedMemoryGraphs(),
28176
28439
  canManage: async () => {
28177
28440
  return hasPermission(await managementHost.context(), "kb:config:manage");
28178
28441
  },