@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,284 @@
1
+ // Host half of the settings panel: one same-origin JSON route the browser
2
+ // companion calls. The write path is the Host's own `configEditor`, so the
3
+ // profile patch stays the single source of truth and a switch edit goes
4
+ // through the same validate/persist/reconcile path as any other row change.
5
+ //
6
+ // Route shape follows the Web server composition contract (`kind: 'exact'`,
7
+ // one handler per path); the handler dispatches GET/POST itself because
8
+ // duplicate (kind, path) registrations are rejected by WebServer.register.
9
+
10
+ import {
11
+ FLAGS_PACKAGE,
12
+ FLAGS_ROW_ID,
13
+ FlagsError,
14
+ createFlagsService,
15
+ setFlagInConfig,
16
+ } from './flags.js';
17
+
18
+ /** Browser-facing endpoint of the panel. */
19
+ export const FLAGS_PATH = '/api/longlive/flags';
20
+ /** Upper bound for one switch request body. */
21
+ export const FLAGS_BODY_LIMIT = 16 * 1024;
22
+
23
+ const warned = new Set();
24
+
25
+ function warnOnce(key, error) {
26
+ if (warned.has(key)) return;
27
+ warned.add(key);
28
+ try {
29
+ console.warn(`[longlive] ${key}: ${error?.stack ?? error?.message ?? String(error)}`);
30
+ } catch {
31
+ /* logging must never break activation */
32
+ }
33
+ }
34
+
35
+ function getEditor(ctx) {
36
+ if (typeof ctx?.get !== 'function') return undefined;
37
+ try {
38
+ return ctx.get('configEditor') ?? undefined;
39
+ } catch {
40
+ return undefined;
41
+ }
42
+ }
43
+
44
+ function findOwnEntry(ctx, editor, rowId = FLAGS_ROW_ID) {
45
+ let entries;
46
+ try {
47
+ entries = editor?.entries?.() ?? [];
48
+ } catch {
49
+ return undefined;
50
+ }
51
+ if (!Array.isArray(entries)) return undefined;
52
+ let own;
53
+ try {
54
+ own = ctx?.fiber?.entry;
55
+ } catch {
56
+ own = undefined;
57
+ }
58
+ if (own !== undefined && entries.includes(own)) return own;
59
+ const named = entries.filter((entry) => entry?.options?.name === FLAGS_PACKAGE);
60
+ return named.find((entry) => entry?.options?.id === rowId) ?? named[0];
61
+ }
62
+
63
+ function copyRaw(value) {
64
+ if (value === null || typeof value !== 'object') return {};
65
+ try {
66
+ return structuredClone(value);
67
+ } catch {
68
+ return { ...value };
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Build the route service over the live Host context.
74
+ * @param ctx - the plugin context (for `ctx.fiber.entry` and `configEditor`).
75
+ * @param options - `{ config, memoryRoot, rowId }`.
76
+ * @returns the service consumed by {@link createFlagsRoute}.
77
+ */
78
+ export function createUiService(ctx, options = {}) {
79
+ const rowId = options.rowId ?? FLAGS_ROW_ID;
80
+ const editorEntry = () => {
81
+ const editor = getEditor(ctx);
82
+ return editor === undefined ? undefined : findOwnEntry(ctx, editor, rowId);
83
+ };
84
+
85
+ return createFlagsService({
86
+ readConfig: () => {
87
+ const entry = editorEntry();
88
+ if (entry !== undefined) return copyRaw(entry.options?.config);
89
+ return copyRaw(options.config);
90
+ },
91
+ canWrite: () => {
92
+ const editor = getEditor(ctx);
93
+ return editor !== undefined && findOwnEntry(ctx, editor, rowId) !== undefined;
94
+ },
95
+ writeConfig: async (key, value) => {
96
+ const editor = getEditor(ctx);
97
+ if (editor === undefined) {
98
+ throw new FlagsError('E_FLAG_WRITE', '当前宿主没有 configEditor 服务,无法保存插件配置。');
99
+ }
100
+ const entry = findOwnEntry(ctx, editor, rowId);
101
+ if (entry === undefined) {
102
+ throw new FlagsError('E_FLAG_WRITE', '找不到 session-longlive 的配置行,无法保存(可能由 home patch 覆盖)。');
103
+ }
104
+ await editor.edit(entry, (current) => setFlagInConfig(current, key, value));
105
+ },
106
+ memoryRoot: options.memoryRoot,
107
+ });
108
+ }
109
+
110
+ function statusFor(error) {
111
+ if (error instanceof FlagsError) {
112
+ if (error.code === 'E_FLAG_WRITE') return 409;
113
+ return 400;
114
+ }
115
+ return 500;
116
+ }
117
+
118
+ function writeJson(res, status, body, headers = {}) {
119
+ if (res.writableEnded === true || res.headersSent === true) return;
120
+ const payload = JSON.stringify(body);
121
+ try {
122
+ res.writeHead(status, {
123
+ 'content-type': 'application/json; charset=utf-8',
124
+ 'cache-control': 'no-store',
125
+ 'content-length': Buffer.byteLength(payload),
126
+ ...headers,
127
+ });
128
+ res.end(payload);
129
+ } catch {
130
+ try {
131
+ res.destroy?.();
132
+ } catch {
133
+ /* the peer is already gone */
134
+ }
135
+ }
136
+ }
137
+
138
+ /** Read one small JSON object from a Node request. */
139
+ export function readJsonBody(req, limit = FLAGS_BODY_LIMIT) {
140
+ return new Promise((resolve, reject) => {
141
+ let size = 0;
142
+ const chunks = [];
143
+ let settled = false;
144
+ const fail = (error) => {
145
+ if (settled) return;
146
+ settled = true;
147
+ reject(error);
148
+ };
149
+ req.on('data', (chunk) => {
150
+ if (settled) return;
151
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
152
+ size += buffer.length;
153
+ if (size > limit) {
154
+ fail(new FlagsError('E_FLAG_BODY', `请求体超过 ${limit} 字节。`));
155
+ return;
156
+ }
157
+ chunks.push(buffer);
158
+ });
159
+ req.on('end', () => {
160
+ if (settled) return;
161
+ settled = true;
162
+ if (chunks.length === 0) {
163
+ resolve({});
164
+ return;
165
+ }
166
+ try {
167
+ const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
168
+ resolve(parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {});
169
+ } catch {
170
+ reject(new FlagsError('E_FLAG_BODY', '请求体不是合法 JSON。'));
171
+ }
172
+ });
173
+ req.on('error', fail);
174
+ req.on('aborted', () => fail(new FlagsError('E_FLAG_BODY', '请求被中断。')));
175
+ });
176
+ }
177
+
178
+ /**
179
+ * The configuration endpoint is loopback-only: writing a profile patch is a
180
+ * local operation, and the GUI itself is served from 127.0.0.1. A paired
181
+ * remote device is intentionally not granted this write path.
182
+ */
183
+ export function isLoopbackRequest(req) {
184
+ const address = req?.socket?.remoteAddress;
185
+ if (typeof address !== 'string' || address === '') return true; // test / in-process callers
186
+ return address.startsWith('127.')
187
+ || address === '::1'
188
+ || address === '::ffff:127.0.0.1'
189
+ || address === '::ffff:7f00:1'
190
+ || address === 'localhost';
191
+ }
192
+
193
+ /**
194
+ * Create the exact-path route.
195
+ * @param service - from {@link createUiService}.
196
+ * @returns a WebServer route object.
197
+ */
198
+ export function createFlagsRoute(service) {
199
+ async function handle(req, res) {
200
+ if (!isLoopbackRequest(req)) {
201
+ writeJson(res, 403, { ok: false, code: 'E_FLAG_FORBIDDEN', error: '配置接口只允许本机访问(loopback-only)。' });
202
+ return;
203
+ }
204
+ const method = typeof req?.method === 'string' ? req.method.toUpperCase() : 'GET';
205
+ try {
206
+ if (method === 'GET') {
207
+ writeJson(res, 200, service.snapshot());
208
+ return;
209
+ }
210
+ if (method === 'POST') {
211
+ // A JSON content type is required for two reasons: the client always
212
+ // sends it, and a cross-origin HTML form cannot set it (a cross-origin
213
+ // JSON fetch needs a preflight this route never grants).
214
+ const contentType = String(req?.headers?.['content-type'] ?? '').toLowerCase();
215
+ if (!contentType.startsWith('application/json')) {
216
+ throw new FlagsError('E_FLAG_BODY', 'POST 请求必须使用 application/json。');
217
+ }
218
+ const body = await readJsonBody(req);
219
+ const key = body.key;
220
+ const value = body.value;
221
+ if (typeof key !== 'string' || key === '') {
222
+ throw new FlagsError('E_FLAG_BODY', '请求缺少 key。');
223
+ }
224
+ if (typeof value !== 'boolean') {
225
+ throw new FlagsError('E_FLAG_BODY', '请求的 value 必须是布尔值。');
226
+ }
227
+ const snapshot = await service.setFlag(key, value);
228
+ writeJson(res, 200, { ...snapshot, saved: { key, value } });
229
+ return;
230
+ }
231
+ writeJson(res, 405, { ok: false, error: `不支持的请求方法:${method}` }, { allow: 'GET, POST' });
232
+ } catch (error) {
233
+ writeJson(res, statusFor(error), {
234
+ ok: false,
235
+ code: error instanceof FlagsError ? error.code : 'E_FLAG_INTERNAL',
236
+ error: error?.message ?? String(error),
237
+ });
238
+ }
239
+ }
240
+ return { kind: 'exact', path: FLAGS_PATH, handler: handle };
241
+ }
242
+
243
+ /**
244
+ * Register the panel route once the Web server is available. A profile with no
245
+ * web server (a headless boot or a test context) simply gets no route; the
246
+ * plugin still loads.
247
+ * @param ctx - the plugin context.
248
+ * @param options - `{ config, memoryRoot, rowId }`.
249
+ * @returns true when an `inject` watch was installed.
250
+ */
251
+ export function registerUiRoutes(ctx, options = {}) {
252
+ // EA-08: with memoryV2 enabled the cap-gated read-only #1 owns /api/longlive/flags;
253
+ // registering the legacy loopback route on the same path would double-register.
254
+ if (options.skipFlags === true) return true;
255
+ if (typeof ctx?.inject !== 'function') return false;
256
+ try {
257
+ ctx.inject(['webServer'], (webCtx) => {
258
+ const webServer = webCtx?.webServer;
259
+ if (webServer === undefined || typeof webServer.register !== 'function') return;
260
+ const service = createUiService(ctx, options);
261
+ const route = createFlagsRoute(service);
262
+ let dispose;
263
+ try {
264
+ dispose = webServer.register(route);
265
+ } catch (error) {
266
+ warnOnce('settings route registration failed', error);
267
+ return;
268
+ }
269
+ if (typeof webCtx.effect === 'function') {
270
+ try {
271
+ webCtx.effect(() => () => {
272
+ if (typeof dispose === 'function') dispose();
273
+ }, 'longlive: settings route');
274
+ } catch (error) {
275
+ warnOnce('settings route effect failed', error);
276
+ }
277
+ }
278
+ });
279
+ return true;
280
+ } catch (error) {
281
+ warnOnce('settings route inject failed', error);
282
+ return false;
283
+ }
284
+ }
@@ -0,0 +1,368 @@
1
+ // src/util/append-store.js — S1(rc.7 整合线):统一的追加写封装。
2
+ //
3
+ // 目标(审计报告 P1-10):
4
+ // * 单写锁:每个 append 目标一个 `<file>.lock` 租约(holder + pid + acquiredAt +
5
+ // expiresAt,复用 src/memory/lock.js 的 O_EXCL 语义),过期可接管;
6
+ // * fsync:写入后 fsync,崩溃不丢已确认的行;
7
+ // * 坏行隔离:追加前检查文件尾,遇到半行/坏 JSON 尾先搬到 quarantine 目录并告警,
8
+ // 再把文件截到最后一条完整行,绝不把新行接在坏行后面;
9
+ // * 结构化错误:永不抛出;失败返回 `{ok:false, code, error:{code,message}}`;
10
+ // * 失败不再静默:logger.warn + 进程内计数,并(在提供 healthRoot 时)把计数写进
11
+ // `.longlive/metrics/write-health.json`(面板 #9 write-health 路由可读)。
12
+ //
13
+ // 该模块只做文件 IO,不持有业务语义;业务行格式由调用方决定(一行一个 JSON)。
14
+
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+
18
+ import { acquireLease, releaseLease } from '../memory/lock.js';
19
+
20
+ export const APPEND_STORE_SCHEMA = 'append-store/v1';
21
+ export const DEFAULT_APPEND_LOCK_TTL_MS = 30_000;
22
+ export const DEFAULT_APPEND_LOCK_WAIT_MS = 3_000;
23
+ export const DEFAULT_QUARANTINE_DIRNAME = '.longlive/quarantine';
24
+
25
+ let logger = null;
26
+ let clock = () => Date.now();
27
+
28
+ const stats = {
29
+ attempts: 0,
30
+ ok: 0,
31
+ failed: 0,
32
+ locked: 0,
33
+ bytes: 0,
34
+ quarantined: 0,
35
+ byLabel: Object.create(null),
36
+ lastError: null,
37
+ };
38
+
39
+ function bumpLabel(label, ok) {
40
+ const key = typeof label === 'string' && label !== '' ? label : 'append';
41
+ const slot = stats.byLabel[key] ?? (stats.byLabel[key] = { attempts: 0, ok: 0, failed: 0 });
42
+ slot.attempts += 1;
43
+ if (ok) slot.ok += 1; else slot.failed += 1;
44
+ }
45
+
46
+ /** Install the plugin logger (and a test clock). Safe to call more than once. */
47
+ export function configureAppendStore(options = {}) {
48
+ if (options.logger && typeof options.logger.warn === 'function') logger = options.logger;
49
+ else if (typeof options.logger === 'function') logger = { warn: options.logger };
50
+ if (typeof options.now === 'function') clock = options.now;
51
+ return { ok: true };
52
+ }
53
+
54
+ /** Test hook: clear the in-process counters. */
55
+ export function resetAppendStats() {
56
+ stats.attempts = 0;
57
+ stats.ok = 0;
58
+ stats.failed = 0;
59
+ stats.locked = 0;
60
+ stats.bytes = 0;
61
+ stats.quarantined = 0;
62
+ stats.byLabel = Object.create(null);
63
+ stats.lastError = null;
64
+ }
65
+
66
+ /** Snapshot of the counters (status / metrics / doctor read this). */
67
+ export function getAppendStats() {
68
+ return {
69
+ schema: APPEND_STORE_SCHEMA,
70
+ attempts: stats.attempts,
71
+ ok: stats.ok,
72
+ failed: stats.failed,
73
+ locked: stats.locked,
74
+ bytes: stats.bytes,
75
+ quarantined: stats.quarantined,
76
+ byLabel: JSON.parse(JSON.stringify(stats.byLabel)),
77
+ lastError: stats.lastError,
78
+ };
79
+ }
80
+
81
+ function warn(message) {
82
+ try {
83
+ if (logger && typeof logger.warn === 'function') logger.warn(`[append-store] ${message}`);
84
+ else if (logger && typeof logger === 'function') logger(`[append-store] ${message}`);
85
+ } catch {
86
+ /* logging a write failure must not create another one */
87
+ }
88
+ }
89
+
90
+ function nowMs(now) {
91
+ try {
92
+ const value = typeof now === 'function' ? now() : (now === undefined ? clock() : now);
93
+ const date = value instanceof Date ? value : new Date(value);
94
+ return Number.isNaN(date.getTime()) ? Date.now() : date.getTime();
95
+ } catch {
96
+ return Date.now();
97
+ }
98
+ }
99
+
100
+ function sleepMs(ms) {
101
+ try {
102
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, Math.max(1, Math.round(ms)));
103
+ } catch {
104
+ /* Atomics.wait unavailable (exotic runtime): fall back to a bounded busy spin */
105
+ const end = Date.now() + Math.max(1, Math.round(ms));
106
+ while (Date.now() < end) { /* spin */ }
107
+ }
108
+ }
109
+
110
+ function sanitizeName(name) {
111
+ return String(name ?? 'append').replace(/[^A-Za-z0-9_.-]/g, '_').slice(0, 80) || 'append';
112
+ }
113
+
114
+ function quarantinePathFor(directory, file, label) {
115
+ const stamp = new Date(nowMs()).toISOString().replace(/[:.]/g, '-');
116
+ return path.join(directory, `${sanitizeName(path.basename(file))}.${sanitizeName(label)}.${stamp}.${process.pid}.bad`);
117
+ }
118
+
119
+ /**
120
+ * Move an incomplete/corrupt tail to the quarantine directory and truncate the
121
+ * file back to its last complete line. Returns `{quarantined, file, bytes}`.
122
+ * Never throws.
123
+ */
124
+ export function quarantineBadTail(file, options = {}) {
125
+ const resolved = path.resolve(String(file));
126
+ const result = { quarantined: false, file: null, bytes: 0 };
127
+ let stat;
128
+ try {
129
+ stat = fs.statSync(resolved);
130
+ } catch {
131
+ return result;
132
+ }
133
+ if (!stat.isFile() || stat.size === 0) return result;
134
+
135
+ // Read the last chunk; a complete file always ends with '\n'.
136
+ let chunk = '';
137
+ try {
138
+ const chunkSize = Math.min(stat.size, 256 * 1024);
139
+ const fd = fs.openSync(resolved, 'r');
140
+ try {
141
+ const buffer = Buffer.alloc(chunkSize);
142
+ const read = fs.readSync(fd, buffer, 0, chunkSize, stat.size - chunkSize);
143
+ chunk = buffer.subarray(0, read).toString('utf8');
144
+ } finally {
145
+ fs.closeSync(fd);
146
+ }
147
+ } catch {
148
+ return result;
149
+ }
150
+
151
+ const lastNewline = chunk.lastIndexOf('\n');
152
+ const tail = lastNewline >= 0 ? chunk.slice(lastNewline + 1) : chunk;
153
+ if (tail === '') return result; // file ends on a line boundary
154
+ const isCompleteJson = (() => {
155
+ try {
156
+ JSON.parse(tail);
157
+ return true;
158
+ } catch {
159
+ return false;
160
+ }
161
+ })();
162
+ if (isCompleteJson) {
163
+ // A complete line that lost its trailing newline (crash between write and
164
+ // newline): keep the data, just terminate it so the next append is a line.
165
+ try {
166
+ fs.appendFileSync(resolved, '\n', 'utf8');
167
+ return { ...result, terminated: true };
168
+ } catch {
169
+ return result;
170
+ }
171
+ }
172
+
173
+ const tailBytes = Buffer.byteLength(tail, 'utf8');
174
+ if (tailBytes > stat.size) return result;
175
+ const quarantineDir = options.quarantineDir
176
+ ? path.resolve(String(options.quarantineDir))
177
+ : path.join(path.dirname(path.dirname(resolved)), DEFAULT_QUARANTINE_DIRNAME.split('/').slice(1).join('/'));
178
+ const target = quarantinePathFor(quarantineDir, resolved, options.label ?? 'append');
179
+ try {
180
+ fs.mkdirSync(quarantineDir, { recursive: true });
181
+ fs.writeFileSync(target, `${JSON.stringify({ schema: 'append-quarantine/v1', source: resolved, label: options.label ?? 'append', bytes: tailBytes, at: new Date(nowMs()).toISOString() })}\n${tail}\n`, 'utf8');
182
+ fs.truncateSync(resolved, stat.size - tailBytes);
183
+ } catch (error) {
184
+ warn(`坏行隔离失败 ${path.basename(resolved)}: ${error?.code ?? error?.message ?? error}`);
185
+ return result;
186
+ }
187
+ stats.quarantined += 1;
188
+ warn(`隔离坏行 ${tailBytes}B:${path.basename(resolved)} → ${target}`);
189
+ return { quarantined: true, file: target, bytes: tailBytes };
190
+ }
191
+
192
+ /**
193
+ * Run `fn` while holding the per-file lease. Returns `{ok:true, value}` or a
194
+ * structured `{ok:false, code:'E_APPEND_LOCKED'}` after `waitMs`.
195
+ */
196
+ export function withFileLock(file, fn, options = {}) {
197
+ if (typeof fn !== 'function') return { ok: false, code: 'E_APPEND_ARGUMENT', error: { code: 'E_APPEND_ARGUMENT', message: 'withFileLock requires fn' } };
198
+ const lockFile = options.lockFile ? path.resolve(String(options.lockFile)) : `${path.resolve(String(file))}.lock`;
199
+ const ttlMs = Number.isInteger(options.ttlMs) && options.ttlMs > 0 ? options.ttlMs : DEFAULT_APPEND_LOCK_TTL_MS;
200
+ const waitMs = Number.isFinite(Number(options.waitMs)) ? Math.max(0, Number(options.waitMs)) : DEFAULT_APPEND_LOCK_WAIT_MS;
201
+ const holder = typeof options.holder === 'string' && options.holder !== ''
202
+ ? options.holder
203
+ : `append-${process.pid}-${nowMs(options.now)}-${Math.random().toString(36).slice(2, 8)}`;
204
+ const deadline = nowMs(options.now) + waitMs;
205
+ let lease = null;
206
+ for (;;) {
207
+ try {
208
+ lease = acquireLease(lockFile, { holder, ttlMs, now: options.now });
209
+ break;
210
+ } catch (error) {
211
+ if (error?.code !== 'E_LOCKED') {
212
+ return { ok: false, code: 'E_APPEND_LOCK_IO', error: { code: error?.code ?? 'E_APPEND_LOCK_IO', message: String(error?.message ?? error) }, lockFile };
213
+ }
214
+ if (nowMs(options.now) >= deadline) {
215
+ return { ok: false, code: 'E_APPEND_LOCKED', error: { code: 'E_APPEND_LOCKED', message: `写锁被占用:${lockFile}` }, lockFile };
216
+ }
217
+ sleepMs(Math.min(50, Math.max(5, deadline - nowMs(options.now))));
218
+ }
219
+ }
220
+ try {
221
+ return { ok: true, value: fn(lease) };
222
+ } finally {
223
+ try {
224
+ releaseLease(lockFile, lease.holder);
225
+ } catch {
226
+ /* release is best effort; the lease expires on its own */
227
+ }
228
+ }
229
+ }
230
+
231
+ /**
232
+ * Append one JSON line. Never throws.
233
+ *
234
+ * @param {{file:string,row:object,label?:string,fsync?:boolean,skipLock?:boolean,
235
+ * quarantineDir?:string,healthRoot?:string,lock?:object,now?:Function}} options
236
+ * @returns {{ok:boolean,file:string,bytes?:number,code?:string,error?:object,
237
+ * quarantined?:boolean,quarantineFile?:string}}
238
+ */
239
+ export function appendJsonLine(options = {}) {
240
+ const file = options.file;
241
+ if (typeof file !== 'string' || file.trim() === '') {
242
+ stats.attempts += 1;
243
+ stats.failed += 1;
244
+ const error = { code: 'E_APPEND_ARGUMENT', message: 'appendJsonLine requires file' };
245
+ stats.lastError = { ...error, at: new Date(nowMs(options.now)).toISOString() };
246
+ return { ok: false, file: '', code: error.code, error };
247
+ }
248
+ const resolved = path.resolve(file);
249
+ const label = typeof options.label === 'string' && options.label !== '' ? options.label : 'append';
250
+ stats.attempts += 1;
251
+ const healthRoot = typeof options.healthRoot === 'string' && options.healthRoot !== '' ? options.healthRoot : null;
252
+
253
+ const finish = (result) => {
254
+ if (result.ok) {
255
+ stats.ok += 1;
256
+ stats.bytes += Number(result.bytes) || 0;
257
+ bumpLabel(label, true);
258
+ } else {
259
+ stats.failed += 1;
260
+ bumpLabel(label, false);
261
+ if (result.code === 'E_APPEND_LOCKED') stats.locked += 1;
262
+ stats.lastError = { code: result.code ?? 'E_APPEND_IO', message: String(result.error?.message ?? ''), at: new Date(nowMs(options.now)).toISOString() };
263
+ warn(`${label} 追加失败(${result.code ?? 'E_APPEND_IO'}):${path.basename(resolved)} — ${result.error?.message ?? ''}`);
264
+ if (healthRoot) flushAppendHealth(healthRoot, { now: options.now });
265
+ }
266
+ return result;
267
+ };
268
+
269
+ try {
270
+ fs.mkdirSync(path.dirname(resolved), { recursive: true });
271
+ let body;
272
+ try {
273
+ body = JSON.stringify(options.row);
274
+ } catch (error) {
275
+ return finish({ ok: false, file: resolved, code: 'E_APPEND_JSON', error: { code: 'E_APPEND_JSON', message: String(error?.message ?? error) } });
276
+ }
277
+ if (typeof body !== 'string') {
278
+ return finish({ ok: false, file: resolved, code: 'E_APPEND_JSON', error: { code: 'E_APPEND_JSON', message: 'row is not JSON-serializable' } });
279
+ }
280
+ const line = `${body}\n`;
281
+ const write = () => {
282
+ const repaired = quarantineBadTail(resolved, { label, quarantineDir: options.quarantineDir, now: options.now });
283
+ const fd = fs.openSync(resolved, 'a');
284
+ try {
285
+ fs.writeSync(fd, line, null, 'utf8');
286
+ if (options.fsync !== false) {
287
+ try {
288
+ fs.fsyncSync(fd);
289
+ } catch (error) {
290
+ return { ok: false, file: resolved, code: 'E_APPEND_FSYNC', error: { code: error?.code ?? 'E_APPEND_FSYNC', message: String(error?.message ?? error) }, quarantined: repaired.quarantined };
291
+ }
292
+ }
293
+ } finally {
294
+ try { fs.closeSync(fd); } catch { /* already closed */ }
295
+ }
296
+ return { ok: true, file: resolved, bytes: Buffer.byteLength(line, 'utf8'), quarantined: repaired.quarantined, quarantineFile: repaired.file };
297
+ };
298
+ if (options.skipLock === true) return finish(write());
299
+ const locked = withFileLock(resolved, write, { ...(options.lock ?? {}), now: options.now });
300
+ if (!locked.ok) return finish({ ok: false, file: resolved, code: locked.code, error: locked.error, lockFile: locked.lockFile });
301
+ return finish(locked.value);
302
+ } catch (error) {
303
+ const code = error?.code === 'E_LOCKED' ? 'E_APPEND_LOCKED' : 'E_APPEND_IO';
304
+ return finish({ ok: false, file: resolved, code, error: { code: error?.code ?? code, message: String(error?.message ?? error) } });
305
+ }
306
+ }
307
+
308
+ /** Read JSON lines resiliently (bad lines counted, never fatal). */
309
+ export function readJsonLines(file, options = {}) {
310
+ const resolved = path.resolve(String(file));
311
+ let text = '';
312
+ try {
313
+ text = fs.readFileSync(resolved, 'utf8');
314
+ } catch (error) {
315
+ if (error?.code === 'ENOENT') return { ok: true, file: resolved, present: false, rows: [], badLines: 0 };
316
+ return { ok: false, file: resolved, present: false, rows: [], badLines: 0, code: error?.code ?? 'E_APPEND_READ', error: String(error?.message ?? error) };
317
+ }
318
+ const rows = [];
319
+ const bad = [];
320
+ for (const line of text.split('\n')) {
321
+ if (line.trim() === '') continue;
322
+ try {
323
+ rows.push(JSON.parse(line));
324
+ } catch {
325
+ bad.push(line);
326
+ }
327
+ }
328
+ const limit = Number.isInteger(options.limit) && options.limit > 0 ? options.limit : 0;
329
+ return { ok: true, file: resolved, present: true, rows: limit > 0 ? rows.slice(-limit) : rows, badLines: bad.length };
330
+ }
331
+
332
+ /** Merge the append counters into `.longlive/metrics/write-health.json` (atomic). */
333
+ export function flushAppendHealth(memoryRoot, options = {}) {
334
+ const root = typeof memoryRoot === 'string' ? memoryRoot.trim() : '';
335
+ if (root === '') return { ok: false, code: 'E_NO_MEMORY_ROOT' };
336
+ const file = path.join(path.resolve(root), '.longlive', 'metrics', 'write-health.json');
337
+ let existing = {};
338
+ try {
339
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
340
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) existing = parsed;
341
+ } catch {
342
+ existing = {};
343
+ }
344
+ const payload = {
345
+ ...existing,
346
+ schema: existing.schema ?? 'write-health/v1',
347
+ appendStore: getAppendStats(),
348
+ updatedAt: new Date(nowMs(options.now)).toISOString(),
349
+ };
350
+ const tmp = `${file}.tmp-${process.pid}-${Date.now().toString(36)}`;
351
+ try {
352
+ fs.mkdirSync(path.dirname(file), { recursive: true });
353
+ const fd = fs.openSync(tmp, 'w');
354
+ try {
355
+ fs.writeSync(fd, `${JSON.stringify(payload, null, 2)}\n`, null, 'utf8');
356
+ fs.fsyncSync(fd);
357
+ } finally {
358
+ fs.closeSync(fd);
359
+ }
360
+ fs.renameSync(tmp, file);
361
+ return { ok: true, file };
362
+ } catch (error) {
363
+ try { fs.unlinkSync(tmp); } catch { /* best effort */ }
364
+ return { ok: false, file, code: error?.code ?? 'E_APPEND_HEALTH', error: String(error?.message ?? error) };
365
+ }
366
+ }
367
+
368
+ export { stats as appendStats };
@@ -0,0 +1,30 @@
1
+ // src/util/local-day.js — local-day primitives shared outside the router.
2
+ //
3
+ // `localDayKey` (YYYY-MM-DD) is what quotas roll over on at local midnight.
4
+ // It used to live only in src/router/service/paths.mjs, but 1.8.4's proactive
5
+ // lifecycle (src/lifecycle/proactive.js) needs the same key and product code
6
+ // must not import src/router (R1-ID4: the router is reachable only through the
7
+ // explicit seam in src/index.js). It lives here, in a neutral module, and the
8
+ // router path helper re-exports it so existing router callers are untouched.
9
+ //
10
+ // Pure functions, no IO.
11
+
12
+ /** Coerce Date | epoch ms | parseable string into a Date; fall back to now. */
13
+ export function nowDate(value) {
14
+ if (value instanceof Date) return Number.isFinite(value.getTime()) ? value : new Date();
15
+ if (typeof value === 'number' && Number.isFinite(value)) return new Date(value);
16
+ if (typeof value === 'string') {
17
+ const ms = Date.parse(value);
18
+ if (Number.isFinite(ms)) return new Date(ms);
19
+ }
20
+ return new Date();
21
+ }
22
+
23
+ /** Local-day key (YYYY-MM-DD) — quotas roll over at local midnight. */
24
+ export function localDayKey(value) {
25
+ const date = nowDate(value);
26
+ const y = date.getFullYear();
27
+ const m = String(date.getMonth() + 1).padStart(2, '0');
28
+ const d = String(date.getDate()).padStart(2, '0');
29
+ return `${y}-${m}-${d}`;
30
+ }