@modusensus/dsh-mneme 0.8.5 → 0.8.6

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.
@@ -408,3 +408,120 @@ test("issue#257 schema default for sleepMaxTokens is 8192 (was hardcoded 2048)",
408
408
  const cfg = Config({});
409
409
  assert.equal(cfg.sleepMaxTokens, 8192, "schema default covers the measured full-set peak (6967)");
410
410
  });
411
+
412
+ // ------------------------------------------- sleep LLM accounting (issue #250)
413
+ // Bug8 给 dream 与 summarize 接记账时漏了 sleep:src/dream/sleep.js 有一份自己的
414
+ // streamText,签名里没有 onUsage,两条 LLM 链路(conflict 裁决 / pattern 挖掘)的
415
+ // token 与状态从未进 llm_audit_logs——面板因此只看到两条链路,回答不了「sleep 花了
416
+ // 多少」。下面两条用例锁定「审计行落库 + token 数值来自 usage chunk」。
417
+ // 两条链路共用同一处 streamText 改动,故放在同一轮 red-green 里。
418
+
419
+ /** 在 base ctx 的流里、finish 之前插入一个 usage chunk(形态同 llm-audit.test.js)。 */
420
+ function withUsageChunk(base, usageChunk) {
421
+ return {
422
+ ...base,
423
+ llm: {
424
+ async *stream(options) {
425
+ for await (const chunk of base.llm.stream(options)) {
426
+ if (chunk.type === "finish") yield usageChunk;
427
+ yield chunk;
428
+ }
429
+ }
430
+ }
431
+ };
432
+ }
433
+
434
+ test("issue#250 sleep conflict phase writes an llm_audit row with the streamed tokens", async () => {
435
+ const { service, store, vectorIndex } = setup();
436
+ const { a, b } = seedConflictPair(service, vectorIndex, 1.0);
437
+ const ctx = withUsageChunk(
438
+ mockCtx(() => JSON.stringify([{ action: "conflict", winner: a.id, loser: b.id, reason: "重复覆盖" }])),
439
+ { type: "usage", usage: { inputTokens: 1200, outputTokens: 300, totalTokens: 1500 } }
440
+ );
441
+ const result = await runSleep(ctx, service, baseConfig(), ctx.logger, { embedder, vectorIndex }, null);
442
+ assert.equal(result.phases.conflicts.status, "ok", "conflict resolved");
443
+
444
+ const conflict = service.listLlmAudits({ source: "sleep" }).find((r) => r.operation_type === "sleep_conflict");
445
+ assert.ok(conflict, "sleep_conflict audit row present");
446
+ assert.equal(conflict.trigger_source, "sleep");
447
+ assert.equal(conflict.status, "success");
448
+ assert.equal(conflict.model_id, "mock:sleep-model", "route actually used is recorded");
449
+ assert.equal(conflict.input_tokens, 1200, "input tokens come from chunk.usage");
450
+ assert.equal(conflict.output_tokens, 300, "output tokens come from chunk.usage");
451
+ assert.equal(conflict.total_tokens, 1500);
452
+ assert.ok(typeof conflict.duration_ms === "number" && conflict.duration_ms >= 0);
453
+ store.close();
454
+ });
455
+
456
+ test("issue#250 sleep pattern phase writes an llm_audit row with the streamed tokens", async () => {
457
+ const { service, store } = setup();
458
+ const a = makeMemory(service, "模式A", "反复出现的模式A", "project");
459
+ const b = makeMemory(service, "模式B", "反复出现的模式B", "project");
460
+ const ctx = withUsageChunk(
461
+ mockCtx(() => JSON.stringify([
462
+ { action: "create", type: "pattern", title: "真模式", content: "从 a 和 b 提取", importance: 3, evidence: [a.id, b.id] }
463
+ ])),
464
+ { type: "usage", usage: { inputTokens: 900, outputTokens: 250, totalTokens: 1150 } }
465
+ );
466
+ const result = await runSleep(ctx, service, baseConfig({ sleepPatternMinMemories: 10 }), ctx.logger, null, null);
467
+ assert.ok(result.phases.patterns, "pattern phase ran");
468
+
469
+ const pattern = service.listLlmAudits({ source: "sleep" }).find((r) => r.operation_type === "sleep_pattern");
470
+ assert.ok(pattern, "sleep_pattern audit row present");
471
+ assert.equal(pattern.trigger_source, "sleep");
472
+ assert.equal(pattern.status, "success");
473
+ assert.equal(pattern.input_tokens, 900, "input tokens come from chunk.usage");
474
+ assert.equal(pattern.output_tokens, 250, "output tokens come from chunk.usage");
475
+ assert.equal(pattern.total_tokens, 1150);
476
+ store.close();
477
+ });
478
+
479
+ // 审计诚实性(issue #250):流式成功但输出里没有 JSON 数组时,phase 报 failed,
480
+ // 审计行也必须记 error——不能一个调用在两表里自相矛盾。
481
+ test("issue#250 sleep conflict parse failure is audited as status=error, not fake success", async () => {
482
+ const { service, store, vectorIndex } = setup();
483
+ const { a, b } = seedConflictPair(service, vectorIndex, 1.0);
484
+ const ctx = mockCtx(() => "抱歉,我无法把裁决整理成 JSON。");
485
+ const result = await runSleep(ctx, service, baseConfig(), ctx.logger, { embedder, vectorIndex }, null);
486
+ assert.equal(result.phases.conflicts.status, "failed", "the phase reports the failure");
487
+
488
+ const row = service.listLlmAudits({ source: "sleep" }).find((r) => r.operation_type === "sleep_conflict");
489
+ assert.ok(row, "the failed call is still audited");
490
+ assert.equal(row.status, "error", "a stream that returned unusable output is not a success");
491
+ assert.match(row.error_message, /no json array in llm output/);
492
+ store.close();
493
+ });
494
+
495
+ test("issue#250 sleep pattern parse failure is audited as status=error, not fake success", async () => {
496
+ const { service, store } = setup();
497
+ makeMemory(service, "模式A", "反复出现的模式A", "project");
498
+ makeMemory(service, "模式B", "反复出现的模式B", "project");
499
+ const ctx = mockCtx(() => "这不是 JSON 数组");
500
+ const result = await runSleep(ctx, service, baseConfig({ sleepPatternMinMemories: 10 }), ctx.logger, null, null);
501
+ // pattern 阶段对不可解析输出的既定语义是 skipped("no patterns found")——那是
502
+ // 「有没有铸造出模式」的结论,不是「这次调用成没成功」的结论,此处不改上游语义。
503
+ assert.equal(result.phases.patterns.status, "skipped", "the phase keeps its existing semantics");
504
+
505
+ const row = service.listLlmAudits({ source: "sleep" }).find((r) => r.operation_type === "sleep_pattern");
506
+ assert.ok(row, "the call still consumed tokens and is still audited");
507
+ assert.equal(row.status, "error", "the audit records the call's truth, not the phase's conclusion");
508
+ assert.match(row.error_message, /no json array in llm output/);
509
+ store.close();
510
+ });
511
+
512
+ // 回归护栏:llmAudit.enabled === false 时 auditedSleepLlm 整段早退,auditError 钩子
513
+ // 不会被调用。所以两个 phase 的控制流必须各自解析输出、不能依赖那个钩子的副作用
514
+ // ——dream 的 runAuditedLlm 正是那样踩了(关掉审计 flag 会让 autoDream 直接失效)。
515
+ test("issue#250 sleep still adjudicates normally when llmAudit.enabled === false", async () => {
516
+ const { service, store, vectorIndex } = setup();
517
+ const { a, b } = seedConflictPair(service, vectorIndex, 1.0);
518
+ const ctx = mockCtx(() =>
519
+ JSON.stringify([{ action: "conflict", winner: a.id, loser: b.id, reason: "重复覆盖" }])
520
+ );
521
+ const config = baseConfig({ llmAudit: { enabled: false } });
522
+ const result = await runSleep(ctx, service, config, ctx.logger, { embedder, vectorIndex }, null);
523
+ assert.equal(result.phases.conflicts.status, "ok", "turning the audit off must not break sleep");
524
+ assert.equal(service.getById(b.id).archived, true, "the arbitration still applied");
525
+ assert.equal(service.listLlmAudits().length, 0, "no audit rows when disabled");
526
+ store.close();
527
+ });