dsh-memu-memory 1.2.7 → 1.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.
Files changed (106) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +472 -0
  3. package/README.md +10 -15
  4. package/README.zh.md +10 -15
  5. package/docs/memory-semantics.md +23 -3
  6. package/lib/backup.js +155 -26
  7. package/lib/binding-diagnostics.js +1 -2
  8. package/lib/budget.js +31 -9
  9. package/lib/client.js +221 -128
  10. package/lib/commitment.js +138 -0
  11. package/lib/consolidation-ledger.js +5 -2
  12. package/lib/consolidation-receipt.js +2 -0
  13. package/lib/consolidation-worker.js +3 -0
  14. package/lib/curator-policy.js +23 -0
  15. package/lib/cycle.js +8 -4
  16. package/lib/embedding-download.js +168 -28
  17. package/lib/embedding-runtime.js +76 -17
  18. package/lib/engine.js +0 -6
  19. package/lib/freshness.js +24 -0
  20. package/lib/graph.js +139 -11
  21. package/lib/index.js +71 -20
  22. package/lib/inject.js +167 -17
  23. package/lib/lexicon.js +62 -17
  24. package/lib/local-vector-service.js +25 -2
  25. package/lib/media.js +49 -12
  26. package/lib/memory.js +1202 -123
  27. package/lib/memu.js +4 -0
  28. package/lib/paths.js +0 -7
  29. package/lib/preset-scope.js +6 -1
  30. package/lib/private.js +50 -10
  31. package/lib/prompts/private-consolidation.mixed.md +2 -2
  32. package/lib/prompts/private-consolidation.rp.md +6 -1
  33. package/lib/prompts/private-policy.rp.md +4 -0
  34. package/lib/prompts/system-guide.rp.md +3 -0
  35. package/lib/prompts.js +0 -7
  36. package/lib/recall-cache.js +10 -2
  37. package/lib/rpc.js +104 -19
  38. package/lib/snippet.js +41 -0
  39. package/lib/state.js +109 -30
  40. package/lib/stats.js +2 -2
  41. package/lib/temporal.js +348 -0
  42. package/lib/text-retrieval.js +191 -44
  43. package/lib/text-similarity.js +205 -24
  44. package/lib/tokenizer-v2.js +0 -24
  45. package/lib/tools.js +81 -4
  46. package/lib/vector-migration.js +15 -0
  47. package/lib/vector-profile.js +81 -8
  48. package/lib/visibility.js +0 -4
  49. package/lib/webui/standalone.css +17 -22
  50. package/lib/webui/standalone.js +27 -9
  51. package/lib/webui.js +4 -4
  52. package/package.json +3 -2
  53. package/scripts/acceptance-local.mjs +2 -2
  54. package/scripts/bench-recall.mjs +2 -2
  55. package/scripts/check-all.mjs +3 -1
  56. package/scripts/check-i18n.mjs +35 -1
  57. package/scripts/check-seed-compat.mjs +1 -1
  58. package/scripts/migrate-visibility.mjs +3 -3
  59. package/scripts/prune-sessions.mjs +34 -0
  60. package/scripts/prune-vectors.mjs +24 -0
  61. package/tests/appendix-b.test.mjs +5 -4
  62. package/tests/audit-batch3.test.mjs +247 -0
  63. package/tests/audit-regression.test.mjs +2 -2
  64. package/tests/backup.test.mjs +85 -85
  65. package/tests/browser.test.mjs +6 -1
  66. package/tests/client-render.test.mjs +2 -2
  67. package/tests/commitment.test.mjs +144 -0
  68. package/tests/consolidation-fork.test.mjs +3 -3
  69. package/tests/curator-clusters.test.mjs +18 -0
  70. package/tests/curator-pairing.test.mjs +59 -16
  71. package/tests/disclosure.test.mjs +34 -17
  72. package/tests/dynamic-rrf.test.mjs +22 -19
  73. package/tests/dynamic-threshold.test.mjs +52 -0
  74. package/tests/fact-version.test.mjs +146 -0
  75. package/tests/fixtures/tokenizer-cases.mjs +27 -0
  76. package/tests/graph-cascade.test.mjs +29 -0
  77. package/tests/graph.test.mjs +45 -0
  78. package/tests/help-page.test.mjs +1 -1
  79. package/tests/inject-conflict.test.mjs +112 -0
  80. package/tests/inject-guide.test.mjs +5 -3
  81. package/tests/inject.test.mjs +2 -2
  82. package/tests/injection-intent-budget.test.mjs +92 -0
  83. package/tests/lexical-bm25.test.mjs +171 -0
  84. package/tests/lexicon-frequency.test.mjs +17 -1
  85. package/tests/lexicon-inject.test.mjs +21 -0
  86. package/tests/lexicon-perf.test.mjs +37 -9
  87. package/tests/lexicon-scope.test.mjs +2 -2
  88. package/tests/lexicon-ui.test.mjs +1 -1
  89. package/tests/managed-memory.test.mjs +19 -0
  90. package/tests/memory-chain.test.mjs +140 -0
  91. package/tests/memory-fields.test.mjs +134 -0
  92. package/tests/memu-resident.test.mjs +33 -0
  93. package/tests/ops-hardening.test.mjs +209 -0
  94. package/tests/package-shipping.test.mjs +4 -0
  95. package/tests/prompt-semantics.test.mjs +51 -0
  96. package/tests/query-decompose.test.mjs +62 -0
  97. package/tests/recall-cache.test.mjs +4 -2
  98. package/tests/recall-intent.test.mjs +123 -0
  99. package/tests/slot-similarity.test.mjs +153 -0
  100. package/tests/speaker-provenance.test.mjs +120 -0
  101. package/tests/state-gc.test.mjs +34 -0
  102. package/tests/state.test.mjs +2 -2
  103. package/tests/temporal.test.mjs +124 -0
  104. package/tests/tokenizer-v2.test.mjs +1 -1
  105. package/tests/vector-gc.test.mjs +37 -0
  106. package/tests/webui.test.mjs +27 -0
package/lib/state.js CHANGED
@@ -6,12 +6,12 @@ import {
6
6
  ensureDir, readJson, readFailure, readFailuresUnder, writeJson, withFileLock, assertJsonShape, warn, stamp, shortHash, libraryIdForScope, isSafeId,
7
7
  } from './paths.js'
8
8
  import {
9
- activeLeases, createBackup, deleteBackupEntry, listBackupEntries,
10
- pruneBackups, restoreFromBackup, withBackupLock,
9
+ createBackup, deleteBackupEntry, listBackupEntries, restoreFromBackup,
11
10
  } from './backup.js'
12
11
  import { migrateIndexVisibility } from './visibility.js'
13
12
  import { memuDbFor, memuGlobalDbFor, removeActiveLibrary } from './vector-profile.js'
14
13
  import { normalizeEmotion, derivedValence } from './mood.js'
14
+ import { localCalendarDay } from './temporal.js'
15
15
 
16
16
  const STATE_FILE = () => path.join(dataDir(), 'state.json')
17
17
  const GLOBAL_DB = () => path.join(dataDir(), 'global.sqlite3')
@@ -255,6 +255,11 @@ export function updateState(fn) {
255
255
  return next
256
256
  }
257
257
 
258
+ // Codes that mean "the store was momentarily unavailable", not "this write can never
259
+ // succeed". Only these are re-armed; a read-only filesystem or a corrupt path would
260
+ // otherwise retry forever at FLUSH_MS.
261
+ const RETRYABLE_FLUSH_CODES = ['DSH_MEMU_STORE_BUSY', 'EPERM', 'EBUSY', 'EACCES']
262
+
258
263
  function scheduleFlush() {
259
264
  if (flushTimer) return
260
265
  flushTimer = setTimeout(() => {
@@ -263,7 +268,7 @@ function scheduleFlush() {
263
268
  flushState()
264
269
  } catch (error) {
265
270
  warnSinkSafe(`state flush failed: ${error?.message || error}`)
266
- if (['DSH_MEMU_STORE_BUSY', 'EPERM', 'EBUSY', 'EACCES'].includes(error?.code)) scheduleFlush()
271
+ if (RETRYABLE_FLUSH_CODES.includes(error?.code)) scheduleFlush()
267
272
  }
268
273
  }, FLUSH_MS)
269
274
  flushTimer.unref?.()
@@ -276,7 +281,18 @@ export function flushState() {
276
281
  flushTimer = null
277
282
  }
278
283
  if (!dirty || !cache) return
279
- return withFileLock(STATE_FILE(), flushStateLocked)
284
+ try {
285
+ return withFileLock(STATE_FILE(), flushStateLocked)
286
+ } catch (error) {
287
+ // S-10: the timer was already cleared above, so a failed flush used to leave the
288
+ // pending bookkeeping dirty with nothing scheduled — one busy lock was enough to
289
+ // strand inbound pending / lastRecallError / sleepRetryAt in memory until the next
290
+ // unrelated write (or a crash). Re-arm before rethrowing so the batch is retried;
291
+ // the caller still sees the error.
292
+ warnSinkSafe(`state flush failed: ${error?.message || error}`)
293
+ if (RETRYABLE_FLUSH_CODES.includes(error?.code)) scheduleFlush()
294
+ throw error
295
+ }
280
296
  }
281
297
 
282
298
  function mergeChanges(base, local, disk) {
@@ -1045,8 +1061,7 @@ export function markAnniversaryShown(sessionId, memoryId, dayKey) {
1045
1061
  const OPEN_LOOP_REMIND_PRUNE_MS = 90 * 86_400_000
1046
1062
 
1047
1063
  function localDayKeyOf(date) {
1048
- const d = date instanceof Date ? date : new Date(date)
1049
- return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
1064
+ return localCalendarDay(date)
1050
1065
  }
1051
1066
 
1052
1067
  function prunedOpenLoopReminded(sessionId, now = new Date()) {
@@ -1329,12 +1344,22 @@ export function loadPrivateIndex(libraryId) {
1329
1344
  })
1330
1345
  }
1331
1346
 
1332
- export function savePrivateIndex(libraryId, index) {
1347
+ /**
1348
+ * Persist one library index.
1349
+ *
1350
+ * `bumpRevision: false` exists for writes that cannot change what recall would find:
1351
+ * the injector's own bookkeeping (injectCount / lastInjectAt) runs *after* every
1352
+ * successful injection, so bumping the revision there guaranteed that the next turn's
1353
+ * recall and BM25 corpus both missed. The write still happens, still notifies
1354
+ * listeners and still records the write event — only the "something a cached result
1355
+ * depends on changed" claim is withheld, because it is not true.
1356
+ */
1357
+ export function savePrivateIndex(libraryId, index, { bumpRevision = true } = {}) {
1333
1358
  if (!isSafeId(libraryId)) throw new Error('invalid library id')
1334
1359
  if (!validIndex(index)) throw new Error('invalid memory index shape')
1335
1360
  const file = path.join(indexDir(), `${libraryId}.json`)
1336
1361
  const saved = writeIndex(file, index)
1337
- bumpMemoryRevision()
1362
+ if (bumpRevision) bumpMemoryRevision()
1338
1363
  noteMemoryWrite('private', libraryId)
1339
1364
  for (const listener of indexWriteListeners) {
1340
1365
  try { listener(libraryId, saved) } catch (error) { warn(`memory sidecar update failed: ${error?.message || error}`) }
@@ -1354,10 +1379,10 @@ function validIndex(value) {
1354
1379
  && Object.values(value.entries).every(entry => entry && typeof entry === 'object' && !Array.isArray(entry))
1355
1380
  }
1356
1381
 
1357
- export function saveGlobalIndex(index) {
1382
+ export function saveGlobalIndex(index, { bumpRevision = true } = {}) {
1358
1383
  if (!validIndex(index)) throw new Error('invalid memory index shape')
1359
1384
  writeIndex(GLOBAL_INDEX(), index)
1360
- bumpMemoryRevision()
1385
+ if (bumpRevision) bumpMemoryRevision()
1361
1386
  noteMemoryWrite('global', null)
1362
1387
  }
1363
1388
 
@@ -1419,12 +1444,12 @@ export function newMemoryId(prefix = 'mem') {
1419
1444
  * Returns the published directory: callers (engine switch, library delete,
1420
1445
  * scripts) treat the return value as a path.
1421
1446
  */
1422
- export function backupDatabases(options = {}) {
1447
+ export async function backupDatabases(options = {}) {
1423
1448
  // Pending bookkeeping changes live in memory for up to 50ms; a backup taken
1424
1449
  // before a flush would silently capture the previous state.
1425
1450
  let report
1426
1451
  try {
1427
- report = createBackup({ ...options, flushState })
1452
+ report = await createBackup({ ...options, flushState })
1428
1453
  } catch (error) {
1429
1454
  // A refusal is the safety property working, not something to swallow: a
1430
1455
  // database the engine could not snapshot aborts the backup, and the reason
@@ -1468,22 +1493,6 @@ export function deleteBackup(name) {
1468
1493
  return { deleted: result.deleted, status: result.status }
1469
1494
  }
1470
1495
 
1471
- /**
1472
- * Applies the retention rule on demand. Creation already prunes, so this exists
1473
- * for the paths that must reclaim the space a protected restore target kept
1474
- * alive, and for callers that want the report without making a backup.
1475
- */
1476
- export function pruneOldBackups(options = {}) {
1477
- const result = pruneBackups(options)
1478
- lastBackupReport = { at: stamp(), action: 'prune', ...result }
1479
- return result
1480
- }
1481
-
1482
- /** Names of backups that a running restore or migration is reading right now. */
1483
- export function leasedBackups() {
1484
- return Object.keys(activeLeases())
1485
- }
1486
-
1487
1496
  /**
1488
1497
  * Puts a backup back. The target is leased and its whole inventory is verified
1489
1498
  * before anything is written; the live root is saved as a safety backup next;
@@ -1493,8 +1502,8 @@ export function leasedBackups() {
1493
1502
  * vector-active pointer, so recall falls back to text instead of querying
1494
1503
  * databases that no longer match the restored index.
1495
1504
  */
1496
- export function restoreBackup(name, { beforeRestore = null, keep = undefined } = {}) {
1497
- const result = restoreFromBackup(name, { beforeRestore, flushState, clearCaches, keep })
1505
+ export async function restoreBackup(name, { beforeRestore = null, keep = undefined } = {}) {
1506
+ const result = await restoreFromBackup(name, { beforeRestore, flushState, clearCaches, keep })
1498
1507
  lastBackupReport = { at: stamp(), action: 'restore', ...result }
1499
1508
  return result
1500
1509
  }
@@ -1510,3 +1519,73 @@ export function clearCaches() {
1510
1519
  bumpMemoryRevision()
1511
1520
  noteMemoryWrite('restore', null)
1512
1521
  }
1522
+
1523
+ /**
1524
+ * P2-5: explicit session-binding GC. Idle time is not an automatic deletion
1525
+ * trigger (docs/binding-lifecycle.md); this is a dry-run-first maintenance call.
1526
+ * A binding with no parseable lastTurnAt is never a candidate.
1527
+ */
1528
+ /**
1529
+ * Session-binding garbage collection.
1530
+ *
1531
+ * This deletes bindings, which is not recoverable. Three guards, because the old
1532
+ * version had none and a `--days 0` invocation wiped every binding in the store:
1533
+ *
1534
+ * · `olderThanDays` must be strictly positive. Zero/negative is a mistake, not a
1535
+ * "clean everything" request, so it throws instead of quietly becoming one.
1536
+ * · `isBusy(sessionId)` lets the caller veto a candidate: a session with a live
1537
+ * consolidation lease is in the middle of writing, and lastTurnAt is not the only
1538
+ * clock that matters.
1539
+ * · the apply pass re-reads each candidate inside `updateState`. A dry-run and an
1540
+ * apply are two separate loads, and a conversation that woke up in between must
1541
+ * not be deleted on the strength of the earlier snapshot.
1542
+ */
1543
+ export function pruneSessionBindings({ olderThanDays = 30, dryRun = true, now = Date.now(), isBusy = null } = {}) {
1544
+ const days = Number(olderThanDays)
1545
+ if (!Number.isFinite(days) || days <= 0) throw new Error('olderThanDays must be a positive number of days')
1546
+ const cutoff = Number(now) - days * 86_400_000
1547
+ const state = loadState()
1548
+ const candidates = []
1549
+ const skipped = []
1550
+ for (const [sessionId, binding] of Object.entries(state.sessions || {})) {
1551
+ const at = Date.parse(String(binding?.lastTurnAt || ''))
1552
+ if (!Number.isFinite(at) || at >= cutoff) continue
1553
+ if (typeof isBusy === 'function') {
1554
+ let busy = false
1555
+ try { busy = isBusy(sessionId) === true } catch (error) {
1556
+ // An unreadable lease file is not permission to delete: treat it as busy.
1557
+ busy = true
1558
+ warn(`prune-session-bindings: liveness check failed for ${sessionId} (${error?.message || error}); kept`)
1559
+ }
1560
+ if (busy) {
1561
+ skipped.push({ sessionId, reason: 'a consolidation lease is still live' })
1562
+ continue
1563
+ }
1564
+ }
1565
+ candidates.push({ sessionId, lastTurnAt: binding.lastTurnAt, libraryId: binding.libraryId || null })
1566
+ }
1567
+ const base = {
1568
+ dryRun: dryRun !== false,
1569
+ olderThanDays: days,
1570
+ cutoff: new Date(cutoff).toISOString(),
1571
+ candidates,
1572
+ skipped,
1573
+ }
1574
+ if (dryRun !== false || candidates.length === 0) return { ...base, removed: [] }
1575
+ const removed = []
1576
+ const revalidated = []
1577
+ updateState((next) => {
1578
+ for (const item of candidates) {
1579
+ const current = next.sessions?.[item.sessionId]
1580
+ if (!current) continue
1581
+ const at = Date.parse(String(current.lastTurnAt || ''))
1582
+ // Same predicate as the candidate pass, on the fresh copy: `at < cutoff` alone
1583
+ // would still delete a binding that just came back with a stale lastTurnAt.
1584
+ if (!Number.isFinite(at) || at >= cutoff) { revalidated.push(item.sessionId); continue }
1585
+ delete next.sessions[item.sessionId]
1586
+ removed.push(item.sessionId)
1587
+ }
1588
+ return next
1589
+ })
1590
+ return { ...base, removed, revalidated }
1591
+ }
package/lib/stats.js CHANGED
@@ -8,6 +8,7 @@
8
8
  import fs from 'node:fs'
9
9
  import path from 'node:path'
10
10
  import { indexDir, readJsonStrict, writeJson, withFileLock, warn, isSafeId } from './paths.js'
11
+ import { localCalendarDay } from './temporal.js'
11
12
 
12
13
  export const STATS_KEPT_DAYS = 90
13
14
  export const STATS_KINDS = ['written', 'injected', 'recalled', 'archived']
@@ -56,8 +57,7 @@ export function loadStats(libraryId) {
56
57
  }
57
58
 
58
59
  function dayKey(now) {
59
- const date = new Date(now)
60
- return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
60
+ return localCalendarDay(now)
61
61
  }
62
62
 
63
63
  function keepWindow(days, keptDays) {
@@ -0,0 +1,348 @@
1
+ // 相对日期 → 绝对日期。
2
+ //
3
+ // 相对日期不能靠模型心算。写入时按这一轮的逻辑时间(sceneTime)解析,
4
+ // 召回时也先把查询里的相对日期解析成绝对日期再拼检索词。这是个纯函数模块:
5
+ // 不做 IO、不读系统时钟(除非调用方不传 now),失败返回 null,绝不猜。
6
+
7
+ const DAY_MS = 86_400_000
8
+ const DEFAULT_TIME_ZONE = 'Asia/Shanghai'
9
+ const YEAR_MIN = 1900
10
+ const YEAR_MAX = 2999
11
+
12
+ const WEEKDAY_INDEX = new Map([
13
+ ['一', 0], ['二', 1], ['三', 2], ['四', 3], ['五', 4], ['六', 5], ['日', 6], ['天', 6],
14
+ ['1', 0], ['2', 1], ['3', 2], ['4', 3], ['5', 4], ['6', 5], ['7', 6],
15
+ ])
16
+
17
+ const RELATIVE_DAY_TERMS = [
18
+ ['大后天', 3], ['大前天', -3],
19
+ ['后天', 2], ['前天', -2],
20
+ ['明天', 1], ['昨天', -1], ['今天', 0],
21
+ ['明日', 1], ['昨日', -1], ['今日', 0],
22
+ ].sort((a, b) => b[0].length - a[0].length)
23
+
24
+ const EN_RELATIVE_DAYS = new Map([
25
+ ['today', 0], ['tomorrow', 1], ['yesterday', -1],
26
+ ['the day after tomorrow', 2], ['the day before yesterday', -2],
27
+ ])
28
+
29
+ const formatterCache = new Map()
30
+
31
+ function pad2(value) {
32
+ return String(value).padStart(2, '0')
33
+ }
34
+
35
+ function formatDate({ y, m, d }) {
36
+ return `${String(y).padStart(4, '0')}-${pad2(m)}-${pad2(d)}`
37
+ }
38
+
39
+ function daysInMonth(y, m) {
40
+ return new Date(Date.UTC(y, m, 0)).getUTCDate()
41
+ }
42
+
43
+ function validCalendar(y, m, d) {
44
+ if (!Number.isInteger(y) || !Number.isInteger(m) || !Number.isInteger(d)) return false
45
+ if (y < YEAR_MIN || y > YEAR_MAX || m < 1 || m > 12 || d < 1) return false
46
+ return d <= daysInMonth(y, m)
47
+ }
48
+
49
+ function addDays({ y, m, d }, days) {
50
+ const at = new Date(Date.UTC(y, m - 1, d) + Number(days) * DAY_MS)
51
+ return { y: at.getUTCFullYear(), m: at.getUTCMonth() + 1, d: at.getUTCDate() }
52
+ }
53
+
54
+ function weekdayMondayIndex({ y, m, d }) {
55
+ return (new Date(Date.UTC(y, m - 1, d)).getUTCDay() + 6) % 7
56
+ }
57
+
58
+ function mondayOfWeek({ y, m, d }) {
59
+ return addDays({ y, m, d }, -weekdayMondayIndex({ y, m, d }))
60
+ }
61
+
62
+ function addMonths({ y, m }, months) {
63
+ const at = new Date(Date.UTC(y, m - 1 + Number(months), 1))
64
+ return { y: at.getUTCFullYear(), m: at.getUTCMonth() + 1 }
65
+ }
66
+
67
+ function formatterFor(timeZone) {
68
+ const key = String(timeZone || '')
69
+ if (formatterCache.has(key)) return formatterCache.get(key)
70
+ let formatter
71
+ try {
72
+ formatter = new Intl.DateTimeFormat('en-US', {
73
+ timeZone: key || DEFAULT_TIME_ZONE,
74
+ year: 'numeric', month: '2-digit', day: '2-digit',
75
+ })
76
+ } catch {
77
+ formatter = new Intl.DateTimeFormat('en-US', {
78
+ timeZone: DEFAULT_TIME_ZONE,
79
+ year: 'numeric', month: '2-digit', day: '2-digit',
80
+ })
81
+ }
82
+ formatterCache.set(key, formatter)
83
+ return formatter
84
+ }
85
+
86
+ function instantOf(now) {
87
+ if (now instanceof Date) return Number.isFinite(now.getTime()) ? now : new Date()
88
+ if (typeof now === 'number') {
89
+ const at = new Date(now)
90
+ return Number.isFinite(at.getTime()) ? at : new Date()
91
+ }
92
+ if (typeof now === 'string' && now.trim()) {
93
+ const at = new Date(now)
94
+ if (Number.isFinite(at.getTime())) return at
95
+ }
96
+ return new Date()
97
+ }
98
+
99
+ function zonedCalendar(instant, timeZone) {
100
+ const parts = formatterFor(timeZone).formatToParts(instant)
101
+ const values = {}
102
+ for (const part of parts) {
103
+ if (part.type === 'year' || part.type === 'month' || part.type === 'day') values[part.type] = Number(part.value)
104
+ }
105
+ if (!validCalendar(values.year, values.month, values.day)) {
106
+ return { y: instant.getUTCFullYear(), m: instant.getUTCMonth() + 1, d: instant.getUTCDate() }
107
+ }
108
+ return { y: values.year, m: values.month, d: values.day }
109
+ }
110
+
111
+ function candidate(index, sourceText, calendar, precision, dateSource, priority) {
112
+ if (!validCalendar(calendar.y, calendar.m, calendar.d)) return null
113
+ return {
114
+ absoluteDate: formatDate(calendar),
115
+ precision,
116
+ sourceText: String(sourceText || '').trim(),
117
+ dateSource,
118
+ index: Number(index) || 0,
119
+ priority,
120
+ calendar,
121
+ }
122
+ }
123
+
124
+ function matchesOf(re, text, build) {
125
+ const out = []
126
+ re.lastIndex = 0
127
+ let match
128
+ while ((match = re.exec(text)) !== null) {
129
+ const item = build(match)
130
+ if (item) out.push(item)
131
+ if (match[0].length === 0) re.lastIndex += 1
132
+ }
133
+ return out
134
+ }
135
+
136
+ function explicitCandidates(text, today) {
137
+ // 只认完整年月日;不带年份的 MM-DD 是周年日,不是某一天。
138
+ const re = /(?<![\d])(\d{4})\s*[-/年]\s*(\d{1,2})\s*[-/月]\s*(\d{1,2})\s*[日号]?(?![\d])/g
139
+ return matchesOf(re, text, (match) => candidate(
140
+ match.index,
141
+ match[0],
142
+ { y: Number(match[1]), m: Number(match[2]), d: Number(match[3]) },
143
+ 'day',
144
+ 'explicit',
145
+ 0,
146
+ ))
147
+ }
148
+
149
+ function relativeDayCandidates(text, today) {
150
+ const out = []
151
+ for (const [term, offset] of RELATIVE_DAY_TERMS) {
152
+ let from = 0
153
+ while (from < text.length) {
154
+ const at = text.indexOf(term, from)
155
+ if (at < 0) break
156
+ // "大后天" 里的 "后天" 不单独算一次:长度更长的词优先。
157
+ const longerBefore = at > 0 && RELATIVE_DAY_TERMS.some(([other]) => other.length > term.length
158
+ && text.slice(Math.max(0, at - (other.length - term.length)), at + term.length) === other)
159
+ const longerAt = RELATIVE_DAY_TERMS.some(([other]) => other.length > term.length
160
+ && text.slice(at, at + other.length) === other)
161
+ if (!longerBefore && !longerAt) {
162
+ const item = candidate(at, term, addDays(today, offset), 'day', 'relative', 10)
163
+ if (item) out.push(item)
164
+ }
165
+ from = at + term.length
166
+ }
167
+ }
168
+ const en = /(?<![a-z])(the day after tomorrow|the day before yesterday|today|tomorrow|yesterday)(?![a-z])/gi
169
+ for (const match of matchesOf(en, text, (item) => item)) {
170
+ const offset = EN_RELATIVE_DAYS.get(match[0].toLowerCase())
171
+ if (offset === undefined) continue
172
+ const item = candidate(match.index, match[0], addDays(today, offset), 'day', 'relative', 10)
173
+ if (item) out.push(item)
174
+ }
175
+ return out
176
+ }
177
+
178
+ function weekCandidates(text, today) {
179
+ const re = /(上上|上|下个|下|这个|这|本)\s*(?:周|星期|礼拜)\s*([一二三四五六日天1-7])/g
180
+ return matchesOf(re, text, (match) => {
181
+ const prefix = match[1]
182
+ const weekday = WEEKDAY_INDEX.get(match[2])
183
+ if (weekday === undefined) return null
184
+ let weeks = 0
185
+ if (prefix === '下' || prefix === '下个') weeks = 1
186
+ else if (prefix === '上') weeks = -1
187
+ else if (prefix === '上上') weeks = -2
188
+ const monday = mondayOfWeek(today)
189
+ return candidate(match.index, match[0], addDays(monday, weeks * 7 + weekday), 'day', 'relative', 20)
190
+ })
191
+ }
192
+
193
+ function monthDayCandidates(text, today) {
194
+ const re = /(下个?月|下月份?|本月|这个月份?)\s*(\d{1,2})\s*[号日]/g
195
+ return matchesOf(re, text, (match) => {
196
+ const day = Number(match[2])
197
+ const month = match[1].startsWith('下') ? addMonths(today, 1) : { y: today.y, m: today.m }
198
+ if (day < 1 || day > daysInMonth(month.y, month.m)) return null
199
+ return candidate(match.index, match[0], { y: month.y, m: month.m, d: day }, 'day', 'relative', 30)
200
+ })
201
+ }
202
+
203
+ function monthBoundaryCandidates(text, today) {
204
+ const re = /(下个?月|下月份?|本月|这个月份?|月)\s*(?:底|末)/g
205
+ return matchesOf(re, text, (match) => {
206
+ const prefix = match[1]
207
+ const month = prefix.startsWith('下') ? addMonths(today, 1) : { y: today.y, m: today.m }
208
+ return candidate(match.index, match[0], { y: month.y, m: month.m, d: daysInMonth(month.y, month.m) }, 'month', 'relative', 40)
209
+ })
210
+ }
211
+
212
+ function yearBoundaryCandidates(text, today) {
213
+ const out = []
214
+ for (const match of text.matchAll(/年初/g)) {
215
+ const item = candidate(match.index, match[0], { y: today.y, m: 1, d: 1 }, 'year', 'relative', 50)
216
+ if (item) out.push(item)
217
+ }
218
+ for (const match of text.matchAll(/(?:年底|年末)/g)) {
219
+ const item = candidate(match.index, match[0], { y: today.y, m: 12, d: 31 }, 'year', 'relative', 50)
220
+ if (item) out.push(item)
221
+ }
222
+ return out
223
+ }
224
+
225
+ function offsetDayCandidates(text, today) {
226
+ const out = []
227
+ const after = /(\d{1,3})\s*天\s*(?:之|以)?后/g
228
+ for (const match of text.matchAll(after)) {
229
+ const days = Number(match[1])
230
+ if (!Number.isFinite(days)) continue
231
+ const item = candidate(match.index, match[0], addDays(today, days), 'day', 'relative', 12)
232
+ if (item) out.push(item)
233
+ }
234
+ const before = /(\d{1,3})\s*天\s*(?:之|以)?前/g
235
+ for (const match of text.matchAll(before)) {
236
+ const days = Number(match[1])
237
+ if (!Number.isFinite(days)) continue
238
+ const item = candidate(match.index, match[0], addDays(today, -days), 'day', 'relative', 12)
239
+ if (item) out.push(item)
240
+ }
241
+ return out
242
+ }
243
+
244
+ function allCandidates(text, { now, timeZone } = {}) {
245
+ const normalized = String(text ?? '').normalize('NFKC')
246
+ if (!normalized.trim()) return []
247
+ const today = zonedCalendar(instantOf(now), timeZone)
248
+ const found = [
249
+ ...explicitCandidates(normalized, today),
250
+ ...relativeDayCandidates(normalized, today),
251
+ ...weekCandidates(normalized, today),
252
+ ...monthDayCandidates(normalized, today),
253
+ ...monthBoundaryCandidates(normalized, today),
254
+ ...yearBoundaryCandidates(normalized, today),
255
+ ...offsetDayCandidates(normalized, today),
256
+ ]
257
+ // 同一位置同一句只留最具体的一条(显式日期 > 相对日 > 周 > 月日 > 月底 > 年)。
258
+ const best = new Map()
259
+ for (const item of found) {
260
+ const key = `${item.index}:${item.sourceText}`
261
+ const current = best.get(key)
262
+ if (!current || item.priority < current.priority) best.set(key, item)
263
+ }
264
+ return [...best.values()].sort((a, b) => a.index - b.index || a.priority - b.priority)
265
+ }
266
+
267
+ /**
268
+ * 解析文本里最可信的一个日期表达。
269
+ * @returns {{absoluteDate: string, precision: 'day'|'month'|'year', sourceText: string,
270
+ * dateSource: 'explicit'|'relative', index: number}|null}
271
+ */
272
+ export function parseTemporalExpression(text, { now = new Date(), timeZone = DEFAULT_TIME_ZONE } = {}) {
273
+ const found = allCandidates(text, { now, timeZone })
274
+ if (found.length === 0) return null
275
+ const ordered = found.slice().sort((a, b) => a.priority - b.priority || a.index - b.index)
276
+ const chosen = ordered[0]
277
+ return {
278
+ absoluteDate: chosen.absoluteDate,
279
+ precision: chosen.precision,
280
+ sourceText: chosen.sourceText,
281
+ dateSource: chosen.dateSource,
282
+ index: chosen.index,
283
+ }
284
+ }
285
+
286
+ /** 文本里所有可解析的日期表达,按出现顺序。 */
287
+ export function extractTemporalExpressions(text, options = {}) {
288
+ return allCandidates(text, options).map((item) => ({
289
+ absoluteDate: item.absoluteDate,
290
+ precision: item.precision,
291
+ sourceText: item.sourceText,
292
+ dateSource: item.dateSource,
293
+ index: item.index,
294
+ }))
295
+ }
296
+
297
+ /** 查询侧:文本里所有绝对日期,去重后按出现顺序。 */
298
+ export function resolveQueryDates(text, options = {}) {
299
+ const dates = []
300
+ for (const item of extractTemporalExpressions(text, options)) {
301
+ if (!dates.includes(item.absoluteDate)) dates.push(item.absoluteDate)
302
+ }
303
+ return dates
304
+ }
305
+
306
+ /** 有相对时间词、但可能解析不出来(例如只说“下周”)。 */
307
+ export function hasTemporalHint(text) {
308
+ const value = String(text ?? '').normalize('NFKC')
309
+ return /大后天|大前天|后天|前天|明天|昨天|今天|今日|明日|昨日|下周|这周|本周|下周|上周|下个?月|本月|这个月|月底|月末|年初|年底|年末|\d\s*天\s*(?:之|以)?[前后]|(?<![a-z])(today|tomorrow|yesterday)(?![a-z])/i.test(value)
310
+ }
311
+
312
+ /** 严格 YYYY-MM-DD;非法日期返回 null(不猜)。 */
313
+ export function parseAbsoluteDate(value) {
314
+ const text = String(value ?? '').trim()
315
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text)
316
+ if (!match) return null
317
+ const y = Number(match[1])
318
+ const m = Number(match[2])
319
+ const d = Number(match[3])
320
+ if (!validCalendar(y, m, d)) return null
321
+ return formatDate({ y, m, d })
322
+ }
323
+
324
+ /** 某个瞬间在指定时区里的本地日期(YYYY-MM-DD)。 */
325
+ export function localDateKeyInZone(value = new Date(), timeZone = DEFAULT_TIME_ZONE) {
326
+ return formatDate(zonedCalendar(instantOf(value), timeZone))
327
+ }
328
+
329
+ /**
330
+ * 宿主本地的日历日(YYYY-MM-DD)。
331
+ *
332
+ * 这一行原来在 state / stats / freshness / commitment / salient-wake / inject /
333
+ * memory 里各写了一遍(8 处,padStart 与 pad2 两种风格混用,其中一处漏了补零)。
334
+ * 它们算的是同一件事,只是各写各的;统一到这里以后,「本地日历日」只有一种写法。
335
+ *
336
+ * 与 localDateKeyInZone 的分工是**有意的**,不是重复实现:那个按指定时区算,用于
337
+ * 解析记忆文本里的相对日期(默认 Asia/Shanghai,见 DEFAULT_TIME_ZONE);这个按宿主
338
+ * 时区算,用于「今天 / 连续多少天 / 统计桶」这类必须跟着用户本地时钟走的口径。两者
339
+ * 在 UTC+8 上一致,在别的时区会相差一天——这条口径差目前是已知未收敛项,改动它等于
340
+ * 改产品语义,不在这次清理范围内。
341
+ */
342
+ export function localCalendarDay(value = new Date()) {
343
+ const date = value instanceof Date ? value : new Date(value)
344
+ const at = Number.isFinite(date.getTime()) ? date : new Date()
345
+ return `${at.getFullYear()}-${pad2(at.getMonth() + 1)}-${pad2(at.getDate())}`
346
+ }
347
+
348
+ export { DEFAULT_TIME_ZONE, DAY_MS }