@danceiny/gotry 0.0.1-rc.21 → 0.0.1-rc.24

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 (327) hide show
  1. package/README.md +102 -194
  2. package/README.zh-CN.md +115 -210
  3. package/bin/gotry-backend.js +53 -0
  4. package/bin/gotry-bootstrap.js +466 -35
  5. package/bin/gotry-inner.js +255 -36
  6. package/bin/gotry-process-liveness.d.ts +27 -0
  7. package/bin/gotry-process-liveness.js +97 -0
  8. package/bin/gotry-runtime-resolution.d.ts +1 -1
  9. package/bin/gotry-runtime-resolution.js +2 -2
  10. package/client/client.js +174 -0
  11. package/cordis.gotry-patch.yml +70 -93
  12. package/dist/capabilities/agent-reach-deep.js +45 -122
  13. package/dist/capabilities/agent-reach.js +63 -148
  14. package/dist/capabilities/anything.js +89 -75
  15. package/dist/capabilities/artifacts.js +123 -104
  16. package/dist/capabilities/channel-health.js +65 -45
  17. package/dist/capabilities/channel-registry.js +108 -87
  18. package/dist/capabilities/doctor.js +357 -235
  19. package/dist/capabilities/effect.js +223 -309
  20. package/dist/capabilities/fact-log.js +28 -14
  21. package/dist/capabilities/flyai.js +245 -156
  22. package/dist/capabilities/ground-transfer.js +509 -0
  23. package/dist/capabilities/hbcli.js +144 -148
  24. package/dist/capabilities/hotelbyte-transaction.js +194 -0
  25. package/dist/capabilities/incident-log.js +131 -61
  26. package/dist/capabilities/model-override.js +30 -10
  27. package/dist/capabilities/opensky.js +54 -43
  28. package/dist/capabilities/resilience.js +50 -32
  29. package/dist/capabilities/session/action-cache.js +50 -44
  30. package/dist/capabilities/session/adapters/ctrip-flight.js +119 -62
  31. package/dist/capabilities/session/adapters/ctrip-hotel.js +125 -110
  32. package/dist/capabilities/session/adapters/dida-portal.js +206 -0
  33. package/dist/capabilities/session/adapters/meituan-local.js +35 -54
  34. package/dist/capabilities/session/adapters/rail-12306.js +169 -112
  35. package/dist/capabilities/session/benchmark.js +85 -149
  36. package/dist/capabilities/session/extension-bridge.js +320 -259
  37. package/dist/capabilities/session/extension-channel.js +57 -76
  38. package/dist/capabilities/session/extension-distribution.js +115 -119
  39. package/dist/capabilities/session/extract.js +31 -21
  40. package/dist/capabilities/session/golden-score.js +55 -33
  41. package/dist/capabilities/session/health-watch.js +146 -154
  42. package/dist/capabilities/session/read-guard.js +55 -47
  43. package/dist/capabilities/session/static-flight-golden.js +49 -36
  44. package/dist/capabilities/session/transport.js +54 -61
  45. package/dist/capabilities/session/wizard.js +63 -93
  46. package/dist/capabilities/session-consent.js +143 -47
  47. package/dist/capabilities/session-login.js +95 -126
  48. package/dist/capabilities/session-search.js +391 -253
  49. package/dist/capabilities/sponsor-plugin.js +341 -0
  50. package/dist/capabilities/visa-policy.js +87 -73
  51. package/dist/capabilities/weather.js +163 -235
  52. package/dist/scripts/action-cache-tests.js +24 -59
  53. package/dist/scripts/agent-planning-turn-deadline-e2e.js +91 -142
  54. package/dist/scripts/agent-planning-turn-deadline-tests.js +80 -176
  55. package/dist/scripts/agent-reach-deep-tests.js +30 -40
  56. package/dist/scripts/agent-reach-tests.js +26 -18
  57. package/dist/scripts/agent-reach-wrapper-tests.js +46 -50
  58. package/dist/scripts/anything-tests.js +58 -62
  59. package/dist/scripts/artifact-client-contract-tests.js +69 -0
  60. package/dist/scripts/artifacts-capability-tests.js +235 -0
  61. package/dist/scripts/async-collect.js +26 -15
  62. package/dist/scripts/benchmark-environment-bridge-e2e.js +287 -684
  63. package/dist/scripts/benchmark-environment-bridge-tests.js +818 -3123
  64. package/dist/scripts/booking-copilot-availability-ledger-binding-tests.js +66 -279
  65. package/dist/scripts/booking-copilot-availability-policy-tests.js +153 -1257
  66. package/dist/scripts/booking-copilot-bin-proof-tests.js +22 -45
  67. package/dist/scripts/booking-copilot-crossrepo-fixture-server.js +64 -76
  68. package/dist/scripts/booking-copilot-dsh-core-proof-tests.js +69 -199
  69. package/dist/scripts/booking-copilot-dsh-planner-proof-tests.js +393 -759
  70. package/dist/scripts/booking-copilot-dsh-plugin-proof-tests.js +33 -75
  71. package/dist/scripts/booking-copilot-event-sequence-concurrency-proof-tests.js +60 -110
  72. package/dist/scripts/booking-copilot-gap-code-contract-proof-tests.js +28 -66
  73. package/dist/scripts/booking-copilot-operation-ledger-concurrency-proof-tests.js +72 -271
  74. package/dist/scripts/booking-copilot-receipt-ledger-concurrency-proof-tests.js +73 -275
  75. package/dist/scripts/booking-copilot-runtime-proof-tests.js +784 -3398
  76. package/dist/scripts/booking-copilot-server-proof-tests.js +63 -168
  77. package/dist/scripts/booking-copilot-startup-proof-tests.js +38 -124
  78. package/dist/scripts/booking-executor-tests.js +80 -0
  79. package/dist/scripts/booking-recovery-chain-tests.js +182 -0
  80. package/dist/scripts/booking-saga-tests.js +61 -123
  81. package/dist/scripts/booking-surface-contract-proof-tests.js +152 -1167
  82. package/dist/scripts/bootstrap-tests.js +1383 -128
  83. package/dist/scripts/build-changelog.js +89 -130
  84. package/dist/scripts/build-metrics-report.js +135 -143
  85. package/dist/scripts/changelog-tests.js +35 -82
  86. package/dist/scripts/channel-probe-tests.js +44 -116
  87. package/dist/scripts/channel-probe.js +84 -167
  88. package/dist/scripts/channel-registry-tests.js +97 -185
  89. package/dist/scripts/companion-tests.js +25 -70
  90. package/dist/scripts/dida-cookie-probe.js +87 -0
  91. package/dist/scripts/dida-sw-probe.js +114 -0
  92. package/dist/scripts/diff-test.js +17 -12
  93. package/dist/scripts/doctor-tests.js +428 -120
  94. package/dist/scripts/dsh-artifact-e2e.js +150 -0
  95. package/dist/scripts/dsh-artifact-web-e2e.js +443 -0
  96. package/dist/scripts/dsh-http-proxy-sse-proof.js +90 -0
  97. package/dist/scripts/dsh-runtime-closure-tests.js +110 -153
  98. package/dist/scripts/dsh-runtime-closure.js +75 -63
  99. package/dist/scripts/dsh-session-v3-migration-proof.js +106 -0
  100. package/dist/scripts/dsh-subprocess-local-proof.js +149 -0
  101. package/dist/scripts/dsh-target-closure-proof.js +178 -0
  102. package/dist/scripts/effect-tests.js +165 -552
  103. package/dist/scripts/engine-run.js +1 -3
  104. package/dist/scripts/engine-tests.js +16 -10
  105. package/dist/scripts/evaluation-cadence-tests.js +69 -242
  106. package/dist/scripts/evaluation-contract-tests.js +193 -499
  107. package/dist/scripts/extension-distribution-cli.js +19 -15
  108. package/dist/scripts/extension-distribution-tests.js +98 -211
  109. package/dist/scripts/extension-tests.js +366 -389
  110. package/dist/scripts/fact-gate-tests.js +725 -263
  111. package/dist/scripts/fixtures/extension-bridge-unref-child.mjs +21 -0
  112. package/dist/scripts/flight-hotel-anchor-363-registered-e2e.js +169 -0
  113. package/dist/scripts/flight-malformed-tests.js +159 -0
  114. package/dist/scripts/flyai-tests.js +325 -68
  115. package/dist/scripts/g5-guard-tests.js +131 -0
  116. package/dist/scripts/g5-guard.js +189 -0
  117. package/dist/scripts/gen-lunar-anchors.js +106 -0
  118. package/dist/scripts/gotry-backend-kernel-tests.js +79 -0
  119. package/dist/scripts/ground-transfer-tests.js +956 -0
  120. package/dist/scripts/hbcli-e2e-tests.js +71 -90
  121. package/dist/scripts/hbcli-live-optin-tests.js +96 -0
  122. package/dist/scripts/hbcli-release-contract-tests.js +122 -0
  123. package/dist/scripts/hbcli-tests.js +41 -115
  124. package/dist/scripts/health-watch-cli.js +42 -28
  125. package/dist/scripts/hotel-date-gate-tests.js +496 -0
  126. package/dist/scripts/hotelbyte-reconcile-tests.js +141 -0
  127. package/dist/scripts/hotelbyte-spawn-e2e-tests.js +373 -0
  128. package/dist/scripts/i18n-tests.js +16 -9
  129. package/dist/scripts/incident-tests.js +281 -87
  130. package/dist/scripts/issue-194-job-id-guard-tests.js +106 -0
  131. package/dist/scripts/issue-233-cancel-refund-commission-tests.js +392 -0
  132. package/dist/scripts/issue-271-liveness-tests.js +547 -0
  133. package/dist/scripts/issue-289-model-retry-real-tests.js +296 -0
  134. package/dist/scripts/issue-289-model-retry-tests.js +441 -0
  135. package/dist/scripts/issue-289-web-retry-e2e.js +630 -0
  136. package/dist/scripts/issue-338-home-city-e2e.js +577 -0
  137. package/dist/scripts/issue343-real-entry-e2e.js +160 -0
  138. package/dist/scripts/journey-tests.js +22 -27
  139. package/dist/scripts/kernel-manifest-evidence.js +109 -0
  140. package/dist/scripts/kernel-manifest-gate.js +126 -0
  141. package/dist/scripts/kernel-manifest-tests.js +212 -0
  142. package/dist/scripts/kernel-manifest-trace-entry.js +7 -0
  143. package/dist/scripts/kernel-manifest-trace-hook.mjs +28 -0
  144. package/dist/scripts/kernel-manifest.js +369 -0
  145. package/dist/scripts/ledger-repair-apply-tests.js +316 -0
  146. package/dist/scripts/ledger-repair-plan-tests.js +375 -0
  147. package/dist/scripts/ledger-tests.js +325 -340
  148. package/dist/scripts/ledger-workflow-crash.js +10 -20
  149. package/dist/scripts/map-tools-vendor-package-proof.js +206 -134
  150. package/dist/scripts/memory-capture-tests.js +242 -61
  151. package/dist/scripts/memory-decay-tests.js +18 -52
  152. package/dist/scripts/memory-lifecycle-tests.js +657 -0
  153. package/dist/scripts/memory-lifecycle.js +196 -0
  154. package/dist/scripts/memory-metrics.js +24 -12
  155. package/dist/scripts/memory-value-report.js +474 -222
  156. package/dist/scripts/memory-value-tests.js +328 -0
  157. package/dist/scripts/metrics-report-tests.js +62 -199
  158. package/dist/scripts/model-override-e2e.js +66 -105
  159. package/dist/scripts/nightly-evidence-tests.js +64 -89
  160. package/dist/scripts/nightly-evidence.js +108 -111
  161. package/dist/scripts/nudge-digest.js +39 -28
  162. package/dist/scripts/onboarding-tests.js +63 -88
  163. package/dist/scripts/opensky-check.js +18 -13
  164. package/dist/scripts/opensky-tests.js +28 -28
  165. package/dist/scripts/persona-surface-guard-tests.js +37 -12
  166. package/dist/scripts/pnpm-dsh-closure-proof.js +2 -5
  167. package/dist/scripts/policy-anchor-359-registered-e2e.js +214 -0
  168. package/dist/scripts/price-drift-tests.js +126 -227
  169. package/dist/scripts/price-drift-watch.js +209 -253
  170. package/dist/scripts/probe-poi-tests.js +52 -45
  171. package/dist/scripts/product-metrics.js +187 -273
  172. package/dist/scripts/publish-preverify.js +47 -41
  173. package/dist/scripts/realtime-pricing-tests.js +37 -76
  174. package/dist/scripts/replay-async.js +20 -18
  175. package/dist/scripts/replay-real.js +16 -18
  176. package/dist/scripts/replay.js +52 -82
  177. package/dist/scripts/session-attach-diagnose.js +16 -12
  178. package/dist/scripts/session-attach-poc.js +34 -37
  179. package/dist/scripts/session-benchmark.js +66 -147
  180. package/dist/scripts/session-dida-live-e2e.js +151 -0
  181. package/dist/scripts/session-extract-tests.js +14 -35
  182. package/dist/scripts/session-login.js +14 -13
  183. package/dist/scripts/session-tests.js +545 -583
  184. package/dist/scripts/sf-live-benchmark.js +92 -110
  185. package/dist/scripts/sf-live-cli-tests.js +2 -9
  186. package/dist/scripts/sf-soft-score-tests.js +19 -60
  187. package/dist/scripts/sf-summary-tests.js +149 -0
  188. package/dist/scripts/sf-summary.js +466 -84
  189. package/dist/scripts/skeleton-check.js +16 -14
  190. package/dist/scripts/skeleton-integration-test.js +11 -10
  191. package/dist/scripts/skills-contract-tests.js +51 -46
  192. package/dist/scripts/smoke-session-gate-tests.js +12 -20
  193. package/dist/scripts/smoke.js +541 -422
  194. package/dist/scripts/sponsor-reuse-tests.js +262 -0
  195. package/dist/scripts/state-cli-tests.js +226 -101
  196. package/dist/scripts/state-cli.js +549 -212
  197. package/dist/scripts/static-golden-tests.js +46 -180
  198. package/dist/scripts/time-eval-tests.js +210 -192
  199. package/dist/scripts/travel-timeline-tests.js +29 -93
  200. package/dist/scripts/turn-handoff-collect-tests.js +46 -93
  201. package/dist/scripts/turn-handoff-collect.js +71 -99
  202. package/dist/scripts/turn-policy-tests.js +28 -29
  203. package/dist/scripts/typed-contract-canary.js +77 -162
  204. package/dist/scripts/tz-resolver-sanity.js +50 -0
  205. package/dist/scripts/tz-resolver-tests.js +584 -0
  206. package/dist/scripts/unified-tests.js +23 -19
  207. package/dist/scripts/visa-policy-tests.js +31 -44
  208. package/dist/scripts/weather-tests.js +121 -543
  209. package/dist/scripts/wish-channel-gate-tests.js +29 -86
  210. package/dist/scripts/write-gate-tests.js +522 -0
  211. package/dist/scripts/z3-lifecycle-fault-tests.js +188 -0
  212. package/dist/scripts/z3-lifecycle-tests.js +170 -0
  213. package/dist/scripts/z3-race-repeat-tests.js +39 -0
  214. package/dist/scripts/z3-race-tests.js +18 -12
  215. package/dist/src/artifact-gate.js +652 -221
  216. package/dist/src/backend/kernel.js +91 -0
  217. package/dist/src/backend/modules/booking-copilot.js +55 -0
  218. package/dist/src/backend/modules/booking-executor.js +124 -0
  219. package/dist/src/backend/modules/session-search.js +194 -0
  220. package/dist/src/benchmark-agent-conformance.js +296 -262
  221. package/dist/src/benchmark-environment-bridge.js +298 -413
  222. package/dist/src/benchmark-headless-child-diagnostics.js +93 -100
  223. package/dist/src/benchmark-tool-isolation.js +94 -67
  224. package/dist/src/bookable-facts.js +299 -174
  225. package/dist/src/booking-saga.js +64 -120
  226. package/dist/src/booking-surface/availability-policy.js +443 -576
  227. package/dist/src/booking-surface/cancel-refund-commission.js +379 -0
  228. package/dist/src/booking-surface/contracts.js +24 -80
  229. package/dist/src/booking-surface/dsh-planner.js +510 -281
  230. package/dist/src/booking-surface/dsh-plugin.js +17 -1
  231. package/dist/src/booking-surface/error-codes.js +82 -10
  232. package/dist/src/booking-surface/index.js +0 -3
  233. package/dist/src/booking-surface/profile.js +10 -54
  234. package/dist/src/booking-surface/recovery-chain.js +367 -0
  235. package/dist/src/booking-surface/runtime.js +765 -891
  236. package/dist/src/booking-surface/server.js +200 -251
  237. package/dist/src/booking-surface/startup.js +58 -54
  238. package/dist/src/booking-surface/validation.js +150 -218
  239. package/dist/src/bridge.js +20 -13
  240. package/dist/src/companions.js +48 -74
  241. package/dist/src/contracts.js +21 -43
  242. package/dist/src/dsh-llm.js +82 -120
  243. package/dist/src/engine.js +253 -239
  244. package/dist/src/evaluation-cadence.js +72 -209
  245. package/dist/src/evaluation-contracts.js +220 -843
  246. package/dist/src/flight-pack-adapter.js +54 -0
  247. package/dist/src/flight-pack-contract.js +2 -0
  248. package/dist/src/gotry-backend.js +70 -0
  249. package/dist/src/hotel-date-gate.js +118 -0
  250. package/dist/src/i18n.js +18 -7
  251. package/dist/src/index.js +1425 -1629
  252. package/dist/src/journey.js +132 -81
  253. package/dist/src/ledger-repair-apply.js +538 -0
  254. package/dist/src/ledger-repair-plan.js +463 -0
  255. package/dist/src/loop.js +257 -166
  256. package/dist/src/memory-capture.js +180 -32
  257. package/dist/src/memory-decay.js +30 -14
  258. package/dist/src/memory-lifecycle.js +1310 -0
  259. package/dist/src/memory-utility.js +27 -40
  260. package/dist/src/mock-llm.js +36 -61
  261. package/dist/src/model.js +81 -36
  262. package/dist/src/realtime-pricing.js +63 -72
  263. package/dist/src/slot-spec.js +84 -106
  264. package/dist/src/state-ledger.js +310 -471
  265. package/dist/src/subagent-job-id-guard.js +58 -0
  266. package/dist/src/time-anchor.js +231 -33
  267. package/dist/src/tool-packet.js +20 -8
  268. package/dist/src/travel-slots.js +58 -35
  269. package/dist/src/travel-timeline.js +44 -63
  270. package/dist/src/turn-deadline.js +121 -127
  271. package/dist/src/turn-policy.js +61 -89
  272. package/dist/src/tz-resolver.js +143 -0
  273. package/dist/src/unified.js +504 -381
  274. package/dist/src/wish-pool.js +39 -14
  275. package/dist/src/write-gate.js +495 -0
  276. package/dist/src/z3-shared.js +273 -7
  277. package/extension/README.md +4 -3
  278. package/extension/background.js +125 -14
  279. package/extension/content-bridge.js +23 -1
  280. package/extension/content-main.js +15 -4
  281. package/extension/manifest.json +16 -8
  282. package/package.json +251 -220
  283. package/ts/capabilities/agent-reach.ts +4 -4
  284. package/ts/capabilities/anything.ts +1 -1
  285. package/ts/capabilities/artifacts.ts +46 -9
  286. package/ts/capabilities/flyai.ts +156 -37
  287. package/ts/capabilities/hbcli.ts +1 -1
  288. package/ts/capabilities/incident-log.ts +88 -59
  289. package/ts/capabilities/session/adapters/ctrip-flight.ts +99 -36
  290. package/ts/capabilities/session/adapters/dida-portal.ts +250 -0
  291. package/ts/capabilities/session/adapters/rail-12306.ts +123 -24
  292. package/ts/capabilities/session/extension-bridge.ts +226 -101
  293. package/ts/capabilities/session/extension-channel.ts +22 -9
  294. package/ts/capabilities/session/wizard.ts +2 -2
  295. package/ts/capabilities/session-consent.ts +98 -14
  296. package/ts/capabilities/session-login.ts +1 -0
  297. package/ts/capabilities/session-search.ts +315 -31
  298. package/ts/dsh-runtime/vendor/README.md +8 -4
  299. package/ts/dsh-runtime/vendor/dsh-map-tools/README.en.md +7 -1
  300. package/ts/dsh-runtime/vendor/dsh-map-tools/README.md +5 -3
  301. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/settings-ns.js +1 -1
  302. package/ts/dsh-runtime/vendor/dsh-map-tools/lib/types/settings-ns.d.ts +1 -1
  303. package/ts/dsh-runtime/vendor/dsh-map-tools/package.json +6 -6
  304. package/ts/package.json +236 -16
  305. package/ts/scripts/map-tools-vendor-package-proof.ts +152 -31
  306. package/ts/scripts/state-cli.ts +418 -51
  307. package/ts/src/artifact-gate.ts +561 -15
  308. package/ts/src/benchmark-environment-bridge.ts +37 -20
  309. package/ts/src/bookable-facts.ts +183 -7
  310. package/ts/src/booking-surface/cancel-refund-commission.ts +488 -0
  311. package/ts/src/booking-surface/dsh-planner.ts +240 -32
  312. package/ts/src/booking-surface/dsh-plugin.js +17 -1
  313. package/ts/src/booking-surface/error-codes.ts +75 -0
  314. package/ts/src/booking-surface/recovery-chain.ts +409 -0
  315. package/ts/src/booking-surface/server.ts +84 -51
  316. package/ts/src/booking-surface/validation.ts +2 -0
  317. package/ts/src/contracts.ts +12 -2
  318. package/ts/src/dsh-llm.ts +4 -8
  319. package/ts/src/index.ts +609 -90
  320. package/ts/src/loop.ts +116 -7
  321. package/ts/src/memory-capture.ts +227 -3
  322. package/ts/src/mock-llm.ts +4 -8
  323. package/ts/src/model.ts +88 -2
  324. package/ts/src/state-ledger.ts +47 -29
  325. package/ts/src/subagent-job-id-guard.ts +72 -0
  326. package/ts/src/time-anchor.ts +217 -13
  327. package/ts/src/unified.ts +316 -54
@@ -0,0 +1,488 @@
1
+ /**
2
+ * Cancel/refund independent outcomes + explicit commission disclosure
3
+ * (issue #233, M5-4 pre-entry contract layer; parent #136).
4
+ *
5
+ * Contract only: pure types + pure functions. Zero network, zero subprocess,
6
+ * zero ledger/schema change, zero supplier call surface — the write path stays
7
+ * sealed behind #136 M5 Entry; receipt/outbox/dispatch authority belongs to
8
+ * #231/#232 and is deliberately NOT modeled here.
9
+ *
10
+ * Frozen sources of truth:
11
+ * - docs/design/write-gate-production-design.md §3 (SupplierOutcome closed set),
12
+ * §4 (commission_disclosure digest enters the request fingerprint; a
13
+ * disclosure change invalidates the old receipt), §7 (outcome × user copy
14
+ * matrix), §8 (cancellation / refund order / wallet refund are separate
15
+ * outcomes; cancel.serviceFee is not the customer refund amount; pending →
16
+ * compensated cancels only the local suggestion and never means "refunded"),
17
+ * §10 (commission/sponsorship disclosure before confirmation; unknown must
18
+ * not default to none), §11 (redaction);
19
+ * - docs/design/fact-writegate-seam.md §2.3 (wording authority per claim type:
20
+ * "cancellation requested" only; refunded only from authoritative evidence).
21
+ *
22
+ * Default-off: nothing in this module is wired into any runtime path. The
23
+ * focused suite ts/scripts/issue-233-cancel-refund-commission-tests.ts pins
24
+ * the contract (run-all §62).
25
+ */
26
+
27
+ import { createHash } from 'node:crypto'
28
+
29
+ // ---- 1. Independent outcome closed sets -----------------------------------------
30
+
31
+ export const CANCELLATION_OUTCOME_SCHEMA = 'gotry.cancellation_outcome.v1' as const
32
+ /** Cancel REQUEST outcome. There is deliberately no "cancelled" terminal here:
33
+ * only an explicit supplier cancellation receipt (supplierCancellationConfirmed)
34
+ * upgrades a submission into a confirmed cancellation. */
35
+ export const CANCELLATION_STATUSES = ['not_requested', 'cancel_submitted', 'cancel_failed', 'cancel_unknown'] as const
36
+ export type CancellationStatus = (typeof CANCELLATION_STATUSES)[number]
37
+
38
+ export const REFUND_OUTCOME_SCHEMA = 'gotry.refund_outcome.v1' as const
39
+ /** Money-arrival outcome. Independent from the cancellation outcome by design:
40
+ * the two objects are never merged into a single success state. */
41
+ export const REFUND_STATUSES = ['not_applicable', 'refund_pending', 'refund_failed', 'refunded', 'refund_unknown'] as const
42
+ export type RefundStatus = (typeof REFUND_STATUSES)[number]
43
+
44
+ /** ADR-17 ledger alphabet, mirrored read-only for copy consistency checks.
45
+ * This module does not touch the ledger (that is #231's surface). */
46
+ export const LOCAL_LEDGER_STATUSES = ['pending', 'confirmed', 'compensated'] as const
47
+ export type LocalLedgerStatus = (typeof LOCAL_LEDGER_STATUSES)[number]
48
+
49
+ /** Refund amount may only be concluded from authoritative refund/wallet records. */
50
+ export const REFUND_AUTHORITY_SOURCES = ['supplier_refund_record', 'wallet_refund_record'] as const
51
+ export type RefundAuthoritySource = (typeof REFUND_AUTHORITY_SOURCES)[number]
52
+ /** The supplier cancellation fee is a separate disclosure; it is never a refund amount. */
53
+ export const SERVICE_FEE_SOURCE = 'cancel_return_service_fee' as const
54
+
55
+ /** supplierReferenceNo is used only as a supplier-returned value — never decoded
56
+ * or guessed from customerReferenceNo (write-gate design §2/§6). The only way to
57
+ * construct one is `supplierReferenceNoFromReturn` with an explicit return source. */
58
+ export const SUPPLIER_REFERENCE_RETURN_SOURCES = ['supplier_cancel_return', 'supplier_query_return', 'supplier_refund_return'] as const
59
+ export type SupplierReferenceReturnSource = (typeof SUPPLIER_REFERENCE_RETURN_SOURCES)[number]
60
+
61
+ export interface SupplierReferenceNo {
62
+ readonly value: string
63
+ readonly source: SupplierReferenceReturnSource
64
+ }
65
+
66
+ export function supplierReferenceNoFromReturn(value: string, source: SupplierReferenceReturnSource): { ok: true; value: SupplierReferenceNo } | { ok: false; reason: string } {
67
+ const trimmed = typeof value === 'string' ? value.trim() : ''
68
+ if (trimmed === '') return { ok: false, reason: 'supplier_reference_empty' }
69
+ if (!(SUPPLIER_REFERENCE_RETURN_SOURCES as readonly string[]).includes(source)) return { ok: false, reason: 'supplier_reference_not_returned_value' }
70
+ return { ok: true, value: Object.freeze({ value: trimmed, source }) }
71
+ }
72
+
73
+ export interface MoneyAmount {
74
+ readonly amount: string
75
+ readonly currency: string
76
+ /** Where this number is authoritative from (refund authorities only for customerRefund). */
77
+ readonly source: string
78
+ }
79
+
80
+ export interface RefundEvidence {
81
+ readonly kind: RefundAuthoritySource
82
+ readonly digest: string
83
+ }
84
+
85
+ export interface CancellationOutcome {
86
+ readonly schema: typeof CANCELLATION_OUTCOME_SCHEMA
87
+ readonly status: CancellationStatus
88
+ readonly customerReferenceNo: string
89
+ readonly supplierReferenceNo?: SupplierReferenceNo
90
+ /** Explicit supplier cancellation receipt; its presence (and only it) allows
91
+ * "cancelled" wording. Requested-but-unconfirmed stays orderCancelled=unknown. */
92
+ readonly supplierCancellationConfirmed?: { readonly digest: string }
93
+ readonly evidenceDigest?: string
94
+ readonly observedAt: string
95
+ }
96
+
97
+ export interface RefundOutcome {
98
+ readonly schema: typeof REFUND_OUTCOME_SCHEMA
99
+ readonly status: RefundStatus
100
+ /** Customer refund amount — only from REFUND_AUTHORITY_SOURCES; never the cancel serviceFee. */
101
+ readonly customerRefund?: MoneyAmount
102
+ /** Supplier-side cancellation fee, disclosed separately; not the refund. */
103
+ readonly supplierServiceFee?: { readonly amount: string; readonly currency: string }
104
+ /** Arrival conclusion binds authoritative evidence; `refunded` requires it. */
105
+ readonly evidence?: RefundEvidence
106
+ readonly reasonCode?: string
107
+ readonly observedAt: string
108
+ }
109
+
110
+ const AMOUNT_RE = /^\d+(\.\d+)?$/
111
+ function nonEmpty(v: unknown): v is string {
112
+ return typeof v === 'string' && v.trim() !== ''
113
+ }
114
+ function validAmount(v: unknown): v is string {
115
+ return nonEmpty(v) && AMOUNT_RE.test(v.trim())
116
+ }
117
+
118
+ export type ContractResult<T> = { ok: true; value: T } | { ok: false; reason: string }
119
+
120
+ export function cancellationOutcome(input: CancellationOutcome): ContractResult<CancellationOutcome> {
121
+ if (input?.schema !== CANCELLATION_OUTCOME_SCHEMA) return { ok: false, reason: 'schema_mismatch' }
122
+ if (!(CANCELLATION_STATUSES as readonly string[]).includes(input.status)) return { ok: false, reason: 'unknown_cancellation_status' }
123
+ if (!nonEmpty(input.customerReferenceNo)) return { ok: false, reason: 'customer_reference_required' }
124
+ if (input.supplierReferenceNo !== undefined) {
125
+ const r = input.supplierReferenceNo
126
+ if (!nonEmpty(r?.value) || !(SUPPLIER_REFERENCE_RETURN_SOURCES as readonly string[]).includes(r?.source)) {
127
+ return { ok: false, reason: 'supplier_reference_not_returned_value' }
128
+ }
129
+ }
130
+ if (input.supplierCancellationConfirmed !== undefined && !nonEmpty(input.supplierCancellationConfirmed?.digest)) {
131
+ return { ok: false, reason: 'supplier_cancellation_receipt_digest_required' }
132
+ }
133
+ if (!nonEmpty(input.observedAt)) return { ok: false, reason: 'observed_at_required' }
134
+ return { ok: true, value: Object.freeze({ ...input }) }
135
+ }
136
+
137
+ export function refundOutcome(input: RefundOutcome): ContractResult<RefundOutcome> {
138
+ if (input?.schema !== REFUND_OUTCOME_SCHEMA) return { ok: false, reason: 'schema_mismatch' }
139
+ if (!(REFUND_STATUSES as readonly string[]).includes(input.status)) return { ok: false, reason: 'unknown_refund_status' }
140
+ if (!nonEmpty(input.observedAt)) return { ok: false, reason: 'observed_at_required' }
141
+ if (input.customerRefund !== undefined) {
142
+ const cr = input.customerRefund
143
+ if (!validAmount(cr?.amount) || !nonEmpty(cr?.currency)) return { ok: false, reason: 'refund_amount_invalid' }
144
+ if (cr.source === SERVICE_FEE_SOURCE) return { ok: false, reason: 'service_fee_used_as_refund_amount' }
145
+ }
146
+ if (input.status === 'refunded') {
147
+ const authoritative =
148
+ input.customerRefund !== undefined &&
149
+ (REFUND_AUTHORITY_SOURCES as readonly string[]).includes(input.customerRefund.source) &&
150
+ input.evidence !== undefined &&
151
+ (REFUND_AUTHORITY_SOURCES as readonly string[]).includes(input.evidence?.kind) &&
152
+ nonEmpty(input.evidence?.digest)
153
+ if (!authoritative) return { ok: false, reason: 'refund_claimed_without_evidence' }
154
+ }
155
+ if (input.supplierServiceFee !== undefined && (!validAmount(input.supplierServiceFee?.amount) || !nonEmpty(input.supplierServiceFee?.currency))) {
156
+ return { ok: false, reason: 'service_fee_invalid' }
157
+ }
158
+ return { ok: true, value: Object.freeze({ ...input }) }
159
+ }
160
+
161
+ // ---- 2. Aftercare facts (never one merged status) --------------------------------
162
+
163
+ export interface AftercareFacts {
164
+ /** A cancellation request was submitted to the supplier. */
165
+ readonly cancellationRequested: boolean
166
+ /** true only with an explicit supplier cancellation receipt; false on
167
+ * cancel_failed; 'unknown' while submitted-but-unconfirmed (requested ≠ cancelled). */
168
+ readonly orderCancelled: boolean | 'unknown'
169
+ /** true only on evidenced refunded; 'unknown' while pending/unknown. */
170
+ readonly moneyReturned: boolean | 'unknown'
171
+ readonly refundStatus: RefundStatus
172
+ }
173
+
174
+ export function aftercareFacts(cancel: CancellationOutcome, refund: RefundOutcome): AftercareFacts {
175
+ return Object.freeze({
176
+ cancellationRequested: cancel.status === 'cancel_submitted',
177
+ orderCancelled:
178
+ cancel.supplierCancellationConfirmed !== undefined
179
+ ? true
180
+ : cancel.status === 'cancel_failed'
181
+ ? false
182
+ : 'unknown',
183
+ moneyReturned:
184
+ refund.status === 'refunded'
185
+ ? true
186
+ : refund.status === 'refund_failed' || refund.status === 'not_applicable'
187
+ ? false
188
+ : 'unknown',
189
+ refundStatus: refund.status,
190
+ })
191
+ }
192
+
193
+ // ---- 3. Commission / sponsorship disclosure --------------------------------------
194
+
195
+ export const COMMISSION_DISCLOSURE_SCHEMA = 'gotry.commission_disclosure.v1' as const
196
+ export const COMMISSION_BENEFIT_KINDS = ['commission', 'rebate', 'sponsorship', 'preferred_placement'] as const
197
+ export type CommissionBenefitKind = (typeof COMMISSION_BENEFIT_KINDS)[number]
198
+ export const COMMISSION_CERTAINTIES = ['known_benefit', 'known_none', 'unknown'] as const
199
+ export type CommissionCertainty = (typeof COMMISSION_CERTAINTIES)[number]
200
+ export const COMMISSION_SOURCES = ['supplier_field', 'contract_rule'] as const
201
+ export type CommissionSource = (typeof COMMISSION_SOURCES)[number]
202
+ export const COMMISSION_AMOUNT_BASES = ['fixed', 'percent_of_total', 'per_night'] as const
203
+ export type CommissionAmountBasis = (typeof COMMISSION_AMOUNT_BASES)[number]
204
+
205
+ const PAID_BY = ['supplier', 'distributor', 'customer'] as const
206
+ export type CommissionPaidBy = (typeof PAID_BY)[number]
207
+
208
+ export interface CommissionBenefit {
209
+ readonly kind: CommissionBenefitKind
210
+ readonly paidBy: CommissionPaidBy
211
+ /** Recipient as an HMAC pseudonym or 'gotry'; never a raw name (§11 redaction). */
212
+ readonly paidTo: string
213
+ readonly basis: {
214
+ readonly type: CommissionAmountBasis
215
+ readonly amount?: string
216
+ readonly percent?: string
217
+ readonly currency?: string
218
+ }
219
+ }
220
+
221
+ export interface CommissionDisclosure {
222
+ readonly schema: typeof COMMISSION_DISCLOSURE_SCHEMA
223
+ readonly certainty: CommissionCertainty
224
+ readonly benefits: readonly CommissionBenefit[]
225
+ readonly source: CommissionSource
226
+ }
227
+
228
+ export const COMMISSION_VIOLATION_CODES = [
229
+ 'commission_undisclosed',
230
+ 'commission_none_without_source',
231
+ 'commission_benefit_incomplete',
232
+ 'commission_amount_basis_inconsistent',
233
+ 'disclosure_digest_mismatch',
234
+ ] as const
235
+ export type CommissionViolationCode = (typeof COMMISSION_VIOLATION_CODES)[number]
236
+
237
+ const POSITIVE_NUMBER_RE = /^(0*[1-9][0-9]*(\.[0-9]+)?|0*\.[0-9]*[1-9][0-9]*)$/
238
+
239
+ export function validateCommissionDisclosure(v: unknown): { ok: true } | { ok: false; violations: CommissionViolationCode[] } {
240
+ if (typeof v !== 'object' || v === null || (v as CommissionDisclosure).schema !== COMMISSION_DISCLOSURE_SCHEMA) {
241
+ return { ok: false, violations: ['commission_undisclosed'] }
242
+ }
243
+ const d = v as CommissionDisclosure
244
+ if (!(COMMISSION_CERTAINTIES as readonly string[]).includes(d.certainty)) return { ok: false, violations: ['commission_undisclosed'] }
245
+ if (!(COMMISSION_SOURCES as readonly string[]).includes(d.source)) return { ok: false, violations: ['commission_benefit_incomplete'] }
246
+ const violations: CommissionViolationCode[] = []
247
+ if (!Array.isArray(d.benefits)) return { ok: false, violations: ['commission_benefit_incomplete'] }
248
+ if (d.certainty === 'known_none' || d.certainty === 'unknown') {
249
+ if (d.benefits.length > 0) violations.push('commission_benefit_incomplete')
250
+ if (d.certainty === 'known_none' && d.source !== 'contract_rule') violations.push('commission_none_without_source')
251
+ }
252
+ if (d.certainty === 'known_benefit') {
253
+ if (d.benefits.length === 0) violations.push('commission_benefit_incomplete')
254
+ }
255
+ for (const b of d.benefits) {
256
+ if (
257
+ !(COMMISSION_BENEFIT_KINDS as readonly string[]).includes(b?.kind) ||
258
+ !(PAID_BY as readonly string[]).includes(b?.paidBy) ||
259
+ !nonEmpty(b?.paidTo)
260
+ ) {
261
+ violations.push('commission_benefit_incomplete')
262
+ continue
263
+ }
264
+ const basis = b.basis
265
+ if (!(COMMISSION_AMOUNT_BASES as readonly string[]).includes(basis?.type)) {
266
+ violations.push('commission_amount_basis_inconsistent')
267
+ continue
268
+ }
269
+ if (basis.type === 'percent_of_total') {
270
+ const okPercent = validAmount(basis.percent) && POSITIVE_NUMBER_RE.test(basis.percent.trim()) && basis.amount === undefined
271
+ if (!okPercent) violations.push('commission_amount_basis_inconsistent')
272
+ } else {
273
+ const okFixed = validAmount(basis.amount) && nonEmpty(basis.currency) && basis.percent === undefined
274
+ if (!okFixed) violations.push('commission_amount_basis_inconsistent')
275
+ }
276
+ }
277
+ return violations.length === 0 ? { ok: true } : { ok: false, violations }
278
+ }
279
+
280
+ /** Canonical JSON (sorted keys, stable) — local to keep this module dependency-free. */
281
+ function canonicalJson(value: unknown): string {
282
+ if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null'
283
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`
284
+ const obj = value as Record<string, unknown>
285
+ return `{${Object.keys(obj)
286
+ .sort()
287
+ .map(key => `${JSON.stringify(key)}:${canonicalJson(obj[key])}`)
288
+ .join(',')}}`
289
+ }
290
+
291
+ export function computeDisclosureDigest(disclosure: CommissionDisclosure): string {
292
+ return createHash('sha256')
293
+ .update(canonicalJson({ schema: disclosure.schema, certainty: disclosure.certainty, benefits: disclosure.benefits, source: disclosure.source }))
294
+ .digest('hex')
295
+ }
296
+
297
+ /** Confirmation boundary: no disclosure object at all is a hard reject — a card
298
+ * may not be confirmed without explicit commission disclosure (§10). */
299
+ export function disclosureForConfirmation(v: unknown): { ok: true; disclosure: CommissionDisclosure; digest: string } | { ok: false; violation: CommissionViolationCode } {
300
+ const checked = validateCommissionDisclosure(v)
301
+ if (!checked.ok) return { ok: false, violation: checked.violations[0] }
302
+ const disclosure = v as CommissionDisclosure
303
+ return { ok: true, disclosure, digest: computeDisclosureDigest(disclosure) }
304
+ }
305
+
306
+ /** The request-fingerprint field carrying the disclosure digest (design §4). */
307
+ export const COMMISSION_DISCLOSURE_FINGERPRINT_FIELD = 'commission_disclosure' as const
308
+
309
+ export function bindDisclosureToFingerprint(
310
+ fingerprint: Record<string, unknown>,
311
+ disclosure: CommissionDisclosure,
312
+ ): { ok: true; fingerprint: Record<string, unknown>; digest: string } | { ok: false; violation: Extract<CommissionViolationCode, 'disclosure_digest_mismatch'> } {
313
+ const digest = computeDisclosureDigest(disclosure)
314
+ const existing = fingerprint[COMMISSION_DISCLOSURE_FINGERPRINT_FIELD]
315
+ if (typeof existing === 'string' && existing !== digest) {
316
+ // Disclosure caliber changed after confirmation: the old receipt is invalid;
317
+ // re-confirmation against the new disclosure is required.
318
+ return { ok: false, violation: 'disclosure_digest_mismatch' }
319
+ }
320
+ return { ok: true, fingerprint: { ...fingerprint, [COMMISSION_DISCLOSURE_FINGERPRINT_FIELD]: digest }, digest }
321
+ }
322
+
323
+ // ---- 4. User copy: ledger tokens and copy tokens stay consistent -----------------
324
+
325
+ export type AftercareCopyLocale = 'en' | 'zh-CN'
326
+
327
+ /** Arrival claims. If copy states these while the outcome is not an evidenced
328
+ * `refunded`, the wording contradicts the ledger-side tokens. */
329
+ const ARRIVAL_TOKENS: Record<AftercareCopyLocale, readonly string[]> = {
330
+ en: ['refunded', 'refund received', 'refund has arrived'],
331
+ 'zh-CN': ['已退款', '退款已到账', '退款到账'],
332
+ }
333
+ const CANCEL_DONE_TOKENS: Record<AftercareCopyLocale, readonly string[]> = {
334
+ en: ['cancelled'],
335
+ 'zh-CN': ['已取消'],
336
+ }
337
+ const BENEFIT_MARKERS: Record<AftercareCopyLocale, readonly string[]> = {
338
+ en: ['commission', 'rebate', 'sponsorship', 'preferred placement'],
339
+ 'zh-CN': ['佣金', '返利', '赞助', '优先位'],
340
+ }
341
+ /** A definite benefit claim (only allowed when certainty='known_benefit'). */
342
+ const DEFINITE_BENEFIT_TOKENS: Record<AftercareCopyLocale, readonly string[]> = {
343
+ en: ['paid by', '% of total'],
344
+ 'zh-CN': ['支付给', '%'],
345
+ }
346
+
347
+ const ZH_BENEFIT_KIND: Record<CommissionBenefitKind, string> = {
348
+ commission: '佣金',
349
+ rebate: '返利',
350
+ sponsorship: '赞助',
351
+ preferred_placement: '优先位',
352
+ }
353
+
354
+ export const COPY_VIOLATION_CODES = [
355
+ 'copy_claimed_cancelled_without_supplier_evidence',
356
+ 'copy_claimed_refund_arrival_without_authority',
357
+ 'copy_refund_wording_while_pending_or_unknown',
358
+ 'copy_refund_wording_on_local_compensation_only',
359
+ 'commission_disclosure_missing_from_summary',
360
+ 'commission_status_contradicts_summary',
361
+ ] as const
362
+ export type CopyViolationCode = (typeof COPY_VIOLATION_CODES)[number]
363
+
364
+ export function localLedgerCopy(status: LocalLedgerStatus, locale: AftercareCopyLocale): string {
365
+ if (locale === 'zh-CN') {
366
+ if (status === 'pending') return '本地建议待确认;未下单。'
367
+ if (status === 'confirmed') return '本地已确认授权;供应商结果待回执。'
368
+ return '本地账面已补偿;这只是账务动作,退款状态以退款结果为准。'
369
+ }
370
+ if (status === 'pending') return 'Local suggestion pending confirmation; no order placed.'
371
+ if (status === 'confirmed') return 'Confirmed and authorized locally; supplier outcome pending receipt.'
372
+ return 'Compensated locally; this is a ledger action only — refund state is tracked by the refund outcome.'
373
+ }
374
+
375
+ function basisLabel(basis: CommissionBenefit['basis'], locale: AftercareCopyLocale): string {
376
+ if (basis.type === 'percent_of_total') return locale === 'zh-CN' ? `总价 ${basis.percent}%` : `${basis.percent}% of total`
377
+ if (basis.type === 'per_night') return locale === 'zh-CN' ? `每晚 ${basis.amount} ${basis.currency}` : `${basis.amount} ${basis.currency} per night`
378
+ return locale === 'zh-CN' ? `固定 ${basis.amount} ${basis.currency}` : `${basis.amount} ${basis.currency} fixed`
379
+ }
380
+
381
+ function disclosureLines(disclosure: CommissionDisclosure, locale: AftercareCopyLocale): string[] {
382
+ const zh = locale === 'zh-CN'
383
+ if (disclosure.certainty === 'unknown') return [zh ? '佣金/返利/赞助披露:未知(不默认没有)。' : 'Commission/sponsorship disclosure: unknown (not assumed none).']
384
+ if (disclosure.certainty === 'known_none') return [zh ? '佣金/返利/赞助披露:无(依据合同规则记录)。' : 'Commission/sponsorship disclosure: none (source: contract rule).']
385
+ return disclosure.benefits.map(b =>
386
+ zh
387
+ ? `${ZH_BENEFIT_KIND[b.kind]}:由 ${b.paidBy} 支付给 ${b.paidTo},口径 ${basisLabel(b.basis, locale)}。`
388
+ : `${b.kind.replaceAll('_', ' ')}: paid by ${b.paidBy} to ${b.paidTo} — ${basisLabel(b.basis, locale)}.`,
389
+ )
390
+ }
391
+
392
+ export function renderAftercareCopy(
393
+ cancel: CancellationOutcome,
394
+ refund: RefundOutcome,
395
+ ledgerStatus: LocalLedgerStatus,
396
+ disclosure: CommissionDisclosure | undefined,
397
+ locale: AftercareCopyLocale,
398
+ ): string {
399
+ const zh = locale === 'zh-CN'
400
+ const lines: string[] = [localLedgerCopy(ledgerStatus, locale)]
401
+ if (cancel.supplierCancellationConfirmed !== undefined) {
402
+ lines.push(zh ? '供应商回执确认已取消(证据摘要已留存)。' : 'Cancelled per supplier receipt (evidence digest on file).')
403
+ } else if (cancel.status === 'not_requested') {
404
+ lines.push(zh ? '未申请取消。' : 'No cancellation requested.')
405
+ } else if (cancel.status === 'cancel_submitted') {
406
+ lines.push(zh ? '已提交取消申请;等待供应商确认。' : 'Cancellation requested/submitted; awaiting supplier confirmation.')
407
+ } else if (cancel.status === 'cancel_failed') {
408
+ lines.push(zh ? '取消失败。' : 'Cancellation failed.')
409
+ } else {
410
+ lines.push(zh ? '取消结果未知;对账中。' : 'Cancellation outcome unknown; reconciling.')
411
+ }
412
+ if (refund.status === 'not_applicable') {
413
+ lines.push(zh ? '不涉及退款。' : 'No refund involved.')
414
+ } else if (refund.status === 'refund_pending') {
415
+ lines.push(zh ? '退款处理中;尚未到账。' : 'Refund pending; not yet arrived.')
416
+ } else if (refund.status === 'refund_failed') {
417
+ lines.push(zh ? '退款失败;未到账。' : 'Refund failed; the refund did not arrive.')
418
+ } else if (refund.status === 'refund_unknown') {
419
+ lines.push(zh ? '退款结果未知;对账中。' : 'Refund outcome unknown; reconciling.')
420
+ } else {
421
+ lines.push(
422
+ zh
423
+ ? `退款已到账:${refund.customerRefund?.amount} ${refund.customerRefund?.currency}(依据 ${refund.evidence?.kind})。`
424
+ : `Refund received: ${refund.customerRefund?.amount} ${refund.customerRefund?.currency} per ${refund.evidence?.kind}.`,
425
+ )
426
+ }
427
+ if (refund.supplierServiceFee !== undefined) {
428
+ lines.push(
429
+ zh
430
+ ? `供应商取消手续费(供应商收取,不是退款金额):${refund.supplierServiceFee.amount} ${refund.supplierServiceFee.currency}。`
431
+ : `Supplier cancellation service fee (charged by supplier, not the refund): ${refund.supplierServiceFee.amount} ${refund.supplierServiceFee.currency}.`,
432
+ )
433
+ }
434
+ if (disclosure !== undefined) lines.push(...disclosureLines(disclosure, locale))
435
+ return lines.join('\n')
436
+ }
437
+
438
+ export interface CopyCheckState {
439
+ readonly cancel: CancellationOutcome
440
+ readonly refund: RefundOutcome
441
+ readonly ledgerStatus: LocalLedgerStatus
442
+ readonly disclosure: CommissionDisclosure | undefined
443
+ readonly locale: AftercareCopyLocale
444
+ }
445
+
446
+ /** Mechanical token gate: copy shown to the user must not claim states the
447
+ * outcome objects (and the ledger mirror) do not carry, and must not hide the
448
+ * commission disclosure behind a total price. This is a regression anchor for
449
+ * generated/hand-written/LLM copy — not an NLU claim. */
450
+ export function copyTokenViolations(text: string, state: CopyCheckState): CopyViolationCode[] {
451
+ const violations: CopyViolationCode[] = []
452
+ const zh = state.locale === 'zh-CN'
453
+ const hay = zh ? text : text.toLowerCase()
454
+ const has = (tokens: readonly string[]): boolean => tokens.some(t => hay.includes(t))
455
+ const arrival = ARRIVAL_TOKENS[state.locale]
456
+ const cancelDone = CANCEL_DONE_TOKENS[state.locale]
457
+
458
+ if (state.cancel.supplierCancellationConfirmed === undefined && has(cancelDone)) {
459
+ violations.push('copy_claimed_cancelled_without_supplier_evidence')
460
+ }
461
+ if (state.refund.status !== 'refunded' && has(arrival)) {
462
+ violations.push('copy_claimed_refund_arrival_without_authority')
463
+ if (state.refund.status === 'refund_pending' || state.refund.status === 'refund_unknown') {
464
+ violations.push('copy_refund_wording_while_pending_or_unknown')
465
+ }
466
+ }
467
+ if (state.ledgerStatus === 'compensated' && state.refund.status === 'not_applicable' && has(arrival)) {
468
+ violations.push('copy_refund_wording_on_local_compensation_only')
469
+ }
470
+ const d = state.disclosure
471
+ if (d !== undefined) {
472
+ if (d.certainty === 'known_benefit') {
473
+ if (!has(BENEFIT_MARKERS[state.locale])) violations.push('commission_disclosure_missing_from_summary')
474
+ } else {
475
+ const required =
476
+ d.certainty === 'unknown'
477
+ ? zh
478
+ ? hay.includes('佣金') && hay.includes('未知')
479
+ : hay.includes('commission') && hay.includes('unknown')
480
+ : zh
481
+ ? hay.includes('无(依据')
482
+ : hay.includes('none')
483
+ if (!required) violations.push('commission_disclosure_missing_from_summary')
484
+ if (has(DEFINITE_BENEFIT_TOKENS[state.locale])) violations.push('commission_status_contradicts_summary')
485
+ }
486
+ }
487
+ return violations
488
+ }