@jjh32456/longlive 0.0.0-stage → 1.8.12

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 (309) hide show
  1. package/CHANGELOG.md +205 -0
  2. package/LICENSE +21 -0
  3. package/QUICKSTART.md +363 -0
  4. package/README.en.md +55 -0
  5. package/README.md +225 -2
  6. package/SPEC.md +211 -0
  7. package/build-info.json +1555 -0
  8. package/cordis.patch.yml +177 -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 +807 -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 +46 -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 +160 -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-a1-legacy.mjs +62 -0
  55. package/scripts/migrate-lifecycle.mjs +157 -0
  56. package/scripts/pack.mjs +392 -0
  57. package/scripts/recall-index-build.mjs +128 -0
  58. package/scripts/recall-links-build.mjs +420 -0
  59. package/scripts/rescore-cards.mjs +36 -0
  60. package/scripts/resident-watcher-status.ps1 +15 -0
  61. package/scripts/resident-watcher.ps1 +643 -0
  62. package/scripts/session-watch-drill.mjs +553 -0
  63. package/scripts/session-watch-status.ps1 +146 -0
  64. package/scripts/session-watch.mjs +1367 -0
  65. package/scripts/surgery-inspect.mjs +122 -0
  66. package/scripts/surgery-run.cmd +34 -0
  67. package/scripts/truncate-cli.mjs +279 -0
  68. package/scripts/unattended-surgery.ps1 +1019 -0
  69. package/scripts/uninstall-resident-watcher.ps1 +15 -0
  70. package/scripts/uninstall-session-watch.ps1 +192 -0
  71. package/scripts/verify-card-anchors.mjs +138 -0
  72. package/scripts/watch-loop.ps1 +916 -0
  73. package/src/actions/audit.js +125 -0
  74. package/src/actions/evidence.js +122 -0
  75. package/src/actions/fs.js +162 -0
  76. package/src/activity/index.js +873 -0
  77. package/src/activity/model.js +351 -0
  78. package/src/activity/store.js +786 -0
  79. package/src/activity/summary.js +180 -0
  80. package/src/activity/thinking.js +191 -0
  81. package/src/adapters/constants.js +11 -0
  82. package/src/adapters/engram/data/aliases.json +51 -0
  83. package/src/adapters/engram/data/policy.json +8 -0
  84. package/src/adapters/engram/data/routing-rules.json +546 -0
  85. package/src/adapters/engram/index.js +278 -0
  86. package/src/adapters/registry.js +315 -0
  87. package/src/answer/audit.js +238 -0
  88. package/src/answer/evidence.js +30 -0
  89. package/src/answer/guard.js +1370 -0
  90. package/src/answer/index.js +1086 -0
  91. package/src/answer/query.js +111 -0
  92. package/src/answer/second-hop.mjs +101 -0
  93. package/src/auto-truncate-status.js +164 -0
  94. package/src/auto-truncate.js +1181 -0
  95. package/src/autoprocedure/candidate.js +342 -0
  96. package/src/autoprocedure/config.js +122 -0
  97. package/src/autoprocedure/evidence.js +345 -0
  98. package/src/autoprocedure/index.js +83 -0
  99. package/src/autoprocedure/ledger.js +329 -0
  100. package/src/autoprocedure/lint.js +232 -0
  101. package/src/autoprocedure/llm.js +409 -0
  102. package/src/autoprocedure/locks.js +102 -0
  103. package/src/autoprocedure/paths.js +39 -0
  104. package/src/autoprocedure/privacy.js +87 -0
  105. package/src/autoprocedure/rules.js +288 -0
  106. package/src/autoprocedure/runtime.js +718 -0
  107. package/src/autoprocedure/session-reader.js +328 -0
  108. package/src/backup.js +146 -0
  109. package/src/bus/bus.mjs +1446 -0
  110. package/src/codec.js +269 -0
  111. package/src/compaction/cut-engine.js +44 -0
  112. package/src/compaction/engine-core.js +1237 -0
  113. package/src/compaction/entry.js +228 -0
  114. package/src/compaction.js +230 -0
  115. package/src/conclusion.js +366 -0
  116. package/src/config.js +824 -0
  117. package/src/d6/runtime.js +517 -0
  118. package/src/d6/surface.js +181 -0
  119. package/src/deps.js +189 -0
  120. package/src/engine-status.js +141 -0
  121. package/src/features.js +912 -0
  122. package/src/handoff/index.js +944 -0
  123. package/src/handoff/model.js +1010 -0
  124. package/src/handoff/store.js +1233 -0
  125. package/src/heartbeat.js +385 -0
  126. package/src/home.js +16 -0
  127. package/src/host-version.js +280 -0
  128. package/src/hot-truncate-diag.js +98 -0
  129. package/src/identity/card-marker.js +281 -0
  130. package/src/identity/handover.js +657 -0
  131. package/src/identity/index.js +337 -0
  132. package/src/identity/inject-position.js +131 -0
  133. package/src/identity/writeback.js +344 -0
  134. package/src/identity.js +118 -0
  135. package/src/index.js +647 -0
  136. package/src/lifecycle/gap-clocks.js +364 -0
  137. package/src/lifecycle/index.js +269 -0
  138. package/src/lifecycle/proactive.js +1426 -0
  139. package/src/live-target.js +212 -0
  140. package/src/live.js +1603 -0
  141. package/src/log-rotation.js +153 -0
  142. package/src/memory/a1-migration.js +124 -0
  143. package/src/memory/activity-capture.js +229 -0
  144. package/src/memory/anchor-fallback.js +116 -0
  145. package/src/memory/anchors.js +194 -0
  146. package/src/memory/audit-records.js +222 -0
  147. package/src/memory/auto-cards.js +441 -0
  148. package/src/memory/capture-host.js +228 -0
  149. package/src/memory/capture.js +457 -0
  150. package/src/memory/card-anchors.js +203 -0
  151. package/src/memory/card-priority.js +110 -0
  152. package/src/memory/cards.js +425 -0
  153. package/src/memory/conclusion-distill.js +332 -0
  154. package/src/memory/conclusion-drafts.js +239 -0
  155. package/src/memory/conflicts.js +147 -0
  156. package/src/memory/consolidate.js +815 -0
  157. package/src/memory/decay.js +311 -0
  158. package/src/memory/distill.js +485 -0
  159. package/src/memory/event-index.js +1826 -0
  160. package/src/memory/evidence-chain.js +295 -0
  161. package/src/memory/evidence.js +213 -0
  162. package/src/memory/filter-runner.js +555 -0
  163. package/src/memory/filter.js +1035 -0
  164. package/src/memory/forget-v2.js +410 -0
  165. package/src/memory/forget.js +512 -0
  166. package/src/memory/frames-activation.js +247 -0
  167. package/src/memory/frontmatter.js +454 -0
  168. package/src/memory/fts-query.js +342 -0
  169. package/src/memory/governance.js +604 -0
  170. package/src/memory/index-freshness.js +234 -0
  171. package/src/memory/index.js +362 -0
  172. package/src/memory/l2-gate.js +169 -0
  173. package/src/memory/lifecycle.js +107 -0
  174. package/src/memory/lock.js +121 -0
  175. package/src/memory/maintenance.js +785 -0
  176. package/src/memory/manifest.js +245 -0
  177. package/src/memory/migrate-lifecycle.js +1808 -0
  178. package/src/memory/migrate.js +139 -0
  179. package/src/memory/paths.js +229 -0
  180. package/src/memory/procedure.js +963 -0
  181. package/src/memory/provenance.js +119 -0
  182. package/src/memory/recall-v2.js +206 -0
  183. package/src/memory/recall.js +256 -0
  184. package/src/memory/reconcile.js +265 -0
  185. package/src/memory/records.js +433 -0
  186. package/src/memory/reinforce.js +145 -0
  187. package/src/memory/retention.js +128 -0
  188. package/src/memory/review.js +124 -0
  189. package/src/memory/state.js +279 -0
  190. package/src/memory/tiers.js +168 -0
  191. package/src/memory/topic-phrases.js +73 -0
  192. package/src/memory/trust.js +97 -0
  193. package/src/memory/version-chain.js +264 -0
  194. package/src/memory/wal.js +137 -0
  195. package/src/memory/working-frame.js +516 -0
  196. package/src/metrics/classify.mjs +189 -0
  197. package/src/metrics/estimate.mjs +108 -0
  198. package/src/metrics/index.mjs +204 -0
  199. package/src/metrics/measure.mjs +462 -0
  200. package/src/metrics/prestep-latency.mjs +307 -0
  201. package/src/metrics/store.mjs +264 -0
  202. package/src/original.js +294 -0
  203. package/src/policy/threshold-policy.js +224 -0
  204. package/src/policy-profile.js +463 -0
  205. package/src/recall/anaphora.mjs +87 -0
  206. package/src/recall/archive-fallback.mjs +235 -0
  207. package/src/recall/archive-search.mjs +425 -0
  208. package/src/recall/cards.mjs +202 -0
  209. package/src/recall/edges.js +379 -0
  210. package/src/recall/embedding.mjs +698 -0
  211. package/src/recall/entities.mjs +112 -0
  212. package/src/recall/explain.mjs +433 -0
  213. package/src/recall/force-policy.mjs +138 -0
  214. package/src/recall/index.js +1036 -0
  215. package/src/recall/inject-order.mjs +277 -0
  216. package/src/recall/link-recall.mjs +183 -0
  217. package/src/recall/links.mjs +696 -0
  218. package/src/recall/privacy.mjs +208 -0
  219. package/src/recall/recall-core.mjs +765 -0
  220. package/src/recall/shared-visibility.js +302 -0
  221. package/src/recall/time-normalizer.mjs +196 -0
  222. package/src/retention/config.js +106 -0
  223. package/src/retention/index.js +643 -0
  224. package/src/role/activation.js +191 -0
  225. package/src/role/attention.js +318 -0
  226. package/src/role/base.js +36 -0
  227. package/src/role/channels.js +423 -0
  228. package/src/role/index.js +425 -0
  229. package/src/role/interfaces.js +115 -0
  230. package/src/role/personality.js +370 -0
  231. package/src/role/readers.js +151 -0
  232. package/src/role/relationships.js +477 -0
  233. package/src/role/store.js +202 -0
  234. package/src/role/writeprotect.js +373 -0
  235. package/src/router/aliases.json +182 -0
  236. package/src/router/background/agent-runner.mjs +239 -0
  237. package/src/router/background/anchor.mjs +323 -0
  238. package/src/router/background/audit.mjs +337 -0
  239. package/src/router/background/budget-ledger.mjs +648 -0
  240. package/src/router/background/host-sim.mjs +451 -0
  241. package/src/router/background/index.mjs +81 -0
  242. package/src/router/background/memory.mjs +63 -0
  243. package/src/router/background/mock-llm.mjs +203 -0
  244. package/src/router/background/queue.mjs +224 -0
  245. package/src/router/background/retry.mjs +255 -0
  246. package/src/router/background/router.mjs +1459 -0
  247. package/src/router/background/stream.mjs +276 -0
  248. package/src/router/background/tool-policy.mjs +255 -0
  249. package/src/router/design-headings.json +221 -0
  250. package/src/router/face/config.mjs +155 -0
  251. package/src/router/face/context.mjs +284 -0
  252. package/src/router/face/face.mjs +466 -0
  253. package/src/router/face/identity.mjs +130 -0
  254. package/src/router/face/index.mjs +65 -0
  255. package/src/router/face/journal.mjs +119 -0
  256. package/src/router/face/llm.mjs +252 -0
  257. package/src/router/face/outbox.mjs +153 -0
  258. package/src/router/face/paths.mjs +54 -0
  259. package/src/router/judge.mjs +987 -0
  260. package/src/router/policies/generic.json +131 -0
  261. package/src/router/route.js +1766 -0
  262. package/src/router/router.mjs +535 -0
  263. package/src/router/routing-rules.json +816 -0
  264. package/src/router/run-sim.mjs +530 -0
  265. package/src/router/runtime.js +569 -0
  266. package/src/router/service/apply.mjs +1218 -0
  267. package/src/router/service/board.mjs +712 -0
  268. package/src/router/service/caller.mjs +131 -0
  269. package/src/router/service/config.mjs +361 -0
  270. package/src/router/service/context.mjs +314 -0
  271. package/src/router/service/hint.mjs +668 -0
  272. package/src/router/service/lease.mjs +494 -0
  273. package/src/router/service/live.mjs +251 -0
  274. package/src/router/service/lock.mjs +550 -0
  275. package/src/router/service/merge.mjs +255 -0
  276. package/src/router/service/model-resolve.mjs +350 -0
  277. package/src/router/service/paths.mjs +168 -0
  278. package/src/router/service/proposals.mjs +1461 -0
  279. package/src/router/service/queue.mjs +477 -0
  280. package/src/router/service/reconcile.mjs +271 -0
  281. package/src/router/service/service.mjs +2998 -0
  282. package/src/router/service/sources.mjs +352 -0
  283. package/src/router/service/status.mjs +520 -0
  284. package/src/router/service/store.mjs +476 -0
  285. package/src/router/service/ticklock.mjs +239 -0
  286. package/src/router/service/tokens.mjs +95 -0
  287. package/src/router/service/tools.mjs +248 -0
  288. package/src/router/service/wake.mjs +544 -0
  289. package/src/router/service/wal.mjs +685 -0
  290. package/src/router/shadow.mjs +821 -0
  291. package/src/surgery-recovery.js +1909 -0
  292. package/src/tool-output.js +485 -0
  293. package/src/tools.js +3146 -0
  294. package/src/truncate-visible.js +2416 -0
  295. package/src/truncate.js +999 -0
  296. package/src/ui/actions.js +1312 -0
  297. package/src/ui/flags.js +259 -0
  298. package/src/ui/panel-api.js +371 -0
  299. package/src/ui/panel-auth.js +251 -0
  300. package/src/ui/panel-integrity.js +243 -0
  301. package/src/ui/routes-readonly.js +759 -0
  302. package/src/ui/routes.js +284 -0
  303. package/src/util/append-store.js +368 -0
  304. package/src/util/local-day.js +30 -0
  305. package/src/util/redact.js +227 -0
  306. package/src/util/stale-locks.js +148 -0
  307. package/src/version.js +99 -0
  308. package/test/fixtures/pre-step-container.mjs +100 -0
  309. package/test/p1_probe.mjs +97 -0
@@ -0,0 +1,366 @@
1
+ // conclusion.js — A1「结论自动回流」v1.
2
+ //
3
+ // At `turn/end` (reason: completed) this bridge looks at the turn's last real
4
+ // user message and the assistant's final text blocks, decides locally — no
5
+ // LLM call — whether the turn contains a conclusion (定了 / 决定 / 结论 /
6
+ // 就这样 / 改成 ...), and, when it does, appends one *draft* to
7
+ // `<memoryRoot>/.longlive/index/conclusion-drafts.jsonl` plus a per-session
8
+ // marker under `<memoryRoot>/.longlive/bridge/` that keeps the same
9
+ // session+turn idempotent and publishes the one-line conclusion the shared
10
+ // board reads (A2). Drafts are raw material only: memory/conclusion-distill.js
11
+ // is the only path that may turn a validated draft into a recallable card.
12
+ //
13
+ // Privacy reuses the auto-recall gate (`recall/privacy.mjs`): a local_only
14
+ // verdict, or a throwing gate, silently drops the draft. Every path is wrapped
15
+ // so a failure never blocks the turn that triggered it.
16
+
17
+ import fs from 'node:fs';
18
+ import path from 'node:path';
19
+ import crypto from 'node:crypto';
20
+ import { isoStamp } from './memory/frontmatter.js';
21
+ import { appendDraft, draftIdOf } from './memory/conclusion-drafts.js';
22
+ import { privacyScan as defaultPrivacyScan } from './recall/privacy.mjs';
23
+ import { isUserAuthoredMessage } from './truncate-visible.js';
24
+
25
+ export const BRIDGE_VERSION = 1;
26
+ export const CONCLUSION_BODY_MAX = 500;
27
+ export const CONCLUSION_TEXT_MAX = 120;
28
+ export const CONCLUSION_TITLE_MAX = 60;
29
+ export const CONCLUSION_USER_MAX = 200;
30
+ export const CONCLUSION_ASSISTANT_MAX = 280;
31
+ export const BRIDGE_TURNS_MAX = 50;
32
+ export const CONCLUSION_CARD_PREFIX = 'conclusion';
33
+
34
+ /** Words that mark a decision. Checked before FACT_TRIGGERS (「结论是」 wins). */
35
+ export const DECISION_TRIGGERS = Object.freeze([
36
+ '定了', '决定', '拍板', '敲定', '定稿', '就这么', '就这样', '按这个',
37
+ '以后都', '改成', '最终方案', '最后决定', '结论是', '就按',
38
+ ]);
39
+
40
+ /** Weaker conclusion markers: a summary/answer rather than a directive. */
41
+ export const FACT_TRIGGERS = Object.freeze([
42
+ '结论', '最后', '总结', '因此', '所以', '确定', '确认', '记下',
43
+ ]);
44
+
45
+ const SESSION_ID_RE = /^[a-z0-9][a-z0-9._-]{0,127}$/;
46
+
47
+ function oneLine(value, maxChars = 0) {
48
+ const text = String(value ?? '')
49
+ .replace(/[\u0000-\u001f\u007f]+/g, ' ')
50
+ .replace(/\s+/g, ' ')
51
+ .trim();
52
+ return maxChars > 0 ? clip(text, maxChars) : text;
53
+ }
54
+
55
+ function clip(value, maxChars) {
56
+ const text = String(value ?? '');
57
+ if (maxChars <= 0) return '';
58
+ const chars = Array.from(text);
59
+ if (chars.length <= maxChars) return text;
60
+ return `${chars.slice(0, maxChars - 1).join('')}…`;
61
+ }
62
+
63
+ function textBlocks(content) {
64
+ if (!Array.isArray(content)) return '';
65
+ const parts = [];
66
+ for (const block of content) {
67
+ if (!block || block.type !== 'text') continue; // reasoning / tool-call are skipped
68
+ if (typeof block.text !== 'string') continue;
69
+ const text = block.text.trim();
70
+ if (text !== '') parts.push(text);
71
+ }
72
+ return parts.join('\n');
73
+ }
74
+
75
+ function sentences(text) {
76
+ return oneLine(text)
77
+ .split(/(?<=[。!?!?;;])/)
78
+ .map((item) => item.trim())
79
+ .filter((item) => item !== '');
80
+ }
81
+
82
+ function firstSentence(text) {
83
+ return sentences(text)[0] ?? '';
84
+ }
85
+
86
+ function triggerSentence(text) {
87
+ return sentences(text).find((item) => classifyConclusionText(item) !== null) ?? '';
88
+ }
89
+
90
+ /** Local rule: which kind of conclusion marker (if any) the text carries. */
91
+ export function classifyConclusionText(text) {
92
+ const value = oneLine(text);
93
+ if (value === '') return null;
94
+ if (DECISION_TRIGGERS.some((word) => value.includes(word))) return 'decision';
95
+ if (FACT_TRIGGERS.some((word) => value.includes(word))) return 'fact';
96
+ return null;
97
+ }
98
+
99
+ /** Short statement other sessions see as 「结论」. v2: user text only. */
100
+ export function pickExcerpt(userText, assistantText) {
101
+ const user = oneLine(userText);
102
+ const candidate = sentences(user).find((item) => isUserDecisionText(item))
103
+ || firstSentence(user);
104
+ return clip(oneLine(candidate), CONCLUSION_TEXT_MAX);
105
+ }
106
+
107
+ /** v2: narrow "user decision" recognizer. Ordinary narration, questions and
108
+ * long process reports are not decisions even when they contain 定了/所以. */
109
+ const USER_DECISION_START = /(?:^|[,。!?;、\s])(?:好[,,]?\s*)?(?:就这么|就这样|按这个|改成|以后都|决定|拍板|敲定|定稿|定了|就按|就用|行[,,]?\s*就)/u;
110
+ export function isUserDecisionText(text) {
111
+ const value = oneLine(text);
112
+ if (value === '' || Array.from(value).length > 160) return false;
113
+ if (/[??]\s*$/u.test(value)) return false;
114
+ if (/(?:什么|吗|呢|怎么|如何)\s*[??]?\s*$/u.test(value)) return false;
115
+ if (/(?:行不行|好不好|可以吗|怎么样|如何|是不是|要不要)/u.test(value)) return false;
116
+ if (/(?:分析|给个|帮我看|告诉我|看看|怎么改|如何改)/u.test(value)) return false;
117
+ return USER_DECISION_START.test(value);
118
+ }
119
+
120
+ /**
121
+ * A1 v2 decision source rule: only a *user-authored decision* can become a
122
+ * draft. Assistant text may appear in the body as context/evidence, but it is
123
+ * never consulted for the trigger or the conclusion sentence.
124
+ */
125
+ export function judgeConclusion({ userText, assistantText } = {}) {
126
+ const user = oneLine(userText);
127
+ const assistant = oneLine(assistantText);
128
+ if (Array.from(user).length < 2) return null;
129
+ if (!isUserDecisionText(user)) return null;
130
+ const decisionSentence = sentences(user).find((item) => isUserDecisionText(item)) ?? firstSentence(user);
131
+ const excerpt = clip(oneLine(decisionSentence), CONCLUSION_TEXT_MAX);
132
+ if (excerpt === '') return null;
133
+ // v3: title/body are user text only. No assistant context is stored on the
134
+ // draft, so no card path can ever copy assistant prose.
135
+ const title = clip(excerpt, CONCLUSION_TITLE_MAX);
136
+ const body = `用户:${clip(user, CONCLUSION_USER_MAX)}`;
137
+ return {
138
+ kind: 'decision', title, excerpt, text: excerpt, body,
139
+ sourceRole: 'user', userText: user,
140
+ };
141
+ }
142
+
143
+ /** `<memoryRoot>/.longlive/bridge` — same directory A2's board reads. */
144
+ export function bridgeDirFor(memoryRoot) {
145
+ return path.join(memoryRoot, '.longlive', 'bridge');
146
+ }
147
+
148
+ export function bridgeMarkerFile(memoryRoot, sessionId) {
149
+ return path.join(bridgeDirFor(memoryRoot), `${sessionId}.json`);
150
+ }
151
+
152
+ export function readBridgeMarker(memoryRoot, sessionId) {
153
+ try {
154
+ return JSON.parse(fs.readFileSync(bridgeMarkerFile(memoryRoot, sessionId), 'utf8'));
155
+ } catch {
156
+ return null;
157
+ }
158
+ }
159
+
160
+ function hash8(value) {
161
+ return crypto.createHash('sha256').update(String(value)).digest('hex').slice(0, 8);
162
+ }
163
+
164
+ function writeJsonAtomic(file, value) {
165
+ const dir = path.dirname(file);
166
+ fs.mkdirSync(dir, { recursive: true });
167
+ const tmp = path.join(dir, `.${path.basename(file)}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`);
168
+ fs.writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
169
+ fs.renameSync(tmp, file);
170
+ }
171
+
172
+ export function conclusionCardFile(memoryRoot, sessionId, turn) {
173
+ return path.join(memoryRoot, 'topics', `${CONCLUSION_CARD_PREFIX}-t${turn}-${hash8(sessionId)}.md`);
174
+ }
175
+
176
+ /**
177
+ * A1 1.8.1: the turn's conclusion is only a *draft*. It is appended to the
178
+ * append-only candidate pool under `.longlive/index/`, never to `topics/`.
179
+ * Distillation in memory/conclusion-distill.js is the only path to recall.
180
+ */
181
+ function writeDraft(memoryRoot, sessionId, turn, at, judged, privacyVerdict) {
182
+ const text = judged.body;
183
+ const result = appendDraft(memoryRoot, {
184
+ id: draftIdOf({ sessionId, turn, kind: judged.kind, text }),
185
+ sessionId,
186
+ turn,
187
+ at,
188
+ kind: judged.kind,
189
+ title: judged.title,
190
+ excerpt: judged.excerpt,
191
+ text,
192
+ privacyVerdict,
193
+ status: 'pending',
194
+ sourceRole: 'user',
195
+ userText: judged.userText ?? judged.body,
196
+ }, { now: at });
197
+ return result;
198
+ }
199
+
200
+ function dateOf(value) {
201
+ if (value instanceof Date) return value;
202
+ return new Date(value ?? Date.now());
203
+ }
204
+
205
+ function resolveSessionId(session, event) {
206
+ const raw = session?.id
207
+ ?? session?.header?.id
208
+ ?? event?.sessionId
209
+ ?? '';
210
+ if (typeof raw !== 'string') return '';
211
+ const id = raw.trim().toLowerCase();
212
+ return SESSION_ID_RE.test(id) ? id : '';
213
+ }
214
+
215
+ /**
216
+ * Create the bridge. `enabled === true` is the only switch (A1 is opt-in, so
217
+ * the plugin's default behaviour is unchanged). The returned onSessionEvent is
218
+ * meant to be wired to `ctx.on('session/event', ...)`.
219
+ */
220
+ export function createConclusionBridge(options = {}) {
221
+ const enabled = options.enabled === true;
222
+ const memoryRoot = typeof options.memoryRoot === 'string' ? options.memoryRoot.trim() : '';
223
+ const now = typeof options.now === 'function' ? options.now : () => new Date();
224
+ const scan = typeof options.privacyScan === 'function' ? options.privacyScan : defaultPrivacyScan;
225
+ const stats = { turns: 0, written: 0, skipped: 0, duplicates: 0, privacy: 0, errors: 0 };
226
+ const sessions = new Map();
227
+
228
+ function reset() {
229
+ sessions.clear();
230
+ stats.turns = 0;
231
+ stats.written = 0;
232
+ stats.skipped = 0;
233
+ stats.duplicates = 0;
234
+ stats.privacy = 0;
235
+ stats.errors = 0;
236
+ }
237
+
238
+ if (!enabled || memoryRoot === '') {
239
+ return { enabled: false, memoryRoot, stats, onSessionEvent() {}, reset };
240
+ }
241
+
242
+ function flush(state, turn) {
243
+ const judged = judgeConclusion({ userText: state.userText, assistantText: state.assistantText });
244
+ if (judged === null) {
245
+ stats.skipped += 1;
246
+ return { written: false, reason: 'not-conclusion' };
247
+ }
248
+ const prior = readBridgeMarker(memoryRoot, state.sessionId);
249
+ const priorTurns = prior && typeof prior.turns === 'object' && prior.turns !== null
250
+ ? prior.turns
251
+ : {};
252
+ if (priorTurns[String(turn)] !== undefined
253
+ || (prior?.lastConclusion && prior.lastConclusion.turn === turn)) {
254
+ stats.duplicates += 1;
255
+ return { written: false, reason: 'duplicate' };
256
+ }
257
+ let verdict = null;
258
+ try {
259
+ verdict = scan(judged.body);
260
+ } catch {
261
+ verdict = { verdict: 'local_only' };
262
+ }
263
+ if (!verdict || verdict.verdict === 'local_only') {
264
+ stats.privacy += 1;
265
+ return { written: false, reason: 'privacy' };
266
+ }
267
+ try {
268
+ const at = dateOf(now());
269
+ const written = writeDraft(memoryRoot, state.sessionId, turn, at, judged, verdict.verdict);
270
+ if (!written.written) {
271
+ stats.duplicates += 1;
272
+ return { written: false, reason: 'duplicate' };
273
+ }
274
+ const turns = { ...priorTurns };
275
+ turns[String(turn)] = isoStamp(at);
276
+ const keys = Object.keys(turns).sort((a, b) => Number(a) - Number(b));
277
+ while (keys.length > BRIDGE_TURNS_MAX) delete turns[keys.shift()];
278
+ writeJsonAtomic(bridgeMarkerFile(memoryRoot, state.sessionId), {
279
+ v: BRIDGE_VERSION,
280
+ sessionId: state.sessionId,
281
+ updatedAt: isoStamp(at),
282
+ lastConclusion: {
283
+ text: judged.text,
284
+ kind: judged.kind,
285
+ turn,
286
+ at: isoStamp(at),
287
+ },
288
+ turns,
289
+ });
290
+ stats.written += 1;
291
+ return { written: true, reason: 'drafted', draft: written.entry, kind: judged.kind, text: judged.text };
292
+ } catch {
293
+ stats.errors += 1;
294
+ return { written: false, reason: 'error' };
295
+ }
296
+ }
297
+
298
+ function handle(session, event) {
299
+ const type = event?.type;
300
+ if (typeof type !== 'string') return;
301
+ const sessionId = resolveSessionId(session, event);
302
+ if (type === 'session/disposed') {
303
+ if (sessionId !== '') sessions.delete(sessionId);
304
+ return;
305
+ }
306
+ if (sessionId === '') return;
307
+ let state = sessions.get(sessionId);
308
+ if (!state) {
309
+ state = { sessionId, turn: null, userText: '', assistantText: '' };
310
+ sessions.set(sessionId, state);
311
+ }
312
+
313
+ if (type === 'turn/start') {
314
+ const turn = event?.data?.turn;
315
+ state.turn = Number.isInteger(turn) ? turn : state.turn;
316
+ state.userText = '';
317
+ state.assistantText = '';
318
+ return;
319
+ }
320
+
321
+ if (type === 'user/message') {
322
+ if (!isUserAuthoredMessage(event)) return;
323
+ const text = textBlocks(event?.data?.content);
324
+ if (text !== '') state.userText = text;
325
+ return;
326
+ }
327
+
328
+ if (type === 'assistant/message') {
329
+ const data = event?.data ?? {};
330
+ const turn = data.turn;
331
+ if (Number.isInteger(turn) && Number.isInteger(state.turn) && turn !== state.turn) return;
332
+ const message = data.message && typeof data.message === 'object' ? data.message : data;
333
+ const text = textBlocks(message?.content);
334
+ // Only the final non-empty text wins; a tool-only closing step leaves the
335
+ // previous text in place.
336
+ if (text !== '') state.assistantText = text;
337
+ return;
338
+ }
339
+
340
+ if (type === 'turn/end') {
341
+ const turn = event?.data?.turn;
342
+ const reason = event?.data?.reason?.kind;
343
+ const resolved = Number.isInteger(turn) ? turn : state.turn;
344
+ stats.turns += 1;
345
+ if (Number.isInteger(resolved) && reason === 'completed') flush(state, resolved);
346
+ else stats.skipped += 1;
347
+ state.userText = '';
348
+ state.assistantText = '';
349
+ state.turn = Number.isInteger(resolved) ? resolved : null;
350
+ }
351
+ }
352
+
353
+ return {
354
+ enabled: true,
355
+ memoryRoot,
356
+ stats,
357
+ reset,
358
+ onSessionEvent(session, event) {
359
+ try {
360
+ handle(session, event);
361
+ } catch {
362
+ stats.errors += 1;
363
+ }
364
+ },
365
+ };
366
+ }