@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,1077 @@
1
+ // src/handoff/index.js — cross-session handoff card wiring (02, v4).
2
+ //
3
+ // Producer (`session/event`): after every completed turn, merge a locally
4
+ // extracted delta (goal / decided / open / next / lastAction) into the
5
+ // source session's per-session latest card under
6
+ // `<memoryRoot>/.longlive/bridge/<safeSrc>.handoff-card.json`. Local rules
7
+ // only — no model call, no session-log scan. Only user-authored messages are
8
+ // carried (`isUserAuthoredMessage`), so an injected card can never become the
9
+ // next card's goal ("card begets card").
10
+ //
11
+ // Consumer (`agent/pre-step`, step 1 / turn 1): read at most `maxIndexFiles`
12
+ // latest cards, run the five gates (cwd → liveness → relevance/substance/
13
+ // continuation-intent → budget → claim), then splice ONE hidden ≤281-code-point
14
+ // message into the first-step payload. per-session O_EXCL claim makes it
15
+ // once-per-session across processes; the per-card claim is pid-recoverable
16
+ // before the splice and fail-closed afterwards. Anything unreadable/unjudgeable
17
+ // simply does not inject (fail-closed); a turn is never blocked.
18
+ //
19
+ // Default OFF: `handoff.enabled` must be the literal boolean `true` (or the
20
+ // profile config row must carry it); `DSH_LONGLIVE_DISABLE_HANDOFF=1|true` is
21
+ // the independent kill switch. `dryRun:true` selects/audits but never claims or
22
+ // injects, so a first enablement can be watched before the real switch.
23
+
24
+ import fs from 'node:fs';
25
+ import path from 'node:path';
26
+
27
+ import { isSubagentSession } from '../identity/index.js';
28
+ import { isUserAuthoredMessage } from '../truncate-visible.js';
29
+ import { privacyScan as defaultPrivacyScan } from '../recall/privacy.mjs';
30
+ import { notePrestepDegrade, startPrestepPhase } from '../metrics/prestep-latency.mjs';
31
+ import { messageTextOf, toolSummaryOf } from '../activity/index.js';
32
+ import {
33
+ assertInjectionSource,
34
+ injectionSource,
35
+ insertionIndex,
36
+ isHumanMessage,
37
+ isInjectedMessage,
38
+ textOfMessage,
39
+ } from '../identity/inject-position.js';
40
+ import {
41
+ AUDIT_SCHEMA,
42
+ HANDOFF_ANCHOR_MAX_CHARS,
43
+ HANDOFF_DECIDED_MAX,
44
+ HANDOFF_FOOTER,
45
+ HANDOFF_HEAD_RE,
46
+ HANDOFF_INTENT_SEMANTICS,
47
+ HANDOFF_MAX_CHARS,
48
+ HANDOFF_MIN_CHARS,
49
+ HANDOFF_RENDER_MAX,
50
+ HANDOFF_SCHEMA,
51
+ charLengthOf,
52
+ contentHashOf,
53
+ buildCardDelta,
54
+ cardIdOf,
55
+ cardSubstantive,
56
+ hash8,
57
+ isActiveSessionId,
58
+ mergeLatestCard,
59
+ renderHandoffCard,
60
+ sanitizeCardFields,
61
+ selectCandidate,
62
+ summarizeHandoffCard,
63
+ } from './model.js';
64
+ import {
65
+ appendAudit,
66
+ claimCard,
67
+ claimSession,
68
+ finalizeCardClaim,
69
+ finalizeSessionClaim,
70
+ handoffArchiveFile,
71
+ handoffAuditFile,
72
+ latestCardFile,
73
+ markCardSpliced,
74
+ maybeTrimAuditBoard,
75
+ pruneCards,
76
+ pruneClaims,
77
+ readHandoffBoard,
78
+ readLatestCard,
79
+ readLatestCards,
80
+ readLiveRow,
81
+ releaseCardClaim,
82
+ releaseSessionClaim,
83
+ resetTrimThrottle,
84
+ sessionClaimFile,
85
+ writeLatestCardAtomic,
86
+ } from './store.js';
87
+
88
+ // ------------------------------------------------------------------ config (§8)
89
+
90
+ export const HANDOFF_DEFAULTS = Object.freeze({
91
+ enabled: false, // hard constraint ①: never changes 1.8.3 behaviour unless opted in
92
+ dryRun: false,
93
+ maxChars: HANDOFF_MAX_CHARS,
94
+ maxAgeHours: 24,
95
+ firstTurnOnly: true,
96
+ inject: true,
97
+ write: true,
98
+ decidedMax: HANDOFF_DECIDED_MAX,
99
+ relevanceContainShort: 0.4,
100
+ relevanceDiceLong: 0.2,
101
+ intentBypass: true,
102
+ intentFreshMinutes: 60,
103
+ intentSemantics: HANDOFF_INTENT_SEMANTICS,
104
+ maxIndexFiles: 64,
105
+ auditWindowRows: 500,
106
+ privacyScan: true,
107
+ trimMinIntervalMs: 60_000,
108
+ });
109
+
110
+ function clampNumber(value, fallback, min, max) {
111
+ const number = Number(value);
112
+ if (!Number.isFinite(number)) return fallback;
113
+ return Math.min(max, Math.max(min, number));
114
+ }
115
+
116
+ function clampInt(value, fallback, min, max) {
117
+ return Math.floor(clampNumber(value, fallback, min, max));
118
+ }
119
+
120
+ /**
121
+ * Normalise the `handoff` config block. Bad values never throw (a typo cannot
122
+ * keep the plugin from loading); `enabled` stays OFF unless it is literally
123
+ * `true`, and the env kill switch wins over everything.
124
+ */
125
+ export function normalizeHandoffConfig(input = {}, options = {}) {
126
+ const raw = input && typeof input === 'object' ? input : {};
127
+ const env = options && typeof options.env === 'object' && options.env !== null ? options.env : process.env;
128
+ const disabledByEnv = env?.DSH_LONGLIVE_DISABLE_HANDOFF === '1' || env?.DSH_LONGLIVE_DISABLE_HANDOFF === 'true';
129
+ const boolOr = (value, fallback) => (typeof value === 'boolean' ? value : fallback);
130
+ const semantics = raw.intentSemantics === 'latest' ? 'latest' : HANDOFF_INTENT_SEMANTICS;
131
+ return {
132
+ enabled: disabledByEnv ? false : raw.enabled === true,
133
+ dryRun: raw.dryRun === true,
134
+ maxChars: clampInt(raw.maxChars, HANDOFF_DEFAULTS.maxChars, HANDOFF_MIN_CHARS, HANDOFF_MAX_CHARS),
135
+ maxAgeHours: clampInt(raw.maxAgeHours, HANDOFF_DEFAULTS.maxAgeHours, 1, 168),
136
+ firstTurnOnly: boolOr(raw.firstTurnOnly, HANDOFF_DEFAULTS.firstTurnOnly),
137
+ inject: boolOr(raw.inject, HANDOFF_DEFAULTS.inject),
138
+ write: boolOr(raw.write, HANDOFF_DEFAULTS.write),
139
+ decidedMax: clampInt(raw.decidedMax, HANDOFF_DEFAULTS.decidedMax, 1, HANDOFF_DECIDED_MAX),
140
+ relevanceContainShort: clampNumber(raw.relevanceContainShort, HANDOFF_DEFAULTS.relevanceContainShort, 0.2, 0.8),
141
+ relevanceDiceLong: clampNumber(raw.relevanceDiceLong, HANDOFF_DEFAULTS.relevanceDiceLong, 0.1, 0.6),
142
+ intentBypass: boolOr(raw.intentBypass, HANDOFF_DEFAULTS.intentBypass),
143
+ intentFreshMinutes: clampInt(raw.intentFreshMinutes, HANDOFF_DEFAULTS.intentFreshMinutes, 10, 180),
144
+ intentSemantics: semantics,
145
+ maxIndexFiles: clampInt(raw.maxIndexFiles, HANDOFF_DEFAULTS.maxIndexFiles, 8, 256),
146
+ auditWindowRows: clampInt(raw.auditWindowRows, HANDOFF_DEFAULTS.auditWindowRows, 100, 2000),
147
+ privacyScan: boolOr(raw.privacyScan, HANDOFF_DEFAULTS.privacyScan),
148
+ trimMinIntervalMs: clampInt(raw.trimMinIntervalMs, HANDOFF_DEFAULTS.trimMinIntervalMs, 0, 3_600_000),
149
+ createUserMessage: typeof raw.createUserMessage === 'function' ? raw.createUserMessage : undefined,
150
+ killSwitch: disabledByEnv,
151
+ };
152
+ }
153
+
154
+ // ------------------------------------------------------------------ small helpers
155
+
156
+ function nowFnOf(value) {
157
+ if (typeof value === 'function') {
158
+ return () => {
159
+ const produced = value();
160
+ return produced instanceof Date ? produced : new Date(Number.isFinite(produced) ? produced : Date.now());
161
+ };
162
+ }
163
+ if (value instanceof Date || Number.isFinite(value)) {
164
+ const frozen = value instanceof Date ? value.getTime() : Number(value);
165
+ return () => new Date(frozen);
166
+ }
167
+ return () => new Date();
168
+ }
169
+
170
+ function headerOf(payload) {
171
+ const agent = payload?.agent;
172
+ return agent?.session?.header ?? agent?.header ?? payload?.session?.header ?? {};
173
+ }
174
+
175
+ function sessionObjectOf(payload) {
176
+ const agent = payload?.agent;
177
+ return agent?.session ?? payload?.session ?? null;
178
+ }
179
+
180
+ function preStepSessionId(payload) {
181
+ const header = headerOf(payload);
182
+ const agent = payload?.agent;
183
+ const raw = header.id ?? agent?.sessionId ?? sessionObjectOf(payload)?.id ?? payload?.sessionId;
184
+ if (typeof raw !== 'string') return '';
185
+ const id = raw.trim().toLowerCase();
186
+ return isActiveSessionId(id) ? id : '';
187
+ }
188
+
189
+ function sessionIdOfEvent(session, event) {
190
+ const raw = session?.id ?? session?.header?.id ?? event?.sessionId ?? '';
191
+ if (typeof raw !== 'string') return '';
192
+ const id = raw.trim().toLowerCase();
193
+ return isActiveSessionId(id) ? id : '';
194
+ }
195
+
196
+ function firstLineOf(text) {
197
+ return String(text ?? '').trimStart().split('\n', 1)[0]?.trim() ?? '';
198
+ }
199
+
200
+ function warnOnceFactory(logger) {
201
+ const seen = new Set();
202
+ return (key, message) => {
203
+ if (seen.has(key)) return;
204
+ seen.add(key);
205
+ try {
206
+ logger(message);
207
+ } catch {
208
+ /* logging must never break a turn */
209
+ }
210
+ };
211
+ }
212
+
213
+ async function resolveCreateUserMessage(explicit) {
214
+ if (typeof explicit === 'function') return explicit;
215
+ try {
216
+ const mod = await import('@deepseek-ai/dsh-llm');
217
+ return typeof mod?.createUserMessage === 'function' ? mod.createUserMessage : null;
218
+ } catch {
219
+ return null;
220
+ }
221
+ }
222
+
223
+ function compactTrace(trace) {
224
+ if (!Array.isArray(trace)) return [];
225
+ return trace.slice(0, 8).map((entry) => ({
226
+ sessionId: entry?.sessionId ?? null,
227
+ cardId: entry?.cardId ?? null,
228
+ code: entry?.code ?? null,
229
+ skipped: entry?.skipped ?? null,
230
+ cwd: entry?.gates?.cwd === true,
231
+ live: entry?.gates?.live ?? null,
232
+ relevance: entry?.gates?.relevance
233
+ ? {
234
+ kind: entry.gates.relevance.kind,
235
+ score: entry.gates.relevance.score,
236
+ field: entry.gates.relevance.field,
237
+ threshold: entry.gates.relevance.threshold,
238
+ pass: entry.gates.relevance.pass,
239
+ ...(entry.gates.relevance.intent ? { intent: entry.gates.relevance.intent } : {}),
240
+ }
241
+ : null,
242
+ }));
243
+ }
244
+
245
+ // ------------------------------------------------------------------ handoffSummary (M24)
246
+
247
+ function summaryFileName(atMs) {
248
+ const date = new Date(Number.isFinite(atMs) ? atMs : Date.now());
249
+ const day = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
250
+ return `${day}-handoff.md`;
251
+ }
252
+
253
+ /**
254
+ * 把最新交接卡提炼成 1–2 行,落到 `<memoryRoot>/handover/<YYYY-MM-DD>-handoff.md`。
255
+ * 承接链路:handoff 生产侧 → handover 卡(markdown)→ identityCard「▍交接卡」节
256
+ * (A 批 M04 已实装读取侧)。只写摘要,不复制卡里其它字段。
257
+ */
258
+ export function writeHandoffSummary(input = {}) {
259
+ const root = typeof input?.memoryRoot === 'string' && input.memoryRoot.trim() !== ''
260
+ ? path.resolve(input.memoryRoot)
261
+ : '';
262
+ if (root === '') return { ok: false, code: 'E_HANDOFF_NO_MEMORY_ROOT', file: null, text: '' };
263
+ const nowMs = typeof input.now === 'number' && Number.isFinite(input.now)
264
+ ? input.now
265
+ : (input.now instanceof Date && Number.isFinite(input.now.getTime()) ? input.now.getTime() : Date.now());
266
+ const summary = summarizeHandoffCard(input.card);
267
+ if (!summary.ok) return { ok: false, code: 'E_HANDOFF_SUMMARY_EMPTY', file: null, text: '', lines: [] };
268
+ const dir = path.join(root, 'handover');
269
+ const file = path.join(dir, summaryFileName(nowMs));
270
+ try {
271
+ fs.mkdirSync(dir, { recursive: true });
272
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
273
+ fs.writeFileSync(tmp, `${summary.text}\n`, 'utf8');
274
+ fs.renameSync(tmp, file);
275
+ } catch (error) {
276
+ return { ok: false, code: error?.code ?? 'E_HANDOFF_WRITE', file, text: summary.text, lines: summary.lines };
277
+ }
278
+ return { ok: true, file, text: summary.text, lines: summary.lines, chars: summary.chars };
279
+ }
280
+
281
+ /**
282
+ * 读取当前最新交接卡并返回 1–2 行 handoffSummary(只读;无卡/无实质内容如实返回空)。
283
+ * 主源:`<memoryRoot>/.longlive/bridge/*.handoff-card.json`;回退源:`<memoryRoot>/handover/*.json`
284
+ * (旧口径/夹具把卡直接落在 handover 目录;只接受 cardSubstantive 为真的卡)。
285
+ * 返回 { ok, code, text, summary, lines, chars, cardId, at, source }。
286
+ */
287
+ export function handoffSummary(input = {}) {
288
+ const root = typeof input?.memoryRoot === 'string' && input.memoryRoot.trim() !== ''
289
+ ? path.resolve(input.memoryRoot)
290
+ : '';
291
+ if (root === '') return { ok: false, code: 'E_HANDOFF_NO_MEMORY_ROOT', text: '', lines: [] };
292
+ const read = readLatestCards(root, { maxFiles: 64 });
293
+ let cards = read.ok
294
+ ? (Array.isArray(read.cards) ? read.cards : []).filter((entry) => cardSubstantive(entry.card))
295
+ : [];
296
+ if (cards.length === 0) cards = readHandoverJsonCards(root);
297
+ if (cards.length === 0) return { ok: false, code: 'E_HANDOFF_SUMMARY_EMPTY', text: '', lines: [], cards: 0 };
298
+ const entry = cards[0];
299
+ const summary = summarizeHandoffCard(entry.card);
300
+ return {
301
+ ok: summary.ok,
302
+ code: summary.ok ? null : summary.code,
303
+ text: summary.text,
304
+ summary: summary.text,
305
+ lines: summary.lines,
306
+ chars: summary.chars,
307
+ cardId: entry.cardId,
308
+ at: entry.card?.at ?? null,
309
+ source: {
310
+ sessionId: entry.card?.source?.sessionId ?? null,
311
+ turn: entry.card?.turn ?? null,
312
+ },
313
+ };
314
+ }
315
+
316
+ /** handover 目录里的卡 JSON 回退源(mtime 降序,只留 cardSubstantive)。 */
317
+ function readHandoverJsonCards(root) {
318
+ const dir = path.join(root, 'handover');
319
+ let entries = [];
320
+ try {
321
+ entries = fs.readdirSync(dir, { withFileTypes: true });
322
+ } catch {
323
+ return [];
324
+ }
325
+ const cards = [];
326
+ for (const entry of entries) {
327
+ if (!entry.isFile() || !/\.json$/iu.test(entry.name) || entry.name.startsWith('.')) continue;
328
+ const file = path.join(dir, entry.name);
329
+ let stat;
330
+ try {
331
+ stat = fs.statSync(file);
332
+ } catch {
333
+ continue;
334
+ }
335
+ let card;
336
+ try {
337
+ card = JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
338
+ } catch {
339
+ continue;
340
+ }
341
+ if (!cardSubstantive(card)) continue;
342
+ cards.push({
343
+ card,
344
+ cardId: cardIdOf({ sessionId: card?.source?.sessionId, turn: card?.turn }),
345
+ file,
346
+ mtimeMs: stat.mtimeMs,
347
+ });
348
+ }
349
+ cards.sort((left, right) => right.mtimeMs - left.mtimeMs);
350
+ return cards;
351
+ }
352
+
353
+ // ------------------------------------------------------------------ stream
354
+
355
+ /**
356
+ * Build the handoff stream. Everything is injected (memoryRoot / now /
357
+ * privacyScan / createUserMessage / hooks) so tests drive the exact same code
358
+ * path the host hooks use.
359
+ */
360
+ export function createHandoffStream(options = {}) {
361
+ const cfg = normalizeHandoffConfig(options.cfg ?? options);
362
+ const rawRoot = typeof options.memoryRoot === 'string' && options.memoryRoot.trim() !== ''
363
+ ? options.memoryRoot
364
+ : (typeof options.cfg?.memoryRoot === 'string' ? options.cfg.memoryRoot : null);
365
+ let memoryRoot = null;
366
+ try {
367
+ memoryRoot = rawRoot === null ? null : path.resolve(rawRoot);
368
+ } catch {
369
+ memoryRoot = null;
370
+ }
371
+ const now = nowFnOf(options.now);
372
+ const logger = typeof options.logger === 'function' ? options.logger : () => {};
373
+ const warnOnce = warnOnceFactory(logger);
374
+ const privacyGate = cfg.privacyScan
375
+ ? (typeof options.privacyScan === 'function' ? options.privacyScan : defaultPrivacyScan)
376
+ : null;
377
+ const hooks = options.hooks && typeof options.hooks === 'object' ? options.hooks : {};
378
+ const explicitFactory = typeof options.createUserMessage === 'function'
379
+ ? options.createUserMessage
380
+ : (typeof cfg.createUserMessage === 'function' ? cfg.createUserMessage : undefined);
381
+ const hook = (name) => (ctx) => {
382
+ const fn = hooks[name];
383
+ if (typeof fn !== 'function') return;
384
+ fn(ctx);
385
+ };
386
+ const maxAgeMs = cfg.maxAgeHours * 3600 * 1000;
387
+ const enabled = cfg.enabled === true && memoryRoot !== null;
388
+ const sessions = new Map();
389
+ const fired = new Set();
390
+ const stats = {
391
+ turns: 0,
392
+ events: 0,
393
+ writeOk: 0,
394
+ writeSkip: 0,
395
+ cards: 0,
396
+ injected: 0,
397
+ skipped: 0,
398
+ skippedByCode: {},
399
+ gateSkip: 0,
400
+ claims: 0,
401
+ errors: 0,
402
+ lastError: null,
403
+ };
404
+
405
+ function nowMs() {
406
+ return now().getTime();
407
+ }
408
+
409
+ function countSkip(code) {
410
+ stats.skipped += 1;
411
+ const key = code ?? 'none';
412
+ stats.skippedByCode[key] = (stats.skippedByCode[key] ?? 0) + 1;
413
+ }
414
+
415
+ function audit(op, fields) {
416
+ try {
417
+ return appendAudit(memoryRoot, {
418
+ schema: AUDIT_SCHEMA,
419
+ op,
420
+ at: new Date(nowMs()).toISOString(),
421
+ ...fields,
422
+ });
423
+ } catch (error) {
424
+ stats.errors += 1;
425
+ stats.lastError = { code: error?.code ?? 'E_HANDOFF_WRITE', at: new Date(nowMs()).toISOString() };
426
+ return { ok: false, code: error?.code ?? 'E_HANDOFF_WRITE' };
427
+ }
428
+ }
429
+
430
+ function auditSkip(sessionId, code, extra = {}) {
431
+ countSkip(code);
432
+ return audit('skip', { sessionId, code, ...extra });
433
+ }
434
+
435
+ function auditWriteSkip(sessionId, turn, code, card) {
436
+ stats.writeSkip += 1;
437
+ return audit('write-skip', {
438
+ sessionId,
439
+ turn,
440
+ cardId: cardIdOf({ sessionId, turn }),
441
+ code,
442
+ goalChars: charLengthOf(card?.goal ?? ''),
443
+ goalHash: hash8(card?.goal ?? ''),
444
+ decidedN: Array.isArray(card?.decided) ? card.decided.length : 0,
445
+ substantiveChars: card?.substantiveChars ?? 0,
446
+ });
447
+ }
448
+
449
+ // M23:交接质量门。垃圾/薄卡不产卡,只记审计事件(op='gate',code=E_HANDOFF_CARD_TOO_THIN)。
450
+ function auditGate(sessionId, turn, code, card) {
451
+ stats.gateSkip += 1;
452
+ return audit('gate', {
453
+ sessionId,
454
+ turn,
455
+ gate: 'handoff',
456
+ cardId: cardIdOf({ sessionId, turn }),
457
+ code,
458
+ goalChars: charLengthOf(card?.goal ?? ''),
459
+ decidedN: Array.isArray(card?.decided) ? card.decided.length : 0,
460
+ substantiveChars: card?.substantiveChars ?? 0,
461
+ });
462
+ }
463
+
464
+ // ---- producer -----------------------------------------------------------
465
+
466
+ function stateFor(sessionId) {
467
+ let state = sessions.get(sessionId);
468
+ if (!state) {
469
+ state = { sessionId, turn: null, userText: '', assistantText: '', tool: null, cwd: null, completedTurns: 0 };
470
+ sessions.set(sessionId, state);
471
+ }
472
+ return state;
473
+ }
474
+
475
+ function produce(state, turn, atMs) {
476
+ const cwd = typeof state.cwd === 'string' ? state.cwd.trim() : '';
477
+ if (cwd === '') {
478
+ warnOnce('no-cwd', '[handoff] 生产侧取不到 session.header.cwd — 本轮不写卡(E_HANDOFF_NO_CWD)。');
479
+ return auditWriteSkip(state.sessionId, turn, 'E_HANDOFF_NO_CWD', null);
480
+ }
481
+ const oldRead = readLatestCard(memoryRoot, state.sessionId);
482
+ const oldCard = oldRead.ok && oldRead.present ? oldRead.card : null;
483
+ if (oldRead.ok === false && oldRead.present) {
484
+ audit('write-skip', {
485
+ sessionId: state.sessionId,
486
+ turn,
487
+ code: 'E_HANDOFF_CORRUPT',
488
+ note: 'old-card-unreadable',
489
+ });
490
+ }
491
+ const delta = buildCardDelta({
492
+ turn,
493
+ userText: state.userText,
494
+ assistantText: state.assistantText,
495
+ tool: state.tool,
496
+ // `completed` here means "the assistant says the work is finished" (N10),
497
+ // not merely "the turn ended with reason=completed".
498
+ });
499
+ const sanitized = sanitizeCardFields(delta, { privacyScan: privacyGate });
500
+ const merged = mergeLatestCard(oldCard, {
501
+ ...sanitized,
502
+ turn,
503
+ // completedTurns counts every completed turn of this session, including
504
+ // the no-delta ACK turns whose card write is skipped (V3 expects 3 after
505
+ // three completed rounds even when the middle one wrote nothing).
506
+ completedTurns: Math.max(state.completedTurns, (oldCard?.source?.completedTurns ?? 0) + 1),
507
+ sessionId: state.sessionId,
508
+ cwd,
509
+ cwdHash: hash8(cwd),
510
+ at: new Date(atMs).toISOString(),
511
+ });
512
+ if (merged.replay) return { written: false, skipped: 'replay' };
513
+ if (merged.empty) return auditWriteSkip(state.sessionId, turn, 'E_HANDOFF_EMPTY', merged.card);
514
+ if (merged.trivial) return auditWriteSkip(state.sessionId, turn, 'E_HANDOFF_TRIVIAL', merged.card);
515
+ if (!merged.changed) return auditWriteSkip(state.sessionId, turn, 'E_HANDOFF_NO_DELTA', merged.card);
516
+ // M23(DESIGN §2 G 行 / §3):trivial 与薄卡一律不产卡;质量门必须先于写入。
517
+ if (!cardSubstantive(merged.card)) return auditGate(state.sessionId, turn, 'E_HANDOFF_CARD_TOO_THIN', merged.card);
518
+ // Bounded maintenance rides on the write path (N3/M4).
519
+ try { pruneCards(memoryRoot, { now: atMs, maxAgeMs }); } catch { /* best effort */ }
520
+ try { pruneClaims(memoryRoot, { now: atMs, maxAgeMs }); } catch { /* best effort */ }
521
+ const written = writeLatestCardAtomic(memoryRoot, merged.card);
522
+ if (!written.ok) {
523
+ stats.errors += 1;
524
+ stats.lastError = { code: written.code ?? 'E_HANDOFF_WRITE', at: new Date(atMs).toISOString() };
525
+ return audit('write', {
526
+ sessionId: state.sessionId,
527
+ turn,
528
+ cardId: cardIdOf({ sessionId: state.sessionId, turn }),
529
+ code: written.code ?? 'E_HANDOFF_WRITE',
530
+ ok: false,
531
+ });
532
+ }
533
+ stats.writeOk += 1;
534
+ stats.cards = Math.max(stats.cards, 1);
535
+ // M24:承接 —— 卡写成后同步 1–2 行 handoffSummary,供 identityCard「▍交接卡」注入。
536
+ try {
537
+ writeHandoffSummary({ memoryRoot, card: merged.card, now: atMs });
538
+ } catch { /* 摘要承接是尽力而为,失败不影响卡本身 */ }
539
+ return audit('write', {
540
+ sessionId: state.sessionId,
541
+ turn,
542
+ cardId: cardIdOf({ sessionId: state.sessionId, turn }),
543
+ cwdHash: merged.card.source.cwdHash,
544
+ goalChars: charLengthOf(merged.card.goal),
545
+ goalHash: hash8(merged.card.goal),
546
+ decidedN: merged.card.decided.length,
547
+ substantiveChars: merged.card.substantiveChars,
548
+ chars: merged.card.substantiveChars,
549
+ });
550
+ }
551
+
552
+ function onSessionEvent(session, event) {
553
+ if (!enabled || cfg.write !== true) return;
554
+ try {
555
+ const type = event?.type;
556
+ if (typeof type !== 'string') return;
557
+ if (isSubagentSession(session)) return; // M8/N7
558
+ const sessionId = sessionIdOfEvent(session, event);
559
+ if (type === 'session/disposed') {
560
+ if (sessionId !== '') sessions.delete(sessionId);
561
+ return;
562
+ }
563
+ if (sessionId === '') return;
564
+ const state = stateFor(sessionId);
565
+ const header = session?.header ?? session?.session?.header ?? {};
566
+ if (typeof header.cwd === 'string' && header.cwd.trim() !== '') {
567
+ const nextCwd = header.cwd.trim();
568
+ if (state.cwd !== null && state.cwd !== nextCwd) {
569
+ // E_HANDOFF_CWD_DRIFT: same session id, different cwd (abnormal). Audit
570
+ // it and use the new value; the cwd gate compares against the card.
571
+ audit('write-skip', { sessionId, code: 'E_HANDOFF_CWD_DRIFT' });
572
+ }
573
+ state.cwd = nextCwd;
574
+ }
575
+
576
+ if (type === 'turn/start') {
577
+ const turn = event?.data?.turn;
578
+ state.turn = Number.isInteger(turn) ? turn : state.turn;
579
+ state.userText = '';
580
+ state.assistantText = '';
581
+ state.tool = null;
582
+ return;
583
+ }
584
+ if (type === 'user/message') {
585
+ // N9: only a host-proven user-authored message may become a card goal.
586
+ if (!isUserAuthoredMessage(event)) return;
587
+ const text = messageTextOf(event);
588
+ if (text !== '') state.userText = text;
589
+ return;
590
+ }
591
+ if (type === 'assistant/message') {
592
+ const data = event?.data ?? {};
593
+ const turn = data.turn;
594
+ if (Number.isInteger(turn) && Number.isInteger(state.turn) && turn !== state.turn) return;
595
+ const text = messageTextOf(event);
596
+ if (text !== '') state.assistantText = text;
597
+ return;
598
+ }
599
+ if (type === 'tool/call') {
600
+ state.tool = { ...toolSummaryOf(event?.data), isError: false };
601
+ return;
602
+ }
603
+ if (type === 'tool/result') {
604
+ const data = event?.data ?? {};
605
+ const message = data.message && typeof data.message === 'object' ? data.message : data;
606
+ const isError = message?.isError === true || data.isError === true;
607
+ if (isError) {
608
+ if (!state.tool && typeof data.name === 'string' && data.name.trim() !== '') {
609
+ state.tool = { ...toolSummaryOf(data), isError: true };
610
+ }
611
+ if (state.tool) state.tool.isError = true;
612
+ }
613
+ return;
614
+ }
615
+ if (type === 'turn/end') {
616
+ const turn = event?.data?.turn;
617
+ const reason = typeof event?.data?.reason?.kind === 'string'
618
+ ? event.data.reason.kind.trim().toLowerCase()
619
+ : '';
620
+ const resolved = Number.isInteger(turn) ? turn : state.turn;
621
+ stats.turns += 1;
622
+ if (reason === 'completed' && Number.isInteger(resolved) && resolved > 0) {
623
+ state.completedTurns += 1;
624
+ produce(state, resolved, nowMs());
625
+ }
626
+ state.userText = '';
627
+ state.assistantText = '';
628
+ state.tool = null;
629
+ state.turn = Number.isInteger(resolved) ? resolved : null;
630
+ }
631
+ } catch (error) {
632
+ stats.errors += 1;
633
+ stats.lastError = { code: error?.code ?? 'E_HANDOFF_PRODUCER', at: new Date(nowMs()).toISOString() };
634
+ }
635
+ }
636
+
637
+ // ---- consumer -----------------------------------------------------------
638
+
639
+ function skipResult(skipped, decision, extra = {}) {
640
+ const code = typeof extra.code === 'string'
641
+ ? extra.code
642
+ : (typeof skipped === 'string' && skipped.startsWith('E_') ? skipped : null);
643
+ const { code: _ignored, ...rest } = extra;
644
+ void _ignored;
645
+ return { injected: false, skipped, code, decision, ...rest };
646
+ }
647
+
648
+ async function injectOnce(payload, next) {
649
+ const pass = typeof next === 'function'
650
+ ? next
651
+ : async () => ({ kind: 'ok', messages: payload?.messages });
652
+ if (!enabled || cfg.inject !== true) {
653
+ return skipResult('disabled', await pass());
654
+ }
655
+ if (Number(payload?.step) !== 1) return skipResult('not-step-1', await pass());
656
+ if (cfg.firstTurnOnly && payload?.turn !== 1) return skipResult('not-first-turn', await pass());
657
+ const sessionId = preStepSessionId(payload);
658
+ if (sessionId === '') return skipResult('no-session', await pass());
659
+ if (isSubagentSession({ header: headerOf(payload) })) return skipResult('subagent', await pass());
660
+ if (isSubagentSession(sessionObjectOf(payload))) return skipResult('subagent', await pass());
661
+ const messages = payload?.messages;
662
+ if (!Array.isArray(messages)) return skipResult('no-messages', await pass());
663
+ if (fired.has(sessionId)) {
664
+ auditSkip(sessionId, 'E_HANDOFF_ALREADY_FIRED');
665
+ return skipResult('already-fired', await pass());
666
+ }
667
+ const anchorMessage = messages.find((message) => isHumanMessage(message));
668
+ if (!anchorMessage) {
669
+ auditSkip(sessionId, 'E_HANDOFF_NO_ANCHOR');
670
+ notePrestepDegrade(sessionId, payload?.turn, { kind: 'handoff-skip', phase: 'handoff', detail: 'E_HANDOFF_NO_ANCHOR' });
671
+ return skipResult('no-anchor', await pass());
672
+ }
673
+ const anchorText = textOfMessage(anchorMessage);
674
+ // m6: never inject a second card into a context that already has one.
675
+ const alreadyInContext = messages.some((message) => isInjectedMessage(message)
676
+ && HANDOFF_HEAD_RE.test(firstLineOf(textOfMessage(message))));
677
+ if (alreadyInContext) {
678
+ auditSkip(sessionId, 'E_HANDOFF_ALREADY_IN_CONTEXT');
679
+ return skipResult('already-in-context', await pass(), { code: 'E_HANDOFF_ALREADY_IN_CONTEXT' });
680
+ }
681
+ const header = headerOf(payload);
682
+ const selfCwd = typeof header.cwd === 'string' ? header.cwd : '';
683
+ const atMs = nowMs();
684
+ const listing = readLatestCards(memoryRoot, { maxFiles: cfg.maxIndexFiles });
685
+ if (!listing.ok) {
686
+ auditSkip(sessionId, listing.code ?? 'E_HANDOFF_READ');
687
+ return skipResult('read-failed', await pass());
688
+ }
689
+ if (listing.cards.length === 0) {
690
+ auditSkip(sessionId, 'E_HANDOFF_NO_CARD');
691
+ return skipResult('no-card', await pass());
692
+ }
693
+ const selection = selectCandidate({
694
+ cards: listing.cards,
695
+ selfSessionId: sessionId,
696
+ selfCwd,
697
+ nowMs: atMs,
698
+ maxAgeMs,
699
+ liveOf: (sourceSessionId) => readLiveRow(memoryRoot, sourceSessionId, { now: atMs }),
700
+ anchorText,
701
+ intentBypass: cfg.intentBypass,
702
+ intentSemantics: cfg.intentSemantics,
703
+ intentFreshMs: cfg.intentFreshMinutes * 60 * 1000,
704
+ relevanceContainShort: cfg.relevanceContainShort,
705
+ relevanceDiceLong: cfg.relevanceDiceLong,
706
+ });
707
+ const gatesForAudit = {
708
+ candidates: compactTrace(selection.trace),
709
+ intent: selection.intent ?? null,
710
+ };
711
+ if (!selection.card) {
712
+ const code = selection.code ?? 'E_HANDOFF_IRRELEVANT';
713
+ auditSkip(sessionId, code, {
714
+ gates: gatesForAudit,
715
+ targetSessionId: selection.trace?.[0]?.sessionId ?? null,
716
+ });
717
+ notePrestepDegrade(sessionId, payload?.turn, { kind: 'handoff-skip', phase: 'handoff', detail: code });
718
+ return skipResult(code, await pass(), { gates: gatesForAudit });
719
+ }
720
+ const chosenTrace = (selection.trace ?? []).find((entry) => entry.cardId === selection.cardId) ?? null;
721
+ const injectGates = {
722
+ cwd: true,
723
+ live: chosenTrace?.gates?.live ?? null,
724
+ relevance: {
725
+ ...selection.relevance,
726
+ intent: selection.intent ?? null,
727
+ },
728
+ };
729
+ if (cfg.dryRun) {
730
+ audit('dry-run', {
731
+ sessionId,
732
+ sourceSessionId: selection.card.source.sessionId,
733
+ cardId: selection.cardId,
734
+ cwdHash: selection.card.source.cwdHash,
735
+ chars: renderHandoffCard(selection.card, { maxChars: cfg.maxChars }).chars,
736
+ gates: injectGates,
737
+ dryRun: true,
738
+ });
739
+ stats.skipped += 1;
740
+ return { injected: false, skipped: 'dry-run', dryRun: true, cardId: selection.cardId, gates: injectGates, decision: await pass() };
741
+ }
742
+
743
+ // gate 7: per-session unique claim.
744
+ const sessionClaim = claimSession(memoryRoot, sessionId, { now: atMs });
745
+ if (!sessionClaim.ok) {
746
+ auditSkip(sessionId, sessionClaim.code ?? 'E_HANDOFF_ALREADY_CLAIMED', {
747
+ sourceSessionId: selection.card.source.sessionId,
748
+ cardId: selection.cardId,
749
+ });
750
+ notePrestepDegrade(sessionId, payload?.turn, {
751
+ kind: 'handoff-skip',
752
+ phase: 'handoff',
753
+ detail: sessionClaim.code ?? 'E_HANDOFF_ALREADY_CLAIMED',
754
+ });
755
+ return skipResult(sessionClaim.code ?? 'E_HANDOFF_ALREADY_CLAIMED', await pass());
756
+ }
757
+ stats.claims += 1;
758
+ const ranked = Array.isArray(selection.ranked) ? selection.ranked.slice(0, 8) : [];
759
+ let lastCode = 'E_HANDOFF_ALL_CARDS_CLAIMED';
760
+ let lastBudget = null;
761
+ for (const candidate of ranked) {
762
+ try {
763
+ hook('beforeCardClaim')({ cardId: candidate.cardId, sessionId, file: candidate.file ?? null });
764
+ } catch (error) {
765
+ lastCode = 'E_HANDOFF_CARD_CLAIMED_OTHER';
766
+ continue;
767
+ }
768
+ const cardClaim = claimCard(memoryRoot, candidate.cardId, {
769
+ now: atMs,
770
+ cardAtMs: candidate.atMs,
771
+ maxAgeMs,
772
+ cardFile: candidate.file ?? latestCardFile(memoryRoot, candidate.card.source.sessionId),
773
+ sessionId,
774
+ });
775
+ if (!cardClaim.ok) {
776
+ audit('claim', {
777
+ sessionId,
778
+ sourceSessionId: candidate.card.source.sessionId,
779
+ cardId: candidate.cardId,
780
+ code: cardClaim.code ?? 'E_ALREADY_CLAIMED',
781
+ });
782
+ lastCode = cardClaim.code ?? 'E_HANDOFF_ALREADY_CLAIMED';
783
+ continue;
784
+ }
785
+ stats.claims += 1;
786
+ audit('claim', {
787
+ sessionId,
788
+ sourceSessionId: candidate.card.source.sessionId,
789
+ cardId: candidate.cardId,
790
+ pid: process.pid,
791
+ });
792
+ const rendered = renderHandoffCard(candidate.card, { maxChars: cfg.maxChars });
793
+ if (rendered.empty) {
794
+ releaseCardClaim(cardClaim);
795
+ auditSkip(sessionId, 'E_HANDOFF_EMPTY', { sourceSessionId: candidate.card.source.sessionId, cardId: candidate.cardId });
796
+ lastCode = 'E_HANDOFF_EMPTY';
797
+ continue;
798
+ }
799
+ if (rendered.chars > cfg.maxChars || rendered.withinMax !== true) {
800
+ releaseCardClaim(cardClaim);
801
+ lastBudget = { chars: rendered.chars, maxChars: cfg.maxChars };
802
+ auditSkip(sessionId, 'E_HANDOFF_OVER_BUDGET', { sourceSessionId: candidate.card.source.sessionId, cardId: candidate.cardId, chars: rendered.chars });
803
+ lastCode = 'E_HANDOFF_OVER_BUDGET';
804
+ continue;
805
+ }
806
+ // Record "the payload may already contain this message" *before* the splice.
807
+ try {
808
+ hook('beforeSplice')({ cardId: candidate.cardId, sessionId, file: candidate.file ?? null });
809
+ } catch (error) {
810
+ // In-process failure before the splice evidence exists: the card claim is
811
+ // safely releasable (nothing was spliced), so try the next candidate.
812
+ releaseCardClaim(cardClaim);
813
+ lastCode = error?.code ?? 'E_HANDOFF_WRITE';
814
+ continue;
815
+ }
816
+ const spliced = markCardSpliced(cardClaim, { now: atMs, sessionId });
817
+ if (!spliced.ok) {
818
+ releaseCardClaim(cardClaim);
819
+ lastCode = spliced.code ?? 'E_HANDOFF_WRITE';
820
+ continue;
821
+ }
822
+ const factory = await resolveCreateUserMessage(explicitFactory);
823
+ if (typeof factory !== 'function') {
824
+ releaseCardClaim(cardClaim);
825
+ releaseSessionClaim(sessionClaim);
826
+ auditSkip(sessionId, 'E_HANDOFF_NO_FACTORY', { sourceSessionId: candidate.card.source.sessionId, cardId: candidate.cardId });
827
+ return skipResult('no-factory', await pass());
828
+ }
829
+ let message;
830
+ try {
831
+ message = assertInjectionSource(factory({
832
+ role: 'user',
833
+ content: [{ type: 'text', text: rendered.text }],
834
+ source: injectionSource(),
835
+ }));
836
+ } catch {
837
+ releaseCardClaim(cardClaim);
838
+ releaseSessionClaim(sessionClaim);
839
+ auditSkip(sessionId, 'E_HANDOFF_INJECT_REJECTED', { sourceSessionId: candidate.card.source.sessionId, cardId: candidate.cardId });
840
+ return skipResult('create-message-failed', await pass());
841
+ }
842
+ const index = insertionIndex(messages);
843
+ if (index <= 0) {
844
+ releaseCardClaim(cardClaim);
845
+ releaseSessionClaim(sessionClaim);
846
+ auditSkip(sessionId, 'E_HANDOFF_NO_ANCHOR', { sourceSessionId: candidate.card.source.sessionId, cardId: candidate.cardId });
847
+ return skipResult('no-human-message', await pass());
848
+ }
849
+ try {
850
+ messages.splice(index, 0, message);
851
+ } catch {
852
+ releaseCardClaim(cardClaim);
853
+ releaseSessionClaim(sessionClaim);
854
+ auditSkip(sessionId, 'E_HANDOFF_WRITE', { sourceSessionId: candidate.card.source.sessionId, cardId: candidate.cardId });
855
+ return skipResult('splice-failed', await pass());
856
+ }
857
+ const withdraw = () => {
858
+ const at = messages.indexOf(message);
859
+ if (at !== -1) messages.splice(at, 1);
860
+ };
861
+ let decision;
862
+ try {
863
+ decision = await pass();
864
+ } catch (error) {
865
+ withdraw();
866
+ releaseCardClaim(cardClaim);
867
+ releaseSessionClaim(sessionClaim);
868
+ audit('release', {
869
+ sessionId,
870
+ sourceSessionId: candidate.card.source.sessionId,
871
+ cardId: candidate.cardId,
872
+ code: 'E_HANDOFF_INJECT_REJECTED',
873
+ });
874
+ throw error;
875
+ }
876
+ if (!decision || decision.kind === 'reject') {
877
+ withdraw();
878
+ releaseCardClaim(cardClaim);
879
+ releaseSessionClaim(sessionClaim);
880
+ audit('release', {
881
+ sessionId,
882
+ sourceSessionId: candidate.card.source.sessionId,
883
+ cardId: candidate.cardId,
884
+ code: 'E_HANDOFF_INJECT_REJECTED',
885
+ });
886
+ return skipResult('rejected', decision);
887
+ }
888
+ // ---- accept boundary: finalize failures are warnings, never releases ----
889
+ fired.add(sessionId);
890
+ stats.injected += 1;
891
+ let finalizeFailure = null;
892
+ try {
893
+ hook('beforeFinalize')({ cardId: candidate.cardId, sessionId, file: candidate.file ?? null });
894
+ } catch (error) {
895
+ finalizeFailure = { code: error?.code ?? 'E_HANDOFF_FINALIZE', claimState: 'spliced' };
896
+ }
897
+ if (finalizeFailure === null) {
898
+ const sessionFinal = finalizeSessionClaim(sessionClaim, {
899
+ now: atMs,
900
+ cardId: candidate.cardId,
901
+ sourceSessionId: candidate.card.source.sessionId,
902
+ chars: rendered.chars,
903
+ });
904
+ if (!sessionFinal.ok) finalizeFailure = { code: sessionFinal.code ?? 'E_HANDOFF_FINALIZE', claimState: 'claimed' };
905
+ }
906
+ if (finalizeFailure === null) {
907
+ const cardFinal = finalizeCardClaim(cardClaim, { now: atMs, sessionId });
908
+ if (!cardFinal.ok) finalizeFailure = { code: cardFinal.code ?? 'E_HANDOFF_FINALIZE', claimState: 'spliced' };
909
+ }
910
+ if (finalizeFailure !== null) {
911
+ stats.errors += 1;
912
+ stats.lastError = { code: finalizeFailure.code, at: new Date(atMs).toISOString() };
913
+ warnOnce(`finalize-failed:${candidate.cardId}`, `[handoff] finalize 失败(${finalizeFailure.code}):占位 claim 保留,不释放。`);
914
+ audit('finalize-failed', {
915
+ sessionId,
916
+ sourceSessionId: candidate.card.source.sessionId,
917
+ cardId: candidate.cardId,
918
+ claimState: finalizeFailure.claimState,
919
+ code: finalizeFailure.code,
920
+ });
921
+ }
922
+ audit('inject', {
923
+ sessionId,
924
+ sourceSessionId: candidate.card.source.sessionId,
925
+ cardId: candidate.cardId,
926
+ cwdHash: candidate.card.source.cwdHash,
927
+ chars: rendered.chars,
928
+ gates: injectGates,
929
+ pid: process.pid,
930
+ });
931
+ return { injected: true, decision, cardId: candidate.cardId, chars: rendered.chars, gates: injectGates, intent: selection.intent ?? null };
932
+ }
933
+ // nothing could be claimed/rendered → no message was injected, release is safe.
934
+ releaseSessionClaim(sessionClaim);
935
+ auditSkip(sessionId, 'E_HANDOFF_ALL_CARDS_CLAIMED', { gates: gatesForAudit, ...(lastBudget ? { budget: lastBudget } : {}) });
936
+ notePrestepDegrade(sessionId, payload?.turn, { kind: 'handoff-skip', phase: 'handoff', detail: lastCode });
937
+ return skipResult('all-claimed', await pass(), { code: 'E_HANDOFF_ALL_CARDS_CLAIMED', lastCode });
938
+ }
939
+
940
+ async function maybeInject(payload, next) {
941
+ try {
942
+ return await injectOnce(payload, next);
943
+ } catch (error) {
944
+ const sessionId = preStepSessionId(payload);
945
+ stats.errors += 1;
946
+ stats.lastError = { code: error?.code ?? 'E_HANDOFF_PRE_STEP', at: new Date(nowMs()).toISOString() };
947
+ notePrestepDegrade(sessionId, payload?.turn, { kind: 'handoff-skip', phase: 'handoff', detail: error?.code ?? 'E_HANDOFF_PRE_STEP' });
948
+ throw error;
949
+ }
950
+ }
951
+
952
+ // ---- wiring -------------------------------------------------------------
953
+
954
+ const disposers = [];
955
+
956
+ function install(ctx) {
957
+ if (!enabled || !ctx || typeof ctx.on !== 'function') return false;
958
+ // Startup: bounded board + expired cards/claims (never blocks loading).
959
+ try {
960
+ resetTrimThrottle();
961
+ maybeTrimAuditBoard(memoryRoot, { now: nowMs(), minIntervalMs: 0, windowRows: cfg.auditWindowRows });
962
+ } catch { /* best effort */ }
963
+ try { pruneCards(memoryRoot, { now: nowMs(), maxAgeMs }); } catch { /* best effort */ }
964
+ try { pruneClaims(memoryRoot, { now: nowMs(), maxAgeMs }); } catch { /* best effort */ }
965
+ try {
966
+ const dispose = ctx.on('session/event', (session, event) => onSessionEvent(session, event));
967
+ if (typeof dispose === 'function') disposers.push(dispose);
968
+ } catch (error) {
969
+ stats.errors += 1;
970
+ logger(`[handoff] session/event 监听注册失败:${error?.code ?? error?.message ?? error}`);
971
+ }
972
+ try {
973
+ const dispose = ctx.on('agent/pre-step', async (payload, next) => {
974
+ const sessionId = preStepSessionId(payload);
975
+ const phase = startPrestepPhase(sessionId, payload?.turn, 'handoff');
976
+ try {
977
+ const result = await injectOnce(payload, next);
978
+ return result?.decision;
979
+ } catch (error) {
980
+ stats.errors += 1;
981
+ stats.lastError = { code: error?.code ?? 'E_HANDOFF_PRE_STEP', at: new Date(nowMs()).toISOString() };
982
+ notePrestepDegrade(sessionId, payload?.turn, {
983
+ kind: 'handoff-skip',
984
+ phase: 'handoff',
985
+ detail: error?.code ?? 'E_HANDOFF_PRE_STEP',
986
+ });
987
+ throw error;
988
+ } finally {
989
+ try { phase.end(); } catch { /* timing only */ }
990
+ }
991
+ });
992
+ if (typeof dispose === 'function') disposers.push(dispose);
993
+ } catch (error) {
994
+ stats.errors += 1;
995
+ logger(`[handoff] agent/pre-step 监听注册失败:${error?.code ?? error?.message ?? error}`);
996
+ }
997
+ return true;
998
+ }
999
+
1000
+ function dispose() {
1001
+ while (disposers.length > 0) {
1002
+ const disposer = disposers.pop();
1003
+ try {
1004
+ disposer();
1005
+ } catch {
1006
+ /* already disposed */
1007
+ }
1008
+ }
1009
+ sessions.clear();
1010
+ fired.clear();
1011
+ }
1012
+
1013
+ return {
1014
+ enabled,
1015
+ memoryRoot,
1016
+ config: { ...cfg },
1017
+ stats,
1018
+ install,
1019
+ dispose,
1020
+ onSessionEvent,
1021
+ maybeInject,
1022
+ injectOnce,
1023
+ prune: () => {
1024
+ const now = nowMs();
1025
+ const cards = pruneCards(memoryRoot, { now, maxAgeMs });
1026
+ const claims = pruneClaims(memoryRoot, { now, maxAgeMs });
1027
+ const trim = maybeTrimAuditBoard(memoryRoot, { now, minIntervalMs: 0, windowRows: cfg.auditWindowRows });
1028
+ return { cards, claims, trim };
1029
+ },
1030
+ paths: {
1031
+ audit: handoffAuditFile(memoryRoot),
1032
+ archive: (monthKey) => handoffArchiveFile(memoryRoot, monthKey),
1033
+ card: (sessionId) => latestCardFile(memoryRoot, sessionId),
1034
+ sessionClaim: (sessionId) => sessionClaimFile(memoryRoot, sessionId),
1035
+ },
1036
+ board: () => {
1037
+ try {
1038
+ return readHandoffBoard(memoryRoot, { now: nowMs() });
1039
+ } catch {
1040
+ return { present: false, rows: [], counts: {}, cards: [] };
1041
+ }
1042
+ },
1043
+ };
1044
+ }
1045
+
1046
+
1047
+
1048
+ // ------------------------------------------------------------------ wiring helper
1049
+
1050
+ /**
1051
+ * Register the handoff feature. Mirrors `registerActivityStream`: a disabled
1052
+ * stream registers nothing, reads nothing and logs nothing.
1053
+ */
1054
+ export function registerHandoffCard(ctx, cfg = {}, options = {}) {
1055
+ const stream = createHandoffStream({
1056
+ cfg,
1057
+ memoryRoot: options.memoryRoot,
1058
+ now: options.now,
1059
+ privacyScan: options.privacyScan,
1060
+ createUserMessage: cfg.createUserMessage ?? options.createUserMessage,
1061
+ hooks: options.hooks,
1062
+ logger: options.logger,
1063
+ });
1064
+ if (!stream.enabled) return stream;
1065
+ if (typeof ctx?.on !== 'function') return stream;
1066
+ stream.install(ctx);
1067
+ if (typeof ctx?.effect === 'function') {
1068
+ try {
1069
+ ctx.effect(() => () => stream.dispose(), 'longlive.handoff-card');
1070
+ } catch {
1071
+ /* a fake context may not own an effect scope */
1072
+ }
1073
+ }
1074
+ return stream;
1075
+ }
1076
+
1077
+ export { HANDOFF_MAX_CHARS, HANDOFF_MIN_CHARS, HANDOFF_RENDER_MAX, HANDOFF_FOOTER, HANDOFF_SCHEMA };