@modusensus/dsh-mneme 0.2.8 → 0.2.9
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 +3 -3
- package/lib/config.js +8 -1
- package/lib/dream.js +60 -6
- package/lib/service.js +7 -1
- package/lib/store.js +96 -0
- package/package.json +1 -1
- package/src/config.js +8 -1
- package/src/dream.js +60 -6
- package/src/service.js +7 -1
- package/src/store.js +96 -0
- package/test/conflict-freeze.test.js +290 -0
- package/test/dream.test.js +126 -0
- package/test/store.test.js +67 -0
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
[](https://www.npmjs.com/package/@modusensus/dsh-mneme)
|
|
6
6
|
[](LICENSE)
|
|
7
7
|
[](https://github.com/awesome-dsh-plugin/awesome-dsh-plugin)
|
|
8
|
-
[](https://github.com/modusensus/dsh-mneme)
|
|
9
9
|
|
|
10
10
|
> 给 DeepSeek Harness 的跨会话记忆插件:让 Agent 记住你、记住项目、自动整理记忆。**Mneme**(Μνήμη)——希腊记忆女神 Mnemosyne 之名,掌管记忆与梦境,正如 autoDream 在后台巩固记忆。
|
|
11
11
|
|
|
@@ -225,7 +225,7 @@ src/
|
|
|
225
225
|
lib/
|
|
226
226
|
├── client.js # Web 面板(手写 ModuleLoader bundle)
|
|
227
227
|
└── *.js # src 的同步分发产物
|
|
228
|
-
test/ #
|
|
228
|
+
test/ # 355 个 node:test 测试(含审计与三轴线压测不变量)
|
|
229
229
|
scripts/ # e2e-dsh.js 端到端演示 · stress-dsh.js 三轴线压测 · sync-lib.js 同步
|
|
230
230
|
```
|
|
231
231
|
|
|
@@ -234,7 +234,7 @@ scripts/ # e2e-dsh.js 端到端演示 · stress-dsh.js 三轴线压
|
|
|
234
234
|
```bash
|
|
235
235
|
cd dsh-mneme
|
|
236
236
|
npm install # 安装 peer 依赖(以 devDependencies 形式,用于本地测试)
|
|
237
|
-
npm test # 运行
|
|
237
|
+
npm test # 运行 355 个测试
|
|
238
238
|
npm run stress # 三轴线压测:长会话检索 / 冲突仲裁 / 多 Agent 并发(离线 mock LLM)
|
|
239
239
|
npm run sync # 把 src/ 同步到 lib/(发布时由 prepack 钩子自动执行)
|
|
240
240
|
```
|
package/lib/config.js
CHANGED
|
@@ -67,5 +67,12 @@ export const Config = z.object({
|
|
|
67
67
|
reflectionUpdateEnabled: z.boolean().default(true),
|
|
68
68
|
reflectionFailureTracking: z.boolean().default(true),
|
|
69
69
|
reflectionUpdateMaxPerRun: z.natural().min(0).max(5).default(2),
|
|
70
|
-
reflectionUpdateMinAgeHours: z.natural().min(0).max(168).default(24)
|
|
70
|
+
reflectionUpdateMinAgeHours: z.natural().min(0).max(168).default(24),
|
|
71
|
+
|
|
72
|
+
// --- conflict freeze: manual review for conflicting memories (v0.2.1) ---
|
|
73
|
+
// Opt-in by default: when true, conflicting memories are not auto-merged
|
|
74
|
+
// and are marked as pending manual review instead.
|
|
75
|
+
conflictFreezeEnabled: z.boolean().default(false),
|
|
76
|
+
// Maximum number of frozen conflicts to keep pending for manual review.
|
|
77
|
+
conflictFreezeMaxPending: z.natural().min(1).max(1000).default(100),
|
|
71
78
|
});
|
package/lib/dream.js
CHANGED
|
@@ -350,6 +350,10 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
|
|
|
350
350
|
const route = resolveRoute(ctx, config, logger);
|
|
351
351
|
const runId = randomUUID();
|
|
352
352
|
const snapshotHash = hashSnapshot([...snapshot.values()]);
|
|
353
|
+
// Conflict freeze (opt-in): when enabled, conflict decisions are parked for
|
|
354
|
+
// manual review instead of auto-adjudicated. Read once up front so the
|
|
355
|
+
// prompt hint and the apply-split agree on the same gate.
|
|
356
|
+
const freezeEnabled = config.conflictFreezeEnabled === true;
|
|
353
357
|
// Every exit (success or failure) funnels through `finish`, which writes
|
|
354
358
|
// the audit row + receipt. A record failure is logged, never thrown —
|
|
355
359
|
// auditing must not break the consolidation path. Failed runs still
|
|
@@ -440,6 +444,12 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
|
|
|
440
444
|
).join("\n");
|
|
441
445
|
}
|
|
442
446
|
|
|
447
|
+
// Freeze-aware prompt: in freeze mode the conflict branch still outputs
|
|
448
|
+
// winner/loser (validation requires them) but they are treated as tentative
|
|
449
|
+
// candidates — the human makes the final call, not the model.
|
|
450
|
+
const consolidationPrompt = freezeEnabled
|
|
451
|
+
? CONSOLIDATION_PROMPT + `\n\n当前为「冲突冻结」模式:检测到内容矛盾的条目时,仍请输出 conflict,并以 winner/loser 作为候选、reason 说明理由;冲突不会被自动裁决,而会冻结待人工确认。`
|
|
452
|
+
: CONSOLIDATION_PROMPT;
|
|
443
453
|
let decisionText;
|
|
444
454
|
try {
|
|
445
455
|
decisionText = await streamText(ctx, {
|
|
@@ -448,7 +458,7 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
|
|
|
448
458
|
purpose: "compaction",
|
|
449
459
|
maxTokens: config.dreamMaxTokens ?? 4096,
|
|
450
460
|
messages: [
|
|
451
|
-
{ role: "system", content: [{ type: "text", text:
|
|
461
|
+
{ role: "system", content: [{ type: "text", text: consolidationPrompt }] },
|
|
452
462
|
{ role: "user", content: [{ type: "text", text: listText }] }
|
|
453
463
|
]
|
|
454
464
|
});
|
|
@@ -492,10 +502,46 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
|
|
|
492
502
|
}
|
|
493
503
|
}
|
|
494
504
|
|
|
505
|
+
// Conflict freeze (opt-in): when enabled, conflict decisions are not
|
|
506
|
+
// auto-adjudicated — no winner kept, no loser archived. The pair is parked
|
|
507
|
+
// in conflict_pending for human review instead. Best-effort: a store
|
|
508
|
+
// failure here must never block the run (fail-safe — the memories are left
|
|
509
|
+
// untouched and nothing is arbitrated). The cap (conflictFreezeMaxPending)
|
|
510
|
+
// bounds the review queue; overflow is skipped with a warning.
|
|
511
|
+
let frozenCount = 0;
|
|
512
|
+
const frozenIds = [];
|
|
513
|
+
const applyList = freezeEnabled ? decisions.filter((d) => d.action !== "conflict") : decisions;
|
|
514
|
+
if (freezeEnabled) {
|
|
515
|
+
const conflictsToFreeze = decisions.filter((d) => d.action === "conflict");
|
|
516
|
+
if (conflictsToFreeze.length > 0) {
|
|
517
|
+
try {
|
|
518
|
+
const maxPending = Number.isInteger(config.conflictFreezeMaxPending) ? config.conflictFreezeMaxPending : 100;
|
|
519
|
+
const pendingNow = service.countConflictPending();
|
|
520
|
+
const budget = Math.max(0, maxPending - pendingNow);
|
|
521
|
+
const toFreeze = conflictsToFreeze.slice(0, budget);
|
|
522
|
+
if (conflictsToFreeze.length > budget) {
|
|
523
|
+
logger?.warn?.(`dsh-mneme dream: conflict freeze queue full (${pendingNow}/${maxPending}), skipped ${conflictsToFreeze.length - budget} conflict(s)`);
|
|
524
|
+
}
|
|
525
|
+
for (const d of toFreeze) {
|
|
526
|
+
try {
|
|
527
|
+
service.saveConflictPending({ run_id: runId, memory_a: d.winner, memory_b: d.loser, reason: d.reason });
|
|
528
|
+
frozenCount++;
|
|
529
|
+
frozenIds.push(d.winner, d.loser);
|
|
530
|
+
} catch (error) {
|
|
531
|
+
logger?.warn?.(`dsh-mneme dream: failed to freeze conflict ${d.winner}/${d.loser}: ${String(error)}`);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
} catch (error) {
|
|
535
|
+
logger?.warn?.(`dsh-mneme dream: conflict freeze lookup failed: ${String(error)}`);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
|
|
495
540
|
// CAS-guarded, per-decision-transactional apply against the run snapshot:
|
|
496
541
|
// a target changed during the LLM call is skipped and reported as a
|
|
497
|
-
// conflict instead of being overwritten (item ①).
|
|
498
|
-
|
|
542
|
+
// conflict instead of being overwritten (item ①). Frozen conflicts are
|
|
543
|
+
// excluded from this list (they are parked, not applied).
|
|
544
|
+
const { applied, conflicts, failures, committed } = applyDecisions(applyList, service, logger, snapshot);
|
|
499
545
|
// Per-record receipt chain: one row per actually-committed merge/conflict/
|
|
500
546
|
// update verdict, stamped with the decision-basis digest + idempotency
|
|
501
547
|
// counters (count_before → count_after). Written here, before the run audit
|
|
@@ -521,18 +567,25 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
|
|
|
521
567
|
// claim "merge-archived" (item ②). Conflicts/failures ride along so the
|
|
522
568
|
// audit row records why the run diverged.
|
|
523
569
|
const outcome = { ...buildOutcome(committed), conflicts, failures };
|
|
570
|
+
// Frozen conflicts were not adjudicated: mark both sides pending in the
|
|
571
|
+
// per-id outcome so the audit row shows they were parked, not skipped.
|
|
572
|
+
if (frozenIds.length) {
|
|
573
|
+
for (const id of frozenIds) outcome.byId[id] = "conflict-pending";
|
|
574
|
+
}
|
|
524
575
|
// Decisions validated but not fully committed → reconcile (not ok).
|
|
525
576
|
const partial = conflicts.length > 0 || failures.length > 0;
|
|
526
577
|
// No decision landed (all-keep, or every decision skipped as an idempotent
|
|
527
578
|
// replay) → nothing substantive changed. Distinct from a success: such a
|
|
528
579
|
// run must never be reported as ok, or the audit claims work that never
|
|
529
580
|
// happened and the scheduler refreshes the baseline on a false positive.
|
|
530
|
-
|
|
581
|
+
// Frozen conflicts are substantive output (parked for review), so a run
|
|
582
|
+
// that only froze conflicts is not a noop.
|
|
583
|
+
const noChange = frozenCount === 0 && applied === 0 && committed.every((c) => c.action === "keep");
|
|
531
584
|
|
|
532
585
|
// Keep the vector index consistent with the post-dream store state.
|
|
533
586
|
if (semantic?.embedder && semantic?.vectorIndex) {
|
|
534
587
|
try {
|
|
535
|
-
await maintainIndexAfterDream(
|
|
588
|
+
await maintainIndexAfterDream(applyList, service, semantic);
|
|
536
589
|
} catch (error) {
|
|
537
590
|
logger?.warn?.(`[dsh-mneme] dream index maintenance failed: ${String(error)}`);
|
|
538
591
|
}
|
|
@@ -554,7 +607,7 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
|
|
|
554
607
|
});
|
|
555
608
|
} catch (error) {
|
|
556
609
|
logger?.warn?.(`dsh-mneme dream: summary llm call failed: ${String(error)}`);
|
|
557
|
-
return finish({ ok: false, error: "llm failed", applied, decisions: auditDecisions, outcome, summary: false });
|
|
610
|
+
return finish({ ok: false, error: "llm failed", applied, decisions: auditDecisions, outcome, frozen: frozenCount, summary: false });
|
|
558
611
|
}
|
|
559
612
|
let summaryStored = false;
|
|
560
613
|
if (summaryText !== undefined && summaryText.trim()) {
|
|
@@ -601,6 +654,7 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
|
|
|
601
654
|
outcome,
|
|
602
655
|
conflicts,
|
|
603
656
|
failures,
|
|
657
|
+
frozen: frozenCount,
|
|
604
658
|
summary: summaryStored
|
|
605
659
|
});
|
|
606
660
|
}
|
package/lib/service.js
CHANGED
|
@@ -479,6 +479,12 @@ export function createService({ store, mirror, config, onWrite }) {
|
|
|
479
479
|
// audit write, never a write-hook-triggering memory mutation).
|
|
480
480
|
saveReceipt: (r) => store.saveReceipt(r),
|
|
481
481
|
getReceipt: (id) => store.getReceipt(id),
|
|
482
|
-
listReceipts: (opts) => store.listReceipts(opts)
|
|
482
|
+
listReceipts: (opts) => store.listReceipts(opts),
|
|
483
|
+
// Conflict freeze bookkeeping (same semantics as the audit passthroughs
|
|
484
|
+
// above: an audit write, never a write-hook-triggering memory mutation).
|
|
485
|
+
saveConflictPending: (r) => store.saveConflictPending(r),
|
|
486
|
+
listConflictPending: (opts) => store.listConflictPending(opts),
|
|
487
|
+
resolveConflictPending: (id, o) => store.resolveConflictPending(id, o),
|
|
488
|
+
countConflictPending: () => store.countConflictPending()
|
|
483
489
|
};
|
|
484
490
|
}
|
package/lib/store.js
CHANGED
|
@@ -100,6 +100,24 @@ CREATE TABLE IF NOT EXISTS receipt_chain (
|
|
|
100
100
|
);
|
|
101
101
|
CREATE INDEX IF NOT EXISTS idx_receipt_chain_record ON receipt_chain(record_id);
|
|
102
102
|
CREATE INDEX IF NOT EXISTS idx_receipt_chain_run ON receipt_chain(run_id);
|
|
103
|
+
|
|
104
|
+
-- conflict_pending: conflicts parked for manual review (conflict freeze mode,
|
|
105
|
+
-- opt-in via config.conflictFreezeEnabled). When enabled, the dream layer does
|
|
106
|
+
-- NOT auto-adjudicate winner/loser — the conflicting pair is parked here until
|
|
107
|
+
-- a human reviews it. resolveConflictPending stamps resolved_at (plus the chosen
|
|
108
|
+
-- winner) so the review action stays auditable. Like the other audit tables this
|
|
109
|
+
-- is bookkeeping: it never triggers write hooks.
|
|
110
|
+
CREATE TABLE IF NOT EXISTS conflict_pending (
|
|
111
|
+
id TEXT PRIMARY KEY,
|
|
112
|
+
run_id TEXT,
|
|
113
|
+
memory_a TEXT NOT NULL,
|
|
114
|
+
memory_b TEXT NOT NULL,
|
|
115
|
+
reason TEXT,
|
|
116
|
+
created_at TEXT NOT NULL,
|
|
117
|
+
resolved_at TEXT,
|
|
118
|
+
resolved_winner TEXT
|
|
119
|
+
);
|
|
120
|
+
CREATE INDEX IF NOT EXISTS idx_conflict_pending_unresolved ON conflict_pending(resolved_at);
|
|
103
121
|
`;
|
|
104
122
|
|
|
105
123
|
const TYPES = new Set(["preference", "project", "decision", "history", "summary"]);
|
|
@@ -183,6 +201,20 @@ function toReceipt(row) {
|
|
|
183
201
|
};
|
|
184
202
|
}
|
|
185
203
|
|
|
204
|
+
function toConflictPending(row) {
|
|
205
|
+
if (!row) return undefined;
|
|
206
|
+
return {
|
|
207
|
+
id: row.id,
|
|
208
|
+
run_id: row.run_id ?? undefined,
|
|
209
|
+
memory_a: row.memory_a,
|
|
210
|
+
memory_b: row.memory_b,
|
|
211
|
+
reason: row.reason ?? undefined,
|
|
212
|
+
created_at: row.created_at,
|
|
213
|
+
resolved_at: row.resolved_at ?? undefined,
|
|
214
|
+
resolved_winner: row.resolved_winner ?? undefined
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
186
218
|
function toRecallRun(row) {
|
|
187
219
|
if (!row) return undefined;
|
|
188
220
|
return {
|
|
@@ -702,6 +734,66 @@ export function createStore(path) {
|
|
|
702
734
|
return db.prepare("DELETE FROM failure_memories WHERE created_at < ?").run(before).changes;
|
|
703
735
|
}
|
|
704
736
|
|
|
737
|
+
// --- conflict freeze: pending manual review ------------------------------
|
|
738
|
+
|
|
739
|
+
/**
|
|
740
|
+
* Park a detected conflict for human review (conflict freeze mode). The pair
|
|
741
|
+
* order is normalized (sorted by id) so the same two memories are only ever
|
|
742
|
+
* pending once — a re-detection in a later dream run is a no-op, never a
|
|
743
|
+
* duplicate queue entry. Returns the pending row (freshly inserted, or the
|
|
744
|
+
* existing unresolved row when the pair is already pending).
|
|
745
|
+
*/
|
|
746
|
+
function saveConflictPending({ run_id, memory_a, memory_b, reason }) {
|
|
747
|
+
const [a, b] = [memory_a, memory_b].sort();
|
|
748
|
+
const existing = db.prepare(
|
|
749
|
+
"SELECT * FROM conflict_pending WHERE memory_a = ? AND memory_b = ? AND resolved_at IS NULL LIMIT 1"
|
|
750
|
+
).get(a, b);
|
|
751
|
+
if (existing) return toConflictPending(existing);
|
|
752
|
+
const id = randomUUID();
|
|
753
|
+
const now = nowIso();
|
|
754
|
+
db.prepare(
|
|
755
|
+
`INSERT INTO conflict_pending (id, run_id, memory_a, memory_b, reason, created_at)
|
|
756
|
+
VALUES (?, ?, ?, ?, ?, ?)`
|
|
757
|
+
).run(id, run_id ?? null, a, b, reason ?? null, now);
|
|
758
|
+
return toConflictPending(db.prepare("SELECT * FROM conflict_pending WHERE id = ?").get(id));
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
/**
|
|
762
|
+
* List pending conflicts, newest first. Unresolved rows only by default;
|
|
763
|
+
* pass includeResolved to include resolved ones (audit view).
|
|
764
|
+
*/
|
|
765
|
+
function listConflictPending({ limit = 50, offset = 0, includeResolved = false } = {}) {
|
|
766
|
+
const { limit: lim, offset: off } = sanitizePage(limit, offset, 50);
|
|
767
|
+
const clauses = [];
|
|
768
|
+
const params = [];
|
|
769
|
+
if (!includeResolved) clauses.push("resolved_at IS NULL");
|
|
770
|
+
const where = clauses.length ? `WHERE ${clauses.join(" AND ")}` : "";
|
|
771
|
+
const rows = db.prepare(
|
|
772
|
+
`SELECT * FROM conflict_pending ${where} ORDER BY created_at DESC, id LIMIT ? OFFSET ?`
|
|
773
|
+
).all(...params, lim, off);
|
|
774
|
+
return rows.map(toConflictPending);
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/**
|
|
778
|
+
* Mark a pending conflict as reviewed. winner (optional) records which side
|
|
779
|
+
* the human chose, keeping the resolution auditable. Returns the updated row,
|
|
780
|
+
* or undefined for an unknown id.
|
|
781
|
+
*/
|
|
782
|
+
function resolveConflictPending(id, { winner } = {}) {
|
|
783
|
+
const row = db.prepare("SELECT * FROM conflict_pending WHERE id = ?").get(id);
|
|
784
|
+
if (!row) return undefined;
|
|
785
|
+
db.prepare("UPDATE conflict_pending SET resolved_at = ?, resolved_winner = ? WHERE id = ?")
|
|
786
|
+
.run(nowIso(), winner ?? null, id);
|
|
787
|
+
return toConflictPending(db.prepare("SELECT * FROM conflict_pending WHERE id = ?").get(id));
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
/** Number of unresolved (awaiting review) pending conflicts. */
|
|
791
|
+
function countConflictPending() {
|
|
792
|
+
return db.prepare(
|
|
793
|
+
"SELECT count(*) AS c FROM conflict_pending WHERE resolved_at IS NULL"
|
|
794
|
+
).get().c;
|
|
795
|
+
}
|
|
796
|
+
|
|
705
797
|
function getFailureStats({ since } = {}) {
|
|
706
798
|
const clause = since ? "WHERE created_at >= ?" : "";
|
|
707
799
|
const params = since ? [since] : [];
|
|
@@ -744,6 +836,10 @@ export function createStore(path) {
|
|
|
744
836
|
listFailures,
|
|
745
837
|
getFailureStats,
|
|
746
838
|
deleteOldFailures,
|
|
839
|
+
saveConflictPending,
|
|
840
|
+
listConflictPending,
|
|
841
|
+
resolveConflictPending,
|
|
842
|
+
countConflictPending,
|
|
747
843
|
close() {
|
|
748
844
|
db.close();
|
|
749
845
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@modusensus/dsh-mneme",
|
|
3
3
|
"description": "Cross-session memory plugin for DeepSeek Harness with autoDream consolidation: SQLite store, Markdown mirrors, 6 model tools, automatic injection, session summarization, user profile/rules, custom slash commands, vector (semantic) search, and a Web GUI panel",
|
|
4
|
-
"version": "0.2.
|
|
4
|
+
"version": "0.2.9",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "lib/index.js",
|
package/src/config.js
CHANGED
|
@@ -67,5 +67,12 @@ export const Config = z.object({
|
|
|
67
67
|
reflectionUpdateEnabled: z.boolean().default(true),
|
|
68
68
|
reflectionFailureTracking: z.boolean().default(true),
|
|
69
69
|
reflectionUpdateMaxPerRun: z.natural().min(0).max(5).default(2),
|
|
70
|
-
reflectionUpdateMinAgeHours: z.natural().min(0).max(168).default(24)
|
|
70
|
+
reflectionUpdateMinAgeHours: z.natural().min(0).max(168).default(24),
|
|
71
|
+
|
|
72
|
+
// --- conflict freeze: manual review for conflicting memories (v0.2.1) ---
|
|
73
|
+
// Opt-in by default: when true, conflicting memories are not auto-merged
|
|
74
|
+
// and are marked as pending manual review instead.
|
|
75
|
+
conflictFreezeEnabled: z.boolean().default(false),
|
|
76
|
+
// Maximum number of frozen conflicts to keep pending for manual review.
|
|
77
|
+
conflictFreezeMaxPending: z.natural().min(1).max(1000).default(100),
|
|
71
78
|
});
|
package/src/dream.js
CHANGED
|
@@ -350,6 +350,10 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
|
|
|
350
350
|
const route = resolveRoute(ctx, config, logger);
|
|
351
351
|
const runId = randomUUID();
|
|
352
352
|
const snapshotHash = hashSnapshot([...snapshot.values()]);
|
|
353
|
+
// Conflict freeze (opt-in): when enabled, conflict decisions are parked for
|
|
354
|
+
// manual review instead of auto-adjudicated. Read once up front so the
|
|
355
|
+
// prompt hint and the apply-split agree on the same gate.
|
|
356
|
+
const freezeEnabled = config.conflictFreezeEnabled === true;
|
|
353
357
|
// Every exit (success or failure) funnels through `finish`, which writes
|
|
354
358
|
// the audit row + receipt. A record failure is logged, never thrown —
|
|
355
359
|
// auditing must not break the consolidation path. Failed runs still
|
|
@@ -440,6 +444,12 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
|
|
|
440
444
|
).join("\n");
|
|
441
445
|
}
|
|
442
446
|
|
|
447
|
+
// Freeze-aware prompt: in freeze mode the conflict branch still outputs
|
|
448
|
+
// winner/loser (validation requires them) but they are treated as tentative
|
|
449
|
+
// candidates — the human makes the final call, not the model.
|
|
450
|
+
const consolidationPrompt = freezeEnabled
|
|
451
|
+
? CONSOLIDATION_PROMPT + `\n\n当前为「冲突冻结」模式:检测到内容矛盾的条目时,仍请输出 conflict,并以 winner/loser 作为候选、reason 说明理由;冲突不会被自动裁决,而会冻结待人工确认。`
|
|
452
|
+
: CONSOLIDATION_PROMPT;
|
|
443
453
|
let decisionText;
|
|
444
454
|
try {
|
|
445
455
|
decisionText = await streamText(ctx, {
|
|
@@ -448,7 +458,7 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
|
|
|
448
458
|
purpose: "compaction",
|
|
449
459
|
maxTokens: config.dreamMaxTokens ?? 4096,
|
|
450
460
|
messages: [
|
|
451
|
-
{ role: "system", content: [{ type: "text", text:
|
|
461
|
+
{ role: "system", content: [{ type: "text", text: consolidationPrompt }] },
|
|
452
462
|
{ role: "user", content: [{ type: "text", text: listText }] }
|
|
453
463
|
]
|
|
454
464
|
});
|
|
@@ -492,10 +502,46 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
|
|
|
492
502
|
}
|
|
493
503
|
}
|
|
494
504
|
|
|
505
|
+
// Conflict freeze (opt-in): when enabled, conflict decisions are not
|
|
506
|
+
// auto-adjudicated — no winner kept, no loser archived. The pair is parked
|
|
507
|
+
// in conflict_pending for human review instead. Best-effort: a store
|
|
508
|
+
// failure here must never block the run (fail-safe — the memories are left
|
|
509
|
+
// untouched and nothing is arbitrated). The cap (conflictFreezeMaxPending)
|
|
510
|
+
// bounds the review queue; overflow is skipped with a warning.
|
|
511
|
+
let frozenCount = 0;
|
|
512
|
+
const frozenIds = [];
|
|
513
|
+
const applyList = freezeEnabled ? decisions.filter((d) => d.action !== "conflict") : decisions;
|
|
514
|
+
if (freezeEnabled) {
|
|
515
|
+
const conflictsToFreeze = decisions.filter((d) => d.action === "conflict");
|
|
516
|
+
if (conflictsToFreeze.length > 0) {
|
|
517
|
+
try {
|
|
518
|
+
const maxPending = Number.isInteger(config.conflictFreezeMaxPending) ? config.conflictFreezeMaxPending : 100;
|
|
519
|
+
const pendingNow = service.countConflictPending();
|
|
520
|
+
const budget = Math.max(0, maxPending - pendingNow);
|
|
521
|
+
const toFreeze = conflictsToFreeze.slice(0, budget);
|
|
522
|
+
if (conflictsToFreeze.length > budget) {
|
|
523
|
+
logger?.warn?.(`dsh-mneme dream: conflict freeze queue full (${pendingNow}/${maxPending}), skipped ${conflictsToFreeze.length - budget} conflict(s)`);
|
|
524
|
+
}
|
|
525
|
+
for (const d of toFreeze) {
|
|
526
|
+
try {
|
|
527
|
+
service.saveConflictPending({ run_id: runId, memory_a: d.winner, memory_b: d.loser, reason: d.reason });
|
|
528
|
+
frozenCount++;
|
|
529
|
+
frozenIds.push(d.winner, d.loser);
|
|
530
|
+
} catch (error) {
|
|
531
|
+
logger?.warn?.(`dsh-mneme dream: failed to freeze conflict ${d.winner}/${d.loser}: ${String(error)}`);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
} catch (error) {
|
|
535
|
+
logger?.warn?.(`dsh-mneme dream: conflict freeze lookup failed: ${String(error)}`);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
|
|
495
540
|
// CAS-guarded, per-decision-transactional apply against the run snapshot:
|
|
496
541
|
// a target changed during the LLM call is skipped and reported as a
|
|
497
|
-
// conflict instead of being overwritten (item ①).
|
|
498
|
-
|
|
542
|
+
// conflict instead of being overwritten (item ①). Frozen conflicts are
|
|
543
|
+
// excluded from this list (they are parked, not applied).
|
|
544
|
+
const { applied, conflicts, failures, committed } = applyDecisions(applyList, service, logger, snapshot);
|
|
499
545
|
// Per-record receipt chain: one row per actually-committed merge/conflict/
|
|
500
546
|
// update verdict, stamped with the decision-basis digest + idempotency
|
|
501
547
|
// counters (count_before → count_after). Written here, before the run audit
|
|
@@ -521,18 +567,25 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
|
|
|
521
567
|
// claim "merge-archived" (item ②). Conflicts/failures ride along so the
|
|
522
568
|
// audit row records why the run diverged.
|
|
523
569
|
const outcome = { ...buildOutcome(committed), conflicts, failures };
|
|
570
|
+
// Frozen conflicts were not adjudicated: mark both sides pending in the
|
|
571
|
+
// per-id outcome so the audit row shows they were parked, not skipped.
|
|
572
|
+
if (frozenIds.length) {
|
|
573
|
+
for (const id of frozenIds) outcome.byId[id] = "conflict-pending";
|
|
574
|
+
}
|
|
524
575
|
// Decisions validated but not fully committed → reconcile (not ok).
|
|
525
576
|
const partial = conflicts.length > 0 || failures.length > 0;
|
|
526
577
|
// No decision landed (all-keep, or every decision skipped as an idempotent
|
|
527
578
|
// replay) → nothing substantive changed. Distinct from a success: such a
|
|
528
579
|
// run must never be reported as ok, or the audit claims work that never
|
|
529
580
|
// happened and the scheduler refreshes the baseline on a false positive.
|
|
530
|
-
|
|
581
|
+
// Frozen conflicts are substantive output (parked for review), so a run
|
|
582
|
+
// that only froze conflicts is not a noop.
|
|
583
|
+
const noChange = frozenCount === 0 && applied === 0 && committed.every((c) => c.action === "keep");
|
|
531
584
|
|
|
532
585
|
// Keep the vector index consistent with the post-dream store state.
|
|
533
586
|
if (semantic?.embedder && semantic?.vectorIndex) {
|
|
534
587
|
try {
|
|
535
|
-
await maintainIndexAfterDream(
|
|
588
|
+
await maintainIndexAfterDream(applyList, service, semantic);
|
|
536
589
|
} catch (error) {
|
|
537
590
|
logger?.warn?.(`[dsh-mneme] dream index maintenance failed: ${String(error)}`);
|
|
538
591
|
}
|
|
@@ -554,7 +607,7 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
|
|
|
554
607
|
});
|
|
555
608
|
} catch (error) {
|
|
556
609
|
logger?.warn?.(`dsh-mneme dream: summary llm call failed: ${String(error)}`);
|
|
557
|
-
return finish({ ok: false, error: "llm failed", applied, decisions: auditDecisions, outcome, summary: false });
|
|
610
|
+
return finish({ ok: false, error: "llm failed", applied, decisions: auditDecisions, outcome, frozen: frozenCount, summary: false });
|
|
558
611
|
}
|
|
559
612
|
let summaryStored = false;
|
|
560
613
|
if (summaryText !== undefined && summaryText.trim()) {
|
|
@@ -601,6 +654,7 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
|
|
|
601
654
|
outcome,
|
|
602
655
|
conflicts,
|
|
603
656
|
failures,
|
|
657
|
+
frozen: frozenCount,
|
|
604
658
|
summary: summaryStored
|
|
605
659
|
});
|
|
606
660
|
}
|
package/src/service.js
CHANGED
|
@@ -479,6 +479,12 @@ export function createService({ store, mirror, config, onWrite }) {
|
|
|
479
479
|
// audit write, never a write-hook-triggering memory mutation).
|
|
480
480
|
saveReceipt: (r) => store.saveReceipt(r),
|
|
481
481
|
getReceipt: (id) => store.getReceipt(id),
|
|
482
|
-
listReceipts: (opts) => store.listReceipts(opts)
|
|
482
|
+
listReceipts: (opts) => store.listReceipts(opts),
|
|
483
|
+
// Conflict freeze bookkeeping (same semantics as the audit passthroughs
|
|
484
|
+
// above: an audit write, never a write-hook-triggering memory mutation).
|
|
485
|
+
saveConflictPending: (r) => store.saveConflictPending(r),
|
|
486
|
+
listConflictPending: (opts) => store.listConflictPending(opts),
|
|
487
|
+
resolveConflictPending: (id, o) => store.resolveConflictPending(id, o),
|
|
488
|
+
countConflictPending: () => store.countConflictPending()
|
|
483
489
|
};
|
|
484
490
|
}
|
package/src/store.js
CHANGED
|
@@ -100,6 +100,24 @@ CREATE TABLE IF NOT EXISTS receipt_chain (
|
|
|
100
100
|
);
|
|
101
101
|
CREATE INDEX IF NOT EXISTS idx_receipt_chain_record ON receipt_chain(record_id);
|
|
102
102
|
CREATE INDEX IF NOT EXISTS idx_receipt_chain_run ON receipt_chain(run_id);
|
|
103
|
+
|
|
104
|
+
-- conflict_pending: conflicts parked for manual review (conflict freeze mode,
|
|
105
|
+
-- opt-in via config.conflictFreezeEnabled). When enabled, the dream layer does
|
|
106
|
+
-- NOT auto-adjudicate winner/loser — the conflicting pair is parked here until
|
|
107
|
+
-- a human reviews it. resolveConflictPending stamps resolved_at (plus the chosen
|
|
108
|
+
-- winner) so the review action stays auditable. Like the other audit tables this
|
|
109
|
+
-- is bookkeeping: it never triggers write hooks.
|
|
110
|
+
CREATE TABLE IF NOT EXISTS conflict_pending (
|
|
111
|
+
id TEXT PRIMARY KEY,
|
|
112
|
+
run_id TEXT,
|
|
113
|
+
memory_a TEXT NOT NULL,
|
|
114
|
+
memory_b TEXT NOT NULL,
|
|
115
|
+
reason TEXT,
|
|
116
|
+
created_at TEXT NOT NULL,
|
|
117
|
+
resolved_at TEXT,
|
|
118
|
+
resolved_winner TEXT
|
|
119
|
+
);
|
|
120
|
+
CREATE INDEX IF NOT EXISTS idx_conflict_pending_unresolved ON conflict_pending(resolved_at);
|
|
103
121
|
`;
|
|
104
122
|
|
|
105
123
|
const TYPES = new Set(["preference", "project", "decision", "history", "summary"]);
|
|
@@ -183,6 +201,20 @@ function toReceipt(row) {
|
|
|
183
201
|
};
|
|
184
202
|
}
|
|
185
203
|
|
|
204
|
+
function toConflictPending(row) {
|
|
205
|
+
if (!row) return undefined;
|
|
206
|
+
return {
|
|
207
|
+
id: row.id,
|
|
208
|
+
run_id: row.run_id ?? undefined,
|
|
209
|
+
memory_a: row.memory_a,
|
|
210
|
+
memory_b: row.memory_b,
|
|
211
|
+
reason: row.reason ?? undefined,
|
|
212
|
+
created_at: row.created_at,
|
|
213
|
+
resolved_at: row.resolved_at ?? undefined,
|
|
214
|
+
resolved_winner: row.resolved_winner ?? undefined
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
186
218
|
function toRecallRun(row) {
|
|
187
219
|
if (!row) return undefined;
|
|
188
220
|
return {
|
|
@@ -702,6 +734,66 @@ export function createStore(path) {
|
|
|
702
734
|
return db.prepare("DELETE FROM failure_memories WHERE created_at < ?").run(before).changes;
|
|
703
735
|
}
|
|
704
736
|
|
|
737
|
+
// --- conflict freeze: pending manual review ------------------------------
|
|
738
|
+
|
|
739
|
+
/**
|
|
740
|
+
* Park a detected conflict for human review (conflict freeze mode). The pair
|
|
741
|
+
* order is normalized (sorted by id) so the same two memories are only ever
|
|
742
|
+
* pending once — a re-detection in a later dream run is a no-op, never a
|
|
743
|
+
* duplicate queue entry. Returns the pending row (freshly inserted, or the
|
|
744
|
+
* existing unresolved row when the pair is already pending).
|
|
745
|
+
*/
|
|
746
|
+
function saveConflictPending({ run_id, memory_a, memory_b, reason }) {
|
|
747
|
+
const [a, b] = [memory_a, memory_b].sort();
|
|
748
|
+
const existing = db.prepare(
|
|
749
|
+
"SELECT * FROM conflict_pending WHERE memory_a = ? AND memory_b = ? AND resolved_at IS NULL LIMIT 1"
|
|
750
|
+
).get(a, b);
|
|
751
|
+
if (existing) return toConflictPending(existing);
|
|
752
|
+
const id = randomUUID();
|
|
753
|
+
const now = nowIso();
|
|
754
|
+
db.prepare(
|
|
755
|
+
`INSERT INTO conflict_pending (id, run_id, memory_a, memory_b, reason, created_at)
|
|
756
|
+
VALUES (?, ?, ?, ?, ?, ?)`
|
|
757
|
+
).run(id, run_id ?? null, a, b, reason ?? null, now);
|
|
758
|
+
return toConflictPending(db.prepare("SELECT * FROM conflict_pending WHERE id = ?").get(id));
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
/**
|
|
762
|
+
* List pending conflicts, newest first. Unresolved rows only by default;
|
|
763
|
+
* pass includeResolved to include resolved ones (audit view).
|
|
764
|
+
*/
|
|
765
|
+
function listConflictPending({ limit = 50, offset = 0, includeResolved = false } = {}) {
|
|
766
|
+
const { limit: lim, offset: off } = sanitizePage(limit, offset, 50);
|
|
767
|
+
const clauses = [];
|
|
768
|
+
const params = [];
|
|
769
|
+
if (!includeResolved) clauses.push("resolved_at IS NULL");
|
|
770
|
+
const where = clauses.length ? `WHERE ${clauses.join(" AND ")}` : "";
|
|
771
|
+
const rows = db.prepare(
|
|
772
|
+
`SELECT * FROM conflict_pending ${where} ORDER BY created_at DESC, id LIMIT ? OFFSET ?`
|
|
773
|
+
).all(...params, lim, off);
|
|
774
|
+
return rows.map(toConflictPending);
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/**
|
|
778
|
+
* Mark a pending conflict as reviewed. winner (optional) records which side
|
|
779
|
+
* the human chose, keeping the resolution auditable. Returns the updated row,
|
|
780
|
+
* or undefined for an unknown id.
|
|
781
|
+
*/
|
|
782
|
+
function resolveConflictPending(id, { winner } = {}) {
|
|
783
|
+
const row = db.prepare("SELECT * FROM conflict_pending WHERE id = ?").get(id);
|
|
784
|
+
if (!row) return undefined;
|
|
785
|
+
db.prepare("UPDATE conflict_pending SET resolved_at = ?, resolved_winner = ? WHERE id = ?")
|
|
786
|
+
.run(nowIso(), winner ?? null, id);
|
|
787
|
+
return toConflictPending(db.prepare("SELECT * FROM conflict_pending WHERE id = ?").get(id));
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
/** Number of unresolved (awaiting review) pending conflicts. */
|
|
791
|
+
function countConflictPending() {
|
|
792
|
+
return db.prepare(
|
|
793
|
+
"SELECT count(*) AS c FROM conflict_pending WHERE resolved_at IS NULL"
|
|
794
|
+
).get().c;
|
|
795
|
+
}
|
|
796
|
+
|
|
705
797
|
function getFailureStats({ since } = {}) {
|
|
706
798
|
const clause = since ? "WHERE created_at >= ?" : "";
|
|
707
799
|
const params = since ? [since] : [];
|
|
@@ -744,6 +836,10 @@ export function createStore(path) {
|
|
|
744
836
|
listFailures,
|
|
745
837
|
getFailureStats,
|
|
746
838
|
deleteOldFailures,
|
|
839
|
+
saveConflictPending,
|
|
840
|
+
listConflictPending,
|
|
841
|
+
resolveConflictPending,
|
|
842
|
+
countConflictPending,
|
|
747
843
|
close() {
|
|
748
844
|
db.close();
|
|
749
845
|
}
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { Config } from "../src/config.js";
|
|
4
|
+
import { createStore } from "../src/store.js";
|
|
5
|
+
import { createService } from "../src/service.js";
|
|
6
|
+
import { createDreamScheduler } from "../src/dream.js";
|
|
7
|
+
|
|
8
|
+
// ---------------------------------------------------------------------------
|
|
9
|
+
// conflict freeze (冲突冻结) — 测试用例由 Kimi K2.7 设计,覆盖 config/store/
|
|
10
|
+
// service/dream 单测 + runDream 端到端(mock LLM 输出 conflict)。
|
|
11
|
+
// 核心约定:freeze 默认关闭(自动裁决行为完全不变);开启后 conflict 不自动
|
|
12
|
+
// 裁决、存入 conflict_pending 待人工确认,outcome 标 conflict-pending。
|
|
13
|
+
// ---------------------------------------------------------------------------
|
|
14
|
+
|
|
15
|
+
// ---------------------------------------------------------------- config
|
|
16
|
+
|
|
17
|
+
test("config: conflictFreezeEnabled 默认关闭", () => {
|
|
18
|
+
const cfg = Config({});
|
|
19
|
+
assert.equal(cfg.conflictFreezeEnabled, false, "freeze 默认不开启");
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
test("config: conflictFreezeEnabled 可显式开启", () => {
|
|
23
|
+
const cfg = Config({ conflictFreezeEnabled: true });
|
|
24
|
+
assert.equal(cfg.conflictFreezeEnabled, true);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
test("config: conflictFreezeMaxPending 默认为 100 且为整数", () => {
|
|
28
|
+
const cfg = Config({});
|
|
29
|
+
assert.equal(cfg.conflictFreezeMaxPending, 100);
|
|
30
|
+
assert.ok(Number.isInteger(cfg.conflictFreezeMaxPending));
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test("config: conflictFreezeMaxPending 可显式覆盖", () => {
|
|
34
|
+
const cfg = Config({ conflictFreezeMaxPending: 5 });
|
|
35
|
+
assert.equal(cfg.conflictFreezeMaxPending, 5);
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test("config: freeze 配置项不影响其它字段", () => {
|
|
39
|
+
const base = Config({});
|
|
40
|
+
const tuned = Config({ conflictFreezeEnabled: true, conflictFreezeMaxPending: 7 });
|
|
41
|
+
assert.equal(tuned.rerankEnabled, base.rerankEnabled, "rerank 不受影响");
|
|
42
|
+
assert.equal(tuned.autoDream, base.autoDream, "autoDream 不受影响");
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
// ---------------------------------------------------------------- store
|
|
46
|
+
|
|
47
|
+
function openStore() {
|
|
48
|
+
return createStore(":memory:");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
test("store: saveConflictPending 插入后 listConflictPending 读回", () => {
|
|
52
|
+
const store = openStore();
|
|
53
|
+
const pending = store.saveConflictPending({ run_id: "run-1", memory_a: "a", memory_b: "b", reason: "日期矛盾" });
|
|
54
|
+
assert.ok(pending.id, "有 id");
|
|
55
|
+
assert.equal(pending.run_id, "run-1");
|
|
56
|
+
assert.equal(pending.reason, "日期矛盾");
|
|
57
|
+
assert.ok(pending.created_at, "有 created_at");
|
|
58
|
+
assert.equal(pending.resolved_at, undefined, "未决行没有 resolved_at");
|
|
59
|
+
|
|
60
|
+
const list = store.listConflictPending();
|
|
61
|
+
assert.equal(list.length, 1);
|
|
62
|
+
assert.ok([list[0].memory_a, list[0].memory_b].includes("a"), "pair 包含双方");
|
|
63
|
+
assert.ok([list[0].memory_a, list[0].memory_b].includes("b"));
|
|
64
|
+
store.close();
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test("store: 对序归一化去重 —— 同一对不管顺序只存一次", () => {
|
|
68
|
+
const store = openStore();
|
|
69
|
+
const p1 = store.saveConflictPending({ memory_a: "a", memory_b: "b", reason: "r1" });
|
|
70
|
+
const p2 = store.saveConflictPending({ memory_a: "b", memory_b: "a", reason: "r2" });
|
|
71
|
+
assert.equal(p2.id, p1.id, "反序重报返回同一条 pending");
|
|
72
|
+
assert.equal(p2.reason, "r1", "保留首次 reason");
|
|
73
|
+
assert.equal(store.countConflictPending(), 1, "绝不重复入队");
|
|
74
|
+
store.close();
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
test("store: 不同对不去重", () => {
|
|
78
|
+
const store = openStore();
|
|
79
|
+
store.saveConflictPending({ memory_a: "a", memory_b: "b", reason: "ab" });
|
|
80
|
+
store.saveConflictPending({ memory_a: "a", memory_b: "c", reason: "ac" });
|
|
81
|
+
assert.equal(store.countConflictPending(), 2);
|
|
82
|
+
store.close();
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test("store: resolveConflictPending 标 resolved + winner,默认列表不再返回", () => {
|
|
86
|
+
const store = openStore();
|
|
87
|
+
const pending = store.saveConflictPending({ memory_a: "a", memory_b: "b", reason: "r" });
|
|
88
|
+
const resolved = store.resolveConflictPending(pending.id, { winner: "a" });
|
|
89
|
+
assert.ok(resolved.resolved_at, "resolved_at 已盖章");
|
|
90
|
+
assert.equal(resolved.resolved_winner, "a");
|
|
91
|
+
assert.equal(store.listConflictPending().length, 0, "已解决默认排除");
|
|
92
|
+
const all = store.listConflictPending({ includeResolved: true });
|
|
93
|
+
assert.equal(all.length, 1, "includeResolved 可见");
|
|
94
|
+
assert.equal(all[0].resolved_winner, "a");
|
|
95
|
+
store.close();
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test("store: resolveConflictPending 未知 id 返回 undefined", () => {
|
|
99
|
+
const store = openStore();
|
|
100
|
+
assert.equal(store.resolveConflictPending("ghost"), undefined);
|
|
101
|
+
store.close();
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test("store: countConflictPending 只统计未决行", () => {
|
|
105
|
+
const store = openStore();
|
|
106
|
+
store.saveConflictPending({ memory_a: "a", memory_b: "b", reason: "ab" });
|
|
107
|
+
const p2 = store.saveConflictPending({ memory_a: "b", memory_b: "c", reason: "bc" });
|
|
108
|
+
assert.equal(store.countConflictPending(), 2);
|
|
109
|
+
store.resolveConflictPending(p2.id, { winner: "b" });
|
|
110
|
+
assert.equal(store.countConflictPending(), 1, "已解决不再计入");
|
|
111
|
+
store.close();
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test("store: 已解决的同一对后续可再次 pending", () => {
|
|
115
|
+
const store = openStore();
|
|
116
|
+
const p1 = store.saveConflictPending({ memory_a: "a", memory_b: "b", reason: "r" });
|
|
117
|
+
store.resolveConflictPending(p1.id, { winner: "a" });
|
|
118
|
+
// 去重只看未决行 —— 已解决后再现同一对应产生新 pending
|
|
119
|
+
const p2 = store.saveConflictPending({ memory_a: "b", memory_b: "a", reason: "again" });
|
|
120
|
+
assert.notEqual(p2.id, p1.id, "已解决行不参与去重");
|
|
121
|
+
assert.equal(p2.resolved_at, undefined);
|
|
122
|
+
assert.equal(store.countConflictPending(), 1);
|
|
123
|
+
store.close();
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
// ---------------------------------------------------------------- service passthrough
|
|
127
|
+
|
|
128
|
+
function openService() {
|
|
129
|
+
const store = createStore(":memory:");
|
|
130
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
131
|
+
return { store, service };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
test("service: 4 个 conflict freeze passthrough 委托到 store", () => {
|
|
135
|
+
const { store, service } = openService();
|
|
136
|
+
const saved = service.saveConflictPending({ run_id: "run-1", memory_a: "a", memory_b: "b", reason: "r" });
|
|
137
|
+
assert.equal(store.countConflictPending(), 1, "save 落到 store");
|
|
138
|
+
assert.equal(service.countConflictPending(), 1, "count 读回一致");
|
|
139
|
+
assert.equal(service.listConflictPending().length, 1, "list 读回一致");
|
|
140
|
+
const resolved = service.resolveConflictPending(saved.id, { winner: "a" });
|
|
141
|
+
assert.ok(resolved.resolved_at, "resolve 落到 store");
|
|
142
|
+
assert.equal(service.listConflictPending().length, 0, "已解决从默认列表消失");
|
|
143
|
+
store.close();
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
test("service: passthrough 透传 store 异常", () => {
|
|
147
|
+
const { store, service } = openService();
|
|
148
|
+
const original = store.countConflictPending;
|
|
149
|
+
store.countConflictPending = () => { throw new Error("db boom"); };
|
|
150
|
+
assert.throws(() => service.countConflictPending(), /db boom/);
|
|
151
|
+
store.countConflictPending = original;
|
|
152
|
+
store.close();
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
// ---------------------------------------------------------------- dream: runDream 端到端
|
|
156
|
+
|
|
157
|
+
function dreamSetup() {
|
|
158
|
+
const store = createStore(":memory:");
|
|
159
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
160
|
+
return { store, service };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// mock LLM:第一次调用返回 consolidation decisions,第二次返回 summary。
|
|
164
|
+
function freezeCtx({ conflicts, includes = [], summaryText = "记忆库总览摘要" }) {
|
|
165
|
+
let calls = 0;
|
|
166
|
+
const warnings = [];
|
|
167
|
+
const ctx = {
|
|
168
|
+
warnings,
|
|
169
|
+
llm: {
|
|
170
|
+
stream: async function* () {
|
|
171
|
+
calls++;
|
|
172
|
+
const list = [...includes, ...conflicts];
|
|
173
|
+
yield { type: "text-delta", text: calls === 1 ? JSON.stringify(list) : summaryText };
|
|
174
|
+
yield { type: "finish", reason: { kind: "ok" } };
|
|
175
|
+
}
|
|
176
|
+
},
|
|
177
|
+
logger: { warn: (m) => warnings.push(m) }
|
|
178
|
+
};
|
|
179
|
+
return ctx;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const BASE_CONFIG = { dreamProvider: "deepseek", dreamModel: "deepseek-chat" };
|
|
183
|
+
|
|
184
|
+
test("dream: freeze=false(默认)conflict 仍自动裁决(回归)", async () => {
|
|
185
|
+
const { store, service } = dreamSetup();
|
|
186
|
+
const { memory: w } = service.saveWithDedupe({ type: "decision", title: "截止", content: "8月20日", importance: 4 });
|
|
187
|
+
const { memory: l } = service.saveWithDedupe({ type: "decision", title: "截止旧", content: "8月15日", importance: 4 });
|
|
188
|
+
const ctx = freezeCtx({ conflicts: [{ action: "conflict", winner: w.id, loser: l.id, reason: "日期更新" }] });
|
|
189
|
+
const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
|
|
190
|
+
const result = await dream.runDream(ctx, service, BASE_CONFIG);
|
|
191
|
+
assert.equal(result.ok, true);
|
|
192
|
+
assert.equal(result.applied, 1, "conflict 被自动裁决");
|
|
193
|
+
assert.equal(result.frozen, 0, "无冻结");
|
|
194
|
+
assert.equal(store.getById(l.id).archived, true, "loser 被归档");
|
|
195
|
+
assert.ok(store.getById(w.id).content.includes("已否决旧信息"), "winner 附带来源批注");
|
|
196
|
+
assert.equal(store.listConflictPending().length, 0, "freeze 关闭不产生 pending");
|
|
197
|
+
store.close();
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
test("dream: freeze=true conflict 不自动裁决、存入 pending、outcome 标 conflict-pending", async () => {
|
|
201
|
+
const { store, service } = dreamSetup();
|
|
202
|
+
const { memory: w } = service.saveWithDedupe({ type: "decision", title: "截止", content: "8月20日", importance: 4 });
|
|
203
|
+
const { memory: l } = service.saveWithDedupe({ type: "decision", title: "截止旧", content: "8月15日", importance: 4 });
|
|
204
|
+
const ctx = freezeCtx({ conflicts: [{ action: "conflict", winner: w.id, loser: l.id, reason: "日期更新,候选取新" }] });
|
|
205
|
+
const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
|
|
206
|
+
const result = await dream.runDream(ctx, service, { ...BASE_CONFIG, conflictFreezeEnabled: true });
|
|
207
|
+
assert.equal(result.ok, true);
|
|
208
|
+
assert.equal(result.applied, 0, "conflict 未被应用");
|
|
209
|
+
assert.equal(result.frozen, 1, "1 个 conflict 被冻结");
|
|
210
|
+
const pending = store.listConflictPending();
|
|
211
|
+
assert.equal(pending.length, 1, "pending 记录写入");
|
|
212
|
+
assert.equal(pending[0].reason, "日期更新,候选取新");
|
|
213
|
+
assert.equal(store.getById(l.id).archived, false, "loser 未归档");
|
|
214
|
+
assert.equal(store.getById(w.id).archived, false, "winner 未归档");
|
|
215
|
+
assert.ok(!store.getById(w.id).content.includes("已否决旧信息"), "无来源批注");
|
|
216
|
+
const run = store.listDreamRuns()[0];
|
|
217
|
+
assert.equal(run.outcome.byId[w.id], "conflict-pending", "audit outcome 标记双方 pending");
|
|
218
|
+
assert.equal(run.outcome.byId[l.id], "conflict-pending");
|
|
219
|
+
assert.equal(store.listReceipts().length, 0, "冻结 conflict 不写 per-record 收据");
|
|
220
|
+
store.close();
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
test("dream: freeze=true 非 conflict 决策照常执行,仅 conflict 冻结", async () => {
|
|
224
|
+
const { store, service } = dreamSetup();
|
|
225
|
+
const { memory: a } = service.saveWithDedupe({ type: "project", title: "插件", content: "旧", importance: 3 });
|
|
226
|
+
const { memory: b } = service.saveWithDedupe({ type: "project", title: "插件2", content: "新细节", importance: 4 });
|
|
227
|
+
const { memory: w } = service.saveWithDedupe({ type: "decision", title: "截止", content: "8月20日", importance: 4 });
|
|
228
|
+
const { memory: l } = service.saveWithDedupe({ type: "decision", title: "截止旧", content: "8月15日", importance: 4 });
|
|
229
|
+
const ctx = freezeCtx({
|
|
230
|
+
includes: [{ action: "merge", ids: [a.id, b.id], title: "插件总览", content: "合并内容", importance: 5, keepSource: b.id }],
|
|
231
|
+
conflicts: [{ action: "conflict", winner: w.id, loser: l.id, reason: "日期更新" }]
|
|
232
|
+
});
|
|
233
|
+
const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
|
|
234
|
+
const result = await dream.runDream(ctx, service, { ...BASE_CONFIG, conflictFreezeEnabled: true });
|
|
235
|
+
assert.equal(result.applied, 1, "merge 正常应用");
|
|
236
|
+
assert.equal(result.frozen, 1, "conflict 被冻结");
|
|
237
|
+
assert.equal(store.getById(b.id).title, "插件总览", "merge keeper 已更新");
|
|
238
|
+
assert.equal(store.getById(a.id).archived, true, "merge 源已归档");
|
|
239
|
+
assert.equal(store.getById(l.id).archived, false, "conflict loser 未被本次运行触碰");
|
|
240
|
+
assert.equal(store.listConflictPending().length, 1);
|
|
241
|
+
store.close();
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
test("dream: freeze=true 超过 conflictFreezeMaxPending 上限跳过(不抛错)", async () => {
|
|
245
|
+
const { store, service } = dreamSetup();
|
|
246
|
+
const { memory: w } = service.saveWithDedupe({ type: "decision", title: "截止", content: "8月20日", importance: 4 });
|
|
247
|
+
const { memory: l } = service.saveWithDedupe({ type: "decision", title: "截止旧", content: "8月15日", importance: 4 });
|
|
248
|
+
const ctx = freezeCtx({ conflicts: [{ action: "conflict", winner: w.id, loser: l.id, reason: "x" }] });
|
|
249
|
+
const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
|
|
250
|
+
const result = await dream.runDream(ctx, service, {
|
|
251
|
+
...BASE_CONFIG, conflictFreezeEnabled: true, conflictFreezeMaxPending: 0
|
|
252
|
+
});
|
|
253
|
+
assert.equal(result.frozen, 0, "容量 0 时无冻结");
|
|
254
|
+
assert.equal(store.listConflictPending().length, 0, "无 pending 写入");
|
|
255
|
+
assert.ok(ctx.warnings.some((m) => m.includes("freeze queue full")), "超限警告已记录");
|
|
256
|
+
store.close();
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
test("dream: freeze=true 存 pending 失败 fail-safe 不阻断 run", async () => {
|
|
260
|
+
const { store, service } = dreamSetup();
|
|
261
|
+
const { memory: w } = service.saveWithDedupe({ type: "decision", title: "截止", content: "8月20日", importance: 4 });
|
|
262
|
+
const { memory: l } = service.saveWithDedupe({ type: "decision", title: "截止旧", content: "8月15日", importance: 4 });
|
|
263
|
+
service.saveConflictPending = () => { throw new Error("pending store boom"); };
|
|
264
|
+
service.countConflictPending = () => { throw new Error("count boom"); };
|
|
265
|
+
const ctx = freezeCtx({ conflicts: [{ action: "conflict", winner: w.id, loser: l.id, reason: "x" }] });
|
|
266
|
+
const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
|
|
267
|
+
const result = await dream.runDream(ctx, service, { ...BASE_CONFIG, conflictFreezeEnabled: true });
|
|
268
|
+
assert.equal(result.ok, true, "尽管 pending 存储失败,run 正常完成");
|
|
269
|
+
assert.equal(result.frozen, 0, "无冻结");
|
|
270
|
+
assert.ok(ctx.warnings.length >= 1, "freeze 失败已记录");
|
|
271
|
+
assert.equal(store.getById(l.id).archived, false, "记忆无副作用");
|
|
272
|
+
assert.equal(store.getById(w.id).content, "8月20日", "winner 未被改动");
|
|
273
|
+
store.close();
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
test("dream: freeze=true 同一对跨 run 去重 —— 只保留一条 pending", async () => {
|
|
277
|
+
const { store, service } = dreamSetup();
|
|
278
|
+
const { memory: w } = service.saveWithDedupe({ type: "decision", title: "截止", content: "8月20日", importance: 4 });
|
|
279
|
+
const { memory: l } = service.saveWithDedupe({ type: "decision", title: "截止旧", content: "8月15日", importance: 4 });
|
|
280
|
+
const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
|
|
281
|
+
const ctx = freezeCtx({ conflicts: [{ action: "conflict", winner: w.id, loser: l.id, reason: "日期矛盾" }] });
|
|
282
|
+
const r1 = await dream.runDream(ctx, service, { ...BASE_CONFIG, conflictFreezeEnabled: true });
|
|
283
|
+
// mock LLM 计数器按 run 重置:每次 runDream 用独立的 ctx
|
|
284
|
+
const ctx2 = freezeCtx({ conflicts: [{ action: "conflict", winner: w.id, loser: l.id, reason: "日期矛盾" }] });
|
|
285
|
+
const r2 = await dream.runDream(ctx2, service, { ...BASE_CONFIG, conflictFreezeEnabled: true });
|
|
286
|
+
assert.equal(r1.frozen, 1);
|
|
287
|
+
assert.equal(r2.frozen, 1, "每次 run 都检出并上报该对");
|
|
288
|
+
assert.equal(store.countConflictPending(), 1, "但队列只有一条 pending");
|
|
289
|
+
store.close();
|
|
290
|
+
});
|
package/test/dream.test.js
CHANGED
|
@@ -545,3 +545,129 @@ test("applyDecisions merge is atomic: a throwing archive step rolls back the kee
|
|
|
545
545
|
assert.ok(warnings.length >= 1, "failure logged");
|
|
546
546
|
store.close();
|
|
547
547
|
});
|
|
548
|
+
|
|
549
|
+
// --- conflict freeze: manual review instead of auto-adjudication ----------
|
|
550
|
+
|
|
551
|
+
function freezeCtx({ conflicts, includes = [], summaryText = "记忆库总览摘要" }) {
|
|
552
|
+
let calls = 0;
|
|
553
|
+
const warnings = [];
|
|
554
|
+
const ctx = {
|
|
555
|
+
warnings,
|
|
556
|
+
llm: {
|
|
557
|
+
stream: async function* () {
|
|
558
|
+
calls++;
|
|
559
|
+
const list = [...includes, ...conflicts];
|
|
560
|
+
yield { type: "text-delta", text: calls === 1 ? JSON.stringify(list) : summaryText };
|
|
561
|
+
yield { type: "finish", reason: { kind: "ok" } };
|
|
562
|
+
}
|
|
563
|
+
},
|
|
564
|
+
logger: { warn: (m) => warnings.push(m) }
|
|
565
|
+
};
|
|
566
|
+
return ctx;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
test("runDream with conflictFreezeEnabled parks conflicts instead of adjudicating", async () => {
|
|
570
|
+
const { store, service } = dreamSetup();
|
|
571
|
+
const { memory: w } = service.saveWithDedupe({ type: "decision", title: "截止", content: "8月20日", importance: 4 });
|
|
572
|
+
const { memory: l } = service.saveWithDedupe({ type: "decision", title: "截止旧", content: "8月15日", importance: 4 });
|
|
573
|
+
const ctx = freezeCtx({ conflicts: [{ action: "conflict", winner: w.id, loser: l.id, reason: "日期更新,候选取新" }] });
|
|
574
|
+
const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
|
|
575
|
+
const result = await dream.runDream(ctx, service, {
|
|
576
|
+
dreamProvider: "deepseek", dreamModel: "deepseek-chat", conflictFreezeEnabled: true
|
|
577
|
+
});
|
|
578
|
+
assert.equal(result.ok, true);
|
|
579
|
+
assert.equal(result.applied, 0, "no conflict applied");
|
|
580
|
+
assert.equal(result.frozen, 1, "one conflict frozen");
|
|
581
|
+
// pending row recorded for human review
|
|
582
|
+
const pending = store.listConflictPending();
|
|
583
|
+
assert.equal(pending.length, 1);
|
|
584
|
+
assert.equal(pending[0].reason, "日期更新,候选取新");
|
|
585
|
+
// neither side was auto-adjudicated
|
|
586
|
+
assert.equal(store.getById(l.id).archived, false, "loser NOT archived");
|
|
587
|
+
assert.equal(store.getById(w.id).archived, false, "winner NOT archived");
|
|
588
|
+
assert.ok(!store.getById(w.id).content.includes("已否决旧信息"), "no provenance note appended");
|
|
589
|
+
// audit outcome marks both sides pending
|
|
590
|
+
const run = store.listDreamRuns()[0];
|
|
591
|
+
assert.equal(run.outcome.byId[w.id], "conflict-pending");
|
|
592
|
+
assert.equal(run.outcome.byId[l.id], "conflict-pending");
|
|
593
|
+
assert.equal(run.status, "ok", "summary stored + freeze landed → ok");
|
|
594
|
+
assert.equal(store.listReceipts().length, 0, "no conflict receipt for a frozen (unapplied) conflict");
|
|
595
|
+
store.close();
|
|
596
|
+
});
|
|
597
|
+
|
|
598
|
+
test("runDream freeze keeps auto-adjudication when disabled (default)", async () => {
|
|
599
|
+
const { store, service } = dreamSetup();
|
|
600
|
+
const { memory: w } = service.saveWithDedupe({ type: "decision", title: "截止", content: "8月20日", importance: 4 });
|
|
601
|
+
const { memory: l } = service.saveWithDedupe({ type: "decision", title: "截止旧", content: "8月15日", importance: 4 });
|
|
602
|
+
const ctx = freezeCtx({ conflicts: [{ action: "conflict", winner: w.id, loser: l.id, reason: "更新" }] });
|
|
603
|
+
const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
|
|
604
|
+
const result = await dream.runDream(ctx, service, { dreamProvider: "deepseek", dreamModel: "deepseek-chat" });
|
|
605
|
+
assert.equal(result.ok, true);
|
|
606
|
+
assert.equal(result.applied, 1, "conflict auto-adjudicated when freeze is off");
|
|
607
|
+
assert.equal(result.frozen, 0);
|
|
608
|
+
assert.equal(store.getById(l.id).archived, true, "loser archived");
|
|
609
|
+
assert.ok(store.getById(w.id).content.includes("已否决旧信息"), "provenance note appended");
|
|
610
|
+
assert.equal(store.listConflictPending().length, 0, "no pending rows in auto mode");
|
|
611
|
+
store.close();
|
|
612
|
+
});
|
|
613
|
+
|
|
614
|
+
test("runDream freeze applies non-conflict decisions while parking conflicts", async () => {
|
|
615
|
+
const { store, service } = dreamSetup();
|
|
616
|
+
const { memory: a } = service.saveWithDedupe({ type: "project", title: "插件", content: "旧", importance: 3 });
|
|
617
|
+
const { memory: b } = service.saveWithDedupe({ type: "project", title: "插件2", content: "新细节", importance: 4 });
|
|
618
|
+
const { memory: w } = service.saveWithDedupe({ type: "decision", title: "截止", content: "8月20日", importance: 4 });
|
|
619
|
+
const { memory: l } = service.saveWithDedupe({ type: "decision", title: "截止旧", content: "8月15日", importance: 4 });
|
|
620
|
+
const ctx = freezeCtx({
|
|
621
|
+
includes: [{ action: "merge", ids: [a.id, b.id], title: "插件总览", content: "合并内容", importance: 5, keepSource: b.id }],
|
|
622
|
+
conflicts: [{ action: "conflict", winner: w.id, loser: l.id, reason: "日期更新" }]
|
|
623
|
+
});
|
|
624
|
+
const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
|
|
625
|
+
const result = await dream.runDream(ctx, service, {
|
|
626
|
+
dreamProvider: "deepseek", dreamModel: "deepseek-chat", conflictFreezeEnabled: true
|
|
627
|
+
});
|
|
628
|
+
assert.equal(result.ok, true);
|
|
629
|
+
assert.equal(result.applied, 1, "merge applied normally");
|
|
630
|
+
assert.equal(result.frozen, 1, "conflict frozen");
|
|
631
|
+
assert.equal(store.getById(b.id).title, "插件总览", "merge keeper updated");
|
|
632
|
+
assert.equal(store.getById(a.id).archived, true, "merge source archived");
|
|
633
|
+
assert.equal(store.getById(l.id).archived, false, "conflict loser untouched by the merge run");
|
|
634
|
+
const pending = store.listConflictPending();
|
|
635
|
+
assert.equal(pending.length, 1);
|
|
636
|
+
assert.ok(pending[0].reason.includes("日期更新"));
|
|
637
|
+
store.close();
|
|
638
|
+
});
|
|
639
|
+
|
|
640
|
+
test("runDream freeze respects conflictFreezeMaxPending cap and skips overflow", async () => {
|
|
641
|
+
const { store, service } = dreamSetup();
|
|
642
|
+
const { memory: w } = service.saveWithDedupe({ type: "decision", title: "截止", content: "8月20日", importance: 4 });
|
|
643
|
+
const { memory: l } = service.saveWithDedupe({ type: "decision", title: "截止旧", content: "8月15日", importance: 4 });
|
|
644
|
+
const ctx = freezeCtx({ conflicts: [{ action: "conflict", winner: w.id, loser: l.id, reason: "x" }] });
|
|
645
|
+
const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
|
|
646
|
+
const result = await dream.runDream(ctx, service, {
|
|
647
|
+
dreamProvider: "deepseek", dreamModel: "deepseek-chat",
|
|
648
|
+
conflictFreezeEnabled: true, conflictFreezeMaxPending: 0
|
|
649
|
+
});
|
|
650
|
+
assert.equal(result.frozen, 0, "nothing frozen at capacity");
|
|
651
|
+
assert.equal(store.listConflictPending().length, 0, "no pending rows");
|
|
652
|
+
assert.ok(ctx.warnings.some((m) => m.includes("freeze queue full")), "capacity warning logged");
|
|
653
|
+
store.close();
|
|
654
|
+
});
|
|
655
|
+
|
|
656
|
+
test("runDream freeze store failure never blocks the run (fail-safe)", async () => {
|
|
657
|
+
const { store, service } = dreamSetup();
|
|
658
|
+
const { memory: w } = service.saveWithDedupe({ type: "decision", title: "截止", content: "8月20日", importance: 4 });
|
|
659
|
+
const { memory: l } = service.saveWithDedupe({ type: "decision", title: "截止旧", content: "8月15日", importance: 4 });
|
|
660
|
+
service.saveConflictPending = () => { throw new Error("pending store boom"); };
|
|
661
|
+
service.countConflictPending = () => { throw new Error("count boom"); };
|
|
662
|
+
const ctx = freezeCtx({ conflicts: [{ action: "conflict", winner: w.id, loser: l.id, reason: "x" }] });
|
|
663
|
+
const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
|
|
664
|
+
const result = await dream.runDream(ctx, service, {
|
|
665
|
+
dreamProvider: "deepseek", dreamModel: "deepseek-chat", conflictFreezeEnabled: true
|
|
666
|
+
});
|
|
667
|
+
assert.equal(result.ok, true, "run completes despite freeze store failure");
|
|
668
|
+
assert.equal(result.frozen, 0, "nothing frozen");
|
|
669
|
+
assert.ok(ctx.warnings.length >= 1, "freeze failure logged");
|
|
670
|
+
assert.equal(store.getById(l.id).archived, false, "no side effects on memories");
|
|
671
|
+
assert.equal(store.getById(w.id).content, "8月20日", "winner untouched");
|
|
672
|
+
store.close();
|
|
673
|
+
});
|
package/test/store.test.js
CHANGED
|
@@ -291,3 +291,70 @@ test("compareAndUpdate on unknown id throws like update", () => {
|
|
|
291
291
|
assert.throws(() => store.compareAndUpdate("ghost", "any", { content: "x" }), /not found/);
|
|
292
292
|
store.close();
|
|
293
293
|
});
|
|
294
|
+
|
|
295
|
+
// --- conflict freeze: pending manual review -------------------------------
|
|
296
|
+
|
|
297
|
+
test("saveConflictPending inserts and listConflictPending excludes resolved by default", () => {
|
|
298
|
+
const store = openMemory();
|
|
299
|
+
const a = store.save({ type: "decision", title: "截止", content: "8月20日", importance: 4 });
|
|
300
|
+
const b = store.save({ type: "decision", title: "截止旧", content: "8月15日", importance: 4 });
|
|
301
|
+
const pending = store.saveConflictPending({ run_id: "run-1", memory_a: a.id, memory_b: b.id, reason: "日期更新" });
|
|
302
|
+
assert.ok(pending.id, "has id");
|
|
303
|
+
assert.equal(pending.run_id, "run-1");
|
|
304
|
+
assert.equal(pending.reason, "日期更新");
|
|
305
|
+
assert.ok(pending.created_at);
|
|
306
|
+
assert.equal(pending.resolved_at, undefined);
|
|
307
|
+
|
|
308
|
+
const list = store.listConflictPending();
|
|
309
|
+
assert.equal(list.length, 1);
|
|
310
|
+
assert.ok([list[0].memory_a, list[0].memory_b].includes(a.id), "pair holds both sides");
|
|
311
|
+
assert.ok([list[0].memory_a, list[0].memory_b].includes(b.id));
|
|
312
|
+
|
|
313
|
+
const resolved = store.resolveConflictPending(pending.id, { winner: a.id });
|
|
314
|
+
assert.ok(resolved.resolved_at, "resolution stamped");
|
|
315
|
+
assert.equal(resolved.resolved_winner, a.id);
|
|
316
|
+
assert.equal(store.listConflictPending().length, 0, "resolved excluded by default");
|
|
317
|
+
const all = store.listConflictPending({ includeResolved: true });
|
|
318
|
+
assert.equal(all.length, 1, "resolved visible with includeResolved");
|
|
319
|
+
assert.equal(all[0].resolved_winner, a.id);
|
|
320
|
+
store.close();
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
test("saveConflictPending dedupes the same pair regardless of order", () => {
|
|
324
|
+
const store = openMemory();
|
|
325
|
+
const a = store.save({ type: "decision", title: "截止", content: "x" });
|
|
326
|
+
const b = store.save({ type: "decision", title: "截止2", content: "y" });
|
|
327
|
+
const p1 = store.saveConflictPending({ memory_a: a.id, memory_b: b.id, reason: "r1" });
|
|
328
|
+
const p2 = store.saveConflictPending({ memory_a: b.id, memory_b: a.id, reason: "r2" });
|
|
329
|
+
assert.equal(p2.id, p1.id, "same pair re-detected returns the existing pending row");
|
|
330
|
+
assert.equal(p2.reason, "r1", "original reason preserved");
|
|
331
|
+
assert.equal(store.listConflictPending().length, 1, "never a duplicate queue entry");
|
|
332
|
+
store.close();
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
test("countConflictPending counts unresolved rows only; resolve unknown id is undefined", () => {
|
|
336
|
+
const store = openMemory();
|
|
337
|
+
const a = store.save({ type: "decision", title: "a", content: "x" });
|
|
338
|
+
const b = store.save({ type: "decision", title: "b", content: "y" });
|
|
339
|
+
const c = store.save({ type: "decision", title: "c", content: "z" });
|
|
340
|
+
store.saveConflictPending({ memory_a: a.id, memory_b: b.id, reason: "ab" });
|
|
341
|
+
const p2 = store.saveConflictPending({ memory_a: b.id, memory_b: c.id, reason: "bc" });
|
|
342
|
+
assert.equal(store.countConflictPending(), 2);
|
|
343
|
+
store.resolveConflictPending(p2.id, { winner: b.id });
|
|
344
|
+
assert.equal(store.countConflictPending(), 1, "resolved no longer pending");
|
|
345
|
+
assert.equal(store.resolveConflictPending("ghost"), undefined, "unknown id resolves to undefined");
|
|
346
|
+
store.close();
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
test("conflict_pending table persists across store reopen", () => {
|
|
350
|
+
const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-conflict-"));
|
|
351
|
+
const path = join(dir, "memory.db");
|
|
352
|
+
const s1 = createStore(path);
|
|
353
|
+
s1.saveConflictPending({ run_id: "run-1", memory_a: "ma", memory_b: "mb", reason: "x" });
|
|
354
|
+
s1.close();
|
|
355
|
+
const s2 = createStore(path);
|
|
356
|
+
const pending = s2.listConflictPending();
|
|
357
|
+
assert.equal(pending.length, 1);
|
|
358
|
+
assert.equal(pending[0].reason, "x");
|
|
359
|
+
s2.close();
|
|
360
|
+
});
|