@sparkelf/dsh-knowledge-base 0.6.0 → 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. */
@@ -16553,13 +16553,13 @@ const CONTENT_FIELD = {
16553
16553
  episodic: "summary",
16554
16554
  fact: "statement"
16555
16555
  };
16556
- const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
16556
+ const isRecord$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
16557
16557
  const messageOf$1 = (error) => error instanceof Error ? error.message : String(error);
16558
- const ok = (body) => ({
16558
+ const ok$1 = (body) => ({
16559
16559
  status: 200,
16560
16560
  body
16561
16561
  });
16562
- const fail = (status, error, code, extra) => ({
16562
+ const fail$1 = (status, error, code, extra) => ({
16563
16563
  status,
16564
16564
  body: {
16565
16565
  error,
@@ -16587,15 +16587,15 @@ function clipLine(value, max = 80) {
16587
16587
  return clean.length <= max ? clean : `${clean.slice(0, max - 1)}…`;
16588
16588
  }
16589
16589
  /** A technical token that should never be the first thing a reader sees in a row. */
16590
- function looksTechnical(value) {
16590
+ function looksTechnical$1(value) {
16591
16591
  if (/[\\/]|session-|kb_[a-z]|\.md\b|\bSOP\b|[a-z]+_[a-z]+/iu.test(value)) return true;
16592
16592
  return value.trim().length > 12 && /^[a-z0-9._-]+$/u.test(value.trim());
16593
16593
  }
16594
16594
  /** Short, non-technical fallback for entries written before displayTitle existed. */
16595
16595
  function fallbackTitle(entry) {
16596
16596
  switch (entry.type) {
16597
- case "preference": return clipLine(looksTechnical(entry.value) ? entry.topic : entry.value, 20);
16598
- 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);
16599
16599
  case "episodic":
16600
16600
  if (entry.tags?.includes("SOP评估")) return "方法评估";
16601
16601
  if (entry.tags?.includes("SOP晋升")) return "方法晋升";
@@ -16603,7 +16603,7 @@ function fallbackTitle(entry) {
16603
16603
  if (entry.tags?.includes("compaction")) return "压缩触发";
16604
16604
  if (entry.tags?.includes("dream")) return "记忆整理";
16605
16605
  return "情景记录";
16606
- case "fact": return looksTechnical(entry.key) ? "事实记录" : clipLine(entry.key, 20);
16606
+ case "fact": return looksTechnical$1(entry.key) ? "事实记录" : clipLine(entry.key, 20);
16607
16607
  case "sop": return clipLine(entry.title, 20);
16608
16608
  }
16609
16609
  }
@@ -16673,81 +16673,81 @@ function readEntryId(body) {
16673
16673
  const readNonEmptyString = (value) => typeof value === "string" && value.trim() !== "" ? value : void 0;
16674
16674
  /** Extract and validate the patch, translating the generic `content` alias. */
16675
16675
  function readUpdatePatch(body, entry) {
16676
- 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") };
16677
16677
  const hasPatchObject = Object.prototype.hasOwnProperty.call(body, "patch");
16678
- 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") };
16679
16679
  const source = hasPatchObject ? body.patch : body;
16680
16680
  if (hasPatchObject) {
16681
16681
  const extra = Object.keys(body).filter((key) => key !== "id" && key !== "patch");
16682
- 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") };
16683
16683
  } else {
16684
16684
  const extra = Object.keys(body).filter((key) => key !== "id" && !PATCH_FIELDS.has(key));
16685
- 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") };
16686
16686
  }
16687
- 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") };
16688
16688
  const unknown = Object.keys(source).filter((key) => !PATCH_FIELDS.has(key) && (hasPatchObject || key !== "id"));
16689
- 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") };
16690
16690
  const patch = {};
16691
16691
  if (source.title !== void 0) {
16692
16692
  const title = readNonEmptyString(source.title);
16693
- 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") };
16694
16694
  patch.title = title;
16695
16695
  }
16696
16696
  if (source.content !== void 0) {
16697
16697
  const content = readNonEmptyString(source.content);
16698
- 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") };
16699
16699
  const field = CONTENT_FIELD[entry.type];
16700
- if (field === void 0) return { error: fail(400, `content cannot be edited on a ${entry.type} entry; edit title or steps`, "invalid") };
16701
- 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") };
16702
16702
  patch[String(field)] = content;
16703
16703
  }
16704
16704
  if (source.value !== void 0) {
16705
16705
  const value = readNonEmptyString(source.value);
16706
- 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") };
16707
16707
  patch.value = value;
16708
16708
  }
16709
16709
  if (source.statement !== void 0) {
16710
16710
  const statement = readNonEmptyString(source.statement);
16711
- 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") };
16712
16712
  patch.statement = statement;
16713
16713
  }
16714
16714
  if (source.solution !== void 0) {
16715
16715
  const solution = readNonEmptyString(source.solution);
16716
- 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") };
16717
16717
  patch.solution = solution;
16718
16718
  }
16719
16719
  if (source.steps !== void 0) {
16720
16720
  const steps = source.steps;
16721
- 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") };
16722
16722
  patch.steps = steps;
16723
16723
  }
16724
16724
  if (source.privacy !== void 0) {
16725
- 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") };
16726
16726
  patch.privacy = source.privacy;
16727
16727
  }
16728
16728
  return { patch };
16729
16729
  }
16730
16730
  /** Extract and validate the settings write, translating `enabled` to the stored field. */
16731
16731
  function readSettingsPatch(body, options) {
16732
- if (Object.prototype.hasOwnProperty.call(body, "userId")) return { error: fail(400, "userId must not be supplied; the caller is resolved from the request", "invalid") };
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
16733
  const unknown = Object.keys(body).filter((key) => key !== "enabled" && key !== "consolidationIntervalMinutes");
16734
- if (unknown.length > 0) return { error: fail(400, `unsupported settings field(s): ${unknown.join(", ")}`, "invalid") };
16735
- if (options.requireEnabled && body.enabled === void 0) return { error: fail(400, "enabled must be a boolean", "invalid") };
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
16736
  const patch = {};
16737
16737
  if (body.enabled !== void 0) {
16738
- if (typeof body.enabled !== "boolean") return { error: fail(400, "enabled must be a boolean", "invalid") };
16738
+ if (typeof body.enabled !== "boolean") return { error: fail$1(400, "enabled must be a boolean", "invalid") };
16739
16739
  patch.memoryEnabled = body.enabled;
16740
16740
  }
16741
16741
  if (body.consolidationIntervalMinutes !== void 0) try {
16742
16742
  patch.consolidationIntervalMinutes = normalizeConsolidationInterval(body.consolidationIntervalMinutes);
16743
16743
  } catch (error) {
16744
- if (error instanceof MemorySettingsError) return { error: fail(400, error.message, error.code, {
16744
+ if (error instanceof MemorySettingsError) return { error: fail$1(400, error.message, error.code, {
16745
16745
  min: 15,
16746
16746
  max: MEMORY_CONSOLIDATION_INTERVAL_MAX
16747
16747
  }) };
16748
16748
  throw error;
16749
16749
  }
16750
- if (patch.memoryEnabled === void 0 && patch.consolidationIntervalMinutes === void 0) return { error: fail(400, "at least one memory setting must be supplied", "invalid") };
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
16751
  return { patch };
16752
16752
  }
16753
16753
  /** Reconcile the personal-memory graph; a derived failure must not undo the write. */
@@ -16760,12 +16760,12 @@ async function syncGraph(graphWriter) {
16760
16760
  }
16761
16761
  }
16762
16762
  /** Map a store/validation failure to an actionable status; unknown errors escape. */
16763
- function failureOf(error) {
16764
- if (error instanceof MemorySettingsError) return fail(400, error.message, error.code);
16765
- 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 });
16766
16766
  if (error instanceof MemoryStoreError) {
16767
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;
16768
- return fail(status, error.message, error.code);
16768
+ return fail$1(status, error.message, error.code);
16769
16769
  }
16770
16770
  throw error;
16771
16771
  }
@@ -16779,62 +16779,792 @@ function failureOf(error) {
16779
16779
  */
16780
16780
  async function handleMemoryRoute(input) {
16781
16781
  const { method, caller, store, settings, graphWriter } = input;
16782
- if (!isSafeUserId(caller.userId)) return fail(403, "unsafe caller id; memory is scoped to the authenticated user", "forbidden");
16783
- 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 : {};
16784
16784
  try {
16785
16785
  switch (method) {
16786
16786
  case "memory.list": {
16787
16787
  const [settingsState, entries] = await Promise.all([settings.read(caller.userId, readOptions(input.defaultEnabled)), store.listEntries()]);
16788
- return ok({
16788
+ return ok$1({
16789
16789
  enabled: settingsState.memoryEnabled,
16790
16790
  entries: entries.map(listRow)
16791
16791
  });
16792
16792
  }
16793
16793
  case "memory.get": {
16794
16794
  const id = readEntryId(body);
16795
- 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");
16796
16796
  const entry = await store.getEntry(id);
16797
- if (entry === void 0) return fail(404, "memory entry not found", "not-found");
16798
- 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));
16799
16799
  }
16800
16800
  case "memory.update": {
16801
16801
  const id = readEntryId(body);
16802
- 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");
16803
16803
  const entry = await store.getEntry(id);
16804
- 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");
16805
16805
  const built = readUpdatePatch(body, entry);
16806
16806
  if ("error" in built) return built.error;
16807
16807
  const updated = await store.updateEntry(id, built.patch);
16808
16808
  const graphSyncWarning = await syncGraph(graphWriter);
16809
- return ok({
16809
+ return ok$1({
16810
16810
  ...entryPayload(updated),
16811
16811
  ...graphSyncWarning === void 0 ? {} : { graphSyncWarning }
16812
16812
  });
16813
16813
  }
16814
16814
  case "memory.forget": {
16815
16815
  const id = readEntryId(body);
16816
- 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");
16817
16817
  const forgotten = await store.forgetEntry(id);
16818
16818
  const graphSyncWarning = forgotten.removed ? await syncGraph(graphWriter) : void 0;
16819
- return ok({
16819
+ return ok$1({
16820
16820
  ...forgotten,
16821
16821
  ...graphSyncWarning === void 0 ? {} : { graphSyncWarning }
16822
16822
  });
16823
16823
  }
16824
- case "memory.settings": return ok(settingsPayload(await settings.read(caller.userId, readOptions(input.defaultEnabled))));
16824
+ case "memory.settings": return ok$1(settingsPayload(await settings.read(caller.userId, readOptions(input.defaultEnabled))));
16825
16825
  case "memory.set-enabled": {
16826
16826
  const built = readSettingsPatch(body, { requireEnabled: true });
16827
16827
  if ("error" in built) return built.error;
16828
16828
  const next = await settings.save(caller.userId, built.patch, readOptions(input.defaultEnabled));
16829
- return ok(settingsPayload(next));
16829
+ return ok$1(settingsPayload(next));
16830
16830
  }
16831
16831
  case "memory.save-settings": {
16832
16832
  const built = readSettingsPatch(body, { requireEnabled: false });
16833
16833
  if ("error" in built) return built.error;
16834
16834
  const next = await settings.save(caller.userId, built.patch, readOptions(input.defaultEnabled));
16835
- return ok(settingsPayload(next));
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
+ });
17496
+ }
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
+ });
16836
17546
  }
16837
- default: return fail(404, `unknown memory method: ${method}`, "not-found");
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");
16838
17568
  }
16839
17569
  } catch (error) {
16840
17570
  return failureOf(error);
@@ -23226,6 +23956,8 @@ function permissionForKbRoute(method) {
23226
23956
  if (method === "memory.list" || method === "memory.get" || method === "memory.settings") return "kb:file:read";
23227
23957
  if (method === "memory.update" || method === "memory.set-enabled" || method === "memory.save-settings") return "kb:file:write";
23228
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";
23229
23961
  if (method === "index" || method === "extract.retry") return "kb:file:extract";
23230
23962
  if (method === "index.status") return "kb:file:read";
23231
23963
  if (method === "audit.list") return "kb:audit:read";
@@ -25842,6 +26574,50 @@ function apply(ctx, deploymentConfig) {
25842
26574
  });
25843
26575
  return writeJson(res, result.status, result.body);
25844
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
+ }
25845
26621
  default: return writeJson(res, 404, { error: `unknown knowledge-base method: ${method}` });
25846
26622
  }
25847
26623
  } catch (error) {