@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,302 @@
1
+ // src/recall/shared-visibility.js — M2-C R1–R6:双我可见的共享可见块
2
+ //
3
+ // 新会话首轮 agent/pre-step 注入一块 ≤300 字的「共享可见块」(session-reference
4
+ // 隐藏消息),让当前会话看到**其它活体会话**的目标 / 末活动 / 最后真实用户消息 /
5
+ // 最后记忆写入 / 陈旧标记,无需读原始日志(R1:≤2s;R3:不拿心跳冒充实时)。
6
+ //
7
+ // 数据源:
8
+ // - 活体表:liveList(与面板 #23 frames 同口径,src/live.js)
9
+ // - 记忆写入:resolveMemoryWriteAt(与 memory-gap 同源,src/lifecycle/gap-clocks.js)
10
+ // - 最后真实用户消息:事件索引(.longlive/index/events.db,kind=user),
11
+ // 无索引时退回 live 行扩展字段;两者都没有 => 不猜(lastUserMessage=null)
12
+ //
13
+ // 纪律:只读;失败静默(不阻断 turn);隐私门命中整行丢弃;≤300 字;只首轮注入。
14
+
15
+ import { liveList } from '../live.js';
16
+ import { resolveMemoryWriteAt } from '../lifecycle/gap-clocks.js';
17
+
18
+ export const SHARED_VISIBILITY_SCHEMA = 'shared-visibility/v1';
19
+ export const SHARED_BLOCK_MAX_CHARS = 300;
20
+ export const GOAL_STALE_MS = 5 * 60 * 1000;
21
+ export const SESSION_STALE_MS = 30 * 60 * 1000;
22
+ export const ACK_WORDS = Object.freeze(['对', '好', '嗯', '收到', '可以', '是的', '行', '不错', '好的', '知道了', 'ok', 'OK']);
23
+ const ACK_RE = new RegExp(`^(?:${ACK_WORDS.map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')})[。.!!??~~ ]*$`, 'u');
24
+
25
+ function toMs(value) {
26
+ if (value instanceof Date) return value.getTime();
27
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
28
+ if (typeof value === 'string' && value.trim() !== '') {
29
+ const parsed = Date.parse(value);
30
+ return Number.isFinite(parsed) ? parsed : null;
31
+ }
32
+ return null;
33
+ }
34
+
35
+ function clampText(value, max) {
36
+ const text = String(value ?? '').replace(/\s+/gu, ' ').trim();
37
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
38
+ }
39
+
40
+ /** 「无信息量」判定:长度 <6 或命中 ack 词表(「对的」不是最后意图)。 */
41
+ export function isInformativeUserText(text) {
42
+ const value = String(text ?? '').trim();
43
+ if (value === '') return false;
44
+ if ([...value].length < 6) return false;
45
+ return !ACK_RE.test(value);
46
+ }
47
+
48
+ function isoWithOffset(ms, offsetMinutes = 480) {
49
+ if (!Number.isFinite(ms)) return null;
50
+ const shifted = new Date(ms + offsetMinutes * 60 * 1000);
51
+ const pad = (n, w = 2) => String(n).padStart(w, '0');
52
+ return `${shifted.getUTCFullYear()}-${pad(shifted.getUTCMonth() + 1)}-${pad(shifted.getUTCDate())}T${pad(shifted.getUTCHours())}:${pad(shifted.getUTCMinutes())}:${pad(shifted.getUTCSeconds())}.${pad(shifted.getUTCMilliseconds(), 3)}+08:00`;
53
+ }
54
+
55
+ function clockText(ms, offsetMinutes = 480) {
56
+ if (!Number.isFinite(ms)) return '';
57
+ const shifted = new Date(ms + offsetMinutes * 60 * 1000);
58
+ const pad = (n) => String(n).padStart(2, '0');
59
+ return `${pad(shifted.getUTCHours())}:${pad(shifted.getUTCMinutes())}:${pad(shifted.getUTCSeconds())}`;
60
+ }
61
+
62
+ function ageText(ms) {
63
+ if (!Number.isFinite(ms) || ms < 0) return '';
64
+ const minutes = Math.floor(ms / 60_000);
65
+ if (minutes < 1) return '刚刚';
66
+ if (minutes < 60) return `${minutes} 分钟前`;
67
+ const hours = Math.floor(minutes / 60);
68
+ if (hours < 24) return `${hours} 小时前`;
69
+ return `${Math.floor(hours / 24)} 天前`;
70
+ }
71
+
72
+ function pickLastUserMessage(sessionId, lastUserMessages) {
73
+ const entry = lastUserMessages?.[sessionId] ?? null;
74
+ if (!entry || typeof entry !== 'object') return null;
75
+ if (typeof entry.text !== 'string' || entry.text.trim() === '') return null;
76
+ const text = clampText(entry.text, 80);
77
+ const prev = Array.isArray(entry.prev)
78
+ ? entry.prev.filter((item) => item && typeof item.text === 'string' && item.text.trim() !== '').slice(0, 2).map((item) => ({ text: clampText(item.text, 60), at: item.at ?? null }))
79
+ : [];
80
+ return { text, at: entry.at ?? null, informative: isInformativeUserText(text), prev };
81
+ }
82
+
83
+ /**
84
+ * Pure core: build the shared-visibility rows from live entries + injected data.
85
+ * @returns {{schema,sessions:object[],injectedAt:string,count:number}|null}
86
+ */
87
+ export function buildSharedVisibility({
88
+ entries = [],
89
+ currentSessionId = null,
90
+ now = Date.now(),
91
+ memoryWrite = null,
92
+ lastUserMessages = {},
93
+ projectOf = null,
94
+ maxSessions = 2,
95
+ } = {}) {
96
+ const nowMs = toMs(now) ?? Date.now();
97
+ const sessions = [];
98
+ for (const entry of Array.isArray(entries) ? entries : []) {
99
+ if (!entry || typeof entry !== 'object') continue;
100
+ if (entry.sessionId === currentSessionId) continue;
101
+ if (entry.effectiveState === 'dead' || entry.effectiveState === 'corrupt') continue;
102
+ const updatedMs = toMs(entry.updatedAt);
103
+ const goalAtMs = toMs(entry.goalUpdatedAt) ?? updatedMs;
104
+ const goalText = clampText(entry.goal, 80);
105
+ const action = entry.last_action && typeof entry.last_action === 'object' ? entry.last_action : null;
106
+ const actionAtMs = toMs(action?.at);
107
+ const attribution = {
108
+ present: entry.sessionId != null,
109
+ // 归属校验 = 行里同时有 host+pid 证据;不拿心跳冒充实时(R3)。
110
+ verified: typeof entry.host === 'string' && entry.host.trim() !== '' && Number.isInteger(entry.pid),
111
+ };
112
+ sessions.push({
113
+ project: typeof projectOf === 'function' ? (projectOf(entry) ?? null) : (entry.project ?? null),
114
+ sessionId: entry.sessionId,
115
+ attribution,
116
+ goal: goalText === '' ? null : {
117
+ text: goalText,
118
+ ageMs: Number.isFinite(goalAtMs) ? Math.max(0, nowMs - goalAtMs) : null,
119
+ stale: !Number.isFinite(goalAtMs) || nowMs - goalAtMs > GOAL_STALE_MS,
120
+ },
121
+ lastAction: action === null ? null : {
122
+ kind: clampText(action.kind ?? action.type ?? 'action', 24),
123
+ detail: clampText(action.detail ?? action.summary ?? '', 120),
124
+ at: isoWithOffset(actionAtMs),
125
+ ageMs: Number.isFinite(actionAtMs) ? Math.max(0, nowMs - actionAtMs) : null,
126
+ stale: !Number.isFinite(actionAtMs) || nowMs - actionAtMs > GOAL_STALE_MS,
127
+ },
128
+ lastUserMessage: pickLastUserMessage(entry.sessionId, lastUserMessages),
129
+ lastMemoryWrite: memoryWrite && Number.isFinite(toMs(memoryWrite.atMs))
130
+ ? {
131
+ at: isoWithOffset(toMs(memoryWrite.atMs)),
132
+ sourceFile: memoryWrite.rel ?? memoryWrite.sourceFile ?? null,
133
+ gapSec: Number.isFinite(memoryWrite.gapSec) ? memoryWrite.gapSec : (Number.isFinite(toMs(memoryWrite.atMs)) ? Math.max(0, Math.floor((nowMs - toMs(memoryWrite.atMs)) / 1000)) : null),
134
+ }
135
+ : null,
136
+ injectedAt: isoWithOffset(nowMs),
137
+ stale: !Number.isFinite(updatedMs) || nowMs - updatedMs > SESSION_STALE_MS,
138
+ effectiveState: entry.effectiveState ?? entry.state ?? null,
139
+ });
140
+ if (sessions.length >= Math.max(1, Number(maxSessions) || 2)) break;
141
+ }
142
+ if (sessions.length === 0) return null;
143
+ return { schema: SHARED_VISIBILITY_SCHEMA, sessions, injectedAt: isoWithOffset(nowMs), count: sessions.length };
144
+ }
145
+
146
+ /** Render the ≤300-char hidden block. Privacy hits drop the whole line (never the turn). */
147
+ export function renderSharedVisibilityBlock(visibility, { maxChars = SHARED_BLOCK_MAX_CHARS, privacyScan = null } = {}) {
148
+ if (!visibility || !Array.isArray(visibility.sessions) || visibility.sessions.length === 0) return '';
149
+ const scan = typeof privacyScan === 'function' ? privacyScan : null;
150
+ const safe = (text) => {
151
+ if (typeof text !== 'string' || text === '') return '';
152
+ if (scan !== null) {
153
+ try {
154
+ if (scan(text)?.verdict === 'local_only') return '';
155
+ } catch { return ''; }
156
+ }
157
+ return text;
158
+ };
159
+ const lines = [`【共享可见 · 只读】现在 ${visibility.count} 个思维活着。`];
160
+ let memoryWriteLine = '';
161
+ for (const session of visibility.sessions) {
162
+ const shortId = session.sessionId ? session.sessionId.slice(0, 18) : 'unknown';
163
+ const project = session.project ? `(${session.project})` : '';
164
+ const goal = session.goal
165
+ ? `目标:${safe(session.goal.text)}${session.goal.stale ? `(${ageText(session.goal.ageMs)}·陈旧)` : ''}`
166
+ : '';
167
+ const action = session.lastAction
168
+ ? `末活动:${safe(session.lastAction.kind)}/${safe(session.lastAction.detail)}${Number.isFinite(session.lastAction.ageMs) ? `(${ageText(session.lastAction.ageMs)})` : ''}`
169
+ : '';
170
+ const user = session.lastUserMessage
171
+ ? `最后用户消息:「${safe(session.lastUserMessage.text)}」${session.lastUserMessage.informative ? '' : '(无信息量)'}${session.lastUserMessage.prev.length > 0 ? `;前一条:「${safe(session.lastUserMessage.prev[0].text)}」` : ''}`
172
+ : '';
173
+ const row = [shortId + project, goal, action, user].filter(Boolean).join('|');
174
+ if (row !== '') lines.push(`· ${row}`);
175
+ if (session.lastMemoryWrite && session.lastMemoryWrite.sourceFile) {
176
+ memoryWriteLine = `· 最后记忆写入 ${clockText(toMs(session.lastMemoryWrite.at))} · 来源 ${safe(String(session.lastMemoryWrite.sourceFile))}`;
177
+ }
178
+ if (session.stale && session.lastAction === null) lines.push('· (该会话已 >30 分钟无心跳,按陈旧处理)');
179
+ }
180
+ if (memoryWriteLine !== '') lines.push(memoryWriteLine);
181
+ let text = lines.join('\n');
182
+ if (text.length > maxChars && memoryWriteLine !== '') {
183
+ // R1: the memory-write line is contract data (golden) — keep it even when
184
+ // trimming the rest of the block to the ≤300-char budget.
185
+ const header = lines[0];
186
+ const bodyLines = lines.slice(1).filter((line) => line !== memoryWriteLine);
187
+ let budget = maxChars - header.length - memoryWriteLine.length - 2;
188
+ if (budget < 0) {
189
+ text = `${header}\n${memoryWriteLine}`.slice(0, Math.max(0, maxChars - 1)) + '…';
190
+ return text;
191
+ }
192
+ const kept = [];
193
+ for (const line of bodyLines) {
194
+ if (line.length <= budget) {
195
+ kept.push(line);
196
+ budget -= line.length + 1;
197
+ } else {
198
+ break;
199
+ }
200
+ }
201
+ text = [header, ...kept, memoryWriteLine].join('\n');
202
+ }
203
+ if (text.length > maxChars) text = `${text.slice(0, Math.max(0, maxChars - 1))}…`;
204
+ return text;
205
+ }
206
+
207
+ function readIndexLastUserMessages({ memoryRoot, sessionIds = [] } = {}) {
208
+ const wanted = new Set(Array.isArray(sessionIds) ? sessionIds : []);
209
+ if (wanted.size === 0) return {};
210
+ try {
211
+ // Lazy import keeps the module cheap when no index exists.
212
+ const eventIndex = requireEventIndex();
213
+ const dbPath = `${String(memoryRoot)}/.longlive/index/events.db`;
214
+ if (!eventIndex || !dbPath) return {};
215
+ const fs = requireFs();
216
+ const path = requirePath();
217
+ const resolved = path.resolve(String(memoryRoot));
218
+ if (!fs.existsSync(path.join(resolved, '.longlive', 'index', 'events.db'))) return {};
219
+ const index = eventIndex.openEventIndex({ memoryRoot: resolved });
220
+ try {
221
+ const rows = index.listEvents({ kind: 'user', limit: 200 });
222
+ const out = {};
223
+ for (const sessionId of wanted) {
224
+ const own = rows.filter((row) => row.session_id === sessionId)
225
+ .sort((a, b) => (toMs(b.time_end) ?? 0) - (toMs(a.time_end) ?? 0));
226
+ if (own.length === 0) continue;
227
+ const text = String(own[0].summary ?? '').trim();
228
+ if (text === '') continue;
229
+ out[sessionId] = {
230
+ text,
231
+ at: isoWithOffset(toMs(own[0].time_end)),
232
+ prev: own.slice(1, 3).map((row) => ({ text: String(row.summary ?? '').trim(), at: isoWithOffset(toMs(row.time_end)) })),
233
+ };
234
+ }
235
+ return out;
236
+ } finally {
237
+ index.close();
238
+ }
239
+ } catch {
240
+ return {};
241
+ }
242
+ }
243
+
244
+ // Node builtins are loaded lazily so the pure builders stay dependency-free at import time.
245
+ let cachedEventIndex = null;
246
+ let cachedFs = null;
247
+ let cachedPath = null;
248
+ function requireEventIndex() {
249
+ return cachedEventIndex;
250
+ }
251
+ function requireFs() {
252
+ return cachedFs;
253
+ }
254
+ function requirePath() {
255
+ return cachedPath;
256
+ }
257
+ async function loadDeps() {
258
+ try {
259
+ cachedEventIndex = await import('../memory/event-index.js');
260
+ cachedFs = await import('node:fs');
261
+ cachedPath = await import('node:path');
262
+ } catch {
263
+ cachedEventIndex = null;
264
+ }
265
+ }
266
+
267
+ /**
268
+ * Production wrapper (read-only). Missing pieces degrade to null, never throw.
269
+ * @returns {null|{schema,sessions,injectedAt,count,block}}
270
+ */
271
+ export function sharedVisibility({ memoryRoot, currentSessionId = null, now = Date.now(), privacyScan = null, projectOf = null } = {}) {
272
+ try {
273
+ loadDepsSync();
274
+ const nowMs = toMs(now) ?? Date.now();
275
+ const listed = liveList({ includeDead: false }, { memoryRoot, now: nowMs });
276
+ const entries = Array.isArray(listed?.entries) ? listed.entries : [];
277
+ if (entries.length === 0) return null;
278
+ let memoryWrite = null;
279
+ try {
280
+ const resolved = resolveMemoryWriteAt({ memoryRoot, bootAtMs: nowMs });
281
+ if (resolved && Number.isFinite(resolved.atMs)) memoryWrite = { atMs: resolved.atMs, rel: resolved.rel };
282
+ } catch { /* memory write is optional */ }
283
+ const sessionIds = entries.map((entry) => entry.sessionId).filter((id) => id != null && id !== currentSessionId);
284
+ const lastUserMessages = readIndexLastUserMessages({ memoryRoot, sessionIds });
285
+ const visibility = buildSharedVisibility({ entries, currentSessionId, now: nowMs, memoryWrite, lastUserMessages, projectOf });
286
+ if (visibility === null) return null;
287
+ const block = renderSharedVisibilityBlock(visibility, { privacyScan });
288
+ return block === '' ? null : { ...visibility, block };
289
+ } catch {
290
+ return null;
291
+ }
292
+ }
293
+
294
+ // Resolve lazy deps synchronously via createRequire (fs/path) and a static import of the index.
295
+ import fsDefault from 'node:fs';
296
+ import pathDefault from 'node:path';
297
+ import * as eventIndexModule from '../memory/event-index.js';
298
+ function loadDepsSync() {
299
+ cachedEventIndex = eventIndexModule;
300
+ cachedFs = fsDefault;
301
+ cachedPath = pathDefault;
302
+ }
@@ -0,0 +1,196 @@
1
+ // src/recall/time-normalizer.mjs — B2:时间归一化(相对/绝对 → 事件时间区间)
2
+ //
3
+ // 纪律:只用**注入的事件时间**(now),本文件不读系统时钟;无法解析返回 null,
4
+ // 绝不猜一个日期。用于召回排序的时间亲和与 memory_recall_v2 的时间过滤。
5
+
6
+ export const TIME_SCHEMA = 'time-normalizer/v1';
7
+ export const DEFAULT_TZ_OFFSET_MINUTES = 8 * 60; // Asia/Shanghai (no DST)
8
+ const DAY_MS = 24 * 60 * 60 * 1000;
9
+
10
+ function toMs(value) {
11
+ if (value instanceof Date) return value.getTime();
12
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
13
+ if (typeof value === 'string' && value !== '') {
14
+ const parsed = Date.parse(value);
15
+ return Number.isFinite(parsed) ? parsed : null;
16
+ }
17
+ return null;
18
+ }
19
+
20
+ function tzOffset(options) {
21
+ return Number.isInteger(options?.tzOffsetMinutes) ? options.tzOffsetMinutes : DEFAULT_TZ_OFFSET_MINUTES;
22
+ }
23
+
24
+ /** Day start (local offset) for a wall-clock instant. */
25
+ export function dayStartMs(ms, options = {}) {
26
+ const offset = tzOffset(options) * 60 * 1000;
27
+ return Math.floor((ms + offset) / DAY_MS) * DAY_MS - offset;
28
+ }
29
+
30
+ function dayRange(ms, options = {}) {
31
+ const start = dayStartMs(ms, options);
32
+ return { startMs: start, endMs: start + DAY_MS - 1 };
33
+ }
34
+
35
+ function localParts(ms, options = {}) {
36
+ const offset = tzOffset(options) * 60 * 1000;
37
+ const shifted = new Date(ms + offset);
38
+ return {
39
+ year: shifted.getUTCFullYear(),
40
+ month: shifted.getUTCMonth() + 1,
41
+ day: shifted.getUTCDate(),
42
+ hour: shifted.getUTCHours(),
43
+ minute: shifted.getUTCMinutes(),
44
+ weekday: shifted.getUTCDay(), // 0=Sunday
45
+ };
46
+ }
47
+
48
+ function localMs(year, month, day, hour = 0, minute = 0, options = {}) {
49
+ const offset = tzOffset(options) * 60 * 1000;
50
+ return Date.UTC(year, month - 1, day, hour, minute) - offset;
51
+ }
52
+
53
+ function periodRange(ms, { unit, delta }, options = {}) {
54
+ const p = localParts(ms, options);
55
+ if (unit === 'day') {
56
+ const start = localMs(p.year, p.month, p.day, 0, 0, options) + delta * DAY_MS;
57
+ return { startMs: start, endMs: start + DAY_MS - 1 };
58
+ }
59
+ if (unit === 'week') {
60
+ // Monday-based week
61
+ const mondayOffset = (p.weekday + 6) % 7;
62
+ const start = localMs(p.year, p.month, p.day, 0, 0, options) - mondayOffset * DAY_MS + delta * 7 * DAY_MS;
63
+ return { startMs: start, endMs: start + 7 * DAY_MS - 1 };
64
+ }
65
+ if (unit === 'month') {
66
+ const start = localMs(p.year, p.month + delta, 1, 0, 0, options);
67
+ const end = localMs(p.year, p.month + delta + 1, 1, 0, 0, options) - 1;
68
+ return { startMs: start, endMs: end };
69
+ }
70
+ if (unit === 'year') {
71
+ const start = localMs(p.year + delta, 1, 1, 0, 0, options);
72
+ const end = localMs(p.year + delta + 1, 1, 1, 0, 0, options) - 1;
73
+ return { startMs: start, endMs: end };
74
+ }
75
+ return null;
76
+ }
77
+
78
+ function result(kind, startMs, endMs, raw, extra = {}) {
79
+ return { schema: TIME_SCHEMA, kind, raw, startMs, endMs, ...extra };
80
+ }
81
+
82
+ /**
83
+ * Normalize ONE time expression. `now` is required for relative expressions.
84
+ * @returns {null|{schema,kind,raw,startMs,endMs}}
85
+ */
86
+ export function normalizeTimeExpr(expr, { now = null, tzOffsetMinutes = DEFAULT_TZ_OFFSET_MINUTES } = {}) {
87
+ const raw = String(expr ?? '').trim();
88
+ if (raw === '') return null;
89
+ const options = { tzOffsetMinutes };
90
+ const nowMs = toMs(now);
91
+ // absolute YYYY-MM-DD / YYYY/MM/DD
92
+ let m = raw.match(/(\d{4})[-/年](\d{1,2})[-/月](\d{1,2})/u);
93
+ if (m) {
94
+ const range = dayRange(localMs(Number(m[1]), Number(m[2]), Number(m[3]), 0, 0, options), options);
95
+ return result('day', range.startMs, range.endMs, raw, { date: `${m[1]}-${String(m[2]).padStart(2, '0')}-${String(m[3]).padStart(2, '0')}` });
96
+ }
97
+ // YYYY-MM(月份)
98
+ m = raw.match(/(\d{4})[-/年](\d{1,2})月?/u);
99
+ if (m && !/(\d{1,2}):/u.test(raw)) {
100
+ const start = localMs(Number(m[1]), Number(m[2]), 1, 0, 0, options);
101
+ const end = localMs(Number(m[1]), Number(m[2]) + 1, 1, 0, 0, options) - 1;
102
+ return result('month', start, end, raw);
103
+ }
104
+ // 今天/昨天/前天/明天/后天
105
+ const relativeDays = { 今天: 0, 今日: 0, 昨天: -1, 昨日: -1, 前天: -2, 明天: 1, 后天: 2 };
106
+ for (const [word, delta] of Object.entries(relativeDays)) {
107
+ if (raw.includes(word)) {
108
+ if (nowMs === null) return null;
109
+ const range = periodRange(nowMs, { unit: 'day', delta }, options);
110
+ return result('day', range.startMs, range.endMs, raw);
111
+ }
112
+ }
113
+ // N 天前 / N 天后 / N 周前 / N 个月前
114
+ m = raw.match(/(\d+)\s*(天|日|周|个?月|年)\s*(前|后)/u);
115
+ if (m) {
116
+ if (nowMs === null) return null;
117
+ const n = Number(m[1]) * (m[3] === '前' ? -1 : 1);
118
+ const unitMap = { 天: 'day', 日: 'day', 周: 'week', 月: 'month', 个月: 'month', 年: 'year' };
119
+ const unit = unitMap[m[2].replace(/^个/u, '') === '月' ? '月' : m[2]];
120
+ if (unit === 'day' && '天日'.includes(m[2])) {
121
+ const start = dayStartMs(nowMs, options) + n * DAY_MS;
122
+ return result('day', start, start + DAY_MS - 1, raw);
123
+ }
124
+ const range = periodRange(nowMs, { unit, delta: n }, options);
125
+ if (range) return result(unit, range.startMs, range.endMs, raw);
126
+ return null;
127
+ }
128
+ // 本周/这周/上周/下周
129
+ const weekMap = { 本周: 0, 这周: 0, 上周: -1, 下周: 1 };
130
+ for (const [word, delta] of Object.entries(weekMap)) {
131
+ if (raw.includes(word)) {
132
+ if (nowMs === null) return null;
133
+ const range = periodRange(nowMs, { unit: 'week', delta }, options);
134
+ return range ? result('week', range.startMs, range.endMs, raw) : null;
135
+ }
136
+ }
137
+ // 上午/下午/晚上 + H 点(只给 day range + 时段边界)
138
+ m = raw.match(/(凌晨|早上|上午|中午|下午|傍晚|晚上)?\s*(\d{1,2})\s*[点::时]/u);
139
+ if (m) {
140
+ if (nowMs === null) return null;
141
+ const hour = Number(m[2]);
142
+ const bucket = m[1] ?? '';
143
+ const normalizedHour = bucket === '下午' || bucket === '傍晚' || bucket === '晚上' ? (hour < 12 ? hour + 12 : hour) : hour;
144
+ const p = localParts(nowMs, options);
145
+ const start = localMs(p.year, p.month, p.day, Math.min(23, normalizedHour), 0, options);
146
+ return result('instant', start, start + 60 * 60 * 1000 - 1, raw, { hour: normalizedHour });
147
+ }
148
+ // 刚才/刚刚/最近 → 最近 10 分钟(相对事件时间)
149
+ if (/刚才|刚刚/u.test(raw)) {
150
+ if (nowMs === null) return null;
151
+ return result('instant', nowMs - 10 * 60 * 1000, nowMs, raw);
152
+ }
153
+ return null;
154
+ }
155
+
156
+ /** Extract non-overlapping time refs from free text (longest match first). */
157
+ export function extractTimeRefs(text, options = {}) {
158
+ const value = typeof text === 'string' ? text : '';
159
+ if (value.trim() === '') return [];
160
+ const patterns = [
161
+ /\d{4}[-/年]\d{1,2}[-/月]\d{1,2}日?/gu,
162
+ /\d{4}[-/年]\d{1,2}月?/gu,
163
+ /今天|今日|昨天|昨日|前天|明天|后天/gu,
164
+ /\d+\s*(?:天|日|周|个?月|年)\s*(?:前|后)/gu,
165
+ /本周|这周|上周|下周/gu,
166
+ /(?:凌晨|早上|上午|中午|下午|傍晚|晚上)?\s*\d{1,2}\s*[点::时]/gu,
167
+ /刚才|刚刚/gu,
168
+ ];
169
+ const hits = [];
170
+ for (const re of patterns) {
171
+ for (const match of value.matchAll(re)) {
172
+ const raw = match[0];
173
+ const expr = normalizeTimeExpr(raw, options);
174
+ if (!expr) continue;
175
+ hits.push({ ...expr, index: match.index, length: raw.length });
176
+ }
177
+ }
178
+ hits.sort((a, b) => a.index - b.index || b.length - a.length);
179
+ const out = [];
180
+ let lastEnd = -1;
181
+ for (const hit of hits) {
182
+ if (hit.index < lastEnd) continue;
183
+ out.push(hit);
184
+ lastEnd = hit.index + hit.length;
185
+ }
186
+ return out;
187
+ }
188
+
189
+ /** Card date (YYYY-MM-DD / ISO / lastUsed) affinity against normalized refs. */
190
+ export function cardTimeAffinity(card, refs) {
191
+ if (!card || !Array.isArray(refs) || refs.length === 0) return 0;
192
+ const raw = card.date ?? card.createdAt ?? card.lastUsed ?? null;
193
+ const ms = toMs(raw);
194
+ if (ms === null) return 0;
195
+ return refs.some((ref) => ms >= ref.startMs && ms <= ref.endMs) ? 1 : 0;
196
+ }
@@ -0,0 +1,154 @@
1
+ // B3 已落 worktree · 召回块按「每轮统一预算」注入的挂点模块(2026-11-29 已接线:src/recall/index.js 渲染 + src/recall/brain.mjs 判决)
2
+ //
3
+ // 挂点位置(worktree 现状):
4
+ // - src/recall/index.js:1020-1031:finalText 组装后只有 token 口径的 while 裁剪(cfg.budget 默认 1200 token),
5
+ // 没有 2,000 字/轮 的字符口径上限 → 本模块替换该段。
6
+ // - src/recall/index.js:1105-1115:logRecall 只带 tokens=estimateTokens(finalText),没有延迟/字符数。
7
+ // - src/recall/brain.mjs:211/374/440:writeGateRow / finishPendingInjection / recordPendingResult 写 gate 行,
8
+ // ok 行 reason 为空、且没有 injectedTokens/elapsedMs → 本模块 + gate-metrics.mjs 补齐。
9
+ //
10
+ // 拆账(DESIGN.v0.5.2 L103 / MERGE-PLAN §10):召回块 990 字 =
11
+ // 头/recallId/取代冲突/零命中 60 + 卡区 750(5 卡 × 150 字)+ 程序卡 2×60=120 + 当前线 60。
12
+ // 这里拆出子额度只做诊断和渲染参数(卡摘要 120 字、每卡 150 字),硬保证仍是整块 990 字上限。
13
+
14
+ import {
15
+ TURN_BUDGET_RECALL_CHARS,
16
+ charLength,
17
+ estimateTurnTokens,
18
+ trimToChars,
19
+ } from '../memory/turn-budget.mjs';
20
+
21
+ export const RECALL_LANE_HEADER_CHARS = 60;
22
+ export const RECALL_LANE_CARD_AREA_CHARS = 750;
23
+ export const RECALL_LANE_PROCEDURE_AREA_CHARS = 120;
24
+ export const RECALL_LANE_CURRENT_LINE_CHARS = 60;
25
+ export const RECALL_CARD_TOTAL_CHARS = 150;
26
+ export const RECALL_CARD_EXCERPT_CHARS = 120;
27
+
28
+ export const RECALL_LANE_SUB_BUDGET = Object.freeze({
29
+ header: RECALL_LANE_HEADER_CHARS,
30
+ cards: RECALL_LANE_CARD_AREA_CHARS,
31
+ procedures: RECALL_LANE_PROCEDURE_AREA_CHARS,
32
+ currentLine: RECALL_LANE_CURRENT_LINE_CHARS,
33
+ total: TURN_BUDGET_RECALL_CHARS,
34
+ });
35
+
36
+ // 召回注入的判决空间:B3 口径下不存在 'skip'(每用户轮必注入);
37
+ // 关掉硬门 = disabled,子代理/非用户轮 = warn 且不注入,失败 = fail 带原因码,零命中 = zero-hit 仍注入兜底块。
38
+ export const RECALL_INJECTION_DECISIONS = Object.freeze(['ok', 'zero-hit', 'disabled', 'fail', 'warn']);
39
+
40
+ function codedError(code, message, detail) {
41
+ const error = new Error(`${code} ${message}`);
42
+ error.code = code;
43
+ if (detail !== undefined) error.detail = detail;
44
+ return error;
45
+ }
46
+
47
+ export function recallLaneSubBudget() {
48
+ return { ...RECALL_LANE_SUB_BUDGET };
49
+ }
50
+
51
+ export function recallSubBudgetSum() {
52
+ return (
53
+ RECALL_LANE_HEADER_CHARS + RECALL_LANE_CARD_AREA_CHARS + RECALL_LANE_PROCEDURE_AREA_CHARS + RECALL_LANE_CURRENT_LINE_CHARS
54
+ );
55
+ }
56
+
57
+ export function recallLaneCapChars() {
58
+ return TURN_BUDGET_RECALL_CHARS;
59
+ }
60
+
61
+ // 传给 recall-core.chooseRecall 的 token 预算:990 字扣掉固定头 60 字后按 2 字/token 折算(≈465 token)。
62
+ // 只作为 chooseRecall 的中间约束,最终仍由 applyRecallLaneBudget 用字符口径兜底。
63
+ export function recallChooseBudgetTokens() {
64
+ const chars = Math.max(0, TURN_BUDGET_RECALL_CHARS - RECALL_LANE_HEADER_CHARS);
65
+ return Math.max(1, estimateTurnTokens(chars));
66
+ }
67
+
68
+ // 单卡摘要的 token 上限:DESIGN 每卡 150 字含 title/path/锚点,摘要 120 字 → ≈60 token。
69
+ export function recallExcerptTokens() {
70
+ return Math.max(1, estimateTurnTokens(RECALL_CARD_EXCERPT_CHARS));
71
+ }
72
+
73
+ function isProcedureBlock(block) {
74
+ return /(^|\n)\s*(?:[-*]\s*)?(\[程序\]|【程序】)/.test(block);
75
+ }
76
+
77
+ function isCurrentLineBlock(block) {
78
+ return /当前线/.test(block);
79
+ }
80
+
81
+ // 诊断用:把最终注入文本按「头 / 卡区 / 程序卡 / 当前线」粗分,检查是否超子额度。
82
+ // 注意:超子额度只告警,硬上限是整块 990 字,裁剪从尾部做(DESIGN L103「超限从尾裁剪」)。
83
+ export function measureRecallLane(text) {
84
+ const source = typeof text === 'string' ? text : '';
85
+ const totalChars = charLength(source);
86
+ const blocks = source.length > 0 ? source.split(/\n{2,}/) : [];
87
+ const holder = blocks[0] ?? '';
88
+ const headerChars = charLength(holder);
89
+ const procedureChars = blocks.slice(1).filter(isProcedureBlock).reduce((sum, block) => sum + charLength(block), 0);
90
+ const currentLineChars = blocks.slice(1).filter(isCurrentLineBlock).reduce((sum, block) => sum + charLength(block), 0);
91
+ const cardAreaChars = Math.max(0, totalChars - headerChars - procedureChars - currentLineChars);
92
+ const subBudget = recallLaneSubBudget();
93
+ const overflows = [];
94
+ if (totalChars > subBudget.total) overflows.push({ part: 'total', chars: totalChars, cap: subBudget.total });
95
+ if (headerChars > subBudget.header) overflows.push({ part: 'header', chars: headerChars, cap: subBudget.header });
96
+ if (cardAreaChars > subBudget.cards) overflows.push({ part: 'cards', chars: cardAreaChars, cap: subBudget.cards });
97
+ if (procedureChars > subBudget.procedures) overflows.push({ part: 'procedures', chars: procedureChars, cap: subBudget.procedures });
98
+ if (currentLineChars > subBudget.currentLine) overflows.push({ part: 'currentLine', chars: currentLineChars, cap: subBudget.currentLine });
99
+ return { totalChars, headerChars, cardAreaChars, procedureChars, currentLineChars, subBudget, overflows };
100
+ }
101
+
102
+ // 挂点主函数:召回注入前把 finalText 压进 990 字车道(超限从尾裁剪,保留头/recallId)。
103
+ export function applyRecallLaneBudget(text, options = {}) {
104
+ const laneChars = Number.isFinite(Number(options.laneChars))
105
+ ? Math.max(0, Math.floor(Number(options.laneChars)))
106
+ : TURN_BUDGET_RECALL_CHARS;
107
+ const source = typeof text === 'string' ? text : '';
108
+ const holder = trimToChars(source, laneChars, { ellipsis: options.ellipsis ?? '…' });
109
+ const measurement = measureRecallLane(holder.text);
110
+ if (holder.chars > laneChars) {
111
+ throw codedError('E_HG_RECALL_LANE_OVERFLOW', `召回注入 ${holder.chars} 字超 ${laneChars} 字`, { chars: holder.chars, laneChars });
112
+ }
113
+ return { text: holder.text, chars: holder.chars, trimmed: holder.trimmed, laneChars, measurement };
114
+ }
115
+
116
+ // gate-log / recall-log 记录用:字符数 + token 估算 + 本轮耗时(L7 的 token/延迟字段来源)。
117
+ export function buildRecallLaneMetrics(lane, elapsedMs = 0) {
118
+ const chars = Math.max(0, Math.floor(Number(lane?.chars) || 0));
119
+ const elapsed = Math.max(0, Math.floor(Number(elapsedMs) || 0));
120
+ return { injectedChars: chars, injectedTokens: estimateTurnTokens(chars), elapsedMs: elapsed };
121
+ }
122
+
123
+ export function assertRecallLaneFit(lane) {
124
+ const chars = Math.max(0, Math.floor(Number(lane?.chars) || 0));
125
+ if (chars > recallLaneCapChars()) {
126
+ throw codedError('E_HG_RECALL_LANE_OVERFLOW', `召回注入 ${chars} 字超 ${recallLaneCapChars()} 字`, { chars, cap: recallLaneCapChars() });
127
+ }
128
+ return lane;
129
+ }
130
+
131
+ // 注入判决:B3 每用户轮必注入;子代理/非用户轮只记 warn 不注入;关硬门记 disabled;
132
+ // 失败记 fail + 原因码;零命中仍注入兜底块并记 zero-hit。任何分支都不返回 'skip'。
133
+ export function resolveRecallInjectionDecision(options = {}) {
134
+ const { killswitch = false, subagent = false, nonUser = false, zeroHit = false, failed = false, noChannel = false } = options;
135
+ if (failed || noChannel) {
136
+ return { inject: false, decision: 'fail', reason: noChannel ? 'E_HG_RECALL_NO_CHANNEL' : 'E_HG_RECALL_INJECT', metricsRequired: true };
137
+ }
138
+ if (killswitch) return { inject: false, decision: 'disabled', reason: 'killswitch', metricsRequired: false };
139
+ if (subagent) return { inject: false, decision: 'warn', reason: 'W_HG_SUBAGENT', metricsRequired: false };
140
+ if (nonUser) return { inject: false, decision: 'warn', reason: 'W_HG_NONUSER', metricsRequired: false };
141
+ if (zeroHit) return { inject: true, decision: 'zero-hit', reason: 'zero-hit', metricsRequired: true };
142
+ return { inject: true, decision: 'ok', reason: 'hit', metricsRequired: true };
143
+ }
144
+
145
+ export function assertRecallInjectionDecision(verdict) {
146
+ const decision = String(verdict?.decision ?? '');
147
+ if (!RECALL_INJECTION_DECISIONS.includes(decision)) {
148
+ throw codedError('E_HG_RECALL_DECISION', `非法召回判决 ${decision || '(空)'}`, { decision });
149
+ }
150
+ if (String(verdict?.reason ?? '').trim() === '') {
151
+ throw codedError('E_HG_RECALL_REASON', '召回判决必须带非空 reason', { decision });
152
+ }
153
+ return verdict;
154
+ }