@jjh32456/longlive 0.0.0-stage → 2.0.0

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 (331) hide show
  1. package/CHANGELOG.md +235 -0
  2. package/LICENSE +21 -0
  3. package/QUICKSTART.md +362 -0
  4. package/README.en.md +64 -0
  5. package/README.md +256 -2
  6. package/SPEC.md +211 -0
  7. package/build-info.json +1665 -0
  8. package/cordis.patch.yml +208 -0
  9. package/docs/A1-MIGRATION.md +75 -0
  10. package/docs/ANSWER-GUARD.md +92 -0
  11. package/docs/ARCHITECTURE.md +128 -0
  12. package/docs/AUTO-RECALL-WIRING.md +115 -0
  13. package/docs/AUTO-RECALL.md +237 -0
  14. package/docs/CONCEPTS.md +143 -0
  15. package/docs/CONFIG.md +839 -0
  16. package/docs/ERRORS.md +271 -0
  17. package/docs/FAQ.md +186 -0
  18. package/docs/FEATURES.md +579 -0
  19. package/docs/INDEX-FRESHNESS.md +21 -0
  20. package/docs/METRICS.md +244 -0
  21. package/docs/MIGRATION-1.6.0.md +220 -0
  22. package/docs/OPERATIONS.md +439 -0
  23. package/docs/PANEL-INTEGRATION.md +190 -0
  24. package/docs/PRIVACY.md +88 -0
  25. package/docs/QUICKSTART.md +155 -0
  26. package/docs/RAW-INDEX-POLICY.md +7 -0
  27. package/docs/README.en.md +48 -0
  28. package/docs/RESIDENT-WATCHER.md +90 -0
  29. package/docs/SESSION-WATCH.md +214 -0
  30. package/docs/TOOLS.md +184 -0
  31. package/docs/TROUBLESHOOTING.md +329 -0
  32. package/icon.svg +11 -0
  33. package/lib/client.js +436 -0
  34. package/locale/en.json +6 -0
  35. package/locale/zh.json +6 -0
  36. package/package.json +163 -4
  37. package/runbook.md +343 -0
  38. package/scripts/archive-digest-build.mjs +668 -0
  39. package/scripts/auto-truncate-run.ps1 +752 -0
  40. package/scripts/backfill-auto-cards.mjs +98 -0
  41. package/scripts/edges-build.mjs +1003 -0
  42. package/scripts/index-maintain.mjs +39 -0
  43. package/scripts/index-reconcile.mjs +49 -0
  44. package/scripts/index-status.mjs +28 -0
  45. package/scripts/install-resident-watcher.ps1 +15 -0
  46. package/scripts/install-session-watch.ps1 +332 -0
  47. package/scripts/install-surgery-task.ps1 +174 -0
  48. package/scripts/lib/auto-truncate-run.ps1 +512 -0
  49. package/scripts/lib/session-watch-fixture.mjs +207 -0
  50. package/scripts/longlive-doctor.mjs +578 -0
  51. package/scripts/metrics-read.mjs +79 -0
  52. package/scripts/metrics-sample.mjs +215 -0
  53. package/scripts/migrate-180.mjs +163 -0
  54. package/scripts/migrate-200.mjs +8 -0
  55. package/scripts/migrate-a1-legacy.mjs +62 -0
  56. package/scripts/migrate-lifecycle.mjs +157 -0
  57. package/scripts/pack.mjs +392 -0
  58. package/scripts/recall-index-build.mjs +128 -0
  59. package/scripts/recall-links-build.mjs +420 -0
  60. package/scripts/rescore-cards.mjs +36 -0
  61. package/scripts/resident-watcher-status.ps1 +15 -0
  62. package/scripts/resident-watcher.ps1 +643 -0
  63. package/scripts/session-watch-drill.mjs +553 -0
  64. package/scripts/session-watch-status.ps1 +146 -0
  65. package/scripts/session-watch.mjs +1367 -0
  66. package/scripts/surgery-inspect.mjs +122 -0
  67. package/scripts/surgery-run.cmd +34 -0
  68. package/scripts/truncate-cli.mjs +279 -0
  69. package/scripts/unattended-surgery.ps1 +1019 -0
  70. package/scripts/uninstall-resident-watcher.ps1 +15 -0
  71. package/scripts/uninstall-session-watch.ps1 +192 -0
  72. package/scripts/verify-card-anchors.mjs +138 -0
  73. package/scripts/watch-loop.ps1 +916 -0
  74. package/src/actions/audit.js +125 -0
  75. package/src/actions/evidence.js +122 -0
  76. package/src/actions/fs.js +162 -0
  77. package/src/activity/index.js +873 -0
  78. package/src/activity/model.js +351 -0
  79. package/src/activity/store.js +786 -0
  80. package/src/activity/summary.js +180 -0
  81. package/src/activity/thinking.js +191 -0
  82. package/src/adapters/constants.js +11 -0
  83. package/src/adapters/engram/data/aliases.json +51 -0
  84. package/src/adapters/engram/data/policy.json +8 -0
  85. package/src/adapters/engram/data/routing-rules.json +546 -0
  86. package/src/adapters/engram/index.js +278 -0
  87. package/src/adapters/registry.js +315 -0
  88. package/src/answer/audit.js +238 -0
  89. package/src/answer/claim-guard.mjs +234 -0
  90. package/src/answer/evidence.js +30 -0
  91. package/src/answer/guard.js +1370 -0
  92. package/src/answer/index.js +1086 -0
  93. package/src/answer/query.js +111 -0
  94. package/src/answer/second-hop.mjs +101 -0
  95. package/src/auto-truncate-status.js +164 -0
  96. package/src/auto-truncate.js +1181 -0
  97. package/src/autoprocedure/candidate.js +342 -0
  98. package/src/autoprocedure/config.js +122 -0
  99. package/src/autoprocedure/evidence.js +345 -0
  100. package/src/autoprocedure/index.js +83 -0
  101. package/src/autoprocedure/ledger.js +329 -0
  102. package/src/autoprocedure/lint.js +232 -0
  103. package/src/autoprocedure/llm.js +409 -0
  104. package/src/autoprocedure/locks.js +102 -0
  105. package/src/autoprocedure/paths.js +39 -0
  106. package/src/autoprocedure/privacy.js +87 -0
  107. package/src/autoprocedure/rules.js +288 -0
  108. package/src/autoprocedure/runtime.js +718 -0
  109. package/src/autoprocedure/session-reader.js +328 -0
  110. package/src/backup.js +310 -0
  111. package/src/bus/bus.mjs +1446 -0
  112. package/src/codec.js +269 -0
  113. package/src/compaction/cut-engine.js +44 -0
  114. package/src/compaction/engine-core.js +1237 -0
  115. package/src/compaction/entry.js +228 -0
  116. package/src/compaction.js +230 -0
  117. package/src/conclusion.js +366 -0
  118. package/src/config.js +835 -0
  119. package/src/d6/runtime.js +517 -0
  120. package/src/d6/surface.js +181 -0
  121. package/src/deps.js +189 -0
  122. package/src/engine-status.js +141 -0
  123. package/src/features.js +1035 -0
  124. package/src/handoff/index.js +1077 -0
  125. package/src/handoff/model.js +1058 -0
  126. package/src/handoff/store.js +1233 -0
  127. package/src/heartbeat.js +385 -0
  128. package/src/home.js +16 -0
  129. package/src/host-version.js +280 -0
  130. package/src/hot-truncate-diag.js +98 -0
  131. package/src/identity/card-marker.js +281 -0
  132. package/src/identity/handover.js +845 -0
  133. package/src/identity/index.js +337 -0
  134. package/src/identity/inject-position.js +133 -0
  135. package/src/identity/writeback.js +344 -0
  136. package/src/identity.js +118 -0
  137. package/src/index.js +647 -0
  138. package/src/lifecycle/gap-clocks.js +364 -0
  139. package/src/lifecycle/index.js +269 -0
  140. package/src/lifecycle/proactive.js +1426 -0
  141. package/src/live-target.js +212 -0
  142. package/src/live.js +1603 -0
  143. package/src/log-rotation.js +153 -0
  144. package/src/memory/a1-migration.js +190 -0
  145. package/src/memory/activity-capture.js +229 -0
  146. package/src/memory/anchor-fallback.js +116 -0
  147. package/src/memory/anchors.js +194 -0
  148. package/src/memory/archive-cold-state.mjs +794 -0
  149. package/src/memory/archive-staging.mjs +305 -0
  150. package/src/memory/archive.mjs +415 -0
  151. package/src/memory/audit-records.js +222 -0
  152. package/src/memory/auto-cards.js +441 -0
  153. package/src/memory/capture-host.js +297 -0
  154. package/src/memory/capture.js +496 -0
  155. package/src/memory/card-anchors.js +203 -0
  156. package/src/memory/card-priority.js +110 -0
  157. package/src/memory/cards.js +425 -0
  158. package/src/memory/catchup.mjs +534 -0
  159. package/src/memory/conclusion-distill.js +381 -0
  160. package/src/memory/conclusion-drafts.js +243 -0
  161. package/src/memory/conflicts.js +1060 -0
  162. package/src/memory/consolidate.js +834 -0
  163. package/src/memory/decay.js +311 -0
  164. package/src/memory/distill.js +485 -0
  165. package/src/memory/event-index.js +1826 -0
  166. package/src/memory/evidence-chain.js +295 -0
  167. package/src/memory/evidence.js +213 -0
  168. package/src/memory/filter-runner.js +555 -0
  169. package/src/memory/filter.js +1035 -0
  170. package/src/memory/forget-v2.js +680 -0
  171. package/src/memory/forget.js +531 -0
  172. package/src/memory/frames-activation.js +249 -0
  173. package/src/memory/frontmatter.js +454 -0
  174. package/src/memory/fts-query.js +342 -0
  175. package/src/memory/governance.js +604 -0
  176. package/src/memory/index-freshness.js +234 -0
  177. package/src/memory/index.js +435 -0
  178. package/src/memory/l2-gate.js +169 -0
  179. package/src/memory/land.mjs +743 -0
  180. package/src/memory/lifecycle.js +235 -0
  181. package/src/memory/lock.js +121 -0
  182. package/src/memory/maintenance.js +1149 -0
  183. package/src/memory/manifest.js +245 -0
  184. package/src/memory/memory-health.mjs +607 -0
  185. package/src/memory/migrate-200.js +1681 -0
  186. package/src/memory/migrate-lifecycle.js +1808 -0
  187. package/src/memory/migrate.js +139 -0
  188. package/src/memory/paths.js +229 -0
  189. package/src/memory/procedure-candidate.mjs +377 -0
  190. package/src/memory/procedure.js +982 -0
  191. package/src/memory/prospective-memory.mjs +362 -0
  192. package/src/memory/provenance.js +119 -0
  193. package/src/memory/recall-feedback.mjs +406 -0
  194. package/src/memory/recall-v2.js +218 -0
  195. package/src/memory/recall.js +357 -0
  196. package/src/memory/reconcile.js +265 -0
  197. package/src/memory/records.js +433 -0
  198. package/src/memory/reinforce.js +281 -0
  199. package/src/memory/retention.js +162 -0
  200. package/src/memory/review.js +124 -0
  201. package/src/memory/state.js +279 -0
  202. package/src/memory/tiers.js +168 -0
  203. package/src/memory/topic-phrases.js +73 -0
  204. package/src/memory/trust.js +97 -0
  205. package/src/memory/turn-budget.mjs +290 -0
  206. package/src/memory/version-chain.js +264 -0
  207. package/src/memory/wake-bridge.mjs +2999 -0
  208. package/src/memory/wal.js +137 -0
  209. package/src/memory/working-frame.js +779 -0
  210. package/src/metrics/classify.mjs +191 -0
  211. package/src/metrics/estimate.mjs +108 -0
  212. package/src/metrics/index.mjs +204 -0
  213. package/src/metrics/measure.mjs +462 -0
  214. package/src/metrics/prestep-latency.mjs +307 -0
  215. package/src/metrics/store.mjs +264 -0
  216. package/src/original.js +294 -0
  217. package/src/policy/threshold-policy.js +224 -0
  218. package/src/policy-profile.js +463 -0
  219. package/src/recall/anaphora.mjs +87 -0
  220. package/src/recall/archive-config.mjs +130 -0
  221. package/src/recall/archive-fallback.mjs +390 -0
  222. package/src/recall/archive-search.mjs +428 -0
  223. package/src/recall/archive-state.mjs +588 -0
  224. package/src/recall/brain.mjs +501 -0
  225. package/src/recall/cards.mjs +202 -0
  226. package/src/recall/current-line.mjs +110 -0
  227. package/src/recall/edges.js +398 -0
  228. package/src/recall/embedding.mjs +698 -0
  229. package/src/recall/entities.mjs +112 -0
  230. package/src/recall/explain.mjs +443 -0
  231. package/src/recall/force-policy.mjs +138 -0
  232. package/src/recall/gate-log.mjs +280 -0
  233. package/src/recall/gate-metrics.mjs +191 -0
  234. package/src/recall/index.js +1337 -0
  235. package/src/recall/inject-order.mjs +279 -0
  236. package/src/recall/link-recall.mjs +183 -0
  237. package/src/recall/links.mjs +696 -0
  238. package/src/recall/privacy.mjs +208 -0
  239. package/src/recall/recall-core.mjs +810 -0
  240. package/src/recall/shared-visibility.js +302 -0
  241. package/src/recall/time-normalizer.mjs +196 -0
  242. package/src/recall/turn-budget-inject.mjs +154 -0
  243. package/src/retention/cold-gate.mjs +146 -0
  244. package/src/retention/config.js +163 -0
  245. package/src/retention/index.js +801 -0
  246. package/src/role/activation.js +191 -0
  247. package/src/role/attention.js +318 -0
  248. package/src/role/base.js +36 -0
  249. package/src/role/channels.js +423 -0
  250. package/src/role/index.js +425 -0
  251. package/src/role/interfaces.js +115 -0
  252. package/src/role/personality.js +370 -0
  253. package/src/role/readers.js +151 -0
  254. package/src/role/relationships.js +477 -0
  255. package/src/role/store.js +202 -0
  256. package/src/role/writeprotect.js +373 -0
  257. package/src/router/aliases.json +182 -0
  258. package/src/router/background/agent-runner.mjs +239 -0
  259. package/src/router/background/anchor.mjs +323 -0
  260. package/src/router/background/audit.mjs +337 -0
  261. package/src/router/background/budget-ledger.mjs +648 -0
  262. package/src/router/background/host-sim.mjs +451 -0
  263. package/src/router/background/index.mjs +81 -0
  264. package/src/router/background/memory.mjs +63 -0
  265. package/src/router/background/mock-llm.mjs +203 -0
  266. package/src/router/background/queue.mjs +224 -0
  267. package/src/router/background/retry.mjs +255 -0
  268. package/src/router/background/router.mjs +1459 -0
  269. package/src/router/background/stream.mjs +276 -0
  270. package/src/router/background/tool-policy.mjs +255 -0
  271. package/src/router/design-headings.json +221 -0
  272. package/src/router/face/config.mjs +155 -0
  273. package/src/router/face/context.mjs +284 -0
  274. package/src/router/face/face.mjs +466 -0
  275. package/src/router/face/identity.mjs +130 -0
  276. package/src/router/face/index.mjs +65 -0
  277. package/src/router/face/journal.mjs +119 -0
  278. package/src/router/face/llm.mjs +252 -0
  279. package/src/router/face/outbox.mjs +153 -0
  280. package/src/router/face/paths.mjs +54 -0
  281. package/src/router/judge.mjs +987 -0
  282. package/src/router/policies/generic.json +131 -0
  283. package/src/router/route.js +1766 -0
  284. package/src/router/router.mjs +535 -0
  285. package/src/router/routing-rules.json +816 -0
  286. package/src/router/run-sim.mjs +530 -0
  287. package/src/router/runtime.js +569 -0
  288. package/src/router/service/apply.mjs +1218 -0
  289. package/src/router/service/board.mjs +712 -0
  290. package/src/router/service/caller.mjs +131 -0
  291. package/src/router/service/config.mjs +361 -0
  292. package/src/router/service/context.mjs +314 -0
  293. package/src/router/service/hint.mjs +668 -0
  294. package/src/router/service/lease.mjs +494 -0
  295. package/src/router/service/live.mjs +251 -0
  296. package/src/router/service/lock.mjs +550 -0
  297. package/src/router/service/merge.mjs +255 -0
  298. package/src/router/service/model-resolve.mjs +350 -0
  299. package/src/router/service/paths.mjs +168 -0
  300. package/src/router/service/proposals.mjs +1461 -0
  301. package/src/router/service/queue.mjs +477 -0
  302. package/src/router/service/reconcile.mjs +271 -0
  303. package/src/router/service/service.mjs +2998 -0
  304. package/src/router/service/sources.mjs +352 -0
  305. package/src/router/service/status.mjs +520 -0
  306. package/src/router/service/store.mjs +476 -0
  307. package/src/router/service/ticklock.mjs +239 -0
  308. package/src/router/service/tokens.mjs +95 -0
  309. package/src/router/service/tools.mjs +248 -0
  310. package/src/router/service/wake.mjs +544 -0
  311. package/src/router/service/wal.mjs +685 -0
  312. package/src/router/shadow.mjs +821 -0
  313. package/src/surgery-recovery.js +1909 -0
  314. package/src/tool-output.js +485 -0
  315. package/src/tools.js +3262 -0
  316. package/src/truncate-visible.js +2416 -0
  317. package/src/truncate.js +999 -0
  318. package/src/ui/actions.js +1312 -0
  319. package/src/ui/flags.js +259 -0
  320. package/src/ui/panel-api.js +371 -0
  321. package/src/ui/panel-auth.js +251 -0
  322. package/src/ui/panel-integrity.js +243 -0
  323. package/src/ui/routes-readonly.js +759 -0
  324. package/src/ui/routes.js +284 -0
  325. package/src/util/append-store.js +368 -0
  326. package/src/util/local-day.js +30 -0
  327. package/src/util/redact.js +227 -0
  328. package/src/util/stale-locks.js +148 -0
  329. package/src/version.js +99 -0
  330. package/test/fixtures/pre-step-container.mjs +100 -0
  331. package/test/p1_probe.mjs +97 -0
@@ -0,0 +1,1149 @@
1
+ // Daily memory maintenance (feature batch 2026-11-05, B1/B2).
2
+ //
3
+ // B1: once per local calendar day, run `memory_consolidate` (report only; it
4
+ // never edits a card) and record the result.
5
+ // B2: once per local calendar day, run `memory_forget` with NO `confirm`, i.e.
6
+ // the dry-run branch, and write a human-readable pending list. There is no
7
+ // code path here that can move, delete or rewrite a card: the confirm word
8
+ // is never supplied by this module.
9
+ //
10
+ // Triggering is deliberately cheap: one unref'd `setTimeout` to the next local
11
+ // midnight, re-armed after each run, plus one catch-up run at plugin start.
12
+ // There is no polling loop and no per-turn hook, so a failed run cannot affect
13
+ // a turn. Every failure is caught, recorded in the schedule state and at most
14
+ // logged as one warning.
15
+ //
16
+ // Shared state lives at `<memoryRoot>/.longlive/bridge/schedule.json` with
17
+ // `lastConsolidateDate` / `lastForgetDate` as the per-day idempotency keys.
18
+ // Reports live in `<memoryRoot>/.longlive/reports/`:
19
+ // consolidate-<YYYY-MM-DD>.md (written by memoryConsolidate)
20
+ // forget-pending-<YYYYMMDD>.md (written here)
21
+
22
+ import fs from 'node:fs';
23
+ import path from 'node:path';
24
+ import zlib from 'node:zlib';
25
+ import crypto from 'node:crypto';
26
+
27
+ import { dayString, isoStamp } from './frontmatter.js';
28
+ import { memoryRootFromConfig, resolveInside, relativePath } from './paths.js';
29
+ import { ensureDir, writeFileAtomic } from './state.js';
30
+ import { memoryConsolidate } from './consolidate.js';
31
+ import { memoryForget } from './forget.js';
32
+ import { proposeForget, FORGET_SUGGESTIONS_REL } from './forget-v2.js';
33
+ import { runConclusionDistillJob } from './conclusion-distill.js';
34
+ // 2.0.0 W3b(⑧):冷档状态探针——archive-state.json 的唯一写入方(fail-closed,自身不抛)。
35
+ import { probeAndWriteArchiveState } from '../recall/archive-state.mjs';
36
+ // 2.0.0 W3c(B7):冷层迁移待办探针——只写 pending.json,永不自动迁移(两次人工 approve 缺一不可)。
37
+ import { probePending as probeMigrationPending } from './migrate-200.js';
38
+
39
+ export const SCHEDULE_VERSION = 1;
40
+ export const SCHEDULE_REL = path.join('.longlive', 'bridge', 'schedule.json');
41
+ export const LOCK_REL = path.join('.longlive', 'bridge', 'schedule.lock');
42
+ export const PENDING_REPORT_PREFIX = 'forget-pending-';
43
+ export const RUN_HISTORY_LIMIT = 30;
44
+ export const DEFAULT_START_DELAY_MS = 500;
45
+ export const MIDNIGHT_PAD_MS = 1000;
46
+ const LOCK_STALE_MS = 10 * 60 * 1000;
47
+
48
+ export const AUTO_MAINTENANCE_DEFAULTS = Object.freeze({
49
+ enabled: false,
50
+ consolidate: true,
51
+ forget: true,
52
+ forgetSuggestions: true,
53
+ runOnStart: true,
54
+ startDelayMs: DEFAULT_START_DELAY_MS,
55
+ });
56
+
57
+ const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
58
+
59
+ function isDay(value) {
60
+ return typeof value === 'string' && DAY_RE.test(value.trim());
61
+ }
62
+
63
+ function errorInfo(error) {
64
+ return {
65
+ code: error?.code ?? 'E_MAINTENANCE_FAILED',
66
+ message: String(error?.message ?? error),
67
+ };
68
+ }
69
+
70
+ function warnTo(logger, message) {
71
+ try {
72
+ if (typeof logger === 'function') logger(message);
73
+ else if (logger && typeof logger.warn === 'function') logger.warn(message);
74
+ } catch {
75
+ /* a logger failure must never break maintenance */
76
+ }
77
+ }
78
+
79
+ function toClock(now) {
80
+ if (typeof now === 'function') {
81
+ return () => {
82
+ const value = now();
83
+ const date = value instanceof Date ? value : new Date(value);
84
+ return Number.isNaN(date.getTime()) ? new Date() : date;
85
+ };
86
+ }
87
+ if (now instanceof Date) {
88
+ return () => new Date(now.getTime());
89
+ }
90
+ return () => new Date();
91
+ }
92
+
93
+ function emptyState() {
94
+ return {
95
+ version: SCHEDULE_VERSION,
96
+ lastConsolidateDate: null,
97
+ lastConsolidateAt: null,
98
+ lastConsolidateReport: null,
99
+ lastConsolidateProposals: null,
100
+ lastConsolidateError: null,
101
+ lastForgetDate: null,
102
+ lastForgetAt: null,
103
+ lastForgetPending: null,
104
+ lastForgetPendingCount: null,
105
+ lastForgetError: null,
106
+ lastForgetSuggestionsDate: null,
107
+ lastForgetSuggestionsAt: null,
108
+ lastForgetSuggestionsQueued: null,
109
+ lastForgetSuggestionsError: null,
110
+ lastConclusionDistillDate: null,
111
+ lastConclusionDistillAt: null,
112
+ lastConclusionDistillResult: null,
113
+ lastConclusionDistillError: null,
114
+ // 2.0.0 W3b(⑧):冷档探针(archive-state 写入方)的每日槽。
115
+ lastArchiveStateDate: null,
116
+ lastArchiveStateAt: null,
117
+ lastArchiveStateStatus: null,
118
+ lastArchiveStateError: null,
119
+ // 2.0.0 W3c(B7):冷层迁移待办探针(migrate-200 写入方)的每日槽。
120
+ lastMigrate200Date: null,
121
+ lastMigrate200At: null,
122
+ lastMigrate200Status: null,
123
+ lastMigrate200Error: null,
124
+ lastRunAt: null,
125
+ lastRunDay: null,
126
+ lastTrigger: null,
127
+ runs: [],
128
+ };
129
+ }
130
+
131
+ function normalizeState(raw) {
132
+ const state = emptyState();
133
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return state;
134
+ state.lastConsolidateDate = isDay(raw.lastConsolidateDate) ? raw.lastConsolidateDate : null;
135
+ state.lastForgetDate = isDay(raw.lastForgetDate) ? raw.lastForgetDate : null;
136
+ state.lastForgetSuggestionsDate = isDay(raw.lastForgetSuggestionsDate) ? raw.lastForgetSuggestionsDate : null;
137
+ state.lastConclusionDistillDate = isDay(raw.lastConclusionDistillDate) ? raw.lastConclusionDistillDate : null;
138
+ state.lastArchiveStateDate = isDay(raw.lastArchiveStateDate) ? raw.lastArchiveStateDate : null;
139
+ state.lastMigrate200Date = isDay(raw.lastMigrate200Date) ? raw.lastMigrate200Date : null;
140
+ for (const key of [
141
+ 'lastConsolidateAt', 'lastConsolidateReport',
142
+ 'lastForgetAt', 'lastForgetPending', 'lastForgetSuggestionsAt',
143
+ 'lastConclusionDistillAt', 'lastArchiveStateAt', 'lastArchiveStateStatus',
144
+ 'lastMigrate200At', 'lastMigrate200Status',
145
+ 'lastRunAt', 'lastRunDay', 'lastTrigger',
146
+ ]) {
147
+ if (raw[key] == null || typeof raw[key] === 'string') state[key] = raw[key] ?? null;
148
+ }
149
+ for (const key of ['lastConsolidateError', 'lastForgetError', 'lastForgetSuggestionsError', 'lastConclusionDistillError', 'lastArchiveStateError', 'lastMigrate200Error']) {
150
+ const value = raw[key];
151
+ if (value == null) {
152
+ state[key] = null;
153
+ } else if (typeof value === 'string') {
154
+ state[key] = { code: 'E_MAINTENANCE_FAILED', message: value };
155
+ } else if (typeof value === 'object' && !Array.isArray(value)) {
156
+ state[key] = {
157
+ code: typeof value.code === 'string' ? value.code : 'E_MAINTENANCE_FAILED',
158
+ message: typeof value.message === 'string' ? value.message : '',
159
+ ...(typeof value.at === 'string' ? { at: value.at } : {}),
160
+ ...(typeof value.day === 'string' ? { day: value.day } : {}),
161
+ };
162
+ } else {
163
+ state[key] = null;
164
+ }
165
+ }
166
+ for (const key of ['lastConsolidateProposals', 'lastForgetPendingCount', 'lastForgetSuggestionsQueued']) {
167
+ if (Number.isFinite(raw[key])) state[key] = raw[key];
168
+ }
169
+ state.lastConclusionDistillResult = raw.lastConclusionDistillResult
170
+ && typeof raw.lastConclusionDistillResult === 'object'
171
+ && !Array.isArray(raw.lastConclusionDistillResult)
172
+ ? {
173
+ archived: Number(raw.lastConclusionDistillResult.archived) || 0,
174
+ distilled: Number(raw.lastConclusionDistillResult.distilled) || 0,
175
+ rejected: Number(raw.lastConclusionDistillResult.rejected) || 0,
176
+ skipped: Number(raw.lastConclusionDistillResult.skipped) || 0,
177
+ }
178
+ : null;
179
+ state.runs = Array.isArray(raw.runs)
180
+ ? raw.runs.filter((entry) => entry && typeof entry === 'object').slice(-RUN_HISTORY_LIMIT)
181
+ : [];
182
+ return state;
183
+ }
184
+
185
+ export function scheduleStatePath(root) {
186
+ return resolveInside(root, SCHEDULE_REL);
187
+ }
188
+
189
+ function lockPathFor(root) {
190
+ return resolveInside(root, LOCK_REL);
191
+ }
192
+
193
+ /**
194
+ * Best-effort cross-process guard. Multiple sessions can share one memoryRoot;
195
+ * without this, two startup ticks could both run the same day's jobs. The lock
196
+ * is advisory and stale after 10 minutes, so a crashed process cannot block
197
+ * maintenance forever.
198
+ */
199
+ function acquireLock(root, { now = new Date() } = {}) {
200
+ const file = lockPathFor(root);
201
+ ensureDir(root, path.dirname(file));
202
+ for (let attempt = 0; attempt < 2; attempt += 1) {
203
+ try {
204
+ const fd = fs.openSync(file, 'wx');
205
+ try {
206
+ fs.writeSync(fd, JSON.stringify({
207
+ pid: process.pid,
208
+ at: isoStamp(now),
209
+ day: dayString(now),
210
+ }));
211
+ } finally {
212
+ fs.closeSync(fd);
213
+ }
214
+ return {
215
+ acquired: true,
216
+ path: file,
217
+ release: () => {
218
+ try {
219
+ fs.unlinkSync(file);
220
+ } catch {
221
+ /* already gone */
222
+ }
223
+ },
224
+ };
225
+ } catch (error) {
226
+ if (error?.code !== 'EEXIST') {
227
+ return { acquired: false, reason: 'lock-error', error: errorInfo(error) };
228
+ }
229
+ let stat;
230
+ try {
231
+ stat = fs.statSync(file);
232
+ } catch {
233
+ continue;
234
+ }
235
+ if (Date.now() - stat.mtimeMs > LOCK_STALE_MS) {
236
+ try {
237
+ fs.unlinkSync(file);
238
+ } catch {
239
+ /* raced with another cleaner; retry */
240
+ }
241
+ continue;
242
+ }
243
+ let holder = null;
244
+ try {
245
+ holder = JSON.parse(fs.readFileSync(file, 'utf8'));
246
+ } catch {
247
+ /* unreadable holder is still a live lock */
248
+ }
249
+ return { acquired: false, reason: 'locked', holder };
250
+ }
251
+ }
252
+ return { acquired: false, reason: 'locked' };
253
+ }
254
+
255
+ // 批 C(M19/catchup):补跑与维护链共用同一把 schedule.lock,必须能按名取得。
256
+ export const acquireScheduleLock = acquireLock;
257
+
258
+ /**
259
+ * Read the schedule state. A missing file is an empty state; a corrupt file is
260
+ * reported (never thrown) and is backed up by the next atomic write.
261
+ */
262
+ export function readScheduleState(root) {
263
+ const file = scheduleStatePath(root);
264
+ let text;
265
+ try {
266
+ text = fs.readFileSync(file, 'utf8');
267
+ } catch (error) {
268
+ if (error?.code === 'ENOENT') {
269
+ return { state: emptyState(), exists: false, corrupt: false, error: null, path: file };
270
+ }
271
+ return {
272
+ state: emptyState(),
273
+ exists: true,
274
+ corrupt: true,
275
+ error: errorInfo(error),
276
+ path: file,
277
+ };
278
+ }
279
+ try {
280
+ const raw = JSON.parse(text);
281
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
282
+ throw new Error('schedule.json 必须是对象');
283
+ }
284
+ return { state: normalizeState(raw), exists: true, corrupt: false, error: null, path: file };
285
+ } catch (error) {
286
+ return {
287
+ state: emptyState(),
288
+ exists: true,
289
+ corrupt: true,
290
+ error: errorInfo(error),
291
+ path: file,
292
+ };
293
+ }
294
+ }
295
+
296
+ export function writeScheduleState(root, state, { now = new Date() } = {}) {
297
+ const file = scheduleStatePath(root);
298
+ ensureDir(root, path.dirname(file));
299
+ const next = normalizeState(state);
300
+ next.version = SCHEDULE_VERSION;
301
+ next.updatedAt = isoStamp(now);
302
+ const write = writeFileAtomic(root, file, `${JSON.stringify(next, null, 2)}\n`, { backup: true, now });
303
+ return { state: next, write };
304
+ }
305
+
306
+ /** Next local midnight (+ a small pad so dayString() has already changed). */
307
+ export function nextLocalMidnight(now = new Date(), padMs = MIDNIGHT_PAD_MS) {
308
+ const base = now instanceof Date ? now : new Date(now);
309
+ const next = new Date(base.getFullYear(), base.getMonth(), base.getDate() + 1, 0, 0, 0, 0);
310
+ const pad = Number.isFinite(padMs) && padMs > 0 ? Math.floor(padMs) : 0;
311
+ next.setTime(next.getTime() + pad);
312
+ return next;
313
+ }
314
+
315
+ function compactDay(day) {
316
+ return String(day).replaceAll('-', '');
317
+ }
318
+
319
+ export function pendingReportPath(root, day) {
320
+ return resolveInside(root, path.join('.longlive', 'reports', `${PENDING_REPORT_PREFIX}${compactDay(day)}.md`));
321
+ }
322
+
323
+ /**
324
+ * Write the pending list. If today's file already exists (e.g. a manual rerun
325
+ * after a state-write failure), keep a copy in reports/.backups first, matching
326
+ * the memoryConsolidate convention.
327
+ */
328
+ function writePendingReport(root, file, content, { now = new Date() } = {}) {
329
+ ensureDir(root, path.dirname(file));
330
+ if (fs.existsSync(file)) {
331
+ const backupDir = resolveInside(root, path.join('.longlive', 'reports', '.backups'));
332
+ ensureDir(root, backupDir);
333
+ const stamp = isoStamp(now).replace(/[:.]/g, '-');
334
+ const stem = path.basename(file, '.md');
335
+ let name = `${stem}.${stamp}.md`;
336
+ for (let suffix = 2; fs.existsSync(path.join(backupDir, name)); suffix += 1) {
337
+ name = `${stem}.${stamp}-${suffix}.md`;
338
+ }
339
+ fs.copyFileSync(file, path.join(backupDir, name));
340
+ }
341
+ return writeFileAtomic(root, file, content, { backup: false, now });
342
+ }
343
+
344
+ function kindLabel(kind) {
345
+ if (kind === 'tombstone') return '立碑(tombstone)';
346
+ if (kind === 'epochs') return '降级(epochs)';
347
+ return String(kind ?? '未知');
348
+ }
349
+
350
+ /**
351
+ * Render the B2 pending list. Pure: takes the dry-run result and returns text.
352
+ * Deliberately repeats the confirm requirement so a human never mistakes this
353
+ * file for an executed forget run.
354
+ */
355
+ export function renderForgetPending({ day, at = new Date(), result = {} } = {}) {
356
+ const proposals = Array.isArray(result.proposals) ? result.proposals : [];
357
+ const immune = Array.isArray(result.immune) ? result.immune : [];
358
+ const undated = Array.isArray(result.undated) ? result.undated : [];
359
+ const missing = Array.isArray(result.scaffold?.missing) ? result.scaffold.missing : [];
360
+ const tombstones = proposals.filter((item) => item.kind === 'tombstone').length;
361
+ const epochs = proposals.filter((item) => item.kind === 'epochs').length;
362
+ const scanned = Number.isFinite(result.scanned) ? result.scanned : 0;
363
+ const lines = [];
364
+
365
+ lines.push(`# 遗忘提案待确认 · ${day}`, '');
366
+ lines.push(
367
+ '> 本文件由每日自动维护任务对 `memory_forget` 执行的 dry-run 生成:**没有移动、删除或改写任何卡片**。',
368
+ `> 真正执行仍需人工显式确认 \`confirm:"FORGET"\`;自动任务不会触发执行。`,
369
+ '',
370
+ );
371
+ lines.push(`- 生成时间:${isoStamp(at)}`);
372
+ lines.push(`- 扫描卡片:${scanned}`);
373
+ lines.push(`- 待确认提案:${proposals.length}(立碑 ${tombstones} / 降级 ${epochs})`);
374
+ lines.push(`- 核心记忆免疫:${immune.length}`);
375
+ lines.push(`- 无 last_used 跳过:${undated.length}`);
376
+ lines.push(`- 脚手架:${missing.length ? `缺 ${missing.join('/')}` : '齐全'}`);
377
+ lines.push('');
378
+
379
+ if (proposals.length === 0) {
380
+ lines.push('今天没有到期的遗忘提案。', '');
381
+ } else {
382
+ lines.push('## 待确认提案', '');
383
+ proposals.forEach((item, index) => {
384
+ lines.push(`### ${index + 1}. \`${item.path}\``, '');
385
+ lines.push(`- 动作:${kindLabel(item.kind)}`);
386
+ lines.push(
387
+ `- 年龄:${item.ageDays ?? '—'} 天` +
388
+ `(last_used: ${item.last_used ?? '—'},strength: ${item.strength ?? '—'},salience: ${item.salience ?? '—'})`,
389
+ );
390
+ lines.push(`- 依据:${item.reason ?? '—'}`);
391
+ lines.push(`- 目标位置:\`${item.destRel ?? '—'}\``);
392
+ if (item.epitaph && typeof item.epitaph === 'object') {
393
+ lines.push('- 墓志铭:');
394
+ lines.push(` - 为什么关:${item.epitaph.reason ?? '—'}`);
395
+ lines.push(` - 影响谁:${item.epitaph.affects ?? '—'}`);
396
+ lines.push(` - 还有用吗:${item.epitaph.stillUseful ?? '—'}`);
397
+ }
398
+ lines.push('');
399
+ });
400
+ }
401
+
402
+ if (immune.length > 0) {
403
+ lines.push('## 免疫(未列入提案)', '');
404
+ lines.push('| 卡片 | 状态 | 原因 |');
405
+ lines.push('|---|---|---|');
406
+ for (const item of immune) {
407
+ lines.push(`| \`${item.path}\` | ${item.status ?? 'active'} | ${item.reason ?? '—'} |`);
408
+ }
409
+ lines.push('');
410
+ }
411
+
412
+ if (undated.length > 0) {
413
+ lines.push('## 无日期跳过', '');
414
+ for (const item of undated) {
415
+ lines.push(`- \`${item.path}\` — ${item.reason ?? '没有可用的 last_used'}`);
416
+ }
417
+ lines.push('');
418
+ }
419
+
420
+ lines.push(
421
+ '---',
422
+ '',
423
+ '确认方式:人工核对本清单后,调用 `memory_forget` 并传 `confirm:"FORGET"`。',
424
+ '自动维护只产生本清单;没有卡被移动、删除或改写。',
425
+ '',
426
+ );
427
+ return lines.join('\n');
428
+ }
429
+
430
+ /**
431
+ * Run the daily jobs once. Both jobs are independent: one failing does not stop
432
+ * the other, and neither failure is thrown to the caller. A job is skipped when
433
+ * its `last*Date` already equals today's local date.
434
+ *
435
+ * Returns a plain summary:
436
+ * { ok, ran, day, trigger, consolidate, forget, state, corruptState?, stateError? }
437
+ */
438
+ function runDailyMaintenanceSync({
439
+ memoryRoot,
440
+ config = {},
441
+ now = new Date(),
442
+ logger = null,
443
+ trigger = 'manual',
444
+ consolidate = memoryConsolidate,
445
+ forget = memoryForget,
446
+ forgetSuggestions = proposeForget,
447
+ lockHeld = false,
448
+ } = {}) {
449
+ let root;
450
+ try {
451
+ root = memoryRoot ? path.resolve(memoryRoot) : memoryRootFromConfig(config);
452
+ } catch (error) {
453
+ return { ok: false, ran: false, reason: 'no-memory-root', error: errorInfo(error) };
454
+ }
455
+ if (!root) return { ok: false, ran: false, reason: 'no-memory-root' };
456
+
457
+ const at = now instanceof Date ? now : new Date(now);
458
+ if (Number.isNaN(at.getTime())) return { ok: false, ran: false, reason: 'bad-clock' };
459
+ const day = isDay(config.today) ? config.today.trim() : dayString(at);
460
+ const wantConsolidate = config.consolidate !== false;
461
+ const wantForget = config.forget !== false;
462
+ const wantSuggestions = config.forgetSuggestions !== false;
463
+ const wantDrafts = config.autoConclusion !== false;
464
+ // 2.0.0 W3b(⑧):冷档探针槽默认随每日维护跑(archiveState:false 可关)。
465
+ const wantArchiveState = config.archiveState !== false;
466
+ // 2.0.0 W3c(B7):冷层迁移待办探针槽(migrate200:false 可关);只探测、不迁移。
467
+ const wantMigrate200 = config.migrate200 !== false;
468
+ if (!wantConsolidate && !wantForget && !wantSuggestions && !wantDrafts && !wantArchiveState && !wantMigrate200) {
469
+ return { ok: true, ran: false, reason: 'disabled', day, trigger };
470
+ }
471
+
472
+ const summary = {
473
+ ok: true,
474
+ ran: false,
475
+ day,
476
+ trigger,
477
+ consolidate: null,
478
+ forget: null,
479
+ forgetSuggestions: null,
480
+ conclusionDistill: null,
481
+ archiveState: null,
482
+ migrate200: null,
483
+ rotation: null,
484
+ state: null,
485
+ corruptState: false,
486
+ };
487
+
488
+ let read;
489
+ try {
490
+ read = readScheduleState(root);
491
+ } catch (error) {
492
+ return { ...summary, ok: false, reason: 'state-unreadable', error: errorInfo(error) };
493
+ }
494
+ summary.corruptState = read.corrupt;
495
+ if (read.corrupt) {
496
+ warnTo(
497
+ logger,
498
+ `[auto-maintenance] schedule.json 不可读(${read.error?.code ?? 'E_STATE_CORRUPT'})— 按空状态继续,下一次写入会先备份旧文件`,
499
+ );
500
+ }
501
+ let state = read.state;
502
+
503
+ let needConsolidate = wantConsolidate && state.lastConsolidateDate !== day;
504
+ let needForget = wantForget && state.lastForgetDate !== day;
505
+ let needSuggestions = wantSuggestions && state.lastForgetSuggestionsDate !== day;
506
+ let needDrafts = wantDrafts && state.lastConclusionDistillDate !== day;
507
+ let needArchiveState = wantArchiveState && state.lastArchiveStateDate !== day;
508
+ let needMigrate200 = wantMigrate200 && state.lastMigrate200Date !== day;
509
+ if (!needConsolidate && !needForget && !needSuggestions && !needDrafts && !needArchiveState && !needMigrate200) {
510
+ return { ...summary, reason: 'already-ran-today', state };
511
+ }
512
+
513
+ // lockHeld=true:调用方(memory/catchup.mjs)已持有同一把 schedule.lock,
514
+ // 这里不能再取一次;否则补跑会永远撞「locked」。
515
+ const lock = lockHeld ? null : acquireLock(root, { now: at });
516
+ if (!lockHeld && !lock.acquired) {
517
+ return {
518
+ ...summary,
519
+ reason: lock.reason === 'lock-error' ? 'lock-error' : 'locked',
520
+ lock: lock.holder ?? null,
521
+ error: lock.error,
522
+ state,
523
+ };
524
+ }
525
+
526
+ try {
527
+ // Re-read after taking the lock: another session may have finished the
528
+ // same day's jobs between our first read and the lock acquisition.
529
+ const latest = readScheduleState(root);
530
+ if (latest.corrupt) summary.corruptState = true;
531
+ state = latest.state;
532
+ needConsolidate = wantConsolidate && state.lastConsolidateDate !== day;
533
+ needForget = wantForget && state.lastForgetDate !== day;
534
+ needSuggestions = wantSuggestions && state.lastForgetSuggestionsDate !== day;
535
+ needDrafts = wantDrafts && state.lastConclusionDistillDate !== day;
536
+ needArchiveState = wantArchiveState && state.lastArchiveStateDate !== day;
537
+ needMigrate200 = wantMigrate200 && state.lastMigrate200Date !== day;
538
+ if (!needConsolidate && !needForget && !needSuggestions && !needDrafts && !needArchiveState && !needMigrate200) {
539
+ return { ...summary, reason: 'already-ran-today', state };
540
+ }
541
+
542
+ // ---- B1: consolidate (report only) ------------------------------------
543
+ if (needConsolidate) {
544
+ try {
545
+ const result = consolidate({}, { memoryRoot: root, now: at });
546
+ const proposals = Array.isArray(result?.proposals) ? result.proposals.length : 0;
547
+ summary.consolidate = {
548
+ status: 'ran',
549
+ reportRel: result?.reportRel ?? null,
550
+ proposals,
551
+ stateUpdated: result?.stateUpdated === true,
552
+ };
553
+ state.lastConsolidateDate = day;
554
+ state.lastConsolidateAt = isoStamp(at);
555
+ state.lastConsolidateReport = summary.consolidate.reportRel;
556
+ state.lastConsolidateProposals = proposals;
557
+ state.lastConsolidateError = null;
558
+ } catch (error) {
559
+ summary.consolidate = { status: 'failed', ...errorInfo(error) };
560
+ state.lastConsolidateError = { ...errorInfo(error), at: isoStamp(at), day };
561
+ warnTo(
562
+ logger,
563
+ `[auto-maintenance] consolidate 失败(${summary.consolidate.code})— ${summary.consolidate.message};已跳过,不影响对话`,
564
+ );
565
+ }
566
+ }
567
+
568
+ // ---- B2: forget dry-run + pending list --------------------------------
569
+ if (needForget) {
570
+ try {
571
+ // `{}` means no confirm -> memoryForget's dry-run branch. The guard below
572
+ // is defensive: if a future refactor ever makes this write cards, the
573
+ // scheduler reports a failure instead of silently applying a forget.
574
+ const result = forget({}, { memoryRoot: root, now: at });
575
+ if (!result || result.dryRun !== true || result.applied === true) {
576
+ const error = new Error('memory_forget 调度必须停留在 dry-run');
577
+ error.code = 'E_MAINTENANCE_DRYRUN_REQUIRED';
578
+ throw error;
579
+ }
580
+ const file = pendingReportPath(root, day);
581
+ const content = renderForgetPending({ day, at, result });
582
+ const write = writePendingReport(root, file, content, { now: at });
583
+ const pending = Array.isArray(result.proposals) ? result.proposals.length : 0;
584
+ summary.forget = {
585
+ status: 'ran',
586
+ pending,
587
+ pendingRel: relativePath(root, file),
588
+ immune: Array.isArray(result.immune) ? result.immune.length : 0,
589
+ undated: Array.isArray(result.undated) ? result.undated.length : 0,
590
+ sha256: write.sha256,
591
+ };
592
+ state.lastForgetDate = day;
593
+ state.lastForgetAt = isoStamp(at);
594
+ state.lastForgetPending = summary.forget.pendingRel;
595
+ state.lastForgetPendingCount = pending;
596
+ state.lastForgetError = null;
597
+ } catch (error) {
598
+ summary.forget = { status: 'failed', ...errorInfo(error) };
599
+ state.lastForgetError = { ...errorInfo(error), at: isoStamp(at), day };
600
+ warnTo(
601
+ logger,
602
+ `[auto-maintenance] forget dry-run 失败(${summary.forget.code})— ${summary.forget.message};卡未改动,不影响对话`,
603
+ );
604
+ }
605
+ }
606
+
607
+ // ---- B2b: D13 forget suggestions (autoApply:false) --------------------
608
+ // 选择性遗忘建议队列:只写 .longlive/hardgate/forget-suggestions.jsonl,
609
+ // 绝不自动标 historical;人工确认仍只走既有 memory_forget。
610
+ if (needSuggestions) {
611
+ try {
612
+ const result = forgetSuggestions({}, { memoryRoot: root, now: at, today: day });
613
+ const suggestions = Array.isArray(result?.suggestions) ? result.suggestions : [];
614
+ summary.forgetSuggestions = {
615
+ status: 'ran',
616
+ autoApply: false,
617
+ queued: Number(result?.queued) || 0,
618
+ scanned: Number(result?.scanned) || 0,
619
+ missingMeta: Number(result?.missingMeta) || 0,
620
+ immune: Number(result?.immune) || 0,
621
+ suggestions: suggestions.length,
622
+ suggestionsFile: result?.suggestionsFile ?? FORGET_SUGGESTIONS_REL,
623
+ };
624
+ state.lastForgetSuggestionsDate = day;
625
+ state.lastForgetSuggestionsAt = isoStamp(at);
626
+ state.lastForgetSuggestionsQueued = summary.forgetSuggestions.queued;
627
+ state.lastForgetSuggestionsError = null;
628
+ } catch (error) {
629
+ summary.forgetSuggestions = { status: 'failed', ...errorInfo(error) };
630
+ state.lastForgetSuggestionsError = { ...errorInfo(error), at: isoStamp(at), day };
631
+ warnTo(
632
+ logger,
633
+ `[auto-maintenance] forget-suggestions 失败(${summary.forgetSuggestions.code})— ${summary.forgetSuggestions.message};卡未改动,不影响对话`,
634
+ );
635
+ }
636
+ }
637
+
638
+ // ---- B3: A1 conclusion drafts -> distilled topic cards -----------------
639
+ // Distillation is a maintenance concern: raw A1 output stays in the draft
640
+ // pool; only validated, source-anchored extracts reach topics/. A failure
641
+ // here is recorded and audited but never thrown to the caller.
642
+ if (needDrafts) {
643
+ try {
644
+ const result = runConclusionDistillJob({
645
+ memoryRoot: root, config, now: at,
646
+ sessionsRoot: config.sessionsRoot,
647
+ });
648
+ // 批 C(M19):ok:false 绝不算成功。旧实现只要没抛就推进
649
+ // lastConclusionDistillDate,导致坏 draft 让补跑永远无法重试。
650
+ if (result && result.ok === false) {
651
+ const code = String(result.code ?? result.errors?.[0]?.code ?? 'E_HG_DISTILL_FAILED');
652
+ const info = { code, message: `conclusion distill 返回 ok:false(${code})`, at: isoStamp(at), day };
653
+ summary.conclusionDistill = { status: 'failed', ...info, result };
654
+ state.lastConclusionDistillError = info;
655
+ warnTo(
656
+ logger,
657
+ `[auto-maintenance] conclusion distill 未成功(${code})— 不推进日期,补跑会重试;候选保留,不影响对话`,
658
+ );
659
+ } else {
660
+ summary.conclusionDistill = { status: 'ran', ...result };
661
+ state.lastConclusionDistillDate = day;
662
+ state.lastConclusionDistillAt = isoStamp(at);
663
+ state.lastConclusionDistillResult = {
664
+ archived: result?.archived ?? 0,
665
+ distilled: result?.distilled ?? 0,
666
+ rejected: result?.rejected ?? 0,
667
+ skipped: result?.skipped ?? 0,
668
+ };
669
+ state.lastConclusionDistillError = null;
670
+ }
671
+ } catch (error) {
672
+ summary.conclusionDistill = { status: 'failed', ...errorInfo(error) };
673
+ state.lastConclusionDistillError = { ...errorInfo(error), at: isoStamp(at), day };
674
+ warnTo(
675
+ logger,
676
+ `[auto-maintenance] conclusion distill 失败(${summary.conclusionDistill.code})— ${summary.conclusionDistill.message};候选保留,不影响对话`,
677
+ );
678
+ }
679
+ }
680
+
681
+ // ---- B4: L0 journal 轮转(月文件→日文件,再按 30 天/2MB 归档) --------
682
+ // 归档只压缩搬移,绝不删除;原文移入 .longlive/archive/journal/ 后不参与召回。
683
+ if (config.journalRotate !== false) {
684
+ try {
685
+ summary.rotation = rotateJournals({ memoryRoot: root, now: at, config });
686
+ } catch (error) {
687
+ summary.rotation = { ok: false, ...errorInfo(error) };
688
+ warnTo(
689
+ logger,
690
+ `[auto-maintenance] journal 轮转失败(${summary.rotation.code})— 原文件未动`,
691
+ );
692
+ }
693
+ }
694
+
695
+ // ---- B5(2.0.0 W3b ⑧):冷档状态探针 → archive-state.json ----------------
696
+ // 每日/启动各一次(槽 lastArchiveStateDate 幂等)。卷不在/只读/低空间/迁移不一致
697
+ // 只写 state + gate-log,绝不抛、不阻塞对话;写失败不推进日期,下次补跑重试。
698
+ if (needArchiveState) {
699
+ try {
700
+ const result = probeAndWriteArchiveState({
701
+ memoryRoot: root,
702
+ archiveRoot: config.archiveRoot ?? null,
703
+ archiveStatePath: config.archiveStatePath ?? null,
704
+ now: at,
705
+ logger,
706
+ });
707
+ if (result && result.ok === true) {
708
+ summary.archiveState = {
709
+ status: 'ran',
710
+ written: result.written === true,
711
+ reason: result.reason ?? null,
712
+ probeStatus: result.status ?? null,
713
+ code: result.code ?? null,
714
+ statePath: result.statePath ?? null,
715
+ bytes: result.bytes ?? null,
716
+ };
717
+ state.lastArchiveStateDate = day;
718
+ state.lastArchiveStateAt = isoStamp(at);
719
+ state.lastArchiveStateStatus = result.status ?? null;
720
+ state.lastArchiveStateError = null;
721
+ } else {
722
+ const code = String(result?.error?.code ?? result?.reason ?? 'E_HG_ARCHIVE_STATE_FAILED');
723
+ const info = { code, message: `archive-state 未写入(${code})`, at: isoStamp(at), day };
724
+ summary.archiveState = { status: 'failed', ...info, result };
725
+ state.lastArchiveStateError = info;
726
+ warnTo(
727
+ logger,
728
+ `[auto-maintenance] archive-state 未成功(${code})— 不推进日期,下次补跑重试;不影响对话`,
729
+ );
730
+ }
731
+ } catch (error) {
732
+ summary.archiveState = { status: 'failed', ...errorInfo(error) };
733
+ state.lastArchiveStateError = { ...errorInfo(error), at: isoStamp(at), day };
734
+ warnTo(
735
+ logger,
736
+ `[auto-maintenance] archive-state 探针失败(${summary.archiveState.code})— 已跳过,不影响对话`,
737
+ );
738
+ }
739
+ }
740
+
741
+ // ---- B7(2.0.0 W3c):冷层迁移待办探针 → .longlive/migrate-200/pending.json ----
742
+ // 只读扫描 + 只写 pending:不 plan、不 backup、不 apply;两次人工 approve 之前不迁移任何文件。
743
+ // 探针失败只告警、不推进日期,下次补跑重试;绝不阻塞对话。
744
+ if (needMigrate200) {
745
+ try {
746
+ const result = probeMigrationPending({ memoryRoot: root, now: at });
747
+ if (result && result.ok === true) {
748
+ summary.migrate200 = {
749
+ status: 'ran',
750
+ state: result.status ?? null,
751
+ counts: result.counts ?? null,
752
+ pendingPath: result.pendingPath ?? null,
753
+ };
754
+ state.lastMigrate200Date = day;
755
+ state.lastMigrate200At = isoStamp(at);
756
+ state.lastMigrate200Status = result.status ?? null;
757
+ state.lastMigrate200Error = null;
758
+ } else {
759
+ const code = String(result?.code ?? 'E_HG_MIGRATE_PROBE_FAILED');
760
+ summary.migrate200 = { status: 'failed', code };
761
+ state.lastMigrate200Error = { code, at: isoStamp(at), day };
762
+ warnTo(
763
+ logger,
764
+ `[auto-maintenance] migrate-200 探针未成功(${code})— 不推进日期,下次补跑;本次未迁移任何文件`,
765
+ );
766
+ }
767
+ } catch (error) {
768
+ summary.migrate200 = { status: 'failed', ...errorInfo(error) };
769
+ state.lastMigrate200Error = { ...errorInfo(error), at: isoStamp(at), day };
770
+ warnTo(
771
+ logger,
772
+ `[auto-maintenance] migrate-200 探针失败(${summary.migrate200.code})— 已跳过,不影响对话`,
773
+ );
774
+ }
775
+ }
776
+
777
+ // ---- state -------------------------------------------------------------
778
+ if (!summary.consolidate && !summary.forget && !summary.conclusionDistill && !summary.archiveState && !summary.migrate200 && !summary.rotation) {
779
+ return { ...summary, reason: 'nothing-to-do', state };
780
+ }
781
+ summary.ran = true;
782
+ state.lastRunAt = isoStamp(at);
783
+ state.lastRunDay = day;
784
+ state.lastTrigger = trigger;
785
+ state.runs = [
786
+ ...(Array.isArray(state.runs) ? state.runs : []),
787
+ {
788
+ at: isoStamp(at),
789
+ day,
790
+ trigger,
791
+ consolidate: summary.consolidate?.status ?? 'skipped',
792
+ forget: summary.forget?.status ?? 'skipped',
793
+ forgetSuggestions: summary.forgetSuggestions?.status ?? 'skipped',
794
+ ...(summary.consolidate?.status === 'ran' ? { consolidateReport: summary.consolidate.reportRel } : {}),
795
+ ...(summary.consolidate?.status === 'failed' ? { consolidateError: summary.consolidate.code } : {}),
796
+ ...(summary.forget?.status === 'ran' ? { forgetPending: summary.forget.pendingRel } : {}),
797
+ ...(summary.forget?.status === 'failed' ? { forgetError: summary.forget.code } : {}),
798
+ conclusionDistill: summary.conclusionDistill?.status ?? 'skipped',
799
+ ...(summary.conclusionDistill?.status === 'failed' ? { conclusionDistillError: summary.conclusionDistill.code } : {}),
800
+ archiveState: summary.archiveState?.status ?? 'skipped',
801
+ migrate200: summary.migrate200?.status ?? 'skipped',
802
+ ...(summary.archiveState?.probeStatus ? { archiveStateStatus: summary.archiveState.probeStatus } : {}),
803
+ ...(summary.archiveState?.status === 'failed' ? { archiveStateError: summary.archiveState.code } : {}),
804
+ ...(summary.migrate200?.state ? { migrate200State: summary.migrate200.state } : {}),
805
+ ...(summary.rotation ? { rotationArchived: summary.rotation.archived ?? 0 } : {}),
806
+ },
807
+ ].slice(-RUN_HISTORY_LIMIT);
808
+
809
+ try {
810
+ const written = writeScheduleState(root, state, { now: at });
811
+ summary.state = written.state;
812
+ summary.stateWrite = written.write;
813
+ } catch (error) {
814
+ summary.ok = false;
815
+ summary.state = state;
816
+ summary.stateError = errorInfo(error);
817
+ warnTo(
818
+ logger,
819
+ `[auto-maintenance] schedule.json 写入失败(${summary.stateError.code})— ${summary.stateError.message};下次启动会重试`,
820
+ );
821
+ }
822
+ return summary;
823
+ } finally {
824
+ if (lock) lock.release();
825
+ }
826
+ }
827
+
828
+ function defaultTimers() {
829
+ return {
830
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
831
+ clearTimeout: (handle) => clearTimeout(handle),
832
+ };
833
+ }
834
+
835
+ /**
836
+ * Create the daily scheduler. Injectable clock/timers/runner make it testable
837
+ * without waiting a day:
838
+ * now : Date | () => Date
839
+ * timers : { setTimeout(fn, ms), clearTimeout(handle) }
840
+ * run : async/sync (options) => summary (default runDailyMaintenance)
841
+ *
842
+ * start() arms exactly one timer: a short startup tick (runOnStart !== false)
843
+ * or directly the next local midnight. Each tick re-arms the next midnight;
844
+ * a run that straddles midnight arms a 1s catch-up tick instead of skipping a
845
+ * whole day.
846
+ */
847
+ export function createMaintenanceScheduler(options = {}) {
848
+ const memoryRoot = options.memoryRoot ?? null;
849
+ const config = options.config && typeof options.config === 'object' ? options.config : {};
850
+ const clock = toClock(options.now);
851
+ const timers = options.timers && typeof options.timers.setTimeout === 'function'
852
+ ? options.timers
853
+ : defaultTimers();
854
+ const clearTimer = typeof timers.clearTimeout === 'function'
855
+ ? (handle) => timers.clearTimeout(handle)
856
+ : () => {};
857
+ const runner = typeof options.run === 'function' ? options.run : runDailyMaintenance;
858
+ const logger = options.logger ?? null;
859
+ const startupDelay = Number.isFinite(options.startDelayMs)
860
+ ? Math.max(0, options.startDelayMs)
861
+ : Number.isFinite(config.startDelayMs)
862
+ ? Math.max(0, config.startDelayMs)
863
+ : DEFAULT_START_DELAY_MS;
864
+
865
+ let timer = null;
866
+ let started = false;
867
+ let stopped = false;
868
+ let running = false;
869
+ let lastResult = null;
870
+
871
+ function unref(handle) {
872
+ if (handle && typeof handle.unref === 'function') handle.unref();
873
+ }
874
+
875
+ function clear() {
876
+ if (timer) {
877
+ try {
878
+ clearTimer(timer);
879
+ } catch {
880
+ /* a timer implementation failure must not break stop() */
881
+ }
882
+ timer = null;
883
+ }
884
+ }
885
+
886
+ function arm(delayMs, trigger) {
887
+ if (stopped) return null;
888
+ const delay = Math.max(0, Math.floor(Number(delayMs) || 0));
889
+ timer = timers.setTimeout(() => {
890
+ timer = null;
891
+ return tick(trigger);
892
+ }, delay);
893
+ unref(timer);
894
+ return timer;
895
+ }
896
+
897
+ function armNextMidnight() {
898
+ const current = clock();
899
+ const next = nextLocalMidnight(current, MIDNIGHT_PAD_MS);
900
+ const delay = Math.max(0, next.getTime() - current.getTime());
901
+ arm(delay, 'midnight');
902
+ return { at: next.toISOString(), delayMs: delay };
903
+ }
904
+
905
+ async function tick(trigger) {
906
+ if (stopped) return { ok: true, ran: false, reason: 'stopped' };
907
+ if (running) return { ok: true, ran: false, reason: 'busy' };
908
+ running = true;
909
+ const startedAt = clock();
910
+ try {
911
+ const result = await runner({
912
+ memoryRoot,
913
+ config,
914
+ now: startedAt,
915
+ logger,
916
+ trigger,
917
+ });
918
+ lastResult = result;
919
+ return result;
920
+ } catch (error) {
921
+ const info = errorInfo(error);
922
+ lastResult = { ok: false, ran: false, reason: 'failed', error: info };
923
+ warnTo(
924
+ logger,
925
+ `[auto-maintenance] ${trigger} 运行失败(${info.code})— ${info.message};已跳过,不影响对话`,
926
+ );
927
+ return lastResult;
928
+ } finally {
929
+ running = false;
930
+ if (!stopped) {
931
+ const finishedAt = clock();
932
+ if (dayString(finishedAt) !== dayString(startedAt)) {
933
+ // The run started before local midnight and finished after it; run
934
+ // again for the new date rather than waiting a full extra day.
935
+ arm(1000, 'midnight-catchup');
936
+ } else {
937
+ armNextMidnight();
938
+ }
939
+ }
940
+ }
941
+ }
942
+
943
+ function start() {
944
+ if (stopped) return { started: false, reason: 'stopped' };
945
+ if (started) return { started: true, reason: 'already-started', timerArmed: timer !== null };
946
+ if (!memoryRoot) return { started: false, reason: 'no-memory-root' };
947
+ if (config.consolidate === false && config.forget === false) {
948
+ return { started: false, reason: 'disabled' };
949
+ }
950
+ started = true;
951
+ if (config.runOnStart !== false) {
952
+ arm(startupDelay, 'startup');
953
+ return { started: true, mode: 'startup', delayMs: startupDelay };
954
+ }
955
+ const next = armNextMidnight();
956
+ return { started: true, mode: 'midnight', ...next };
957
+ }
958
+
959
+ function stop() {
960
+ stopped = true;
961
+ started = false;
962
+ clear();
963
+ return { stopped: true };
964
+ }
965
+
966
+ async function runNow(trigger = 'manual') {
967
+ clear();
968
+ return tick(trigger);
969
+ }
970
+
971
+ function status() {
972
+ return {
973
+ started,
974
+ stopped,
975
+ running,
976
+ timerArmed: timer !== null,
977
+ lastResult,
978
+ };
979
+ }
980
+
981
+ return { start, stop, runNow, status };
982
+ }
983
+
984
+ // ---------------------------------------------------------------------------
985
+ // 批 C(M19):L0 journal 轮转
986
+ // ---------------------------------------------------------------------------
987
+
988
+ export const JOURNAL_DIR_REL = 'journal';
989
+ export const JOURNAL_ARCHIVE_REL = '.longlive/archive/journal';
990
+ export const JOURNAL_MANIFEST_REL = '.longlive/archive/journal/manifest.jsonl';
991
+ export const JOURNAL_ROTATE_DEFAULTS = Object.freeze({ afterDays: 30, maxBytes: 2 * 1024 * 1024 });
992
+ const MONTH_JOURNAL_RE = /^(\d{4})-(\d{2})\.md$/;
993
+ const DAY_JOURNAL_RE = /^(\d{4}-\d{2}-\d{2})\.md$/;
994
+
995
+ function sha256Bytes(bytes) {
996
+ return crypto.createHash('sha256').update(bytes).digest('hex');
997
+ }
998
+
999
+ function gzipTo(archiveDir, rel, bytes, now) {
1000
+ ensureDir(archiveDir, archiveDir);
1001
+ const gzRel = `${rel}.gz`;
1002
+ const gzAbs = path.join(archiveDir, gzRel);
1003
+ const gz = zlib.gzipSync(bytes, { level: 9 });
1004
+ fs.writeFileSync(gzAbs, gz);
1005
+ return { gzRel, gzAbs, gzBytes: gz.length };
1006
+ }
1007
+
1008
+ function appendRotationManifest(root, row) {
1009
+ const file = resolveInside(root, JOURNAL_MANIFEST_REL);
1010
+ ensureDir(root, path.dirname(file));
1011
+ fs.appendFileSync(file, `${JSON.stringify(row)}\n`, 'utf8');
1012
+ return file;
1013
+ }
1014
+
1015
+ /**
1016
+ * 月文件 → 日文件:只按「行首 YYYY-MM-DD」分组,无日期前缀的行跟随上一组
1017
+ * (开头无日期的行归入第一组);原月文件压缩归档,不删除内容。
1018
+ * 日文件已存在时追加(同一日两条流水不互相覆盖)。
1019
+ */
1020
+ function splitMonthJournal(root, name, now, dryRun) {
1021
+ const journalDir = resolveInside(root, JOURNAL_DIR_REL);
1022
+ const abs = path.join(journalDir, name);
1023
+ const text = fs.readFileSync(abs, 'utf8');
1024
+ const lines = text.split('\n');
1025
+ const groups = new Map();
1026
+ let current = null;
1027
+ for (const line of lines) {
1028
+ const hit = /^(\d{4}-\d{2}-\d{2})/.exec(line);
1029
+ if (hit) current = hit[1];
1030
+ if (current === null) continue; // 头部无日期:留给归档,不硬塞进某一天
1031
+ if (!groups.has(current)) groups.set(current, []);
1032
+ groups.get(current).push(line);
1033
+ }
1034
+ if (groups.size === 0) return { name, ok: false, reason: 'no-dated-lines' };
1035
+ const written = [];
1036
+ if (!dryRun) {
1037
+ for (const [day, groupLines] of groups) {
1038
+ const dayFile = path.join(journalDir, `${day}.md`);
1039
+ const body = `${groupLines.join('\n').replace(/\n+$/, '')}\n`;
1040
+ fs.appendFileSync(dayFile, `${fs.existsSync(dayFile) ? '' : ''}${body}`, 'utf8');
1041
+ written.push(`${JOURNAL_DIR_REL}/${day}.md`);
1042
+ }
1043
+ const bytes = fs.readFileSync(abs);
1044
+ const archiveDir = resolveInside(root, JOURNAL_ARCHIVE_REL);
1045
+ const archived = gzipTo(archiveDir, name, bytes, now);
1046
+ fs.unlinkSync(abs);
1047
+ appendRotationManifest(root, {
1048
+ at: isoStamp(now), rel: `${JOURNAL_DIR_REL}/${name}`, gz: archived.gzRel,
1049
+ bytes: bytes.length, gzBytes: archived.gzBytes, sha256: sha256Bytes(bytes),
1050
+ reason: 'month-to-day-split', days: [...groups.keys()].sort(),
1051
+ });
1052
+ return { name, ok: true, split: true, days: [...groups.keys()].sort(), written, archived: archived.gzRel };
1053
+ }
1054
+ return { name, ok: true, split: true, dryRun: true, days: [...groups.keys()].sort() };
1055
+ }
1056
+
1057
+ /**
1058
+ * L0 轮转:先月→日拆分,再把「>afterDays 天」或「>maxBytes 字节」的日文件
1059
+ * gzip 归档到 .longlive/archive/journal/(写 manifest,原文移走不删除)。
1060
+ * 纯本地、幂等:同一天重复调用不会重复归档(文件已不在 journal/ 下)。
1061
+ */
1062
+ export function rotateJournals({ memoryRoot, now = new Date(), config = {}, dryRun = false } = {}) {
1063
+ const root = typeof memoryRoot === 'string' && memoryRoot.trim() !== '' ? path.resolve(memoryRoot) : null;
1064
+ if (!root) return { ok: false, reason: 'no-memory-root' };
1065
+ const at = now instanceof Date ? now : new Date(now ?? Date.now());
1066
+ if (Number.isNaN(at.getTime())) return { ok: false, reason: 'bad-clock' };
1067
+ const opts = { ...JOURNAL_ROTATE_DEFAULTS, ...(config.journalRotate && typeof config.journalRotate === 'object' ? config.journalRotate : {}) };
1068
+ const afterDays = Number.isFinite(Number(opts.afterDays)) ? Math.max(1, Math.floor(Number(opts.afterDays))) : JOURNAL_ROTATE_DEFAULTS.afterDays;
1069
+ const maxBytes = Number.isFinite(Number(opts.maxBytes)) ? Math.max(1024, Math.floor(Number(opts.maxBytes))) : JOURNAL_ROTATE_DEFAULTS.maxBytes;
1070
+ const journalDir = resolveInside(root, JOURNAL_DIR_REL);
1071
+ const report = { ok: true, dryRun, scanned: 0, split: [], archived: [], bytes: 0, errors: [] };
1072
+ if (!fs.existsSync(journalDir)) return report;
1073
+ const names = fs.readdirSync(journalDir).filter((name) => name.endsWith('.md'));
1074
+ // 1) 月文件拆分(必须在轮转之前:否则月文件按 mtime 会被整体归档)。
1075
+ for (const name of names) {
1076
+ const monthHit = MONTH_JOURNAL_RE.exec(name);
1077
+ if (!monthHit) continue;
1078
+ report.scanned += 1;
1079
+ try {
1080
+ const result = splitMonthJournal(root, name, at, dryRun);
1081
+ if (result.ok) report.split.push(result);
1082
+ } catch (error) {
1083
+ report.errors.push({ name, code: String(error?.code ?? error?.message ?? error) });
1084
+ }
1085
+ }
1086
+ // 2) 日文件按龄/按量归档。
1087
+ const dayNames = fs.readdirSync(journalDir).filter((name) => DAY_JOURNAL_RE.test(name));
1088
+ const archiveDir = resolveInside(root, JOURNAL_ARCHIVE_REL);
1089
+ for (const name of dayNames) {
1090
+ const day = DAY_JOURNAL_RE.exec(name)[1];
1091
+ const abs = path.join(journalDir, name);
1092
+ let stat;
1093
+ try {
1094
+ stat = fs.statSync(abs);
1095
+ } catch {
1096
+ continue;
1097
+ }
1098
+ report.scanned += 1;
1099
+ const ageMs = at.getTime() - Date.parse(`${day}T00:00:00`);
1100
+ const tooOld = Number.isFinite(ageMs) && ageMs > afterDays * 24 * 60 * 60 * 1000;
1101
+ const tooBig = stat.size > maxBytes;
1102
+ if (!tooOld && !tooBig) continue;
1103
+ if (dryRun) {
1104
+ report.archived.push({ name, bytes: stat.size, reason: tooOld ? 'age' : 'size', dryRun: true });
1105
+ continue;
1106
+ }
1107
+ try {
1108
+ const bytes = fs.readFileSync(abs);
1109
+ const archived = gzipTo(archiveDir, name, bytes, at);
1110
+ fs.unlinkSync(abs);
1111
+ appendRotationManifest(root, {
1112
+ at: isoStamp(at), rel: `${JOURNAL_DIR_REL}/${name}`, gz: archived.gzRel,
1113
+ bytes: bytes.length, gzBytes: archived.gzBytes, sha256: sha256Bytes(bytes),
1114
+ reason: tooOld ? 'age' : 'size',
1115
+ });
1116
+ report.archived.push({ name, bytes: bytes.length, gz: archived.gzRel, reason: tooOld ? 'age' : 'size' });
1117
+ report.bytes += bytes.length;
1118
+ } catch (error) {
1119
+ report.errors.push({ name, code: String(error?.code ?? error?.message ?? error) });
1120
+ }
1121
+ }
1122
+ if (report.errors.length > 0) report.ok = false;
1123
+ return report;
1124
+ }
1125
+
1126
+ // ---------------------------------------------------------------------------
1127
+ // 批 C(M19):runDailyMaintenance 的 thenable 兼容包装。
1128
+ // d10 夹具按 Promise 用法调用(.catch/.then),而现有 test:080 按同步返回值断言。
1129
+ // 返回对象保留全部字段,同时提供非枚举 then/catch;await 得到浅拷贝。
1130
+ // ---------------------------------------------------------------------------
1131
+ export function runDailyMaintenance(options) {
1132
+ return asThenable(runDailyMaintenanceSync(options));
1133
+ }
1134
+
1135
+ function asThenable(result) {
1136
+ if (!result || typeof result !== 'object') return result;
1137
+ if (typeof result.then === 'function') return result;
1138
+ Object.defineProperty(result, 'then', {
1139
+ value: (resolve) => { resolve({ ...result }); },
1140
+ enumerable: false,
1141
+ configurable: true,
1142
+ });
1143
+ Object.defineProperty(result, 'catch', {
1144
+ value: () => result,
1145
+ enumerable: false,
1146
+ configurable: true,
1147
+ });
1148
+ return result;
1149
+ }