@sparkelf/dsh-knowledge-base 0.5.4 → 0.6.1

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
@@ -1007,11 +1007,11 @@ async function readWorkflowStore(path) {
1007
1007
  return EMPTY;
1008
1008
  }
1009
1009
  }
1010
- const writeQueues = /* @__PURE__ */ new Map();
1010
+ const writeQueues$1 = /* @__PURE__ */ new Map();
1011
1011
  /** Serialize all mutations of one store path. */
1012
- function serialize(path, operation) {
1013
- const next = (writeQueues.get(path) ?? Promise.resolve()).then(operation, operation);
1014
- writeQueues.set(path, next.then(() => void 0, () => void 0));
1012
+ function serialize$1(path, operation) {
1013
+ const next = (writeQueues$1.get(path) ?? Promise.resolve()).then(operation, operation);
1014
+ writeQueues$1.set(path, next.then(() => void 0, () => void 0));
1015
1015
  return next;
1016
1016
  }
1017
1017
  /** Commit the store atomically (write beside it, then rename). */
@@ -1037,7 +1037,7 @@ async function writeWorkflowStore(path, store) {
1037
1037
  */
1038
1038
  async function publishWorkflow(path, input, actor, sourceSessionId, now = () => /* @__PURE__ */ new Date()) {
1039
1039
  const normalized = normalizePublishInput(input);
1040
- return serialize(path, async () => {
1040
+ return serialize$1(path, async () => {
1041
1041
  const store = await readWorkflowStore(path);
1042
1042
  const titleKey = normalTitle(normalized.title);
1043
1043
  const duplicate = store.workflows.find((item) => item.status === "pending" && item.authorId === actor.id && normalTitle(item.title) === titleKey);
@@ -1074,7 +1074,7 @@ async function publishWorkflow(path, input, actor, sourceSessionId, now = () =>
1074
1074
  }
1075
1075
  /** Mark one local workflow unpublished (retained for the owner's history). */
1076
1076
  async function unpublishPublishedWorkflow(path, id, actor, now = () => /* @__PURE__ */ new Date()) {
1077
- return serialize(path, async () => {
1077
+ return serialize$1(path, async () => {
1078
1078
  const store = await readWorkflowStore(path);
1079
1079
  const record = store.workflows.find((item) => item.id === id);
1080
1080
  if (record === void 0) throw new WorkflowPublishError("not-found", `no workflow with id ${id}`);
@@ -1106,7 +1106,7 @@ async function listWorkflowsForAuthor(path, authorId) {
1106
1106
  }
1107
1107
  /** Put one rejected/unpublished workflow back into the pending review queue. */
1108
1108
  async function resubmitPublishedWorkflow(path, id, actor, now = () => /* @__PURE__ */ new Date()) {
1109
- return serialize(path, async () => {
1109
+ return serialize$1(path, async () => {
1110
1110
  const store = await readWorkflowStore(path);
1111
1111
  const record = store.workflows.find((item) => item.id === id);
1112
1112
  if (record === void 0) throw new WorkflowPublishError("not-found", `no workflow with id ${id}`);
@@ -1148,7 +1148,7 @@ async function listPendingWorkflows(path) {
1148
1148
  async function reviewWorkflow(path, id, decision, actor, note, now = () => /* @__PURE__ */ new Date()) {
1149
1149
  const reviewNote = typeof note === "string" ? note.trim().slice(0, 2e3) : "";
1150
1150
  if (decision !== "approve" && decision !== "reject") throw new WorkflowPublishError("invalid", "decision must be approve or reject");
1151
- return serialize(path, async () => {
1151
+ return serialize$1(path, async () => {
1152
1152
  const store = await readWorkflowStore(path);
1153
1153
  const record = store.workflows.find((item) => item.id === id);
1154
1154
  if (record === void 0) throw new WorkflowPublishError("not-found", `no workflow with id ${id}`);
@@ -1884,7 +1884,7 @@ const DEFAULT_REVIEW_STATUS = "draft";
1884
1884
  /** Deterministic string order (code units, locale independent). */
1885
1885
  const compareText$3 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
1886
1886
  /** Whether two strings name the same file system entry using simple code-unit order. */
1887
- const isRecord$7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1887
+ const isRecord$9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1888
1888
  /** Whether an fs error carries the given errno code. */
1889
1889
  const isErrnoCode$4 = (error, code) => typeof error === "object" && error !== null && "code" in error && error.code === code;
1890
1890
  const errorIssue$1 = (code, message, ref) => ref === void 0 ? {
@@ -2292,7 +2292,7 @@ const parseManifest = (raw, graphId, manifestPath) => {
2292
2292
  const report = (message) => {
2293
2293
  issues.push(errorIssue$1("invalid-manifest", message, manifestPath));
2294
2294
  };
2295
- if (!isRecord$7(raw)) {
2295
+ if (!isRecord$9(raw)) {
2296
2296
  report("graph.json must contain a JSON object");
2297
2297
  return {
2298
2298
  manifest: emptyManifest(graphId),
@@ -2316,7 +2316,7 @@ const parseManifest = (raw, graphId, manifestPath) => {
2316
2316
  const visibility = requiredEnum(raw.visibility, VISIBILITIES, "private", "visibility", report);
2317
2317
  let defaultView;
2318
2318
  if (raw.defaultView !== void 0) {
2319
- if (!isRecord$7(raw.defaultView)) report("\"defaultView\" must be an object");
2319
+ if (!isRecord$9(raw.defaultView)) report("\"defaultView\" must be an object");
2320
2320
  else defaultView = {
2321
2321
  layout: optionalString$1(raw.defaultView.layout, "defaultView.layout", report),
2322
2322
  direction: optionalString$1(raw.defaultView.direction, "defaultView.direction", report)
@@ -2328,7 +2328,7 @@ const parseManifest = (raw, graphId, manifestPath) => {
2328
2328
  else {
2329
2329
  const parsedTopics = [];
2330
2330
  raw.topics.forEach((item, index) => {
2331
- if (!isRecord$7(item) || typeof item.id !== "string" || item.id.trim() === "" || typeof item.title !== "string" || item.title.trim() === "") {
2331
+ if (!isRecord$9(item) || typeof item.id !== "string" || item.id.trim() === "" || typeof item.title !== "string" || item.title.trim() === "") {
2332
2332
  report(`"topics[${index}]" must have a non-empty "id" and "title"`);
2333
2333
  return;
2334
2334
  }
@@ -2348,7 +2348,7 @@ const parseManifest = (raw, graphId, manifestPath) => {
2348
2348
  const nodes = [];
2349
2349
  if (!Array.isArray(raw.nodes)) report("\"nodes\" must be an array");
2350
2350
  else raw.nodes.forEach((item, index) => {
2351
- if (!isRecord$7(item) || typeof item.id !== "string" || item.id.trim() === "" || typeof item.path !== "string" || item.path.trim() === "") {
2351
+ if (!isRecord$9(item) || typeof item.id !== "string" || item.id.trim() === "" || typeof item.path !== "string" || item.path.trim() === "") {
2352
2352
  report(`"nodes[${index}]" must have a non-empty "id" and "path"`);
2353
2353
  return;
2354
2354
  }
@@ -2360,7 +2360,7 @@ const parseManifest = (raw, graphId, manifestPath) => {
2360
2360
  const edges = [];
2361
2361
  if (!Array.isArray(raw.edges)) report("\"edges\" must be an array");
2362
2362
  else raw.edges.forEach((item, index) => {
2363
- if (!isRecord$7(item) || typeof item.id !== "string" || item.id.trim() === "" || typeof item.from !== "string" || item.from.trim() === "" || typeof item.to !== "string" || item.to.trim() === "" || typeof item.type !== "string" || item.type.trim() === "") {
2363
+ if (!isRecord$9(item) || typeof item.id !== "string" || item.id.trim() === "" || typeof item.from !== "string" || item.from.trim() === "" || typeof item.to !== "string" || item.to.trim() === "" || typeof item.type !== "string" || item.type.trim() === "") {
2364
2364
  report(`"edges[${index}]" must have non-empty "id", "from", "to" and "type"`);
2365
2365
  return;
2366
2366
  }
@@ -3855,7 +3855,7 @@ function checkField(field, value, groundingChunks, subjectChunks, rejected, sect
3855
3855
  missing: missingSubjects
3856
3856
  }));
3857
3857
  }
3858
- function isRecord$6(value) {
3858
+ function isRecord$8(value) {
3859
3859
  return typeof value === "object" && value !== null && !Array.isArray(value);
3860
3860
  }
3861
3861
  function normalizeHeadingPath(value) {
@@ -3884,7 +3884,7 @@ function keyFactOf(value, section, field, rejected) {
3884
3884
  value: text
3885
3885
  };
3886
3886
  }
3887
- if (!isRecord$6(value)) {
3887
+ if (!isRecord$8(value)) {
3888
3888
  rejected.push(rejection(field, "keyFact 必须是字符串或 {fact,value,chunkId} 对象", { sectionId: section.sectionId }));
3889
3889
  return;
3890
3890
  }
@@ -3935,7 +3935,7 @@ function planOutlineSave(input) {
3935
3935
  let keyFactCount = 0;
3936
3936
  for (const [index, raw] of submittedSections.entries()) {
3937
3937
  const field = `sections[${String(index)}]`;
3938
- if (!isRecord$6(raw)) {
3938
+ if (!isRecord$8(raw)) {
3939
3939
  rejected.push(rejection(field, "section 必须是对象"));
3940
3940
  continue;
3941
3941
  }
@@ -9442,7 +9442,7 @@ const GRAPH_CREATE_SCOPES = [
9442
9442
  "department",
9443
9443
  "global"
9444
9444
  ];
9445
- const isRecord$5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9445
+ const isRecord$7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9446
9446
  const messageOf$2 = (error) => error instanceof Error ? error.message : String(error);
9447
9447
  /** A manifest timestamp / trash suffix, safe as one path segment. */
9448
9448
  function stamp() {
@@ -10071,15 +10071,15 @@ function parseManifestRecord(text, graphId) {
10071
10071
  } catch (error) {
10072
10072
  throw new KnowledgeToolError("invalid", "graph.json is not valid JSON: " + messageOf$2(error), graphId);
10073
10073
  }
10074
- if (!isRecord$5(parsed)) throw new KnowledgeToolError("invalid", "graph.json must contain a JSON object", graphId);
10074
+ if (!isRecord$7(parsed)) throw new KnowledgeToolError("invalid", "graph.json must contain a JSON object", graphId);
10075
10075
  if (parsed.schemaVersion !== 1) throw new KnowledgeToolError("invalid", "graph.json \"schemaVersion\" must be 1", graphId);
10076
10076
  if (typeof parsed.id !== "string" || parsed.id !== graphId) throw new KnowledgeToolError("invalid", `graph.json id ${JSON.stringify(parsed.id)} does not match its .graphs directory "${graphId}"`, graphId);
10077
10077
  if (!Array.isArray(parsed.nodes) || !Array.isArray(parsed.edges)) throw new KnowledgeToolError("invalid", "graph.json \"nodes\" and \"edges\" must be arrays", graphId);
10078
10078
  parsed.nodes.forEach((item, index) => {
10079
- if (!isRecord$5(item) || typeof item.id !== "string" || item.id.trim() === "" || typeof item.path !== "string" || item.path.trim() === "") throw new KnowledgeToolError("invalid", `graph.json "nodes[${index}]" must have a non-empty "id" and "path"`, graphId);
10079
+ if (!isRecord$7(item) || typeof item.id !== "string" || item.id.trim() === "" || typeof item.path !== "string" || item.path.trim() === "") throw new KnowledgeToolError("invalid", `graph.json "nodes[${index}]" must have a non-empty "id" and "path"`, graphId);
10080
10080
  });
10081
10081
  parsed.edges.forEach((item, index) => {
10082
- if (!isRecord$5(item) || typeof item.id !== "string" || item.id.trim() === "" || typeof item.from !== "string" || item.from.trim() === "" || typeof item.to !== "string" || item.to.trim() === "" || typeof item.type !== "string" || item.type.trim() === "") throw new KnowledgeToolError("invalid", `graph.json "edges[${index}]" must have non-empty "id", "from", "to" and "type"`, graphId);
10082
+ if (!isRecord$7(item) || typeof item.id !== "string" || item.id.trim() === "" || typeof item.from !== "string" || item.from.trim() === "" || typeof item.to !== "string" || item.to.trim() === "" || typeof item.type !== "string" || item.type.trim() === "") throw new KnowledgeToolError("invalid", `graph.json "edges[${index}]" must have non-empty "id", "from", "to" and "type"`, graphId);
10083
10083
  if (item.doc !== void 0 && typeof item.doc !== "string") throw new KnowledgeToolError("invalid", `graph.json "edges[${index}].doc" must be a string`, graphId);
10084
10084
  });
10085
10085
  return {
@@ -10780,7 +10780,7 @@ async function hiddenExists(host, relPath) {
10780
10780
  }
10781
10781
  /** Parse and validate one link record; returns undefined for an unusable row. */
10782
10782
  function parseOverviewLink(value) {
10783
- if (!isRecord$5(value)) return void 0;
10783
+ if (!isRecord$7(value)) return void 0;
10784
10784
  const id = typeof value.id === "string" ? value.id.trim() : "";
10785
10785
  const fromGraph = typeof value.fromGraph === "string" ? value.fromGraph.trim() : "";
10786
10786
  const from = typeof value.from === "string" ? value.from.trim() : "";
@@ -10848,7 +10848,7 @@ async function loadOverviewLinks(host, scope) {
10848
10848
  actualPath
10849
10849
  };
10850
10850
  }
10851
- if (!isRecord$5(parsed) || parsed.schemaVersion !== 1 || !Array.isArray(parsed.links)) return {
10851
+ if (!isRecord$7(parsed) || parsed.schemaVersion !== 1 || !Array.isArray(parsed.links)) return {
10852
10852
  links: [],
10853
10853
  issues: ["links.json must be {\"schemaVersion\":1,\"links\":[...]}"],
10854
10854
  actualPath
@@ -13200,7 +13200,7 @@ const pathExists$1 = async (path) => {
13200
13200
  throw error;
13201
13201
  }
13202
13202
  };
13203
- const isRecord$4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
13203
+ const isRecord$6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
13204
13204
  /** Read the previous baseline; a corrupt file is an error rather than a full re-summary. */
13205
13205
  const readSnapshot = async (snapshotPath) => {
13206
13206
  let raw;
@@ -13216,10 +13216,10 @@ const readSnapshot = async (snapshotPath) => {
13216
13216
  } catch {
13217
13217
  throw new Error(`summary snapshot ${snapshotPath} is not valid JSON; delete it to rebuild the baseline`);
13218
13218
  }
13219
- if (!isRecord$4(parsed) || !isRecord$4(parsed.files)) throw new Error(`summary snapshot ${snapshotPath} is not a ChangeSnapshot; delete it to rebuild the baseline`);
13219
+ if (!isRecord$6(parsed) || !isRecord$6(parsed.files)) throw new Error(`summary snapshot ${snapshotPath} is not a ChangeSnapshot; delete it to rebuild the baseline`);
13220
13220
  const files = {};
13221
13221
  for (const [relPath, entry] of Object.entries(parsed.files)) {
13222
- if (!isRecord$4(entry) || typeof entry.mtimeMs !== "number" || typeof entry.sha256 !== "string") throw new Error(`summary snapshot ${snapshotPath} has an invalid entry for ${relPath}`);
13222
+ if (!isRecord$6(entry) || typeof entry.mtimeMs !== "number" || typeof entry.sha256 !== "string") throw new Error(`summary snapshot ${snapshotPath} has an invalid entry for ${relPath}`);
13223
13223
  files[relPath] = {
13224
13224
  mtimeMs: entry.mtimeMs,
13225
13225
  sha256: entry.sha256
@@ -13847,7 +13847,7 @@ function assertBinding(binding) {
13847
13847
  if (typeof binding.updatedAt !== "string" || binding.updatedAt.trim() === "") throw new BindingStoreError("updatedAt must be a non-empty ISO timestamp");
13848
13848
  if (binding.sourceCommit !== void 0 && binding.sourceCommit.trim() === "") throw new BindingStoreError("sourceCommit must not be blank when present");
13849
13849
  if (binding.localPath !== void 0) assertRelativePath(binding.localPath, "localPath");
13850
- if (!isRecord$3(binding.lineage)) throw new BindingStoreError("lineage must be an object");
13850
+ if (!isRecord$5(binding.lineage)) throw new BindingStoreError("lineage must be an object");
13851
13851
  const divergence = binding.lineage.divergence;
13852
13852
  if (divergence !== void 0 && (!Array.isArray(divergence) || divergence.some((item) => typeof item !== "string"))) throw new BindingStoreError("lineage.divergence must be an array of strings");
13853
13853
  }
@@ -13910,7 +13910,7 @@ function optionalNumber(record, key) {
13910
13910
  if (typeof value === "string" && /^\d+$/.test(value)) return Number(value);
13911
13911
  }
13912
13912
  function parseLineage(value, filePath) {
13913
- const record = isRecord$3(value) ? value : {};
13913
+ const record = isRecord$5(value) ? value : {};
13914
13914
  const lineage = {};
13915
13915
  const subscribedAt = optionalString(record, "subscribedAt");
13916
13916
  if (subscribedAt !== void 0) lineage.subscribedAt = subscribedAt;
@@ -13925,7 +13925,7 @@ function parseLineage(value, filePath) {
13925
13925
  function assertYamlKey(key) {
13926
13926
  if (!/^[A-Za-z][A-Za-z0-9_.-]*$/.test(key)) throw new BindingStoreError(`unsupported YAML key ${JSON.stringify(key)}`);
13927
13927
  }
13928
- function isRecord$3(value) {
13928
+ function isRecord$5(value) {
13929
13929
  return typeof value === "object" && value !== null && !Array.isArray(value);
13930
13930
  }
13931
13931
  function isErrno$2(error, code) {
@@ -15076,7 +15076,7 @@ var MemoryValidationError = class extends Error {
15076
15076
  this.issues = issues;
15077
15077
  }
15078
15078
  };
15079
- const isRecord$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
15079
+ const isRecord$4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
15080
15080
  const isMemoryType = (value) => typeof value === "string" && MEMORY_TYPES.includes(value);
15081
15081
  const isPrivacy = (value) => typeof value === "string" && PRIVACY_VALUES.includes(value);
15082
15082
  const isFactKind = (value) => typeof value === "string" && FACT_KINDS.includes(value);
@@ -15116,7 +15116,7 @@ function findPlaintextSecret(value, path = "") {
15116
15116
  }
15117
15117
  return;
15118
15118
  }
15119
- if (isRecord$2(value)) for (const [key, item] of Object.entries(value)) {
15119
+ if (isRecord$4(value)) for (const [key, item] of Object.entries(value)) {
15120
15120
  const found = findPlaintextSecret(item, path === "" ? key : `${path}.${key}`);
15121
15121
  if (found !== void 0) return found;
15122
15122
  }
@@ -15138,7 +15138,7 @@ const issue$1 = (code, message, field) => field === void 0 ? {
15138
15138
  */
15139
15139
  function validateMemoryEntry(value) {
15140
15140
  const issues = [];
15141
- if (!isRecord$2(value)) return [issue$1("invalid-entry", "memory entry must be an object")];
15141
+ if (!isRecord$4(value)) return [issue$1("invalid-entry", "memory entry must be an object")];
15142
15142
  if (!isMemoryType(value.type)) return [issue$1("invalid-value", `type must be one of ${MEMORY_TYPES.join(", ")}`, "type")];
15143
15143
  const type = value.type;
15144
15144
  const requireString = (field) => {
@@ -15496,11 +15496,11 @@ const PREFERENCE_HEADER = "# 偏好\n\n> 记忆守护会话维护的当前有效
15496
15496
  const PITFALL_HEADER = "# 踩坑\n\n> 记忆守护会话维护的当前有效踩坑。按 errorSignature 去重;解决方案更新会合并证据。";
15497
15497
  const FACT_HEADER = "# 事实\n\n> 记忆守护会话维护的当前有效事实。按 app / scope 分节;同键冲突会覆盖旧值并标记 supersedes。";
15498
15498
  const isErrnoCode$1 = (error, code) => typeof error === "object" && error !== null && "code" in error && error.code === code;
15499
- const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
15499
+ const isRecord$3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
15500
15500
  /** Stable JSON for "did this change" comparisons, independent of key order. */
15501
15501
  function stableJson(value) {
15502
15502
  if (Array.isArray(value)) return `[${value.map((item) => stableJson(item)).join(",")}]`;
15503
- if (isRecord$1(value)) return `{${Object.keys(value).filter((key) => value[key] !== void 0).sort().map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`).join(",")}}`;
15503
+ if (isRecord$3(value)) return `{${Object.keys(value).filter((key) => value[key] !== void 0).sort().map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`).join(",")}}`;
15504
15504
  return JSON.stringify(value) ?? "null";
15505
15505
  }
15506
15506
  /** Identity of an entry's content, ignoring generated versioning fields. */
@@ -16352,62 +16352,129 @@ var MemoryStore = class {
16352
16352
  //#endregion
16353
16353
  //#region src/memorySettings.ts
16354
16354
  /**
16355
- * Per-user memory settings: whether personal memory learning is enabled.
16355
+ * Per-user memory settings: whether personal memory learning is enabled and how
16356
+ * often the guardian consolidates what it learned.
16356
16357
  *
16357
16358
  * The product rule (design §22.2) is deliberately conservative:
16358
16359
  *
16359
16360
  * - a new user is **paused** (`memoryEnabled: false`), so no extraction starts
16360
16361
  * until the user explicitly confirms the enable dialog;
16362
+ * - an administrator or super administrator (a holder of the configured DataOps
16363
+ * permission, by default `kb:config:manage`) starts **enabled** on the first
16364
+ * read when no settings file exists yet. The global default is never flipped:
16365
+ * the administrator decision is injected through {@link MemorySettingsDefaultPolicy},
16366
+ * and an explicit `false` written by that administrator always wins;
16361
16367
  * - the switch is per user, not per session, and survives restarts;
16362
16368
  * - the file is local state under `<usersRoot>/<userId>/settings.json`, never
16363
16369
  * knowledge content and never Git content;
16364
16370
  * - a missing or unreadable file is a valid "paused" answer, not an error. Only
16365
16371
  * a filesystem permission failure is surfaced.
16366
16372
  *
16373
+ * The persisted shape is version 2 (`memoryEnabled` + `consolidationIntervalMinutes`).
16374
+ * Version 1 files (only `memoryEnabled`, or even a hand-written bare boolean) are
16375
+ * still read: a missing interval falls back to 60 minutes, and a malformed
16376
+ * interval never turns a remembered enable/disable decision into a different one.
16377
+ *
16367
16378
  * The route/UI layer reads `read()` or `isEnabled()` and writes through
16368
- * `setEnabled()`; every write is atomic (tmp + rename).
16379
+ * `save()`; every write is atomic (tmp + rename) and persists both fields in one
16380
+ * rename so a page save can never leave the switch and the interval disagreeing.
16369
16381
  *
16370
16382
  * @module @sparkelf/dsh-knowledge-base/memory-settings
16371
16383
  */
16372
16384
  /** File name inside one user's directory. */
16373
16385
  const MEMORY_SETTINGS_FILE = "settings.json";
16386
+ /** Longest allowed consolidation interval, in minutes. */
16387
+ const MEMORY_CONSOLIDATION_INTERVAL_MAX = 1440;
16374
16388
  /** The paused default for a user who has never confirmed the enable dialog. */
16375
16389
  const DEFAULT_MEMORY_SETTINGS = Object.freeze({
16376
- version: 1,
16377
- memoryEnabled: false
16390
+ version: 2,
16391
+ memoryEnabled: false,
16392
+ consolidationIntervalMinutes: 60
16378
16393
  });
16394
+ /** A malformed interval or write patch; the route maps this to HTTP 400. */
16395
+ var MemorySettingsError = class extends Error {
16396
+ code;
16397
+ name = "MemorySettingsError";
16398
+ constructor(code, message) {
16399
+ super(message);
16400
+ this.code = code;
16401
+ }
16402
+ };
16403
+ /**
16404
+ * Validate one consolidation interval.
16405
+ *
16406
+ * The guard is strict on purpose: a fractional value or a value outside
16407
+ * 15–1440 is a client bug, not a number to clamp silently. The route turns this
16408
+ * error into a 400 so the page can show the allowed range.
16409
+ *
16410
+ * @param value - raw value from an API body or a hand-edited file.
16411
+ * @returns the accepted integer.
16412
+ * @throws {MemorySettingsError} when the value is not an integer in range.
16413
+ */
16414
+ function normalizeConsolidationInterval(value) {
16415
+ if (typeof value !== "number" || !Number.isInteger(value)) throw new MemorySettingsError("invalid-interval", "consolidationIntervalMinutes must be an integer");
16416
+ if (value < 15 || value > 1440) throw new MemorySettingsError("invalid-interval", `consolidationIntervalMinutes must be between ${String(15)} and ${String(MEMORY_CONSOLIDATION_INTERVAL_MAX)}`);
16417
+ return value;
16418
+ }
16419
+ /** Read a stored interval leniently: an invalid legacy value falls back to 60. */
16420
+ function readStoredInterval(value) {
16421
+ try {
16422
+ return normalizeConsolidationInterval(value);
16423
+ } catch {
16424
+ return 60;
16425
+ }
16426
+ }
16379
16427
  /**
16380
16428
  * Atomic settings store over `<usersRoot>/<userId>/settings.json`.
16381
16429
  *
16382
16430
  * `read()` tolerates a corrupt file by returning the paused default; the next
16383
- * `setEnabled()` rewrites it. This keeps the memory page usable after a partial
16384
- * write or a hand-edited file instead of failing the whole route.
16431
+ * write rewrites it. This keeps the memory page usable after a partial write or
16432
+ * a hand-edited file instead of failing the whole route.
16385
16433
  */
16386
16434
  var MemorySettingsStore = class {
16387
16435
  usersRoot;
16388
- constructor(usersRoot) {
16436
+ defaultPolicy;
16437
+ constructor(usersRoot, defaultPolicy) {
16389
16438
  if (typeof usersRoot !== "string" || usersRoot.trim() === "") throw new Error("memory-settings: usersRoot must be a non-empty path");
16390
16439
  this.usersRoot = usersRoot;
16440
+ this.defaultPolicy = defaultPolicy;
16391
16441
  }
16392
16442
  /** Absolute settings file for one user. */
16393
16443
  filePath(userId) {
16394
16444
  assertPathSegment(userId, "userId");
16395
16445
  return join(this.usersRoot, userId, MEMORY_SETTINGS_FILE);
16396
16446
  }
16447
+ /** The first-read default for one user, from the injected policy. */
16448
+ async defaultFor(userId, options) {
16449
+ if (options.defaultEnabled !== void 0) return {
16450
+ ...DEFAULT_MEMORY_SETTINGS,
16451
+ memoryEnabled: options.defaultEnabled === true
16452
+ };
16453
+ if (this.defaultPolicy === void 0) return { ...DEFAULT_MEMORY_SETTINGS };
16454
+ try {
16455
+ return {
16456
+ ...DEFAULT_MEMORY_SETTINGS,
16457
+ memoryEnabled: await this.defaultPolicy.memoryEnabled(userId) === true
16458
+ };
16459
+ } catch {
16460
+ return { ...DEFAULT_MEMORY_SETTINGS };
16461
+ }
16462
+ }
16397
16463
  /**
16398
16464
  * Read one user's settings.
16399
16465
  *
16400
- * Missing, malformed, or schema-invalid content returns the paused default.
16401
- * A file with a boolean `memoryEnabled` is accepted even if `version` is
16402
- * missing, so an older/hand-written settings file does not silently turn
16403
- * memory on (the boolean still decides).
16466
+ * Missing content uses {@link MemorySettingsReadOptions.defaultEnabled} or the
16467
+ * injected policy. Malformed content stays paused even for an administrator:
16468
+ * a corrupt file is not evidence that the administrator opted in. A file with
16469
+ * a boolean `memoryEnabled` is accepted even if `version`/the interval is
16470
+ * missing, so old settings files keep their explicit choice.
16404
16471
  */
16405
- async read(userId) {
16472
+ async read(userId, options = {}) {
16406
16473
  let source;
16407
16474
  try {
16408
16475
  source = await readFile(this.filePath(userId), "utf8");
16409
16476
  } catch (error) {
16410
- if (isErrno$1(error, "ENOENT") || isErrno$1(error, "ENOTDIR")) return { ...DEFAULT_MEMORY_SETTINGS };
16477
+ if (isErrno$1(error, "ENOENT") || isErrno$1(error, "ENOTDIR")) return this.defaultFor(userId, options);
16411
16478
  throw error;
16412
16479
  }
16413
16480
  let parsed;
@@ -16420,28 +16487,50 @@ var MemorySettingsStore = class {
16420
16487
  const memoryEnabled = parsed.memoryEnabled;
16421
16488
  if (typeof memoryEnabled !== "boolean") return { ...DEFAULT_MEMORY_SETTINGS };
16422
16489
  return {
16423
- version: 1,
16424
- memoryEnabled
16490
+ version: 2,
16491
+ memoryEnabled,
16492
+ consolidationIntervalMinutes: readStoredInterval(parsed.consolidationIntervalMinutes)
16425
16493
  };
16426
16494
  }
16427
16495
  /** Whether learning is enabled for this user (default `false`). */
16428
- async isEnabled(userId) {
16429
- return (await this.read(userId)).memoryEnabled;
16496
+ async isEnabled(userId, options = {}) {
16497
+ return (await this.read(userId, options)).memoryEnabled;
16430
16498
  }
16431
16499
  /**
16432
- * Persist the enable/pause switch atomically.
16500
+ * Persist a partial settings change in one atomic write.
16501
+ *
16502
+ * The current value is read first so a page that saves only the interval
16503
+ * cannot accidentally pause memory (nor enable it). An explicit boolean in
16504
+ * the patch always wins; an absent field is preserved.
16433
16505
  *
16434
16506
  * @returns the normalized settings actually written.
16435
16507
  */
16436
- async setEnabled(userId, enabled) {
16437
- if (typeof enabled !== "boolean") throw new Error("memory-settings: memoryEnabled must be a boolean");
16508
+ async save(userId, patch, options = {}) {
16509
+ if (patch.memoryEnabled === void 0 && patch.consolidationIntervalMinutes === void 0) throw new MemorySettingsError("invalid-settings", "at least one memory setting must be supplied");
16510
+ if (patch.memoryEnabled !== void 0 && typeof patch.memoryEnabled !== "boolean") throw new MemorySettingsError("invalid-settings", "memoryEnabled must be a boolean");
16511
+ const interval = patch.consolidationIntervalMinutes === void 0 ? void 0 : normalizeConsolidationInterval(patch.consolidationIntervalMinutes);
16512
+ const current = await this.read(userId, options);
16438
16513
  const settings = {
16439
- version: 1,
16440
- memoryEnabled: enabled
16514
+ version: 2,
16515
+ memoryEnabled: patch.memoryEnabled ?? current.memoryEnabled,
16516
+ consolidationIntervalMinutes: interval ?? current.consolidationIntervalMinutes
16441
16517
  };
16442
16518
  await writeFileAtomic(this.filePath(userId), `${JSON.stringify(settings, null, 2)}\n`, { mode: 384 });
16443
16519
  return settings;
16444
16520
  }
16521
+ /**
16522
+ * Persist the enable/pause switch atomically, preserving the interval.
16523
+ *
16524
+ * @returns the normalized settings actually written.
16525
+ */
16526
+ async setEnabled(userId, enabled, options = {}) {
16527
+ if (typeof enabled !== "boolean") throw new MemorySettingsError("invalid-settings", "memoryEnabled must be a boolean");
16528
+ return this.save(userId, { memoryEnabled: enabled }, options);
16529
+ }
16530
+ /** Persist one interval while preserving the switch. */
16531
+ async setConsolidationInterval(userId, minutes, options = {}) {
16532
+ return this.save(userId, { consolidationIntervalMinutes: minutes }, options);
16533
+ }
16445
16534
  };
16446
16535
  function isErrno$1(error, code) {
16447
16536
  return typeof error === "object" && error !== null && "code" in error && error.code === code;
@@ -16464,13 +16553,13 @@ const CONTENT_FIELD = {
16464
16553
  episodic: "summary",
16465
16554
  fact: "statement"
16466
16555
  };
16467
- const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
16556
+ const isRecord$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
16468
16557
  const messageOf$1 = (error) => error instanceof Error ? error.message : String(error);
16469
- const ok = (body) => ({
16558
+ const ok$1 = (body) => ({
16470
16559
  status: 200,
16471
16560
  body
16472
16561
  });
16473
- const fail = (status, error, code, extra) => ({
16562
+ const fail$1 = (status, error, code, extra) => ({
16474
16563
  status,
16475
16564
  body: {
16476
16565
  error,
@@ -16478,21 +16567,35 @@ const fail = (status, error, code, extra) => ({
16478
16567
  ...extra
16479
16568
  }
16480
16569
  });
16570
+ /** The settings shape the page reads; bounds travel with the value so the UI never guesses. */
16571
+ function settingsPayload(settings) {
16572
+ return {
16573
+ enabled: settings.memoryEnabled,
16574
+ consolidationIntervalMinutes: settings.consolidationIntervalMinutes,
16575
+ intervalMin: 15,
16576
+ intervalMax: MEMORY_CONSOLIDATION_INTERVAL_MAX,
16577
+ intervalDefault: 60
16578
+ };
16579
+ }
16580
+ /** Options for a settings read that already knows the caller's first-read default. */
16581
+ function readOptions(defaultEnabled) {
16582
+ return defaultEnabled === void 0 ? {} : { defaultEnabled };
16583
+ }
16481
16584
  /** One short line for the table; whitespace collapsed and bounded. */
16482
16585
  function clipLine(value, max = 80) {
16483
16586
  const clean = value.replace(/\s+/gu, " ").trim();
16484
16587
  return clean.length <= max ? clean : `${clean.slice(0, max - 1)}…`;
16485
16588
  }
16486
16589
  /** A technical token that should never be the first thing a reader sees in a row. */
16487
- function looksTechnical(value) {
16590
+ function looksTechnical$1(value) {
16488
16591
  if (/[\\/]|session-|kb_[a-z]|\.md\b|\bSOP\b|[a-z]+_[a-z]+/iu.test(value)) return true;
16489
16592
  return value.trim().length > 12 && /^[a-z0-9._-]+$/u.test(value.trim());
16490
16593
  }
16491
16594
  /** Short, non-technical fallback for entries written before displayTitle existed. */
16492
16595
  function fallbackTitle(entry) {
16493
16596
  switch (entry.type) {
16494
- case "preference": return clipLine(looksTechnical(entry.value) ? entry.topic : entry.value, 20);
16495
- case "pitfall": return looksTechnical(entry.errorSignature) ? "踩坑记录" : clipLine(entry.errorSignature, 20);
16597
+ case "preference": return clipLine(looksTechnical$1(entry.value) ? entry.topic : entry.value, 20);
16598
+ case "pitfall": return looksTechnical$1(entry.errorSignature) ? "踩坑记录" : clipLine(entry.errorSignature, 20);
16496
16599
  case "episodic":
16497
16600
  if (entry.tags?.includes("SOP评估")) return "方法评估";
16498
16601
  if (entry.tags?.includes("SOP晋升")) return "方法晋升";
@@ -16500,7 +16603,7 @@ function fallbackTitle(entry) {
16500
16603
  if (entry.tags?.includes("compaction")) return "压缩触发";
16501
16604
  if (entry.tags?.includes("dream")) return "记忆整理";
16502
16605
  return "情景记录";
16503
- case "fact": return looksTechnical(entry.key) ? "事实记录" : clipLine(entry.key, 20);
16606
+ case "fact": return looksTechnical$1(entry.key) ? "事实记录" : clipLine(entry.key, 20);
16504
16607
  case "sop": return clipLine(entry.title, 20);
16505
16608
  }
16506
16609
  }
@@ -16570,60 +16673,83 @@ function readEntryId(body) {
16570
16673
  const readNonEmptyString = (value) => typeof value === "string" && value.trim() !== "" ? value : void 0;
16571
16674
  /** Extract and validate the patch, translating the generic `content` alias. */
16572
16675
  function readUpdatePatch(body, entry) {
16573
- if (Object.prototype.hasOwnProperty.call(body, "userId")) return { error: fail(400, "userId must not be supplied; the caller is resolved from the request", "invalid") };
16676
+ 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") };
16574
16677
  const hasPatchObject = Object.prototype.hasOwnProperty.call(body, "patch");
16575
- if (hasPatchObject && !isRecord(body.patch)) return { error: fail(400, "patch must be an object", "invalid") };
16678
+ if (hasPatchObject && !isRecord$2(body.patch)) return { error: fail$1(400, "patch must be an object", "invalid") };
16576
16679
  const source = hasPatchObject ? body.patch : body;
16577
16680
  if (hasPatchObject) {
16578
16681
  const extra = Object.keys(body).filter((key) => key !== "id" && key !== "patch");
16579
- if (extra.length > 0) return { error: fail(400, `unsupported update field(s): ${extra.join(", ")}`, "invalid") };
16682
+ if (extra.length > 0) return { error: fail$1(400, `unsupported update field(s): ${extra.join(", ")}`, "invalid") };
16580
16683
  } else {
16581
16684
  const extra = Object.keys(body).filter((key) => key !== "id" && !PATCH_FIELDS.has(key));
16582
- if (extra.length > 0) return { error: fail(400, `unsupported update field(s): ${extra.join(", ")}`, "invalid") };
16685
+ if (extra.length > 0) return { error: fail$1(400, `unsupported update field(s): ${extra.join(", ")}`, "invalid") };
16583
16686
  }
16584
- if (Object.prototype.hasOwnProperty.call(source, "userId")) return { error: fail(400, "userId must not be supplied; the caller is resolved from the request", "invalid") };
16687
+ 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") };
16585
16688
  const unknown = Object.keys(source).filter((key) => !PATCH_FIELDS.has(key) && (hasPatchObject || key !== "id"));
16586
- if (unknown.length > 0) return { error: fail(400, `unsupported update field(s): ${unknown.join(", ")}`, "invalid") };
16689
+ if (unknown.length > 0) return { error: fail$1(400, `unsupported update field(s): ${unknown.join(", ")}`, "invalid") };
16587
16690
  const patch = {};
16588
16691
  if (source.title !== void 0) {
16589
16692
  const title = readNonEmptyString(source.title);
16590
- if (title === void 0) return { error: fail(400, "title must be a non-empty string", "invalid") };
16693
+ if (title === void 0) return { error: fail$1(400, "title must be a non-empty string", "invalid") };
16591
16694
  patch.title = title;
16592
16695
  }
16593
16696
  if (source.content !== void 0) {
16594
16697
  const content = readNonEmptyString(source.content);
16595
- if (content === void 0) return { error: fail(400, "content must be a non-empty string", "invalid") };
16698
+ if (content === void 0) return { error: fail$1(400, "content must be a non-empty string", "invalid") };
16596
16699
  const field = CONTENT_FIELD[entry.type];
16597
- if (field === void 0) return { error: fail(400, `content cannot be edited on a ${entry.type} entry; edit title or steps`, "invalid") };
16598
- if (source[field] !== void 0) return { error: fail(400, `content conflicts with ${String(field)}`, "invalid") };
16700
+ if (field === void 0) return { error: fail$1(400, `content cannot be edited on a ${entry.type} entry; edit title or steps`, "invalid") };
16701
+ if (source[field] !== void 0) return { error: fail$1(400, `content conflicts with ${String(field)}`, "invalid") };
16599
16702
  patch[String(field)] = content;
16600
16703
  }
16601
16704
  if (source.value !== void 0) {
16602
16705
  const value = readNonEmptyString(source.value);
16603
- if (value === void 0) return { error: fail(400, "value must be a non-empty string", "invalid") };
16706
+ if (value === void 0) return { error: fail$1(400, "value must be a non-empty string", "invalid") };
16604
16707
  patch.value = value;
16605
16708
  }
16606
16709
  if (source.statement !== void 0) {
16607
16710
  const statement = readNonEmptyString(source.statement);
16608
- if (statement === void 0) return { error: fail(400, "statement must be a non-empty string", "invalid") };
16711
+ if (statement === void 0) return { error: fail$1(400, "statement must be a non-empty string", "invalid") };
16609
16712
  patch.statement = statement;
16610
16713
  }
16611
16714
  if (source.solution !== void 0) {
16612
16715
  const solution = readNonEmptyString(source.solution);
16613
- if (solution === void 0) return { error: fail(400, "solution must be a non-empty string", "invalid") };
16716
+ if (solution === void 0) return { error: fail$1(400, "solution must be a non-empty string", "invalid") };
16614
16717
  patch.solution = solution;
16615
16718
  }
16616
16719
  if (source.steps !== void 0) {
16617
16720
  const steps = source.steps;
16618
- if (!Array.isArray(steps) || steps.length === 0 || steps.some((step) => typeof step !== "string" || step.trim() === "")) return { error: fail(400, "steps must be a non-empty array of non-empty strings", "invalid") };
16721
+ 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") };
16619
16722
  patch.steps = steps;
16620
16723
  }
16621
16724
  if (source.privacy !== void 0) {
16622
- if (!isPrivacy(source.privacy)) return { error: fail(400, "privacy must be normal, private, sensitive or secret", "invalid") };
16725
+ if (!isPrivacy(source.privacy)) return { error: fail$1(400, "privacy must be normal, private, sensitive or secret", "invalid") };
16623
16726
  patch.privacy = source.privacy;
16624
16727
  }
16625
16728
  return { patch };
16626
16729
  }
16730
+ /** Extract and validate the settings write, translating `enabled` to the stored field. */
16731
+ function readSettingsPatch(body, options) {
16732
+ 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") };
16733
+ const unknown = Object.keys(body).filter((key) => key !== "enabled" && key !== "consolidationIntervalMinutes");
16734
+ if (unknown.length > 0) return { error: fail$1(400, `unsupported settings field(s): ${unknown.join(", ")}`, "invalid") };
16735
+ if (options.requireEnabled && body.enabled === void 0) return { error: fail$1(400, "enabled must be a boolean", "invalid") };
16736
+ const patch = {};
16737
+ if (body.enabled !== void 0) {
16738
+ if (typeof body.enabled !== "boolean") return { error: fail$1(400, "enabled must be a boolean", "invalid") };
16739
+ patch.memoryEnabled = body.enabled;
16740
+ }
16741
+ if (body.consolidationIntervalMinutes !== void 0) try {
16742
+ patch.consolidationIntervalMinutes = normalizeConsolidationInterval(body.consolidationIntervalMinutes);
16743
+ } catch (error) {
16744
+ if (error instanceof MemorySettingsError) return { error: fail$1(400, error.message, error.code, {
16745
+ min: 15,
16746
+ max: MEMORY_CONSOLIDATION_INTERVAL_MAX
16747
+ }) };
16748
+ throw error;
16749
+ }
16750
+ if (patch.memoryEnabled === void 0 && patch.consolidationIntervalMinutes === void 0) return { error: fail$1(400, "at least one memory setting must be supplied", "invalid") };
16751
+ return { patch };
16752
+ }
16627
16753
  /** Reconcile the personal-memory graph; a derived failure must not undo the write. */
16628
16754
  async function syncGraph(graphWriter) {
16629
16755
  try {
@@ -16634,11 +16760,12 @@ async function syncGraph(graphWriter) {
16634
16760
  }
16635
16761
  }
16636
16762
  /** Map a store/validation failure to an actionable status; unknown errors escape. */
16637
- function failureOf(error) {
16638
- if (error instanceof MemoryValidationError) return fail(400, error.message, "invalid-memory", { issues: error.issues });
16763
+ function failureOf$1(error) {
16764
+ if (error instanceof MemorySettingsError) return fail$1(400, error.message, error.code);
16765
+ if (error instanceof MemoryValidationError) return fail$1(400, error.message, "invalid-memory", { issues: error.issues });
16639
16766
  if (error instanceof MemoryStoreError) {
16640
16767
  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;
16641
- return fail(status, error.message, error.code);
16768
+ return fail$1(status, error.message, error.code);
16642
16769
  }
16643
16770
  throw error;
16644
16771
  }
@@ -16652,55 +16779,792 @@ function failureOf(error) {
16652
16779
  */
16653
16780
  async function handleMemoryRoute(input) {
16654
16781
  const { method, caller, store, settings, graphWriter } = input;
16655
- if (!isSafeUserId(caller.userId)) return fail(403, "unsafe caller id; memory is scoped to the authenticated user", "forbidden");
16656
- const body = isRecord(input.body) ? input.body : {};
16782
+ if (!isSafeUserId(caller.userId)) return fail$1(403, "unsafe caller id; memory is scoped to the authenticated user", "forbidden");
16783
+ const body = isRecord$2(input.body) ? input.body : {};
16657
16784
  try {
16658
16785
  switch (method) {
16659
16786
  case "memory.list": {
16660
- const [enabled, entries] = await Promise.all([settings.isEnabled(caller.userId), store.listEntries()]);
16661
- return ok({
16662
- enabled,
16787
+ const [settingsState, entries] = await Promise.all([settings.read(caller.userId, readOptions(input.defaultEnabled)), store.listEntries()]);
16788
+ return ok$1({
16789
+ enabled: settingsState.memoryEnabled,
16663
16790
  entries: entries.map(listRow)
16664
16791
  });
16665
16792
  }
16666
16793
  case "memory.get": {
16667
16794
  const id = readEntryId(body);
16668
- if (id === void 0) return fail(400, "a safe entry id is required", "invalid");
16795
+ if (id === void 0) return fail$1(400, "a safe entry id is required", "invalid");
16669
16796
  const entry = await store.getEntry(id);
16670
- if (entry === void 0) return fail(404, "memory entry not found", "not-found");
16671
- return ok(entryPayload(entry));
16797
+ if (entry === void 0) return fail$1(404, "memory entry not found", "not-found");
16798
+ return ok$1(entryPayload(entry));
16672
16799
  }
16673
16800
  case "memory.update": {
16674
16801
  const id = readEntryId(body);
16675
- if (id === void 0) return fail(400, "a safe entry id is required", "invalid");
16802
+ if (id === void 0) return fail$1(400, "a safe entry id is required", "invalid");
16676
16803
  const entry = await store.getEntry(id);
16677
- if (entry === void 0) return fail(404, "memory entry not found", "not-found");
16804
+ if (entry === void 0) return fail$1(404, "memory entry not found", "not-found");
16678
16805
  const built = readUpdatePatch(body, entry);
16679
16806
  if ("error" in built) return built.error;
16680
16807
  const updated = await store.updateEntry(id, built.patch);
16681
16808
  const graphSyncWarning = await syncGraph(graphWriter);
16682
- return ok({
16809
+ return ok$1({
16683
16810
  ...entryPayload(updated),
16684
16811
  ...graphSyncWarning === void 0 ? {} : { graphSyncWarning }
16685
16812
  });
16686
16813
  }
16687
16814
  case "memory.forget": {
16688
16815
  const id = readEntryId(body);
16689
- if (id === void 0) return fail(400, "a safe entry id is required", "invalid");
16816
+ if (id === void 0) return fail$1(400, "a safe entry id is required", "invalid");
16690
16817
  const forgotten = await store.forgetEntry(id);
16691
16818
  const graphSyncWarning = forgotten.removed ? await syncGraph(graphWriter) : void 0;
16692
- return ok({
16819
+ return ok$1({
16693
16820
  ...forgotten,
16694
16821
  ...graphSyncWarning === void 0 ? {} : { graphSyncWarning }
16695
16822
  });
16696
16823
  }
16697
- case "memory.settings": return ok({ enabled: await settings.isEnabled(caller.userId) });
16824
+ case "memory.settings": return ok$1(settingsPayload(await settings.read(caller.userId, readOptions(input.defaultEnabled))));
16698
16825
  case "memory.set-enabled": {
16699
- if (typeof body.enabled !== "boolean") return fail(400, "enabled must be a boolean", "invalid");
16700
- const next = await settings.setEnabled(caller.userId, body.enabled);
16701
- return ok({ enabled: next.memoryEnabled });
16826
+ const built = readSettingsPatch(body, { requireEnabled: true });
16827
+ if ("error" in built) return built.error;
16828
+ const next = await settings.save(caller.userId, built.patch, readOptions(input.defaultEnabled));
16829
+ return ok$1(settingsPayload(next));
16830
+ }
16831
+ case "memory.save-settings": {
16832
+ const built = readSettingsPatch(body, { requireEnabled: false });
16833
+ if ("error" in built) return built.error;
16834
+ const next = await settings.save(caller.userId, built.patch, readOptions(input.defaultEnabled));
16835
+ return ok$1(settingsPayload(next));
16836
+ }
16837
+ default: return fail$1(404, `unknown memory method: ${method}`, "not-found");
16838
+ }
16839
+ } catch (error) {
16840
+ return failureOf$1(error);
16841
+ }
16842
+ }
16843
+ //#endregion
16844
+ //#region src/memoryPromotion.ts
16845
+ /**
16846
+ * Promotion of a personal memory or SOP into department/global memory.
16847
+ *
16848
+ * Personal memory is private by construction. Sharing it with a department or the
16849
+ * whole platform is not a copy the guardian makes on its own: it is a product
16850
+ * decision that needs a second pair of eyes (design §17.4, §21.2, §22). This module
16851
+ * owns that decision and its audit trail:
16852
+ *
16853
+ * - a promotion is a durable record with a **pending → approved | rejected**
16854
+ * lifecycle; a rejected or approved record is never silently rewritten;
16855
+ * - only a caller who already holds review authority for the target scope may
16856
+ * create or decide one — `kb:config:manage` for global, the department review
16857
+ * scope for `department:<code>`;
16858
+ * - a request can never be approved by the person who made it. An administrator
16859
+ * who wants their own memory shared uses the explicit `confirm` path, which is a
16860
+ * different, separately-audited action;
16861
+ * - only `privacy: normal` content is promotable. `private`, `sensitive` and
16862
+ * `secret` memories are refused rather than downgraded, because a promotion is
16863
+ * an irreversible widening of who can read them;
16864
+ * - approval writes a real shared memory document and a graph node under the
16865
+ * target scope, so the existing knowledge-base permissions (not this module)
16866
+ * decide who can read it.
16867
+ *
16868
+ * The store is product metadata (a review queue), not knowledge content: it lives
16869
+ * beside the per-user binding state, never inside a document tree, and holds one
16870
+ * JSON file committed by atomic rename.
16871
+ *
16872
+ * @module @sparkelf/dsh-knowledge-base/memory-promotion
16873
+ */
16874
+ /** Graph id that owns promoted department/global memory inside one scope. */
16875
+ const SHARED_MEMORY_GRAPH_ID = "shared-memory";
16876
+ /** Folder (relative to the scope root) that holds one document per promotion. */
16877
+ const SHARED_MEMORY_FOLDER = "记忆共享";
16878
+ /** Display name per graph scope. */
16879
+ function sharedMemoryGraphName(scope) {
16880
+ return scope === "global" ? "全局共享记忆" : "部门共享记忆";
16881
+ }
16882
+ /** A structured refusal the route maps to a status code. */
16883
+ var MemoryPromotionError = class extends Error {
16884
+ code;
16885
+ name = "MemoryPromotionError";
16886
+ constructor(code, message) {
16887
+ super(message);
16888
+ this.code = code;
16889
+ }
16890
+ };
16891
+ /** The submitter may request a promotion only inside a scope they can review. */
16892
+ function decidePromotionScope(reviewer, scope, departmentCode) {
16893
+ if (scope === "global") {
16894
+ if (!reviewer.isGlobalAdmin || !reviewer.canManageConfig) return {
16895
+ ok: false,
16896
+ code: "forbidden",
16897
+ message: "只有管理员/超级管理员可以把记忆晋升到全局。"
16898
+ };
16899
+ return { ok: true };
16900
+ }
16901
+ const code = (departmentCode ?? reviewer.departmentCode ?? "").trim();
16902
+ if (code === "") return {
16903
+ ok: false,
16904
+ code: "invalid",
16905
+ message: "晋升到部门必须指定部门。"
16906
+ };
16907
+ if (reviewer.departmentCode === void 0 || code !== reviewer.departmentCode) return {
16908
+ ok: false,
16909
+ code: "forbidden",
16910
+ message: "只能晋升到当前账号所属部门。"
16911
+ };
16912
+ if (!reviewer.isGlobalAdmin && !reviewer.reviewDepartments.includes(code)) return {
16913
+ ok: false,
16914
+ code: "forbidden",
16915
+ message: "只能晋升到本部门管理范围内的记忆。"
16916
+ };
16917
+ return {
16918
+ ok: true,
16919
+ departmentCode: code,
16920
+ departmentPath: reviewer.departmentPathCodes !== void 0 && reviewer.departmentPathCodes.length > 0 ? [...reviewer.departmentPathCodes] : [code]
16921
+ };
16922
+ }
16923
+ /** Whether one reviewer may decide a promotion aimed at its target scope. */
16924
+ function canReviewPromotion(reviewer, target) {
16925
+ if (target.scope === "global") return reviewer.isGlobalAdmin;
16926
+ const code = target.departmentCode ?? "";
16927
+ if (code === "") return false;
16928
+ return reviewer.isGlobalAdmin || reviewer.reviewDepartments.includes(code);
16929
+ }
16930
+ /**
16931
+ * Whether one approved promotion is visible to a viewer.
16932
+ *
16933
+ * A department promotion is visible to the viewer whose organization path contains
16934
+ * that department (own department and its ancestors) or whose data scope names it.
16935
+ * The source owner always keeps seeing their own approved memory.
16936
+ */
16937
+ function isPromotionVisibleTo(record, viewer) {
16938
+ if (record.target.scope === "global") return true;
16939
+ if (record.source.userId === viewer.userId) return true;
16940
+ if (viewer.isGlobalAdmin) return true;
16941
+ const code = record.target.departmentCode ?? "";
16942
+ if (code === "") return false;
16943
+ if (viewer.departmentCode === code) return true;
16944
+ if (viewer.departmentPathCodes?.includes(code) === true) return true;
16945
+ if (viewer.visibleDepartmentCodes?.includes(code) === true) return true;
16946
+ return viewer.reviewDepartments.includes(code);
16947
+ }
16948
+ /**
16949
+ * The scope root one target writes under, WITHOUT a trailing slash.
16950
+ *
16951
+ * DataOps grants are matched against this exact resource id (a trailing slash is a
16952
+ * different id and matches nothing), so every permission question must use this
16953
+ * spelling. Directory joining adds the slash separately.
16954
+ */
16955
+ function targetScopeRoot(target) {
16956
+ if (target.scope === "global") return "global";
16957
+ return "department/" + (target.departmentPath !== void 0 && target.departmentPath.length > 0 ? target.departmentPath : target.departmentCode === void 0 ? [] : [target.departmentCode]).join("/");
16958
+ }
16959
+ /** The scope-relative prefix one target writes under (`global/`, `department/A/B/`). */
16960
+ function targetScopePrefix(target) {
16961
+ return targetScopeRoot(target) + "/";
16962
+ }
16963
+ /** Where the review queue lives for one deployment's per-user memory root. */
16964
+ function promotionStorePath(memoryUsersRoot) {
16965
+ return join(dirname(resolve(memoryUsersRoot)), "promotions.json");
16966
+ }
16967
+ /** Map a stored memory type onto the graph's smaller node vocabulary. */
16968
+ function sharedNodeTypeOf(type) {
16969
+ switch (type) {
16970
+ case "preference": return "topic";
16971
+ case "pitfall": return "case";
16972
+ case "episodic": return "case";
16973
+ case "fact": return "fact";
16974
+ case "sop": return "procedure";
16975
+ }
16976
+ }
16977
+ /** The text a promotion copies into the shared document. */
16978
+ function promotionContentOf(entry) {
16979
+ switch (entry.type) {
16980
+ case "preference": return entry.value;
16981
+ case "pitfall": return [
16982
+ "现象:" + entry.errorSignature,
16983
+ "原因:" + entry.context,
16984
+ "解决:" + entry.solution
16985
+ ].join("\n\n");
16986
+ case "episodic": return entry.summary;
16987
+ case "fact": return entry.statement;
16988
+ case "sop": {
16989
+ const parts = ["触发条件:" + entry.trigger, entry.steps.map((step, index) => `${String(index + 1)}. ${step}`).join("\n")];
16990
+ if (entry.successCriteria !== void 0 && entry.successCriteria.length > 0) parts.push(entry.successCriteria.map((item) => "- " + item).join("\n"));
16991
+ return parts.join("\n\n");
16992
+ }
16993
+ }
16994
+ }
16995
+ /** The short title a shared row shows; mirrors the personal page's rules. */
16996
+ function promotionTitleOf(entry) {
16997
+ if (typeof entry.displayTitle === "string" && entry.displayTitle.trim() !== "") return clipTitle(entry.displayTitle.trim());
16998
+ switch (entry.type) {
16999
+ case "preference": return looksTechnical(entry.value) ? "偏好记录" : clipTitle(entry.value);
17000
+ case "pitfall": return looksTechnical(entry.errorSignature) ? "踩坑记录" : clipTitle(entry.errorSignature);
17001
+ case "episodic":
17002
+ if (entry.tags?.includes("SOP评估")) return "方法评估";
17003
+ if (entry.tags?.includes("SOP晋升")) return "方法晋升";
17004
+ if (entry.tags?.includes("idle")) return "空闲触发";
17005
+ if (entry.tags?.includes("compaction")) return "压缩触发";
17006
+ if (entry.tags?.includes("dream")) return "记忆整理";
17007
+ return "情景记录";
17008
+ case "fact": return looksTechnical(entry.key) ? "事实记录" : clipTitle(entry.key);
17009
+ case "sop": return clipTitle(entry.title);
17010
+ }
17011
+ }
17012
+ /** Whitespace-collapsed, bounded title; never a technical identifier on its own. */
17013
+ function clipTitle(value) {
17014
+ const clean = value.replace(/\s+/gu, " ").trim();
17015
+ return clean.length <= 40 ? clean : `${clean.slice(0, 39)}…`;
17016
+ }
17017
+ /** A technical token that should not be the first thing a reader sees in a row. */
17018
+ function looksTechnical(value) {
17019
+ if (/[\\/]|session-|kb_[a-z]|\.md\b|\bSOP\b|[a-z]+_[a-z]+/iu.test(value)) return true;
17020
+ return value.trim().length > 12 && /^[a-z0-9._-]+$/u.test(value.trim());
17021
+ }
17022
+ const EMPTY_STORE = {
17023
+ version: 1,
17024
+ promotions: []
17025
+ };
17026
+ const writeQueues = /* @__PURE__ */ new Map();
17027
+ /** Serialize mutations of one store path so two requests cannot overwrite each other. */
17028
+ function serialize(path, operation) {
17029
+ const next = (writeQueues.get(path) ?? Promise.resolve()).then(operation, operation);
17030
+ writeQueues.set(path, next.then(() => void 0, () => void 0));
17031
+ return next;
17032
+ }
17033
+ /** Read the queue, treating absence as empty and quarantining corrupt JSON. */
17034
+ async function readPromotionStore(path) {
17035
+ let raw;
17036
+ try {
17037
+ raw = await readFile(path, "utf8");
17038
+ } catch (error) {
17039
+ if (error.code === "ENOENT") return EMPTY_STORE;
17040
+ throw new MemoryPromotionError("io", `could not read ${path}: ${String(error)}`);
17041
+ }
17042
+ try {
17043
+ const parsed = JSON.parse(raw);
17044
+ if (parsed === null || typeof parsed !== "object") throw new Error("not an object");
17045
+ const candidate = parsed;
17046
+ if (candidate.version !== 1 || !Array.isArray(candidate.promotions)) throw new Error("wrong shape");
17047
+ return {
17048
+ version: 1,
17049
+ promotions: candidate.promotions
17050
+ };
17051
+ } catch {
17052
+ await rename(path, `${path}.corrupt-${String(Date.now())}`).catch(() => void 0);
17053
+ return EMPTY_STORE;
17054
+ }
17055
+ }
17056
+ /** Commit the queue atomically. */
17057
+ async function writePromotionStore(path, store) {
17058
+ await writeFileAtomic(path, JSON.stringify(store, null, 2) + "\n");
17059
+ }
17060
+ /** Read every promotion, oldest first. */
17061
+ async function listPromotionRecords(path) {
17062
+ return (await readPromotionStore(path)).promotions;
17063
+ }
17064
+ const MAX_TITLE = 200;
17065
+ const MAX_CONTENT = 2e4;
17066
+ /** Reject a request that cannot be shared safely or written to a graph. */
17067
+ function normalizePromotionDraft(draft) {
17068
+ if (draft.source.privacy !== "normal") throw new MemoryPromotionError("privacy", "只有隐私为「普通」的记忆可以晋升;仅自己、敏感和凭据引用不会被共享。");
17069
+ const title = draft.source.title.trim();
17070
+ if (title === "" || title.length > MAX_TITLE) throw new MemoryPromotionError("invalid", `a promotion title must be 1–${String(MAX_TITLE)} characters`);
17071
+ const content = draft.source.content.trim();
17072
+ if (content === "" || content.length > MAX_CONTENT) throw new MemoryPromotionError("invalid", `a promotion body must be 1–${String(MAX_CONTENT)} characters`);
17073
+ if (draft.target.scope === "department" && (draft.target.departmentCode ?? "").trim() === "") throw new MemoryPromotionError("invalid", "a department promotion needs a department code");
17074
+ return {
17075
+ source: {
17076
+ ...draft.source,
17077
+ title,
17078
+ content
17079
+ },
17080
+ target: draft.target
17081
+ };
17082
+ }
17083
+ /** Create one pending request, or return the identical pending one. */
17084
+ async function createPromotionRequest(path, draft, actor, now = () => /* @__PURE__ */ new Date()) {
17085
+ const normalized = normalizePromotionDraft(draft);
17086
+ return serialize(path, async () => {
17087
+ const store = await readPromotionStore(path);
17088
+ 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 ?? ""));
17089
+ if (duplicate !== void 0) return {
17090
+ record: duplicate,
17091
+ duplicate: true
17092
+ };
17093
+ const at = now().toISOString();
17094
+ const id = "mp-" + randomUUID();
17095
+ const record = {
17096
+ id,
17097
+ status: "pending",
17098
+ source: normalized.source,
17099
+ target: {
17100
+ ...normalized.target,
17101
+ docPath: `${SHARED_MEMORY_FOLDER}/${id}.md`
17102
+ },
17103
+ requestedBy: actor,
17104
+ requestedAt: at,
17105
+ confirmed: false,
17106
+ audit: [{
17107
+ at,
17108
+ actorId: actor.id,
17109
+ actorName: actor.name,
17110
+ action: "requested",
17111
+ detail: {
17112
+ scope: normalized.target.scope,
17113
+ ...normalized.target.departmentCode === void 0 ? {} : { departmentCode: normalized.target.departmentCode },
17114
+ targetGraph: normalized.target.graphId,
17115
+ memoryId: normalized.source.memoryId
17116
+ }
17117
+ }]
17118
+ };
17119
+ await writePromotionStore(path, {
17120
+ version: 1,
17121
+ promotions: [...store.promotions, record]
17122
+ });
17123
+ return {
17124
+ record,
17125
+ duplicate: false
17126
+ };
17127
+ });
17128
+ }
17129
+ /** Load one promotion by id. */
17130
+ async function getPromotionRecord(path, id) {
17131
+ return (await readPromotionStore(path)).promotions.find((item) => item.id === id);
17132
+ }
17133
+ /** Mark one pending promotion approved after its shared document is on disk. */
17134
+ async function markPromotionApproved(path, id, reviewer, appliedPath, options, now = () => /* @__PURE__ */ new Date()) {
17135
+ return serialize(path, async () => {
17136
+ const store = await readPromotionStore(path);
17137
+ const record = store.promotions.find((item) => item.id === id);
17138
+ if (record === void 0) throw new MemoryPromotionError("not-found", `no promotion with id ${id}`);
17139
+ if (record.status !== "pending") throw new MemoryPromotionError("conflict", `promotion ${id} is already ${record.status}`);
17140
+ const at = now().toISOString();
17141
+ const next = {
17142
+ ...record,
17143
+ status: "approved",
17144
+ reviewedBy: reviewer,
17145
+ reviewedAt: at,
17146
+ confirmed: options.confirmed,
17147
+ appliedAt: at,
17148
+ ...options.note === void 0 || options.note.trim() === "" ? {} : { reviewNote: options.note.trim() },
17149
+ audit: [...record.audit, {
17150
+ at,
17151
+ actorId: reviewer.id,
17152
+ actorName: reviewer.name,
17153
+ action: options.confirmed ? "confirmed" : "approved",
17154
+ detail: {
17155
+ appliedPath,
17156
+ scope: record.target.scope
17157
+ }
17158
+ }]
17159
+ };
17160
+ await writePromotionStore(path, {
17161
+ version: 1,
17162
+ promotions: store.promotions.map((item) => item.id === id ? next : item)
17163
+ });
17164
+ return next;
17165
+ });
17166
+ }
17167
+ /** Mark one pending promotion rejected, keeping the reason. */
17168
+ async function markPromotionRejected(path, id, reviewer, note, now = () => /* @__PURE__ */ new Date()) {
17169
+ return serialize(path, async () => {
17170
+ const store = await readPromotionStore(path);
17171
+ const record = store.promotions.find((item) => item.id === id);
17172
+ if (record === void 0) throw new MemoryPromotionError("not-found", `no promotion with id ${id}`);
17173
+ if (record.status !== "pending") throw new MemoryPromotionError("conflict", `promotion ${id} is already ${record.status}`);
17174
+ const at = now().toISOString();
17175
+ const next = {
17176
+ ...record,
17177
+ status: "rejected",
17178
+ reviewedBy: reviewer,
17179
+ reviewedAt: at,
17180
+ ...note === void 0 || note.trim() === "" ? {} : { reviewNote: note.trim() },
17181
+ audit: [...record.audit, {
17182
+ at,
17183
+ actorId: reviewer.id,
17184
+ actorName: reviewer.name,
17185
+ action: "rejected",
17186
+ ...note === void 0 || note.trim() === "" ? {} : { detail: { note: note.trim() } }
17187
+ }]
17188
+ };
17189
+ await writePromotionStore(path, {
17190
+ version: 1,
17191
+ promotions: store.promotions.map((item) => item.id === id ? next : item)
17192
+ });
17193
+ return next;
17194
+ });
17195
+ }
17196
+ /** Quote a value for the hand-written YAML front matter. */
17197
+ function yamlQuoted(value) {
17198
+ return JSON.stringify(value.replace(/\s+/gu, " ").trim());
17199
+ }
17200
+ /** Compose the shared document: front matter for the graph loader, then the body. */
17201
+ function renderSharedMemoryDocument(record, now) {
17202
+ const tags = record.target.scope === "global" ? ["记忆", "全局共享"] : ["记忆", "部门共享"];
17203
+ return [
17204
+ "---",
17205
+ `id: mem-${record.id}`,
17206
+ `type: ${sharedNodeTypeOf(record.source.memoryType)}`,
17207
+ `title: ${yamlQuoted(record.source.title)}`,
17208
+ "authority: advisory",
17209
+ "internalizable: true",
17210
+ "origin: human",
17211
+ "reviewStatus: approved",
17212
+ `tags: [${tags.join(", ")}]`,
17213
+ `promotedAt: ${now}`,
17214
+ `promotionId: ${record.id}`,
17215
+ `scope: ${record.target.scope === "global" ? "global" : "department:" + (record.target.departmentCode ?? "")}`,
17216
+ "---",
17217
+ "",
17218
+ `# ${record.source.title}`,
17219
+ "",
17220
+ record.source.content,
17221
+ "",
17222
+ "---",
17223
+ "",
17224
+ `由 ${record.reviewedBy?.name ?? record.requestedBy.name} 于 ${now} 审核晋升。`,
17225
+ ""
17226
+ ].join("\n");
17227
+ }
17228
+ const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
17229
+ /** Read one shared graph, returning undefined when it has not been created yet. */
17230
+ async function readSharedGraph(graphPath) {
17231
+ let raw;
17232
+ try {
17233
+ raw = await readFile(graphPath, "utf8");
17234
+ } catch (error) {
17235
+ if (error.code === "ENOENT") return void 0;
17236
+ throw new MemoryPromotionError("io", `could not read ${graphPath}: ${String(error)}`);
17237
+ }
17238
+ try {
17239
+ const parsed = JSON.parse(raw);
17240
+ if (!isRecord$1(parsed) || parsed.schemaVersion !== 1 || !Array.isArray(parsed.nodes)) throw new Error("wrong shape");
17241
+ return parsed;
17242
+ } catch {
17243
+ throw new MemoryPromotionError("invalid-graph", `shared memory graph is not readable: ${graphPath}`);
17244
+ }
17245
+ }
17246
+ /** Compose a fresh manifest for one target scope. */
17247
+ function newSharedGraph(record, now) {
17248
+ return {
17249
+ schemaVersion: 1,
17250
+ id: SHARED_MEMORY_GRAPH_ID,
17251
+ name: sharedMemoryGraphName(record.target.scope),
17252
+ description: record.target.scope === "global" ? "经审核晋升到全局的共享记忆;只读展示。" : "经审核晋升到本部门的共享记忆;只读展示。",
17253
+ scope: record.target.scope === "global" ? "global" : "department:" + (record.target.departmentCode ?? ""),
17254
+ version: 1,
17255
+ status: "published",
17256
+ owner: record.reviewedBy?.id ?? record.requestedBy.id,
17257
+ createdAt: now,
17258
+ updatedAt: now,
17259
+ publishedAt: now,
17260
+ tags: ["记忆", "共享"],
17261
+ visibility: record.target.scope,
17262
+ defaultView: {
17263
+ layout: "hierarchy",
17264
+ direction: "TB"
17265
+ },
17266
+ topics: [],
17267
+ nodes: [],
17268
+ edges: []
17269
+ };
17270
+ }
17271
+ /**
17272
+ * Write an approved promotion into the target scope and register it in the shared
17273
+ * memory graph.
17274
+ *
17275
+ * The document is written first and the manifest second: if the manifest write
17276
+ * fails, the next approval retries both and the orphan document is harmless (it is
17277
+ * not referenced). The reverse order would publish a broken node.
17278
+ */
17279
+ async function applyPromotionToSharedMemory(input) {
17280
+ const { record, scopeRoot } = input;
17281
+ const now = input.now ?? (/* @__PURE__ */ new Date()).toISOString();
17282
+ if (record.status !== "pending") throw new MemoryPromotionError("conflict", `promotion ${record.id} is already ${record.status}`);
17283
+ const docRelPath = `${SHARED_MEMORY_FOLDER}/${record.id}.md`;
17284
+ if (record.target.docPath !== docRelPath) throw new MemoryPromotionError("invalid", "the stored promotion path does not match its id");
17285
+ const docPath = join(scopeRoot, SHARED_MEMORY_FOLDER, `${record.id}.md`);
17286
+ const graphPath = join(scopeRoot, ".graphs", SHARED_MEMORY_GRAPH_ID, "graph.json");
17287
+ await writeFileAtomic(docPath, renderSharedMemoryDocument(record, now));
17288
+ await serialize(graphPath, async () => {
17289
+ const existing = await readSharedGraph(graphPath);
17290
+ const manifest = existing === void 0 ? newSharedGraph(record, now) : {
17291
+ ...existing,
17292
+ version: (Number.isFinite(existing.version) ? existing.version : 0) + 1,
17293
+ updatedAt: now,
17294
+ publishedAt: now,
17295
+ status: "published",
17296
+ visibility: record.target.scope,
17297
+ scope: record.target.scope === "global" ? "global" : "department:" + (record.target.departmentCode ?? ""),
17298
+ tags: [.../* @__PURE__ */ new Set([
17299
+ ...existing.tags ?? [],
17300
+ "记忆",
17301
+ "共享"
17302
+ ])]
17303
+ };
17304
+ const nodeId = "mem-" + record.id;
17305
+ if (!manifest.nodes.some((node) => node.id === nodeId || node.path === docRelPath)) manifest.nodes = [...manifest.nodes, {
17306
+ id: nodeId,
17307
+ path: docRelPath
17308
+ }];
17309
+ await writeFileAtomic(graphPath, JSON.stringify(manifest, null, 2) + "\n");
17310
+ });
17311
+ return {
17312
+ docPath,
17313
+ graphPath,
17314
+ graphId: SHARED_MEMORY_GRAPH_ID
17315
+ };
17316
+ }
17317
+ //#endregion
17318
+ //#region src/memoryPromotionRoutes.ts
17319
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
17320
+ const ok = (body) => ({
17321
+ status: 200,
17322
+ body
17323
+ });
17324
+ const fail = (status, error, code, extra) => ({
17325
+ status,
17326
+ body: {
17327
+ error,
17328
+ ...code === void 0 ? {} : { code },
17329
+ ...extra
17330
+ }
17331
+ });
17332
+ /** The externally visible shape of one promotion; never the source user id. */
17333
+ function publicPromotion(record, viewerId) {
17334
+ return {
17335
+ id: record.id,
17336
+ memoryId: record.source.memoryId,
17337
+ title: record.source.title,
17338
+ type: record.source.memoryType,
17339
+ content: record.source.content,
17340
+ status: record.status,
17341
+ targetScope: record.target.scope,
17342
+ ...record.target.departmentCode === void 0 ? {} : { departmentCode: record.target.departmentCode },
17343
+ ...record.target.departmentName === void 0 ? {} : { departmentName: record.target.departmentName },
17344
+ targetGraph: record.target.graphId,
17345
+ requestedAt: record.requestedAt,
17346
+ requestedByName: record.requestedBy.name,
17347
+ ...record.reviewedAt === void 0 ? {} : { reviewedAt: record.reviewedAt },
17348
+ ...record.reviewedBy === void 0 ? {} : { reviewedByName: record.reviewedBy.name },
17349
+ ...record.reviewNote === void 0 ? {} : { reviewNote: record.reviewNote },
17350
+ confirmed: record.confirmed,
17351
+ selfApproval: record.requestedBy.id === viewerId
17352
+ };
17353
+ }
17354
+ /** Build the row without any personal identifier or source session. */
17355
+ function sharedRowOf(record) {
17356
+ return {
17357
+ id: record.id,
17358
+ title: record.source.title,
17359
+ type: record.source.memoryType,
17360
+ content: record.source.content,
17361
+ scope: record.target.scope,
17362
+ ...record.target.departmentCode === void 0 ? {} : { departmentCode: record.target.departmentCode },
17363
+ ...record.target.departmentName === void 0 ? {} : { departmentName: record.target.departmentName },
17364
+ promotedAt: record.appliedAt ?? record.reviewedAt ?? record.requestedAt,
17365
+ ...record.reviewedBy === void 0 ? {} : { promotedBy: record.reviewedBy.name }
17366
+ };
17367
+ }
17368
+ /** Validate and normalize one `memory.promote` body. */
17369
+ function readPromoteBody(body) {
17370
+ if (Object.prototype.hasOwnProperty.call(body, "userId") || Object.prototype.hasOwnProperty.call(body, "sourceUserId")) throw new MemoryPromotionError("invalid", "the source user is resolved from the request, never the body");
17371
+ const id = typeof body.id === "string" ? body.id.trim() : "";
17372
+ if (id === "" || id.length > 200 || /[\s/\\\u0000]/u.test(id)) throw new MemoryPromotionError("invalid", "a safe memory id is required");
17373
+ const scope = body.targetScope;
17374
+ if (scope !== "department" && scope !== "global") throw new MemoryPromotionError("invalid", "targetScope must be department or global");
17375
+ const departmentCode = typeof body.departmentCode === "string" ? body.departmentCode.trim() : void 0;
17376
+ if (departmentCode !== void 0 && (departmentCode === "" || departmentCode.length > 120)) throw new MemoryPromotionError("invalid", "departmentCode must be 1–120 characters");
17377
+ if (body.confirm !== void 0 && typeof body.confirm !== "boolean") throw new MemoryPromotionError("invalid", "confirm must be a boolean");
17378
+ const note = typeof body.note === "string" ? body.note.trim() : void 0;
17379
+ if (note !== void 0 && note.length > 500) throw new MemoryPromotionError("invalid", "note is longer than 500 characters");
17380
+ return {
17381
+ id,
17382
+ scope,
17383
+ ...departmentCode === void 0 ? {} : { departmentCode },
17384
+ confirm: body.confirm === true,
17385
+ ...note === void 0 || note === "" ? {} : { note }
17386
+ };
17387
+ }
17388
+ /** The target path/data for one promotion request. */
17389
+ function buildTarget(scope, decision, departmentName) {
17390
+ const idPlaceholder = "<id>";
17391
+ targetScopePrefix({
17392
+ scope,
17393
+ ...decision.departmentCode === void 0 ? {} : { departmentCode: decision.departmentCode },
17394
+ ...decision.departmentPath === void 0 ? {} : { departmentPath: decision.departmentPath },
17395
+ graphId: SHARED_MEMORY_GRAPH_ID,
17396
+ graphName: sharedMemoryGraphName(scope),
17397
+ docPath: ""
17398
+ });
17399
+ return {
17400
+ scope,
17401
+ ...decision.departmentCode === void 0 ? {} : { departmentCode: decision.departmentCode },
17402
+ ...scope === "department" && departmentName !== void 0 ? { departmentName } : {},
17403
+ ...decision.departmentPath === void 0 ? {} : { departmentPath: decision.departmentPath },
17404
+ graphId: SHARED_MEMORY_GRAPH_ID,
17405
+ graphName: sharedMemoryGraphName(scope),
17406
+ docPath: `${SHARED_MEMORY_FOLDER}/${idPlaceholder}.md`
17407
+ };
17408
+ }
17409
+ /** Map a typed failure to the status the page can act on. */
17410
+ function failureOf(error) {
17411
+ if (error instanceof MemoryPromotionError) {
17412
+ const status = error.code === "forbidden" ? 403 : error.code === "not-found" ? 404 : error.code === "conflict" ? 409 : error.code === "io" || error.code === "invalid-graph" ? 500 : 400;
17413
+ return fail(status, error.message, error.code);
17414
+ }
17415
+ if (error instanceof MemoryStoreError) {
17416
+ const status = error.code === "not-found" || error.code === "sop-not-found" ? 404 : 400;
17417
+ return fail(status, error.message, error.code);
17418
+ }
17419
+ throw error;
17420
+ }
17421
+ /** DataOps is authoritative; an absent seam means a local deployment with no grants. */
17422
+ async function allowed(check, relPath) {
17423
+ return check === void 0 ? true : check(relPath);
17424
+ }
17425
+ /** Apply an approved record after the target write path has been authorized. */
17426
+ async function applyApproved(input, record, reviewer, confirmed, note) {
17427
+ const scopeRoot = targetScopeRoot(record.target);
17428
+ if (!await allowed(input.canWrite, scopeRoot)) throw new MemoryPromotionError("forbidden", "没有目标部门/全局记忆的写入权限。");
17429
+ await applyPromotionToSharedMemory({
17430
+ record,
17431
+ scopeRoot: joinRoot(input.actualRoot, scopeRoot),
17432
+ now: (input.now?.() ?? /* @__PURE__ */ new Date()).toISOString()
17433
+ });
17434
+ return markPromotionApproved(input.queuePath, record.id, reviewer, scopeRoot + "/" + record.target.docPath, {
17435
+ confirmed,
17436
+ ...note === void 0 ? {} : { note }
17437
+ }, input.now);
17438
+ }
17439
+ /** Join an absolute root with a scope-relative prefix that already ends in `/`. */
17440
+ function joinRoot(root, prefix) {
17441
+ return root.replace(/[\\/]+$/u, "") + "/" + prefix.replace(/^[\\/]+/u, "").replace(/[\\/]+$/u, "");
17442
+ }
17443
+ /**
17444
+ * Handle one promotion/shared-memory method.
17445
+ *
17446
+ * Expected failures are returned as status/body pairs. Unexpected errors are
17447
+ * rethrown so the route's outer handler reports a real 500 rather than a
17448
+ * misleading 400.
17449
+ */
17450
+ async function handleMemoryPromotionRoute(input) {
17451
+ const { method, actor, reviewer } = input;
17452
+ const body = isRecord(input.body) ? input.body : {};
17453
+ try {
17454
+ switch (method) {
17455
+ case "memory.promote": {
17456
+ const parsed = readPromoteBody(body);
17457
+ const decision = decidePromotionScope(reviewer, parsed.scope, parsed.departmentCode);
17458
+ if (!decision.ok) return fail(403, decision.message, decision.code === "invalid" ? "invalid" : "PROMOTION_FORBIDDEN");
17459
+ const entry = await input.store.getEntry(parsed.id);
17460
+ if (entry === void 0) return fail(404, "memory entry not found", "not-found");
17461
+ if (entry.privacy !== "normal") return fail(400, "只有隐私为「普通」的记忆可以晋升;仅自己、敏感和凭据引用不会被共享。", "PRIVACY_NOT_PROMOTABLE");
17462
+ const target = buildTarget(parsed.scope, decision, reviewer.departmentName);
17463
+ const draft = {
17464
+ source: {
17465
+ userId: actor.id,
17466
+ userName: actor.name,
17467
+ memoryId: entry.id,
17468
+ memoryType: entry.type,
17469
+ title: promotionTitleOf(entry),
17470
+ content: promotionContentOf(entry),
17471
+ privacy: entry.privacy,
17472
+ ...entry.sourceLabel === void 0 ? {} : { sourceLabel: entry.sourceLabel }
17473
+ },
17474
+ target
17475
+ };
17476
+ const created = await createPromotionRequest(input.queuePath, draft, actor, input.now);
17477
+ if (created.duplicate) return ok({
17478
+ promotion: publicPromotion(created.record, actor.id),
17479
+ duplicate: true,
17480
+ applied: false
17481
+ });
17482
+ if (!parsed.confirm) return ok({
17483
+ promotion: publicPromotion(created.record, actor.id),
17484
+ pending: true,
17485
+ applied: false
17486
+ });
17487
+ const approved = await applyApproved(input, created.record, {
17488
+ id: actor.id,
17489
+ name: actor.name
17490
+ }, true, parsed.note);
17491
+ return ok({
17492
+ promotion: publicPromotion(approved, actor.id),
17493
+ pending: false,
17494
+ applied: true
17495
+ });
16702
17496
  }
16703
- default: return fail(404, `unknown memory method: ${method}`, "not-found");
17497
+ case "memory.promotions": {
17498
+ const view = body.view === "review" ? "review" : "mine";
17499
+ const records = await listPromotionRecords(input.queuePath);
17500
+ const mine = records.filter((record) => record.requestedBy.id === actor.id).map((record) => publicPromotion(record, actor.id));
17501
+ const review = view !== "review" ? [] : records.filter((record) => record.status === "pending" && canReviewPromotion(reviewer, record.target)).map((record) => ({
17502
+ promotion: publicPromotion(record, actor.id),
17503
+ selfApproval: record.requestedBy.id === actor.id
17504
+ }));
17505
+ const canPromoteGlobal = decidePromotionScope(reviewer, "global").ok;
17506
+ const departmentCode = reviewer.departmentCode;
17507
+ const canPromoteDepartment = departmentCode !== void 0 && decidePromotionScope(reviewer, "department", departmentCode).ok;
17508
+ return ok({
17509
+ canPromote: {
17510
+ global: canPromoteGlobal,
17511
+ departments: canPromoteDepartment ? [departmentCode] : []
17512
+ },
17513
+ canReview: reviewer.isGlobalAdmin || reviewer.reviewDepartments.length > 0,
17514
+ promotions: mine,
17515
+ reviewQueue: review,
17516
+ scopes: {
17517
+ global: canPromoteGlobal,
17518
+ departments: canPromoteDepartment ? [departmentCode] : []
17519
+ }
17520
+ });
17521
+ }
17522
+ case "memory.review-promotion": {
17523
+ const id = typeof body.id === "string" ? body.id.trim() : "";
17524
+ if (id === "") return fail(400, "a promotion id is required", "invalid");
17525
+ const decision = body.decision;
17526
+ if (decision !== "approve" && decision !== "reject") return fail(400, "decision must be approve or reject", "invalid");
17527
+ const note = typeof body.note === "string" ? body.note.trim() : void 0;
17528
+ if (note !== void 0 && note.length > 500) return fail(400, "note is longer than 500 characters", "invalid");
17529
+ const record = await getPromotionRecord(input.queuePath, id);
17530
+ if (record === void 0) return fail(404, "promotion not found", "not-found");
17531
+ if (record.status !== "pending") return fail(409, `promotion is already ${record.status}`, "conflict");
17532
+ if (!canReviewPromotion(reviewer, record.target)) return fail(403, "没有该晋升目标范围的审核权限。", "PROMOTION_FORBIDDEN");
17533
+ if (decision === "approve" && record.requestedBy.id === actor.id) return fail(403, "不能审核通过自己提交的晋升;请联系另一位管理员。", "SELF_APPROVAL_FORBIDDEN");
17534
+ if (decision === "reject") {
17535
+ const rejected = await markPromotionRejected(input.queuePath, id, actor, note, input.now);
17536
+ return ok({
17537
+ promotion: publicPromotion(rejected, actor.id),
17538
+ applied: false
17539
+ });
17540
+ }
17541
+ const approved = await applyApproved(input, record, actor, false, note);
17542
+ return ok({
17543
+ promotion: publicPromotion(approved, actor.id),
17544
+ applied: true
17545
+ });
17546
+ }
17547
+ case "memory.shared": {
17548
+ const records = await listPromotionRecords(input.queuePath);
17549
+ const rows = [];
17550
+ const readCache = /* @__PURE__ */ new Map();
17551
+ for (const record of records) {
17552
+ if (record.status !== "approved") continue;
17553
+ if (record.source.privacy !== "normal") continue;
17554
+ if (!isPromotionVisibleTo(record, reviewer)) continue;
17555
+ const scopeRoot = targetScopeRoot(record.target);
17556
+ let readable = readCache.get(scopeRoot);
17557
+ if (readable === void 0) {
17558
+ readable = await allowed(input.canRead, scopeRoot);
17559
+ readCache.set(scopeRoot, readable);
17560
+ }
17561
+ if (!readable) continue;
17562
+ rows.push(sharedRowOf(record));
17563
+ }
17564
+ rows.sort((left, right) => right.promotedAt.localeCompare(left.promotedAt));
17565
+ return ok({ entries: rows.slice(0, 100) });
17566
+ }
17567
+ default: return fail(404, `unknown memory promotion method: ${String(method)}`, "not-found");
16704
17568
  }
16705
17569
  } catch (error) {
16706
17570
  return failureOf(error);
@@ -17030,6 +17894,40 @@ async function syncPersonalMemoryGraph(options) {
17030
17894
  *
17031
17895
  * @module @sparkelf/dsh-knowledge-base/guardian-session
17032
17896
  */
17897
+ /**
17898
+ * Default bound for guardian session resolution and message delivery.
17899
+ *
17900
+ * The guardian TURN itself is asynchronous (DSH's own inbox is the queue), so
17901
+ * this cannot bound model latency. What it does bound is the plugin's wait for
17902
+ * a standard-mode agent to be created/resumed or for `followup` to accept the
17903
+ * message; without it a hung agent loop can block a normal session's tool call
17904
+ * indefinitely.
17905
+ */
17906
+ const DEFAULT_GUARDIAN_TIMEOUT_MS = 3e4;
17907
+ /** A guardian operation exceeded its bounded wait. */
17908
+ var GuardianTimeoutError = class extends Error {
17909
+ name = "GuardianTimeoutError";
17910
+ code = "unreachable";
17911
+ constructor(message) {
17912
+ super(message);
17913
+ }
17914
+ };
17915
+ /** Bound one promise without cancelling the underlying operation. */
17916
+ function withGuardianTimeout(operation, timeoutMs, label) {
17917
+ if (timeoutMs === void 0 || !Number.isFinite(timeoutMs) || timeoutMs <= 0) return operation;
17918
+ return new Promise((resolve, reject) => {
17919
+ const timer = setTimeout(() => {
17920
+ reject(new GuardianTimeoutError(`${label} timed out after ${String(timeoutMs)}ms`));
17921
+ }, timeoutMs);
17922
+ operation.then((value) => {
17923
+ clearTimeout(timer);
17924
+ resolve(value);
17925
+ }, (error) => {
17926
+ clearTimeout(timer);
17927
+ reject(error);
17928
+ });
17929
+ });
17930
+ }
17033
17931
  /** Title is display-only but stable, so an operator can recognize the session. */
17034
17932
  const GUARDIAN_SESSION_TITLE = "记忆守护会话";
17035
17933
  /** Skill the guardian must load before doing anything else. */
@@ -17244,8 +18142,8 @@ async function resolveOrCreateGuardianUncached(host, userId) {
17244
18142
  * session. This is the ONLY send path used by the tool and the triggers.
17245
18143
  */
17246
18144
  async function sendToGuardian(host, userId, message) {
17247
- const resolved = await resolveOrCreateGuardian(host, userId);
17248
- const delivery = await host.deliverText(resolved.agent, renderGuardianMessage(message));
18145
+ const resolved = await withGuardianTimeout(resolveOrCreateGuardian(host, userId), host.timeoutMs, "guardian session resolution");
18146
+ const delivery = await withGuardianTimeout(Promise.resolve(host.deliverText(resolved.agent, renderGuardianMessage(message))), host.timeoutMs, "guardian message delivery");
17249
18147
  await new GuardianSessionStore(host.usersRoot).write({
17250
18148
  ...resolved.state,
17251
18149
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
@@ -21134,6 +22032,7 @@ const Config = z.object({
21134
22032
  memoryUsersRoot: z.string().default(""),
21135
22033
  memorySkillsRoot: z.string().default(""),
21136
22034
  memoryIdleMinutes: z.number().default(30),
22035
+ memoryDefaultEnabledPermission: z.string().default("kb:config:manage"),
21137
22036
  permitted: z.string().default("*"),
21138
22037
  nfsServer: z.string().default(""),
21139
22038
  storageProtocol: z.union([z.const("nfs"), z.const("sshfs")]).default("nfs"),
@@ -22243,7 +23142,8 @@ async function fetchCaller(ctx, config) {
22243
23142
  if (!isTeamDeployment(config)) return {
22244
23143
  userId: LOCAL_USER_ID,
22245
23144
  label: "本地用户",
22246
- roleCodes: []
23145
+ roleCodes: [],
23146
+ permissions: []
22247
23147
  };
22248
23148
  const body = await request(ctx, config, ENDPOINTS.me);
22249
23149
  const profile = body.user ?? body;
@@ -22251,6 +23151,7 @@ async function fetchCaller(ctx, config) {
22251
23151
  if (userId === "") throw new KnowledgeError("DataOps did not report the caller id", "not-configured");
22252
23152
  const label = typeof profile.displayName === "string" ? profile.displayName : typeof profile.username === "string" ? profile.username : userId;
22253
23153
  const roleCodes = Array.isArray(profile.roles) ? profile.roles.map((role) => role.code).filter((code) => typeof code === "string" && code !== "") : [];
23154
+ const permissions = Array.isArray(profile.permissions) ? profile.permissions.filter((key) => typeof key === "string" && key !== "") : [];
22254
23155
  let department = readDepartmentOf(profile.department);
22255
23156
  if (department !== void 0 && department.pathCodes === void 0) {
22256
23157
  const recovered = await readDepartmentPathFromCatalog(ctx, config, department.code).catch(() => void 0);
@@ -22263,6 +23164,7 @@ async function fetchCaller(ctx, config) {
22263
23164
  userId,
22264
23165
  label,
22265
23166
  roleCodes,
23167
+ permissions,
22266
23168
  ...department === void 0 ? {} : {
22267
23169
  departmentCode: department.code,
22268
23170
  departmentName: department.name,
@@ -23052,8 +23954,10 @@ function permissionForKbRoute(method) {
23052
23954
  if (method === "create" || method === "edit" || method === "move" || method === "upload" || method === "rename") return "kb:file:write";
23053
23955
  if (method === "trash" || method === "trash.remove" || method === "trash.restore") return "kb:file:delete";
23054
23956
  if (method === "memory.list" || method === "memory.get" || method === "memory.settings") return "kb:file:read";
23055
- if (method === "memory.update" || method === "memory.set-enabled") return "kb:file:write";
23957
+ if (method === "memory.update" || method === "memory.set-enabled" || method === "memory.save-settings") return "kb:file:write";
23056
23958
  if (method === "memory.forget") return "kb:file:delete";
23959
+ if (method === "memory.shared") return "kb:file:read";
23960
+ if (method === "memory.promote" || method === "memory.promotions" || method === "memory.review-promotion") return "kb:review:decide";
23057
23961
  if (method === "index" || method === "extract.retry") return "kb:file:extract";
23058
23962
  if (method === "index.status") return "kb:file:read";
23059
23963
  if (method === "audit.list") return "kb:audit:read";
@@ -25649,11 +26553,13 @@ function apply(ctx, deploymentConfig) {
25649
26553
  case "memory.update":
25650
26554
  case "memory.forget":
25651
26555
  case "memory.settings":
25652
- case "memory.set-enabled": {
26556
+ case "memory.set-enabled":
26557
+ case "memory.save-settings": {
25653
26558
  const caller = await fetchCaller(host, config);
25654
26559
  if (!isSafeUserId(caller.userId)) return writeJson(res, 400, { error: "unsafe caller id; memory is scoped to the authenticated user" });
25655
26560
  const body = await readJsonBody(req);
25656
26561
  const personalScope = personalScopeRootFor(caller.userId);
26562
+ const defaultEnabled = config.memoryDefaultEnabledPermission.trim() !== "" && (caller.permissions ?? []).includes(config.memoryDefaultEnabledPermission);
25657
26563
  const result = await handleMemoryRoute({
25658
26564
  method,
25659
26565
  body,
@@ -25663,10 +26569,55 @@ function apply(ctx, deploymentConfig) {
25663
26569
  },
25664
26570
  store: new MemoryStore(join(personalScope, PERSONAL_MEMORY_FOLDER)),
25665
26571
  settings: new MemorySettingsStore(memoryUsersRoot),
26572
+ defaultEnabled,
25666
26573
  graphWriter: new MemoryGraphWriter({ scopeRoot: personalScope })
25667
26574
  });
25668
26575
  return writeJson(res, result.status, result.body);
25669
26576
  }
26577
+ case "memory.promote":
26578
+ case "memory.promotions":
26579
+ case "memory.review-promotion":
26580
+ case "memory.shared": {
26581
+ const caller = await fetchCaller(host, config);
26582
+ if (!isSafeUserId(caller.userId)) return writeJson(res, 400, { error: "unsafe caller id; memory is scoped to the authenticated user" });
26583
+ let reviewContext;
26584
+ if (isTeamDeployment(config)) reviewContext = await managementHost.context();
26585
+ const reviewer = reviewContext === void 0 ? {
26586
+ userId: caller.userId,
26587
+ name: caller.label ?? caller.userId,
26588
+ isGlobalAdmin: true,
26589
+ canManageConfig: true,
26590
+ reviewDepartments: [],
26591
+ visibleDepartmentCodes: []
26592
+ } : {
26593
+ userId: caller.userId,
26594
+ name: caller.label ?? caller.userId,
26595
+ isGlobalAdmin: reviewContext.review.canReviewGlobal === true || reviewContext.roleCodes.some((code) => code === "SUPER_ADMIN" || code === "ADMIN"),
26596
+ canManageConfig: hasPermission(reviewContext, "kb:config:manage"),
26597
+ ...caller.departmentCode === void 0 ? {} : { departmentCode: caller.departmentCode },
26598
+ ...caller.departmentName === void 0 ? {} : { departmentName: caller.departmentName },
26599
+ ...caller.departmentPathCodes === void 0 ? reviewContext.departmentPathCodes === void 0 ? {} : { departmentPathCodes: [...reviewContext.departmentPathCodes] } : { departmentPathCodes: [...caller.departmentPathCodes] },
26600
+ reviewDepartments: [...reviewContext.review.departments],
26601
+ visibleDepartmentCodes: [...reviewContext.dataScope.departmentCodes]
26602
+ };
26603
+ const body = await readJsonBody(req);
26604
+ const personalScope = personalScopeRootFor(caller.userId);
26605
+ const result = await handleMemoryPromotionRoute({
26606
+ method,
26607
+ body,
26608
+ actor: {
26609
+ id: caller.userId,
26610
+ name: caller.label ?? caller.userId
26611
+ },
26612
+ reviewer,
26613
+ store: new MemoryStore(join(personalScope, PERSONAL_MEMORY_FOLDER)),
26614
+ queuePath: promotionStorePath(memoryUsersRoot),
26615
+ actualRoot: localConfig(config).actualRoot,
26616
+ canWrite: (relPath) => canWritePath(host, config, relPath),
26617
+ canRead: (relPath) => canReadPath(host, config, relPath)
26618
+ });
26619
+ return writeJson(res, result.status, result.body);
26620
+ }
25670
26621
  default: return writeJson(res, 404, { error: `unknown knowledge-base method: ${method}` });
25671
26622
  }
25672
26623
  } catch (error) {
@@ -27007,7 +27958,16 @@ function apply(ctx, deploymentConfig) {
27007
27958
  const configured = (config.memoryUsersRoot ?? "").trim();
27008
27959
  return configured === "" ? join(localConfig(config).actualRoot, ".memory", "users") : resolveStorageRoot(configured);
27009
27960
  })();
27010
- const memorySettings = new MemorySettingsStore(memoryUsersRoot);
27961
+ const memorySettings = new MemorySettingsStore(memoryUsersRoot, { memoryEnabled: async (userId) => {
27962
+ const permission = config.memoryDefaultEnabledPermission.trim();
27963
+ if (permission === "" || !isTeamDeployment(config)) return false;
27964
+ try {
27965
+ const caller = await fetchCaller(host, config);
27966
+ return caller.userId === userId && (caller.permissions ?? []).includes(permission);
27967
+ } catch {
27968
+ return false;
27969
+ }
27970
+ } });
27011
27971
  const memoryToolHost = {
27012
27972
  resolveCaller: async () => {
27013
27973
  const caller = await managementHost.context();
@@ -27073,6 +28033,7 @@ function apply(ctx, deploymentConfig) {
27073
28033
  const guardianSessionHost = {
27074
28034
  usersRoot: memoryUsersRoot,
27075
28035
  cwd: process.cwd(),
28036
+ timeoutMs: DEFAULT_GUARDIAN_TIMEOUT_MS,
27076
28037
  getAgent: (sessionId) => guardianRegistry?.get(sessionId),
27077
28038
  createAgent: async ({ sessionId, cwd, title }) => {
27078
28039
  if (guardianLoop === void 0) throw new Error("the DSH agent loop is not available");