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