@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,228 @@
1
+ // Thin, fail-open entry for the hot-truncate compaction row.
2
+ //
3
+ // This file must evaluate even when the engine cannot: a throw at import time
4
+ // would leave the host's stock compaction row disabled (the bundle patch turns
5
+ // `compaction-basic` off) and `/compact` waiting forever. It follows the
6
+ // dsh-live-compact shell pattern:
7
+ //
8
+ // 1. load the host packages + engine; remember the first failure;
9
+ // 2. choose: defer to live-compact / hand back to stock / register our cut;
10
+ // 3. on any construction failure, RELEASE the just-registered ctx.compaction
11
+ // and construct the stock BasicCompactionEngine;
12
+ // 4. if even stock cannot load, return a no-op plugin that only logs.
13
+ //
14
+ // Nothing here touches a real profile; the bundle patch that inserts this row
15
+ // is shipped separately in PATCH.md.
16
+
17
+ import fs from 'node:fs';
18
+ import os from 'node:os';
19
+ import path from 'node:path';
20
+ import { createRequire } from 'node:module';
21
+ import { normalizeOptions, stockConfig } from './engine-core.js';
22
+
23
+ const STOCK_PACKAGE = '@deepseek-ai/dsh-compaction-basic';
24
+ const OUR_NAME = 'hot-truncate';
25
+ const LIVE_COMPACT_PACKAGES = Object.freeze(['dsh-live-compact', '@deepseek-ai/dsh-live-compact']);
26
+
27
+ function reasonOf(error) {
28
+ return error instanceof Error ? error.message : String(error);
29
+ }
30
+
31
+ function log(ctx, level, message) {
32
+ try {
33
+ const logger = ctx?.logger;
34
+ if (typeof logger?.[level] === 'function') logger[level](message);
35
+ else if (level === 'warn') console.error(message);
36
+ } catch {
37
+ // A logger failure must never cascade into a plugin failure.
38
+ }
39
+ }
40
+
41
+ // -- failure path: release the service this constructor registered ----------
42
+
43
+ /**
44
+ * Undo a Cordis Service registration. The reference implementation walks both
45
+ * symbol and string keys of the reflective store; a plain `delete
46
+ * ctx.compaction` is not enough because Cordis keeps services behind symbols.
47
+ */
48
+ export function releaseCompaction(ctx) {
49
+ let released = false;
50
+ try {
51
+ const store = ctx?.reflect?.store;
52
+ if (store) {
53
+ const keys = [...Object.getOwnPropertySymbols(store), ...Object.keys(store)];
54
+ for (const key of keys) {
55
+ if (store[key]?.name !== 'compaction') continue;
56
+ delete store[key];
57
+ released = true;
58
+ }
59
+ }
60
+ if (ctx?.fiber?.store && ctx.fiber.store.compaction) {
61
+ delete ctx.fiber.store.compaction;
62
+ released = true;
63
+ }
64
+ } catch {
65
+ // Reported by the caller through the fallback; never thrown.
66
+ }
67
+ return released;
68
+ }
69
+
70
+ // -- coexistence -------------------------------------------------------------
71
+
72
+ /**
73
+ * Detect an installed/live live-compact. The task requires "row id
74
+ * compaction-spine or package name dsh-live-compact" to win by default, so
75
+ * every probe is conservative: any positive match means defer.
76
+ *
77
+ * Order: explicit config/env override → an already-registered compaction
78
+ * service → live-compact's gate service → package resolution → the active
79
+ * profile text. The last probe is what sees a row id (`compaction-spine`) even
80
+ * when the package is installed outside this module's resolution path.
81
+ */
82
+ export function detectLiveCompact(ctx, options = {}, env = process.env) {
83
+ if (options?.assumeLiveCompact === true) return 'config.assumeLiveCompact';
84
+ if (env?.DSH_HOT_TRUNCATE_LIVE_COMPACT === '1') return 'env.DSH_HOT_TRUNCATE_LIVE_COMPACT';
85
+ if (env?.DSH_HOT_TRUNCATE_LIVE_COMPACT === '0') return null;
86
+
87
+ const probe = (name) => {
88
+ try {
89
+ return ctx?.get?.(name) ?? null;
90
+ } catch {
91
+ return null;
92
+ }
93
+ };
94
+ if (probe('compaction') !== null) return 'ctx.compaction 已被另一个压缩引擎注册';
95
+ if (probe('liveCompactPresetGate') !== null) return 'live-compact gate service';
96
+
97
+ try {
98
+ const require = createRequire(import.meta.url);
99
+ for (const name of LIVE_COMPACT_PACKAGES) {
100
+ try {
101
+ require.resolve(name);
102
+ return `已安装 ${name}`;
103
+ } catch {
104
+ // try the next name
105
+ }
106
+ }
107
+ } catch {
108
+ // createRequire itself failed; the profile scan below is independent.
109
+ }
110
+
111
+ try {
112
+ const home = typeof env?.DSH_HOME === 'string' && env.DSH_HOME.trim()
113
+ ? path.resolve(env.DSH_HOME.trim())
114
+ : path.join(os.homedir(), '.dsh');
115
+ const profiles = path.join(home, 'profiles');
116
+ for (const name of fs.readdirSync(profiles)) {
117
+ for (const file of ['package.json', 'cordis.patch.yml', 'cordis.yml']) {
118
+ try {
119
+ const text = fs.readFileSync(path.join(profiles, name, file), 'utf8');
120
+ if (/dsh-live-compact|compaction-spine/.test(text)) return `${name}/${file} 提到 live-compact`;
121
+ } catch {
122
+ // Missing/unreadable file: not a match.
123
+ }
124
+ }
125
+ }
126
+ } catch {
127
+ // No readable profiles directory is the normal test/no-host case.
128
+ }
129
+ return null;
130
+ }
131
+
132
+ // -- module load (top-level await keeps a broken engine from failing import) --
133
+
134
+ let Engine = null;
135
+ let Stock = null;
136
+ let loadError = null;
137
+
138
+ if (process.env.DSH_HOT_TRUNCATE_ENGINE_FAIL !== 'import') {
139
+ try {
140
+ const module = await import('./cut-engine.js');
141
+ Engine = module.default;
142
+ } catch (error) {
143
+ loadError = error instanceof Error ? error : new Error(String(error));
144
+ }
145
+ } else {
146
+ loadError = new Error('hot-truncate: engine import refused by DSH_HOT_TRUNCATE_ENGINE_FAIL');
147
+ }
148
+
149
+ try {
150
+ const module = await import(process.env.DSH_HOT_TRUNCATE_HOST_STOCK || STOCK_PACKAGE);
151
+ Stock = module.BasicCompactionEngine ?? module.default ?? null;
152
+ } catch (error) {
153
+ // Stock may legitimately be absent (a profile that only uses longlive).
154
+ loadError ??= error instanceof Error ? error : new Error(String(error));
155
+ }
156
+
157
+ function installStock(ctx, rawConfig, cause, { claimed = false } = {}) {
158
+ // If a compaction engine was already registered by somebody else (a partly
159
+ // applied bundle, or stock left enabled), never steal or tear it down: this
160
+ // row is optional and the host must keep working.
161
+ let existing = null;
162
+ try {
163
+ existing = ctx?.get?.('compaction') ?? null;
164
+ } catch {
165
+ existing = null;
166
+ }
167
+ if (existing !== null && !claimed) {
168
+ log(ctx, 'warn', `${OUR_NAME}: 已有压缩引擎占据 ctx.compaction,本行不重复注册。${cause ? `原因:${cause}` : ''}`);
169
+ return new Deferred(ctx, null);
170
+ }
171
+ releaseCompaction(ctx);
172
+ if (typeof Stock !== 'function') {
173
+ log(ctx, 'warn', `${OUR_NAME}: 引擎与 stock 压缩都不可用,本会话不接管压缩。${cause ? `原因:${cause}` : ''}`);
174
+ return new Deferred(ctx, null);
175
+ }
176
+ try {
177
+ const engine = new Stock(ctx, stockConfig(rawConfig));
178
+ log(ctx, 'warn', `${OUR_NAME}: 回退 stock 压缩。${cause ? `原因:${cause}` : ''}`);
179
+ return engine;
180
+ } catch (error) {
181
+ releaseCompaction(ctx);
182
+ log(ctx, 'warn', `${OUR_NAME}: stock 压缩构造失败,本会话不接管压缩。原因:${reasonOf(error)}`);
183
+ return new Deferred(ctx, null);
184
+ }
185
+ }
186
+
187
+ /** A plugin that registers nothing; used when taking over would conflict. */
188
+ class Deferred {
189
+ constructor(ctx, message) {
190
+ if (message) log(ctx, 'info', message);
191
+ }
192
+ }
193
+
194
+ export default class HotTruncateEntry {
195
+ // Stock needs llm/tokenMeter/sessions; declare them so the fallback can be
196
+ // constructed on the same context (Cordis treats an undeclared read as a bug).
197
+ static inject = ['llm', 'tokenMeter', 'sessions'];
198
+
199
+ constructor(ctx, config) {
200
+ let options;
201
+ try {
202
+ options = normalizeOptions(config);
203
+ } catch (error) {
204
+ return installStock(ctx, config, `配置无效:${reasonOf(error)}`);
205
+ }
206
+
207
+ const live = detectLiveCompact(ctx, options, process.env);
208
+ if (live !== null) {
209
+ const label = typeof live === 'string' && live.startsWith('ctx.compaction')
210
+ ? `检测到已有压缩引擎(${live})`
211
+ : `检测到 live-compact(${live})`;
212
+ return new Deferred(ctx, `${OUR_NAME}: ${label},热截断让位`);
213
+ }
214
+ if (options.mode === 'off') {
215
+ return installStock(ctx, config, 'mode=off');
216
+ }
217
+ if (typeof Engine !== 'function') {
218
+ return installStock(ctx, config, `引擎未加载:${reasonOf(loadError)}`);
219
+ }
220
+ try {
221
+ return new Engine(ctx, config);
222
+ } catch (error) {
223
+ return installStock(ctx, config, `引擎构造失败:${reasonOf(error)}`, { claimed: true });
224
+ }
225
+ }
226
+ }
227
+
228
+ export { Deferred };
@@ -0,0 +1,230 @@
1
+ // Compaction-aware session analysis.
2
+ //
3
+ // A DSH compaction never deletes anything. It *appends* a `compaction/summary`
4
+ // event plus a checkpoint `user/message` whose `surfaceOp` replaces the shadowed
5
+ // span. The bytes stay in the log; only the model-visible surface shrinks.
6
+ //
7
+ // That gives two numbers every longevity tool has to tell apart:
8
+ // shadowed - how much history the model no longer sees
9
+ // reclaimed - how much shadowed history has actually been deleted from disk
10
+ //
11
+ // A session can be heavily shadowed and still be 20 MB on disk; it can also be
12
+ // small on disk while showing the model its entire history (exactly the state
13
+ // that produced the 2026-10-30 payload overflow). Truncation is both safe and
14
+ // useful only *after* a compaction has shadowed a prefix, which is why health
15
+ // has to report both.
16
+
17
+ import fs from 'node:fs';
18
+ import { parseSession, foldSurface, MESSAGE_TYPES } from './codec.js';
19
+
20
+ /** Group every compaction-owned event by compactionId. */
21
+ function groupCompactions(events) {
22
+ const groups = new Map();
23
+ for (const event of events) {
24
+ const data = event.data ?? {};
25
+ const id = data.compactionId ?? data.source?.compactionId;
26
+ if (typeof id !== 'string' || id.length === 0) continue;
27
+ if (!groups.has(id)) {
28
+ groups.set(id, { id, starts: [], summaries: [], ends: [], checkpoints: [] });
29
+ }
30
+ const group = groups.get(id);
31
+ if (event.type === 'compaction/start') group.starts.push(event);
32
+ else if (event.type === 'compaction/summary') group.summaries.push(event);
33
+ else if (event.type === 'compaction/end') group.ends.push(event);
34
+ else if (data.source?.kind === 'compact-checkpoint') group.checkpoints.push(event);
35
+ }
36
+ return groups;
37
+ }
38
+
39
+ /**
40
+ * A checkpoint's surface span, whichever field names the log used. The codec
41
+ * accepts both `startSeq/endSeq` and `start/end` (codec.js:137, :161), and real
42
+ * logs use the short pair — reading only the long pair made a compressed prefix
43
+ * look like it had never been shadowed (F6).
44
+ */
45
+ function spanOf(event) {
46
+ const op = event?.surfaceOp;
47
+ if (!op || typeof op !== 'object') return null;
48
+ const num = (a, b) => (typeof op[a] === 'number' ? op[a] : typeof op[b] === 'number' ? op[b] : null);
49
+ const start = num('startSeq', 'start');
50
+ const end = num('endSeq', 'end');
51
+ if (start === null || end === null || end < start) return null;
52
+ return { start, end };
53
+ }
54
+
55
+ /** Every stored seq inside an inclusive range, in log order. */
56
+ function seqsInRange(events, start, end) {
57
+ if (typeof start !== 'number' || typeof end !== 'number' || end < start) return [];
58
+ return events
59
+ .filter((event) => typeof event.seq === 'number' && event.seq >= start && event.seq <= end)
60
+ .map((event) => event.seq);
61
+ }
62
+
63
+ /**
64
+ * Count the shadowed seqs that are *still physically in the log on disk*.
65
+ *
66
+ * The point is that "reclaimed" is a claim about the disk, so it has to be read
67
+ * back from the disk. Any failure (missing file, unreadable, unparseable) is
68
+ * reported as unverified — the caller then says `unknown` instead of guessing.
69
+ */
70
+ function countStillOnDisk(filePath, seqs) {
71
+ const wanted = new Set(seqs);
72
+ try {
73
+ const stat = fs.statSync(filePath);
74
+ if (!stat.isFile()) return { verified: false, error: 'NOT_A_FILE' };
75
+ const parsed = parseSession(fs.readFileSync(filePath));
76
+ let stored = 0;
77
+ const present = new Set();
78
+ for (const event of parsed.events) {
79
+ if (!wanted.has(event.seq)) continue;
80
+ stored += 1;
81
+ present.add(event.seq);
82
+ }
83
+ return { verified: true, stored, present, diskEvents: parsed.events.length };
84
+ } catch (error) {
85
+ return { verified: false, error: error?.code ?? error?.message ?? 'READ_FAILED' };
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Describe what the log remembers about compaction.
91
+ *
92
+ * @param parsed - decoded session ({ header, events }).
93
+ * @param options.filePath - the log's path on disk. When given, the analysis
94
+ * re-reads it so "reclaimed" is counted, not inferred. Without it the reclaim
95
+ * state is reported as `unknown`, never as `true`.
96
+ * @returns structurally stable facts, no policy and no thresholds.
97
+ */
98
+ export function analyzeCompaction(parsed, options = {}) {
99
+ const events = parsed.events ?? [];
100
+ // Address events by seq, never by array index: a decoded log is contiguous,
101
+ // but an edited or partially filtered one is not.
102
+ const bySeq = new Map(events.map((event) => [event.seq, event]));
103
+ const groups = groupCompactions(events);
104
+ const surface = foldSurface(events);
105
+ const surfaceSeqs = new Set(surface.map((node) => node.seq));
106
+ const surfaceMessages = surface.filter((node) => MESSAGE_TYPES.has(node.type));
107
+
108
+ const files = [];
109
+ const seen = new Set();
110
+ const fileShadowSeqs = new Map();
111
+ for (const group of groups.values()) {
112
+ const summary = group.summaries[0];
113
+ const checkpoint = group.checkpoints[0];
114
+ const data = summary?.data ?? {};
115
+ // The summary records the shadowed span, but a checkpoint can outlive it
116
+ // (a hand-edited log, or a summary lost to a bad truncation). The
117
+ // checkpoint's own surfaceOp still shadowed that span, so recover the
118
+ // measurement from the range rather than reporting zero.
119
+ const checkpointSpan = spanOf(checkpoint);
120
+ let shadowedSeqs = [];
121
+ let measurementSource = 'none';
122
+ if (Array.isArray(data.shadowedSeqs) && data.shadowedSeqs.length > 0) {
123
+ shadowedSeqs = data.shadowedSeqs;
124
+ measurementSource = 'summary.shadowedSeqs';
125
+ } else if (checkpointSpan) {
126
+ shadowedSeqs = seqsInRange(events, checkpointSpan.start, checkpointSpan.end);
127
+ measurementSource = 'checkpoint.surfaceOp';
128
+ } else if (data.shadowedRange && typeof data.shadowedRange.start === 'number'
129
+ && typeof data.shadowedRange.end === 'number') {
130
+ shadowedSeqs = seqsInRange(events, data.shadowedRange.start, data.shadowedRange.end);
131
+ measurementSource = 'summary.shadowedRange';
132
+ }
133
+ fileShadowSeqs.set(group.id, shadowedSeqs);
134
+ for (const seq of shadowedSeqs) seen.add(seq);
135
+ files.push({
136
+ compactionId: group.id,
137
+ startSeq: group.starts[0]?.seq ?? null,
138
+ summarySeq: summary?.seq ?? null,
139
+ checkpointSeq: checkpoint?.seq ?? null,
140
+ closed: group.ends.length > 0,
141
+ shadowedRange: data.shadowedRange ?? checkpointSpan,
142
+ // How the count was obtained; 'none' means it could not be measured.
143
+ shadowedSeqSource: measurementSource,
144
+ shadowedEvents: shadowedSeqs.length,
145
+ shadowedTokens: data.shadowedTokenCount ?? null,
146
+ summaryChars: typeof data.summary?.[0]?.text === 'string' ? data.summary[0].text.length : 0,
147
+ checkpointOnSurface: checkpoint ? surfaceSeqs.has(checkpoint.seq) : false,
148
+ // A checkpoint with no summary still shadows through its surfaceOp, but
149
+ // its span and token count are no longer recorded anywhere.
150
+ metadataIncomplete: Boolean(checkpoint && !summary),
151
+ // True when the shadowed events are still physically present, i.e. the
152
+ // compaction saved context but not disk. Those are the reclaimable bytes.
153
+ shadowedStillStored: shadowedSeqs.filter((seq) => bySeq.has(seq)).length,
154
+ // Filled in from the disk re-read below; null when disk was not read.
155
+ shadowedStillStoredOnDisk: null,
156
+ checkpointChars: checkpoint
157
+ ? JSON.stringify(checkpoint.data?.content ?? '').length
158
+ : 0,
159
+ });
160
+ }
161
+
162
+ const disk = typeof options.filePath === 'string' && options.filePath.length > 0
163
+ ? countStillOnDisk(options.filePath, [...seen])
164
+ : { verified: false, error: 'NO_FILE_PATH' };
165
+ if (disk.verified) {
166
+ for (const file of files) {
167
+ const seqs = fileShadowSeqs.get(file.compactionId) ?? [];
168
+ file.shadowedStillStoredOnDisk = seqs.filter((seq) => disk.present.has(seq)).length;
169
+ }
170
+ }
171
+
172
+ const stored = events.length;
173
+ const shadowedStored = [...seen].filter((seq) => bySeq.has(seq)).length;
174
+ return {
175
+ compactionFiles: files.length,
176
+ closedCompactions: files.filter((f) => f.closed).length,
177
+ checkpointsOnSurface: files.filter((f) => f.checkpointOnSurface).length,
178
+ // History the model can no longer reach, in events and stored events.
179
+ shadowedEvents: seen.size,
180
+ shadowedEventsStillStored: shadowedStored,
181
+ // A disk read is required before "reclaimed" may be true: the in-memory
182
+ // event list cannot prove what the file no longer contains.
183
+ diskVerified: disk.verified,
184
+ diskError: disk.verified ? null : (disk.error ?? 'UNKNOWN'),
185
+ shadowedEventsStillStoredOnDisk: disk.verified ? disk.stored : null,
186
+ reclaimed: disk.verified ? disk.stored === 0 : 'unknown',
187
+ shadowedTokens: files.reduce((sum, f) => sum + (f.shadowedTokens ?? 0), 0),
188
+ visibleMessages: surfaceMessages.length,
189
+ visibleFirstSeq: surfaceMessages[0]?.seq ?? null,
190
+ storedEvents: stored,
191
+ files,
192
+ };
193
+ }
194
+
195
+ /**
196
+ * One-line verdict a tool can hand to a model or a person.
197
+ *
198
+ * @param analysis - value from analyzeCompaction.
199
+ * @returns short sentence naming the actionable state.
200
+ */
201
+ export function describeCompaction(analysis) {
202
+ if (analysis.compactionFiles === 0) {
203
+ return 'never compacted: the model still sees the whole history, so truncation can only delete visible conversation. Run /compact first.';
204
+ }
205
+ if (analysis.checkpointsOnSurface === 0) {
206
+ return 'compaction records exist but no checkpoint is on the surface: the model sees the whole history. Run /compact again.';
207
+ }
208
+ if (analysis.files.some((file) => file.metadataIncomplete)) {
209
+ return 'compaction records are incomplete: a checkpoint survived without its summary, so the shadowed span can no longer be measured. Run /compact again to rewrite it.';
210
+ }
211
+ const visible = `${analysis.visibleMessages} messages remain visible`;
212
+ // "Already gone from disk" is an assertion about the filesystem, so it needs a
213
+ // real count. No count ⇒ say unknown instead of guessing (F6).
214
+ if (analysis.shadowedEvents === 0) {
215
+ return 'compacted: the shadowed span could not be measured (no shadowedSeqs and no usable checkpoint range), '
216
+ + `so reclaim status is unknown; ${visible}.`;
217
+ }
218
+ if (analysis.reclaimed !== true && analysis.reclaimed !== false) {
219
+ return `compacted: ${analysis.shadowedEvents} history events are shadowed `
220
+ + `(${analysis.shadowedEventsStillStored} still stored), reclaim status unknown — `
221
+ + `the log was not re-read from disk; ${visible}.`;
222
+ }
223
+ if (analysis.reclaimed === true) {
224
+ return 'compacted and reclaimed: shadowed history is already gone from disk '
225
+ + `(counted on disk: 0 of ${analysis.shadowedEvents} shadowed events remain); ${visible}.`;
226
+ }
227
+ const stored = analysis.shadowedEventsStillStoredOnDisk ?? analysis.shadowedEventsStillStored;
228
+ return `compacted: ${analysis.shadowedEvents} history events are shadowed (${stored} still stored and reclaimable), `
229
+ + `${visible}.`;
230
+ }