@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,1035 @@
1
+ // 0.9.0-rc.1 feature wiring — every capability here is OFF by default.
2
+ //
3
+ // This module is deliberately side-effect free at import time. `registerFeatures`
4
+ // is called at the end of `apply()`; when every switch is off it registers no
5
+ // listener, performs no filesystem access and emits no log line, so a 0.9.0-rc.1
6
+ // install behaves exactly like 0.8.0 until an operator opts in.
7
+ //
8
+ // Wiring (see docs/FEATURES.md):
9
+ // identityCard.enabled -> agent/pre-step (open card, prepend:true)
10
+ // autoRecall.enabled -> agent/pre-step (recall, prepend:false) + session/event
11
+ // presenceBus.enabled -> session/event (drain this session's bus inbox)
12
+ // sharedBrain.activity.enabled -> session/event (write this turn's activity)
13
+ // + agent/pre-step (inject other sessions' new rows)
14
+ // autoMaintenance.enabled -> one unref'd timer to the next local midnight
15
+ // (consolidate report + forget dry-run pending list;
16
+ // no turn hook, so a failure cannot affect a turn)
17
+ // routerRuntime -> unchanged 0.8.0 off|shadow|on adapter (src/router/runtime.js)
18
+ //
19
+ // The router background modules under src/router/background/ are shipped code
20
+ // plus their own test suite; 0.9.0-rc.1 does not register a second router hook.
21
+
22
+ import fs from 'node:fs';
23
+ import path from 'node:path';
24
+ import { randomUUID } from 'node:crypto';
25
+
26
+ import { collectOpenCard, resolveMemoryRoot } from './identity/handover.js';
27
+ import {
28
+ claimCardMarker,
29
+ finalizeCardMarker,
30
+ pruneCardMarkers,
31
+ readCardMarker,
32
+ releaseCardMarker,
33
+ } from './identity/card-marker.js';
34
+ import { isInsideRoot, memoryError, PATH_CODES } from './memory/paths.js';
35
+ import {
36
+ assertInjectionSource,
37
+ injectionSource,
38
+ insertionIndex,
39
+ placeAfterFirstHuman,
40
+ sameMessageOrder,
41
+ } from './identity/inject-position.js';
42
+ import {
43
+ composePreStepBlocks,
44
+ createWorkingFrameStore,
45
+ insertWorkingMessage,
46
+ updateFrameFromMessages,
47
+ } from './memory/working-frame.js';
48
+ import { apply as applyAutoRecall } from './recall/index.js';
49
+ import { startPrestepPhase } from './metrics/prestep-latency.mjs';
50
+ import { createBus, normalizeSessionId, shouldAckOnTurnEnd } from './bus/bus.mjs';
51
+ import { createMaintenanceScheduler } from './memory/maintenance.js';
52
+ import { registerDailyHealth } from './memory/memory-health.mjs';
53
+ import { registerHardgateWake } from './memory/wake-bridge.mjs';
54
+ import { registerRetention, retentionHealth } from './retention/index.js';
55
+ import { normalizeActivityConfig, registerActivityStream } from './activity/index.js';
56
+ import { registerRole } from './role/index.js';
57
+ import {
58
+ normalizeProactiveConfig,
59
+ registerProactive,
60
+ } from './lifecycle/proactive.js';
61
+ import { normalizeHandoffConfig, registerHandoffCard } from './handoff/index.js';
62
+ import {
63
+ claimFallbackInjection,
64
+ markReceiptFallbackInjected,
65
+ readSurgeryState,
66
+ recordFallbackInjectionSkip,
67
+ releaseFallbackInjectionClaim,
68
+ } from './surgery-recovery.js';
69
+
70
+ export const FEATURE_DEFAULTS = Object.freeze({
71
+ autoRecall: Object.freeze({ enabled: true, topK: 3, budgetTokens: 2000, everyNTurns: 6 }),
72
+ identityCard: Object.freeze({
73
+ enabled: true,
74
+ path: '<memoryRoot>/STATE.md',
75
+ maxChars: 2233,
76
+ recentBudgetChars: 1161,
77
+ // M04(DESIGN §8 C / G-D7):开机卡承接 handoff 摘要;handoff 退役前由 identityCard
78
+ // 承接,显式 false 时开机卡不注入交接节(HANDOVER_SUMMARY_DISABLED)。
79
+ handoffSummary: true,
80
+ }),
81
+ presenceBus: Object.freeze({ enabled: true, pollMs: 3000 }),
82
+ sharedBrain: Object.freeze({
83
+ // 1.8.8 M3: 24h live window (time first, row guard second) + recap budget.
84
+ activity: Object.freeze({
85
+ enabled: true,
86
+ injectMaxChars: 300,
87
+ maxItems: 5,
88
+ retainHours: 24,
89
+ recentMaxRows: 3200,
90
+ summaryMaxChars: 400,
91
+ }),
92
+ thinkingInjection: true,
93
+ }),
94
+ autoMaintenance: Object.freeze({
95
+ enabled: true,
96
+ consolidate: true,
97
+ forget: true,
98
+ runOnStart: true,
99
+ startDelayMs: 500,
100
+ }),
101
+ // 02-handoff: default OFF (hard constraint ① — 1.8.3 behaviour is unchanged
102
+ // unless the profile config row opts in with `handoff.enabled: true`).
103
+ handoff: Object.freeze({ enabled: false, dryRun: false }),
104
+ // H 批 hardgate 唤醒桥(N15):默认 OFF。这里只放「文档占位」,真正的 6 键归一化/
105
+ // 钳制在 src/memory/wake-bridge.mjs 的 normalizeWakeConfig(raw passthrough,与
106
+ // proactive/handoff 同法,不加 schemastery 节点——config schema 153 节点锁不变)。
107
+ hardgate: Object.freeze({ wake: Object.freeze({ enabled: false }) }),
108
+ });
109
+
110
+ function clampInt(value, fallback, min, max) {
111
+ const number = Number(value);
112
+ if (!Number.isFinite(number)) return fallback;
113
+ return Math.min(max, Math.max(min, Math.floor(number)));
114
+ }
115
+
116
+ function bool(value) {
117
+ return value !== false;
118
+ }
119
+
120
+ function text(value) {
121
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined;
122
+ }
123
+
124
+ /** Normalize the five feature blocks. Pure: no I/O, no logging. */
125
+ export function normalizeFeatureConfig(config = {}) {
126
+ const value = config && typeof config === 'object' ? config : {};
127
+ const auto = value.autoRecall && typeof value.autoRecall === 'object' ? value.autoRecall : {};
128
+ const identity = value.identityCard && typeof value.identityCard === 'object' ? value.identityCard : {};
129
+ const bus = value.presenceBus && typeof value.presenceBus === 'object' ? value.presenceBus : {};
130
+ const sharedBrain = value.sharedBrain && typeof value.sharedBrain === 'object' ? value.sharedBrain : {};
131
+ const activity = sharedBrain.activity && typeof sharedBrain.activity === 'object' ? sharedBrain.activity : {};
132
+ const maintenance = value.autoMaintenance && typeof value.autoMaintenance === 'object'
133
+ ? value.autoMaintenance
134
+ : {};
135
+ const handoff = value.handoff && typeof value.handoff === 'object' ? value.handoff : {};
136
+ // H 批 hardgate 唤醒桥(N15):只读 raw `config.hardgate?.wake`,raw 透传给
137
+ // wake-bridge(同 F 批 archiveRoot 三键做法:这里不归一化、不加 schemastery 节点,
138
+ // config schema 153 节点锁不变;6/12 键默认值与钳制仍在
139
+ // wake-bridge.normalizeWakeConfig,注册 registerHardgateWake 时执行)。
140
+ const hardgate = value.hardgate && typeof value.hardgate === 'object' ? value.hardgate : {};
141
+ const wake = hardgate.wake && typeof hardgate.wake === 'object' && !Array.isArray(hardgate.wake)
142
+ ? hardgate.wake
143
+ : null;
144
+
145
+ const normalized = {
146
+ autoRecall: {
147
+ enabled: bool(auto.enabled),
148
+ topK: clampInt(auto.topK, FEATURE_DEFAULTS.autoRecall.topK, 1, 10),
149
+ budgetTokens: clampInt(auto.budgetTokens, FEATURE_DEFAULTS.autoRecall.budgetTokens, 200, 2000),
150
+ everyNTurns: clampInt(auto.everyNTurns, FEATURE_DEFAULTS.autoRecall.everyNTurns, 1, 1000),
151
+ // Test seam; production resolves @deepseek-ai/dsh-llm lazily.
152
+ createUserMessage: typeof auto.createUserMessage === 'function' ? auto.createUserMessage : undefined,
153
+ },
154
+ identityCard: {
155
+ enabled: bool(identity.enabled),
156
+ path: text(identity.path) ?? FEATURE_DEFAULTS.identityCard.path,
157
+ maxChars: clampInt(identity.maxChars, FEATURE_DEFAULTS.identityCard.maxChars, 120, 4000),
158
+ recentBudgetChars: clampInt(
159
+ identity.recentBudgetChars,
160
+ FEATURE_DEFAULTS.identityCard.recentBudgetChars,
161
+ 120,
162
+ 4000,
163
+ ),
164
+ handoffSummary: bool(identity.handoffSummary),
165
+ createUserMessage: typeof identity.createUserMessage === 'function' ? identity.createUserMessage : undefined,
166
+ },
167
+ presenceBus: {
168
+ enabled: bool(bus.enabled),
169
+ pollMs: clampInt(bus.pollMs, FEATURE_DEFAULTS.presenceBus.pollMs, 0, 3600000),
170
+ root: text(bus.root),
171
+ },
172
+ sharedBrain: {
173
+ activity: normalizeActivityConfig(activity),
174
+ thinkingInjection: bool(sharedBrain.thinkingInjection),
175
+ },
176
+ autoMaintenance: {
177
+ enabled: bool(maintenance.enabled),
178
+ consolidate: maintenance.consolidate !== false,
179
+ forget: maintenance.forget !== false,
180
+ runOnStart: maintenance.runOnStart !== false,
181
+ startDelayMs: clampInt(
182
+ maintenance.startDelayMs,
183
+ FEATURE_DEFAULTS.autoMaintenance.startDelayMs,
184
+ 0,
185
+ 300000,
186
+ ),
187
+ },
188
+ // Optional block, additive only: absent → default OFF (zero hooks, zero IO).
189
+ handoff: normalizeHandoffConfig(handoff),
190
+ };
191
+ // H 批 hardgate 唤醒桥(N15,spec §5.5:314):只有 raw config 带 `hardgate.wake`
192
+ // 时才追加该键(值/键原样透传,浅拷贝防外部改写);不带该键时输出仍是上面那 6 键,
193
+ // 既有 defaults 快照(feature-flags deepEqual)逐字节不变。
194
+ if (wake) normalized.hardgate = { wake: { ...wake } };
195
+ return normalized;
196
+ }
197
+
198
+ /** Resolve `<memoryRoot>/STATE.md` and prove it stays inside the memory root. */
199
+ export function resolveCardPath(rawPath, memoryRoot) {
200
+ const raw = text(rawPath) ?? FEATURE_DEFAULTS.identityCard.path;
201
+ if (raw.includes('<memoryRoot>') && !memoryRoot) return null;
202
+ const root = memoryRoot ? path.resolve(memoryRoot) : null;
203
+ const resolved = raw.includes('<memoryRoot>')
204
+ ? path.resolve(raw.replaceAll('<memoryRoot>', root))
205
+ : path.isAbsolute(raw) ? path.resolve(raw) : path.resolve(root ?? process.cwd(), raw);
206
+ if (!root) return resolved;
207
+ // 复核 M2:`../`、根外绝对路径、盘符跳转一律 E_PATH_OUTSIDE_ROOT。
208
+ // 只做词法判定、不读盘:越界路径在读任何文件之前就被拒绝。
209
+ if (!isInsideRoot(root, resolved)) {
210
+ throw memoryError(
211
+ PATH_CODES.PATH_OUTSIDE_ROOT,
212
+ `identityCard.path 越界:${resolved} 不在记忆根 ${root} 内 (E_PATH_OUTSIDE_ROOT)`,
213
+ );
214
+ }
215
+ return resolved;
216
+ }
217
+
218
+ function loggerOf(ctx) {
219
+ try {
220
+ const logger = typeof ctx?.logger === 'function' ? ctx.logger() : ctx?.logger;
221
+ return logger && typeof logger.warn === 'function' ? logger : null;
222
+ } catch {
223
+ return null;
224
+ }
225
+ }
226
+
227
+ async function resolveUserMessageFactory(explicit) {
228
+ if (typeof explicit === 'function') return explicit;
229
+ try {
230
+ const mod = await import('@deepseek-ai/dsh-llm');
231
+ return typeof mod?.createUserMessage === 'function' ? mod.createUserMessage : null;
232
+ } catch {
233
+ return null;
234
+ }
235
+ }
236
+
237
+ function isSubagent(agent) {
238
+ return agent?.session?.header?.origin === 'subagent' || agent?.origin === 'subagent';
239
+ }
240
+
241
+ function keyOf(agent) {
242
+ return String(agent?.session?.id ?? agent?.id ?? 'unknown');
243
+ }
244
+
245
+ /**
246
+ * Identity card only: pre-step, outer waterfall, splice before next().
247
+ * Mirrors `src/identity/index.js` but deliberately does NOT register the
248
+ * writeback hooks — `identityCard` is a card-injection switch, not permission
249
+ * to write handover drafts.
250
+ */
251
+ function registerIdentityCard(ctx, cfg, memoryRoot, warn) {
252
+ const states = new Map();
253
+ const stateFor = (key) => {
254
+ let state = states.get(key);
255
+ if (!state) {
256
+ state = { card: null, opened: false, warned: false, markerWarned: false };
257
+ states.set(key, state);
258
+ }
259
+ return state;
260
+ };
261
+
262
+ // 跨进程判定落在磁盘上。memoryRoot 的解析沿用开机卡自己的解析器:没有显式
263
+ // memoryRoot 时用 `<DSH home>/longlive-memory`(或 DSH_IDENTITY_MEMORY_ROOT),绝不写进 cwd。
264
+ let markerRoot = null;
265
+ try {
266
+ markerRoot = memoryRoot ? path.resolve(memoryRoot) : resolveMemoryRoot({});
267
+ } catch {
268
+ markerRoot = null;
269
+ }
270
+ // 启动时顺手清掉 30 天以上的旧标记。best-effort:目录不存在/只读都静默。
271
+ if (markerRoot) pruneCardMarkers(markerRoot);
272
+
273
+ let cardPath = null;
274
+ let cardPathResolved = false;
275
+
276
+ ctx.on('agent/pre-step', async (payload, next) => {
277
+ if (Number(payload?.step) !== 1) return next();
278
+ const agent = payload?.agent;
279
+ if (!agent || isSubagent(agent)) return next();
280
+
281
+ const sessionId = keyOf(agent);
282
+ const state = stateFor(sessionId);
283
+ if (state.opened) return next();
284
+
285
+ // 先看持久化标记:已经开过就直接放行,连卡都不读。
286
+ if (!markerRoot) {
287
+ if (!state.markerWarned) {
288
+ state.markerWarned = true;
289
+ warn('[identity-card] 没有可用的记忆根,跳过注入(无法保证跨进程只注入一次)。');
290
+ }
291
+ return next();
292
+ }
293
+ const marker = readCardMarker({ memoryRoot: markerRoot, sessionId });
294
+ if (marker.ok && marker.exists) return next();
295
+ if (!marker.ok) {
296
+ // 读/解析失败、sessionId 对不上:fail-closed 到「不重复注入」。
297
+ if (!state.markerWarned) {
298
+ state.markerWarned = true;
299
+ warn(`[identity-card] 开机标记不可用(${marker.code ?? 'E_MARKER'}),跳过注入以免重复。`);
300
+ }
301
+ return next();
302
+ }
303
+
304
+ if (state.card === null) {
305
+ try {
306
+ // 延迟到首次注入才解析:越界路径只让本特性静默失效,不阻断插件加载。
307
+ if (!cardPathResolved) {
308
+ cardPath = resolveCardPath(cfg.path, memoryRoot);
309
+ cardPathResolved = true;
310
+ }
311
+ const card = collectOpenCard({
312
+ memoryRoot: memoryRoot ?? undefined,
313
+ statePath: cardPath ?? undefined,
314
+ maxChars: cfg.maxChars,
315
+ recentBudgetChars: cfg.recentBudgetChars,
316
+ handoffSummary: cfg.handoffSummary,
317
+ });
318
+ state.card = typeof card?.text === 'string' ? card.text : '';
319
+ } catch (error) {
320
+ state.card = '';
321
+ if (!state.warned) {
322
+ state.warned = true;
323
+ warn(`[identity-card] 开机卡生成失败:${error?.code ?? error?.message ?? error}`);
324
+ }
325
+ }
326
+ }
327
+ if (state.card.trim() === '') return next();
328
+
329
+ const createUserMessage = await resolveUserMessageFactory(cfg.createUserMessage);
330
+ if (!createUserMessage) return next();
331
+
332
+ let message;
333
+ try {
334
+ message = assertInjectionSource(createUserMessage({
335
+ content: [{ type: 'text', text: state.card }],
336
+ source: injectionSource(),
337
+ }));
338
+ } catch (error) {
339
+ if (!state.warned) {
340
+ state.warned = true;
341
+ warn(`[identity-card] 注入消息被拒绝:${error?.code ?? error?.message ?? error}`);
342
+ }
343
+ return next();
344
+ }
345
+
346
+ // 注入前用 O_EXCL 抢占本会话的 marker:两个进程同时到 step 1 时只有赢家
347
+ // 注入,输家(E_ALREADY_CLAIMED)直接放行。写入失败(只读盘、权限)也跳过:
348
+ // 记不下来就无法保证下一次不重复,宁可这一次不开。
349
+ const claim = claimCardMarker({ memoryRoot: markerRoot, sessionId });
350
+ if (!claim.ok) {
351
+ if (claim.code !== 'E_ALREADY_CLAIMED' && !state.markerWarned) {
352
+ state.markerWarned = true;
353
+ warn(`[identity-card] 开机标记写入失败(${claim.code ?? 'E_MARKER'}),跳过注入以免重复。`);
354
+ }
355
+ return next();
356
+ }
357
+
358
+ const claimed = Array.isArray(payload?.messages) ? payload.messages : null;
359
+ if (claimed) claimed.splice(insertionIndex(claimed), 0, message);
360
+ const withdraw = () => {
361
+ if (!claimed) return;
362
+ const index = claimed.indexOf(message);
363
+ if (index !== -1) claimed.splice(index, 1);
364
+ };
365
+
366
+ let decision;
367
+ try {
368
+ decision = await next();
369
+ } catch (error) {
370
+ withdraw();
371
+ releaseCardMarker(claim);
372
+ throw error;
373
+ }
374
+ if (!decision || decision.kind === 'reject') {
375
+ withdraw();
376
+ releaseCardMarker(claim);
377
+ return decision;
378
+ }
379
+
380
+ state.opened = true;
381
+ // 注入已被宿主接受:原子落最终 marker。写失败不抛、只 warn 一次;磁盘上还留着
382
+ // 抢占时写的占位 marker,后续进程照样跳过(本进程也由 state.opened 拦住)。
383
+ const finalized = finalizeCardMarker(claim, { sessionId });
384
+ if (!finalized.ok && !state.markerWarned) {
385
+ state.markerWarned = true;
386
+ warn(`[identity-card] 开机标记落盘失败(${finalized.code ?? 'E_MARKER'}):本进程只注入一次,后续进程按已注入处理。`);
387
+ }
388
+ const messages = Array.isArray(decision.messages) ? decision.messages : [];
389
+ const ordered = placeAfterFirstHuman(messages, message);
390
+ if (sameMessageOrder(messages, ordered)) return decision;
391
+ return { ...decision, messages: ordered };
392
+ }, { prepend: true });
393
+ }
394
+
395
+ /**
396
+ * Presence bus consumer. On a COMPLETED turn/end only, poll this session's
397
+ * inbox at most once per `pollMs`, spool non-control messages to
398
+ * `<busRoot>/spool/<sessionId>.jsonl`, then ack. A failed spool write leaves
399
+ * the message pending (at-least-once); an ack failure leaves it for the next
400
+ * poll. Failed/aborted turns never poll, so nothing is consumed for a turn the
401
+ * model did not finish.
402
+ */
403
+ function registerPresenceBus(ctx, cfg, memoryRoot, warn) {
404
+ if (!cfg.root && !memoryRoot) {
405
+ warn('[presence-bus] 没有 memoryRoot 且未配置 presenceBus.root — 总线消费不启用。');
406
+ return;
407
+ }
408
+ const root = cfg.root ?? path.join(memoryRoot, '.longlive', 'bus');
409
+ const sessions = new Map();
410
+
411
+ const stateFor = (sessionId) => {
412
+ let state = sessions.get(sessionId);
413
+ if (!state) {
414
+ state = { lastPoll: -Infinity, bus: null };
415
+ sessions.set(sessionId, state);
416
+ }
417
+ return state;
418
+ };
419
+
420
+ ctx.on('session/event', (session, event) => {
421
+ try {
422
+ if (!shouldAckOnTurnEnd(event)) return;
423
+ const sessionId = normalizeSessionId(session?.id, 'sessionId');
424
+ const state = stateFor(sessionId);
425
+ const now = Date.now();
426
+ if (now - state.lastPoll < cfg.pollMs) return;
427
+ state.lastPoll = now;
428
+
429
+ state.bus ??= createBus({ root, sessionId, memoryRoot: memoryRoot ?? undefined });
430
+ const pending = state.bus.poll({ since: 0, limit: 100 });
431
+ const messages = pending.messages.filter((message) => message.kind !== 'control');
432
+ if (messages.length === 0) return;
433
+
434
+ const spoolDir = path.join(root, 'spool');
435
+ fs.mkdirSync(spoolDir, { recursive: true });
436
+ const spool = path.join(spoolDir, `${sessionId}.jsonl`);
437
+ const receivedAt = new Date().toISOString();
438
+ for (const message of messages) {
439
+ fs.appendFileSync(spool, `${JSON.stringify({ receivedAt, sessionId, message })}\n`, 'utf8');
440
+ }
441
+ for (const message of messages) {
442
+ try {
443
+ state.bus.ack(message.id);
444
+ } catch (error) {
445
+ if (error?.code !== 'E_NOT_FOUND') {
446
+ warn(`[presence-bus] ack 失败 ${message.id}: ${error?.code ?? error?.message ?? error}`);
447
+ }
448
+ }
449
+ }
450
+ } catch (error) {
451
+ warn(`[presence-bus] 消费失败:${error?.code ?? error?.message ?? error}`);
452
+ }
453
+ });
454
+
455
+ if (typeof ctx.effect === 'function') {
456
+ try {
457
+ ctx.effect(() => () => sessions.clear(), 'longlive.presence-bus');
458
+ } catch {
459
+ /* fake context without effect scope */
460
+ }
461
+ }
462
+ }
463
+
464
+ /**
465
+ * Visible surgery receipt (必修二, fallback path).
466
+ *
467
+ * The launcher normally appends this text to the session itself before the
468
+ * restart, so the next activation already shows it. When that write never
469
+ * happened (crash / older state / failed run), this one-shot pre-step hook
470
+ * injects the exact same text as a *visible* user message on the first step of
471
+ * the first turn, then unregisters. The message uses `source.kind: 'user'`
472
+ * because the host renders user-sourced messages as conversation text; a
473
+ * `session-reference` source would land in the invisible context rail.
474
+ *
475
+ * With no receipt text this function is not called at all (index.js passes
476
+ * null), so a clean start registers no hook and reads nothing.
477
+ */
478
+ function registerSurgeryReceipt(ctx, receipt, warn, { memoryRoot = null } = {}) {
479
+ const text = typeof receipt === 'string' ? receipt.trim() : '';
480
+ if (!text) return false;
481
+
482
+ let done = false;
483
+ let dispose = null;
484
+
485
+ // Stop offering the receipt in this process. Safe to call more than once.
486
+ const stop = () => {
487
+ done = true;
488
+ if (typeof dispose === 'function') {
489
+ try {
490
+ dispose();
491
+ } catch {
492
+ /* already disposed */
493
+ }
494
+ }
495
+ };
496
+
497
+ const handler = async (payload, next) => {
498
+ if (done || Number(payload?.step) !== 1) return next();
499
+ if (isSubagent(payload?.agent)) return next();
500
+ const decision = await next();
501
+ if (done || !decision || decision.kind === 'reject' || !Array.isArray(decision.messages)) {
502
+ return decision;
503
+ }
504
+ // R3-03: two hosts can reach step 1 of the same session at the same time.
505
+ // Claim the injection across processes before touching anything; the loser
506
+ // skips (`skipped-concurrent`, audited by the claim) instead of appending
507
+ // the same receipt twice.
508
+ let claimed = null;
509
+ if (memoryRoot) {
510
+ try {
511
+ const claim = claimFallbackInjection({ memoryRoot });
512
+ if (!claim.ok) {
513
+ if (claim.code !== 'skipped-concurrent') {
514
+ warn(`[surgery-receipt] 兜底占用失败:${claim.code}`);
515
+ }
516
+ return decision;
517
+ }
518
+ claimed = claim.claim;
519
+ } catch (error) {
520
+ warn(`[surgery-receipt] 兜底占用失败:${error?.code ?? error?.message ?? error}`);
521
+ return decision;
522
+ }
523
+ // R4-01: both hosts can pass the startup check before either injects, so
524
+ // holding the claim is not enough. Re-read the persistent state while the
525
+ // claim is held: if the other host already marked (or a real receipt was
526
+ // written), this host must skip instead of appending a second copy.
527
+ let current = null;
528
+ try {
529
+ current = readSurgeryState(memoryRoot);
530
+ } catch {
531
+ current = null;
532
+ }
533
+ const receiptState = current?.exists && current?.state ? current.state.receipt : null;
534
+ if (receiptState?.written === true || receiptState?.fallbackInjected === true) {
535
+ stop();
536
+ // Release before the early return: the loop below only runs for the
537
+ // append path, and a retained lock would block the next host for 60s.
538
+ try {
539
+ releaseFallbackInjectionClaim({ memoryRoot, claim: claimed });
540
+ } catch {
541
+ /* the TTL expires the claim even if the release fails */
542
+ }
543
+ claimed = null;
544
+ recordFallbackInjectionSkip({ memoryRoot, result: 'skipped-already' });
545
+ return decision;
546
+ }
547
+ }
548
+ try {
549
+ // A plain frozen-shape user message: the host validates id/role/source/
550
+ // content and renders `source.kind === 'user'` as visible chat text.
551
+ const message = Object.freeze({
552
+ id: `surgery-receipt-${randomUUID()}`,
553
+ role: 'user',
554
+ content: Object.freeze([Object.freeze({ type: 'text', text })]),
555
+ source: Object.freeze({ kind: 'user' }),
556
+ });
557
+ // R2-02 / minor: mark the one-shot fallback only after the injection was
558
+ // accepted. The marker is atomic and idempotent; a second start reads it
559
+ // and skips the receipt instead of appending the same text again.
560
+ if (memoryRoot) {
561
+ try {
562
+ const marked = markReceiptFallbackInjected({ memoryRoot });
563
+ if (!marked.ok) {
564
+ warn(`[surgery-receipt] 兜底标记未写入:${marked.code}`);
565
+ } else if (marked.alreadyMarked === true || marked.written === true) {
566
+ // R4-01: lost the gap between the re-read and the atomic mark.
567
+ // Whatever happened, a receipt already exists — never append a
568
+ // second one.
569
+ stop();
570
+ recordFallbackInjectionSkip({ memoryRoot, result: 'skipped-already' });
571
+ return decision;
572
+ }
573
+ } catch (error) {
574
+ warn(`[surgery-receipt] 兜底标记未写入:${error?.code ?? error?.message ?? error}`);
575
+ }
576
+ }
577
+ stop();
578
+ // Append at the end: the receipt is the newest thing the operator sees.
579
+ return { ...decision, messages: [...decision.messages, message] };
580
+ } catch (error) {
581
+ warn(`[surgery-receipt] 注入失败:${error?.code ?? error?.message ?? error}`);
582
+ return decision;
583
+ } finally {
584
+ if (claimed) {
585
+ try {
586
+ releaseFallbackInjectionClaim({ memoryRoot, claim: claimed });
587
+ } catch {
588
+ /* the TTL expires the claim even if the release fails */
589
+ }
590
+ }
591
+ }
592
+ };
593
+
594
+ dispose = ctx.on('agent/pre-step', handler, { prepend: false });
595
+ return true;
596
+ }
597
+
598
+ /**
599
+ * Register the opt-in features. Returns `{ enabled: string[] }` for tests and
600
+ * for a single startup log line; with every flag off it touches nothing.
601
+ */
602
+
603
+ /**
604
+ * v2.6.4 §14.2 连续性:pre-step 注入未过期的 working-frame(≤300 字)。
605
+ * 注入顺序由 handler 注册顺序保证:[boot, shared, working, recall];本函数在
606
+ * autoRecall 之前注册(同一 append 语义),working 块因此出现在 recall 之前。
607
+ * 过期帧不注入(标 stale,不删);时钟回拨 fail closed 后静默跳过。
608
+ */
609
+ function registerWorkingFrame(ctx, options = {}) {
610
+ const memoryRoot = options.memoryRoot ?? null;
611
+ const warn = typeof options.warn === 'function' ? options.warn : () => {};
612
+ if (!memoryRoot) return false;
613
+ let store = null;
614
+ try {
615
+ store = createWorkingFrameStore({
616
+ memoryRoot,
617
+ now: options.now,
618
+ monoNow: options.monoNow,
619
+ });
620
+ } catch (error) {
621
+ warn(`[working-frame] 初始化失败(${error?.code ?? error?.message ?? error}),跳过注入。`);
622
+ return false;
623
+ }
624
+ ctx.on('agent/pre-step', async (payload, next) => {
625
+ if (Number(payload?.step) !== 1) return next();
626
+ if (isSubagent(payload?.agent)) return next();
627
+ const decision = await next();
628
+ if (!decision || decision.kind === 'reject' || !Array.isArray(decision.messages)) return decision;
629
+ const sessionId = keyOf(payload.agent);
630
+ const turn = Number.isInteger(payload?.turn) ? payload.turn : 0;
631
+ // B3: working phase = frame lookup + injection + next-turn focus update (timing only).
632
+ const workPhase = startPrestepPhase(sessionId, turn, 'working');
633
+ try {
634
+ let block = null;
635
+ try {
636
+ block = store.frameForInjection({ sessionId });
637
+ } catch (error) {
638
+ warn(`[working-frame] 注入判定失败(${error?.code ?? error?.message ?? error})。`);
639
+ return decision;
640
+ }
641
+ let message = null;
642
+ if (block && block.inject === true && typeof block.text === 'string' && block.text.trim() !== '') {
643
+ try {
644
+ // 任务: composePreStepBlocks has a REAL production call point (order [boot, shared, working, recall]).
645
+ const composed = composePreStepBlocks([{ kind: 'working', text: block.text }]);
646
+ const workingText = composed[0]?.text ?? block.text;
647
+ message = assertInjectionSource({
648
+ id: `working-frame-${randomUUID()}`,
649
+ role: 'user',
650
+ content: [{ type: 'text', text: workingText }],
651
+ source: injectionSource(),
652
+ });
653
+ } catch (error) {
654
+ warn(`[working-frame] 注入消息被拒绝(${error?.code ?? error?.message ?? error})。`);
655
+ message = null;
656
+ }
657
+ }
658
+ // EA-05: this turn's focus is recorded for the NEXT turn (real caller, always runs).
659
+ try {
660
+ updateFrameFromMessages({
661
+ store,
662
+ sessionId,
663
+ messages: Array.isArray(decision.messages) ? decision.messages : (payload?.messages ?? []),
664
+ turn,
665
+ });
666
+ } catch (error) {
667
+ warn(`[working-frame] 焦点更新失败(${error?.code ?? error?.message ?? error})。`);
668
+ }
669
+ // EA-04: real order [boot, shared, working, recall].
670
+ return message === null ? decision : { ...decision, messages: insertWorkingMessage(decision.messages, message) };
671
+ } finally {
672
+ try { workPhase.end(); } catch { /* timing only */ }
673
+ }
674
+ });
675
+ return true;
676
+ }
677
+
678
+ /** Pure activation switch resolver (任务 A1): default ON, explicit false / env = kill switch. */
679
+ export function resolveActivationSwitches(config = {}, options = {}, env = process.env) {
680
+ const killed = (name) => env?.[name] === '1' || env?.[name] === 'true';
681
+ // Release default is carried by the Config schema (memoryV2.enabled=true); this runtime
682
+ // gate honours the resolved config value so partial/legacy configs stay explicit-off.
683
+ const memoryV2Enabled = options.memoryV2Enabled !== false
684
+ && config?.memoryV2?.enabled === true
685
+ && !killed('DSH_LONGLIVE_DISABLE_MEMORY_V2');
686
+ const roleEnabled = options.roleEnabled !== false
687
+ && config?.role?.enabled === true
688
+ && !killed('DSH_LONGLIVE_DISABLE_ROLE');
689
+ const answerGuardEnabled = options.answerGuardEnabled !== false
690
+ && config?.answerGuard?.enabled === true
691
+ && !killed('DSH_LONGLIVE_DISABLE_ANSWER_GUARD');
692
+ return { memoryV2Enabled, roleEnabled, answerGuardEnabled };
693
+ }
694
+
695
+ export function registerFeatures(ctx, config = {}, options = {}) {
696
+ const cfg = normalizeFeatureConfig(config);
697
+ const memoryRoot = options.memoryRoot ?? null;
698
+ const logger = loggerOf(ctx);
699
+ const warn = (message) => {
700
+ if (logger) logger.warn(message);
701
+ };
702
+ const enabled = [];
703
+ const killSwitch = (name) => process.env[name] === '1' || process.env[name] === 'true';
704
+ // 任务 activation: default ON, independent kill switch per subsystem.
705
+ // Config schema (src/config.js) defaults memoryV2.enabled / role.enabled = true, so a real host
706
+ // config arrives with enabled:true. For role the wiring is default-ON even when a caller passes a
707
+ // bare config without the role block (A1: "功能没跑起来就等于没实现"); only an explicit
708
+ // `role.enabled: false` (or DSH_LONGLIVE_DISABLE_ROLE=1) kills it.
709
+ const activation = resolveActivationSwitches(config, options);
710
+ const memoryV2On = activation.memoryV2Enabled;
711
+ const roleOn = options.roleEnabled !== false && config?.role?.enabled !== false && !killSwitch('DSH_LONGLIVE_DISABLE_ROLE');
712
+
713
+ // Not an opt-in feature: this is the operator-facing receipt required after
714
+ // every surgery. `index.js` passes text only when a state exists and its
715
+ // receipt is missing, so a clean start stays side-effect free.
716
+ if (registerSurgeryReceipt(ctx, options.surgeryReceipt, warn, { memoryRoot })) {
717
+ enabled.push('surgeryReceipt');
718
+ }
719
+
720
+ if (cfg.identityCard.enabled) {
721
+ registerIdentityCard(ctx, cfg.identityCard, memoryRoot, warn);
722
+ enabled.push('identityCard');
723
+ }
724
+
725
+ // 04 主动浮现(proactive surface):默认关闭(字面 enabled:true 才注册)。
726
+ // 独立 kill switch:DSH_LONGLIVE_DISABLE_PROACTIVE=1 → normalize 里置 enabled:false。
727
+ // 注册在 identityCard 之后 → 更外层 → 能看到 boot 卡并让位(设计 §9.1 / M-7)。
728
+ if (config?.proactive && typeof config.proactive === 'object') {
729
+ const proactiveCfg = normalizeProactiveConfig(config.proactive, {
730
+ env: process.env,
731
+ warn: (message) => warn(message),
732
+ });
733
+ if (proactiveCfg.enabled === true) {
734
+ try {
735
+ const proactive = registerProactive(ctx, proactiveCfg, {
736
+ memoryRoot,
737
+ warn,
738
+ // 测试缝(生产不配置):与 autoRecall/identityCard 的 createUserMessage 同款。
739
+ createUserMessage: typeof config.proactive.createUserMessage === 'function'
740
+ ? config.proactive.createUserMessage
741
+ : undefined,
742
+ });
743
+ if (proactive.enabled) enabled.push('proactive');
744
+ else if (proactive.reason === 'no-memory-root') {
745
+ warn('[proactive] 已开启但没有可解析的 memoryRoot — 已跳过');
746
+ }
747
+ } catch (error) {
748
+ warn(`[proactive] 注册失败(${error?.code ?? error?.message ?? error})— 已跳过,插件继续加载。`);
749
+ }
750
+ }
751
+ }
752
+
753
+ // 02 跨会话交接卡(handoff):默认关闭(字面 enabled:true 才注册);独立 kill
754
+ // switch DSH_LONGLIVE_DISABLE_HANDOFF=1 → normalizeHandoffConfig 里置 enabled:false。
755
+ // 注册顺序在 identityCard/proactive 之后、workingFrame 之前:pre-step 里它在
756
+ // boot/shared 之后 splice,workingFrame 再包一层,于是注入相对序为
757
+ // [真 user, 开机卡, 共享大脑提示, 交接卡, 工作帧, 自动想起](V6 只断言相对序)。
758
+ // 没有 memoryRoot 时 warn-skip(对齐 sharedBrain/autoMaintenance 的写法)。
759
+ if (cfg.handoff.enabled) {
760
+ if (!memoryRoot) {
761
+ warn('[longlive] handoff 已开启但没有可解析的 memoryRoot — 已跳过');
762
+ } else {
763
+ try {
764
+ const stream = registerHandoffCard(ctx, {
765
+ ...cfg.handoff,
766
+ createUserMessage: cfg.handoff.createUserMessage,
767
+ }, {
768
+ memoryRoot,
769
+ now: config.now,
770
+ // Test seams only; the host config never carries these.
771
+ privacyScan: typeof config.handoffPrivacyScan === 'function' ? config.handoffPrivacyScan : undefined,
772
+ hooks: config.handoffHooks && typeof config.handoffHooks === 'object' ? config.handoffHooks : undefined,
773
+ logger: warn,
774
+ });
775
+ if (stream.enabled) enabled.push('handoff');
776
+ } catch (error) {
777
+ warn(`[handoff] 注册失败(${error?.code ?? error?.message ?? error})— 已跳过,插件继续加载。`);
778
+ }
779
+ }
780
+ }
781
+
782
+ // v2.6.4 连续性最小集:working-frame 只随 memoryV2 开启(默认 off);
783
+ // 注册顺序在 identityCard 之后、autoRecall 之前 => 注入顺序 [boot, shared, working, recall]。
784
+ if (memoryV2On && options.workingFrame !== false) {
785
+ try {
786
+ if (registerWorkingFrame(ctx, { memoryRoot, warn, now: options.now, monoNow: options.monoNow })) {
787
+ enabled.push('workingFrame');
788
+ }
789
+ } catch (error) {
790
+ warn(`[working-frame] 注册失败(${error?.code ?? error?.message ?? error})`);
791
+ }
792
+ }
793
+
794
+ // M04:硬门 handler 恒注册(kill switch 也是注册态)。
795
+ // autoRecall.enabled=false 不再「不挂钩子」——apply() 里 handler 恒挂,交给 brain 走
796
+ // killswitch 分支:注入「硬门已被关闭(配置)」告警块 + gate-log decision=disabled。
797
+ {
798
+ const recallConfig = {
799
+ autoRecall: cfg.autoRecall.enabled !== false,
800
+ maxItems: cfg.autoRecall.topK,
801
+ budget: cfg.autoRecall.budgetTokens,
802
+ everyNTurns: cfg.autoRecall.everyNTurns,
803
+ skipSubagents: true,
804
+ log: false,
805
+ };
806
+ if (memoryRoot) recallConfig.memoryRoot = memoryRoot;
807
+ if (cfg.autoRecall.createUserMessage) recallConfig.createUserMessage = cfg.autoRecall.createUserMessage;
808
+ // A3/A4:embedding 是 autoRecall 的一个可选后端,不属于 normalizeFeatureConfig
809
+ // 的三块开关(feature-flags 的既有 deepEqual 锁死了那个输出形状)。
810
+ if (config.embedding && typeof config.embedding === 'object') recallConfig.embedding = config.embedding;
811
+ // 1.8.8 M2:强制触发 + 链路学习。两个键都从 raw profile 配置读:
812
+ // autoRecall.forceOnUserMessage(默认 true;显式 false 回落 1.8.7)
813
+ // recall.links.(默认开启;links.enabled:false 回落 1.8.7)
814
+ // 不进 normalizeFeatureConfig 的输出形状(1.8.7 的 deepEqual 锁死了那个形状),
815
+ // recall 也不声明 schemastery 节点(settings schema 节点数保持不变)。
816
+ const rawAutoRecall = config.autoRecall && typeof config.autoRecall === 'object' ? config.autoRecall : {};
817
+ if (rawAutoRecall.forceOnUserMessage !== undefined) recallConfig.forceOnUserMessage = rawAutoRecall.forceOnUserMessage;
818
+ // 2026-11-26 红队复攻 P2-5:privacyPolicy 也走 raw 透传('drop' 默认 / 'title' 只遮摘要;
819
+ // 标题与路径命中在任何策略下都整卡丢弃)。recall-core 内部归一化,其余值一律回落 drop。
820
+ if (rawAutoRecall.privacyPolicy !== undefined) recallConfig.privacyPolicy = rawAutoRecall.privacyPolicy;
821
+ const rawRecallLinks = config.recall && typeof config.recall === 'object' ? config.recall.links : null;
822
+ if (rawRecallLinks && typeof rawRecallLinks === 'object') recallConfig.links = rawRecallLinks;
823
+ // 2.0.0 W3b(M31/M32):冷档三键同走 raw 透传——archiveRoot / archiveStatePath /
824
+ // archiveFailOpen 只影响 recall 的归档兜底,不属于 normalizeFeatureConfig 的三块开关
825
+ // (feature-flags 的既有 deepEqual 锁死了那个输出形状;153 节点锁保持不变),
826
+ // recall 也不为它们声明 schemastery 节点。
827
+ const rawRecall = config.recall && typeof config.recall === 'object' ? config.recall : {};
828
+ if (typeof rawRecall.archiveRoot === 'string' && rawRecall.archiveRoot.trim() !== '') {
829
+ recallConfig.archiveRoot = rawRecall.archiveRoot;
830
+ }
831
+ if (typeof rawRecall.archiveStatePath === 'string' && rawRecall.archiveStatePath.trim() !== '') {
832
+ recallConfig.archiveStatePath = rawRecall.archiveStatePath;
833
+ }
834
+ if (rawRecall.archiveFailOpen !== undefined) recallConfig.archiveFailOpen = rawRecall.archiveFailOpen;
835
+ applyAutoRecall(ctx, recallConfig);
836
+ // The hardgate handler is always registered (kill switch is decided inside
837
+ // src/recall/index.js), but a killed recall is NOT an opt-in feature: the
838
+ // activation list and the startup log line stay byte-identical for flags-off.
839
+ if (cfg.autoRecall.enabled !== false) enabled.push('autoRecall');
840
+ }
841
+
842
+ if (cfg.presenceBus.enabled) {
843
+ registerPresenceBus(ctx, cfg.presenceBus, memoryRoot, warn);
844
+ enabled.push('presenceBus');
845
+ }
846
+
847
+ if (cfg.sharedBrain.thinkingInjection && !cfg.sharedBrain.activity.enabled) {
848
+ warn('[longlive] sharedBrain.thinkingInjection 已开启但 sharedBrain.activity.enabled=false — thinking 摘要需要活动流开启,已跳过');
849
+ }
850
+ if (cfg.sharedBrain.activity.enabled) {
851
+ if (!memoryRoot) {
852
+ warn('[longlive] sharedBrain.activity 已开启但没有可解析的 memoryRoot — 已跳过');
853
+ } else {
854
+ const stream = registerActivityStream(ctx, {
855
+ ...cfg.sharedBrain.activity,
856
+ thinkingInjection: cfg.sharedBrain.thinkingInjection,
857
+ }, {
858
+ memoryRoot,
859
+ // Test seam only; the host config never carries these.
860
+ now: config.now,
861
+ privacyScan: typeof config.activityPrivacyScan === 'function' ? config.activityPrivacyScan : undefined,
862
+ logger: warn,
863
+ });
864
+ if (stream.enabled) enabled.push('sharedBrain.activity');
865
+ }
866
+ }
867
+
868
+ if (cfg.autoMaintenance.enabled) {
869
+ if (!memoryRoot) {
870
+ warn('[longlive] autoMaintenance 已开启但没有可解析的 memoryRoot — 已跳过');
871
+ } else {
872
+ try {
873
+ // 2.0.0 W3b(⑧):每日维护/启动探针要拿冷档根与 state 路径,同样走 raw 透传。
874
+ const rawRecallArchive = config.recall && typeof config.recall === 'object' ? config.recall : {};
875
+ const archiveRootRaw = typeof rawRecallArchive.archiveRoot === 'string' && rawRecallArchive.archiveRoot.trim() !== ''
876
+ ? rawRecallArchive.archiveRoot
877
+ : null;
878
+ const archiveStatePathRaw = typeof rawRecallArchive.archiveStatePath === 'string' && rawRecallArchive.archiveStatePath.trim() !== ''
879
+ ? rawRecallArchive.archiveStatePath
880
+ : null;
881
+ const scheduler = createMaintenanceScheduler({
882
+ memoryRoot,
883
+ config: {
884
+ ...cfg.autoMaintenance,
885
+ // Host-injected session root; never derive it from an implicit
886
+ // memory root or the current machine's home.
887
+ sessionsRoot: options.sessionsRoot ?? null,
888
+ // 冷档探针槽(archive-state 写入方)的输入;未配置则为 null → 槽 not_run。
889
+ archiveRoot: archiveRootRaw,
890
+ archiveStatePath: archiveStatePathRaw,
891
+ },
892
+ // Test seam only (CONFIG.md lists `now` as internal); never a
893
+ // deployment-facing setting.
894
+ now: config.now,
895
+ timers: config.timers,
896
+ logger: warn,
897
+ });
898
+ const started = scheduler.start();
899
+ if (started?.started === false && started.reason === 'disabled') {
900
+ warn('[longlive] autoMaintenance 已开启但 consolidate/forget 都为 false — 已跳过');
901
+ } else {
902
+ if (typeof ctx.effect === 'function') {
903
+ try {
904
+ ctx.effect(() => () => scheduler.stop(), 'longlive.auto-maintenance');
905
+ } catch {
906
+ /* a fake/simple ctx may not support effect; the timer still runs */
907
+ }
908
+ }
909
+ enabled.push('autoMaintenance');
910
+ }
911
+ } catch (error) {
912
+ warn(`[longlive] autoMaintenance 启动失败(${error?.code ?? error?.message ?? error})— 已跳过`);
913
+ }
914
+ }
915
+ }
916
+
917
+ // D21(§14 接线):记忆体检每日 job —— 与 memory vault(memoryV2)同一个开关,
918
+ // 还要有 memoryRoot;单 timer(启动后轻量跑一次,此后每日本地午夜一次,同日重入跳过),
919
+ // 由 ctx.effect 释放;失败只落 health 文件 errorCodes + stderr,不写 gate 事件、不抛。
920
+ if (memoryV2On && memoryRoot) {
921
+ try {
922
+ const healthJob = registerDailyHealth({
923
+ memoryRoot,
924
+ now: config.now,
925
+ timers: config.timers,
926
+ logger: warn,
927
+ });
928
+ if (healthJob.enabled) {
929
+ healthJob.start();
930
+ if (typeof ctx.effect === 'function') {
931
+ try {
932
+ ctx.effect(() => () => healthJob.stop(), 'longlive.memory-health');
933
+ } catch {
934
+ /* a fake/simple ctx may not support effect; the timer still runs */
935
+ }
936
+ }
937
+ enabled.push('memoryHealth');
938
+ }
939
+ } catch (error) {
940
+ warn(`[longlive] memory-health 启动失败(${error?.code ?? error?.message ?? error})— 已跳过`);
941
+ }
942
+ }
943
+
944
+ // Startup health check is independent of whether the janitor is enabled:
945
+ // the panel can read the returned/status object, and an over-budget
946
+ // .longlive produces one visible warning instead of silently growing.
947
+ if (memoryRoot && config?.retention && typeof config.retention === 'object') {
948
+ try {
949
+ const health = retentionHealth(memoryRoot, config.retention);
950
+ if (health.state !== 'ok') {
951
+ warn(`[longlive] retention health=${health.state}: .longlive ${health.totalBytes}/${health.budgetBytes} bytes`);
952
+ }
953
+ } catch (error) {
954
+ warn(`[longlive] retention health check failed(${error?.code ?? error?.message ?? error})`);
955
+ }
956
+ }
957
+
958
+ // Unified retention (S5): off by default; even when enabled, dryRun defaults
959
+ // true. It gets its own timer so the existing autoMaintenance contract and
960
+ // tests (one timer when consolidation/forget are on) stay unchanged.
961
+ if (config?.retention?.enabled === true) {
962
+ if (!memoryRoot) {
963
+ warn('[longlive] retention 已开启但没有可解析的 memoryRoot — 已跳过');
964
+ } else {
965
+ try {
966
+ const retentionJob = registerRetention(ctx, {
967
+ memoryRoot,
968
+ config: config.retention,
969
+ now: config.now,
970
+ timers: config.timers,
971
+ warn,
972
+ });
973
+ if (retentionJob.enabled) enabled.push('retention');
974
+ } catch (error) {
975
+ warn(`[longlive] retention 启动失败(${error?.code ?? error?.message ?? error})— 已跳过`);
976
+ }
977
+ }
978
+ }
979
+
980
+ // v2.8 §16.3 角色内核(1.8.0 默认 ON;任务 激活门禁):
981
+ // 默认注册 hook / 落盘;显式 role.enabled:false 或 DSH_LONGLIVE_DISABLE_ROLE=1 是独立 kill
982
+ // switch(零 hook、零目录、零 IO)。子开关走 normalizeRoleConfig 的代码默认。
983
+ if (roleOn) {
984
+ try {
985
+ const roleKernel = registerRole(ctx, config, {
986
+ memoryRoot,
987
+ now: config.now,
988
+ warn,
989
+ channels: Array.isArray(config.roleChannels) ? config.roleChannels : undefined,
990
+ channelSend: typeof config.roleChannelSend === 'function' ? config.roleChannelSend : undefined,
991
+ });
992
+ if (roleKernel.enabled) enabled.push('role');
993
+ else if (roleKernel.reason === 'no-memory-root') {
994
+ warn('[longlive] role 已开启但没有可解析的 memoryRoot — 已跳过');
995
+ }
996
+ } catch (error) {
997
+ warn(`[longlive] role 装配失败(${error?.code ?? error?.message ?? error})— 已跳过`);
998
+ }
999
+ }
1000
+ // H 批 hardgate 唤醒桥(N15):常驻钩子插在 role kernel 之后、内建 working-frame 注入之后
1001
+ // (pre-step {prepend:false})。它是「后台会话工厂」而不是审查器:能力探测(auto preset +
1002
+ // 0.2.3-alpha.2)失败一律 fail-closed(0 会话 0 重试),只写 gate-log/panel 让人能看见。
1003
+ // daily 对账 timer 由 wake-bridge 自己按 nextLocalMidnight 调度,独立于 autoMaintenance。
1004
+ if (memoryRoot && config?.hardgate && typeof config.hardgate === 'object' && config.hardgate.wake && typeof config.hardgate.wake === 'object') {
1005
+ try {
1006
+ const wakeHandle = registerHardgateWake(ctx, config.hardgate.wake, {
1007
+ memoryRoot,
1008
+ now: typeof config.now === 'function' ? config.now : undefined,
1009
+ timers: config.timers,
1010
+ env: process.env,
1011
+ warn,
1012
+ installToolPolicy: typeof config.hardgateWakeInstallToolPolicy === 'function' ? config.hardgateWakeInstallToolPolicy : undefined,
1013
+ });
1014
+ if (wakeHandle && typeof wakeHandle.dispose === 'function') {
1015
+ try {
1016
+ ctx.effect(() => () => wakeHandle.dispose(), 'longlive.hardgate-wake');
1017
+ } catch {
1018
+ /* a fake/simple ctx may not support effect; the handle still disposes on demand */
1019
+ }
1020
+ }
1021
+ if (wakeHandle?.enabled) enabled.push('hardgate.wake');
1022
+ else if (wakeHandle?.registered === true) {
1023
+ // 钩子已装但能力暂缺:可见 warning,不在下一轮静默重试(drain 自带 enabled 门)。
1024
+ warn(`[longlive] hardgate.wake 未启用(${wakeHandle.code ?? 'capability-missing'}: ${wakeHandle.detail?.reason ?? 'unknown'})— fail-closed`);
1025
+ }
1026
+ } catch (error) {
1027
+ warn(`[longlive] hardgate.wake 装配失败(${error?.code ?? error?.message ?? error})— 已跳过`);
1028
+ }
1029
+ }
1030
+
1031
+ if (enabled.length > 0 && logger && typeof logger.info === 'function') {
1032
+ logger.info(`[longlive] opt-in features: ${enabled.join(', ')}`);
1033
+ }
1034
+ return { enabled, config: cfg };
1035
+ }