@modusensus/dsh-mneme 0.1.6 → 0.2.0
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/LICENSE +21 -21
- package/README.md +239 -207
- package/cordis.patch.yml +15 -15
- package/lib/api.js +277 -245
- package/lib/client.js +461 -461
- package/lib/commands.js +64 -64
- package/lib/config.js +49 -15
- package/lib/dream/clustering.js +118 -0
- package/lib/dream/decisions.js +128 -121
- package/lib/dream.js +428 -209
- package/lib/embedding.js +97 -97
- package/lib/index.js +176 -120
- package/lib/inject.js +47 -47
- package/lib/local-embedder.js +265 -0
- package/lib/mirror.js +131 -131
- package/lib/reranker.js +203 -0
- package/lib/service.js +268 -174
- package/lib/settings.js +142 -142
- package/lib/store.js +409 -310
- package/lib/summarize.js +171 -171
- package/lib/tools.js +230 -241
- package/lib/vector-index.js +106 -0
- package/package.json +7 -3
- package/src/api.js +277 -245
- package/src/commands.js +64 -64
- package/src/config.js +49 -15
- package/src/dream/clustering.js +118 -0
- package/src/dream/decisions.js +128 -121
- package/src/dream.js +428 -209
- package/src/embedding.js +97 -97
- package/src/index.js +176 -120
- package/src/inject.js +47 -47
- package/src/local-embedder.js +265 -0
- package/src/mirror.js +131 -131
- package/src/reranker.js +203 -0
- package/src/service.js +268 -174
- package/src/settings.js +142 -142
- package/src/store.js +409 -310
- package/src/summarize.js +171 -171
- package/src/tools.js +230 -241
- package/src/vector-index.js +106 -0
package/lib/commands.js
CHANGED
|
@@ -1,64 +1,64 @@
|
|
|
1
|
-
// Custom slash-command manager: keeps the DSH command registry in sync with
|
|
2
|
-
// user-defined commands persisted in SQLite. Commands are registered on boot
|
|
3
|
-
// and (re)registered on add/remove through the API.
|
|
4
|
-
//
|
|
5
|
-
// Each custom command's handler returns the user-authored instruction as a
|
|
6
|
-
// success result; the DSH UI surfaces it as a model-directed instruction.
|
|
7
|
-
export function createCommandManager({ ctx, settings, logger }) {
|
|
8
|
-
const registered = new Map(); // name -> disposer
|
|
9
|
-
|
|
10
|
-
function registerOne(command) {
|
|
11
|
-
if (registered.has(command.name)) return;
|
|
12
|
-
let dispose;
|
|
13
|
-
try {
|
|
14
|
-
dispose = ctx.commands.register({
|
|
15
|
-
name: command.name,
|
|
16
|
-
description: command.description || `自定义指令 ${command.name}`,
|
|
17
|
-
handler: () => ({ kind: "success", text: command.instruction })
|
|
18
|
-
});
|
|
19
|
-
} catch (error) {
|
|
20
|
-
logger?.warn?.(`dsh-mneme: failed to register command /${command.name}: ${String(error)}`);
|
|
21
|
-
return;
|
|
22
|
-
}
|
|
23
|
-
registered.set(command.name, dispose);
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
function unregisterOne(name) {
|
|
27
|
-
const dispose = registered.get(name);
|
|
28
|
-
if (dispose) {
|
|
29
|
-
try {
|
|
30
|
-
dispose();
|
|
31
|
-
} catch {
|
|
32
|
-
/* ignore double-dispose */
|
|
33
|
-
}
|
|
34
|
-
registered.delete(name);
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/** Register every stored command (boot-time sync). */
|
|
39
|
-
function sync() {
|
|
40
|
-
for (const command of settings.listCommands()) registerOne(command);
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
/** Add (or replace) a command and register it live. */
|
|
44
|
-
function add({ name, description, instruction }) {
|
|
45
|
-
const command = settings.addCommand({ name, description, instruction });
|
|
46
|
-
registerOne(command);
|
|
47
|
-
return command;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
/** Remove a command by id and unregister it live. */
|
|
51
|
-
function remove(id) {
|
|
52
|
-
const existing = settings.listCommands().find((c) => c.id === id);
|
|
53
|
-
if (!existing) return false;
|
|
54
|
-
if (!settings.removeCommand(id)) return false;
|
|
55
|
-
unregisterOne(existing.name);
|
|
56
|
-
return true;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
function dispose() {
|
|
60
|
-
for (const name of [...registered.keys()]) unregisterOne(name);
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
return { sync, add, remove, list: () => settings.listCommands(), dispose };
|
|
64
|
-
}
|
|
1
|
+
// Custom slash-command manager: keeps the DSH command registry in sync with
|
|
2
|
+
// user-defined commands persisted in SQLite. Commands are registered on boot
|
|
3
|
+
// and (re)registered on add/remove through the API.
|
|
4
|
+
//
|
|
5
|
+
// Each custom command's handler returns the user-authored instruction as a
|
|
6
|
+
// success result; the DSH UI surfaces it as a model-directed instruction.
|
|
7
|
+
export function createCommandManager({ ctx, settings, logger }) {
|
|
8
|
+
const registered = new Map(); // name -> disposer
|
|
9
|
+
|
|
10
|
+
function registerOne(command) {
|
|
11
|
+
if (registered.has(command.name)) return;
|
|
12
|
+
let dispose;
|
|
13
|
+
try {
|
|
14
|
+
dispose = ctx.commands.register({
|
|
15
|
+
name: command.name,
|
|
16
|
+
description: command.description || `自定义指令 ${command.name}`,
|
|
17
|
+
handler: () => ({ kind: "success", text: command.instruction })
|
|
18
|
+
});
|
|
19
|
+
} catch (error) {
|
|
20
|
+
logger?.warn?.(`dsh-mneme: failed to register command /${command.name}: ${String(error)}`);
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
registered.set(command.name, dispose);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function unregisterOne(name) {
|
|
27
|
+
const dispose = registered.get(name);
|
|
28
|
+
if (dispose) {
|
|
29
|
+
try {
|
|
30
|
+
dispose();
|
|
31
|
+
} catch {
|
|
32
|
+
/* ignore double-dispose */
|
|
33
|
+
}
|
|
34
|
+
registered.delete(name);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Register every stored command (boot-time sync). */
|
|
39
|
+
function sync() {
|
|
40
|
+
for (const command of settings.listCommands()) registerOne(command);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Add (or replace) a command and register it live. */
|
|
44
|
+
function add({ name, description, instruction }) {
|
|
45
|
+
const command = settings.addCommand({ name, description, instruction });
|
|
46
|
+
registerOne(command);
|
|
47
|
+
return command;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Remove a command by id and unregister it live. */
|
|
51
|
+
function remove(id) {
|
|
52
|
+
const existing = settings.listCommands().find((c) => c.id === id);
|
|
53
|
+
if (!existing) return false;
|
|
54
|
+
if (!settings.removeCommand(id)) return false;
|
|
55
|
+
unregisterOne(existing.name);
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function dispose() {
|
|
60
|
+
for (const name of [...registered.keys()]) unregisterOne(name);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return { sync, add, remove, list: () => settings.listCommands(), dispose };
|
|
64
|
+
}
|
package/lib/config.js
CHANGED
|
@@ -1,15 +1,49 @@
|
|
|
1
|
-
import z from "@deepseek-ai/schemastery";
|
|
2
|
-
|
|
3
|
-
export const Config = z.object({
|
|
4
|
-
memoryDir: z.string().default("~/.dsh/memory"),
|
|
5
|
-
autoInject: z.boolean().default(true),
|
|
6
|
-
autoSummarize: z.boolean().default(true),
|
|
7
|
-
maxInjectedItems: z.natural().min(1).max(20).default(5),
|
|
8
|
-
importanceThreshold: z.natural().min(1).max(5).default(3),
|
|
9
|
-
autoDream: z.boolean().default(true),
|
|
10
|
-
dreamThresholdCount: z.natural().min(1).max(1000).default(10),
|
|
11
|
-
dreamThresholdChars: z.natural().min(100).max(100000).default(5000),
|
|
12
|
-
dreamDelayMs: z.natural().min(0).max(60000).default(2000),
|
|
13
|
-
dreamProvider: z.string(),
|
|
14
|
-
dreamModel: z.string()
|
|
15
|
-
|
|
1
|
+
import z from "@deepseek-ai/schemastery";
|
|
2
|
+
|
|
3
|
+
export const Config = z.object({
|
|
4
|
+
memoryDir: z.string().default("~/.dsh/memory"),
|
|
5
|
+
autoInject: z.boolean().default(true),
|
|
6
|
+
autoSummarize: z.boolean().default(true),
|
|
7
|
+
maxInjectedItems: z.natural().min(1).max(20).default(5),
|
|
8
|
+
importanceThreshold: z.natural().min(1).max(5).default(3),
|
|
9
|
+
autoDream: z.boolean().default(true),
|
|
10
|
+
dreamThresholdCount: z.natural().min(1).max(1000).default(10),
|
|
11
|
+
dreamThresholdChars: z.natural().min(100).max(100000).default(5000),
|
|
12
|
+
dreamDelayMs: z.natural().min(0).max(60000).default(2000),
|
|
13
|
+
dreamProvider: z.string(),
|
|
14
|
+
dreamModel: z.string(),
|
|
15
|
+
dreamMaxTokens: z.natural().min(256).max(32768).default(4096),
|
|
16
|
+
|
|
17
|
+
// --- semantic: local embedding provider (v0.2) --------------------------
|
|
18
|
+
// "openai" keeps the legacy external-API path (settings vector config);
|
|
19
|
+
// "local" runs an ONNX model in-process; "ollama" calls a local Ollama.
|
|
20
|
+
embedProvider: z.union([z.const("openai"), z.const("local"), z.const("ollama")]).default("openai"),
|
|
21
|
+
|
|
22
|
+
// Local ONNX embedder (transformers.js / onnxruntime).
|
|
23
|
+
localEmbedModel: z.string().default("Xenova/bge-small-zh-v1.5"),
|
|
24
|
+
localEmbedDimension: z.natural().default(512),
|
|
25
|
+
localEmbedDevice: z.union([z.const("cpu"), z.const("gpu")]).default("cpu"),
|
|
26
|
+
localEmbedBatchSize: z.natural().min(1).max(64).default(8),
|
|
27
|
+
|
|
28
|
+
// Ollama embedder.
|
|
29
|
+
ollamaBaseUrl: z.string().default("http://localhost:11434"),
|
|
30
|
+
ollamaModel: z.string().default("nomic-embed-text"),
|
|
31
|
+
|
|
32
|
+
// Model download/cache.
|
|
33
|
+
embedModelCacheDir: z.string().default(""),
|
|
34
|
+
embedModelMirror: z.string().default("https://hf-mirror.com"),
|
|
35
|
+
|
|
36
|
+
// Vector search tuning.
|
|
37
|
+
vectorSearchTopK: z.natural().min(1).max(100).default(20),
|
|
38
|
+
vectorSearchThreshold: z.number().min(0).max(1).default(0.65),
|
|
39
|
+
hybridSearchVectorWeight: z.number().min(0).max(1).default(0.6),
|
|
40
|
+
hybridSearchKeywordWeight: z.number().min(0).max(1).default(0.4),
|
|
41
|
+
|
|
42
|
+
// --- semantic: rerank layer (v0.2) --------------------------------------
|
|
43
|
+
rerankEnabled: z.boolean().default(true),
|
|
44
|
+
rerankProvider: z.union([z.const("local"), z.const("none")]).default("local"),
|
|
45
|
+
rerankModel: z.string().default("Xenova/bge-reranker-base"),
|
|
46
|
+
rerankBatchSize: z.natural().min(1).max(64).default(8),
|
|
47
|
+
rerankMaxCandidates: z.natural().min(5).max(100).default(30),
|
|
48
|
+
rerankScoreThreshold: z.number().min(0).max(1).default(0.1)
|
|
49
|
+
});
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// Cosine similarity of two equal-length numeric vectors. Returns 0 for empty
|
|
2
|
+
// or mismatched-length inputs, and for zero-norm vectors (numerically stable).
|
|
3
|
+
export function cosineSimilarity(a, b) {
|
|
4
|
+
if (!Array.isArray(a) || !Array.isArray(b) || a.length === 0 || a.length !== b.length) return 0;
|
|
5
|
+
let dot = 0, na = 0, nb = 0;
|
|
6
|
+
for (let i = 0; i < a.length; i++) {
|
|
7
|
+
dot += a[i] * b[i];
|
|
8
|
+
na += a[i] * a[i];
|
|
9
|
+
nb += b[i] * b[i];
|
|
10
|
+
}
|
|
11
|
+
if (na === 0 || nb === 0) return 0;
|
|
12
|
+
return dot / (Math.sqrt(na) * Math.sqrt(nb));
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// K-Means clustering of numeric vectors. Returns one index array per cluster.
|
|
16
|
+
// Uses k-means++ seeding and repairs empty clusters mid-iteration.
|
|
17
|
+
export function kMeans(vectors, k, opts = {}) {
|
|
18
|
+
const n = vectors.length;
|
|
19
|
+
if (n === 0) return [];
|
|
20
|
+
const { maxIter = 100, tol = 1e-4 } = opts ?? {};
|
|
21
|
+
if (k <= 0 || k >= n) return [vectors.map((_, i) => i)];
|
|
22
|
+
|
|
23
|
+
const dim = vectors[0].length;
|
|
24
|
+
const randomIndex = () => Math.floor(Math.random() * n);
|
|
25
|
+
const squaredDist = (v, c) => {
|
|
26
|
+
let s = 0;
|
|
27
|
+
for (let d = 0; d < dim; d++) s += (v[d] - c[d]) * (v[d] - c[d]);
|
|
28
|
+
return s;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
// k-means++ seeding: first centroid uniform-random, later centroids sampled
|
|
32
|
+
// with probability proportional to squared distance from nearest centroid.
|
|
33
|
+
const centroids = [[...vectors[randomIndex()]]];
|
|
34
|
+
while (centroids.length < k) {
|
|
35
|
+
const dist = new Array(n);
|
|
36
|
+
let sum = 0;
|
|
37
|
+
for (let i = 0; i < n; i++) {
|
|
38
|
+
let best = Infinity;
|
|
39
|
+
for (const c of centroids) best = Math.min(best, squaredDist(vectors[i], c));
|
|
40
|
+
dist[i] = best;
|
|
41
|
+
sum += best;
|
|
42
|
+
}
|
|
43
|
+
if (sum === 0) {
|
|
44
|
+
// All points coincide with a centroid; fall back to uniform random.
|
|
45
|
+
centroids.push([...vectors[randomIndex()]]);
|
|
46
|
+
} else {
|
|
47
|
+
let r = Math.random() * sum;
|
|
48
|
+
let pick = 0;
|
|
49
|
+
for (let i = 0; i < n; i++) {
|
|
50
|
+
r -= dist[i];
|
|
51
|
+
if (r <= 0) { pick = i; break; }
|
|
52
|
+
}
|
|
53
|
+
centroids.push([...vectors[pick]]);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const assignment = new Array(n).fill(0);
|
|
58
|
+
for (let iter = 0; iter < maxIter; iter++) {
|
|
59
|
+
// Assign each point to its nearest centroid.
|
|
60
|
+
let changed = false;
|
|
61
|
+
for (let i = 0; i < n; i++) {
|
|
62
|
+
let best = 0, bestD = Infinity;
|
|
63
|
+
for (let j = 0; j < k; j++) {
|
|
64
|
+
const d = squaredDist(vectors[i], centroids[j]);
|
|
65
|
+
if (d < bestD) { bestD = d; best = j; }
|
|
66
|
+
}
|
|
67
|
+
if (assignment[i] !== best) { assignment[i] = best; changed = true; }
|
|
68
|
+
}
|
|
69
|
+
if (!changed) break; // stable assignment => converged.
|
|
70
|
+
|
|
71
|
+
// Recompute centroids as cluster means; reseed empty clusters randomly.
|
|
72
|
+
const sums = Array.from({ length: k }, () => new Array(dim).fill(0));
|
|
73
|
+
const counts = new Array(k).fill(0);
|
|
74
|
+
for (let i = 0; i < n; i++) {
|
|
75
|
+
counts[assignment[i]]++;
|
|
76
|
+
for (let d = 0; d < dim; d++) sums[assignment[i]][d] += vectors[i][d];
|
|
77
|
+
}
|
|
78
|
+
let maxMove = 0;
|
|
79
|
+
for (let j = 0; j < k; j++) {
|
|
80
|
+
if (counts[j] === 0) {
|
|
81
|
+
centroids[j] = [...vectors[randomIndex()]];
|
|
82
|
+
maxMove = Infinity; // never call this converged this round.
|
|
83
|
+
} else {
|
|
84
|
+
for (let d = 0; d < dim; d++) {
|
|
85
|
+
const mean = sums[j][d] / counts[j];
|
|
86
|
+
const move = mean - centroids[j][d];
|
|
87
|
+
if (move * move > maxMove) maxMove = move * move;
|
|
88
|
+
centroids[j][d] = mean;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (Math.sqrt(maxMove) < tol) break; // centroids moved less than tol.
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Build clusters from final assignments.
|
|
96
|
+
const clusters = Array.from({ length: k }, () => []);
|
|
97
|
+
for (let i = 0; i < n; i++) clusters[assignment[i]].push(i);
|
|
98
|
+
return clusters;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Group memories by vector clustering, preserving original object references.
|
|
102
|
+
export function clusterMemories(memories, vectors, k) {
|
|
103
|
+
return kMeans(vectors, k).map((indices) => indices.map((i) => memories[i]));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Find memory pairs that are highly similar yet could contradict each other.
|
|
107
|
+
// Only same-type pairs count; each pair reported once, lower index first.
|
|
108
|
+
export function findPotentialConflicts(memories, vectors, threshold = 0.85) {
|
|
109
|
+
const pairs = [];
|
|
110
|
+
for (let i = 0; i < memories.length; i++) {
|
|
111
|
+
for (let j = i + 1; j < memories.length; j++) {
|
|
112
|
+
if (memories[i].type !== memories[j].type) continue;
|
|
113
|
+
const sim = cosineSimilarity(vectors[i], vectors[j]);
|
|
114
|
+
if (sim > threshold) pairs.push({ a: memories[i], b: memories[j], similarity: sim });
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return pairs;
|
|
118
|
+
}
|
package/lib/dream/decisions.js
CHANGED
|
@@ -1,121 +1,128 @@
|
|
|
1
|
-
const ACTIONS = new Set(["keep", "merge", "archive", "conflict"]);
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Validate a dream decision list against a snapshot of eligible memories.
|
|
5
|
-
* @param decisions - LLM-produced decision list.
|
|
6
|
-
* @param snapshot - Map<id, memory> of eligible (non-archived, non-summary) entries.
|
|
7
|
-
* @returns {{ok: boolean, errors: string[]}}
|
|
8
|
-
*/
|
|
9
|
-
export function validateDecisions(decisions, snapshot) {
|
|
10
|
-
const errors = [];
|
|
11
|
-
if (!Array.isArray(decisions) || decisions.length === 0) {
|
|
12
|
-
return { ok: false, errors: ["decision list must be a non-empty array"] };
|
|
13
|
-
}
|
|
14
|
-
const claimed = new Set();
|
|
15
|
-
for (const [index, d] of decisions.entries()) {
|
|
16
|
-
const at = `decision[${index}]`;
|
|
17
|
-
if (!d || typeof d !== "object" || !ACTIONS.has(d.action)) {
|
|
18
|
-
errors.push(`${at}: invalid action ${JSON.stringify(d?.action)}`);
|
|
19
|
-
continue;
|
|
20
|
-
}
|
|
21
|
-
const ids = d.action === "conflict" ? [d.winner, d.loser] : (d.ids ?? []);
|
|
22
|
-
if (d.action === "conflict") {
|
|
23
|
-
if (!d.winner || !d.loser || d.winner === d.loser) {
|
|
24
|
-
errors.push(`${at}: conflict needs distinct winner and loser`);
|
|
25
|
-
continue;
|
|
26
|
-
}
|
|
27
|
-
} else if (!Array.isArray(d.ids) || d.ids.length === 0) {
|
|
28
|
-
errors.push(`${at}: ${d.action} needs non-empty ids`);
|
|
29
|
-
continue;
|
|
30
|
-
}
|
|
31
|
-
for (const id of ids) {
|
|
32
|
-
const mem = snapshot.get(id);
|
|
33
|
-
if (!mem) {
|
|
34
|
-
errors.push(`${at}: unknown id ${JSON.stringify(id)}`);
|
|
35
|
-
} else if (mem.archived || mem.type === "summary") {
|
|
36
|
-
errors.push(`${at}: id ${JSON.stringify(id)} is archived or summary (not eligible)`);
|
|
37
|
-
}
|
|
38
|
-
if (claimed.has(id)) {
|
|
39
|
-
errors.push(`${at}: id ${JSON.stringify(id)} claimed by multiple decisions`);
|
|
40
|
-
}
|
|
41
|
-
claimed.add(id);
|
|
42
|
-
}
|
|
43
|
-
if (d.action === "merge") {
|
|
44
|
-
if (!d.keepSource || !d.ids.includes(d.keepSource)) {
|
|
45
|
-
errors.push(`${at}: merge keepSource must be one of ids`);
|
|
46
|
-
}
|
|
47
|
-
if (typeof d.title !== "string" || !d.title.trim() || typeof d.content !== "string" || !d.content.trim()) {
|
|
48
|
-
errors.push(`${at}: merge needs non-empty title and content`);
|
|
49
|
-
}
|
|
50
|
-
if (d.importance !== undefined && (!Number.isInteger(d.importance) || d.importance < 1 || d.importance > 5)) {
|
|
51
|
-
errors.push(`${at}: merge importance must be an integer 1-5 when provided`);
|
|
52
|
-
}
|
|
53
|
-
// Merging across types would blur preference/project/decision boundaries
|
|
54
|
-
// in the injected context; the snapshot carries each entry's type.
|
|
55
|
-
const mergeTypes = new Set(d.ids.map((id) => snapshot.get(id)?.type));
|
|
56
|
-
if (mergeTypes.size > 1) {
|
|
57
|
-
errors.push(`${at}: merge ids span multiple types (${[...mergeTypes].join(", ")})`);
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
// Every snapshot id must appear in at least one decision
|
|
62
|
-
for (const id of snapshot.keys()) {
|
|
63
|
-
if (!claimed.has(id)) errors.push(`memory ${JSON.stringify(id)} missing from decisions`);
|
|
64
|
-
}
|
|
65
|
-
return { ok: errors.length === 0, errors };
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* Apply a validated decision list to the service. Caller must validate first.
|
|
70
|
-
*
|
|
71
|
-
* Note: merge is intentionally non-atomic — the keeper is updated before the
|
|
72
|
-
* other sources are archived, so a failure between the two never loses content.
|
|
73
|
-
*
|
|
74
|
-
* @param decisions - validated decision list.
|
|
75
|
-
* @param service - memory service (saveWithDedupe/getById/update/setArchived).
|
|
76
|
-
* @param logger - optional logger ({ warn }); per-decision failures are logged.
|
|
77
|
-
* @returns number of applied decisions (archive counts each archived memory as one).
|
|
78
|
-
*/
|
|
79
|
-
export function applyDecisions(decisions, service, logger = null) {
|
|
80
|
-
let applied = 0;
|
|
81
|
-
for (const [i, d] of decisions.entries()) {
|
|
82
|
-
try {
|
|
83
|
-
if (d.action === "keep") continue;
|
|
84
|
-
if (d.action === "archive") {
|
|
85
|
-
for (const id of d.ids) {
|
|
86
|
-
const mem = service.getById(id);
|
|
87
|
-
if (mem && !mem.archived) { service.setArchived(id, true); applied++; }
|
|
88
|
-
}
|
|
89
|
-
} else if (d.action === "merge") {
|
|
90
|
-
const keeper = service.getById(d.keepSource);
|
|
91
|
-
if (!keeper || keeper.archived) continue;
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
service.
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
}
|
|
1
|
+
const ACTIONS = new Set(["keep", "merge", "archive", "conflict"]);
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Validate a dream decision list against a snapshot of eligible memories.
|
|
5
|
+
* @param decisions - LLM-produced decision list.
|
|
6
|
+
* @param snapshot - Map<id, memory> of eligible (non-archived, non-summary) entries.
|
|
7
|
+
* @returns {{ok: boolean, errors: string[]}}
|
|
8
|
+
*/
|
|
9
|
+
export function validateDecisions(decisions, snapshot) {
|
|
10
|
+
const errors = [];
|
|
11
|
+
if (!Array.isArray(decisions) || decisions.length === 0) {
|
|
12
|
+
return { ok: false, errors: ["decision list must be a non-empty array"] };
|
|
13
|
+
}
|
|
14
|
+
const claimed = new Set();
|
|
15
|
+
for (const [index, d] of decisions.entries()) {
|
|
16
|
+
const at = `decision[${index}]`;
|
|
17
|
+
if (!d || typeof d !== "object" || !ACTIONS.has(d.action)) {
|
|
18
|
+
errors.push(`${at}: invalid action ${JSON.stringify(d?.action)}`);
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
const ids = d.action === "conflict" ? [d.winner, d.loser] : (d.ids ?? []);
|
|
22
|
+
if (d.action === "conflict") {
|
|
23
|
+
if (!d.winner || !d.loser || d.winner === d.loser) {
|
|
24
|
+
errors.push(`${at}: conflict needs distinct winner and loser`);
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
} else if (!Array.isArray(d.ids) || d.ids.length === 0) {
|
|
28
|
+
errors.push(`${at}: ${d.action} needs non-empty ids`);
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
for (const id of ids) {
|
|
32
|
+
const mem = snapshot.get(id);
|
|
33
|
+
if (!mem) {
|
|
34
|
+
errors.push(`${at}: unknown id ${JSON.stringify(id)}`);
|
|
35
|
+
} else if (mem.archived || mem.type === "summary") {
|
|
36
|
+
errors.push(`${at}: id ${JSON.stringify(id)} is archived or summary (not eligible)`);
|
|
37
|
+
}
|
|
38
|
+
if (claimed.has(id)) {
|
|
39
|
+
errors.push(`${at}: id ${JSON.stringify(id)} claimed by multiple decisions`);
|
|
40
|
+
}
|
|
41
|
+
claimed.add(id);
|
|
42
|
+
}
|
|
43
|
+
if (d.action === "merge") {
|
|
44
|
+
if (!d.keepSource || !d.ids.includes(d.keepSource)) {
|
|
45
|
+
errors.push(`${at}: merge keepSource must be one of ids`);
|
|
46
|
+
}
|
|
47
|
+
if (typeof d.title !== "string" || !d.title.trim() || typeof d.content !== "string" || !d.content.trim()) {
|
|
48
|
+
errors.push(`${at}: merge needs non-empty title and content`);
|
|
49
|
+
}
|
|
50
|
+
if (d.importance !== undefined && (!Number.isInteger(d.importance) || d.importance < 1 || d.importance > 5)) {
|
|
51
|
+
errors.push(`${at}: merge importance must be an integer 1-5 when provided`);
|
|
52
|
+
}
|
|
53
|
+
// Merging across types would blur preference/project/decision boundaries
|
|
54
|
+
// in the injected context; the snapshot carries each entry's type.
|
|
55
|
+
const mergeTypes = new Set(d.ids.map((id) => snapshot.get(id)?.type));
|
|
56
|
+
if (mergeTypes.size > 1) {
|
|
57
|
+
errors.push(`${at}: merge ids span multiple types (${[...mergeTypes].join(", ")})`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
// Every snapshot id must appear in at least one decision
|
|
62
|
+
for (const id of snapshot.keys()) {
|
|
63
|
+
if (!claimed.has(id)) errors.push(`memory ${JSON.stringify(id)} missing from decisions`);
|
|
64
|
+
}
|
|
65
|
+
return { ok: errors.length === 0, errors };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Apply a validated decision list to the service. Caller must validate first.
|
|
70
|
+
*
|
|
71
|
+
* Note: merge is intentionally non-atomic — the keeper is updated before the
|
|
72
|
+
* other sources are archived, so a failure between the two never loses content.
|
|
73
|
+
*
|
|
74
|
+
* @param decisions - validated decision list.
|
|
75
|
+
* @param service - memory service (saveWithDedupe/getById/update/setArchived).
|
|
76
|
+
* @param logger - optional logger ({ warn }); per-decision failures are logged.
|
|
77
|
+
* @returns number of applied decisions (archive counts each archived memory as one).
|
|
78
|
+
*/
|
|
79
|
+
export function applyDecisions(decisions, service, logger = null) {
|
|
80
|
+
let applied = 0;
|
|
81
|
+
for (const [i, d] of decisions.entries()) {
|
|
82
|
+
try {
|
|
83
|
+
if (d.action === "keep") continue;
|
|
84
|
+
if (d.action === "archive") {
|
|
85
|
+
for (const id of d.ids) {
|
|
86
|
+
const mem = service.getById(id);
|
|
87
|
+
if (mem && !mem.archived) { service.setArchived(id, true); applied++; }
|
|
88
|
+
}
|
|
89
|
+
} else if (d.action === "merge") {
|
|
90
|
+
const keeper = service.getById(d.keepSource);
|
|
91
|
+
if (!keeper || keeper.archived) continue;
|
|
92
|
+
const sources = d.ids.filter((id) => id !== d.keepSource);
|
|
93
|
+
// Idempotent replay: if every other source is already archived, this
|
|
94
|
+
// merge already landed — skip so a replayed/concurrent decision never
|
|
95
|
+
// double-counts or re-applies (guard against duplicate merges).
|
|
96
|
+
if (sources.every((id) => service.getById(id)?.archived)) continue;
|
|
97
|
+
service.update(d.keepSource, {
|
|
98
|
+
title: d.title,
|
|
99
|
+
content: d.content,
|
|
100
|
+
importance: d.importance ?? Math.max(keeper.importance, ...d.ids.map((id) => service.getById(id)?.importance ?? 1))
|
|
101
|
+
});
|
|
102
|
+
for (const id of sources) {
|
|
103
|
+
const mem = service.getById(id);
|
|
104
|
+
if (mem && !mem.archived) { service.setArchived(id, true); }
|
|
105
|
+
}
|
|
106
|
+
applied++;
|
|
107
|
+
} else if (d.action === "conflict") {
|
|
108
|
+
const winner = service.getById(d.winner);
|
|
109
|
+
const loser = service.getById(d.loser);
|
|
110
|
+
if (!winner || !loser) continue;
|
|
111
|
+
// Idempotent replay: an already-archived loser means the conflict was
|
|
112
|
+
// already adjudicated — skip so the provenance note is never
|
|
113
|
+
// re-appended and the loser is not re-archived.
|
|
114
|
+
if (loser.archived) continue;
|
|
115
|
+
service.update(d.winner, {
|
|
116
|
+
content: `${winner.content}\n\n(已否决旧信息:${[...loser.content].slice(0, 100).join("")})`
|
|
117
|
+
});
|
|
118
|
+
service.setArchived(d.loser, true);
|
|
119
|
+
applied++;
|
|
120
|
+
}
|
|
121
|
+
} catch (error) {
|
|
122
|
+
// Skip individual bad decision; never corrupt the store. The optional
|
|
123
|
+
// logger makes the failure visible instead of failing silently.
|
|
124
|
+
logger?.warn?.(`dsh-mneme dream: failed to apply ${d.action} at index ${i}: ${error.message}`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return applied;
|
|
128
|
+
}
|