@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{getRolePersonality}from'../role/profiles.js';import{getIndustryStrategy}from'../knowledge/industry-strategy.js';import{reviewNudgeLine}from'../strategy/review.js';const PRODUCTION_ROLES=new Set(['merchant','supplier']);function compactList(a,b=0x4){return a['filter'](c=>typeof c==='string'&&c['length']>0x0)['slice'](0x0,b);}function renderActiveRoleProfile(b,e){const f=[],g=(h,i)=>{if(Array['isArray'](i)){const j=compactList(i,0x6);if(j['length'])f['push']('\x20\x20-\x20'+h+':\x20'+j['join'](',\x20'));}else typeof i==='string'&&i['length']>0x0&&f['push']('\x20\x20-\x20'+h+':\x20'+i);};e['tastes']&&(g('taste\x20materials',e['tastes']['materials']),g('taste\x20colors',e['tastes']['colors']),g('taste\x20styles',e['tastes']['styles']),g('taste\x20tags',e['tastes']['tags']),g('taste\x20brands',e['tastes']['brands']),g('taste\x20avoid',e['tastes']['avoid']));if(e['consumption']){const h=e['consumption'];g('buy\x20frequency',h['frequency']),g('price\x20band',h['price_band']),g('decision\x20speed',h['decision_speed']),g('trusted\x20channels',h['channels']),g('repeat\x20orientation',h['repeat_orientation']),g('avg\x20order\x20range',h['avg_order_range']),g('consumption\x20notes',h['notes']);}e['merchant']&&(g('strategic\x20posture',e['merchant']['posture']),g('pricing\x20style',e['merchant']['pricing_style']),g('service\x20style',e['merchant']['service_style']),g('communication',e['merchant']['communication']),g('growth\x20focus',e['merchant']['growth_focus']));if(e['supplier']){const i=e['supplier'];g('min\x20order',i['min_order']),g('lead\x20time',i['lead_time']),g('settlement\x20terms',i['settlement_terms']),g('categories',i['categories']),g('capacity',i['capacity']);}if(e['collaborator']){const j=e['collaborator'];g('scope\x20discipline',j['scope_discipline']),g('notifications',j['notifications']),g('working\x20hours',j['working_hours']),g('advance\x20style',j['advance_style']);}if(e['arbitrator']){const k=e['arbitrator'];g('case\x20types',k['case_types']),g('response\x20speed',k['response_speed']),g('ruling\x20style',k['ruling_style']);}if(e['demander']){const l=e['demander'];if(l['award_weights']&&Object['keys'](l['award_weights'])['length']>0x0){const m=Object['entries'](l['award_weights'])['map'](([n,o])=>n+'='+o)['join'](',\x20');f['push']('\x20\x20-\x20award\x20weights:\x20'+m);}g('pilot\x20budget',l['pilot_budget']),g('RFP\x20openness',l['rfp_openness']),g('decision\x20basis',l['decision_basis']);}return e['preferences']&&Object['keys'](e['preferences'])['length']>0x0&&f['push']('\x20\x20-\x20role\x20preferences:\x20'+JSON['stringify'](e['preferences'])),f;}function roleProfileToInjectionPrefs(b,e){const f={},g=(h,i)=>{if(Array['isArray'](i)){if(i['length']>0x0)f[h]=i;}else i!==undefined&&i!==null&&i!==''&&(f[h]=i);};e['tastes']&&(g('taste_materials',e['tastes']['materials']),g('taste_colors',e['tastes']['colors']),g('taste_styles',e['tastes']['styles']),g('taste_tags',e['tastes']['tags']),g('taste_brands',e['tastes']['brands']),g('taste_avoid',e['tastes']['avoid']));if(e['consumption']){const h=e['consumption'];g('buy_frequency',h['frequency']),g('buy_price_band',h['price_band']),g('buy_decision_speed',h['decision_speed']),g('buy_channels',h['channels']),g('buy_repeat_orientation',h['repeat_orientation']),g('buy_avg_order_range',h['avg_order_range']),g('buy_notes',h['notes']);}e['merchant']&&(g('merchant_posture',e['merchant']['posture']),g('merchant_pricing_style',e['merchant']['pricing_style']),g('merchant_service_style',e['merchant']['service_style']),g('merchant_communication',e['merchant']['communication']),g('merchant_growth_focus',e['merchant']['growth_focus']));if(e['supplier']){const i=e['supplier'];g('supplier_min_order',i['min_order']),g('supplier_lead_time',i['lead_time']),g('supplier_settlement_terms',i['settlement_terms']),g('supplier_categories',i['categories']),g('supplier_capacity',i['capacity']);}if(e['collaborator']){const j=e['collaborator'];g('collaborator_scope',j['scope_discipline']),g('collaborator_notifications',j['notifications']),g('collaborator_working_hours',j['working_hours']),g('collaborator_advance_style',j['advance_style']);}if(e['arbitrator']){const l=e['arbitrator'];g('arbitrator_case_types',l['case_types']),g('arbitrator_response_speed',l['response_speed']),g('arbitrator_ruling_style',l['ruling_style']);}if(e['demander']){const m=e['demander'];if(m['award_weights']&&Object['keys'](m['award_weights'])['length']>0x0)for(const [n,o]of Object['entries'](m['award_weights'])){if(typeof o==='number')g('award_weight_'+n,o);}g('demander_pilot_budget',m['pilot_budget']),g('demander_rfp_openness',m['rfp_openness']),g('demander_decision_basis',m['decision_basis']);}if(Object['keys'](f)['length']>0x0)f['active_role']=b;return f;}function renderBusinessStrategy(a){const b=a['industries'][0x0];if(!b||!PRODUCTION_ROLES['has'](a['role']))return[];const c=getIndustryStrategy(b);if(!c)return[];const d=a['layer']['profiles']?.['merchant']?.['merchant']?.['posture']??'balanced',e=c['postures'][d],f=c['pricing']['models']['find'](h=>h['id']===c['pricing']['default_model_id'])??c['pricing']['models'][0x0],g=['-\x20business\x20strategy\x20('+b+',\x20'+d+'\x20posture):'];g['push']('\x20\x20-\x20benchmark:\x20'+c['benchmark']+'\x20(tier\x20'+c['priority_tier']+',\x20launch\x20'+c['launch_window']+')');if(f)g['push']('\x20\x20-\x20default\x20pricing\x20model:\x20'+f['name']+'\x20—\x20'+f['applicable_when']);g['push']('\x20\x20-\x20posture\x20thesis:\x20'+e['thesis']),g['push']('\x20\x20-\x20competitor\x20watch\x20cadence:\x20'+c['competitor_watch']['cadence']+'\x20('+c['competitor_watch']['cadence_days']+'d)\x20on\x20'+c['competitor_watch']['dimensions']['slice'](0x0,0x4)['join'](',\x20'));for(const h of c['red_lines']['slice'](0x0,0x3))g['push']('\x20\x20-\x20red\x20line:\x20'+h);return g['push']('\x20\x20-\x20deep\x20playbook\x20on\x20demand:\x20industry_pack_operation\x20action=\x27get\x27\x20category=\x27'+b+'\x27\x20(playbook)\x20and\x20read_file\x20\x27strategy-manual.md\x27'),g;}const REQUIREMENT_RULE_MAP=[{'keywords':['arbitration','arb'],'rule_id':'r_trust'},{'keywords':['compensation','fund'],'rule_id':'r_fund'},{'keywords':['region','location'],'rule_id':'r_region'},{'keywords':['price','budget'],'rule_id':'r_price'},{'keywords':['industry'],'rule_id':'r_industry'},{'keywords':['capability'],'rule_id':'r_capabilities'},{'keywords':['trust','score'],'rule_id':'r_trust'}],FORBID_KEYWORDS=['forbid','never','no\x20'];function mapRequirement(a){const b=a['toLowerCase'](),c=FORBID_KEYWORDS['some'](d=>b['includes'](d));for(const d of REQUIREMENT_RULE_MAP){if(d['keywords']['some'](e=>b['includes'](e)))return{'rule_id':d['rule_id'],'condition':c?'forbid':'require','note':a};}return{'rule_id':'r_trust','condition':c?'forbid':'require','note':a};}export function personaToInjection(a){const b=(a['layer']['requirements']??[])['map'](mapRequirement),c=['role='+a['role'],a['industries']['length']?'industries='+a['industries']['join'](','):'',a['layer']['identity']?.['self_description']??'']['filter'](Boolean)['join'](';\x20'),d=a['layer']['profiles']?.[a['role']],e=d?roleProfileToInjectionPrefs(a['role'],d):{};return{'intent':c,'preferences':{...e,...a['layer']['preferences']??{}},'requirements':b['length']?b:undefined};}export function personaToContextText(a,c={}){const d=[];d['push']('#\x20Effective\x20Persona\x20(role='+a['role']+',\x20industries='+(a['industries']['join'](',')||'any')+')');const e=a['layer']['identity'];if(e){if(e['self_description'])d['push']('-\x20self:\x20'+e['self_description']);if(e['region'])d['push']('-\x20region:\x20'+e['region']);if(e['languages']?.['length'])d['push']('-\x20languages:\x20'+e['languages']['join'](',\x20'));}const f=getRolePersonality(a['role']);if(f){d['push']('-\x20active\x20role\x20lens:\x20'+f['archetype']),d['push']('\x20\x20-\x20motivations:\x20'+f['motivations']['slice'](0x0,0x4)['join'](';\x20')),d['push']('\x20\x20-\x20communication:\x20'+f['communication']);const j=f['game_moves']['filter'](k=>k['taboo'])['slice'](0x0,0x3);if(j['length']){d['push']('\x20\x20-\x20role\x20taboos:');for(const k of j)d['push']('\x20\x20\x20\x20-\x20'+k['move']);}f['path_preferences']['length']&&d['push']('\x20\x20-\x20path\x20preference:\x20'+f['path_preferences'][0x0]),d['push']('\x20\x20-\x20winning\x20looks\x20like:\x20'+f['feedback_signals']['win']['slice'](0x0,0x2)['join'](';\x20'));}const g=a['layer']['profiles']?.[a['role']];g&&(d['push']('-\x20active\x20role\x20profile:'),d['push'](...renderActiveRoleProfile(a['role'],g)));d['push'](...renderBusinessStrategy(a));if(a['role']==='merchant'){const l=a['industries'][0x0];if(l){const m=reviewNudgeLine(l,c['lastStrategyReviewAt']??null,c['now']??Date['now']());if(m)d['push']('-\x20'+m);}}if(a['layer']['strategy']?.['length']){d['push']('-\x20strategy:');for(const n of a['layer']['strategy'])d['push']('\x20\x20-\x20'+n);}if(a['layer']['rules']?.['length']){d['push']('-\x20rules:');for(const o of a['layer']['rules'])d['push']('\x20\x20-\x20'+o);}if(a['layer']['requirements']?.['length']){d['push']('-\x20requirements:');for(const p of a['layer']['requirements'])d['push']('\x20\x20-\x20'+p);}const h=a['layer']['policy'],i=a['layer']['overrides'];if(h||i){d['push']('-\x20safety\x20policy:');if(h?.['confirm']?.['mode'])d['push']('\x20\x20-\x20confirm\x20mode:\x20'+h['confirm']['mode']);h?.['confirm']?.['batch_standard']===!![]&&d['push']('\x20\x20-\x20independent\x20routine\x20confirmations\x20in\x20one\x20turn\x20are\x20batched\x20into\x20one\x20card');h?.['confirm']?.['session_remember']?.['length']&&d['push']('\x20\x20-\x20remember\x20session\x20approvals:\x20'+h['confirm']['session_remember']['join'](',\x20'));h?.['confirm']?.['intent_bypass']===![]&&d['push']('\x20\x20-\x20explicit\x20intent\x20phrases\x20do\x20NOT\x20skip\x20a\x20confirmation\x20(a\x20click\x20is\x20required)');if(h?.['budget']?.['daily_wow']!==undefined){const q=h['budget']['daily_wow'];d['push']('\x20\x20-\x20daily\x20spend\x20ceiling:\x20'+(q===null?'unlimited':q+'\x20base\x20units'));}h?.['allowlist']?.['length']&&d['push']('\x20\x20-\x20allowlist:\x20'+h['allowlist']['join'](',\x20'));if(h?.['audit']===!![])d['push']('\x20\x20-\x20audit\x20logging:\x20on');if(i)for(const [u,v]of Object['entries'](i)){d['push']('\x20\x20-\x20rule\x20override\x20'+u+':\x20'+v);}d['push']('\x20\x20-\x20hard\x20floor\x20(never\x20relaxable):\x20fund\x20movement,\x20irreversible/publish/amount\x20operations,\x20guard\x20creation');}return a['layer']['spec']&&(d['push']('-\x20spec:'),d['push'](a['layer']['spec'])),d['join']('\x0a');}export function mergeInjections(a,b){if(!a&&!b)return undefined;if(!a)return b??undefined;if(!b)return a;return{'intent':b['intent']??a['intent'],'preferences':{...a['preferences']??{},...b['preferences']??{}},'requirements':[...a['requirements']??[],...b['requirements']??[]],'overrides':{'rules':{...a['overrides']?.['rules']??{},...b['overrides']?.['rules']??{}},'data_sources':{...a['overrides']?.['data_sources']??{},...b['overrides']?.['data_sources']??{}}}};}
1
+ import{getRolePersonality}from'../role/profiles.js';import{getIndustryStrategy}from'../knowledge/industry-strategy.js';import{reviewNudgeLine}from'../strategy/review.js';const PRODUCTION_ROLES=new Set(['merchant','supplier']);function compactList(a,b=0x4){return a['filter'](c=>typeof c==='string'&&c['length']>0x0)['slice'](0x0,b);}function renderActiveRoleProfile(b,e){const f=[],g=(h,i)=>{if(Array['isArray'](i)){const j=compactList(i,0x6);if(j['length'])f['push']('\x20\x20-\x20'+h+':\x20'+j['join'](',\x20'));}else typeof i==='string'&&i['length']>0x0&&f['push']('\x20\x20-\x20'+h+':\x20'+i);};e['tastes']&&(g('taste\x20materials',e['tastes']['materials']),g('taste\x20colors',e['tastes']['colors']),g('taste\x20styles',e['tastes']['styles']),g('taste\x20tags',e['tastes']['tags']),g('taste\x20brands',e['tastes']['brands']),g('taste\x20avoid',e['tastes']['avoid']));if(e['consumption']){const h=e['consumption'];g('buy\x20frequency',h['frequency']),g('price\x20band',h['price_band']),g('decision\x20speed',h['decision_speed']),g('trusted\x20channels',h['channels']),g('repeat\x20orientation',h['repeat_orientation']),g('avg\x20order\x20range',h['avg_order_range']),g('consumption\x20notes',h['notes']);}e['merchant']&&(g('strategic\x20posture',e['merchant']['posture']),g('pricing\x20style',e['merchant']['pricing_style']),g('service\x20style',e['merchant']['service_style']),g('communication',e['merchant']['communication']),g('growth\x20focus',e['merchant']['growth_focus']));if(e['supplier']){const i=e['supplier'];g('min\x20order',i['min_order']),g('lead\x20time',i['lead_time']),g('settlement\x20terms',i['settlement_terms']),g('categories',i['categories']),g('capacity',i['capacity']);}if(e['collaborator']){const j=e['collaborator'];g('scope\x20discipline',j['scope_discipline']),g('notifications',j['notifications']),g('working\x20hours',j['working_hours']),g('advance\x20style',j['advance_style']);}if(e['arbitrator']){const k=e['arbitrator'];g('case\x20types',k['case_types']),g('response\x20speed',k['response_speed']),g('ruling\x20style',k['ruling_style']);}if(e['demander']){const l=e['demander'];if(l['award_weights']&&Object['keys'](l['award_weights'])['length']>0x0){const m=Object['entries'](l['award_weights'])['map'](([n,o])=>n+'='+o)['join'](',\x20');f['push']('\x20\x20-\x20award\x20weights:\x20'+m);}g('pilot\x20budget',l['pilot_budget']),g('RFP\x20openness',l['rfp_openness']),g('decision\x20basis',l['decision_basis']);}return e['preferences']&&Object['keys'](e['preferences'])['length']>0x0&&f['push']('\x20\x20-\x20role\x20preferences:\x20'+JSON['stringify'](e['preferences'])),f;}function roleProfileToInjectionPrefs(b,e){const f={},g=(h,i)=>{if(Array['isArray'](i)){if(i['length']>0x0)f[h]=i;}else i!==undefined&&i!==null&&i!==''&&(f[h]=i);};e['tastes']&&(g('taste_materials',e['tastes']['materials']),g('taste_colors',e['tastes']['colors']),g('taste_styles',e['tastes']['styles']),g('taste_tags',e['tastes']['tags']),g('taste_brands',e['tastes']['brands']),g('taste_avoid',e['tastes']['avoid']));if(e['consumption']){const h=e['consumption'];g('buy_frequency',h['frequency']),g('buy_price_band',h['price_band']),g('buy_decision_speed',h['decision_speed']),g('buy_channels',h['channels']),g('buy_repeat_orientation',h['repeat_orientation']),g('buy_avg_order_range',h['avg_order_range']),g('buy_notes',h['notes']);}e['merchant']&&(g('merchant_posture',e['merchant']['posture']),g('merchant_pricing_style',e['merchant']['pricing_style']),g('merchant_service_style',e['merchant']['service_style']),g('merchant_communication',e['merchant']['communication']),g('merchant_growth_focus',e['merchant']['growth_focus']));if(e['supplier']){const i=e['supplier'];g('supplier_min_order',i['min_order']),g('supplier_lead_time',i['lead_time']),g('supplier_settlement_terms',i['settlement_terms']),g('supplier_categories',i['categories']),g('supplier_capacity',i['capacity']);}if(e['collaborator']){const j=e['collaborator'];g('collaborator_scope',j['scope_discipline']),g('collaborator_notifications',j['notifications']),g('collaborator_working_hours',j['working_hours']),g('collaborator_advance_style',j['advance_style']);}if(e['arbitrator']){const l=e['arbitrator'];g('arbitrator_case_types',l['case_types']),g('arbitrator_response_speed',l['response_speed']),g('arbitrator_ruling_style',l['ruling_style']);}if(e['demander']){const m=e['demander'];if(m['award_weights']&&Object['keys'](m['award_weights'])['length']>0x0)for(const [n,o]of Object['entries'](m['award_weights'])){if(typeof o==='number')g('award_weight_'+n,o);}g('demander_pilot_budget',m['pilot_budget']),g('demander_rfp_openness',m['rfp_openness']),g('demander_decision_basis',m['decision_basis']);}if(Object['keys'](f)['length']>0x0)f['active_role']=b;return f;}function renderBusinessStrategy(a){const b=a['industries'][0x0];if(!b||!PRODUCTION_ROLES['has'](a['role']))return[];const c=getIndustryStrategy(b);if(!c)return[];const d=a['layer']['profiles']?.['merchant']?.['merchant']?.['posture']??'balanced',e=c['postures'][d],f=c['pricing']['models']['find'](h=>h['id']===c['pricing']['default_model_id'])??c['pricing']['models'][0x0],g=['-\x20business\x20strategy\x20('+b+',\x20'+d+'\x20posture):'];g['push']('\x20\x20-\x20benchmark:\x20'+c['benchmark']+'\x20(tier\x20'+c['priority_tier']+',\x20launch\x20'+c['launch_window']+')');if(f)g['push']('\x20\x20-\x20default\x20pricing\x20model:\x20'+f['name']+'\x20—\x20'+f['applicable_when']);g['push']('\x20\x20-\x20posture\x20thesis:\x20'+e['thesis']),g['push']('\x20\x20-\x20competitor\x20watch\x20cadence:\x20'+c['competitor_watch']['cadence']+'\x20('+c['competitor_watch']['cadence_days']+'d)\x20on\x20'+c['competitor_watch']['dimensions']['slice'](0x0,0x4)['join'](',\x20'));for(const h of c['red_lines']['slice'](0x0,0x3))g['push']('\x20\x20-\x20red\x20line:\x20'+h);return g['push']('\x20\x20-\x20deep\x20playbook\x20on\x20demand:\x20industry_pack_operation\x20action=\x27get\x27\x20category=\x27'+b+'\x27\x20(playbook)\x20and\x20read_file\x20\x27strategy-manual.md\x27'),g;}const REQUIREMENT_RULE_MAP=[{'keywords':['arbitration','arb'],'rule_id':'r_trust'},{'keywords':['compensation','fund'],'rule_id':'r_fund'},{'keywords':['region','location'],'rule_id':'r_region'},{'keywords':['price','budget'],'rule_id':'r_price'},{'keywords':['industry'],'rule_id':'r_industry'},{'keywords':['capability'],'rule_id':'r_capabilities'},{'keywords':['trust','score'],'rule_id':'r_trust'}],FORBID_KEYWORDS=['forbid','never','no\x20'];function mapRequirement(a){const b=a['toLowerCase'](),c=FORBID_KEYWORDS['some'](d=>b['includes'](d));for(const d of REQUIREMENT_RULE_MAP){if(d['keywords']['some'](e=>b['includes'](e)))return{'rule_id':d['rule_id'],'condition':c?'forbid':'require','note':a};}return{'rule_id':'r_trust','condition':c?'forbid':'require','note':a};}export function personaToInjection(a){const b=(a['layer']['requirements']??[])['map'](mapRequirement),c=['role='+a['role'],a['industries']['length']?'industries='+a['industries']['join'](','):'',a['layer']['identity']?.['self_description']??'']['filter'](Boolean)['join'](';\x20'),d=a['layer']['profiles']?.[a['role']],e=d?roleProfileToInjectionPrefs(a['role'],d):{},f=a['layer']['evaluation']?.['weights']??{},g=Object['fromEntries'](Object['entries'](f)['filter'](([,h])=>typeof h==='number'&&Number['isFinite'](h))['map'](([h,i])=>[h,{'weight':i}]));return{'intent':c,'preferences':{...e,...a['layer']['preferences']??{}},'requirements':b['length']?b:undefined,...Object['keys'](g)['length']?{'overrides':{'rules':g}}:{}};}export function personaToContextText(a,c={}){const d=[];d['push']('#\x20Effective\x20Persona\x20(role='+a['role']+',\x20industries='+(a['industries']['join'](',')||'any')+')');const e=a['layer']['identity'];if(e){if(e['self_description'])d['push']('-\x20self:\x20'+e['self_description']);if(e['region'])d['push']('-\x20region:\x20'+e['region']);if(e['languages']?.['length'])d['push']('-\x20languages:\x20'+e['languages']['join'](',\x20'));}const f=getRolePersonality(a['role']);if(f){d['push']('-\x20active\x20role\x20lens:\x20'+f['archetype']),d['push']('\x20\x20-\x20motivations:\x20'+f['motivations']['slice'](0x0,0x4)['join'](';\x20')),d['push']('\x20\x20-\x20communication:\x20'+f['communication']);const k=f['game_moves']['filter'](l=>l['taboo'])['slice'](0x0,0x3);if(k['length']){d['push']('\x20\x20-\x20role\x20taboos:');for(const l of k)d['push']('\x20\x20\x20\x20-\x20'+l['move']);}f['path_preferences']['length']&&d['push']('\x20\x20-\x20path\x20preference:\x20'+f['path_preferences'][0x0]),d['push']('\x20\x20-\x20winning\x20looks\x20like:\x20'+f['feedback_signals']['win']['slice'](0x0,0x2)['join'](';\x20'));}const g=a['layer']['profiles']?.[a['role']];g&&(d['push']('-\x20active\x20role\x20profile:'),d['push'](...renderActiveRoleProfile(a['role'],g)));d['push'](...renderBusinessStrategy(a));if(a['role']==='merchant'){const m=a['industries'][0x0];if(m){const n=reviewNudgeLine(m,c['lastStrategyReviewAt']??null,c['now']??Date['now']());if(n)d['push']('-\x20'+n);}}if(a['layer']['strategy']?.['length']){d['push']('-\x20strategy:');for(const o of a['layer']['strategy'])d['push']('\x20\x20-\x20'+o);}const h=Object['entries'](a['layer']['evaluation']?.['weights']??{});h['length']&&(d['push']('-\x20evaluation\x20standards\x20(dimension\x20weight\x20overrides):'),d['push']('\x20\x20-\x20'+h['map'](([p,q])=>p+'='+q)['join'](',\x20')));if(a['layer']['rules']?.['length']){d['push']('-\x20rules:');for(const p of a['layer']['rules'])d['push']('\x20\x20-\x20'+p);}if(a['layer']['requirements']?.['length']){d['push']('-\x20requirements:');for(const q of a['layer']['requirements'])d['push']('\x20\x20-\x20'+q);}const i=a['layer']['policy'],j=a['layer']['overrides'];if(i||j){d['push']('-\x20safety\x20policy:');if(i?.['confirm']?.['mode'])d['push']('\x20\x20-\x20confirm\x20mode:\x20'+i['confirm']['mode']);i?.['confirm']?.['batch_standard']===!![]&&d['push']('\x20\x20-\x20independent\x20routine\x20confirmations\x20in\x20one\x20turn\x20are\x20batched\x20into\x20one\x20card');i?.['confirm']?.['session_remember']?.['length']&&d['push']('\x20\x20-\x20remember\x20session\x20approvals:\x20'+i['confirm']['session_remember']['join'](',\x20'));i?.['confirm']?.['intent_bypass']===![]&&d['push']('\x20\x20-\x20explicit\x20intent\x20phrases\x20do\x20NOT\x20skip\x20a\x20confirmation\x20(a\x20click\x20is\x20required)');if(i?.['budget']?.['daily_wow']!==undefined){const u=i['budget']['daily_wow'];d['push']('\x20\x20-\x20daily\x20spend\x20ceiling:\x20'+(u===null?'unlimited':u+'\x20base\x20units'));}i?.['allowlist']?.['length']&&d['push']('\x20\x20-\x20allowlist:\x20'+i['allowlist']['join'](',\x20'));if(i?.['audit']===!![])d['push']('\x20\x20-\x20audit\x20logging:\x20on');if(j)for(const [v,w]of Object['entries'](j)){d['push']('\x20\x20-\x20rule\x20override\x20'+v+':\x20'+w);}d['push']('\x20\x20-\x20hard\x20floor\x20(never\x20relaxable):\x20fund\x20movement,\x20irreversible/publish/amount\x20operations,\x20guard\x20creation');}return a['layer']['spec']&&(d['push']('-\x20spec:'),d['push'](a['layer']['spec'])),d['join']('\x0a');}export function mergeInjections(a,b){if(!a&&!b)return undefined;if(!a)return b??undefined;if(!b)return a;return{'intent':b['intent']??a['intent'],'preferences':{...a['preferences']??{},...b['preferences']??{}},'requirements':[...a['requirements']??[],...b['requirements']??[]],'overrides':{'rules':{...a['overrides']?.['rules']??{},...b['overrides']?.['rules']??{}},'data_sources':{...a['overrides']?.['data_sources']??{},...b['overrides']?.['data_sources']??{}}}};}
@@ -0,0 +1,33 @@
1
+ import { type FacetId } from "../evaluation/facets/catalog.js";
2
+ import type { Industry, PersonaFacetSettings, PersonaRole } from "./types.js";
3
+ export interface IndustryFacetTemplate {
4
+ label: string;
5
+ order: readonly FacetId[];
6
+ rationale: string;
7
+ }
8
+ export declare const INDUSTRY_FACET_DEFAULTS: Readonly<Record<string, IndustryFacetTemplate>>;
9
+ export declare function getIndustryFacetTemplate(industry?: Industry): IndustryFacetTemplate | undefined;
10
+ export interface ResolvedFacetSetting {
11
+ visible: boolean;
12
+ order: number;
13
+ weight?: number;
14
+ threshold?: number;
15
+ }
16
+ export interface ResolvedFacetProfile {
17
+ role?: PersonaRole;
18
+ industry?: string;
19
+ personaApplied: boolean;
20
+ sources: string[];
21
+ facets: Record<FacetId, ResolvedFacetSetting>;
22
+ }
23
+ export interface ResolveFacetProfileInput {
24
+ role?: PersonaRole;
25
+ industry?: Industry;
26
+ personaEvaluation?: {
27
+ facets?: PersonaFacetSettings;
28
+ };
29
+ personaApplied?: boolean;
30
+ request?: PersonaFacetSettings;
31
+ }
32
+ export declare function resolveFacetProfile(input?: ResolveFacetProfileInput): ResolvedFacetProfile;
33
+ export declare function deriveRuleWeights(profile: ResolvedFacetProfile): Record<string, number>;
@@ -0,0 +1 @@
1
+ import{FACET_CATALOG,FACET_IDS,ROLE_FACET_DEFAULTS}from'../evaluation/facets/catalog.js';import{defaultWeight}from'../evaluation/standards.js';export const INDUSTRY_FACET_DEFAULTS={'freelance':{'label':'freelance','order':['workflow','fund_flow','fulfillment'],'rationale':'milestone\x20ladder\x20and\x20per-milestone\x20release\x20decide\x20both\x20safety\x20and\x20completion'},'rental':{'label':'rental','order':['fund_safety','fund_flow','fulfillment'],'rationale':'deposit\x20round-trip:\x20coverage\x20and\x20the\x20return\x20path\x20before\x20anything\x20else'},'education':{'label':'education','order':['workflow','fulfillment','fund_safety'],'rationale':'per-lesson\x20release\x20ladder\x20carries\x20delivery\x20and\x20refund\x20points'},'travel':{'label':'travel','order':['workflow','fund_flow','supply_chain'],'rationale':'multi-leg\x20trips:\x20process\x20legs,\x20the\x20waterfall,\x20upstream\x20suppliers'},'subscription':{'label':'subscription','order':['fund_flow','fulfillment','permission'],'rationale':'recurring\x20charges,\x20period\x20delivery,\x20who\x20can\x20change\x20the\x20schedule'},'retail':{'label':'retail','order':['fund_safety','fulfillment','supply_chain'],'rationale':'escrow\x20receipt:\x20coverage,\x20completion,\x20the\x20upstream\x20stock\x20chain'}};export function getIndustryFacetTemplate(a){if(!a)return undefined;return INDUSTRY_FACET_DEFAULTS[a];}function isFacetId(a){return FACET_IDS['includes'](a);}export function resolveFacetProfile(a={}){const b=['catalog\x20defaults'],c=new Map(FACET_CATALOG['map'](j=>[j['id'],j['defaultOrder']])),d=new Map(),e=(j,k,l)=>{const m=j['filter'](isFacetId);if(!m['length'])return;const n=new Set(m),o=FACET_IDS['filter'](p=>!n['has'](p))['sort']((p,q)=>c['get'](p)-c['get'](q));[...m,...o]['forEach']((p,q)=>c['set'](p,q+0x1)),b['push'](l?k+'\x20('+l+')':k);},f=(j,k)=>{if(!j)return![];let l=![];for(const [m,n]of Object['entries'](j)){if(!isFacetId(m)||!n)continue;const o=d['get'](m)??{'visible':!![],'order':c['get'](m)},p={'visible':n['visible']!==undefined?n['visible']:o['visible'],'order':n['order']!==undefined?n['order']:o['order']};if(n['weight']!==undefined)p['weight']=n['weight'];else{if(o['weight']!==undefined)p['weight']=o['weight'];}if(n['threshold']!==undefined)p['threshold']=n['threshold'];else{if(o['threshold']!==undefined)p['threshold']=o['threshold'];}d['set'](m,p);if(n['order']!==undefined)c['set'](m,n['order']);l=!![];}if(l)b['push'](k);return l;};a['role']&&ROLE_FACET_DEFAULTS[a['role']]&&e(ROLE_FACET_DEFAULTS[a['role']]['order'],'role\x20default:'+a['role'],ROLE_FACET_DEFAULTS[a['role']]['rationale']);const g=getIndustryFacetTemplate(a['industry']);g&&e(g['order'],'industry\x20default:'+g['label'],g['rationale']);const h=f(a['personaEvaluation']?.['facets'],'persona\x20evaluation.facets');f(a['request'],'request\x20facet\x20injection');const i={};for(const j of FACET_CATALOG){const k=d['get'](j['id']);i[j['id']]={'visible':k?.['visible']??!![],'order':c['get'](j['id']),...k?.['weight']!==undefined?{'weight':k['weight']}:{},...k?.['threshold']!==undefined?{'threshold':k['threshold']}:{}};}return{...a['role']?{'role':a['role']}:{},...a['industry']?{'industry':a['industry']}:{},'personaApplied':a['personaApplied']??h,'sources':b,'facets':i};}export function deriveRuleWeights(a){const b={},c=new Map(FACET_CATALOG['map'](d=>[d['id'],d]));for(const [d,e]of Object['entries'](a['facets'])){if(e['weight']===undefined)continue;const f=c['get'](d)?.['ruleIds'];if(!f?.['length'])continue;const g=f['reduce']((h,i)=>h+defaultWeight(i),0x0);if(g<=0x0)continue;for(const h of f){b[h]=e['weight']*defaultWeight(h)/g;}}return b;}
@@ -1,6 +1,7 @@
1
- import { type EffectivePersona, type Persona, type PersonaLayer, type PersonaMutationMode, type RoleProfile } from "./types.js";
1
+ import { type EffectivePersona, type Persona, type PersonaFacetSettings, type PersonaLayer, type PersonaMutationMode, type RoleProfile } from "./types.js";
2
2
  export declare function mergeRoleProfiles(a: RoleProfile | undefined, b: RoleProfile | undefined): RoleProfile | undefined;
3
3
  export declare function mergeProfileMaps(a: PersonaLayer["profiles"], b: PersonaLayer["profiles"]): PersonaLayer["profiles"] | undefined;
4
+ export declare function mergeFacetSettings(a?: PersonaFacetSettings, b?: PersonaFacetSettings): PersonaFacetSettings | undefined;
4
5
  export interface LayerMergeMeta {
5
6
  part: "long_term" | "current";
6
7
  group: number;
@@ -1 +1 @@
1
- import{PERSONA_MAX_LINES,PERSONA_ROLES,PERSONA_VERSION}from'./types.js';import{validateLayerOverrides}from'./overrides.js';import{normalizeTopologyFocusPref}from'../graph/onchain/strategy.js';function dedupe(a){return Array['from'](new Set(a['filter'](b=>typeof b==='string'&&b['length']>0x0)));}const OVERRIDE_RANK={'auto':0x0,'warn':0x1,'prompt':0x2,'block':0x3},MODE_SUPPRESSION_RANK={'full':0x0,'streamlined':0x1,'quiet':0x2};function stricterOverride(c,d){if(!c)return d;if(!d)return c;return OVERRIDE_RANK[c]>=OVERRIDE_RANK[d]?c:d;}function mergePolicySequence(a){const b={};for(const c of a){if(!c)continue;if(c['confirm'])b['confirm']={...b['confirm'],...c['confirm']};if(c['budget'])b['budget']={...b['budget'],...c['budget']};if(c['allowlist']!==undefined)b['allowlist']=c['allowlist'];if(c['audit']!==undefined)b['audit']=c['audit'];}return b;}function parseDailyWow(a){if(a===undefined)return undefined;if(a===null)return null;if(!/^\d+$/['test'](a['trim']()))return undefined;try{return BigInt(a['trim']());}catch{return undefined;}}function tightenPolicy(a,b){const c={},d=a['confirm']?.['mode'],e=b['confirm']?.['mode'];let f=d;if(e){if(!d)f=e;else{if(MODE_SUPPRESSION_RANK[e]<MODE_SUPPRESSION_RANK[d])f=e;}}const g=a['confirm']?.['batch_standard'],h=a['confirm']?.['session_remember'];let i=a['confirm']?.['intent_bypass'];if(b['confirm']?.['intent_bypass']===![])i=![];if(f!==undefined||g!==undefined||h!==undefined||i!==undefined){c['confirm']={};if(f!==undefined)c['confirm']['mode']=f;if(g!==undefined)c['confirm']['batch_standard']=g;if(h!==undefined)c['confirm']['session_remember']=h;if(i!==undefined)c['confirm']['intent_bypass']=i;}const j=parseDailyWow(a['budget']?.['daily_wow']),k=parseDailyWow(b['budget']?.['daily_wow']);let l=j;if(k!==undefined){if(j===undefined)l=k;else{if(j===null)l=k;else{if(k!==null)l=j<k?j:k;}}}if(l!==undefined)c['budget']={'daily_wow':l===null?null:l['toString']()};if(a['allowlist']!==undefined)c['allowlist']=a['allowlist'];const m=a['audit']===!![]||b['audit']===!![];if(m)c['audit']=!![];return c;}function clampOverrideMap(a,b){const c={...a};for(const [d,e]of Object['entries'](b)){c[d]=stricterOverride(a[d],e)??e;}return c;}function mergeSafetyControls(a){const b=new Map(),c=new Map(),d=new Map(),e=new Map(),f=(l,n)=>{let o=l['get'](n);return!o&&(o={},l['set'](n,o)),o;},g=(l,m)=>{let n=l['get'](m);return!n&&(n=[],l['set'](m,n)),n;};for(const {layer:l,part:m,group:n}of a){l['overrides']&&Object['assign'](f(m==='current'?c:b,n),l['overrides']);if(l['policy'])g(m==='current'?e:d,n)['push'](l['policy']);}const h=Array['from'](new Set(a['map'](o=>o['group'])))['sort']((o,p)=>o-p);let i={};const j=[];for(const o of h){const p=clampOverrideMap(b['get'](o)??{},c['get'](o)??{});i={...i,...p};const q=tightenPolicy(mergePolicySequence(d['get'](o)??[]),mergePolicySequence(e['get'](o)??[]));j['push'](q);}const k=mergePolicySequence(j);return{'overrides':Object['keys'](i)['length']>0x0?i:undefined,'policy':Object['keys'](k)['length']>0x0?k:undefined};}const ROLE_PROFILE_SECTIONS=['tastes','consumption','merchant','supplier','collaborator','arbitrator','demander','topology'];function isPlainObject(a){return typeof a==='object'&&a!==null&&!Array['isArray'](a);}function mergeProfileSection(c,d){if(!d)return c;const e={...c??{}};for(const [f,g]of Object['entries'](d)){const h=e[f];if(Array['isArray'](g)){const i=Array['isArray'](h)?[...h,...g]:g;e[f]=dedupe(i['filter'](j=>typeof j==='string'));}else isPlainObject(g)?e[f]=isPlainObject(h)?{...h,...g}:{...g}:e[f]=g;}return Object['keys'](e)['length']>0x0?e:undefined;}export function mergeRoleProfiles(c,d){if(!d)return c;const e={...c??{}};for(const f of ROLE_PROFILE_SECTIONS){const g=mergeProfileSection(c?.[f],d[f]);if(g)e[f]=g;}return d['preferences']&&(e['preferences']={...c?.['preferences']??{},...d['preferences']}),Object['keys'](e)['length']>0x0?e:undefined;}export function mergeProfileMaps(c,d){if(!d)return c;const e={...c??{}};for(const [f,g]of Object['entries'](d)){e[f]=mergeRoleProfiles(e[f],g);}return Object['keys'](e)['length']>0x0?e:undefined;}export function mergeLayers(a,b){const c={},d=[];for(let e=0x0;e<a['length'];e++){const f=a[e];if(!f)continue;d['push']({'layer':f,'part':b?.[e]?.['part']??'long_term','group':b?.[e]?.['group']??0x0}),f['identity']&&(c['identity']={...c['identity'],...f['identity']},f['identity']['languages']&&(c['identity']['languages']=dedupe([...c['identity']['languages']??[],...f['identity']['languages']]))),f['preferences']&&(c['preferences']={...c['preferences'],...f['preferences']}),f['strategy']&&(c['strategy']=dedupe([...c['strategy']??[],...f['strategy']])),f['rules']&&(c['rules']=dedupe([...c['rules']??[],...f['rules']])),f['requirements']&&(c['requirements']=dedupe([...c['requirements']??[],...f['requirements']])),f['spec']&&(c['spec']=[c['spec'],f['spec']]['filter'](Boolean)['join']('\x0a\x0a')),f['profiles']&&(c['profiles']=mergeProfileMaps(c['profiles'],f['profiles'])),f['analyze']?.['key_questions']?.['length']&&(c['analyze']={...c['analyze'],'key_questions':dedupe([...c['analyze']?.['key_questions']??[],...f['analyze']['key_questions']])});}if(b){const g=mergeSafetyControls(d);if(g['overrides'])c['overrides']=g['overrides'];if(g['policy'])c['policy']=g['policy'];}else for(const {layer:h}of d){if(h['overrides'])c['overrides']={...c['overrides'],...h['overrides']};if(h['policy'])c['policy']=mergePolicySequence([c['policy']??{},h['policy']]);}return c;}export function effectiveAnalyzeQuestions(a){return(a?.['analyze']?.['key_questions']??[])['slice'](0x0,0x2);}const AI_DELTA_FORBIDDEN_KEYS=['policy','overrides'];export function assertAiCurrentDelta(a){for(const b of AI_DELTA_FORBIDDEN_KEYS){if(b in a)throw new Error('AI-generated\x20persona\x20delta\x20must\x20not\x20contain\x20\x27'+b+'\x27:\x20safety\x20controls\x20are\x20user-driven\x20only\x20'+'(use\x20persona_operation\x20action=\x27set\x27\x20with\x20an\x20explicit\x20user\x20payload)');}}export function mutateLayer(a,b,c){if(c==='replace')return{...b};return mergeLayers([a,b]);}function isEmptyLayer(a){return!a||Object['keys'](a)['length']===0x0;}export function resolveEffective(a,b,c){const d=[],e=[],f=[],g=(j,k,l,m,n)=>{d['push'](k),e['push']({'part':l,'group':m}),f['push'](n==='account'?{'scope':n,'account':j['account'],'part':l}:{'scope':n,'part':l});};a&&(g(a,a['long_term'],'long_term',0x0,'system'),g(a,a['current'],'current',0x0,'system'));c&&(g(c,c['long_term'],'long_term',0x1,c['scope']),g(c,c['current'],'current',0x1,c['scope']));b&&(g(b,b['long_term'],'long_term',0x2,'account'),g(b,b['current'],'current',0x2,'account'));const h=!!b&&(!isEmptyLayer(b['long_term'])||!isEmptyLayer(b['current'])),i=h?b:c??a;return{'scope':b?'account':'system','account':b?.['account']??a?.['account'],'role':i?.['role']??'customer','industries':i?.['industries']??[],'layer':mergeLayers(d,e),'sources':f};}export function countPersonaLines(a){return JSON['stringify'](a,null,0x2)['split']('\x0a')['length'];}export function validateLayerPolicy(a,b){const d=[],e=a['policy'];if(!e)return d;const f='policy\x20('+b+')';if(e['confirm']){const g=e['confirm'];g['mode']!==undefined&&!['full','streamlined','quiet']['includes'](g['mode'])&&d['push'](f+'.confirm.mode\x20must\x20be\x20full|streamlined|quiet');for(const h of['batch_standard','intent_bypass']){g[h]!==undefined&&typeof g[h]!=='boolean'&&d['push'](f+'.confirm.'+h+'\x20must\x20be\x20a\x20boolean');}g['session_remember']!==undefined&&((!Array['isArray'](g['session_remember'])||!g['session_remember']['every'](i=>typeof i==='string'))&&d['push'](f+'.confirm.session_remember\x20must\x20be\x20an\x20array\x20of\x20strings'));}if(e['budget']?.['daily_wow']!==undefined&&e['budget']['daily_wow']!==null){const i=e['budget']['daily_wow'];(typeof i!=='string'||!/^\d+$/['test'](i['trim']()))&&d['push'](f+'.budget.daily_wow\x20must\x20be\x20a\x20decimal\x20string\x20(WOW\x20base\x20units)\x20or\x20null');}return e['allowlist']!==undefined&&((!Array['isArray'](e['allowlist'])||!e['allowlist']['every'](j=>typeof j==='string'))&&d['push'](f+'.allowlist\x20must\x20be\x20an\x20array\x20of\x20address\x20strings')),e['audit']!==undefined&&typeof e['audit']!=='boolean'&&d['push'](f+'.audit\x20must\x20be\x20a\x20boolean'),d;}const ENUM_FIELDS={'consumption.frequency':['rare','occasional','regular','frequent'],'consumption.price_band':['budget','mid','premium','luxury'],'consumption.decision_speed':['fast','deliberate','slow'],'consumption.repeat_orientation':['novelty','balanced','loyal'],'merchant.posture':['volume','balanced','margin'],'merchant.pricing_style':['competitive','value','premium','custom_quote'],'collaborator.scope_discipline':['strict','balanced','flexible'],'collaborator.notifications':['minimal','digest','realtime'],'arbitrator.response_speed':['fast','standard','thorough'],'arbitrator.ruling_style':['concise','detailed'],'demander.rfp_openness':['open','passport_gated','invite_only']},STRING_ARRAY_FIELDS=['tastes.materials','tastes.colors','tastes.styles','tastes.tags','tastes.brands','tastes.avoid','consumption.channels','consumption.notes','merchant.service_style','merchant.growth_focus','supplier.settlement_terms','supplier.categories','collaborator.advance_style','arbitrator.case_types','demander.decision_basis'],STRING_FIELDS=['consumption.avg_order_range','merchant.communication','supplier.min_order','supplier.lead_time','supplier.capacity','collaborator.working_hours','demander.pilot_budget'];function isObject(a){return typeof a==='object'&&a!==null&&!Array['isArray'](a);}export function validateLayerProfiles(a,b){const c=[],d=a['profiles'];if(!d)return c;if(!isObject(d))return c['push']('profiles\x20('+b+')\x20must\x20be\x20an\x20object\x20keyed\x20by\x20persona\x20role'),c;for(const [e,f]of Object['entries'](d)){const g='profiles.'+e+'\x20('+b+')';if(!PERSONA_ROLES['includes'](e)){c['push'](g+':\x20unknown\x20role\x20\x27'+e+'\x27');continue;}if(!isObject(f)){c['push'](g+'\x20must\x20be\x20an\x20object');continue;}for(const [h,i]of Object['entries'](f)){if(h==='preferences'){if(!isObject(i))c['push'](g+'.preferences\x20must\x20be\x20an\x20object');continue;}if(h==='topology'){const j=normalizeTopologyFocusPref(i);!j&&Object['keys'](isObject(i)?i:{})['length']>0x0&&c['push'](g+'.topology\x20has\x20no\x20valid\x20field\x20(see\x20TopologyFocusPref)');continue;}if(!ROLE_PROFILE_SECTIONS['includes'](h)){c['push'](g+':\x20unknown\x20section\x20\x27'+h+'\x27');continue;}if(!isObject(i)){c['push'](g+'.'+h+'\x20must\x20be\x20an\x20object');continue;}for(const [k,l]of Object['entries'](i)){const m=h+'.'+k,n=ENUM_FIELDS[m];if(n){(typeof l!=='string'||!n['includes'](l))&&c['push'](g+'.'+m+'\x20must\x20be\x20one\x20of:\x20'+n['join']('|'));continue;}if(STRING_ARRAY_FIELDS['includes'](m)){(!Array['isArray'](l)||!l['every'](o=>typeof o==='string'))&&c['push'](g+'.'+m+'\x20must\x20be\x20an\x20array\x20of\x20strings');continue;}if(STRING_FIELDS['includes'](m)){if(typeof l!=='string')c['push'](g+'.'+m+'\x20must\x20be\x20a\x20string');continue;}if(k==='award_weights'){(!isObject(l)||!Object['values'](l)['every'](o=>typeof o==='number'&&isFinite(o)))&&c['push'](g+'.demander.award_weights\x20must\x20be\x20an\x20object\x20of\x20finite\x20numbers');continue;}c['push'](g+'.'+m+'\x20is\x20not\x20a\x20known\x20field');}}}return c;}export function validatePersona(a){const b=[];a['version']!==PERSONA_VERSION&&b['push']('version\x20must\x20be\x20'+PERSONA_VERSION);a['scope']==='account'&&!a['account']&&b['push']('account\x20is\x20required\x20when\x20scope=account');a['scope']!=='account'&&a['account']&&b['push']('account\x20should\x20only\x20be\x20set\x20when\x20scope=account');(!a['role']||!PERSONA_ROLES['includes'](a['role']))&&b['push']('role\x20must\x20be\x20a\x20persona\x20role\x20(merchant|customer|demander|prospect|supplier|collaborator|arbitrator)');!Array['isArray'](a['industries'])&&b['push']('industries\x20must\x20be\x20an\x20array');b['push'](...validateLayerOverrides(a['long_term'])),b['push'](...validateLayerOverrides(a['current'])),b['push'](...validateLayerPolicy(a['long_term'],'long_term')),b['push'](...validateLayerPolicy(a['current'],'current')),b['push'](...validateLayerProfiles(a['long_term'],'long_term')),b['push'](...validateLayerProfiles(a['current'],'current'));const c=countPersonaLines(a);return c>PERSONA_MAX_LINES&&b['push']('persona\x20is\x20'+c+'\x20lines\x20(max\x20'+PERSONA_MAX_LINES+')'),b;}export function emptyPersona(a,b,c,d){return{'version':PERSONA_VERSION,'scope':a,'account':b,'role':c,'industries':d,'long_term':{},'current':{},'updated_at':Date['now']()};}
1
+ import{PERSONA_MAX_LINES,PERSONA_ROLES,PERSONA_VERSION}from'./types.js';import{validateLayerOverrides}from'./overrides.js';import{normalizeTopologyFocusPref}from'../graph/onchain/strategy.js';function dedupe(a){return Array['from'](new Set(a['filter'](b=>typeof b==='string'&&b['length']>0x0)));}const OVERRIDE_RANK={'auto':0x0,'warn':0x1,'prompt':0x2,'block':0x3},MODE_SUPPRESSION_RANK={'full':0x0,'streamlined':0x1,'quiet':0x2};function stricterOverride(c,d){if(!c)return d;if(!d)return c;return OVERRIDE_RANK[c]>=OVERRIDE_RANK[d]?c:d;}function mergePolicySequence(a){const b={};for(const c of a){if(!c)continue;if(c['confirm'])b['confirm']={...b['confirm'],...c['confirm']};if(c['budget'])b['budget']={...b['budget'],...c['budget']};if(c['allowlist']!==undefined)b['allowlist']=c['allowlist'];if(c['audit']!==undefined)b['audit']=c['audit'];}return b;}function parseDailyWow(a){if(a===undefined)return undefined;if(a===null)return null;if(!/^\d+$/['test'](a['trim']()))return undefined;try{return BigInt(a['trim']());}catch{return undefined;}}function tightenPolicy(a,b){const c={},d=a['confirm']?.['mode'],e=b['confirm']?.['mode'];let f=d;if(e){if(!d)f=e;else{if(MODE_SUPPRESSION_RANK[e]<MODE_SUPPRESSION_RANK[d])f=e;}}const g=a['confirm']?.['batch_standard'],h=a['confirm']?.['session_remember'];let i=a['confirm']?.['intent_bypass'];if(b['confirm']?.['intent_bypass']===![])i=![];if(f!==undefined||g!==undefined||h!==undefined||i!==undefined){c['confirm']={};if(f!==undefined)c['confirm']['mode']=f;if(g!==undefined)c['confirm']['batch_standard']=g;if(h!==undefined)c['confirm']['session_remember']=h;if(i!==undefined)c['confirm']['intent_bypass']=i;}const j=parseDailyWow(a['budget']?.['daily_wow']),k=parseDailyWow(b['budget']?.['daily_wow']);let l=j;if(k!==undefined){if(j===undefined)l=k;else{if(j===null)l=k;else{if(k!==null)l=j<k?j:k;}}}if(l!==undefined)c['budget']={'daily_wow':l===null?null:l['toString']()};if(a['allowlist']!==undefined)c['allowlist']=a['allowlist'];const m=a['audit']===!![]||b['audit']===!![];if(m)c['audit']=!![];return c;}function clampOverrideMap(a,b){const c={...a};for(const [d,e]of Object['entries'](b)){c[d]=stricterOverride(a[d],e)??e;}return c;}function mergeSafetyControls(a){const b=new Map(),c=new Map(),d=new Map(),e=new Map(),f=(l,n)=>{let o=l['get'](n);return!o&&(o={},l['set'](n,o)),o;},g=(l,m)=>{let n=l['get'](m);return!n&&(n=[],l['set'](m,n)),n;};for(const {layer:l,part:m,group:n}of a){l['overrides']&&Object['assign'](f(m==='current'?c:b,n),l['overrides']);if(l['policy'])g(m==='current'?e:d,n)['push'](l['policy']);}const h=Array['from'](new Set(a['map'](o=>o['group'])))['sort']((o,p)=>o-p);let i={};const j=[];for(const o of h){const p=clampOverrideMap(b['get'](o)??{},c['get'](o)??{});i={...i,...p};const q=tightenPolicy(mergePolicySequence(d['get'](o)??[]),mergePolicySequence(e['get'](o)??[]));j['push'](q);}const k=mergePolicySequence(j);return{'overrides':Object['keys'](i)['length']>0x0?i:undefined,'policy':Object['keys'](k)['length']>0x0?k:undefined};}const ROLE_PROFILE_SECTIONS=['tastes','consumption','merchant','supplier','collaborator','arbitrator','demander','topology'];function isPlainObject(a){return typeof a==='object'&&a!==null&&!Array['isArray'](a);}function mergeProfileSection(c,d){if(!d)return c;const e={...c??{}};for(const [f,g]of Object['entries'](d)){const h=e[f];if(Array['isArray'](g)){const i=Array['isArray'](h)?[...h,...g]:g;e[f]=dedupe(i['filter'](j=>typeof j==='string'));}else isPlainObject(g)?e[f]=isPlainObject(h)?{...h,...g}:{...g}:e[f]=g;}return Object['keys'](e)['length']>0x0?e:undefined;}export function mergeRoleProfiles(c,d){if(!d)return c;const e={...c??{}};for(const f of ROLE_PROFILE_SECTIONS){const g=mergeProfileSection(c?.[f],d[f]);if(g)e[f]=g;}return d['preferences']&&(e['preferences']={...c?.['preferences']??{},...d['preferences']}),Object['keys'](e)['length']>0x0?e:undefined;}export function mergeProfileMaps(c,d){if(!d)return c;const e={...c??{}};for(const [f,g]of Object['entries'](d)){e[f]=mergeRoleProfiles(e[f],g);}return Object['keys'](e)['length']>0x0?e:undefined;}export function mergeFacetSettings(c,d){if(!d)return c;const e={...c??{}};for(const [f,g]of Object['entries'](d)){const h=e[f]??{},i={...g['visible']!==undefined?{'visible':g['visible']}:{},...g['order']!==undefined?{'order':g['order']}:{},...g['weight']!==undefined?{'weight':g['weight']}:{},...g['threshold']!==undefined?{'threshold':g['threshold']}:{}},j={...h['visible']!==undefined&&i['visible']===undefined?{'visible':h['visible']}:{},...h['order']!==undefined&&i['order']===undefined?{'order':h['order']}:{},...h['weight']!==undefined&&i['weight']===undefined?{'weight':h['weight']}:{},...h['threshold']!==undefined&&i['threshold']===undefined?{'threshold':h['threshold']}:{},...i};e[f]=j;}return Object['keys'](e)['length']>0x0?e:undefined;}export function mergeLayers(a,b){const c={},d=[];for(let e=0x0;e<a['length'];e++){const f=a[e];if(!f)continue;d['push']({'layer':f,'part':b?.[e]?.['part']??'long_term','group':b?.[e]?.['group']??0x0}),f['identity']&&(c['identity']={...c['identity'],...f['identity']},f['identity']['languages']&&(c['identity']['languages']=dedupe([...c['identity']['languages']??[],...f['identity']['languages']]))),f['preferences']&&(c['preferences']={...c['preferences'],...f['preferences']}),f['strategy']&&(c['strategy']=dedupe([...c['strategy']??[],...f['strategy']])),f['rules']&&(c['rules']=dedupe([...c['rules']??[],...f['rules']])),f['requirements']&&(c['requirements']=dedupe([...c['requirements']??[],...f['requirements']])),f['spec']&&(c['spec']=[c['spec'],f['spec']]['filter'](Boolean)['join']('\x0a\x0a')),f['profiles']&&(c['profiles']=mergeProfileMaps(c['profiles'],f['profiles'])),f['analyze']?.['key_questions']?.['length']&&(c['analyze']={...c['analyze'],'key_questions':dedupe([...c['analyze']?.['key_questions']??[],...f['analyze']['key_questions']])}),f['evaluation']&&(c['evaluation']={...c['evaluation'],'weights':{...c['evaluation']?.['weights']??{},...f['evaluation']['weights']},...f['evaluation']['facets']?{'facets':mergeFacetSettings(c['evaluation']?.['facets'],f['evaluation']['facets'])}:{}});}if(b){const g=mergeSafetyControls(d);if(g['overrides'])c['overrides']=g['overrides'];if(g['policy'])c['policy']=g['policy'];}else for(const {layer:h}of d){if(h['overrides'])c['overrides']={...c['overrides'],...h['overrides']};if(h['policy'])c['policy']=mergePolicySequence([c['policy']??{},h['policy']]);}return c;}export function effectiveAnalyzeQuestions(a){return(a?.['analyze']?.['key_questions']??[])['slice'](0x0,0x2);}const AI_DELTA_FORBIDDEN_KEYS=['policy','overrides'];export function assertAiCurrentDelta(a){for(const b of AI_DELTA_FORBIDDEN_KEYS){if(b in a)throw new Error('AI-generated\x20persona\x20delta\x20must\x20not\x20contain\x20\x27'+b+'\x27:\x20safety\x20controls\x20are\x20user-driven\x20only\x20'+'(use\x20persona_operation\x20action=\x27set\x27\x20with\x20an\x20explicit\x20user\x20payload)');}}export function mutateLayer(a,b,c){if(c==='replace')return{...b};return mergeLayers([a,b]);}function isEmptyLayer(a){return!a||Object['keys'](a)['length']===0x0;}export function resolveEffective(a,b,c){const d=[],e=[],f=[],g=(j,k,l,m,n)=>{d['push'](k),e['push']({'part':l,'group':m}),f['push'](n==='account'?{'scope':n,'account':j['account'],'part':l}:{'scope':n,'part':l});};a&&(g(a,a['long_term'],'long_term',0x0,'system'),g(a,a['current'],'current',0x0,'system'));c&&(g(c,c['long_term'],'long_term',0x1,c['scope']),g(c,c['current'],'current',0x1,c['scope']));b&&(g(b,b['long_term'],'long_term',0x2,'account'),g(b,b['current'],'current',0x2,'account'));const h=!!b&&(!isEmptyLayer(b['long_term'])||!isEmptyLayer(b['current'])),i=h?b:c??a;return{'scope':b?'account':'system','account':b?.['account']??a?.['account'],'role':i?.['role']??'customer','industries':i?.['industries']??[],'layer':mergeLayers(d,e),'sources':f};}export function countPersonaLines(a){return JSON['stringify'](a,null,0x2)['split']('\x0a')['length'];}export function validateLayerPolicy(a,b){const d=[],e=a['policy'];if(!e)return d;const f='policy\x20('+b+')';if(e['confirm']){const g=e['confirm'];g['mode']!==undefined&&!['full','streamlined','quiet']['includes'](g['mode'])&&d['push'](f+'.confirm.mode\x20must\x20be\x20full|streamlined|quiet');for(const h of['batch_standard','intent_bypass']){g[h]!==undefined&&typeof g[h]!=='boolean'&&d['push'](f+'.confirm.'+h+'\x20must\x20be\x20a\x20boolean');}g['session_remember']!==undefined&&((!Array['isArray'](g['session_remember'])||!g['session_remember']['every'](i=>typeof i==='string'))&&d['push'](f+'.confirm.session_remember\x20must\x20be\x20an\x20array\x20of\x20strings'));}if(e['budget']?.['daily_wow']!==undefined&&e['budget']['daily_wow']!==null){const i=e['budget']['daily_wow'];(typeof i!=='string'||!/^\d+$/['test'](i['trim']()))&&d['push'](f+'.budget.daily_wow\x20must\x20be\x20a\x20decimal\x20string\x20(WOW\x20base\x20units)\x20or\x20null');}return e['allowlist']!==undefined&&((!Array['isArray'](e['allowlist'])||!e['allowlist']['every'](j=>typeof j==='string'))&&d['push'](f+'.allowlist\x20must\x20be\x20an\x20array\x20of\x20address\x20strings')),e['audit']!==undefined&&typeof e['audit']!=='boolean'&&d['push'](f+'.audit\x20must\x20be\x20a\x20boolean'),d;}const ENUM_FIELDS={'consumption.frequency':['rare','occasional','regular','frequent'],'consumption.price_band':['budget','mid','premium','luxury'],'consumption.decision_speed':['fast','deliberate','slow'],'consumption.repeat_orientation':['novelty','balanced','loyal'],'merchant.posture':['volume','balanced','margin'],'merchant.pricing_style':['competitive','value','premium','custom_quote'],'collaborator.scope_discipline':['strict','balanced','flexible'],'collaborator.notifications':['minimal','digest','realtime'],'arbitrator.response_speed':['fast','standard','thorough'],'arbitrator.ruling_style':['concise','detailed'],'demander.rfp_openness':['open','passport_gated','invite_only']},STRING_ARRAY_FIELDS=['tastes.materials','tastes.colors','tastes.styles','tastes.tags','tastes.brands','tastes.avoid','consumption.channels','consumption.notes','merchant.service_style','merchant.growth_focus','supplier.settlement_terms','supplier.categories','collaborator.advance_style','arbitrator.case_types','demander.decision_basis'],STRING_FIELDS=['consumption.avg_order_range','merchant.communication','supplier.min_order','supplier.lead_time','supplier.capacity','collaborator.working_hours','demander.pilot_budget'];function isObject(a){return typeof a==='object'&&a!==null&&!Array['isArray'](a);}export function validateLayerProfiles(a,b){const c=[],d=a['profiles'];if(!d)return c;if(!isObject(d))return c['push']('profiles\x20('+b+')\x20must\x20be\x20an\x20object\x20keyed\x20by\x20persona\x20role'),c;for(const [e,f]of Object['entries'](d)){const g='profiles.'+e+'\x20('+b+')';if(!PERSONA_ROLES['includes'](e)){c['push'](g+':\x20unknown\x20role\x20\x27'+e+'\x27');continue;}if(!isObject(f)){c['push'](g+'\x20must\x20be\x20an\x20object');continue;}for(const [h,i]of Object['entries'](f)){if(h==='preferences'){if(!isObject(i))c['push'](g+'.preferences\x20must\x20be\x20an\x20object');continue;}if(h==='topology'){const j=normalizeTopologyFocusPref(i);!j&&Object['keys'](isObject(i)?i:{})['length']>0x0&&c['push'](g+'.topology\x20has\x20no\x20valid\x20field\x20(see\x20TopologyFocusPref)');continue;}if(!ROLE_PROFILE_SECTIONS['includes'](h)){c['push'](g+':\x20unknown\x20section\x20\x27'+h+'\x27');continue;}if(!isObject(i)){c['push'](g+'.'+h+'\x20must\x20be\x20an\x20object');continue;}for(const [k,l]of Object['entries'](i)){const m=h+'.'+k,n=ENUM_FIELDS[m];if(n){(typeof l!=='string'||!n['includes'](l))&&c['push'](g+'.'+m+'\x20must\x20be\x20one\x20of:\x20'+n['join']('|'));continue;}if(STRING_ARRAY_FIELDS['includes'](m)){(!Array['isArray'](l)||!l['every'](o=>typeof o==='string'))&&c['push'](g+'.'+m+'\x20must\x20be\x20an\x20array\x20of\x20strings');continue;}if(STRING_FIELDS['includes'](m)){if(typeof l!=='string')c['push'](g+'.'+m+'\x20must\x20be\x20a\x20string');continue;}if(k==='award_weights'){(!isObject(l)||!Object['values'](l)['every'](o=>typeof o==='number'&&isFinite(o)))&&c['push'](g+'.demander.award_weights\x20must\x20be\x20an\x20object\x20of\x20finite\x20numbers');continue;}c['push'](g+'.'+m+'\x20is\x20not\x20a\x20known\x20field');}}}return c;}export function validatePersona(a){const b=[];a['version']!==PERSONA_VERSION&&b['push']('version\x20must\x20be\x20'+PERSONA_VERSION);a['scope']==='account'&&!a['account']&&b['push']('account\x20is\x20required\x20when\x20scope=account');a['scope']!=='account'&&a['account']&&b['push']('account\x20should\x20only\x20be\x20set\x20when\x20scope=account');(!a['role']||!PERSONA_ROLES['includes'](a['role']))&&b['push']('role\x20must\x20be\x20a\x20persona\x20role\x20(merchant|customer|demander|prospect|supplier|collaborator|arbitrator)');!Array['isArray'](a['industries'])&&b['push']('industries\x20must\x20be\x20an\x20array');b['push'](...validateLayerOverrides(a['long_term'])),b['push'](...validateLayerOverrides(a['current'])),b['push'](...validateLayerPolicy(a['long_term'],'long_term')),b['push'](...validateLayerPolicy(a['current'],'current')),b['push'](...validateLayerProfiles(a['long_term'],'long_term')),b['push'](...validateLayerProfiles(a['current'],'current'));const c=countPersonaLines(a);return c>PERSONA_MAX_LINES&&b['push']('persona\x20is\x20'+c+'\x20lines\x20(max\x20'+PERSONA_MAX_LINES+')'),b;}export function emptyPersona(a,b,c,d){return{'version':PERSONA_VERSION,'scope':a,'account':b,'role':c,'industries':d,'long_term':{},'current':{},'updated_at':Date['now']()};}
@@ -1 +1 @@
1
- export const STRATEGY_LEVER_MAP={'sales_priority':['discount','reward'],'profit_priority':['discount','machine_design'],'buyer_screening':['buy_guard'],'gross_margin_control':['discount','machine_design']};const LEVER_ACTION={'discount':'issue/limit\x20Service.discount\x20coupons\x20(DISCOUNT_TYPE_RATES/MINUS)\x20to\x20steer\x20SKU\x20volume\x20vs\x20margin','reward':'bind\x20a\x20Reward\x20to\x20Service.rewards\x20and\x20gate\x20it\x20by\x20a\x20Guard\x20to\x20incentivize\x20the\x20target\x20segment','buy_guard':'set\x20Service.buy_guard\x20(post-publish\x20mutable)\x20to\x20qualify/restrict\x20eligible\x20buyers','machine_design':'adjust\x20Machine\x20topology/guards\x20(design-time)\x20to\x20enforce\x20the\x20target\x20acceptance\x20flow'};export function resolveObjective(a){if(!a)return null;const b=a['toLowerCase']();if(/(margin|profit|毛利率|利润)/['test'](b))return'gross_margin_control';if(/(volume|sales|销量|sell more|销量优先)/['test'](b))return'sales_priority';if(/(screen|qualify|filter|筛选|筛选购买人|eligible buyer)/['test'](b))return'buyer_screening';if(/(profit first|利润优先|margin first)/['test'](b))return'profit_priority';return null;}export function buildStrategyIntent(a,b,c){return{'objective':a,'metrics':c??[],'levers':STRATEGY_LEVER_MAP[a]??[],'target':b??''};}export function suggestLevers(a){return a['levers']['map'](b=>({'lever':b,'objective':a['objective'],'action':LEVER_ACTION[b],'target':a['target']}));}export function resolveStrategyIntents(a,b){if(a!=='merchant')return[];const c=[];for(const d of b??[]){const e=resolveObjective(d);if(e)c['push'](buildStrategyIntent(e,d));}return c;}
1
+ export const STRATEGY_LEVER_MAP={'sales_priority':['discount','reward'],'profit_priority':['discount','machine_design'],'buyer_screening':['buy_guard'],'gross_margin_control':['discount','machine_design']};const LEVER_ACTION={'discount':'issue/limit\x20Service.discount\x20coupons\x20(DISCOUNT_TYPE_RATES/MINUS)\x20to\x20steer\x20SKU\x20volume\x20vs\x20margin','reward':'bind\x20a\x20Reward\x20to\x20Service.rewards\x20and\x20gate\x20it\x20by\x20a\x20Guard\x20to\x20incentivize\x20the\x20target\x20segment','buy_guard':'set\x20Service.buy_guard\x20(post-publish\x20mutable)\x20to\x20qualify/restrict\x20eligible\x20buyers','machine_design':'adjust\x20Machine\x20topology/guards\x20(design-time)\x20to\x20enforce\x20the\x20target\x20acceptance\x20flow'};export function resolveObjective(a){if(!a)return null;const b=a['toLowerCase']();if(/(margin|profit)/['test'](b))return'gross_margin_control';if(/(volume|sales|sell more)/['test'](b))return'sales_priority';if(/(screen|qualify|filter|eligible buyer)/['test'](b))return'buyer_screening';if(/(profit first|margin first)/['test'](b))return'profit_priority';return null;}export function buildStrategyIntent(a,b,c){return{'objective':a,'metrics':c??[],'levers':STRATEGY_LEVER_MAP[a]??[],'target':b??''};}export function suggestLevers(a){return a['levers']['map'](b=>({'lever':b,'objective':a['objective'],'action':LEVER_ACTION[b],'target':a['target']}));}export function resolveStrategyIntents(a,b){if(a!=='merchant')return[];const c=[];for(const d of b??[]){const e=resolveObjective(d);if(e)c['push'](buildStrategyIntent(e,d));}return c;}
@@ -1,9 +1,8 @@
1
- import type { Industry, PersonaRole } from "./types.js";
1
+ import type { Industry, PersonaEvaluationStandards, PersonaRole } from "./types.js";
2
2
  import type { PersonaDrive } from "../evaluation/game-strategy.js";
3
3
  import { type StrategyFragment, type TopologyFocusPref, type TopologyIntent } from "../graph/onchain/strategy.js";
4
4
  export interface RoleTopologyDefault {
5
5
  intents: TopologyIntent[];
6
- fragment?: StrategyFragment;
7
6
  rationale: string;
8
7
  }
9
8
  export declare const ROLE_TOPOLOGY_DEFAULTS: Record<PersonaRole, RoleTopologyDefault>;
@@ -19,6 +18,7 @@ export interface ResolvedTopologyContext {
19
18
  personaPref?: TopologyFocusPref;
20
19
  drive?: PersonaDrive;
21
20
  personaRole?: PersonaRole;
21
+ evaluation?: PersonaEvaluationStandards;
22
22
  }
23
23
  export declare function resolveTopologyContext(params: {
24
24
  account?: string;
@@ -1 +1 @@
1
- import{getEffectivePersona}from'./index.js';import{INTENT_PRESETS,isTopologyIntent,normalizeTopologyFocusPref}from'../graph/onchain/strategy.js';export const ROLE_TOPOLOGY_DEFAULTS={'customer':{'intents':['order_health','counterparty'],'rationale':'track\x20own\x20orders\x20to\x20completion\x20and\x20know\x20who\x20is\x20on\x20the\x20other\x20side'},'prospect':{'intents':['counterparty','reputation','fund_flow'],'rationale':'pre-order\x20due\x20diligence:\x20seller\x20credibility,\x20fund\x20safety,\x20social\x20proof'},'merchant':{'intents':['order_health','supply_chain'],'rationale':'track\x20incoming\x20orders\x20and\x20the\x20settlement\x20waterfall\x20of\x20each'},'supplier':{'intents':['supply_chain','workflow'],'rationale':'sub-order\x20settlement\x20structure\x20and\x20the\x20process\x20it\x20hangs\x20on'},'collaborator':{'intents':['workflow','permission'],'rationale':'which\x20forwards\x20exist\x20and\x20what\x20is\x20within\x20own\x20permission\x20scope'},'arbitrator':{'intents':['arbitration','reputation'],'rationale':'cases\x20at\x20hand\x20plus\x20the\x20parties\x27\x20track\x20record'},'demander':{'intents':['demand_match','counterparty'],'rationale':'evaluate\x20presenters\x20against\x20the\x20demand\x20and\x20know\x20who\x20they\x20are'}};export const INDUSTRY_TOPOLOGY_DEFAULTS={'freelance':{'label':'freelance','familyDepths':{'W':0x4,'M':0x3},'tableEdges':['machine.node']},'rental':{'label':'rental','familyDepths':{'M':0x4,'W':0x2}},'education':{'label':'education','familyDepths':{'W':0x4,'M':0x2},'tableEdges':['machine.node']},'travel':{'label':'travel','familyDepths':{'W':0x4,'M':0x3},'tableEdges':['machine.node']},'subscription':{'label':'subscription','familyDepths':{'M':0x3,'W':0x2}},'retail':{'label':'retail','familyDepths':{'M':0x3}}};export function getIndustryTopologyTemplate(a){if(!a)return undefined;return INDUSTRY_TOPOLOGY_DEFAULTS[a];}export async function resolvePersonaTopologyFocus(a,b,c){try{const d=await getEffectivePersona(a,b,c),e=c??d['role'],f=d['layer']['profiles']?.[e]?.['topology'];if(f===undefined)return undefined;return normalizeTopologyFocusPref(f)??undefined;}catch{return undefined;}}export async function resolveTopologyContext(a){const b=a['role']?ROLE_TOPOLOGY_DEFAULTS[a['role']]:undefined,c=getIndustryTopologyTemplate(a['industry']);let d,e,f;try{const g=await getEffectivePersona(a['account'],a['industry'],a['role']),h=a['role']??g['role'];f=h;const i=g['layer']['profiles']?.[h]?.['topology'];if(i!==undefined)d=normalizeTopologyFocusPref(i)??undefined;const j=g['layer']['preferences']?.['risk_appetite'],k=j==='conservative'||j==='balanced'||j==='aggressive'?j:undefined,l=g['layer']['requirements'];(k!=null||(l?.['length']??0x0)>0x0)&&(e={...k!=null?{'risk_appetite':k}:{},...l?.['length']?{'requirements':l}:{}});}catch{}return{'roleDefault':b,'industryTemplate':c,'personaPref':d,'drive':e,...f?{'personaRole':f}:{}};}export function describeIntents(){return Object['entries'](INTENT_PRESETS)['map'](([a,b])=>{const c=b['families']?'\x20families\x20'+b['families']['join']('/'):'',d=b['familyDepths']?'\x20depths\x20'+Object['entries'](b['familyDepths'])['map'](([e,g])=>e+'≤'+g)['join']('\x20'):'';return a+':\x20'+b['description']+c+d;});}export function assertIntent(a){if(!isTopologyIntent(a))throw new Error('unknown\x20topology\x20intent\x20\x27'+a+'\x27\x20(valid:\x20'+Object['keys'](INTENT_PRESETS)['join'](',\x20')+')');return a;}
1
+ import{getEffectivePersona}from'./index.js';import{INTENT_PRESETS,isTopologyIntent,normalizeTopologyFocusPref}from'../graph/onchain/strategy.js';export const ROLE_TOPOLOGY_DEFAULTS={'customer':{'intents':['order_health','counterparty'],'rationale':'track\x20own\x20orders\x20to\x20completion\x20and\x20know\x20who\x20is\x20on\x20the\x20other\x20side'},'prospect':{'intents':['counterparty','reputation','fund_flow'],'rationale':'pre-order\x20due\x20diligence:\x20seller\x20credibility,\x20fund\x20safety,\x20social\x20proof'},'merchant':{'intents':['order_health','supply_chain'],'rationale':'track\x20incoming\x20orders\x20and\x20the\x20settlement\x20waterfall\x20of\x20each'},'supplier':{'intents':['supply_chain','workflow'],'rationale':'sub-order\x20settlement\x20structure\x20and\x20the\x20process\x20it\x20hangs\x20on'},'collaborator':{'intents':['workflow','permission'],'rationale':'which\x20forwards\x20exist\x20and\x20what\x20is\x20within\x20own\x20permission\x20scope'},'arbitrator':{'intents':['arbitration','reputation'],'rationale':'cases\x20at\x20hand\x20plus\x20the\x20parties\x27\x20track\x20record'},'demander':{'intents':['demand_match','counterparty'],'rationale':'evaluate\x20presenters\x20against\x20the\x20demand\x20and\x20know\x20who\x20they\x20are'}};export const INDUSTRY_TOPOLOGY_DEFAULTS={'freelance':{'label':'freelance','familyDepths':{'W':0x4,'M':0x3},'tableEdges':['machine.node']},'rental':{'label':'rental','familyDepths':{'M':0x4,'W':0x2}},'education':{'label':'education','familyDepths':{'W':0x4,'M':0x2},'tableEdges':['machine.node']},'travel':{'label':'travel','familyDepths':{'W':0x4,'M':0x3},'tableEdges':['machine.node']},'subscription':{'label':'subscription','familyDepths':{'M':0x3,'W':0x2}},'retail':{'label':'retail','familyDepths':{'M':0x3}}};export function getIndustryTopologyTemplate(a){if(!a)return undefined;return INDUSTRY_TOPOLOGY_DEFAULTS[a];}export async function resolvePersonaTopologyFocus(a,b,c){try{const d=await getEffectivePersona(a,b,c),e=c??d['role'],f=d['layer']['profiles']?.[e]?.['topology'];if(f===undefined)return undefined;return normalizeTopologyFocusPref(f)??undefined;}catch{return undefined;}}export async function resolveTopologyContext(a){const b=a['role']?ROLE_TOPOLOGY_DEFAULTS[a['role']]:undefined,c=getIndustryTopologyTemplate(a['industry']);let d,e,f,g;try{const h=await getEffectivePersona(a['account'],a['industry'],a['role']),i=a['role']??h['role'];f=i,g=h['layer']['evaluation'];const j=h['layer']['profiles']?.[i]?.['topology'];if(j!==undefined)d=normalizeTopologyFocusPref(j)??undefined;const k=h['layer']['preferences']?.['risk_appetite'],l=k==='conservative'||k==='balanced'||k==='aggressive'?k:undefined,m=h['layer']['requirements'];(l!=null||(m?.['length']??0x0)>0x0)&&(e={...l!=null?{'risk_appetite':l}:{},...m?.['length']?{'requirements':m}:{}});}catch{}return{'roleDefault':b,'industryTemplate':c,'personaPref':d,'drive':e,...f?{'personaRole':f}:{},...g?{'evaluation':g}:{}};}export function describeIntents(){return Object['entries'](INTENT_PRESETS)['map'](([a,b])=>{const c=b['families']?'\x20families\x20'+b['families']['join']('/'):'',d=b['familyDepths']?'\x20depths\x20'+Object['entries'](b['familyDepths'])['map'](([e,g])=>e+'≤'+g)['join']('\x20'):'';return a+':\x20'+b['description']+c+d;});}export function assertIntent(a){if(!isTopologyIntent(a))throw new Error('unknown\x20topology\x20intent\x20\x27'+a+'\x27\x20(valid:\x20'+Object['keys'](INTENT_PRESETS)['join'](',\x20')+')');return a;}
@@ -96,6 +96,18 @@ export interface PersonaLayer {
96
96
  policy?: PersonaPolicy;
97
97
  profiles?: Partial<Record<PersonaRole, RoleProfile>>;
98
98
  analyze?: PersonaAnalyzeDefaults;
99
+ evaluation?: PersonaEvaluationStandards;
100
+ }
101
+ export interface PersonaEvaluationStandards {
102
+ weights?: Record<string, number>;
103
+ facets?: PersonaFacetSettings;
104
+ }
105
+ export type PersonaFacetSettings = Record<string, PersonaFacetSetting>;
106
+ export interface PersonaFacetSetting {
107
+ visible?: boolean;
108
+ order?: number;
109
+ weight?: number;
110
+ threshold?: number;
99
111
  }
100
112
  export interface PersonaAnalyzeDefaults {
101
113
  key_questions?: string[];
@@ -1 +1 @@
1
- import{initServicePuzzleFromIntent,initMachinePuzzleFromIntent,initAllocationPuzzleFromIntent,initTreasuryPuzzleFromIntent,initArbitrationPuzzleFromIntent,initRewardPuzzleFromIntent,initProgressPuzzleFromIntent,initOrderPuzzleFromIntent,initPuzzleFromIntent as a241a,checkServicePuzzleCompleteness,checkMachinePuzzleCompleteness,checkAllocationPuzzleCompleteness,checkTreasuryPuzzleCompleteness,checkArbitrationPuzzleCompleteness,checkRewardPuzzleCompleteness,checkProgressPuzzleCompleteness,checkOrderPuzzleCompleteness,checkPuzzleCompleteness as a241b}from'../../knowledge/index.js';import{initPuzzleFromIntent as a241c,checkPuzzleCompleteness as a241d}from'../../knowledge/permission-puzzle.js';const KEYWORD_TABLE=[{'category':'Product/Service','keywords_zh':['product','selling','sell','sales','store','open\x20shop'],'keywords_en':['sell','product','sale','shop','store'],'objects':['service','order','progress'],'required_level':'R','scene_id':'retail'},{'category':'Subscription','keywords_zh':['subscription','cycle','renewal'],'keywords_en':['subscribe','recurring','subscription'],'objects':['service','machine','reward'],'required_level':'C','scene_id':'subscription'},{'category':'Rental','keywords_zh':['rent','lease','return'],'keywords_en':['rent','lease','return'],'objects':['service','machine','arb'],'required_level':'C','scene_id':'rental_return'},{'category':'Trust','keywords_zh':['deposit','pledge','verify','trust'],'keywords_en':['deposit','trust','verify'],'objects':['guard','permission','treasury'],'required_level':'R','scene_id':'trust_deposit'},{'category':'Funds','keywords_zh':['split','collect','share\x20profit','income','incentive'],'keywords_en':['split','revenue','reward'],'objects':['allocation','treasury','reward'],'required_level':'R','scene_id':'revenue_split'},{'category':'Workflow','keywords_zh':['node','stage','process','workflow'],'keywords_en':['workflow','stage','node'],'objects':['machine','progress'],'required_level':'R','scene_id':'workflow'},{'category':'Dispute','keywords_zh':['arbitration','refund','conflict','rights\x20protection'],'keywords_en':['arbitration','refund','dispute'],'objects':['arb','proof'],'required_level':'C','scene_id':'arbitration_dispute'},{'category':'Contact','keywords_zh':['customer\x20service','contact','communication'],'keywords_en':['contact','support','im'],'objects':['contact'],'required_level':'C','scene_id':'contact_im'},{'category':'Data','keywords_zh':['evidence','record','data'],'keywords_en':['evidence','record','data'],'objects':['repository','proof'],'required_level':'C','scene_id':'evidence_record'},{'category':'User\x20Profile','keywords_zh':['personal\x20info','preference','privacy'],'keywords_en':['personal','profile','privacy'],'objects':['personal','contact'],'required_level':'OPTIONAL','scene_id':'user_profile'},{'category':'Demand\x20Submission','keywords_zh':['demand','publish','inquiry'],'keywords_en':['demand','request','inquiry'],'objects':['demand'],'required_level':'OPTIONAL','scene_id':'demand_inquiry'}],INDUSTRY_KEYWORDS=[{'industry':'freelance','words':['freelance','outsourcing','freelance','gig']},{'industry':'rental','words':['rental','lease','rental','rent']},{'industry':'education','words':['education','course','training','education','course']},{'industry':'travel','words':['travel','tour','itinerary','travel','trip']},{'industry':'subscription','words':['subscription','cycle','subscription','recurring']}];function buildPuzzleDispatch(){const a=(c,d)=>{try{return c(d);}catch{return undefined;}},b=(c,d)=>{if(!c)return{'missing':[],'complete':![],'next_step':'init\x20failed'};try{return d(c);}catch{return{'missing':[],'complete':![],'next_step':'check\x20failed'};}};return{'service':{'init':c=>a(initServicePuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkServicePuzzleCompleteness)},'machine':{'init':c=>a(initMachinePuzzleFromIntent,c),'check':c=>b(c,checkMachinePuzzleCompleteness)},'allocation':{'init':c=>a(initAllocationPuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkAllocationPuzzleCompleteness)},'treasury':{'init':c=>a(initTreasuryPuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkTreasuryPuzzleCompleteness)},'arb':{'init':c=>a(initArbitrationPuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkArbitrationPuzzleCompleteness)},'reward':{'init':c=>a(initRewardPuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkRewardPuzzleCompleteness)},'progress':{'init':c=>a(initProgressPuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkProgressPuzzleCompleteness)},'order':{'init':c=>a(initOrderPuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkOrderPuzzleCompleteness)},'permission':{'init':c=>a(a241c,{'primary_goal':c}),'check':c=>b(c,a241d)},'guard':{'init':c=>a(a241a,{'primary_goal':c}),'check':c=>b(c,a241b)}};}export function extractKeywords(a){if(!a||typeof a!=='string')return[];const b=[];for(const c of KEYWORD_TABLE){const d=[...c['keywords_zh'],...c['keywords_en']];for(const e of d){try{const f=new RegExp(escapeRegex(e),'gi'),g=(a['match'](f)||[])['length'];g>0x0&&b['push']({'keyword':e,'category':c['category'],'matched_objects':[...c['objects']],'required_level':c['required_level'],'match_count':g});}catch{}}}return b['sort']((h,i)=>i['match_count']-h['match_count']),b;}function escapeRegex(a){return a['replace'](/[.*+?^${}()|[\]\\]/g,'\x5c$&');}export function resolveIndustry(a,b){const c=((a??'')+'\x20'+(b??''))['toLowerCase']();for(const d of INDUSTRY_KEYWORDS){for(const e of d['words']){if(c['includes'](e['toLowerCase']()))return d['industry'];}}return'general';}export function identifyObjects(a,b){if(b['length']===0x0)return{'primary':'service','secondary':['permission','machine','progress'],'scenes':[{'object':'service','scene_id':'general'}]};const c=b['find'](i=>i['required_level']==='R'),d=(c??b[0x0])['matched_objects'][0x0],e=new Set([d]),f=[];for(const i of b){for(const j of i['matched_objects']){!e['has'](j)&&(e['add'](j),f['push'](j));}}const g=[],h=new Set();for(const k of KEYWORD_TABLE){const l=b['find'](n=>n['category']===k['category']);if(!l)continue;if(h['has'](k['scene_id']))continue;h['add'](k['scene_id']),g['push']({'object':k['objects'][0x0],'scene_id':k['scene_id']});}return{'primary':d,'secondary':f,'scenes':g};}export function analyzeBusinessIntent(a){const b=[];if(!a||!a['user_intent']||typeof a['user_intent']!=='string')return{'intent_parsed':{'primary_object':'service','secondary_objects':[],'detected_scenes':[],'industry':'general','keyword_matches':[]},'puzzles':{},'overall_completeness':'empty','next_step':'Please\x20provide\x20a\x20non-empty\x20business\x20intent.','recommended_creation_order':[],'warnings':['input.user_intent\x20is\x20empty']};const c=a['user_intent'],e=extractKeywords(c),f=resolveIndustry(c,a['industry']),{primary:g,secondary:h,scenes:i}=identifyObjects(c,e);let j=[g,...h];if(a['target_objects']&&a['target_objects']['length']>0x0){const p=a['target_objects']['filter'](q=>['service','machine','guard','permission','reward','arb','progress','treasury','demand','repository','contact','order','allocation','personal','payment','proof']['includes'](q));if(p['length']>0x0)j=p;}const k=buildPuzzleDispatch(),l={};for(const q of j){const r=k[q];if(!r){b['push']('No\x20puzzle\x20module\x20for\x20\x27'+q+'\x27\x20—\x20skipped\x20(L3\x20object)');continue;}const s=r['init'](c),t=s?r['check'](s):undefined,u=extractMissingDimensions(t);l[q]={'puzzle':s,'completeness':t,'missing_dimensions':u},!s&&b['push']('Puzzle\x20init\x20failed\x20for\x20\x27'+q+'\x27');}const m=aggregatePuzzleCompleteness(l),n=suggestNextPuzzleStep({'intent_parsed':{'primary_object':g,'secondary_objects':h,'detected_scenes':i,'industry':f,'keyword_matches':e},'puzzles':l,'overall_completeness':m,'next_step':'','recommended_creation_order':[],'warnings':b}),o=['permission','progress','machine','guard','allocation','service'];return{'intent_parsed':{'primary_object':g,'secondary_objects':h,'detected_scenes':i,'industry':f,'keyword_matches':e},'puzzles':l,'overall_completeness':m,'next_step':n,'recommended_creation_order':o,'warnings':b};}function extractMissingDimensions(a){if(!a||typeof a!=='object')return[];const b=a,d=b['missing'];if(Array['isArray'](d))return d['map'](f=>String(f));const e=b['missing_details'];if(Array['isArray'](e))return e['map'](f=>String(f?.['dimension']??f));return[];}export function aggregatePuzzleCompleteness(a){const b=Object['values'](a??{});if(b['length']===0x0)return'empty';const c=b['filter'](f=>!f['puzzle'])['length'];if(c===b['length'])return'empty';const d=b['reduce']((f,g)=>f+(g['missing_dimensions']?.['length']??0x0),0x0);if(d===0x0)return'complete';return'partial';}export function suggestNextPuzzleStep(a){if(!a)return'No\x20result\x20to\x20suggest\x20from.';if(a['overall_completeness']==='complete')return'All\x20puzzle\x20dimensions\x20are\x20complete\x20—\x20ready\x20for\x20risk\x20calibration\x20(stage\x203).';if(a['overall_completeness']==='empty')return'No\x20puzzle\x20has\x20been\x20initialized.\x20Provide\x20more\x20concrete\x20business\x20intent\x20so\x20the\x20primary\x20object\x20can\x20be\x20identified.';const b=['permission','treasury','allocation','guard','machine','service','order','progress','arb','reward','proof','repository','demand','contact','personal','payment'],d=a['puzzles']??{},e=b['filter'](f=>d[f]);for(const f of e){const g=d[f];if(!g)continue;const h=g['missing_dimensions']??[];if(h['length']===0x0)continue;const i=g['completeness'],j=i&&typeof i==='object'?i['next_step']:undefined;if(typeof j==='string'&&j['trim']())return'['+f+']\x20'+j;return'['+f+']\x20Complete\x20dimension'+(h['length']>0x1?'s':'')+'\x20'+h['join'](',\x20')+'\x20to\x20advance\x20the\x20puzzle.';}return'Continue\x20dialog\x20to\x20fill\x20remaining\x20pending\x20fields.';}
1
+ import{initServicePuzzleFromIntent,initMachinePuzzleFromIntent,initAllocationPuzzleFromIntent,initTreasuryPuzzleFromIntent,initArbitrationPuzzleFromIntent,initRewardPuzzleFromIntent,initProgressPuzzleFromIntent,initOrderPuzzleFromIntent,initPuzzleFromIntent as a272a,checkServicePuzzleCompleteness,checkMachinePuzzleCompleteness,checkAllocationPuzzleCompleteness,checkTreasuryPuzzleCompleteness,checkArbitrationPuzzleCompleteness,checkRewardPuzzleCompleteness,checkProgressPuzzleCompleteness,checkOrderPuzzleCompleteness,checkPuzzleCompleteness as a272b}from'../../knowledge/index.js';import{initPuzzleFromIntent as a272c,checkPuzzleCompleteness as a272d}from'../../knowledge/permission-puzzle.js';const KEYWORD_TABLE=[{'category':'Product/Service','keywords_zh':['product','selling','sell','sales','store','open\x20shop'],'keywords_en':['sell','product','sale','shop','store'],'objects':['service','order','progress'],'required_level':'R','scene_id':'retail'},{'category':'Subscription','keywords_zh':['subscription','cycle','renewal'],'keywords_en':['subscribe','recurring','subscription'],'objects':['service','machine','reward'],'required_level':'C','scene_id':'subscription'},{'category':'Rental','keywords_zh':['rent','lease','return'],'keywords_en':['rent','lease','return'],'objects':['service','machine','arb'],'required_level':'C','scene_id':'rental_return'},{'category':'Trust','keywords_zh':['deposit','pledge','verify','trust'],'keywords_en':['deposit','trust','verify'],'objects':['guard','permission','treasury'],'required_level':'R','scene_id':'trust_deposit'},{'category':'Funds','keywords_zh':['split','collect','share\x20profit','income','incentive'],'keywords_en':['split','revenue','reward'],'objects':['allocation','treasury','reward'],'required_level':'R','scene_id':'revenue_split'},{'category':'Workflow','keywords_zh':['node','stage','process','workflow'],'keywords_en':['workflow','stage','node'],'objects':['machine','progress'],'required_level':'R','scene_id':'workflow'},{'category':'Dispute','keywords_zh':['arbitration','refund','conflict','rights\x20protection'],'keywords_en':['arbitration','refund','dispute'],'objects':['arb','proof'],'required_level':'C','scene_id':'arbitration_dispute'},{'category':'Contact','keywords_zh':['customer\x20service','contact','communication'],'keywords_en':['contact','support','im'],'objects':['contact'],'required_level':'C','scene_id':'contact_im'},{'category':'Data','keywords_zh':['evidence','record','data'],'keywords_en':['evidence','record','data'],'objects':['repository','proof'],'required_level':'C','scene_id':'evidence_record'},{'category':'User\x20Profile','keywords_zh':['personal\x20info','preference','privacy'],'keywords_en':['personal','profile','privacy'],'objects':['personal','contact'],'required_level':'OPTIONAL','scene_id':'user_profile'},{'category':'Demand\x20Submission','keywords_zh':['demand','publish','inquiry'],'keywords_en':['demand','request','inquiry'],'objects':['demand'],'required_level':'OPTIONAL','scene_id':'demand_inquiry'}],INDUSTRY_KEYWORDS=[{'industry':'freelance','words':['freelance','outsourcing','freelance','gig']},{'industry':'rental','words':['rental','lease','rental','rent']},{'industry':'education','words':['education','course','training','education','course']},{'industry':'travel','words':['travel','tour','itinerary','travel','trip']},{'industry':'subscription','words':['subscription','cycle','subscription','recurring']}];function buildPuzzleDispatch(){const a=(c,d)=>{try{return c(d);}catch{return undefined;}},b=(c,d)=>{if(!c)return{'missing':[],'complete':![],'next_step':'init\x20failed'};try{return d(c);}catch{return{'missing':[],'complete':![],'next_step':'check\x20failed'};}};return{'service':{'init':c=>a(initServicePuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkServicePuzzleCompleteness)},'machine':{'init':c=>a(initMachinePuzzleFromIntent,c),'check':c=>b(c,checkMachinePuzzleCompleteness)},'allocation':{'init':c=>a(initAllocationPuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkAllocationPuzzleCompleteness)},'treasury':{'init':c=>a(initTreasuryPuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkTreasuryPuzzleCompleteness)},'arb':{'init':c=>a(initArbitrationPuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkArbitrationPuzzleCompleteness)},'reward':{'init':c=>a(initRewardPuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkRewardPuzzleCompleteness)},'progress':{'init':c=>a(initProgressPuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkProgressPuzzleCompleteness)},'order':{'init':c=>a(initOrderPuzzleFromIntent,{'primary_goal':c}),'check':c=>b(c,checkOrderPuzzleCompleteness)},'permission':{'init':c=>a(a272c,{'primary_goal':c}),'check':c=>b(c,a272d)},'guard':{'init':c=>a(a272a,{'primary_goal':c}),'check':c=>b(c,a272b)}};}export function extractKeywords(a){if(!a||typeof a!=='string')return[];const b=[];for(const c of KEYWORD_TABLE){const d=[...c['keywords_zh'],...c['keywords_en']];for(const e of d){try{const f=new RegExp(escapeRegex(e),'gi'),g=(a['match'](f)||[])['length'];g>0x0&&b['push']({'keyword':e,'category':c['category'],'matched_objects':[...c['objects']],'required_level':c['required_level'],'match_count':g});}catch{}}}return b['sort']((h,i)=>i['match_count']-h['match_count']),b;}function escapeRegex(a){return a['replace'](/[.*+?^${}()|[\]\\]/g,'\x5c$&');}export function resolveIndustry(a,b){const c=((a??'')+'\x20'+(b??''))['toLowerCase']();for(const d of INDUSTRY_KEYWORDS){for(const e of d['words']){if(c['includes'](e['toLowerCase']()))return d['industry'];}}return'general';}export function identifyObjects(a,b){if(b['length']===0x0)return{'primary':'service','secondary':['permission','machine','progress'],'scenes':[{'object':'service','scene_id':'general'}]};const c=b['find'](i=>i['required_level']==='R'),d=(c??b[0x0])['matched_objects'][0x0],e=new Set([d]),f=[];for(const i of b){for(const j of i['matched_objects']){!e['has'](j)&&(e['add'](j),f['push'](j));}}const g=[],h=new Set();for(const k of KEYWORD_TABLE){const l=b['find'](n=>n['category']===k['category']);if(!l)continue;if(h['has'](k['scene_id']))continue;h['add'](k['scene_id']),g['push']({'object':k['objects'][0x0],'scene_id':k['scene_id']});}return{'primary':d,'secondary':f,'scenes':g};}export function analyzeBusinessIntent(a){const b=[];if(!a||!a['user_intent']||typeof a['user_intent']!=='string')return{'intent_parsed':{'primary_object':'service','secondary_objects':[],'detected_scenes':[],'industry':'general','keyword_matches':[]},'puzzles':{},'overall_completeness':'empty','next_step':'Please\x20provide\x20a\x20non-empty\x20business\x20intent.','recommended_creation_order':[],'warnings':['input.user_intent\x20is\x20empty']};const c=a['user_intent'],e=extractKeywords(c),f=resolveIndustry(c,a['industry']),{primary:g,secondary:h,scenes:i}=identifyObjects(c,e);let j=[g,...h];if(a['target_objects']&&a['target_objects']['length']>0x0){const p=a['target_objects']['filter'](q=>['service','machine','guard','permission','reward','arb','progress','treasury','demand','repository','contact','order','allocation','personal','payment','proof']['includes'](q));if(p['length']>0x0)j=p;}const k=buildPuzzleDispatch(),l={};for(const q of j){const r=k[q];if(!r){b['push']('No\x20puzzle\x20module\x20for\x20\x27'+q+'\x27\x20—\x20skipped\x20(L3\x20object)');continue;}const s=r['init'](c),t=s?r['check'](s):undefined,u=extractMissingDimensions(t);l[q]={'puzzle':s,'completeness':t,'missing_dimensions':u},!s&&b['push']('Puzzle\x20init\x20failed\x20for\x20\x27'+q+'\x27');}const m=aggregatePuzzleCompleteness(l),n=suggestNextPuzzleStep({'intent_parsed':{'primary_object':g,'secondary_objects':h,'detected_scenes':i,'industry':f,'keyword_matches':e},'puzzles':l,'overall_completeness':m,'next_step':'','recommended_creation_order':[],'warnings':b}),o=['permission','progress','machine','guard','allocation','service'];return{'intent_parsed':{'primary_object':g,'secondary_objects':h,'detected_scenes':i,'industry':f,'keyword_matches':e},'puzzles':l,'overall_completeness':m,'next_step':n,'recommended_creation_order':o,'warnings':b};}function extractMissingDimensions(a){if(!a||typeof a!=='object')return[];const b=a,d=b['missing'];if(Array['isArray'](d))return d['map'](f=>String(f));const e=b['missing_details'];if(Array['isArray'](e))return e['map'](f=>String(f?.['dimension']??f));return[];}export function aggregatePuzzleCompleteness(a){const b=Object['values'](a??{});if(b['length']===0x0)return'empty';const c=b['filter'](f=>!f['puzzle'])['length'];if(c===b['length'])return'empty';const d=b['reduce']((f,g)=>f+(g['missing_dimensions']?.['length']??0x0),0x0);if(d===0x0)return'complete';return'partial';}export function suggestNextPuzzleStep(a){if(!a)return'No\x20result\x20to\x20suggest\x20from.';if(a['overall_completeness']==='complete')return'All\x20puzzle\x20dimensions\x20are\x20complete\x20—\x20ready\x20for\x20risk\x20calibration\x20(stage\x203).';if(a['overall_completeness']==='empty')return'No\x20puzzle\x20has\x20been\x20initialized.\x20Provide\x20more\x20concrete\x20business\x20intent\x20so\x20the\x20primary\x20object\x20can\x20be\x20identified.';const b=['permission','treasury','allocation','guard','machine','service','order','progress','arb','reward','proof','repository','demand','contact','personal','payment'],d=a['puzzles']??{},e=b['filter'](f=>d[f]);for(const f of e){const g=d[f];if(!g)continue;const h=g['missing_dimensions']??[];if(h['length']===0x0)continue;const i=g['completeness'],j=i&&typeof i==='object'?i['next_step']:undefined;if(typeof j==='string'&&j['trim']())return'['+f+']\x20'+j;return'['+f+']\x20Complete\x20dimension'+(h['length']>0x1?'s':'')+'\x20'+h['join'](',\x20')+'\x20to\x20advance\x20the\x20puzzle.';}return'Continue\x20dialog\x20to\x20fill\x20remaining\x20pending\x20fields.';}
@@ -0,0 +1,22 @@
1
+ import { type ENTRYPOINT } from "@wowok/wowok";
2
+ import { type ChainValueDisplay } from "../../knowledge/fund-layer.js";
3
+ import type { FacetMoney } from "../../graph/onchain/facet-projection.js";
4
+ export type CoinResolver = (coinType: string, network?: ENTRYPOINT) => Promise<ChainValueDisplay | undefined>;
5
+ export interface AnnotatableFacet {
6
+ amounts?: Array<{
7
+ key: string;
8
+ label: string;
9
+ money: FacetMoney;
10
+ }>;
11
+ evidence: string[];
12
+ }
13
+ export declare function withMinDecimals(text: string, min?: number): string;
14
+ export interface MoneyAnnotation {
15
+ display: string;
16
+ tip: string;
17
+ precision_known: boolean;
18
+ symbol?: string;
19
+ decimals?: number;
20
+ }
21
+ export declare function formatMoneyAnnotation(raw: string | null | undefined, coinType: string | null | undefined, network?: ENTRYPOINT): Promise<MoneyAnnotation>;
22
+ export declare function annotateFacetMoney(items: AnnotatableFacet[], network?: ENTRYPOINT, resolve?: CoinResolver): Promise<void>;
@@ -0,0 +1 @@
1
+ import{formatUnits}from'@wowok/wowok';import{formatChainValue}from'../../knowledge/fund-layer.js';const defaultCoinResolver=async(a,b)=>{try{return await formatChainValue('0',a,b);}catch{return undefined;}};function unknownCoinTip(a){return'Raw\x20smallest\x20units\x20—\x20token\x20precision\x20unavailable\x20for\x20'+a+';\x20this\x20is\x20NOT\x20a\x20unit\x20value\x20'+'(unit\x20=\x20raw\x20/\x2010^N\x20once\x20decimals\x20N\x20are\x20known).';}export function withMinDecimals(a,b=0x2){const c=a['indexOf']('.');if(c<0x0)return a+'.'+'0'['repeat'](b);const d=a['length']-c-0x1;return d<b?a+'0'['repeat'](b-d):a;}export async function formatMoneyAnnotation(a,b,c){if(a===null||a===undefined||a==='')return{'display':'','tip':'','precision_known':![]};if(!b)return{'display':a,'tip':unknownCoinTip('unknown\x20coin\x20(payment\x20token\x20unresolved)'),'precision_known':![]};try{const d=await formatChainValue(a,b,c);if(d['precision_known']){const e=withMinDecimals(d['display']);return{'display':d['symbol']?e+'\x20'+d['symbol']:e,'tip':d['text'],'precision_known':!![],...d['symbol']?{'symbol':d['symbol']}:{},...d['decimals']!==undefined?{'decimals':d['decimals']}:{}};}return{'display':a,'tip':unknownCoinTip(b),'precision_known':![]};}catch{return{'display':a,'tip':unknownCoinTip(b),'precision_known':![]};}}export async function annotateFacetMoney(a,b,c=defaultCoinResolver){const d=new Map(),e=f=>{const g=d['get'](f);if(g)return g;const h=c(f,b)['then'](i=>i?{'precisionKnown':i['precision_known'],...i['precision_known']&&i['decimals']!==undefined?{'decimals':i['decimals'],'symbol':i['symbol']}:{}}:undefined);return d['set'](f,h),h;};for(const f of a){if(!f['amounts']?.['length'])continue;const g=new Map();for(const h of f['amounts']){const i=h['money'];let j=i['raw'];if(!i['coin_type']){g['set'](h['key'],j);continue;}let k;try{k=await e(i['coin_type']);}catch{k=undefined;}if(k?.['precisionKnown']&&k['decimals']!==undefined){let l=i['raw'];try{l=withMinDecimals(formatUnits(BigInt(i['raw']),k['decimals']));}catch{}i['display']=l,i['decimals']=k['decimals'];if(k['symbol'])i['symbol']=k['symbol'];i['precision_known']=!![],j=k['symbol']?l+'\x20'+k['symbol']:l;}else i['precision_known']=![],i['tip']=unknownCoinTip(i['coin_type']),j=i['raw'];g['set'](h['key'],j);}g['size']>0x0&&(f['evidence']=f['evidence']['map'](n=>n['replace'](/\{(\w+)\}/g,(o,p)=>g['get'](p)??'{'+p+'}')));}}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ import{describe,expect,it,vi}from'vitest';import{annotateFacetMoney}from'./facet-money.js';const WOW='0x2::wow::WOW',USDT='0x2::wow::coins::USDT',XYZ='0x99::meme::XYZ';function display(a,b,c,d){return{'raw':'0','display':'0','token_type':a,'precision_known':b,...c?{'symbol':c}:{},...d!==undefined?{'decimals':d}:{},'text':''};}function facet(a,b,c){return{'id':a,'label':a,'question':'q','state':'present','evidence':c,...b?{'amounts':b}:{}};}describe('annotateFacetMoney',()=>{it('resolves\x20each\x20coin\x20type\x20once\x20and\x20converts\x20with\x20a\x20two-decimal\x20floor',async()=>{const c=vi['fn'](async i=>{if(i===WOW)return display(WOW,!![],'WOW',0x9);if(i===USDT)return display(USDT,!![],'USDT',0x6);return display(i,![]);}),d=[facet('fund_safety',[{'key':'a','label':'A','money':{'raw':'2000000000','coin_type':WOW,'precision_known':![]}},{'key':'b','label':'B','money':{'raw':'200000000','coin_type':WOW,'precision_known':![]}}],['price\x20{a}\x20and\x20{b}']),facet('offering_price',[{'key':'p','label':'P','money':{'raw':'1500000','coin_type':USDT,'precision_known':![]}},{'key':'x','label':'X','money':{'raw':'7','coin_type':XYZ,'precision_known':![]}}],['offer\x20{p};\x20unknown\x20{x}'])];await annotateFacetMoney(d,undefined,c),expect(c)['toHaveBeenCalledTimes'](0x3),expect(c)['toHaveBeenCalledWith'](WOW,undefined),expect(c)['toHaveBeenCalledWith'](XYZ,undefined);const [e,f]=[d[0x0]['amounts'][0x0]['money'],d[0x0]['amounts'][0x1]['money']];expect(e)['toMatchObject']({'raw':'2000000000','display':'2.00','symbol':'WOW','decimals':0x9,'precision_known':!![]}),expect(f['display'])['toBe']('0.20'),expect(d[0x0]['evidence'][0x0])['toBe']('price\x202.00\x20WOW\x20and\x200.20\x20WOW');const g=d[0x1]['amounts'][0x0]['money'];expect(g['display'])['toBe']('1.50'),expect(d[0x1]['evidence'][0x0])['toContain']('offer\x201.50\x20USDT');const h=d[0x1]['amounts'][0x1]['money'];expect(h['precision_known'])['toBe'](![]),expect(h['display'])['toBeUndefined'](),expect(h['tip'])['toContain'](XYZ),expect(d[0x1]['evidence'][0x0])['toContain']('unknown\x207');}),it('keeps\x20micro\x20fractions\x20exact\x20beyond\x20the\x20two-decimal\x20floor',async()=>{const a=vi['fn'](async()=>display(WOW,!![],'WOW',0x9)),b=[facet('fund_safety',[{'key':'m','label':'M','money':{'raw':'1','coin_type':WOW,'precision_known':![]}}],['{m}'])];await annotateFacetMoney(b,undefined,a),expect(b[0x0]['amounts'][0x0]['money']['display'])['toBe']('0.000000001'),expect(b[0x0]['evidence'][0x0])['toBe']('0.000000001\x20WOW');}),it('fails\x20soft\x20when\x20the\x20resolver\x20throws',async()=>{const a=vi['fn'](async()=>{throw new Error('network\x20down');}),b=[facet('fund_safety',[{'key':'a','label':'A','money':{'raw':'42','coin_type':WOW,'precision_known':![]}}],['{a}\x20raw'])];await expect(annotateFacetMoney(b,undefined,a))['resolves']['toBeUndefined']();const c=b[0x0]['amounts'][0x0]['money'];expect(c['precision_known'])['toBe'](![]),expect(c['display'])['toBeUndefined'](),expect(c['raw'])['toBe']('42'),expect(c['tip'])['toContain'](WOW),expect(b[0x0]['evidence'][0x0])['toBe']('42\x20raw');}),it('never\x20resolves\x20amounts\x20without\x20a\x20coin\x20type',async()=>{const a=vi['fn'](async()=>display(WOW,!![],'WOW',0x9)),b=[facet('fund_safety',[{'key':'a','label':'A','money':{'raw':'99','precision_known':![]}}],['bare\x20{a}']),facet('supply_chain',undefined,['no\x20money\x20here'])];await annotateFacetMoney(b,undefined,a),expect(a)['not']['toHaveBeenCalled'](),expect(b[0x0]['evidence'][0x0])['toBe']('bare\x2099'),expect(b[0x0]['amounts'][0x0]['money']['precision_known'])['toBe'](![]);}),it('leaves\x20unknown\x20placeholders\x20intact',async()=>{const a=vi['fn'](async()=>display(WOW,!![],'WOW',0x9)),b=[facet('fund_safety',[{'key':'a','label':'A','money':{'raw':'1','coin_type':WOW,'precision_known':![]}}],['{a}\x20/\x20{missing}'])];await annotateFacetMoney(b,undefined,a),expect(b[0x0]['evidence'][0x0])['toBe']('0.000000001\x20WOW\x20/\x20{missing}');});});
@@ -1 +1 @@
1
- import{findSimilarIndustries,inferTraitsFromDescription}from'../../knowledge/industry-generalizer.js';const INTENT_KEYWORDS={'sell_service':['design','develop','consult','freelance','service','build','create','write','translate'],'sell_product':['sell','product','item','goods','merchandise','store','shop'],'sell_subscription':['subscribe','subscription','membership','monthly','recurring','creator','patron'],'rent_asset':['rent','rental','lease','borrow','car','house','apartment','equipment'],'crowdfund':['crowdfund','fund','raise','campaign','donation','backer'],'escrow':['escrow','hold','mediate','intermediary','safe','secure\x20transaction']};function classifyIntentType(a){const b=a['toLowerCase']();let c='sell_service',d=0x0;for(const [e,f]of Object['entries'](INTENT_KEYWORDS)){const g=f['filter'](h=>b['includes'](h))['length'];g>d&&(d=g,c=e);}return c;}function inferPaymentModel(a){const b=a['toLowerCase']();if(b['includes']('milestone')||b['includes']('phase')||b['includes']('stage'))return'milestone';if(b['includes']('subscription')||b['includes']('monthly')||b['includes']('recurring'))return'subscription';if(b['includes']('per\x20use')||b['includes']('hourly')||b['includes']('per\x20session'))return'per_use';if(b['includes']('escrow')||b['includes']('hold'))return'escrow';return'upfront';}function inferRefundPolicy(a){const b=a['toLowerCase']();if(b['includes']('no\x20refund')||b['includes']('non-refundable'))return'no_refund';if(b['includes']('milestone')&&b['includes']('refund'))return'milestone_prorated';if(b['includes']('full\x20refund'))return'full';return'partial';}function inferArbitration(a){const b=a['toLowerCase']();if(b['includes']('no\x20arbitration')||b['includes']('no\x20dispute'))return'none';if(b['includes']('third\x20party')||b['includes']('independent'))return'third_party';if(b['includes']('mutual'))return'mutual_pick';return'merchant_pick';}export async function analyzeIntent(a,b){const c=[],d=classifyIntentType(a),e=inferTraitsFromDescription(a),f=findSimilarIndustries(e['traits'],0x3),g=f['map'](n=>n['industry']),h=b?.['preferredIndustry']??g[0x0]??'general',i=g['includes'](h)?0.85:0.5,j=e['traits'],k={'intent':d,'industry':h,'description':a,'roles':{'merchant':{'name':'merchant','description':'Service\x20provider\x20or\x20seller','obligations':['Deliver\x20as\x20described','Maintain\x20compensation_fund\x20if\x20required','Accept\x20arbitration\x20verdicts'],'rights':['Receive\x20payment\x20upon\x20verified\x20delivery','Set\x20service\x20terms\x20before\x20publish']},'customer':{'name':'customer','description':'Buyer\x20or\x20service\x20recipient','obligations':['Pay\x20according\x20to\x20agreed\x20schedule','Provide\x20acceptance/rejection\x20within\x20timeout'],'rights':['Receive\x20deliverables\x20as\x20described','Request\x20refund\x20if\x20delivery\x20fails','Initiate\x20arbitration\x20for\x20disputes']}},'deliverables':[{'name':'main_deliverable','type':inferDeliverableType(a),'acceptanceCriteria':'To\x20be\x20defined\x20by\x20merchant\x20during\x20configuration','proofOfDelivery':'wip_hash'}],'payment':{'model':inferPaymentModel(a),'currency':b?.['currency']??'WOW','triggers':[{'event':inferPaymentModel(a)==='milestone'?'milestone\x20completion':'service\x20confirmation','guardDescription':'Guard\x20verifies\x20deliverable\x20meets\x20acceptance\x20criteria'}],'allocation':[{'recipient':'merchant','percentage':0x5a},{'recipient':'platform','percentage':0x0},{'recipient':'arbitration_reserve','percentage':0xa}]},'trust':{'refundPolicy':inferRefundPolicy(a),'arbitration':inferArbitration(a),'escrow':!![],'transparency':'full'}};k['payment']['model']==='milestone'&&!a['toLowerCase']()['includes']('milestone')&&c['push']('Payment\x20model\x20inferred\x20as\x20\x27milestone\x27\x20but\x20not\x20explicitly\x20mentioned.\x20Please\x20verify.');k['trust']['arbitration']==='none'&&c['push']('No\x20arbitration\x20configured.\x20This\x20increases\x20risk\x20for\x20both\x20parties.\x20Consider\x20adding\x20independent_arbitration\x20module.');k['payment']['allocation']&&k['payment']['allocation']['some'](n=>n['recipient']==='platform'&&n['percentage']>0x0)&&c['push']('Platform\x20fee\x20>\x200\x20detected.\x20WOW\x20philosophy\x20recommends\x200%\x20platform\x20fee\x20for\x20peer-to-peer\x20transactions.');const l=a['toLowerCase']();/(refund|cancel|dispute)/['test'](l)&&k['payment']['model']==='milestone'&&c['push']('T1\x20B-1:\x20\x27refund/dispute\x27\x20must\x20be\x20modeled\x20via\x20the\x20Allocation\x20waterfall\x20(order_allocators)\x20+\x20'+'the\x20bound\x20Arbitration\x20—\x20NOT\x20a\x20Machine\x20\x27refunded\x27/\x27disputed\x27\x20node\x20(R-M1-11).');/(按(实际|定损|损失|评估)[^。]{0,8}(金额|赔付|赔偿)|variable amount|dynamic amount|actual loss|assessed loss)/['test'](l)&&c['push']('T1\x20B-2:\x20a\x20variable/conditional\x20payout\x20amount\x20cannot\x20be\x20expressed\x20in\x20Allocation\x20—\x20amounts\x20are\x20'+'pre-configured.\x20Use\x20fixed\x20tiers\x20guarded\x20by\x20distinct\x20Guards,\x20or\x20an\x20Amount\x20with\x20a\x20max\x20cap.');/(auto|automatic|automatically|after \d+ (day|hour|week)|within \d+ (day|hour|week)|自动|到期后)/['test'](l)&&c['push']('T1\x20B-3:\x20\x27auto\x20/\x20after\x20N\x20days\x27\x20has\x20no\x20on-chain\x20cron\x20—\x20it\x20requires\x20a\x20time_guard\x20PLUS\x20an\x20off-chain\x20'+'keeper\x20to\x20submit.\x20Configuring\x20a\x20time_guard\x20without\x20a\x20keeper\x20means\x20nothing\x20ever\x20fires.');let m=[];try{const {recommendModules:n}=await import('../../extensions/business-modules.js'),o=n(h,a,{'maxModules':0x5});m=o['map'](p=>p['id']);}catch{m=['milestone_escrow','independent_arbitration','wip_provenance'];}return{'intent':k,'inferredIndustry':h,'industryConfidence':i,'similarIndustries':g,'inferredTraits':j,'recommendedModules':m,'warnings':c};}function inferDeliverableType(a){const b=a['toLowerCase']();if(b['includes']('design')||b['includes']('code')||b['includes']('write')||b['includes']('digital'))return'digital';if(b['includes']('class')||b['includes']('lesson')||b['includes']('session'))return'service_session';if(b['includes']('rent')||b['includes']('access'))return'access_right';return'physical';}
1
+ import{findSimilarIndustries,inferTraitsFromDescription}from'../../knowledge/industry-generalizer.js';const INTENT_KEYWORDS={'sell_service':['design','develop','consult','freelance','service','build','create','write','translate'],'sell_product':['sell','product','item','goods','merchandise','store','shop'],'sell_subscription':['subscribe','subscription','membership','monthly','recurring','creator','patron'],'rent_asset':['rent','rental','lease','borrow','car','house','apartment','equipment'],'crowdfund':['crowdfund','fund','raise','campaign','donation','backer'],'escrow':['escrow','hold','mediate','intermediary','safe','secure\x20transaction']};function classifyIntentType(a){const b=a['toLowerCase']();let c='sell_service',d=0x0;for(const [e,f]of Object['entries'](INTENT_KEYWORDS)){const g=f['filter'](h=>b['includes'](h))['length'];g>d&&(d=g,c=e);}return c;}function inferPaymentModel(a){const b=a['toLowerCase']();if(b['includes']('milestone')||b['includes']('phase')||b['includes']('stage'))return'milestone';if(b['includes']('subscription')||b['includes']('monthly')||b['includes']('recurring'))return'subscription';if(b['includes']('per\x20use')||b['includes']('hourly')||b['includes']('per\x20session'))return'per_use';if(b['includes']('escrow')||b['includes']('hold'))return'escrow';return'upfront';}function inferRefundPolicy(a){const b=a['toLowerCase']();if(b['includes']('no\x20refund')||b['includes']('non-refundable'))return'no_refund';if(b['includes']('milestone')&&b['includes']('refund'))return'milestone_prorated';if(b['includes']('full\x20refund'))return'full';return'partial';}function inferArbitration(a){const b=a['toLowerCase']();if(b['includes']('no\x20arbitration')||b['includes']('no\x20dispute'))return'none';if(b['includes']('third\x20party')||b['includes']('independent'))return'third_party';if(b['includes']('mutual'))return'mutual_pick';return'merchant_pick';}export async function analyzeIntent(a,b){const c=[],d=classifyIntentType(a),e=inferTraitsFromDescription(a),f=findSimilarIndustries(e['traits'],0x3),g=f['map'](n=>n['industry']),h=b?.['preferredIndustry']??g[0x0]??'general',i=g['includes'](h)?0.85:0.5,j=e['traits'],k={'intent':d,'industry':h,'description':a,'roles':{'merchant':{'name':'merchant','description':'Service\x20provider\x20or\x20seller','obligations':['Deliver\x20as\x20described','Maintain\x20compensation_fund\x20if\x20required','Accept\x20arbitration\x20verdicts'],'rights':['Receive\x20payment\x20upon\x20verified\x20delivery','Set\x20service\x20terms\x20before\x20publish']},'customer':{'name':'customer','description':'Buyer\x20or\x20service\x20recipient','obligations':['Pay\x20according\x20to\x20agreed\x20schedule','Provide\x20acceptance/rejection\x20within\x20timeout'],'rights':['Receive\x20deliverables\x20as\x20described','Request\x20refund\x20if\x20delivery\x20fails','Initiate\x20arbitration\x20for\x20disputes']}},'deliverables':[{'name':'main_deliverable','type':inferDeliverableType(a),'acceptanceCriteria':'To\x20be\x20defined\x20by\x20merchant\x20during\x20configuration','proofOfDelivery':'wip_hash'}],'payment':{'model':inferPaymentModel(a),'currency':b?.['currency']??'WOW','triggers':[{'event':inferPaymentModel(a)==='milestone'?'milestone\x20completion':'service\x20confirmation','guardDescription':'Guard\x20verifies\x20deliverable\x20meets\x20acceptance\x20criteria'}],'allocation':[{'recipient':'merchant','percentage':0x5a},{'recipient':'platform','percentage':0x0},{'recipient':'arbitration_reserve','percentage':0xa}]},'trust':{'refundPolicy':inferRefundPolicy(a),'arbitration':inferArbitration(a),'escrow':!![],'transparency':'full'}};k['payment']['model']==='milestone'&&!a['toLowerCase']()['includes']('milestone')&&c['push']('Payment\x20model\x20inferred\x20as\x20\x27milestone\x27\x20but\x20not\x20explicitly\x20mentioned.\x20Please\x20verify.');k['trust']['arbitration']==='none'&&c['push']('No\x20arbitration\x20configured.\x20This\x20increases\x20risk\x20for\x20both\x20parties.\x20Consider\x20adding\x20independent_arbitration\x20module.');k['payment']['allocation']&&k['payment']['allocation']['some'](n=>n['recipient']==='platform'&&n['percentage']>0x0)&&c['push']('Platform\x20fee\x20>\x200\x20detected.\x20WOW\x20philosophy\x20recommends\x200%\x20platform\x20fee\x20for\x20peer-to-peer\x20transactions.');const l=a['toLowerCase']();/(refund|cancel|dispute)/['test'](l)&&k['payment']['model']==='milestone'&&c['push']('T1\x20B-1:\x20\x27refund/dispute\x27\x20must\x20be\x20modeled\x20via\x20the\x20Allocation\x20waterfall\x20(order_allocators)\x20+\x20'+'the\x20bound\x20Arbitration\x20—\x20NOT\x20a\x20Machine\x20\x27refunded\x27/\x27disputed\x27\x20node\x20(R-M1-11).');/(variable amount|dynamic amount|actual loss|assessed loss)/['test'](l)&&c['push']('T1\x20B-2:\x20a\x20variable/conditional\x20payout\x20amount\x20cannot\x20be\x20expressed\x20in\x20Allocation\x20—\x20amounts\x20are\x20'+'pre-configured.\x20Use\x20fixed\x20tiers\x20guarded\x20by\x20distinct\x20Guards,\x20or\x20an\x20Amount\x20with\x20a\x20max\x20cap.');/(auto|automatic|automatically|after \d+ (day|hour|week)|within \d+ (day|hour|week))/['test'](l)&&c['push']('T1\x20B-3:\x20\x27auto\x20/\x20after\x20N\x20days\x27\x20has\x20no\x20on-chain\x20cron\x20—\x20it\x20requires\x20a\x20time_guard\x20PLUS\x20an\x20off-chain\x20'+'keeper\x20to\x20submit.\x20Configuring\x20a\x20time_guard\x20without\x20a\x20keeper\x20means\x20nothing\x20ever\x20fires.');let m=[];try{const {recommendModules:n}=await import('../../extensions/business-modules.js'),o=n(h,a,{'maxModules':0x5});m=o['map'](p=>p['id']);}catch{m=['milestone_escrow','independent_arbitration','wip_provenance'];}return{'intent':k,'inferredIndustry':h,'industryConfidence':i,'similarIndustries':g,'inferredTraits':j,'recommendedModules':m,'warnings':c};}function inferDeliverableType(a){const b=a['toLowerCase']();if(b['includes']('design')||b['includes']('code')||b['includes']('write')||b['includes']('digital'))return'digital';if(b['includes']('class')||b['includes']('lesson')||b['includes']('session'))return'service_session';if(b['includes']('rent')||b['includes']('access'))return'access_right';return'physical';}
@@ -24,6 +24,8 @@ export interface MachinePanoramaResult {
24
24
  };
25
25
  progresses: {
26
26
  count: number;
27
+ window_saturated: boolean;
28
+ preview_truncated: boolean;
27
29
  items: {
28
30
  progress: string;
29
31
  name: string | null;
@@ -36,6 +38,7 @@ export interface MachinePanoramaResult {
36
38
  };
37
39
  related: {
38
40
  count: number;
41
+ window_saturated: boolean;
39
42
  groups: {
40
43
  label: string;
41
44
  items: {
@@ -1 +1 @@
1
- import{Config,LocalMark,query_objects,objectTypeFromAddress,ObjectType}from'@wowok/wowok';import{fetchMachineNodes,buildMachineGraph}from'./machine-nodes.js';import{batchQueryObjectsByIds,fetchObjectLinkerTx}from'../../graph/onchain/sdk-batch.js';export async function handleMachinePanorama(a){const b=a['object_address'];if(!b)throw new Error('\x27object_address\x27\x20is\x20required\x20for\x20machine_panorama');let c=a['context_network']??undefined;const d=[];let f=b;if(!/^0x[0-9a-fA-F]{32,64}$/['test'](b)){const q=await LocalMark['Instance']()['get_address'](b);if(!q)throw new Error('Cannot\x20resolve\x20machine\x20\x27'+b+'\x27\x20—\x20not\x20a\x20valid\x20address\x20and\x20no\x20LocalMark\x20entry\x20found.\x20'+'Pass\x20the\x200x\x20Machine\x20object\x20address\x20directly\x20or\x20register\x20the\x20name\x20via\x20local_mark_operation.');f=q;}let g=null;try{if(!c)c=await Config['Instance']()['network_get']();const s=await query_objects({'objects':[f],'network':c});g=s?.['objects']?.[0x0]??null;if(!g&&a['context_network']){const u=await Config['Instance']()['network_get']();if(u&&u!==c){const w=await query_objects({'objects':[f],'network':u,'no_cache':!![]}),x=w?.['objects']?.[0x0]??null;x&&(g=x,c=u);}}}catch(y){throw new Error('Failed\x20to\x20query\x20Machine\x20'+f+'\x20on\x20'+c+':\x20'+(''+(y instanceof Error?y['message']:String(y))));}if(!g)throw new Error('Machine\x20'+f+'\x20not\x20found\x20on\x20'+c+'.\x20It\x20may\x20not\x20exist\x20on\x20this\x20network.');f=g['object']??f;let h=null,j=[];try{const z=await LocalMark['Instance']()['list']({'address':f});z['length']>0x0&&(h=z[0x0]['name']??null,j=(z[0x0]['tags']??[])['map'](A=>String(A)));}catch{d['push']('head:\x20LocalMark\x20lookup\x20failed');}let k={'nodes':[],'edges':[]};try{const A=await fetchMachineNodes(f,c);k=buildMachineGraph(A);}catch{d['push']('graph:\x20node\x20fetch\x20failed\x20(non-blocking)');}const l=[];let m=0x0,n=0x0,p=[];try{const B=await fetchObjectLinkerTx(f,c,!![]),C=B?.['items']??[],D=new Map();for(const K of C){const L=typeof K?.['who']==='string'?K['who']['toLowerCase']():'';if(!L||L==='0x0')continue;if(!objectTypeFromAddress(L))continue;const M=typeof K?.['time']==='number'?K['time']:null,N=D['get'](L);D['set'](L,N==null?M:M==null?N:Math['max'](N,M));}n=D['size'];const E=new Map();for(const [O,P]of D){const Q=String(objectTypeFromAddress(O)),R=E['get'](Q)??[];R['push']({'address':O,'time':P}),E['set'](Q,R);}for(const S of E['values']()){S['sort']((T,U)=>(U['time']??0x0)-(T['time']??0x0));}const F=['Progress','Allocation','Payment','Guard'];p=[];for(const T of F){const U=E['get'](T);U&&U['length']>0x0&&(p['push']({'label':T,'items':U}),E['delete'](T));}for(const [V,W]of E){if(W['length']>0x0)p['push']({'label':V,'items':W});}const G=C['filter'](X=>objectTypeFromAddress(X['who'])===ObjectType['Progress']);m=G['length'];const H=G['slice'](-0x32)['reverse'](),I=H['map'](X=>X['who']),J=new Map();if(I['length']>0x0)try{const X=await batchQueryObjectsByIds(I,c,!![]);for(const Y of X){if(Y?.['object'])J['set'](Y['object'],Y);}}catch{d['push']('progresses:\x20detail\x20fetch\x20failed');}for(const Z of H){const a0=typeof Z?.['who']==='string'?Z['who']:'';if(!a0)continue;const a1=J['get'](a0);l['push']({'progress':a0,'name':null,'current':a1?.['current']??null,'task':a1?.['task']??null,'history_count':typeof a1?.['history_count']==='number'?a1['history_count']:null,'current_time':typeof a1?.['current_time']==='number'?a1['current_time']:null,'created_at':typeof Z?.['time']==='number'?Z['time']:null});}}catch{d['push']('progresses:\x20global-table\x20lookup\x20failed\x20(non-blocking)');}return{'action':'machine_panorama','machineAddress':f,'network':String(c),'head':{'name':h,'tags':j,'description':typeof g['description']==='string'?g['description']:null,'published':typeof g['bPublished']==='boolean'?g['bPublished']:null,'paused':typeof g['bPaused']==='boolean'?g['bPaused']:null},'fields':{'permission':g['permission']??null,'um':g['um']??null,'node_count':typeof g['node_count']==='number'?g['node_count']:null,'consensus_repositories':Array['isArray'](g['consensus_repositories'])?g['consensus_repositories']:[]},'graph':k,'progresses':{'count':m,'items':l},'related':{'count':n,'groups':p},'data_gaps':d};}
1
+ import{Config,LocalMark,query_objects,objectTypeFromAddress,ObjectType}from'@wowok/wowok';import{fetchMachineNodes,buildMachineGraph}from'./machine-nodes.js';import{batchQueryObjectsByIds,fetchObjectLinkerTx,ringWindowSaturated}from'../../graph/onchain/sdk-batch.js';export async function handleMachinePanorama(a){const b=a['object_address'];if(!b)throw new Error('\x27object_address\x27\x20is\x20required\x20for\x20machine_panorama');let c=a['context_network']??undefined;const d=[];let f=b;if(!/^0x[0-9a-fA-F]{32,64}$/['test'](b)){const s=await LocalMark['Instance']()['get_address'](b);if(!s)throw new Error('Cannot\x20resolve\x20machine\x20\x27'+b+'\x27\x20—\x20not\x20a\x20valid\x20address\x20and\x20no\x20LocalMark\x20entry\x20found.\x20'+'Pass\x20the\x200x\x20Machine\x20object\x20address\x20directly\x20or\x20register\x20the\x20name\x20via\x20local_mark_operation.');f=s;}let g=null;try{if(!c)c=await Config['Instance']()['network_get']();const u=await query_objects({'objects':[f],'network':c});g=u?.['objects']?.[0x0]??null;if(!g&&a['context_network']){const w=await Config['Instance']()['network_get']();if(w&&w!==c){const x=await query_objects({'objects':[f],'network':w,'no_cache':!![]}),y=x?.['objects']?.[0x0]??null;y&&(g=y,c=w);}}}catch(z){throw new Error('Failed\x20to\x20query\x20Machine\x20'+f+'\x20on\x20'+c+':\x20'+(''+(z instanceof Error?z['message']:String(z))));}if(!g)throw new Error('Machine\x20'+f+'\x20not\x20found\x20on\x20'+c+'.\x20It\x20may\x20not\x20exist\x20on\x20this\x20network.');f=g['object']??f;let h=null,j=[];try{const A=await LocalMark['Instance']()['list']({'address':f});A['length']>0x0&&(h=A[0x0]['name']??null,j=(A[0x0]['tags']??[])['map'](B=>String(B)));}catch{d['push']('head:\x20LocalMark\x20lookup\x20failed');}let k={'nodes':[],'edges':[]};try{const B=await fetchMachineNodes(f,c);k=buildMachineGraph(B);}catch{d['push']('graph:\x20node\x20fetch\x20failed\x20(non-blocking)');}const l=[];let m=0x0,n=0x0,p=![],q=[];try{const C=await fetchObjectLinkerTx(f,c,!![]),D=C?.['items']??[];p=ringWindowSaturated(D['length']);const E=new Map();for(const L of D){const M=typeof L?.['who']==='string'?L['who']['toLowerCase']():'';if(!M||M==='0x0')continue;if(!objectTypeFromAddress(M))continue;const N=typeof L?.['time']==='number'?L['time']:null,O=E['get'](M);E['set'](M,O==null?N:N==null?O:Math['max'](O,N));}n=E['size'];const F=new Map();for(const [P,Q]of E){const R=String(objectTypeFromAddress(P)),S=F['get'](R)??[];S['push']({'address':P,'time':Q}),F['set'](R,S);}for(const T of F['values']()){T['sort']((U,V)=>(V['time']??0x0)-(U['time']??0x0));}const G=['Progress','Allocation','Payment','Guard'];q=[];for(const U of G){const V=F['get'](U);V&&V['length']>0x0&&(q['push']({'label':U,'items':V}),F['delete'](U));}for(const [W,X]of F){if(X['length']>0x0)q['push']({'label':W,'items':X});}const H=D['filter'](Y=>objectTypeFromAddress(Y['who'])===ObjectType['Progress']);m=H['length'];const I=H['slice'](-0x32)['reverse'](),J=I['map'](Y=>Y['who']),K=new Map();if(J['length']>0x0)try{const Y=await batchQueryObjectsByIds(J,c,!![]);for(const Z of Y){if(Z?.['object'])K['set'](Z['object'],Z);}}catch{d['push']('progresses:\x20detail\x20fetch\x20failed');}for(const a0 of I){const a1=typeof a0?.['who']==='string'?a0['who']:'';if(!a1)continue;const a2=K['get'](a1);l['push']({'progress':a1,'name':null,'current':a2?.['current']??null,'task':a2?.['task']??null,'history_count':typeof a2?.['history_count']==='number'?a2['history_count']:null,'current_time':typeof a2?.['current_time']==='number'?a2['current_time']:null,'created_at':typeof a0?.['time']==='number'?a0['time']:null});}}catch{d['push']('progresses:\x20global-table\x20lookup\x20failed\x20(non-blocking)');}return{'action':'machine_panorama','machineAddress':f,'network':String(c),'head':{'name':h,'tags':j,'description':typeof g['description']==='string'?g['description']:null,'published':typeof g['bPublished']==='boolean'?g['bPublished']:null,'paused':typeof g['bPaused']==='boolean'?g['bPaused']:null},'fields':{'permission':g['permission']??null,'um':g['um']??null,'node_count':typeof g['node_count']==='number'?g['node_count']:null,'consensus_repositories':Array['isArray'](g['consensus_repositories'])?g['consensus_repositories']:[]},'graph':k,'progresses':{'count':m,'window_saturated':p,'preview_truncated':m>l['length'],'items':l},'related':{'count':n,'window_saturated':p,'groups':q},'data_gaps':d};}