@modusensus/dsh-mneme 0.4.1 → 0.4.2
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 +28 -7
- package/lib/api.js +1 -1
- package/lib/config.js +39 -24
- package/lib/dream/decisions.js +33 -63
- package/lib/{sleep.js → dream/sleep.js} +118 -29
- package/lib/index.js +9 -12
- package/lib/mirror.js +24 -12
- package/lib/service.js +115 -49
- package/lib/store.js +144 -75
- package/lib/summarize.js +6 -3
- package/package.json +3 -3
- package/scripts/e2e-dsh.js +4 -2
- package/src/api.js +1 -1
- package/src/config.js +39 -24
- package/src/dream/decisions.js +33 -63
- package/src/{sleep.js → dream/sleep.js} +118 -29
- package/src/index.js +9 -12
- package/src/mirror.js +24 -12
- package/src/service.js +115 -49
- package/src/store.js +144 -75
- package/src/summarize.js +6 -3
- package/test/mirror-generation.test.js +34 -1
- package/test/peer-blockers.test.js +42 -0
- package/test/sleep.test.js +297 -333
- package/test/summarize.test.js +35 -0
package/test/sleep.test.js
CHANGED
|
@@ -1,401 +1,365 @@
|
|
|
1
1
|
import test from "node:test";
|
|
2
2
|
import assert from "node:assert/strict";
|
|
3
|
+
import { createSleepScheduler, runSleep } from "../src/dream/sleep.js";
|
|
3
4
|
import { createStore } from "../src/store.js";
|
|
4
5
|
import { createService } from "../src/service.js";
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
/** Dummy embedder/vector index: every text maps to the same vector, so any two
|
|
22
|
-
* same-type memories score cosine 1.0 and become conflict candidates. */
|
|
23
|
-
function fakeSemantic() {
|
|
24
|
-
return {
|
|
25
|
-
embedder: {
|
|
26
|
-
embed: async (texts) => texts.map(() => [1, 0, 0])
|
|
27
|
-
},
|
|
28
|
-
vectorIndex: {
|
|
29
|
-
getEmbedding: () => null,
|
|
30
|
-
saveEmbedding: () => {},
|
|
31
|
-
search: () => []
|
|
32
|
-
}
|
|
33
|
-
};
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
/** Deterministic sleep LLM stub: conflict prompt (user text contains 候选冲突)
|
|
37
|
-
* routes to onConflict, everything else to onPattern. */
|
|
38
|
-
function sleepCtx({ onConflict = () => "[]", onPattern = () => "[]" } = {}) {
|
|
6
|
+
import { createVectorIndex } from "../src/vector-index.js";
|
|
7
|
+
|
|
8
|
+
// Mock embedder: every query maps to [1,0,0] so vectors are identical unless a
|
|
9
|
+
// test pre-seeds a custom vector via vectorIndex.saveEmbedding.
|
|
10
|
+
const embedder = {
|
|
11
|
+
embedSingle: async () => [1, 0, 0],
|
|
12
|
+
embed: async () => [1, 0, 0],
|
|
13
|
+
schedule: () => {},
|
|
14
|
+
modelHash: "mock#1",
|
|
15
|
+
dimension: 3
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
// Deterministic LLM: onConsolidation(userText) => decisions JSON string.
|
|
19
|
+
function mockCtx(onConsolidation, selection = { provider: "mock", model: "sleep-model" }) {
|
|
39
20
|
return {
|
|
40
21
|
logger: { warn: () => {}, info: () => {} },
|
|
41
|
-
agentDefaultModel: { currentSelection: () =>
|
|
22
|
+
agentDefaultModel: { currentSelection: () => selection },
|
|
42
23
|
llm: {
|
|
43
24
|
async *stream(options) {
|
|
44
25
|
const userText = options.messages.find((m) => m.role === "user")?.content?.[0]?.text ?? "";
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
index: 0,
|
|
48
|
-
text: userText.includes("候选冲突") ? onConflict(userText) : onPattern(userText)
|
|
49
|
-
};
|
|
26
|
+
const reply = onConsolidation ? onConsolidation(userText) : "[]";
|
|
27
|
+
yield { type: "text-delta", index: 0, text: reply };
|
|
50
28
|
yield { type: "finish", reason: { kind: "stop" } };
|
|
51
29
|
}
|
|
52
30
|
}
|
|
53
31
|
};
|
|
54
32
|
}
|
|
55
33
|
|
|
34
|
+
function baseConfig(overrides = {}) {
|
|
35
|
+
return {
|
|
36
|
+
sleepModeEnabled: true,
|
|
37
|
+
sleepIdleMinutes: 5,
|
|
38
|
+
sleepMinIntervalHours: 8,
|
|
39
|
+
sleepConflictStrictness: "normal",
|
|
40
|
+
sleepArchiveDays: 30,
|
|
41
|
+
sleepCompressDays: 90,
|
|
42
|
+
sleepPatternMinMemories: 100,
|
|
43
|
+
sleepMaxPatternPerRun: 3,
|
|
44
|
+
...overrides
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function setup() {
|
|
49
|
+
const store = createStore(":memory:");
|
|
50
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
51
|
+
const vectorIndex = createVectorIndex({ store });
|
|
52
|
+
service.setEmbedder(embedder);
|
|
53
|
+
service.setVectorIndex(vectorIndex);
|
|
54
|
+
return { store, service, vectorIndex };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function makeMemory(service, title, content, type = "project") {
|
|
58
|
+
return service.saveWithDedupe({ type, title, content, importance: 3 }).memory;
|
|
59
|
+
}
|
|
60
|
+
|
|
56
61
|
// ------------------------------------------------------------ scheduler
|
|
57
62
|
|
|
58
|
-
test("scheduler
|
|
59
|
-
const { service } = setup();
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
config: { sleepEnabled: true, sleepIdleMinutes: 30, sleepMinIntervalHours: 8 },
|
|
65
|
-
onRun: async () => { runs++; return { ok: true }; },
|
|
66
|
-
now: () => t
|
|
63
|
+
test("sleep: scheduler does not run when disabled", () => {
|
|
64
|
+
const { service, store } = setup();
|
|
65
|
+
const sched = createSleepScheduler({
|
|
66
|
+
service, config: baseConfig({ sleepModeEnabled: false }), logger: { warn: () => {} },
|
|
67
|
+
onRun: async () => ({ ok: true }),
|
|
68
|
+
now: () => 1_000_000, setTimeoutFn: () => 1, clearTimeoutFn: () => {}
|
|
67
69
|
});
|
|
68
|
-
assert.equal(
|
|
69
|
-
|
|
70
|
-
assert.equal(sleep.shouldRun(t), true, "idle met + no prior run → runnable");
|
|
71
|
-
assert.equal(await sleep.maybeSchedule(), true);
|
|
72
|
-
assert.equal(runs, 1);
|
|
73
|
-
assert.equal(sleep.shouldRun(t), false, "interval gate: just ran");
|
|
74
|
-
assert.equal(await sleep.maybeSchedule(), false);
|
|
75
|
-
t += 8 * 3600000 + 1; // interval satisfied
|
|
76
|
-
assert.equal(sleep.shouldRun(t), true, "interval passed → runnable again");
|
|
70
|
+
assert.equal(sched.shouldRun(1_000_000 + 60 * 60000), false, "disabled never schedules");
|
|
71
|
+
store.close();
|
|
77
72
|
});
|
|
78
73
|
|
|
79
|
-
test("
|
|
80
|
-
const { service } = setup();
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
const timers = [];
|
|
84
|
-
const sleep = createSleepScheduler({
|
|
85
|
-
service,
|
|
86
|
-
config: { sleepEnabled: true, sleepIdleMinutes: 30, sleepMinIntervalHours: 8 },
|
|
74
|
+
test("sleep: scheduler fires once idle window elapses", () => {
|
|
75
|
+
const { service, store } = setup();
|
|
76
|
+
const sched = createSleepScheduler({
|
|
77
|
+
service, config: baseConfig(), logger: { warn: () => {} },
|
|
87
78
|
onRun: async () => ({ ok: true }),
|
|
88
|
-
now: () =>
|
|
89
|
-
setTimeoutFn: (fn, ms) => { timers.push({ fn, ms }); return timers.length; },
|
|
90
|
-
clearTimeoutFn: () => { cleared++; }
|
|
79
|
+
now: () => 1_000_000, setTimeoutFn: () => 1, clearTimeoutFn: () => {}
|
|
91
80
|
});
|
|
92
|
-
|
|
93
|
-
assert.equal(
|
|
94
|
-
|
|
95
|
-
t += 5 * 60000;
|
|
96
|
-
sleep.noteWrite();
|
|
97
|
-
assert.equal(cleared, 1, "stale timer cleared, not left to fire early");
|
|
98
|
-
assert.equal(timers.length, 2, "fresh timer armed on the write");
|
|
99
|
-
assert.equal(timers[1].ms, 30 * 60000 + 1000, "re-armed against a full idle window from the write");
|
|
81
|
+
assert.equal(sched.shouldRun(1_000_000 + 4 * 60000), false, "still within idle window");
|
|
82
|
+
assert.equal(sched.shouldRun(1_000_000 + 6 * 60000), true, "idle window elapsed");
|
|
83
|
+
store.close();
|
|
100
84
|
});
|
|
101
85
|
|
|
102
|
-
test("
|
|
103
|
-
const { service } = setup();
|
|
104
|
-
let
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
onRun: async () => { runs++; return { ok: true }; },
|
|
110
|
-
now: () => t
|
|
86
|
+
test("sleep: noteWrite resets the idle clock (stale-timer guard)", () => {
|
|
87
|
+
const { service, store } = setup();
|
|
88
|
+
let now = 1_000_000;
|
|
89
|
+
const sched = createSleepScheduler({
|
|
90
|
+
service, config: baseConfig(), logger: { warn: () => {} },
|
|
91
|
+
onRun: async () => ({ ok: true }),
|
|
92
|
+
now: () => now, setTimeoutFn: () => 1, clearTimeoutFn: () => {}
|
|
111
93
|
});
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
94
|
+
assert.equal(sched.shouldRun(now + 6 * 60000), true, "idle after 6min");
|
|
95
|
+
now = 1_000_000 + 6 * 60000;
|
|
96
|
+
sched.noteWrite();
|
|
97
|
+
assert.equal(sched.shouldRun(now), false, "write resets idle clock");
|
|
98
|
+
assert.equal(sched.shouldRun(now + 4 * 60000), false, "still idle-pending after reset");
|
|
99
|
+
assert.equal(sched.shouldRun(now + 6 * 60000), true, "idle again after fresh window");
|
|
100
|
+
store.close();
|
|
115
101
|
});
|
|
116
102
|
|
|
117
|
-
test("
|
|
118
|
-
const { service } = setup();
|
|
119
|
-
const
|
|
120
|
-
service,
|
|
121
|
-
config: { sleepEnabled: false, sleepIdleMinutes: 0, sleepMinIntervalHours: 0 },
|
|
103
|
+
test("sleep: first-ever run is not blocked by min interval (lastRunAt=0)", () => {
|
|
104
|
+
const { service, store } = setup();
|
|
105
|
+
const sched = createSleepScheduler({
|
|
106
|
+
service, config: baseConfig(), logger: { warn: () => {} },
|
|
122
107
|
onRun: async () => ({ ok: true }),
|
|
123
|
-
now: () => 1_000_000
|
|
108
|
+
now: () => 1_000_000, setTimeoutFn: () => 1, clearTimeoutFn: () => {}
|
|
124
109
|
});
|
|
125
|
-
assert.equal(
|
|
110
|
+
assert.equal(sched.shouldRun(1_000_000 + 6 * 60000), true, "first run allowed");
|
|
111
|
+
store.close();
|
|
126
112
|
});
|
|
127
113
|
|
|
128
|
-
test("
|
|
129
|
-
const { service } = setup();
|
|
130
|
-
let
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
onRun: async () => { calls++; if (calls === 1) throw new Error("boom"); return { ok: true }; },
|
|
136
|
-
now: () => t
|
|
114
|
+
test("sleep: min interval blocks a re-run within the window, allows after", async () => {
|
|
115
|
+
const { service, store } = setup();
|
|
116
|
+
let now = 1_000_000;
|
|
117
|
+
const sched = createSleepScheduler({
|
|
118
|
+
service, config: baseConfig(), logger: { warn: () => {} },
|
|
119
|
+
onRun: async () => ({ ok: true }),
|
|
120
|
+
now: () => now, setTimeoutFn: () => 1, clearTimeoutFn: () => {}
|
|
137
121
|
});
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
assert.equal(
|
|
141
|
-
|
|
142
|
-
assert.equal(
|
|
143
|
-
|
|
122
|
+
now = 1_000_000 + 6 * 60000; // idle satisfied
|
|
123
|
+
const ok = await sched.maybeSchedule();
|
|
124
|
+
assert.equal(ok, true, "first run executed");
|
|
125
|
+
assert.equal(sched.shouldRun(now + 1 * 3600000), false, "1h later still inside 8h min interval");
|
|
126
|
+
assert.equal(sched.shouldRun(now + 9 * 3600000), true, "9h later past min interval → allowed");
|
|
127
|
+
store.close();
|
|
144
128
|
});
|
|
145
129
|
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
const
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
const
|
|
158
|
-
const
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
assert.
|
|
163
|
-
|
|
164
|
-
assert.equal(store.getById(b.id).archived, true);
|
|
165
|
-
assert.equal(store.getById(c.id).archived, false);
|
|
166
|
-
assert.equal(store.getById(c.id)._full_content, undefined);
|
|
130
|
+
test("sleep: maybeSchedule enqueues via service and serializes with other work", async () => {
|
|
131
|
+
const { service, store } = setup();
|
|
132
|
+
const config = baseConfig();
|
|
133
|
+
let now = 1_000_000;
|
|
134
|
+
let order = [];
|
|
135
|
+
const sched = createSleepScheduler({
|
|
136
|
+
service, config, logger: { warn: () => {} },
|
|
137
|
+
onRun: async () => { order.push("sleep"); return { ok: true, applied: 7 }; },
|
|
138
|
+
now: () => now, setTimeoutFn: () => 1, clearTimeoutFn: () => {}
|
|
139
|
+
});
|
|
140
|
+
now = 1_000_000 + 6 * 60000;
|
|
141
|
+
const p1 = service.enqueue(async () => { order.push("a"); });
|
|
142
|
+
const p2 = sched.maybeSchedule();
|
|
143
|
+
await p1;
|
|
144
|
+
const result = await p2;
|
|
145
|
+
assert.equal(result, true, "run result propagated through enqueue");
|
|
146
|
+
assert.deepEqual(order, ["a", "sleep"], "sleep run serialized behind queued work");
|
|
147
|
+
store.close();
|
|
167
148
|
});
|
|
168
149
|
|
|
169
|
-
test("
|
|
170
|
-
const store =
|
|
171
|
-
|
|
172
|
-
const
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
assert.
|
|
181
|
-
|
|
150
|
+
test("sleep: dispose clears the timer and prevents further runs", async () => {
|
|
151
|
+
const { service, store } = setup();
|
|
152
|
+
let cleared = false;
|
|
153
|
+
const sched = createSleepScheduler({
|
|
154
|
+
service, config: baseConfig(), logger: { warn: () => {} },
|
|
155
|
+
onRun: async () => ({ ok: true }),
|
|
156
|
+
now: () => 1_000_000,
|
|
157
|
+
setTimeoutFn: () => 1,
|
|
158
|
+
clearTimeoutFn: () => { cleared = true; }
|
|
159
|
+
});
|
|
160
|
+
sched.noteWrite(); // arm the idle timer so dispose has something to clear
|
|
161
|
+
assert.equal(cleared, false, "timer armed, not yet cleared");
|
|
162
|
+
await sched.dispose();
|
|
163
|
+
assert.equal(cleared, true, "idle timer cleared on dispose");
|
|
164
|
+
assert.equal(sched.shouldRun(1_000_000 + 6 * 60000), false, "disposed never runs");
|
|
165
|
+
store.close();
|
|
182
166
|
});
|
|
183
167
|
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
const
|
|
189
|
-
const
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
const
|
|
193
|
-
const
|
|
194
|
-
assert.equal(
|
|
195
|
-
assert.
|
|
196
|
-
assert.
|
|
197
|
-
assert.equal(
|
|
168
|
+
// ------------------------------------------------------------ runSleep phases
|
|
169
|
+
|
|
170
|
+
test("sleep: demotion shrinks cold memory to summary, keeps _full_content", async () => {
|
|
171
|
+
const { service, store } = setup();
|
|
172
|
+
const now = Date.now();
|
|
173
|
+
const m = makeMemory(service, "cold", "原内容".repeat(60), "project");
|
|
174
|
+
service.touchLastAccess(m.id, new Date(now - 40 * 86400000).toISOString());
|
|
175
|
+
const ctx = mockCtx(() => "[]");
|
|
176
|
+
const result = await runSleep(ctx, service, baseConfig(), ctx.logger, null, null);
|
|
177
|
+
const after = service.getById(m.id);
|
|
178
|
+
assert.equal(result.status, "ok");
|
|
179
|
+
assert.ok(after._full_content && after._full_content.length > 0, "full body preserved");
|
|
180
|
+
assert.ok(after.content.length < "原内容".repeat(60).length, "content shrank to summary");
|
|
181
|
+
assert.equal(after.archived, false, "not fully archived at 40 days");
|
|
182
|
+
store.close();
|
|
198
183
|
});
|
|
199
184
|
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
const
|
|
204
|
-
|
|
205
|
-
const
|
|
206
|
-
const
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
{ action: "create", type: "pattern", title: "中文偏好", content: "用户偏好中文内容", importance: 3, evidence: [m1.id] }
|
|
212
|
-
]);
|
|
213
|
-
}
|
|
214
|
-
});
|
|
215
|
-
const result = await runSleep(ctx, service, { sleepEnabled: true, sleepMaxPatterns: 5, policyEpoch: 1 }, ctx.logger);
|
|
216
|
-
assert.equal(result.phases.patterns.status, "ok");
|
|
217
|
-
assert.equal(result.phases.patterns.applied, 1);
|
|
218
|
-
const patterns = store.list({ type: "pattern" });
|
|
219
|
-
assert.equal(patterns.length, 1);
|
|
220
|
-
assert.equal(patterns[0].title, "中文偏好");
|
|
221
|
-
assert.ok(patterns[0].tags.includes(`ev:${m1.id}`), "evidence ref stored as tag");
|
|
222
|
-
// sleep run is audited with run_type=sleep
|
|
223
|
-
const runs = store.listDreamRuns();
|
|
224
|
-
assert.ok(runs.some((r) => r.run_type === "sleep" && r.status === "ok"), "sleep audit row written");
|
|
185
|
+
test("sleep: demotion fully archives memory past sleepCompressDays", async () => {
|
|
186
|
+
const { service, store } = setup();
|
|
187
|
+
const now = Date.now();
|
|
188
|
+
const m = makeMemory(service, "ancient", "很老的记忆", "project");
|
|
189
|
+
service.touchLastAccess(m.id, new Date(now - 100 * 86400000).toISOString());
|
|
190
|
+
const ctx = mockCtx(() => "[]");
|
|
191
|
+
const result = await runSleep(ctx, service, baseConfig(), ctx.logger, null, null);
|
|
192
|
+
const after = service.getById(m.id);
|
|
193
|
+
assert.equal(result.status, "ok");
|
|
194
|
+
assert.equal(after.archived, true, "past compress days → archived");
|
|
195
|
+
store.close();
|
|
225
196
|
});
|
|
226
197
|
|
|
227
|
-
test("
|
|
228
|
-
const {
|
|
229
|
-
const
|
|
230
|
-
const
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
assert.equal(
|
|
236
|
-
assert.equal(
|
|
237
|
-
|
|
198
|
+
test("sleep: demoteToSummary minRefTimeMs skips a memory touched after snapshot", () => {
|
|
199
|
+
const { service, store } = setup();
|
|
200
|
+
const now = Date.now();
|
|
201
|
+
const m = makeMemory(service, "touched", "内容".repeat(60), "project");
|
|
202
|
+
service.touchLastAccess(m.id, new Date(now - 40 * 86400000).toISOString());
|
|
203
|
+
const snapshotCut = now - 1 * 86400000;
|
|
204
|
+
service.touchLastAccess(m.id, new Date(snapshotCut + 60000).toISOString());
|
|
205
|
+
const updated = service.demoteToSummary(m.id, "摘要", { minRefTimeMs: snapshotCut });
|
|
206
|
+
assert.equal(updated, undefined, "touched-after-snapshot memory is not demoted");
|
|
207
|
+
assert.equal(service.getById(m.id)._full_content ?? null, null, "no demotion happened");
|
|
208
|
+
store.close();
|
|
238
209
|
});
|
|
239
210
|
|
|
240
|
-
test("
|
|
241
|
-
const {
|
|
242
|
-
const
|
|
243
|
-
const
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
assert.equal(result.phases.patterns.status, "ok");
|
|
250
|
-
const patterns = store.list({ type: "pattern" });
|
|
251
|
-
assert.equal(patterns.length, 1);
|
|
252
|
-
assert.ok(patterns[0].tags.includes(`ev:${m1.id}`), "real evidence kept");
|
|
253
|
-
assert.ok(!patterns[0].tags.some((t) => t === "ev:made-up-id-123"), "fabricated evidence dropped");
|
|
211
|
+
test("sleep: demotion demotes a memory still cold after snapshot", () => {
|
|
212
|
+
const { service, store } = setup();
|
|
213
|
+
const now = Date.now();
|
|
214
|
+
const m = makeMemory(service, "stillcold", "内容".repeat(60), "project");
|
|
215
|
+
service.touchLastAccess(m.id, new Date(now - 40 * 86400000).toISOString());
|
|
216
|
+
const snapshotCut = now - 1 * 86400000;
|
|
217
|
+
const updated = service.demoteToSummary(m.id, "摘要", { minRefTimeMs: snapshotCut });
|
|
218
|
+
assert.ok(updated && updated._full_content, "cold memory demoted to summary");
|
|
219
|
+
store.close();
|
|
254
220
|
});
|
|
255
221
|
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
const
|
|
260
|
-
const
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
assert.
|
|
267
|
-
|
|
268
|
-
assert.
|
|
222
|
+
test("sleep: pattern discovery filters fabricated evidence ids", async () => {
|
|
223
|
+
const { service, store } = setup();
|
|
224
|
+
const a = makeMemory(service, "模式A", "反复出现的模式A", "project");
|
|
225
|
+
const b = makeMemory(service, "模式B", "反复出现的模式B", "project");
|
|
226
|
+
const ctx = mockCtx(() =>
|
|
227
|
+
JSON.stringify([
|
|
228
|
+
{ action: "create", type: "pattern", title: "真模式", content: "从 a 和 b 提取", importance: 3, evidence: [a.id, "fake-zzz", b.id] }
|
|
229
|
+
])
|
|
230
|
+
);
|
|
231
|
+
const result = await runSleep(ctx, service, baseConfig({ sleepPatternMinMemories: 10 }), ctx.logger, null, null);
|
|
232
|
+
assert.ok(!JSON.stringify(result.phases.patterns).includes("fake-zzz"), "fabricated evidence filtered before apply");
|
|
233
|
+
const pattern = service.all().find((x) => x.type === "pattern");
|
|
234
|
+
assert.ok(pattern, "pattern minted");
|
|
235
|
+
store.close();
|
|
269
236
|
});
|
|
270
237
|
|
|
271
|
-
test("
|
|
272
|
-
const {
|
|
273
|
-
const
|
|
274
|
-
const
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
assert.
|
|
281
|
-
assert.
|
|
282
|
-
|
|
238
|
+
test("sleep: relation completion links orphan entities co-occurring in a memory", async () => {
|
|
239
|
+
const { service, store } = setup();
|
|
240
|
+
const alpha = service.createEntity({ name: "Alpha", type: "project" });
|
|
241
|
+
const beta = service.createEntity({ name: "Beta", type: "project" });
|
|
242
|
+
makeMemory(service, "协作", "Alpha 与 Beta 一起干活", "project");
|
|
243
|
+
const ctx = mockCtx(() => "[]");
|
|
244
|
+
const result = await runSleep(ctx, service, baseConfig(), ctx.logger, null, null);
|
|
245
|
+
assert.equal(result.phases.relations.status, "ok", "relations phase ran");
|
|
246
|
+
const rels = service.getRelations(alpha.id);
|
|
247
|
+
assert.ok(rels.length >= 1, "orphan Alpha gained a relation");
|
|
248
|
+
assert.ok(rels.some((r) => r.to_entity === beta.id || r.from_entity === beta.id), "relation targets Beta");
|
|
249
|
+
store.close();
|
|
283
250
|
});
|
|
284
251
|
|
|
285
|
-
test("
|
|
286
|
-
const { service } = setup();
|
|
287
|
-
const
|
|
288
|
-
const
|
|
289
|
-
|
|
290
|
-
const
|
|
291
|
-
|
|
252
|
+
test("sleep: runSleep writes an audit receipt with run_type='sleep'", async () => {
|
|
253
|
+
const { service, store } = setup();
|
|
254
|
+
const now = Date.now();
|
|
255
|
+
const m = makeMemory(service, "cold", "内容".repeat(60), "project");
|
|
256
|
+
service.touchLastAccess(m.id, new Date(now - 40 * 86400000).toISOString());
|
|
257
|
+
const ctx = mockCtx(() => "[]");
|
|
258
|
+
const result = await runSleep(ctx, service, baseConfig(), ctx.logger, null, null);
|
|
259
|
+
const runs = service.listDreamRuns();
|
|
260
|
+
const last = runs[runs.length - 1];
|
|
261
|
+
assert.equal(last.run_type, "sleep", "audit row tagged sleep");
|
|
262
|
+
assert.equal(result.runId, last.id, "run id matches audit row");
|
|
263
|
+
assert.ok(typeof result.receipt === "string" && result.receipt.startsWith("dsh-mneme:run:"), "receipt is the audit string");
|
|
264
|
+
store.close();
|
|
292
265
|
});
|
|
293
266
|
|
|
294
|
-
test("
|
|
295
|
-
const {
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
for (let i = 0; i < 4; i++) {
|
|
301
|
-
const { memory } = service.saveWithDedupe({ type: "decision", title: `D${i}`, content: `内容 ${i}` });
|
|
302
|
-
ids.push(memory.id);
|
|
303
|
-
}
|
|
304
|
-
const ctx = sleepCtx({
|
|
305
|
-
onConflict: (text) => {
|
|
306
|
-
const [first, second] = [...text.matchAll(/id=([^\s|]+)/g)].map((m) => m[1]);
|
|
307
|
-
assert.ok(first && second, "conflict prompt shows a pair");
|
|
308
|
-
return JSON.stringify([{ action: "conflict", winner: first, loser: second, reason: "矛盾" }]);
|
|
309
|
-
}
|
|
267
|
+
test("sleep: a failing phase does not block the others (fail-safe)", async () => {
|
|
268
|
+
const { service, store } = setup();
|
|
269
|
+
service.setEmbedder({
|
|
270
|
+
embed: async () => { throw new Error("embed down"); },
|
|
271
|
+
embedSingle: async () => { throw new Error("embed down"); },
|
|
272
|
+
modelHash: "x", dimension: 3
|
|
310
273
|
});
|
|
311
|
-
const
|
|
312
|
-
|
|
313
|
-
|
|
274
|
+
const now = Date.now();
|
|
275
|
+
const m = makeMemory(service, "cold", "内容".repeat(60), "project");
|
|
276
|
+
service.touchLastAccess(m.id, new Date(now - 40 * 86400000).toISOString());
|
|
277
|
+
const ctx = mockCtx(() => "[]");
|
|
278
|
+
const result = await runSleep(ctx, service, baseConfig(), ctx.logger, null, null);
|
|
279
|
+
assert.equal(result.phases.conflicts.status, "skipped", "conflicts phase degraded gracefully (no usable vectors)");
|
|
280
|
+
assert.equal(result.phases.demotion.status, "ok", "demotion still ran");
|
|
281
|
+
assert.equal(result.status, "ok", "overall run still ok despite conflicts degrading");
|
|
282
|
+
assert.ok(service.getById(m.id)._full_content, "cold memory still demoted despite conflicts failure");
|
|
283
|
+
store.close();
|
|
314
284
|
});
|
|
315
285
|
|
|
316
|
-
test("
|
|
317
|
-
const {
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
const
|
|
322
|
-
|
|
323
|
-
assert.equal(result.phases.conflicts.
|
|
286
|
+
test("sleep: no LLM route skips LLM phases but demotion still runs", async () => {
|
|
287
|
+
const { service, store } = setup();
|
|
288
|
+
const now = Date.now();
|
|
289
|
+
const m = makeMemory(service, "cold", "内容".repeat(60), "project");
|
|
290
|
+
service.touchLastAccess(m.id, new Date(now - 40 * 86400000).toISOString());
|
|
291
|
+
const ctx = mockCtx(() => "[]", null); // currentSelection() → null, no route
|
|
292
|
+
const result = await runSleep(ctx, service, baseConfig(), ctx.logger, null, null);
|
|
293
|
+
assert.equal(result.phases.conflicts.status, "skipped", "no llm route → conflicts skipped");
|
|
294
|
+
assert.equal(result.phases.patterns.status, "skipped", "no llm route → patterns skipped");
|
|
295
|
+
assert.equal(result.phases.demotion.status, "ok", "demotion is LLM-free and runs");
|
|
296
|
+
store.close();
|
|
324
297
|
});
|
|
325
298
|
|
|
326
|
-
// ------------------------------------------------------------
|
|
327
|
-
|
|
328
|
-
test("validateDecisions: valid create passes with empty snapshot", () => {
|
|
329
|
-
const { ok, errors } = validateDecisions(
|
|
330
|
-
[{ action: "create", type: "pattern", title: "P", content: "c", importance: 3, evidence: ["x"] }],
|
|
331
|
-
new Map(),
|
|
332
|
-
{ maxCreatePerRun: 5 }
|
|
333
|
-
);
|
|
334
|
-
assert.equal(ok, true, errors.join("; "));
|
|
335
|
-
});
|
|
299
|
+
// ------------------------------------------------------------ conflict strictness
|
|
336
300
|
|
|
337
|
-
|
|
338
|
-
const
|
|
339
|
-
const
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
const cap = validateDecisions(
|
|
346
|
-
Array.from({ length: 6 }, (_, i) => ({ action: "create", title: `P${i}`, content: "c" })),
|
|
347
|
-
empty,
|
|
348
|
-
{ maxCreatePerRun: 5 }
|
|
349
|
-
);
|
|
350
|
-
assert.equal(cap.ok, false, "exceeding maxCreatePerRun rejects");
|
|
351
|
-
});
|
|
301
|
+
function seedConflictPair(service, vectorIndex, sim) {
|
|
302
|
+
const a = makeMemory(service, "主题X", "内容A 关于主题X", "project");
|
|
303
|
+
const b = makeMemory(service, "主题X副本", "内容B 关于主题X", "project");
|
|
304
|
+
const sin = Math.sqrt(Math.max(0, 1 - sim * sim));
|
|
305
|
+
vectorIndex.saveEmbedding(a.id, [1, 0, 0]);
|
|
306
|
+
vectorIndex.saveEmbedding(b.id, [sim, sin, 0]);
|
|
307
|
+
return { a, b };
|
|
308
|
+
}
|
|
352
309
|
|
|
353
|
-
test("
|
|
354
|
-
const
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
310
|
+
test("sleep: conflict strictness gentle ignores sim 0.88 pairs", async () => {
|
|
311
|
+
const { service, store, vectorIndex } = setup();
|
|
312
|
+
seedConflictPair(service, vectorIndex, 0.88);
|
|
313
|
+
const config = baseConfig({ sleepConflictStrictness: "gentle", conflictFreezeEnabled: true });
|
|
314
|
+
const ctx = mockCtx(() => "[]");
|
|
315
|
+
const result = await runSleep(ctx, service, config, ctx.logger, { embedder, vectorIndex }, null);
|
|
316
|
+
assert.equal(result.phases.conflicts.status, "skipped", "0.88 below gentle 0.92 → no conflicts");
|
|
317
|
+
store.close();
|
|
358
318
|
});
|
|
359
319
|
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
const
|
|
364
|
-
const
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
assert.ok(
|
|
320
|
+
test("sleep: conflict strictness normal resolves sim 0.88 pairs", async () => {
|
|
321
|
+
const { service, store, vectorIndex } = setup();
|
|
322
|
+
seedConflictPair(service, vectorIndex, 0.88);
|
|
323
|
+
const config = baseConfig({ sleepConflictStrictness: "normal", conflictFreezeEnabled: true });
|
|
324
|
+
const ctx = mockCtx(() => "[]");
|
|
325
|
+
const result = await runSleep(ctx, service, config, ctx.logger, { embedder, vectorIndex }, null);
|
|
326
|
+
assert.equal(result.phases.conflicts.status, "ok", "0.88 above normal 0.85 → conflicts found");
|
|
327
|
+
assert.ok(result.phases.conflicts.frozen >= 1, "pairs frozen for review");
|
|
328
|
+
store.close();
|
|
368
329
|
});
|
|
369
330
|
|
|
370
|
-
test("
|
|
371
|
-
const store =
|
|
372
|
-
|
|
373
|
-
const
|
|
374
|
-
|
|
375
|
-
|
|
331
|
+
test("sleep: conflict strictness aggressive adjudicates low-confidence pairs", async () => {
|
|
332
|
+
const { service, store, vectorIndex } = setup();
|
|
333
|
+
seedConflictPair(service, vectorIndex, 0.80);
|
|
334
|
+
const config = baseConfig({ sleepConflictStrictness: "aggressive", conflictFreezeEnabled: true });
|
|
335
|
+
const ctx = mockCtx(() => "[]");
|
|
336
|
+
const result = await runSleep(ctx, service, config, ctx.logger, { embedder, vectorIndex }, null);
|
|
337
|
+
assert.equal(result.phases.conflicts.status, "ok", "0.80 above aggressive 0.75 → conflicts found");
|
|
338
|
+
assert.ok(result.phases.conflicts.frozen >= 1, "pairs frozen");
|
|
339
|
+
store.close();
|
|
376
340
|
});
|
|
377
341
|
|
|
378
|
-
test("
|
|
379
|
-
const { store,
|
|
380
|
-
|
|
381
|
-
const
|
|
382
|
-
|
|
383
|
-
|
|
342
|
+
test("sleep: conflict LLM arbitration applies winner/loser", async () => {
|
|
343
|
+
const { service, store, vectorIndex } = setup();
|
|
344
|
+
const { a, b } = seedConflictPair(service, vectorIndex, 1.0);
|
|
345
|
+
const ctx = mockCtx(() =>
|
|
346
|
+
JSON.stringify([{ action: "conflict", winner: a.id, loser: b.id, reason: "重复覆盖" }])
|
|
347
|
+
);
|
|
348
|
+
const result = await runSleep(ctx, service, baseConfig(), ctx.logger, { embedder, vectorIndex }, null);
|
|
349
|
+
assert.equal(result.phases.conflicts.status, "ok", "conflict resolved");
|
|
350
|
+
assert.equal(service.getById(b.id).archived, true, "loser archived by arbitration");
|
|
351
|
+
store.close();
|
|
384
352
|
});
|
|
385
353
|
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
const
|
|
390
|
-
|
|
391
|
-
const
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
assert.equal(result.phases.
|
|
396
|
-
|
|
397
|
-
const runs = store.listDreamRuns();
|
|
398
|
-
assert.equal(runs.length, 1);
|
|
399
|
-
assert.equal(runs[0].run_type, "sleep");
|
|
400
|
-
assert.equal(runs[0].status, "noop");
|
|
354
|
+
test("sleep: runSleep is abortable via signal between phases", async () => {
|
|
355
|
+
const { service, store } = setup();
|
|
356
|
+
const now = Date.now();
|
|
357
|
+
const m = makeMemory(service, "cold", "内容".repeat(60), "project");
|
|
358
|
+
service.touchLastAccess(m.id, new Date(now - 40 * 86400000).toISOString());
|
|
359
|
+
const ctrl = new AbortController();
|
|
360
|
+
ctrl.abort(); // pre-aborted
|
|
361
|
+
const ctx = mockCtx(() => "[]");
|
|
362
|
+
const result = await runSleep(ctx, service, baseConfig(), ctx.logger, null, ctrl.signal);
|
|
363
|
+
assert.equal(result.phases.conflicts, undefined, "aborted before any phase ran");
|
|
364
|
+
store.close();
|
|
401
365
|
});
|