@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,712 @@
1
+ // WP2 · L2 board builder (read-only projection).
2
+ //
3
+ // Inputs, in priority order:
4
+ // 1. live rows `<memoryRoot>/.longlive/live/*.json` (declared state, goal)
5
+ // 2. session metadata fallback (`ctx.get('sessions').list()` /
6
+ // `sessionQuery.listSessions()`), state always `unknown` — never inferred.
7
+ // 3. proposal files under `<vault>/proposals/` (WP3 owns writing them; WP2 only
8
+ // reads titles/counts, never transcripts).
9
+ //
10
+ // Outputs:
11
+ // board.json ≤ 8KB, stable logical `boardHash`
12
+ // index/roster.json per-session projection, source live|sessions|both
13
+ //
14
+ // boardHash deliberately excludes volatile rendered fields: only v, focus
15
+ // {sessionId,goal}, timeline {kind,ref,summary,at-minute}, counts and pending.
16
+
17
+ import fs from 'node:fs';
18
+ import path from 'node:path';
19
+
20
+ import { BOARD_MAX_BYTES, BOARD_VERSION, ROSTER_VERSION, isoOrNull, listJsonFiles, localDayKey, readJsonFile, sha256Hex, writeJsonAtomic } from './paths.mjs';
21
+ import { ACTIVE_STATE_SET, scanLiveRows } from './live.mjs';
22
+
23
+ export const BOARD_FILE_NAME = 'board.json';
24
+ export const ROSTER_FILE_NAME = 'roster.json';
25
+ export const FOCUS_GOAL_MAX = 80;
26
+ export const FOCUS_ACTION_KIND_MAX = 40;
27
+ export const FOCUS_ACTION_DETAIL_MAX = 60;
28
+ // A2: one-line conclusion per focus session (from A1's bridge marker, else the
29
+ // session's last_action.detail). Capped so one line cannot eat the hint budget.
30
+ export const LAST_CONCLUSION_MAX = 120;
31
+ export const TIMELINE_MAX = 8;
32
+ export const ROSTER_MAX = 256;
33
+ // R3: a declared goal older than this is no longer "what the session is doing
34
+ // right now". The board says so instead of letting the heartbeat timestamp
35
+ // masquerade as the goal's freshness.
36
+ export const FOCUS_STALE_MS = 30 * 60 * 1000;
37
+
38
+ const STATE_PRIORITY = Object.freeze({ running: 0, blocked: 1, waiting: 2, idle: 3 });
39
+
40
+ function cleanText(value, maxChars) {
41
+ let text = String(value ?? '')
42
+ // Control chars and newlines would break the single-line hint format.
43
+ .replace(/[\u0000-\u001f\u007f]+/g, ' ')
44
+ .replace(/\s+/g, ' ')
45
+ .trim();
46
+ if (maxChars && Array.from(text).length > maxChars) {
47
+ text = `${Array.from(text).slice(0, Math.max(0, maxChars - 1)).join('')}…`;
48
+ }
49
+ return text;
50
+ }
51
+
52
+ /** Keep external text as data: wrap in 「」 and cap it. */
53
+ export function quoted(value, maxChars) {
54
+ const text = cleanText(value, maxChars);
55
+ return text === '' ? '(未声明)' : `「${text.replace(/[「」]/g, '')}」`;
56
+ }
57
+
58
+ export function truncateChars(value, maxChars) {
59
+ const text = String(value ?? '');
60
+ const chars = Array.from(text);
61
+ if (chars.length <= maxChars) return text;
62
+ return `${chars.slice(0, Math.max(0, maxChars - 1)).join('')}…`;
63
+ }
64
+
65
+ /**
66
+ * L2 presence upgrade: a live row's `last_action`, reduced to exactly the
67
+ * three fields the board may carry. The detail is truncated here and again at
68
+ * render time; it is plugin-written tool metadata, never message text.
69
+ */
70
+ export function focusActionOf(value) {
71
+ if (!value || typeof value !== 'object') return null;
72
+ const kind = cleanText(value.kind, FOCUS_ACTION_KIND_MAX);
73
+ const detail = cleanText(value.detail, FOCUS_ACTION_DETAIL_MAX);
74
+ const at = isoOrNull(value.at);
75
+ if (kind === '' && detail === '' && at === null) return null;
76
+ return { kind, detail, at };
77
+ }
78
+
79
+ function queuedCountOf(value) {
80
+ return Array.isArray(value) ? value.length : 0;
81
+ }
82
+
83
+ /**
84
+ * A2: one conclusion string, or null. Accepts the bridge marker's
85
+ * `lastConclusion` (an object carrying `text`) or a plain string; every other
86
+ * shape (number, array, nested junk) is dropped instead of rendered.
87
+ */
88
+ export function lastConclusionOf(value) {
89
+ let raw = null;
90
+ if (typeof value === 'string') raw = value;
91
+ else if (value && typeof value === 'object' && typeof value.text === 'string') raw = value.text;
92
+ if (raw === null) return null;
93
+ const text = cleanText(raw, LAST_CONCLUSION_MAX);
94
+ return text === '' ? null : text;
95
+ }
96
+
97
+ // A2 fallback: the live writer always fills a last_action, so lifecycle-only
98
+ // details must not surface as a "conclusion" in the hint.
99
+ const LIFECYCLE_DETAIL = /^(?:state=(?:idle|running|waiting|blocked)|turn\/end #\d+|turn\/start #\d+)$/;
100
+
101
+ /** A2: derive a conclusion from a live row's last_action (or null). */
102
+ export function conclusionFromAction(lastAction) {
103
+ const detail = typeof lastAction?.detail === 'string' ? lastAction.detail : '';
104
+ if (detail === '' || LIFECYCLE_DETAIL.test(detail)) return null;
105
+ return lastConclusionOf(detail);
106
+ }
107
+
108
+ /** Read `.longlive/bridge/*.json` into Map<sessionId, conclusion text>. */
109
+ export function readBridgeConclusions(bridgeDir) {
110
+ const map = new Map();
111
+ if (typeof bridgeDir !== 'string' || bridgeDir === '') return map;
112
+ for (const file of listJsonFiles(bridgeDir)) {
113
+ const read = readJsonFile(file);
114
+ if (!read.ok || !read.value || typeof read.value !== 'object') continue;
115
+ const sessionId = sessionIdFrom(read.value);
116
+ if (!sessionId) continue;
117
+ const text = lastConclusionOf(read.value.lastConclusion);
118
+ if (text !== null) map.set(sessionId, text);
119
+ }
120
+ return map;
121
+ }
122
+
123
+ function sessionIdFrom(value) {
124
+ if (!value || typeof value !== 'object') return null;
125
+ const raw = value.sessionId ?? value.id ?? value.header?.id ?? value.session?.header?.id;
126
+ if (typeof raw !== 'string') return null;
127
+ const id = raw.trim().toLowerCase();
128
+ if (!/^[a-z0-9][a-z0-9._-]{0,127}$/.test(id)) return null;
129
+ return id;
130
+ }
131
+
132
+ export function normalizeMetadataList(raw) {
133
+ if (!raw) return null;
134
+ const list = Array.isArray(raw)
135
+ ? raw
136
+ : (Array.isArray(raw.sessions) ? raw.sessions
137
+ : (Array.isArray(raw.items) ? raw.items : (Array.isArray(raw.list) ? raw.list : null)));
138
+ if (!list) return null;
139
+ const sessions = [];
140
+ for (const item of list) {
141
+ const sessionId = sessionIdFrom(item);
142
+ if (!sessionId) continue;
143
+ const header = item.header ?? item.session?.header ?? {};
144
+ sessions.push({
145
+ sessionId,
146
+ origin: header.origin ?? item.origin ?? null,
147
+ parentSession: header.parentSession ?? header.parentSessionId ?? item.parentSession ?? null,
148
+ isSeeded: header.isSeeded === true || item.isSeeded === true,
149
+ seenAt: isoOrNull(header.updatedAt ?? item.updatedAt ?? item.lastActiveAt ?? header.createdAt ?? item.createdAt),
150
+ });
151
+ }
152
+ return sessions;
153
+ }
154
+
155
+ /** Dual-source roster metadata; returns null when the host exposes neither source. */
156
+ export async function listSessionMetadata(ctx) {
157
+ if (!ctx || typeof ctx.get !== 'function') return null;
158
+ const get = async (key) => {
159
+ try { return await ctx.get(key); } catch { return null; }
160
+ };
161
+ const calls = [];
162
+ const sessions = await get('sessions');
163
+ if (sessions && typeof sessions.list === 'function') calls.push(() => sessions.list());
164
+ const query = await get('sessionQuery');
165
+ if (query && typeof query.listSessions === 'function') calls.push(() => query.listSessions());
166
+ for (const call of calls) {
167
+ try {
168
+ const list = normalizeMetadataList(await call());
169
+ if (list) return list;
170
+ } catch { /* try the next source */ }
171
+ }
172
+ return null;
173
+ }
174
+
175
+ /** Read proposal files defensively; WP3 owns the real schema. */
176
+ export function readProposalSummaries(proposalsDir) {
177
+ const dirs = [proposalsDir, proposalsDir ? path.join(proposalsDir, 'queue') : null];
178
+ const items = [];
179
+ for (const dir of dirs) {
180
+ if (!dir) continue;
181
+ for (const file of listJsonFiles(dir)) {
182
+ const read = readJsonFile(file);
183
+ if (!read.ok || !read.value || typeof read.value !== 'object') continue;
184
+ const raw = read.value.proposal && typeof read.value.proposal === 'object' ? read.value.proposal : read.value;
185
+ const id = cleanText(raw.id ?? raw.proposalId ?? path.basename(file, '.json'), 60);
186
+ const status = cleanText(raw.status ?? '', 20).toLowerCase();
187
+ if (!id || !status) continue;
188
+ items.push({
189
+ id,
190
+ status,
191
+ title: cleanText(raw.title ?? raw.summary ?? raw.goal ?? '', 60),
192
+ at: isoOrNull(raw.appliedAt ?? raw.updatedAt ?? raw.createdAt),
193
+ });
194
+ }
195
+ }
196
+ return items;
197
+ }
198
+
199
+ function proposalCounts(items) {
200
+ const approved = items.filter((item) => item.status === 'approved');
201
+ const ready = items.filter((item) => item.status === 'approved' || item.status === 'ready');
202
+ const queued = items.filter((item) => item.status === 'pending' || item.status === 'queued' || item.status === 'open');
203
+ const blocked = items.filter((item) => item.status === 'blocked');
204
+ const applied = items
205
+ .filter((item) => item.status === 'applied' || item.status === 'done')
206
+ .sort((a, b) => String(b.at ?? '').localeCompare(String(a.at ?? '')));
207
+ return {
208
+ approved: approved.length,
209
+ ready: ready.length,
210
+ queued: queued.length,
211
+ blocked: blocked.length,
212
+ applied,
213
+ lastApplyAt: applied[0]?.at ?? null,
214
+ };
215
+ }
216
+
217
+ export function boardHashOf(board) {
218
+ const canonical = {
219
+ v: BOARD_VERSION,
220
+ // Presence upgrade: the action and queue size are logical inputs too, so a
221
+ // changed tool action invalidates the hint dedupe hash on the next turn.
222
+ focus: (board.focus ?? []).map((item) => ({
223
+ sessionId: item.sessionId,
224
+ goal: item.goal,
225
+ lastAction: item.lastAction && typeof item.lastAction === 'object'
226
+ ? {
227
+ kind: item.lastAction.kind ?? null,
228
+ detail: item.lastAction.detail ?? null,
229
+ at: item.lastAction.at ?? null,
230
+ }
231
+ : null,
232
+ queuedCount: Number.isInteger(item.queuedCount) ? item.queuedCount : 0,
233
+ // A2: a changed conclusion must invalidate the hint dedupe hash.
234
+ lastConclusion: typeof item.lastConclusion === 'string' ? item.lastConclusion : null,
235
+ })),
236
+ timeline: (board.timeline ?? []).map((item) => ({
237
+ kind: item.kind ?? null,
238
+ ref: item.ref ?? null,
239
+ summary: item.summary ?? null,
240
+ at: typeof item.at === 'string' ? item.at.slice(0, 16) : null,
241
+ })),
242
+ counts: {
243
+ active: board.counts?.active ?? 0,
244
+ running: board.counts?.running ?? 0,
245
+ blocked: board.counts?.blocked ?? 0,
246
+ queuedProposals: board.counts?.queuedProposals ?? 0,
247
+ blockedOnUser: board.counts?.blockedOnUser ?? 0,
248
+ readyProposals: board.counts?.readyProposals ?? 0,
249
+ },
250
+ pending: {
251
+ count: board.pending?.count ?? 0,
252
+ ticket: board.pending?.ticket ?? null,
253
+ },
254
+ };
255
+ return sha256Hex(JSON.stringify(canonical));
256
+ }
257
+
258
+ export function boardHashPrefixed(board) {
259
+ return `sha256:${boardHashOf(board)}`;
260
+ }
261
+
262
+ /** The on-disk shape is exactly DESIGN §3.2; in-memory extras never leak. */
263
+ function persistedBoard(board) {
264
+ return {
265
+ v: board.v,
266
+ seq: board.seq,
267
+ generatedAt: board.generatedAt,
268
+ source: board.source,
269
+ focus: board.focus,
270
+ timeline: board.timeline,
271
+ pulse: board.pulse,
272
+ warnings: board.warnings,
273
+ hash: board.hash,
274
+ };
275
+ }
276
+
277
+ function serializeBoard(board) {
278
+ return `${JSON.stringify(persistedBoard(board), null, 2)}\n`;
279
+ }
280
+
281
+ function fitBoard(board) {
282
+ let text = serializeBoard(board);
283
+ if (Buffer.byteLength(text, 'utf8') <= BOARD_MAX_BYTES) return { text, truncated: false };
284
+ board.warnings = Array.isArray(board.warnings) ? board.warnings : [];
285
+ if (!board.warnings.includes('BOARD_TRUNCATED')) board.warnings.push('BOARD_TRUNCATED');
286
+ let guard = 512;
287
+ while (Buffer.byteLength(text, 'utf8') > BOARD_MAX_BYTES && guard > 0) {
288
+ guard -= 1;
289
+ if (board.timeline.length > 0) {
290
+ board.timeline.pop();
291
+ } else if (board.focus.length > 1) {
292
+ board.focus.pop();
293
+ } else if (board.warnings.length > 1) {
294
+ const index = board.warnings.findIndex((code) => code !== 'BOARD_TRUNCATED');
295
+ if (index >= 0) board.warnings.splice(index, 1);
296
+ else board.warnings.length = 1;
297
+ } else if (board.focus.length === 1 && Array.from(board.focus[0].goal).length > 20) {
298
+ board.focus[0].goal = truncateChars(board.focus[0].goal, 20);
299
+ } else if (board.focus.length === 1 && board.focus[0].lastAction
300
+ && Array.from(board.focus[0].lastAction.detail ?? '').length > 12) {
301
+ board.focus[0].lastAction.detail = truncateChars(board.focus[0].lastAction.detail, 12);
302
+ } else if (board.focus.length === 1 && typeof board.focus[0].lastConclusion === 'string'
303
+ && Array.from(board.focus[0].lastConclusion).length > 24) {
304
+ board.focus[0].lastConclusion = truncateChars(board.focus[0].lastConclusion, 24);
305
+ } else {
306
+ break;
307
+ }
308
+ text = serializeBoard(board);
309
+ }
310
+ return { text, truncated: true };
311
+ }
312
+
313
+ export function createBoardBuilder(options = {}) {
314
+ const memoryRoot = options.memoryRoot ?? null;
315
+ const config = options.config ?? {};
316
+ const now = typeof options.now === 'function' ? options.now : () => new Date();
317
+ const paths = options.paths ?? {};
318
+ const boardFile = paths.boardFile ?? null;
319
+ const rosterFile = paths.rosterFile ?? null;
320
+ const proposalsDir = paths.proposalsDir ?? null;
321
+ // A2 reads the same markers A1 writes. `paths.bridgeDir` is the router path
322
+ // module's value; tests may pass only a memoryRoot, so derive it too.
323
+ const bridgeDir = paths.bridgeDir
324
+ ?? (memoryRoot ? path.join(memoryRoot, '.longlive', 'bridge') : null);
325
+ const maxSessions = Number.isInteger(config.boardMaxSessions) ? config.boardMaxSessions : 5;
326
+ const maxRows = Number.isInteger(config.liveRowsMax) ? config.liveRowsMax : 128;
327
+ let seq = options.seq ?? 0;
328
+
329
+ function build(args = {}) {
330
+ const at = now();
331
+ const generatedAt = isoOrNull(at);
332
+ const scan = scanLiveRows({ memoryRoot, now: at });
333
+ const warnings = [];
334
+ if (!scan.ok) warnings.push('LIVE_UNREADABLE');
335
+ if (args.saturated === true) warnings.push('LIVE_ROWS_SATURATED');
336
+
337
+ const metadata = Array.isArray(args.metadata) ? args.metadata : null;
338
+ // A host that cannot list sessions (no metadata source) leaves row origin
339
+ // unknown. A non-empty list is treated as authoritative; an empty/absent
340
+ // one falls into the fail-safe heuristic below.
341
+ const metadataAvailable = Array.isArray(metadata) && metadata.length > 0;
342
+ const metaMap = new Map();
343
+ for (const item of metadata ?? []) metaMap.set(item.sessionId, item);
344
+
345
+ /**
346
+ * R4.6: main vs subagent origin for one live row.
347
+ * With metadata: the host list is authoritative; a row missing from it is
348
+ * `unknown` (fail-safe: never counted as active/running/focus).
349
+ * Without metadata: the host contract (verified against real DSH session
350
+ * dirs on this machine) is root sessions `session-<uuid>` / subagent and
351
+ * worker sessions bare UUID ids; a bare UUID row is therefore `unknown`
352
+ * until proven otherwise, everything else stays `main` so a host that
353
+ * cannot list sessions never silently drops its rows.
354
+ */
355
+ const originOfSession = (sessionId) => {
356
+ if (typeof sessionId !== 'string' || sessionId === '') return 'unknown';
357
+ if (metadataAvailable) {
358
+ const meta = metaMap.get(sessionId) ?? null;
359
+ if (!meta) return 'unknown';
360
+ return meta.origin === 'subagent' ? 'subagent' : 'main';
361
+ }
362
+ return isBareUuidSessionId(sessionId) ? 'unknown' : 'main';
363
+ };
364
+ const originMap = new Map();
365
+ for (const entry of scan.entries) {
366
+ if (entry.sessionId) originMap.set(entry.sessionId, originOfSession(entry.sessionId));
367
+ }
368
+ const originRank = (entry) => originMap.get(entry.sessionId) ?? 'unknown';
369
+
370
+ const liveEntries = scan.entries.filter((entry) => !entry.corrupt && entry.sessionId);
371
+ const liveMap = new Map(liveEntries.map((entry) => [entry.sessionId, entry]));
372
+ const liveCount = liveEntries.length;
373
+
374
+ const roster = [];
375
+ for (const entry of liveEntries) {
376
+ const meta = metaMap.get(entry.sessionId) ?? null;
377
+ roster.push({
378
+ sessionId: entry.sessionId,
379
+ source: meta ? 'both' : 'live',
380
+ effectiveState: entry.effectiveState,
381
+ state: entry.state ?? null,
382
+ seenAt: isoOrNull(entry.heartbeatAt),
383
+ unknown: false,
384
+ origin: meta?.origin ?? null,
385
+ });
386
+ }
387
+ for (const meta of metaMap.values()) {
388
+ if (liveMap.has(meta.sessionId)) continue;
389
+ roster.push({
390
+ sessionId: meta.sessionId,
391
+ source: 'sessions',
392
+ effectiveState: 'unknown',
393
+ state: null,
394
+ seenAt: meta.seenAt ?? null,
395
+ unknown: true,
396
+ origin: meta.origin ?? null,
397
+ });
398
+ }
399
+ roster.sort((a, b) => a.sessionId.localeCompare(b.sessionId));
400
+ if (roster.length > ROSTER_MAX) roster.length = ROSTER_MAX;
401
+
402
+ const metadataUnknownSessions = roster.filter((item) => item.unknown === true && item.origin !== 'subagent').length;
403
+ // Active/focus set: rows we can prove are main sessions and that are not
404
+ // dead/stale/corrupt (ACTIVE_STATE_SET is exactly the declared-state band).
405
+ const activeEntries = liveEntries.filter((entry) => originRank(entry) === 'main'
406
+ && ACTIVE_STATE_SET.has(entry.effectiveState));
407
+ // Rows whose origin we cannot prove: fail-safe — never counted active or
408
+ // shown in focus, but reported as unknown instead of silently believed
409
+ // (R4.6 边界:metadata 缺失时的 subagent 行不得再抬高 running/active).
410
+ const unknownOriginEntries = liveEntries.filter((entry) => originRank(entry) === 'unknown'
411
+ && ACTIVE_STATE_SET.has(entry.effectiveState));
412
+ // A live row we can see but cannot decode still proves a session exists.
413
+ // DESIGN §9 counts such a row as active (state unknown), while a zero-byte
414
+ // file is an interrupted write and is ignored (and later cleaned).
415
+ const unreadableActive = scan.entries.filter((entry) => entry.corrupt === true
416
+ && entry.sessionId
417
+ && originRank(entry) === 'main'
418
+ && fileHasBytes(entry.file)).length;
419
+ const unreadableUnknown = scan.entries.filter((entry) => entry.corrupt === true
420
+ && entry.sessionId
421
+ && originRank(entry) === 'unknown'
422
+ && fileHasBytes(entry.file)).length;
423
+ // Sessions we cannot classify (no metadata + child-shaped id, or a live row
424
+ // missing from the host's session list) are reported as unknown, never as
425
+ // running/main. Subagents are counted only in counts.subagents.
426
+ const unknownSessions = metadataUnknownSessions + unknownOriginEntries.length + unreadableUnknown;
427
+ const allActive = activeEntries.length + unreadableActive;
428
+ if (activeEntries.length > Math.max(1, maxSessions)) warnings.push('FOCUS_LIMITED');
429
+ // R4.7: pulse counts share the active/focus set (main sessions, not
430
+ // dead/stale/corrupt) and count the row's DECLARED state. effectiveState
431
+ // alone cannot answer this: a fresh heartbeat returns `running` for every
432
+ // row, so a live declared-blocked row would never count as blocked (the
433
+ // R4.7 first-round over-fix; RE-R47.1).
434
+ const running = activeEntries.filter((entry) => entry.state === 'running').length;
435
+ const blocked = activeEntries.filter((entry) => entry.state === 'blocked').length;
436
+ const subagents = roster.filter((item) => item.origin === 'subagent').length;
437
+
438
+ const proposals = readProposalSummaries(proposalsDir);
439
+ const countsProposals = proposalCounts(proposals);
440
+ const conclusions = readBridgeConclusions(bridgeDir);
441
+ const atMs = at.getTime();
442
+
443
+ const focus = activeEntries
444
+ .map((entry) => {
445
+ const goalText = cleanText(entry.goal ?? '', FOCUS_GOAL_MAX);
446
+ const lastAction = focusActionOf(entry.last_action);
447
+ // A2: A1's conclusion wins; otherwise share the live row's last action
448
+ // detail (already capped to 60 chars), skipping lifecycle-only noise.
449
+ const conclusion = conclusions.get(entry.sessionId)
450
+ ?? conclusionFromAction(lastAction);
451
+ // R3: focus.updatedAt is the goal's own clock; heartbeatAt must never
452
+ // pretend to be it. Rows that never declared a goal (or rows written
453
+ // before the goal clock existed) get null — unknown, not fabricated —
454
+ // and are never marked stale because there is no goal to be stale.
455
+ const goalUpdatedMs = Date.parse(entry.goalUpdatedAt ?? '');
456
+ const goalUpdatedAt = Number.isFinite(goalUpdatedMs) ? entry.goalUpdatedAt : null;
457
+ const declared = goalText !== '';
458
+ const goalAgeMs = declared && goalUpdatedAt !== null ? Math.max(0, atMs - goalUpdatedMs) : null;
459
+ const stale = goalAgeMs !== null && goalAgeMs > FOCUS_STALE_MS;
460
+ return {
461
+ sessionId: entry.sessionId,
462
+ goal: goalText || '(未声明)',
463
+ updatedAt: goalUpdatedAt,
464
+ goalAgeMs,
465
+ stale,
466
+ lastAction,
467
+ lastConclusion: lastConclusionOf(conclusion),
468
+ queuedCount: queuedCountOf(entry.queued),
469
+ state: entry.effectiveState,
470
+ declared,
471
+ };
472
+ })
473
+ .sort((a, b) => {
474
+ // DESIGN §3.2: declared goal → running → freshest goal write.
475
+ if (a.declared !== b.declared) return a.declared ? -1 : 1;
476
+ const pa = STATE_PRIORITY[a.state] ?? 9;
477
+ const pb = STATE_PRIORITY[b.state] ?? 9;
478
+ if (pa !== pb) return pa - pb;
479
+ return String(b.updatedAt ?? '').localeCompare(String(a.updatedAt ?? ''))
480
+ || a.sessionId.localeCompare(b.sessionId);
481
+ })
482
+ .slice(0, Math.max(1, maxSessions))
483
+ .map((item) => ({
484
+ sessionId: item.sessionId,
485
+ goal: item.goal,
486
+ updatedAt: item.updatedAt,
487
+ lastAction: item.lastAction,
488
+ lastConclusion: item.lastConclusion,
489
+ queuedCount: item.queuedCount,
490
+ // R3.2: the stale flag is the single tree-wide signal (focus item);
491
+ // omitted when fresh so the persisted 6-field shape is unchanged.
492
+ ...(item.stale ? { stale: true } : {}),
493
+ }));
494
+ const focusStale = focus.some((item) => item.stale === true);
495
+
496
+ const timeline = countsProposals.applied
497
+ .filter((item) => item.title !== '')
498
+ .slice(0, TIMELINE_MAX)
499
+ .map((item) => ({
500
+ kind: 'proposal.applied',
501
+ ref: item.id,
502
+ summary: item.title,
503
+ at: item.at,
504
+ }));
505
+
506
+ const pulse = {
507
+ active: allActive,
508
+ running,
509
+ blocked,
510
+ unknownSessions,
511
+ queuedProposals: countsProposals.queued,
512
+ approvedProposals: countsProposals.approved,
513
+ blockedOnUser: countsProposals.blocked,
514
+ readyProposals: countsProposals.ready,
515
+ queueHead: null,
516
+ lease: null,
517
+ lastApplyAt: countsProposals.lastApplyAt,
518
+ };
519
+
520
+ const board = {
521
+ v: BOARD_VERSION,
522
+ seq: seq + 1,
523
+ generatedAt,
524
+ source: {
525
+ liveRows: liveCount,
526
+ proposals: proposals.length,
527
+ scanMs: Math.max(0, Date.now() - at.getTime()),
528
+ },
529
+ focus,
530
+ timeline,
531
+ pulse,
532
+ warnings,
533
+ hash: null,
534
+ // In-memory-only projections used by the Router status; the file written
535
+ // to disk is trimmed to the DESIGN §3.2 shape in write().
536
+ activeSessions: allActive,
537
+ unknownSessions,
538
+ focusVisible: focus.length,
539
+ // In-memory aggregate of R3 staleness (focus items carry stale:true).
540
+ // Never persisted: board.json shows it on the individual focus row.
541
+ stale: focusStale,
542
+ counts: {
543
+ active: allActive,
544
+ running,
545
+ blocked,
546
+ queuedProposals: countsProposals.queued,
547
+ blockedOnUser: countsProposals.blocked,
548
+ readyProposals: countsProposals.ready,
549
+ subagents,
550
+ },
551
+ pending: { count: countsProposals.ready, ticket: null },
552
+ };
553
+ board.boardHash = boardHashOf(board);
554
+ board.hash = `sha256:${sha256Hex(JSON.stringify({
555
+ v: board.v,
556
+ seq: board.seq,
557
+ generatedAt: board.generatedAt,
558
+ source: board.source,
559
+ focus: board.focus,
560
+ timeline: board.timeline,
561
+ pulse: board.pulse,
562
+ warnings: board.warnings,
563
+ }))}`;
564
+
565
+ const shared = {
566
+ hintTokensLast: 0,
567
+ injectedTurns: 0,
568
+ injectedTokensToday: 0,
569
+ skipped: 0,
570
+ readyProposals: countsProposals.ready,
571
+ lastInjectAt: null,
572
+ lastInjectSha256: null,
573
+ liveRows: liveCount,
574
+ unknownSessions,
575
+ maxRows,
576
+ saturated: args.saturated === true,
577
+ day: localDayKey(at),
578
+ };
579
+
580
+ const live = {
581
+ rows: liveCount,
582
+ maxRows,
583
+ unknown: unknownSessions,
584
+ saturated: args.saturated === true,
585
+ corrupt: scan.counts?.corrupt ?? 0,
586
+ warnings,
587
+ };
588
+
589
+ return { board, roster, shared, live, boardHash: board.boardHash };
590
+ }
591
+
592
+ function write(snapshot) {
593
+ if (!boardFile) return { ok: false, code: 'E_NO_BOARD_PATH' };
594
+ const board = { ...snapshot.board };
595
+ cleanBoardTmp(boardFile, now().getTime());
596
+ // build() already reserved the next seq; write must not advance it twice.
597
+ seq = Math.max(seq, Number.isInteger(board.seq) ? board.seq : 0);
598
+ board.seq = seq;
599
+ const fit = fitBoard(board);
600
+ // The persisted hash must describe what is actually on disk, including a
601
+ // truncated timeline/focus, so recompute it after the fit pass.
602
+ const hashed = persistedBoard(board);
603
+ delete hashed.hash;
604
+ board.hash = `sha256:${sha256Hex(JSON.stringify(hashed))}`;
605
+ let result = writeJsonAtomic(boardFile, persistedBoard(board));
606
+ if (result.ok) {
607
+ // DESIGN §3.2 read-back: parse, then verify hash and seq. One retry.
608
+ const check = verifyBoardWrite(boardFile, board);
609
+ if (!check.ok) result = writeJsonAtomic(boardFile, persistedBoard(board));
610
+ }
611
+ if (!result.ok) return { ok: false, code: result.error ?? 'E_BOARD_WRITE' };
612
+ let rosterWritten = null;
613
+ if (rosterFile) {
614
+ const roster = {
615
+ v: ROSTER_VERSION,
616
+ generatedAt: board.generatedAt,
617
+ source: board.source,
618
+ counts: board.counts,
619
+ sessions: snapshot.roster,
620
+ };
621
+ rosterWritten = writeJsonAtomic(rosterFile, roster);
622
+ }
623
+ return {
624
+ ok: true,
625
+ board,
626
+ bytes: Buffer.byteLength(fit.text, 'utf8'),
627
+ truncated: fit.truncated,
628
+ rosterOk: rosterWritten ? rosterWritten.ok === true : false,
629
+ };
630
+ }
631
+
632
+ function read() {
633
+ if (!boardFile) return null;
634
+ const read = readJsonFile(boardFile);
635
+ return read.ok ? read.value : null;
636
+ }
637
+
638
+ return {
639
+ build,
640
+ write,
641
+ read,
642
+ // Orphan temp cleanup is useful even when sharedBoard is off: a stale
643
+ // board.json.tmp-* from a previous run must not survive a tick (J-05/L-02).
644
+ cleanTmp: () => {
645
+ if (boardFile) cleanBoardTmp(boardFile, now().getTime());
646
+ },
647
+ get seq() { return seq; },
648
+ boardFile,
649
+ rosterFile,
650
+ };
651
+ }
652
+
653
+ function fileHasBytes(file) {
654
+ try {
655
+ return typeof file === 'string' && fs.statSync(file).size > 0;
656
+ } catch {
657
+ return false;
658
+ }
659
+ }
660
+
661
+ function cleanBoardTmp(boardFile, nowMs) {
662
+ if (!boardFile) return 0;
663
+ const dir = path.dirname(boardFile);
664
+ const prefix = `${path.basename(boardFile)}.tmp-`;
665
+ let names = [];
666
+ try { names = fs.readdirSync(dir); } catch { return 0; }
667
+ let removed = 0;
668
+ for (const name of names) {
669
+ if (!name.startsWith(prefix)) continue;
670
+ const file = path.join(dir, name);
671
+ try {
672
+ if (nowMs - fs.statSync(file).mtimeMs > 60 * 60 * 1000) {
673
+ fs.unlinkSync(file);
674
+ removed += 1;
675
+ }
676
+ } catch { /* a concurrent writer may have renamed it already */ }
677
+ }
678
+ return removed;
679
+ }
680
+
681
+ /**
682
+ * R4.6 fail-safe: the host's child-session id shape. Real DSH session dirs on
683
+ * this machine show root/main sessions as `session-<uuid>` while spawned
684
+ * subagent/worker sessions get a bare UUID. When the host exposes no session
685
+ * metadata this is the only honest signal available, so a bare-UUID row is
686
+ * treated as *unknown origin* (reported in unknownSessions, never counted as
687
+ * running/active/main). Requires metadata to be certain: with metadata the
688
+ * host list wins and this heuristic is not consulted.
689
+ */
690
+ export function isBareUuidSessionId(sessionId) {
691
+ return typeof sessionId === 'string'
692
+ && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sessionId);
693
+ }
694
+
695
+ function verifyBoardWrite(file, board) {
696
+ const read = readJsonFile(file);
697
+ if (!read.ok) return { ok: false };
698
+ return {
699
+ ok: read.value?.seq === board.seq && read.value?.hash === board.hash,
700
+ };
701
+ }
702
+
703
+ /** Format one focus row for the fixed hint template. */
704
+ export function renderFocusLine(item) {
705
+ const stale = item?.stale === true ? ' · stale(目标超 30 分钟未更新)' : '';
706
+ return `- ${item.sessionId} ${item.state ?? ''} · 目标${quoted(item.goal, FOCUS_GOAL_MAX)} · ${timeOf(item.updatedAt)}${stale}`;
707
+ }
708
+
709
+ export function timeOf(iso) {
710
+ if (typeof iso !== 'string' || iso.length < 16) return '--:--';
711
+ return iso.slice(11, 16);
712
+ }