@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,463 @@
1
+ // 策略 profile 加载器:generic 是唯一默认层,owner profile 只能在其上收窄或补充。
2
+ // 这一层刻意放在 src/router 之外:判定层(route.js)可以 import 它,
3
+ // 但产品代码(index.js)不需要 import 任何带 router 字样的模块。
4
+ import { readFileSync } from 'node:fs';
5
+ import { applyAdapterPolicy } from './adapters/registry.js';
6
+
7
+ export const POLICY_PROFILE_DEFAULT = 'generic';
8
+ export const POLICY_PROFILE_BASE = 'generic';
9
+ export const POLICY_PROFILE_SOURCE = 'example-policy';
10
+ export const POLICY_PROFILE_DIR = new URL('./router/policies/', import.meta.url);
11
+
12
+ export const E_ROUTE_PROFILE_UNKNOWN = 'E_ROUTE_PROFILE_UNKNOWN';
13
+ export const E_ROUTE_POLICY_INVALID = 'E_ROUTE_POLICY_INVALID';
14
+
15
+ const PROFILE_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
16
+ const BASE_KEYS = new Set([
17
+ '$schema', 'name', 'description', 'version', 'source', 'failClosed', 'extends', 'rulings',
18
+ 'thresholds', 'limits', 'ask', 'privacy', 'rest', 'distill', 'revise', 'identity', 'writeScope'
19
+ ]);
20
+ const OVERLAY_KEYS = new Set([
21
+ '$schema', 'name', 'description', 'version', 'extends', 'source', 'failClosed', 'rulings',
22
+ 'thresholds', 'limits', 'ask', 'privacy', 'rest', 'distill', 'revise', 'identity', 'writeScope'
23
+ ]);
24
+ const SECTION_KEYS = {
25
+ thresholds: ['principle', 'compressAt', 'redAt', 'dispatchAt', 'taskboardAt'],
26
+ limits: ['principle', 'maxRules', 'maxDecisions', 'maxCompeting'],
27
+ ask: ['principle', 'maxQuestions', 'maxCandidates', 'guessAllowed', 'missing', 'prompt'],
28
+ privacy: ['principle', 'markers', 'extraMarkers', 'store', 'dataClass', 'retention', 'echoBack', 'networkCalls', 'uploadAllowed'],
29
+ rest: ['principle', 'markers', 'terminators', 'kind', 'resumable', 'terminal', 'resumePoint', 'resumePointRequired', 'pendingTask', 'forbiddenActions'],
30
+ distill: ['principle', 'preferDistill', 'deleteBeforeConfirm', 'requireSupersedes', 'maxQuestions'],
31
+ revise: ['principle', 'needsHuman'],
32
+ identity: ['principle', 'consentHolder', 'userConsentCounts', 'requireQuote', 'requireQuoteId'],
33
+ writeScope: ['principle', 'note', 'allowPrefixes']
34
+ };
35
+
36
+ let configuredName = POLICY_PROFILE_DEFAULT;
37
+
38
+ function isObject(value) {
39
+ return !!value && typeof value === 'object' && !Array.isArray(value);
40
+ }
41
+
42
+ function isNonEmptyString(value) {
43
+ return typeof value === 'string' && value.trim().length > 0;
44
+ }
45
+
46
+ function isStringArray(value, { allowEmpty = false } = {}) {
47
+ if (!Array.isArray(value)) return false;
48
+ if (!allowEmpty && value.length === 0) return false;
49
+ return value.every(isNonEmptyString);
50
+ }
51
+
52
+ function uniquePrefixes(list) {
53
+ return [...new Set(list)];
54
+ }
55
+
56
+ function unknownKeys(object, allowed) {
57
+ return Object.keys(object).filter((key) => !allowed.includes(key));
58
+ }
59
+
60
+ function safeScopePrefix(value) {
61
+ if (!isNonEmptyString(value)) return false;
62
+ if (/^[A-Za-z]:/.test(value)) return false;
63
+ if (value.startsWith('/') || value.startsWith('\\') || value.startsWith('~')) return false;
64
+ if (value.includes('..') || value.includes('\\')) return false;
65
+ return true;
66
+ }
67
+
68
+ function invalid(name, detail) {
69
+ return {
70
+ ok: false,
71
+ name,
72
+ code: E_ROUTE_POLICY_INVALID,
73
+ message: `策略文件 ${name}.json 不合法:${detail}`
74
+ };
75
+ }
76
+
77
+ function unknown(name) {
78
+ return {
79
+ ok: false,
80
+ name,
81
+ code: E_ROUTE_PROFILE_UNKNOWN,
82
+ message: `未找到策略 profile「${name}」:可选值见 src/router/policies/*.json`
83
+ };
84
+ }
85
+
86
+ function validateThresholds(base, section, where, fail) {
87
+ if (!isObject(section)) return fail(`${where} 必须是对象`);
88
+ const extra = unknownKeys(section, SECTION_KEYS.thresholds);
89
+ if (extra.length) return fail(`${where} 有未知字段 ${extra.join(', ')}`);
90
+ for (const key of ['compressAt', 'redAt', 'dispatchAt', 'taskboardAt']) {
91
+ if (section[key] === undefined) continue;
92
+ if (!Number.isInteger(section[key])) return fail(`${where}.${key} 必须是整数`);
93
+ if (section[key] < 0) return fail(`${where}.${key} 不能为负数`);
94
+ }
95
+ if (section.compressAt !== undefined && section.compressAt <= 0) return fail(`${where}.compressAt 必须 > 0`);
96
+ const compressAt = section.compressAt ?? base.compressAt;
97
+ const redAt = section.redAt ?? base.redAt;
98
+ if (redAt <= compressAt) return fail(`${where}.redAt 必须大于 compressAt`);
99
+ if (section.compressAt !== undefined && section.compressAt > base.compressAt) {
100
+ return fail(`${where}.compressAt 不能放宽(> ${base.compressAt})`);
101
+ }
102
+ if (section.redAt !== undefined && section.redAt > base.redAt) {
103
+ return fail(`${where}.redAt 不能放宽(> ${base.redAt})`);
104
+ }
105
+ if (section.dispatchAt !== undefined && section.dispatchAt < base.dispatchAt) {
106
+ return fail(`${where}.dispatchAt 不能放宽(< ${base.dispatchAt})`);
107
+ }
108
+ if (section.taskboardAt !== undefined && section.taskboardAt < base.taskboardAt) {
109
+ return fail(`${where}.taskboardAt 不能放宽(< ${base.taskboardAt})`);
110
+ }
111
+ return null;
112
+ }
113
+
114
+ function validateLimits(base, section, where, fail) {
115
+ if (!isObject(section)) return fail(`${where} 必须是对象`);
116
+ const extra = unknownKeys(section, SECTION_KEYS.limits);
117
+ if (extra.length) return fail(`${where} 有未知字段 ${extra.join(', ')}`);
118
+ for (const key of ['maxRules', 'maxDecisions', 'maxCompeting']) {
119
+ if (section[key] === undefined) continue;
120
+ if (!Number.isInteger(section[key]) || section[key] < 1) return fail(`${where}.${key} 必须是正整数`);
121
+ if (section[key] > base[key]) return fail(`${where}.${key} 不能放宽(> ${base[key]})`);
122
+ }
123
+ return null;
124
+ }
125
+
126
+ function validateAsk(base, section, where, fail) {
127
+ if (!isObject(section)) return fail(`${where} 必须是对象`);
128
+ const extra = unknownKeys(section, SECTION_KEYS.ask);
129
+ if (extra.length) return fail(`${where} 有未知字段 ${extra.join(', ')}`);
130
+ if (section.maxQuestions !== undefined) {
131
+ if (!Number.isInteger(section.maxQuestions) || section.maxQuestions < 1 || section.maxQuestions > base.maxQuestions) {
132
+ return fail(`${where}.maxQuestions 必须在 1..${base.maxQuestions}`);
133
+ }
134
+ }
135
+ if (section.maxCandidates !== undefined) {
136
+ if (!Number.isInteger(section.maxCandidates) || section.maxCandidates < 1 || section.maxCandidates > base.maxCandidates) {
137
+ return fail(`${where}.maxCandidates 必须在 1..${base.maxCandidates}`);
138
+ }
139
+ }
140
+ if (section.guessAllowed !== undefined && section.guessAllowed !== false) {
141
+ return fail(`${where}.guessAllowed 不能改成 true(含糊必问)`);
142
+ }
143
+ if (section.missing !== undefined) {
144
+ if (!isStringArray(section.missing)) return fail(`${where}.missing 必须是非空字符串数组`);
145
+ const widened = section.missing.filter((item) => !base.missing.includes(item));
146
+ if (widened.length) return fail(`${where}.missing 不能新增维度 ${widened.join(', ')}`);
147
+ }
148
+ if (section.prompt !== undefined && !isNonEmptyString(section.prompt)) return fail(`${where}.prompt 必须是非空字符串`);
149
+ return null;
150
+ }
151
+
152
+ function validatePrivacy(base, section, where, fail) {
153
+ if (!isObject(section)) return fail(`${where} 必须是对象`);
154
+ const extra = unknownKeys(section, SECTION_KEYS.privacy);
155
+ if (extra.length) return fail(`${where} 有未知字段 ${extra.join(', ')}`);
156
+ for (const key of ['markers', 'extraMarkers']) {
157
+ if (section[key] !== undefined && !isStringArray(section[key])) return fail(`${where}.${key} 必须是字符串数组`);
158
+ }
159
+ if (section.echoBack !== undefined && section.echoBack !== false) return fail(`${where}.echoBack 不能改成 true`);
160
+ if (section.networkCalls !== undefined && section.networkCalls !== 0) return fail(`${where}.networkCalls 必须为 0`);
161
+ if (section.uploadAllowed !== undefined && section.uploadAllowed !== false) return fail(`${where}.uploadAllowed 必须为 false`);
162
+ return null;
163
+ }
164
+
165
+ function validateRest(base, section, where, fail) {
166
+ if (!isObject(section)) return fail(`${where} 必须是对象`);
167
+ const extra = unknownKeys(section, SECTION_KEYS.rest);
168
+ if (extra.length) return fail(`${where} 有未知字段 ${extra.join(', ')}`);
169
+ if (section.resumePoint !== undefined && !isNonEmptyString(section.resumePoint)) {
170
+ return fail(`${where}.resumePoint 必须是非空字符串`);
171
+ }
172
+ if (section.resumePointRequired !== undefined && section.resumePointRequired !== true) {
173
+ return fail(`${where}.resumePointRequired 不能改成 false`);
174
+ }
175
+ if (section.kind !== undefined && section.kind !== 'TEMPORARY') return fail(`${where}.kind 只能是 TEMPORARY`);
176
+ if (section.resumable !== undefined && section.resumable !== true) return fail(`${where}.resumable 不能改成 false`);
177
+ if (section.terminal !== undefined && section.terminal !== false) return fail(`${where}.terminal 不能改成 true`);
178
+ if (section.forbiddenActions !== undefined) {
179
+ if (!isStringArray(section.forbiddenActions)) return fail(`${where}.forbiddenActions 必须是字符串数组`);
180
+ const missing = base.forbiddenActions.filter((item) => !section.forbiddenActions.includes(item));
181
+ if (missing.length) return fail(`${where}.forbiddenActions 不能删项 ${missing.join(', ')}`);
182
+ }
183
+ return null;
184
+ }
185
+
186
+ function validateDistill(base, section, where, fail) {
187
+ if (!isObject(section)) return fail(`${where} 必须是对象`);
188
+ const extra = unknownKeys(section, SECTION_KEYS.distill);
189
+ if (extra.length) return fail(`${where} 有未知字段 ${extra.join(', ')}`);
190
+ if (section.preferDistill !== undefined && section.preferDistill !== true) return fail(`${where}.preferDistill 不能改成 false`);
191
+ if (section.deleteBeforeConfirm !== undefined && section.deleteBeforeConfirm !== false) {
192
+ return fail(`${where}.deleteBeforeConfirm 不能改成 true`);
193
+ }
194
+ if (section.requireSupersedes !== undefined && section.requireSupersedes !== true) {
195
+ return fail(`${where}.requireSupersedes 不能改成 false`);
196
+ }
197
+ if (section.maxQuestions !== undefined) {
198
+ if (!Number.isInteger(section.maxQuestions) || section.maxQuestions < 1 || section.maxQuestions > base.maxQuestions) {
199
+ return fail(`${where}.maxQuestions 必须在 1..${base.maxQuestions}`);
200
+ }
201
+ }
202
+ return null;
203
+ }
204
+
205
+ function validateIdentity(section, where, fail) {
206
+ if (!isObject(section)) return fail(`${where} 必须是对象`);
207
+ const extra = unknownKeys(section, SECTION_KEYS.identity);
208
+ if (extra.length) return fail(`${where} 有未知字段 ${extra.join(', ')}`);
209
+ if (section.consentHolder !== undefined && section.consentHolder !== 'assistant') {
210
+ return fail(`${where}.consentHolder 只能是 assistant`);
211
+ }
212
+ if (section.userConsentCounts !== undefined && section.userConsentCounts !== false) {
213
+ return fail(`${where}.userConsentCounts 不能改成 true`);
214
+ }
215
+ if (section.requireQuote !== undefined && section.requireQuote !== true) {
216
+ return fail(`${where}.requireQuote 不能改成 false`);
217
+ }
218
+ if (section.requireQuoteId !== undefined && section.requireQuoteId !== true) {
219
+ return fail(`${where}.requireQuoteId 只能收窄为 true`);
220
+ }
221
+ return null;
222
+ }
223
+
224
+ function validateWriteScope(base, section, where, fail) {
225
+ if (!isObject(section)) return fail(`${where} 必须是对象`);
226
+ const extra = unknownKeys(section, SECTION_KEYS.writeScope);
227
+ if (extra.length) return fail(`${where} 有未知字段 ${extra.join(', ')}`);
228
+ if (section.allowPrefixes === undefined) return null;
229
+ if (!isStringArray(section.allowPrefixes)) return fail(`${where}.allowPrefixes 必须是非空字符串数组`);
230
+ const bad = section.allowPrefixes.filter((prefix) => !safeScopePrefix(prefix));
231
+ if (bad.length) return fail(`${where}.allowPrefixes 含不安全前缀 ${bad.join(', ')}`);
232
+ const widened = section.allowPrefixes.filter((prefix) => !base.allowPrefixes.includes(prefix));
233
+ if (widened.length) return fail(`${where}.allowPrefixes 不能新增 ${widened.join(', ')}`);
234
+ return null;
235
+ }
236
+
237
+ function validateBase(value, expectedName) {
238
+ const fail = (detail) => invalid(expectedName, detail);
239
+ if (!isObject(value)) return fail('根节点必须是对象');
240
+ const extra = Object.keys(value).filter((key) => !BASE_KEYS.has(key));
241
+ if (extra.length) return fail(`有未知字段 ${extra.join(', ')}`);
242
+ if (value.name !== expectedName) return fail(`name 必须是「${expectedName}」`);
243
+ if (value.failClosed !== true) return fail('failClosed 必须为 true');
244
+ for (const key of ['thresholds', 'limits', 'ask', 'privacy', 'rest', 'distill', 'revise', 'identity', 'writeScope']) {
245
+ if (!isObject(value[key])) return fail(`缺少 ${key} 段`);
246
+ }
247
+ const sectionFail = (detail) => fail(detail);
248
+ let problem = validateThresholds(value.thresholds, value.thresholds, 'thresholds', sectionFail);
249
+ if (problem) return problem;
250
+ problem = validateLimits(value.limits, value.limits, 'limits', sectionFail);
251
+ if (problem) return problem;
252
+ problem = validateAsk(value.ask, value.ask, 'ask', sectionFail);
253
+ if (problem) return problem;
254
+ problem = validatePrivacy(value.privacy, value.privacy, 'privacy', sectionFail);
255
+ if (problem) return problem;
256
+ problem = validateRest(value.rest, value.rest, 'rest', sectionFail);
257
+ if (problem) return problem;
258
+ problem = validateDistill(value.distill, value.distill, 'distill', sectionFail);
259
+ if (problem) return problem;
260
+ problem = validateWriteScope(value.writeScope, value.writeScope, 'writeScope', sectionFail);
261
+ if (problem) return problem;
262
+ for (const key of ['compressAt', 'redAt', 'dispatchAt', 'taskboardAt']) {
263
+ if (!Number.isInteger(value.thresholds[key])) return fail(`thresholds.${key} 必须是整数`);
264
+ }
265
+ for (const key of ['maxRules', 'maxDecisions', 'maxCompeting']) {
266
+ if (!Number.isInteger(value.limits[key]) || value.limits[key] < 1) return fail(`limits.${key} 必须是正整数`);
267
+ }
268
+ if (!Number.isInteger(value.ask.maxQuestions) || value.ask.maxQuestions < 1) return fail('ask.maxQuestions 必须是正整数');
269
+ if (!Number.isInteger(value.ask.maxCandidates) || value.ask.maxCandidates < 1) return fail('ask.maxCandidates 必须是正整数');
270
+ if (value.ask.guessAllowed !== false) return fail('ask.guessAllowed 必须为 false');
271
+ if (!isStringArray(value.ask.missing)) return fail('ask.missing 必须是非空字符串数组');
272
+ if (!isNonEmptyString(value.ask.prompt)) return fail('ask.prompt 必须是非空字符串');
273
+ if (!isStringArray(value.privacy.markers)) return fail('privacy.markers 必须是非空字符串数组');
274
+ if (!safeScopePrefix(value.privacy.store)) return fail('privacy.store 必须是安全的相对路径');
275
+ if (!isNonEmptyString(value.privacy.dataClass)) return fail('privacy.dataClass 必须是非空字符串');
276
+ if (!isNonEmptyString(value.privacy.retention)) return fail('privacy.retention 必须是非空字符串');
277
+ if (value.privacy.echoBack !== false) return fail('privacy.echoBack 必须为 false');
278
+ if (value.privacy.networkCalls !== 0) return fail('privacy.networkCalls 必须为 0');
279
+ if (value.privacy.uploadAllowed !== false) return fail('privacy.uploadAllowed 必须为 false');
280
+ if (!isStringArray(value.rest.markers)) return fail('rest.markers 必须是非空字符串数组');
281
+ if (!isStringArray(value.rest.terminators)) return fail('rest.terminators 必须是非空字符串数组');
282
+ if (value.rest.kind !== 'TEMPORARY') return fail('rest.kind 必须是 TEMPORARY');
283
+ if (value.rest.resumable !== true) return fail('rest.resumable 必须为 true');
284
+ if (value.rest.terminal !== false) return fail('rest.terminal 必须为 false');
285
+ if (!isNonEmptyString(value.rest.resumePoint)) return fail('rest.resumePoint 必须是非空字符串');
286
+ if (value.rest.resumePointRequired !== true) return fail('rest.resumePointRequired 必须为 true');
287
+ if (value.rest.pendingTask !== 'keep') return fail('rest.pendingTask 必须是 keep');
288
+ if (!isStringArray(value.rest.forbiddenActions)) return fail('rest.forbiddenActions 必须是非空字符串数组');
289
+ if (value.distill.preferDistill !== true) return fail('distill.preferDistill 必须为 true');
290
+ if (value.distill.deleteBeforeConfirm !== false) return fail('distill.deleteBeforeConfirm 必须为 false');
291
+ if (value.distill.requireSupersedes !== true) return fail('distill.requireSupersedes 必须为 true');
292
+ if (value.revise.needsHuman !== false) return fail('revise.needsHuman 必须为 false');
293
+ if (value.identity.consentHolder !== 'assistant') return fail('identity.consentHolder 必须是 assistant');
294
+ if (value.identity.userConsentCounts !== false) return fail('identity.userConsentCounts 必须为 false');
295
+ if (value.identity.requireQuote !== true) return fail('identity.requireQuote 必须为 true');
296
+ if (typeof value.identity.requireQuoteId !== 'boolean') return fail('identity.requireQuoteId 必须是布尔值');
297
+ if (!isStringArray(value.writeScope.allowPrefixes)) return fail('writeScope.allowPrefixes 必须是非空字符串数组');
298
+ for (const prefix of value.writeScope.allowPrefixes) {
299
+ if (!safeScopePrefix(prefix)) return fail(`writeScope.allowPrefixes 含不安全前缀 ${prefix}`);
300
+ }
301
+ return null;
302
+ }
303
+
304
+ function validateRulings(rulings, fail) {
305
+ if (!Array.isArray(rulings) || rulings.length === 0) return fail('rulings 必须是非空数组');
306
+ const ids = new Set();
307
+ for (const [index, ruling] of rulings.entries()) {
308
+ const where = `rulings[${index}]`;
309
+ if (!isObject(ruling)) return fail(`${where} 必须是对象`);
310
+ const extra = Object.keys(ruling).filter((key) => !['id', 'title', 'rule', 'source', 'quote'].includes(key));
311
+ if (extra.length) return fail(`${where} 有未知字段 ${extra.join(', ')}`);
312
+ for (const key of ['id', 'title', 'rule', 'source']) {
313
+ if (!isNonEmptyString(ruling[key])) return fail(`${where}.${key} 必须是非空字符串`);
314
+ }
315
+ if (ruling.quote !== undefined && !isNonEmptyString(ruling.quote)) return fail(`${where}.quote 必须是非空字符串`);
316
+ if (ruling.source !== POLICY_PROFILE_SOURCE) return fail(`${where}.source 必须是 ${POLICY_PROFILE_SOURCE}`);
317
+ if (ids.has(ruling.id)) return fail(`${where}.id 重复:${ruling.id}`);
318
+ ids.add(ruling.id);
319
+ }
320
+ return null;
321
+ }
322
+
323
+ function validateOverlay(value, base, expectedName) {
324
+ const fail = (detail) => invalid(expectedName, detail);
325
+ if (!isObject(value)) return fail('根节点必须是对象');
326
+ const extra = Object.keys(value).filter((key) => !OVERLAY_KEYS.has(key));
327
+ if (extra.length) return fail(`有未知字段 ${extra.join(', ')}`);
328
+ if (value.name !== expectedName) return fail(`name 必须是「${expectedName}」`);
329
+ if (value.extends !== POLICY_PROFILE_BASE) return fail(`extends 必须是 ${POLICY_PROFILE_BASE}`);
330
+ if (value.failClosed !== undefined && value.failClosed !== true) return fail('failClosed 不能改成 false');
331
+ const sections = ['thresholds', 'limits', 'ask', 'privacy', 'rest', 'distill', 'revise', 'identity', 'writeScope'];
332
+ const declared = sections.filter((key) => value[key] !== undefined);
333
+ if (declared.length === 0 && value.rulings === undefined) return fail('至少声明一个差异段或 rulings');
334
+ const sectionFail = (detail) => fail(detail);
335
+ let problem = null;
336
+ if (value.thresholds !== undefined) problem = validateThresholds(base.thresholds, value.thresholds, 'thresholds', sectionFail);
337
+ if (!problem && value.limits !== undefined) problem = validateLimits(base, value.limits, 'limits', sectionFail);
338
+ if (!problem && value.ask !== undefined) problem = validateAsk(base.ask, value.ask, 'ask', sectionFail);
339
+ if (!problem && value.privacy !== undefined) problem = validatePrivacy(base.privacy, value.privacy, 'privacy', sectionFail);
340
+ if (!problem && value.rest !== undefined) problem = validateRest(base.rest, value.rest, 'rest', sectionFail);
341
+ if (!problem && value.distill !== undefined) problem = validateDistill(base.distill, value.distill, 'distill', sectionFail);
342
+ if (!problem && value.revise !== undefined) {
343
+ if (!isObject(value.revise)) problem = fail('revise 必须是对象');
344
+ else {
345
+ const extraRevise = unknownKeys(value.revise, SECTION_KEYS.revise);
346
+ if (extraRevise.length) problem = fail(`revise 有未知字段 ${extraRevise.join(', ')}`);
347
+ else if (value.revise.needsHuman !== undefined && value.revise.needsHuman !== false) problem = fail('revise.needsHuman 不能改成 true');
348
+ }
349
+ }
350
+ if (!problem && value.identity !== undefined) problem = validateIdentity(value.identity, 'identity', sectionFail);
351
+ if (!problem && value.writeScope !== undefined) problem = validateWriteScope(base.writeScope, value.writeScope, 'writeScope', sectionFail);
352
+ if (!problem && value.rulings !== undefined) problem = validateRulings(value.rulings, sectionFail);
353
+ return problem;
354
+ }
355
+
356
+ export function mergePolicyProfile(base, overlay) {
357
+ const merged = JSON.parse(JSON.stringify(base));
358
+ merged.name = overlay.name;
359
+ merged.extends = POLICY_PROFILE_BASE;
360
+ merged.source = overlay.source || base.source;
361
+ merged.rulings = overlay.rulings ? JSON.parse(JSON.stringify(overlay.rulings)) : [];
362
+ if (overlay.description !== undefined) merged.description = overlay.description;
363
+
364
+ if (overlay.thresholds) Object.assign(merged.thresholds, overlay.thresholds);
365
+ if (overlay.limits) Object.assign(merged.limits, overlay.limits);
366
+ if (overlay.ask) Object.assign(merged.ask, overlay.ask);
367
+ if (overlay.privacy) {
368
+ const markers = [
369
+ ...base.privacy.markers,
370
+ ...(overlay.privacy.markers || []),
371
+ ...(overlay.privacy.extraMarkers || [])
372
+ ];
373
+ merged.privacy.markers = uniquePrefixes(markers);
374
+ merged.privacy.extraMarkers = (overlay.privacy.extraMarkers || []).slice();
375
+ if (overlay.privacy.echoBack !== undefined) merged.privacy.echoBack = overlay.privacy.echoBack;
376
+ if (overlay.privacy.networkCalls !== undefined) merged.privacy.networkCalls = overlay.privacy.networkCalls;
377
+ if (overlay.privacy.uploadAllowed !== undefined) merged.privacy.uploadAllowed = overlay.privacy.uploadAllowed;
378
+ }
379
+ if (overlay.rest) {
380
+ if (overlay.rest.resumePoint !== undefined) merged.rest.resumePoint = overlay.rest.resumePoint;
381
+ if (overlay.rest.forbiddenActions !== undefined) {
382
+ merged.rest.forbiddenActions = uniquePrefixes([...base.rest.forbiddenActions, ...overlay.rest.forbiddenActions]);
383
+ }
384
+ }
385
+ if (overlay.distill) Object.assign(merged.distill, overlay.distill);
386
+ if (overlay.revise) Object.assign(merged.revise, overlay.revise);
387
+ if (overlay.identity) Object.assign(merged.identity, overlay.identity);
388
+ if (overlay.writeScope && overlay.writeScope.allowPrefixes !== undefined) {
389
+ merged.writeScope.allowPrefixes = overlay.writeScope.allowPrefixes.slice();
390
+ }
391
+ return merged;
392
+ }
393
+
394
+ function readProfile(name, dir = POLICY_PROFILE_DIR) {
395
+ const url = new URL(`${name}.json`, dir);
396
+ let text;
397
+ try {
398
+ text = readFileSync(url, 'utf8');
399
+ } catch (error) {
400
+ if (error && (error.code === 'ENOENT' || error.code === 'ENOTDIR')) return { error: unknown(name) };
401
+ return { error: invalid(name, `读取失败:${error && error.message ? error.message : String(error)}`) };
402
+ }
403
+ try {
404
+ return { value: JSON.parse(text) };
405
+ } catch (error) {
406
+ return { error: invalid(name, `JSON 解析失败:${error && error.message ? error.message : String(error)}`) };
407
+ }
408
+ }
409
+
410
+ // options.dir 只给测试用:指向另一份 policies/(URL),用来在 tmp 里放坏文件,
411
+ // 避免套件运行期间往包树写样本(P6 会给包树拍快照)。生产调用不传。
412
+ export function loadPolicyProfile(name = POLICY_PROFILE_DEFAULT, options = {}) {
413
+ if (!isNonEmptyString(name) || !PROFILE_NAME_RE.test(name)) return unknown(String(name));
414
+ const dir = options && options.dir ? options.dir : POLICY_PROFILE_DIR;
415
+ const baseRead = readProfile(POLICY_PROFILE_BASE, dir);
416
+ if (baseRead.error) return baseRead.error;
417
+ const baseProblem = validateBase(baseRead.value, POLICY_PROFILE_BASE);
418
+ if (baseProblem) return baseProblem;
419
+ const base = baseRead.value;
420
+ if (name === POLICY_PROFILE_BASE) {
421
+ // M2-E:adapter 策略片段(第三方写作用域等)在核心 profile 校验后并入;失败仅降级。
422
+ const patched = applyAdapterPolicy(base);
423
+ if (patched.degraded) {
424
+ return { ok: true, name, policy: patched.policy, sources: [`${name}.json`], adapterDegraded: patched.errors };
425
+ }
426
+ const patchedProblem = validateBase(patched.policy, name);
427
+ if (patchedProblem) return patchedProblem;
428
+ return { ok: true, name, policy: patched.policy, sources: [`${name}.json`] };
429
+ }
430
+ const overlayRead = readProfile(name, dir);
431
+ if (overlayRead.error) return overlayRead.error;
432
+ const overlayProblem = validateOverlay(overlayRead.value, base, name);
433
+ if (overlayProblem) return overlayProblem;
434
+ const policy = mergePolicyProfile(base, overlayRead.value);
435
+ const mergedProblem = validateBase(policy, name);
436
+ if (mergedProblem) return mergedProblem;
437
+ // M2-E:adapter 策略片段并入(失败仅降级,不阻塞核心 profile)。
438
+ const patched = applyAdapterPolicy(policy);
439
+ if (patched.degraded) {
440
+ return { ok: true, name, policy: patched.policy, sources: [`${POLICY_PROFILE_BASE}.json`, `${name}.json`], adapterDegraded: patched.errors };
441
+ }
442
+ const patchedProblem = validateBase(patched.policy, name);
443
+ if (patchedProblem) return patchedProblem;
444
+ return { ok: true, name, policy: patched.policy, sources: [`${POLICY_PROFILE_BASE}.json`, `${name}.json`] };
445
+ }
446
+
447
+ export function configurePolicyProfile(name) {
448
+ const requested = name === undefined || name === null || name === '' ? POLICY_PROFILE_DEFAULT : name;
449
+ configuredName = typeof requested === 'string' ? requested : String(requested);
450
+ return loadPolicyProfile(configuredName);
451
+ }
452
+
453
+ export function configuredPolicyProfileName() {
454
+ return configuredName;
455
+ }
456
+
457
+ export function resetPolicyProfileForTests() {
458
+ configuredName = POLICY_PROFILE_DEFAULT;
459
+ }
460
+
461
+ export function isPolicyProfileName(name) {
462
+ return isNonEmptyString(name) && PROFILE_NAME_RE.test(name);
463
+ }
@@ -0,0 +1,87 @@
1
+ // src/recall/anaphora.mjs — B2:指代链解析(它/这个/那个/他/她/上面/刚才)
2
+ //
3
+ // 只用上下文(焦点实体 + 最近用户文本),无候选时 resolved=null(不猜)。
4
+ // 输出可回填查询:把 resolved 实体追加进查询词,提升同实体卡片命中。
5
+
6
+ export const ANAPHORA_SCHEMA = 'anaphora/v1';
7
+
8
+ export const PRONOUN_PATTERNS = Object.freeze([
9
+ { pronoun: '它', regex: /它/gu },
10
+ { pronoun: '它们', regex: /它们/gu },
11
+ { pronoun: '这个', regex: /这个/gu },
12
+ { pronoun: '那个', regex: /那个/gu },
13
+ { pronoun: '这些', regex: /这些/gu },
14
+ { pronoun: '那些', regex: /那些/gu },
15
+ { pronoun: '上面', regex: /上面|上述|前面/u },
16
+ { pronoun: '刚才', regex: /刚才|刚刚/u },
17
+ { pronoun: '他', regex: /他(?![们])/gu },
18
+ { pronoun: '她', regex: /她(?![们])/gu },
19
+ { pronoun: '他们', regex: /他们/gu },
20
+ { pronoun: '她们', regex: /她们/gu },
21
+ ]);
22
+
23
+ const STOPWORDS = new Set([
24
+ '这个', '那个', '这些', '那些', '什么', '怎么', '可以', '我们', '你们', '他们', '她们', '自己',
25
+ '一个', '一下', '现在', '然后', '因为', '所以', '但是', '如果', '已经', '还是', '不是', '没有',
26
+ '没有', '就是', '这样', '那样', '这里', '那里', '时候', '东西', '事情', '问题', '继续', '开始',
27
+ ]);
28
+
29
+ function normalizeToken(token) {
30
+ return String(token ?? '').trim();
31
+ }
32
+
33
+ /** Extract plausible entity tokens from a text (CJK 2-12 chars / ASCII words), stopwords dropped. */
34
+ export function extractEntityTokens(text, { max = 12 } = {}) {
35
+ const value = typeof text === 'string' ? text : '';
36
+ const tokens = [];
37
+ const seen = new Set();
38
+ const cjk = value.match(/[\u3400-\u9fff]{2,12}/gu) ?? [];
39
+ const ascii = value.match(/[A-Za-z][A-Za-z0-9_.-]{1,30}/gu) ?? [];
40
+ for (const token of [...cjk, ...ascii]) {
41
+ if (STOPWORDS.has(token)) continue;
42
+ if (seen.has(token)) continue;
43
+ seen.add(token);
44
+ tokens.push(token);
45
+ if (tokens.length >= max) break;
46
+ }
47
+ return tokens;
48
+ }
49
+
50
+ /**
51
+ * Resolve pronouns in `text` against focus entities first, then recent user texts.
52
+ * @returns {{schema,references:{pronoun,resolved,candidates}[],terms:string[],unresolved:string[]}}
53
+ */
54
+ export function resolveAnaphora({ text = '', recentTexts = [], focusEntities = [] } = {}) {
55
+ const query = typeof text === 'string' ? text : '';
56
+ const focus = (Array.isArray(focusEntities) ? focusEntities : [])
57
+ .map(normalizeToken)
58
+ .filter((token) => token !== '' && !STOPWORDS.has(token));
59
+ const recentTokens = [];
60
+ for (const recent of Array.isArray(recentTexts) ? recentTexts.slice(-3) : []) {
61
+ for (const token of extractEntityTokens(recent)) {
62
+ if (!recentTokens.includes(token)) recentTokens.push(token);
63
+ }
64
+ }
65
+ const candidates = [...new Set([...focus, ...recentTokens])];
66
+ const references = [];
67
+ const terms = [];
68
+ const unresolved = [];
69
+ for (const { pronoun, regex } of PRONOUN_PATTERNS) {
70
+ regex.lastIndex = 0;
71
+ if (!regex.test(query)) continue;
72
+ // Prefer the most recent focus entity; never invent one when no candidate exists.
73
+ const resolved = candidates.length > 0 ? candidates[0] : null;
74
+ references.push({ pronoun, resolved, candidates: candidates.slice(0, 5) });
75
+ if (resolved !== null && !terms.includes(resolved)) terms.push(resolved);
76
+ if (resolved === null) unresolved.push(pronoun);
77
+ }
78
+ return { schema: ANAPHORA_SCHEMA, references, terms, unresolved };
79
+ }
80
+
81
+ /** Append resolved referents to the query (no-op when nothing resolved). */
82
+ export function expandQueryWithAnaphora(queryText, resolution) {
83
+ const terms = Array.isArray(resolution?.terms) ? resolution.terms : [];
84
+ const base = String(queryText ?? '');
85
+ const fresh = terms.filter((term) => !base.includes(term));
86
+ return { text: fresh.length === 0 ? base : `${base} ${fresh.join(' ')}`, changed: fresh.length > 0, terms: fresh };
87
+ }