dsh-memu-memory 1.2.7 → 1.2.8

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.
Files changed (49) hide show
  1. package/AGENTS.md +1 -1
  2. package/README.md +10 -15
  3. package/README.zh.md +10 -15
  4. package/docs/memory-semantics.md +23 -3
  5. package/lib/backup.js +1 -1
  6. package/lib/budget.js +31 -0
  7. package/lib/commitment.js +138 -0
  8. package/lib/consolidation-receipt.js +2 -0
  9. package/lib/consolidation-worker.js +3 -0
  10. package/lib/freshness.js +24 -0
  11. package/lib/inject.js +117 -10
  12. package/lib/lexicon.js +1 -1
  13. package/lib/local-vector-service.js +4 -1
  14. package/lib/memory.js +565 -32
  15. package/lib/memu.js +4 -0
  16. package/lib/private.js +5 -3
  17. package/lib/prompts/private-consolidation.mixed.md +2 -2
  18. package/lib/prompts/private-consolidation.rp.md +6 -1
  19. package/lib/prompts/private-policy.rp.md +4 -0
  20. package/lib/prompts/system-guide.rp.md +3 -0
  21. package/lib/recall-cache.js +10 -2
  22. package/lib/rpc.js +9 -2
  23. package/lib/snippet.js +25 -0
  24. package/lib/temporal.js +329 -0
  25. package/lib/text-retrieval.js +71 -0
  26. package/lib/tools.js +81 -4
  27. package/package.json +1 -1
  28. package/scripts/bench-recall.mjs +2 -2
  29. package/scripts/check-seed-compat.mjs +1 -1
  30. package/tests/backup.test.mjs +2 -2
  31. package/tests/commitment.test.mjs +144 -0
  32. package/tests/consolidation-fork.test.mjs +3 -3
  33. package/tests/disclosure.test.mjs +34 -17
  34. package/tests/fact-version.test.mjs +128 -0
  35. package/tests/help-page.test.mjs +1 -1
  36. package/tests/inject-conflict.test.mjs +94 -0
  37. package/tests/inject-guide.test.mjs +5 -3
  38. package/tests/inject.test.mjs +2 -2
  39. package/tests/injection-intent-budget.test.mjs +92 -0
  40. package/tests/lexicon-frequency.test.mjs +1 -1
  41. package/tests/memory-chain.test.mjs +140 -0
  42. package/tests/memory-fields.test.mjs +134 -0
  43. package/tests/memu-resident.test.mjs +33 -0
  44. package/tests/prompt-semantics.test.mjs +51 -0
  45. package/tests/query-decompose.test.mjs +62 -0
  46. package/tests/recall-cache.test.mjs +4 -2
  47. package/tests/recall-intent.test.mjs +100 -0
  48. package/tests/speaker-provenance.test.mjs +120 -0
  49. package/tests/temporal.test.mjs +124 -0
package/lib/tools.js CHANGED
@@ -275,15 +275,42 @@ export function registerTools(ctx, { only = null } = {}) {
275
275
  pin_reason: { type: 'string', description: 'Required for must_remember; first-person reason.' },
276
276
  pin_source: { type: 'string', description: 'user_explicit, side_event, or self.' },
277
277
  side_event_id: { type: 'string', description: 'Required when pin_source=side_event.' },
278
+ fact_key: { type: 'string', description: 'Optional stable key for the fact, such as "user:floor_color". Passing it declares that an existing active memory with the same key is another version of this fact; the new entry then becomes a conflict pair unless you pass supersedes.' },
279
+ conflicts_with: { type: 'string', description: 'Id of an existing memory that says something different about the same fact. Both versions stay active and are recalled together with a conflict card; use this instead of overwriting or deleting the old claim.' },
280
+ supersedes: { type: 'string', description: 'Id of an existing memory this new statement explicitly replaces. The old row keeps its text but is retired (superseded + valid_to). Use only when the newer statement really is the corrected truth.' },
278
281
  tags: { type: 'array', items: { type: 'string' }, description: 'Optional tags.' },
279
- open_loop: { type: 'boolean', description: 'Mark an unfinished promise/task/unsaid thing.' },
282
+ open_loop: { type: 'boolean', description: 'Mark an unfinished promise/task/unsaid thing. Prefer the commitment object; this boolean remains for compatibility and is kept in sync with commitment.status.' },
283
+ commitment: {
284
+ type: 'object',
285
+ properties: {
286
+ counterparty: { type: 'string' },
287
+ action: { type: 'string' },
288
+ due_at: { type: 'string' },
289
+ status: { type: 'string' },
290
+ closed_by: { type: 'string' },
291
+ evidence_seq: { type: 'integer' },
292
+ },
293
+ additionalProperties: false,
294
+ description: 'A promise or arrangement: counterparty (who it is with), action (what was promised), due_at (YYYY-MM-DD or ISO), status (open/done/cancelled/expired), closed_by / evidence_seq (proof of fulfilment). Use status=open only while it is still owed; update it when it is done or cancelled.',
295
+ },
280
296
  disclosure: { type: 'string', description: 'can_tell, only_if_asked, or never_say.' },
281
297
  owner: { type: 'string', description: 'me, us, about_user, or about_project.' },
282
298
  visibility: { type: 'string', description: 'shared (default: the whole folder) or secret (kept out of the prompt and out of automatic recall; still readable by an explicit recall from the same folder). Scope a memory to one channel / character / world / branch with the context field instead of trying to hide it.' },
283
299
  source: {
284
300
  type: 'string',
285
- description: 'Where this came from: inferred (default — you concluded it), user_said (only when the words are actually theirs and quotable), imagined, or told.',
301
+ description: 'Where this came from: inferred (default — you concluded it), user_said (only when the words are actually theirs and quotable), assistant_said (your own promise, plan or claim), imagined, told, or tool (read from a tool result).',
286
302
  },
303
+ source_kind: { type: 'string', description: 'Provenance detail: user_said, assistant_said, told, imagined, inferred, or tool. Defaults to source. Assistant promises and plans belong here; never file them as user_said.' },
304
+ speaker_id: { type: 'string', description: 'Stable identity of who said it: user, assistant, character:<id>, or group:<id>. Never infer from a display name. Defaults to the conversation speaker or user/assistant by source_kind.' },
305
+ quote_span: {
306
+ type: 'object',
307
+ properties: { seq: { type: 'integer' }, turn: { type: 'integer' }, textHash: { type: 'string' } },
308
+ additionalProperties: false,
309
+ description: 'Optional pointer back to the source turn: seq/turn numbers plus a short text hash. Do not paste the whole quote here.',
310
+ },
311
+ storyline_id: { type: 'string', description: 'Optional storyline / plot thread id when several stories share one library.' },
312
+ branch_id: { type: 'string', description: 'Optional branch id; defaults to the conversation branch.' },
313
+ known_by: { type: 'array', items: { type: 'string' }, description: 'Character identities that know this fact. Omit to inherit the conversation boundary.' },
287
314
  confidence: { type: 'number', description: '0-1 confidence in this memory. Below 0.45 it is injected as a hedge, so use it honestly.' },
288
315
  mood_valence: { type: 'number', description: '派生值:给了 emotion 时由四项算出,-1(坏)到 1(好)。省略则沿用当前会话读数。' },
289
316
  arousal: { type: 'number', description: 'How strongly it hit, 0-1.' },
@@ -298,6 +325,11 @@ export function registerTools(ctx, { only = null } = {}) {
298
325
  peak: { type: 'boolean', description: 'A high point or low point of the arc — peaks and endings stay easier to recall.' },
299
326
  allow_duplicate: { type: 'boolean', description: 'Only for two genuinely independent observations of the same fact (e.g. the same event recorded twice in one day). The default false refuses a near-identical rewrite and returns the existing memory id; passing true states you looked at that existing memory and still want a separate entry.' },
300
327
  salient_date: { type: 'string', description: 'MM-DD for something that comes back every year (a birthday, an anniversary of an event); it resurfaces on that day each year. YYYY-MM-DD for a one-off dated commitment or appointment: it is raised the day before and on the day itself, and never again after it has passed. Use the annual form only when the day really does recur. A relative day (今天/明天/后天/today/tomorrow) must be resolved to the absolute date it points at: sending a bare MM-DD turns one appointment into a yearly reminder. If the content itself names a date, pass it here too: when this field is empty the plugin only falls back to a single unambiguous YYYY-MM-DD found in the text.' },
328
+ observed_at: { type: 'string', description: 'ISO date/time when this statement was made (the scene time). Omit to use the conversation sceneTime. Relative dates are resolved against this instant, never against the wall clock.' },
329
+ absolute_date: { type: 'string', description: 'YYYY-MM-DD this memory is about, when you already know it. The plugin also resolves 今天/明天/下周X/月底 itself against observed_at; pass this only to override or when the wording has no parseable date.' },
330
+ valid_from: { type: 'string', description: 'Optional YYYY-MM-DD from which the fact is true. Omit for facts with no known start.' },
331
+ valid_to: { type: 'string', description: 'Optional YYYY-MM-DD after which the fact is no longer true. Omit for open-ended facts; the entry is hidden from recall after this day.' },
332
+ date_precision: { type: 'string', description: 'day (default for a concrete date), month (月底/下个月), year (年初/年底), or unknown (relative wording that could not be resolved).' },
301
333
  track: { type: 'string', description: 'memory (default) or habit for an aggregated expression/sticker habit; do not write one habit per occurrence.' },
302
334
  attachments: { type: 'array', items: { type: 'object', properties: { sha256: { type: 'string', required: true } }, additionalProperties: true }, description: 'At most 8 sha256 references received in this conversation. Never supply paths or bytes. Ordinary image memories default to short_term if layer is omitted; choose long_term explicitly only when important.' },
303
335
  context: { type: 'object', properties: {
@@ -319,10 +351,20 @@ export function registerTools(ctx, { only = null } = {}) {
319
351
  sideEventId: args.side_event_id,
320
352
  tags: args.tags,
321
353
  openLoop: args.open_loop,
354
+ commitment: args.commitment,
355
+ factKey: args.fact_key ?? null,
356
+ conflictsWith: args.conflicts_with ?? null,
357
+ supersedes: args.supersedes ?? null,
322
358
  disclosure: args.disclosure,
323
359
  owner: args.owner,
324
360
  visibility: args.visibility,
325
361
  source: args.source,
362
+ sourceKind: args.source_kind,
363
+ speakerId: args.speaker_id ?? null,
364
+ quoteSpan: args.quote_span ?? null,
365
+ storylineId: args.storyline_id,
366
+ branchId: args.branch_id,
367
+ knownBy: args.known_by,
326
368
  confidence: args.confidence,
327
369
  moodValence: args.mood_valence ?? null,
328
370
  arousal: args.arousal ?? null,
@@ -333,6 +375,11 @@ export function registerTools(ctx, { only = null } = {}) {
333
375
  dominance: args.dominance ?? null,
334
376
  peak: args.peak === true,
335
377
  salientDate: args.salient_date ?? null,
378
+ observedAt: args.observed_at ?? null,
379
+ absoluteDate: args.absolute_date ?? null,
380
+ validFrom: args.valid_from,
381
+ validTo: args.valid_to,
382
+ datePrecision: args.date_precision,
336
383
  allowDuplicate: args.allow_duplicate === true,
337
384
  })
338
385
  // 事实级去重:几乎相同的重写被拒,返回的是
@@ -424,6 +471,19 @@ export function registerTools(ctx, { only = null } = {}) {
424
471
  status: { type: 'string', description: 'active, archived, fragment, suppressed, or expired.' },
425
472
  layer: { type: 'string', description: 'long_term to promote a short_term draft once it has proven worth keeping, or short_term to re-arm the deadline. must_remember needs a pin_reason and is only writable through memu_private_remember.' },
426
473
  open_loop: { type: 'boolean' },
474
+ commitment: {
475
+ type: 'object',
476
+ properties: {
477
+ counterparty: { type: 'string' },
478
+ action: { type: 'string' },
479
+ due_at: { type: 'string' },
480
+ status: { type: 'string' },
481
+ closed_by: { type: 'string' },
482
+ evidence_seq: { type: 'integer' },
483
+ },
484
+ additionalProperties: false,
485
+ description: 'Replace the commitment object. Set status=done/cancelled/expired to close it; open_loop follows status.',
486
+ },
427
487
  disclosure: { type: 'string', description: 'can_tell, only_if_asked, or never_say. Changing this changes how the memory is phrased when it is injected.' },
428
488
  owner: { type: 'string', description: 'me, us, about_user, or about_project.' },
429
489
  visibility: { type: 'string', description: 'shared or secret. secret keeps it out of the prompt and out of automatic recall; an explicit recall from the same folder can still read it.' },
@@ -431,7 +491,13 @@ export function registerTools(ctx, { only = null } = {}) {
431
491
  // Provenance and track are claims about what a memory *is*; both were writable
432
492
  // in memory.js and the panel while staying unreachable from the tool surface,
433
493
  // so the agent could file a quote as an inference and never correct it.
434
- source: { type: 'string', description: 'user_said, inferred, imagined, or told. Only user_said may be repeated as the user\'s own words, so correct this rather than living with a wrong provenance.' },
494
+ source: { type: 'string', description: 'user_said, assistant_said, told, imagined, inferred, or tool. Only user_said may be repeated as the user\'s own words, so correct this rather than living with a wrong provenance.' },
495
+ source_kind: { type: 'string', description: 'Same values as source; correcting the provenance must keep this in sync.' },
496
+ speaker_id: { type: 'string', description: 'Who said it: user, assistant, character:<id>, or group:<id>. Empty string clears it.' },
497
+ quote_span: { type: 'object', properties: { seq: { type: 'integer' }, turn: { type: 'integer' }, textHash: { type: 'string' } }, additionalProperties: false, description: 'Pointer back to the source turn; omit to keep, null to clear.' },
498
+ storyline_id: { type: 'string', description: 'Storyline / plot thread id; empty string clears it.' },
499
+ branch_id: { type: 'string', description: 'Branch id; empty string clears it.' },
500
+ known_by: { type: 'array', items: { type: 'string' }, description: 'Character identities that know this fact; empty array clears it.' },
435
501
  track: { type: 'string', description: 'memory or habit. habit folds repeat attachments of the same fact into one entry; a wrong track changes that aggregation and can now be corrected.' },
436
502
  peak: { type: 'boolean', description: 'Flashbulb flag: the moment was charged. Changing it recomputes accuracy.' },
437
503
  mood_valence: { type: 'number', description: 'How the moment felt, -1..1. Used as a retrieval lens; omitted keeps the stored value.' },
@@ -444,18 +510,29 @@ export function registerTools(ctx, { only = null } = {}) {
444
510
  },
445
511
  dominance: { type: 'number', description: '谁在掌控:-1 完全失控 … +1 完全掌控。省略=保留原值。' },
446
512
  salient_date: { type: 'string', description: 'Re-date the memory: MM-DD for an annual anniversary, YYYY-MM-DD for a one-off dated commitment, or an empty string to remove the date. Use this to repair a date that was stored without its year.' },
513
+ observed_at: { type: 'string', description: 'ISO scene time for this edit; relative dates in the new text resolve against it. Omit to use the conversation sceneTime.' },
514
+ absolute_date: { type: 'string', description: 'YYYY-MM-DD this memory is about. Omit to re-derive from the new title/content; pass an empty string to clear it.' },
515
+ valid_from: { type: 'string', description: 'YYYY-MM-DD the fact starts being true; empty string clears it.' },
516
+ valid_to: { type: 'string', description: 'YYYY-MM-DD the fact stops being true; empty string clears it.' },
447
517
  },
448
518
  async (args, exec) => {
449
519
  const result = await privateUpdate({
450
520
  exec, id: args.id, content: args.content, title: args.title, tags: args.tags,
451
- status: args.status, openLoop: args.open_loop, disclosure: args.disclosure, confidence: args.confidence,
521
+ status: args.status, openLoop: args.open_loop, commitment: args.commitment, disclosure: args.disclosure, confidence: args.confidence,
452
522
  layer: args.layer, owner: args.owner, visibility: args.visibility,
453
523
  source: args.source, track: args.track, peak: args.peak,
524
+ sourceKind: args.source_kind, speakerId: args.speaker_id,
525
+ quoteSpan: args.quote_span, storylineId: args.storyline_id,
526
+ branchId: args.branch_id, knownBy: args.known_by,
454
527
  moodValence: args.mood_valence, arousal: args.arousal,
455
528
  // undefined 就是"省略",必须原样传下去;换成 null 会把保留变成清除。
456
529
  emotion: args.emotion, dominance: args.dominance,
457
530
  // Sentinel: absent means "leave the date as it is", '' means "clear it".
458
531
  salientDate: args.salient_date,
532
+ observedAt: args.observed_at,
533
+ absoluteDate: args.absolute_date,
534
+ validFrom: args.valid_from,
535
+ validTo: args.valid_to,
459
536
  })
460
537
  return `已更新 ${result.id}: ${result.entry.title} (${result.entry.layer}, ${result.entry.status})`
461
538
  },
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-memu-memory",
3
3
  "icon": "./assets/icon.png",
4
- "version": "1.2.7",
4
+ "version": "1.2.8",
5
5
  "description": "面向长篇 RP 与陪伴对话的 DeepSeek Harness 记忆插件:三层记忆、逐轮召回、来源标注、关系图、图片附件与独立 WebUI。",
6
6
  "keywords": [
7
7
  "deepseek-harness",
@@ -1,4 +1,4 @@
1
- // 召回基准台(1.3.0 P1-3):对比 HEAD 基线与施工后 lib 的检索质量与延迟。
1
+ // 召回基准台(1.2.8 P1-3):对比 HEAD 基线与升级后 lib 的检索质量与延迟。
2
2
  //
3
3
  // 用法:
4
4
  // node scripts/bench-recall.mjs # 测当前仓库 lib
@@ -9,7 +9,7 @@
9
9
  // - 指标:rankPairCandidates 延迟(N=300 精确两两 / N=2000 blocking 两档)、
10
10
  // buildCandidateClusters 延迟、Recall@10 / MRR(查询 → 目标条目是否进前 10)。
11
11
  // - 不引入任何依赖;被测导出(buildCorpus/rankPairCandidates/buildCandidateClusters)
12
- // 是 curator.js/global-graph.js 的既有公共面,任何施工都不应改动其签名。
12
+ // 是 curator.js/global-graph.js 的既有公共面,任何改动都不应改动其签名。
13
13
 
14
14
  import { pathToFileURL, fileURLToPath } from 'node:url'
15
15
  import { performance } from 'node:perf_hooks'
@@ -2,7 +2,7 @@
2
2
  //
3
3
  // node scripts/check-seed-compat.mjs --session-pkg <@deepseek-ai/dsh-session/lib/index.js 路径>
4
4
  //
5
- // 背景(1.3.0 实测):DSH 0.2.2-rc.1 的种子校验(assertAssistantSettlementShape)
5
+ // 背景(1.2.7 实测):DSH 0.2.2-rc.1 的种子校验(assertAssistantSettlementShape)
6
6
  // 要求 assistant/message 的 data.stream 是数组,而插件曾直接 delete 该字段,导致
7
7
  // 0.2.2-rc.1 上每个整理 fork 种子都被拒("invalid settlement fields")。修复后种子
8
8
  // 携带空数组。本脚本把「compactSeedEvents 产物 → 宿主 Session.create」这一环固化成
@@ -87,7 +87,7 @@ test('a backup can be deleted, and only that one', () => {
87
87
  })
88
88
 
89
89
  // ---------------------------------------------------------------------------
90
- // Retention, staging and recovery (本地向量施工文档 §14.9).
90
+ // Retention, staging and recovery.
91
91
  // Every test below runs in its own temporary data root: no real user backup is
92
92
  // created, pruned or restored by this file.
93
93
  // ---------------------------------------------------------------------------
@@ -468,7 +468,7 @@ test('the backup manifest carries identity, never a credential', () => {
468
468
  } finally { releaseRoot(root) }
469
469
  })
470
470
  // ---------------------------------------------------------------------------
471
- // Live SQLite snapshotting (本地向量施工文档 §14.9, rule 2).
471
+ // Live SQLite snapshotting (rule 2).
472
472
  //
473
473
  // A non-empty database may only be snapshotted by SQLite's own backup API, run
474
474
  // by the plugin's isolated engine/<version>/venv interpreter. These tests prove
@@ -0,0 +1,144 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+
7
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-commitment-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+
10
+ const state = await import('../lib/state.js')
11
+ const memory = await import('../lib/memory.js')
12
+ const inject = await import('../lib/inject.js')
13
+ const commitment = await import('../lib/commitment.js')
14
+
15
+ test.after(() => {
16
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
17
+ })
18
+
19
+ const NOW = new Date('2026-11-06T12:00:00+08:00')
20
+
21
+ let seq = 0
22
+ function session(name, sceneTime = '2026-11-06T04:00:00.000Z') {
23
+ seq += 1
24
+ const cwd = path.join(home, 'ws', `${name}-${seq}`)
25
+ const sessionId = `${name}-${seq}`
26
+ state.ensureSession(sessionId, { cwd, agentPreset: 'rp' })
27
+ state.setSessionBinding(sessionId, { sceneTime })
28
+ return {
29
+ sessionId,
30
+ exec: { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'rp' } } } },
31
+ }
32
+ }
33
+
34
+ test('an explicit commitment is normalized and kept in sync with open_loop', async () => {
35
+ const { exec } = session('commit-write')
36
+ const result = await memory.privateRemember({
37
+ exec, title: '答应帮林查机票', content: '我答应明天帮林查去冰岛的机票。',
38
+ sourceKind: 'assistant_said',
39
+ commitment: { counterparty: 'character:lin', action: '查去冰岛的机票', due_at: '2026-11-07', status: 'open' },
40
+ })
41
+ assert.equal(result.entry.openLoop, true)
42
+ assert.deepEqual(result.entry.commitment, {
43
+ counterparty: 'character:lin', action: '查去冰岛的机票', due_at: '2026-11-07',
44
+ status: 'open', closed_by: null, evidence_seq: null,
45
+ })
46
+
47
+ const done = await memory.privateUpdate({
48
+ exec, id: result.id,
49
+ commitment: { ...result.entry.commitment, status: 'done', closed_by: 'turn:12', evidence_seq: 12 },
50
+ })
51
+ assert.equal(done.entry.openLoop, false)
52
+ assert.equal(done.entry.commitment.status, 'done')
53
+ assert.equal(done.entry.commitment.closed_by, 'turn:12')
54
+ })
55
+
56
+ test('open_loop=true derives a commitment; close it through either field', async () => {
57
+ const { exec } = session('commit-legacy')
58
+ const opened = await memory.privateRemember({
59
+ exec, title: '答应回电话', content: '答应了昨天回电话。', openLoop: true,
60
+ salientDate: '2026-11-05',
61
+ })
62
+ assert.equal(opened.entry.commitment.status, 'open')
63
+ assert.equal(opened.entry.commitment.due_at, '2026-11-05')
64
+ assert.equal(opened.entry.commitment.action, '答应回电话')
65
+
66
+ const closed = await memory.privateUpdate({ exec, id: opened.id, openLoop: false })
67
+ assert.equal(closed.entry.commitment.status, 'done', 'the legacy boolean closes the authoritative object')
68
+ assert.equal(closed.entry.openLoop, false)
69
+ })
70
+
71
+ test('invalid commitments are refused before anything is written', async () => {
72
+ const { exec } = session('commit-invalid')
73
+ await assert.rejects(
74
+ () => memory.privateRemember({ exec, title: '坏承诺', content: '测试。', commitment: { action: 'x', status: 'later' } }),
75
+ /commitment\.status/,
76
+ )
77
+ await assert.rejects(
78
+ () => memory.privateRemember({ exec, title: '坏日期', content: '测试。', commitment: { action: 'x', due_at: '2026-02-30' } }),
79
+ /commitment\.due_at/,
80
+ )
81
+ await assert.rejects(
82
+ () => memory.privateRemember({ exec, title: '没动作', content: '测试。', commitment: { due_at: '2026-11-07' } }),
83
+ /commitment\.action/,
84
+ )
85
+ })
86
+
87
+ test('dueCommitments returns overdue, today and tomorrow only, ordered by due date', async () => {
88
+ const { exec, sessionId } = session('commit-due')
89
+ const overdue = await memory.privateRemember({
90
+ exec, title: '逾期的事', content: '欠着一件事。',
91
+ commitment: { counterparty: 'user', action: '回电话', due_at: '2026-11-04', status: 'open' },
92
+ })
93
+ const today = await memory.privateRemember({
94
+ exec, title: '今天到期', content: '今天要交周报。',
95
+ commitment: { counterparty: 'user', action: '交周报', due_at: '2026-11-06', status: 'open' },
96
+ })
97
+ const tomorrow = await memory.privateRemember({
98
+ exec, title: '明天到期', content: '明天要带伞。',
99
+ commitment: { counterparty: 'user', action: '带伞', due_at: '2026-11-07', status: 'open' },
100
+ })
101
+ const distant = await memory.privateRemember({
102
+ exec, title: '远期约定', content: '下个月再说。',
103
+ commitment: { counterparty: 'user', action: '下月见面', due_at: '2026-12-20', status: 'open' },
104
+ })
105
+ const done = await memory.privateRemember({
106
+ exec, title: '已经兑现', content: '已经做完了。',
107
+ commitment: { counterparty: 'user', action: '已经做完', due_at: '2026-11-04', status: 'done' },
108
+ })
109
+ const binding = state.getSessionBinding(sessionId)
110
+ const due = memory.dueCommitments({ libraryId: binding.libraryId, now: NOW.getTime(), sessionId, limit: 3 })
111
+ assert.deepEqual(due.map((item) => item.id), [overdue.id, today.id, tomorrow.id])
112
+ assert.deepEqual(due.map((item) => item.daysUntil), [-2, 0, 1])
113
+ assert.ok(!due.some((item) => item.id === distant.id), 'a distant promise does not spend the per-turn budget')
114
+ assert.ok(!due.some((item) => item.id === done.id), 'a done commitment is not a reminder')
115
+
116
+ const nudge = inject.buildCommitmentNudge(binding, state.getSettings(), sessionId, { now: NOW })
117
+ assert.match(nudge.text, /\[commitment\]/)
118
+ assert.match(nudge.text, /已逾期 2 天/)
119
+ assert.match(nudge.text, /今天到期/)
120
+ assert.match(nudge.text, /明天到期/)
121
+ assert.equal(nudge.ids.length, 3)
122
+ assert.equal(nudge.text.includes(distant.id), false)
123
+ })
124
+
125
+ test('commitment.status outranks the legacy open_loop flag in dueOpenLoops', async () => {
126
+ const { exec, sessionId } = session('commit-authority')
127
+ const { id } = await memory.privateRemember({
128
+ exec, title: '旧布尔值', content: '答应过的事。', openLoop: true, salientDate: '2026-11-01',
129
+ })
130
+ const binding = state.getSessionBinding(sessionId)
131
+ state.updatePrivateIndex(binding.libraryId, (index) => {
132
+ index.entries[id].openLoop = true
133
+ index.entries[id].commitment = {
134
+ counterparty: null, action: '答应过的事', due_at: '2026-11-01',
135
+ status: 'done', closed_by: 'turn:9', evidence_seq: 9,
136
+ }
137
+ })
138
+ const due = memory.dueOpenLoops({
139
+ libraryId: binding.libraryId, now: NOW.getTime(), days: 1, limit: 5,
140
+ includeOverdueDated: true, sessionId,
141
+ })
142
+ assert.equal(due.some((item) => item.id === id), false, 'a done commitment must not resurface as an overdue loop')
143
+ assert.equal(commitment.isOpenThread(state.loadPrivateIndex(binding.libraryId).entries[id]), false)
144
+ })
@@ -573,9 +573,9 @@ test('a non-PTC header without write tools still refuses to fork', async () => {
573
573
  // 超时预算按范围大小推:935 条事件那次实测「180 s 到点只写了 3 条,退避重试 131 s 完成」,
574
574
  // 约 0.14–0.2 s/事件;政策取 0.35 s/事件(≈2 倍余量)并夹在 [180 s, 600 s]。
575
575
  test('the consolidation wait budget scales with the transcript, not a fixed 180 s', () => {
576
- assert.equal(consolidationWaitBudget(0), CONSOLIDATION_WAIT_POLICY.minMs, 'an empty range still gets the old floor')
577
- assert.equal(consolidationWaitBudget(100), 180_000, 'small sessions keep the original three minutes')
578
- assert.equal(consolidationWaitBudget(200), 190_000)
576
+ assert.equal(consolidationWaitBudget(0), CONSOLIDATION_WAIT_POLICY.minMs, 'an empty range still gets the floor')
577
+ assert.equal(consolidationWaitBudget(100), 420_000, 'small sessions get the slow-reasoning floor')
578
+ assert.equal(consolidationWaitBudget(200), 420_000)
579
579
  assert.equal(consolidationWaitBudget(935), 447_250, 'the session that timed out gets ~7.5 minutes')
580
580
  assert.equal(consolidationWaitBudget(5_000), CONSOLIDATION_WAIT_POLICY.maxMs, 'a wedged fork still dies inside ten minutes')
581
581
  assert.equal(consolidationWaitBudget(undefined), CONSOLIDATION_WAIT_POLICY.minMs)
@@ -34,25 +34,35 @@ function seedGlobal(id, patch) {
34
34
  state.saveGlobalIndex(index)
35
35
  }
36
36
 
37
- test('disclosure changes the wording of the injected line, not whether it arrives', async () => {
37
+ test('disclosure decides when a memory may surface, not just how it is worded', async () => {
38
38
  const cwd = path.join(home, 'proj-tone')
39
39
  const sessionId = 'tone-suffix'
40
40
  state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
41
41
  const exec = execFor(sessionId, cwd)
42
42
  const settings = { ...state.getSettings(), relevanceThreshold: 0, privateTopK: 5 }
43
43
 
44
- await memory.privateRemember({ exec, content: 'The ledger file lives in docs/ledger.md.', title: 'ledger file', disclosure: 'can_tell' })
45
- await memory.privateRemember({ exec, content: 'The ledger file is generated by the old importer.', title: 'ledger importer', disclosure: 'only_if_asked' })
46
- await memory.privateRemember({ exec, content: 'The ledger file was named after his father.', title: 'ledger name', disclosure: 'never_say' })
44
+ const open = await memory.privateRemember({ exec, content: 'The ledger file lives in docs/ledger.md.', title: 'ledger file', disclosure: 'can_tell' })
45
+ const ask = await memory.privateRemember({ exec, content: 'The ledger file is generated by the old importer.', title: 'ledger importer', disclosure: 'only_if_asked' })
46
+ const never = await memory.privateRemember({ exec, content: 'The ledger file was named after his father.', title: 'ledger name', disclosure: 'never_say' })
47
47
 
48
- const recall = await inject.buildRecall(state.getSessionBinding(sessionId), 'ledger file', 1, settings, exec, sessionId)
49
- assert.deepEqual(recall.errors, [])
50
- assert.ok(recall.text.includes('ledger file'), 'a can_tell memory arrives as before')
51
- assert.equal(recall.text.split('对方不问就别主动提').length - 1, 1, 'only_if_asked carries its suffix')
52
- assert.equal(recall.text.split('记得,但别直接说出口').length - 1, 1, 'never_say carries its suffix')
48
+ const automatic = await inject.buildRecall(state.getSessionBinding(sessionId), 'ledger file', 1, settings, exec, sessionId)
49
+ assert.deepEqual(automatic.errors, [])
50
+ assert.ok(automatic.text.includes('ledger file'), 'a can_tell memory arrives as before')
51
+ assert.equal(automatic.text.includes(ask.id), false, 'only_if_asked waits for a direct question')
52
+ assert.equal(automatic.text.includes(never.id), false)
53
53
  // The default case must stay silent: adding a suffix to every line would be noise.
54
- const canTellLine = recall.text.split('\n').find((line) => line.includes('ledger file ·') || line.includes('ledger file'))
54
+ const canTellLine = automatic.text.split('\n').find((line) => line.includes('ledger file ·') || line.includes('ledger file'))
55
55
  assert.ok(canTellLine && !canTellLine.includes('对方不问') && !canTellLine.includes('别直接说出口'))
56
+
57
+ const explicit = await memory.privateRecall({ exec, query: 'ledger file', topK: 10, relevanceThreshold: 0 })
58
+ const explicitIds = explicit.files.map((file) => file.name)
59
+ assert.ok(explicitIds.includes(ask.id) && explicitIds.includes(never.id), 'an explicit recall can still read both')
60
+
61
+ const boundary = await inject.buildRecall(state.getSessionBinding(sessionId), 'ledger 的秘密是什么', 2, settings, exec, sessionId)
62
+ assert.deepEqual(boundary.errors, [])
63
+ assert.ok(boundary.text.includes(ask.id), 'a direct boundary question releases only_if_asked')
64
+ assert.equal(boundary.text.split('对方不问就别主动提').length - 1, 1, 'only_if_asked carries its suffix when released')
65
+ assert.equal(boundary.text.includes(never.id), false, 'never_say never auto-surfaces, even when asked')
56
66
  })
57
67
 
58
68
  test('a secret stays out of the anchor but is still reachable through recall', async () => {
@@ -98,25 +108,32 @@ test('a secret stays out of the anchor but is still reachable through recall', a
98
108
  assert.ok(recalled.files.some((file) => file.name === sharedId))
99
109
  })
100
110
 
101
- test('the short-term pointer card carries the disclosure suffix too', async () => {
111
+ test('an unsayable short-term draft stays out of the anchor pointer', async () => {
102
112
  const cwd = path.join(home, 'proj-pointer')
103
113
  const sessionId = 'tone-pointer'
104
114
  const binding = state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
105
115
  const exec = execFor(sessionId, cwd)
106
116
 
107
- const { id } = await memory.privateRemember({
117
+ const never = await memory.privateRemember({
108
118
  exec,
109
- content: 'BODY he was still deciding about the surgery.',
119
+ content: 'BODY-NEVER he was still deciding about the surgery.',
110
120
  title: 'the surgery question',
111
121
  layer: 'short_term',
112
122
  disclosure: 'never_say',
113
123
  })
124
+ const open = await memory.privateRemember({
125
+ exec,
126
+ content: 'BODY-OPEN the follow-up appointment is on Thursday.',
127
+ title: 'the follow-up',
128
+ layer: 'short_term',
129
+ })
114
130
  const anchor = inject.buildAnchor(binding, { ...state.getSettings(), anchorTokens: 700 })
115
- const line = anchor.text.split('\n').find((row) => row.includes(id))
116
- assert.ok(line, 'the pointer row exists')
131
+ assert.equal(anchor.text.includes(never.id), false, 'never_say does not enter the automatic pointer list')
132
+ const line = anchor.text.split('\n').find((row) => row.includes(open.id))
133
+ assert.ok(line, 'an ordinary draft still gets a pointer')
117
134
  assert.ok(line.includes('小时后过期'))
118
- assert.ok(line.includes('记得,但别直接说出口'), 'a draft can be just as unsayable as a durable memory')
119
- assert.equal(anchor.text.includes('BODY he was still'), false)
135
+ assert.equal(anchor.text.includes('BODY-NEVER'), false)
136
+ assert.equal(anchor.text.includes('BODY-OPEN'), false)
120
137
  })
121
138
 
122
139
  test('owner prefixes only about_user, and the prefix is cheap', async () => {
@@ -0,0 +1,128 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+
7
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-fact-version-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+
10
+ const state = await import('../lib/state.js')
11
+ const memory = await import('../lib/memory.js')
12
+
13
+ test.after(() => {
14
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
15
+ })
16
+
17
+ let seq = 0
18
+ function session(name, sceneTime = '2026-11-06T04:00:00.000Z') {
19
+ seq += 1
20
+ const cwd = path.join(home, 'ws', `${name}-${seq}`)
21
+ const sessionId = `${name}-${seq}`
22
+ state.ensureSession(sessionId, { cwd, agentPreset: 'rp' })
23
+ state.setSessionBinding(sessionId, { sceneTime })
24
+ return {
25
+ sessionId,
26
+ exec: { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'rp' } } } },
27
+ }
28
+ }
29
+
30
+ function entries(sessionId) {
31
+ const binding = state.getSessionBinding(sessionId)
32
+ return state.loadPrivateIndex(binding.libraryId).entries
33
+ }
34
+
35
+ test('two statements about one fact coexist, cross-linked, with both bodies intact', async () => {
36
+ const { exec, sessionId } = session('fact-conflict')
37
+ const first = await memory.privateRemember({
38
+ exec, title: '客厅地板颜色', content: '客厅地板是木色的,去年刚铺的。',
39
+ factKey: 'home:living_floor_color',
40
+ })
41
+ assert.equal(first.entry.fact_key, 'home:living_floor_color')
42
+ assert.equal(first.entry.version, 1)
43
+
44
+ const second = await memory.privateRemember({
45
+ exec, title: '客厅地板颜色改口', content: '客厅地板不是木色,是灰色瓷砖。',
46
+ factKey: 'home:living_floor_color',
47
+ })
48
+ assert.equal(second.entry.status, 'active', 'a conflict pair is not held for review')
49
+ assert.equal(second.entry.version, 2)
50
+ assert.equal(second.entry.conflicts_with, first.id)
51
+ assert.equal(second.conflictsWith, first.id)
52
+
53
+ const stored = entries(sessionId)
54
+ assert.equal(stored[first.id].status, 'active')
55
+ assert.equal(stored[first.id].conflicts_with, second.id, 'the pair points both ways')
56
+ assert.equal(stored[first.id].content, '客厅地板是木色的,去年刚铺的。', 'the old claim keeps its exact wording')
57
+ assert.equal(stored[second.id].content, '客厅地板不是木色,是灰色瓷砖。')
58
+ })
59
+
60
+ test('explicit supersede retires the old row without deleting its text', async () => {
61
+ const { exec, sessionId } = session('fact-supersede')
62
+ const first = await memory.privateRemember({
63
+ exec, title: '缴费日', content: '物业费每月5号缴。', factKey: 'home:fee_day',
64
+ })
65
+ const second = await memory.privateRemember({
66
+ exec, title: '缴费日补充', content: '物业费每月5号缴,遇节假日顺延。', factKey: 'home:fee_day',
67
+ })
68
+ // The second statement conflicting with the first creates v2; then an explicit
69
+ // correction supersedes v2.
70
+ const third = await memory.privateRemember({
71
+ exec, title: '缴费日最终确认', content: '物业费改成每月10号缴。',
72
+ factKey: 'home:fee_day', supersedes: second.id,
73
+ })
74
+ assert.equal(third.entry.status, 'active')
75
+ assert.equal(third.entry.version, 3)
76
+ assert.equal(third.entry.supersedes, second.id)
77
+ assert.equal(third.supersedes, second.id)
78
+
79
+ const stored = entries(sessionId)
80
+ assert.equal(stored[second.id].status, 'superseded')
81
+ assert.equal(stored[second.id].content, '物业费每月5号缴,遇节假日顺延。', 'the superseded body is still there')
82
+ assert.equal(stored[second.id].valid_to, '2026-11-06')
83
+ assert.equal(stored[second.id].supersededBy, third.id)
84
+ assert.equal(stored[first.id].content, '物业费每月5号缴。')
85
+
86
+ const recalled = await memory.privateRecall({ exec, query: '物业费缴费日', topK: 10, relevanceThreshold: 0 })
87
+ const ids = recalled.files.map((file) => file.name)
88
+ assert.ok(ids.includes(third.id), 'the current version is recallable')
89
+ assert.ok(!ids.includes(second.id), 'the superseded version is not recalled as current truth')
90
+ assert.ok(ids.includes(first.id), 'the earliest version is kept unless it was superseded too')
91
+ })
92
+
93
+ test('a compatible supplement updates the same id and does not create a version', async () => {
94
+ const { exec } = session('fact-supplement')
95
+ const first = await memory.privateRemember({
96
+ exec, title: '咖啡口味', content: '他只喝黑咖啡。', factKey: 'user:coffee',
97
+ })
98
+ const before = entries(exec.agent.session.header.id)[first.id]
99
+ const updated = await memory.privateUpdate({
100
+ exec, id: first.id, content: '他只喝黑咖啡,不加糖也不加奶。',
101
+ })
102
+ assert.equal(updated.id, first.id)
103
+ assert.equal(updated.entry.version, before.version, 'a compatible supplement is not a new version')
104
+ assert.equal(updated.entry.fact_key, 'user:coffee')
105
+ })
106
+
107
+ test('relation targets must exist, be active and share the scope', async () => {
108
+ const { exec, sessionId } = session('fact-targets')
109
+ const active = await memory.privateRemember({ exec, title: '在用的条目', content: '这条还在用。' })
110
+ await assert.rejects(
111
+ () => memory.privateRemember({ exec, title: '坏目标', content: '测试。', conflictsWith: 'mem-nope' }),
112
+ /unknown memory/,
113
+ )
114
+ await memory.privateUpdate({ exec, id: active.id, status: 'archived' })
115
+ await assert.rejects(
116
+ () => memory.privateRemember({ exec, title: '归档目标', content: '测试。', conflictsWith: active.id }),
117
+ /only an active memory/,
118
+ )
119
+ const stored = entries(sessionId)
120
+ assert.ok(!Object.values(stored).some((entry) => entry.title === '坏目标'), 'nothing is written when the target is invalid')
121
+ })
122
+
123
+ test('a derived fact_key is stored even without an explicit key', async () => {
124
+ const { exec } = session('fact-derived')
125
+ const { entry } = await memory.privateRemember({ exec, title: '窗台的绿萝', content: '窗台有一盆绿萝。' })
126
+ assert.match(entry.fact_key, /^me:窗台的绿萝$/)
127
+ assert.equal(entry.version, 1)
128
+ })
@@ -1,4 +1,4 @@
1
- // 帮助页与首次安装引导(施工稿 §6.5 包 E)+ 实体孤立分组的渲染断言(§6.4 包 D 第 5 条)。
1
+ // 帮助页与首次安装引导 + 实体孤立分组的渲染断言。
2
2
  // 沿用 client-render.test.mjs 的最小 React 运行时:一个在渲染期 throw 的页面块就是
3
3
  // 白屏,必须在构建期失败而不是静默白板。每一页都渲染,因为块只在选中该页时挂载。
4
4
  import test from 'node:test'