@wowok/agent-mcp 3.1.0 → 3.1.3

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 (337) hide show
  1. package/dist/config/runtime.js +1 -1
  2. package/dist/customer/index.d.ts +3 -9
  3. package/dist/customer/index.js +1 -1
  4. package/dist/customer/industry-risks.d.ts +3 -17
  5. package/dist/customer/industry-risks.js +1 -1
  6. package/dist/customer/types.d.ts +1 -165
  7. package/dist/customer/types.js +1 -1
  8. package/dist/customer/user-preferences.d.ts +0 -49
  9. package/dist/customer/user-preferences.js +1 -1
  10. package/dist/evaluation/arbitration-game.js +1 -1
  11. package/dist/evaluation/architecture.spec.d.ts +1 -0
  12. package/dist/evaluation/architecture.spec.js +1 -0
  13. package/dist/evaluation/builtins/graph-service.d.ts +16 -0
  14. package/dist/evaluation/builtins/graph-service.js +1 -0
  15. package/dist/evaluation/builtins/graph-service.spec.d.ts +1 -0
  16. package/dist/evaluation/builtins/graph-service.spec.js +1 -0
  17. package/dist/evaluation/builtins/index.d.ts +1 -1
  18. package/dist/evaluation/builtins/index.js +1 -1
  19. package/dist/evaluation/builtins/purity.spec.d.ts +1 -0
  20. package/dist/evaluation/builtins/purity.spec.js +1 -0
  21. package/dist/evaluation/engine.js +1 -1
  22. package/dist/evaluation/facets/catalog.d.ts +19 -0
  23. package/dist/evaluation/facets/catalog.js +1 -0
  24. package/dist/evaluation/guard-scan.d.ts +10 -0
  25. package/dist/evaluation/guard-scan.js +1 -0
  26. package/dist/evaluation/location-match.js +1 -1
  27. package/dist/evaluation/standards.d.ts +31 -0
  28. package/dist/evaluation/standards.js +1 -0
  29. package/dist/evaluation/standards.spec.d.ts +1 -0
  30. package/dist/evaluation/standards.spec.js +1 -0
  31. package/dist/evaluation/types.d.ts +9 -0
  32. package/dist/experience/realtime-feedback.js +1 -1
  33. package/dist/extensions/index.d.ts +1 -1
  34. package/dist/extensions/index.js +1 -1
  35. package/dist/extensions/industry-layers.d.ts +6 -5
  36. package/dist/extensions/industry-layers.js +1 -1
  37. package/dist/extensions/industry-pack.js +1 -1
  38. package/dist/goal/GoalClassifier.js +1 -1
  39. package/dist/graph/onchain/analyze.d.ts +16 -3
  40. package/dist/graph/onchain/analyze.js +1 -1
  41. package/dist/graph/onchain/analyze.spec.js +1 -1
  42. package/dist/graph/onchain/dataplane.d.ts +1 -1
  43. package/dist/graph/onchain/dataplane.js +1 -1
  44. package/dist/graph/onchain/edge-batch.spec.d.ts +1 -0
  45. package/dist/graph/onchain/edge-batch.spec.js +1 -0
  46. package/dist/graph/onchain/edge-schema.d.ts +11 -3
  47. package/dist/graph/onchain/edge-schema.js +1 -1
  48. package/dist/graph/onchain/entity-profile.spec.d.ts +1 -0
  49. package/dist/graph/onchain/entity-profile.spec.js +1 -0
  50. package/dist/graph/onchain/event-history.spec.d.ts +1 -0
  51. package/dist/graph/onchain/event-history.spec.js +1 -0
  52. package/dist/graph/onchain/expand.js +1 -1
  53. package/dist/graph/onchain/extract-deep.spec.d.ts +1 -0
  54. package/dist/graph/onchain/extract-deep.spec.js +1 -0
  55. package/dist/graph/onchain/extract.d.ts +11 -3
  56. package/dist/graph/onchain/extract.js +1 -1
  57. package/dist/graph/onchain/facet-projection.d.ts +99 -0
  58. package/dist/graph/onchain/facet-projection.js +1 -0
  59. package/dist/graph/onchain/facet-projection.spec.d.ts +1 -0
  60. package/dist/graph/onchain/facet-projection.spec.js +1 -0
  61. package/dist/graph/onchain/facts.d.ts +103 -0
  62. package/dist/graph/onchain/facts.js +1 -0
  63. package/dist/graph/onchain/facts.spec.d.ts +1 -0
  64. package/dist/graph/onchain/facts.spec.js +1 -0
  65. package/dist/graph/onchain/field-manifest.d.ts +29 -0
  66. package/dist/graph/onchain/field-manifest.js +1 -0
  67. package/dist/graph/onchain/field-manifest.spec.d.ts +1 -0
  68. package/dist/graph/onchain/field-manifest.spec.js +1 -0
  69. package/dist/graph/onchain/fixtures.d.ts +80 -0
  70. package/dist/graph/onchain/fixtures.js +1 -0
  71. package/dist/graph/onchain/fixtures.spec.d.ts +1 -0
  72. package/dist/graph/onchain/fixtures.spec.js +1 -0
  73. package/dist/graph/onchain/index.d.ts +8 -2
  74. package/dist/graph/onchain/index.js +1 -1
  75. package/dist/graph/onchain/interest.js +1 -1
  76. package/dist/graph/onchain/label-lint.spec.d.ts +1 -0
  77. package/dist/graph/onchain/label-lint.spec.js +1 -0
  78. package/dist/graph/onchain/names.d.ts +23 -0
  79. package/dist/graph/onchain/names.js +1 -0
  80. package/dist/graph/onchain/names.spec.d.ts +1 -0
  81. package/dist/graph/onchain/names.spec.js +1 -0
  82. package/dist/graph/onchain/onchain.spec.js +1 -1
  83. package/dist/graph/onchain/proposal-graph.d.ts +11 -0
  84. package/dist/graph/onchain/proposal-graph.js +1 -0
  85. package/dist/graph/onchain/proposal-graph.spec.d.ts +1 -0
  86. package/dist/graph/onchain/proposal-graph.spec.js +1 -0
  87. package/dist/graph/onchain/sdk-batch.d.ts +5 -1
  88. package/dist/graph/onchain/sdk-batch.js +1 -1
  89. package/dist/graph/onchain/sdk-dataplane.js +1 -1
  90. package/dist/graph/onchain/strategy.d.ts +16 -0
  91. package/dist/graph/onchain/strategy.js +1 -1
  92. package/dist/graph/onchain/strategy.spec.js +1 -1
  93. package/dist/graph/onchain/table-ledger.spec.d.ts +1 -0
  94. package/dist/graph/onchain/table-ledger.spec.js +1 -0
  95. package/dist/graph/onchain/types.d.ts +51 -11
  96. package/dist/graph/onchain/viewport.d.ts +1 -0
  97. package/dist/graph/onchain/viewport.js +1 -1
  98. package/dist/harness/index.d.ts +1 -5
  99. package/dist/harness/index.js +1 -1
  100. package/dist/harness/verify.d.ts +6 -1
  101. package/dist/harness/verify.js +1 -1
  102. package/dist/index.js +1 -1
  103. package/dist/knowledge/allocation-ledger.d.ts +2 -0
  104. package/dist/knowledge/allocation-ledger.js +1 -1
  105. package/dist/knowledge/allocation-puzzle.js +1 -1
  106. package/dist/knowledge/allocation-risk.d.ts +2 -3
  107. package/dist/knowledge/allocation-risk.js +1 -1
  108. package/dist/knowledge/arb-risk.d.ts +0 -1
  109. package/dist/knowledge/arb-risk.js +1 -1
  110. package/dist/knowledge/arbitration-risk.d.ts +0 -2
  111. package/dist/knowledge/arbitration-risk.js +1 -1
  112. package/dist/knowledge/baselines/evaluation-baselines.json +79 -0
  113. package/dist/knowledge/baselines/guard-lint-baseline.spec.d.ts +1 -0
  114. package/dist/knowledge/baselines/guard-lint-baseline.spec.js +1 -0
  115. package/dist/knowledge/baselines/risk-baselines.spec.d.ts +1 -0
  116. package/dist/knowledge/baselines/risk-baselines.spec.js +1 -0
  117. package/dist/knowledge/baselines/risk-cases.d.ts +8 -0
  118. package/dist/knowledge/baselines/risk-cases.js +1 -0
  119. package/dist/knowledge/bridge-risk.d.ts +0 -1
  120. package/dist/knowledge/bridge-risk.js +1 -1
  121. package/dist/knowledge/contact-risk.d.ts +0 -1
  122. package/dist/knowledge/contact-risk.js +1 -1
  123. package/dist/knowledge/contract-invariants.d.ts +1 -0
  124. package/dist/knowledge/contract-invariants.js +1 -1
  125. package/dist/knowledge/demand-risk.d.ts +0 -1
  126. package/dist/knowledge/demand-risk.js +1 -1
  127. package/dist/knowledge/getting-started.js +1 -1
  128. package/dist/knowledge/guard-design-patterns.js +1 -1
  129. package/dist/knowledge/guard-eval.d.ts +15 -0
  130. package/dist/knowledge/guard-eval.js +1 -0
  131. package/dist/knowledge/guard-eval.spec.d.ts +1 -0
  132. package/dist/knowledge/guard-eval.spec.js +1 -0
  133. package/dist/knowledge/guard-field-cognition.d.ts +48 -0
  134. package/dist/knowledge/guard-field-cognition.js +1 -0
  135. package/dist/knowledge/guard-lint.d.ts +1 -1
  136. package/dist/knowledge/guard-lint.js +1 -1
  137. package/dist/knowledge/guard-risk.d.ts +4 -19
  138. package/dist/knowledge/guard-risk.js +1 -1
  139. package/dist/knowledge/index.d.ts +42 -43
  140. package/dist/knowledge/index.js +1 -1
  141. package/dist/knowledge/industry-registry.js +1 -1
  142. package/dist/knowledge/industry-rule-node.d.ts +7 -0
  143. package/dist/knowledge/industry-rule-node.js +1 -0
  144. package/dist/knowledge/industry-strategy.js +1 -1
  145. package/dist/knowledge/jsonrpc-enum.js +1 -1
  146. package/dist/knowledge/machine-risk.d.ts +0 -6
  147. package/dist/knowledge/machine-risk.js +1 -1
  148. package/dist/knowledge/order-risk.d.ts +1 -9
  149. package/dist/knowledge/order-risk.js +1 -1
  150. package/dist/knowledge/payment-risk.d.ts +0 -1
  151. package/dist/knowledge/payment-risk.js +1 -1
  152. package/dist/knowledge/permission-risk.d.ts +0 -3
  153. package/dist/knowledge/permission-risk.js +1 -1
  154. package/dist/knowledge/personal-risk.d.ts +0 -1
  155. package/dist/knowledge/personal-risk.js +1 -1
  156. package/dist/knowledge/progress-risk.d.ts +0 -2
  157. package/dist/knowledge/progress-risk.js +1 -1
  158. package/dist/knowledge/proof-risk.d.ts +0 -1
  159. package/dist/knowledge/proof-risk.js +1 -1
  160. package/dist/knowledge/puzzle-projections.d.ts +11 -0
  161. package/dist/knowledge/puzzle-projections.js +1 -0
  162. package/dist/knowledge/recipient-constraint.d.ts +6 -1
  163. package/dist/knowledge/recipient-constraint.js +1 -1
  164. package/dist/knowledge/registrar-risk.d.ts +0 -1
  165. package/dist/knowledge/registrar-risk.js +1 -1
  166. package/dist/knowledge/repository-risk.d.ts +0 -1
  167. package/dist/knowledge/repository-risk.js +1 -1
  168. package/dist/knowledge/resource-risk.d.ts +0 -1
  169. package/dist/knowledge/resource-risk.js +1 -1
  170. package/dist/knowledge/reward-risk.d.ts +1 -5
  171. package/dist/knowledge/reward-risk.js +1 -1
  172. package/dist/knowledge/rule-node-analyzers.d.ts +43 -0
  173. package/dist/knowledge/rule-node-analyzers.js +1 -0
  174. package/dist/knowledge/rule-node-analyzers.spec.d.ts +1 -0
  175. package/dist/knowledge/rule-node-analyzers.spec.js +1 -0
  176. package/dist/knowledge/rule-outcome.d.ts +5 -0
  177. package/dist/knowledge/rule-outcome.js +1 -0
  178. package/dist/knowledge/safety-rules.js +1 -1
  179. package/dist/knowledge/scenario-topology.js +1 -1
  180. package/dist/knowledge/service-allocator-audit-node.d.ts +3 -0
  181. package/dist/knowledge/service-allocator-audit-node.js +1 -0
  182. package/dist/knowledge/service-risk-node.js +1 -1
  183. package/dist/knowledge/service-risk.d.ts +0 -3
  184. package/dist/knowledge/service-risk.js +1 -1
  185. package/dist/knowledge/template-registry.js +1 -1
  186. package/dist/knowledge/tools-reference.js +1 -1
  187. package/dist/knowledge/treasury-risk.d.ts +2 -3
  188. package/dist/knowledge/treasury-risk.js +1 -1
  189. package/dist/knowledge/util-risk.d.ts +0 -1
  190. package/dist/knowledge/util-risk.js +1 -1
  191. package/dist/knowledge/workflow-guidance.d.ts +2 -0
  192. package/dist/knowledge/workflow-guidance.js +1 -1
  193. package/dist/monitor/MonitorLoop.js +1 -1
  194. package/dist/persona/bridge.js +1 -1
  195. package/dist/persona/facet-profile.d.ts +33 -0
  196. package/dist/persona/facet-profile.js +1 -0
  197. package/dist/persona/model.d.ts +2 -1
  198. package/dist/persona/model.js +1 -1
  199. package/dist/persona/strategy-intent.js +1 -1
  200. package/dist/persona/topology-focus.d.ts +2 -2
  201. package/dist/persona/topology-focus.js +1 -1
  202. package/dist/persona/types.d.ts +12 -0
  203. package/dist/playbooks/service-build/business-puzzle.js +1 -1
  204. package/dist/playbooks/service-build/facet-money.d.ts +22 -0
  205. package/dist/playbooks/service-build/facet-money.js +1 -0
  206. package/dist/playbooks/service-build/facet-money.spec.d.ts +1 -0
  207. package/dist/playbooks/service-build/facet-money.spec.js +1 -0
  208. package/dist/playbooks/service-build/intent-analyzer.js +1 -1
  209. package/dist/playbooks/service-build/machine-panorama.d.ts +3 -0
  210. package/dist/playbooks/service-build/machine-panorama.js +1 -1
  211. package/dist/playbooks/service-build/object-panorama.d.ts +27 -27
  212. package/dist/playbooks/service-build/object-panorama.js +1 -1
  213. package/dist/playbooks/service-build/pipeline-actions.d.ts +2 -2
  214. package/dist/playbooks/service-build/pipeline-actions.js +1 -1
  215. package/dist/playbooks/service-build/risk-aggregator.d.ts +2 -1
  216. package/dist/playbooks/service-build/risk-aggregator.js +1 -1
  217. package/dist/playbooks/service-build/service-panorama.d.ts +4 -9
  218. package/dist/playbooks/service-build/service-panorama.js +1 -1
  219. package/dist/playbooks/service-build/topology-evaluation.spec.d.ts +1 -0
  220. package/dist/playbooks/service-build/topology-evaluation.spec.js +1 -0
  221. package/dist/playbooks/service-build/topology-query.d.ts +13 -2
  222. package/dist/playbooks/service-build/topology-query.js +1 -1
  223. package/dist/review/arb.d.ts +0 -2
  224. package/dist/review/arb.js +1 -1
  225. package/dist/review/order.d.ts +0 -1
  226. package/dist/review/order.js +1 -1
  227. package/dist/role/profiles.js +1 -1
  228. package/dist/rules.d.ts +1 -2
  229. package/dist/rules.js +1 -1
  230. package/dist/safety/confirm-gate.js +1 -1
  231. package/dist/safety/preview.js +1 -1
  232. package/dist/schema/call/base.d.ts +3372 -668
  233. package/dist/schema/call/base.js +1 -1
  234. package/dist/schema/call/handler.js +1 -1
  235. package/dist/schema/call/receipt.d.ts +28 -0
  236. package/dist/schema/call/receipt.js +1 -0
  237. package/dist/schema/call/semantic-customer-advice.spec.d.ts +1 -0
  238. package/dist/schema/call/semantic-customer-advice.spec.js +1 -0
  239. package/dist/schema/call/semantic.d.ts +5 -2
  240. package/dist/schema/call/semantic.js +1 -1
  241. package/dist/schema/call/treasury.js +1 -1
  242. package/dist/schema/common/index.js +1 -1
  243. package/dist/schema/evaluation/index.d.ts +289 -211
  244. package/dist/schema/evaluation/index.js +1 -1
  245. package/dist/schema/goal/index.d.ts +1 -1
  246. package/dist/schema/goal/planning.d.ts +2 -2
  247. package/dist/schema/index.d.ts +0 -1
  248. package/dist/schema/index.js +1 -1
  249. package/dist/schema/industry-pack/index.d.ts +1 -1
  250. package/dist/schema/keeper/index.d.ts +1 -1
  251. package/dist/schema/local/index.js +1 -1
  252. package/dist/schema/operations.d.ts +28 -10
  253. package/dist/schema/operations.js +1 -1
  254. package/dist/schema/persona/index.d.ts +24 -24
  255. package/dist/schema/query/bi.d.ts +629 -14
  256. package/dist/schema/query/bi.js +1 -1
  257. package/dist/schema/query/index.d.ts +9 -9
  258. package/dist/schema/query/index.js +1 -1
  259. package/dist/schema/schema-version.js +1 -1
  260. package/dist/schema/workspace/index.d.ts +2 -2
  261. package/dist/schema-query-impl/index.js +1 -1
  262. package/dist/schemas/account_operation.output.json +10 -10
  263. package/dist/schemas/account_operation.schema.json +3 -3
  264. package/dist/schemas/bridge_operation.output.json +10 -10
  265. package/dist/schemas/evaluation_operation.output.json +697 -169
  266. package/dist/schemas/evaluation_operation.schema.json +5 -434
  267. package/dist/schemas/index.json +1 -7
  268. package/dist/schemas/keeper_operation.output.json +10 -10
  269. package/dist/schemas/local_history_operation.output.json +10 -10
  270. package/dist/schemas/local_info_operation.output.json +10 -10
  271. package/dist/schemas/local_mark_operation.output.json +10 -10
  272. package/dist/schemas/messenger_operation.output.json +10 -10
  273. package/dist/schemas/monitor_events.output.json +10 -10
  274. package/dist/schemas/monitor_subscription.output.json +10 -10
  275. package/dist/schemas/onchain_events.output.json +11 -11
  276. package/dist/schemas/onchain_operations.output.json +6369 -3736
  277. package/dist/schemas/onchain_operations.schema.json +48 -48
  278. package/dist/schemas/onchain_operations_allocation.schema.json +5 -5
  279. package/dist/schemas/onchain_operations_arbitration.schema.json +3 -3
  280. package/dist/schemas/onchain_operations_contact.schema.json +2 -2
  281. package/dist/schemas/onchain_operations_demand.schema.json +2 -2
  282. package/dist/schemas/onchain_operations_machine.schema.json +2 -2
  283. package/dist/schemas/onchain_operations_order.schema.json +2 -2
  284. package/dist/schemas/onchain_operations_payment.schema.json +2 -2
  285. package/dist/schemas/onchain_operations_permission.schema.json +2 -2
  286. package/dist/schemas/onchain_operations_progress.schema.json +2 -2
  287. package/dist/schemas/onchain_operations_repository.schema.json +2 -2
  288. package/dist/schemas/onchain_operations_reward.schema.json +6 -6
  289. package/dist/schemas/onchain_operations_service.schema.json +8 -8
  290. package/dist/schemas/onchain_operations_treasury.schema.json +10 -10
  291. package/dist/schemas/onchain_table_data.output.json +78 -84
  292. package/dist/schemas/query_toolkit.output.json +1087 -254
  293. package/dist/schemas/query_toolkit.schema.json +65 -3
  294. package/dist/strategy/collectors.js +1 -1
  295. package/dist/strategy/metrics.js +1 -1
  296. package/dist/task/playbook.js +1 -1
  297. package/dist/tools/handlers/bridge.js +1 -1
  298. package/dist/tools/handlers/config.js +1 -1
  299. package/dist/tools/handlers/dispatch-expectations.d.ts +3 -0
  300. package/dist/tools/handlers/dispatch-expectations.js +1 -0
  301. package/dist/tools/handlers/evaluation.js +1 -1
  302. package/dist/tools/handlers/evaluation.spec.js +1 -1
  303. package/dist/tools/handlers/onchain.js +1 -1
  304. package/dist/tools/handlers/query.js +1 -1
  305. package/dist/tools/index.js +1 -1
  306. package/dist/tools/registry/evaluation.d.ts +2 -0
  307. package/dist/tools/registry/evaluation.js +1 -0
  308. package/dist/tools/registry/monitor.js +1 -1
  309. package/dist/tools/registry/query.js +1 -1
  310. package/dist/tools/shared.d.ts +0 -1
  311. package/dist/tools/shared.js +1 -1
  312. package/dist/tools/wrap.js +1 -1
  313. package/package.json +4 -3
  314. package/dist/customer/customer-advice.d.ts +0 -32
  315. package/dist/customer/customer-advice.js +0 -1
  316. package/dist/customer/info-puzzle.d.ts +0 -146
  317. package/dist/customer/info-puzzle.js +0 -1
  318. package/dist/customer/order-strategy.d.ts +0 -17
  319. package/dist/customer/order-strategy.js +0 -1
  320. package/dist/customer/preorder-compare.d.ts +0 -24
  321. package/dist/customer/preorder-compare.js +0 -1
  322. package/dist/customer/reminder-system.d.ts +0 -42
  323. package/dist/customer/reminder-system.js +0 -1
  324. package/dist/customer/risk-assessment.d.ts +0 -13
  325. package/dist/customer/risk-assessment.js +0 -1
  326. package/dist/evaluation/builtins/service-risk.d.ts +0 -7
  327. package/dist/evaluation/builtins/service-risk.js +0 -1
  328. package/dist/knowledge/trust-metrics.d.ts +0 -66
  329. package/dist/knowledge/trust-metrics.js +0 -1
  330. package/dist/schema/trust/index.d.ts +0 -334
  331. package/dist/schema/trust/index.js +0 -1
  332. package/dist/schemas/trust_score.output.json +0 -847
  333. package/dist/schemas/trust_score.schema.json +0 -364
  334. package/dist/tools/handlers/trust.d.ts +0 -16
  335. package/dist/tools/handlers/trust.js +0 -1
  336. package/dist/tools/registry/trust.d.ts +0 -2
  337. package/dist/tools/registry/trust.js +0 -1
@@ -1 +1 @@
1
- import{readdirSync,readFileSync,existsSync,mkdirSync,writeFileSync}from'node:fs';import{join}from'node:path';import{getWowokIndustryDir}from'@wowok/wowok';import{getIndustryModeRegistry}from'./registry.js';import{BUILTIN_MODES}from'./modes.js';import{registerCategoryMatchRules}from'../evaluation/category-match-rules.js';import{registerIndustryPersonae,unregisterIndustryPersonae}from'../persona/pack-personae.js';import{PERSONA_ROLES,SUPPORTED_INDUSTRIES}from'../persona/types.js';import{UNIVERSAL_TEMPLATE}from'../knowledge/universal-template.js';import{STRATEGY_MANUAL_FILENAME,renderStrategyManual,classifyManualFile}from'../knowledge/strategy-manuals.js';import{registerDisputeRules,registerComplianceRules,registerSupplyRules,registerIndustryRules,registerIndustryPlaybook,registerIndustryRulesToEngine}from'./industry-layers.js';const FORBIDDEN_PRICING_MODES=new Set(UNIVERSAL_TEMPLATE['pricing_redlines']),packRegistry=new Map();export function validatePackManifest(a){const b=[];return(!a||a['pack']!=='industry-pack')&&b['push']('manifest.pack\x20must\x20be\x20\x27industry-pack\x27'),(!a['name']||typeof a['name']!=='string')&&b['push']('manifest.name\x20is\x20required'),(!a['version']||typeof a['version']!=='string')&&b['push']('manifest.version\x20is\x20required'),(!Array['isArray'](a['layers'])||a['layers']['length']===0x0)&&b['push']('manifest.layers\x20must\x20be\x20a\x20non-empty\x20array'),{'valid':b['length']===0x0,'errors':b};}function isMeaningfulMatch(a){if(!a)return![];return(a['hard_constraints']?.['length']??0x0)>0x0||Object['keys'](a['soft_weights']??{})['length']>0x0||(a['pricing_rules']?.['length']??0x0)>0x0||(a['highlight_fields']?.['length']??0x0)>0x0;}function isMeaningfulPersona(a){const b=a['long_term']??{},c=a['current']??{};return(c['strategy']?.['length']??0x0)>0x0||(c['requirements']?.['length']??0x0)>0x0||(c['rules']?.['length']??0x0)>0x0||(c['spec']?.['length']??0x0)>0x0||Object['keys'](c['preferences']??{})['length']>0x0||Object['keys'](b['preferences']??{})['length']>0x0||(b['identity']?.['region']?.['length']??0x0)>0x0||(b['identity']?.['languages']?.['length']??0x0)>0x0;}function isMeaningfulDispute(a){return(a?.['sla_tiers']?.['length']??0x0)>0x0||(a?.['fault_rules']?.['length']??0x0)>0x0;}function isMeaningfulCompliance(a){return!!a?.['prepay_mode']||(a?.['qualification']?.['length']??0x0)>0x0||(a?.['disclosure']?.['length']??0x0)>0x0||a?.['refund_window']?.['days']!==undefined&&!a?.['refund_window']?.['not_applicable'];}function isMeaningfulSupply(a){return(a?.['supplier_qualification']?.['length']??0x0)>0x0||!!a?.['first_order_policy']||a?.['redundancy_required']===!![];}function isMeaningfulRules(a){return(a?.['rules']?.['length']??0x0)>0x0;}function isMeaningfulPlaybook(a){if(!a)return![];const b=a['content']??'',c=b['replace'](/# .*Industry Playbook/g,'')['replace'](/> .*/g,'')['replace'](/## (Experience|Strategy|Personalization)/g,'')['replace'](/- \(Add .*\)/g,'')['trim']();return c['length']>0x0;}export function registerIndustryPack(a,b=![]){const c=[],d=[],e=a['manifest'],f=validatePackManifest(e);c['push'](...f['errors']);if(!f['valid'])return{'ok':![],'errors':c,'registered':d};const g=packRegistry['get'](e['name']),h=g!==undefined&&g['version']!==e['version'],i=h||b;if(e['layers']['includes']('mode')){if(!a['mode'])c['push']('pack\x20\x27'+e['name']+'\x27\x20declares\x20layer\x20\x27mode\x27\x20but\x20mode.json\x20is\x20missing');else{const j=getIndustryModeRegistry();i&&j['hasMode'](a['mode']['name'])&&j['unregisterMode'](a['mode']['name']),!j['registerMode'](a['mode'])?c['push']('mode\x20\x27'+a['mode']['name']+'\x27\x20failed\x20to\x20register\x20(already\x20registered?).\x20'+'Unregister\x20first\x20or\x20upgrade\x20with\x20a\x20different\x20version.'):d['push']('mode');}}if(e['layers']['includes']('match')){if(!a['match'])c['push']('pack\x20\x27'+e['name']+'\x27\x20declares\x20layer\x20\x27match\x27\x20but\x20match.json\x20is\x20missing');else{if(!isMeaningfulMatch(a['match'])){}else{const k=a['match']['pricing_rules']['filter'](l=>FORBIDDEN_PRICING_MODES['has'](l));if(k['length']>0x0)c['push']('match.pricing_rules\x20contains\x20forbidden\x20modes:\x20'+k['join'](',\x20')+'\x20'+'(violates\x20upper-layer\x20pricing\x20red\x20lines,\x20K3\x2015\x20§4.2)');else!registerCategoryMatchRules(a['match'],i)?c['push']('match\x20rules\x20for\x20\x27'+a['match']['category']+'\x27\x20already\x20registered'):d['push']('match');}}}if(e['layers']['includes']('personae')){if(!a['personae']||a['personae']['length']===0x0)c['push']('pack\x20\x27'+e['name']+'\x27\x20declares\x20layer\x20\x27personae\x27\x20but\x20personae\x20are\x20missing');else{const l=a['personae']['filter'](isMeaningfulPersona);if(l['length']===0x0){}else registerIndustryPersonae(e['name'],l),d['push']('personae');}}if(e['layers']['includes']('dispute')){if(!a['dispute'])c['push']('pack\x20\x27'+e['name']+'\x27\x20declares\x20layer\x20\x27dispute\x27\x20but\x20dispute.json\x20is\x20missing');else{if(!isMeaningfulDispute(a['dispute'])){}else!registerDisputeRules(a['dispute'],i)?c['push']('dispute\x20rules\x20for\x20\x27'+a['dispute']['category']+'\x27\x20already\x20registered'):d['push']('dispute');}}if(e['layers']['includes']('compliance')){if(!a['compliance'])c['push']('pack\x20\x27'+e['name']+'\x27\x20declares\x20layer\x20\x27compliance\x27\x20but\x20compliance.json\x20is\x20missing');else{if(!isMeaningfulCompliance(a['compliance'])){}else!registerComplianceRules(a['compliance'],i)?c['push']('compliance\x20rules\x20for\x20\x27'+a['compliance']['category']+'\x27\x20already\x20registered'):d['push']('compliance');}}if(e['layers']['includes']('supply')){if(!a['supply'])c['push']('pack\x20\x27'+e['name']+'\x27\x20declares\x20layer\x20\x27supply\x27\x20but\x20supply.json\x20is\x20missing');else{if(!isMeaningfulSupply(a['supply'])){}else!registerSupplyRules(a['supply'],i)?c['push']('supply\x20rules\x20for\x20\x27'+a['supply']['category']+'\x27\x20already\x20registered'):d['push']('supply');}}if(e['layers']['includes']('rules')){if(!a['rules'])c['push']('pack\x20\x27'+e['name']+'\x27\x20declares\x20layer\x20\x27rules\x27\x20but\x20rules.json\x20is\x20missing');else{if(!isMeaningfulRules(a['rules'])){}else!registerIndustryRules(a['rules'],i)?c['push']('industry\x20rules\x20for\x20\x27'+a['rules']['category']+'\x27\x20already\x20registered'):(d['push']('rules'),registerIndustryRulesToEngine(a['rules']));}}if(e['layers']['includes']('playbook')){if(!a['playbook'])c['push']('pack\x20\x27'+e['name']+'\x27\x20declares\x20layer\x20\x27playbook\x27\x20but\x20playbook.md\x20is\x20missing');else{if(!isMeaningfulPlaybook(a['playbook'])){}else!registerIndustryPlaybook(a['playbook'],i)?c['push']('playbook\x20for\x20\x27'+a['playbook']['category']+'\x27\x20already\x20registered'):d['push']('playbook');}}return c['length']===0x0&&packRegistry['set'](e['name'],{'version':e['version'],'layers':[...e['layers']],'registered_at':Date['now']()}),{'ok':c['length']===0x0,'errors':c,'registered':d};}let builtinModesAsPacksRegistered=![];function ensureBuiltinModesAsPacks(){if(builtinModesAsPacksRegistered)return;builtinModesAsPacksRegistered=!![];for(const a of BUILTIN_MODES){if(packRegistry['has'](a['name']))continue;packRegistry['set'](a['name'],{'version':a['version'],'layers':['mode','match'],'registered_at':Date['now']()});}}export function listRegisteredPacks(){return ensureBuiltinModesAsPacks(),Array['from'](packRegistry['entries']())['map'](([a,b])=>({'name':a,...b}));}export function unregisterIndustryPack(a){const b=new Set(BUILTIN_MODES['map'](c=>c['name']));if(b['has'](a))return![];if(!packRegistry['has'](a))return![];return packRegistry['delete'](a),unregisterIndustryPersonae(a),!![];}export function diffIndustryPack(a){const b=packRegistry['get'](a)??null,c=resolveIndustryPackDir(),d=join(c,a),e=readMergedPackIfPresent(d);let f=null;try{if(e&&e['manifest'])f={'version':e['manifest']['version'],'layers':e['manifest']['layers']??[]};else{const l=join(d,'manifest.json');if(existsSync(l)){const m=JSON['parse'](readFileSync(l,'utf-8'));f={'version':m['version'],'layers':m['layers']??[]};}}}catch{f=null;}const g=b?.['layers']??[],h=f?.['layers']??[],i=h['filter'](n=>!g['includes'](n)),j=g['filter'](n=>!h['includes'](n)),k=!!b&&!!f&&(b['version']!==f['version']||i['length']>0x0||j['length']>0x0);return{'name':a,'registered':b?{...b,'layers':[...b['layers']]}:null,'disk':f,'upgradable':k,'layer_diff':{'added':i,'removed':j}};}export function scanPacks(a){const b=[];if(!existsSync(a))return b;for(const c of readdirSync(a,{'withFileTypes':!![]})){if(!c['isDirectory']())continue;const d=join(a,c['name']);try{const e=loadPackFromDir(d);if(!e)continue;b['push'](registerIndustryPack(e));}catch(f){b['push']({'ok':![],'errors':['failed\x20to\x20load\x20pack\x20\x27'+c['name']+'\x27:\x20'+f['message']],'registered':[]});}}return b;}function loadPackFromDir(a){const b=readMergedPackIfPresent(a),c=join(a,'manifest.json'),d=existsSync(c);if(!b&&!d)return null;if(b){const p=b['manifest'],q={'layout':'merged','manifest':p};if(b['mode'])q['mode']=b['mode'];if(b['match'])q['match']=b['match'];b['personae']&&Array['isArray'](b['personae'])&&(q['personae']=b['personae']);if(b['dispute'])q['dispute']=b['dispute'];if(b['compliance'])q['compliance']=b['compliance'];if(b['supply'])q['supply']=b['supply'];if(b['rules'])q['rules']=b['rules'];const r=join(a,'playbook.md');return existsSync(r)&&(q['playbook']={'category':p['name'],'content':readFileSync(r,'utf-8')}),q;}const e=JSON['parse'](readFileSync(c,'utf-8')),g={'layout':'legacy','manifest':e},h=join(a,'mode.json'),i=join(a,'match.json');existsSync(h)&&(g['mode']=JSON['parse'](readFileSync(h,'utf-8')));existsSync(i)&&(g['match']=JSON['parse'](readFileSync(i,'utf-8')));const j=join(a,'personae');if(existsSync(j)){const s=[];for(const t of readdirSync(j)){if(!t['endsWith']('.json'))continue;s['push'](JSON['parse'](readFileSync(join(j,t),'utf-8')));}if(s['length']>0x0)g['personae']=s;}const k=join(a,'dispute.json');existsSync(k)&&(g['dispute']=JSON['parse'](readFileSync(k,'utf-8')));const l=join(a,'compliance.json');existsSync(l)&&(g['compliance']=JSON['parse'](readFileSync(l,'utf-8')));const m=join(a,'supply.json');existsSync(m)&&(g['supply']=JSON['parse'](readFileSync(m,'utf-8')));const n=join(a,'rules.json');existsSync(n)&&(g['rules']=JSON['parse'](readFileSync(n,'utf-8')));const o=join(a,'playbook.md');return existsSync(o)&&(g['playbook']={'category':e['name'],'content':readFileSync(o,'utf-8')}),g;}export function rescanPack(a){const b=join(resolveIndustryPackDir(),a);try{const c=loadPackFromDir(b);if(!c)return{'ok':![],'errors':['no\x20pack\x20found\x20for\x20\x27'+a+'\x27'],'registered':[]};return registerIndustryPack(c,!![]);}catch(d){return{'ok':![],'errors':['failed\x20to\x20rescan\x20pack\x20\x27'+a+'\x27:\x20'+d['message']],'registered':[]};}}export function resolveIndustryPackDir(){return process['env']['WOWOK_INDUSTRY_DIR']||getWowokIndustryDir();}export function scanDefaultIndustryPacks(){return seedBuiltinIndustryTemplates(),seedBuiltinStrategyManuals(),ensureIndustryReadme(),ensureBuiltinModesAsPacks(),scanPacks(resolveIndustryPackDir());}export function seedBuiltinIndustryTemplates(a=SUPPORTED_INDUSTRIES){const b=[],c=resolveIndustryPackDir();mkdirSync(c,{'recursive':!![]}),ensureIndustryReadme();for(const d of a){const e=join(c,d);if(existsSync(join(e,'manifest.json'))||existsSync(join(e,'pack.json')))continue;const f=scaffoldIndustryPack(d,c);if(f['ok'])b['push'](d);}return b;}export function seedBuiltinStrategyManuals(a=SUPPORTED_INDUSTRIES){const b=[],c=resolveIndustryPackDir();for(const d of a){const e=renderStrategyManual(d);if(!e)continue;const f=join(c,d,STRATEGY_MANUAL_FILENAME);try{const g=join(c,d);if(!existsSync(join(g,'manifest.json'))&&!existsSync(join(g,'pack.json'))){const j=scaffoldIndustryPack(d,c);if(!j['ok']){b['push']({'industry':d,'status':'error','path':f,'detail':j['errors']['join'](';\x20')});continue;}}if(!existsSync(f)){writeFileSync(f,e,'utf-8'),b['push']({'industry':d,'status':'written','path':f});continue;}const h=readFileSync(f,'utf-8'),i=classifyManualFile(d,h);if(i==='outdated')writeFileSync(f,e,'utf-8'),b['push']({'industry':d,'status':'updated','path':f});else{if(i==='current')b['push']({'industry':d,'status':'current','path':f});else i==='user_modified'?b['push']({'industry':d,'status':'skipped_user_modified','path':f,'detail':'strategy-manual.md\x20was\x20edited\x20locally;\x20keeping\x20user\x20content\x20and\x20not\x20upgrading'}):b['push']({'industry':d,'status':'skipped_user_file','path':f,'detail':'strategy-manual.md\x20exists\x20without\x20builtin\x20sentinel;\x20leaving\x20user\x20file\x20untouched'});}}catch(k){b['push']({'industry':d,'status':'error','path':f,'detail':k['message']});}}return b;}export const LAYER_FILE_SECTION={'match.json':'match','dispute.json':'dispute','compliance.json':'compliance','supply.json':'supply','rules.json':'rules','mode.json':'mode'};export const PERSONAE_DIR='personae';function manifestSection(a){return{'pack':'industry-pack','name':a,'display_name':a,'version':'0.1.0','layers':['match','personae','dispute','compliance','supply','rules','playbook']};}function matchSection(a){return{'category':a,'hard_constraints':[],'soft_weights':{},'highlight_fields':[],'calendar_mode':'none','geo_mode':'strict','pricing_rules':[]};}function personaPerRole(a,b){return{'role':a,'industry':b,'long_term':{'identity':{'self_description':b+'\x20'+a},'preferences':{}},'current':{'strategy':[],'requirements':[],'rules':[],'spec':'','preferences':{}}};}function disputeSection(a){return{'category':a,'sla_tiers':[],'fault_rules':[]};}function complianceSection(a){return{'category':a,'prepay_mode':'','qualification':[],'disclosure':[],'refund_window':{'days':0x7,'not_applicable':![]}};}function supplySection(a){return{'category':a,'supplier_qualification':[],'first_order_policy':'','redundancy_required':![]};}function rulesSection(a){return{'category':a,'rules':[]};}export function buildPristineMergedPack(a){const b=PERSONA_ROLES['map'](c=>personaPerRole(c,a));return{'manifest':manifestSection(a),'match':matchSection(a),'personae':b,'dispute':disputeSection(a),'compliance':complianceSection(a),'supply':supplySection(a),'rules':rulesSection(a),'mode':null};}export function industryReadmeContent(){return['#\x20WoWok\x20Industry\x20Packs','','>\x20This\x20folder\x20is\x20the\x20WoWok\x20industry\x20knowledge\x20root.\x20Each\x20sub-folder\x20is\x20one','>\x20industry\x20pack.\x20Pack\x20layers\x20are\x20registered\x20into\x20the\x20runtime\x20registry\x20and','>\x20consumed\x20on\x20demand\x20by\x20the\x20build/recommendation\x20tools\x20(merchant_guide,','>\x20recommend_industry,\x20…);\x20a\x20compact\x20strategy\x20summary\x20for\x20the\x20active','>\x20merchant/supplier\x20lens\x20is\x20injected\x20into\x20every\x20chat\x20turn.','','##\x20Pack\x20structure\x20(unified\x20layout)','','Every\x20pack\x20is\x20exactly\x20two\x20files:','','-\x20**`<pack>/pack.json`**\x20—\x20machine-checkable\x20**settings\x20only**.\x20No\x20comments,','\x20\x20no\x20documentation.\x20One\x20section\x20per\x20layer\x20(see\x20below).','-\x20**`<pack>/playbook.md`**\x20—\x20human\x20strategy,\x20tone\x20and\x20field-tested\x20experience.','\x20\x20Registered\x20on\x20scan\x20and\x20read\x20ON\x20DEMAND\x20via\x20industry_pack_operation','\x20\x20(action=\x27get\x27);\x20it\x20OVERRIDES\x20built-in\x20industry\x20data\x20for\x20this\x20account.','','All\x20field\x20explanations\x20live\x20in\x20THIS\x20file,\x20so\x20pack.json\x20stays\x20small\x20and\x20you','can\x20focus\x20on\x20configuration.\x20The\x20editor\x20also\x20validates\x20JSON\x20on\x20save\x20—\x20a\x20file','that\x20fails\x20to\x20parse\x20(or\x20a\x20pack.json\x20missing\x20its\x20manifest)\x20is\x20blocked.','','##\x20How\x20changes\x20take\x20effect','','1.\x20**Save**\x20in\x20the\x20Editor\x20writes\x20bytes\x20to\x20disk.','2.\x20**Scan**\x20(Industry\x20drawer)\x20re-registers\x20each\x20pack\x20into\x20the\x20runtime\x20AI','\x20\x20\x20registry\x20(and\x20SQLite\x20cache).\x20A\x20save\x20of\x20an\x20industry\x20file\x20already\x20runs','\x20\x20\x20Scan\x20automatically.','3.\x20**Next\x20AI\x20chat\x20turn**\x20the\x20registered\x20layers\x20are\x20available\x20to\x20the','\x20\x20\x20on-demand\x20tools\x20(and\x20the\x20merchant/supplier\x20strategy\x20summary\x20is\x20fresh','\x20\x20\x20in\x20the\x20persona\x20context),\x20so\x20the\x20AI\x20reasons\x20against\x20your\x20edited\x20rules','\x20\x20\x20from\x20that\x20point\x20onward.','','##\x20manifest\x20—\x20pack\x20metadata\x20+\x20layer\x20ENABLE\x20flags','','-\x20`name`:\x20snake_case\x20identifier,\x20must\x20match\x20the\x20folder\x20name.','-\x20`version`:\x20bump\x20after\x20editing\x20content\x20so\x20the\x20registry\x20treats\x20it\x20as\x20an\x20upgrade.','-\x20`display_name`:\x20user-visible\x20label.','-\x20`layers`:\x20which\x20sections\x20are\x20validated\x20and\x20registered\x20on\x20scan.\x20Remove\x20a','\x20\x20layer\x20name\x20to\x20DISABLE\x20it\x20(the\x20section\x20stays\x20in\x20pack.json\x20but\x20is\x20ignored).','','##\x20match\x20—\x20category-match\x20rules','','Decides\x20whether\x20an\x20order/service/account\x20belongs\x20to\x20this\x20industry\x20pack:','-\x20`hard_constraints`:\x20array\x20of\x20REQUIRED\x20predicates;\x20ALL\x20must\x20match\x20before\x20the','\x20\x20pack\x20is\x20considered.\x20Example:','\x20\x20`[{\x20key:\x20\x27order.metadata.service_kind\x27,\x20equals:\x20\x27food_onsite\x27\x20}]`','-\x20`soft_weights`:\x20dict\x20`<heuristic_key:\x20number\x200..1>`;\x20higher\x20=\x20stronger\x20signal.','-\x20`pricing_rules`:\x20pricing\x20modes\x20this\x20industry\x20requires.','-\x20`highlight_fields`:\x20dot-paths\x20surfaced\x20in\x20the\x20UI\x20as\x20important\x20info.','-\x20`geo_mode`:\x20`\x27strict\x27`\x20(region\x20must\x20match)\x20|\x20`\x27none\x27`\x20(ignore\x20region).','-\x20`calendar_mode`:\x20`\x27seasonal\x27`\x20|\x20`\x27weekday\x27`\x20|\x20`\x27none\x27`.','','##\x20personae\x20—\x20per-role\x20AI\x20personas','','One\x20persona\x20per\x20role\x20(`merchant`,\x20`customer`,\x20`supplier`,\x20`collaborator`,','`arbitrator`,\x20`prospect`).\x20The\x20AI\x20uses\x20them\x20to\x20role-play\x20negotiation\x20posture:','-\x20`long_term`:\x20stable\x20properties\x20—\x20`identity.self_description`\x20(free-text\x20bio),','\x20\x20`identity.region/languages`,\x20`preferences`\x20(`<key:\x20string[]>`).','-\x20`current`:\x20per-negotiation\x20posture\x20—\x20`strategy`\x20(moves\x20to\x20make),','\x20\x20`requirements`\x20(non-negotiable\x20demands),\x20`rules`\x20(constraints/axioms),','\x20\x20`spec`\x20(free-form\x20text),\x20`preferences`\x20(per-turn\x20overrides).','','##\x20dispute\x20—\x20SLA\x20tiers\x20+\x20fault\x20assignment','','-\x20`sla_tiers[]`:\x20response/remedy\x20windows\x20per\x20severity\x20level.','\x20\x20Example:\x20`{\x20level:\x20\x27L1\x27,\x20response_hours:\x2024,\x20remedy:\x20\x27reply\x27\x20}`','-\x20`fault_rules[]`:\x20automatic\x20fault\x20attribution\x20—\x20a\x20condition\x20plus\x20the\x20side','\x20\x20that\x20bears\x20fault\x20(`merchant`/`customer`/`supplier`/`operator`/`shared`).','\x20\x20Example:\x20`{\x20when:\x20{\x20evidence_has:\x20[\x27late\x20delivery\x20photo\x27]\x20},\x20assign_to:\x20\x27merchant\x27,\x20weight:\x201.0\x20}`','','##\x20compliance\x20—\x20hard\x20requirements\x20before\x20checkout','','-\x20`prepay_mode`:\x20`\x27\x27`\x20|\x20`\x27full\x27`\x20|\x20`\x27partial\x27`\x20|\x20`\x27deposit\x27`.','-\x20`qualification[]`:\x20licenses/certifications\x20a\x20merchant\x20must\x20hold.','\x20\x20Example:\x20`{\x20label:\x20\x27Food\x20Service\x20License\x27,\x20required:\x20true,\x20region:\x20\x27CN\x27\x20}`','-\x20`disclosure[]`:\x20text\x20the\x20merchant\x20MUST\x20show\x20buyers\x20up-front.','-\x20`refund_window`:\x20`{\x20days:\x20number,\x20not_applicable:\x20boolean,\x20exceptions:\x20[...]\x20}`','','##\x20supply\x20—\x20supply-chain\x20/\x20supplier\x20qualification','','-\x20`supplier_qualification[]`:\x20same\x20shape\x20as\x20compliance\x20qualifications,\x20but','\x20\x20evaluated\x20on\x20the\x20SUPPLIER\x20side\x20(multi-party\x20orders).','-\x20`first_order_policy`:\x20policy\x20string\x20on\x20the\x20first\x20order\x20from\x20a\x20new\x20supplier','\x20\x20(e.g.\x20`\x27sample-only\x27`,\x20`\x27reduced-quantity\x27`).','-\x20`redundancy_required`:\x20true\x20=\x20require\x20≥2\x20eligible\x20suppliers\x20before\x20accepting','\x20\x20an\x20order\x20(mitigates\x20single-sourcing).','','##\x20rules\x20—\x20declarative\x20machine-checked\x20rules','','Each\x20rule\x20is\x20an\x20AST\x20node\x20compiled\x20into\x20the\x20evaluation\x20engine:','`{\x20id:\x20\x27rule_...\x27,\x20when:\x20<bool-condition>,\x20then:\x20\x27reject\x27\x20|\x20\x27warn\x27\x20|\x20\x27flag\x27,\x20message:\x20\x27Text\x27\x20}`','Use\x20`rules`\x20for\x20rules\x20that\x20must\x20be\x20machine-checked;\x20put\x20human\x20strategy\x20in','`playbook.md`.','','##\x20mode\x20—\x20IndustryMode\x20(deep\x20shape)','','Not\x20scaffolded\x20by\x20default.\x20Add\x20it\x20when\x20you\x20need\x20a\x20full\x20driving\x20mode\x20for\x20the','industry,\x20or\x20ask\x20the\x20AI:\x20\x22help\x20me\x20fill\x20mode\x20for\x20<industry>\x22.','','Registered\x20into\x20`IndustryModeRegistry`\x20on\x20scan\x20(manifest\x20must\x20list\x20the','`mode`\x20layer).\x20A\x20pack\x20mode\x20with\x20the\x20same\x20name\x20as\x20a\x20builtin\x20replaces\x20it\x20when','the\x20pack\x20version\x20changes\x20or\x20on\x20a\x20forced\x20rescan.','','###\x20How\x20the\x20mode\x20is\x20consumed','','-\x20**Service\x20build\x20(priors)**:\x20`merchant_guide`\x20resolves\x20the\x20confirmed','\x20\x20industry\x20to\x20a\x20mode\x20(user\x20mode\x20first,\x20then\x20pack\x20mode,\x20then\x20builtin)\x20and','\x20\x20feeds\x20`machine_shape`\x20/\x20`guards`\x20/\x20`allocator`\x20/\x20`key_risk`\x20into\x20the','\x20\x20SemanticObjectGraph\x20build.','-\x20**Evaluation**:\x20the\x20metric\x20+\x20constraint\x20registries\x20score\x20the\x20mode','\x20\x20(risk/benefit\x200-100,\x20hard\x20violations\x20block\x20adoption).\x20Custom\x20metrics\x20and','\x20\x20constraints\x20registered\x20via\x20`industry_pack_operation`\x20participate\x20too.','-\x20**Recommendation**:\x20`recommend_industry`\x20matches\x20trait\x20similarity\x20and,','\x20\x20when\x20a\x20merchant\x20strategy\x20is\x20given,\x20re-ranks\x20by\x20lever\x20alignment\x20(70%','\x20\x20similarity\x20+\x2030%\x20alignment).','','###\x20Field\x20reference','','-\x20**Identity**:\x20`name`\x20(snake_case),\x20`display_name`,\x20`version`\x20(e.g.\x20`v1`),','\x20\x20`source`\x20(`builtin`\x20|\x20`custom`).','-\x20`traits`:\x2010-dimension\x20industry\x20trait\x20vector\x20(logistics,\x20cycle,\x20deposit,','\x20\x20regulatory\x20intensity,\x20...).\x20Drives\x20`recommend_industry`\x20similarity.','-\x20`machine_shape`:\x20Machine\x20node\x20topology\x20—\x20`[{\x20name,\x20role\x20}]`.\x20Node\x20names\x20are','\x20\x20business\x20states.\x20R-M1-11:\x20NEVER\x20model\x20refund/dispute\x20terminals','\x20\x20(`refunded`,\x20`disputed`,\x20`arb_*`)\x20as\x20nodes\x20—\x20disputes\x20flow\x20through','\x20\x20Service.arbitrations\x20independently;\x20route\x20refunds\x20via\x20the\x20Allocator','\x20\x20triggered\x20by\x20business\x20states\x20(`cancelled`,\x20`returned`).','-\x20`guards`:\x20`[{\x20template_id,\x20host,\x20purpose\x20}]`\x20—\x20guard\x20templates\x20to\x20attach.','\x20\x20`host`\x20is\x20one\x20of\x20`service`\x20|\x20`machine`\x20|\x20`reward`\x20|\x20`repository`\x20|','\x20\x20`arbitration`.','-\x20`allocator`:\x20`{\x20recipient,\x20count,\x20mode,\x20description\x20}`\x20—\x20fund\x20split.','\x20\x20`recipient`:\x20`signer`\x20|\x20`entity`;\x20`count`\x20>\x201\x20switches\x20to\x20multi-party','\x20\x20distribution;\x20`mode`:\x20`surplus`\x20|\x20`rate`\x20|\x20`milestone`.','-\x20`risk_checks`\x20/\x20`needs`:\x20buyer-side\x20due-diligence\x20entries\x20surfaced\x20in','\x20\x20prospect\x20evaluation.','-\x20`flywheel`:\x20acquisition\x20flywheel\x20—\x20`rewardStrategy`\x20/\x20`discountStrategy`','\x20\x20/\x20`trustSellingPoints`.\x20A\x20concrete\x20(non-`User-defined`)\x20strategy\x20turns','\x20\x20the\x20`reward`/`discount`\x20levers\x20on\x20for\x20strategy\x20alignment.','-\x20`key_risk`\x20(string)\x20/\x20`build_notes`\x20(string[]):\x20the\x20headline\x20risk\x20and','\x20\x20actionable\x20build\x20guidance\x20shown\x20to\x20the\x20merchant.','-\x20`capabilities_used`:\x20CapabilityCard\x20IDs\x20(e.g.\x20`guard.validate_buy`,','\x20\x20`machine.node_topology`,\x20`allocation.distribute_milestone`).\x20Powers\x20the','\x20\x20`buy_guard`\x20/\x20`machine_design`\x20levers\x20and\x20constraint\x20checks.','-\x20`config_overrides`:\x20per-object\x20field\x20defaults,\x20e.g.','\x20\x20`{\x20service:\x20{\x20engagement_type:\x20\x27milestone\x27\x20},\x20machine:\x20{\x20wip_required:\x20true\x20}\x20}`.','-\x20`config_override_rules`:\x20conditional\x20overrides\x20—','\x20\x20`{\x20object_type,\x20field_path,\x20value\x20|\x20{\x20intent_contains,\x20then_value,\x20else_value\x20}\x20}`.','-\x20`expected_benefits`:\x20`[{\x20metric,\x20expected_value,\x20evidence\x20}]`\x20—\x20what\x20the','\x20\x20mode\x20is\x20supposed\x20to\x20buy\x20you.','-\x20`risk_appetite`:\x20`conservative`\x20|\x20`balanced`\x20|\x20`aggressive`\x20(thresholds','\x20\x20for\x20the\x20risk/benefit\x20verdict).','-\x20`risk_constraints`:\x20`{\x20require_arbitration,\x20require_compensation_fund,','\x20\x20require_wip_evidence,\x20max_single_transaction?,','\x20\x20compensation_fund_coverage_ratio?,\x20other_constraints?\x20}`.\x20Coverage\x20ratio','\x20\x20multiplies\x20max\x20single\x20order\x20to\x20size\x20the\x20compensation\x20fund\x20(retail\x205,','\x20\x20rental\x2010,\x20subscription\x203;\x20default\x205).','-\x20`applicable_conditions`:\x20`{\x20business_scale,\x20min_daily_orders?,','\x20\x20other_conditions?\x20}`\x20—\x20when\x20the\x20mode\x20fits.','-\x20`similar_industries`\x20/\x20`novel_capabilities`:\x20migration\x20hints.','-\x20`disabled_builtin_constraints`:\x20builtin\x20constraint\x20IDs\x20this\x20mode','\x20\x20deliberately\x20opts\x20out\x20of\x20(e.g.\x20retail_d2c\x20skips\x20`require_arbitration`).','\x20\x20Custom\x20constraints\x20are\x20never\x20skipped.','','###\x20Persona\x20integration\x20(strategy\x20→\x20levers)','','The\x20personae\x20section\x27s\x20`current.strategy`\x20statements\x20are\x20bridged\x20into\x20mode','ranking\x20(value\x20intent\x20↔\x20game\x20path\x20unification).\x20Deterministic\x20mapping\x20—','\x22enumerable\x20→\x20MCP,\x20not\x20prompt\x22:','','-\x20`sales_priority`\x20(volume\x20first)\x20→\x20levers\x20`discount`\x20+\x20`reward`','-\x20`profit_priority`\x20(margin\x20first)\x20→\x20levers\x20`discount`\x20+\x20`machine_design`','-\x20`buyer_screening`\x20(qualify\x20buyers)\x20→\x20lever\x20`buy_guard`','-\x20`gross_margin_control`\x20(margin\x20band)\x20→\x20levers\x20`discount`\x20+\x20`machine_design`','','A\x20mode\x20supports\x20a\x20lever\x20when\x20its\x20data\x20says\x20so:\x20`guard.validate_buy`','capability\x20or\x20a\x20buy-guard\x20template\x20enables\x20`buy_guard`;\x20a\x20concrete','flywheel\x20reward/discount\x20strategy\x20enables\x20`reward`/`discount`;\x20a','non-empty\x20`machine_shape`\x20with\x20`machine.node_topology`\x20enables','`machine_design`.\x20Pass\x20strategy\x20text\x20to\x20`recommend_industry`\x20and\x20each','recommendation\x20reports\x20`strategy_alignment`\x20(matched/missing\x20levers).','','##\x20custom-registry.json\x20—\x20global\x20custom\x20metrics\x20/\x20constraints\x20/\x20modes','','Custom\x20metrics,\x20constraints\x20and\x20user\x20modes\x20registered\x20via','`industry_pack_operation`\x20(register_custom_metric\x20/','register_custom_constraint\x20/\x20derive_user_mode\x20/\x20register_user_mode)','persist\x20to\x20THIS\x20root-level\x20file\x20—\x20it\x20is\x20global\x20and\x20applies\x20to\x20every','industry\x20pack.\x20Layout:\x20`metrics`\x20keyed\x20by\x20metric\x20id,\x20`constraints`','keyed\x20by\x20constraint\x20id,\x20`user_modes`\x20keyed\x20by\x20`<owner>:<name>`.\x20The','file\x20is\x20created\x20on\x20first\x20use\x20(seeded\x20from\x20the\x20legacy\x20SQLite\x20cache\x20when','present);\x20hand\x20edits\x20take\x20effect\x20on\x20the\x20next\x20registry\x20call,\x20and','deleting\x20an\x20entry\x20removes\x20it.','','##\x20Reset','','Right-click\x20any\x20file/pack\x20folder\x20in\x20the\x20Industry\x20drawer\x20and\x20choose\x20*Reset*','to\x20restore\x20the\x20pristine\x20template\x20at\x20any\x20time.','']['join']('\x0a');}export function ensureIndustryReadme(){const a=resolveIndustryPackDir();mkdirSync(a,{'recursive':!![]});const b=join(a,'README.md');return writeFileSync(b,industryReadmeContent(),'utf-8'),b;}export function scaffoldIndustryPack(a,b){const c=join(b??resolveIndustryPackDir(),a),d=[],e=[];if(!/^[a-z][a-z0-9_]*$/['test'](a))return{'ok':![],'dir':c,'files':d,'errors':['industry\x20name\x20\x27'+a+'\x27\x20must\x20be\x20lowercase\x20snake_case\x20(a-z,\x200-9,\x20_)']};try{mkdirSync(c,{'recursive':!![]}),ensureIndustryReadme();const f=buildPristineMergedPack(a);return writeFileSync(join(c,'pack.json'),JSON['stringify'](f,null,0x2)+'\x0a'),d['push']('pack.json'),writeFileSync(join(c,'playbook.md'),playbookTemplate(a)),d['push']('playbook.md'),{'ok':!![],'dir':c,'files':d,'errors':e};}catch(g){return{'ok':![],'dir':c,'files':d,'errors':['scaffold\x20failed:\x20'+g['message']]};}}export function readMergedPackIfPresent(a){const b=join(a,'pack.json');if(!existsSync(b))return null;try{const c=readFileSync(b,'utf-8');return JSON['parse'](c);}catch{return null;}}function playbookTemplate(a){return['#\x20'+a+'\x20—\x20Industry\x20Playbook','','>\x20📘\x20This\x20file\x20captures\x20human\x20business\x20intelligence\x20for\x20the\x20`'+a+'`','>\x20industry.\x20Content\x20here\x20is\x20READ\x20BY\x20THE\x20AI\x20AS\x20CONTEXT\x20on\x20every\x20turn,','>\x20and\x20OVERRIDES\x20WoWok\x27s\x20generic\x20built-in\x20industry\x20data/rules\x20for\x20this','>\x20account.\x20The\x20companion\x20`pack.json`\x20file\x20stores\x20machine-checkable','>\x20rules;\x20THIS\x20file\x20stores\x20human\x20strategy,\x20tone,\x20experience,\x20and\x20ethics.','','>\x20💡\x20Hint\x20for\x20the\x20AI:\x20when\x20the\x20user\x20asks\x20a\x20question\x20about\x20\x22how\x20to','>\x20handle\x20'+a+'\x22\x20or\x20\x22what\x20should\x20I\x20do?\x22,\x20check\x20this\x20file\x20first\x20for\x20the','>\x20merchant/customer\x20voice,\x20then\x20fall\x20back\x20to\x20your\x20built-in\x20data.\x20Cite','>\x20section\x20titles\x20in\x20your\x20reply\x20so\x20the\x20user\x20knows\x20where\x20advice\x20comes\x20from.','','##\x20Experience\x20(Field-Tested\x20Rules\x20of\x20Thumb)','','>\x20Write\x20what\x20actually\x20works\x20in\x20this\x20industry\x20—\x20not\x20what\x20textbooks\x20say.','>\x20Short\x20bullet\x20points\x20preferred;\x20the\x20AI\x20reads\x20them\x20as\x20axioms.\x20Include','>\x20specific\x20numbers\x20when\x20you\x20have\x20them.','','-\x20(Example)\x20\x22Catering:\x20if\x20the\x20event\x20starts\x20before\x2010:00,\x20always\x20assume','\x20\x20the\x20customer\x20wants\x20breakfast\x20service\x20too\x20—\x20upsell\x20it\x20proactively.\x22','-\x20(Example)\x20\x22Common\x20pitfall:\x20last-minute\x20menu\x20swaps\x20on\x20Fridays\x20—\x20require','\x20\x20a\x20written\x20change\x20request\x2048\x20h\x20before\x20the\x20event\x20or\x20charge\x20a\x2015%\x20fee.\x22','-\x20(Add\x20more\x20below\x20—\x20delete\x20the\x20examples\x20above\x20when\x20you\x20have\x20real\x20ones.)','','##\x20Strategy\x20(Competitive\x20/\x20Game-Theory)','','>\x20How\x20should\x20each\x20role\x20act\x20in\x20a\x20negotiation\x20/\x20dispute\x20/\x20supplier','>\x20relationship?\x20Think\x20in\x20\x22always\x20/\x20never\x20/\x20depends-on-X\x22\x20rules,\x20and\x20call','>\x20out\x20the\x20trade-offs.','','-\x20Merchant\x20strategy:\x20(Add\x20how\x20a\x20merchant\x20in\x20this\x20industry\x20should\x20act\x20—','\x20\x20price\x20anchoring,\x20which\x20concessions\x20to\x20give\x20early\x20vs\x20late,\x20what\x20to','\x20\x20never\x20concede\x20on,\x20etc.)','-\x20Customer\x20strategy:\x20(Add\x20what\x20a\x20smart\x20customer\x20should\x20push\x20for.)','-\x20Dispute\x20strategy:\x20(When\x20to\x20settle\x20fast\x20vs\x20when\x20to\x20fight\x20for\x20full','\x20\x20evidence\x20+\x20arbitration.\x20Call\x20out\x20the\x20escalation\x20thresholds.)','','##\x20Personalization\x20(Tone,\x20Brand,\x20Ethics,\x20Red\x20Lines)','','-\x20Tone\x20/\x20voice:\x20(Write\x20one\x20sentence\x20describing\x20the\x20exact\x20conversational','\x20\x20voice\x20this\x20account\x20should\x20use\x20—\x20casual,\x20formal,\x20technical,\x20etc.)','-\x20Brand\x20rules:\x20(Logo,\x20link-out\x20style,\x20forbidden\x20terminology,','\x20\x20always-include\x20phrases,\x20etc.)','-\x20Red\x20lines:\x20(Non-negotiable.\x20Example:\x20\x22Never\x20make\x20a\x20refund\x20promise','\x20\x20larger\x20than\x2030%\x20without\x20arbitration\x20evidence.\x22)','-\x20Ethics:\x20(Example:\x20\x22If\x20customer\x20appears\x20intoxicated,\x20refuse\x20service','\x20\x20and\x20refer\x20to\x20supervisor;\x20never\x20take\x20the\x20order\x20for\x20profit.\x22)','','##\x20Playbook\x20Maintenance','','>\x20You\x20don\x27t\x20need\x20to\x20be\x20perfect\x20on\x20day\x20one.\x20After\x20every\x20real\x20deal,\x20add\x20a','>\x20bullet\x20to\x20the\x20above\x20sections\x20with\x20what\x20worked\x20/\x20what\x20failed.\x20Every','>\x20entry\x20improves\x20the\x20AI\x27s\x20future\x20decisions.','','>\x20Right-click\x20the\x20file\x20or\x20this\x20pack\x20folder\x20in\x20the\x20Industry\x20drawer\x20at','>\x20any\x20time\x20and\x20choose\x20\x22Reset\x22\x20to\x20restore\x20this\x20annotated\x20template.','']['join']('\x0a');}export function locatePackAndRemainder(a){const b=a['replace'](/^[\\/]+/,'')['replace'](/[\\/]+$/,'');if(!b)return null;const [c,...d]=b['split'](/[\\/]+/);if(!c)return null;return{'packName':c,'remainder':d['join']('/')};}export function resetIndustryPath(a,b){const c=[],d=[],f=b??resolveIndustryPackDir(),g=locatePackAndRemainder(a),h=a;if(!g)return{'ok':![],'layout':'merged','target':h,'restored_files':[],'errors':['invalid\x20reset\x20path\x20\x27'+a+'\x27']};const {packName:i,remainder:j}=g,k=join(f,i);if(!existsSync(k))return{'ok':![],'layout':'merged','target':h,'restored_files':[],'errors':['pack\x20directory\x20\x27'+i+'\x27\x20does\x20not\x20exist']};if(!/^[a-z][a-z0-9_]*$/['test'](i))return{'ok':![],'layout':'merged','target':h,'restored_files':[],'errors':['pack\x20name\x20\x27'+i+'\x27\x20is\x20not\x20a\x20valid\x20snake_case\x20identifier']};const l=readMergedPackIfPresent(k),n=l?'merged':'legacy';if(j==='')try{mkdirSync(k,{'recursive':!![]});const s=buildPristineMergedPack(i);return writeFileSync(join(k,'pack.json'),JSON['stringify'](s,null,0x2)+'\x0a'),d['push']('pack.json'),writeFileSync(join(k,'playbook.md'),playbookTemplate(i)),d['push']('playbook.md'),{'ok':!![],'layout':'merged','target':h,'restored_files':d,'errors':c};}catch(t){return{'ok':![],'layout':n,'target':h,'restored_files':d,'errors':['pack\x20reset\x20failed:\x20'+t['message']]};}const o=j['split']('/')['slice'](-0x1)[0x0],p=j==='playbook.md',q=j['startsWith'](PERSONAE_DIR+'/')&&o['endsWith']('.json');if(n==='merged'){if(p)try{return writeFileSync(join(k,'playbook.md'),playbookTemplate(i)),d['push']('playbook.md'),{'ok':!![],'layout':n,'target':h,'restored_files':d,'errors':c};}catch(v){return{'ok':![],'layout':n,'target':h,'restored_files':d,'errors':['playbook\x20reset\x20failed:\x20'+v['message']]};}const u=LAYER_FILE_SECTION[j];if(u)try{const w=readMergedPackIfPresent(k)??buildPristineMergedPack(i);switch(u){case'match':w['match']=matchSection(i);break;case'dispute':w['dispute']=disputeSection(i);break;case'compliance':w['compliance']=complianceSection(i);break;case'supply':w['supply']=supplySection(i);break;case'rules':w['rules']=rulesSection(i);break;case'mode':w['mode']=null;break;}return writeFileSync(join(k,'pack.json'),JSON['stringify'](w,null,0x2)+'\x0a'),d['push']('pack.json'),{'ok':!![],'layout':n,'target':h,'restored_files':d,'errors':c};}catch(x){return{'ok':![],'layout':n,'target':h,'restored_files':d,'errors':['section\x20reset\x20failed:\x20'+x['message']]};}if(q){const y=o['replace'](/\.json$/,'');if(!PERSONA_ROLES['includes'](y))return{'ok':![],'layout':n,'target':h,'restored_files':[],'errors':['unknown\x20persona\x20role\x20\x27'+y+'\x27']};try{const z=readMergedPackIfPresent(k)??buildPristineMergedPack(i),A=z['personae']&&Array['isArray'](z['personae'])?[...z['personae']]:[],B=A['findIndex'](D=>D['role']===y),C=personaPerRole(y,i);if(B>=0x0)A[B]=C;else A['push'](C);return z['personae']=A,writeFileSync(join(k,'pack.json'),JSON['stringify'](z,null,0x2)+'\x0a'),d['push']('pack.json'),{'ok':!![],'layout':n,'target':h,'restored_files':d,'errors':c};}catch(D){return{'ok':![],'layout':n,'target':h,'restored_files':d,'errors':['persona\x20reset\x20failed:\x20'+D['message']]};}}if(j==='manifest.json'||j==='manifest')try{const E=readMergedPackIfPresent(k)??buildPristineMergedPack(i);return E['manifest']=manifestSection(i),writeFileSync(join(k,'pack.json'),JSON['stringify'](E,null,0x2)+'\x0a'),d['push']('pack.json'),{'ok':!![],'layout':n,'target':h,'restored_files':d,'errors':c};}catch(F){return{'ok':![],'layout':n,'target':h,'restored_files':d,'errors':['manifest\x20reset\x20failed:\x20'+F['message']]};}return{'ok':![],'layout':n,'target':h,'restored_files':[],'errors':['path\x20\x27'+j+'\x27\x20is\x20not\x20a\x20standard\x20section\x20file\x20of\x20pack\x20\x27'+i+'\x27.\x20Reset\x20is\x20only\x20provided\x20for\x20pack.json\x20standard\x20sections\x20and\x20playbook.md.']};}if(p)try{return writeFileSync(join(k,'playbook.md'),playbookTemplate(i)),d['push']('playbook.md'),{'ok':!![],'layout':n,'target':h,'restored_files':d,'errors':c};}catch(G){return{'ok':![],'layout':n,'target':h,'restored_files':d,'errors':['legacy\x20playbook\x20reset\x20failed:\x20'+G['message']]};}if(j==='manifest.json')try{const H=manifestSection(i);return writeFileSync(join(k,'manifest.json'),JSON['stringify'](H,null,0x2)+'\x0a'),d['push']('manifest.json'),{'ok':!![],'layout':n,'target':h,'restored_files':d,'errors':c};}catch(I){return{'ok':![],'layout':n,'target':h,'restored_files':d,'errors':['legacy\x20manifest\x20reset\x20failed:\x20'+I['message']]};}const r=LAYER_FILE_SECTION[j];if(r)try{let J='';switch(r){case'match':J=JSON['stringify'](matchSection(i),null,0x2)+'\x0a';break;case'dispute':J=JSON['stringify'](disputeSection(i),null,0x2)+'\x0a';break;case'compliance':J=JSON['stringify'](complianceSection(i),null,0x2)+'\x0a';break;case'supply':J=JSON['stringify'](supplySection(i),null,0x2)+'\x0a';break;case'rules':J=JSON['stringify'](rulesSection(i),null,0x2)+'\x0a';break;case'mode':J=JSON['stringify']({},null,0x2)+'\x0a';break;}return writeFileSync(join(k,j),J),d['push'](j),{'ok':!![],'layout':n,'target':h,'restored_files':d,'errors':c};}catch(K){return{'ok':![],'layout':n,'target':h,'restored_files':d,'errors':['legacy\x20section\x20reset\x20failed:\x20'+K['message']]};}if(q){const L=o['replace'](/\.json$/,'');if(!PERSONA_ROLES['includes'](L))return{'ok':![],'layout':n,'target':h,'restored_files':[],'errors':['unknown\x20persona\x20\x27'+L+'\x27']};try{return writeFileSync(join(k,j),JSON['stringify'](personaPerRole(L,i),null,0x2)+'\x0a'),d['push'](j),{'ok':!![],'layout':n,'target':h,'restored_files':d,'errors':c};}catch(M){return{'ok':![],'layout':n,'target':h,'restored_files':d,'errors':['legacy\x20persona\x20reset\x20failed:\x20'+M['message']]};}}return{'ok':![],'layout':n,'target':h,'restored_files':[],'errors':['cannot\x20reset\x20non-standard\x20file\x20\x27'+j+'\x27\x20in\x20legacy\x20layout.\x20Only\x20standard\x20layer\x20files,\x20personae/*.json,\x20manifest.json,\x20and\x20playbook.md\x20can\x20be\x20reset.']};}
1
+ import{readdirSync,readFileSync,existsSync,mkdirSync,writeFileSync}from'node:fs';import{join}from'node:path';import{getWowokIndustryDir}from'@wowok/wowok';import{getIndustryModeRegistry}from'./registry.js';import{BUILTIN_MODES}from'./modes.js';import{registerCategoryMatchRules}from'../evaluation/category-match-rules.js';import{registerIndustryPersonae,unregisterIndustryPersonae}from'../persona/pack-personae.js';import{PERSONA_ROLES,SUPPORTED_INDUSTRIES}from'../persona/types.js';import{UNIVERSAL_TEMPLATE}from'../knowledge/universal-template.js';import{STRATEGY_MANUAL_FILENAME,renderStrategyManual,classifyManualFile}from'../knowledge/strategy-manuals.js';import{registerDisputeRules,registerComplianceRules,registerSupplyRules,registerIndustryRules,registerIndustryPlaybook}from'./industry-layers.js';const FORBIDDEN_PRICING_MODES=new Set(UNIVERSAL_TEMPLATE['pricing_redlines']),packRegistry=new Map();export function validatePackManifest(a){const b=[];return(!a||a['pack']!=='industry-pack')&&b['push']('manifest.pack\x20must\x20be\x20\x27industry-pack\x27'),(!a['name']||typeof a['name']!=='string')&&b['push']('manifest.name\x20is\x20required'),(!a['version']||typeof a['version']!=='string')&&b['push']('manifest.version\x20is\x20required'),(!Array['isArray'](a['layers'])||a['layers']['length']===0x0)&&b['push']('manifest.layers\x20must\x20be\x20a\x20non-empty\x20array'),{'valid':b['length']===0x0,'errors':b};}function isMeaningfulMatch(a){if(!a)return![];return(a['hard_constraints']?.['length']??0x0)>0x0||Object['keys'](a['soft_weights']??{})['length']>0x0||(a['pricing_rules']?.['length']??0x0)>0x0||(a['highlight_fields']?.['length']??0x0)>0x0;}function isMeaningfulPersona(a){const b=a['long_term']??{},c=a['current']??{};return(c['strategy']?.['length']??0x0)>0x0||(c['requirements']?.['length']??0x0)>0x0||(c['rules']?.['length']??0x0)>0x0||(c['spec']?.['length']??0x0)>0x0||Object['keys'](c['preferences']??{})['length']>0x0||Object['keys'](b['preferences']??{})['length']>0x0||(b['identity']?.['region']?.['length']??0x0)>0x0||(b['identity']?.['languages']?.['length']??0x0)>0x0;}function isMeaningfulDispute(a){return(a?.['sla_tiers']?.['length']??0x0)>0x0||(a?.['fault_rules']?.['length']??0x0)>0x0;}function isMeaningfulCompliance(a){return!!a?.['prepay_mode']||(a?.['qualification']?.['length']??0x0)>0x0||(a?.['disclosure']?.['length']??0x0)>0x0||a?.['refund_window']?.['days']!==undefined&&!a?.['refund_window']?.['not_applicable'];}function isMeaningfulSupply(a){return(a?.['supplier_qualification']?.['length']??0x0)>0x0||!!a?.['first_order_policy']||a?.['redundancy_required']===!![];}function isMeaningfulRules(a){return(a?.['rules']?.['length']??0x0)>0x0;}function isMeaningfulPlaybook(a){if(!a)return![];const b=a['content']??'',c=b['replace'](/# .*Industry Playbook/g,'')['replace'](/> .*/g,'')['replace'](/## (Experience|Strategy|Personalization)/g,'')['replace'](/- \(Add .*\)/g,'')['trim']();return c['length']>0x0;}export function registerIndustryPack(a,b=![]){const c=[],d=[],e=a['manifest'],f=validatePackManifest(e);c['push'](...f['errors']);if(!f['valid'])return{'ok':![],'errors':c,'registered':d};const g=packRegistry['get'](e['name']),h=g!==undefined&&g['version']!==e['version'],i=h||b;if(e['layers']['includes']('mode')){if(!a['mode'])c['push']('pack\x20\x27'+e['name']+'\x27\x20declares\x20layer\x20\x27mode\x27\x20but\x20mode.json\x20is\x20missing');else{const j=getIndustryModeRegistry();i&&j['hasMode'](a['mode']['name'])&&j['unregisterMode'](a['mode']['name']),!j['registerMode'](a['mode'])?c['push']('mode\x20\x27'+a['mode']['name']+'\x27\x20failed\x20to\x20register\x20(already\x20registered?).\x20'+'Unregister\x20first\x20or\x20upgrade\x20with\x20a\x20different\x20version.'):d['push']('mode');}}if(e['layers']['includes']('match')){if(!a['match'])c['push']('pack\x20\x27'+e['name']+'\x27\x20declares\x20layer\x20\x27match\x27\x20but\x20match.json\x20is\x20missing');else{if(!isMeaningfulMatch(a['match'])){}else{const k=a['match']['pricing_rules']['filter'](l=>FORBIDDEN_PRICING_MODES['has'](l));if(k['length']>0x0)c['push']('match.pricing_rules\x20contains\x20forbidden\x20modes:\x20'+k['join'](',\x20')+'\x20'+'(violates\x20upper-layer\x20pricing\x20red\x20lines,\x20K3\x2015\x20§4.2)');else!registerCategoryMatchRules(a['match'],i)?c['push']('match\x20rules\x20for\x20\x27'+a['match']['category']+'\x27\x20already\x20registered'):d['push']('match');}}}if(e['layers']['includes']('personae')){if(!a['personae']||a['personae']['length']===0x0)c['push']('pack\x20\x27'+e['name']+'\x27\x20declares\x20layer\x20\x27personae\x27\x20but\x20personae\x20are\x20missing');else{const l=a['personae']['filter'](isMeaningfulPersona);if(l['length']===0x0){}else registerIndustryPersonae(e['name'],l),d['push']('personae');}}if(e['layers']['includes']('dispute')){if(!a['dispute'])c['push']('pack\x20\x27'+e['name']+'\x27\x20declares\x20layer\x20\x27dispute\x27\x20but\x20dispute.json\x20is\x20missing');else{if(!isMeaningfulDispute(a['dispute'])){}else!registerDisputeRules(a['dispute'],i)?c['push']('dispute\x20rules\x20for\x20\x27'+a['dispute']['category']+'\x27\x20already\x20registered'):d['push']('dispute');}}if(e['layers']['includes']('compliance')){if(!a['compliance'])c['push']('pack\x20\x27'+e['name']+'\x27\x20declares\x20layer\x20\x27compliance\x27\x20but\x20compliance.json\x20is\x20missing');else{if(!isMeaningfulCompliance(a['compliance'])){}else!registerComplianceRules(a['compliance'],i)?c['push']('compliance\x20rules\x20for\x20\x27'+a['compliance']['category']+'\x27\x20already\x20registered'):d['push']('compliance');}}if(e['layers']['includes']('supply')){if(!a['supply'])c['push']('pack\x20\x27'+e['name']+'\x27\x20declares\x20layer\x20\x27supply\x27\x20but\x20supply.json\x20is\x20missing');else{if(!isMeaningfulSupply(a['supply'])){}else!registerSupplyRules(a['supply'],i)?c['push']('supply\x20rules\x20for\x20\x27'+a['supply']['category']+'\x27\x20already\x20registered'):d['push']('supply');}}if(e['layers']['includes']('rules')){if(!a['rules'])c['push']('pack\x20\x27'+e['name']+'\x27\x20declares\x20layer\x20\x27rules\x27\x20but\x20rules.json\x20is\x20missing');else{if(!isMeaningfulRules(a['rules'])){}else!registerIndustryRules(a['rules'],i)?c['push']('industry\x20rules\x20for\x20\x27'+a['rules']['category']+'\x27\x20already\x20registered'):d['push']('rules');}}if(e['layers']['includes']('playbook')){if(!a['playbook'])c['push']('pack\x20\x27'+e['name']+'\x27\x20declares\x20layer\x20\x27playbook\x27\x20but\x20playbook.md\x20is\x20missing');else{if(!isMeaningfulPlaybook(a['playbook'])){}else!registerIndustryPlaybook(a['playbook'],i)?c['push']('playbook\x20for\x20\x27'+a['playbook']['category']+'\x27\x20already\x20registered'):d['push']('playbook');}}return c['length']===0x0&&packRegistry['set'](e['name'],{'version':e['version'],'layers':[...e['layers']],'registered_at':Date['now']()}),{'ok':c['length']===0x0,'errors':c,'registered':d};}let builtinModesAsPacksRegistered=![];function ensureBuiltinModesAsPacks(){if(builtinModesAsPacksRegistered)return;builtinModesAsPacksRegistered=!![];for(const a of BUILTIN_MODES){if(packRegistry['has'](a['name']))continue;packRegistry['set'](a['name'],{'version':a['version'],'layers':['mode','match'],'registered_at':Date['now']()});}}export function listRegisteredPacks(){return ensureBuiltinModesAsPacks(),Array['from'](packRegistry['entries']())['map'](([a,b])=>({'name':a,...b}));}export function unregisterIndustryPack(a){const b=new Set(BUILTIN_MODES['map'](c=>c['name']));if(b['has'](a))return![];if(!packRegistry['has'](a))return![];return packRegistry['delete'](a),unregisterIndustryPersonae(a),!![];}export function diffIndustryPack(a){const b=packRegistry['get'](a)??null,c=resolveIndustryPackDir(),d=join(c,a),e=readMergedPackIfPresent(d);let f=null;try{if(e&&e['manifest'])f={'version':e['manifest']['version'],'layers':e['manifest']['layers']??[]};else{const l=join(d,'manifest.json');if(existsSync(l)){const m=JSON['parse'](readFileSync(l,'utf-8'));f={'version':m['version'],'layers':m['layers']??[]};}}}catch{f=null;}const g=b?.['layers']??[],h=f?.['layers']??[],i=h['filter'](n=>!g['includes'](n)),j=g['filter'](n=>!h['includes'](n)),k=!!b&&!!f&&(b['version']!==f['version']||i['length']>0x0||j['length']>0x0);return{'name':a,'registered':b?{...b,'layers':[...b['layers']]}:null,'disk':f,'upgradable':k,'layer_diff':{'added':i,'removed':j}};}export function scanPacks(a){const b=[];if(!existsSync(a))return b;for(const c of readdirSync(a,{'withFileTypes':!![]})){if(!c['isDirectory']())continue;const d=join(a,c['name']);try{const e=loadPackFromDir(d);if(!e)continue;b['push'](registerIndustryPack(e));}catch(f){b['push']({'ok':![],'errors':['failed\x20to\x20load\x20pack\x20\x27'+c['name']+'\x27:\x20'+f['message']],'registered':[]});}}return b;}function loadPackFromDir(a){const b=readMergedPackIfPresent(a),c=join(a,'manifest.json'),d=existsSync(c);if(!b&&!d)return null;if(b){const p=b['manifest'],q={'layout':'merged','manifest':p};if(b['mode'])q['mode']=b['mode'];if(b['match'])q['match']=b['match'];b['personae']&&Array['isArray'](b['personae'])&&(q['personae']=b['personae']);if(b['dispute'])q['dispute']=b['dispute'];if(b['compliance'])q['compliance']=b['compliance'];if(b['supply'])q['supply']=b['supply'];if(b['rules'])q['rules']=b['rules'];const r=join(a,'playbook.md');return existsSync(r)&&(q['playbook']={'category':p['name'],'content':readFileSync(r,'utf-8')}),q;}const e=JSON['parse'](readFileSync(c,'utf-8')),g={'layout':'legacy','manifest':e},h=join(a,'mode.json'),i=join(a,'match.json');existsSync(h)&&(g['mode']=JSON['parse'](readFileSync(h,'utf-8')));existsSync(i)&&(g['match']=JSON['parse'](readFileSync(i,'utf-8')));const j=join(a,'personae');if(existsSync(j)){const s=[];for(const t of readdirSync(j)){if(!t['endsWith']('.json'))continue;s['push'](JSON['parse'](readFileSync(join(j,t),'utf-8')));}if(s['length']>0x0)g['personae']=s;}const k=join(a,'dispute.json');existsSync(k)&&(g['dispute']=JSON['parse'](readFileSync(k,'utf-8')));const l=join(a,'compliance.json');existsSync(l)&&(g['compliance']=JSON['parse'](readFileSync(l,'utf-8')));const m=join(a,'supply.json');existsSync(m)&&(g['supply']=JSON['parse'](readFileSync(m,'utf-8')));const n=join(a,'rules.json');existsSync(n)&&(g['rules']=JSON['parse'](readFileSync(n,'utf-8')));const o=join(a,'playbook.md');return existsSync(o)&&(g['playbook']={'category':e['name'],'content':readFileSync(o,'utf-8')}),g;}export function rescanPack(a){const b=join(resolveIndustryPackDir(),a);try{const c=loadPackFromDir(b);if(!c)return{'ok':![],'errors':['no\x20pack\x20found\x20for\x20\x27'+a+'\x27'],'registered':[]};return registerIndustryPack(c,!![]);}catch(d){return{'ok':![],'errors':['failed\x20to\x20rescan\x20pack\x20\x27'+a+'\x27:\x20'+d['message']],'registered':[]};}}export function resolveIndustryPackDir(){return process['env']['WOWOK_INDUSTRY_DIR']||getWowokIndustryDir();}export function scanDefaultIndustryPacks(){return seedBuiltinIndustryTemplates(),seedBuiltinStrategyManuals(),ensureIndustryReadme(),ensureBuiltinModesAsPacks(),scanPacks(resolveIndustryPackDir());}export function seedBuiltinIndustryTemplates(a=SUPPORTED_INDUSTRIES){const b=[],c=resolveIndustryPackDir();mkdirSync(c,{'recursive':!![]}),ensureIndustryReadme();for(const d of a){const e=join(c,d);if(existsSync(join(e,'manifest.json'))||existsSync(join(e,'pack.json')))continue;const f=scaffoldIndustryPack(d,c);if(f['ok'])b['push'](d);}return b;}export function seedBuiltinStrategyManuals(a=SUPPORTED_INDUSTRIES){const b=[],c=resolveIndustryPackDir();for(const d of a){const e=renderStrategyManual(d);if(!e)continue;const f=join(c,d,STRATEGY_MANUAL_FILENAME);try{const g=join(c,d);if(!existsSync(join(g,'manifest.json'))&&!existsSync(join(g,'pack.json'))){const j=scaffoldIndustryPack(d,c);if(!j['ok']){b['push']({'industry':d,'status':'error','path':f,'detail':j['errors']['join'](';\x20')});continue;}}if(!existsSync(f)){writeFileSync(f,e,'utf-8'),b['push']({'industry':d,'status':'written','path':f});continue;}const h=readFileSync(f,'utf-8'),i=classifyManualFile(d,h);if(i==='outdated')writeFileSync(f,e,'utf-8'),b['push']({'industry':d,'status':'updated','path':f});else{if(i==='current')b['push']({'industry':d,'status':'current','path':f});else i==='user_modified'?b['push']({'industry':d,'status':'skipped_user_modified','path':f,'detail':'strategy-manual.md\x20was\x20edited\x20locally;\x20keeping\x20user\x20content\x20and\x20not\x20upgrading'}):b['push']({'industry':d,'status':'skipped_user_file','path':f,'detail':'strategy-manual.md\x20exists\x20without\x20builtin\x20sentinel;\x20leaving\x20user\x20file\x20untouched'});}}catch(k){b['push']({'industry':d,'status':'error','path':f,'detail':k['message']});}}return b;}export const LAYER_FILE_SECTION={'match.json':'match','dispute.json':'dispute','compliance.json':'compliance','supply.json':'supply','rules.json':'rules','mode.json':'mode'};export const PERSONAE_DIR='personae';function manifestSection(a){return{'pack':'industry-pack','name':a,'display_name':a,'version':'0.1.0','layers':['match','personae','dispute','compliance','supply','rules','playbook']};}function matchSection(a){return{'category':a,'hard_constraints':[],'soft_weights':{},'highlight_fields':[],'calendar_mode':'none','geo_mode':'strict','pricing_rules':[]};}function personaPerRole(a,b){return{'role':a,'industry':b,'long_term':{'identity':{'self_description':b+'\x20'+a},'preferences':{}},'current':{'strategy':[],'requirements':[],'rules':[],'spec':'','preferences':{}}};}function disputeSection(a){return{'category':a,'sla_tiers':[],'fault_rules':[]};}function complianceSection(a){return{'category':a,'prepay_mode':'','qualification':[],'disclosure':[],'refund_window':{'days':0x7,'not_applicable':![]}};}function supplySection(a){return{'category':a,'supplier_qualification':[],'first_order_policy':'','redundancy_required':![]};}function rulesSection(a){return{'category':a,'rules':[]};}export function buildPristineMergedPack(a){const b=PERSONA_ROLES['map'](c=>personaPerRole(c,a));return{'manifest':manifestSection(a),'match':matchSection(a),'personae':b,'dispute':disputeSection(a),'compliance':complianceSection(a),'supply':supplySection(a),'rules':rulesSection(a),'mode':null};}export function industryReadmeContent(){return['#\x20WoWok\x20Industry\x20Packs','','>\x20This\x20folder\x20is\x20the\x20WoWok\x20industry\x20knowledge\x20root.\x20Each\x20sub-folder\x20is\x20one','>\x20industry\x20pack.\x20Pack\x20layers\x20are\x20registered\x20into\x20the\x20runtime\x20registry\x20and','>\x20consumed\x20on\x20demand\x20by\x20the\x20build/recommendation\x20tools\x20(merchant_guide,','>\x20recommend_industry,\x20…);\x20a\x20compact\x20strategy\x20summary\x20for\x20the\x20active','>\x20merchant/supplier\x20lens\x20is\x20injected\x20into\x20every\x20chat\x20turn.','','##\x20Pack\x20structure\x20(unified\x20layout)','','Every\x20pack\x20is\x20exactly\x20two\x20files:','','-\x20**`<pack>/pack.json`**\x20—\x20machine-checkable\x20**settings\x20only**.\x20No\x20comments,','\x20\x20no\x20documentation.\x20One\x20section\x20per\x20layer\x20(see\x20below).','-\x20**`<pack>/playbook.md`**\x20—\x20human\x20strategy,\x20tone\x20and\x20field-tested\x20experience.','\x20\x20Registered\x20on\x20scan\x20and\x20read\x20ON\x20DEMAND\x20via\x20industry_pack_operation','\x20\x20(action=\x27get\x27);\x20it\x20OVERRIDES\x20built-in\x20industry\x20data\x20for\x20this\x20account.','','All\x20field\x20explanations\x20live\x20in\x20THIS\x20file,\x20so\x20pack.json\x20stays\x20small\x20and\x20you','can\x20focus\x20on\x20configuration.\x20The\x20editor\x20also\x20validates\x20JSON\x20on\x20save\x20—\x20a\x20file','that\x20fails\x20to\x20parse\x20(or\x20a\x20pack.json\x20missing\x20its\x20manifest)\x20is\x20blocked.','','##\x20How\x20changes\x20take\x20effect','','1.\x20**Save**\x20in\x20the\x20Editor\x20writes\x20bytes\x20to\x20disk.','2.\x20**Scan**\x20(Industry\x20drawer)\x20re-registers\x20each\x20pack\x20into\x20the\x20runtime\x20AI','\x20\x20\x20registry\x20(and\x20SQLite\x20cache).\x20A\x20save\x20of\x20an\x20industry\x20file\x20already\x20runs','\x20\x20\x20Scan\x20automatically.','3.\x20**Next\x20AI\x20chat\x20turn**\x20the\x20registered\x20layers\x20are\x20available\x20to\x20the','\x20\x20\x20on-demand\x20tools\x20(and\x20the\x20merchant/supplier\x20strategy\x20summary\x20is\x20fresh','\x20\x20\x20in\x20the\x20persona\x20context),\x20so\x20the\x20AI\x20reasons\x20against\x20your\x20edited\x20rules','\x20\x20\x20from\x20that\x20point\x20onward.','','##\x20manifest\x20—\x20pack\x20metadata\x20+\x20layer\x20ENABLE\x20flags','','-\x20`name`:\x20snake_case\x20identifier,\x20must\x20match\x20the\x20folder\x20name.','-\x20`version`:\x20bump\x20after\x20editing\x20content\x20so\x20the\x20registry\x20treats\x20it\x20as\x20an\x20upgrade.','-\x20`display_name`:\x20user-visible\x20label.','-\x20`layers`:\x20which\x20sections\x20are\x20validated\x20and\x20registered\x20on\x20scan.\x20Remove\x20a','\x20\x20layer\x20name\x20to\x20DISABLE\x20it\x20(the\x20section\x20stays\x20in\x20pack.json\x20but\x20is\x20ignored).','','##\x20match\x20—\x20category-match\x20rules','','Decides\x20whether\x20an\x20order/service/account\x20belongs\x20to\x20this\x20industry\x20pack:','-\x20`hard_constraints`:\x20array\x20of\x20REQUIRED\x20predicates;\x20ALL\x20must\x20match\x20before\x20the','\x20\x20pack\x20is\x20considered.\x20Example:','\x20\x20`[{\x20key:\x20\x27order.metadata.service_kind\x27,\x20equals:\x20\x27food_onsite\x27\x20}]`','-\x20`soft_weights`:\x20dict\x20`<heuristic_key:\x20number\x200..1>`;\x20higher\x20=\x20stronger\x20signal.','-\x20`pricing_rules`:\x20pricing\x20modes\x20this\x20industry\x20requires.','-\x20`highlight_fields`:\x20dot-paths\x20surfaced\x20in\x20the\x20UI\x20as\x20important\x20info.','-\x20`geo_mode`:\x20`\x27strict\x27`\x20(region\x20must\x20match)\x20|\x20`\x27none\x27`\x20(ignore\x20region).','-\x20`calendar_mode`:\x20`\x27seasonal\x27`\x20|\x20`\x27weekday\x27`\x20|\x20`\x27none\x27`.','','##\x20personae\x20—\x20per-role\x20AI\x20personas','','One\x20persona\x20per\x20role\x20(`merchant`,\x20`customer`,\x20`supplier`,\x20`collaborator`,','`arbitrator`,\x20`prospect`).\x20The\x20AI\x20uses\x20them\x20to\x20role-play\x20negotiation\x20posture:','-\x20`long_term`:\x20stable\x20properties\x20—\x20`identity.self_description`\x20(free-text\x20bio),','\x20\x20`identity.region/languages`,\x20`preferences`\x20(`<key:\x20string[]>`).','-\x20`current`:\x20per-negotiation\x20posture\x20—\x20`strategy`\x20(moves\x20to\x20make),','\x20\x20`requirements`\x20(non-negotiable\x20demands),\x20`rules`\x20(constraints/axioms),','\x20\x20`spec`\x20(free-form\x20text),\x20`preferences`\x20(per-turn\x20overrides).','','##\x20dispute\x20—\x20SLA\x20tiers\x20+\x20fault\x20assignment','','-\x20`sla_tiers[]`:\x20response/remedy\x20windows\x20per\x20severity\x20level.','\x20\x20Example:\x20`{\x20level:\x20\x27L1\x27,\x20response_hours:\x2024,\x20remedy:\x20\x27reply\x27\x20}`','-\x20`fault_rules[]`:\x20automatic\x20fault\x20attribution\x20—\x20a\x20condition\x20plus\x20the\x20side','\x20\x20that\x20bears\x20fault\x20(`merchant`/`customer`/`supplier`/`operator`/`shared`).','\x20\x20Example:\x20`{\x20when:\x20{\x20evidence_has:\x20[\x27late\x20delivery\x20photo\x27]\x20},\x20assign_to:\x20\x27merchant\x27,\x20weight:\x201.0\x20}`','','##\x20compliance\x20—\x20hard\x20requirements\x20before\x20checkout','','-\x20`prepay_mode`:\x20`\x27\x27`\x20|\x20`\x27full\x27`\x20|\x20`\x27partial\x27`\x20|\x20`\x27deposit\x27`.','-\x20`qualification[]`:\x20licenses/certifications\x20a\x20merchant\x20must\x20hold.','\x20\x20Example:\x20`{\x20label:\x20\x27Food\x20Service\x20License\x27,\x20required:\x20true,\x20region:\x20\x27CN\x27\x20}`','-\x20`disclosure[]`:\x20text\x20the\x20merchant\x20MUST\x20show\x20buyers\x20up-front.','-\x20`refund_window`:\x20`{\x20days:\x20number,\x20not_applicable:\x20boolean,\x20exceptions:\x20[...]\x20}`','','##\x20supply\x20—\x20supply-chain\x20/\x20supplier\x20qualification','','-\x20`supplier_qualification[]`:\x20same\x20shape\x20as\x20compliance\x20qualifications,\x20but','\x20\x20evaluated\x20on\x20the\x20SUPPLIER\x20side\x20(multi-party\x20orders).','-\x20`first_order_policy`:\x20policy\x20string\x20on\x20the\x20first\x20order\x20from\x20a\x20new\x20supplier','\x20\x20(e.g.\x20`\x27sample-only\x27`,\x20`\x27reduced-quantity\x27`).','-\x20`redundancy_required`:\x20true\x20=\x20require\x20≥2\x20eligible\x20suppliers\x20before\x20accepting','\x20\x20an\x20order\x20(mitigates\x20single-sourcing).','','##\x20rules\x20—\x20declarative\x20machine-checked\x20rules','','Each\x20rule\x20is\x20an\x20AST\x20node\x20compiled\x20into\x20the\x20evaluation\x20engine:','`{\x20id:\x20\x27rule_...\x27,\x20when:\x20<bool-condition>,\x20then:\x20\x27reject\x27\x20|\x20\x27warn\x27\x20|\x20\x27flag\x27,\x20message:\x20\x27Text\x27\x20}`','Use\x20`rules`\x20for\x20rules\x20that\x20must\x20be\x20machine-checked;\x20put\x20human\x20strategy\x20in','`playbook.md`.','','##\x20mode\x20—\x20IndustryMode\x20(deep\x20shape)','','Not\x20scaffolded\x20by\x20default.\x20Add\x20it\x20when\x20you\x20need\x20a\x20full\x20driving\x20mode\x20for\x20the','industry,\x20or\x20ask\x20the\x20AI:\x20\x22help\x20me\x20fill\x20mode\x20for\x20<industry>\x22.','','Registered\x20into\x20`IndustryModeRegistry`\x20on\x20scan\x20(manifest\x20must\x20list\x20the','`mode`\x20layer).\x20A\x20pack\x20mode\x20with\x20the\x20same\x20name\x20as\x20a\x20builtin\x20replaces\x20it\x20when','the\x20pack\x20version\x20changes\x20or\x20on\x20a\x20forced\x20rescan.','','###\x20How\x20the\x20mode\x20is\x20consumed','','-\x20**Service\x20build\x20(priors)**:\x20`merchant_guide`\x20resolves\x20the\x20confirmed','\x20\x20industry\x20to\x20a\x20mode\x20(user\x20mode\x20first,\x20then\x20pack\x20mode,\x20then\x20builtin)\x20and','\x20\x20feeds\x20`machine_shape`\x20/\x20`guards`\x20/\x20`allocator`\x20/\x20`key_risk`\x20into\x20the','\x20\x20SemanticObjectGraph\x20build.','-\x20**Evaluation**:\x20the\x20metric\x20+\x20constraint\x20registries\x20score\x20the\x20mode','\x20\x20(risk/benefit\x200-100,\x20hard\x20violations\x20block\x20adoption).\x20Custom\x20metrics\x20and','\x20\x20constraints\x20registered\x20via\x20`industry_pack_operation`\x20participate\x20too.','-\x20**Recommendation**:\x20`recommend_industry`\x20matches\x20trait\x20similarity\x20and,','\x20\x20when\x20a\x20merchant\x20strategy\x20is\x20given,\x20re-ranks\x20by\x20lever\x20alignment\x20(70%','\x20\x20similarity\x20+\x2030%\x20alignment).','','###\x20Field\x20reference','','-\x20**Identity**:\x20`name`\x20(snake_case),\x20`display_name`,\x20`version`\x20(e.g.\x20`v1`),','\x20\x20`source`\x20(`builtin`\x20|\x20`custom`).','-\x20`traits`:\x2010-dimension\x20industry\x20trait\x20vector\x20(logistics,\x20cycle,\x20deposit,','\x20\x20regulatory\x20intensity,\x20...).\x20Drives\x20`recommend_industry`\x20similarity.','-\x20`machine_shape`:\x20Machine\x20node\x20topology\x20—\x20`[{\x20name,\x20role\x20}]`.\x20Node\x20names\x20are','\x20\x20business\x20states.\x20R-M1-11:\x20NEVER\x20model\x20refund/dispute\x20terminals','\x20\x20(`refunded`,\x20`disputed`,\x20`arb_*`)\x20as\x20nodes\x20—\x20disputes\x20flow\x20through','\x20\x20Service.arbitrations\x20independently;\x20route\x20refunds\x20via\x20the\x20Allocator','\x20\x20triggered\x20by\x20business\x20states\x20(`cancelled`,\x20`returned`).','-\x20`guards`:\x20`[{\x20template_id,\x20host,\x20purpose\x20}]`\x20—\x20guard\x20templates\x20to\x20attach.','\x20\x20`host`\x20is\x20one\x20of\x20`service`\x20|\x20`machine`\x20|\x20`reward`\x20|\x20`repository`\x20|','\x20\x20`arbitration`.','-\x20`allocator`:\x20`{\x20recipient,\x20count,\x20mode,\x20description\x20}`\x20—\x20fund\x20split.','\x20\x20`recipient`:\x20`signer`\x20|\x20`entity`;\x20`count`\x20>\x201\x20switches\x20to\x20multi-party','\x20\x20distribution;\x20`mode`:\x20`surplus`\x20|\x20`rate`\x20|\x20`milestone`.','-\x20`risk_checks`\x20/\x20`needs`:\x20buyer-side\x20due-diligence\x20entries\x20surfaced\x20in','\x20\x20prospect\x20evaluation.','-\x20`flywheel`:\x20acquisition\x20flywheel\x20—\x20`rewardStrategy`\x20/\x20`discountStrategy`','\x20\x20/\x20`trustSellingPoints`.\x20A\x20concrete\x20(non-`User-defined`)\x20strategy\x20turns','\x20\x20the\x20`reward`/`discount`\x20levers\x20on\x20for\x20strategy\x20alignment.','-\x20`key_risk`\x20(string)\x20/\x20`build_notes`\x20(string[]):\x20the\x20headline\x20risk\x20and','\x20\x20actionable\x20build\x20guidance\x20shown\x20to\x20the\x20merchant.','-\x20`capabilities_used`:\x20CapabilityCard\x20IDs\x20(e.g.\x20`guard.validate_buy`,','\x20\x20`machine.node_topology`,\x20`allocation.distribute_milestone`).\x20Powers\x20the','\x20\x20`buy_guard`\x20/\x20`machine_design`\x20levers\x20and\x20constraint\x20checks.','-\x20`config_overrides`:\x20per-object\x20field\x20defaults,\x20e.g.','\x20\x20`{\x20service:\x20{\x20engagement_type:\x20\x27milestone\x27\x20},\x20machine:\x20{\x20wip_required:\x20true\x20}\x20}`.','-\x20`config_override_rules`:\x20conditional\x20overrides\x20—','\x20\x20`{\x20object_type,\x20field_path,\x20value\x20|\x20{\x20intent_contains,\x20then_value,\x20else_value\x20}\x20}`.','-\x20`expected_benefits`:\x20`[{\x20metric,\x20expected_value,\x20evidence\x20}]`\x20—\x20what\x20the','\x20\x20mode\x20is\x20supposed\x20to\x20buy\x20you.','-\x20`risk_appetite`:\x20`conservative`\x20|\x20`balanced`\x20|\x20`aggressive`\x20(thresholds','\x20\x20for\x20the\x20risk/benefit\x20verdict).','-\x20`risk_constraints`:\x20`{\x20require_arbitration,\x20require_compensation_fund,','\x20\x20require_wip_evidence,\x20max_single_transaction?,','\x20\x20compensation_fund_coverage_ratio?,\x20other_constraints?\x20}`.\x20Coverage\x20ratio','\x20\x20multiplies\x20max\x20single\x20order\x20to\x20size\x20the\x20compensation\x20fund\x20(retail\x205,','\x20\x20rental\x2010,\x20subscription\x203;\x20default\x205).','-\x20`applicable_conditions`:\x20`{\x20business_scale,\x20min_daily_orders?,','\x20\x20other_conditions?\x20}`\x20—\x20when\x20the\x20mode\x20fits.','-\x20`similar_industries`\x20/\x20`novel_capabilities`:\x20migration\x20hints.','-\x20`disabled_builtin_constraints`:\x20builtin\x20constraint\x20IDs\x20this\x20mode','\x20\x20deliberately\x20opts\x20out\x20of\x20(e.g.\x20retail_d2c\x20skips\x20`require_arbitration`).','\x20\x20Custom\x20constraints\x20are\x20never\x20skipped.','','###\x20Persona\x20integration\x20(strategy\x20→\x20levers)','','The\x20personae\x20section\x27s\x20`current.strategy`\x20statements\x20are\x20bridged\x20into\x20mode','ranking\x20(value\x20intent\x20↔\x20game\x20path\x20unification).\x20Deterministic\x20mapping\x20—','\x22enumerable\x20→\x20MCP,\x20not\x20prompt\x22:','','-\x20`sales_priority`\x20(volume\x20first)\x20→\x20levers\x20`discount`\x20+\x20`reward`','-\x20`profit_priority`\x20(margin\x20first)\x20→\x20levers\x20`discount`\x20+\x20`machine_design`','-\x20`buyer_screening`\x20(qualify\x20buyers)\x20→\x20lever\x20`buy_guard`','-\x20`gross_margin_control`\x20(margin\x20band)\x20→\x20levers\x20`discount`\x20+\x20`machine_design`','','A\x20mode\x20supports\x20a\x20lever\x20when\x20its\x20data\x20says\x20so:\x20`guard.validate_buy`','capability\x20or\x20a\x20buy-guard\x20template\x20enables\x20`buy_guard`;\x20a\x20concrete','flywheel\x20reward/discount\x20strategy\x20enables\x20`reward`/`discount`;\x20a','non-empty\x20`machine_shape`\x20with\x20`machine.node_topology`\x20enables','`machine_design`.\x20Pass\x20strategy\x20text\x20to\x20`recommend_industry`\x20and\x20each','recommendation\x20reports\x20`strategy_alignment`\x20(matched/missing\x20levers).','','##\x20custom-registry.json\x20—\x20global\x20custom\x20metrics\x20/\x20constraints\x20/\x20modes','','Custom\x20metrics,\x20constraints\x20and\x20user\x20modes\x20registered\x20via','`industry_pack_operation`\x20(register_custom_metric\x20/','register_custom_constraint\x20/\x20derive_user_mode\x20/\x20register_user_mode)','persist\x20to\x20THIS\x20root-level\x20file\x20—\x20it\x20is\x20global\x20and\x20applies\x20to\x20every','industry\x20pack.\x20Layout:\x20`metrics`\x20keyed\x20by\x20metric\x20id,\x20`constraints`','keyed\x20by\x20constraint\x20id,\x20`user_modes`\x20keyed\x20by\x20`<owner>:<name>`.\x20The','file\x20is\x20created\x20on\x20first\x20use\x20(seeded\x20from\x20the\x20legacy\x20SQLite\x20cache\x20when','present);\x20hand\x20edits\x20take\x20effect\x20on\x20the\x20next\x20registry\x20call,\x20and','deleting\x20an\x20entry\x20removes\x20it.','','##\x20Reset','','Right-click\x20any\x20file/pack\x20folder\x20in\x20the\x20Industry\x20drawer\x20and\x20choose\x20*Reset*','to\x20restore\x20the\x20pristine\x20template\x20at\x20any\x20time.','']['join']('\x0a');}export function ensureIndustryReadme(){const a=resolveIndustryPackDir();mkdirSync(a,{'recursive':!![]});const b=join(a,'README.md');return writeFileSync(b,industryReadmeContent(),'utf-8'),b;}export function scaffoldIndustryPack(a,b){const c=join(b??resolveIndustryPackDir(),a),d=[],e=[];if(!/^[a-z][a-z0-9_]*$/['test'](a))return{'ok':![],'dir':c,'files':d,'errors':['industry\x20name\x20\x27'+a+'\x27\x20must\x20be\x20lowercase\x20snake_case\x20(a-z,\x200-9,\x20_)']};try{mkdirSync(c,{'recursive':!![]}),ensureIndustryReadme();const f=buildPristineMergedPack(a);return writeFileSync(join(c,'pack.json'),JSON['stringify'](f,null,0x2)+'\x0a'),d['push']('pack.json'),writeFileSync(join(c,'playbook.md'),playbookTemplate(a)),d['push']('playbook.md'),{'ok':!![],'dir':c,'files':d,'errors':e};}catch(g){return{'ok':![],'dir':c,'files':d,'errors':['scaffold\x20failed:\x20'+g['message']]};}}export function readMergedPackIfPresent(a){const b=join(a,'pack.json');if(!existsSync(b))return null;try{const c=readFileSync(b,'utf-8');return JSON['parse'](c);}catch{return null;}}function playbookTemplate(a){return['#\x20'+a+'\x20—\x20Industry\x20Playbook','','>\x20📘\x20This\x20file\x20captures\x20human\x20business\x20intelligence\x20for\x20the\x20`'+a+'`','>\x20industry.\x20Content\x20here\x20is\x20READ\x20BY\x20THE\x20AI\x20AS\x20CONTEXT\x20on\x20every\x20turn,','>\x20and\x20OVERRIDES\x20WoWok\x27s\x20generic\x20built-in\x20industry\x20data/rules\x20for\x20this','>\x20account.\x20The\x20companion\x20`pack.json`\x20file\x20stores\x20machine-checkable','>\x20rules;\x20THIS\x20file\x20stores\x20human\x20strategy,\x20tone,\x20experience,\x20and\x20ethics.','','>\x20💡\x20Hint\x20for\x20the\x20AI:\x20when\x20the\x20user\x20asks\x20a\x20question\x20about\x20\x22how\x20to','>\x20handle\x20'+a+'\x22\x20or\x20\x22what\x20should\x20I\x20do?\x22,\x20check\x20this\x20file\x20first\x20for\x20the','>\x20merchant/customer\x20voice,\x20then\x20fall\x20back\x20to\x20your\x20built-in\x20data.\x20Cite','>\x20section\x20titles\x20in\x20your\x20reply\x20so\x20the\x20user\x20knows\x20where\x20advice\x20comes\x20from.','','##\x20Experience\x20(Field-Tested\x20Rules\x20of\x20Thumb)','','>\x20Write\x20what\x20actually\x20works\x20in\x20this\x20industry\x20—\x20not\x20what\x20textbooks\x20say.','>\x20Short\x20bullet\x20points\x20preferred;\x20the\x20AI\x20reads\x20them\x20as\x20axioms.\x20Include','>\x20specific\x20numbers\x20when\x20you\x20have\x20them.','','-\x20(Example)\x20\x22Catering:\x20if\x20the\x20event\x20starts\x20before\x2010:00,\x20always\x20assume','\x20\x20the\x20customer\x20wants\x20breakfast\x20service\x20too\x20—\x20upsell\x20it\x20proactively.\x22','-\x20(Example)\x20\x22Common\x20pitfall:\x20last-minute\x20menu\x20swaps\x20on\x20Fridays\x20—\x20require','\x20\x20a\x20written\x20change\x20request\x2048\x20h\x20before\x20the\x20event\x20or\x20charge\x20a\x2015%\x20fee.\x22','-\x20(Add\x20more\x20below\x20—\x20delete\x20the\x20examples\x20above\x20when\x20you\x20have\x20real\x20ones.)','','##\x20Strategy\x20(Competitive\x20/\x20Game-Theory)','','>\x20How\x20should\x20each\x20role\x20act\x20in\x20a\x20negotiation\x20/\x20dispute\x20/\x20supplier','>\x20relationship?\x20Think\x20in\x20\x22always\x20/\x20never\x20/\x20depends-on-X\x22\x20rules,\x20and\x20call','>\x20out\x20the\x20trade-offs.','','-\x20Merchant\x20strategy:\x20(Add\x20how\x20a\x20merchant\x20in\x20this\x20industry\x20should\x20act\x20—','\x20\x20price\x20anchoring,\x20which\x20concessions\x20to\x20give\x20early\x20vs\x20late,\x20what\x20to','\x20\x20never\x20concede\x20on,\x20etc.)','-\x20Customer\x20strategy:\x20(Add\x20what\x20a\x20smart\x20customer\x20should\x20push\x20for.)','-\x20Dispute\x20strategy:\x20(When\x20to\x20settle\x20fast\x20vs\x20when\x20to\x20fight\x20for\x20full','\x20\x20evidence\x20+\x20arbitration.\x20Call\x20out\x20the\x20escalation\x20thresholds.)','','##\x20Personalization\x20(Tone,\x20Brand,\x20Ethics,\x20Red\x20Lines)','','-\x20Tone\x20/\x20voice:\x20(Write\x20one\x20sentence\x20describing\x20the\x20exact\x20conversational','\x20\x20voice\x20this\x20account\x20should\x20use\x20—\x20casual,\x20formal,\x20technical,\x20etc.)','-\x20Brand\x20rules:\x20(Logo,\x20link-out\x20style,\x20forbidden\x20terminology,','\x20\x20always-include\x20phrases,\x20etc.)','-\x20Red\x20lines:\x20(Non-negotiable.\x20Example:\x20\x22Never\x20make\x20a\x20refund\x20promise','\x20\x20larger\x20than\x2030%\x20without\x20arbitration\x20evidence.\x22)','-\x20Ethics:\x20(Example:\x20\x22If\x20customer\x20appears\x20intoxicated,\x20refuse\x20service','\x20\x20and\x20refer\x20to\x20supervisor;\x20never\x20take\x20the\x20order\x20for\x20profit.\x22)','','##\x20Playbook\x20Maintenance','','>\x20You\x20don\x27t\x20need\x20to\x20be\x20perfect\x20on\x20day\x20one.\x20After\x20every\x20real\x20deal,\x20add\x20a','>\x20bullet\x20to\x20the\x20above\x20sections\x20with\x20what\x20worked\x20/\x20what\x20failed.\x20Every','>\x20entry\x20improves\x20the\x20AI\x27s\x20future\x20decisions.','','>\x20Right-click\x20the\x20file\x20or\x20this\x20pack\x20folder\x20in\x20the\x20Industry\x20drawer\x20at','>\x20any\x20time\x20and\x20choose\x20\x22Reset\x22\x20to\x20restore\x20this\x20annotated\x20template.','']['join']('\x0a');}export function locatePackAndRemainder(a){const b=a['replace'](/^[\\/]+/,'')['replace'](/[\\/]+$/,'');if(!b)return null;const [c,...d]=b['split'](/[\\/]+/);if(!c)return null;return{'packName':c,'remainder':d['join']('/')};}export function resetIndustryPath(a,b){const c=[],d=[],f=b??resolveIndustryPackDir(),g=locatePackAndRemainder(a),h=a;if(!g)return{'ok':![],'layout':'merged','target':h,'restored_files':[],'errors':['invalid\x20reset\x20path\x20\x27'+a+'\x27']};const {packName:i,remainder:j}=g,k=join(f,i);if(!existsSync(k))return{'ok':![],'layout':'merged','target':h,'restored_files':[],'errors':['pack\x20directory\x20\x27'+i+'\x27\x20does\x20not\x20exist']};if(!/^[a-z][a-z0-9_]*$/['test'](i))return{'ok':![],'layout':'merged','target':h,'restored_files':[],'errors':['pack\x20name\x20\x27'+i+'\x27\x20is\x20not\x20a\x20valid\x20snake_case\x20identifier']};const l=readMergedPackIfPresent(k),n=l?'merged':'legacy';if(j==='')try{mkdirSync(k,{'recursive':!![]});const s=buildPristineMergedPack(i);return writeFileSync(join(k,'pack.json'),JSON['stringify'](s,null,0x2)+'\x0a'),d['push']('pack.json'),writeFileSync(join(k,'playbook.md'),playbookTemplate(i)),d['push']('playbook.md'),{'ok':!![],'layout':'merged','target':h,'restored_files':d,'errors':c};}catch(t){return{'ok':![],'layout':n,'target':h,'restored_files':d,'errors':['pack\x20reset\x20failed:\x20'+t['message']]};}const o=j['split']('/')['slice'](-0x1)[0x0],p=j==='playbook.md',q=j['startsWith'](PERSONAE_DIR+'/')&&o['endsWith']('.json');if(n==='merged'){if(p)try{return writeFileSync(join(k,'playbook.md'),playbookTemplate(i)),d['push']('playbook.md'),{'ok':!![],'layout':n,'target':h,'restored_files':d,'errors':c};}catch(v){return{'ok':![],'layout':n,'target':h,'restored_files':d,'errors':['playbook\x20reset\x20failed:\x20'+v['message']]};}const u=LAYER_FILE_SECTION[j];if(u)try{const w=readMergedPackIfPresent(k)??buildPristineMergedPack(i);switch(u){case'match':w['match']=matchSection(i);break;case'dispute':w['dispute']=disputeSection(i);break;case'compliance':w['compliance']=complianceSection(i);break;case'supply':w['supply']=supplySection(i);break;case'rules':w['rules']=rulesSection(i);break;case'mode':w['mode']=null;break;}return writeFileSync(join(k,'pack.json'),JSON['stringify'](w,null,0x2)+'\x0a'),d['push']('pack.json'),{'ok':!![],'layout':n,'target':h,'restored_files':d,'errors':c};}catch(x){return{'ok':![],'layout':n,'target':h,'restored_files':d,'errors':['section\x20reset\x20failed:\x20'+x['message']]};}if(q){const y=o['replace'](/\.json$/,'');if(!PERSONA_ROLES['includes'](y))return{'ok':![],'layout':n,'target':h,'restored_files':[],'errors':['unknown\x20persona\x20role\x20\x27'+y+'\x27']};try{const z=readMergedPackIfPresent(k)??buildPristineMergedPack(i),A=z['personae']&&Array['isArray'](z['personae'])?[...z['personae']]:[],B=A['findIndex'](D=>D['role']===y),C=personaPerRole(y,i);if(B>=0x0)A[B]=C;else A['push'](C);return z['personae']=A,writeFileSync(join(k,'pack.json'),JSON['stringify'](z,null,0x2)+'\x0a'),d['push']('pack.json'),{'ok':!![],'layout':n,'target':h,'restored_files':d,'errors':c};}catch(D){return{'ok':![],'layout':n,'target':h,'restored_files':d,'errors':['persona\x20reset\x20failed:\x20'+D['message']]};}}if(j==='manifest.json'||j==='manifest')try{const E=readMergedPackIfPresent(k)??buildPristineMergedPack(i);return E['manifest']=manifestSection(i),writeFileSync(join(k,'pack.json'),JSON['stringify'](E,null,0x2)+'\x0a'),d['push']('pack.json'),{'ok':!![],'layout':n,'target':h,'restored_files':d,'errors':c};}catch(F){return{'ok':![],'layout':n,'target':h,'restored_files':d,'errors':['manifest\x20reset\x20failed:\x20'+F['message']]};}return{'ok':![],'layout':n,'target':h,'restored_files':[],'errors':['path\x20\x27'+j+'\x27\x20is\x20not\x20a\x20standard\x20section\x20file\x20of\x20pack\x20\x27'+i+'\x27.\x20Reset\x20is\x20only\x20provided\x20for\x20pack.json\x20standard\x20sections\x20and\x20playbook.md.']};}if(p)try{return writeFileSync(join(k,'playbook.md'),playbookTemplate(i)),d['push']('playbook.md'),{'ok':!![],'layout':n,'target':h,'restored_files':d,'errors':c};}catch(G){return{'ok':![],'layout':n,'target':h,'restored_files':d,'errors':['legacy\x20playbook\x20reset\x20failed:\x20'+G['message']]};}if(j==='manifest.json')try{const H=manifestSection(i);return writeFileSync(join(k,'manifest.json'),JSON['stringify'](H,null,0x2)+'\x0a'),d['push']('manifest.json'),{'ok':!![],'layout':n,'target':h,'restored_files':d,'errors':c};}catch(I){return{'ok':![],'layout':n,'target':h,'restored_files':d,'errors':['legacy\x20manifest\x20reset\x20failed:\x20'+I['message']]};}const r=LAYER_FILE_SECTION[j];if(r)try{let J='';switch(r){case'match':J=JSON['stringify'](matchSection(i),null,0x2)+'\x0a';break;case'dispute':J=JSON['stringify'](disputeSection(i),null,0x2)+'\x0a';break;case'compliance':J=JSON['stringify'](complianceSection(i),null,0x2)+'\x0a';break;case'supply':J=JSON['stringify'](supplySection(i),null,0x2)+'\x0a';break;case'rules':J=JSON['stringify'](rulesSection(i),null,0x2)+'\x0a';break;case'mode':J=JSON['stringify']({},null,0x2)+'\x0a';break;}return writeFileSync(join(k,j),J),d['push'](j),{'ok':!![],'layout':n,'target':h,'restored_files':d,'errors':c};}catch(K){return{'ok':![],'layout':n,'target':h,'restored_files':d,'errors':['legacy\x20section\x20reset\x20failed:\x20'+K['message']]};}if(q){const L=o['replace'](/\.json$/,'');if(!PERSONA_ROLES['includes'](L))return{'ok':![],'layout':n,'target':h,'restored_files':[],'errors':['unknown\x20persona\x20\x27'+L+'\x27']};try{return writeFileSync(join(k,j),JSON['stringify'](personaPerRole(L,i),null,0x2)+'\x0a'),d['push'](j),{'ok':!![],'layout':n,'target':h,'restored_files':d,'errors':c};}catch(M){return{'ok':![],'layout':n,'target':h,'restored_files':d,'errors':['legacy\x20persona\x20reset\x20failed:\x20'+M['message']]};}}return{'ok':![],'layout':n,'target':h,'restored_files':[],'errors':['cannot\x20reset\x20non-standard\x20file\x20\x27'+j+'\x27\x20in\x20legacy\x20layout.\x20Only\x20standard\x20layer\x20files,\x20personae/*.json,\x20manifest.json,\x20and\x20playbook.md\x20can\x20be\x20reset.']};}
@@ -1 +1 @@
1
- import{GOAL_TYPES}from'./types.js';export const GOAL_KEYWORD_RULES=[{'goal_type':'publish_service','keywords':['发布服务','开店','上线服务','开个店','开个点','出售服务','上架','publish\x20service','launch\x20service','open\x20store','open\x20a\x20store','open\x20shop','sell\x20service']},{'goal_type':'fulfill_order','keywords':['履约','交付订单','新订单','推进订单','处理订单','订单交付','fulfill','fulfil','deliver\x20order','new\x20order','process\x20order']},{'goal_type':'capture_demand','keywords':['需求机会','接单','有什么需求','找需求','需求匹配','capture\x20demand','opportunities','opportunity','demands\x20available','what\x20demands']},{'goal_type':'purchase_service','keywords':['购买服务','帮我买','帮我找','定制','下单','买个','buy','purchase','order\x20a\x20service','customize','custom-made']},{'goal_type':'collaborate_flow','keywords':['待办','我的节点','协作','员工','工作任务','my\x20tasks','pending\x20nodes','collaborate','my\x20node','todo']},{'goal_type':'supply_suborder','keywords':['子订单','应征','供应商','供货','sub-order','suborder','supplier','present']},{'goal_type':'publish_demand','keywords':['发布需求','找人做','悬赏','求人','publish\x20demand','post\x20demand','bounty','looking\x20for\x20someone']},{'goal_type':'run_arbitration','keywords':['仲裁业务','仲裁服务','经营仲裁','仲裁经营','arbitration\x20business','arbitrator','arbitration\x20service']},{'goal_type':'dispute_resolution','keywords':['争议','纠纷','投诉','申诉','维权','dispute','complaint','appeal']},{'goal_type':'manage_assets','keywords':['资产','资金','数据管理','盘点','权限盘点','权限管理','财务','治理','金库','treasury','assets','manage\x20funds','asset','inventory','permission\x20management','governance','fund\x20audit','withdraw']}];const ASCII_RE=/^[\x20-\x7e]+$/;function keywordWeight(a){return a['length']>=0x4?0x2:0x1;}function escapeRe(a){return a['replace'](/[.*+?^${}()|[\]\\]/g,'\x5c$&');}const boundaryCache=new Map();function keywordMatches(a,b){if(ASCII_RE['test'](a)){let c=boundaryCache['get'](a);return!c&&(c=new RegExp('\x5cb'+escapeRe(a)+'\x5cb','i'),boundaryCache['set'](a,c)),c['test'](b);}return b['includes'](a);}export function classifyGoal(a){const b=(a??'')['trim']()['toLowerCase'](),c={'goal_type':null,'confidence':0x0,'matched':[],'alternatives':[]};if(!b)return c;const d=[];for(const k of GOAL_KEYWORD_RULES){const l=[];let m=0x0;for(const n of k['keywords']){keywordMatches(n,b)&&(l['push'](n),m+=keywordWeight(n));}if(m>0x0)d['push']({'goal_type':k['goal_type'],'score':m,'matched':l});}if(d['length']===0x0)return c;let e=d[0x0];for(const o of d){if(o['score']>e['score'])e=o;}const f=d['reduce']((p,q)=>p+q['score'],0x0),g=e['score']/f,h=Math['min'](0x1,e['score']/0x3),i=Math['round'](g*h*0x3e8)/0x3e8,j=d['filter'](p=>p['goal_type']!==e['goal_type'])['sort']((p,q)=>q['score']-p['score'])['map'](({goal_type:p,score:q})=>({'goal_type':p,'score':q}));return{'goal_type':e['goal_type'],'confidence':i,'matched':e['matched'],'alternatives':j};}export{GOAL_TYPES};
1
+ import{GOAL_TYPES}from'./types.js';export const GOAL_KEYWORD_RULES=[{'goal_type':'publish_service','keywords':['publish\x20service','launch\x20service','open\x20store','open\x20a\x20store','open\x20shop','sell\x20service','list\x20service','start\x20selling','set\x20up\x20shop']},{'goal_type':'fulfill_order','keywords':['fulfill','fulfil','deliver\x20order','new\x20order','process\x20order','advance\x20order','order\x20delivery','handle\x20order']},{'goal_type':'capture_demand','keywords':['capture\x20demand','opportunities','opportunity','demands\x20available','what\x20demands','find\x20demand','demand\x20matching','take\x20orders']},{'goal_type':'purchase_service','keywords':['buy','purchase','order\x20a\x20service','customize','custom-made','buy\x20for\x20me','help\x20me\x20find','place\x20an\x20order']},{'goal_type':'collaborate_flow','keywords':['my\x20tasks','pending\x20nodes','collaborate','my\x20node','todo','to-do','collaboration','staff','work\x20task']},{'goal_type':'supply_suborder','keywords':['sub-order','suborder','supplier','present','apply\x20for\x20sub-order','supply\x20goods']},{'goal_type':'publish_demand','keywords':['publish\x20demand','post\x20demand','bounty','looking\x20for\x20someone','find\x20someone\x20to','need\x20someone']},{'goal_type':'run_arbitration','keywords':['arbitration\x20business','arbitrator','arbitration\x20service','run\x20arbitration','operate\x20arbitration']},{'goal_type':'dispute_resolution','keywords':['dispute','complaint','appeal','raise\x20a\x20dispute']},{'goal_type':'manage_assets','keywords':['treasury','assets','manage\x20funds','asset','inventory','permission\x20management','governance','fund\x20audit','withdraw','finance','financial','data\x20management','permission\x20audit']}];const ASCII_RE=/^[\x20-\x7e]+$/;function keywordWeight(a){return a['length']>=0x4?0x2:0x1;}function escapeRe(a){return a['replace'](/[.*+?^${}()|[\]\\]/g,'\x5c$&');}const boundaryCache=new Map();function keywordMatches(a,b){if(ASCII_RE['test'](a)){let c=boundaryCache['get'](a);return!c&&(c=new RegExp('\x5cb'+escapeRe(a)+'\x5cb','i'),boundaryCache['set'](a,c)),c['test'](b);}return b['includes'](a);}export function classifyGoal(a){const b=(a??'')['trim']()['toLowerCase'](),c={'goal_type':null,'confidence':0x0,'matched':[],'alternatives':[]};if(!b)return c;const d=[];for(const k of GOAL_KEYWORD_RULES){const l=[];let m=0x0;for(const n of k['keywords']){keywordMatches(n,b)&&(l['push'](n),m+=keywordWeight(n));}if(m>0x0)d['push']({'goal_type':k['goal_type'],'score':m,'matched':l});}if(d['length']===0x0)return c;let e=d[0x0];for(const o of d){if(o['score']>e['score'])e=o;}const f=d['reduce']((p,q)=>p+q['score'],0x0),g=e['score']/f,h=Math['min'](0x1,e['score']/0x3),i=Math['round'](g*h*0x3e8)/0x3e8,j=d['filter'](p=>p['goal_type']!==e['goal_type'])['sort']((p,q)=>q['score']-p['score'])['map'](({goal_type:p,score:q})=>({'goal_type':p,'score':q}));return{'goal_type':e['goal_type'],'confidence':i,'matched':e['matched'],'alternatives':j};}export{GOAL_TYPES};
@@ -1,4 +1,14 @@
1
1
  import type { Analyzer, Confidence, Finding, FindingKind, FindingSeverity, NodeAnalyzer, Retention, TopoNode, ViewerRole, Viewport } from "./types.js";
2
+ import type { NameResolver } from "./names.js";
3
+ export declare function findingWhere(f: {
4
+ id: string;
5
+ title?: string;
6
+ }): string;
7
+ export declare function findingWhereResolved(f: {
8
+ id: string;
9
+ title?: string;
10
+ }, names: NameResolver): string;
11
+ export declare const RETENTION_RANK: Record<Retention, number>;
2
12
  export declare function pathConfidence(v: Viewport, pathEdges: Array<{
3
13
  schema: string;
4
14
  from: string;
@@ -27,11 +37,14 @@ export declare function runAnalyzers(v: Viewport, opts?: {
27
37
  }): Finding[];
28
38
  export interface NodeRuleOutcome {
29
39
  severity?: FindingSeverity;
30
- titleZh: string;
31
- detailZh: string;
32
- suggestionZh: string;
40
+ title: string;
41
+ detail: string;
42
+ suggestion: string;
33
43
  roles?: ViewerRole[];
34
44
  confidence?: Confidence;
45
+ ruleId?: string;
46
+ evidence?: string;
47
+ nativeRisk?: unknown;
35
48
  }
36
49
  export interface NodeRuleBinding {
37
50
  id: string;
@@ -1 +1 @@
1
- import{detectFakeOrders,detectShellMerchant}from'./anti-cheat.js';import{orderCompletionInGraph}from'./expand.js';function root(a){const b=a?.['raw'],c=b?.['data']??b;return c&&typeof c==='object'?c:undefined;}function str(a){return typeof a==='string'&&a!=='0x0'?a:undefined;}function big(a){if(a==null)return 0x0n;try{return BigInt(typeof a==='number'?Math['trunc'](a):String(a));}catch{return 0x0n;}}function bool(a){return a===!![]||a===0x1||a==='1';}function asList(a){return Array['isArray'](a)?a:[];}function wfNodeName(a){const b=a['indexOf']('::node::');return b>=0x0?a['slice'](b+'::node::'['length']):a;}function wfMachineOf(a){const b=a['indexOf']('::node::');return b>=0x0?a['slice'](0x0,b):'';}function typedNodes(a,b){const c=[];for(const d of a['visibleNodes']){const e=a['graph']['nodes']['get'](d);if(e?.['kind']==='object'&&e['objectType']===b&&e['raw'])c['push'](e);}return c;}function edgeList(a,b){return a['visibleEdges']['filter'](c=>c['schema']===b);}function out(a,b,c){return a['visibleEdges']['filter'](d=>d['from']===b['toLowerCase']()&&d['schema']===c);}function inc(a,b,c){return a['visibleEdges']['filter'](d=>d['to']===b['toLowerCase']()&&d['schema']===c);}const RETENTION_RANK={'complete':0x0,'bounded_exact':0x1,'membership':0x1,'derived':0x2,'bounded_window':0x3},WINDOW_LIMIT=0x1450;export function pathConfidence(a,b){let c=0x0,d=![];for(const g of b){c=Math['max'](c,RETENTION_RANK[g['retention']]??0x0);if(g['retention']==='bounded_window'||g['truncated'])d=!![];}if(d){let h=0x0;for(const i of b){if(i['retention']!=='bounded_window'&&!i['truncated'])continue;const j=a['visibleEdges']['filter'](l=>l['schema']===i['schema']&&l['from']===i['from'])['length'];h=Math['max'](h,j);const k=a['graph']['truncations']['find'](l=>l['nodeId']===i['from']&&l['schema']===i['schema']);if(k)h=Math['max'](h,k['observed']);}return{'confidence':'windowed','window':{'observed':h||b['length'],'limit':WINDOW_LIMIT}};}const f=c===0x0?'exact':c===0x2?'derived':'bounded';return{'confidence':f};}function makeFinding(a,b,c,d,e){const {confidence:f,window:g}=pathConfidence(a,e['pathEdges']??[]);return{'id':b,'kind':c,'severity':e['severity']??'info','titleZh':d,'path':e['path'],'confidence':f,...g?{'window':g}:{},'roles':e['roles']??['neutral'],'detailZh':e['detailZh'],'suggestionZh':e['suggestionZh']};}const MAX_FINDINGS_PER_RULE=0x14,ROLE_OWNER_OR_ADMIN=0x1|0x2;export function buildControlIndex(a){const b=new Map(),c=new Map(),d=new Map(),f=(h,i,j)=>{const l=h['get'](i)??new Set();l['add'](j),h['set'](i,l);},g=new Map();for(const h of edgeList(a,'eoa.permission')){const i=typeof h['payload']?.['roleBits']==='number'?h['payload']['roleBits']:ROLE_OWNER_OR_ADMIN;if((i&ROLE_OWNER_OR_ADMIN)===0x0)continue;f(g,h['from'],h['to']);}for(const j of edgeList(a,'permission.core_binding')){const k=a['graph']['nodes']['get'](j['to']);if(!k||k['kind']!=='object')continue;f(d,j['to'],j['from']);for(const [l,m]of g){if(!m['has'](j['from']))continue;f(b,j['to'],l),f(c,l,j['to']);}}return{'controllers':b,'objectsByEoa':c,'permsOfObject':d};}function machineViews(a){const b=new Map();for(const d of edgeList(a,'wf.transition')){const f=wfMachineOf(d['from']);if(!f)continue;const g=b['get'](f)??[];g['push'](d),b['set'](f,g);}const c=[];for(const [h,i]of b){const j=a['graph']['nodes']['get'](h);if(!j||!a['visibleNodes']['has'](h))continue;const k=new Set([...(function*(){const l=new Set(i['map'](p=>String(p['payload']?.['node']??''))['filter'](Boolean)),o=new Set(i['map'](p=>String(p['payload']?.['prevNode']??''))['filter'](Boolean));for(const p of l)if(!o['has'](p))yield p;}())]);c['push']({'machine':j,'transitions':i,'terminals':k});}return c;}const ROLES_RISK_NEUTRAL_MERCHANT=['neutral','system','merchant'],R1={'id':'R1','kind':'risk','run'(b){const c=buildControlIndex(b),d=[],e=typedNodes(b,'Service'),f=typedNodes(b,'Arbitration');o:for(const g of e){const h=c['controllers']['get'](g['id']);if(!h)continue;for(const i of f){const j=c['controllers']['get'](i['id']);if(!j)continue;const k=c['permsOfObject']['get'](g['id']),l=c['permsOfObject']['get'](i['id']),m=[...k??[]]['some'](n=>l?.['has'](n));if(m)continue;for(const n of h){if(!j['has'](n))continue;d['push'](makeFinding(b,'R1:'+g['id']+':'+i['id']+':'+n,'risk','同裁风险:店铺与仲裁服务受同一实控\x20EOA\x20支配',{'severity':'high','path':[n,'eoa.permission','permission.core_binding',g['id'],i['id']],'pathEdges':edgeList(b,'permission.core_binding'),'roles':['neutral','system','merchant','arbitrator'],'detailZh':'EOA\x20'+n+'\x20同时以\x20owner/admin\x20身份控制\x20Service\x20'+g['id']+'\x20与\x20Arbitration\x20'+i['id']+','+'且二者挂接在不同\x20Permission\x20下(E33\x20只禁止同一\x20Permission,未禁跨组同裁)。'+'该\x20EOA\x20在结构上可以同时影响被裁店铺与裁决结果。','suggestionZh':'核查该\x20EOA\x20的实控关系;要求店铺与仲裁服务的\x20owner/admin\x20集合互不相交,或将该仲裁服务移出可选列表。'}));if(d['length']>=MAX_FINDINGS_PER_RULE)break o;}}}return d;}},R2={'id':'R2','kind':'risk','run'(a){const b=[];for(const c of typedNodes(a,'Service')){const f=root(c),g=out(a,c['id'],'service.order');if(g['length']===0x0)continue;let h=0x0n,i=0x0;for(const l of g){const m=root(a['graph']['nodes']['get'](l['to']));if(!m)continue;h+=big(m['amount']),i++;}if(i===0x0)continue;const j=big(f['compensation_fund']),k=h*0x3n;if(j>=k)continue;b['push'](makeFinding(a,'R2:'+c['id'],'risk','赔付敞口:补偿基金低于窗口订单额的\x203\x20倍上限',{'severity':j<h?'high':'medium','path':[c['id'],'service.order','Order.amount','Service.compensation_fund'],'pathEdges':g,'roles':['neutral','system','merchant','buyer'],'detailZh':'补偿基金\x20'+j+'\x20基准单位,窗口内\x20'+i+'\x20笔订单金额合计\x20'+h+','+('法定赔付封顶为单笔\x203×amount\x20的结构总敞口\x20'+k+'(arb.move:302-321)。'),'suggestionZh':'补足\x20compensation_fund\x20至窗口金额\x203\x20倍以上,或在窗口内降低未结订单规模。'}));if(b['length']>=MAX_FINDINGS_PER_RULE)break;}return b;}},CONTROL_TYPES=new Set(['Service','Machine','Treasury']),CONTROL_FANOUT_ALERT=0x3,R3={'id':'R3','kind':'risk','run'(a){const b=buildControlIndex(a),c=[];for(const [d,e]of b['objectsByEoa']){const f=[...e]['filter'](i=>CONTROL_TYPES['has'](a['graph']['nodes']['get'](i)?.['objectType']??''));if(f['length']<CONTROL_FANOUT_ALERT)continue;const g=f['filter'](i=>a['graph']['nodes']['get'](i)?.['objectType']==='Service'),h=g['reduce']((i,j)=>i+out(a,j,'service.order')['length'],0x0);c['push'](makeFinding(a,'R3:'+d,'risk','权限集中:单个\x20EOA\x20控制多个经营核心对象',{'severity':f['length']>=0x5?'medium':'low','path':[d,'eoa.permission','permission.core_binding'],'pathEdges':edgeList(a,'eoa.permission')['concat'](edgeList(a,'permission.core_binding')),'roles':ROLES_RISK_NEUTRAL_MERCHANT,'detailZh':'EOA\x20'+d+'\x20通过\x20owner/admin\x20权限控制\x20'+f['length']+'\x20个\x20Service/Machine/Treasury\x20对象'+('(其中\x20Service\x20'+g['length']+'\x20个,窗口内可见订单\x20'+h+'\x20笔),经营规模与权限分散度不匹配。'),'suggestionZh':'将日常运营权限下放给独立\x20admin/entity\x20角色,owner\x20仅保留紧急处置;核心对象避免同组挂接。'}));if(c['length']>=MAX_FINDINGS_PER_RULE)break;}return c;}},R4={'id':'R4','kind':'risk','run'(a){const b=[];p:for(const c of machineViews(a)){const d=new Map();for(const g of c['transitions']){if(!c['terminals']['has'](String(g['payload']?.['node']??'')))continue;const h=g['from']+'→'+g['to'],i=d['get'](h)??[];i['push'](g),d['set'](h,i);}for(const [j,k]of d){const l=new Set();let m=![];for(const n of k){if(str(n['payload']?.['namedOperator']))l['add']('name:'+n['payload']['namedOperator']);if(typeof n['payload']?.['permissionIndex']==='number')l['add']('perm:'+n['payload']['permissionIndex']);if(str(n['payload']?.['guard']))m=!![];}if(l['size']===0x1&&!m){const o=[...l][0x0];b['push'](makeFinding(a,'R4:'+c['machine']['id']+':'+j,'risk','流程单点:终态前\x20Forward\x20仅唯一操作方且无替补\x20Guard',{'severity':'medium','path':[c['machine']['id'],'machine.node','wf.transition',j],'pathEdges':k,'roles':['neutral','system','merchant','collaborator'],'detailZh':'Machine\x20'+c['machine']['id']+'\x20进入终态\x20'+wfNodeName(k[0x0]['to'])+'\x20的路径\x20'+j+'\x20上,'+('唯一可执行操作方为\x20'+o+',且所有\x20Forward\x20均无\x20guard\x20兜底;该操作方离线即流程卡死。'),'suggestionZh':'为该\x20Forward\x20增加\x20permissionIndex\x20备选或挂接\x20guard\x20自动推进条件,避免单人阻断终态。'}));if(b['length']>=MAX_FINDINGS_PER_RULE)break p;}}}return b;}},R5={'id':'R5','kind':'risk','run'(a){const b=[],c=new Set();for(const d of a['graph']['truncations']){if(!a['visibleNodes']['has'](d['nodeId']))continue;const e=d['nodeId']+'|'+d['schema'];if(c['has'](e))continue;c['add'](e),b['push']({'id':'R5:'+e,'kind':'risk','severity':'info','titleZh':'窗口截断:相关结论仅为\x20≤5200\x20FIFO/环形窗口内下界','path':[d['nodeId'],d['schema']],'confidence':'windowed','window':{'observed':d['observed'],'limit':d['limit']??WINDOW_LIMIT},'roles':['neutral','system','merchant','buyer','supplier','arbitrator','collaborator'],'detailZh':'节点\x20'+d['nodeId']+'\x20的\x20'+d['schema']+'\x20扇出被截断(已观测\x20'+d['observed']+',窗口上限\x20'+(d['limit']??WINDOW_LIMIT)+');'+'依赖该路径的任何结论都必须表述为\x22窗口内/至少\x22,不得当作全量真值。','suggestionZh':'需要全量结论时改走事件通道(channel\x20D)或在预算内放大\x20perKindCaps。'});if(b['length']>=MAX_FINDINGS_PER_RULE)break;}return b;}},R6={'id':'R6','kind':'risk','run'(a){const b=[];for(const c of typedNodes(a,'Service')){const e=root(c);if(!bool(e['bPublished']))continue;if(big(e['setting_lock_duration'])!==0x0n)continue;b['push'](makeFinding(a,'R6:'+c['id'],'risk','设置锁缺失:已发布\x20Service\x20的\x20setting_lock_duration=0',{'severity':'medium','path':[c['id'],'Service.setting_lock_duration'],'roles':ROLES_RISK_NEUTRAL_MERCHANT['concat']('buyer'),'detailZh':'Service\x20'+c['id']+'\x20已发布但\x20setting_lock_duration=0:order_allocators\x20/\x20rewards\x20/\x20arbitrations\x20/\x20machine\x20'+'与\x20compensation_fund\x20提现可被即时修改(默认锁为\x2030\x20天,service.move:38),买家面对的是可瞬变条款。','suggestionZh':'发布后设置\x20setting_lock_duration(30\x20天=2592000000\x20毫秒起),条款变更必须经过等待期。'}));if(b['length']>=MAX_FINDINGS_PER_RULE)break;}return b;}},RATE_BASIS=0x2710n;function allocationStructuralIssues(a){const b=[];let c=0x0,d=![];for(const e of asList(a)){const f=e??{};let g=0x0n,h=![];for(const i of asList(f['sharing'])){const j=i??{},k=Number(j['mode']);if(k===0x2||j['mode']==='Surplus'){c++,d=!![];continue;}k===0x1||j['mode']==='Rate'?g+=big(j['sharing']):h=!![];}g!==0x0n&&g!==RATE_BASIS&&!d&&b['push']('存在\x20Rate\x20分账合计\x20'+g+'\x20≠\x2010000\x20基点且无\x20Surplus\x20兜底,支付时将中止'),h&&(f['max']==null||big(f['max'])===0x0n)&&b['push']('定额(Amount)分账\x20Allocator\x20缺少\x20max\x20上限,guard\x20触发时存在超额划出空间');}if(c>0x1)b['push']('Surplus\x20条目\x20'+c+'\x20个(合法至多\x201\x20个),多余收益归属不确定');return[...new Set(b)];}const A1={'id':'A1','kind':'arbitrage','run'(a){const b=[],c=(e,f,g,h)=>{const i=allocationStructuralIssues(f);if(i['length']===0x0||h['has'](e))return;h['add'](e),b['push'](makeFinding(a,'A1:'+e,'arbitrage','分账结构错配:Rate/Surplus/max\x20配置存在可被触发的结构性问题',{'severity':'medium','path':[e,'allocators[].sharing'],'pathEdges':g,'roles':['neutral','system','merchant','buyer'],'detailZh':e+':'+i['join'](';')+'(allocation.move:173-200)。','suggestionZh':'Rate\x20组补齐至\x2010000\x20或配置唯一\x20Surplus;定额\x20Allocator\x20必须设置\x20max;上线前用分账预检工具回归。'}));},d=new Set();for(const e of typedNodes(a,'Allocation')){c(e['id'],root(e)['allocators'],inc(a,e['id'],'order.allocation'),d);}for(const f of typedNodes(a,'Service')){const g=root(f)['order_allocators'];if(g?.['allocators'])c(f['id'],g['allocators'],edgeList(a,'service.order_allocator_guard'),d);}return b['slice'](0x0,MAX_FINDINGS_PER_RULE);}},DISCOUNT_FIXED=0x1,THIRTY_DAYS_MS=0x1en*0x18n*0x3cn*0x3cn*0x3e8n,A2={'id':'A2','kind':'arbitrage','run'(a){const b=[];for(const c of typedNodes(a,'Discount')){const e=root(c),f=big(e['time_end'])-big(e['time_start'])>=THIRTY_DAYS_MS;if(!bool(e['transferable'])||!f)continue;if(Number(e['discount_type'])!==DISCOUNT_FIXED)continue;if(e['benchmark']!=null&&e['benchmark']!=='0')continue;b['push'](makeFinding(a,'A2:'+c['id'],'arbitrage','折扣组合:可转让\x20+\x20宽时间窗\x20+\x20无\x20benchmark\x20固定额折扣',{'severity':'low','path':[c['id'],'Discount.transferable/time_window/benchmark'],'roles':['neutral','system','merchant'],'detailZh':'Discount\x20'+c['id']+'\x20可转让、有效期\x20≥30\x20天、为固定额折扣且无\x20benchmark\x20价格校验(service.move:109-121),'+'存在囤券与转手套利空间。','suggestionZh':'缩短有效期、改为\x20RATES\x20比例折扣或增加\x20benchmark\x20\x20Guards;必要时关闭\x20transferable。'}));if(b['length']>=MAX_FINDINGS_PER_RULE)break;}return b;}},A3={'id':'A3','kind':'arbitrage','run'(a){const b=[];for(const e of typedNodes(a,'Arbitration')){const f=root(e),g=big(f['fee'])===0x0n&&!str(f['usage_guard']);g&&b['push'](makeFinding(a,'A3:'+e['id'],'arbitrage','救济成本结构:零费用\x20+\x20无使用门槛,恶意纠纷具备正期望结构条件',{'severity':'medium','path':[e['id'],'Arbitration.fee','Arbitration.usage_guard'],'roles':['neutral','system','arbitrator','merchant','buyer'],'detailZh':'Arbitration\x20'+e['id']+'\x20的\x20fee=0\x20且\x20usage_guard\x20为空;叠加赔付封顶\x203×amount、单次\x20claim、'+'30\x20天提现锁等规则(arb.move:302-358,\x20order.move:86-96),恶意发起纠纷在结构上无需前置成本。','suggestionZh':'设置非零\x20fee\x20覆盖裁决成本,或用\x20usage_guard\x20要求纠纷方持有链上参与凭证。'}));if(b['length']>=MAX_FINDINGS_PER_RULE)break;}const c=new Map();for(const h of a['visibleNodes']){const i=a['graph']['nodes']['get'](h),j=i?.['raw']?.['type_raw'];if(typeof j!=='string'||!j['includes']('::payment::CoinWrapper<'))continue;const k=j['slice'](j['indexOf']('<')+0x1,j['lastIndexOf']('>'))['trim'](),l=c['get'](k)??[];l['push'](h),c['set'](k,l);}if(c['size']>0x0){const m=[...c['keys']()]['sort']();b['push']({'id':'A3:coinwrapper','kind':'arbitrage','severity':'info','titleZh':'跨币托管审查点:图中存在\x20CoinWrapper<K>\x20托管对象','path':['payment::CoinWrapper'],'confidence':'exact','roles':['neutral','system','arbitrator','merchant'],'detailZh':'可见\x20CoinWrapper\x20托管覆盖币种:'+m['join'](',\x20')+'(对象数\x20'+[...c['values']()]['reduce']((o,p)=>o+p['length'],0x0)+')。'+'v1\x20不做行情估值;涉及救济/分账时须人工审查币种错配与脱锚风险。','suggestionZh':'核对托管币种与服务币种\x20T\x20是否一致;跨币场景补充独立汇率/预言机证据后再下结论。'});}return b['slice'](0x0,MAX_FINDINGS_PER_RULE);}},SCARCE_PRESENTERS=0x2;function demandGuardIds(a,b){const c=new Set();for(const d of out(a,b,'demand.guard'))c['add'](d['to']);return c;}function serviceGuardIds(a,b){const c=new Set();for(const f of out(a,b['id'],'service.buy_guard'))c['add'](f['to']);const d=out(a,b['id'],'service.machine')[0x0]?.['to'];if(d)for(const g of a['visibleEdges']){if(g['schema']==='wf.forward_guard'&&g['from']['startsWith'](d+'::node::'))c['add'](g['to']);}return c;}const O1={'id':'O1','kind':'opportunity','run'(a){const b=[],c=typedNodes(a,'Service');for(const d of typedNodes(a,'Demand')){const e=out(a,d['id'],'demand.presenter');if(e['length']>=SCARCE_PRESENTERS)continue;const f=demandGuardIds(a,d['id']),g=[];for(const i of c){const j=serviceGuardIds(a,i);if(f['size']===0x0||[...f]['every'](k=>j['has'](k)))g['push'](i['id']);}const h=e;b['push'](makeFinding(a,'O1:'+d['id'],'opportunity','开放需求:提案稀缺,存在结构能力匹配的供应方',{'severity':'info','path':[d['id'],'demand.presenter','demand.guard','Service'],'pathEdges':h['concat'](out(a,d['id'],'demand.guard')),'roles':['neutral','system','supplier'],'detailZh':'Demand\x20'+d['id']+'\x20当前仅\x20'+e['length']+'\x20个提案;按\x20Guard\x20结构(不解析\x20Guard\x20字节码)匹配到\x20'+(g['length']+'\x20个候选\x20Service:'+(g['slice'](0x0,0x5)['join'](',\x20')||'(图内无匹配)')+'。'),'suggestionZh':'候选供方可准备\x20present\x20证据(需求\x20Guards\x20的可通过性证明);机会结论为结构性,不构成履约能力背书。'}));if(b['length']>=MAX_FINDINGS_PER_RULE)break;}return b;}},O2={'id':'O2','kind':'opportunity','run'(a){const b=typedNodes(a,'Service'),c=typedNodes(a,'Demand');if(b['length']===0x0&&c['length']===0x0)return[];const d=b['filter'](f=>bool(root(f)['bPublished'])&&!bool(root(f)['bPaused']))['length'],e=c['filter'](f=>out(a,f['id'],'demand.presenter')['length']===0x0)['length'];return[makeFinding(a,'O2:graph','opportunity','供需密度:图内供应/开放需求统计',{'path':['Service','Demand','demand.presenter'],'pathEdges':edgeList(a,'demand.presenter'),'roles':['neutral','system','supplier','merchant'],'detailZh':'当前视角内\x20Service\x20'+b['length']+'\x20个(已发布未暂停\x20'+d+'),Demand\x20'+c['length']+'\x20个'+('(无提案的开放需求\x20'+e+')。开放需求/活跃供应比\x20=\x20')+((d>0x0?(e/d)['toFixed'](0x3):'n/a')+'。'),'suggestionZh':'比值偏高说明供给稀缺;结合类目精确匹配数(collectors\x20category_enumerated_count)判断切入品类。'})];}},O3={'id':'O3','kind':'opportunity','run'(a){const b=[];for(const c of machineViews(a)){const d=new Map();for(const g of c['transitions']){if(str(g['payload']?.['namedOperator'])||g['payload']?.['permissionIndex']!=null)continue;const h=String(g['payload']?.['forward']??g['payload']?.['prevNode']+'→'+g['payload']?.['node']);d['set'](wfNodeName(g['from'])+':'+h,g);}if(d['size']===0x0)continue;const f=[...d['values']()];b['push'](makeFinding(a,'O3:'+c['machine']['id'],'opportunity','流程空位:关键\x20Forward\x20无操作方绑定(仅\x20guard/付款方直通)',{'path':[c['machine']['id'],'machine.node','wf.transition'],'pathEdges':f,'roles':['neutral','system','supplier','collaborator','merchant'],'detailZh':'Machine\x20'+c['machine']['id']+'\x20有\x20'+d['size']+'\x20个\x20Forward\x20无\x20namedOperator/permissionIndex\x20绑定:'+([...d['keys']()]['slice'](0x0,0x8)['join'](',\x20')+'。这些位点只能由\x20guard\x20自动满足或付款交易直接推进。'),'suggestionZh':'供应方/协作者可承接这些位点的操作职责,或推动商家把隐式直通改为显式角色绑定。'}));if(b['length']>=MAX_FINDINGS_PER_RULE)break;}return b;}};function arbitrationCases(a,b){return inc(a,b,'arb.arbitration_service')['map'](c=>a['graph']['nodes']['get'](c['from']))['filter'](c=>!!c&&c['objectType']==='Arb'&&!!c['raw']);}const G1={'id':'G1','kind':'game','run'(a){const b=[];for(const e of typedNodes(a,'Arbitration')){const f=root(e),g=asList(f['voting_guard']),h=new Set(g['map'](l=>l['vote_weight']&&typeof l['vote_weight']==='object'?Object['keys'](l['vote_weight'])[0x0]:'unknown')),i=arbitrationCases(a,e['id']),j=new Map();let k=0x0;for(const l of i){for(const m of asList(root(l)['voted'])){const n=Number(m['weight']??0x0);j['set'](n,(j['get'](n)??0x0)+0x1),k++;}}b['push'](makeFinding(a,'G1:'+e['id'],'game','投票权结构:仲裁投票\x20Guard\x20配置与实际投票权重分布',{'severity':'info','path':[e['id'],'arbitration.voting_guard','arb.arbitration_service','arb.voter'],'pathEdges':out(a,e['id'],'arbitration.voting_guard')['concat'](edgeList(a,'arb.voter')),'roles':['neutral','system','arbitrator','merchant','buyer'],'detailZh':'Arbitration\x20'+e['id']+':voting_guard\x20'+(g['length']===0x0?'为空=全员可投(arbitration.move:48-59)':'权重制('+[...h]['join']('/')+')')+';'+('窗口内案件\x20'+i['length']+'\x20个、实际投票\x20'+k+'\x20人次')+(j['size']?',权重分布\x20'+[...j['entries']()]['map'](([o,p])=>'w'+o+'×'+p)['join'](',\x20'):'')+'。','suggestionZh':'全员可投适合低标的高频场景;高标的应使用权重\x20Guard;该结论只描述客观局面,打分由博弈模块完成。'}));if(b['length']>=MAX_FINDINGS_PER_RULE)break;}return b;}},G2={'id':'G2','kind':'game','run'(a){const b=[];n:for(const c of machineViews(a)){const d=out(a,c['machine']['id'],'machine.permission')[0x0]?.['to'],f=d?inc(a,d,'permission.entity')['map'](h=>({'eoa':h['to'],'bits':h['payload']?.['permIndices']??[]})):[],g=new Set();for(const h of c['transitions']){const i=String(h['payload']?.['forward']??h['payload']?.['prevNode']+'→'+h['payload']?.['node']),j=wfNodeName(h['from'])+':'+i;if(g['has'](j))continue;let k,l='';if(str(h['payload']?.['namedOperator']))k=0x1,l='namedOperator='+h['payload']['namedOperator'];else{if(h['payload']?.['permissionIndex']!=null){if(!d)continue;const m=Number(h['payload']['permissionIndex']);k=f['filter'](n=>n['bits']['includes'](m))['length'],l='permissionIndex='+m;if(k===0x0)continue;}else continue;}if(k!==0x1)continue;g['add'](j),b['push'](makeFinding(a,'G2:'+c['machine']['id']+':'+j,'game','操作权可替代池=1:敲竹杠位点',{'severity':'low','path':[c['machine']['id'],'machine.node','wf.transition',j],'pathEdges':[h],'roles':['neutral','system','collaborator','merchant','supplier'],'detailZh':'Machine\x20'+c['machine']['id']+'\x20的\x20Forward\x20'+j+'('+l+')可执行方池大小为\x201:'+'该方在流程节点上拥有不可替代的议价地位(machine.move\x20操作预检)。','suggestionZh':'增加同\x20permissionIndex\x20的备选实体或设置\x20namedOperator\x20候补;签订覆盖该位点的\x20SLA/惩罚条款。'}));if(b['length']>=MAX_FINDINGS_PER_RULE)break n;}}return b;}},G3={'id':'G3','kind':'game','run'(a){const b=[];for(const c of typedNodes(a,'Arbitration')){const e=root(c),f=asList(e['voting_guard']);b['push'](makeFinding(a,'G3:'+c['id'],'game','救济策略参数:收益/等待矩阵的结构化输入',{'severity':'info','path':[c['id'],'Arbitration.fee/usage_guard/voting_guard'],'roles':['neutral','system','arbitrator','merchant','buyer'],'detailZh':'Arbitration\x20'+c['id']+':fee='+big(e['fee'])+',usage_guard='+(str(e['usage_guard'])??'无')+',voting_guard='+f['length']+'\x20个。'+'全局结构常量:赔付封顶\x203×amount、补偿提现\x2030\x20天锁、赔付单次\x20claim、撤回/异议窗\x2030\x20天'+'(arb.move:302-358,\x20order.move:86-96)。','suggestionZh':'将上述参数作为\x20node-game/arbitration-game\x20的收益与等待矩阵输入;本分析器不打分、不排序。'}));if(b['length']>=MAX_FINDINGS_PER_RULE)break;}return b;}},ANTI_CHEAT_ROLES=['neutral','system','merchant','buyer'];function projectOrderEvidence(a,b){const c=[];for(const d of typedNodes(a,'Service')){const f=[...b['controllers']['get'](d['id'])??[]];if(f['length']===0x0)continue;for(const g of out(a,d['id'],'service.order')){const h=a['graph']['nodes']['get'](g['to']);if(!h||h['kind']!=='object'||h['objectType']!=='Order'||!h['raw'])continue;const i=out(a,h['id'],'order.builder')[0x0]?.['to'];if(!i)continue;const j=orderCompletionInGraph(a['graph'],h['id'])['status'],k=String(root(h)?.['amount']??0x0),l=out(a,h['id'],'order.allocation')[0x0]?.['to']??null;for(const m of f){c['push']({'service':d['id'],'id':h['id'],'buyer':i,'seller':m,'amount':k,'status':j,'allocation':l});}}}return c;}function orderCheatEdges(a){return edgeList(a,'service.order')['concat'](edgeList(a,'eoa.permission'))['concat'](edgeList(a,'permission.core_binding'));}function shortRefs(a){const b=a['slice'](0x0,0x5)['join']('、');return a['length']>0x5?b+'\x20等\x20'+a['length']+'\x20个对象':b;}const AC1={'id':'AC1','kind':'risk','run'(a){const b=projectOrderEvidence(a,buildControlIndex(a)),c=detectFakeOrders(b)['find'](e=>e['code']==='self_buy');if(!c)return[];const d=c['refs']??[];return[makeFinding(a,'AC1:'+d['join'](','),'risk','刷单嫌疑:窗口内订单买家即店铺实控\x20EOA(自买自卖)',{'severity':'high','path':['EOA','eoa.permission','permission.core_binding','Service','service.order','Order','order.builder'],'pathEdges':orderCheatEdges(a),'roles':ANTI_CHEAT_ROLES,'detailZh':'窗口内可见\x20'+d['length']+'\x20笔订单的买家\x20EOA\x20同时以\x20owner/admin\x20身份控制售出该订单的\x20Service'+('('+shortRefs(d)+'):买卖双方处于同一实控集合,资金体内循环,不构成真实竞争成交。'),'suggestionZh':'将该批订单剔除出销量/声誉统计,结合支付分账腿与时间窗复核;对该\x20Service\x20降低市场曝光与推荐权重。'})];}},AC2={'id':'AC2','kind':'risk','run'(a){const b=projectOrderEvidence(a,buildControlIndex(a)),c=detectFakeOrders(b)['find'](e=>e['code']==='reciprocal_loop');if(!c)return[];const d=c['refs']??[];return[makeFinding(a,'AC2:'+d['join'](','),'risk','对倒嫌疑:窗口内存在买卖角色互换的资金循环',{'severity':c['severity'],'path':['EOA-A','order.builder','Order@Service-B','service.order','EOA-B','order.builder','Order@Service-A'],'pathEdges':orderCheatEdges(a),'roles':ANTI_CHEAT_ROLES,'detailZh':'窗口内\x20'+d['length']+'\x20笔订单构成买卖互换:A\x20实控集合购买\x20B\x20的\x20Service,同时\x20B\x20实控集合购买\x20A\x20的\x20Service'+('('+shortRefs(d)+')。双向成交可能是互为捧场的资金对倒。'),'suggestionZh':'核查两个实控集合的关联关系(设备/权限/资金往来);对互购订单不计入有效竞争成交。'})];}},AC3={'id':'AC3','kind':'risk','run'(a){const b=projectOrderEvidence(a,buildControlIndex(a)),c=detectFakeOrders(b)['find'](e=>e['code']==='no_allocation');if(!c)return[];const d=c['refs']??[];return[makeFinding(a,'AC3:'+d['join'](','),'risk','无资金闭环:已完成的正额订单缺少\x20Allocation\x20分账对象',{'severity':c['severity'],'path':['Service','service.order','Order','order.allocation'],'pathEdges':orderCheatEdges(a),'roles':ANTI_CHEAT_ROLES,'detailZh':'窗口内\x20'+d['length']+'\x20笔已完成(完成态由\x20order-status\x20结构终结点集权威判定)且\x20amount>0\x20的订单没有\x20Allocation'+('('+shortRefs(d)+')。order.move\x20L130\x20规定正额订单必有分账路径,缺失意味着该“成交”无资金闭环证据。')+'零额订单不在此列(无资金流)。','suggestionZh':'复核订单原始支付记录;无支付凭证的完成订单不得计入声誉;排查无\x20Allocation\x20完成路径的合约入口。'})];}},SHELL_COPY={'shell_no_arbitration':{'titleZh':'空壳商家:已发布\x20Service\x20无仲裁绑定,争议无救济路径','detailZh':'Service\x20处于已发布状态但\x20arbitrations\x20为空:买家下单后没有可选仲裁服务,争议无法进入裁决流程。','suggestionZh':'发布前至少绑定一个与店铺\x20Permission\x20不同组的\x20Arbitration;无救济路径的店铺不应进入推荐。'},'shell_funded_no_arbitration':{'titleZh':'赔付资金悬空:补偿基金已充值但无\x20Arbitration,赔付无法裁决/发放','detailZh':'compensation_fund>0\x20却没有任何\x20Arbitration:触发赔付时无人可裁、无路径可发,充值只构成宣传假象。','suggestionZh':'先绑定仲裁服务再对外宣传赔付保障;市场侧应将“有基金无仲裁”标记为高危并限制曝光。'},'shell_no_machine':{'titleZh':'空壳商家:已发布\x20Service\x20未绑定\x20Machine,无结构化履约流程','detailZh':'Service\x20已发布但\x20machine\x20为空:没有冻结的工作流模板,交付与完成节点均无链上结构约束。','suggestionZh':'绑定并发布\x20Machine\x20后再开张;无工作流的已发布店铺仅适合现货即时交割类目。'}},AC4={'id':'AC4','kind':'risk','run'(a){const b=[];for(const c of typedNodes(a,'Service')){const e=root(c);if(!bool(e['bPublished']))continue;const f=e['arbitrations']!=null?asList(e['arbitrations'])['length']:out(a,c['id'],'service.arbitration')['length'],g=str(e['machine'])??out(a,c['id'],'service.machine')[0x0]?.['to']??null,h=detectShellMerchant({'object':c['id'],'arbitrations':Array(f)['fill']('x'),'compensation_fund':String(big(e['compensation_fund'])),'machine':g,'bPublished':!![]}),i=out(a,c['id'],'service.arbitration')['concat'](out(a,c['id'],'service.machine'));for(const j of h){const k=SHELL_COPY[j['code']];if(!k)continue;b['push'](makeFinding(a,'AC4:'+c['id']+':'+j['code'],'risk',k['titleZh'],{'severity':j['severity'],'path':[c['id'],'Service.bPublished','Service.arbitrations','Service.machine','Service.compensation_fund'],'pathEdges':i,'roles':ANTI_CHEAT_ROLES,'detailZh':k['detailZh']+'(对象:'+c['id']+')','suggestionZh':k['suggestionZh']}));if(b['length']>=MAX_FINDINGS_PER_RULE)return b;}}return b;}};export const DEFAULT_ANALYZERS=[R1,R2,R3,R4,R5,R6,A1,A2,A3,O1,O2,O3,G1,G2,G3,AC1,AC2,AC3,AC4];const registry=new Map(DEFAULT_ANALYZERS['map'](b=>[b['id'],b]));export function registerAnalyzer(a){registry['set'](a['id'],a);}export function getAnalyzer(a){return registry['get'](a);}export function listAnalyzers(){return[...registry['keys']()];}export function runAnalyzers(a,b){const c=b?.['only']?new Set(b['only']):undefined,d=[];for(const e of registry['values']()){if(c&&!c['has'](e['id']))continue;if(b?.['kinds']&&!b['kinds']['includes'](e['kind']))continue;try{d['push'](...e['run'](a));}catch{}}return d;}export function adaptNodeAnalyzer(a){return{'id':a['id'],'kind':a['kind'],'objectType':a['objectType'],'run'(b,c){const d=a['inspect'](b,c);return d['map']((e,f)=>({'id':a['id']+':'+b['id']+'#'+f,'kind':a['kind'],'severity':e['severity']??'info','titleZh':e['titleZh'],'path':[b['id']],'confidence':e['confidence']??'exact','roles':e['roles']??['neutral'],'detailZh':e['detailZh'],'suggestionZh':e['suggestionZh']}));}};}export function runNodeAnalyzers(a,b){const c=[];for(const d of b){for(const e of typedNodes(a,d['objectType'])){try{c['push'](...d['run'](e,a));}catch{}}}return c;}
1
+ import{detectFakeOrders,detectShellMerchant}from'./anti-cheat.js';import{orderCompletionInGraph}from'./expand.js';import{PROPOSAL_GAP_ANALYZER}from'./proposal-graph.js';function root(a){const b=a?.['raw'],c=b?.['data']??b;return c&&typeof c==='object'?c:undefined;}function str(a){return typeof a==='string'&&a!=='0x0'?a:undefined;}function big(a){if(a==null)return 0x0n;try{return BigInt(typeof a==='number'?Math['trunc'](a):String(a));}catch{return 0x0n;}}function bool(a){return a===!![]||a===0x1||a==='1';}function asList(a){return Array['isArray'](a)?a:[];}function wfNodeName(a){const b=a['indexOf']('::node::');return b>=0x0?a['slice'](b+'::node::'['length']):a;}function wfMachineOf(a){const b=a['indexOf']('::node::');return b>=0x0?a['slice'](0x0,b):'';}export function findingWhere(a){const b=a['id'];if(b['startsWith']('R4:')){const c=b['slice'](0x3),d=c['indexOf'](':'),e=d>=0x0?c['slice'](0x0,d):c,g=d>=0x0?c['slice'](d+0x1):'';return e+':\x20'+g['split']('→')['map'](h=>wfNodeName(h['trim']()))['join']('\x20→\x20');}if(b['startsWith']('R7:treasury:'))return'Treasury\x20'+b['slice']('R7:treasury:'['length']);if(b['startsWith']('R7:reward:'))return'Reward\x20'+b['slice']('R7:reward:'['length']);if(b['startsWith']('R2:'))return b['slice'](0x3);if(b['startsWith']('R5:')){const [h,i]=b['slice'](0x3)['split']('|');return wfNodeName(h??'')+'\x20('+(i??'window')+')';}return a['title']??a['id'];}export function findingWhereResolved(a,b){const c=a['id'];if(c['startsWith']('R4:')){const d=c['slice'](0x3),e=d['indexOf'](':'),g=e>=0x0?d['slice'](0x0,e):d,h=e>=0x0?d['slice'](e+0x1):'',i=b['resolve'](g)['label'],j=l=>b['resolveWf'](l)?.['node']['label']??b['resolve'](l)['label'],k=h['split']('→')['map'](l=>j(l['trim']()))['join']('\x20→\x20');return i+':\x20'+k;}if(c['startsWith']('R7:treasury:'))return'Treasury\x20'+b['resolve'](c['slice']('R7:treasury:'['length']))['label'];if(c['startsWith']('R7:reward:'))return'Reward\x20'+b['resolve'](c['slice']('R7:reward:'['length']))['label'];if(c['startsWith']('R2:'))return b['resolve'](c['slice'](0x3))['label'];if(c['startsWith']('R5:')){const [l,m]=c['slice'](0x3)['split']('|');return b['resolve'](l??'')['label']+'\x20('+(m??'window')+')';}return a['title']??a['id'];}function typedNodes(a,b){const c=[];for(const d of a['visibleNodes']){const e=a['graph']['nodes']['get'](d);if(e?.['kind']==='object'&&e['objectType']===b&&e['raw']&&!e['proposal'])c['push'](e);}return c;}function edgeList(a,b){return a['visibleEdges']['filter'](c=>c['schema']===b);}function out(a,b,c){return a['visibleEdges']['filter'](d=>d['from']===b['toLowerCase']()&&d['schema']===c);}function inc(a,b,c){return a['visibleEdges']['filter'](d=>d['to']===b['toLowerCase']()&&d['schema']===c);}export const RETENTION_RANK={'complete':0x0,'event_full':0x0,'bounded_exact':0x1,'membership':0x1,'derived':0x2,'bounded_window':0x3,'event_degraded':0x3};const WINDOW_LIMIT=0x1450;export function pathConfidence(a,b){let c=0x0,d=![];for(const g of b){c=Math['max'](c,RETENTION_RANK[g['retention']]??0x0);if(g['retention']==='bounded_window'||g['retention']==='event_degraded'||g['truncated'])d=!![];}if(d){let h=0x0;for(const i of b){if(i['retention']!=='bounded_window'&&!i['truncated'])continue;const j=a['visibleEdges']['filter'](l=>l['schema']===i['schema']&&l['from']===i['from'])['length'];h=Math['max'](h,j);const k=a['graph']['truncations']['find'](l=>l['nodeId']===i['from']&&l['schema']===i['schema']);if(k)h=Math['max'](h,k['observed']);}return{'confidence':'windowed','window':{'observed':h||b['length'],'limit':WINDOW_LIMIT}};}const f=c===0x0?'exact':c===0x2?'derived':'bounded';return{'confidence':f};}function makeFinding(a,b,c,d,e){const {confidence:f,window:g}=pathConfidence(a,e['pathEdges']??[]);return{'id':b,'kind':c,'severity':e['severity']??'info','title':d,'path':e['path'],'confidence':f,...g?{'window':g}:{},'roles':e['roles']??['neutral'],'detail':e['detail'],'suggestion':e['suggestion']};}const MAX_FINDINGS_PER_RULE=0x14,ROLE_OWNER_OR_ADMIN=0x1|0x2;export function buildControlIndex(a){const b=new Map(),c=new Map(),d=new Map(),f=(h,i,j)=>{const l=h['get'](i)??new Set();l['add'](j),h['set'](i,l);},g=new Map();for(const h of edgeList(a,'eoa.permission')){const i=typeof h['payload']?.['roleBits']==='number'?h['payload']['roleBits']:ROLE_OWNER_OR_ADMIN;if((i&ROLE_OWNER_OR_ADMIN)===0x0)continue;f(g,h['from'],h['to']);}for(const j of edgeList(a,'permission.core_binding')){const k=a['graph']['nodes']['get'](j['to']);if(!k||k['kind']!=='object')continue;f(d,j['to'],j['from']);for(const [l,m]of g){if(!m['has'](j['from']))continue;f(b,j['to'],l),f(c,l,j['to']);}}return{'controllers':b,'objectsByEoa':c,'permsOfObject':d};}function machineViews(a){const b=new Map();for(const d of edgeList(a,'wf.transition')){const f=wfMachineOf(d['from']);if(!f)continue;const g=b['get'](f)??[];g['push'](d),b['set'](f,g);}const c=[];for(const [h,i]of b){const j=a['graph']['nodes']['get'](h);if(!j||!a['visibleNodes']['has'](h))continue;const k=new Set([...(function*(){const l=new Set(i['map'](p=>String(p['payload']?.['node']??''))['filter'](Boolean)),o=new Set(i['map'](p=>String(p['payload']?.['prevNode']??''))['filter'](Boolean));for(const p of l)if(!o['has'](p))yield p;}())]);c['push']({'machine':j,'transitions':i,'terminals':k});}return c;}const ROLES_RISK_NEUTRAL_MERCHANT=['neutral','system','merchant'],R1={'id':'R1','kind':'risk','run'(b){const c=buildControlIndex(b),d=[],e=typedNodes(b,'Service'),f=typedNodes(b,'Arbitration');o:for(const g of e){const h=c['controllers']['get'](g['id']);if(!h)continue;for(const i of f){const j=c['controllers']['get'](i['id']);if(!j)continue;const k=c['permsOfObject']['get'](g['id']),l=c['permsOfObject']['get'](i['id']),m=[...k??[]]['some'](n=>l?.['has'](n));if(m)continue;for(const n of h){if(!j['has'](n))continue;d['push'](makeFinding(b,'R1:'+g['id']+':'+i['id']+':'+n,'risk','Same-controller\x20arbitration\x20risk:\x20the\x20service\x20and\x20the\x20arbitration\x20service\x20are\x20controlled\x20by\x20the\x20same\x20EOA',{'severity':'high','path':[n,'eoa.permission','permission.core_binding',g['id'],i['id']],'pathEdges':edgeList(b,'permission.core_binding'),'roles':['neutral','system','merchant','arbitrator'],'detail':'EOA\x20'+n+'\x20controls\x20both\x20Service\x20'+g['id']+'\x20and\x20Arbitration\x20'+i['id']+'\x20as\x20owner/admin,\x20'+'and\x20the\x20two\x20are\x20attached\x20to\x20DIFFERENT\x20Permissions\x20(E33\x20only\x20forbids\x20the\x20same\x20Permission,\x20not\x20cross-group\x20arbitration).\x20'+'structurally\x20this\x20EOA\x20can\x20influence\x20both\x20the\x20arbitrated\x20service\x20and\x20the\x20ruling\x20outcome.','suggestion':'Verify\x20the\x20EOA\x27s\x20control\x20relationships;\x20require\x20disjoint\x20owner/admin\x20sets\x20between\x20the\x20service\x20and\x20the\x20arbitration\x20service,\x20or\x20remove\x20that\x20arbitration\x20service\x20from\x20the\x20selectable\x20list.'}));if(d['length']>=MAX_FINDINGS_PER_RULE)break o;}}}return d;}},R2={'id':'R2','kind':'risk','run'(a){const b=[];for(const c of typedNodes(a,'Service')){const f=root(c),g=out(a,c['id'],'service.order');if(g['length']===0x0)continue;let h=0x0n,i=0x0;for(const l of g){const m=root(a['graph']['nodes']['get'](l['to']));if(!m)continue;h+=big(m['amount']),i++;}if(i===0x0)continue;const j=big(f['compensation_fund']),k=h*0x3n;if(j>=k)continue;b['push'](makeFinding(a,'R2:'+c['id'],'risk','Payout\x20exposure:\x20compensation\x20fund\x20is\x20below\x20the\x203x\x20ceiling\x20of\x20windowed\x20order\x20amounts',{'severity':j<h?'high':'medium','path':[c['id'],'service.order','Order.amount','Service.compensation_fund'],'pathEdges':g,'roles':['neutral','system','merchant','buyer'],'detail':'Compensation\x20fund\x20'+j+'\x20base\x20units;\x20'+i+'\x20windowed\x20orders\x20total\x20'+h+';\x20'+('the\x20per-order\x20statutory\x20payout\x20cap\x20of\x203x\x20amount\x20gives\x20a\x20structural\x20total\x20exposure\x20of\x20'+k+'\x20(arb.move:302-321).'),'suggestion':'Top\x20up\x20compensation_fund\x20to\x20more\x20than\x203x\x20the\x20windowed\x20amount,\x20or\x20reduce\x20open\x20order\x20volume\x20within\x20the\x20window.'}));if(b['length']>=MAX_FINDINGS_PER_RULE)break;}return b;}},CONTROL_TYPES=new Set(['Service','Machine','Treasury']),CONTROL_FANOUT_ALERT=0x3,R3={'id':'R3','kind':'risk','run'(a){const b=buildControlIndex(a),c=[];for(const [d,e]of b['objectsByEoa']){const f=[...e]['filter'](i=>CONTROL_TYPES['has'](a['graph']['nodes']['get'](i)?.['objectType']??''));if(f['length']<CONTROL_FANOUT_ALERT)continue;const g=f['filter'](i=>a['graph']['nodes']['get'](i)?.['objectType']==='Service'),h=g['reduce']((i,j)=>i+out(a,j,'service.order')['length'],0x0);c['push'](makeFinding(a,'R3:'+d,'risk','Permission\x20concentration:\x20a\x20single\x20EOA\x20controls\x20multiple\x20business-critical\x20objects',{'severity':f['length']>=0x5?'medium':'low','path':[d,'eoa.permission','permission.core_binding'],'pathEdges':edgeList(a,'eoa.permission')['concat'](edgeList(a,'permission.core_binding')),'roles':ROLES_RISK_NEUTRAL_MERCHANT,'detail':'EOA\x20'+d+'\x20controls\x20'+f['length']+'\x20Service/Machine/Treasury\x20objects\x20via\x20owner/admin\x20permissions\x20'+('('+g['length']+'\x20of\x20them\x20Services,\x20'+h+'\x20orders\x20visible\x20in\x20the\x20window);\x20business\x20scale\x20does\x20not\x20match\x20permission\x20dispersion.'),'suggestion':'Delegate\x20day-to-day\x20operations\x20to\x20dedicated\x20admin/entity\x20roles\x20and\x20keep\x20owner\x20for\x20emergencies\x20only;\x20avoid\x20attaching\x20core\x20objects\x20to\x20the\x20same\x20permission\x20group.'}));if(c['length']>=MAX_FINDINGS_PER_RULE)break;}return c;}},R4={'id':'R4','kind':'risk','run'(a){const b=[];p:for(const c of machineViews(a)){const d=new Map();for(const g of c['transitions']){if(!c['terminals']['has'](String(g['payload']?.['node']??'')))continue;const h=g['from']+'→'+g['to'],i=d['get'](h)??[];i['push'](g),d['set'](h,i);}for(const [j,k]of d){const l=new Set();let m=![];for(const n of k){if(str(n['payload']?.['namedOperator']))l['add']('name:'+n['payload']['namedOperator']);if(typeof n['payload']?.['permissionIndex']==='number')l['add']('perm:'+n['payload']['permissionIndex']);if(str(n['payload']?.['guard']))m=!![];}if(l['size']===0x1&&!m){const o=[...l][0x0];b['push'](makeFinding(a,'R4:'+c['machine']['id']+':'+j,'risk','Workflow\x20single\x20point:\x20the\x20only\x20Forward\x20before\x20a\x20terminal\x20state\x20has\x20a\x20single\x20operator\x20and\x20no\x20fallback\x20Guard',{'severity':'medium','path':[c['machine']['id'],'machine.node','wf.transition',j],'pathEdges':k,'roles':['neutral','system','merchant','collaborator'],'detail':'On\x20Machine\x20'+c['machine']['id']+',\x20path\x20'+j+'\x20toward\x20terminal\x20state\x20'+wfNodeName(k[0x0]['to'])+':\x20'+('the\x20only\x20operable\x20party\x20is\x20'+o+'\x20and\x20no\x20Forward\x20has\x20a\x20guard\x20fallback;\x20if\x20that\x20party\x20goes\x20offline\x20the\x20workflow\x20stalls.'),'suggestion':'Add\x20a\x20permissionIndex\x20alternative\x20or\x20attach\x20a\x20guard\x20auto-advance\x20condition\x20to\x20this\x20Forward\x20so\x20one\x20party\x20cannot\x20block\x20the\x20terminal\x20state.'}));if(b['length']>=MAX_FINDINGS_PER_RULE)break p;}}}return b;}},R5={'id':'R5','kind':'risk','run'(a){const b=[],c=new Set();for(const d of a['graph']['truncations']){if(!a['visibleNodes']['has'](d['nodeId']))continue;const e=d['nodeId']+'|'+d['schema'];if(c['has'](e))continue;c['add'](e),b['push']({'id':'R5:'+e,'kind':'risk','severity':'info','title':'Window\x20truncation:\x20affected\x20conclusions\x20are\x20lower\x20bounds\x20within\x20the\x20<=5200\x20FIFO/ring\x20window\x20only','path':[d['nodeId'],d['schema']],'confidence':'windowed','window':{'observed':d['observed'],'limit':d['limit']??WINDOW_LIMIT},'roles':['neutral','system','merchant','buyer','supplier','arbitrator','collaborator'],'detail':'Fanout\x20of\x20'+d['schema']+'\x20at\x20node\x20'+d['nodeId']+'\x20is\x20truncated\x20(observed\x20'+d['observed']+',\x20window\x20limit\x20'+(d['limit']??WINDOW_LIMIT)+');\x20'+'any\x20conclusion\x20relying\x20on\x20this\x20path\x20must\x20be\x20worded\x20as\x20\x22within\x20the\x20window\x20/\x20at\x20least\x22,\x20never\x20as\x20exhaustive\x20truth.','suggestion':'For\x20exhaustive\x20conclusions\x20switch\x20to\x20the\x20event\x20channel\x20(channel\x20D)\x20or\x20raise\x20perKindCaps\x20within\x20budget.'});if(b['length']>=MAX_FINDINGS_PER_RULE)break;}return b;}},R6={'id':'R6','kind':'risk','run'(a){const b=[];for(const c of typedNodes(a,'Service')){const e=root(c);if(!bool(e['bPublished']))continue;if(big(e['setting_lock_duration'])!==0x0n)continue;b['push'](makeFinding(a,'R6:'+c['id'],'risk','Missing\x20setting\x20lock:\x20published\x20Service\x20has\x20setting_lock_duration=0',{'severity':'medium','path':[c['id'],'Service.setting_lock_duration'],'roles':ROLES_RISK_NEUTRAL_MERCHANT['concat']('buyer'),'detail':'Service\x20'+c['id']+'\x20is\x20published\x20but\x20setting_lock_duration=0:\x20order_allocators\x20/\x20rewards\x20/\x20arbitrations\x20/\x20machine\x20'+'and\x20compensation_fund\x20withdrawals\x20can\x20be\x20changed\x20instantly\x20(default\x20lock\x20is\x2030\x20days,\x20service.move:38);\x20buyers\x20face\x20instantly\x20mutable\x20terms.','suggestion':'Set\x20setting_lock_duration\x20after\x20publishing\x20(30\x20days\x20=\x202592000000\x20ms\x20at\x20minimum);\x20term\x20changes\x20must\x20go\x20through\x20a\x20waiting\x20period.'}));if(b['length']>=MAX_FINDINGS_PER_RULE)break;}return b;}},OBJECT_USER_ROLES=['neutral','system','buyer','supplier'],R7={'id':'R7','kind':'risk','run'(a){const b=[];for(const c of typedNodes(a,'Treasury')){const d=asList(root(c)?.['external_withdraw_guard']);if(d['length']===0x0)continue;b['push'](makeFinding(a,'R7:treasury:'+c['id'],'risk','Object-user\x20CRITICAL:\x20Treasury\x20has\x20a\x20permission-free\x20external\x20release\x20path',{'severity':'critical','path':[c['id'],'Treasury.external_withdraw_guard'],'roles':OBJECT_USER_ROLES,'detail':'Treasury\x20'+c['id']+'\x20has\x20'+d['length']+'\x20external_withdraw_guard\x20entry/entries:\x20external_withdraw\x20needs\x20no\x20Treasury\x20'+'Permission\x20—\x20only\x20the\x20Guard\x27s\x20boolean\x20verdict\x20stands\x20between\x20an\x20external\x20caller\x20and\x20the\x20balance.\x20The\x20topology\x20performs\x20'+'no\x20Guard-bytecode\x20analysis,\x20so\x20the\x20Guard\x27s\x20strength\x20is\x20UNVERIFIABLE\x20here.\x20Move\x20truth\x20(protocol\x20140):\x20the\x20destination\x20is\x20'+'forced\x20to\x20the\x20transaction\x20sender\x20(abort\x20code\x2010\x20on\x20mismatch),\x20which\x20blocks\x20third-party\x20redirection\x20but\x20NOT\x20release\x20to\x20a\x20'+'caller\x20whose\x20transaction\x20satisfies\x20a\x20weak\x20Guard\x20(for\x20example,\x20a\x20constant-true\x20root\x20with\x20a\x20static\x20amount\x20slot).','suggestion':'Do\x20not\x20rely\x20on\x20or\x20transact\x20through\x20this\x20Treasury\x20until\x20the\x20owner\x20presents\x20the\x20full\x20Guard\x20definitions;\x20verify\x20the\x20predicate\x20'+'constrains\x20the\x20amount\x20slot;\x20require\x20a\x20testnet\x20regression\x20(recipient\x20!=\x20sender\x20must\x20abort\x20with\x20code\x2010).'}));if(b['length']>=MAX_FINDINGS_PER_RULE)break;}for(const e of typedNodes(a,'Reward')){const f=asList(root(e)?.['guards']);if(f['length']===0x0)continue;b['push'](makeFinding(a,'R7:reward:'+e['id'],'risk','Object-user\x20CRITICAL:\x20Reward\x20has\x20a\x20permission-free\x20claim\x20path\x20with\x20an\x20unverifiable\x20payout\x20slot',{'severity':'critical','path':[e['id'],'Reward.guards'],'roles':OBJECT_USER_ROLES,'detail':'Reward\x20'+e['id']+'\x20has\x20'+f['length']+'\x20claim\x20guard\x20entry/entries:\x20claim()\x20needs\x20no\x20Permission,\x20and\x20with\x20a\x20'+'Recipient::GuardIdentifier\x20entry\x20the\x20payout\x20address\x20is\x20read\x20from\x20the\x20claim-time\x20passport\x20submission.\x20Whether\x20that\x20slot\x20'+'is\x20constrained\x20is\x20decided\x20inside\x20the\x20Guard\x20predicate,\x20which\x20the\x20topology\x20cannot\x20verify\x20—\x20a\x20guard\x20that\x20passes\x20without\x20'+'constraining\x20the\x20recipient\x20slot\x20lets\x20any\x20passing\x20party\x20fill\x20the\x20slot\x20with\x20their\x20own\x20address\x20and\x20claim\x20the\x20pool.','suggestion':'Do\x20not\x20treat\x20the\x20reward\x20pool\x20as\x20sound\x20until\x20the\x20owner\x20presents\x20the\x20Guard\x20definitions;\x20verify\x20the\x20predicate\x20binds\x20the\x20'+'recipient\x20slot\x20(Signer/entity),\x20or\x20confirm\x20the\x20entries\x20use\x20Entity/Signer\x20recipients\x20that\x20do\x20not\x20depend\x20on\x20submitted\x20slots.'}));if(b['length']>=MAX_FINDINGS_PER_RULE)break;}return b;}},RATE_BASIS=0x2710n;function allocationStructuralIssues(a){const b=[];let c=0x0,d=![];for(const e of asList(a)){const f=e??{};let g=0x0n,h=![];for(const i of asList(f['sharing'])){const j=i??{},k=Number(j['mode']);if(k===0x2||j['mode']==='Surplus'){c++,d=!![];continue;}k===0x1||j['mode']==='Rate'?g+=big(j['sharing']):h=!![];}g!==0x0n&&g!==RATE_BASIS&&!d&&b['push']('Rate\x20allocation\x20totals\x20'+g+'\x20!=\x2010000\x20basis\x20points\x20with\x20no\x20Surplus\x20fallback;\x20payment\x20will\x20abort'),h&&(f['max']==null||big(f['max'])===0x0n)&&b['push']('Fixed-amount\x20(Amount)\x20allocation\x20Allocator\x20lacks\x20a\x20max\x20cap;\x20excess\x20transfer\x20is\x20possible\x20when\x20the\x20guard\x20triggers');}if(c>0x1)b['push'](c+'\x20Surplus\x20entries\x20(at\x20most\x201\x20is\x20legal);\x20surplus\x20ownership\x20is\x20ambiguous');return[...new Set(b)];}const A1={'id':'A1','kind':'arbitrage','run'(a){const b=[],c=(e,f,g,h)=>{const i=allocationStructuralIssues(f);if(i['length']===0x0||h['has'](e))return;h['add'](e),b['push'](makeFinding(a,'A1:'+e,'arbitrage','Allocation\x20structure\x20mismatch:\x20Rate/Surplus/max\x20configuration\x20has\x20triggerable\x20structural\x20defects',{'severity':'medium','path':[e,'allocators[].sharing'],'pathEdges':g,'roles':['neutral','system','merchant','buyer'],'detail':e+':\x20'+i['join'](';\x20')+'\x20(allocation.move:173-200).','suggestion':'Complete\x20Rate\x20groups\x20to\x2010000\x20or\x20configure\x20a\x20single\x20Surplus;\x20fixed-amount\x20Allocators\x20must\x20set\x20max;\x20run\x20the\x20allocation\x20precheck\x20before\x20going\x20live.'}));},d=new Set();for(const e of typedNodes(a,'Allocation')){c(e['id'],root(e)['allocators'],inc(a,e['id'],'order.allocation'),d);}for(const f of typedNodes(a,'Service')){const g=root(f)['order_allocators'];if(g?.['allocators'])c(f['id'],g['allocators'],edgeList(a,'service.order_allocator_guard'),d);}return b['slice'](0x0,MAX_FINDINGS_PER_RULE);}},DISCOUNT_FIXED=0x1,THIRTY_DAYS_MS=0x1en*0x18n*0x3cn*0x3cn*0x3e8n,A2={'id':'A2','kind':'arbitrage','run'(a){const b=[];for(const c of typedNodes(a,'Discount')){const e=root(c),f=big(e['time_end'])-big(e['time_start'])>=THIRTY_DAYS_MS;if(!bool(e['transferable'])||!f)continue;if(Number(e['discount_type'])!==DISCOUNT_FIXED)continue;if(e['benchmark']!=null&&e['benchmark']!=='0')continue;b['push'](makeFinding(a,'A2:'+c['id'],'arbitrage','Discount\x20combination:\x20transferable\x20+\x20long\x20validity\x20window\x20+\x20fixed-amount\x20discount\x20without\x20benchmark',{'severity':'low','path':[c['id'],'Discount.transferable/time_window/benchmark'],'roles':['neutral','system','merchant'],'detail':'Discount\x20'+c['id']+'\x20is\x20transferable,\x20valid\x20>=30\x20days,\x20is\x20a\x20fixed-amount\x20discount,\x20and\x20has\x20no\x20benchmark\x20price\x20check\x20(service.move:109-121);\x20'+'this\x20leaves\x20room\x20for\x20coupon\x20hoarding\x20and\x20resale\x20arbitrage.','suggestion':'Shorten\x20the\x20validity\x20window,\x20switch\x20to\x20RATES\x20proportional\x20discounts,\x20or\x20add\x20benchmark\x20Guards;\x20disable\x20transferable\x20if\x20needed.'}));if(b['length']>=MAX_FINDINGS_PER_RULE)break;}return b;}},A3={'id':'A3','kind':'arbitrage','run'(a){const b=[];for(const e of typedNodes(a,'Arbitration')){const f=root(e),g=big(f['fee'])===0x0n&&!str(f['usage_guard']);g&&b['push'](makeFinding(a,'A3:'+e['id'],'arbitrage','Remedy\x20cost\x20structure:\x20zero\x20fee\x20+\x20no\x20usage\x20gate\x20gives\x20malicious\x20disputes\x20a\x20positive-expected-value\x20setup',{'severity':'medium','path':[e['id'],'Arbitration.fee','Arbitration.usage_guard'],'roles':['neutral','system','arbitrator','merchant','buyer'],'detail':'Arbitration\x20'+e['id']+'\x20has\x20fee=0\x20and\x20an\x20empty\x20usage_guard;\x20combined\x20with\x20the\x203x\x20amount\x20payout\x20cap,\x20single\x20claim,\x20'+'and\x2030-day\x20withdrawal\x20lock\x20rules\x20(arb.move:302-358,\x20order.move:86-96),\x20filing\x20a\x20malicious\x20dispute\x20carries\x20no\x20structural\x20upfront\x20cost.','suggestion':'Set\x20a\x20non-zero\x20fee\x20to\x20cover\x20adjudication\x20cost,\x20or\x20use\x20usage_guard\x20to\x20require\x20disputing\x20parties\x20to\x20hold\x20on-chain\x20participation\x20credentials.'}));if(b['length']>=MAX_FINDINGS_PER_RULE)break;}const c=new Map();for(const h of a['visibleNodes']){const i=a['graph']['nodes']['get'](h),j=i?.['raw']?.['type_raw'];if(typeof j!=='string'||!j['includes']('::payment::CoinWrapper<'))continue;const k=j['slice'](j['indexOf']('<')+0x1,j['lastIndexOf']('>'))['trim'](),l=c['get'](k)??[];l['push'](h),c['set'](k,l);}if(c['size']>0x0){const m=[...c['keys']()]['sort']();b['push']({'id':'A3:coinwrapper','kind':'arbitrage','severity':'info','title':'Cross-coin\x20escrow\x20review\x20point:\x20CoinWrapper<K>\x20escrow\x20objects\x20exist\x20in\x20the\x20graph','path':['payment::CoinWrapper'],'confidence':'exact','roles':['neutral','system','arbitrator','merchant'],'detail':'Visible\x20CoinWrapper\x20escrow\x20covers\x20coin\x20types:\x20'+m['join'](',\x20')+'\x20('+[...c['values']()]['reduce']((o,p)=>o+p['length'],0x0)+'\x20objects).\x20'+'v1\x20performs\x20no\x20market\x20valuation;\x20remedy/allocation\x20conclusions\x20across\x20coins\x20require\x20manual\x20review\x20of\x20coin\x20mismatch\x20and\x20depeg\x20risk.','suggestion':'Verify\x20the\x20escrow\x20coin\x20type\x20matches\x20the\x20service\x20coin\x20type\x20T;\x20add\x20independent\x20exchange-rate/oracle\x20evidence\x20before\x20concluding\x20cross-coin\x20cases.'});}return b['slice'](0x0,MAX_FINDINGS_PER_RULE);}},SCARCE_PRESENTERS=0x2;function demandGuardIds(a,b){const c=new Set();for(const d of out(a,b,'demand.guard'))c['add'](d['to']);return c;}function serviceGuardIds(a,b){const c=new Set();for(const f of out(a,b['id'],'service.buy_guard'))c['add'](f['to']);const d=out(a,b['id'],'service.machine')[0x0]?.['to'];if(d)for(const g of a['visibleEdges']){if(g['schema']==='wf.forward_guard'&&g['from']['startsWith'](d+'::node::'))c['add'](g['to']);}return c;}const O1={'id':'O1','kind':'opportunity','run'(a){const b=[],c=typedNodes(a,'Service');for(const d of typedNodes(a,'Demand')){const e=out(a,d['id'],'demand.presenter');if(e['length']>=SCARCE_PRESENTERS)continue;const f=demandGuardIds(a,d['id']),g=[];for(const i of c){const j=serviceGuardIds(a,i);if(f['size']===0x0||[...f]['every'](k=>j['has'](k)))g['push'](i['id']);}const h=e;b['push'](makeFinding(a,'O1:'+d['id'],'opportunity','Open\x20demand:\x20few\x20proposals,\x20with\x20structurally\x20capable\x20suppliers\x20present',{'severity':'info','path':[d['id'],'demand.presenter','demand.guard','Service'],'pathEdges':h['concat'](out(a,d['id'],'demand.guard')),'roles':['neutral','system','supplier'],'detail':'Demand\x20'+d['id']+'\x20currently\x20has\x20only\x20'+e['length']+'\x20proposal(s);\x20matched\x20by\x20Guard\x20structure\x20(no\x20Guard\x20bytecode\x20parsing)\x20to\x20'+(g['length']+'\x20candidate\x20Service(s):\x20'+(g['slice'](0x0,0x5)['join'](',\x20')||'(no\x20match\x20in\x20graph)')+'.'),'suggestion':'Candidate\x20suppliers\x20can\x20prepare\x20present\x20evidence\x20(proof\x20of\x20satisfying\x20the\x20demand\x20Guards);\x20the\x20opportunity\x20conclusion\x20is\x20structural\x20only\x20and\x20does\x20not\x20endorse\x20fulfillment\x20capability.'}));if(b['length']>=MAX_FINDINGS_PER_RULE)break;}return b;}},O2={'id':'O2','kind':'opportunity','run'(a){const b=typedNodes(a,'Service'),c=typedNodes(a,'Demand');if(b['length']===0x0&&c['length']===0x0)return[];const d=b['filter'](f=>bool(root(f)['bPublished'])&&!bool(root(f)['bPaused']))['length'],e=c['filter'](f=>out(a,f['id'],'demand.presenter')['length']===0x0)['length'];return[makeFinding(a,'O2:graph','opportunity','Supply/demand\x20density:\x20in-graph\x20supply\x20and\x20open-demand\x20statistics',{'path':['Service','Demand','demand.presenter'],'pathEdges':edgeList(a,'demand.presenter'),'roles':['neutral','system','supplier','merchant'],'detail':'In\x20the\x20current\x20viewport:\x20'+b['length']+'\x20Service(s)\x20('+d+'\x20published\x20and\x20unpaused),\x20'+c['length']+'\x20Demand(s)\x20'+('('+e+'\x20open\x20demand(s)\x20without\x20proposals).\x20Open-demand/active-supply\x20ratio\x20=\x20')+((d>0x0?(e/d)['toFixed'](0x3):'n/a')+'.'),'suggestion':'A\x20high\x20ratio\x20indicates\x20scarce\x20supply;\x20use\x20category\x20exact-match\x20counts\x20(collectors\x20category_enumerated_count)\x20to\x20pick\x20an\x20entry\x20category.'})];}},O3={'id':'O3','kind':'opportunity','run'(a){const b=[];for(const c of machineViews(a)){const d=new Map();for(const g of c['transitions']){if(str(g['payload']?.['namedOperator'])||g['payload']?.['permissionIndex']!=null)continue;const h=String(g['payload']?.['forward']??g['payload']?.['prevNode']+'→'+g['payload']?.['node']);d['set'](wfNodeName(g['from'])+':'+h,g);}if(d['size']===0x0)continue;const f=[...d['values']()];b['push'](makeFinding(a,'O3:'+c['machine']['id'],'opportunity','Workflow\x20gaps:\x20key\x20Forwards\x20have\x20no\x20operator\x20binding\x20(guard/payment\x20passthrough\x20only)',{'path':[c['machine']['id'],'machine.node','wf.transition'],'pathEdges':f,'roles':['neutral','system','supplier','collaborator','merchant'],'detail':'Machine\x20'+c['machine']['id']+'\x20has\x20'+d['size']+'\x20Forward(s)\x20without\x20namedOperator/permissionIndex\x20binding:\x20'+([...d['keys']()]['slice'](0x0,0x8)['join'](',\x20')+'.\x20These\x20slots\x20can\x20only\x20be\x20satisfied\x20automatically\x20by\x20guards\x20or\x20advanced\x20directly\x20by\x20payment\x20transactions.'),'suggestion':'Suppliers/collaborators\x20can\x20take\x20over\x20these\x20operator\x20slots,\x20or\x20push\x20the\x20merchant\x20to\x20convert\x20implicit\x20passthrough\x20into\x20explicit\x20role\x20bindings.'}));if(b['length']>=MAX_FINDINGS_PER_RULE)break;}return b;}};function arbitrationCases(a,b){return inc(a,b,'arb.arbitration_service')['map'](c=>a['graph']['nodes']['get'](c['from']))['filter'](c=>!!c&&c['objectType']==='Arb'&&!!c['raw']);}const G1={'id':'G1','kind':'game','run'(a){const b=[];for(const e of typedNodes(a,'Arbitration')){const f=root(e),g=asList(f['voting_guard']),h=new Set(g['map'](l=>l['vote_weight']&&typeof l['vote_weight']==='object'?Object['keys'](l['vote_weight'])[0x0]:'unknown')),i=arbitrationCases(a,e['id']),j=new Map();let k=0x0;for(const l of i){for(const m of asList(root(l)['voted'])){const n=Number(m['weight']??0x0);j['set'](n,(j['get'](n)??0x0)+0x1),k++;}}b['push'](makeFinding(a,'G1:'+e['id'],'game','Voting\x20power\x20structure:\x20arbitration\x20voting\x20Guard\x20configuration\x20vs\x20actual\x20voting\x20weight\x20distribution',{'severity':'info','path':[e['id'],'arbitration.voting_guard','arb.arbitration_service','arb.voter'],'pathEdges':out(a,e['id'],'arbitration.voting_guard')['concat'](edgeList(a,'arb.voter')),'roles':['neutral','system','arbitrator','merchant','buyer'],'detail':'Arbitration\x20'+e['id']+':\x20voting_guard\x20'+(g['length']===0x0?'empty\x20=\x20open\x20to\x20all\x20members\x20(arbitration.move:48-59)':'weighted\x20('+[...h]['join']('/')+')')+';\x20'+(i['length']+'\x20case(s)\x20in\x20window,\x20'+k+'\x20actual\x20vote(s)')+(j['size']?',\x20weight\x20distribution\x20'+[...j['entries']()]['map'](([o,p])=>'w'+o+'x'+p)['join'](',\x20'):'')+'.','suggestion':'Open\x20voting\x20suits\x20high-frequency\x20low-stakes\x20cases;\x20high-stakes\x20cases\x20should\x20use\x20weighted\x20Guards;\x20this\x20describes\x20the\x20objective\x20situation\x20only\x20—\x20scoring\x20belongs\x20to\x20the\x20game\x20modules.'}));if(b['length']>=MAX_FINDINGS_PER_RULE)break;}return b;}},G2={'id':'G2','kind':'game','run'(a){const b=[];n:for(const c of machineViews(a)){const d=out(a,c['machine']['id'],'machine.permission')[0x0]?.['to'],f=d?inc(a,d,'permission.entity')['map'](h=>({'eoa':h['to'],'bits':h['payload']?.['permIndices']??[]})):[],g=new Set();for(const h of c['transitions']){const i=String(h['payload']?.['forward']??h['payload']?.['prevNode']+'→'+h['payload']?.['node']),j=wfNodeName(h['from'])+':'+i;if(g['has'](j))continue;let k,l='';if(str(h['payload']?.['namedOperator']))k=0x1,l='namedOperator='+h['payload']['namedOperator'];else{if(h['payload']?.['permissionIndex']!=null){if(!d)continue;const m=Number(h['payload']['permissionIndex']);k=f['filter'](n=>n['bits']['includes'](m))['length'],l='permissionIndex='+m;if(k===0x0)continue;}else continue;}if(k!==0x1)continue;g['add'](j),b['push'](makeFinding(a,'G2:'+c['machine']['id']+':'+j,'game','Operator\x20replaceable\x20pool\x20=\x201:\x20hold-up\x20slot',{'severity':'low','path':[c['machine']['id'],'machine.node','wf.transition',j],'pathEdges':[h],'roles':['neutral','system','collaborator','merchant','supplier'],'detail':'Forward\x20'+j+'\x20('+l+')\x20on\x20Machine\x20'+c['machine']['id']+'\x20has\x20an\x20operable-party\x20pool\x20of\x20size\x201:\x20'+'that\x20party\x20holds\x20an\x20irreplaceable\x20bargaining\x20position\x20at\x20this\x20workflow\x20node\x20(machine.move\x20operation\x20precheck).','suggestion':'Add\x20an\x20alternative\x20entity\x20under\x20the\x20same\x20permissionIndex\x20or\x20a\x20namedOperator\x20backup;\x20sign\x20SLA/penalty\x20terms\x20covering\x20this\x20slot.'}));if(b['length']>=MAX_FINDINGS_PER_RULE)break n;}}return b;}},G3={'id':'G3','kind':'game','run'(a){const b=[];for(const c of typedNodes(a,'Arbitration')){const e=root(c),f=asList(e['voting_guard']);b['push'](makeFinding(a,'G3:'+c['id'],'game','Remedy\x20strategy\x20parameters:\x20structured\x20inputs\x20for\x20the\x20payoff/waiting\x20matrices',{'severity':'info','path':[c['id'],'Arbitration.fee/usage_guard/voting_guard'],'roles':['neutral','system','arbitrator','merchant','buyer'],'detail':'Arbitration\x20'+c['id']+':\x20fee='+big(e['fee'])+',\x20usage_guard='+(str(e['usage_guard'])??'none')+',\x20voting_guard='+f['length']+'.\x20'+'Global\x20structural\x20constants:\x20payout\x20cap\x203x\x20amount,\x2030-day\x20compensation\x20withdrawal\x20lock,\x20single\x20claim\x20per\x20payout,\x2030-day\x20withdraw/objection\x20window\x20'+'(arb.move:302-358,\x20order.move:86-96).','suggestion':'Feed\x20these\x20parameters\x20into\x20node-game/arbitration-game\x20payoff\x20and\x20waiting\x20matrices;\x20this\x20analyzer\x20does\x20not\x20score\x20or\x20rank.'}));if(b['length']>=MAX_FINDINGS_PER_RULE)break;}return b;}},ANTI_CHEAT_ROLES=['neutral','system','merchant','buyer'];function projectOrderEvidence(a,b){const c=[];for(const d of typedNodes(a,'Service')){const f=[...b['controllers']['get'](d['id'])??[]];if(f['length']===0x0)continue;for(const g of out(a,d['id'],'service.order')){const h=a['graph']['nodes']['get'](g['to']);if(!h||h['kind']!=='object'||h['objectType']!=='Order'||!h['raw'])continue;const i=out(a,h['id'],'order.builder')[0x0]?.['to'];if(!i)continue;const j=orderCompletionInGraph(a['graph'],h['id'])['status'],k=String(root(h)?.['amount']??0x0),l=out(a,h['id'],'order.allocation')[0x0]?.['to']??null;for(const m of f){c['push']({'service':d['id'],'id':h['id'],'buyer':i,'seller':m,'amount':k,'status':j,'allocation':l});}}}return c;}function orderCheatEdges(a){return edgeList(a,'service.order')['concat'](edgeList(a,'eoa.permission'))['concat'](edgeList(a,'permission.core_binding'));}function shortRefs(a){const b=a['slice'](0x0,0x5)['join'](',\x20');return a['length']>0x5?b+'\x20and\x20'+a['length']+'\x20object(s)\x20in\x20total':b;}const AC1={'id':'AC1','kind':'risk','run'(a){const b=projectOrderEvidence(a,buildControlIndex(a)),c=detectFakeOrders(b)['find'](e=>e['code']==='self_buy');if(!c)return[];const d=c['refs']??[];return[makeFinding(a,'AC1:'+d['join'](','),'risk','Fake-order\x20suspicion:\x20windowed\x20order\x20buyers\x20are\x20the\x20selling\x20service\x27s\x20controlling\x20EOA\x20(self-trading)',{'severity':'high','path':['EOA','eoa.permission','permission.core_binding','Service','service.order','Order','order.builder'],'pathEdges':orderCheatEdges(a),'roles':ANTI_CHEAT_ROLES,'detail':d['length']+'\x20order(s)\x20visible\x20in\x20the\x20window\x20have\x20buyer\x20EOAs\x20that\x20also\x20control\x20the\x20selling\x20Service\x20as\x20owner/admin\x20'+('('+shortRefs(d)+'):\x20buyer\x20and\x20seller\x20sit\x20in\x20the\x20same\x20control\x20set,\x20funds\x20circulate\x20internally,\x20and\x20this\x20is\x20not\x20genuine\x20competitive\x20volume.'),'suggestion':'Exclude\x20these\x20orders\x20from\x20sales/reputation\x20statistics\x20and\x20re-verify\x20via\x20payment\x20allocation\x20legs\x20and\x20time\x20windows;\x20reduce\x20market\x20exposure\x20and\x20recommendation\x20weight\x20for\x20this\x20Service.'})];}},AC2={'id':'AC2','kind':'risk','run'(a){const b=projectOrderEvidence(a,buildControlIndex(a)),c=detectFakeOrders(b)['find'](e=>e['code']==='reciprocal_loop');if(!c)return[];const d=c['refs']??[];return[makeFinding(a,'AC2:'+d['join'](','),'risk','Wash-trading\x20suspicion:\x20reciprocal\x20buy/sell\x20role-swapping\x20fund\x20loops\x20in\x20the\x20window',{'severity':c['severity'],'path':['EOA-A','order.builder','Order@Service-B','service.order','EOA-B','order.builder','Order@Service-A'],'pathEdges':orderCheatEdges(a),'roles':ANTI_CHEAT_ROLES,'detail':d['length']+'\x20order(s)\x20in\x20the\x20window\x20form\x20a\x20buy/sell\x20swap:\x20control\x20set\x20A\x20buys\x20B\x27s\x20Service\x20while\x20control\x20set\x20B\x20buys\x20A\x27s\x20Service\x20'+('('+shortRefs(d)+').\x20The\x20two-way\x20volume\x20may\x20be\x20mutually\x20staged\x20wash\x20trading.'),'suggestion':'Investigate\x20links\x20between\x20the\x20two\x20control\x20sets\x20(devices/permissions/fund\x20flows);\x20exclude\x20mutually-purchased\x20orders\x20from\x20genuine\x20competitive\x20volume.'})];}},AC3={'id':'AC3','kind':'risk','run'(a){const b=projectOrderEvidence(a,buildControlIndex(a)),c=detectFakeOrders(b)['find'](e=>e['code']==='no_allocation');if(!c)return[];const d=c['refs']??[];return[makeFinding(a,'AC3:'+d['join'](','),'risk','Missing\x20fund\x20closure:\x20completed\x20positive-amount\x20orders\x20lack\x20an\x20Allocation\x20object',{'severity':c['severity'],'path':['Service','service.order','Order','order.allocation'],'pathEdges':orderCheatEdges(a),'roles':ANTI_CHEAT_ROLES,'detail':d['length']+'\x20completed\x20order(s)\x20in\x20the\x20window\x20(completion\x20authoritatively\x20judged\x20by\x20the\x20order-status\x20terminal\x20node\x20set)\x20with\x20amount>0\x20have\x20no\x20Allocation\x20'+('('+shortRefs(d)+').\x20order.move\x20L130\x20requires\x20positive-amount\x20orders\x20to\x20have\x20an\x20allocation\x20path;\x20its\x20absence\x20means\x20the\x20\x22transaction\x22\x20lacks\x20fund-closure\x20evidence.\x20')+'Zero-amount\x20orders\x20are\x20excluded\x20(no\x20fund\x20flow).','suggestion':'Review\x20original\x20payment\x20records;\x20completed\x20orders\x20without\x20payment\x20evidence\x20must\x20not\x20count\x20toward\x20reputation;\x20audit\x20contract\x20entry\x20points\x20that\x20complete\x20without\x20an\x20Allocation\x20path.'})];}},SHELL_COPY={'shell_no_arbitration':{'title':'Shell\x20merchant:\x20published\x20Service\x20has\x20no\x20arbitration\x20binding,\x20disputes\x20have\x20no\x20remedy\x20path','detail':'The\x20Service\x20is\x20published\x20but\x20arbitrations\x20is\x20empty:\x20buyers\x20have\x20no\x20selectable\x20arbitration\x20service\x20after\x20ordering\x20and\x20disputes\x20cannot\x20enter\x20adjudication.','suggestion':'Bind\x20at\x20least\x20one\x20Arbitration\x20in\x20a\x20different\x20group\x20than\x20the\x20shop\x20Permission\x20before\x20publishing;\x20shops\x20without\x20a\x20remedy\x20path\x20should\x20not\x20be\x20recommended.'},'shell_funded_no_arbitration':{'title':'Floating\x20payout\x20funds:\x20compensation\x20fund\x20is\x20funded\x20but\x20no\x20Arbitration\x20exists,\x20payouts\x20cannot\x20be\x20adjudicated\x20or\x20released','detail':'compensation_fund>0\x20with\x20no\x20Arbitration\x20at\x20all:\x20when\x20a\x20payout\x20triggers\x20there\x20is\x20no\x20one\x20to\x20adjudicate\x20and\x20no\x20path\x20to\x20release;\x20the\x20funding\x20is\x20marketing\x20theater.','suggestion':'Bind\x20an\x20arbitration\x20service\x20before\x20advertising\x20payout\x20guarantees;\x20marketplaces\x20should\x20flag\x20\x27fund\x20without\x20arbitration\x27\x20as\x20high\x20risk\x20and\x20limit\x20exposure.'},'shell_no_machine':{'title':'Shell\x20merchant:\x20published\x20Service\x20has\x20no\x20Machine\x20binding,\x20no\x20structured\x20fulfillment\x20workflow','detail':'The\x20Service\x20is\x20published\x20but\x20machine\x20is\x20empty:\x20no\x20frozen\x20workflow\x20template\x20exists,\x20and\x20delivery/completion\x20nodes\x20carry\x20no\x20on-chain\x20structural\x20constraints.','suggestion':'Bind\x20and\x20publish\x20a\x20Machine\x20before\x20opening;\x20published\x20shops\x20without\x20workflows\x20suit\x20only\x20instant\x20spot-delivery\x20categories.'}},AC4={'id':'AC4','kind':'risk','run'(a){const b=[];for(const c of typedNodes(a,'Service')){const e=root(c);if(!bool(e['bPublished']))continue;const f=e['arbitrations']!=null?asList(e['arbitrations'])['length']:out(a,c['id'],'service.arbitration')['length'],g=str(e['machine'])??out(a,c['id'],'service.machine')[0x0]?.['to']??null,h=detectShellMerchant({'object':c['id'],'arbitrations':Array(f)['fill']('x'),'compensation_fund':String(big(e['compensation_fund'])),'machine':g,'bPublished':!![]}),i=out(a,c['id'],'service.arbitration')['concat'](out(a,c['id'],'service.machine'));for(const j of h){const k=SHELL_COPY[j['code']];if(!k)continue;b['push'](makeFinding(a,'AC4:'+c['id']+':'+j['code'],'risk',k['title'],{'severity':j['severity'],'path':[c['id'],'Service.bPublished','Service.arbitrations','Service.machine','Service.compensation_fund'],'pathEdges':i,'roles':ANTI_CHEAT_ROLES,'detail':k['detail']+'\x20(object:\x20'+c['id']+')','suggestion':k['suggestion']}));if(b['length']>=MAX_FINDINGS_PER_RULE)return b;}}return b;}};export const DEFAULT_ANALYZERS=[R1,R2,R3,R4,R5,R6,R7,A1,A2,A3,O1,O2,O3,G1,G2,G3,AC1,AC2,AC3,AC4,PROPOSAL_GAP_ANALYZER];const registry=new Map(DEFAULT_ANALYZERS['map'](b=>[b['id'],b]));export function registerAnalyzer(a){registry['set'](a['id'],a);}export function getAnalyzer(a){return registry['get'](a);}export function listAnalyzers(){return[...registry['keys']()];}export function runAnalyzers(a,b){const c=b?.['only']?new Set(b['only']):undefined,d=[];for(const e of registry['values']()){if(c&&!c['has'](e['id']))continue;if(b?.['kinds']&&!b['kinds']['includes'](e['kind']))continue;try{d['push'](...e['run'](a));}catch{}}return d;}export function adaptNodeAnalyzer(a){return{'id':a['id'],'kind':a['kind'],'objectType':a['objectType'],'run'(b,c){const d=a['inspect'](b,c);return d['map']((e,f)=>({'id':a['id']+':'+b['id']+'#'+f,'kind':a['kind'],'severity':e['severity']??'info','title':e['title'],'path':[b['id']],'confidence':e['confidence']??'exact','roles':e['roles']??['neutral'],'detail':e['detail'],'suggestion':e['suggestion'],...e['ruleId']?{'ruleId':e['ruleId']}:{},...e['evidence']?{'evidence':e['evidence']}:{},...e['nativeRisk']!==undefined?{'nativeRisk':e['nativeRisk']}:{},...b['proposal']&&!e['confidence']?{'confidence':'derived'}:{},...b['proposal']?{'source':b['proposal']['provenance']==='external'?'external':'proposal'}:{}}));}};}export function runNodeAnalyzers(a,b){const c=[];for(const d of b){for(const e of a['visibleNodes']){const f=a['graph']['nodes']['get'](e);if(f?.['kind']!=='object'||d['objectType']!=='*'&&f['objectType']!==d['objectType']||!f['raw'])continue;try{c['push'](...d['run'](f,a));}catch{}}}return c;}