@danceiny/gotry 0.0.1-rc.15 → 0.0.1-rc.17

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 (238) hide show
  1. package/README.md +51 -13
  2. package/README.zh-CN.md +26 -12
  3. package/bin/gotry-booking-copilot.js +53 -0
  4. package/bin/gotry-bootstrap.js +357 -8
  5. package/bin/gotry-inner.js +442 -60
  6. package/bin/gotry-runtime-resolution.d.ts +27 -0
  7. package/bin/gotry-runtime-resolution.js +50 -0
  8. package/bin/gotry.js +1 -1
  9. package/cordis.gotry-patch.yml +15 -1
  10. package/data/airline-airports.json +39 -0
  11. package/dist/capabilities/agent-reach-deep.js +1 -1
  12. package/dist/capabilities/agent-reach.js +1 -1
  13. package/dist/capabilities/anything.js +1 -1
  14. package/dist/capabilities/artifacts.js +1 -1
  15. package/dist/capabilities/effect.js +293 -0
  16. package/dist/capabilities/fact-log.js +41 -0
  17. package/dist/capabilities/flyai.js +20 -6
  18. package/dist/capabilities/hbcli.js +43 -1
  19. package/dist/capabilities/incident-log.js +1 -1
  20. package/dist/capabilities/model-override.js +18 -0
  21. package/dist/capabilities/opensky.js +1 -1
  22. package/dist/capabilities/resilience.js +90 -0
  23. package/dist/capabilities/session/action-cache.js +1 -1
  24. package/dist/capabilities/session/adapters/ctrip-flight.js +1 -1
  25. package/dist/capabilities/session/adapters/meituan-local.js +1 -1
  26. package/dist/capabilities/session/benchmark.js +2 -1
  27. package/dist/capabilities/session/extension-bridge.js +358 -0
  28. package/dist/capabilities/session/extension-channel.js +93 -0
  29. package/dist/capabilities/session/extension-distribution.js +234 -0
  30. package/dist/capabilities/session/extract.js +1 -1
  31. package/dist/capabilities/session/golden-score.js +92 -0
  32. package/dist/capabilities/session/health-watch.js +216 -0
  33. package/dist/capabilities/session/read-guard.js +1 -1
  34. package/dist/capabilities/session/static-flight-golden.js +137 -0
  35. package/dist/capabilities/session/transport.js +1 -1
  36. package/dist/capabilities/session/wizard.js +147 -0
  37. package/dist/capabilities/session-consent.js +1 -1
  38. package/dist/capabilities/session-login.js +83 -1
  39. package/dist/capabilities/session-search.js +111 -2
  40. package/dist/capabilities/weather.js +168 -46
  41. package/dist/data/session-golden-20.json +25 -0
  42. package/dist/data/sf-golden-manifest.json +102 -0
  43. package/dist/data/sf-static-routes.json +91 -0
  44. package/dist/scripts/action-cache-tests.js +1 -1
  45. package/dist/scripts/agent-planning-budget-e2e.js +227 -0
  46. package/dist/scripts/agent-planning-budget-tests.js +173 -0
  47. package/dist/scripts/agent-reach-deep-tests.js +1 -1
  48. package/dist/scripts/agent-reach-tests.js +1 -1
  49. package/dist/scripts/agent-reach-wrapper-tests.js +1 -1
  50. package/dist/scripts/anything-tests.js +1 -1
  51. package/dist/scripts/async-collect.js +1 -1
  52. package/dist/scripts/benchmark-environment-bridge-e2e.js +981 -0
  53. package/dist/scripts/benchmark-environment-bridge-tests.js +2544 -0
  54. package/dist/scripts/booking-copilot-availability-ledger-binding-tests.js +335 -0
  55. package/dist/scripts/booking-copilot-availability-policy-v2-tests.js +1355 -0
  56. package/dist/scripts/booking-copilot-bin-proof-tests.js +89 -0
  57. package/dist/scripts/booking-copilot-crossrepo-fixture-server.js +113 -0
  58. package/dist/scripts/booking-copilot-dsh-core-proof-tests.js +356 -0
  59. package/dist/scripts/booking-copilot-dsh-planner-proof-tests.js +557 -0
  60. package/dist/scripts/booking-copilot-dsh-plugin-proof-tests.js +140 -0
  61. package/dist/scripts/booking-copilot-event-sequence-concurrency-proof-tests.js +202 -0
  62. package/dist/scripts/booking-copilot-gap-code-contract-proof-tests.js +102 -0
  63. package/dist/scripts/booking-copilot-operation-ledger-concurrency-proof-tests.js +374 -0
  64. package/dist/scripts/booking-copilot-receipt-ledger-concurrency-proof-tests.js +447 -0
  65. package/dist/scripts/booking-copilot-runtime-proof-tests.js +205 -0
  66. package/dist/scripts/booking-copilot-server-proof-tests.js +317 -0
  67. package/dist/scripts/booking-copilot-startup-proof-tests.js +283 -0
  68. package/dist/scripts/booking-copilot-v2-runtime-proof-tests.js +3935 -0
  69. package/dist/scripts/booking-saga-tests.js +1 -1
  70. package/dist/scripts/booking-surface-contract-proof-tests.js +393 -0
  71. package/dist/scripts/booking-surface-v2-contract-proof-tests.js +1174 -0
  72. package/dist/scripts/bootstrap-tests.js +59 -3
  73. package/dist/scripts/build-changelog.js +279 -0
  74. package/dist/scripts/changelog-tests.js +165 -0
  75. package/dist/scripts/companion-tests.js +1 -1
  76. package/dist/scripts/diff-test.js +1 -1
  77. package/dist/scripts/dsh-runtime-closure-tests.js +225 -0
  78. package/dist/scripts/dsh-runtime-closure.js +150 -0
  79. package/dist/scripts/effect-tests.js +474 -0
  80. package/dist/scripts/engine-run.js +1 -1
  81. package/dist/scripts/engine-tests.js +1 -1
  82. package/dist/scripts/evaluation-cadence-tests.js +347 -0
  83. package/dist/scripts/evaluation-contract-tests.js +574 -0
  84. package/dist/scripts/extension-distribution-cli.js +35 -0
  85. package/dist/scripts/extension-distribution-tests.js +341 -0
  86. package/dist/scripts/extension-tests.js +573 -0
  87. package/dist/scripts/fact-gate-tests.js +318 -0
  88. package/dist/scripts/flyai-tests.js +1 -1
  89. package/dist/scripts/hbcli-e2e-tests.js +180 -0
  90. package/dist/scripts/hbcli-tests.js +1 -1
  91. package/dist/scripts/health-watch-cli.js +51 -0
  92. package/dist/scripts/i18n-tests.js +1 -1
  93. package/dist/scripts/incident-tests.js +1 -1
  94. package/dist/scripts/journey-tests.js +1 -1
  95. package/dist/scripts/ledger-tests.js +1 -1
  96. package/dist/scripts/ledger-workflow-crash.js +1 -1
  97. package/dist/scripts/memory-capture-tests.js +1 -1
  98. package/dist/scripts/memory-decay-tests.js +1 -1
  99. package/dist/scripts/memory-metrics.js +1 -1
  100. package/dist/scripts/memory-value-report.js +1 -1
  101. package/dist/scripts/model-override-e2e.js +176 -0
  102. package/dist/scripts/nightly-evidence-tests.js +67 -4
  103. package/dist/scripts/nightly-evidence.js +59 -3
  104. package/dist/scripts/nudge-digest.js +1 -1
  105. package/dist/scripts/onboarding-tests.js +186 -0
  106. package/dist/scripts/opensky-check.js +1 -1
  107. package/dist/scripts/opensky-tests.js +1 -1
  108. package/dist/scripts/pnpm-dsh-closure-proof.js +20 -0
  109. package/dist/scripts/price-drift-tests.js +441 -0
  110. package/dist/scripts/price-drift-watch.js +491 -0
  111. package/dist/scripts/probe-poi-tests.js +1 -1
  112. package/dist/scripts/product-metrics.js +1 -1
  113. package/dist/scripts/publish-preverify.js +40 -4
  114. package/dist/scripts/realtime-pricing-tests.js +1 -1
  115. package/dist/scripts/replay-async.js +1 -1
  116. package/dist/scripts/replay-real.js +1 -1
  117. package/dist/scripts/replay.js +1 -1
  118. package/dist/scripts/session-attach-diagnose.js +1 -1
  119. package/dist/scripts/session-attach-poc.js +1 -1
  120. package/dist/scripts/session-benchmark.js +1 -1
  121. package/dist/scripts/session-extract-tests.js +1 -1
  122. package/dist/scripts/session-login.js +1 -1
  123. package/dist/scripts/session-tests.js +70 -20
  124. package/dist/scripts/sf-live-benchmark.js +338 -0
  125. package/dist/scripts/sf-live-cli-tests.js +21 -0
  126. package/dist/scripts/sf-soft-score-tests.js +108 -0
  127. package/dist/scripts/sf-summary.js +93 -0
  128. package/dist/scripts/skeleton-check.js +1 -1
  129. package/dist/scripts/skeleton-integration-test.js +1 -1
  130. package/dist/scripts/skills-contract-tests.js +1 -1
  131. package/dist/scripts/smoke-session-gate-tests.js +29 -0
  132. package/dist/scripts/smoke.js +154 -33
  133. package/dist/scripts/state-cli-tests.js +1 -1
  134. package/dist/scripts/state-cli.js +1 -1
  135. package/dist/scripts/static-golden-tests.js +299 -0
  136. package/dist/scripts/time-eval-tests.js +1 -1
  137. package/dist/scripts/travel-timeline-tests.js +1 -1
  138. package/dist/scripts/unified-tests.js +1 -1
  139. package/dist/scripts/weather-tests.js +694 -44
  140. package/dist/scripts/z3-race-tests.js +1 -1
  141. package/dist/src/artifact-gate.js +310 -0
  142. package/dist/src/benchmark-agent-conformance.js +370 -0
  143. package/dist/src/benchmark-environment-bridge.js +384 -0
  144. package/dist/src/benchmark-headless-child-diagnostics.js +173 -0
  145. package/dist/src/benchmark-tool-isolation.js +124 -0
  146. package/dist/src/bookable-facts.js +349 -0
  147. package/dist/src/booking-saga.js +1 -1
  148. package/dist/src/booking-surface/availability-policy-v2.js +830 -0
  149. package/dist/src/booking-surface/canonical-schema.js +113 -0
  150. package/dist/src/booking-surface/contracts-v2.js +89 -0
  151. package/dist/src/booking-surface/contracts.js +46 -0
  152. package/dist/src/booking-surface/dsh-planner.js +453 -0
  153. package/dist/src/booking-surface/dsh-plugin.js +93 -0
  154. package/dist/src/booking-surface/error-codes.js +94 -0
  155. package/dist/src/booking-surface/index.js +15 -0
  156. package/dist/src/booking-surface/profile.js +68 -0
  157. package/dist/src/booking-surface/runtime-v2.js +1771 -0
  158. package/dist/src/booking-surface/runtime.js +351 -0
  159. package/dist/src/booking-surface/server-v2.js +334 -0
  160. package/dist/src/booking-surface/server.js +302 -0
  161. package/dist/src/booking-surface/startup.js +159 -0
  162. package/dist/src/booking-surface/validation-v2.js +319 -0
  163. package/dist/src/booking-surface/validation.js +809 -0
  164. package/dist/src/bridge.js +1 -1
  165. package/dist/src/companions.js +1 -1
  166. package/dist/src/contracts.js +1 -1
  167. package/dist/src/dsh-llm.js +1 -1
  168. package/dist/src/engine.js +1 -1
  169. package/dist/src/evaluation-cadence.js +234 -0
  170. package/dist/src/evaluation-contracts.js +906 -0
  171. package/dist/src/i18n.js +1 -1
  172. package/dist/src/index.js +234 -60
  173. package/dist/src/journey.js +1 -1
  174. package/dist/src/loop.js +1 -1
  175. package/dist/src/memory-capture.js +1 -1
  176. package/dist/src/memory-decay.js +1 -1
  177. package/dist/src/memory-utility.js +1 -1
  178. package/dist/src/mock-llm.js +1 -1
  179. package/dist/src/model.js +1 -1
  180. package/dist/src/realtime-pricing.js +14 -7
  181. package/dist/src/slot-spec.js +1 -1
  182. package/dist/src/state-ledger.js +2 -1
  183. package/dist/src/time-anchor.js +1 -1
  184. package/dist/src/tool-budget.js +136 -0
  185. package/dist/src/tool-packet.js +1 -1
  186. package/dist/src/travel-slots.js +1 -1
  187. package/dist/src/travel-timeline.js +1 -1
  188. package/dist/src/unified.js +1 -1
  189. package/dist/src/wish-pool.js +1 -1
  190. package/dist/src/z3-shared.js +1 -1
  191. package/extension/README.md +50 -0
  192. package/extension/background.js +160 -0
  193. package/extension/content-bridge.js +41 -0
  194. package/extension/content-main.js +62 -0
  195. package/extension/manifest.json +32 -0
  196. package/package.json +291 -12
  197. package/schemas/booking.surface.v1.schema.json +927 -0
  198. package/schemas/booking.surface.v2.schema.json +61 -0
  199. package/ts/capabilities/fact-log.ts +54 -0
  200. package/ts/capabilities/flyai.ts +16 -3
  201. package/ts/capabilities/hbcli.ts +46 -0
  202. package/ts/capabilities/session/benchmark.ts +4 -1
  203. package/ts/capabilities/session/extension-bridge.ts +377 -0
  204. package/ts/capabilities/session/extension-channel.ts +95 -0
  205. package/ts/capabilities/session/extension-distribution.ts +264 -0
  206. package/ts/capabilities/session/golden-score.ts +139 -0
  207. package/ts/capabilities/session/health-watch.ts +257 -0
  208. package/ts/capabilities/session/static-flight-golden.ts +209 -0
  209. package/ts/capabilities/session/wizard.ts +140 -0
  210. package/ts/capabilities/session-login.ts +63 -2
  211. package/ts/capabilities/session-search.ts +105 -3
  212. package/ts/capabilities/weather.ts +141 -52
  213. package/ts/package.json +3 -3
  214. package/ts/src/artifact-gate.ts +365 -0
  215. package/ts/src/benchmark-agent-conformance.ts +448 -0
  216. package/ts/src/benchmark-environment-bridge.ts +348 -0
  217. package/ts/src/benchmark-headless-child-diagnostics.ts +184 -0
  218. package/ts/src/benchmark-tool-isolation.ts +166 -0
  219. package/ts/src/bookable-facts.ts +557 -0
  220. package/ts/src/booking-surface/availability-policy-v2.ts +523 -0
  221. package/ts/src/booking-surface/canonical-schema.js +113 -0
  222. package/ts/src/booking-surface/contracts-v2.ts +118 -0
  223. package/ts/src/booking-surface/contracts.ts +380 -0
  224. package/ts/src/booking-surface/dsh-planner.ts +452 -0
  225. package/ts/src/booking-surface/dsh-plugin.js +93 -0
  226. package/ts/src/booking-surface/error-codes.ts +101 -0
  227. package/ts/src/booking-surface/index.ts +12 -0
  228. package/ts/src/booking-surface/profile.ts +42 -0
  229. package/ts/src/booking-surface/runtime-v2.ts +1466 -0
  230. package/ts/src/booking-surface/runtime.ts +483 -0
  231. package/ts/src/booking-surface/server-v2.ts +247 -0
  232. package/ts/src/booking-surface/server.ts +324 -0
  233. package/ts/src/booking-surface/startup.ts +196 -0
  234. package/ts/src/booking-surface/validation-v2.ts +205 -0
  235. package/ts/src/booking-surface/validation.ts +453 -0
  236. package/ts/src/index.ts +161 -14
  237. package/ts/src/state-ledger.ts +1 -0
  238. package/ts/src/tool-budget.ts +165 -0
@@ -0,0 +1,557 @@
1
+ /**
2
+ * 可下单事实模型 gotry_bookable_fact.v1(issue #46,ADR-19)。
3
+ *
4
+ * 问题(2026-08-29 实测会话):exact-date 工具全部 miss 后,LLM 用航线页当日班期
5
+ * (2026 快照)填充 2027 行程,航班号/时刻/机场/价格以「✓/推荐」确定性语气手写进
6
+ * 产物——「错误但看起来已验证」比 unknown 更危险。
7
+ *
8
+ * 本层职责(纯函数,零 I/O——持久化见 capabilities/fact-log.ts):
9
+ * 1. 结构化事实 schema:route/exact local date/时刻/航班号/营销与实际承运(分开)/
10
+ * 机场/直飞或中转/价格/币种/source/query_id/fetched_at/as_of/confidence/bookability;
11
+ * 2. 证据分层永不合并:live_inventory(exact-date 命中)/ route_exists(只验证航线)/
12
+ * historical_schedule(旧航季)/ benchmark_price(历史促销价)——miss 落「负事实」,
13
+ * exact-date 无库存 ≠ 可用历史填充;
14
+ * 3. 判定原语:航班 claim 可述性(fail closed)/ 同日衔接硬约束 / 行程统计不变量
15
+ * (酒店夜+机上夜/O&D 段数/flight legs/预算自洽)/ 回头路检测;
16
+ * 4. 确定性渲染:航班行/政策行只从结构化对象生成,政策恒带 as_of + 复核日期,
17
+ * 分票永不称「联程」(protected_connection=true 才允许)。
18
+ *
19
+ * 渲染闸(从 markdown 反向核验)在 artifact-gate.ts。
20
+ */
21
+
22
+ import { createHash } from 'node:crypto'
23
+
24
+ export const BOOKABLE_FACT_SCHEMA = 'gotry_bookable_fact.v1' as const
25
+
26
+ /** 证据分层:四层永不合并(issue #46 根因②——skeleton/historical/live 被混写) */
27
+ export type EvidenceTier =
28
+ | 'live_inventory' // exact-date 实时库存命中(唯一可下单层)
29
+ | 'route_exists' // 只验证了「航线存在」(骨架/航线页),不得升级为「该日期有该航班」
30
+ | 'historical_schedule' // 历史/旧航季班期,只作参考叙述
31
+ | 'benchmark_price' // 历史促销价,只作 benchmark,不进预算下限
32
+
33
+ /** 可下单状态:fail-closed 四态 */
34
+ export type Bookability =
35
+ | 'bookable_exact_date' // exact-date 源返回,可下单
36
+ | 'unavailable_exact_date' // exact-date 源正常返回 0 条(负事实)
37
+ | 'unverified' // 未经 exact-date 核验
38
+ | 'conflict' // 两源冲突,不得给 ✓
39
+
40
+ export interface FlightFact {
41
+ schema: typeof BOOKABLE_FACT_SCHEMA
42
+ /** 语义派生 id:sha(route|date|flight_no|query_id)——同查询重放幂等 */
43
+ fact_id: string
44
+ kind: 'flight' | 'train'
45
+ route: { origin: string; destination: string; origin_airport?: string; dest_airport?: string }
46
+ /** 出发地当地日期 YYYY-MM-DD(exact local date) */
47
+ date: string
48
+ /** 营销航班号(如 CZ8582);负事实为空串 */
49
+ flight_no: string
50
+ /** 营销承运与实际承运分开保存(codeshare 必须两者同输出) */
51
+ marketing_carrier?: string
52
+ operating_carrier?: string
53
+ dep_local?: string // HH:MM
54
+ arr_local?: string // HH:MM
55
+ nonstop?: boolean
56
+ price?: number
57
+ currency?: string
58
+ baggage_included?: boolean
59
+ /** 仅当同票联程(同一票号/行李直挂/误机保护)为 true;两段接得上 ≠ 联程 */
60
+ protected_connection?: boolean
61
+ tier: EvidenceTier
62
+ bookability: Bookability
63
+ /** 数据源标识(flyai / session:ctrip-flight / …) */
64
+ source: string
65
+ /** 可重放查询 id(如 flyai:flight:HKG-HKT:2027-07-17) */
66
+ query_id: string
67
+ /** 取数时刻 ISO */
68
+ fetched_at: string
69
+ /** 数据快照日(证据 as_of) */
70
+ as_of: string
71
+ /** 下次复核截止(远期班期/政策必带) */
72
+ review_by?: string
73
+ }
74
+
75
+ /** 动态政策事实:签证/免签/入境申报只允许「截至 as_of 的现行政策」表述 */
76
+ export interface PolicyFact {
77
+ schema: typeof BOOKABLE_FACT_SCHEMA
78
+ fact_id: string
79
+ kind: 'policy'
80
+ /** 政策对象(如 泰国免签 / 迪拜入境) */
81
+ subject: string
82
+ /** 政策内容陈述(不带时间无条件断言) */
83
+ statement: string
84
+ source: string
85
+ query_id: string
86
+ fetched_at: string
87
+ as_of: string
88
+ /** 复核 gate(通常 D-30/D-7) */
89
+ review_by?: string
90
+ }
91
+
92
+ export type BookableFact = FlightFact | PolicyFact
93
+
94
+ // ---------------------------------------------------------------------------
95
+ // id 与查询词(可重放:query_id 即重放凭证)
96
+ // ---------------------------------------------------------------------------
97
+
98
+ function sha16(text: string): string {
99
+ return createHash('sha256').update(text).digest('hex').slice(0, 16)
100
+ }
101
+
102
+ export function makeQueryId(source: string, kind: string, origin: string, destination: string, date: string): string {
103
+ return `${source}:${kind}:${origin}-${destination}:${date}`
104
+ }
105
+
106
+ export function makeFactId(parts: Array<string | undefined>): string {
107
+ return sha16(parts.map(p => p ?? '').join('|'))
108
+ }
109
+
110
+ /** 城市→IATA 词表(data/airline-airports.json city_alias);转换时把 route 归一到 IATA 空间 */
111
+ export type CityAlias = Record<string, string>
112
+
113
+ function iataOf(alias: CityAlias | undefined, city: string): string {
114
+ return alias?.[city] ?? city
115
+ }
116
+
117
+ // ---------------------------------------------------------------------------
118
+ // 工具结果 → 事实(转换器):hit 落正事实,miss 落负事实,error 不落(无结论)
119
+ // ---------------------------------------------------------------------------
120
+
121
+ /** flyai 机/火结果形状(capabilities/flyai.ts FlyaiOption 的输入侧最小面) */
122
+ export interface FlyaiLikeOption {
123
+ no?: string
124
+ name?: string
125
+ depDateTime?: string
126
+ arrDateTime?: string
127
+ depStation?: string
128
+ arrStation?: string
129
+ price?: number
130
+ priceRaw?: string
131
+ /** 直达/中转;缺省视为直达(单段条目),中转条目必须显式 false */
132
+ nonstop?: boolean
133
+ }
134
+
135
+ export interface FlyaiLikeResult {
136
+ verdict: 'hit' | 'miss' | 'error'
137
+ options?: FlyaiLikeOption[]
138
+ evidence?: string
139
+ }
140
+
141
+ /** 会话检索(携程)结果形状(session-search.ts 最小面) */
142
+ export interface SessionLikeOption {
143
+ flightNo?: string
144
+ airline?: string
145
+ depDateTime?: string
146
+ arrDateTime?: string
147
+ depAirport?: string
148
+ arrAirport?: string
149
+ price?: number
150
+ }
151
+
152
+ export interface SessionLikeResult {
153
+ verdict: string
154
+ options?: SessionLikeOption[]
155
+ }
156
+
157
+ const YMD = /^\d{4}-\d{2}-\d{2}$/
158
+
159
+ function hmOf(dateTime: string | undefined): string | undefined {
160
+ const m = dateTime?.match(/T?(\d{2}:\d{2})/)
161
+ return m?.[1]
162
+ }
163
+
164
+ function dateOf(dateTime: string | undefined, fallback: string): string {
165
+ const m = dateTime?.match(/^(\d{4}-\d{2}-\d{2})/)
166
+ return m?.[1] ?? fallback
167
+ }
168
+
169
+ /** exact-date miss → 负事实(route+date 级「当前不可售/无结果」记录,fail-closed 的另一半) */
170
+ export function negativeFact(queryId: string, kind: 'flight' | 'train', origin: string, destination: string, date: string, source: string, fetchedAt: string, alias?: CityAlias): FlightFact {
171
+ return {
172
+ schema: BOOKABLE_FACT_SCHEMA,
173
+ fact_id: makeFactId(['neg', kind, iataOf(alias, origin), iataOf(alias, destination), date, queryId]),
174
+ kind,
175
+ route: { origin: iataOf(alias, origin), destination: iataOf(alias, destination) },
176
+ date,
177
+ flight_no: '',
178
+ tier: 'live_inventory',
179
+ bookability: 'unavailable_exact_date',
180
+ source,
181
+ query_id: queryId,
182
+ fetched_at: fetchedAt,
183
+ as_of: fetchedAt.slice(0, 10),
184
+ }
185
+ }
186
+
187
+ /** flyai hit/miss → 事实列(error 不落事实——无结论不是证据) */
188
+ export function factsFromFlyai(q: { kind: 'flight' | 'train'; origin: string; destination: string; date: string }, r: FlyaiLikeResult, fetchedAt: string, alias?: CityAlias): FlightFact[] {
189
+ const source = 'flyai'
190
+ const queryId = makeQueryId(source, q.kind, q.origin, q.destination, q.date)
191
+ const origin = iataOf(alias, q.origin)
192
+ const destination = iataOf(alias, q.destination)
193
+ if (r.verdict === 'error') return []
194
+ if (r.verdict === 'miss') return [negativeFact(queryId, q.kind, q.origin, q.destination, q.date, source, fetchedAt, alias)]
195
+ const facts: FlightFact[] = []
196
+ for (const o of r.options ?? []) {
197
+ if (!o.no || !o.depDateTime) continue
198
+ const numeric = typeof o.price === 'number' && Number.isFinite(o.price) && o.price > 0 ? o.price : undefined
199
+ facts.push({
200
+ schema: BOOKABLE_FACT_SCHEMA,
201
+ fact_id: makeFactId([q.kind, origin, destination, q.date, o.no, queryId]),
202
+ kind: q.kind,
203
+ route: { origin, destination, origin_airport: o.depStation, dest_airport: o.arrStation },
204
+ date: dateOf(o.depDateTime, q.date),
205
+ flight_no: o.no,
206
+ marketing_carrier: o.name || undefined,
207
+ operating_carrier: undefined, // flyai 上游只给营销承运;实际承运未知 ≠ 相同,留空不猜
208
+ dep_local: hmOf(o.depDateTime),
209
+ arr_local: hmOf(o.arrDateTime),
210
+ nonstop: o.nonstop !== false,
211
+ price: numeric,
212
+ currency: numeric !== undefined ? 'CNY' : undefined,
213
+ tier: 'live_inventory',
214
+ bookability: 'bookable_exact_date',
215
+ source,
216
+ query_id: queryId,
217
+ fetched_at: fetchedAt,
218
+ as_of: fetchedAt.slice(0, 10),
219
+ })
220
+ }
221
+ // hit 但解析后零有效条目 = 与 miss 同语义(无可用事实,落负事实)
222
+ return facts.length > 0 ? facts : [negativeFact(queryId, q.kind, q.origin, q.destination, q.date, source, fetchedAt, alias)]
223
+ }
224
+
225
+ /** 会话检索 hit → 事实列(用户本人登录态来源,与 flyai 并列独立 source) */
226
+ export function factsFromSession(q: { origin: string; destination: string; date: string }, r: SessionLikeResult, fetchedAt: string, alias?: CityAlias): FlightFact[] {
227
+ const source = 'session:ctrip-flight'
228
+ const queryId = makeQueryId(source, 'flight', q.origin, q.destination, q.date)
229
+ const origin = iataOf(alias, q.origin)
230
+ const destination = iataOf(alias, q.destination)
231
+ if (r.verdict !== 'hit') {
232
+ // miss/cooldown/challenged/needs-login:仅「正常返回 0 条」是负事实;通道不可用不落事实
233
+ return r.verdict === 'miss' ? [negativeFact(queryId, 'flight', q.origin, q.destination, q.date, source, fetchedAt, alias)] : []
234
+ }
235
+ const facts: FlightFact[] = []
236
+ for (const o of r.options ?? []) {
237
+ if (!o.flightNo || !o.depDateTime) continue
238
+ const numeric = typeof o.price === 'number' && Number.isFinite(o.price) && o.price > 0 ? o.price : undefined
239
+ facts.push({
240
+ schema: BOOKABLE_FACT_SCHEMA,
241
+ fact_id: makeFactId(['flight', origin, destination, q.date, o.flightNo, queryId]),
242
+ kind: 'flight',
243
+ route: { origin, destination, origin_airport: o.depAirport, dest_airport: o.arrAirport },
244
+ date: dateOf(o.depDateTime, q.date),
245
+ flight_no: o.flightNo,
246
+ marketing_carrier: o.airline || undefined,
247
+ operating_carrier: undefined,
248
+ dep_local: hmOf(o.depDateTime),
249
+ arr_local: hmOf(o.arrDateTime),
250
+ nonstop: true,
251
+ price: numeric,
252
+ currency: numeric !== undefined ? 'CNY' : undefined,
253
+ tier: 'live_inventory',
254
+ bookability: 'bookable_exact_date',
255
+ source,
256
+ query_id: queryId,
257
+ fetched_at: fetchedAt,
258
+ as_of: fetchedAt.slice(0, 10),
259
+ })
260
+ }
261
+ return facts
262
+ }
263
+
264
+ // ---------------------------------------------------------------------------
265
+ // 注册表(纯函数视图;持久化在 capabilities/fact-log.ts)
266
+ // ---------------------------------------------------------------------------
267
+
268
+ /** 同 fact_id 去重,保留 fetched_at 最新(重查覆盖旧快照,历史不丢——append-only 由持久层保证) */
269
+ export function dedupeFacts<T extends BookableFact>(facts: T[]): T[] {
270
+ const byId = new Map<string, T>()
271
+ for (const f of facts) {
272
+ const prev = byId.get(f.fact_id)
273
+ if (!prev || prev.fetched_at <= f.fetched_at) byId.set(f.fact_id, f)
274
+ }
275
+ return [...byId.values()].sort((a, b) => a.fetched_at.localeCompare(b.fetched_at) || a.fact_id.localeCompare(b.fact_id))
276
+ }
277
+
278
+ /** route+date 的最新查询结论(同日多次查询:最新一次为准,避免「昨天 miss 今天 hit」陈旧否定) */
279
+ export function latestFactsForRouteDate(facts: BookableFact[], origin: string, destination: string, date: string): FlightFact[] {
280
+ const hits = facts.filter((f): f is FlightFact =>
281
+ f.kind !== 'policy'
282
+ && f.route.origin === origin && f.route.destination === destination && f.date === date)
283
+ const latestQueryTs = new Map<string, string>()
284
+ for (const f of hits) {
285
+ const prev = latestQueryTs.get(f.query_id)
286
+ if (!prev || prev < f.fetched_at) latestQueryTs.set(f.query_id, f.fetched_at)
287
+ }
288
+ const latestTs = [...latestQueryTs.values()].sort().pop()
289
+ if (!latestTs) return []
290
+ return hits.filter(f => f.fetched_at === latestTs)
291
+ }
292
+
293
+ // ---------------------------------------------------------------------------
294
+ // 判定原语①:航班 claim 可述性(fail closed)
295
+ // ---------------------------------------------------------------------------
296
+
297
+ export type FlightClaimVerdict =
298
+ | 'traceable' // 注册表内有 bookable_exact_date 的该航班事实
299
+ | 'not_in_source' // 该 route+date 查过 exact-date,结果里没有它——最强违例(填充历史/相邻日期)
300
+ | 'route_unqueried' // 该 route+date 从未查过 exact-date——无证据断言
301
+ | 'contradicted' // 注册表内有同号航班但事实字段冲突(时刻/机场)
302
+
303
+ export interface FlightClaim {
304
+ flight_no: string
305
+ origin?: string
306
+ destination?: string
307
+ date?: string
308
+ }
309
+
310
+ export function flightClaimVerdict(facts: BookableFact[], claim: FlightClaim): { verdict: FlightClaimVerdict; fact?: FlightFact; reason: string } {
311
+ const no = claim.flight_no.toUpperCase().replace(/\s+/g, '')
312
+ const sameNo = facts.filter((f): f is FlightFact =>
313
+ f.kind !== 'policy' && f.flight_no.toUpperCase() === no && f.bookability === 'bookable_exact_date')
314
+ const routeMatched = sameNo.filter(f =>
315
+ (!claim.origin || f.route.origin === claim.origin || f.route.origin_airport === claim.origin)
316
+ && (!claim.destination || f.route.destination === claim.destination || f.route.dest_airport === claim.destination)
317
+ && (!claim.date || f.date === claim.date))
318
+ if (routeMatched.length > 0) return { verdict: 'traceable', fact: routeMatched[0], reason: `回溯 ${routeMatched[0]!.query_id}` }
319
+ // 无同号可下单事实:该 route+date 是否查过?
320
+ if (claim.origin && claim.destination && claim.date) {
321
+ const scoped = latestFactsForRouteDate(facts, claim.origin, claim.destination, claim.date)
322
+ if (scoped.length > 0) {
323
+ return {
324
+ verdict: 'not_in_source',
325
+ reason: scoped.some(f => f.bookability === 'unavailable_exact_date')
326
+ ? `${claim.origin}→${claim.destination} ${claim.date} exact-date 源返回 0 条(${scoped[0]!.query_id})——不得用历史班期/相邻日期填充`
327
+ : `${claim.origin}→${claim.destination} ${claim.date} exact-date 源在架 ${scoped.filter(f => f.bookability === 'bookable_exact_date').map(f => f.flight_no).join('/')}——无 ${no}`,
328
+ }
329
+ }
330
+ return { verdict: 'route_unqueried', reason: `${claim.origin}→${claim.destination} ${claim.date} 从未经 exact-date 源核验` }
331
+ }
332
+ return { verdict: 'route_unqueried', reason: `航班 ${no} 无可回溯的 exact-date 事实(缺 route/date 上下文)` }
333
+ }
334
+
335
+ // ---------------------------------------------------------------------------
336
+ // 判定原语②:同日衔接硬约束(办事结束 → 门到机场 → 值机截止 → 起飞)
337
+ // ---------------------------------------------------------------------------
338
+
339
+ export interface SameDayDepartureConstraint {
340
+ /** 当日地面事务最早结束(当地 HH:MM,如银行办事) */
341
+ errand_end_local: string
342
+ /** 事务地点→机场门到门分钟(含步行/等车) */
343
+ airport_transit_min: number
344
+ /** 起飞前值机/安检截止分钟(国际建议 120) */
345
+ checkin_deadline_min: number
346
+ }
347
+
348
+ export interface SameDayDepartureVerdict {
349
+ feasible: boolean
350
+ /** 事务约束下的最早可接起飞时刻(当地 HH:MM) */
351
+ earliest_departure_local: string
352
+ /** exact-date 在架且满足硬约束的直飞 */
353
+ feasible_flights: FlightFact[]
354
+ /** 被约束排除的在架直飞(带排除原因) */
355
+ excluded: Array<{ flight_no: string; reason: string }>
356
+ /** 不可行时的结构化最小改动建议 */
357
+ suggestions: string[]
358
+ }
359
+
360
+ function hmToMin(hm: string): number {
361
+ const [h, m] = hm.split(':').map(Number)
362
+ return (h ?? 0) * 60 + (m ?? 0)
363
+ }
364
+
365
+ function minToHm(min: number): string {
366
+ return `${String(Math.floor(min / 60)).padStart(2, '0')}:${String(min % 60).padStart(2, '0')}`
367
+ }
368
+
369
+ /**
370
+ * 「上午办事 + 当天下午直飞」类核心衔接判定:
371
+ * 最早起飞 = errand_end + 门到机场 + 值机截止;exact-date 在架直飞逐班过闸。
372
+ * 在架为空的失败语义与「有班但接不上」分开陈述(前者是库存问题,后者是约束问题)。
373
+ */
374
+ export function checkSameDayDeparture(
375
+ facts: BookableFact[],
376
+ q: { origin: string; destination: string; date: string },
377
+ c: SameDayDepartureConstraint,
378
+ ): SameDayDepartureVerdict {
379
+ const earliest = hmToMin(c.errand_end_local) + c.airport_transit_min + c.checkin_deadline_min
380
+ const scoped = latestFactsForRouteDate(facts, q.origin, q.destination, q.date)
381
+ const nonstopBookable = scoped.filter(f => f.bookability === 'bookable_exact_date' && f.nonstop !== false)
382
+ const feasible: FlightFact[] = []
383
+ const excluded: Array<{ flight_no: string; reason: string }> = []
384
+ for (const f of nonstopBookable) {
385
+ const dep = f.dep_local ? hmToMin(f.dep_local) : null
386
+ if (dep === null) {
387
+ excluded.push({ flight_no: f.flight_no, reason: '缺起飞时刻,不参与衔接判定' })
388
+ } else if (dep >= earliest) {
389
+ feasible.push(f)
390
+ } else {
391
+ excluded.push({ flight_no: f.flight_no, reason: `${f.dep_local} 起飞早于最早可接时刻 ${minToHm(earliest)}(${c.errand_end_local} 结束事务 + ${c.airport_transit_min}m 到机场 + ${c.checkin_deadline_min}m 值机)` })
392
+ }
393
+ }
394
+ const ok = feasible.length > 0
395
+ const suggestions: string[] = []
396
+ if (!ok) {
397
+ const inStock = nonstopBookable.map(f => `${f.flight_no} ${f.dep_local ?? '?'}`).join('、')
398
+ suggestions.push(`增加 1 个${q.origin}住宿夜:改乘次日早班${inStock ? `(当日在架:${inStock})` : ''}`)
399
+ suggestions.push('或提前一天完成地面事务/提前一天出发,把同日衔接改为隔夜衔接')
400
+ }
401
+ return { feasible: ok, earliest_departure_local: minToHm(earliest), feasible_flights: feasible, excluded, suggestions }
402
+ }
403
+
404
+ // ---------------------------------------------------------------------------
405
+ // 判定原语③:行程统计不变量(机器断言,不许自然语言总结反算)
406
+ // ---------------------------------------------------------------------------
407
+
408
+ export interface ItineraryFacts {
409
+ trip_start: string // YYYY-MM-DD
410
+ trip_end: string // YYYY-MM-DD(回到家的当地日期)
411
+ stays: Array<{ place: string; check_in: string; check_out: string }>
412
+ /** 机上夜(红眼跨夜)数 */
413
+ onboard_nights: number
414
+ /** O&D 段(用户视角段);flight 段含 legs 数(中转一段多 leg) */
415
+ od_segments: Array<{ from: string; to: string; date: string; mode: 'flight' | 'rail' | 'car'; legs: number }>
416
+ budget_items: Array<{ label: string; min_cny: number; max_cny: number }>
417
+ /** 产物里的预算下限话术(「可压到 ¥N」) */
418
+ claimed_floor_cny?: number
419
+ }
420
+
421
+ export interface InvariantViolation {
422
+ kind: 'nights_inconsistent' | 'legs_inconsistent' | 'budget_floor_inconsistent' | 'date_order'
423
+ detail: string
424
+ }
425
+
426
+ function daysBetween(a: string, b: string): number {
427
+ return Math.round((Date.parse(`${b}T00:00:00Z`) - Date.parse(`${a}T00:00:00Z`)) / 86_400_000)
428
+ }
429
+
430
+ export function itineraryInvariants(it: ItineraryFacts): InvariantViolation[] {
431
+ const violations: InvariantViolation[] = []
432
+ const totalNights = daysBetween(it.trip_start, it.trip_end)
433
+ let hotelNights = 0
434
+ for (const s of it.stays) {
435
+ const n = daysBetween(s.check_in, s.check_out)
436
+ if (n <= 0) violations.push({ kind: 'date_order', detail: `${s.place} 住宿 ${s.check_in}→${s.check_out} 晚数 ≤0` })
437
+ else hotelNights += n
438
+ }
439
+ if (hotelNights + it.onboard_nights !== totalNights) {
440
+ violations.push({
441
+ kind: 'nights_inconsistent',
442
+ detail: `酒店夜 ${hotelNights} + 机上夜 ${it.onboard_nights} = ${hotelNights + it.onboard_nights} ≠ 行程总夜数 ${totalNights}(${it.trip_start}→${it.trip_end})——夜数口径必须由结构化住宿反算,不许自然语言估算`,
443
+ })
444
+ }
445
+ for (const seg of it.od_segments) {
446
+ if (seg.mode === 'flight' && seg.legs < 1) {
447
+ violations.push({ kind: 'legs_inconsistent', detail: `${seg.from}→${seg.to}(${seg.date})flight O&D 段 legs=${seg.legs}——每段至少 1 leg` })
448
+ }
449
+ if (seg.date < it.trip_start || seg.date > it.trip_end) {
450
+ violations.push({ kind: 'date_order', detail: `${seg.from}→${seg.to} 日期 ${seg.date} 落在行程窗 ${it.trip_start}→${it.trip_end} 之外` })
451
+ }
452
+ }
453
+ const minSum = it.budget_items.reduce((acc, b) => acc + b.min_cny, 0)
454
+ if (it.claimed_floor_cny !== undefined && it.claimed_floor_cny < minSum) {
455
+ violations.push({
456
+ kind: 'budget_floor_inconsistent',
457
+ detail: `预算分项最低合计 ¥${minSum.toLocaleString()} > 产物声称可压到 ¥${it.claimed_floor_cny.toLocaleString()}——下限话术不得低于分项最低合计`,
458
+ })
459
+ }
460
+ return violations
461
+ }
462
+
463
+ // ---------------------------------------------------------------------------
464
+ // 判定原语④:回头路检测(A→B→A;存在 B→下一站直飞时给最小改动建议)
465
+ // ---------------------------------------------------------------------------
466
+
467
+ export interface BacktrackFinding {
468
+ kind: 'backtrack'
469
+ /** 回头路径,如 ['HKT','KBV','HKT'] */
470
+ path: string[]
471
+ /** 最小改动建议(存在 B→C 直飞边时) */
472
+ suggestion?: string
473
+ }
474
+
475
+ export function detectBacktrack(stops: string[], nonstopEdges: ReadonlySet<string>): BacktrackFinding[] {
476
+ const findings: BacktrackFinding[] = []
477
+ for (let i = 0; i + 2 < stops.length; i++) {
478
+ const a = stops[i]!, b = stops[i + 1]!, c = stops[i + 2]!
479
+ if (a !== c) continue
480
+ // A→B→A 回头;若 B→D(下一站)有直飞边,建议「去程后直接 B→D」
481
+ const d = stops[i + 3]
482
+ const suggestion = d && nonstopEdges.has(`${b}-${d}`)
483
+ ? `${b}→${d} 有直飞:改为 ${a}→${b} 后直接 ${b}→${d},消除 ${a}→${b}→${a} 回头路`
484
+ : undefined
485
+ findings.push({ kind: 'backtrack', path: [a, b, c], suggestion })
486
+ }
487
+ return findings
488
+ }
489
+
490
+ // ---------------------------------------------------------------------------
491
+ // 确定性渲染:航班/政策行只从结构化对象生成(issue #46 期望①:禁止凭记忆抄写)
492
+ // ---------------------------------------------------------------------------
493
+
494
+ /** 远期复核默认 gate:出发前 30 天 */
495
+ export function defaultReviewBy(tripDate: string): string {
496
+ const d = new Date(Date.parse(`${tripDate}T00:00:00Z`) - 30 * 86_400_000)
497
+ return d.toISOString().slice(0, 10)
498
+ }
499
+
500
+ /**
501
+ * 航班事实行。bookable_exact_date 才允许完整班次行;其余一律 fail-closed 措辞。
502
+ * 永不输出无条件 ✓;证据链(source/query_id/fetched_at)随行必达。
503
+ */
504
+ export function renderFlightFact(f: FlightFact): string {
505
+ const route = `${f.route.origin}→${f.route.destination}`
506
+ const evidence = `[${f.source}@${f.fetched_at} #${f.query_id}]`
507
+ if (f.bookability === 'unavailable_exact_date') {
508
+ const review = f.review_by ?? defaultReviewBy(f.date)
509
+ return `- ${route} ${f.date}:**未确认/当前不可售**——exact-date 源 ${f.source} 于 ${f.fetched_at.slice(0, 10)} 返回 0 条;到 ${review} 复核,不得用历史班期/相邻日期填充 ${evidence}`
510
+ }
511
+ if (f.bookability !== 'bookable_exact_date') {
512
+ return `- ${route} ${f.date} ${f.flight_no || ''}:**未核验**(${f.bookability})——仅作参考,不得作为可下单方案呈现 ${evidence}`
513
+ }
514
+ const carrier = f.operating_carrier && f.operating_carrier !== f.marketing_carrier
515
+ ? `营销 ${f.marketing_carrier ?? '?'} / 实际承运 ${f.operating_carrier}`
516
+ : (f.marketing_carrier ?? '')
517
+ const times = f.dep_local && f.arr_local ? ` ${f.dep_local}→${f.arr_local}` : ''
518
+ const nonstop = f.nonstop === false ? '(中转)' : ' 直飞'
519
+ // 双机场城市防混淆:落点机场码与城市码不同时显式标注(FD 落 DMK / VZ 落 BKK 不互换)
520
+ const airportNote = f.route.dest_airport && f.route.dest_airport !== f.route.destination
521
+ ? `(落 ${f.route.dest_airport})`
522
+ : ''
523
+ const price = f.price !== undefined ? ` ¥${f.price}` : ' 价待询'
524
+ const baggage = f.baggage_included === false ? ',不含托运行李' : ''
525
+ return `- ${route} ${f.date} ${f.flight_no}${carrier ? `(${carrier})` : ''}${times}${nonstop}${airportNote}${price}${baggage} ${evidence}`
526
+ }
527
+
528
+ /**
529
+ * 联程/分票连接行:只有同票保护(protected_connection=true)才允许称「联程」;
530
+ * 分票必须显式标红自助转机风险(无行李直挂/误机无保护)。
531
+ */
532
+ export function renderConnection(legA: FlightFact, legB: FlightFact): string {
533
+ const through = legA.protected_connection === true && legB.protected_connection === true
534
+ const head = `${legA.route.origin}→${legA.route.destination} ${legA.flight_no} + ${legB.route.origin}→${legB.route.destination} ${legB.flight_no}`
535
+ return through
536
+ ? `- ${head}:联程(同一票号/行李直挂/误机保护)`
537
+ : `- ${head}:⚠️ **分票/自助转机**——两段接得上 ≠ 联程;无同一票号、行李需自取重挂、误机无保护,缓冲与风险自担`
538
+ }
539
+
540
+ /**
541
+ * 政策事实行:恒为「截至 as_of 的现行政策」表述 + 复核 gate,永不用无条件 ✓。
542
+ * 远期(出发日晚于 as_of)必须附 review_by(默认 D-30)。
543
+ */
544
+ export function renderPolicyFact(p: PolicyFact, tripStart?: string): string {
545
+ const review = p.review_by ?? (tripStart ? defaultReviewBy(tripStart) : undefined)
546
+ const reviewNote = review ? `;远期政策须复核——到 ${review} 再核验一次` : ''
547
+ return `- ${p.subject}:截至 ${p.as_of} 的现行政策——${p.statement}${reviewNote} [${p.source}@${p.fetched_at} #${p.query_id}]`
548
+ }
549
+
550
+ /** 从结构化行程渲染夜数口径行(机器反算,唯一口径) */
551
+ export function renderNightsLine(it: ItineraryFacts): string {
552
+ const totalNights = daysBetween(it.trip_start, it.trip_end)
553
+ const hotelNights = it.stays.reduce((acc, s) => acc + Math.max(0, daysBetween(s.check_in, s.check_out)), 0)
554
+ const flightOd = it.od_segments.filter(s => s.mode === 'flight').length
555
+ const flightLegs = it.od_segments.filter(s => s.mode === 'flight').reduce((acc, s) => acc + s.legs, 0)
556
+ return `共 ${daysBetween(it.trip_start, it.trip_end) + 1} 天 ${totalNights} 晚 = ${hotelNights} 个酒店夜 + ${it.onboard_nights} 个机上夜;航班按 O&D ${flightOd} 段(共 ${flightLegs} 个 flight legs)`
557
+ }