@jjh32456/longlive 0.0.0-stage → 1.8.12

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 (309) hide show
  1. package/CHANGELOG.md +205 -0
  2. package/LICENSE +21 -0
  3. package/QUICKSTART.md +363 -0
  4. package/README.en.md +55 -0
  5. package/README.md +225 -2
  6. package/SPEC.md +211 -0
  7. package/build-info.json +1555 -0
  8. package/cordis.patch.yml +177 -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 +807 -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 +46 -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 +160 -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-a1-legacy.mjs +62 -0
  55. package/scripts/migrate-lifecycle.mjs +157 -0
  56. package/scripts/pack.mjs +392 -0
  57. package/scripts/recall-index-build.mjs +128 -0
  58. package/scripts/recall-links-build.mjs +420 -0
  59. package/scripts/rescore-cards.mjs +36 -0
  60. package/scripts/resident-watcher-status.ps1 +15 -0
  61. package/scripts/resident-watcher.ps1 +643 -0
  62. package/scripts/session-watch-drill.mjs +553 -0
  63. package/scripts/session-watch-status.ps1 +146 -0
  64. package/scripts/session-watch.mjs +1367 -0
  65. package/scripts/surgery-inspect.mjs +122 -0
  66. package/scripts/surgery-run.cmd +34 -0
  67. package/scripts/truncate-cli.mjs +279 -0
  68. package/scripts/unattended-surgery.ps1 +1019 -0
  69. package/scripts/uninstall-resident-watcher.ps1 +15 -0
  70. package/scripts/uninstall-session-watch.ps1 +192 -0
  71. package/scripts/verify-card-anchors.mjs +138 -0
  72. package/scripts/watch-loop.ps1 +916 -0
  73. package/src/actions/audit.js +125 -0
  74. package/src/actions/evidence.js +122 -0
  75. package/src/actions/fs.js +162 -0
  76. package/src/activity/index.js +873 -0
  77. package/src/activity/model.js +351 -0
  78. package/src/activity/store.js +786 -0
  79. package/src/activity/summary.js +180 -0
  80. package/src/activity/thinking.js +191 -0
  81. package/src/adapters/constants.js +11 -0
  82. package/src/adapters/engram/data/aliases.json +51 -0
  83. package/src/adapters/engram/data/policy.json +8 -0
  84. package/src/adapters/engram/data/routing-rules.json +546 -0
  85. package/src/adapters/engram/index.js +278 -0
  86. package/src/adapters/registry.js +315 -0
  87. package/src/answer/audit.js +238 -0
  88. package/src/answer/evidence.js +30 -0
  89. package/src/answer/guard.js +1370 -0
  90. package/src/answer/index.js +1086 -0
  91. package/src/answer/query.js +111 -0
  92. package/src/answer/second-hop.mjs +101 -0
  93. package/src/auto-truncate-status.js +164 -0
  94. package/src/auto-truncate.js +1181 -0
  95. package/src/autoprocedure/candidate.js +342 -0
  96. package/src/autoprocedure/config.js +122 -0
  97. package/src/autoprocedure/evidence.js +345 -0
  98. package/src/autoprocedure/index.js +83 -0
  99. package/src/autoprocedure/ledger.js +329 -0
  100. package/src/autoprocedure/lint.js +232 -0
  101. package/src/autoprocedure/llm.js +409 -0
  102. package/src/autoprocedure/locks.js +102 -0
  103. package/src/autoprocedure/paths.js +39 -0
  104. package/src/autoprocedure/privacy.js +87 -0
  105. package/src/autoprocedure/rules.js +288 -0
  106. package/src/autoprocedure/runtime.js +718 -0
  107. package/src/autoprocedure/session-reader.js +328 -0
  108. package/src/backup.js +146 -0
  109. package/src/bus/bus.mjs +1446 -0
  110. package/src/codec.js +269 -0
  111. package/src/compaction/cut-engine.js +44 -0
  112. package/src/compaction/engine-core.js +1237 -0
  113. package/src/compaction/entry.js +228 -0
  114. package/src/compaction.js +230 -0
  115. package/src/conclusion.js +366 -0
  116. package/src/config.js +824 -0
  117. package/src/d6/runtime.js +517 -0
  118. package/src/d6/surface.js +181 -0
  119. package/src/deps.js +189 -0
  120. package/src/engine-status.js +141 -0
  121. package/src/features.js +912 -0
  122. package/src/handoff/index.js +944 -0
  123. package/src/handoff/model.js +1010 -0
  124. package/src/handoff/store.js +1233 -0
  125. package/src/heartbeat.js +385 -0
  126. package/src/home.js +16 -0
  127. package/src/host-version.js +280 -0
  128. package/src/hot-truncate-diag.js +98 -0
  129. package/src/identity/card-marker.js +281 -0
  130. package/src/identity/handover.js +657 -0
  131. package/src/identity/index.js +337 -0
  132. package/src/identity/inject-position.js +131 -0
  133. package/src/identity/writeback.js +344 -0
  134. package/src/identity.js +118 -0
  135. package/src/index.js +647 -0
  136. package/src/lifecycle/gap-clocks.js +364 -0
  137. package/src/lifecycle/index.js +269 -0
  138. package/src/lifecycle/proactive.js +1426 -0
  139. package/src/live-target.js +212 -0
  140. package/src/live.js +1603 -0
  141. package/src/log-rotation.js +153 -0
  142. package/src/memory/a1-migration.js +124 -0
  143. package/src/memory/activity-capture.js +229 -0
  144. package/src/memory/anchor-fallback.js +116 -0
  145. package/src/memory/anchors.js +194 -0
  146. package/src/memory/audit-records.js +222 -0
  147. package/src/memory/auto-cards.js +441 -0
  148. package/src/memory/capture-host.js +228 -0
  149. package/src/memory/capture.js +457 -0
  150. package/src/memory/card-anchors.js +203 -0
  151. package/src/memory/card-priority.js +110 -0
  152. package/src/memory/cards.js +425 -0
  153. package/src/memory/conclusion-distill.js +332 -0
  154. package/src/memory/conclusion-drafts.js +239 -0
  155. package/src/memory/conflicts.js +147 -0
  156. package/src/memory/consolidate.js +815 -0
  157. package/src/memory/decay.js +311 -0
  158. package/src/memory/distill.js +485 -0
  159. package/src/memory/event-index.js +1826 -0
  160. package/src/memory/evidence-chain.js +295 -0
  161. package/src/memory/evidence.js +213 -0
  162. package/src/memory/filter-runner.js +555 -0
  163. package/src/memory/filter.js +1035 -0
  164. package/src/memory/forget-v2.js +410 -0
  165. package/src/memory/forget.js +512 -0
  166. package/src/memory/frames-activation.js +247 -0
  167. package/src/memory/frontmatter.js +454 -0
  168. package/src/memory/fts-query.js +342 -0
  169. package/src/memory/governance.js +604 -0
  170. package/src/memory/index-freshness.js +234 -0
  171. package/src/memory/index.js +362 -0
  172. package/src/memory/l2-gate.js +169 -0
  173. package/src/memory/lifecycle.js +107 -0
  174. package/src/memory/lock.js +121 -0
  175. package/src/memory/maintenance.js +785 -0
  176. package/src/memory/manifest.js +245 -0
  177. package/src/memory/migrate-lifecycle.js +1808 -0
  178. package/src/memory/migrate.js +139 -0
  179. package/src/memory/paths.js +229 -0
  180. package/src/memory/procedure.js +963 -0
  181. package/src/memory/provenance.js +119 -0
  182. package/src/memory/recall-v2.js +206 -0
  183. package/src/memory/recall.js +256 -0
  184. package/src/memory/reconcile.js +265 -0
  185. package/src/memory/records.js +433 -0
  186. package/src/memory/reinforce.js +145 -0
  187. package/src/memory/retention.js +128 -0
  188. package/src/memory/review.js +124 -0
  189. package/src/memory/state.js +279 -0
  190. package/src/memory/tiers.js +168 -0
  191. package/src/memory/topic-phrases.js +73 -0
  192. package/src/memory/trust.js +97 -0
  193. package/src/memory/version-chain.js +264 -0
  194. package/src/memory/wal.js +137 -0
  195. package/src/memory/working-frame.js +516 -0
  196. package/src/metrics/classify.mjs +189 -0
  197. package/src/metrics/estimate.mjs +108 -0
  198. package/src/metrics/index.mjs +204 -0
  199. package/src/metrics/measure.mjs +462 -0
  200. package/src/metrics/prestep-latency.mjs +307 -0
  201. package/src/metrics/store.mjs +264 -0
  202. package/src/original.js +294 -0
  203. package/src/policy/threshold-policy.js +224 -0
  204. package/src/policy-profile.js +463 -0
  205. package/src/recall/anaphora.mjs +87 -0
  206. package/src/recall/archive-fallback.mjs +235 -0
  207. package/src/recall/archive-search.mjs +425 -0
  208. package/src/recall/cards.mjs +202 -0
  209. package/src/recall/edges.js +379 -0
  210. package/src/recall/embedding.mjs +698 -0
  211. package/src/recall/entities.mjs +112 -0
  212. package/src/recall/explain.mjs +433 -0
  213. package/src/recall/force-policy.mjs +138 -0
  214. package/src/recall/index.js +1036 -0
  215. package/src/recall/inject-order.mjs +277 -0
  216. package/src/recall/link-recall.mjs +183 -0
  217. package/src/recall/links.mjs +696 -0
  218. package/src/recall/privacy.mjs +208 -0
  219. package/src/recall/recall-core.mjs +765 -0
  220. package/src/recall/shared-visibility.js +302 -0
  221. package/src/recall/time-normalizer.mjs +196 -0
  222. package/src/retention/config.js +106 -0
  223. package/src/retention/index.js +643 -0
  224. package/src/role/activation.js +191 -0
  225. package/src/role/attention.js +318 -0
  226. package/src/role/base.js +36 -0
  227. package/src/role/channels.js +423 -0
  228. package/src/role/index.js +425 -0
  229. package/src/role/interfaces.js +115 -0
  230. package/src/role/personality.js +370 -0
  231. package/src/role/readers.js +151 -0
  232. package/src/role/relationships.js +477 -0
  233. package/src/role/store.js +202 -0
  234. package/src/role/writeprotect.js +373 -0
  235. package/src/router/aliases.json +182 -0
  236. package/src/router/background/agent-runner.mjs +239 -0
  237. package/src/router/background/anchor.mjs +323 -0
  238. package/src/router/background/audit.mjs +337 -0
  239. package/src/router/background/budget-ledger.mjs +648 -0
  240. package/src/router/background/host-sim.mjs +451 -0
  241. package/src/router/background/index.mjs +81 -0
  242. package/src/router/background/memory.mjs +63 -0
  243. package/src/router/background/mock-llm.mjs +203 -0
  244. package/src/router/background/queue.mjs +224 -0
  245. package/src/router/background/retry.mjs +255 -0
  246. package/src/router/background/router.mjs +1459 -0
  247. package/src/router/background/stream.mjs +276 -0
  248. package/src/router/background/tool-policy.mjs +255 -0
  249. package/src/router/design-headings.json +221 -0
  250. package/src/router/face/config.mjs +155 -0
  251. package/src/router/face/context.mjs +284 -0
  252. package/src/router/face/face.mjs +466 -0
  253. package/src/router/face/identity.mjs +130 -0
  254. package/src/router/face/index.mjs +65 -0
  255. package/src/router/face/journal.mjs +119 -0
  256. package/src/router/face/llm.mjs +252 -0
  257. package/src/router/face/outbox.mjs +153 -0
  258. package/src/router/face/paths.mjs +54 -0
  259. package/src/router/judge.mjs +987 -0
  260. package/src/router/policies/generic.json +131 -0
  261. package/src/router/route.js +1766 -0
  262. package/src/router/router.mjs +535 -0
  263. package/src/router/routing-rules.json +816 -0
  264. package/src/router/run-sim.mjs +530 -0
  265. package/src/router/runtime.js +569 -0
  266. package/src/router/service/apply.mjs +1218 -0
  267. package/src/router/service/board.mjs +712 -0
  268. package/src/router/service/caller.mjs +131 -0
  269. package/src/router/service/config.mjs +361 -0
  270. package/src/router/service/context.mjs +314 -0
  271. package/src/router/service/hint.mjs +668 -0
  272. package/src/router/service/lease.mjs +494 -0
  273. package/src/router/service/live.mjs +251 -0
  274. package/src/router/service/lock.mjs +550 -0
  275. package/src/router/service/merge.mjs +255 -0
  276. package/src/router/service/model-resolve.mjs +350 -0
  277. package/src/router/service/paths.mjs +168 -0
  278. package/src/router/service/proposals.mjs +1461 -0
  279. package/src/router/service/queue.mjs +477 -0
  280. package/src/router/service/reconcile.mjs +271 -0
  281. package/src/router/service/service.mjs +2998 -0
  282. package/src/router/service/sources.mjs +352 -0
  283. package/src/router/service/status.mjs +520 -0
  284. package/src/router/service/store.mjs +476 -0
  285. package/src/router/service/ticklock.mjs +239 -0
  286. package/src/router/service/tokens.mjs +95 -0
  287. package/src/router/service/tools.mjs +248 -0
  288. package/src/router/service/wake.mjs +544 -0
  289. package/src/router/service/wal.mjs +685 -0
  290. package/src/router/shadow.mjs +821 -0
  291. package/src/surgery-recovery.js +1909 -0
  292. package/src/tool-output.js +485 -0
  293. package/src/tools.js +3146 -0
  294. package/src/truncate-visible.js +2416 -0
  295. package/src/truncate.js +999 -0
  296. package/src/ui/actions.js +1312 -0
  297. package/src/ui/flags.js +259 -0
  298. package/src/ui/panel-api.js +371 -0
  299. package/src/ui/panel-auth.js +251 -0
  300. package/src/ui/panel-integrity.js +243 -0
  301. package/src/ui/routes-readonly.js +759 -0
  302. package/src/ui/routes.js +284 -0
  303. package/src/util/append-store.js +368 -0
  304. package/src/util/local-day.js +30 -0
  305. package/src/util/redact.js +227 -0
  306. package/src/util/stale-locks.js +148 -0
  307. package/src/version.js +99 -0
  308. package/test/fixtures/pre-step-container.mjs +100 -0
  309. package/test/p1_probe.mjs +97 -0
@@ -0,0 +1,112 @@
1
+ // src/recall/entities.mjs — B2:实体别名表(`.longlive/entities/entities.jsonl`)
2
+ //
3
+ // 字段:{schema:'entities/v1', canonical, aliases[], kind, at}
4
+ // 只读路径给召回查询扩展用;写入口只允许宿主传入(本模块不做权限门,由调用方保证)。
5
+
6
+ import crypto from 'node:crypto';
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+
10
+ export const ENTITIES_SCHEMA = 'entities/v1';
11
+
12
+ export function entitiesPathOf(memoryRoot) {
13
+ return path.join(path.resolve(String(memoryRoot ?? '')), '.longlive', 'entities', 'entities.jsonl');
14
+ }
15
+
16
+ function nowIso(now) {
17
+ const value = typeof now === 'function' ? now() : new Date();
18
+ return (value instanceof Date ? value : new Date(value)).toISOString();
19
+ }
20
+
21
+ /** Read alias registry (append-only; later rows add aliases). Missing file => empty map. */
22
+ export function readEntityAliases({ memoryRoot }) {
23
+ const file = entitiesPathOf(memoryRoot);
24
+ const byCanonical = new Map();
25
+ let text = '';
26
+ try {
27
+ text = fs.readFileSync(file, 'utf8');
28
+ } catch {
29
+ return { present: false, file, aliases: {}, byCanonical: {}, badLines: 0 };
30
+ }
31
+ let bad = 0;
32
+ for (const line of text.split('\n')) {
33
+ if (line.trim() === '') continue;
34
+ let row;
35
+ try {
36
+ row = JSON.parse(line);
37
+ } catch {
38
+ bad += 1;
39
+ continue;
40
+ }
41
+ const canonical = typeof row?.canonical === 'string' ? row.canonical.trim() : '';
42
+ if (canonical === '') continue;
43
+ const aliases = Array.isArray(row.aliases) ? row.aliases.map((a) => String(a).trim()).filter(Boolean) : [];
44
+ const prev = byCanonical.get(canonical) ?? { canonical, aliases: new Set([canonical]), kind: row.kind ?? null };
45
+ for (const alias of aliases) prev.aliases.add(alias);
46
+ byCanonical.set(canonical, prev);
47
+ }
48
+ const aliases = {};
49
+ for (const [canonical, entry] of byCanonical) aliases[canonical] = [...entry.aliases];
50
+ return { present: true, file, aliases, byCanonical, badLines: bad };
51
+ }
52
+
53
+ /** Append one entity alias row (host/panel write path). Idempotent per canonical+alias set. */
54
+ export function appendEntityAlias({ memoryRoot, canonical, aliases = [], kind = null, now = () => new Date() }) {
55
+ const name = typeof canonical === 'string' ? canonical.trim() : '';
56
+ if (name === '') {
57
+ const error = new Error('E_ENTITY_CANONICAL_REQUIRED: canonical 不能为空');
58
+ error.code = 'E_ENTITY_CANONICAL_REQUIRED';
59
+ throw error;
60
+ }
61
+ const list = [...new Set([name, ...(Array.isArray(aliases) ? aliases : [])].map((a) => String(a).trim()).filter(Boolean))];
62
+ const file = entitiesPathOf(memoryRoot);
63
+ fs.mkdirSync(path.dirname(file), { recursive: true });
64
+ const row = { schema: ENTITIES_SCHEMA, canonical: name, aliases: list, kind: kind ?? null, at: nowIso(now) };
65
+ fs.appendFileSync(file, `${JSON.stringify(row)}\n`, 'utf8');
66
+ return { ok: true, file, row };
67
+ }
68
+
69
+ /** Find canonical entities mentioned in `text` (longest alias first). */
70
+ export function resolveEntityAliases(text, aliasMap, { max = 20 } = {}) {
71
+ const value = typeof text === 'string' ? text : '';
72
+ const matches = [];
73
+ const entries = [];
74
+ for (const [canonical, aliases] of Object.entries(aliasMap ?? {})) {
75
+ for (const alias of new Set([canonical, ...(Array.isArray(aliases) ? aliases : [])])) {
76
+ if (typeof alias !== 'string' || alias.trim() === '') continue;
77
+ entries.push({ canonical, alias });
78
+ }
79
+ }
80
+ entries.sort((a, b) => b.alias.length - a.alias.length || a.alias.localeCompare(b.alias));
81
+ const usedRanges = [];
82
+ for (const entry of entries) {
83
+ let from = 0;
84
+ while (matches.length < max) {
85
+ const index = value.indexOf(entry.alias, from);
86
+ if (index === -1) break;
87
+ from = index + entry.alias.length;
88
+ const end = index + entry.alias.length;
89
+ if (usedRanges.some((range) => index < range.end && end > range.start)) continue;
90
+ usedRanges.push({ start: index, end });
91
+ matches.push({ canonical: entry.canonical, alias: entry.alias, index });
92
+ }
93
+ }
94
+ matches.sort((a, b) => a.index - b.index);
95
+ return {
96
+ terms: [...new Set(matches.map((match) => match.canonical))],
97
+ matches,
98
+ };
99
+ }
100
+
101
+ /** Deterministic expansion text: canonical names appended once. */
102
+ export function expandQueryWithEntities(queryText, resolution) {
103
+ const terms = Array.isArray(resolution?.terms) ? resolution.terms : [];
104
+ if (terms.length === 0) return { text: String(queryText ?? ''), changed: false, terms };
105
+ const base = String(queryText ?? '');
106
+ const tail = terms.filter((term) => !base.includes(term)).join(' ');
107
+ return { text: tail === '' ? base : `${base} ${tail}`, changed: tail !== '', terms };
108
+ }
109
+
110
+ export function entityAliasDigest(aliasMap) {
111
+ return crypto.createHash('sha1').update(JSON.stringify(aliasMap ?? {})).digest('hex').slice(0, 12);
112
+ }
@@ -0,0 +1,433 @@
1
+ /**
2
+ * S3 · 召回可解释性(recall explainability)
3
+ *
4
+ * 职责边界:
5
+ * - 本模块只做**读**与纯函数分类/汇总;recall-log 的写在 src/recall/index.js。
6
+ * - 给 recall-log 每条补 why/eligible/dropped/gate/trigger/channel(审计 P1-7),
7
+ * 并把「策略跳过」「零命中」「失败」分开计数,供最近 24h 汇总(面板/健康输出)。
8
+ * - 行为零改动:不改变触发规则(turn<=1 / same-as-last / quiet),
9
+ * 只给已有决策补原因。
10
+ *
11
+ * why 语义(7 类,固定枚举):
12
+ * - everyNTurns 历史 1.8.1 及以前的 every-n-turns 行;1.8.2 起 decideTrigger
13
+ * 不再产生该触发(此处只兼容读旧 recall-log,不是现行触发路径)
14
+ * - injected 本轮确实注入了卡片(非心跳轮)
15
+ * - zero-hit 本轮执行了检索但零命中(非心跳轮)
16
+ * - everyNTurns 本轮由 everyNTurns 心跳触发(不论最终是否有注入;用 injected 数组区分结果)
17
+ * - quiet 触发规则判定本轮「安静」(gate.why === 'quiet')
18
+ * - policy-skip gate 因其它策略跳过(same-as-last / empty-query 等)
19
+ * - user-task 1.8.8 M2:强制触发(autoRecall.forceOnUserMessage)路径。
20
+ * 它与静默/周期路径正交:只要本轮是「真人任务消息 → 强制召回」,
21
+ * why 固定为 user-task、trigger 固定为 forced,不看最终是否注入
22
+ * (是否真注入看 injected 数组与 outcome 字段,禁止用 why 冒充成功)。
23
+ * - error 本轮召回失败(异常 / 注入工厂不可用)
24
+ *
25
+ * trigger 是 gate.why 的稳定口径(turn<=1 等),与 why 正交,便于对照触发规则。
26
+ * 1.8.8 起 trigger 多了 'forced'(强制触发),旧值一个不动。
27
+ */
28
+
29
+ import fs from 'node:fs';
30
+ import path from 'node:path';
31
+
32
+ // 第三方记忆插件的通道 id 只从 adapters 注册表取,核心 src 不出现第三方字面量(独立性门禁)。
33
+ import { EXTERNAL_PLUGIN_IDS } from '../adapters/constants.js';
34
+ import { OUTPUT_RESERVE_NORMAL_TOKENS } from '../policy/threshold-policy.js';
35
+
36
+ export const RECALL_LOG_FILE = 'recall-log.jsonl';
37
+ export const LEGACY_RECALL_LOG_REL = path.join('recall', 'log.jsonl');
38
+ export const RECALL_EXPLAIN_SCHEMA = 'recall-explain/v1';
39
+ export const RECALL_LOG_SCHEMA = 'recall-log/v1';
40
+ export const RECALL_WINDOW_MS = 24 * 60 * 60 * 1000;
41
+
42
+ /** 固定 why 枚举;测试与面板按它校验,不许悄悄加值。 */
43
+ export const RECALL_WHY_VALUES = Object.freeze([
44
+ 'injected',
45
+ 'zero-hit',
46
+ 'everyNTurns',
47
+ 'quiet',
48
+ 'policy-skip',
49
+ 'error',
50
+ // 1.8.8 M2:强制触发路径单列;只在 buildRecallLogRecord({forced:true}) 时出现。
51
+ 'user-task',
52
+ ]);
53
+
54
+ /** gate.why → 面板可读 trigger 口径。 */
55
+ export const RECALL_TRIGGER_BY_GATE = Object.freeze({
56
+ 'new-session': 'turn<=1',
57
+ 'after-compaction': 'after-compaction',
58
+ 'every-n-turns': 'everyNTurns',
59
+ 'topic-switch': 'topic-switch',
60
+ 'same-as-last': 'same-as-last',
61
+ 'quiet': 'quiet',
62
+ 'empty-query': 'empty-query',
63
+ 'mid-turn': 'mid-turn',
64
+ // 1.8.8 M2:强制触发(不看 everyNTurns、不被 quiet 挡)。
65
+ 'forced': 'forced',
66
+ });
67
+
68
+ export const RECALL_CHANNELS = Object.freeze(['file', ...EXTERNAL_PLUGIN_IDS, 'degraded']);
69
+
70
+ /**
71
+ * gate.why → trigger 字段。
72
+ * @param {string|undefined} gateWhy
73
+ * @returns {string}
74
+ */
75
+ export function normalizeTrigger(gateWhy) {
76
+ if (typeof gateWhy !== 'string' || gateWhy === '') return 'unknown';
77
+ return RECALL_TRIGGER_BY_GATE[gateWhy] ?? gateWhy;
78
+ }
79
+
80
+ /**
81
+ * 单轮 why 分类(纯函数,行为语义见文件头)。
82
+ * @param {{gate?:{recall?:boolean, why?:string}, items?:unknown[], error?:boolean, factoryUnavailable?:boolean}} input
83
+ * @returns {'injected'|'zero-hit'|'everyNTurns'|'quiet'|'policy-skip'|'error'}
84
+ */
85
+ export function classifyRecallWhy({ gate = null, items = [], error = false, factoryUnavailable = false } = {}) {
86
+ if (error === true || factoryUnavailable === true) return 'error';
87
+ const recall = gate?.recall === true;
88
+ if (!recall) return gate?.why === 'quiet' ? 'quiet' : 'policy-skip';
89
+ // 1.8.1 及以前的心跳行:只用于读旧日志归类,1.8.2 已没有该触发。
90
+ if (gate?.why === 'every-n-turns') return 'everyNTurns';
91
+ return Array.isArray(items) && items.length > 0 ? 'injected' : 'zero-hit';
92
+ }
93
+
94
+ /**
95
+ * chooseRecall() 的 hits + rejections → 面板可读 dropped 摘要。
96
+ * 只统计「没进本轮注入」的原因;预算内正常落选的重复项也算进去(与 blocked 对齐)。
97
+ * @param {object|null} hits
98
+ * @param {object[]|null} rejections
99
+ * @returns {{budget:number,dedupe:number,seen:number,localOnly:number,privacy:number,lowTrust:number,maxItems:number,total:number}|null}
100
+ */
101
+ export function summarizeDropped(hits = null, rejections = null) {
102
+ if (!hits || typeof hits !== 'object') return null;
103
+ const byReason = {};
104
+ for (const row of Array.isArray(rejections) ? rejections : []) {
105
+ const reason = typeof row?.reason === 'string' ? row.reason : 'unknown';
106
+ byReason[reason] = (byReason[reason] ?? 0) + 1;
107
+ }
108
+ const n = (value) => (Number.isFinite(Number(value)) ? Math.max(0, Number(value)) : 0);
109
+ const out = {
110
+ budget: n(hits.droppedByBudget),
111
+ dedupe: n(hits.droppedByDedupe),
112
+ seen: n(hits.droppedBySeen),
113
+ localOnly: n(hits.droppedLocalOnly),
114
+ privacy: n(hits.droppedByPrivacy),
115
+ lowTrust: n(hits.droppedByLowTrust),
116
+ maxItems: n(byReason['max-items']),
117
+ };
118
+ out.total = out.budget + out.dedupe + out.seen + out.localOnly + out.privacy + out.lowTrust + out.maxItems;
119
+ return out;
120
+ }
121
+
122
+ /**
123
+ * 选择本轮 channel:embedding 降级优先标注;目前召回候选只有文件卡(AutoCard 也是文件派生)。
124
+ * 外部记忆插件通道(EXTERNAL_PLUGIN_IDS)留给后续接入:path 前缀 `<id>:` 时自动标。
125
+ */
126
+ export function resolveChannel({ items = [], embeddingDegraded = false } = {}) {
127
+ if (embeddingDegraded === true) return 'degraded';
128
+ const list = Array.isArray(items) ? items : [];
129
+ const external = EXTERNAL_PLUGIN_IDS.find((id) => list.some((item) => String(item?.path ?? '').startsWith(`${id}:`)));
130
+ return external ?? 'file';
131
+ }
132
+
133
+ /** recall-log 里的 query 摘要上限(字符);只留线索,不留整段对话。 */
134
+ export const RECALL_QUERY_SUMMARY_MAX = 200;
135
+
136
+ /** 日志里的敏感串:手机号 / 邮箱 / 身份证 / IPv4 / 长 token(key)。 */
137
+ const LOG_PII_PATTERNS = Object.freeze([
138
+ /\b1[3-9]\d{9}\b/g,
139
+ /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,
140
+ /\b\d{17}[\dXx]\b/g,
141
+ /\b(?:\d{1,3}\.){3}\d{1,3}\b/g,
142
+ /\b[A-Za-z0-9_-]{24,}\b/g,
143
+ ]);
144
+
145
+ /**
146
+ * 1.8.8 M2:recall-log 的 query 摘要(隐私友好)。
147
+ * 只做四件事:去控制字符、折叠空白、遮蔽常见敏感串、截到 200 字符。
148
+ * 不存整段用户消息,不做语义改写。
149
+ * @param {unknown} text
150
+ * @returns {string}
151
+ */
152
+ export function summarizeQuery(text) {
153
+ let value = String(text ?? '');
154
+ value = value.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim();
155
+ if (value === '') return '';
156
+ for (const pattern of LOG_PII_PATTERNS) value = value.replace(pattern, '[已隐去]');
157
+ if (value.length > RECALL_QUERY_SUMMARY_MAX) value = `${value.slice(0, RECALL_QUERY_SUMMARY_MAX)}…`;
158
+ return value;
159
+ }
160
+
161
+ /** link 统计的最小化形状(只记词数/命中数,不记用户原句)。 */
162
+ function summarizeLinkStat(link) {
163
+ if (!link || typeof link !== 'object') return null;
164
+ const terms = Array.isArray(link.matchedTerms) ? link.matchedTerms.map((t) => String(t)).filter((t) => t !== '').slice(0, 20) : [];
165
+ return {
166
+ enabled: link.enabled !== false,
167
+ matchedTerms: terms,
168
+ injectedCount: Number.isFinite(Number(link.injectedCount)) ? Math.max(0, Number(link.injectedCount)) : 0,
169
+ tokens: Number.isFinite(Number(link.tokens)) ? Math.max(0, Number(link.tokens)) : 0,
170
+ };
171
+ }
172
+
173
+ /**
174
+ * 构造一条 recall-log 行(字段纯计算,不写盘)。
175
+ * @param {object} input
176
+ * @param {Date|string|number} [input.at]
177
+ * @param {string} input.sessionId
178
+ * @param {number} input.turn
179
+ * @param {object|null} [input.result] chooseRecall 结果(skips 传 null)
180
+ * @param {object|null} [input.gate] decideTrigger 结果
181
+ * @param {number} [input.everyNTurns] 历史字段兼容(1.8.2 不再触发)
182
+ * @param {boolean} [input.error]
183
+ * @param {boolean} [input.factoryUnavailable]
184
+ * @param {boolean} [input.embeddingDegraded]
185
+ * @param {unknown[]|null} [input.injectedItems] 覆盖注入项(factory 不可用时传 [])
186
+ * @param {string} [input.query] 1.8.8 M2:触发本轮的真实用户消息摘要(summarizeQuery 后写入)
187
+ * @param {number|null} [input.elapsedMs] 1.8.8 M2:agent/pre-step 内召回耗时(毫秒)
188
+ * @param {boolean} [input.forced] 1.8.8 M2:是否强制触发(autoRecall.forceOnUserMessage)
189
+ * @param {string|null} [input.why] 覆盖 why(强制路径固定 'user-task')
190
+ * @param {string|null} [input.trigger] 覆盖 trigger(强制路径固定 'forced')
191
+ * @param {boolean} [input.archiveUnavailable] 1.8.8 M2:归档兜底模块不可用/调用失败
192
+ * @param {object|null} [input.link] 1.8.8 M2:链路命中统计 {matchedTerms,injectedCount,tokens}
193
+ * @returns {object}
194
+ */
195
+ export function buildRecallLogRecord({
196
+ at = new Date(),
197
+ sessionId = 'unknown',
198
+ turn = 0,
199
+ result = null,
200
+ gate = null,
201
+ everyNTurns = null,
202
+ error = false,
203
+ factoryUnavailable = false,
204
+ embeddingDegraded = false,
205
+ injectedItems = null,
206
+ query = '',
207
+ elapsedMs = null,
208
+ forced = false,
209
+ why: whyOverride = null,
210
+ trigger: triggerOverride = null,
211
+ archiveUnavailable = false,
212
+ link = null,
213
+ } = {}) {
214
+ const items = Array.isArray(injectedItems) ? injectedItems : (Array.isArray(result?.items) ? result.items : []);
215
+ const hits = result?.hits && typeof result.hits === 'object' ? result.hits : null;
216
+ const why = typeof whyOverride === 'string' && whyOverride !== ''
217
+ ? whyOverride
218
+ : classifyRecallWhy({ gate, items, error, factoryUnavailable });
219
+ const dropped = summarizeDropped(hits, result?.rejections);
220
+ const gateSummary = {
221
+ recall: gate?.recall === true,
222
+ why: typeof gate?.why === 'string' ? gate.why : 'unknown',
223
+ everyNTurns: Number.isFinite(Number(everyNTurns)) ? Number(everyNTurns) : null,
224
+ };
225
+ // 注意 Number(null) === 0:缺省(null/undefined/'')必须落 null,不能落 0。
226
+ const elapsedRaw = elapsedMs === null || elapsedMs === undefined || elapsedMs === '' ? null : Number(elapsedMs);
227
+ const elapsed = Number.isFinite(elapsedRaw) && elapsedRaw >= 0 ? Math.round(elapsedRaw) : null;
228
+ let outcome = 'zero-hit';
229
+ if (error === true) outcome = 'error';
230
+ else if (factoryUnavailable === true) outcome = 'factory-unavailable';
231
+ else if (items.length > 0) outcome = 'injected';
232
+ else if (gate && gate.recall !== true) outcome = 'gate-skip';
233
+ return {
234
+ at: at instanceof Date ? at.toISOString() : new Date(at).toISOString(),
235
+ sessionId: String(sessionId ?? 'unknown'),
236
+ turn: Number.isFinite(Number(turn)) ? Number(turn) : 0,
237
+ why,
238
+ eligible: hits ? (Number.isFinite(Number(hits.eligible)) ? Number(hits.eligible) : 0) : null,
239
+ dropped,
240
+ gate: gateSummary,
241
+ trigger: typeof triggerOverride === 'string' && triggerOverride !== ''
242
+ ? triggerOverride
243
+ : normalizeTrigger(gate?.why),
244
+ // 1.8.8 M2:强制触发 / 链路直连 / 归档兜底的取证字段。
245
+ forced: forced === true,
246
+ query: summarizeQuery(query),
247
+ elapsedMs: elapsed,
248
+ outcome,
249
+ archiveUnavailable: archiveUnavailable === true,
250
+ link: summarizeLinkStat(link),
251
+ // D5 forward instrumentation: the existing recall result already carries the
252
+ // rendered token estimate; never read a session or add a new parse path.
253
+ estimatedTokens: Number.isFinite(Number(result?.tokens)) ? Number(result.tokens) : 0,
254
+ budgetUsed: Number.isFinite(Number(result?.tokens)) ? Number(result.tokens) : 0,
255
+ // 1.8.3 D5 shared-window fields: forward-only. The recall path has no
256
+ // session/input read; unavailable fields are explicitly null.
257
+ estimatedInputTokens: null,
258
+ estimatedOutputTokens: null,
259
+ outputReserveTokens: OUTPUT_RESERVE_NORMAL_TOKENS,
260
+ actual_output_tokens: null,
261
+ finish_reason: null,
262
+ truncated: false,
263
+ reserve_class: 'long',
264
+ fold_failed: null,
265
+ fold_busy: false,
266
+ injectedCount: items.length,
267
+ channel: resolveChannel({ items, embeddingDegraded }),
268
+ injected: items.map((item) => ({
269
+ id: item.path,
270
+ title: item.title,
271
+ score: Number(Number(item.score ?? 0).toFixed(3)),
272
+ reason: item.reason ?? 'keyword',
273
+ // 1.8.8 M2:来源 file / link / archive;旧行缺该字段时按 file 读。
274
+ source: typeof item.source === 'string' && item.source !== '' ? item.source : 'file',
275
+ })),
276
+ blocked: (Array.isArray(result?.rejections) ? result.rejections : []).map((item) => ({
277
+ id: item.path,
278
+ title: item.title,
279
+ reason: item.reason,
280
+ })),
281
+ };
282
+ }
283
+
284
+ /**
285
+ * 读取 recall-log 行。
286
+ * 规范位置:<memoryRoot>/.longlive/recall-log.jsonl(auto-recall 写入)。
287
+ * 兼容旧位置:<memoryRoot>/.longlive/recall/log.jsonl(M2-C 读审计);规范文件不存在时才回退。
288
+ * @param {{memoryRoot?:string, limit?:number}} [options]
289
+ */
290
+ export function readRecallLogRows(options = {}) {
291
+ const memoryRoot = typeof options.memoryRoot === 'string' ? options.memoryRoot.trim() : '';
292
+ if (memoryRoot === '') {
293
+ return { ok: false, code: 'E_MEMORY_ROOT_UNSET', present: false, path: '', legacyPath: false, rows: [], bad: 0, bytes: 0 };
294
+ }
295
+ const root = path.resolve(memoryRoot);
296
+ const canonical = path.join(root, '.longlive', RECALL_LOG_FILE);
297
+ const legacy = path.join(root, '.longlive', LEGACY_RECALL_LOG_REL);
298
+ let file = canonical;
299
+ try {
300
+ fs.accessSync(canonical);
301
+ } catch {
302
+ try {
303
+ fs.accessSync(legacy);
304
+ file = legacy;
305
+ } catch {
306
+ file = canonical;
307
+ }
308
+ }
309
+ let text;
310
+ try {
311
+ text = fs.readFileSync(file, 'utf8');
312
+ } catch (error) {
313
+ if (error?.code === 'ENOENT') {
314
+ return { ok: true, present: false, path: file, legacyPath: file === legacy, rows: [], bad: 0, bytes: 0 };
315
+ }
316
+ return { ok: false, code: 'E_RECALL_LOG_READ', present: false, path: file, legacyPath: file === legacy, rows: [], bad: 0, bytes: 0 };
317
+ }
318
+ const rows = [];
319
+ let bad = 0;
320
+ for (const line of text.split(/\r?\n/)) {
321
+ const trimmed = line.trim();
322
+ if (trimmed === '') continue;
323
+ try {
324
+ const row = JSON.parse(trimmed);
325
+ if (row && typeof row === 'object') rows.push(row);
326
+ else bad += 1;
327
+ } catch {
328
+ bad += 1;
329
+ }
330
+ }
331
+ const limit = Number.isInteger(options.limit) && options.limit > 0 ? options.limit : 0;
332
+ return {
333
+ ok: true,
334
+ present: rows.length > 0,
335
+ path: file,
336
+ legacyPath: file === legacy,
337
+ rows: limit > 0 ? rows.slice(-limit) : rows,
338
+ bad,
339
+ bytes: Buffer.byteLength(text, 'utf8'),
340
+ };
341
+ }
342
+
343
+ /**
344
+ * 最近 windowMs(默认 24h)的 why/trigger/channel 计数。
345
+ * 明确把「策略跳过」与「零命中/失败」拆开:policySkipTotal / zeroHitTotal / errorTotal。
346
+ * 旧行(没有 why 字段)单独计入 legacyRows,不猜原因。
347
+ * @param {object[]} rows
348
+ * @param {{now?:Date|number|string, windowMs?:number}} [options]
349
+ */
350
+ export function summarizeRecallRows(rows = [], options = {}) {
351
+ const rawNow = options.now;
352
+ const nowMs = rawNow instanceof Date ? rawNow.getTime()
353
+ : Number.isFinite(Number(rawNow)) ? Number(rawNow)
354
+ : Date.now();
355
+ const windowMs = Number.isFinite(Number(options.windowMs)) && Number(options.windowMs) > 0
356
+ ? Number(options.windowMs)
357
+ : RECALL_WINDOW_MS;
358
+ const cutoff = nowMs - windowMs;
359
+ const byWhy = Object.fromEntries(RECALL_WHY_VALUES.map((why) => [why, 0]));
360
+ const byTrigger = {};
361
+ const byChannel = {};
362
+ const dropped = { budget: 0, dedupe: 0, seen: 0, localOnly: 0, privacy: 0, lowTrust: 0, maxItems: 0, total: 0 };
363
+ let totalRows = 0;
364
+ let inWindow = 0;
365
+ let legacyRows = 0;
366
+ let injectedRounds = 0;
367
+ let emptyInjections = 0;
368
+ let forcedTotal = 0;
369
+ let archiveUnavailableTotal = 0;
370
+ let linkInjectedTotal = 0;
371
+ const byOutcome = {};
372
+ let lastAt = null;
373
+
374
+ const list = Array.isArray(rows) ? rows : [];
375
+ for (const row of list) {
376
+ if (!row || typeof row !== 'object') continue;
377
+ totalRows += 1;
378
+ const atMs = Date.parse(String(row.at ?? ''));
379
+ const inWindowRow = Number.isFinite(atMs) ? atMs >= cutoff : false;
380
+ if (!inWindowRow) continue;
381
+ inWindow += 1;
382
+ if (lastAt === null || (Number.isFinite(atMs) && atMs > Date.parse(lastAt))) lastAt = String(row.at);
383
+ const why = RECALL_WHY_VALUES.includes(row.why) ? row.why : null;
384
+ if (why === null) legacyRows += 1;
385
+ else byWhy[why] += 1;
386
+ const trigger = typeof row.trigger === 'string' && row.trigger !== '' ? row.trigger : 'unknown';
387
+ byTrigger[trigger] = (byTrigger[trigger] ?? 0) + 1;
388
+ const channel = RECALL_CHANNELS.includes(row.channel) ? row.channel : 'file';
389
+ byChannel[channel] = (byChannel[channel] ?? 0) + 1;
390
+ const injected = Array.isArray(row.injected) ? row.injected : [];
391
+ if (injected.length > 0) injectedRounds += 1;
392
+ else emptyInjections += 1;
393
+ // 1.8.8 M2:强制触发 / 归档不可用 / 链路来源计数(只读已有字段,不猜)。
394
+ if (row.forced === true) forcedTotal += 1;
395
+ if (row.archiveUnavailable === true) archiveUnavailableTotal += 1;
396
+ if (injected.some((item) => item?.source === 'link')) linkInjectedTotal += 1;
397
+ const outcome = typeof row.outcome === 'string' && row.outcome !== '' ? row.outcome : 'unknown';
398
+ byOutcome[outcome] = (byOutcome[outcome] ?? 0) + 1;
399
+ if (row.dropped && typeof row.dropped === 'object') {
400
+ for (const key of Object.keys(dropped)) {
401
+ if (key === 'total') continue;
402
+ dropped[key] += Number.isFinite(Number(row.dropped[key])) ? Math.max(0, Number(row.dropped[key])) : 0;
403
+ }
404
+ }
405
+ }
406
+ dropped.total = dropped.budget + dropped.dedupe + dropped.seen + dropped.localOnly
407
+ + dropped.privacy + dropped.lowTrust + dropped.maxItems;
408
+ return {
409
+ schema: RECALL_EXPLAIN_SCHEMA,
410
+ windowHours: Math.round((windowMs / (60 * 60 * 1000)) * 100) / 100,
411
+ windowMs,
412
+ totalRows,
413
+ inWindow,
414
+ legacyRows,
415
+ byWhy,
416
+ byTrigger,
417
+ byChannel,
418
+ byOutcome,
419
+ injectedRounds,
420
+ emptyInjections,
421
+ policySkipTotal: byWhy['policy-skip'] + byWhy.quiet,
422
+ policySkip: { other: byWhy['policy-skip'], quiet: byWhy.quiet },
423
+ zeroHitTotal: byWhy['zero-hit'],
424
+ errorTotal: byWhy.error,
425
+ everyNTurnsTotal: byWhy.everyNTurns,
426
+ forcedTotal,
427
+ userTaskTotal: byWhy['user-task'],
428
+ archiveUnavailableTotal,
429
+ linkInjectedTotal,
430
+ dropped,
431
+ lastAt,
432
+ };
433
+ }
@@ -0,0 +1,138 @@
1
+ /**
2
+ * 1.8.8 M2 强制触发策略(纯函数,无 IO、无随机、无时钟)。
3
+ *
4
+ * 用户原话(1.8.8 需求):触发太钝、不够强制——「我说我要做什么,就直连老记忆」。
5
+ * 所以 M2 在 `agent/pre-step` 的第 1 步加一条**用户任务消息**的强制通道:
6
+ *
7
+ * step===1 且最后一条消息是真实 user 消息(isRealUserMessage)
8
+ * 且这条消息**不是纯应答** → 强制召回一次,不再看 everyNTurns、不被 quiet 挡。
9
+ *
10
+ * 纯应答的机械判据(规格 §2.2,可复算、不是语义猜测):
11
+ * 去掉空白/标点/emoji 后,长度 ≤ ACK_MAX_CHARS 且不含任何任务动词。
12
+ * 例:好 / 嗯 / ok / 继续 / 谢谢 / 收到 / 好的,继续。
13
+ * 「继续」被用户列为纯应答样例,所以它**不在**任务动词表里。
14
+ *
15
+ * 问句例外(1.8.11 R11 P1-4 修订,SPEC §3 验收 #4):
16
+ * 短问句(如「五问是哪五问?」)虽然 ≤ ACK_MAX_CHARS,但它是提问、不是应答,
17
+ * 必须进强制召回通道。机械判据(不看语义):
18
+ * 原文含问号(?/?)或含疑问词(哪/什么/怎么/为什么/吗/呢/是否/几)。
19
+ * 这条规则**先于长度判定**:命中即非纯应答,不看字数。
20
+ * 「好了吗」「收到??」这类也会被当问句,属于机械规则的既定取舍(宁可多插一次)。
21
+ *
22
+ * 边界(写进 docs/AUTO-RECALL.md,别当秘密):
23
+ * - 长度 ≤6 且没有任务动词、也没有问句信号的真实短任务(如「v39战役」)会被当纯应答跳过;
24
+ * 这是按规格的机械规则执行的既定取舍,宁可少插一次,也不在每句应答后灌上下文。
25
+ * - 任务动词表/疑问词表是固定常量,不从记忆/配置里学;改词表会改行为,属于版本变更。
26
+ */
27
+
28
+ /** 纯应答的最大「去空白/标点后」字符数(规格 §2.2)。 */
29
+ export const ACK_MAX_CHARS = 6;
30
+
31
+ /**
32
+ * 问号字符:原文里出现任意一个就按问句处理(不需要成对判断)。
33
+ * 用原文判断而不是 compactText,因为标点会被 compactText 去掉。
34
+ */
35
+ export const QUESTION_MARKS = Object.freeze(['?', '?']);
36
+
37
+ /**
38
+ * 疑问词:原文包含任意一个就按问句处理(机械规则,不做语法判断)。
39
+ * 覆盖 SPEC §3 验收 #4 的实际问句「五问是哪五问?」(命中「哪」)。
40
+ */
41
+ export const QUESTION_WORDS = Object.freeze(['哪', '什么', '怎么', '为什么', '吗', '呢', '是否', '几']);
42
+
43
+ /**
44
+ * 任务动词:出现任意一个就说明这条消息在派活/改方向,不是纯应答。
45
+ * 注意:`继续`、`好`、`行`、`可以`、`收到`、`谢谢`、`嗯`、`ok` 都不在这里
46
+ * (它们是用户明确列出的纯应答样例)。
47
+ */
48
+ export const TASK_VERBS = Object.freeze([
49
+ // 动作类
50
+ '做', '搞', '弄', '办', '干', '改', '修', '写', '读', '看', '查', '找', '搜',
51
+ '跑', '测', '试', '装', '卸', '删', '加', '换', '发', '停', '开', '关', '搬',
52
+ // 交付类
53
+ '发布', '部署', '上线', '重启', '启动', '同步', '更新', '升级', '整理', '清理',
54
+ '推进', '继续做', '接着做', '帮我', '检查', '确认', '核对',
55
+ '对比', '分析', '实现', '补齐', '补', '迁移', '回滚', '恢复', '备份', '导出',
56
+ '导入', '生成', '识别', '扒', '编', '混', '配', '调', '渲染', '验收', '签字',
57
+ '审', '下载', '上传', '安装', '提交', '推送', '合并', '建', '拆', '编译', '打包',
58
+ '优化', '排查', '定位', '复现', '跑一遍', '来一份', '来一段', '来一个',
59
+ ]);
60
+
61
+ /** 纯应答示例(给测试/文档对齐用;判定本身不依赖这个表)。 */
62
+ export const ACK_EXAMPLES = Object.freeze(['好', '嗯', 'ok', '继续', '谢谢', '收到', '好的', '行', '可以']);
63
+
64
+ /**
65
+ * 只保留「真正的字」:去掉空白、标点、符号、emoji、markdown 记号。
66
+ * 与 recall-core 的 norm 不同:这里只用于长度/词表判定,不参与打分。
67
+ * @param {string} text
68
+ * @returns {string}
69
+ */
70
+ export function compactText(text) {
71
+ return String(text ?? '').replace(/[\s\p{P}\p{S}\p{Extended_Pictographic}]+/gu, '');
72
+ }
73
+
74
+ /**
75
+ * 消息是否含任务动词(在**原文**里找;动词本身可能被标点隔开)。
76
+ * @param {string} text
77
+ * @returns {boolean}
78
+ */
79
+ export function hasTaskVerb(text) {
80
+ const compact = compactText(text);
81
+ if (compact === '') return false;
82
+ return TASK_VERBS.some((verb) => compact.includes(verb));
83
+ }
84
+
85
+ /**
86
+ * 消息是否带问句信号(原文判断:问号或疑问词)。
87
+ * @param {string} text
88
+ * @returns {boolean}
89
+ */
90
+ export function hasQuestionSignal(text) {
91
+ const raw = String(text ?? '');
92
+ if (raw === '') return false;
93
+ if (QUESTION_MARKS.some((mark) => raw.includes(mark))) return true;
94
+ return QUESTION_WORDS.some((word) => raw.includes(word));
95
+ }
96
+
97
+ /**
98
+ * 纯应答判定:去空白/标点后长度 ≤ ACK_MAX_CHARS 且不含任务动词、且无问句信号。
99
+ * 空消息按纯应答处理(不触发强制召回)。
100
+ * 问句信号优先于长度(1.8.11 P1-4):短问句不是应答。
101
+ * @param {string} text
102
+ * @returns {boolean}
103
+ */
104
+ export function isPureAcknowledgement(text) {
105
+ const raw = String(text ?? '');
106
+ const compact = compactText(raw);
107
+ if (compact === '') return true;
108
+ if (hasQuestionSignal(raw)) return false;
109
+ if (Array.from(compact).length > ACK_MAX_CHARS) return false;
110
+ return !hasTaskVerb(raw);
111
+ }
112
+
113
+ /**
114
+ * 这条真实用户消息是否应当触发「强制召回」。
115
+ * 只有真实用户消息才谈得上强制;空消息/纯应答返回 false。
116
+ * @param {string} text
117
+ * @returns {boolean}
118
+ */
119
+ export function shouldForceRecallForMessage(text) {
120
+ const raw = String(text ?? '').trim();
121
+ if (raw === '') return false;
122
+ return !isPureAcknowledgement(raw);
123
+ }
124
+
125
+ /**
126
+ * 反馈词判定(在线学习用;也放这里,避免 learning 模块自己再定义一套口径)。
127
+ * 只判「上一轮注入之后他这句是在确认还是否认」,不做更多语义推断。
128
+ * 否认优先:一句里同时出现「不是这个…就对了」按否认算(宁可少加权重)。
129
+ * @param {string} text
130
+ * @returns {'confirm'|'deny'|null}
131
+ */
132
+ export function classifyLinkFeedback(text) {
133
+ const s = String(text ?? '').trim();
134
+ if (s === '') return null;
135
+ if (/(不对|不是这个|不是它|不是我要|不是那张|错了|搞错|记错|弄错|不准确|没对上|不相关)/u.test(s)) return 'deny';
136
+ if (/(对的|对呀|对。|对,|对$|就是这个|就是它|没错|正是|准确|精准|靠谱|这个对|就是这张|对了)/u.test(s)) return 'confirm';
137
+ return null;
138
+ }