dsh-memu-memory 1.4.2 → 1.4.4

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 (389) hide show
  1. package/AGENTS.md +108 -110
  2. package/CHANGELOG.md +173 -868
  3. package/LICENSE +21 -21
  4. package/README.md +368 -374
  5. package/README.zh.md +354 -360
  6. package/assets/icon.svg +7 -7
  7. package/cordis.patch.yml +8 -8
  8. package/docs/active-memory-ab.md +279 -385
  9. package/docs/binding-lifecycle.md +99 -99
  10. package/docs/client-conventions.md +75 -75
  11. package/docs/contributing.md +217 -217
  12. package/docs/emotion-model-spec.md +247 -281
  13. package/docs/env-and-commands.md +149 -152
  14. package/docs/host-adaptation.md +339 -360
  15. package/docs/host-api.md +131 -137
  16. package/docs/host-versions.md +117 -120
  17. package/docs/mcp-porting.md +146 -146
  18. package/docs/memory-semantics.md +271 -259
  19. package/docs/pending-work.md +44 -51
  20. package/docs/troubleshooting.md +909 -854
  21. package/lib/active-memory.js +160 -165
  22. package/lib/activity-log.js +207 -207
  23. package/lib/auto-link/apply.js +248 -249
  24. package/lib/auto-link/candidates.js +163 -163
  25. package/lib/auto-link/decide.js +300 -300
  26. package/lib/auto-link/normalize.js +99 -99
  27. package/lib/auto-link/policy.js +42 -42
  28. package/lib/auto-link/suppression.js +101 -101
  29. package/lib/auto-link/terminology.js +311 -311
  30. package/lib/backup.js +1254 -1254
  31. package/lib/binding-diagnostics.js +634 -634
  32. package/lib/budget.js +118 -118
  33. package/lib/client.js +9820 -9751
  34. package/lib/commitment.js +178 -138
  35. package/lib/consolidation-ledger.js +434 -438
  36. package/lib/consolidation-receipt.js +386 -387
  37. package/lib/consolidation-snapshot.js +420 -405
  38. package/lib/consolidation-worker.js +240 -241
  39. package/lib/context.js +33 -33
  40. package/lib/curator-evidence.js +131 -131
  41. package/lib/curator-policy.js +198 -202
  42. package/lib/curator.js +1813 -1811
  43. package/lib/cycle.js +524 -513
  44. package/lib/diagnostics.js +524 -524
  45. package/lib/embedding-catalog.js +1051 -1055
  46. package/lib/embedding-download.js +637 -607
  47. package/lib/embedding-runtime.js +946 -946
  48. package/lib/engine.js +1103 -1103
  49. package/lib/entity-repair.js +285 -285
  50. package/lib/environment-check.js +394 -394
  51. package/lib/fork-model.js +312 -312
  52. package/lib/freshness.js +128 -121
  53. package/lib/global-graph.js +389 -389
  54. package/lib/graph.js +1193 -1193
  55. package/lib/host-surface.js +30 -30
  56. package/lib/inbound.js +284 -281
  57. package/lib/index.js +506 -511
  58. package/lib/inject.js +2639 -2619
  59. package/lib/lexicon-scope.js +143 -143
  60. package/lib/lexicon.js +1183 -1192
  61. package/lib/lifecycle-audit.js +37 -0
  62. package/lib/local-embedding-entry.js +145 -145
  63. package/lib/local-embedding-manager.js +306 -306
  64. package/lib/local-embedding-protocol.js +210 -210
  65. package/lib/local-embedding-worker.js +682 -682
  66. package/lib/local-vector-service.js +506 -453
  67. package/lib/maintenance-ledger.js +138 -0
  68. package/lib/maintenance-review.js +103 -0
  69. package/lib/maintenance-runner.js +267 -0
  70. package/lib/managed-runtime.js +118 -118
  71. package/lib/media.js +607 -513
  72. package/lib/memory.js +5035 -4941
  73. package/lib/memu-config.js +213 -213
  74. package/lib/memu.js +565 -565
  75. package/lib/migrate.js +200 -200
  76. package/lib/mood.js +300 -300
  77. package/lib/paths.js +453 -457
  78. package/lib/port-surface.js +82 -82
  79. package/lib/preset-mount.js +85 -0
  80. package/lib/preset-scope.js +126 -126
  81. package/lib/private-links.js +567 -567
  82. package/lib/private.js +2198 -2209
  83. package/lib/prompts/global-curator.md +135 -135
  84. package/lib/prompts/image-caption.md +1 -1
  85. package/lib/prompts/private-consolidation.coding.md +39 -39
  86. package/lib/prompts/private-consolidation.md +32 -32
  87. package/lib/prompts/private-consolidation.mixed.md +37 -37
  88. package/lib/prompts/private-consolidation.rp.md +47 -47
  89. package/lib/prompts/private-policy.coding.md +35 -35
  90. package/lib/prompts/private-policy.md +36 -36
  91. package/lib/prompts/private-policy.mixed.md +29 -29
  92. package/lib/prompts/private-policy.rp.md +43 -43
  93. package/lib/prompts/system-guide.coding.md +20 -20
  94. package/lib/prompts/system-guide.md +25 -25
  95. package/lib/prompts/system-guide.mixed.md +22 -22
  96. package/lib/prompts/system-guide.rp.md +23 -23
  97. package/lib/prompts.js +331 -331
  98. package/lib/recall-cache.js +212 -212
  99. package/lib/remote-summary.js +123 -123
  100. package/lib/rpc.js +2531 -2532
  101. package/lib/salient-wake.js +438 -438
  102. package/lib/snippet.js +125 -125
  103. package/lib/state.js +1948 -1928
  104. package/lib/stats.js +236 -236
  105. package/lib/temporal.js +345 -348
  106. package/lib/text-retrieval.js +992 -1001
  107. package/lib/text-similarity.js +305 -305
  108. package/lib/tokenizer-v2.js +271 -271
  109. package/lib/tools.js +1098 -1091
  110. package/lib/turn-log.js +545 -545
  111. package/lib/vector-migration.js +928 -930
  112. package/lib/vector-profile.js +1353 -1359
  113. package/lib/visibility.js +59 -59
  114. package/lib/webui/graph-LICENSE.txt +1 -1
  115. package/lib/webui/graph-view.bundle.js +2 -2
  116. package/lib/webui/graph-view.js +1171 -1175
  117. package/lib/webui/mark.svg +7 -7
  118. package/lib/webui/standalone.css +1178 -1178
  119. package/lib/webui/standalone.js +238 -238
  120. package/lib/webui.js +136 -136
  121. package/lib/worker-pool.js +1020 -979
  122. package/package.json +153 -153
  123. package/requirements.lock +34 -34
  124. package/scripts/acceptance-local.mjs +946 -946
  125. package/scripts/active-memory-ab-live.mjs +653 -655
  126. package/scripts/active-memory-ab.mjs +1302 -1302
  127. package/scripts/audit-memory-lifecycle.mjs +55 -0
  128. package/scripts/bench-recall.mjs +142 -142
  129. package/scripts/build-graph.mjs +44 -45
  130. package/scripts/chain-matrix.mjs +541 -541
  131. package/scripts/check-all.mjs +68 -74
  132. package/scripts/check-doc-drift.mjs +547 -547
  133. package/scripts/check-graph-browser.mjs +261 -261
  134. package/scripts/check-i18n.mjs +81 -83
  135. package/scripts/check-idle-compositing.mjs +61 -61
  136. package/scripts/check-seed-compat.mjs +115 -118
  137. package/scripts/check-text-format.mjs +55 -0
  138. package/scripts/curator-pair-calibrate.mjs +259 -259
  139. package/scripts/diagnose-bindings.mjs +176 -176
  140. package/scripts/drive-session.mjs +863 -864
  141. package/scripts/engine-smoke.mjs +69 -69
  142. package/scripts/entity-dedupe.mjs +110 -110
  143. package/scripts/lexicon-calibrate.mjs +230 -230
  144. package/scripts/lexicon-dedupe.mjs +318 -318
  145. package/scripts/local-runtime-install.mjs +142 -142
  146. package/scripts/local-runtime-verify.mjs +56 -56
  147. package/scripts/local-vector-verify.mjs +93 -93
  148. package/scripts/make-readme-shots.mjs +59 -59
  149. package/scripts/migrate-visibility.mjs +94 -94
  150. package/scripts/mock-llm.mjs +938 -903
  151. package/scripts/preview.mjs +58 -58
  152. package/scripts/prune-sessions.mjs +31 -34
  153. package/scripts/prune-turnlogs.mjs +29 -30
  154. package/scripts/prune-vectors.mjs +24 -24
  155. package/scripts/rebuild-auto-links.mjs +252 -252
  156. package/scripts/recall-bench.mjs +820 -820
  157. package/scripts/repetition-ab-scenarios.mjs +93 -93
  158. package/scripts/repetition-detector-snapshot.mjs +314 -314
  159. package/scripts/repetition-eval-live.mjs +360 -360
  160. package/scripts/repetition-eval.mjs +702 -702
  161. package/scripts/replay.mjs +705 -575
  162. package/scripts/setup.mjs +46 -46
  163. package/scripts/simulate-injection.mjs +299 -301
  164. package/tests/absorb-review.test.mjs +354 -354
  165. package/tests/activation.test.mjs +89 -89
  166. package/tests/active-memory-ab.test.mjs +745 -745
  167. package/tests/active-memory.test.mjs +129 -129
  168. package/tests/activity-log.test.mjs +126 -126
  169. package/tests/activity-wiring.test.mjs +155 -155
  170. package/tests/appendix-b.test.mjs +217 -217
  171. package/tests/appendix-b2.test.mjs +166 -166
  172. package/tests/audit-batch3.test.mjs +247 -247
  173. package/tests/audit-regression.test.mjs +275 -275
  174. package/tests/audit-safety.test.mjs +227 -227
  175. package/tests/auto-link-candidates.test.mjs +245 -245
  176. package/tests/auto-link-decide.test.mjs +512 -512
  177. package/tests/auto-link-migration.test.mjs +133 -133
  178. package/tests/backend-compensation.test.mjs +272 -272
  179. package/tests/backup.test.mjs +793 -793
  180. package/tests/binding-diagnostics.test.mjs +720 -720
  181. package/tests/browser.test.mjs +476 -476
  182. package/tests/client-export.test.mjs +521 -521
  183. package/tests/client-render.test.mjs +2008 -1728
  184. package/tests/coalesce.test.mjs +113 -113
  185. package/tests/commitment.test.mjs +243 -144
  186. package/tests/config.test.mjs +159 -159
  187. package/tests/consolidation-credential.test.mjs +330 -330
  188. package/tests/consolidation-feed.test.mjs +122 -122
  189. package/tests/consolidation-fork.test.mjs +1587 -1539
  190. package/tests/consolidation-ledger.test.mjs +389 -389
  191. package/tests/consolidation-snapshot.test.mjs +567 -505
  192. package/tests/consolidation-value.test.mjs +89 -89
  193. package/tests/context-scope.test.mjs +40 -40
  194. package/tests/cross-library-recall.test.mjs +269 -269
  195. package/tests/cue.test.mjs +58 -58
  196. package/tests/curator-absorb.test.mjs +444 -444
  197. package/tests/curator-calibrate.test.mjs +173 -173
  198. package/tests/curator-clusters.test.mjs +306 -306
  199. package/tests/curator-commit.test.mjs +325 -325
  200. package/tests/curator-contract.test.mjs +191 -191
  201. package/tests/curator-evidence.test.mjs +102 -102
  202. package/tests/curator-link.test.mjs +317 -317
  203. package/tests/curator-pairing.test.mjs +339 -339
  204. package/tests/curator-probe.test.mjs +490 -490
  205. package/tests/curator-review-mode.test.mjs +315 -315
  206. package/tests/curator.test.mjs +152 -152
  207. package/tests/cycle.test.mjs +567 -568
  208. package/tests/diagnostics.test.mjs +278 -278
  209. package/tests/disclosure.test.mjs +249 -249
  210. package/tests/doc-drift.test.mjs +342 -342
  211. package/tests/drive-session.test.mjs +152 -152
  212. package/tests/dynamic-rrf.test.mjs +182 -182
  213. package/tests/dynamic-threshold.test.mjs +52 -52
  214. package/tests/embedding-catalog.test.mjs +374 -374
  215. package/tests/embedding-download.test.mjs +529 -486
  216. package/tests/embedding-runtime.test.mjs +449 -449
  217. package/tests/emotion-chain.test.mjs +84 -84
  218. package/tests/emotion-contract.test.mjs +445 -445
  219. package/tests/engine.test.mjs +108 -108
  220. package/tests/entity-merge.test.mjs +278 -278
  221. package/tests/environment-check.test.mjs +187 -187
  222. package/tests/fact-version.test.mjs +146 -146
  223. package/tests/fixtures/active-memory-ab/README.md +56 -56
  224. package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
  225. package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
  226. package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
  227. package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
  228. package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
  229. package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
  230. package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
  231. package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
  232. package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
  233. package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
  234. package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
  235. package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
  236. package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
  237. package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
  238. package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
  239. package/tests/fixtures/active-memory-ab/manifest.json +199 -199
  240. package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
  241. package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
  242. package/tests/fixtures/lexicon-stub.mjs +284 -284
  243. package/tests/fixtures/mock-llm/reply.txt +1 -1
  244. package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
  245. package/tests/fixtures/recall-bench/02-exact.json +152 -152
  246. package/tests/fixtures/recall-bench/03-negation.json +172 -172
  247. package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
  248. package/tests/fixtures/recall-bench/05-conflict.json +193 -193
  249. package/tests/fixtures/recall-bench/06-boundary.json +272 -272
  250. package/tests/fixtures/recall-bench/07-secret.json +190 -190
  251. package/tests/fixtures/recall-bench/08-coding.json +163 -163
  252. package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
  253. package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
  254. package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
  255. package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
  256. package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
  257. package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
  258. package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
  259. package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
  260. package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
  261. package/tests/fixtures/repetition-eval/02-en.json +96 -96
  262. package/tests/fixtures/repetition-eval/03-code.json +90 -90
  263. package/tests/fixtures/repetition-eval/04-names.json +115 -115
  264. package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
  265. package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
  266. package/tests/fixtures/tokenizer-cases.mjs +27 -27
  267. package/tests/fork-model.test.mjs +345 -345
  268. package/tests/freshness.test.mjs +140 -140
  269. package/tests/global-graph.test.mjs +106 -106
  270. package/tests/global-lifecycle.test.mjs +149 -149
  271. package/tests/graph-cascade.test.mjs +363 -363
  272. package/tests/graph-view.test.mjs +414 -414
  273. package/tests/graph.test.mjs +371 -371
  274. package/tests/help-page.test.mjs +416 -416
  275. package/tests/hook-order.test.mjs +72 -72
  276. package/tests/humanlike.test.mjs +232 -232
  277. package/tests/hybrid-recall.test.mjs +610 -610
  278. package/tests/inbound.test.mjs +441 -441
  279. package/tests/inject-conflict.test.mjs +173 -173
  280. package/tests/inject-guide.test.mjs +513 -513
  281. package/tests/inject.test.mjs +384 -384
  282. package/tests/injection-budget-settings.test.mjs +35 -35
  283. package/tests/injection-budget.test.mjs +165 -165
  284. package/tests/injection-chain.test.mjs +442 -442
  285. package/tests/injection-intent-budget.test.mjs +92 -92
  286. package/tests/injection-rollback.test.mjs +428 -428
  287. package/tests/issue2-chain.test.mjs +169 -169
  288. package/tests/lexical-bm25.test.mjs +171 -171
  289. package/tests/lexicon-calibrate.test.mjs +48 -48
  290. package/tests/lexicon-dedupe.test.mjs +171 -171
  291. package/tests/lexicon-frequency.test.mjs +195 -195
  292. package/tests/lexicon-inject.test.mjs +459 -459
  293. package/tests/lexicon-perf.test.mjs +464 -464
  294. package/tests/lexicon-scope.test.mjs +256 -256
  295. package/tests/lexicon-ui.test.mjs +667 -667
  296. package/tests/lexicon.test.mjs +922 -922
  297. package/tests/lifecycle-audit.test.mjs +56 -0
  298. package/tests/loader-register.mjs +3 -3
  299. package/tests/loader.mjs +17 -17
  300. package/tests/local-embedding-entry.test.mjs +95 -95
  301. package/tests/local-embedding-env.test.mjs +51 -51
  302. package/tests/local-embedding-manager.test.mjs +494 -494
  303. package/tests/local-embedding-protocol.test.mjs +121 -121
  304. package/tests/local-embedding-worker.test.mjs +440 -440
  305. package/tests/local-vector-service.test.mjs +41 -0
  306. package/tests/maintenance-status.test.mjs +77 -0
  307. package/tests/maintenance.test.mjs +438 -0
  308. package/tests/managed-memory.test.mjs +1234 -1234
  309. package/tests/managed-runtime.test.mjs +72 -72
  310. package/tests/media-injection.test.mjs +225 -0
  311. package/tests/media.test.mjs +135 -135
  312. package/tests/memory-chain.test.mjs +169 -169
  313. package/tests/memory-fields.test.mjs +134 -134
  314. package/tests/memu-resident-route.test.mjs +130 -130
  315. package/tests/memu-resident.test.mjs +33 -33
  316. package/tests/migration-payload.test.mjs +40 -42
  317. package/tests/mock-llm.test.mjs +263 -225
  318. package/tests/mood.test.mjs +109 -109
  319. package/tests/multiprocess.test.mjs +29 -29
  320. package/tests/negation-polarity.test.mjs +135 -135
  321. package/tests/new-session-gate.test.mjs +617 -617
  322. package/tests/open-loop-date.test.mjs +416 -416
  323. package/tests/ops-hardening.test.mjs +209 -209
  324. package/tests/package-shipping.test.mjs +88 -88
  325. package/tests/pending-injection.test.mjs +107 -107
  326. package/tests/port-surface.test.mjs +138 -138
  327. package/tests/preset-mount.test.mjs +132 -0
  328. package/tests/preset-scope.test.mjs +212 -212
  329. package/tests/private-links.test.mjs +493 -493
  330. package/tests/prompt-semantics.test.mjs +51 -51
  331. package/tests/prompts.test.mjs +315 -315
  332. package/tests/query-decompose.test.mjs +62 -62
  333. package/tests/react-snapshot.test.mjs +24 -24
  334. package/tests/recall-bench.test.mjs +317 -317
  335. package/tests/recall-cache.test.mjs +292 -292
  336. package/tests/recall-corpus-eligibility.test.mjs +51 -51
  337. package/tests/recall-dedup.test.mjs +446 -446
  338. package/tests/recall-intent.test.mjs +172 -172
  339. package/tests/regression-sweep.test.mjs +311 -311
  340. package/tests/reminder-fairness.test.mjs +55 -0
  341. package/tests/remote.test.mjs +140 -140
  342. package/tests/rename.test.mjs +30 -30
  343. package/tests/repetition-detector-snapshot.test.mjs +231 -231
  344. package/tests/repetition-eval-live.test.mjs +177 -177
  345. package/tests/repetition-eval.test.mjs +373 -373
  346. package/tests/salience-domain.test.mjs +173 -173
  347. package/tests/salient-date.test.mjs +142 -142
  348. package/tests/salient-wake.test.mjs +389 -389
  349. package/tests/settings-beat.test.mjs +222 -222
  350. package/tests/settings-coverage.test.mjs +97 -97
  351. package/tests/settings-plumbing.test.mjs +79 -79
  352. package/tests/short-term.test.mjs +182 -166
  353. package/tests/sidebar-beat.test.mjs +213 -213
  354. package/tests/sidebar-refresh.test.mjs +123 -123
  355. package/tests/sidebar.test.mjs +102 -74
  356. package/tests/simulate-injection.test.mjs +76 -76
  357. package/tests/slot-similarity.test.mjs +153 -153
  358. package/tests/snippet.test.mjs +79 -79
  359. package/tests/source-kind.test.mjs +52 -52
  360. package/tests/speaker-provenance.test.mjs +120 -120
  361. package/tests/stale-maintenance.test.mjs +206 -131
  362. package/tests/state-gc.test.mjs +34 -34
  363. package/tests/state.test.mjs +155 -155
  364. package/tests/stats.test.mjs +112 -112
  365. package/tests/storage.test.mjs +125 -125
  366. package/tests/stubs/child-process-spy.mjs +14 -14
  367. package/tests/stubs/dsh-llm-pi-ai.js +13 -13
  368. package/tests/stubs/dsh-llm.js +5 -5
  369. package/tests/stubs/dsh-schedule.js +140 -140
  370. package/tests/stubs/dsh-session-query.js +26 -26
  371. package/tests/stubs/dsh-session.js +7 -7
  372. package/tests/stubs/dsh-tools.js +101 -101
  373. package/tests/temporal-repair.test.mjs +78 -0
  374. package/tests/temporal.test.mjs +124 -124
  375. package/tests/text-format.test.mjs +24 -0
  376. package/tests/tokenizer-v2.test.mjs +142 -142
  377. package/tests/tool-schema.test.mjs +126 -126
  378. package/tests/tools.test.mjs +810 -810
  379. package/tests/turn-log.test.mjs +487 -487
  380. package/tests/ui-defaults.test.mjs +57 -57
  381. package/tests/update-fields.test.mjs +138 -138
  382. package/tests/vector-gc.test.mjs +37 -37
  383. package/tests/vector-migration.test.mjs +810 -810
  384. package/tests/vector-profile.test.mjs +449 -449
  385. package/tests/visibility-migration.test.mjs +152 -152
  386. package/tests/webui-auth.test.mjs +963 -963
  387. package/tests/webui.test.mjs +421 -421
  388. package/tests/windows-env.test.mjs +89 -89
  389. package/tests/worker-lifecycle.test.mjs +1522 -1429
@@ -1,438 +1,438 @@
1
- // 工单 E:纪念日到点唤醒(todolist #1)。
2
- //
3
- // 用宿主公开的 `ctx.schedule` 在**投递时区**(`salientWakeTimeZone`,留空跟随系统)的今天/
4
- // 明天到点时,给绑定会话排一条一次性任务。日期与「这一刻过去了吗」都按那个时区算,不然配置
5
- // 时区与机器时区不一致时会排错一天,或把还没到的时刻当成已过而静默跳过。
6
- // schedule 的投递是 `agent.followup(createUserMessage({source:{kind:'schedule'}}))`,
7
- // 会开一整回合,而本插件的注入只认 `source.kind === 'user'` 的真实用户消息 —— 所以
8
- // 这一回合拿不到锚点、召回或纪念日块,prompt 必须自包含。
9
- //
10
- // 这个 pass 只做三件事:读索引找出今天/明天要提的日期记忆、按 `memu:due:` 标题做
11
- // 幂等、把任务交给宿主。它从不抛错(宿主可能根本没有 schedule 服务),也从不覆盖
12
- // 用户的显式操作(暂停的任务不恢复),更不会把正文写进 prompt。没有任何会话需要
13
- // 提醒时它连 `schedule.list` 都不发——空闲装机不该每 5 分钟碰一次宿主的任务表。
14
- //
15
- // 返回值有两种形状,调用方要同时接受:
16
- // - 整个 pass 没跑:`{ skipped: '<off|service|schedule-api|timezone|time>' }`
17
- // - 跑过一轮:`{ created, cleaned, skipped, errors }`(都是计数)
18
- import { getSettings, listSessionBindings, loadPrivateIndex, effectiveScope } from './state.js'
19
- import {
20
- isDatedSalientDate, isMemoryEligible, salientDateFires, salientDaysAhead, visibleToSession,
21
- } from './memory.js'
22
- import { record } from './activity-log.js'
23
-
24
- const DEFAULT_HOUR = '09:00'
25
- const HOUR_RE = /^([01]\d|2[0-3]):[0-5]\d$/
26
- // 宿主 list 的上限是 500(types.ts `ScheduleListRequest.limit` 1-500)。一次 sweep
27
- // 只读一页:这插件每会话每天最多两条任务,500 条已经远超正常装机量。
28
- const LIST_LIMIT = 500
29
- // 一条 prompt 最多列这么多条日期;其余用一句话指回 memu_private_recall,避免一个
30
- // 大库把 schedule 回合的开场白撑成一页目录。
31
- const MAX_LINES = 8
32
- // 宿主拒绝投递的错误码里,这两种是"这个目标本来就不该有提醒",不是故障。
33
- const SKIP_CODES = new Set(['subagent_session', 'invalid_rule'])
34
- const KNOWN_CODES = [
35
- 'subagent_session', 'invalid_rule', 'invalid_time_zone', 'not_future', 'invalid_selector',
36
- 'invalid_prompt', 'time_out_of_range', 'frequency_too_high', 'internal_error',
37
- ]
38
-
39
- // "一次 warn":宿主没有 schedule 服务是装机事实,不必每 5 分钟重复一遍日志。
40
- let serviceWarned = false
41
- // 0.2.0/0.2.1 的 schedule 是会话级 API;本 pass 用的是 0.2.2 起的宿主级任务表。
42
- // 这是能力差异,不是每次 sweep 的故障,同样只提醒一次。
43
- let sessionScopedWarned = false
44
- // 坏时区按取值去重:同一串坏配置只吵一次,换成另一串再吵。
45
- let zoneWarnedFor = null
46
-
47
- /**
48
- * Which schedule API a host exposes.
49
- *
50
- * - `global`: 0.2.2+ creates a host-wide task from one request
51
- * (`create(request)`, `list(request) -> { items }`, `edit({ id, action })`).
52
- * - `session`: 0.2.0/0.2.1 binds every reminder to one session
53
- * (`create(sessionId, request)`, `list({ sessionId }) -> array`, `delete({ sessionId, id })`).
54
- *
55
- * The pass only implements the host-wide shape. Probing structurally (instead of
56
- * comparing versions) keeps this working when a host backports or renames the
57
- * service, and lets an old host skip with one readable line instead of failing
58
- * the same `list` call every sweep.
59
- */
60
- export function scheduleFlavor(schedule) {
61
- if (!schedule || typeof schedule.create !== 'function' || typeof schedule.list !== 'function') return null
62
- if (typeof schedule.edit === 'function') return 'global'
63
- if (typeof schedule.delete === 'function') return 'session'
64
- return null
65
- }
66
-
67
- function pad2(value) {
68
- return String(value).padStart(2, '0')
69
- }
70
-
71
- // 墙上时刻读取按 zone 复用 formatter:这条 pass 每 5 分钟跑一次,构造 Intl 对象不是免费的。
72
- const wallFormatters = new Map()
73
-
74
- function wallParts(instant, zone) {
75
- let fmt = wallFormatters.get(zone)
76
- if (!fmt) {
77
- fmt = new Intl.DateTimeFormat('en-US', {
78
- timeZone: zone, hourCycle: 'h23',
79
- year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit',
80
- })
81
- wallFormatters.set(zone, fmt)
82
- }
83
- const parts = {}
84
- for (const part of fmt.formatToParts(new Date(instant))) {
85
- if (part.type !== 'literal') parts[part.type] = Number(part.value)
86
- }
87
- return parts
88
- }
89
-
90
- /**
91
- * 某个绝对时刻在指定时区里落在哪个日历日,以及那天的「今天/明天」载体。
92
- *
93
- * 日期必须按**投递时区**算,不是系统时区:`salientWakeTimeZone` 填了 UTC 而机器在上海时,
94
- * 用系统墙钟得到的「今天」比配置时区早一天,今天 09:00(UTC) 明明还没到也会被当成已过而静默跳过。
95
- * 载体 Date 只用来喂 `salientDateFires`/`salientDaysAhead`(它们读 getMonth/getDate),正午锚点
96
- * 避开夏令时在午夜附近造出的「这一天不存在 00:00」。
97
- */
98
- export function dayInZone(instant, zone, offsetDays = 0) {
99
- const w = wallParts(instant, zone)
100
- const day = new Date(w.year, w.month - 1, w.day + offsetDays, 12, 0, 0, 0)
101
- return { day, date: `${day.getFullYear()}-${pad2(day.getMonth() + 1)}-${pad2(day.getDate())}` }
102
- }
103
-
104
- /**
105
- * 「该时区的 dateKey hour」对应的绝对毫秒。先把它当 UTC 猜一次,再用该时区在那个瞬间的偏移
106
- * 修正;迭代到不动为止(DST 跳变时第二次才收敛),三次是上限兜底。
107
- * 严格未来判断必须用它:宿主要按 `at.time_zone` 解释日期与时分。
108
- */
109
- export function instantInZone(dateKey, hour, zone) {
110
- const [year, month, day] = String(dateKey).split('-').map(Number)
111
- const [hh, mm] = String(hour).split(':').map(Number)
112
- const target = Date.UTC(year, month - 1, day, hh, mm, 0, 0)
113
- if (!Number.isFinite(target)) return NaN
114
- let instant = target
115
- for (let i = 0; i < 3; i += 1) {
116
- const w = wallParts(instant, zone)
117
- const offset = Date.UTC(w.year, w.month - 1, w.day, w.hour, w.minute, w.second) - instant
118
- const next = target - offset
119
- if (next === instant) break
120
- instant = next
121
- }
122
- return instant
123
- }
124
-
125
- // 时区:显式配置优先,空串跟随系统。空或无效一律返回 null —— 少一条提醒,不是把
126
- // 宿主的时间算错。
127
- function resolveZone(settings) {
128
- const configured = typeof settings?.salientWakeTimeZone === 'string' ? settings.salientWakeTimeZone.trim() : ''
129
- let zone = configured
130
- if (!zone) {
131
- try { zone = String(Intl.DateTimeFormat().resolvedOptions().timeZone || '') } catch { zone = '' }
132
- }
133
- if (!zone) return null
134
- try {
135
- new Intl.DateTimeFormat('en-US', { timeZone: zone })
136
- return zone
137
- } catch {
138
- return null
139
- }
140
- }
141
-
142
- function resolveHour(settings) {
143
- const hour = String(settings?.salientWakeHour ?? '')
144
- if (HOUR_RE.test(hour)) return { hour, fallback: false }
145
- return { hour: DEFAULT_HOUR, fallback: true }
146
- }
147
-
148
- // 宿主会把这些拒绝原样抛成 `ScheduleInputError`(本地服务)或带 details 的
149
- // `RemoteError`(远程传输),两边的 code 位置不同,所以逐个探。
150
- function scheduleErrorCode(error) {
151
- for (const value of [error?.code, error?.details?.code, error?.data?.code]) {
152
- if (typeof value === 'string' && value) return value
153
- }
154
- const text = String(error?.message || error || '')
155
- return KNOWN_CODES.find((code) => text.includes(code)) || ''
156
- }
157
-
158
- function safeTitle(entry) {
159
- // 标题进的是另一回合的开场白:压平换行,别让一条记忆在 prompt 里伪造出新的行。
160
- const text = String(entry?.title || '').replace(/\s+/g, ' ').trim()
161
- return (text || '(untitled)').slice(0, 120)
162
- }
163
-
164
- // 相对"投递日"的措辞:ahead 0 = 今天,ahead 1 = 明天(保留提前一天的语义)。
165
- // 年度日期只在当天触发,因此永远是"今天"。
166
- function whenLabel(entry, day) {
167
- if (!isDatedSalientDate(entry?.salientDate)) return '今天'
168
- return salientDaysAhead(entry.salientDate, day) === 1 ? '明天' : '今天'
169
- }
170
-
171
- function entryLine({ entry }, day) {
172
- const when = whenLabel(entry, day)
173
- const annual = !isDatedSalientDate(entry?.salientDate)
174
- const date = annual ? `每年 ${String(entry?.salientDate || '')}` : String(entry?.salientDate || '')
175
- const title = safeTitle(entry)
176
- // 承诺和日程的语气不同,与 lib/inject.js 的 `<memory-due>` 保持一致:答应了又
177
- // 没做的事听起来是欠账,不是事件。正文一律不进 prompt —— 标题就是目录。
178
- if (entry?.openLoop === true) return `- ${when}:你之前答应过的「${title}」,就是${when}(${date})。`
179
- return `- ${when}:${title}(${date})。`
180
- }
181
-
182
- function buildPrompt({ dateKey, day, hits }) {
183
- const lines = [`[dsh-memu-memory 日期提醒] 本轮日期 ${dateKey}。今天/明天是:`]
184
- for (const hit of hits.slice(0, MAX_LINES)) lines.push(entryLine(hit, day))
185
- if (hits.length > MAX_LINES) lines.push(`- 另有 ${hits.length - MAX_LINES} 条日期记忆,用 memu_private_recall 查。`)
186
- // schedule 回合不触发本插件注入,所以这句是唯一的上下文来源;"不要重复"是宿主
187
- // at-least-once 投递的唯一缓冲。
188
- lines.push('这是记忆里记下的日期;需要细节用 memu_private_recall 查。若你已经说过,不要重复。')
189
- return lines.join('\n')
190
- }
191
-
192
- // 与 `buildAnniversary` 同一套门:可自动注入、非 secret 正文、对本会话可见。
193
- function dueEntries(index, sessionId, day, nowMs) {
194
- const hits = []
195
- for (const [id, entry] of Object.entries(index?.entries || {})) {
196
- if (!entry || typeof entry !== 'object') continue
197
- if (!entry.salientDate) continue
198
- if (entry.visibility === 'secret') continue
199
- if (!salientDateFires(entry.salientDate, day)) continue
200
- if (!isMemoryEligible(entry, { automatic: true, now: nowMs })) continue
201
- try {
202
- if (!visibleToSession(entry, sessionId)) continue
203
- } catch {
204
- continue
205
- }
206
- hits.push({ id, entry })
207
- }
208
- hits.sort((a, b) => String(a.entry.salientDate).localeCompare(String(b.entry.salientDate))
209
- || String(a.entry.title || '').localeCompare(String(b.entry.title || '')))
210
- return hits
211
- }
212
-
213
- function byTitleIndex(items) {
214
- const map = new Map()
215
- for (const item of items) {
216
- if (!item || typeof item.title !== 'string') continue
217
- const list = map.get(item.title) || []
218
- list.push(item)
219
- map.set(item.title, list)
220
- }
221
- return map
222
- }
223
-
224
- /**
225
- * One sweep of the salient-date wake pass (work order E).
226
- *
227
- * Creates one host schedule task per conversation and target date, titled
228
- * `memu:due:<sessionId>:<YYYY-MM-DD>`, so a second sweep is a no-op. Never throws;
229
- * a host without the optional `schedule` service is a skip, not a failure.
230
- *
231
- * @param {object} ctx host context (`ctx.get('schedule')` is optional)
232
- * @param {{ now?: Date|number, log?: (message: string) => void }} [options]
233
- * @returns {{ skipped: string } | { created: number, cleaned: number, skipped: number, errors: number }}
234
- */
235
- export async function runSalientWakePass(ctx, { now = new Date(), log = () => {} } = {}) {
236
- const notify = (message) => { try { log(message) } catch {} }
237
- const stats = { created: 0, cleaned: 0, skipped: 0, errors: 0 }
238
- try {
239
- const settings = getSettings()
240
- if (settings.salientWake !== 'schedule') return { skipped: 'off' }
241
-
242
- let schedule = null
243
- try { schedule = ctx?.get?.('schedule') || null } catch { schedule = null }
244
- const flavor = scheduleFlavor(schedule)
245
- if (flavor === null) {
246
- if (!serviceWarned) {
247
- serviceWarned = true
248
- notify('salient wake is enabled but this host exposes no schedule service; skipping')
249
- record({
250
- kind: 'wake', level: 'warn', ok: false,
251
- message: '日期唤醒已启用,但宿主没有 schedule 服务;本轮跳过',
252
- detail: { trigger: 'wake', stage: 'service' },
253
- })
254
- }
255
- return { skipped: 'service' }
256
- }
257
- if (flavor === 'session') {
258
- if (!sessionScopedWarned) {
259
- sessionScopedWarned = true
260
- notify('salient wake needs the host-wide schedule API (0.2.2+); this host exposes session-scoped reminders, skipping')
261
- record({
262
- kind: 'wake', level: 'warn', ok: false,
263
- message: '日期唤醒需要宿主级 schedule API(0.2.2+);当前宿主只有会话级提醒,本轮跳过',
264
- detail: { trigger: 'wake', stage: 'schedule-api' },
265
- })
266
- }
267
- return { skipped: 'schedule-api' }
268
- }
269
-
270
- const when = now instanceof Date ? now : new Date(now)
271
- if (!Number.isFinite(when.getTime())) return { skipped: 'time' }
272
-
273
- const zone = resolveZone(settings)
274
- if (!zone) {
275
- const key = String(settings?.salientWakeTimeZone ?? '')
276
- if (zoneWarnedFor !== key) {
277
- zoneWarnedFor = key
278
- notify(`salient wake skipped: no usable IANA time zone (configured ${JSON.stringify(key)})`)
279
- record({
280
- kind: 'wake', level: 'warn', ok: false,
281
- message: '日期唤醒已跳过:时区为空或无效',
282
- detail: { trigger: 'wake', stage: 'timezone', zone: key || null },
283
- })
284
- }
285
- return { skipped: 'timezone' }
286
- }
287
-
288
- const { hour, fallback } = resolveHour(settings)
289
- if (fallback) notify(`salient wake: invalid salientWakeHour ${JSON.stringify(settings?.salientWakeHour)}; using ${DEFAULT_HOUR}`)
290
-
291
- // 先把"要提醒什么"算完:没有会话需要提醒时,一次宿主调用都不发。
292
- const today = dayInZone(when.getTime(), zone, 0)
293
- const tomorrow = dayInZone(when.getTime(), zone, 1)
294
- const nowMs = when.getTime()
295
- const plans = []
296
- for (const binding of listSessionBindings()) {
297
- const sessionId = binding?.sessionId
298
- if (!sessionId || !binding.libraryId) continue
299
- if (binding.useLibrary === false) continue
300
- try {
301
- if (!effectiveScope(binding).useLibrary) continue
302
- } catch {
303
- continue
304
- }
305
- let index
306
- try {
307
- index = loadPrivateIndex(binding.libraryId)
308
- } catch (error) {
309
- // 库没了/索引坏了:这一个会话跳过,其他会话照跑。
310
- stats.errors += 1
311
- const message = String(error?.message || error)
312
- notify(`salient wake: cannot read library ${binding.libraryId}: ${message}`)
313
- record({
314
- kind: 'wake', scope: 'private', sessionId, libraryId: binding.libraryId, level: 'warn', ok: false,
315
- message: '日期唤醒:读取记忆库失败:' + message,
316
- detail: { trigger: 'wake', stage: 'index' },
317
- })
318
- continue
319
- }
320
- for (const target of [today, tomorrow]) {
321
- const hits = dueEntries(index, sessionId, target.day, nowMs)
322
- if (hits.length === 0) continue
323
- plans.push({ sessionId, libraryId: binding.libraryId, target: { ...target, hits } })
324
- }
325
- }
326
- if (plans.length === 0) return stats
327
-
328
- let items = []
329
- try {
330
- const page = await schedule.list({ limit: LIST_LIMIT })
331
- items = Array.isArray(page?.items) ? page.items : []
332
- } catch (error) {
333
- const message = String(error?.message || error)
334
- stats.errors += 1
335
- notify(`salient wake: schedule.list failed: ${message}`)
336
- record({
337
- kind: 'wake', level: 'warn', ok: false,
338
- message: '日期唤醒:读取定时任务失败:' + message,
339
- detail: { trigger: 'wake', stage: 'list', code: scheduleErrorCode(error) || null },
340
- })
341
- return stats
342
- }
343
- const byTitle = byTitleIndex(items)
344
-
345
- for (const plan of plans) {
346
- const { sessionId, libraryId, target } = plan
347
- const title = `memu:due:${sessionId}:${target.date}`
348
- const existing = byTitle.get(title) || []
349
- // ended 的任务说明这一天的投递已经发生过(at-least-once),清掉即可,不再补建。
350
- const ended = existing.filter((item) => item?.status === 'ended')
351
- for (const item of ended) {
352
- if (!item?.id) continue
353
- try {
354
- await schedule.edit({ id: item.id, action: 'delete' })
355
- stats.cleaned += 1
356
- notify(`salient wake: removed ended task ${item.id} (${title})`)
357
- } catch (error) {
358
- const message = String(error?.message || error)
359
- stats.errors += 1
360
- notify(`salient wake: could not remove ended task ${item.id}: ${message}`)
361
- record({
362
- kind: 'wake', scope: 'private', sessionId, libraryId, level: 'warn', ok: false,
363
- message: '日期唤醒:清理已结束任务失败:' + message,
364
- detail: { trigger: 'wake', stage: 'cleanup', title, code: scheduleErrorCode(error) || null },
365
- })
366
- }
367
- }
368
- // active 是幂等的证据;paused 是用户的显式暂停,绝不擅自恢复。
369
- if (existing.some((item) => item?.status === 'active') || existing.some((item) => item?.status === 'paused')) {
370
- stats.skipped += 1
371
- continue
372
- }
373
- if (ended.length > 0) {
374
- stats.skipped += 1
375
- continue
376
- }
377
- // 严格未来:今天的 09:00 已经过去就不排今天(被动注入仍然会提),明天照排。
378
- // 严格未来:按**投递时区**判断这一刻有没有过去。今天的 09:00 已经过去就不排今天
379
- // (被动注入仍然会提),明天照排。
380
- if (!(instantInZone(target.date, hour, zone) > when.getTime())) {
381
- stats.skipped += 1
382
- continue
383
- }
384
- const prompt = buildPrompt({ dateKey: target.date, day: target.day, hits: target.hits })
385
- try {
386
- const created = await schedule.create({
387
- title,
388
- prompt,
389
- timing: { kind: 'at', at: { date: target.date, time: hour, time_zone: zone } },
390
- target: { kind: 'session', sessionId },
391
- })
392
- stats.created += 1
393
- byTitle.set(title, [...existing, created || { title, status: 'active' }])
394
- notify(`salient wake: scheduled ${title} at ${target.date} ${hour} ${zone}`)
395
- record({
396
- kind: 'wake', scope: 'private', sessionId, libraryId, ok: true,
397
- message: `日期唤醒已排程:${target.date} ${hour}(${target.hits.length} 条)`,
398
- detail: {
399
- trigger: 'wake', stage: 'create', date: target.date, hour, zone,
400
- ids: target.hits.map((hit) => hit.id).slice(0, 20), taskId: created?.id || null,
401
- },
402
- })
403
- } catch (error) {
404
- const code = scheduleErrorCode(error)
405
- const message = String(error?.message || error)
406
- if (SKIP_CODES.has(code)) {
407
- stats.skipped += 1
408
- notify(`salient wake: ${title} skipped (${code})`)
409
- record({
410
- kind: 'wake', scope: 'private', sessionId, libraryId, ok: true,
411
- message: `日期唤醒跳过(${code}):该目标不收 schedule 投递`,
412
- detail: { trigger: 'wake', stage: 'create', title, code },
413
- })
414
- } else {
415
- stats.errors += 1
416
- notify(`salient wake: ${title} failed: ${message}`)
417
- record({
418
- kind: 'wake', scope: 'private', sessionId, libraryId, level: 'warn', ok: false,
419
- message: '日期唤醒排程失败:' + message,
420
- detail: { trigger: 'wake', stage: 'create', title, code: code || null },
421
- })
422
- }
423
- }
424
- }
425
- return stats
426
- } catch (error) {
427
- // 兜底:这个 pass 的最后一道保险。循环里的每一步已经各自 try 过,走到这里说明
428
- // 是没预料到的形状(例如 state.json 读到一半坏了),不能让 cycle 的 await 炸掉。
429
- stats.errors += 1
430
- notify(`salient wake pass failed: ${error?.message || error}`)
431
- record({
432
- kind: 'wake', level: 'warn', ok: false,
433
- message: '日期唤醒整体失败:' + String(error?.message || error),
434
- detail: { trigger: 'wake', stage: 'pass' },
435
- })
436
- return stats
437
- }
438
- }
1
+ // 基于日期与纪念日的宿主定时唤醒。
2
+ //
3
+ // 用宿主公开的 `ctx.schedule` 在**投递时区**(`salientWakeTimeZone`,留空跟随系统)的今天/
4
+ // 明天到点时,给绑定会话排一条一次性任务。日期与「这一刻过去了吗」都按那个时区算,不然配置
5
+ // 时区与机器时区不一致时会排错一天,或把还没到的时刻当成已过而静默跳过。
6
+ // schedule 的投递是 `agent.followup(createUserMessage({source:{kind:'schedule'}}))`,
7
+ // 会开一整回合,而本插件的注入只认 `source.kind === 'user'` 的真实用户消息 —— 所以
8
+ // 这一回合拿不到锚点、召回或纪念日块,prompt 必须自包含。
9
+ //
10
+ // 这个 pass 只做三件事:读索引找出今天/明天要提的日期记忆、按 `memu:due:` 标题做
11
+ // 幂等、把任务交给宿主。它从不抛错(宿主可能根本没有 schedule 服务),也从不覆盖
12
+ // 用户的显式操作(暂停的任务不恢复),更不会把正文写进 prompt。没有任何会话需要
13
+ // 提醒时它连 `schedule.list` 都不发——空闲装机不该每 5 分钟碰一次宿主的任务表。
14
+ //
15
+ // 返回值有两种形状,调用方要同时接受:
16
+ // - 整个 pass 没跑:`{ skipped: '<off|service|schedule-api|timezone|time>' }`
17
+ // - 跑过一轮:`{ created, cleaned, skipped, errors }`(都是计数)
18
+ import { getSettings, listSessionBindings, loadPrivateIndex, effectiveScope } from './state.js'
19
+ import {
20
+ isDatedSalientDate, isMemoryEligible, salientDateFires, salientDaysAhead, visibleToSession,
21
+ } from './memory.js'
22
+ import { record } from './activity-log.js'
23
+
24
+ const DEFAULT_HOUR = '09:00'
25
+ const HOUR_RE = /^([01]\d|2[0-3]):[0-5]\d$/
26
+ // 宿主 list 的上限是 500(types.ts `ScheduleListRequest.limit` 1-500)。一次 sweep
27
+ // 只读一页:这插件每会话每天最多两条任务,500 条已经远超正常装机量。
28
+ const LIST_LIMIT = 500
29
+ // 一条 prompt 最多列这么多条日期;其余用一句话指回 memu_private_recall,避免一个
30
+ // 大库把 schedule 回合的开场白撑成一页目录。
31
+ const MAX_LINES = 8
32
+ // 宿主拒绝投递的错误码里,这两种是"这个目标本来就不该有提醒",不是故障。
33
+ const SKIP_CODES = new Set(['subagent_session', 'invalid_rule'])
34
+ const KNOWN_CODES = [
35
+ 'subagent_session', 'invalid_rule', 'invalid_time_zone', 'not_future', 'invalid_selector',
36
+ 'invalid_prompt', 'time_out_of_range', 'frequency_too_high', 'internal_error',
37
+ ]
38
+
39
+ // "一次 warn":宿主没有 schedule 服务是装机事实,不必每 5 分钟重复一遍日志。
40
+ let serviceWarned = false
41
+ // 0.2.0/0.2.1 的 schedule 是会话级 API;本 pass 用的是 0.2.2 起的宿主级任务表。
42
+ // 这是能力差异,不是每次 sweep 的故障,同样只提醒一次。
43
+ let sessionScopedWarned = false
44
+ // 坏时区按取值去重:同一串坏配置只吵一次,换成另一串再吵。
45
+ let zoneWarnedFor = null
46
+
47
+ /**
48
+ * Which schedule API a host exposes.
49
+ *
50
+ * - `global`: 0.2.2+ creates a host-wide task from one request
51
+ * (`create(request)`, `list(request) -> { items }`, `edit({ id, action })`).
52
+ * - `session`: 0.2.0/0.2.1 binds every reminder to one session
53
+ * (`create(sessionId, request)`, `list({ sessionId }) -> array`, `delete({ sessionId, id })`).
54
+ *
55
+ * The pass only implements the host-wide shape. Probing structurally (instead of
56
+ * comparing versions) keeps this working when a host backports or renames the
57
+ * service, and lets an old host skip with one readable line instead of failing
58
+ * the same `list` call every sweep.
59
+ */
60
+ export function scheduleFlavor(schedule) {
61
+ if (!schedule || typeof schedule.create !== 'function' || typeof schedule.list !== 'function') return null
62
+ if (typeof schedule.edit === 'function') return 'global'
63
+ if (typeof schedule.delete === 'function') return 'session'
64
+ return null
65
+ }
66
+
67
+ function pad2(value) {
68
+ return String(value).padStart(2, '0')
69
+ }
70
+
71
+ // 墙上时刻读取按 zone 复用 formatter:这条 pass 每 5 分钟跑一次,构造 Intl 对象不是免费的。
72
+ const wallFormatters = new Map()
73
+
74
+ function wallParts(instant, zone) {
75
+ let fmt = wallFormatters.get(zone)
76
+ if (!fmt) {
77
+ fmt = new Intl.DateTimeFormat('en-US', {
78
+ timeZone: zone, hourCycle: 'h23',
79
+ year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit',
80
+ })
81
+ wallFormatters.set(zone, fmt)
82
+ }
83
+ const parts = {}
84
+ for (const part of fmt.formatToParts(new Date(instant))) {
85
+ if (part.type !== 'literal') parts[part.type] = Number(part.value)
86
+ }
87
+ return parts
88
+ }
89
+
90
+ /**
91
+ * 某个绝对时刻在指定时区里落在哪个日历日,以及那天的「今天/明天」载体。
92
+ *
93
+ * 日期必须按**投递时区**算,不是系统时区:`salientWakeTimeZone` 填了 UTC 而机器在上海时,
94
+ * 用系统墙钟得到的「今天」比配置时区早一天,今天 09:00(UTC) 明明还没到也会被当成已过而静默跳过。
95
+ * 载体 Date 只用来喂 `salientDateFires`/`salientDaysAhead`(它们读 getMonth/getDate),正午锚点
96
+ * 避开夏令时在午夜附近造出的「这一天不存在 00:00」。
97
+ */
98
+ export function dayInZone(instant, zone, offsetDays = 0) {
99
+ const w = wallParts(instant, zone)
100
+ const day = new Date(w.year, w.month - 1, w.day + offsetDays, 12, 0, 0, 0)
101
+ return { day, date: `${day.getFullYear()}-${pad2(day.getMonth() + 1)}-${pad2(day.getDate())}` }
102
+ }
103
+
104
+ /**
105
+ * 「该时区的 dateKey hour」对应的绝对毫秒。先把它当 UTC 猜一次,再用该时区在那个瞬间的偏移
106
+ * 修正;迭代到不动为止(DST 跳变时第二次才收敛),三次是上限兜底。
107
+ * 严格未来判断必须用它:宿主要按 `at.time_zone` 解释日期与时分。
108
+ */
109
+ export function instantInZone(dateKey, hour, zone) {
110
+ const [year, month, day] = String(dateKey).split('-').map(Number)
111
+ const [hh, mm] = String(hour).split(':').map(Number)
112
+ const target = Date.UTC(year, month - 1, day, hh, mm, 0, 0)
113
+ if (!Number.isFinite(target)) return NaN
114
+ let instant = target
115
+ for (let i = 0; i < 3; i += 1) {
116
+ const w = wallParts(instant, zone)
117
+ const offset = Date.UTC(w.year, w.month - 1, w.day, w.hour, w.minute, w.second) - instant
118
+ const next = target - offset
119
+ if (next === instant) break
120
+ instant = next
121
+ }
122
+ return instant
123
+ }
124
+
125
+ // 时区:显式配置优先,空串跟随系统。空或无效一律返回 null —— 少一条提醒,不是把
126
+ // 宿主的时间算错。
127
+ function resolveZone(settings) {
128
+ const configured = typeof settings?.salientWakeTimeZone === 'string' ? settings.salientWakeTimeZone.trim() : ''
129
+ let zone = configured
130
+ if (!zone) {
131
+ try { zone = String(Intl.DateTimeFormat().resolvedOptions().timeZone || '') } catch { zone = '' }
132
+ }
133
+ if (!zone) return null
134
+ try {
135
+ new Intl.DateTimeFormat('en-US', { timeZone: zone })
136
+ return zone
137
+ } catch {
138
+ return null
139
+ }
140
+ }
141
+
142
+ function resolveHour(settings) {
143
+ const hour = String(settings?.salientWakeHour ?? '')
144
+ if (HOUR_RE.test(hour)) return { hour, fallback: false }
145
+ return { hour: DEFAULT_HOUR, fallback: true }
146
+ }
147
+
148
+ // 宿主会把这些拒绝原样抛成 `ScheduleInputError`(本地服务)或带 details 的
149
+ // `RemoteError`(远程传输),两边的 code 位置不同,所以逐个探。
150
+ function scheduleErrorCode(error) {
151
+ for (const value of [error?.code, error?.details?.code, error?.data?.code]) {
152
+ if (typeof value === 'string' && value) return value
153
+ }
154
+ const text = String(error?.message || error || '')
155
+ return KNOWN_CODES.find((code) => text.includes(code)) || ''
156
+ }
157
+
158
+ function safeTitle(entry) {
159
+ // 标题进的是另一回合的开场白:压平换行,别让一条记忆在 prompt 里伪造出新的行。
160
+ const text = String(entry?.title || '').replace(/\s+/g, ' ').trim()
161
+ return (text || '(untitled)').slice(0, 120)
162
+ }
163
+
164
+ // 相对"投递日"的措辞:ahead 0 = 今天,ahead 1 = 明天(保留提前一天的语义)。
165
+ // 年度日期只在当天触发,因此永远是"今天"。
166
+ function whenLabel(entry, day) {
167
+ if (!isDatedSalientDate(entry?.salientDate)) return '今天'
168
+ return salientDaysAhead(entry.salientDate, day) === 1 ? '明天' : '今天'
169
+ }
170
+
171
+ function entryLine({ entry }, day) {
172
+ const when = whenLabel(entry, day)
173
+ const annual = !isDatedSalientDate(entry?.salientDate)
174
+ const date = annual ? `每年 ${String(entry?.salientDate || '')}` : String(entry?.salientDate || '')
175
+ const title = safeTitle(entry)
176
+ // 承诺和日程的语气不同,与 lib/inject.js 的 `<memory-due>` 保持一致:答应了又
177
+ // 没做的事听起来是欠账,不是事件。正文一律不进 prompt —— 标题就是目录。
178
+ if (entry?.openLoop === true) return `- ${when}:你之前答应过的「${title}」,就是${when}(${date})。`
179
+ return `- ${when}:${title}(${date})。`
180
+ }
181
+
182
+ function buildPrompt({ dateKey, day, hits }) {
183
+ const lines = [`[dsh-memu-memory 日期提醒] 本轮日期 ${dateKey}。今天/明天是:`]
184
+ for (const hit of hits.slice(0, MAX_LINES)) lines.push(entryLine(hit, day))
185
+ if (hits.length > MAX_LINES) lines.push(`- 另有 ${hits.length - MAX_LINES} 条日期记忆,用 memu_private_recall 查。`)
186
+ // schedule 回合不触发本插件注入,所以这句是唯一的上下文来源;"不要重复"是宿主
187
+ // at-least-once 投递的唯一缓冲。
188
+ lines.push('这是记忆里记下的日期;需要细节用 memu_private_recall 查。若你已经说过,不要重复。')
189
+ return lines.join('\n')
190
+ }
191
+
192
+ // 与 `buildAnniversary` 同一套门:可自动注入、非 secret 正文、对本会话可见。
193
+ function dueEntries(index, sessionId, day, nowMs) {
194
+ const hits = []
195
+ for (const [id, entry] of Object.entries(index?.entries || {})) {
196
+ if (!entry || typeof entry !== 'object') continue
197
+ if (!entry.salientDate) continue
198
+ if (entry.visibility === 'secret') continue
199
+ if (!salientDateFires(entry.salientDate, day)) continue
200
+ if (!isMemoryEligible(entry, { automatic: true, now: nowMs })) continue
201
+ try {
202
+ if (!visibleToSession(entry, sessionId)) continue
203
+ } catch {
204
+ continue
205
+ }
206
+ hits.push({ id, entry })
207
+ }
208
+ hits.sort((a, b) => String(a.entry.salientDate).localeCompare(String(b.entry.salientDate))
209
+ || String(a.entry.title || '').localeCompare(String(b.entry.title || '')))
210
+ return hits
211
+ }
212
+
213
+ function byTitleIndex(items) {
214
+ const map = new Map()
215
+ for (const item of items) {
216
+ if (!item || typeof item.title !== 'string') continue
217
+ const list = map.get(item.title) || []
218
+ list.push(item)
219
+ map.set(item.title, list)
220
+ }
221
+ return map
222
+ }
223
+
224
+ /**
225
+ * One sweep of the salient-date wake pass.
226
+ *
227
+ * Creates one host schedule task per conversation and target date, titled
228
+ * `memu:due:<sessionId>:<YYYY-MM-DD>`, so a second sweep is a no-op. Never throws;
229
+ * a host without the optional `schedule` service is a skip, not a failure.
230
+ *
231
+ * @param {object} ctx host context (`ctx.get('schedule')` is optional)
232
+ * @param {{ now?: Date|number, log?: (message: string) => void }} [options]
233
+ * @returns {{ skipped: string } | { created: number, cleaned: number, skipped: number, errors: number }}
234
+ */
235
+ export async function runSalientWakePass(ctx, { now = new Date(), log = () => {} } = {}) {
236
+ const notify = (message) => { try { log(message) } catch {} }
237
+ const stats = { created: 0, cleaned: 0, skipped: 0, errors: 0 }
238
+ try {
239
+ const settings = getSettings()
240
+ if (settings.salientWake !== 'schedule') return { skipped: 'off' }
241
+
242
+ let schedule = null
243
+ try { schedule = ctx?.get?.('schedule') || null } catch { schedule = null }
244
+ const flavor = scheduleFlavor(schedule)
245
+ if (flavor === null) {
246
+ if (!serviceWarned) {
247
+ serviceWarned = true
248
+ notify('salient wake is enabled but this host exposes no schedule service; skipping')
249
+ record({
250
+ kind: 'wake', level: 'warn', ok: false,
251
+ message: '日期唤醒已启用,但宿主没有 schedule 服务;本轮跳过',
252
+ detail: { trigger: 'wake', stage: 'service' },
253
+ })
254
+ }
255
+ return { skipped: 'service' }
256
+ }
257
+ if (flavor === 'session') {
258
+ if (!sessionScopedWarned) {
259
+ sessionScopedWarned = true
260
+ notify('salient wake needs the host-wide schedule API (0.2.2+); this host exposes session-scoped reminders, skipping')
261
+ record({
262
+ kind: 'wake', level: 'warn', ok: false,
263
+ message: '日期唤醒需要宿主级 schedule API(0.2.2+);当前宿主只有会话级提醒,本轮跳过',
264
+ detail: { trigger: 'wake', stage: 'schedule-api' },
265
+ })
266
+ }
267
+ return { skipped: 'schedule-api' }
268
+ }
269
+
270
+ const when = now instanceof Date ? now : new Date(now)
271
+ if (!Number.isFinite(when.getTime())) return { skipped: 'time' }
272
+
273
+ const zone = resolveZone(settings)
274
+ if (!zone) {
275
+ const key = String(settings?.salientWakeTimeZone ?? '')
276
+ if (zoneWarnedFor !== key) {
277
+ zoneWarnedFor = key
278
+ notify(`salient wake skipped: no usable IANA time zone (configured ${JSON.stringify(key)})`)
279
+ record({
280
+ kind: 'wake', level: 'warn', ok: false,
281
+ message: '日期唤醒已跳过:时区为空或无效',
282
+ detail: { trigger: 'wake', stage: 'timezone', zone: key || null },
283
+ })
284
+ }
285
+ return { skipped: 'timezone' }
286
+ }
287
+
288
+ const { hour, fallback } = resolveHour(settings)
289
+ if (fallback) notify(`salient wake: invalid salientWakeHour ${JSON.stringify(settings?.salientWakeHour)}; using ${DEFAULT_HOUR}`)
290
+
291
+ // 先把"要提醒什么"算完:没有会话需要提醒时,一次宿主调用都不发。
292
+ const today = dayInZone(when.getTime(), zone, 0)
293
+ const tomorrow = dayInZone(when.getTime(), zone, 1)
294
+ const nowMs = when.getTime()
295
+ const plans = []
296
+ for (const binding of listSessionBindings()) {
297
+ const sessionId = binding?.sessionId
298
+ if (!sessionId || !binding.libraryId) continue
299
+ if (binding.useLibrary === false) continue
300
+ try {
301
+ if (!effectiveScope(binding).useLibrary) continue
302
+ } catch {
303
+ continue
304
+ }
305
+ let index
306
+ try {
307
+ index = loadPrivateIndex(binding.libraryId)
308
+ } catch (error) {
309
+ // 库没了/索引坏了:这一个会话跳过,其他会话照跑。
310
+ stats.errors += 1
311
+ const message = String(error?.message || error)
312
+ notify(`salient wake: cannot read library ${binding.libraryId}: ${message}`)
313
+ record({
314
+ kind: 'wake', scope: 'private', sessionId, libraryId: binding.libraryId, level: 'warn', ok: false,
315
+ message: '日期唤醒:读取记忆库失败:' + message,
316
+ detail: { trigger: 'wake', stage: 'index' },
317
+ })
318
+ continue
319
+ }
320
+ for (const target of [today, tomorrow]) {
321
+ const hits = dueEntries(index, sessionId, target.day, nowMs)
322
+ if (hits.length === 0) continue
323
+ plans.push({ sessionId, libraryId: binding.libraryId, target: { ...target, hits } })
324
+ }
325
+ }
326
+ if (plans.length === 0) return stats
327
+
328
+ let items = []
329
+ try {
330
+ const page = await schedule.list({ limit: LIST_LIMIT })
331
+ items = Array.isArray(page?.items) ? page.items : []
332
+ } catch (error) {
333
+ const message = String(error?.message || error)
334
+ stats.errors += 1
335
+ notify(`salient wake: schedule.list failed: ${message}`)
336
+ record({
337
+ kind: 'wake', level: 'warn', ok: false,
338
+ message: '日期唤醒:读取定时任务失败:' + message,
339
+ detail: { trigger: 'wake', stage: 'list', code: scheduleErrorCode(error) || null },
340
+ })
341
+ return stats
342
+ }
343
+ const byTitle = byTitleIndex(items)
344
+
345
+ for (const plan of plans) {
346
+ const { sessionId, libraryId, target } = plan
347
+ const title = `memu:due:${sessionId}:${target.date}`
348
+ const existing = byTitle.get(title) || []
349
+ // ended 的任务说明这一天的投递已经发生过(at-least-once),清掉即可,不再补建。
350
+ const ended = existing.filter((item) => item?.status === 'ended')
351
+ for (const item of ended) {
352
+ if (!item?.id) continue
353
+ try {
354
+ await schedule.edit({ id: item.id, action: 'delete' })
355
+ stats.cleaned += 1
356
+ notify(`salient wake: removed ended task ${item.id} (${title})`)
357
+ } catch (error) {
358
+ const message = String(error?.message || error)
359
+ stats.errors += 1
360
+ notify(`salient wake: could not remove ended task ${item.id}: ${message}`)
361
+ record({
362
+ kind: 'wake', scope: 'private', sessionId, libraryId, level: 'warn', ok: false,
363
+ message: '日期唤醒:清理已结束任务失败:' + message,
364
+ detail: { trigger: 'wake', stage: 'cleanup', title, code: scheduleErrorCode(error) || null },
365
+ })
366
+ }
367
+ }
368
+ // active 是幂等的证据;paused 是用户的显式暂停,绝不擅自恢复。
369
+ if (existing.some((item) => item?.status === 'active') || existing.some((item) => item?.status === 'paused')) {
370
+ stats.skipped += 1
371
+ continue
372
+ }
373
+ if (ended.length > 0) {
374
+ stats.skipped += 1
375
+ continue
376
+ }
377
+ // 严格未来:今天的 09:00 已经过去就不排今天(被动注入仍然会提),明天照排。
378
+ // 严格未来:按**投递时区**判断这一刻有没有过去。今天的 09:00 已经过去就不排今天
379
+ // (被动注入仍然会提),明天照排。
380
+ if (!(instantInZone(target.date, hour, zone) > when.getTime())) {
381
+ stats.skipped += 1
382
+ continue
383
+ }
384
+ const prompt = buildPrompt({ dateKey: target.date, day: target.day, hits: target.hits })
385
+ try {
386
+ const created = await schedule.create({
387
+ title,
388
+ prompt,
389
+ timing: { kind: 'at', at: { date: target.date, time: hour, time_zone: zone } },
390
+ target: { kind: 'session', sessionId },
391
+ })
392
+ stats.created += 1
393
+ byTitle.set(title, [...existing, created || { title, status: 'active' }])
394
+ notify(`salient wake: scheduled ${title} at ${target.date} ${hour} ${zone}`)
395
+ record({
396
+ kind: 'wake', scope: 'private', sessionId, libraryId, ok: true,
397
+ message: `日期唤醒已排程:${target.date} ${hour}(${target.hits.length} 条)`,
398
+ detail: {
399
+ trigger: 'wake', stage: 'create', date: target.date, hour, zone,
400
+ ids: target.hits.map((hit) => hit.id).slice(0, 20), taskId: created?.id || null,
401
+ },
402
+ })
403
+ } catch (error) {
404
+ const code = scheduleErrorCode(error)
405
+ const message = String(error?.message || error)
406
+ if (SKIP_CODES.has(code)) {
407
+ stats.skipped += 1
408
+ notify(`salient wake: ${title} skipped (${code})`)
409
+ record({
410
+ kind: 'wake', scope: 'private', sessionId, libraryId, ok: true,
411
+ message: `日期唤醒跳过(${code}):该目标不收 schedule 投递`,
412
+ detail: { trigger: 'wake', stage: 'create', title, code },
413
+ })
414
+ } else {
415
+ stats.errors += 1
416
+ notify(`salient wake: ${title} failed: ${message}`)
417
+ record({
418
+ kind: 'wake', scope: 'private', sessionId, libraryId, level: 'warn', ok: false,
419
+ message: '日期唤醒排程失败:' + message,
420
+ detail: { trigger: 'wake', stage: 'create', title, code: code || null },
421
+ })
422
+ }
423
+ }
424
+ }
425
+ return stats
426
+ } catch (error) {
427
+ // 兜底:这个 pass 的最后一道保险。循环里的每一步已经各自 try 过,走到这里说明
428
+ // 格式异常(例如 state.json 不完整)时也需保持 cycle 的调用可继续执行。
429
+ stats.errors += 1
430
+ notify(`salient wake pass failed: ${error?.message || error}`)
431
+ record({
432
+ kind: 'wake', level: 'warn', ok: false,
433
+ message: '日期唤醒整体失败:' + String(error?.message || error),
434
+ detail: { trigger: 'wake', stage: 'pass' },
435
+ })
436
+ return stats
437
+ }
438
+ }