@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,786 @@
1
+ // activity/store.js — the activity board's file layer (1.6.1).
2
+ //
3
+ // One append-only JSONL board for every session:
4
+ // <memoryRoot>/.longlive/board/activity.jsonl
5
+ // <memoryRoot>/.longlive/board/activity-YYYYMM.jsonl (overflow archive)
6
+ //
7
+ // Every append is a read-modify-write under a cross-process lock, then an
8
+ // atomic tmp -> fsync -> read-back -> rename. That combination is what makes
9
+ // two sessions writing at the same time produce unique, contiguous seq values
10
+ // instead of a lost update. The recent window is bounded (500 rows by default);
11
+ // old rows move to the monthly archive in the same transition so the board
12
+ // never grows without limit.
13
+ //
14
+ // The store never throws on an IO failure: it returns {ok:false, code}. The
15
+ // caller (index.js) is required to swallow that and let the turn continue.
16
+
17
+ import crypto from 'node:crypto';
18
+ import fs from 'node:fs';
19
+ import path from 'node:path';
20
+
21
+ import { privacyScan as defaultPrivacyScan } from '../recall/privacy.mjs';
22
+ import {
23
+ ACTIVITY_KINDS,
24
+ ACTIVITY_TEXT_MAX,
25
+ ACTIVITY_THINKING_TEXT_MAX,
26
+ DEDUPE_WINDOW,
27
+ DISTILL_MIN_COUNT,
28
+ DISTILL_TOTAL_COUNT,
29
+ SIMILARITY_THRESHOLD,
30
+ charLength,
31
+ clip,
32
+ distillActivityText,
33
+ normalizeKey,
34
+ normalizeText,
35
+ oneLine,
36
+ similarity,
37
+ } from './model.js';
38
+
39
+ export const ACTIVITY_SCHEMA_VERSION = 1;
40
+ export const ACTIVITY_BOARD_DIR = 'board';
41
+ export const ACTIVITY_FILE_NAME = 'activity.jsonl';
42
+ export const ACTIVITY_RECENT_MAX = 500;
43
+ /**
44
+ * 1.8.8 M3: the live window is time-based first. Rows whose effective time
45
+ * (`last_at ?? at`) is older than this move to the monthly archive instead of
46
+ * being kept forever; nothing is deleted. A missing/invalid config means 24h.
47
+ */
48
+ export const ACTIVITY_RETAIN_HOURS = 24;
49
+ /**
50
+ * 1.8.8 M3: hard row cap for the live window (the guard, not the rule). A
51
+ * fan-out storm can produce thousands of rows inside 24h; above this the
52
+ * oldest rows are archived first. Explicit `recentMax` still wins for tests.
53
+ */
54
+ export const ACTIVITY_RECENT_MAX_ROWS = 3200;
55
+ export const ACTIVITY_LOCK_STALE_MS = 10000;
56
+ export const ACTIVITY_LOCK_TIMEOUT_MS = 2000;
57
+ export const ACTIVITY_SESSION_RE = /^[a-z0-9][a-z0-9._-]{0,127}$/;
58
+ /** Monotonic seq high-water mark: survives board deletion/compaction. */
59
+ export const ACTIVITY_SEQ_HIGH_WATER_FILE = '.activity.seq';
60
+ /** Written when the store detects the board was reset (deleted/emptied). */
61
+ export const ACTIVITY_RESET_MARKER_FILE = 'stream.reset.json';
62
+
63
+ const ARCHIVE_RE = /^activity-(\d{6})\.jsonl$/;
64
+
65
+ export function activityBoardDir(memoryRoot) {
66
+ return path.join(String(memoryRoot ?? ''), '.longlive', ACTIVITY_BOARD_DIR);
67
+ }
68
+
69
+ export function activityBoardFile(memoryRoot) {
70
+ return path.join(activityBoardDir(memoryRoot), ACTIVITY_FILE_NAME);
71
+ }
72
+
73
+ /** `<board>/.activity.seq` — the seq high-water sidecar (RE-R15.5). */
74
+ export function activitySeqHighWaterFile(memoryRoot) {
75
+ return path.join(activityBoardDir(memoryRoot), ACTIVITY_SEQ_HIGH_WATER_FILE);
76
+ }
77
+
78
+ /** `<board>/stream.reset.json` — last detected board-reset evidence (RE-R15.5). */
79
+ export function activityResetMarkerFile(memoryRoot) {
80
+ return path.join(activityBoardDir(memoryRoot), ACTIVITY_RESET_MARKER_FILE);
81
+ }
82
+
83
+ export function activityArchiveFile(memoryRoot, monthKey) {
84
+ return path.join(activityBoardDir(memoryRoot), `activity-${monthKey}.jsonl`);
85
+ }
86
+
87
+ export function monthKeyFor(value) {
88
+ const date = value instanceof Date ? value : new Date(value ?? Date.now());
89
+ if (!Number.isFinite(date.getTime())) return '000000';
90
+ const year = date.getFullYear();
91
+ const month = String(date.getMonth() + 1).padStart(2, '0');
92
+ return `${year}${month}`;
93
+ }
94
+
95
+ export function sha256Hex(value) {
96
+ return crypto.createHash('sha256').update(String(value ?? ''), 'utf8').digest('hex');
97
+ }
98
+
99
+ function countOf(entry) {
100
+ const count = Number(entry?.count);
101
+ return Number.isInteger(count) && count > 0 ? count : 1;
102
+ }
103
+
104
+ function isObject(value) {
105
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
106
+ }
107
+
108
+ /** Parse JSONL defensively; bad lines are counted, never thrown. */
109
+ export function parseActivityJsonl(text) {
110
+ const entries = [];
111
+ let bad = 0;
112
+ for (const line of String(text ?? '').replace(/^\uFEFF/, '').split(/\r?\n/)) {
113
+ if (line.trim() === '') continue;
114
+ let row = null;
115
+ try {
116
+ row = JSON.parse(line);
117
+ } catch {
118
+ bad += 1;
119
+ continue;
120
+ }
121
+ if (!isObject(row) || !Number.isInteger(row.seq) || typeof row.text !== 'string' || typeof row.sessionId !== 'string') {
122
+ bad += 1;
123
+ continue;
124
+ }
125
+ entries.push(row);
126
+ }
127
+ entries.sort((left, right) => left.seq - right.seq);
128
+ return { entries, bad };
129
+ }
130
+
131
+ export function serializeActivityEntries(entries) {
132
+ return entries.map((entry) => JSON.stringify(entry)).join('\n') + (entries.length > 0 ? '\n' : '');
133
+ }
134
+
135
+ function sleepSync(ms) {
136
+ try {
137
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
138
+ } catch {
139
+ /* fall through: a busy loop is still bounded by the deadline */
140
+ }
141
+ }
142
+
143
+ function writeTextDurable(file, text) {
144
+ const dir = path.dirname(file);
145
+ fs.mkdirSync(dir, { recursive: true });
146
+ const tmp = path.join(dir, `.${path.basename(file)}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`);
147
+ const fd = fs.openSync(tmp, 'w');
148
+ try {
149
+ fs.writeFileSync(fd, text, 'utf8');
150
+ try {
151
+ fs.fsyncSync(fd);
152
+ } catch {
153
+ /* fsync is best effort on some filesystems */
154
+ }
155
+ } finally {
156
+ try {
157
+ fs.closeSync(fd);
158
+ } catch {
159
+ /* ignore */
160
+ }
161
+ }
162
+ let lastError = null;
163
+ for (let attempt = 0; attempt < 5; attempt += 1) {
164
+ try {
165
+ const readBack = fs.readFileSync(tmp, 'utf8');
166
+ if (readBack !== text) throw new Error('activity write read-back mismatch');
167
+ fs.renameSync(tmp, file);
168
+ return { ok: true };
169
+ } catch (error) {
170
+ lastError = error;
171
+ if (attempt < 4) sleepSync(10 * (attempt + 1));
172
+ }
173
+ }
174
+ try {
175
+ fs.rmSync(tmp, { force: true });
176
+ } catch {
177
+ /* ignore */
178
+ }
179
+ return { ok: false, error: lastError?.code ?? lastError?.message ?? 'E_WRITE' };
180
+ }
181
+
182
+ /** Atomic JSON write used by the per-session lastSeenSeq state. */
183
+ export function writeJsonAtomic(file, value) {
184
+ const text = `${JSON.stringify(value, null, 2)}\n`;
185
+ try {
186
+ const written = writeTextDurable(file, text);
187
+ return written.ok ? { ok: true, file, bytes: Buffer.byteLength(text, 'utf8') } : written;
188
+ } catch (error) {
189
+ return { ok: false, file, error: error?.code ?? error?.message ?? 'E_WRITE' };
190
+ }
191
+ }
192
+
193
+ export function readJsonFile(file) {
194
+ try {
195
+ return { ok: true, value: JSON.parse(fs.readFileSync(file, 'utf8')) };
196
+ } catch (error) {
197
+ return { ok: false, error: error?.code ?? 'E_READ' };
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Write/read the whole recent board under `<board>/.activity.lock`. Returns
203
+ * `{ok:false,code:'E_LOCK_TIMEOUT'}` instead of blocking a turn forever.
204
+ */
205
+ function withLock(memoryRoot, fn) {
206
+ const dir = activityBoardDir(memoryRoot);
207
+ try {
208
+ fs.mkdirSync(dir, { recursive: true });
209
+ } catch (error) {
210
+ return { ok: false, code: 'E_MKDIR', message: error?.message ?? String(error) };
211
+ }
212
+ const lockFile = path.join(dir, '.activity.lock');
213
+ const started = Date.now();
214
+ let fd = null;
215
+ while (fd === null) {
216
+ try {
217
+ fd = fs.openSync(lockFile, 'wx');
218
+ } catch (error) {
219
+ if (error?.code !== 'EEXIST') {
220
+ return { ok: false, code: 'E_LOCK', message: error?.code ?? String(error) };
221
+ }
222
+ try {
223
+ const stat = fs.statSync(lockFile);
224
+ if (Date.now() - stat.mtimeMs > ACTIVITY_LOCK_STALE_MS) {
225
+ fs.rmSync(lockFile, { force: true });
226
+ continue;
227
+ }
228
+ } catch {
229
+ /* the other writer may have released it between open and stat */
230
+ }
231
+ if (Date.now() - started > ACTIVITY_LOCK_TIMEOUT_MS) {
232
+ return { ok: false, code: 'E_LOCK_TIMEOUT' };
233
+ }
234
+ sleepSync(10);
235
+ }
236
+ }
237
+ try {
238
+ try {
239
+ fs.writeSync(fd, `${process.pid} ${Date.now()}\n`);
240
+ } catch {
241
+ /* the lock file's existence is what matters */
242
+ }
243
+ return fn();
244
+ } finally {
245
+ try {
246
+ fs.closeSync(fd);
247
+ } catch {
248
+ /* ignore */
249
+ }
250
+ try {
251
+ fs.rmSync(lockFile, { force: true });
252
+ } catch {
253
+ /* the stale lock expires on its own */
254
+ }
255
+ }
256
+ }
257
+
258
+ function readEntries(memoryRoot) {
259
+ const file = activityBoardFile(memoryRoot);
260
+ let text = '';
261
+ try {
262
+ text = fs.readFileSync(file, 'utf8');
263
+ } catch (error) {
264
+ if (error?.code === 'ENOENT') return { ok: true, entries: [], bad: 0, exists: false };
265
+ return { ok: false, code: error?.code ?? 'E_READ', entries: [], bad: 0, exists: false };
266
+ }
267
+ const parsed = parseActivityJsonl(text);
268
+ return { ok: true, entries: parsed.entries, bad: parsed.bad, exists: true };
269
+ }
270
+
271
+ function archivedMaxSeq(memoryRoot) {
272
+ let names = [];
273
+ try {
274
+ names = fs.readdirSync(activityBoardDir(memoryRoot));
275
+ } catch {
276
+ return 0;
277
+ }
278
+ const archives = names.filter((name) => ARCHIVE_RE.test(name)).sort().reverse();
279
+ for (const name of archives) {
280
+ const file = path.join(activityBoardDir(memoryRoot), name);
281
+ try {
282
+ const stat = fs.statSync(file);
283
+ const readBytes = Math.min(stat.size, 128 * 1024);
284
+ const fd = fs.openSync(file, 'r');
285
+ const buffer = Buffer.alloc(readBytes);
286
+ try {
287
+ fs.readSync(fd, buffer, 0, readBytes, stat.size - readBytes);
288
+ } finally {
289
+ fs.closeSync(fd);
290
+ }
291
+ let text = buffer.toString('utf8');
292
+ if (readBytes < stat.size) text = text.slice(text.indexOf('\n') + 1);
293
+ const lines = text.split(/\r?\n/).filter((line) => line.trim() !== '');
294
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
295
+ try {
296
+ const row = JSON.parse(lines[index]);
297
+ if (Number.isInteger(row?.seq)) return row.seq;
298
+ } catch {
299
+ /* keep scanning backwards */
300
+ }
301
+ }
302
+ } catch {
303
+ /* try the previous archive month */
304
+ }
305
+ }
306
+ return 0;
307
+ }
308
+
309
+ function nextSeq(entries, memoryRoot, floorSeq = 0) {
310
+ let max = Number.isInteger(floorSeq) && floorSeq > 0 ? floorSeq : 0;
311
+ for (const entry of entries) {
312
+ if (Number.isInteger(entry.seq) && entry.seq > max) max = entry.seq;
313
+ }
314
+ if (max === 0) max = archivedMaxSeq(memoryRoot);
315
+ return max + 1;
316
+ }
317
+
318
+ /** Read the seq high-water sidecar; 0 when absent/corrupt (best effort). */
319
+ export function readSeqHighWater(memoryRoot) {
320
+ const read = readJsonFile(activitySeqHighWaterFile(memoryRoot));
321
+ const value = read.ok ? read.value : null;
322
+ return Number.isInteger(value?.seq) && value.seq > 0 ? value.seq : 0;
323
+ }
324
+
325
+ function persistSeqHighWater(memoryRoot, seq, at) {
326
+ const current = readSeqHighWater(memoryRoot);
327
+ if (seq <= current) return;
328
+ try {
329
+ writeJsonAtomic(activitySeqHighWaterFile(memoryRoot), { v: 1, seq, updatedAt: at });
330
+ } catch {
331
+ /* the board remains correct; only the reset protection degrades */
332
+ }
333
+ }
334
+
335
+ function writeResetMarker(memoryRoot, marker) {
336
+ try {
337
+ writeJsonAtomic(activityResetMarkerFile(memoryRoot), marker);
338
+ } catch {
339
+ /* diagnostics only; the high-water sidecar is what prevents the stranding */
340
+ }
341
+ }
342
+
343
+ /**
344
+ * Pick the row a new activity should merge into. Window = the last 10 live rows
345
+ * of this session; a distilled phase row is not a merge target (otherwise its
346
+ * count could never grow into a new phase). Similarity is checked even when the
347
+ * key differs, matching the spec's "key 相同或文本相似度≥0.8".
348
+ */
349
+ export function selectDedupeTarget(entries, candidate, options = {}) {
350
+ const windowSize = Number.isInteger(options.window) ? options.window : DEDUPE_WINDOW;
351
+ const threshold = Number.isFinite(options.threshold) ? options.threshold : SIMILARITY_THRESHOLD;
352
+ const sessionId = String(candidate?.sessionId ?? '');
353
+ const key = normalizeKey(candidate?.key);
354
+ const text = oneLine(candidate?.text);
355
+ const candidateKind = ACTIVITY_KINDS.includes(candidate?.kind) ? candidate.kind : 'doing';
356
+ const thinking = candidateKind === 'thinking';
357
+ const rows = (Array.isArray(entries) ? entries : []).filter(
358
+ (entry) => entry && entry.sessionId === sessionId && entry.archived !== true,
359
+ );
360
+ const windowRows = rows.slice(-Math.max(1, windowSize));
361
+ let best = null;
362
+ for (const row of windowRows) {
363
+ // 1.8.0: thinking summaries and normal activity rows never merge into each
364
+ // other (different kind = different panel section and different cursors).
365
+ if ((row.kind === 'thinking') !== thinking) continue;
366
+ if (normalizeKey(row.key) === key) return { row, reason: 'key', score: 1 };
367
+ const score = similarity(row.text, text);
368
+ if (score >= threshold && (best === null || score > best.score)) best = { row, reason: 'similarity', score };
369
+ }
370
+ return best;
371
+ }
372
+
373
+ /**
374
+ * Distillation plan for one session+key. Trigger: the newest live row with
375
+ * that key was seen ≥3 times (count), or the key's active rows add up to ≥10.
376
+ * A lone phase row is never re-distilled (it is already the compressed form).
377
+ */
378
+ export function planDistillation(entries, options = {}) {
379
+ const sessionId = String(options.sessionId ?? '');
380
+ const key = normalizeKey(options.key);
381
+ const active = (Array.isArray(entries) ? entries : []).filter(
382
+ (entry) => entry
383
+ && entry.sessionId === sessionId
384
+ && entry.archived !== true
385
+ && normalizeKey(entry.key) === key,
386
+ );
387
+ const normal = active.filter((entry) => entry.phase !== true);
388
+ if (normal.length === 0) return null;
389
+ const total = active.reduce((sum, entry) => sum + countOf(entry), 0);
390
+ const newestNormalCount = Math.max(...normal.map(countOf));
391
+ if (newestNormalCount < DISTILL_MIN_COUNT && total < DISTILL_TOTAL_COUNT) return null;
392
+ const ordered = [...active].sort((left, right) => left.seq - right.seq);
393
+ const last = ordered[ordered.length - 1];
394
+ const kind = last.kind === 'blocked' || last.kind === 'done' ? last.kind : 'finding';
395
+ const detail = last.last_text ?? last.text;
396
+ const summary = {
397
+ schemaVersion: ACTIVITY_SCHEMA_VERSION,
398
+ seq: 0, // filled by append after nextSeq()
399
+ sessionId,
400
+ at: options.at ?? new Date().toISOString(),
401
+ last_at: options.at ?? new Date().toISOString(),
402
+ kind,
403
+ text: distillActivityText(key, total, detail),
404
+ last_text: clip(oneLine(detail), ACTIVITY_TEXT_MAX),
405
+ key,
406
+ norm: sha256Hex(normalizeText(detail)).slice(0, 16),
407
+ dupOf: null,
408
+ count: total,
409
+ phase: true,
410
+ };
411
+ return { rows: active, summary };
412
+ }
413
+
414
+ /**
415
+ * A row's effective activity time: `last_at ?? at`, in ms. A merged/refreshed
416
+ * row keeps its original `at` but moves `last_at` forward, so `last_at` is what
417
+ * says "this row is still active". Returns null for an unparseable timestamp.
418
+ */
419
+ function activityRowTimeMs(row) {
420
+ const raw = row && typeof row === 'object' ? (row.last_at ?? row.at) : null;
421
+ const parsed = Date.parse(String(raw ?? ''));
422
+ return Number.isFinite(parsed) ? parsed : null;
423
+ }
424
+
425
+ /**
426
+ * 1.8.8 M3: decide which board rows stay in the live window.
427
+ *
428
+ * Two rules, applied in this order (time first, then the row cap):
429
+ * 1. time: keep rows whose effective time (`last_at ?? at`) is within
430
+ * `retainHours` of `nowMs`. Rows older than that leave the live board.
431
+ * 2. cap: if the survivors still exceed `recentMax`, keep the newest
432
+ * `recentMax` by `seq` (a seq bump is what marks a refreshed row as
433
+ * newly active).
434
+ *
435
+ * `last_at` first is deliberate: a refreshed row keeps its original `at` but
436
+ * gets a new `last_at`, so a rule keyed on `at` alone would archive the
437
+ * just-refreshed row and a sibling's seq-only cursor would stop seeing the
438
+ * latest action (the R1.5 contract).
439
+ *
440
+ * Rows whose timestamp cannot be parsed are kept (never drop data on
441
+ * ambiguity); they are still subject to the row cap.
442
+ *
443
+ * Pure: no I/O. Returns `{ entries, dropped }`; `entries` keeps input order.
444
+ */
445
+ export function trimActivityWindow(entries, options = {}) {
446
+ const list = Array.isArray(entries) ? entries : [];
447
+ const nowMs = Number.isFinite(options.nowMs) ? options.nowMs : Date.now();
448
+ const retainHours = Number.isFinite(options.retainHours) && options.retainHours > 0
449
+ ? options.retainHours
450
+ : ACTIVITY_RETAIN_HOURS;
451
+ const recentMax = Number.isInteger(options.recentMax) && options.recentMax > 0
452
+ ? options.recentMax
453
+ : ACTIVITY_RECENT_MAX_ROWS;
454
+ const cutoff = nowMs - retainHours * 3600000;
455
+ const kept = [];
456
+ const dropped = [];
457
+ for (const row of list) {
458
+ const time = activityRowTimeMs(row);
459
+ if (time !== null && time < cutoff) dropped.push(row);
460
+ else kept.push(row);
461
+ }
462
+ if (kept.length <= recentMax) return { entries: kept, dropped };
463
+ // Recency is seq here (as in 1.6.8): the physical array order is NOT trusted,
464
+ // because a board that grew past the cap may still hold the just-refreshed row
465
+ // at its old position; slicing by position would archive it.
466
+ const ordered = [...kept].sort((left, right) => (left?.seq ?? 0) - (right?.seq ?? 0));
467
+ const capDrop = ordered.slice(0, kept.length - recentMax);
468
+ const capDropSet = new Set(capDrop);
469
+ return {
470
+ entries: kept.filter((row) => !capDropSet.has(row)),
471
+ dropped: [...dropped, ...capDrop],
472
+ };
473
+ }
474
+
475
+ /**
476
+ * Apply the live window and archive the dropped rows first. An archive append
477
+ * failure keeps the whole board unchanged (a long board is better than data
478
+ * loss); the monthly archive is append-only and never deletes.
479
+ */
480
+ function applyActivityWindow(memoryRoot, entries, options = {}) {
481
+ const trimmed = trimActivityWindow(entries, options);
482
+ if (trimmed.dropped.length === 0) return { entries, dropped: 0 };
483
+ const groups = new Map();
484
+ for (const row of trimmed.dropped) {
485
+ const month = monthKeyFor(row.at);
486
+ if (!groups.has(month)) groups.set(month, []);
487
+ groups.get(month).push(row);
488
+ }
489
+ try {
490
+ fs.mkdirSync(activityBoardDir(memoryRoot), { recursive: true });
491
+ for (const [month, rows] of groups) {
492
+ fs.appendFileSync(activityArchiveFile(memoryRoot, month), serializeActivityEntries(rows), 'utf8');
493
+ }
494
+ } catch {
495
+ return { entries, dropped: 0 };
496
+ }
497
+ return { entries: trimmed.entries, dropped: trimmed.dropped.length };
498
+ }
499
+
500
+ /**
501
+ * Read-only live-window facts for the panel/status surface (M3 item 4):
502
+ * coverage hours, live rows, sessions active inside the window, and the
503
+ * monthly archive size. Never throws; absent board/archive is an empty state.
504
+ */
505
+ export function summarizeActivityWindow(memoryRoot, options = {}) {
506
+ const retainHours = Number.isFinite(options.retainHours) && options.retainHours > 0
507
+ ? options.retainHours
508
+ : ACTIVITY_RETAIN_HOURS;
509
+ const nowMs = Number.isFinite(options.nowMs) ? options.nowMs : Date.now();
510
+ const cutoff = nowMs - retainHours * 3600000;
511
+ const read = readEntries(memoryRoot);
512
+ const entries = read.ok ? read.entries : [];
513
+ const sessions = new Set();
514
+ let oldestMs = null;
515
+ let newestMs = null;
516
+ for (const row of entries) {
517
+ const time = activityRowTimeMs(row);
518
+ if (time === null) continue;
519
+ if (time >= cutoff && typeof row.sessionId === 'string') sessions.add(row.sessionId);
520
+ if (oldestMs === null || time < oldestMs) oldestMs = time;
521
+ if (newestMs === null || time > newestMs) newestMs = time;
522
+ }
523
+ let archivedBytes = 0;
524
+ let archivedFiles = 0;
525
+ try {
526
+ const dir = activityBoardDir(memoryRoot);
527
+ for (const name of fs.readdirSync(dir)) {
528
+ if (!ARCHIVE_RE.test(name)) continue;
529
+ try {
530
+ archivedBytes += fs.statSync(path.join(dir, name)).size;
531
+ archivedFiles += 1;
532
+ } catch {
533
+ /* a file that vanished between readdir and stat is just not counted */
534
+ }
535
+ }
536
+ } catch {
537
+ /* absent board dir = empty archive */
538
+ }
539
+ return {
540
+ retainHours,
541
+ rows: entries.length,
542
+ bad: read.ok ? read.bad : 0,
543
+ activeSessions24h: sessions.size,
544
+ oldestAt: oldestMs === null ? null : new Date(oldestMs).toISOString(),
545
+ newestAt: newestMs === null ? null : new Date(newestMs).toISOString(),
546
+ archivedFiles,
547
+ archivedBytes,
548
+ };
549
+ }
550
+
551
+ /**
552
+ * Create the activity store.
553
+ *
554
+ * options: memoryRoot (required), now(), privacyScan(text), and the 1.8.8 live
555
+ * window knobs `retainHours` (default 24) / `recentMaxRows` (default 3200; the
556
+ * legacy explicit `recentMax` still wins so 1.6.8 callers and tests are
557
+ * unchanged).
558
+ * append() is synchronous and serialized across processes by the lock.
559
+ */
560
+ export function createActivityStore(options = {}) {
561
+ const memoryRoot = typeof options.memoryRoot === 'string' && options.memoryRoot.trim() !== ''
562
+ ? path.resolve(options.memoryRoot)
563
+ : null;
564
+ const now = typeof options.now === 'function' ? options.now : () => new Date();
565
+ const privacyScan = typeof options.privacyScan === 'function' ? options.privacyScan : defaultPrivacyScan;
566
+ const retainHours = Number.isFinite(options.retainHours) && options.retainHours > 0
567
+ ? options.retainHours
568
+ : ACTIVITY_RETAIN_HOURS;
569
+ // Row cap precedence: an explicit `recentMax` (tests, 1.6.8 callers) wins,
570
+ // then the M3 `recentMaxRows` config, then the 1.8.8 default guard.
571
+ const recentMax = Number.isInteger(options.recentMax) && options.recentMax > 0
572
+ ? options.recentMax
573
+ : (Number.isInteger(options.recentMaxRows) && options.recentMaxRows > 0
574
+ ? options.recentMaxRows
575
+ : ACTIVITY_RECENT_MAX_ROWS);
576
+
577
+ function read() {
578
+ if (!memoryRoot) return { ok: false, code: 'E_NO_ROOT', entries: [], bad: 0, exists: false };
579
+ return readEntries(memoryRoot);
580
+ }
581
+
582
+ /**
583
+ * Append or merge one activity row.
584
+ *
585
+ * options.touchSeq: a merge still carries new information (a tool call moved
586
+ * on, a turn concluded). The default merge keeps seq stable — that is the
587
+ * rc.1 dedupe contract and the injection cursor was seq-only, which meant a
588
+ * sibling session saw the first row of a long turn and then nothing. With
589
+ * `touchSeq` the merged row takes `nextSeq()`, so every real refresh is
590
+ * strictly newer for `seq > lastSeenSeq`.
591
+ * options.refreshText: replace the whole row text with the newest occurrence
592
+ * (event-level rows show the current action) instead of the default 「首条
593
+ * 正文保留」 rule.
594
+ *
595
+ * Returns {ok, action:'appended'|'merged'|'refreshed'|'distilled', entry, seq,
596
+ * mergedSeq, seqBumped, archivedCount, trimmedCount, streamReset, code}.
597
+ * `archivedCount` counts rows folded by distillation; `trimmedCount` counts
598
+ * rows that left the live window for the monthly archive (time window first,
599
+ * then the recentMaxRows guard). Neither ever deletes data.
600
+ *
601
+ * Sequel monotonicity (RE-R15.5): every successful write persists the max seq
602
+ * seen to `<board>/.activity.seq`, and new rows start above max(board, archive,
603
+ * high-water). Deleting/emptying the board therefore does NOT restart seq at 1,
604
+ * so a sibling's high `lastSeenSeq` cursor keeps working. If a reset is detected
605
+ * (board missing/empty but a previous stream is known), a `stream.reset.json`
606
+ * marker is written for diagnostics / consumer fallback.
607
+ */
608
+ function append(input = {}, options = {}) {
609
+ if (!memoryRoot) return { ok: false, code: 'E_NO_ROOT' };
610
+ const touchSeq = options.touchSeq === true;
611
+ const refreshText = options.refreshText === true;
612
+ const sessionId = String(input.sessionId ?? '').trim().toLowerCase();
613
+ if (!ACTIVITY_SESSION_RE.test(sessionId)) return { ok: false, code: 'E_SESSION_ID' };
614
+ const kind = ACTIVITY_KINDS.includes(input.kind) ? input.kind : 'doing';
615
+ const textMax = kind === 'thinking' ? ACTIVITY_THINKING_TEXT_MAX : ACTIVITY_TEXT_MAX;
616
+ const text = clip(oneLine(input.text), textMax);
617
+ if (text === '') return { ok: false, code: 'E_EMPTY_TEXT' };
618
+ const key = normalizeKey(input.key);
619
+ const atDate = new Date(input.at ?? now());
620
+ const at = Number.isFinite(atDate.getTime()) ? atDate.toISOString() : new Date().toISOString();
621
+
622
+ // Reuse the privacy gate before anything touches disk: a local_only verdict
623
+ // drops the row (board data is shared across sessions).
624
+ try {
625
+ const verdict = privacyScan(`${text}\n${key}`);
626
+ if (!verdict || verdict.verdict === 'local_only') {
627
+ return { ok: false, code: 'E_PRIVACY', skipped: true };
628
+ }
629
+ } catch {
630
+ return { ok: false, code: 'E_PRIVACY', skipped: true };
631
+ }
632
+
633
+ return withLock(memoryRoot, () => {
634
+ const current = readEntries(memoryRoot);
635
+ if (!current.ok) return { ok: false, code: current.code };
636
+ let entries = current.entries;
637
+ // Seq floor: never go below the persisted high-water mark (board deletion
638
+ // or compaction must not rewind seq for sibling cursors).
639
+ const highWater = readSeqHighWater(memoryRoot);
640
+ const seqFor = (list) => nextSeq(list, memoryRoot, highWater);
641
+ let streamReset = null;
642
+ if (entries.length === 0) {
643
+ const archivedMax = archivedMaxSeq(memoryRoot);
644
+ const previous = Math.max(highWater, archivedMax);
645
+ if (previous > 0) {
646
+ streamReset = {
647
+ v: 1,
648
+ at,
649
+ reason: current.exists === false ? 'board-missing' : 'board-empty',
650
+ previousHighWater: highWater,
651
+ archivedMax,
652
+ };
653
+ }
654
+ }
655
+ const target = selectDedupeTarget(entries, { sessionId, key, text, kind });
656
+ let action = 'appended';
657
+ let entry = null;
658
+ let mergedSeq = null;
659
+ let seqBumped = false;
660
+ let archivedCount = 0;
661
+
662
+ if (target) {
663
+ const row = target.row;
664
+ const previousSeq = row.seq;
665
+ row.count = countOf(row) + 1;
666
+ row.last_at = at;
667
+ // The first text is kept for a normal row (spec). A phase row is the
668
+ // generated compression, so it is refreshed with the newest occurrence:
669
+ // 「阶段:…(N 次,最近 …)」 must show the current N and detail.
670
+ row.kind = kind;
671
+ if (kind === 'thinking') {
672
+ if (Number.isInteger(input.turnRef)) row.turnRef = input.turnRef;
673
+ row.charCount = Number.isInteger(input.charCount) ? input.charCount : charLength(text);
674
+ }
675
+ if (row.phase === true) {
676
+ row.last_text = text;
677
+ row.text = distillActivityText(row.key, row.count, text);
678
+ row.norm = sha256Hex(normalizeText(text)).slice(0, 16);
679
+ } else if (refreshText) {
680
+ // Event-level rows track the current action instead of the first one.
681
+ row.text = text;
682
+ row.norm = sha256Hex(normalizeText(text)).slice(0, 16);
683
+ }
684
+ if (touchSeq) {
685
+ // A refresh must be newer than the reader's lastSeenSeq; bump before
686
+ // the distillation plan so the phase row still gets a larger seq.
687
+ row.seq = seqFor(entries);
688
+ seqBumped = true;
689
+ // Keep 「array order tracks recency」 for callers that slice the array
690
+ // directly (live-window trim) — the row was just refreshed, so it
691
+ // must not stay parked at its old physical position.
692
+ const parkedAt = entries.indexOf(row);
693
+ if (parkedAt >= 0 && parkedAt !== entries.length - 1) {
694
+ entries.splice(parkedAt, 1);
695
+ entries.push(row);
696
+ }
697
+ }
698
+ entry = row;
699
+ mergedSeq = previousSeq;
700
+ action = touchSeq ? 'refreshed' : 'merged';
701
+ } else {
702
+ entry = {
703
+ schemaVersion: ACTIVITY_SCHEMA_VERSION,
704
+ seq: seqFor(entries),
705
+ sessionId,
706
+ at,
707
+ last_at: at,
708
+ kind,
709
+ text,
710
+ key,
711
+ norm: sha256Hex(normalizeText(text)).slice(0, 16),
712
+ dupOf: null,
713
+ count: 1,
714
+ };
715
+ // Thinking summaries carry their source turn and size for machine
716
+ // consumers (the injection line shows 「第 N 轮」); normal rows omit them.
717
+ if (kind === 'thinking') {
718
+ if (Number.isInteger(input.turnRef)) entry.turnRef = input.turnRef;
719
+ if (Number.isInteger(input.charCount)) entry.charCount = input.charCount;
720
+ else entry.charCount = charLength(text);
721
+ }
722
+ entries.push(entry);
723
+ action = 'appended';
724
+ }
725
+
726
+ const plan = entry?.phase === true ? null : planDistillation(entries, { sessionId, key: entry.key, at });
727
+ if (plan) {
728
+ for (const row of plan.rows) row.archived = true;
729
+ plan.summary.seq = seqFor(entries);
730
+ entries.push(plan.summary);
731
+ archivedCount = plan.rows.length;
732
+ entry = plan.summary;
733
+ action = 'distilled';
734
+ }
735
+
736
+ // 1.8.8 M3: trim the live window by TIME first (retainHours), then by the
737
+ // recentMaxRows guard. Dropped rows go to the monthly archive (append-only)
738
+ // and stay retrievable by seq; an archive failure keeps the board intact.
739
+ // The trim clock is the store clock (`now()`), not `input.at`: a producer
740
+ // replaying old rows must still trim against the real current time.
741
+ const windowed = applyActivityWindow(memoryRoot, entries, {
742
+ nowMs: now().getTime(),
743
+ retainHours,
744
+ recentMax,
745
+ });
746
+ entries = windowed.entries;
747
+ const trimmedCount = windowed.dropped;
748
+ const written = writeTextDurable(activityBoardFile(memoryRoot), serializeActivityEntries(entries));
749
+ if (!written.ok) return { ok: false, code: 'E_WRITE', message: written.error };
750
+ // High-water sidecar: keeps seq monotonic even if this board is deleted or
751
+ // truncated between now and the next write (RE-R15.5).
752
+ const boardMax = entries.reduce(
753
+ (max, row) => (Number.isInteger(row.seq) && row.seq > max ? row.seq : max),
754
+ Number.isInteger(entry?.seq) ? entry.seq : 0,
755
+ );
756
+ persistSeqHighWater(memoryRoot, boardMax, at);
757
+ if (streamReset) {
758
+ writeResetMarker(memoryRoot, { ...streamReset, boardMax, firstSeq: entry.seq });
759
+ }
760
+ return {
761
+ ok: true,
762
+ action,
763
+ entry,
764
+ seq: entry.seq,
765
+ mergedSeq,
766
+ seqBumped,
767
+ archivedCount,
768
+ trimmedCount,
769
+ streamReset: streamReset !== null,
770
+ recent: entries.length,
771
+ };
772
+ });
773
+ }
774
+
775
+ return {
776
+ memoryRoot,
777
+ boardFile: memoryRoot ? activityBoardFile(memoryRoot) : null,
778
+ recentMax,
779
+ retainHours,
780
+ read,
781
+ append,
782
+ highWater: () => readSeqHighWater(memoryRoot),
783
+ resetMarkerFile: memoryRoot ? activityResetMarkerFile(memoryRoot) : null,
784
+ nextSeq: (entries) => nextSeq(entries ?? read().entries ?? [], memoryRoot, readSeqHighWater(memoryRoot)),
785
+ };
786
+ }