@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,381 @@
1
+ // conclusion-distill.js — A1 候选 → 蒸馏 → 主题卡(1.8.1)。
2
+ //
3
+ // 只有通过 distill.js 的纯抽取/L2/零新事实校验的候选才允许进入 topics/。
4
+ // 锚点必须用当前 L0 parseSession 重算 turnDigest 校验;验不过只写 draft:id。
5
+ // 所有失败只审计,不抛给 maintenance。
6
+
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import crypto from 'node:crypto';
11
+
12
+ import { appendAudit } from './state.js';
13
+ import { parseSession } from '../codec.js';
14
+ import { migrateLegacyA1, preflightA1Legacy } from './a1-migration.js';
15
+ import { memoryIndex } from './index.js';
16
+ import { extractTurns, discoverSessionLogs } from './event-index.js';
17
+ import { turnDigest } from './anchors.js';
18
+ import { buildDistillRecord } from './distill.js';
19
+ import { normalizeForMatch } from './l2-gate.js';
20
+ import { privacyScan } from '../recall/privacy.mjs';
21
+ import { serializeFrontmatter, dayString } from './frontmatter.js';
22
+ import { appendEdge, assertNoDirectTopicsWrite } from './archive.mjs';
23
+ import {
24
+ archiveExpiredDrafts, listDrafts, readDrafts, transitionDraft, DRAFT_DEFAULT_TTL_DAYS,
25
+ } from './conclusion-drafts.js';
26
+ // B7b(lead m00501 裁决):staging 过期 >7 天清退的调用点就是本 job,catchup 不直接调归档。
27
+ // 清退目标是 DESIGN 明文 `.longlive/archive/staging-expired/`(不是 topics/archive)。
28
+ import { archiveExpiredStagingJob, STAGING_TTL_DAYS } from './archive-staging.mjs';
29
+
30
+ export const DISTILL_CARD_TAG = 'auto-conclusion';
31
+ export const DISTILL_SECONDARY_TAG = 'distilled';
32
+ export const DISTILL_BULLET_LIMIT = 20;
33
+ export const DISTILL_RESULT_SCHEMA = 'conclusion-distill/v1';
34
+ // Staging lives under .longlive/ so both 1.8.0 and 1.8.1 scanCards (which only
35
+ // walk topics/journal/procedures and skip dot-directories) can never read it.
36
+ export const STAGING_REL = path.join('.longlive', 'staging', 'auto-cards');
37
+
38
+ function sha256(text) {
39
+ return crypto.createHash('sha256').update(String(text), 'utf8').digest('hex');
40
+ }
41
+
42
+ function normalize(value) {
43
+ return String(value ?? '').toLowerCase().replace(/[\s\p{P}\p{S}]+/gu, '');
44
+ }
45
+
46
+ function slugOf(value) {
47
+ const base = String(value ?? '')
48
+ .toLowerCase()
49
+ .replace(/[^\p{L}\p{N}]+/gu, '-')
50
+ .replace(/^-+|-+$/g, '')
51
+ .slice(0, 60);
52
+ return base === '' ? `draft-${sha256(value).slice(0, 8)}` : base;
53
+ }
54
+
55
+ function defaultSessionsRoot() {
56
+ const home = process.env.DSH_HOME && process.env.DSH_HOME.trim() !== ''
57
+ ? path.resolve(process.env.DSH_HOME.trim())
58
+ : path.join(os.homedir(), '.dsh');
59
+ return path.join(home, 'sessions');
60
+ }
61
+
62
+ function audit(root, action, object, result, extra = {}) {
63
+ try {
64
+ appendAudit(root, {
65
+ action,
66
+ object,
67
+ result,
68
+ now: extra.now instanceof Date ? extra.now : new Date(),
69
+ });
70
+ } catch { /* audit is best-effort, never blocks distillation */ }
71
+ }
72
+
73
+ function userTextsInTurn(parsed, seqStart, seqEnd) {
74
+ const out = [];
75
+ for (const event of parsed.events) {
76
+ if (!(event.seq >= seqStart && event.seq <= seqEnd)) continue;
77
+ if (event.type !== 'user/message') continue;
78
+ const data = event.data ?? {};
79
+ if (data.source?.kind !== 'user') continue;
80
+ const blocks = Array.isArray(data.content) ? data.content : [];
81
+ for (const block of blocks) {
82
+ if (block?.type === 'text' && typeof block.text === 'string' && block.text.trim() !== '') out.push(block.text);
83
+ }
84
+ }
85
+ return out;
86
+ }
87
+
88
+ /** Find a real L0 turn and recompute its digest. Returns null when unverifiable. */
89
+ const l0Cache = new Map();
90
+ export function verifyDraftAnchor(draft, { sessionsRoot = defaultSessionsRoot() } = {}) {
91
+ try {
92
+ const key = `${path.resolve(sessionsRoot)}|${draft.sessionId}`;
93
+ let cached = l0Cache.get(key);
94
+ if (cached === undefined) {
95
+ const logs = discoverSessionLogs([sessionsRoot]);
96
+ const log = logs.find((item) => item.sessionId === draft.sessionId);
97
+ if (!log) { l0Cache.set(key, null); return null; }
98
+ const parsed = parseSession(fs.readFileSync(log.file));
99
+ const turns = extractTurns(parsed.header, parsed.events, parsed.frames, parsed.texts);
100
+ cached = { parsed, turns, file: log.file };
101
+ l0Cache.set(key, cached);
102
+ }
103
+ if (cached === null) return null;
104
+ const turn = cached.turns.find((row) => row.turn === draft.turn);
105
+ if (!turn) return null;
106
+ const digest = turnDigest(cached.parsed.events, turn.seqStart, turn.seqEnd);
107
+ if (typeof digest !== 'string' || digest === '') return null;
108
+ // P0-1 v3: bind the *full* user text, not just the excerpt. The draft must
109
+ // carry userText + its hash; one L0 user message in this turn must match it
110
+ // exactly after normalization, and title/excerpt/text must be substrings of
111
+ // that user text. This rejects a real excerpt paired with a forged title/body.
112
+ const userText = String(draft.userText ?? '').trim();
113
+ if (userText === '' || draft.userTextHash !== sha256(userText)) return null;
114
+ const normalizedUser = normalizeForMatch(userText);
115
+ if (normalizedUser === '') return null;
116
+ const userTexts = userTextsInTurn(cached.parsed, turn.seqStart, turn.seqEnd);
117
+ const exact = userTexts.find((text) => normalizeForMatch(text) === normalizedUser);
118
+ if (!exact) return null;
119
+ for (const field of ['title', 'excerpt', 'text']) {
120
+ let value = normalizeForMatch(draft[field] ?? '');
121
+ if (field === 'text') value = value.replace(/^用户/u, '');
122
+ if (value !== '' && !normalizedUser.includes(value)) return null;
123
+ }
124
+ return {
125
+ kind: 'session_turn',
126
+ sessionId: draft.sessionId,
127
+ turn: draft.turn,
128
+ seqStart: turn.seqStart,
129
+ seqEnd: turn.seqEnd,
130
+ digest,
131
+ userText,
132
+ file: cached.file,
133
+ };
134
+ } catch {
135
+ return null;
136
+ }
137
+ }
138
+
139
+ function bulletFor(draft, anchor, distilled) {
140
+ const parts = [`- 自动回流(已蒸馏)[draft:${draft.id}]`];
141
+ if (anchor) parts.push(`[session_turn: ${anchor.sessionId}#${anchor.turn} @${anchor.digest.slice(0, 16)}]`);
142
+ parts.push(`:${String(distilled.gist ?? draft.excerpt).replace(/[\r\n]+/g, ' ').slice(0, 300)}`);
143
+ return parts.join(' ');
144
+ }
145
+
146
+ function findMatchingCard(root, draft) {
147
+ // v4 staging only. Staging is under .longlive/ so 1.8.0/1.8.1 scans cannot
148
+ // reach it; promotion to topics/ is explicitly out of this job.
149
+ const slug = slugOf(draft.title || draft.excerpt);
150
+ const rel = path.join(STAGING_REL, `${slug}.md`);
151
+ const abs = path.join(root, rel);
152
+ return fs.existsSync(abs) ? { abs, rel } : null;
153
+ }
154
+
155
+ function alreadyHasDraft(text, draftId) {
156
+ return String(text).includes(`[draft:${draftId}]`);
157
+ }
158
+
159
+ function appendBullet(file, bullet, draft) { const text = fs.readFileSync(file, 'utf8');
160
+ if (alreadyHasDraft(text, draft.id)) return { written: false, duplicate: true, reason: 'already-in-card' };
161
+ const count = (text.match(/自动回流(已蒸馏)/g) ?? []).length;
162
+ if (count >= DISTILL_BULLET_LIMIT) return { written: false, reason: 'card-full' };
163
+ const next = `${text.replace(/\s*$/, '')}\n${bullet}\n`;
164
+ fs.writeFileSync(file, next, 'utf8');
165
+ return { written: true, duplicate: false };
166
+ }
167
+
168
+ function createOrAppendCard(root, draft, distill, anchor) {
169
+ const existing = findMatchingCard(root, draft);
170
+ if (existing) {
171
+ const result = appendBullet(existing.abs, bulletFor(draft, anchor, distill), draft);
172
+ return { ...result, card: existing.rel, matched: true };
173
+ }
174
+ const slug = slugOf(draft.title || draft.excerpt);
175
+ const rel = path.join(STAGING_REL, `${slug}.md`);
176
+ const abs = path.join(root, rel);
177
+ if (fs.existsSync(abs)) {
178
+ const result = appendBullet(abs, bulletFor(draft, anchor, distill), draft);
179
+ return { ...result, card: rel, matched: true };
180
+ }
181
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
182
+ // 批 C(M18):蒸馏产卡只允许落 staging;直写 topics/ 一律当场失败。
183
+ assertNoDirectTopicsWrite(rel.replace(/\\/g, '/'));
184
+ const at = new Date();
185
+ const fields = {
186
+ title: `自动回流:${String(draft.title || draft.excerpt).slice(0, 80)}`,
187
+ date: dayString(at),
188
+ tags: [DISTILL_CARD_TAG, DISTILL_SECONDARY_TAG, 'staged'],
189
+ salience: 2,
190
+ strength: 3,
191
+ };
192
+ const extras = {
193
+ source_draft: draft.id,
194
+ auto_conclusion: true,
195
+ distilled_at: at.toISOString(),
196
+ };
197
+ const body = `# ${fields.title}\n\n${bulletFor(draft, anchor, distill)}\n`;
198
+ fs.writeFileSync(abs, `${serializeFrontmatter(fields, extras)}\n\n${body}`, 'utf8');
199
+ return { written: true, duplicate: false, card: rel.replace(/\\/g, '/'), matched: false };
200
+ }
201
+
202
+ /**
203
+ * One-time migration for rc.2/rc.3 trees: move legacy `topics/auto/*.md` into
204
+ * `.longlive/staging/auto-cards/`, so a later downgrade to 1.8.0 cannot recurse
205
+ * them into scanCards. Runs under the same memoryRoot, never deletes content.
206
+ */
207
+ export function migrateLegacyAutoCards(root) {
208
+ return migrateLegacyA1({ memoryRoot: root, dryRun: false });
209
+ }
210
+
211
+ /**
212
+ * One maintenance job: expire TTL drafts, then distill all pending drafts.
213
+ * Every per-draft failure is audited and converted into status=rejected; the
214
+ * job itself returns a summary and never throws for draft-level errors.
215
+ */
216
+ export function runConclusionDistillJob({
217
+ memoryRoot, config = {}, now = new Date(), sessionsRoot = defaultSessionsRoot(),
218
+ } = {}) {
219
+ const root = String(memoryRoot ?? '');
220
+ if (root === '') return { ok: false, code: 'E_MEMORY_ROOT', processed: 0 };
221
+ const draftCfg = config.conclusionDraft && typeof config.conclusionDraft === 'object' ? config.conclusionDraft : {};
222
+ const distillCfg = config.conclusionDistill && typeof config.conclusionDistill === 'object' ? config.conclusionDistill : {};
223
+ const ttlDays = Number.isFinite(Number(draftCfg.ttlDays)) && Number(draftCfg.ttlDays) > 0
224
+ ? Number(draftCfg.ttlDays) : DRAFT_DEFAULT_TTL_DAYS;
225
+ const stagingTtlDays = Number.isFinite(Number(draftCfg.stagingTtlDays)) && Number(draftCfg.stagingTtlDays) > 0
226
+ ? Number(draftCfg.stagingTtlDays) : STAGING_TTL_DAYS;
227
+ const summary = {
228
+ ok: true, schema: DISTILL_RESULT_SCHEMA, ttlDays, stagingTtlDays,
229
+ archived: 0, stagingArchived: 0, processed: 0, distilled: 0, rejected: 0, skipped: 0, edges: 0, errors: [],
230
+ };
231
+ try {
232
+ const preflight = preflightA1Legacy(root);
233
+ summary.legacyPreflight = preflight;
234
+ const migration = migrateLegacyAutoCards(root);
235
+ summary.migrated = migration.moved ?? 0;
236
+ summary.recovered = migration.recovered ?? 0;
237
+ summary.totalLegacy = migration.totalLegacy ?? 0;
238
+ summary.migrationReceipt = migration.receiptPath ?? null;
239
+ if ((migration.moved ?? 0) > 0 || (migration.recovered ?? 0) > 0) {
240
+ // A migration that leaves the old INDEX rows behind is not complete.
241
+ // Rebuild the derived view in the same maintenance run.
242
+ const idx = memoryIndex({ apply: true }, { memoryRoot: root, now });
243
+ summary.indexRebuilt = idx.applied === true;
244
+ summary.indexCards = idx.cards;
245
+ }
246
+ } catch (error) {
247
+ summary.migrationError = String(error?.code ?? error?.message ?? error);
248
+ }
249
+ // TTL/forgetting is an independent lifecycle layer: it runs even when
250
+ // distillation is disabled. Only the pending->card path is gated below.
251
+ try {
252
+ const expired = archiveExpiredDrafts(root, { ttlDays, now });
253
+ summary.archived = expired.archived;
254
+ } catch (error) {
255
+ summary.errors.push({ stage: 'expire', code: String(error?.code ?? error), message: String(error?.message ?? error) });
256
+ audit(root, 'conclusion_distill_expire', null, 'error', { now });
257
+ }
258
+ // B7b(lead m00501 裁决):staging 过期 > stagingTtlDays(默认 7 天未批)→ 清退到
259
+ // `.longlive/archive/staging-expired/` 并降级不召回(DESIGN.v0.3:120 / v0.4:89)。
260
+ // 放在蒸馏前:先清走上一轮遗留的过期 staging 卡,本轮新产卡不会被误归档;
261
+ // 与 TTL/forgetting 同属独立生命周期层,distill disabled 时仍执行。
262
+ try {
263
+ const staging = archiveExpiredStagingJob({ memoryRoot: root, now, ttlDays: stagingTtlDays, dryRun: false });
264
+ summary.stagingArchived = staging.archived?.length ?? 0;
265
+ summary.stagingSweep = {
266
+ ok: staging.ok !== false,
267
+ archiveRel: staging.archiveRel ?? null,
268
+ scanned: staging.scanned ?? 0,
269
+ expired: staging.expired ?? 0,
270
+ archived: (staging.archived ?? []).map((row) => ({ rel: row.rel, to: row.to, alreadyArchived: row.alreadyArchived === true })),
271
+ failed: staging.failed ?? [],
272
+ };
273
+ if (staging.ok === false) {
274
+ summary.errors.push({ stage: 'staging', code: String(staging.code ?? staging.failed?.[0]?.code ?? 'E_HG_ARCHIVE_FAILED'), message: String(staging.message ?? staging.failed?.[0]?.message ?? '') });
275
+ }
276
+ } catch (error) {
277
+ summary.errors.push({ stage: 'staging', code: String(error?.code ?? error), message: String(error?.message ?? error).slice(0, 300) });
278
+ }
279
+ if (distillCfg.enabled === false) {
280
+ return { ...summary, enabled: false, reason: 'distillation-disabled' };
281
+ }
282
+ summary.enabled = true;
283
+ const read = readDrafts(root);
284
+ if (read.corrupt) {
285
+ summary.ok = false;
286
+ summary.errors.push({ stage: 'read', code: 'E_DRAFT_CORRUPT', errors: read.errors });
287
+ audit(root, 'conclusion_distill_read', null, 'corrupt', { now });
288
+ return summary;
289
+ }
290
+ for (const draft of listDrafts(root, { status: 'pending' })) {
291
+ summary.processed += 1;
292
+ try {
293
+ if (draft.sourceRole !== 'user') {
294
+ throw Object.assign(new Error('E_DRAFT_NOT_USER'), { code: 'E_DRAFT_NOT_USER' });
295
+ }
296
+ if (draft.privacyVerdict === 'local_only') {
297
+ throw Object.assign(new Error('E_DRAFT_PRIVACY'), { code: 'E_DRAFT_PRIVACY' });
298
+ }
299
+ let privacy;
300
+ try {
301
+ privacy = privacyScan(draft.text);
302
+ } catch {
303
+ throw Object.assign(new Error('E_DRAFT_PRIVACY'), { code: 'E_DRAFT_PRIVACY' });
304
+ }
305
+ if (!privacy || privacy.verdict === 'local_only') {
306
+ throw Object.assign(new Error('E_DRAFT_PRIVACY'), { code: 'E_DRAFT_PRIVACY' });
307
+ }
308
+ // Hard v2 gate: a user decision must be anchored to the actual L0 user
309
+ // turn; an unverifiable draft is rejected before any card is written.
310
+ const anchor = verifyDraftAnchor(draft, { sessionsRoot });
311
+ if (!anchor) {
312
+ throw Object.assign(new Error('E_DRAFT_ANCHOR_UNVERIFIABLE'), { code: 'E_DRAFT_ANCHOR_UNVERIFIABLE' });
313
+ }
314
+ const distilled = buildDistillRecord({
315
+ topic: slugOf(draft.title || draft.excerpt),
316
+ period: String(draft.at ?? now.toISOString()).slice(0, 10),
317
+ sources: [{
318
+ id: draft.id,
319
+ text: draft.text,
320
+ summary: draft.excerpt,
321
+ sessionId: draft.sessionId,
322
+ turn: draft.turn,
323
+ sourceKind: 'conclusion_draft_user',
324
+ }],
325
+ grade: 'L2',
326
+ trigger: 'conclusion-draft-user',
327
+ reason: 'A1 v2 user decision distillation',
328
+ requiredFields: draft.kind === 'decision'
329
+ ? { decision: ['改成', '决定', '定了', '拍板', '结论', '按这个', '以后都', '就这样', '就这么', '就按', '就用', '敲定', '定稿'] }
330
+ : null,
331
+ important: false,
332
+ now,
333
+ });
334
+ const result = createOrAppendCard(root, draft, distilled, anchor);
335
+ // 批 C(M18):写边——只走 appendEdge(edges.jsonl 只追加),不直写 topics/。
336
+ try {
337
+ const cardRel = String(result?.card ?? '').replace(/\\/g, '/');
338
+ if (cardRel !== '') {
339
+ appendEdge({
340
+ memoryRoot: root,
341
+ now,
342
+ edge: {
343
+ from: `draft:${draft.id}`,
344
+ to: cardRel,
345
+ type: 'derived_from',
346
+ evidence: [String(draft.excerpt ?? draft.text ?? '').slice(0, 400), `turn:${draft.sessionId}:${draft.turn}`],
347
+ source: 'conclusion-distill',
348
+ },
349
+ });
350
+ summary.edges = (summary.edges ?? 0) + 1;
351
+ }
352
+ } catch (error) {
353
+ summary.errors.push({ id: draft.id, stage: 'edge', code: String(error?.code ?? error) });
354
+ }
355
+ if (!result.written && result.reason === 'card-full') {
356
+ summary.skipped += 1;
357
+ transitionDraft(root, draft.id, 'rejected', { reason: 'card-full:20', now });
358
+ audit(root, 'conclusion_distill', draft.id, 'card-full', { now });
359
+ continue;
360
+ }
361
+ if (!result.written && result.duplicate) {
362
+ summary.skipped += 1;
363
+ transitionDraft(root, draft.id, 'distilled', { reason: 'already-in-card', now });
364
+ audit(root, 'conclusion_distill', draft.id, 'duplicate', { now });
365
+ continue;
366
+ }
367
+ transitionDraft(root, draft.id, 'distilled', { reason: `card:${result.card}`, now });
368
+ summary.distilled += 1;
369
+ audit(root, 'conclusion_distill', draft.id, 'distilled', { now });
370
+ } catch (error) {
371
+ summary.rejected += 1;
372
+ const code = String(error?.code ?? error);
373
+ try { transitionDraft(root, draft.id, 'rejected', { reason: code.slice(0, 300), now }); } catch { /* best effort */ }
374
+ summary.errors.push({ id: draft.id, code });
375
+ audit(root, 'conclusion_distill', draft.id, `rejected:${code}`, { now });
376
+ }
377
+ }
378
+ return summary;
379
+ }
380
+
381
+ export { sha256 as conclusionDistillSha256 };
@@ -0,0 +1,243 @@
1
+ // conclusion-drafts.js — A1 候选池(1.8.1)。
2
+ //
3
+ // A1 的原始产出只是蒸馏原料:append-only JSONL,位于
4
+ // `<memoryRoot>/.longlive/index/conclusion-drafts.jsonl`,不在 topics/ 下,
5
+ // 因此 recall / recall-v2 / INDEX.md 都不会直接读到它。
6
+ //
7
+ // 并发:每次 append 走 memory/lock.js 的跨进程 lease,并在持锁期间用
8
+ // tmp→rename 的锁文件 + 单行 append(fsync)保证多会话不丢行。
9
+ // 损坏:每行带 prevHash/lineHash,读取时逐行校验 JSON 与链;损坏会显式报告,
10
+ // 不会把半行当候选。
11
+
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import crypto from 'node:crypto';
15
+ import { withLease } from './lock.js';
16
+
17
+ export const DRAFT_SCHEMA = 'conclusion-draft/v1';
18
+ export const DRAFT_STATUSES = Object.freeze(['pending', 'distilled', 'rejected', 'expired']);
19
+ export const DRAFT_FILE_REL = path.join('.longlive', 'index', 'conclusion-drafts.jsonl');
20
+ export const DRAFT_LOCK_REL = path.join('.longlive', 'index', 'conclusion-drafts.lock');
21
+ export const DRAFT_ARCHIVE_REL = path.join('.longlive', 'archive', 'conclusion-drafts');
22
+ export const DRAFT_DEFAULT_TTL_DAYS = 30;
23
+ export const DRAFT_MAX_TEXT = 2000;
24
+
25
+ const SESSION_ID_RE = /^[a-z0-9][a-z0-9._-]{0,127}$/;
26
+
27
+ function sha256(text) {
28
+ return crypto.createHash('sha256').update(String(text), 'utf8').digest('hex');
29
+ }
30
+
31
+ function nowDate(value) {
32
+ if (value instanceof Date) return value;
33
+ const date = new Date(value ?? Date.now());
34
+ return Number.isNaN(date.getTime()) ? new Date() : date;
35
+ }
36
+
37
+ export function draftsFile(root) {
38
+ return path.join(root, DRAFT_FILE_REL);
39
+ }
40
+
41
+ export function draftsLockFile(root) {
42
+ return path.join(root, DRAFT_LOCK_REL);
43
+ }
44
+
45
+ export function draftsArchiveDir(root) {
46
+ return path.join(root, DRAFT_ARCHIVE_REL);
47
+ }
48
+
49
+ function canonicalLine(entry) {
50
+ const copy = { ...entry };
51
+ delete copy.lineHash;
52
+ return JSON.stringify(copy);
53
+ }
54
+
55
+ function lineHashOf(entry) {
56
+ return sha256(canonicalLine(entry));
57
+ }
58
+
59
+ function normalizeText(value, maxChars = DRAFT_MAX_TEXT) {
60
+ const text = String(value ?? '').replace(/\u0000/g, '').trim();
61
+ return Array.from(text).slice(0, maxChars).join('');
62
+ }
63
+
64
+ function normalizeId(value) {
65
+ return String(value ?? '').toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 80);
66
+ }
67
+
68
+ export function draftIdOf({ sessionId, turn, kind, text }) {
69
+ return `draft:${sha256(`${sessionId}:${turn}:${kind}:${normalizeText(text)}`).slice(0, 20)}`;
70
+ }
71
+
72
+ /**
73
+ * Read and verify the append-only journal. Returns
74
+ * { ok, entries, latest, corrupt, errors }.
75
+ * `latest` is a Map(id -> newest entry) for status transitions.
76
+ */
77
+ export function readDrafts(root, { repair = false } = {}) {
78
+ const file = draftsFile(root);
79
+ let raw = '';
80
+ try { raw = fs.readFileSync(file, 'utf8'); } catch { return { ok: true, entries: [], latest: new Map(), corrupt: false, errors: [] }; }
81
+ const entries = [];
82
+ const errors = [];
83
+ let prevHash = null;
84
+ const lines = raw.split('\n');
85
+ for (let i = 0; i < lines.length; i += 1) {
86
+ const line = lines[i].trim();
87
+ if (line === '') continue;
88
+ let entry;
89
+ try { entry = JSON.parse(line); } catch {
90
+ errors.push({ line: i + 1, code: 'E_DRAFT_JSON' });
91
+ continue;
92
+ }
93
+ if (!entry || entry.schema !== DRAFT_SCHEMA || typeof entry.id !== 'string') {
94
+ errors.push({ line: i + 1, code: 'E_DRAFT_SCHEMA' });
95
+ continue;
96
+ }
97
+ const expected = lineHashOf(entry);
98
+ if (entry.lineHash !== expected) errors.push({ line: i + 1, code: 'E_DRAFT_HASH' });
99
+ if (prevHash !== null && entry.prevHash !== prevHash) errors.push({ line: i + 1, code: 'E_DRAFT_CHAIN' });
100
+ prevHash = entry.lineHash ?? expected;
101
+ entries.push(entry);
102
+ }
103
+ const latest = new Map();
104
+ for (const entry of entries) latest.set(entry.id, entry);
105
+ if (errors.length > 0 && repair) {
106
+ try {
107
+ const corruptPath = `${file}.corrupt-${Date.now()}`;
108
+ fs.copyFileSync(file, corruptPath);
109
+ } catch { /* best effort evidence */ }
110
+ }
111
+ return { ok: errors.length === 0, entries, latest, corrupt: errors.length > 0, errors };
112
+ }
113
+
114
+ function appendLineLocked(root, entry, now) {
115
+ const file = draftsFile(root);
116
+ fs.mkdirSync(path.dirname(file), { recursive: true });
117
+ const existing = readDrafts(root);
118
+ if (existing.corrupt) {
119
+ const error = new Error(`候选池损坏,拒绝追加:${existing.errors[0]?.code ?? 'E_DRAFT_CORRUPT'}`);
120
+ error.code = 'E_DRAFT_CORRUPT';
121
+ throw error;
122
+ }
123
+ const lines = fs.existsSync(file) ? fs.readFileSync(file, 'utf8').split('\n').filter(Boolean) : [];
124
+ const last = lines.length > 0 ? JSON.parse(lines.at(-1)) : null;
125
+ const line = {
126
+ ...entry,
127
+ schema: DRAFT_SCHEMA,
128
+ at: nowDate(now).toISOString(),
129
+ prevHash: last?.lineHash ?? null,
130
+ };
131
+ line.lineHash = lineHashOf(line);
132
+ const fd = fs.openSync(file, 'a');
133
+ try {
134
+ fs.writeFileSync(fd, `${JSON.stringify(line)}\n`, 'utf8');
135
+ try { fs.fsyncSync(fd); } catch { /* fsync unsupported is non-fatal */ }
136
+ } finally {
137
+ fs.closeSync(fd);
138
+ }
139
+ return line;
140
+ }
141
+
142
+ /**
143
+ * Append one draft. Idempotent by id: if the id is already present, returns
144
+ * { written:false, duplicate:true, entry }. The append is serialized by the
145
+ * cross-process lock and fsynced.
146
+ */
147
+ export function appendDraft(root, input = {}, { now = new Date(), holder = `conclusion-${process.pid}` } = {}) {
148
+ const sessionId = String(input.sessionId ?? '').trim().toLowerCase();
149
+ if (!SESSION_ID_RE.test(sessionId)) throw Object.assign(new Error('E_DRAFT_SESSION'), { code: 'E_DRAFT_SESSION' });
150
+ const turn = Number(input.turn);
151
+ if (!Number.isInteger(turn) || turn < 0) throw Object.assign(new Error('E_DRAFT_TURN'), { code: 'E_DRAFT_TURN' });
152
+ const kind = input.kind === 'decision' ? 'decision' : 'fact';
153
+ const text = normalizeText(input.text ?? input.excerpt ?? input.title);
154
+ if (text === '') throw Object.assign(new Error('E_DRAFT_TEXT'), { code: 'E_DRAFT_TEXT' });
155
+ const userText = normalizeText(input.userText ?? input.text ?? input.excerpt ?? input.title);
156
+ if (userText === '') throw Object.assign(new Error('E_DRAFT_USER_TEXT'), { code: 'E_DRAFT_USER_TEXT' });
157
+ const id = typeof input.id === 'string' && input.id.startsWith('draft:')
158
+ ? input.id
159
+ : draftIdOf({ sessionId, turn, kind, text });
160
+ const entry = {
161
+ schema: DRAFT_SCHEMA,
162
+ id,
163
+ sessionId,
164
+ turn,
165
+ at: nowDate(now).toISOString(),
166
+ kind,
167
+ title: normalizeText(input.title ?? text, 160),
168
+ excerpt: normalizeText(input.excerpt ?? text, 240),
169
+ text,
170
+ privacyVerdict: typeof input.privacyVerdict === 'string' ? input.privacyVerdict : 'ok',
171
+ sourceHash: sha256(text),
172
+ userText,
173
+ userTextHash: sha256(userText),
174
+ status: 'pending',
175
+ sourceRole: input.sourceRole === 'assistant' ? 'assistant' : 'user',
176
+ };
177
+ const line = withLease(draftsLockFile(root), { holder, ttlMs: 30_000, now }, () => {
178
+ // 批 C(M28):去重必须在锁内重读——锁外判定会让两个并发调用各写一行。
179
+ const locked = readDrafts(root).latest.get(id);
180
+ if (locked) return { written: false, duplicate: true, entry: locked };
181
+ return appendLineLocked(root, entry, now);
182
+ });
183
+ if (line && line.written === false) return line;
184
+ return { written: true, duplicate: false, entry: line };
185
+ }
186
+
187
+ /** Append a status transition (never rewrite or delete earlier lines). */
188
+ export function transitionDraft(root, id, status, { reason = '', now = new Date(), holder = `conclusion-${process.pid}` } = {}) {
189
+ const allowed = DRAFT_STATUSES.includes(status) ? status : null;
190
+ if (allowed === null) throw Object.assign(new Error('E_DRAFT_STATUS'), { code: 'E_DRAFT_STATUS' });
191
+ const current = readDrafts(root).latest.get(id);
192
+ if (!current) throw Object.assign(new Error('E_DRAFT_NOT_FOUND'), { code: 'E_DRAFT_NOT_FOUND' });
193
+ if (current.status === allowed) return { written: false, entry: current };
194
+ const line = withLease(draftsLockFile(root), { holder, ttlMs: 30_000, now }, () => appendLineLocked(root, {
195
+ ...current,
196
+ status: allowed,
197
+ statusReason: normalizeText(reason, 300),
198
+ updatedAt: nowDate(now).toISOString(),
199
+ lineHash: undefined,
200
+ prevHash: undefined,
201
+ }, now));
202
+ return { written: true, entry: line };
203
+ }
204
+
205
+ /** Newest entries only, optionally filtered. */
206
+ export function listDrafts(root, { status = null } = {}) {
207
+ const read = readDrafts(root);
208
+ const rows = [...read.latest.values()].sort((a, b) => String(a.at).localeCompare(String(b.at)));
209
+ return status === null ? rows : rows.filter((entry) => entry.status === status);
210
+ }
211
+
212
+ /**
213
+ * Move pending drafts older than ttlDays into `.longlive/archive/conclusion-drafts/`
214
+ * (copy + status=expired; nothing is deleted). Returns { archived, ids, auditErrors }.
215
+ */
216
+ export function archiveExpiredDrafts(root, {
217
+ ttlDays = DRAFT_DEFAULT_TTL_DAYS, now = new Date(), holder = `conclusion-${process.pid}`,
218
+ } = {}) {
219
+ const ttl = Number(ttlDays);
220
+ const days = Number.isFinite(ttl) && ttl > 0 ? ttl : DRAFT_DEFAULT_TTL_DAYS;
221
+ const at = nowDate(now);
222
+ const cutoff = at.getTime() - days * 24 * 60 * 60 * 1000;
223
+ const expired = listDrafts(root, { status: 'pending' }).filter((entry) => {
224
+ const ts = Date.parse(String(entry.at ?? ''));
225
+ return Number.isFinite(ts) && ts < cutoff;
226
+ });
227
+ if (expired.length === 0) return { archived: 0, ids: [], auditErrors: [] };
228
+ const dir = draftsArchiveDir(root);
229
+ fs.mkdirSync(dir, { recursive: true });
230
+ const archiveFile = path.join(dir, `${at.toISOString().slice(0, 10)}.jsonl`);
231
+ const auditErrors = [];
232
+ for (const entry of expired) {
233
+ try {
234
+ fs.appendFileSync(archiveFile, `${JSON.stringify({ ...entry, status: 'expired', archivedAt: at.toISOString() })}\n`, 'utf8');
235
+ transitionDraft(root, entry.id, 'expired', { reason: `ttl:${days}d`, now: at, holder });
236
+ } catch (error) {
237
+ auditErrors.push({ id: entry.id, code: String(error?.code ?? error) });
238
+ }
239
+ }
240
+ return { archived: expired.length - auditErrors.length, ids: expired.map((entry) => entry.id), auditErrors, archiveFile };
241
+ }
242
+
243
+ export { sha256 as draftSha256 };