@wowok/agent-mcp 3.4.0 → 3.4.1

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 (405) hide show
  1. package/README.md +8 -0
  2. package/dist/chain-semantics/composition-truth.d.ts +102 -0
  3. package/dist/chain-semantics/composition-truth.js +1 -0
  4. package/dist/chain-semantics/eval-order.js +1 -1
  5. package/dist/chain-semantics/fund-flow.js +1 -1
  6. package/dist/chain-semantics/index.d.ts +1 -0
  7. package/dist/chain-semantics/index.js +1 -1
  8. package/dist/composition/audit.js +1 -1
  9. package/dist/composition/blueprint-view.d.ts +3 -3
  10. package/dist/composition/blueprint-view.js +1 -1
  11. package/dist/composition/compile.d.ts +24 -3
  12. package/dist/composition/compile.js +1 -1
  13. package/dist/composition/emit-phases.d.ts +206 -0
  14. package/dist/composition/emit-phases.js +1 -0
  15. package/dist/composition/generate.d.ts +40 -0
  16. package/dist/composition/generate.js +1 -0
  17. package/dist/composition/guard-fill.d.ts +44 -0
  18. package/dist/composition/guard-fill.js +1 -0
  19. package/dist/composition/inflight.d.ts +20 -2
  20. package/dist/composition/inflight.js +1 -1
  21. package/dist/composition/input-normalize.d.ts +15 -0
  22. package/dist/composition/input-normalize.js +1 -0
  23. package/dist/composition/materialize.d.ts +18 -13
  24. package/dist/composition/materialize.js +1 -1
  25. package/dist/composition/mode-gates.d.ts +35 -0
  26. package/dist/composition/mode-gates.js +1 -0
  27. package/dist/composition/param-disclosure.js +1 -1
  28. package/dist/composition/plan-retry-ledger.d.ts +21 -0
  29. package/dist/composition/plan-retry-ledger.js +1 -0
  30. package/dist/composition/plan.d.ts +7 -2
  31. package/dist/composition/plan.js +1 -1
  32. package/dist/composition/product-card.d.ts +94 -0
  33. package/dist/composition/product-card.js +1 -0
  34. package/dist/composition/supply-chain-emit.d.ts +46 -0
  35. package/dist/composition/supply-chain-emit.js +1 -0
  36. package/dist/config/config-audit.spec.js +1 -1
  37. package/dist/config/config-warnings.d.ts +2 -0
  38. package/dist/config/config-warnings.js +1 -0
  39. package/dist/config/exposure.d.ts +2 -2
  40. package/dist/config/judgment.d.ts +31 -5
  41. package/dist/config/judgment.js +1 -1
  42. package/dist/config/judgment.spec.js +1 -1
  43. package/dist/config/match-policy-file.d.ts +34 -0
  44. package/dist/config/match-policy-file.js +1 -0
  45. package/dist/config/match-policy-file.spec.d.ts +1 -0
  46. package/dist/config/match-policy-file.spec.js +1 -0
  47. package/dist/config/rule-engine.d.ts +5 -5
  48. package/dist/config/rule-engine.js +1 -1
  49. package/dist/config/runtime.d.ts +0 -1
  50. package/dist/config/runtime.js +1 -1
  51. package/dist/config/severity.d.ts +0 -2
  52. package/dist/config/severity.js +1 -1
  53. package/dist/config/store-policy.spec.js +1 -1
  54. package/dist/config/template-params.d.ts +42 -0
  55. package/dist/config/template-params.js +1 -0
  56. package/dist/config/template-params.spec.d.ts +1 -0
  57. package/dist/config/template-params.spec.js +1 -0
  58. package/dist/data/api/api.spec.js +1 -1
  59. package/dist/data/api/server.js +1 -1
  60. package/dist/data/projection/store.d.ts +2 -1
  61. package/dist/data/projection/store.js +1 -1
  62. package/dist/data/projection/types.d.ts +22 -0
  63. package/dist/data/sync/cdc.d.ts +1 -2
  64. package/dist/data/sync/cdc.js +1 -1
  65. package/dist/evaluation/acceptance.d.ts +8 -0
  66. package/dist/evaluation/acceptance.js +1 -1
  67. package/dist/evaluation/builtins/demand-match.js +1 -1
  68. package/dist/evaluation/builtins/graph-service.spec.js +1 -1
  69. package/dist/evaluation/capability.d.ts +2 -0
  70. package/dist/evaluation/category-match-rules.d.ts +0 -1
  71. package/dist/evaluation/category-match-rules.js +1 -1
  72. package/dist/evaluation/composer.d.ts +25 -0
  73. package/dist/evaluation/composer.js +1 -1
  74. package/dist/evaluation/engine.js +1 -1
  75. package/dist/evaluation/extract.d.ts +7 -0
  76. package/dist/evaluation/extract.js +1 -1
  77. package/dist/evaluation/game-strategy.d.ts +0 -3
  78. package/dist/evaluation/game-strategy.js +1 -1
  79. package/dist/evaluation/match-operation.d.ts +9 -0
  80. package/dist/evaluation/match-operation.js +1 -1
  81. package/dist/evaluation/match-policy-resolver.d.ts +9 -0
  82. package/dist/evaluation/match-policy-resolver.js +1 -0
  83. package/dist/evaluation/match-policy.d.ts +3 -1
  84. package/dist/evaluation/match-policy.js +1 -1
  85. package/dist/evaluation/region.d.ts +0 -6
  86. package/dist/evaluation/region.js +1 -1
  87. package/dist/evaluation/standards.d.ts +2 -1
  88. package/dist/evaluation/standards.js +1 -1
  89. package/dist/evaluation/structured-lines.d.ts +8 -0
  90. package/dist/evaluation/structured-lines.js +1 -0
  91. package/dist/evaluation/types.d.ts +6 -0
  92. package/dist/experience/realtime-feedback.js +1 -1
  93. package/dist/extensions/capability-manifest.d.ts +1 -0
  94. package/dist/extensions/capability-manifest.js +1 -1
  95. package/dist/extensions/capability.d.ts +91 -0
  96. package/dist/extensions/capability.js +1 -0
  97. package/dist/extensions/industry-audit.spec.js +1 -1
  98. package/dist/extensions/industry-pack.d.ts +13 -0
  99. package/dist/extensions/industry-pack.js +1 -1
  100. package/dist/extensions/modes.js +1 -1
  101. package/dist/extensions/registry.d.ts +0 -2
  102. package/dist/extensions/registry.js +1 -1
  103. package/dist/goal/GoalEngine.js +1 -1
  104. package/dist/graph/onchain/analyze.js +1 -1
  105. package/dist/graph/onchain/expand.js +1 -1
  106. package/dist/graph/onchain/exposure.js +1 -1
  107. package/dist/graph/onchain/facts.js +1 -1
  108. package/dist/graph/onchain/order-status.d.ts +0 -1
  109. package/dist/graph/onchain/order-status.js +1 -1
  110. package/dist/harness/recover.js +1 -1
  111. package/dist/harness/verify.d.ts +0 -3
  112. package/dist/harness/verify.js +1 -1
  113. package/dist/intent/types.d.ts +0 -1
  114. package/dist/intent/types.js +1 -1
  115. package/dist/keeper/detectors.js +1 -1
  116. package/dist/keeper/types.d.ts +0 -1
  117. package/dist/keeper/types.js +1 -1
  118. package/dist/knowledge/allocation-risk.d.ts +1 -0
  119. package/dist/knowledge/allocation-risk.js +1 -1
  120. package/dist/knowledge/allocator-rail-verifier.d.ts +6 -1
  121. package/dist/knowledge/allocator-rail-verifier.js +1 -1
  122. package/dist/knowledge/arbitration-ledger.js +1 -1
  123. package/dist/knowledge/arbitration-puzzle.js +1 -1
  124. package/dist/knowledge/audit-rules.d.ts +2 -2
  125. package/dist/knowledge/audit-rules.js +1 -1
  126. package/dist/knowledge/baselines/judgment-baselines.json +21 -2
  127. package/dist/knowledge/baselines/rules/oracle.json +120 -0
  128. package/dist/knowledge/baselines/rules/plan.json +384 -17
  129. package/dist/knowledge/baselines/rules/progress.json +20 -2
  130. package/dist/knowledge/builtin-templates.d.ts +12 -1
  131. package/dist/knowledge/builtin-templates.js +1 -1
  132. package/dist/knowledge/component-schema.js +1 -1
  133. package/dist/knowledge/contact-templates.d.ts +0 -1
  134. package/dist/knowledge/contact-templates.js +1 -1
  135. package/dist/knowledge/dynamic-pricing.js +1 -1
  136. package/dist/knowledge/fee-param-bindings.js +1 -1
  137. package/dist/knowledge/fund-layer.d.ts +1 -0
  138. package/dist/knowledge/fund-layer.js +1 -1
  139. package/dist/knowledge/game-scenarios.js +1 -1
  140. package/dist/knowledge/getting-started.js +1 -1
  141. package/dist/knowledge/guard-binding-table.d.ts +52 -0
  142. package/dist/knowledge/guard-binding-table.js +1 -0
  143. package/dist/knowledge/guard-binding-verifier.d.ts +30 -0
  144. package/dist/knowledge/guard-binding-verifier.js +1 -0
  145. package/dist/knowledge/guard-bindings.js +1 -1
  146. package/dist/knowledge/guard-blueprint.d.ts +68 -0
  147. package/dist/knowledge/guard-blueprint.js +1 -0
  148. package/dist/knowledge/guard-design-patterns.d.ts +1 -1
  149. package/dist/knowledge/guard-design-patterns.js +1 -1
  150. package/dist/knowledge/guard-field-cognition.js +1 -1
  151. package/dist/knowledge/guard-host-context.d.ts +24 -0
  152. package/dist/knowledge/guard-host-context.js +1 -0
  153. package/dist/knowledge/guard-lint.js +1 -1
  154. package/dist/knowledge/guard-node-gates.d.ts +3 -0
  155. package/dist/knowledge/guard-node-gates.js +1 -1
  156. package/dist/knowledge/guard-puzzle.js +1 -1
  157. package/dist/knowledge/guard-render.js +1 -1
  158. package/dist/knowledge/guard-risk.js +1 -1
  159. package/dist/knowledge/guard-submission-prompt.d.ts +11 -0
  160. package/dist/knowledge/guard-submission-prompt.js +1 -1
  161. package/dist/knowledge/guard-templates.d.ts +1 -1
  162. package/dist/knowledge/guard-templates.js +1 -1
  163. package/dist/knowledge/guard-translation.js +1 -1
  164. package/dist/knowledge/index.d.ts +1 -1
  165. package/dist/knowledge/index.js +1 -1
  166. package/dist/knowledge/industry-generalizer.d.ts +6 -1
  167. package/dist/knowledge/industry-generalizer.js +1 -1
  168. package/dist/knowledge/industry-registry.js +1 -1
  169. package/dist/knowledge/jsonrpc-enum.d.ts +38 -0
  170. package/dist/knowledge/jsonrpc-enum.js +1 -1
  171. package/dist/knowledge/machine-topology.js +1 -1
  172. package/dist/knowledge/machine-translation.js +1 -1
  173. package/dist/knowledge/object-dependency.d.ts +31 -0
  174. package/dist/knowledge/object-dependency.js +1 -0
  175. package/dist/knowledge/onchain-constants.d.ts +2 -0
  176. package/dist/knowledge/onchain-constants.js +1 -1
  177. package/dist/knowledge/param-schema.d.ts +23 -0
  178. package/dist/knowledge/param-schema.js +1 -1
  179. package/dist/knowledge/param-tiers.js +1 -1
  180. package/dist/knowledge/passport-ledger.js +1 -1
  181. package/dist/knowledge/path-oracle/coverage.d.ts +16 -0
  182. package/dist/knowledge/path-oracle/coverage.js +1 -0
  183. package/dist/knowledge/path-oracle/index.d.ts +5 -0
  184. package/dist/knowledge/path-oracle/index.js +1 -0
  185. package/dist/knowledge/path-oracle/products/food-delivery.d.ts +2 -0
  186. package/dist/knowledge/path-oracle/products/food-delivery.js +1 -0
  187. package/dist/knowledge/path-oracle/schema.d.ts +188 -0
  188. package/dist/knowledge/path-oracle/schema.js +1 -0
  189. package/dist/knowledge/pattern-resolutions.d.ts +2 -0
  190. package/dist/knowledge/pattern-resolutions.js +1 -1
  191. package/dist/knowledge/progress-ledger.js +1 -1
  192. package/dist/knowledge/progress-risk.js +1 -1
  193. package/dist/knowledge/projection.spec.js +1 -1
  194. package/dist/knowledge/protocol-facts.js +1 -1
  195. package/dist/knowledge/requirement-families.d.ts +13 -0
  196. package/dist/knowledge/requirement-families.js +1 -0
  197. package/dist/knowledge/reward-ledger.js +1 -1
  198. package/dist/knowledge/scenario-modes.d.ts +1 -0
  199. package/dist/knowledge/scenario-modes.js +1 -1
  200. package/dist/knowledge/semantic-ir.d.ts +4 -0
  201. package/dist/knowledge/semantic-ir.js +1 -1
  202. package/dist/knowledge/service-ledger.d.ts +1 -1
  203. package/dist/knowledge/service-ledger.js +1 -1
  204. package/dist/knowledge/sku-name-gate.d.ts +17 -0
  205. package/dist/knowledge/sku-name-gate.js +1 -0
  206. package/dist/knowledge/supply-chain.d.ts +9 -0
  207. package/dist/knowledge/supply-chain.js +1 -1
  208. package/dist/knowledge/template-loader.d.ts +14 -6
  209. package/dist/knowledge/template-loader.js +1 -1
  210. package/dist/knowledge/template-nav.d.ts +3 -1
  211. package/dist/knowledge/template-nav.js +1 -1
  212. package/dist/knowledge/template-prose.d.ts +1 -1
  213. package/dist/knowledge/template-registry.js +1 -1
  214. package/dist/knowledge/template-scanner.d.ts +62 -0
  215. package/dist/knowledge/template-scanner.js +1 -1
  216. package/dist/knowledge/template-test-profiles.js +1 -1
  217. package/dist/knowledge/tools-reference.js +1 -1
  218. package/dist/knowledge/workflow-guidance.d.ts +5 -0
  219. package/dist/knowledge/workflow-guidance.js +1 -1
  220. package/dist/monitor/MonitorLoop.js +1 -1
  221. package/dist/participation/radar-core.js +1 -1
  222. package/dist/participation/time-window.js +1 -1
  223. package/dist/persona/address-format.d.ts +0 -1
  224. package/dist/persona/address-format.js +1 -1
  225. package/dist/persona/bridge.js +1 -1
  226. package/dist/persona/index.d.ts +0 -2
  227. package/dist/persona/index.js +1 -1
  228. package/dist/persona/model.js +1 -1
  229. package/dist/persona/persona-audit.spec.js +1 -1
  230. package/dist/persona/types.d.ts +6 -0
  231. package/dist/playbooks/service-build/business-puzzle.js +1 -1
  232. package/dist/playbooks/service-build/game-theory.d.ts +2 -2
  233. package/dist/playbooks/service-build/intent-analyzer.js +1 -1
  234. package/dist/playbooks/service-build/machine-panorama.js +1 -1
  235. package/dist/playbooks/service-build/merchant-guide.d.ts +50 -23
  236. package/dist/playbooks/service-build/merchant-guide.js +1 -1
  237. package/dist/playbooks/service-build/migration-planner.d.ts +2 -0
  238. package/dist/playbooks/service-build/migration-planner.js +1 -1
  239. package/dist/playbooks/service-build/mode-actions.js +1 -1
  240. package/dist/playbooks/service-build/object-panorama.d.ts +8 -0
  241. package/dist/playbooks/service-build/object-panorama.js +1 -1
  242. package/dist/playbooks/service-build/participation-radar.js +1 -1
  243. package/dist/playbooks/service-build/relationship-profile.js +1 -1
  244. package/dist/playbooks/service-build/reverse-mapping.d.ts +6 -0
  245. package/dist/playbooks/service-build/reverse-mapping.js +1 -1
  246. package/dist/playbooks/service-build/service-panorama.d.ts +1 -0
  247. package/dist/playbooks/service-build/service-panorama.js +1 -1
  248. package/dist/playbooks/service-build/service-quote.js +1 -1
  249. package/dist/playbooks/service-build/service-quote.spec.js +1 -1
  250. package/dist/playbooks/service-build/workflow-design-assessment.d.ts +10 -1
  251. package/dist/playbooks/service-build/workflow-design-assessment.js +1 -1
  252. package/dist/review/index.js +1 -1
  253. package/dist/review/repository.js +1 -1
  254. package/dist/safety/confirm-gate.js +1 -1
  255. package/dist/schema/benchmark-migration/index.d.ts +104 -0
  256. package/dist/schema/benchmark-migration/index.js +1 -1
  257. package/dist/schema/call/allocation.d.ts +15 -6
  258. package/dist/schema/call/allocation.js +1 -1
  259. package/dist/schema/call/base.d.ts +256 -0
  260. package/dist/schema/call/base.js +1 -1
  261. package/dist/schema/call/bridge.d.ts +32 -6
  262. package/dist/schema/call/demand.d.ts +15 -6
  263. package/dist/schema/call/demand.js +1 -1
  264. package/dist/schema/call/guard.d.ts +8 -8
  265. package/dist/schema/call/guard.js +1 -1
  266. package/dist/schema/call/handler.d.ts +3 -0
  267. package/dist/schema/call/handler.js +1 -1
  268. package/dist/schema/call/machine.d.ts +32 -8
  269. package/dist/schema/call/machine.js +1 -1
  270. package/dist/schema/call/order.d.ts +26 -8
  271. package/dist/schema/call/order.js +1 -1
  272. package/dist/schema/call/payment.d.ts +20 -8
  273. package/dist/schema/call/payment.js +1 -1
  274. package/dist/schema/call/permission-handler.js +1 -1
  275. package/dist/schema/call/permission.d.ts +330 -114
  276. package/dist/schema/call/permission.js +1 -1
  277. package/dist/schema/call/personal.d.ts +10 -4
  278. package/dist/schema/call/personal.js +1 -1
  279. package/dist/schema/call/progress.d.ts +16 -4
  280. package/dist/schema/call/reward.d.ts +10 -4
  281. package/dist/schema/call/reward.js +1 -1
  282. package/dist/schema/call/semantic.d.ts +1 -0
  283. package/dist/schema/call/semantic.js +1 -1
  284. package/dist/schema/call/service.d.ts +128 -40
  285. package/dist/schema/call/service.js +1 -1
  286. package/dist/schema/call/treasury.d.ts +15 -6
  287. package/dist/schema/call/treasury.js +1 -1
  288. package/dist/schema/common/index.js +1 -1
  289. package/dist/schema/config/index.d.ts +61 -0
  290. package/dist/schema/config/index.js +1 -1
  291. package/dist/schema/envelope-unify.d.ts +4 -0
  292. package/dist/schema/envelope-unify.js +1 -0
  293. package/dist/schema/evaluation/index.d.ts +216 -19
  294. package/dist/schema/evaluation/index.js +1 -1
  295. package/dist/schema/goal/index.d.ts +47 -0
  296. package/dist/schema/goal/planning.d.ts +115 -1
  297. package/dist/schema/goal/planning.js +1 -1
  298. package/dist/schema/industry-pack/index.d.ts +137 -6
  299. package/dist/schema/industry-pack/index.js +1 -1
  300. package/dist/schema/industry-pack/modes.d.ts +6 -6
  301. package/dist/schema/keeper/index.d.ts +26 -0
  302. package/dist/schema/local/index.d.ts +137 -0
  303. package/dist/schema/local/index.js +1 -1
  304. package/dist/schema/local/wip.d.ts +6 -0
  305. package/dist/schema/local/wip.js +1 -1
  306. package/dist/schema/messenger/index.d.ts +26 -0
  307. package/dist/schema/operations.d.ts +342 -83
  308. package/dist/schema/operations.js +1 -1
  309. package/dist/schema/persona/index.d.ts +2907 -640
  310. package/dist/schema/persona/index.js +1 -1
  311. package/dist/schema/query/bi.d.ts +145 -4
  312. package/dist/schema/query/bi.js +1 -1
  313. package/dist/schema/query/index.d.ts +266 -73
  314. package/dist/schema/query/index.js +1 -1
  315. package/dist/schema/schema-query/index.d.ts +1 -1
  316. package/dist/schema/schema-query/index.js +1 -1
  317. package/dist/schema/schema-version.js +1 -1
  318. package/dist/schema/utils/permission-machine-check.d.ts +2 -0
  319. package/dist/schema/utils/permission-machine-check.js +1 -1
  320. package/dist/schema/watch/index.d.ts +16 -0
  321. package/dist/schema/watch/index.js +1 -1
  322. package/dist/schema/workflow/index.d.ts +2 -2
  323. package/dist/schema/workflow/index.js +1 -1
  324. package/dist/schema-query-impl/index.d.ts +1 -1
  325. package/dist/schema-query-impl/index.js +1 -1
  326. package/dist/schemas/account_operation.output.json +94 -0
  327. package/dist/schemas/benchmark_migration_operation.output.json +338 -9
  328. package/dist/schemas/benchmark_migration_operation.schema.json +26 -1
  329. package/dist/schemas/bridge_operation.output.json +94 -0
  330. package/dist/schemas/config_operation.output.json +352 -0
  331. package/dist/schemas/config_operation.schema.json +20 -2
  332. package/dist/schemas/evaluation_operation.output.json +570 -4
  333. package/dist/schemas/evaluation_operation.schema.json +194 -3
  334. package/dist/schemas/goal_operation.schema.json +183 -0
  335. package/dist/schemas/index.json +1 -1
  336. package/dist/schemas/industry_pack_operation.output.json +621 -0
  337. package/dist/schemas/industry_pack_operation.schema.json +20 -2
  338. package/dist/schemas/keeper_operation.output.json +94 -0
  339. package/dist/schemas/local_cache_operation.output.json +94 -0
  340. package/dist/schemas/local_history_operation.output.json +94 -0
  341. package/dist/schemas/local_info_operation.output.json +94 -0
  342. package/dist/schemas/local_mark_operation.output.json +94 -0
  343. package/dist/schemas/messenger_operation.output.json +94 -0
  344. package/dist/schemas/monitor_events.output.json +94 -0
  345. package/dist/schemas/monitor_subscription.output.json +94 -0
  346. package/dist/schemas/onchain_events.output.json +94 -0
  347. package/dist/schemas/onchain_operations.output.json +313 -1
  348. package/dist/schemas/onchain_operations.schema.json +1248 -664
  349. package/dist/schemas/onchain_operations_allocation.schema.json +30 -15
  350. package/dist/schemas/onchain_operations_arbitration.schema.json +9 -2
  351. package/dist/schemas/onchain_operations_contact.schema.json +8 -1
  352. package/dist/schemas/onchain_operations_demand.schema.json +29 -14
  353. package/dist/schemas/onchain_operations_gen_passport.schema.json +8 -1
  354. package/dist/schemas/onchain_operations_guard.schema.json +290 -105
  355. package/dist/schemas/onchain_operations_machine.schema.json +49 -34
  356. package/dist/schemas/onchain_operations_order.schema.json +63 -40
  357. package/dist/schemas/onchain_operations_payment.schema.json +26 -11
  358. package/dist/schemas/onchain_operations_permission.schema.json +362 -235
  359. package/dist/schemas/onchain_operations_personal.schema.json +27 -15
  360. package/dist/schemas/onchain_operations_progress.schema.json +45 -30
  361. package/dist/schemas/onchain_operations_proof.schema.json +8 -1
  362. package/dist/schemas/onchain_operations_repository.schema.json +8 -1
  363. package/dist/schemas/onchain_operations_reward.schema.json +32 -17
  364. package/dist/schemas/onchain_operations_service.schema.json +221 -124
  365. package/dist/schemas/onchain_operations_treasury.schema.json +32 -17
  366. package/dist/schemas/onchain_table_data.output.json +258 -6
  367. package/dist/schemas/onchain_table_data.schema.json +92 -52
  368. package/dist/schemas/persona_operation.output.json +7752 -0
  369. package/dist/schemas/persona_operation.schema.json +1232 -4
  370. package/dist/schemas/query_toolkit.output.json +756 -116
  371. package/dist/schemas/query_toolkit.schema.json +138 -7
  372. package/dist/schemas/schema_query.schema.json +1 -1
  373. package/dist/schemas/watch_operation.output.json +83 -0
  374. package/dist/schemas/wip_file.output.json +8 -0
  375. package/dist/schemas/workflow_operation.schema.json +2 -2
  376. package/dist/tools/handlers/benchmark-migration.d.ts +11 -3
  377. package/dist/tools/handlers/benchmark-migration.js +1 -1
  378. package/dist/tools/handlers/config.js +1 -1
  379. package/dist/tools/handlers/evaluation.js +1 -1
  380. package/dist/tools/handlers/evaluation.spec.js +1 -1
  381. package/dist/tools/handlers/industry-pack.js +1 -1
  382. package/dist/tools/handlers/onchain.d.ts +20 -0
  383. package/dist/tools/handlers/onchain.js +1 -1
  384. package/dist/tools/handlers/persona.js +1 -1
  385. package/dist/tools/handlers/query.d.ts +8 -0
  386. package/dist/tools/handlers/query.js +1 -1
  387. package/dist/tools/handlers/winner-derivation.d.ts +20 -0
  388. package/dist/tools/handlers/winner-derivation.js +1 -0
  389. package/dist/tools/handlers/wip-upload.js +1 -1
  390. package/dist/tools/index.d.ts +1 -0
  391. package/dist/tools/index.js +1 -1
  392. package/dist/tools/registry/business.js +1 -1
  393. package/dist/tools/registry/config.js +1 -1
  394. package/dist/tools/registry/evaluation.js +1 -1
  395. package/dist/tools/registry/identity.js +1 -1
  396. package/dist/tools/registry/query.js +1 -1
  397. package/dist/tools/transport-integrity.d.ts +7 -0
  398. package/dist/tools/transport-integrity.js +1 -0
  399. package/dist/tools/upgrade-check.js +1 -1
  400. package/dist/tools/wrap.d.ts +5 -0
  401. package/dist/tools/wrap.js +1 -1
  402. package/package.json +2 -2
  403. package/dist/extensions/business-modules.d.ts +0 -54
  404. package/dist/extensions/business-modules.js +0 -1
  405. package/dist/schemas/guard-templates.json +0 -379
@@ -1 +1 @@
1
- import{getScenarioMode}from'../knowledge/scenario-modes.js';import{BUILTIN_TEMPLATES}from'../knowledge/builtin-templates.js';import{getIndustryTraits}from'../knowledge/industry-registry.js';import{getIndustryRiskChecks,getIndustryNeeds}from'../customer/index.js';import{SUPPORTED_INDUSTRIES}from'../customer/user-preferences.js';import{getFlywheelForIndustry}from'../knowledge/acquisition-flywheel.js';const GENERAL_TRAITS={'has_logistics':![],'communication_heavy':![],'pure_digital':![],'long_cycle':![],'deposit_required':![],'multi_tier_allocation':![],'regulatory_intensity':'low','trust_sensitivity':'medium','consumption_frequency':'occasional','avg_ticket_size':'medium'},GENERAL_FLYWHEEL={'industry':'general','trustSellingPoints':[],'keyActions':[],'rewardStrategy':'User-defined','discountStrategy':'User-defined','trustDescription':'User-defined\x20trust\x20mechanism'},GENERAL_MACHINE_SHAPE=[{'name':'paid','role':'Entry:\x20order\x20created\x20and\x20paid'},{'name':'delivering','role':'Service\x20delivery\x20in\x20progress'},{'name':'delivered','role':'Deliverable\x20available\x20for\x20review'},{'name':'completed','role':'Service\x20completed,\x20funds\x20released'},{'name':'cancelled','role':'Pre-delivery\x20cancellation\x20—\x20triggers\x20refund\x20Allocator','operator':'order_payer'}],GENERAL_ALLOCATOR={'recipient':'signer','count':0x1,'mode':'surplus','description':'Default:\x20surplus\x20to\x20service\x20owner\x20(general\x20fallback)'},RETAIL_D2C_MACHINE_SHAPE=[{'name':'ordered','role':'Entry:\x20order\x20created\x20(funds\x20escrowed\x20in\x20Allocation)'},{'name':'shipped','role':'Merchant\x20ships\x20goods'},{'name':'delivered','role':'Goods\x20delivered\x20to\x20buyer'},{'name':'completed','role':'Buyer\x20confirms\x20receipt\x20—\x20withdraw_guard\x20releases\x20funds','operator':'order_payer'},{'name':'cancelled','role':'Pre-ship\x20cancellation\x20—\x20refund_guard\x20refunds\x20buyer','operator':'order_payer'}],RETAIL_D2C_GUARDS=[{'template_id':'withdraw_guard_delivery','host':'service','purpose':'Release\x20funds\x20to\x20merchant\x20+\x20processor\x20on\x20order\x20completion\x20(delivery\x20confirmation)'},{'template_id':'refund_guard_cancellation','host':'service','purpose':'Refund\x20100%\x20to\x20buyer\x20on\x20order\x20cancellation'}],RETAIL_D2C_ALLOCATOR={'recipient':'entity','count':0x2,'mode':'rate','description':'Merchant\x2097%\x20+\x20Processor\x203%\x20(rate-based\x20split,\x20no\x20platform\x20commission)'},RETAIL_D2C_KEY_RISK='No\x20platform\x20arbitration\x20—\x20disputes\x20rely\x20on\x20optional\x20Arbitration\x20or\x20off-chain\x20chargeback',RETAIL_D2C_BUILD_NOTES=['Allocation\x20escrow\x20replaces\x20platform\x20custody\x20—\x20funds\x20locked\x20in\x20contract\x20until\x20Guard\x20releases','withdraw_guard\x20enforces\x20delivery\x20gate\x20—\x20merchant\x20must\x20reach\x20\x27completed\x27\x20state\x20to\x20receive\x20payment','refund_guard\x20ensures\x20100%\x20refund\x20on\x20cancellation\x20—\x20no\x20merchant\x20approval\x20needed','No\x20buy_guard\x20needed\x20—\x20D2C\x20doesn\x27t\x20gate\x20purchases\x20(open\x20storefront)','Arbitration\x20is\x20optional\x20—\x20add\x20when\x20dispute\x20volume\x20justifies\x20the\x20cost','Service\x20↔\x20Guard\x20circular\x20dependency:\x20create\x20Service\x20(unpublished)\x20→\x20create\x20Guards\x20→\x20update\x20Service\x20(publish)'],SUPPORTED_INDUSTRY_SET=new Set([...SUPPORTED_INDUSTRIES,'retail_d2c']);function fetchTemplate(a){const b=a==='retail_d2c'?'retail':a,c=getIndustryTraits(b)??GENERAL_TRAITS,d=SUPPORTED_INDUSTRY_SET['has'](a),e=a==='retail_d2c'?'retail':a,f=d?getIndustryRiskChecks(e):[],g=d?getIndustryNeeds(e):[],h=getFlywheelForIndustry(b)??GENERAL_FLYWHEEL;let i,j,k,l,m;if(a==='retail_d2c')i=RETAIL_D2C_MACHINE_SHAPE,j=RETAIL_D2C_GUARDS,k=RETAIL_D2C_ALLOCATOR,l=RETAIL_D2C_KEY_RISK,m=RETAIL_D2C_BUILD_NOTES;else{if(a==='general'){const n=getScenarioMode('general');i=GENERAL_MACHINE_SHAPE,j=[],k=GENERAL_ALLOCATOR,l=n?.['key_risk']??'No\x20safety\x20net\x20—\x20user\x20must\x20design\x20all\x20trust\x20mechanisms\x20manually',m=n?.['build_notes'];}else{const o=getScenarioMode(a);if(!o)throw new Error('No\x20scenario\x20mode\x20found\x20for\x20industry:\x20'+a);const p=BUILTIN_TEMPLATES['find'](q=>q['id']===o['default_template']);if(!p)throw new Error('Mode\x20\x27'+a+'\x27\x20default_template\x20\x27'+o['default_template']+'\x27\x20is\x20not\x20in\x20the\x20builtin\x20template\x20catalog');i=p['machine_shape'],j=p['guards'],k=p['allocator'],l=o['key_risk'],m=o['build_notes'];}}return{'traits':c,'risk_checks':f,'needs':g,'flywheel':h,'machine_shape':i,'guards':j,'allocator':k,'key_risk':l,'build_notes':m};}export const BUILTIN_MODES=[{'name':'freelance','display_name':'Freelance','version':'v1','source':'builtin',...fetchTemplate('freelance'),'analyze':{'key_questions':['Are\x20WIP\x20hashes\x20bound\x20to\x20each\x20milestone,\x20so\x20delivery\x20evidence\x20cannot\x20be\x20substituted\x20after\x20acceptance?','Does\x20the\x20acceptance\x20gate\x20have\x20a\x20time-bounded\x20escape\x20(keeper-driven\x20auto-accept),\x20or\x20can\x20a\x20silent\x20buyer\x20hold\x20the\x20provider\x27s\x20funds\x20hostage\x20indefinitely?']},'capabilities_used':['permission.index_create','permission.role_assign','guard.validate_buy','guard.validate_wip_hash','machine.node_topology','treasury.owner_receive','allocation.distribute','allocation.distribute_milestone','service.publish','progress.advance','arb.vote_weighted','contact.im_create'],'config_overrides':{'service':{'setting_lock_duration':'30d','engagement_type':'milestone'},'machine':{'wip_required':!![],'wip_hash_algorithm':'sha256','acceptance_gate':!![]}},'expected_benefits':[{'metric':'Dispute\x20rate\x20reduction','expected_value':'40%','evidence':'WIP\x20hash\x20+\x20milestone\x20allocation\x20enforces\x20delivery\x20evidence'},{'metric':'Delivery\x20confirmation\x20efficiency','expected_value':'+50%','evidence':'acceptance\x20gate\x20automates\x20acceptance\x20workflow'},{'metric':'Provider\x20payment\x20assurance','expected_value':'100%','evidence':'Funds\x20auto-release\x20to\x20provider\x20after\x20accepted\x20node'}],'risk_appetite':'balanced','risk_constraints':{'require_arbitration':!![],'require_compensation_fund':![],'require_wip_evidence':!![],'other_constraints':['setting_lock_duration\x20>=\x207d\x20to\x20lock\x20engagement-period\x20rules','Acceptance\x20timeout\x20=\x20the\x20template\x27s\x20escrow_release_days\x20(single\x20source:\x20fee_params,\x20override\x20via\x20fee_overrides).\x20Mechanism:\x20dual-branch\x20time-gated\x20forward\x20(pattern.time_lock_progress\x20anchored\x20on\x20the\x20delivered\x20entry);\x20a\x20keeper\x20advances\x20the\x20timeout\x20path.\x20adminUnhold\x20(224)\x20is\x20ONLY\x20the\x20hold-release\x20escape\x20hatch,\x20never\x20the\x20timeout\x20mechanism.']},'applicable_conditions':{'business_scale':'small','min_daily_orders':0x1,'other_conditions':['Suitable\x20for\x20mid-to-long-term\x20project\x20delivery','Requires\x20milestone-based\x20phased\x20acceptance']},'similar_industries':['rental','education'],'novel_capabilities':['allocation.distribute_milestone'],'disabled_builtin_constraints':['require_compensation_fund']},{'name':'rental','display_name':'Rental','version':'v1','source':'builtin',...fetchTemplate('rental'),'analyze':{'key_questions':['Is\x20the\x20deposit\x20escrowed\x20on-chain\x20and\x20sized\x20against\x20the\x20item\x27s\x20full\x20replacement\x20value,\x20not\x20just\x20the\x20rental\x20fee?','Are\x20pre-handover\x20and\x20post-return\x20WIP\x20states\x20hash-recorded,\x20so\x20damage\x20attribution\x20is\x20provable\x20rather\x20than\x20asserted?']},'capabilities_used':['permission.index_create','permission.role_assign','guard.validate_buy','guard.validate_wip_hash','machine.node_topology','treasury.owner_receive','allocation.distribute','service.publish','progress.advance','arb.vote_weighted','contact.im_create'],'config_overrides':{'treasury':{'deposit_escrow':!![],'deposit_deductible':!![]},'machine':{'wip_required':!![],'wip_stages':['handover_out','returned'],'inspection_gate':!![]}},'expected_benefits':[{'metric':'Deposit\x20dispute\x20rate','expected_value':'-60%','evidence':'pre-rental\x20WIP\x20mandatorily\x20records\x20item\x27s\x20original\x20state'},{'metric':'Damage\x20liability\x20accuracy','expected_value':'+70%','evidence':'pre/post\x20WIP\x20hash\x20comparison\x20eliminates\x20unfounded\x20deductions'},{'metric':'Trust\x20score','expected_value':'+25%','evidence':'compensation_fund\x20covers\x20damage\x20risk'}],'risk_appetite':'conservative','risk_constraints':{'require_arbitration':!![],'require_compensation_fund':!![],'require_wip_evidence':!![],'max_single_transaction':0x2710,'compensation_fund_coverage_ratio':0xa,'other_constraints':['Deposit\x20must\x20be\x20escrowed\x20(no\x20direct\x20transfer)','lock_duration\x20>=\x207d\x20to\x20prevent\x20arbitrary\x20merchant\x20withdrawal']},'applicable_conditions':{'business_scale':'small','min_daily_orders':0x1,'other_conditions':['Requires\x20physical\x20item\x20handover','Has\x20logistics\x20or\x20offline\x20delivery\x20leg']},'similar_industries':['retail','travel'],'novel_capabilities':[]},{'name':'education','display_name':'Education','version':'v1','source':'builtin',...fetchTemplate('education'),'analyze':{'key_questions':['Does\x20tuition\x20release\x20per\x20attended\x20session\x20(Progress\x20node),\x20so\x20undelivered\x20sessions\x20stay\x20refundable\x20if\x20the\x20institution\x20disappears?','Does\x20setting_lock_duration\x20span\x20the\x20full\x20term,\x20so\x20the\x20institution\x20cannot\x20tighten\x20refund\x20rules\x20mid-course?']},'capabilities_used':['permission.index_create','permission.role_assign','guard.validate_buy','guard.validate_wip_hash','machine.node_topology','treasury.owner_receive','allocation.distribute','allocation.distribute_milestone','service.publish','progress.advance','arb.vote_weighted','contact.im_create'],'config_overrides':{'allocation':{'strategy':{'recipient':'entity','count':0x1,'mode':'amount','description':'1/N\x20of\x20tuition\x20released\x20per\x20session\x20attendance'},'session_threshold':!![]},'service':{'setting_lock_duration':'120d','anti_runaway':!![]}},'expected_benefits':[{'metric':'Refund\x20dispute\x20rate','expected_value':'-50%','evidence':'per-session\x20release\x20distributes\x20tuition\x20by\x20class'},{'metric':'Institution\x20runaway\x20risk','expected_value':'eliminated','evidence':'Funds\x20release\x20per\x20session;\x20undelivered\x20portion\x20is\x20refundable'},{'metric':'Attendance\x20traceability','expected_value':'100%','evidence':'attendance_guard\x20signs\x20each\x20session'}],'risk_appetite':'conservative','risk_constraints':{'require_arbitration':!![],'require_compensation_fund':!![],'require_wip_evidence':![],'other_constraints':['setting_lock_duration\x20covers\x20the\x20entire\x20term\x20(>=90d)','Long-cycle\x20projects\x20must\x20monitor\x20>90d\x20progress']},'applicable_conditions':{'business_scale':'medium','min_daily_orders':0x1,'other_conditions':['Long-cycle\x20delivery','Requires\x20per-session\x20acceptance','Regulatory\x20intensity:\x20medium']},'similar_industries':['freelance','subscription'],'novel_capabilities':['allocation.distribute_milestone'],'disabled_builtin_constraints':['require_wip_evidence']},{'name':'travel','display_name':'Travel','version':'v1','source':'builtin',...fetchTemplate('travel'),'analyze':{'key_questions':['Does\x20each\x20itinerary\x20segment\x20have\x20its\x20own\x20guard\x20and\x20WIP\x20acceptance,\x20so\x20one\x20failed\x20leg\x20is\x20refundable\x20without\x20unwinding\x20the\x20whole\x20trip?','Is\x20the\x20multi-tier\x20allocation\x20waterfall\x20(agency\x20→\x20hotel/guide/driver)\x20visible\x20on-chain,\x20so\x20the\x20agency\x20cannot\x20silently\x20re-split\x20funds?']},'capabilities_used':['permission.index_create','permission.role_assign','guard.validate_buy','guard.validate_wip_hash','machine.node_topology','treasury.owner_receive','allocation.distribute','service.publish','progress.advance','arb.vote_weighted','contact.im_create'],'config_overrides':{'allocation':{'strategy':{'recipient':'entity','count':0x3,'mode':'amount','description':'Deposit\x2020%\x20to\x20agency,\x20final\x2080%\x20to\x20agency,\x20then\x20agency-side\x20Allocation\x20splits\x20to\x20hotel/guide/driver\x20per\x20segment'},'multi_tier_waterfall':!![],'guard_chaining':!![]},'service':{'supply_chain_suborders':!![],'segment_guard_required':!![]}},'expected_benefits':[{'metric':'Fund\x20transparency','expected_value':'100%','evidence':'multi-tier\x20allocation\x20splits\x20per\x20segment\x20to\x20hotel/guide/driver'},{'metric':'Itinerary\x20change\x20disputes','expected_value':'-45%','evidence':'segment\x20WIP\x20accepts\x20each\x20leg'},{'metric':'Breach\x20compensation\x20assurance','expected_value':'+60%','evidence':'compensation_fund\x20covers\x20itinerary\x20breach'}],'risk_appetite':'balanced','risk_constraints':{'require_arbitration':!![],'require_compensation_fund':!![],'require_wip_evidence':!![],'other_constraints':['Multi-tier\x20allocation\x20requires\x20guard\x20chaining\x20validation','deposit\x2020%\x20+\x20final\x2080%\x20two-stage\x20payment']},'applicable_conditions':{'business_scale':'medium','min_daily_orders':0x1,'other_conditions':['Multi-segment\x20itinerary\x20combination','Requires\x20hotel/guide/driver\x20multi-party\x20allocation']},'similar_industries':['rental','education'],'novel_capabilities':[]},{'name':'subscription','display_name':'Subscription','version':'v1','source':'builtin',...fetchTemplate('subscription'),'analyze':{'key_questions':['Is\x20every\x20periodic\x20charge\x20gated\x20by\x20an\x20explicit\x20user\x20confirmation,\x20with\x20no\x20auto-renew\x20default?','Can\x20the\x20subscriber\x20cancel\x20anytime\x20effective\x20next\x20period,\x20without\x20a\x20dead-end\x20node\x20in\x20the\x20machine?']},'capabilities_used':['permission.index_create','permission.role_assign','guard.validate_buy','machine.node_topology','treasury.owner_receive','allocation.distribute','service.publish','progress.advance','arb.vote_weighted','reward.claim_guard','contact.im_create'],'config_overrides':{'machine':{'no_auto_renew_trap':!![],'user_confirmed_charge':!![],'cancel_anytime':!![],'next_period_effective':!![]},'service':{'creator_data_subscription':!![],'periodic_billing':!![]}},'expected_benefits':[{'metric':'Renewal\x20rate','expected_value':'+25%','evidence':'loyalty\x20reward\x20+\x20transparent\x20subscription\x20mechanism'},{'metric':'Cancellation\x20disputes','expected_value':'eliminated','evidence':'cancel\x20anytime\x20+\x20no\x20auto-renew\x20trap'},{'metric':'Creator\x20retention','expected_value':'+30%','evidence':'deliver_guard_wip\x20prevents\x20content\x20dropout'}],'risk_appetite':'aggressive','risk_constraints':{'require_arbitration':![],'require_compensation_fund':![],'require_wip_evidence':![],'compensation_fund_coverage_ratio':0x3,'other_constraints':['Forbid\x20dead-end\x20nodes\x20(prevent\x20lock-in)','charge_guard\x20requires\x20user\x20confirmation\x20each\x20period']},'applicable_conditions':{'business_scale':'small','min_daily_orders':0x5,'other_conditions':['Pure-digital\x20delivery','Periodic\x20content\x20or\x20SaaS\x20service']},'similar_industries':['freelance','education'],'novel_capabilities':[],'disabled_builtin_constraints':['require_arbitration','require_compensation_fund','require_wip_evidence']},{'name':'retail','display_name':'Retail','version':'v1','source':'builtin',...fetchTemplate('retail'),'analyze':{'key_questions':['Is\x20the\x20logistics\x20tracking\x20number\x20recorded\x20as\x20WIP\x20before\x20the\x20confirm\x20gate,\x20so\x20receipt\x20disputes\x20have\x20carrier\x20evidence?','Is\x20the\x20refund\x20window\x20at\x20least\x207\x20days\x20with\x20an\x20on-chain\x20refund\x20path\x20that\x20does\x20not\x20rely\x20on\x20merchant\x20goodwill?']},'capabilities_used':['permission.index_create','permission.role_assign','guard.validate_buy','guard.validate_wip_hash','machine.node_topology','treasury.owner_receive','allocation.distribute','service.publish','progress.advance','arb.vote_weighted','reward.claim_guard','contact.im_create'],'config_overrides':{'machine':{'wip_required':!![],'wip_field':'tracking_number','confirm_gate':!![],'refund_requires_approval':!![]},'service':{'first_order_discount':!![]}},'expected_benefits':[{'metric':'Return\x20dispute\x20rate','expected_value':'-35%','evidence':'logistics\x20WIP\x20+\x20refund\x20path\x20assurance'},{'metric':'Repurchase\x20rate','expected_value':'+20%','evidence':'spend\x20cashback\x20reward'},{'metric':'Product\x20authenticity\x20traceability','expected_value':'100%','evidence':'WIP\x20verifies\x20product/logistics\x20info'}],'risk_appetite':'conservative','risk_constraints':{'require_arbitration':!![],'require_compensation_fund':!![],'require_wip_evidence':![],'compensation_fund_coverage_ratio':0x5,'other_constraints':['refund_window\x20>=\x207d','confirm_gate:\x20only\x20buyer\x20can\x20confirm\x20receipt']},'applicable_conditions':{'business_scale':'medium','min_daily_orders':0xa,'other_conditions':['Has\x20logistics\x20shipping\x20leg','High-frequency\x20small-ticket\x20transactions']},'similar_industries':['rental','subscription'],'novel_capabilities':[],'disabled_builtin_constraints':['require_wip_evidence']},{'name':'retail_d2c','display_name':'Retail\x20D2C\x20(Direct-to-Consumer)','version':'v1','source':'builtin',...fetchTemplate('retail_d2c'),'analyze':{'key_questions':['Do\x20withdraw_guard\x20and\x20refund_guard\x20fully\x20enclose\x20the\x20Allocation\x20escrow,\x20so\x20neither\x20side\x20can\x20move\x20funds\x20outside\x20the\x20contract\x20path?','With\x20no\x20platform\x20arbitration,\x20what\x20off-chain\x20recourse\x20(if\x20any)\x20backs\x20a\x20delivery\x20failure\x20—\x20and\x20is\x20that\x20acceptable\x20for\x20the\x20ticket\x20size?']},'capabilities_used':['permission.index_create','permission.role_assign','guard.validate_withdraw','guard.validate_refund','machine.node_topology','allocation.distribute','service.publish','progress.advance','contact.im_create'],'config_overrides':{'machine':{'wip_required':![],'confirm_gate':!![],'refund_requires_approval':![]},'service':{'multi_recipient_allocation':!![]}},'expected_benefits':[{'metric':'Merchant\x20revenue\x20share','expected_value':'97%','evidence':'No\x20platform\x20commission\x20—\x20only\x203%\x20processing\x20fee'},{'metric':'Fund\x20safety','expected_value':'contract-grade','evidence':'Allocation\x20escrow\x20+\x20Guard\x20verification\x20replaces\x20platform\x20custody'},{'metric':'Delivery\x20reliability','expected_value':'high','evidence':'withdraw_guard\x20enforces\x20delivery\x20confirmation\x20before\x20payment'}],'risk_appetite':'balanced','risk_constraints':{'require_arbitration':![],'require_compensation_fund':![],'require_wip_evidence':![],'other_constraints':['Allocation\x20escrow\x20required\x20(withdraw_guard\x20+\x20refund_guard)','Service\x20↔\x20Guard\x20circular\x20dependency\x20requires\x203-step\x20creation\x20pattern']},'applicable_conditions':{'business_scale':'small','min_daily_orders':0x1,'other_conditions':['Independent\x20storefront\x20(no\x20marketplace)','Merchant-managed\x20logistics','Allocation\x20escrow\x20model']},'similar_industries':['retail','subscription'],'novel_capabilities':['Allocation\x20escrow\x20as\x20platform-custody\x20alternative','Multi-recipient\x20allocation\x20(merchant\x20+\x20processor)'],'disabled_builtin_constraints':['require_arbitration','require_compensation_fund','require_wip_evidence']},{'name':'licensing','display_name':'Licensing','version':'v1','source':'builtin',...fetchTemplate('licensing'),'analyze':{'key_questions':['Is\x20the\x20license\x20grant\x20(terms\x20+\x20asset/certificate\x20hash)\x20anchored\x20as\x20a\x20WIP\x20artifact\x20and\x20an\x20evidence\x20Repository\x20row\x20BEFORE\x20release,\x20so\x20a\x20misrepresentation\x20dispute\x20has\x20an\x20on-chain\x20artifact\x20to\x20read?','Does\x20the\x20release\x20split\x20sum\x20to\x20exactly\x2010000\x20bps\x20across\x20explicit\x20NON-EMPTY\x20rights-holder\x20Entities\x20(no\x20empty\x20Entity\x20routing\x20the\x20share\x20to\x20the\x20deployer,\x20no\x20Surplus\x20draining\x20the\x20pool)?','Are\x20the\x20chain\x20GAPs\x20disclosed\x20honestly\x20—\x20the\x20auction\x20resolved\x20OFF-chain\x20(no\x20bid\x20ledger)\x20and\x20usage\x20caps\x20enforced\x20as\x20attested-counter\x20arbitration\x20evidence\x20(no\x20metering\x20oracle),\x20never\x20as\x20chain-enforced\x20limits?']},'capabilities_used':['permission.index_create','permission.role_assign','guard.validate_buy','guard.validate_wip_hash','machine.node_topology','treasury.owner_receive','allocation.distribute','service.publish','progress.advance','arb.vote_weighted','contact.im_create'],'config_overrides':{'machine':{'wip_required':!![],'confirm_gate':!![],'refund_requires_approval':!![]},'service':{'multi_recipient_allocation':!![]}},'expected_benefits':[{'metric':'Royalty-split\x20transparency','expected_value':'100%','evidence':'every\x20rights-holder\x20share\x20is\x20an\x20on-chain\x20Rate\x20leg\x20the\x20buyer\x20can\x20audit\x20before\x20ordering'},{'metric':'Misrepresentation\x20dispute\x20rate','expected_value':'-40%','evidence':'inspection-window\x20escrow\x20+\x20grant-artifact\x20WIP\x20anchor\x20the\x20terms\x20before\x20release'},{'metric':'Settlement\x20latency','expected_value':'seconds','evidence':'release\x20fires\x20on\x20buyer\x20accept\x20/\x20time-lock,\x20not\x20a\x20calendar\x20freeze'}],'risk_appetite':'conservative','risk_constraints':{'require_arbitration':!![],'require_compensation_fund':!![],'require_wip_evidence':!![],'other_constraints':['release\x20split\x20Rate\x20legs\x20sum\x20exactly\x2010000\x20(ERATE_NOT_10000);\x20every\x20recipient\x20an\x20explicit\x20NON-EMPTY\x20Entity','inspection/delivery\x20window\x20>=\x203d\x20so\x20the\x20buyer\x20can\x20verify\x20the\x20grant\x20before\x20auto-accept','🔴\x20auction\x20resolved\x20OFF-chain\x20(no\x20bid\x20ledger)\x20and\x20usage\x20caps\x20attested\x20(no\x20oracle)\x20—\x20disclosed,\x20never\x20chain-enforced']},'applicable_conditions':{'business_scale':'small','min_daily_orders':0x1,'other_conditions':['Pure-digital\x20grant\x20(no\x20logistics\x20leg)','Rights-holder\x20/\x20producer\x20/\x20publisher\x20owns\x20the\x20IP','Long-lived\x20value\x20(a\x20royalty\x20share\x20or\x20a\x20license\x20term)']},'similar_industries':['subscription','freelance'],'novel_capabilities':['Multi-recipient\x20royalty\x20split\x20(Allocation\x20Rate\x20plan)','Territory/qualification\x20allowlist\x20buy\x20gate','Inspection-window\x20escrow\x20before\x20release']},{'name':'crowdfunding','display_name':'Crowdfunding','version':'v1','source':'builtin',...fetchTemplate('crowdfunding'),'analyze':{'key_questions':['Is\x20each\x20contribution\x20escrowed\x20to\x20the\x20funder\x27s\x20OWN\x20Order\x20(for_object)\x20and\x20NEVER\x20pooled\x20via\x20balance::join,\x20so\x20per-backer\x20attribution\x20survives\x20settlement\x20or\x20refund?','Does\x20the\x20threshold\x20gate\x20read\x20a\x20WRITER-BOUND\x20Repository\x20numeric\x20row\x20(id_from\x20signer,\x20value\x20=\x20amount)\x20summed\x20via\x20the\x20sum-where\x20query,\x20ANDed\x20with\x20an\x20ABSOLUTE\x20shared\x20campaign\x20deadline\x20—\x20so\x20a\x20funder\x20cannot\x20inflate\x20the\x20total\x20and\x20every\x20backer\x20sees\x20the\x20same\x20cutoff?','Is\x20the\x20aggregate\x20total\x20disclosed\x20honestly\x20as\x20a\x20keeper-attested\x20Repository\x20sum\x20(arbitration\x20evidence,\x20NOT\x20a\x20chain-verified\x20money\x20oracle),\x20and\x20is\x20the\x20escrow-exit\x20two-leg\x20polarity\x20exact\x20(refund\x20claimed_by\x20some==false\x20XOR\x20recover_gate\x20claimed_by\x20some==true,\x20D-BUG-2)?']},'capabilities_used':['permission.index_create','permission.role_assign','guard.validate_buy','guard.validate_wip_hash','machine.node_topology','treasury.owner_receive','allocation.distribute','service.publish','progress.advance','arb.vote_weighted','contact.im_create'],'config_overrides':{'machine':{'wip_required':!![],'confirm_gate':!![],'refund_requires_approval':![]},'service':{'multi_recipient_allocation':!![]}},'expected_benefits':[{'metric':'Backer\x20attribution','expected_value':'100%','evidence':'each\x20contribution\x20is\x20a\x20for_object-bound\x20Allocation\x20on\x20the\x20funder\x27s\x20own\x20Order\x20—\x20never\x20pooled'},{'metric':'Unmet-threshold\x20refund','expected_value':'automatic','evidence':'the\x20sum-where\x20<\x20goal\x20leg\x20fires\x20the\x20refund\x20exit\x20with\x20no\x20merchant\x20approval\x20(D-BUG-2\x20polarity)'},{'metric':'Campaign\x20deadline\x20drift','expected_value':'0','evidence':'one\x20ABSOLUTE\x20Clock\x20timestamp\x20shared\x20by\x20every\x20funder,\x20not\x20per-order\x20entry+duration'}],'risk_appetite':'conservative','risk_constraints':{'require_arbitration':!![],'require_compensation_fund':!![],'require_wip_evidence':!![],'other_constraints':['per-contributor\x20Allocation\x20for_object\x20=\x20own\x20Order;\x20NEVER\x20balance::join\x20(attribution\x20survives)','threshold\x20gate\x20=\x20repository.data\x20sum-where\x20(1174)\x20over\x20WRITER-BOUND\x20rows\x20ANDed\x20with\x20an\x20ABSOLUTE\x20deadline','🔴\x20the\x20aggregate\x20total\x20is\x20a\x20keeper-attested\x20Repository\x20sum\x20(arbitration\x20evidence),\x20NOT\x20a\x20chain-verified\x20money\x20oracle\x20—\x20disclosed','🔴\x20L-01\x20never\x20promises\x20investment\x20returns\x20or\x20promotes\x20coin\x20price;\x20L-05\x20KYC/AML\x20+\x20cross-border\x20caution\x20(HIGH\x20regulatory\x20intensity)']},'applicable_conditions':{'business_scale':'small','min_daily_orders':0x1,'other_conditions':['Aggregate\x20funding\x20goal\x20with\x20a\x20fixed\x20campaign\x20deadline','Per-backer\x20reward\x20tiers\x20or\x20donation\x20(no\x20logistics\x20leg\x20required)','All-or-nothing\x20(refund\x20if\x20unmet)\x20or\x20keep-it-all\x20(no\x20refund)\x20campaign\x20shape']},'similar_industries':['retail','licensing'],'novel_capabilities':['Aggregate-goal\x20threshold\x20gate\x20via\x20writer-bound\x20Repository\x20sum-where','Per-contributor\x20for_object\x20escrow\x20(attribution-preserving,\x20never\x20pooled)','Absolute\x20shared\x20campaign\x20deadline\x20+\x20two-leg\x20escrow-exit\x20(release\x20XOR\x20refund)']},{'name':'delivery','display_name':'Local\x20Delivery','version':'v1','source':'builtin',...fetchTemplate('delivery'),'analyze':{'key_questions':['Who\x20writes\x20the\x20rider\x20roster\x20(permission\x20221)\x20—\x20is\x20that\x20admission\x20power\x20disclosed,\x20and\x20is\x20the\x20roster\x20budget\x20(60\x20rosters\x20/\x2080\x20addresses\x20per\x20Progress)\x20respected?','Does\x20settlement\x20depart\x20a\x20SERIAL\x20claim\x20window\x20(TPL-09)\x20with\x20settle_hours\x20>=\x20claim_window_hours,\x20so\x20no\x20payout\x20can\x20race\x20an\x20open\x20dispute\x20(FACT-ALLOC-03)?','Are\x20handover\x20records\x20(ready/pickup/deliver)\x20writer-bound\x20repository\x20rows,\x20and\x20is\x20the\x20buyer-facing\x20copy\x20honest\x20that\x20dispatch,\x20ETA\x20and\x20rider\x20pay\x20are\x20OFF-CHAIN?']},'capabilities_used':['permission.index_create','permission.role_assign','guard.validate_buy','guard.validate_wip_hash','machine.node_topology','treasury.owner_receive','allocation.distribute','service.publish','progress.advance','progress.named_operator','arb.vote_weighted','contact.im_create'],'config_overrides':{'machine':{'wip_required':!![],'confirm_gate':!![],'refund_requires_approval':![]},'service':{'multi_recipient_allocation':!![]}},'expected_benefits':[{'metric':'Silent-buyer\x20stranding','expected_value':'0','evidence':'buyer-first\x20confirmation\x20+\x20keeper\x20auto-confirm\x20within\x20auto_confirm_hours\x20(T-04)'},{'metric':'Payout/claim\x20race','expected_value':'unreachable','evidence':'the\x20serial\x20claim\x20window\x20makes\x20settlement\x20depart\x20only\x20after\x20filing\x20closes\x20(TPL-09)'},{'metric':'Rider\x20money-surface','expected_value':'0\x20legs','evidence':'the\x20escrow\x20can\x20never\x20pay\x20a\x20per-order\x20rider\x20(for_object\x20lock);\x20payroll\x20is\x20the\x20platform\x27s\x20off-chain\x20duty'}],'risk_appetite':'balanced','risk_constraints':{'require_arbitration':!![],'require_compensation_fund':![],'require_wip_evidence':!![],'other_constraints':['rider\x20roster\x20=\x20rider-admission\x20power;\x20disclose\x20the\x20roster\x20writer\x20(NAMED_OPERATOR_ROSTER_UNDISCLOSED)','settle_hours\x20>=\x20claim_window_hours\x20asserted\x20at\x20generation\x20(serial\x20window\x20math)','🔴\x20rider\x20pay\x20is\x20OFF-CHAIN\x20platform\x20payroll\x20—\x20never\x20model\x20a\x20per-order\x20rider\x20payout\x20leg','🔴\x20no\x20ETA/distance\x20oracle\x20—\x20pricing\x20and\x20delivery\x20estimates\x20are\x20not\x20chain-verifiable']},'applicable_conditions':{'business_scale':'small','min_daily_orders':0x1,'other_conditions':['Local\x20fulfillment\x20within\x20minutes-hours\x20windows\x20(perishable\x20or\x20time-boxed)','Per-order\x20dispatched\x20fulfillers\x20(no\x20fixed\x20staff\x20roster)','Fee-graded\x20cancellation\x20(free\x20pre-acceptance,\x20fee\x20post-acceptance)']},'similar_industries':['retail','group_buy'],'novel_capabilities':['Named-operator\x20roster\x20rail\x20for\x20per-order\x20dispatched\x20riders\x20(K-1)','Serial\x20claim\x20window\x20on\x20hours-scale\x20timing\x20(TPL-09)','Fee-graded\x20cancel\x20taxonomy\x20with\x20a\x20dedicated\x20kill\x20terminal']},{'name':'group_buy','display_name':'Community\x20Group-Buy','version':'v1','source':'builtin',...fetchTemplate('group_buy'),'analyze':{'key_questions':['Is\x20the\x20batch\x20cutoff\x20ONE\x20shared\x20absolute\x20timestamp\x20(keeper-written\x20Repository\x20row\x20+\x20time_source\x20oracle),\x20not\x20a\x20per-order\x20entry+duration\x20lock?','Does\x20the\x20leader\x20template\x20fix\x20the\x20supplier\x27s\x20sub-service\x20address\x20in\x20the\x20ConsolidateBatch\x20guard\x20table\x20(b_submission\x20false,\x20Address)\x20so\x20the\x20procurement\x20graph\x20is\x20diligence-able\x20before\x20any\x20buyer\x20pays?','In\x20threshold\x20mode,\x20are\x20contribution\x20rows\x20ORDER-keyed\x20with\x20the\x20escrow-bound\x20aggregate\x20(per-row\x20min(row,\x20order.amount))\x20and\x20the\x20live-escrow\x20+\x20claimed_by-false\x20legs\x20—\x20the\x20three\x20CROWDFUNDING_*\x20blockers\x20armed?']},'capabilities_used':['permission.index_create','permission.role_assign','guard.validate_buy','guard.validate_wip_hash','machine.node_topology','treasury.owner_receive','allocation.distribute','service.publish','progress.advance','progress.named_operator','repository.data_write','arb.vote_weighted','contact.im_create'],'config_overrides':{'machine':{'wip_required':!![],'confirm_gate':!![],'refund_requires_approval':![]},'service':{'multi_recipient_allocation':!![]}},'expected_benefits':[{'metric':'Cutoff\x20fairness','expected_value':'1\x20clock','evidence':'one\x20absolute\x20shared\x20cutoff\x20per\x20batch\x20(time_lock_absolute),\x20never\x20per-order\x20entry+duration'},{'metric':'Unformed-batch\x20refund','expected_value':'automatic','evidence':'ThresholdMissed\x20/\x20AbandonTimeout\x20rails\x20refund\x20per-order\x20with\x20no\x20merchant\x20grace'},{'metric':'Procurement\x20diligence','expected_value':'pre-order','evidence':'the\x20supplier\x20sub-service\x20address\x20is\x20a\x20fixed\x20guard-table\x20promise\x20(leader\x20shape)'}],'risk_appetite':'conservative','risk_constraints':{'require_arbitration':!![],'require_compensation_fund':!![],'require_wip_evidence':!![],'other_constraints':['batch\x20cutoff\x20=\x20shared\x20ABSOLUTE\x20timestamp\x20via\x20pattern.time_lock_absolute\x20+\x20time_source_repository_oracle','threshold\x20mode\x20reuses\x20the\x20crowdfunding\x20construction\x20(ORDER-keyed\x20rows,\x20escrow-bound\x20aggregate,\x20CROWDFUNDING_*\x20blockers)','🔴\x20multi-level\x20commission\x20is\x20NOT\x20expressible\x20—\x20single-layer\x20rate\x20leg\x20to\x20the\x20platform\x20Entity\x20with\x20off-chain\x20pass-through,\x20disclosed','🔴\x20delay\x20compensation\x20pays\x20from\x20compensation_fund,\x20NEVER\x20the\x20buyer\x20escrow\x20(Order\x20binds\x20<=\x201\x20allocator);\x20fund\x20pre-locked\x203x\x20(B2)']},'applicable_conditions':{'business_scale':'small','min_daily_orders':0x1,'other_conditions':['Neighborhood\x20batch\x20buying\x20with\x20a\x20daily/periodic\x20cutoff','Pickup-point\x20fulfillment\x20(staffed\x20point\x20or\x20automated\x20locker)','Leader\x20consolidation\x20ahead\x20of\x20a\x20supplier\x20sub-order']},'similar_industries':['crowdfunding','delivery'],'novel_capabilities':['Shared\x20absolute\x20batch\x20cutoff\x20via\x20keeper-written\x20Repository\x20row\x20+\x20time-source\x20oracle','Supply-chain\x20suborder\x20commitment\x20in\x20the\x20guard\x20table\x20(pre-order\x20diligence)','point_type-conditional\x20pickup\x20topology\x20(staffed\x20leader\x20rail\x20vs\x20automated\x20locker)']},{'name':'general','display_name':'General','version':'v1','source':'builtin',...fetchTemplate('general'),'analyze':{'key_questions':['Which\x20trust\x20mechanisms\x20(arbitration,\x20compensation\x20fund,\x20WIP\x20evidence)\x20are\x20missing\x20here,\x20and\x20what\x20does\x20each\x20absence\x20cost\x20in\x20the\x20worst\x20case?','What\x20is\x20the\x20single\x20point\x20of\x20failure\x20—\x20who\x20can\x20unilaterally\x20take\x20funds\x20or\x20stall\x20the\x20workflow?']},'capabilities_used':['permission.index_create','machine.node_topology','treasury.owner_receive','allocation.distribute','service.publish','progress.advance'],'expected_benefits':[{'metric':'Flexibility','expected_value':'100%','evidence':'User\x20customizes\x20all\x20trust\x20mechanism\x20parameters'},{'metric':'Degraded\x20safety','expected_value':'usable','evidence':'Can\x20fall\x20back\x20to\x20general\x20at\x20any\x20time'}],'risk_appetite':'balanced','risk_constraints':{'require_arbitration':![],'require_compensation_fund':![],'require_wip_evidence':![]},'applicable_conditions':{'business_scale':'small','other_conditions':['Fallback\x20degraded\x20mode','Hybrid\x20scenarios\x20not\x20covered\x20by\x20other\x20industries']},'similar_industries':[],'novel_capabilities':[],'disabled_builtin_constraints':['require_arbitration','require_compensation_fund','require_wip_evidence']}];
1
+ import{getScenarioMode}from'../knowledge/scenario-modes.js';import{BUILTIN_TEMPLATES}from'../knowledge/builtin-templates.js';import{getIndustryTraits}from'../knowledge/industry-registry.js';import{getIndustryRiskChecks,getIndustryNeeds}from'../customer/index.js';import{SUPPORTED_INDUSTRIES}from'../customer/user-preferences.js';import{getFlywheelForIndustry}from'../knowledge/acquisition-flywheel.js';const GENERAL_TRAITS={'has_logistics':![],'communication_heavy':![],'pure_digital':![],'long_cycle':![],'deposit_required':![],'multi_tier_allocation':![],'regulatory_intensity':'low','trust_sensitivity':'medium','consumption_frequency':'occasional','avg_ticket_size':'medium'},GENERAL_FLYWHEEL={'industry':'general','trustSellingPoints':[],'keyActions':[],'rewardStrategy':'User-defined','discountStrategy':'User-defined','trustDescription':'User-defined\x20trust\x20mechanism'},GENERAL_MACHINE_SHAPE=[{'name':'paid','role':'Entry:\x20order\x20created\x20and\x20paid'},{'name':'delivering','role':'Service\x20delivery\x20in\x20progress'},{'name':'delivered','role':'Deliverable\x20available\x20for\x20review'},{'name':'completed','role':'Service\x20completed,\x20funds\x20released'},{'name':'cancelled','role':'Pre-delivery\x20cancellation\x20—\x20triggers\x20refund\x20Allocator','operator':'order_payer'}],GENERAL_ALLOCATOR={'recipient':'signer','count':0x1,'mode':'surplus','description':'Default:\x20surplus\x20to\x20service\x20owner\x20(general\x20fallback)'},RETAIL_D2C_MACHINE_SHAPE=[{'name':'ordered','role':'Entry:\x20order\x20created\x20(funds\x20escrowed\x20in\x20Allocation)'},{'name':'shipped','role':'Merchant\x20ships\x20goods'},{'name':'delivered','role':'Goods\x20delivered\x20to\x20buyer'},{'name':'completed','role':'Buyer\x20confirms\x20receipt\x20—\x20withdraw_guard\x20releases\x20funds','operator':'order_payer'},{'name':'cancelled','role':'Pre-ship\x20cancellation\x20—\x20refund_guard\x20refunds\x20buyer','operator':'order_payer'}],RETAIL_D2C_GUARDS=[{'template_id':'withdraw_guard_delivery','host':'service','purpose':'Release\x20funds\x20to\x20merchant\x20+\x20processor\x20on\x20order\x20completion\x20(delivery\x20confirmation)'},{'template_id':'refund_guard_cancellation','host':'service','purpose':'Refund\x20100%\x20to\x20buyer\x20on\x20order\x20cancellation'}],RETAIL_D2C_ALLOCATOR={'recipient':'entity','count':0x2,'mode':'rate','description':'Merchant\x2097%\x20+\x20Processor\x203%\x20(rate-based\x20split,\x20no\x20platform\x20commission)'},RETAIL_D2C_KEY_RISK='No\x20platform\x20arbitration\x20—\x20disputes\x20rely\x20on\x20optional\x20Arbitration\x20or\x20off-chain\x20chargeback',RETAIL_D2C_BUILD_NOTES=['Allocation\x20escrow\x20replaces\x20platform\x20custody\x20—\x20funds\x20locked\x20in\x20contract\x20until\x20Guard\x20releases','withdraw_guard\x20enforces\x20delivery\x20gate\x20—\x20merchant\x20must\x20reach\x20\x27completed\x27\x20state\x20to\x20receive\x20payment','refund_guard\x20ensures\x20100%\x20refund\x20on\x20cancellation\x20—\x20no\x20merchant\x20approval\x20needed','No\x20buy_guard\x20needed\x20—\x20D2C\x20doesn\x27t\x20gate\x20purchases\x20(open\x20storefront)','Arbitration\x20is\x20optional\x20—\x20add\x20when\x20dispute\x20volume\x20justifies\x20the\x20cost','Service\x20↔\x20Guard\x20circular\x20dependency:\x20create\x20Service\x20(unpublished)\x20→\x20create\x20Guards\x20→\x20update\x20Service\x20(publish)'],SUPPORTED_INDUSTRY_SET=new Set([...SUPPORTED_INDUSTRIES,'retail_d2c']);function fetchTemplate(a){const b=a==='retail_d2c'?'retail':a,c=getIndustryTraits(b)??GENERAL_TRAITS,d=SUPPORTED_INDUSTRY_SET['has'](a),e=a==='retail_d2c'?'retail':a,f=d?getIndustryRiskChecks(e):[],g=d?getIndustryNeeds(e):[],h=getFlywheelForIndustry(b)??GENERAL_FLYWHEEL;let i,j,k,l,m;if(a==='retail_d2c')i=RETAIL_D2C_MACHINE_SHAPE,j=RETAIL_D2C_GUARDS,k=RETAIL_D2C_ALLOCATOR,l=RETAIL_D2C_KEY_RISK,m=RETAIL_D2C_BUILD_NOTES;else{if(a==='general'){const n=getScenarioMode('general');i=GENERAL_MACHINE_SHAPE,j=[],k=GENERAL_ALLOCATOR,l=n?.['key_risk']??'No\x20safety\x20net\x20—\x20user\x20must\x20design\x20all\x20trust\x20mechanisms\x20manually',m=n?.['build_notes'];}else{const o=getScenarioMode(a);if(!o)throw new Error('No\x20scenario\x20mode\x20found\x20for\x20industry:\x20'+a);const p=BUILTIN_TEMPLATES['find'](q=>q['id']===o['default_template']);if(!p)throw new Error('Mode\x20\x27'+a+'\x27\x20default_template\x20\x27'+o['default_template']+'\x27\x20is\x20not\x20in\x20the\x20builtin\x20template\x20catalog');i=p['machine_shape'],j=p['guards'],k=p['allocator'],l=o['key_risk'],m=o['build_notes'];}}return{'traits':c,'risk_checks':f,'needs':g,'flywheel':h,'machine_shape':i,'guards':j,'allocator':k,'key_risk':l,'build_notes':m};}export const BUILTIN_MODES=[{'name':'freelance','display_name':'Freelance','version':'v1','source':'builtin',...fetchTemplate('freelance'),'analyze':{'key_questions':['Are\x20WIP\x20hashes\x20bound\x20to\x20each\x20milestone,\x20so\x20delivery\x20evidence\x20cannot\x20be\x20substituted\x20after\x20acceptance?','Does\x20the\x20acceptance\x20gate\x20have\x20a\x20time-bounded\x20escape\x20(keeper-driven\x20auto-accept),\x20or\x20can\x20a\x20silent\x20buyer\x20hold\x20the\x20provider\x27s\x20funds\x20hostage\x20indefinitely?']},'capabilities_used':['permission.index_create','permission.role_assign','guard.validate_buy','guard.validate_wip_hash','machine.node_topology','treasury.owner_receive','allocation.distribute','allocation.distribute_milestone','service.publish','progress.advance','arb.vote_weighted','contact.im_create'],'config_overrides':{'service':{'setting_lock_duration':'30d','engagement_type':'milestone'},'machine':{'wip_required':!![],'wip_hash_algorithm':'sha256','acceptance_gate':!![]}},'expected_benefits':[{'metric':'Dispute\x20rate\x20reduction','expected_value':'40%','evidence':'WIP\x20hash\x20+\x20milestone\x20allocation\x20enforces\x20delivery\x20evidence'},{'metric':'Delivery\x20confirmation\x20efficiency','expected_value':'+50%','evidence':'acceptance\x20gate\x20automates\x20acceptance\x20workflow'},{'metric':'Provider\x20payment\x20assurance','expected_value':'100%','evidence':'Funds\x20auto-release\x20to\x20provider\x20after\x20accepted\x20node'}],'risk_appetite':'balanced','risk_constraints':{'require_arbitration':!![],'require_compensation_fund':![],'require_wip_evidence':!![],'other_constraints':['setting_lock_duration\x20>=\x207d\x20to\x20lock\x20engagement-period\x20rules','Acceptance\x20timeout\x20=\x20the\x20template\x27s\x20escrow_release_days\x20(single\x20source:\x20fee_params,\x20override\x20via\x20fee_overrides).\x20Mechanism:\x20dual-branch\x20time-gated\x20forward\x20(pattern.time_lock_progress\x20anchored\x20on\x20the\x20delivered\x20entry);\x20a\x20keeper\x20advances\x20the\x20timeout\x20path.\x20adminUnhold\x20(224)\x20is\x20ONLY\x20the\x20hold-release\x20escape\x20hatch,\x20never\x20the\x20timeout\x20mechanism.']},'applicable_conditions':{'business_scale':'small','min_daily_orders':0x1,'other_conditions':['Suitable\x20for\x20mid-to-long-term\x20project\x20delivery','Requires\x20milestone-based\x20phased\x20acceptance']},'similar_industries':['rental','education'],'novel_capabilities':['allocation.distribute_milestone'],'disabled_builtin_constraints':['require_compensation_fund']},{'name':'rental','display_name':'Rental','version':'v1','source':'builtin',...fetchTemplate('rental'),'analyze':{'key_questions':['Is\x20the\x20deposit\x20escrowed\x20on-chain\x20and\x20sized\x20against\x20the\x20item\x27s\x20full\x20replacement\x20value,\x20not\x20just\x20the\x20rental\x20fee?','Are\x20pre-handover\x20and\x20post-return\x20WIP\x20states\x20hash-recorded,\x20so\x20damage\x20attribution\x20is\x20provable\x20rather\x20than\x20asserted?']},'capabilities_used':['permission.index_create','permission.role_assign','guard.validate_buy','guard.validate_wip_hash','machine.node_topology','treasury.owner_receive','allocation.distribute','service.publish','progress.advance','arb.vote_weighted','contact.im_create'],'config_overrides':{'treasury':{'deposit_escrow':!![],'deposit_deductible':!![]},'machine':{'wip_required':!![],'wip_stages':['handover_out','returned'],'inspection_gate':!![]}},'expected_benefits':[{'metric':'Deposit\x20dispute\x20rate','expected_value':'-60%','evidence':'pre-rental\x20WIP\x20mandatorily\x20records\x20item\x27s\x20original\x20state'},{'metric':'Damage\x20liability\x20accuracy','expected_value':'+70%','evidence':'pre/post\x20WIP\x20hash\x20comparison\x20eliminates\x20unfounded\x20deductions'},{'metric':'Trust\x20score','expected_value':'+25%','evidence':'compensation_fund\x20covers\x20damage\x20risk'}],'risk_appetite':'conservative','risk_constraints':{'require_arbitration':!![],'require_compensation_fund':!![],'require_wip_evidence':!![],'max_single_transaction':0x2710,'compensation_fund_coverage_ratio':0xa,'other_constraints':['Deposit\x20must\x20be\x20escrowed\x20(no\x20direct\x20transfer)','lock_duration\x20>=\x207d\x20to\x20prevent\x20arbitrary\x20merchant\x20withdrawal']},'applicable_conditions':{'business_scale':'small','min_daily_orders':0x1,'other_conditions':['Requires\x20physical\x20item\x20handover','Has\x20logistics\x20or\x20offline\x20delivery\x20leg']},'similar_industries':['retail','travel'],'novel_capabilities':[]},{'name':'education','display_name':'Education','version':'v1','source':'builtin',...fetchTemplate('education'),'analyze':{'key_questions':['Does\x20tuition\x20release\x20per\x20attended\x20session\x20(Progress\x20node),\x20so\x20undelivered\x20sessions\x20stay\x20refundable\x20if\x20the\x20institution\x20disappears?','Does\x20setting_lock_duration\x20span\x20the\x20full\x20term,\x20so\x20the\x20institution\x20cannot\x20tighten\x20refund\x20rules\x20mid-course?']},'capabilities_used':['permission.index_create','permission.role_assign','guard.validate_buy','guard.validate_wip_hash','machine.node_topology','treasury.owner_receive','allocation.distribute','allocation.distribute_milestone','service.publish','progress.advance','arb.vote_weighted','contact.im_create'],'config_overrides':{'allocation':{'strategy':{'recipient':'entity','count':0x1,'mode':'amount','description':'1/N\x20of\x20tuition\x20released\x20per\x20session\x20attendance'},'session_threshold':!![]},'service':{'setting_lock_duration':'120d','anti_runaway':!![]}},'expected_benefits':[{'metric':'Refund\x20dispute\x20rate','expected_value':'-50%','evidence':'per-session\x20release\x20distributes\x20tuition\x20by\x20class'},{'metric':'Institution\x20runaway\x20risk','expected_value':'eliminated','evidence':'Funds\x20release\x20per\x20session;\x20undelivered\x20portion\x20is\x20refundable'},{'metric':'Attendance\x20traceability','expected_value':'100%','evidence':'attendance_guard\x20signs\x20each\x20session'}],'risk_appetite':'conservative','risk_constraints':{'require_arbitration':!![],'require_compensation_fund':!![],'require_wip_evidence':![],'other_constraints':['setting_lock_duration\x20covers\x20the\x20entire\x20term\x20(>=90d)','Long-cycle\x20projects\x20must\x20monitor\x20>90d\x20progress']},'applicable_conditions':{'business_scale':'medium','min_daily_orders':0x1,'other_conditions':['Long-cycle\x20delivery','Requires\x20per-session\x20acceptance','Regulatory\x20intensity:\x20medium']},'similar_industries':['freelance','subscription'],'novel_capabilities':['allocation.distribute_milestone'],'disabled_builtin_constraints':['require_wip_evidence']},{'name':'travel','display_name':'Travel','version':'v1','source':'builtin',...fetchTemplate('travel'),'analyze':{'key_questions':['Does\x20each\x20itinerary\x20segment\x20have\x20its\x20own\x20guard\x20and\x20WIP\x20acceptance,\x20so\x20one\x20failed\x20leg\x20is\x20refundable\x20without\x20unwinding\x20the\x20whole\x20trip?','Is\x20the\x20multi-tier\x20allocation\x20waterfall\x20(agency\x20→\x20hotel/guide/driver)\x20visible\x20on-chain,\x20so\x20the\x20agency\x20cannot\x20silently\x20re-split\x20funds?']},'capabilities_used':['permission.index_create','permission.role_assign','guard.validate_buy','guard.validate_wip_hash','machine.node_topology','treasury.owner_receive','allocation.distribute','service.publish','progress.advance','arb.vote_weighted','contact.im_create'],'config_overrides':{'allocation':{'strategy':{'recipient':'entity','count':0x3,'mode':'amount','description':'Deposit\x2020%\x20to\x20agency,\x20final\x2080%\x20to\x20agency,\x20then\x20agency-side\x20Allocation\x20splits\x20to\x20hotel/guide/driver\x20per\x20segment'},'multi_tier_waterfall':!![],'guard_chaining':!![]},'service':{'supply_chain_suborders':!![],'segment_guard_required':!![]}},'expected_benefits':[{'metric':'Fund\x20transparency','expected_value':'100%','evidence':'multi-tier\x20allocation\x20splits\x20per\x20segment\x20to\x20hotel/guide/driver'},{'metric':'Itinerary\x20change\x20disputes','expected_value':'-45%','evidence':'segment\x20WIP\x20accepts\x20each\x20leg'},{'metric':'Breach\x20compensation\x20assurance','expected_value':'+60%','evidence':'compensation_fund\x20covers\x20itinerary\x20breach'}],'risk_appetite':'balanced','risk_constraints':{'require_arbitration':!![],'require_compensation_fund':!![],'require_wip_evidence':!![],'other_constraints':['Multi-tier\x20allocation\x20requires\x20guard\x20chaining\x20validation','deposit\x2020%\x20+\x20final\x2080%\x20two-stage\x20payment']},'applicable_conditions':{'business_scale':'medium','min_daily_orders':0x1,'other_conditions':['Multi-segment\x20itinerary\x20combination','Requires\x20hotel/guide/driver\x20multi-party\x20allocation']},'similar_industries':['rental','education'],'novel_capabilities':[]},{'name':'subscription','display_name':'Subscription','version':'v1','source':'builtin',...fetchTemplate('subscription'),'analyze':{'key_questions':['Is\x20every\x20periodic\x20charge\x20gated\x20by\x20an\x20explicit\x20user\x20confirmation,\x20with\x20no\x20auto-renew\x20default?','Can\x20the\x20subscriber\x20cancel\x20anytime\x20effective\x20next\x20period,\x20without\x20a\x20dead-end\x20node\x20in\x20the\x20machine?']},'capabilities_used':['permission.index_create','permission.role_assign','guard.validate_buy','machine.node_topology','treasury.owner_receive','allocation.distribute','service.publish','progress.advance','arb.vote_weighted','reward.claim_guard','contact.im_create'],'config_overrides':{'machine':{'no_auto_renew_trap':!![],'user_confirmed_charge':!![],'cancel_anytime':!![],'next_period_effective':!![]},'service':{'creator_data_subscription':!![],'periodic_billing':!![]}},'expected_benefits':[{'metric':'Renewal\x20rate','expected_value':'+25%','evidence':'loyalty\x20reward\x20+\x20transparent\x20subscription\x20mechanism'},{'metric':'Cancellation\x20disputes','expected_value':'eliminated','evidence':'cancel\x20anytime\x20+\x20no\x20auto-renew\x20trap'},{'metric':'Creator\x20retention','expected_value':'+30%','evidence':'deliver_guard_wip\x20prevents\x20content\x20dropout'}],'risk_appetite':'aggressive','risk_constraints':{'require_arbitration':![],'require_compensation_fund':![],'require_wip_evidence':![],'compensation_fund_coverage_ratio':0x3,'other_constraints':['Forbid\x20dead-end\x20nodes\x20(prevent\x20lock-in)','charge_guard\x20requires\x20user\x20confirmation\x20each\x20period']},'applicable_conditions':{'business_scale':'small','min_daily_orders':0x5,'other_conditions':['Pure-digital\x20delivery','Periodic\x20content\x20or\x20SaaS\x20service']},'similar_industries':['freelance','education'],'novel_capabilities':[],'disabled_builtin_constraints':['require_arbitration','require_compensation_fund','require_wip_evidence']},{'name':'retail','display_name':'Retail','version':'v1','source':'builtin',...fetchTemplate('retail'),'analyze':{'key_questions':['Is\x20the\x20logistics\x20tracking\x20number\x20recorded\x20as\x20WIP\x20before\x20the\x20confirm\x20gate,\x20so\x20receipt\x20disputes\x20have\x20carrier\x20evidence?','Is\x20the\x20refund\x20window\x20at\x20least\x207\x20days\x20with\x20an\x20on-chain\x20refund\x20path\x20that\x20does\x20not\x20rely\x20on\x20merchant\x20goodwill?']},'capabilities_used':['permission.index_create','permission.role_assign','guard.validate_buy','guard.validate_wip_hash','machine.node_topology','treasury.owner_receive','allocation.distribute','service.publish','progress.advance','arb.vote_weighted','reward.claim_guard','contact.im_create'],'config_overrides':{'machine':{'wip_required':!![],'wip_field':'tracking_number','confirm_gate':!![],'refund_requires_approval':!![]},'service':{'first_order_discount':!![]}},'expected_benefits':[{'metric':'Return\x20dispute\x20rate','expected_value':'-35%','evidence':'logistics\x20WIP\x20+\x20refund\x20path\x20assurance'},{'metric':'Repurchase\x20rate','expected_value':'+20%','evidence':'spend\x20cashback\x20reward'},{'metric':'Product\x20authenticity\x20traceability','expected_value':'100%','evidence':'WIP\x20verifies\x20product/logistics\x20info'}],'risk_appetite':'conservative','risk_constraints':{'require_arbitration':!![],'require_compensation_fund':!![],'require_wip_evidence':![],'compensation_fund_coverage_ratio':0x5,'other_constraints':['refund_window\x20>=\x207d','confirm_gate:\x20only\x20buyer\x20can\x20confirm\x20receipt']},'applicable_conditions':{'business_scale':'medium','min_daily_orders':0xa,'other_conditions':['Has\x20logistics\x20shipping\x20leg','High-frequency\x20small-ticket\x20transactions']},'similar_industries':['rental','subscription'],'novel_capabilities':[],'disabled_builtin_constraints':['require_wip_evidence']},{'name':'retail_d2c','display_name':'Retail\x20D2C\x20(Direct-to-Consumer)','version':'v1','source':'builtin',...fetchTemplate('retail_d2c'),'analyze':{'key_questions':['Do\x20withdraw_guard\x20and\x20refund_guard\x20fully\x20enclose\x20the\x20Allocation\x20escrow,\x20so\x20neither\x20side\x20can\x20move\x20funds\x20outside\x20the\x20contract\x20path?','With\x20no\x20platform\x20arbitration,\x20what\x20off-chain\x20recourse\x20(if\x20any)\x20backs\x20a\x20delivery\x20failure\x20—\x20and\x20is\x20that\x20acceptable\x20for\x20the\x20ticket\x20size?']},'capabilities_used':['permission.index_create','permission.role_assign','guard.validate_withdraw','guard.validate_refund','machine.node_topology','allocation.distribute','service.publish','progress.advance','contact.im_create'],'config_overrides':{'machine':{'wip_required':![],'confirm_gate':!![],'refund_requires_approval':![]},'service':{'multi_recipient_allocation':!![]}},'expected_benefits':[{'metric':'Merchant\x20revenue\x20share','expected_value':'97%','evidence':'No\x20platform\x20commission\x20—\x20only\x203%\x20processing\x20fee'},{'metric':'Fund\x20safety','expected_value':'contract-grade','evidence':'Allocation\x20escrow\x20+\x20Guard\x20verification\x20replaces\x20platform\x20custody'},{'metric':'Delivery\x20reliability','expected_value':'high','evidence':'withdraw_guard\x20enforces\x20delivery\x20confirmation\x20before\x20payment'}],'risk_appetite':'balanced','risk_constraints':{'require_arbitration':![],'require_compensation_fund':![],'require_wip_evidence':![],'other_constraints':['Allocation\x20escrow\x20required\x20(withdraw_guard\x20+\x20refund_guard)','Service\x20↔\x20Guard\x20circular\x20dependency\x20requires\x203-step\x20creation\x20pattern']},'applicable_conditions':{'business_scale':'small','min_daily_orders':0x1,'other_conditions':['Independent\x20storefront\x20(no\x20marketplace)','Merchant-managed\x20logistics','Allocation\x20escrow\x20model']},'similar_industries':['retail','subscription'],'novel_capabilities':['Allocation\x20escrow\x20as\x20platform-custody\x20alternative','Multi-recipient\x20allocation\x20(merchant\x20+\x20processor)'],'disabled_builtin_constraints':['require_arbitration','require_compensation_fund','require_wip_evidence']},{'name':'licensing','display_name':'Licensing','version':'v1','source':'builtin',...fetchTemplate('licensing'),'analyze':{'key_questions':['Is\x20the\x20license\x20grant\x20(terms\x20+\x20asset/certificate\x20hash)\x20anchored\x20as\x20a\x20WIP\x20artifact\x20and\x20an\x20evidence\x20Repository\x20row\x20BEFORE\x20release,\x20so\x20a\x20misrepresentation\x20dispute\x20has\x20an\x20on-chain\x20artifact\x20to\x20read?','Does\x20the\x20release\x20split\x20sum\x20to\x20exactly\x2010000\x20bps\x20across\x20explicit\x20NON-EMPTY\x20rights-holder\x20Entities\x20(no\x20empty\x20Entity\x20routing\x20the\x20share\x20to\x20the\x20deployer,\x20no\x20Surplus\x20draining\x20the\x20pool)?','Are\x20the\x20chain\x20GAPs\x20disclosed\x20honestly\x20—\x20the\x20auction\x20resolved\x20OFF-chain\x20(no\x20bid\x20ledger)\x20and\x20usage\x20caps\x20enforced\x20as\x20attested-counter\x20arbitration\x20evidence\x20(no\x20metering\x20oracle),\x20never\x20as\x20chain-enforced\x20limits?']},'capabilities_used':['permission.index_create','permission.role_assign','guard.validate_buy','guard.validate_wip_hash','machine.node_topology','treasury.owner_receive','allocation.distribute','service.publish','progress.advance','arb.vote_weighted','contact.im_create'],'config_overrides':{'machine':{'wip_required':!![],'confirm_gate':!![],'refund_requires_approval':!![]},'service':{'multi_recipient_allocation':!![]}},'expected_benefits':[{'metric':'Royalty-split\x20transparency','expected_value':'100%','evidence':'every\x20rights-holder\x20share\x20is\x20an\x20on-chain\x20Rate\x20leg\x20the\x20buyer\x20can\x20audit\x20before\x20ordering'},{'metric':'Misrepresentation\x20dispute\x20rate','expected_value':'-40%','evidence':'inspection-window\x20escrow\x20+\x20grant-artifact\x20WIP\x20anchor\x20the\x20terms\x20before\x20release'},{'metric':'Settlement\x20latency','expected_value':'seconds','evidence':'release\x20fires\x20on\x20buyer\x20accept\x20/\x20time-lock,\x20not\x20a\x20calendar\x20freeze'}],'risk_appetite':'conservative','risk_constraints':{'require_arbitration':!![],'require_compensation_fund':!![],'require_wip_evidence':!![],'other_constraints':['release\x20split\x20Rate\x20legs\x20sum\x20exactly\x2010000\x20(ERATE_NOT_10000);\x20every\x20recipient\x20an\x20explicit\x20NON-EMPTY\x20Entity','inspection/delivery\x20window\x20>=\x203d\x20so\x20the\x20buyer\x20can\x20verify\x20the\x20grant\x20before\x20auto-accept','🔴\x20auction\x20resolved\x20OFF-chain\x20(no\x20bid\x20ledger)\x20and\x20usage\x20caps\x20attested\x20(no\x20oracle)\x20—\x20disclosed,\x20never\x20chain-enforced']},'applicable_conditions':{'business_scale':'small','min_daily_orders':0x1,'other_conditions':['Pure-digital\x20grant\x20(no\x20logistics\x20leg)','Rights-holder\x20/\x20producer\x20/\x20publisher\x20owns\x20the\x20IP','Long-lived\x20value\x20(a\x20royalty\x20share\x20or\x20a\x20license\x20term)']},'similar_industries':['subscription','freelance'],'novel_capabilities':['Multi-recipient\x20royalty\x20split\x20(Allocation\x20Rate\x20plan)','Territory/qualification\x20allowlist\x20buy\x20gate','Inspection-window\x20escrow\x20before\x20release']},{'name':'crowdfunding','display_name':'Crowdfunding','version':'v1','source':'builtin',...fetchTemplate('crowdfunding'),'analyze':{'key_questions':['Is\x20each\x20contribution\x20escrowed\x20to\x20the\x20funder\x27s\x20OWN\x20Order\x20(for_object)\x20and\x20NEVER\x20pooled\x20via\x20balance::join,\x20so\x20per-backer\x20attribution\x20survives\x20settlement\x20or\x20refund?','Does\x20the\x20threshold\x20gate\x20read\x20a\x20WRITER-BOUND\x20Repository\x20numeric\x20row\x20(id_from\x20signer,\x20value\x20=\x20amount)\x20summed\x20via\x20the\x20sum-where\x20query,\x20ANDed\x20with\x20an\x20ABSOLUTE\x20shared\x20campaign\x20deadline\x20—\x20so\x20a\x20funder\x20cannot\x20inflate\x20the\x20total\x20and\x20every\x20backer\x20sees\x20the\x20same\x20cutoff?','Is\x20the\x20aggregate\x20total\x20disclosed\x20honestly\x20as\x20a\x20keeper-attested\x20Repository\x20sum\x20(arbitration\x20evidence,\x20NOT\x20a\x20chain-verified\x20money\x20oracle),\x20and\x20is\x20the\x20escrow-exit\x20two-leg\x20polarity\x20exact\x20(refund\x20claimed_by\x20some==false\x20XOR\x20recover_gate\x20claimed_by\x20some==true,\x20D-BUG-2)?']},'capabilities_used':['permission.index_create','permission.role_assign','guard.validate_buy','guard.validate_wip_hash','machine.node_topology','treasury.owner_receive','allocation.distribute','service.publish','progress.advance','arb.vote_weighted','contact.im_create'],'config_overrides':{'machine':{'wip_required':!![],'confirm_gate':!![],'refund_requires_approval':![]},'service':{'multi_recipient_allocation':!![]}},'expected_benefits':[{'metric':'Backer\x20attribution','expected_value':'100%','evidence':'each\x20contribution\x20is\x20a\x20for_object-bound\x20Allocation\x20on\x20the\x20funder\x27s\x20own\x20Order\x20—\x20never\x20pooled'},{'metric':'Unmet-threshold\x20refund','expected_value':'automatic','evidence':'the\x20sum-where\x20<\x20goal\x20leg\x20fires\x20the\x20refund\x20exit\x20with\x20no\x20merchant\x20approval\x20(D-BUG-2\x20polarity)'},{'metric':'Campaign\x20deadline\x20drift','expected_value':'0','evidence':'one\x20ABSOLUTE\x20Clock\x20timestamp\x20shared\x20by\x20every\x20funder,\x20not\x20per-order\x20entry+duration'}],'risk_appetite':'conservative','risk_constraints':{'require_arbitration':!![],'require_compensation_fund':!![],'require_wip_evidence':!![],'other_constraints':['per-contributor\x20Allocation\x20for_object\x20=\x20own\x20Order;\x20NEVER\x20balance::join\x20(attribution\x20survives)','threshold\x20gate\x20=\x20repository.data\x20sum-where\x20(1174)\x20over\x20WRITER-BOUND\x20rows\x20ANDed\x20with\x20an\x20ABSOLUTE\x20deadline','🔴\x20the\x20aggregate\x20total\x20is\x20a\x20keeper-attested\x20Repository\x20sum\x20(arbitration\x20evidence),\x20NOT\x20a\x20chain-verified\x20money\x20oracle\x20—\x20disclosed','🔴\x20L-01\x20never\x20promises\x20investment\x20returns\x20or\x20promotes\x20coin\x20price;\x20L-05\x20KYC/AML\x20+\x20cross-border\x20caution\x20(HIGH\x20regulatory\x20intensity)']},'applicable_conditions':{'business_scale':'small','min_daily_orders':0x1,'other_conditions':['Aggregate\x20funding\x20goal\x20with\x20a\x20fixed\x20campaign\x20deadline','Per-backer\x20reward\x20tiers\x20or\x20donation\x20(no\x20logistics\x20leg\x20required)','All-or-nothing\x20(refund\x20if\x20unmet)\x20or\x20keep-it-all\x20(no\x20refund)\x20campaign\x20shape']},'similar_industries':['retail','licensing'],'novel_capabilities':['Aggregate-goal\x20threshold\x20gate\x20via\x20writer-bound\x20Repository\x20sum-where','Per-contributor\x20for_object\x20escrow\x20(attribution-preserving,\x20never\x20pooled)','Absolute\x20shared\x20campaign\x20deadline\x20+\x20two-leg\x20escrow-exit\x20(release\x20XOR\x20refund)']},{'name':'delivery','display_name':'Local\x20Delivery','version':'v1','source':'builtin',...fetchTemplate('delivery'),'analyze':{'key_questions':['Who\x20writes\x20the\x20rider\x20roster\x20(permission\x20221)\x20—\x20is\x20that\x20admission\x20power\x20disclosed,\x20and\x20is\x20the\x20roster\x20budget\x20(60\x20rosters\x20/\x2080\x20addresses\x20per\x20Progress)\x20respected?','Does\x20settlement\x20depart\x20a\x20SERIAL\x20claim\x20window\x20(TPL-09)\x20with\x20settle_hours\x20>=\x20claim_window_hours,\x20so\x20no\x20payout\x20can\x20race\x20an\x20open\x20dispute\x20(FACT-ALLOC-03)?','Are\x20handover\x20records\x20(ready/pickup/deliver)\x20writer-bound\x20repository\x20rows,\x20and\x20is\x20the\x20buyer-facing\x20copy\x20honest\x20that\x20dispatch,\x20ETA\x20and\x20rider\x20pay\x20are\x20OFF-CHAIN?']},'capabilities_used':['permission.index_create','permission.role_assign','guard.validate_buy','guard.validate_wip_hash','machine.node_topology','treasury.owner_receive','allocation.distribute','service.publish','progress.advance','progress.named_operator','arb.vote_weighted','contact.im_create'],'config_overrides':{'machine':{'wip_required':!![],'confirm_gate':!![],'refund_requires_approval':![]},'service':{'multi_recipient_allocation':!![]}},'expected_benefits':[{'metric':'Silent-buyer\x20stranding','expected_value':'0','evidence':'buyer-first\x20confirmation\x20+\x20keeper\x20auto-confirm\x20within\x20auto_confirm_hours\x20(T-04)'},{'metric':'Payout/claim\x20race','expected_value':'unreachable','evidence':'the\x20serial\x20claim\x20window\x20makes\x20settlement\x20depart\x20only\x20after\x20filing\x20closes\x20(TPL-09)'},{'metric':'Rider\x20money-surface','expected_value':'0\x20legs','evidence':'the\x20escrow\x20can\x20never\x20pay\x20a\x20per-order\x20rider\x20(for_object\x20lock);\x20payroll\x20is\x20the\x20platform\x27s\x20off-chain\x20duty'}],'risk_appetite':'balanced','risk_constraints':{'require_arbitration':!![],'require_compensation_fund':![],'require_wip_evidence':!![],'other_constraints':['rider\x20roster\x20=\x20rider-admission\x20power;\x20disclose\x20the\x20roster\x20writer\x20(NAMED_OPERATOR_ROSTER_UNDISCLOSED)','settle_hours\x20>=\x20claim_window_hours\x20asserted\x20at\x20generation\x20(serial\x20window\x20math)','🔴\x20rider\x20pay\x20is\x20OFF-CHAIN\x20platform\x20payroll\x20—\x20never\x20model\x20a\x20per-order\x20rider\x20payout\x20leg','🔴\x20no\x20ETA/distance\x20oracle\x20—\x20pricing\x20and\x20delivery\x20estimates\x20are\x20not\x20chain-verifiable']},'applicable_conditions':{'business_scale':'small','min_daily_orders':0x1,'other_conditions':['Local\x20fulfillment\x20within\x20minutes-hours\x20windows\x20(perishable\x20or\x20time-boxed)','Per-order\x20dispatched\x20fulfillers\x20(no\x20fixed\x20staff\x20roster)','Fee-graded\x20cancellation\x20(free\x20pre-acceptance,\x20fee\x20post-acceptance)']},'similar_industries':['retail','group_buy'],'novel_capabilities':['Named-operator\x20roster\x20rail\x20for\x20per-order\x20dispatched\x20riders\x20(K-1)','Serial\x20claim\x20window\x20on\x20hours-scale\x20timing\x20(TPL-09)','Fee-graded\x20cancel\x20taxonomy\x20with\x20a\x20dedicated\x20kill\x20terminal']},{'name':'group_buy','display_name':'Community\x20Group-Buy','version':'v1','source':'builtin',...fetchTemplate('group_buy'),'analyze':{'key_questions':['Is\x20the\x20batch\x20cutoff\x20ONE\x20shared\x20absolute\x20timestamp\x20(keeper-written\x20Repository\x20row\x20+\x20time_source\x20oracle),\x20not\x20a\x20per-order\x20entry+duration\x20lock?','Does\x20the\x20leader\x20template\x20fix\x20the\x20supplier\x27s\x20sub-service\x20address\x20in\x20the\x20ConsolidateBatch\x20guard\x20table\x20(b_submission\x20false,\x20Address)\x20so\x20the\x20procurement\x20graph\x20is\x20diligence-able\x20before\x20any\x20buyer\x20pays?','In\x20threshold\x20mode,\x20are\x20contribution\x20rows\x20ORDER-keyed\x20with\x20the\x20escrow-bound\x20aggregate\x20(per-row\x20min(row,\x20order.amount,\x20live\x20allocation.balance\x20—\x20v139\x20live\x20cap))\x20and\x20the\x20live-escrow\x20+\x20claimed_by-false\x20legs\x20—\x20the\x20three\x20CROWDFUNDING_*\x20blockers\x20armed?']},'capabilities_used':['permission.index_create','permission.role_assign','guard.validate_buy','guard.validate_wip_hash','machine.node_topology','treasury.owner_receive','allocation.distribute','service.publish','progress.advance','progress.named_operator','repository.data_write','arb.vote_weighted','contact.im_create'],'config_overrides':{'machine':{'wip_required':!![],'confirm_gate':!![],'refund_requires_approval':![]},'service':{'multi_recipient_allocation':!![]}},'expected_benefits':[{'metric':'Cutoff\x20fairness','expected_value':'1\x20clock','evidence':'one\x20absolute\x20shared\x20cutoff\x20per\x20batch\x20(time_lock_absolute),\x20never\x20per-order\x20entry+duration'},{'metric':'Unformed-batch\x20refund','expected_value':'automatic','evidence':'ThresholdMissed\x20/\x20AbandonTimeout\x20rails\x20refund\x20per-order\x20with\x20no\x20merchant\x20grace'},{'metric':'Procurement\x20diligence','expected_value':'pre-order','evidence':'the\x20supplier\x20sub-service\x20address\x20is\x20a\x20fixed\x20guard-table\x20promise\x20(leader\x20shape)'}],'risk_appetite':'conservative','risk_constraints':{'require_arbitration':!![],'require_compensation_fund':!![],'require_wip_evidence':!![],'other_constraints':['batch\x20cutoff\x20=\x20shared\x20ABSOLUTE\x20timestamp\x20via\x20pattern.time_lock_absolute\x20+\x20time_source_repository_oracle','threshold\x20mode\x20reuses\x20the\x20crowdfunding\x20construction\x20(ORDER-keyed\x20rows,\x20escrow-bound\x20aggregate,\x20CROWDFUNDING_*\x20blockers)','🔴\x20multi-level\x20commission\x20is\x20NOT\x20expressible\x20—\x20single-layer\x20rate\x20leg\x20to\x20the\x20platform\x20Entity\x20with\x20off-chain\x20pass-through,\x20disclosed','🔴\x20delay\x20compensation\x20pays\x20from\x20compensation_fund,\x20NEVER\x20the\x20buyer\x20escrow\x20(Order\x20binds\x20<=\x201\x20allocator);\x20fund\x20pre-locked\x203x\x20(B2)']},'applicable_conditions':{'business_scale':'small','min_daily_orders':0x1,'other_conditions':['Neighborhood\x20batch\x20buying\x20with\x20a\x20daily/periodic\x20cutoff','Pickup-point\x20fulfillment\x20(staffed\x20point\x20or\x20automated\x20locker)','Leader\x20consolidation\x20ahead\x20of\x20a\x20supplier\x20sub-order']},'similar_industries':['crowdfunding','delivery'],'novel_capabilities':['Shared\x20absolute\x20batch\x20cutoff\x20via\x20keeper-written\x20Repository\x20row\x20+\x20time-source\x20oracle','Supply-chain\x20suborder\x20commitment\x20in\x20the\x20guard\x20table\x20(pre-order\x20diligence)','point_type-conditional\x20pickup\x20topology\x20(staffed\x20leader\x20rail\x20vs\x20automated\x20locker)']},{'name':'general','display_name':'General','version':'v1','source':'builtin',...fetchTemplate('general'),'analyze':{'key_questions':['Which\x20trust\x20mechanisms\x20(arbitration,\x20compensation\x20fund,\x20WIP\x20evidence)\x20are\x20missing\x20here,\x20and\x20what\x20does\x20each\x20absence\x20cost\x20in\x20the\x20worst\x20case?','What\x20is\x20the\x20single\x20point\x20of\x20failure\x20—\x20who\x20can\x20unilaterally\x20take\x20funds\x20or\x20stall\x20the\x20workflow?']},'capabilities_used':['permission.index_create','machine.node_topology','treasury.owner_receive','allocation.distribute','service.publish','progress.advance'],'expected_benefits':[{'metric':'Flexibility','expected_value':'100%','evidence':'User\x20customizes\x20all\x20trust\x20mechanism\x20parameters'},{'metric':'Degraded\x20safety','expected_value':'usable','evidence':'Can\x20fall\x20back\x20to\x20general\x20at\x20any\x20time'}],'risk_appetite':'balanced','risk_constraints':{'require_arbitration':![],'require_compensation_fund':![],'require_wip_evidence':![]},'applicable_conditions':{'business_scale':'small','other_conditions':['Fallback\x20degraded\x20mode','Hybrid\x20scenarios\x20not\x20covered\x20by\x20other\x20industries']},'similar_industries':[],'novel_capabilities':[],'disabled_builtin_constraints':['require_arbitration','require_compensation_fund','require_wip_evidence']}];
@@ -4,8 +4,6 @@ export declare class IndustryModeRegistry {
4
4
  private registrations;
5
5
  private userModes;
6
6
  private aliases;
7
- private evaluator;
8
- private initialized;
9
7
  private file;
10
8
  private userModesSyncedMtime;
11
9
  static Instance(): IndustryModeRegistry;
@@ -1 +1 @@
1
- import{CustomRegistryFile}from'./custom-registry-file.js';import{CapabilityRegistry}from'./capability-manifest.js';import{ModeEvaluator}from'./mode-evaluator.js';import{MetricRegistry}from'./metric-registry.js';import{ConstraintRegistry}from'./constraint-registry.js';import{BUILTIN_MODES}from'./modes.js';import{unannotatedBuyerActionNodes}from'../knowledge/scenario-modes.js';export class IndustryModeRegistry{static ['instance'];['registrations']=new Map();['userModes']=new Map();['aliases']=new Map();['evaluator'];['initialized']=![];['file']=CustomRegistryFile['Instance']();['userModesSyncedMtime']=-0x1;static['Instance'](){return!IndustryModeRegistry['instance']&&(IndustryModeRegistry['instance']=new IndustryModeRegistry()),IndustryModeRegistry['instance'];}constructor(){this['evaluator']=new ModeEvaluator(CapabilityRegistry['Instance'](),MetricRegistry['Instance'](),ConstraintRegistry['Instance']()),this['registerBuiltinModes'](),this['initialized']=!![];}['registerMode'](a,b){if(!a['name']||!a['traits']||!a['machine_shape'])return console['warn']('[IndustryModeRegistry]\x20registerMode\x20rejected:\x20invalid\x20mode\x20'+('(name='+(a['name']||'<missing>')+',\x20traits='+(a['traits']?'ok':'<missing>')+',\x20')+('machine_shape='+(a['machine_shape']?'ok':'<missing>')+').')),![];if(this['registrations']['has'](a['name'])){const d=this['registrations']['get'](a['name']);return console['warn']('[IndustryModeRegistry]\x20registerMode\x20rejected:\x20mode\x20\x27'+a['name']+'\x27\x20already\x20registered\x20'+('(registered_at='+new Date(d?.['registered_at']??0x0)['toISOString']()+').\x20')+'Use\x20evolveMode/deriveMode\x20for\x20user\x20modifications,\x20or\x20unregister\x20first.'),![];}this['registrations']['set'](a['name'],{'mode':a,'aliases':b,'enabled':!![],'registered_at':Date['now']()});const c=unannotatedBuyerActionNodes(a['machine_shape']);c['length']>0x0&&console['warn']('[IndustryModeRegistry]\x20mode\x20\x27'+a['name']+'\x27\x20machine_shape:\x20buyer-action\x20node(s)\x20'+(c['map'](e=>'\x27'+e+'\x27')['join'](',\x20')+'\x20lack\x20an\x20operator\x20annotation\x20')+'(R-OPER-01)\x20—\x20annotate\x20them\x20operator:\x20\x22order_payer\x22\x20or\x20buyers\x20cannot\x20advance\x20them.');if(b)for(const e of b){this['aliases']['set'](e,a['name']);}return!![];}['getMode'](a){const b=this['resolveAlias'](a);return this['registrations']['get'](b)?.['mode'];}['listModes'](){return Array['from'](this['registrations']['values']())['filter'](a=>a['enabled'])['map'](a=>a['mode']);}['resolveAlias'](a){return this['aliases']['get'](a)??a;}['hasMode'](a){const b=this['resolveAlias'](a);return this['registrations']['has'](b);}['unregisterMode'](a){const b=this['resolveAlias'](a);if(!this['registrations']['has'](b))return![];this['registrations']['delete'](b);for(const [c,d]of this['aliases']){if(d===b)this['aliases']['delete'](c);}return!![];}async['registerUserMode'](a,b){await this['ensureUserModesLoaded']();if(!a['name']||!a['owner']||!a['machine_shape'])return![];if(a['source']!=='custom')return![];if(a['owner']!==b)return![];const c=this['userModeKey'](a['owner'],a['name']);if(this['registrations']['has'](a['name']))return![];if(this['userModes']['has'](c))return![];return(!a['evolution_history']||a['evolution_history']['length']===0x0)&&(a['evolution_history']=[{'version':a['version']||'v1','changed_at':Date['now'](),'changes':['Initial\x20registration\x20(registerUserMode)']}]),this['userModes']['set'](c,a),await this['persistUserMode'](a),!![];}async['deriveMode'](a,b,c,d,e){await this['ensureUserModesLoaded']();const f=this['getMode'](a);if(!f)return undefined;if(!d||this['registrations']['has'](d))return undefined;const g=this['userModeKey'](c,d);if(this['userModes']['has'](g))return undefined;const h={'name':d,'display_name':e??d,'version':'v1','source':'custom','traits':b['traits']??f['traits'],'machine_shape':b['machine_shape']??f['machine_shape'],'guards':b['guards']??f['guards'],'allocator':b['allocator']??f['allocator'],'risk_checks':b['risk_checks']??f['risk_checks'],'needs':b['needs']??f['needs'],'flywheel':b['flywheel']??f['flywheel'],'key_risk':b['key_risk']??f['key_risk'],'build_notes':b['build_notes']??f['build_notes'],'analyze':b['analyze']??f['analyze'],'capabilities_used':b['capabilities_used']??f['capabilities_used'],'config_overrides':b['config_overrides']??f['config_overrides'],'config_override_rules':b['config_override_rules']??f['config_override_rules'],'expected_benefits':b['expected_benefits']??f['expected_benefits'],'risk_appetite':b['risk_appetite']??f['risk_appetite'],'risk_constraints':b['risk_constraints']??f['risk_constraints'],'applicable_conditions':b['applicable_conditions']??f['applicable_conditions'],'similar_industries':b['similar_industries']??f['similar_industries'],'novel_capabilities':b['novel_capabilities']??f['novel_capabilities'],'owner':c,'derived_from':a,'custom_metrics':b['custom_metrics']??f['custom_metrics'],'custom_constraints':b['custom_constraints']??f['custom_constraints'],'evolution_history':[{'version':'v1','changed_at':Date['now'](),'changes':['Derived\x20from\x20builtin\x20\x27'+a+'\x27']}]};return this['userModes']['set'](g,h),await this['persistUserMode'](h),h;}async['evolveMode'](a,b,c,d,e=!![]){await this['ensureUserModesLoaded']();const f=this['userModeKey'](c,a),g=this['userModes']['get'](f);if(!g)return undefined;const h=e?this['bumpPatchVersion'](g['version']):g['version'],i={...g,...b,'name':g['name'],'owner':g['owner'],'source':'custom','derived_from':g['derived_from'],'evolution_history':[...g['evolution_history']??[],{'version':h,'changed_at':Date['now'](),'changes':[d]}],'version':h};return this['userModes']['set'](f,i),await this['persistUserMode'](i),i;}async['listUserModes'](a){await this['ensureUserModesLoaded']();const b=[];for(const c of this['userModes']['values']()){c['owner']===a&&b['push'](c);}return b;}async['getUserMode'](a,b){await this['ensureUserModesLoaded']();const c=this['userModeKey'](b,a);return this['userModes']['get'](c);}async['unregisterUserMode'](a,b){await this['ensureUserModesLoaded']();const c=this['userModeKey'](b,a),d=this['userModes']['delete'](c);return d&&await this['unpersistUserMode'](b,a),d;}['userModeKey'](a,b){return a+':'+b;}async['ensureUserModesLoaded'](){const {data:a,mtime:b}=await this['file']['read']();if(b<0x0||b===this['userModesSyncedMtime'])return;this['userModesSyncedMtime']=b,this['userModes']['clear']();for(const [c,d]of Object['entries'](a['user_modes'])){const e=d;e?.['name']&&e?.['owner']&&e?.['machine_shape']?this['userModes']['set'](c,e):console['warn']('[IndustryModeRegistry]\x20Skipping\x20invalid\x20user_modes\x20file\x20entry\x20\x27'+c+'\x27.');}}async['persistUserMode'](a){await this['file']['update'](b=>{b['user_modes'][this['userModeKey'](a['owner'],a['name'])]=a;});}async['unpersistUserMode'](a,b){await this['file']['update'](c=>{delete c['user_modes'][this['userModeKey'](a,b)];});}['bumpPatchVersion'](a){const b=a['replace'](/^v/,''),c=b['split']('.');if(c['length']<0x2)return'v'+b+'.1';const d=parseInt(c[0x1]??'0',0xa);return c[0x1]=String(d+0x1),'v'+c['join']('.');}['registerBuiltinModes'](){for(const a of BUILTIN_MODES){this['registerMode'](a);}}}export function getIndustryModeRegistry(){return IndustryModeRegistry['Instance']();}export const INDUSTRY_MODE_REGISTRY_VERSION=2.3;
1
+ import{CustomRegistryFile}from'./custom-registry-file.js';import{BUILTIN_MODES}from'./modes.js';import{unannotatedBuyerActionNodes}from'../knowledge/scenario-modes.js';export class IndustryModeRegistry{static ['instance'];['registrations']=new Map();['userModes']=new Map();['aliases']=new Map();['file']=CustomRegistryFile['Instance']();['userModesSyncedMtime']=-0x1;static['Instance'](){return!IndustryModeRegistry['instance']&&(IndustryModeRegistry['instance']=new IndustryModeRegistry()),IndustryModeRegistry['instance'];}constructor(){this['registerBuiltinModes']();}['registerMode'](a,b){if(!a['name']||!a['traits']||!a['machine_shape'])return console['warn']('[IndustryModeRegistry]\x20registerMode\x20rejected:\x20invalid\x20mode\x20'+('(name='+(a['name']||'<missing>')+',\x20traits='+(a['traits']?'ok':'<missing>')+',\x20')+('machine_shape='+(a['machine_shape']?'ok':'<missing>')+').')),![];if(this['registrations']['has'](a['name'])){const d=this['registrations']['get'](a['name']);return console['warn']('[IndustryModeRegistry]\x20registerMode\x20rejected:\x20mode\x20\x27'+a['name']+'\x27\x20already\x20registered\x20'+('(registered_at='+new Date(d?.['registered_at']??0x0)['toISOString']()+').\x20')+'Use\x20evolveMode/deriveMode\x20for\x20user\x20modifications,\x20or\x20unregister\x20first.'),![];}this['registrations']['set'](a['name'],{'mode':a,'aliases':b,'enabled':!![],'registered_at':Date['now']()});const c=unannotatedBuyerActionNodes(a['machine_shape']);c['length']>0x0&&console['warn']('[IndustryModeRegistry]\x20mode\x20\x27'+a['name']+'\x27\x20machine_shape:\x20buyer-action\x20node(s)\x20'+(c['map'](e=>'\x27'+e+'\x27')['join'](',\x20')+'\x20lack\x20an\x20operator\x20annotation\x20')+'(R-OPER-01)\x20—\x20annotate\x20them\x20operator:\x20\x22order_payer\x22\x20or\x20buyers\x20cannot\x20advance\x20them.');if(b)for(const e of b){this['aliases']['set'](e,a['name']);}return!![];}['getMode'](a){const b=this['resolveAlias'](a);return this['registrations']['get'](b)?.['mode'];}['listModes'](){return Array['from'](this['registrations']['values']())['filter'](a=>a['enabled'])['map'](a=>a['mode']);}['resolveAlias'](a){return this['aliases']['get'](a)??a;}['hasMode'](a){const b=this['resolveAlias'](a);return this['registrations']['has'](b);}['unregisterMode'](a){const b=this['resolveAlias'](a);if(!this['registrations']['has'](b))return![];this['registrations']['delete'](b);for(const [c,d]of this['aliases']){if(d===b)this['aliases']['delete'](c);}return!![];}async['registerUserMode'](a,b){await this['ensureUserModesLoaded']();if(!a['name']||!a['owner']||!a['machine_shape'])return![];if(a['source']!=='custom')return![];if(a['owner']!==b)return![];const c=this['userModeKey'](a['owner'],a['name']);if(this['registrations']['has'](a['name']))return![];if(this['userModes']['has'](c))return![];return(!a['evolution_history']||a['evolution_history']['length']===0x0)&&(a['evolution_history']=[{'version':a['version']||'v1','changed_at':Date['now'](),'changes':['Initial\x20registration\x20(registerUserMode)']}]),this['userModes']['set'](c,a),await this['persistUserMode'](a),!![];}async['deriveMode'](a,b,c,d,e){await this['ensureUserModesLoaded']();const f=this['getMode'](a);if(!f)return undefined;if(!d||this['registrations']['has'](d))return undefined;const g=this['userModeKey'](c,d);if(this['userModes']['has'](g))return undefined;const h={'name':d,'display_name':e??d,'version':'v1','source':'custom','traits':b['traits']??f['traits'],'machine_shape':b['machine_shape']??f['machine_shape'],'guards':b['guards']??f['guards'],'allocator':b['allocator']??f['allocator'],'risk_checks':b['risk_checks']??f['risk_checks'],'needs':b['needs']??f['needs'],'flywheel':b['flywheel']??f['flywheel'],'key_risk':b['key_risk']??f['key_risk'],'build_notes':b['build_notes']??f['build_notes'],'analyze':b['analyze']??f['analyze'],'capabilities_used':b['capabilities_used']??f['capabilities_used'],'config_overrides':b['config_overrides']??f['config_overrides'],'config_override_rules':b['config_override_rules']??f['config_override_rules'],'expected_benefits':b['expected_benefits']??f['expected_benefits'],'risk_appetite':b['risk_appetite']??f['risk_appetite'],'risk_constraints':b['risk_constraints']??f['risk_constraints'],'applicable_conditions':b['applicable_conditions']??f['applicable_conditions'],'similar_industries':b['similar_industries']??f['similar_industries'],'novel_capabilities':b['novel_capabilities']??f['novel_capabilities'],'owner':c,'derived_from':a,'custom_metrics':b['custom_metrics']??f['custom_metrics'],'custom_constraints':b['custom_constraints']??f['custom_constraints'],'evolution_history':[{'version':'v1','changed_at':Date['now'](),'changes':['Derived\x20from\x20builtin\x20\x27'+a+'\x27']}]};return this['userModes']['set'](g,h),await this['persistUserMode'](h),h;}async['evolveMode'](a,b,c,d,e=!![]){await this['ensureUserModesLoaded']();const f=this['userModeKey'](c,a),g=this['userModes']['get'](f);if(!g)return undefined;const h=e?this['bumpPatchVersion'](g['version']):g['version'],i={...g,...b,'name':g['name'],'owner':g['owner'],'source':'custom','derived_from':g['derived_from'],'evolution_history':[...g['evolution_history']??[],{'version':h,'changed_at':Date['now'](),'changes':[d]}],'version':h};return this['userModes']['set'](f,i),await this['persistUserMode'](i),i;}async['listUserModes'](a){await this['ensureUserModesLoaded']();const b=[];for(const c of this['userModes']['values']()){c['owner']===a&&b['push'](c);}return b;}async['getUserMode'](a,b){await this['ensureUserModesLoaded']();const c=this['userModeKey'](b,a);return this['userModes']['get'](c);}async['unregisterUserMode'](a,b){await this['ensureUserModesLoaded']();const c=this['userModeKey'](b,a),d=this['userModes']['delete'](c);return d&&await this['unpersistUserMode'](b,a),d;}['userModeKey'](a,b){return a+':'+b;}async['ensureUserModesLoaded'](){const {data:a,mtime:b}=await this['file']['read']();if(b<0x0||b===this['userModesSyncedMtime'])return;this['userModesSyncedMtime']=b,this['userModes']['clear']();for(const [c,d]of Object['entries'](a['user_modes'])){const e=d;e?.['name']&&e?.['owner']&&e?.['machine_shape']?this['userModes']['set'](c,e):console['warn']('[IndustryModeRegistry]\x20Skipping\x20invalid\x20user_modes\x20file\x20entry\x20\x27'+c+'\x27.');}}async['persistUserMode'](a){await this['file']['update'](b=>{b['user_modes'][this['userModeKey'](a['owner'],a['name'])]=a;});}async['unpersistUserMode'](a,b){await this['file']['update'](c=>{delete c['user_modes'][this['userModeKey'](a,b)];});}['bumpPatchVersion'](a){const b=a['replace'](/^v/,''),c=b['split']('.');if(c['length']<0x2)return'v'+b+'.1';const d=parseInt(c[0x1]??'0',0xa);return c[0x1]=String(d+0x1),'v'+c['join']('.');}['registerBuiltinModes'](){for(const a of BUILTIN_MODES){this['registerMode'](a);}}}export function getIndustryModeRegistry(){return IndustryModeRegistry['Instance']();}export const INDUSTRY_MODE_REGISTRY_VERSION=2.3;
@@ -1 +1 @@
1
- import{classifyGoal}from'./GoalClassifier.js';import{goalStore}from'./GoalStore.js';import{GOAL_AUTONOMY_LEVELS,isTerminalStage,newGoalId,stageIndex}from'./types.js';import{goalBoundaryQuestions,pursueTick}from'./pursue.js';import{nextStepsForGoal}from'./next-steps.js';import{GENERIC_PLAYBOOK,playbookForGoalType}from'../task/playbook.js';import{PROCESS_SCHEMA_VERSION,newProcessId}from'../task/types.js';import{addFeedback,addSuggestion,appendEvent,deleteProcessDir,initProcess,listFeedback,listProblems,listSuggestions,loadManifest,loadStageState,processesRootDir,readEvents,saveManifest,updateSuggestion}from'../task/ProcessStore.js';import{recordSignature}from'../experience/index.js';import{join}from'path';import{registerPlanApproval,revokePlanApproval}from'./plan-approval.js';import{subscriptionStore}from'../monitor/SubscriptionStore.js';import{createIntent,removeIntent}from'../intent/index.js';import{listLocalAccounts}from'../knowledge/workflow-guidance.js';import{evaluateGoalCompletion}from'../knowledge/goal-completion.js';export const GOAL_PLAYBOOKS={'publish_service':'wowok-provider','fulfill_order':'wowok-provider','capture_demand':'wowok-market','purchase_service':'wowok-order','collaborate_flow':'wowok-collaborator','supply_suborder':'wowok-supplier','publish_demand':'wowok-order','run_arbitration':'wowok-arbitrator','dispute_resolution':'wowok-order','manage_assets':'wowok-governance'};export const PLAN_APPROVAL_COVERS_LEVELS=['standard','none'];export const ADOPT_JACCARD_THRESHOLD=0.6;export function tokenizeIntent(a){const b=new Set(),c=(a??'')['toLowerCase']();for(const d of c['matchAll'](/[a-z0-9]+/g))b['add'](d[0x0]);for(const e of c['matchAll'](/[\u3400-\u9fff\uf900-\ufaff]/g))b['add'](e[0x0]);return b;}export function jaccard(c,d){if(c['size']===0x0||d['size']===0x0)return 0x0;let e=0x0;for(const f of c)if(d['has'](f))e++;return e/(c['size']+d['size']-e);}function deriveTitle(a){const b=(intent_text_first_line(a)||'Untitled\x20goal')['trim']();return b['length']>0x3c?b['slice'](0x0,0x39)+'…':b;}function intent_text_first_line(a){return(a??'')['split'](/\r?\n/,0x1)[0x0]??'';}function newApprovalId(){return'appr_'+Date['now']()['toString'](0x24)+Math['random']()['toString'](0x24)['slice'](0x2,0x8);}export class GoalEngine{['deps'];constructor(a){this['deps']=a;}async['createOrAdopt'](a){const b=a['network']??'default',c=(a['intent_text']??'')['trim']();if(!c)throw new Error('create_or_adopt\x20requires\x20non-empty\x20intent_text');let d=a['goal_type'],f;if(!d){f=classifyGoal(c),d=f['goal_type']??undefined;if(!d)return{'adopted':![],'classification':f,'needs_type':!![]};}const h=await this['deps']['store']['list'](b),i=a['account']??'',j=tokenizeIntent(c);let k;for(const r of h){if(isTerminalStage(r['stage']))continue;if(r['goal_type']!==d)continue;if((r['binding']?.['account']??'')!==i)continue;const s=jaccard(j,tokenizeIntent(r['intent_text']));s>=ADOPT_JACCARD_THRESHOLD&&(!k||s>k['sim'])&&(k={'goal':r,'sim':s});}if(k)return{'goal':k['goal'],'adopted':!![],'classification':f};const l=Date['now']();let m,n='recognized';if(a['account']){const t=await this['preflightAccount'](a['account']);m={'account':a['account'],'persona':a['persona'],'preflight':t},n='bound';}const o={'id':newGoalId(),'goal_type':d,'title':a['title']?.['trim']()||deriveTitle(c),'intent_text':c,...a['conversation_id']?{'conversation_id':a['conversation_id']}:{},'binding':m,'objects':[],'monitor':{'focus_ids':[],'intent_ids':[]},'stage':n,'playbook':GOAL_PLAYBOOKS[d],'approvals':[],'created_at':l,'updated_at':l};await this['deps']['store']['create'](b,o);const p=[],q=playbookForGoalType(d);if(q['name']!==GENERIC_PLAYBOOK||a['create_process']===!![])try{const u=newProcessId(),v=join(this['deps']['processes']['rootDir'](),u),w=new Date(l)['toISOString']();this['deps']['processes']['initProcess'](v,{'schema_version':PROCESS_SCHEMA_VERSION,'mcp_version':'unknown','process_id':u,'playbook':q['name'],'goal_id':o['id'],'title':o['title'],'network':b,'objects':[],'created_at':w,'updated_at':w,'archived':![]},q['stages']),o['process']={'id':u,'playbook':q['name'],'dir':v},o['process_ref']=u,await this['deps']['store']['save'](b,o);}catch(x){p['push']('process\x20creation\x20failed\x20(goal\x20kept\x20without\x20process):\x20'+(x instanceof Error?x['message']:String(x)));}return{'goal':o,'adopted':![],'classification':f,...p['length']?{'warnings':p}:{}};}async['preflightAccount'](a){const b=[];let c;try{const d=await this['deps']['listLocalAccounts']();c=d['find'](f=>f['address']===a||f['name']===a);}catch(f){b['push']('local\x20account\x20lookup\x20failed:\x20'+(f instanceof Error?f['message']:String(f)));}if(c){if(c['address']!==a)b['push']('resolved\x20\x27'+a+'\x27\x20to\x20'+c['address']);}else b['push']('account\x20\x27'+a+'\x27\x20not\x20found\x20among\x20local\x20accounts');return{'account_found':Boolean(c),'notes':b};}async['approve'](a,b,c){const d=await this['mustGet'](a,b);if(isTerminalStage(d['stage']))throw new Error('goal\x20'+b+'\x20is\x20terminal\x20('+d['stage']+')');const e={'id':newApprovalId(),'approved_at':Date['now'](),'scope':'plan','covers_levels':[...PLAN_APPROVAL_COVERS_LEVELS],...c?{'note':c}:{}};d['approvals']['push'](e),registerPlanApproval(d['id']);const f=stageIndex(d['stage']);if(f>=0x0&&f<stageIndex('approved'))d['stage']='approved';return d['updated_at']=Date['now'](),this['deps']['store']['save'](a,d);}async['bind'](a,b,c,d){const e=await this['mustGet'](a,b);if(isTerminalStage(e['stage']))throw new Error('goal\x20'+b+'\x20is\x20terminal\x20('+e['stage']+')');if(!c?.['trim']())throw new Error('bind\x20requires\x20a\x20non-empty\x20account');const f=await this['preflightAccount'](c['trim']());e['binding']={'account':c['trim'](),...d?.['trim']()?{'persona':d['trim']()}:{},'preflight':f};const g=stageIndex(e['stage']);if(g>=0x0&&g<stageIndex('bound'))e['stage']='bound';return e['updated_at']=Date['now'](),this['deps']['store']['save'](a,e);}async['advance'](a,b,c={}){const d=await this['mustGet'](a,b);if(isTerminalStage(d['stage']))throw new Error('goal\x20'+b+'\x20is\x20terminal\x20('+d['stage']+')');const e=[];for(const g of c['objects']??[]){const h=d['objects']['some'](i=>i['type']===g['type']&&i['object']['toLowerCase']()===g['object']['toLowerCase']());!h&&(d['objects']['push']({'type':g['type'],'object':g['object']}),e['push']({'type':g['type'],'object':g['object']}));}const f=c['stage'];if(f){this['assertTransition'](d['stage'],f);const i=f==='monitoring'&&d['stage']!=='monitoring';d['stage']=f,d['updated_at']=Date['now']();if(i)await this['autoBindMonitor'](a,d);if(i)this['emitProcessEvent'](d,'goal_monitoring','goal\x20entered\x20monitoring');}else{if((c['objects']??[])['length']===0x0)throw new Error('advance\x20requires\x20a\x20target\x20stage\x20and/or\x20objects');}return e['length']>0x0&&d['process']&&this['registerProcessObjects'](d,e),d['updated_at']=Date['now'](),this['deps']['store']['save'](a,d);}async['registerActObjects'](a,b,c='default'){if(b['length']===0x0)return 0x0;try{let d=c,e=await this['deps']['store']['get'](d,a);if(!e&&d!=='default'){e=await this['deps']['store']['get']('default',a);if(e)d='default';}if(!e||isTerminalStage(e['stage']))return 0x0;const f=e['objects']['length'],g=await this['advance'](d,a,{'objects':b});return g['objects']['length']-f;}catch{return 0x0;}}async['recordCommunicationEvidence'](a,b,c='default'){try{let d=await this['deps']['store']['get'](c,a);!d&&c!=='default'&&(d=await this['deps']['store']['get']('default',a));if(!d||isTerminalStage(d['stage'])||!d['process'])return![];return this['deps']['processes']['appendEvent'](d['process']['dir'],{'timestamp':new Date()['toISOString'](),'event':'communication_evidence','reason':''+b['title'],'data':{'operation':b['operation'],'kind':b['kind'],...b['detail']?{'detail':b['detail']}:{},...b['data']??{}}}),!![];}catch{return![];}}['registerProcessObjects'](a,b){try{const c=a['process']['dir'],d=this['deps']['processes']['loadManifest'](c);for(const e of b){const f=d['objects']['some'](g=>g['type']===e['type']&&g['object']['toLowerCase']()===e['object']['toLowerCase']());if(!f)d['objects']['push']({'type':e['type'],'object':e['object']});}this['deps']['processes']['saveManifest'](c,d),this['deps']['processes']['appendEvent'](c,{'timestamp':new Date()['toISOString'](),'event':'objects_registered','reason':b['length']+'\x20object(s)\x20registered\x20by\x20goal\x20'+a['id'],'data':{'added':b['map'](g=>g['type']+':'+g['object'])}});}catch{}}['emitProcessEvent'](a,b,c,d){if(!a['process'])return;try{this['deps']['processes']['appendEvent'](a['process']['dir'],{'timestamp':new Date()['toISOString'](),'event':b,'reason':c,...d?{'data':d}:{}});}catch{}}['distillOutcome'](a,b){try{const c={'playbook':a['process']?.['playbook'],'objects_count':a['objects']['length']};if(a['process']){const d=this['deps']['processes']['loadStageState'](a['process']['dir']),e=d?.['stages']['filter'](h=>d['stage_meta'][h]?.['committed'])['length'];if(e!==undefined)c['stages_completed']=e;const f=this['deps']['processes']['listProblems'](a['process']['dir']),g=this['deps']['processes']['listFeedback'](a['process']['dir']);c['problems_open']=f['filter'](h=>h['status']==='open')['length'],c['problems_resolved']=f['filter'](h=>h['status']==='resolved')['length'],c['feedback_positive']=g['filter'](h=>h['sentiment']==='positive')['length'],c['feedback_negative']=g['filter'](h=>h['sentiment']==='negative')['length'];}this['deps']['recordSignature']({'intent':a['goal_type'],'signals':c,'timestamp':Date['now'](),'outcome':b});}catch{}}['assertTransition'](a,b){if(isTerminalStage(a))throw new Error('goal\x20is\x20terminal\x20('+a+')');if(b==='abandoned')throw new Error('use\x20the\x20abandon\x20action\x20to\x20abandon\x20a\x20goal');if(b==='paused')return;if(a==='paused')return;if(b===a)return;const c=stageIndex(a),d=stageIndex(b);if(d<0x0||c<0x0||d<c)throw new Error('invalid\x20stage\x20transition:\x20'+a+'\x20→\x20'+b+'\x20(forward-only\x20along\x20'+'recognized→confirmed→bound→planned→approved→acting→monitoring→completed'+')');}async['pause'](a,b){return this['advance'](a,b,{'stage':'paused'});}async['autoBindMonitor'](a,b){const c=await this['deps']['subscriptionStore']['getConfig'](a),d=c['scope']['focus_objects']['map'](g=>({...g})),e=Date['now']();for(const f of b['objects']){const g=d['some'](h=>h['object']===f['object']&&h['goal_id']===b['id']);if(g)continue;d['push']({'object':f['object'],'added_at':e,'reason':'goal','closure':!![],'goal_id':b['id'],'note':b['title']});if(!b['monitor']['focus_ids']['includes'](f['object']))b['monitor']['focus_ids']['push'](f['object']);}await this['deps']['subscriptionStore']['saveConfig'](a,{'scope':{...c['scope'],'focus_objects':d}});if((b['goal_type']==='capture_demand'||b['goal_type']==='publish_demand')&&b['monitor']['intent_ids']['length']===0x0){const h=await this['deps']['createIntent']({'intent':b['intent_text'],'account':b['binding']?.['account']});b['monitor']['intent_ids']['push'](h['id']);}}async['complete'](a,b,c={}){const d=await this['mustGet'](a,b);if(isTerminalStage(d['stage']))throw new Error('goal\x20'+b+'\x20is\x20terminal\x20('+d['stage']+')');const e=await this['deps']['evaluateCompletion'](d,a),f=c['force']===!![];if(!e['complete']&&!f)return{'goal':d,'completed':![],'verify_report':e};const g=await this['teardown'](a,d);d['stage']='completed',d['outcome']={'success':e['complete']||f,'completed_at':Date['now'](),'verify_report':e,...!e['complete']&&f?{'forced':!![]}:{}},d['updated_at']=Date['now']();if(d['process']){if(c['feedback'])try{this['deps']['processes']['addFeedback'](d['process']['dir'],{'source':'user','sentiment':c['feedback']['sentiment'],'comment':c['feedback']['comment']});}catch{g['push']('feedback\x20recording\x20failed');}this['emitProcessEvent'](d,'goal_completed','goal\x20completed\x20('+d['title']+')');}this['distillOutcome'](d,'success');const h=await this['deps']['store']['save'](a,d);return{'goal':h,'completed':!![],'verify_report':e,'teardown_notes':g['length']?g:undefined};}async['abandon'](a,b,c){const d=await this['mustGet'](a,b);if(isTerminalStage(d['stage']))throw new Error('goal\x20'+b+'\x20is\x20already\x20terminal\x20('+d['stage']+')');const e=await this['teardown'](a,d);d['stage']='abandoned',d['outcome']={'success':![],'completed_at':Date['now'](),...c?{'verify_report':{'reason':c}}:{}},d['updated_at']=Date['now'](),this['emitProcessEvent'](d,'goal_abandoned',c??'goal\x20abandoned'),this['distillOutcome'](d,'failed');const f=await this['deps']['store']['save'](a,d);return{'goal':f,'teardown_notes':e['length']?e:undefined};}async['remove'](a,b,c={}){const d=await this['mustGet'](a,b);let e;if(!isTerminalStage(d['stage'])){if(c['force']!==!![])throw new Error('goal\x20'+b+'\x20is\x20not\x20terminal\x20('+d['stage']+')\x20—\x20complete/abandon\x20it\x20first,\x20or\x20pass\x20force=true');await this['teardown'](a,d),e=!![];}let f;if(d['process'])try{this['deps']['processes']['removeDir'](d['process']['dir']),f=!![];}catch{f=![];}const g=await this['deps']['store']['remove'](a,b);return{'deleted':g,...e!==undefined?{'tore_down_active':e}:{},...f!==undefined?{'process_removed':f}:{}};}async['teardown'](a,b){const c=[];try{const d=await this['deps']['subscriptionStore']['getConfig'](a),f=d['scope']['focus_objects']['filter'](g=>g['goal_id']!==b['id']);f['length']!==d['scope']['focus_objects']['length']&&await this['deps']['subscriptionStore']['saveConfig'](a,{'scope':{...d['scope'],'focus_objects':f}});}catch(g){c['push']('focus\x20teardown\x20failed:\x20'+(g instanceof Error?g['message']:String(g)));}revokePlanApproval(b['id']);for(const h of b['monitor']['intent_ids']){try{await this['deps']['removeIntent'](h);}catch(i){c['push']('intent\x20teardown\x20failed\x20('+h+'):\x20'+(i instanceof Error?i['message']:String(i)));}}return c;}async['get'](a,b){const c=await this['mustGet'](a,b);if(!c['process'])return c;try{return{...c,'process_summary':this['summarizeProcess'](c['process']['dir'],c['process']['id'],c['process']['playbook'])};}catch{return c;}}['summarizeProcess'](a,b,c){const d=this['deps']['processes']['loadStageState'](a),e=this['deps']['processes']['listProblems'](a,{'status':'open'}),f={'critical':0x0,'high':0x1,'medium':0x2,'low':0x3},g=[...e]['sort']((i,j)=>f[i['severity']]-f[j['severity']])['slice'](0x0,0x3)['map'](i=>i['title']),h=this['deps']['processes']['listSuggestions'](a,{'status':'pending'});return{'id':b,'playbook':c,'current_stage':d?.['current_stage']??'unknown','stages':(d?.['stages']??[])['map'](i=>({'name':i,'committed':d?.['stage_meta'][i]?.['committed']??![],'completion':d?.['stage_meta'][i]?.['completion']??0x0})),'open_problems':{'count':e['length'],'top':g},'pending_suggestions':{'count':h['length'],'top':h['slice'](0x0,0x3)['map'](i=>i['title'])},'last_events':this['deps']['processes']['readEvents'](a)['slice'](-0x5),'feedback_count':this['deps']['processes']['listFeedback'](a)['length']};}async['listSuggestions'](a,b,c={}){const d=await this['mustGet'](a,b);if(!d['process'])return{'goal':d,'suggestions':[],'open_problems':[]};const e=this['deps']['processes']['listSuggestions'](d['process']['dir']),f=c['include_resolved']?e:e['filter'](h=>h['status']==='pending'),g=this['deps']['processes']['listProblems'](d['process']['dir'],{'status':'open'});return{'goal':d,'suggestions':f,'open_problems':g};}async['resolveSuggestion'](a,b,c,d){const f=await this['mustGet'](a,b);if(!f['process'])throw new Error('goal\x20'+b+'\x20has\x20no\x20TaskProcess\x20(no\x20suggestion\x20stream)');const g=f['process']['dir'],h=this['deps']['processes']['listSuggestions'](g)['find'](n=>n['id']===c);if(!h)throw new Error('suggestion\x20not\x20found:\x20'+c);if(h['status']!=='pending')throw new Error('suggestion\x20'+c+'\x20already\x20resolved\x20('+h['status']+')');if(d['decision']==='dismiss'){const n=this['deps']['processes']['updateSuggestion'](g,c,{'status':'dismissed',...d['note']?{'resolution_note':d['note']}:{}});return this['emitSuggestionEvent'](f,'suggestion_dismissed',h,d['note']),{'goal':f,'suggestion':n,'applied':![]};}if(d['apply']!==!![]){const o=this['deps']['processes']['updateSuggestion'](g,c,{'status':'confirmed',...d['note']?{'resolution_note':d['note']}:{}});return this['emitSuggestionEvent'](f,'suggestion_confirmed',h,d['note']),{'goal':f,'suggestion':o,'applied':![]};}let i,j,k=![];if(h['kind']==='advance_stage'&&h['stage'])try{await this['advance'](a,b,{'stage':h['stage']}),k=!![];}catch(p){i=p instanceof Error?p['message']:String(p);}else{if(h['kind']==='complete_goal')try{const q=await this['complete'](a,b,{});j=q['verify_report'],q['completed']?k=!![]:i='completion\x20conditions\x20unmet:\x20'+(q['verify_report']['missing']['join'](';\x20')||'no\x20evidence');}catch(r){i=r instanceof Error?r['message']:String(r);}else{if(h['kind']==='register_object'&&h['objects']?.['length'])try{await this['advance'](a,b,{'objects':h['objects']}),k=!![];}catch(s){i=s instanceof Error?s['message']:String(s);}else k=!![];}}if(i){const t=await this['mustGet'](a,b);return{'goal':t,'suggestion':h,'applied':![],'apply_error':i};}const l=this['deps']['processes']['updateSuggestion'](g,c,{'status':'confirmed','applied':!![],...d['note']?{'resolution_note':d['note']}:{}});this['emitSuggestionEvent'](f,'suggestion_applied',h,d['note']);const m=await this['mustGet'](a,b);return{'goal':m,'suggestion':l,'applied':!![],...j?{'complete_report':j}:{}};}async['boundariesView'](a,c){const d=await this['mustGet'](a,c),e=goalBoundaryQuestions(d['goal_type']),f=d['boundaries'],g=[];if(!f?.['budget'])g['push']('budget');if(!f?.['deadline'])g['push']('deadline');if(!f?.['requirements']?.['length'])g['push']('requirements');if(!f?.['autonomy'])g['push']('autonomy');return{'goal':d,...f?{'boundaries':f}:{},'questions':e,'missing':g};}async['setBoundaries'](a,b,c){const d=await this['mustGet'](a,b);if(isTerminalStage(d['stage']))throw new Error('goal\x20'+b+'\x20is\x20terminal\x20('+d['stage']+')');const e={};if(c['budget']!==undefined){if(!/^\d+$/['test'](c['budget']))throw new Error('boundaries.budget\x20must\x20be\x20a\x20non-negative\x20integer\x20decimal\x20string\x20(smallest\x20on-chain\x20unit)');e['budget']=c['budget'];}if(c['deadline']!==undefined){if(!Number['isFinite'](c['deadline'])||c['deadline']<=0x0)throw new Error('boundaries.deadline\x20must\x20be\x20a\x20positive\x20ms-epoch\x20timestamp');e['deadline']=c['deadline'];}if(c['requirements']!==undefined){const h=c['requirements']['map'](i=>i['trim']())['filter'](i=>i['length']>0x0);if(h['length']!==c['requirements']['length'])throw new Error('boundaries.requirements\x20must\x20be\x20non-empty\x20strings');e['requirements']=h;}if(c['autonomy']!==undefined){if(!GOAL_AUTONOMY_LEVELS['includes'](c['autonomy']))throw new Error('boundaries.autonomy\x20must\x20be\x20one\x20of:\x20'+GOAL_AUTONOMY_LEVELS['join']('\x20|\x20'));e['autonomy']=c['autonomy'];}const f=d['boundaries']??{'autonomy':'confirm_all'};d['boundaries']={...f,...e,'confirmed_at':Date['now']()};const g=stageIndex(d['stage']);if(g>=0x0&&g<stageIndex('confirmed'))d['stage']='confirmed';return d['updated_at']=Date['now'](),this['emitProcessEvent'](d,'boundaries_confirmed','goal\x20boundaries\x20set\x20(autonomy\x20'+d['boundaries']['autonomy']+')'),this['deps']['store']['save'](a,d);}async['pursue'](a,b){const d=await this['mustGet'](a,b);if(isTerminalStage(d['stage']))throw new Error('goal\x20'+b+'\x20is\x20terminal\x20('+d['stage']+')');const f=[];if(d['stage']==='paused')return f['push']('goal\x20is\x20paused\x20(the\x20user\x27s\x20explicit\x20hold)\x20—\x20nothing\x20pursued\x20this\x20tick'),{'action':'wait','items':[],'applied':[],'authorized':[],'boundary_status':{'autonomy':d['boundaries']?.['autonomy']??'unset',...d['boundaries']?.['budget']!==undefined?{'budget':d['boundaries']['budget']}:{},...d['boundaries']?.['deadline']!==undefined?{'deadline':d['boundaries']['deadline']}:{},...d['boundaries']?.['requirements']?.['length']?{'requirements':d['boundaries']['requirements']}:{}},'notes':f};const g=[];if(d['process']){const l=this['deps']['processes']['listSuggestions'](d['process']['dir'],{'status':'pending'});for(const m of l){g['push']({'id':m['id'],'kind':m['kind'],...m['stage']?{'stage':m['stage']}:{},...m['objects']?.['length']?{'objects':m['objects']}:{},'title':m['title'],...m['detail']?{'detail':m['detail']}:{},'risk':m['kind']==='incentive'?'high':m['kind']==='advance_stage'||m['kind']==='register_object'||m['kind']==='complete_goal'||m['kind']==='note'?'none':'low','suggestion_id':m['id'],...m['origin']?{'origin':m['origin']}:{}});}}const h=g['some'](n=>n['kind']==='complete_goal');!h&&d['stage']==='monitoring'&&g['push']({'id':'engine:complete-check','kind':'complete_goal','title':'Verify\x20completion\x20conditions\x20on\x20chain','detail':'The\x20engine\x20re-checks\x20the\x20goal-type\x20completion\x20conjunction;\x20completion\x20only\x20lands\x20when\x20chain\x20conditions\x20hold.','risk':'none','origin':{'source':'engine'}});const i=pursueTick(d,g,Date['now']());f['push'](...i['notes']);const j=[],k=[];for(const n of i['items']){if(n['action']!=='execute'){const p=g['find'](q=>q['id']===n['candidate_id']);if(n['action']==='ask_user'&&p&&!p['suggestion_id']&&d['process'])try{this['deps']['processes']['addSuggestion'](d['process']['dir'],{'kind':p['kind'],...p['stage']?{'stage':p['stage']}:{},'title':p['title'],...p['detail']?{'detail':p['detail']+'\x20(pursue:\x20'+n['reason']+')'}:{'detail':n['reason']}});}catch{f['push']('ask_user\x20suggestion\x20could\x20not\x20be\x20recorded\x20for\x20\x27'+p['title']+'\x27');}continue;}const o=g['find'](q=>q['id']===n['candidate_id']);if(!o)continue;if(o['kind']==='onchain_operation'){k['push']({'candidate_id':o['id'],'title':o['title'],'reason':n['reason']});continue;}if(o['suggestion_id'])try{const q=await this['resolveSuggestion'](a,b,o['suggestion_id'],{'decision':'confirm','apply':!![]});j['push']({'candidate_id':o['id'],'outcome':q['applied']?'applied\x20(suggestion\x20confirmed)':'not\x20applied:\x20'+(q['apply_error']??'unknown')});}catch(r){j['push']({'candidate_id':o['id'],'outcome':'failed:\x20'+(r instanceof Error?r['message']:String(r))});}else{if(o['id']==='engine:complete-check')try{const t=await this['complete'](a,b,{});t['completed']?j['push']({'candidate_id':o['id'],'outcome':'goal\x20completed\x20(chain\x20conditions\x20verified)'}):j['push']({'candidate_id':o['id'],'outcome':'conditions\x20unmet\x20—\x20keep\x20waiting:\x20'+(t['verify_report']['missing']['join'](';\x20')||'no\x20evidence\x20yet')});}catch(u){j['push']({'candidate_id':o['id'],'outcome':'completion\x20check\x20failed:\x20'+(u instanceof Error?u['message']:String(u))});}}}return this['emitProcessEvent'](d,'pursue_tick','pursue\x20tick:\x20'+i['action']+'\x20('+i['items']['length']+'\x20candidate(s),\x20'+j['length']+'\x20applied)',{'data':{'action':i['action'],'items':i['items']['map'](v=>({'candidate_id':v['candidate_id'],'action':v['action']})),'applied':j['map'](v=>v['candidate_id'])}}),{'action':i['action'],'items':i['items'],'applied':j,'authorized':k,'boundary_status':i['boundary_status'],'notes':f};}async['nextSteps'](a,b){const c=await this['mustGet'](a,b);let d;if(c['process'])try{const e=this['deps']['processes']['listSuggestions'](c['process']['dir'],{'status':'pending'}),f=this['deps']['processes']['listProblems'](c['process']['dir'],{'status':'open'});d={'pending_suggestions':{'count':e['length'],'top':e['slice'](0x0,0x3)['map'](g=>g['title'])},'open_problems':{'count':f['length'],'top':f['slice'](0x0,0x3)['map'](g=>g['title'])}};}catch{d=undefined;}return{'goal':c,'steps':nextStepsForGoal(c,d)};}['emitSuggestionEvent'](a,b,c,d){if(!a['process'])return;try{this['deps']['processes']['appendEvent'](a['process']['dir'],{'timestamp':new Date()['toISOString'](),'event':b,'reason':c['kind']+'\x20\x27'+c['title']+'\x27\x20('+c['id']+')','data':{'suggestion_id':c['id'],'kind':c['kind'],...c['stage']?{'stage':c['stage']}:{},...d?{'note':d}:{}}});}catch{}}async['list'](a,b={}){const [c,d]=await Promise['all']([this['deps']['store']['list'](a,b),this['deps']['store']['counts'](a)]);return{'goals':c,'counts':d};}async['mustGet'](a,b){const c=await this['deps']['store']['get'](a,b);if(!c)throw new Error('goal\x20not\x20found:\x20'+b);return c;}}export const goalEngine=new GoalEngine({'store':goalStore,'subscriptionStore':subscriptionStore,'createIntent':createIntent,'removeIntent':removeIntent,'listLocalAccounts':listLocalAccounts,'evaluateCompletion':(a,b)=>evaluateGoalCompletion(a,b),'processes':{'rootDir':processesRootDir,'initProcess':initProcess,'loadManifest':loadManifest,'saveManifest':saveManifest,'loadStageState':loadStageState,'appendEvent':appendEvent,'addFeedback':addFeedback,'listProblems':listProblems,'listFeedback':listFeedback,'readEvents':readEvents,'addSuggestion':addSuggestion,'updateSuggestion':updateSuggestion,'listSuggestions':listSuggestions,'removeDir':deleteProcessDir},'recordSignature':recordSignature});
1
+ import{classifyGoal}from'./GoalClassifier.js';import{goalStore}from'./GoalStore.js';import{GOAL_AUTONOMY_LEVELS,isTerminalStage,newGoalId,stageIndex}from'./types.js';import{goalBoundaryQuestions,pursueTick}from'./pursue.js';import{nextStepsForGoal}from'./next-steps.js';import{GENERIC_PLAYBOOK,playbookForGoalType}from'../task/playbook.js';import{PROCESS_SCHEMA_VERSION,newProcessId}from'../task/types.js';import{addFeedback,addSuggestion,appendEvent,deleteProcessDir,initProcess,listFeedback,listProblems,listSuggestions,loadManifest,loadStageState,processesRootDir,readEvents,saveManifest,updateSuggestion}from'../task/ProcessStore.js';import{recordSignature}from'../experience/index.js';import{join}from'path';import{registerPlanApproval,revokePlanApproval}from'./plan-approval.js';import{subscriptionStore}from'../monitor/SubscriptionStore.js';import{createIntent,removeIntent}from'../intent/index.js';import{listLocalAccounts}from'../knowledge/workflow-guidance.js';import{evaluateGoalCompletion}from'../knowledge/goal-completion.js';export const GOAL_PLAYBOOKS={'publish_service':'wowok-provider','fulfill_order':'wowok-provider','capture_demand':'wowok-market','purchase_service':'wowok-order','collaborate_flow':'wowok-collaborator','supply_suborder':'wowok-supplier','publish_demand':'wowok-order','run_arbitration':'wowok-arbitrator','dispute_resolution':'wowok-order','manage_assets':'wowok-governance'};export const PLAN_APPROVAL_COVERS_LEVELS=['standard','none'];export const ADOPT_JACCARD_THRESHOLD=0.6;export function tokenizeIntent(a){const b=new Set(),c=(a??'')['toLowerCase']();for(const d of c['matchAll'](/[a-z0-9]+/g))b['add'](d[0x0]);for(const e of c['matchAll'](/[\u3400-\u9fff\uf900-\ufaff]/g))b['add'](e[0x0]);return b;}export function jaccard(c,d){if(c['size']===0x0||d['size']===0x0)return 0x0;let e=0x0;for(const f of c)if(d['has'](f))e++;return e/(c['size']+d['size']-e);}function deriveTitle(a){const b=(intent_text_first_line(a)||'Untitled\x20goal')['trim']();return b['length']>0x3c?b['slice'](0x0,0x39)+'…':b;}function intent_text_first_line(a){return(a??'')['split'](/\r?\n/,0x1)[0x0]??'';}function newApprovalId(){return'appr_'+Date['now']()['toString'](0x24)+Math['random']()['toString'](0x24)['slice'](0x2,0x8);}export class GoalEngine{['deps'];constructor(a){this['deps']=a;}async['createOrAdopt'](a){const b=a['network']??'default',c=(a['intent_text']??'')['trim']();if(!c)throw new Error('create_or_adopt\x20requires\x20non-empty\x20intent_text');let d=a['goal_type'],f;if(!d){f=classifyGoal(c),d=f['goal_type']??undefined;if(!d)return{'adopted':![],'classification':f,'needs_type':!![]};}const h=await this['deps']['store']['list'](b),i=a['account']??'',j=tokenizeIntent(c);let k;for(const r of h){if(isTerminalStage(r['stage']))continue;if(r['goal_type']!==d)continue;if((r['binding']?.['account']??'')!==i)continue;const s=jaccard(j,tokenizeIntent(r['intent_text']));s>=ADOPT_JACCARD_THRESHOLD&&(!k||s>k['sim'])&&(k={'goal':r,'sim':s});}if(k)return{'goal':k['goal'],'adopted':!![],'classification':f};const l=Date['now']();let m,n='recognized';if(a['account']){const t=await this['preflightAccount'](a['account']);m={'account':a['account'],'persona':a['persona'],'preflight':t},n='bound';}const o={'id':newGoalId(),'goal_type':d,'title':a['title']?.['trim']()||deriveTitle(c),'intent_text':c,...a['conversation_id']?{'conversation_id':a['conversation_id']}:{},'binding':m,'objects':[],'monitor':{'focus_ids':[],'intent_ids':[]},'stage':n,'playbook':GOAL_PLAYBOOKS[d],'approvals':[],'created_at':l,'updated_at':l};await this['deps']['store']['create'](b,o);const p=[],q=playbookForGoalType(d);if(q['name']!==GENERIC_PLAYBOOK||a['create_process']===!![])try{const u=newProcessId(),v=join(this['deps']['processes']['rootDir'](),u),w=new Date(l)['toISOString']();this['deps']['processes']['initProcess'](v,{'schema_version':PROCESS_SCHEMA_VERSION,'mcp_version':'unknown','process_id':u,'playbook':q['name'],'goal_id':o['id'],'title':o['title'],'network':b,'objects':[],'created_at':w,'updated_at':w,'archived':![]},q['stages']),o['process']={'id':u,'playbook':q['name'],'dir':v},o['process_ref']=u,await this['deps']['store']['save'](b,o);}catch(x){p['push']('process\x20creation\x20failed\x20(goal\x20kept\x20without\x20process):\x20'+(x instanceof Error?x['message']:String(x)));}return{'goal':o,'adopted':![],'classification':f,...p['length']?{'warnings':p}:{}};}async['preflightAccount'](a){const b=[];let c;try{const d=await this['deps']['listLocalAccounts']();c=d['find'](f=>f['address']===a||f['name']===a);}catch(f){b['push']('local\x20account\x20lookup\x20failed:\x20'+(f instanceof Error?f['message']:String(f)));}if(c){if(c['address']!==a)b['push']('resolved\x20\x27'+a+'\x27\x20to\x20'+c['address']);}else b['push']('account\x20\x27'+a+'\x27\x20not\x20found\x20among\x20local\x20accounts');return{'account_found':Boolean(c),'notes':b};}async['approve'](a,b,c){const d=await this['mustGet'](a,b);if(isTerminalStage(d['stage']))throw new Error('goal\x20'+b+'\x20is\x20terminal\x20('+d['stage']+')');const e={'id':newApprovalId(),'approved_at':Date['now'](),'scope':'plan','covers_levels':[...PLAN_APPROVAL_COVERS_LEVELS],...c?{'note':c}:{}};d['approvals']['push'](e),registerPlanApproval(d['id']);const f=stageIndex(d['stage']);if(f>=0x0&&f<stageIndex('approved'))d['stage']='approved';return d['updated_at']=Date['now'](),this['deps']['store']['save'](a,d);}async['bind'](a,b,c,d){const e=await this['mustGet'](a,b);if(isTerminalStage(e['stage']))throw new Error('goal\x20'+b+'\x20is\x20terminal\x20('+e['stage']+')');if(!c?.['trim']())throw new Error('bind\x20requires\x20a\x20non-empty\x20account');const f=await this['preflightAccount'](c['trim']());e['binding']={'account':c['trim'](),...d?.['trim']()?{'persona':d['trim']()}:{},'preflight':f};const g=stageIndex(e['stage']);if(g>=0x0&&g<stageIndex('bound'))e['stage']='bound';return e['updated_at']=Date['now'](),this['deps']['store']['save'](a,e);}async['advance'](a,b,c={}){const d=await this['mustGet'](a,b);if(isTerminalStage(d['stage']))throw new Error('goal\x20'+b+'\x20is\x20terminal\x20('+d['stage']+')');const e=[];for(const g of c['objects']??[]){const h=d['objects']['some'](i=>i['type']===g['type']&&i['object']['toLowerCase']()===g['object']['toLowerCase']());!h&&(d['objects']['push']({'type':g['type'],'object':g['object']}),e['push']({'type':g['type'],'object':g['object']}));}const f=c['stage'];if(f){this['assertTransition'](d['stage'],f);const i=f==='monitoring'&&d['stage']!=='monitoring';d['stage']=f,d['updated_at']=Date['now']();if(i)await this['autoBindMonitor'](a,d);if(i)this['emitProcessEvent'](d,'goal_monitoring','goal\x20entered\x20monitoring');}else{if((c['objects']??[])['length']===0x0)throw new Error('advance\x20requires\x20a\x20target\x20stage\x20and/or\x20objects');}return e['length']>0x0&&d['process']&&this['registerProcessObjects'](d,e),d['updated_at']=Date['now'](),this['deps']['store']['save'](a,d);}async['registerActObjects'](a,b,c='default'){if(b['length']===0x0)return 0x0;try{let d=c,e=await this['deps']['store']['get'](d,a);if(!e&&d!=='default'){e=await this['deps']['store']['get']('default',a);if(e)d='default';}if(!e||isTerminalStage(e['stage']))return 0x0;const f=e['objects']['length'],g=await this['advance'](d,a,{'objects':b});return g['objects']['length']-f;}catch{return 0x0;}}async['recordCommunicationEvidence'](a,b,c='default'){try{let d=await this['deps']['store']['get'](c,a);!d&&c!=='default'&&(d=await this['deps']['store']['get']('default',a));if(!d||isTerminalStage(d['stage'])||!d['process'])return![];return this['deps']['processes']['appendEvent'](d['process']['dir'],{'timestamp':new Date()['toISOString'](),'event':'communication_evidence','reason':''+b['title'],'data':{'operation':b['operation'],'kind':b['kind'],...b['detail']?{'detail':b['detail']}:{},...b['data']??{}}}),!![];}catch{return![];}}['registerProcessObjects'](a,b){try{const c=a['process']['dir'],d=this['deps']['processes']['loadManifest'](c);for(const e of b){const f=d['objects']['some'](g=>g['type']===e['type']&&g['object']['toLowerCase']()===e['object']['toLowerCase']());if(!f)d['objects']['push']({'type':e['type'],'object':e['object']});}this['deps']['processes']['saveManifest'](c,d),this['deps']['processes']['appendEvent'](c,{'timestamp':new Date()['toISOString'](),'event':'objects_registered','reason':b['length']+'\x20object(s)\x20registered\x20by\x20goal\x20'+a['id'],'data':{'added':b['map'](g=>g['type']+':'+g['object'])}});}catch{}}['emitProcessEvent'](a,b,c,d){if(!a['process'])return;try{this['deps']['processes']['appendEvent'](a['process']['dir'],{'timestamp':new Date()['toISOString'](),'event':b,'reason':c,...d?{'data':d}:{}});}catch{}}['distillOutcome'](a,b){try{const c={'playbook':a['process']?.['playbook'],'objects_count':a['objects']['length']};if(a['process']){const d=this['deps']['processes']['loadStageState'](a['process']['dir']),e=d?.['stages']['filter'](h=>d['stage_meta'][h]?.['committed'])['length'];if(e!==undefined)c['stages_completed']=e;const f=this['deps']['processes']['listProblems'](a['process']['dir']),g=this['deps']['processes']['listFeedback'](a['process']['dir']);c['problems_open']=f['filter'](h=>h['status']==='open')['length'],c['problems_resolved']=f['filter'](h=>h['status']==='resolved')['length'],c['feedback_positive']=g['filter'](h=>h['sentiment']==='positive')['length'],c['feedback_negative']=g['filter'](h=>h['sentiment']==='negative')['length'];}this['deps']['recordSignature']({'intent':a['goal_type'],'signals':c,'timestamp':Date['now'](),'outcome':b});}catch{}}['assertTransition'](a,b){if(isTerminalStage(a))throw new Error('goal\x20is\x20terminal\x20('+a+')');if(b==='abandoned')throw new Error('use\x20the\x20abandon\x20action\x20to\x20abandon\x20a\x20goal');if(b==='paused')return;if(a==='paused')return;if(b===a)return;const c=stageIndex(a),d=stageIndex(b);if(d<0x0||c<0x0||d<c)throw new Error('invalid\x20stage\x20transition:\x20'+a+'\x20→\x20'+b+'\x20(forward-only\x20along\x20'+'recognized→confirmed→bound→planned→approved→acting→monitoring→completed'+')');}async['pause'](a,b){return this['advance'](a,b,{'stage':'paused'});}async['autoBindMonitor'](a,b){const c=await this['deps']['subscriptionStore']['getConfig'](a),d=c['scope']['focus_objects']['map'](g=>({...g})),e=Date['now']();for(const f of b['objects']){const g=d['some'](h=>h['object']===f['object']&&h['goal_id']===b['id']);if(g)continue;d['push']({'object':f['object'],'added_at':e,'reason':'goal','closure':!![],'goal_id':b['id'],'note':b['title']});if(!b['monitor']['focus_ids']['includes'](f['object']))b['monitor']['focus_ids']['push'](f['object']);}await this['deps']['subscriptionStore']['saveConfig'](a,{'scope':{...c['scope'],'focus_objects':d}});if((b['goal_type']==='capture_demand'||b['goal_type']==='publish_demand')&&b['monitor']['intent_ids']['length']===0x0){const h=await this['deps']['createIntent']({'intent':b['intent_text'],'account':b['binding']?.['account']});b['monitor']['intent_ids']['push'](h['id']);}}async['complete'](a,b,c={}){const d=await this['mustGet'](a,b);if(isTerminalStage(d['stage']))throw new Error('goal\x20'+b+'\x20is\x20terminal\x20('+d['stage']+')');const e=await this['deps']['evaluateCompletion'](d,a),f=c['force']===!![];if(!e['complete']&&!f)return{'goal':d,'completed':![],'verify_report':e};const g=await this['teardown'](a,d);d['stage']='completed',d['outcome']={'success':e['complete']||f,'completed_at':Date['now'](),'verify_report':e,...!e['complete']&&f?{'forced':!![]}:{}},d['updated_at']=Date['now']();if(d['process']){if(c['feedback'])try{this['deps']['processes']['addFeedback'](d['process']['dir'],{'source':'user','sentiment':c['feedback']['sentiment'],'comment':c['feedback']['comment']});}catch{g['push']('feedback\x20recording\x20failed');}this['emitProcessEvent'](d,'goal_completed','goal\x20completed\x20('+d['title']+')');}this['distillOutcome'](d,'success');const h=await this['deps']['store']['save'](a,d);return{'goal':h,'completed':!![],'verify_report':e,'teardown_notes':g['length']?g:undefined};}async['abandon'](a,b,c){const d=await this['mustGet'](a,b);if(isTerminalStage(d['stage']))throw new Error('goal\x20'+b+'\x20is\x20already\x20terminal\x20('+d['stage']+')');const e=await this['teardown'](a,d);d['stage']='abandoned',d['outcome']={'success':![],'completed_at':Date['now'](),...c?{'verify_report':{'reason':c}}:{}},d['updated_at']=Date['now'](),this['emitProcessEvent'](d,'goal_abandoned',c??'goal\x20abandoned'),this['distillOutcome'](d,'failed');const f=await this['deps']['store']['save'](a,d);return{'goal':f,'teardown_notes':e['length']?e:undefined};}async['remove'](a,b,c={}){const d=await this['mustGet'](a,b);let e;if(!isTerminalStage(d['stage'])){if(c['force']!==!![])throw new Error('goal\x20'+b+'\x20is\x20not\x20terminal\x20('+d['stage']+')\x20—\x20complete/abandon\x20it\x20first,\x20or\x20pass\x20force=true');await this['teardown'](a,d),e=!![];}let f;if(d['process'])try{this['deps']['processes']['removeDir'](d['process']['dir']),f=!![];}catch{f=![];}const g=await this['deps']['store']['remove'](a,b);return{'deleted':g,...e!==undefined?{'tore_down_active':e}:{},...f!==undefined?{'process_removed':f}:{}};}async['teardown'](a,b){const c=[];try{const d=await this['deps']['subscriptionStore']['getConfig'](a),f=d['scope']['focus_objects']['filter'](g=>g['goal_id']!==b['id']);f['length']!==d['scope']['focus_objects']['length']&&await this['deps']['subscriptionStore']['saveConfig'](a,{'scope':{...d['scope'],'focus_objects':f}});}catch(g){c['push']('focus\x20teardown\x20failed:\x20'+(g instanceof Error?g['message']:String(g)));}revokePlanApproval(b['id']);for(const h of b['monitor']['intent_ids']){try{await this['deps']['removeIntent'](h);}catch(i){c['push']('intent\x20teardown\x20failed\x20('+h+'):\x20'+(i instanceof Error?i['message']:String(i)));}}return c;}async['get'](a,b){const c=await this['mustGet'](a,b);if(!c['process'])return c;try{return{...c,'process_summary':this['summarizeProcess'](c['process']['dir'],c['process']['id'],c['process']['playbook'])};}catch{return c;}}['summarizeProcess'](a,b,c){const d=this['deps']['processes']['loadStageState'](a),e=this['deps']['processes']['listProblems'](a,{'status':'open'}),f={'critical':0x0,'high':0x1,'medium':0x2,'low':0x3},g=[...e]['sort']((i,j)=>f[i['severity']]-f[j['severity']])['slice'](0x0,0x3)['map'](i=>i['title']),h=this['deps']['processes']['listSuggestions'](a,{'status':'pending'});return{'id':b,'playbook':c,'current_stage':d?.['current_stage']??'unknown','stages':(d?.['stages']??[])['map'](i=>({'name':i,'committed':d?.['stage_meta'][i]?.['committed']??![],'completion':d?.['stage_meta'][i]?.['completion']??0x0})),'open_problems':{'count':e['length'],'top':g},'pending_suggestions':{'count':h['length'],'top':h['slice'](0x0,0x3)['map'](i=>i['title'])},'last_events':this['deps']['processes']['readEvents'](a)['slice'](-0x5),'feedback_count':this['deps']['processes']['listFeedback'](a)['length']};}async['listSuggestions'](a,b,c={}){const d=await this['mustGet'](a,b);if(!d['process'])return{'goal':d,'suggestions':[],'open_problems':[]};const e=this['deps']['processes']['listSuggestions'](d['process']['dir']),f=c['include_resolved']?e:e['filter'](h=>h['status']==='pending'),g=this['deps']['processes']['listProblems'](d['process']['dir'],{'status':'open'});return{'goal':d,'suggestions':f,'open_problems':g};}async['resolveSuggestion'](a,b,c,d){const f=await this['mustGet'](a,b);if(!f['process'])throw new Error('goal\x20'+b+'\x20has\x20no\x20TaskProcess\x20(no\x20suggestion\x20stream)');const g=f['process']['dir'],h=this['deps']['processes']['listSuggestions'](g)['find'](m=>m['id']===c);if(!h)throw new Error('suggestion\x20not\x20found:\x20'+c);if(h['status']!=='pending')throw new Error('suggestion\x20'+c+'\x20already\x20resolved\x20('+h['status']+')');if(d['decision']==='dismiss'){const m=this['deps']['processes']['updateSuggestion'](g,c,{'status':'dismissed',...d['note']?{'resolution_note':d['note']}:{}});return this['emitSuggestionEvent'](f,'suggestion_dismissed',h,d['note']),{'goal':f,'suggestion':m,'applied':![]};}if(d['apply']!==!![]){const n=this['deps']['processes']['updateSuggestion'](g,c,{'status':'confirmed',...d['note']?{'resolution_note':d['note']}:{}});return this['emitSuggestionEvent'](f,'suggestion_confirmed',h,d['note']),{'goal':f,'suggestion':n,'applied':![]};}let i,j;if(h['kind']==='advance_stage'&&h['stage'])try{await this['advance'](a,b,{'stage':h['stage']});}catch(o){i=o instanceof Error?o['message']:String(o);}else{if(h['kind']==='complete_goal')try{const p=await this['complete'](a,b,{});j=p['verify_report'];if(p['completed']){}else i='completion\x20conditions\x20unmet:\x20'+(p['verify_report']['missing']['join'](';\x20')||'no\x20evidence');}catch(q){i=q instanceof Error?q['message']:String(q);}else{if(h['kind']==='register_object'&&h['objects']?.['length'])try{await this['advance'](a,b,{'objects':h['objects']});}catch(r){i=r instanceof Error?r['message']:String(r);}else{}}}if(i){const s=await this['mustGet'](a,b);return{'goal':s,'suggestion':h,'applied':![],'apply_error':i};}const k=this['deps']['processes']['updateSuggestion'](g,c,{'status':'confirmed','applied':!![],...d['note']?{'resolution_note':d['note']}:{}});this['emitSuggestionEvent'](f,'suggestion_applied',h,d['note']);const l=await this['mustGet'](a,b);return{'goal':l,'suggestion':k,'applied':!![],...j?{'complete_report':j}:{}};}async['boundariesView'](a,c){const d=await this['mustGet'](a,c),e=goalBoundaryQuestions(d['goal_type']),f=d['boundaries'],g=[];if(!f?.['budget'])g['push']('budget');if(!f?.['deadline'])g['push']('deadline');if(!f?.['requirements']?.['length'])g['push']('requirements');if(!f?.['autonomy'])g['push']('autonomy');return{'goal':d,...f?{'boundaries':f}:{},'questions':e,'missing':g};}async['setBoundaries'](a,b,c){const d=await this['mustGet'](a,b);if(isTerminalStage(d['stage']))throw new Error('goal\x20'+b+'\x20is\x20terminal\x20('+d['stage']+')');const e={};if(c['budget']!==undefined){if(!/^\d+$/['test'](c['budget']))throw new Error('boundaries.budget\x20must\x20be\x20a\x20non-negative\x20integer\x20decimal\x20string\x20(smallest\x20on-chain\x20unit)');e['budget']=c['budget'];}if(c['deadline']!==undefined){if(!Number['isFinite'](c['deadline'])||c['deadline']<=0x0)throw new Error('boundaries.deadline\x20must\x20be\x20a\x20positive\x20ms-epoch\x20timestamp');e['deadline']=c['deadline'];}if(c['requirements']!==undefined){const h=c['requirements']['map'](i=>i['trim']())['filter'](i=>i['length']>0x0);if(h['length']!==c['requirements']['length'])throw new Error('boundaries.requirements\x20must\x20be\x20non-empty\x20strings');e['requirements']=h;}if(c['autonomy']!==undefined){if(!GOAL_AUTONOMY_LEVELS['includes'](c['autonomy']))throw new Error('boundaries.autonomy\x20must\x20be\x20one\x20of:\x20'+GOAL_AUTONOMY_LEVELS['join']('\x20|\x20'));e['autonomy']=c['autonomy'];}const f=d['boundaries']??{'autonomy':'confirm_all'};d['boundaries']={...f,...e,'confirmed_at':Date['now']()};const g=stageIndex(d['stage']);if(g>=0x0&&g<stageIndex('confirmed'))d['stage']='confirmed';return d['updated_at']=Date['now'](),this['emitProcessEvent'](d,'boundaries_confirmed','goal\x20boundaries\x20set\x20(autonomy\x20'+d['boundaries']['autonomy']+')'),this['deps']['store']['save'](a,d);}async['pursue'](a,b){const d=await this['mustGet'](a,b);if(isTerminalStage(d['stage']))throw new Error('goal\x20'+b+'\x20is\x20terminal\x20('+d['stage']+')');const f=[];if(d['stage']==='paused')return f['push']('goal\x20is\x20paused\x20(the\x20user\x27s\x20explicit\x20hold)\x20—\x20nothing\x20pursued\x20this\x20tick'),{'action':'wait','items':[],'applied':[],'authorized':[],'boundary_status':{'autonomy':d['boundaries']?.['autonomy']??'unset',...d['boundaries']?.['budget']!==undefined?{'budget':d['boundaries']['budget']}:{},...d['boundaries']?.['deadline']!==undefined?{'deadline':d['boundaries']['deadline']}:{},...d['boundaries']?.['requirements']?.['length']?{'requirements':d['boundaries']['requirements']}:{}},'notes':f};const g=[];if(d['process']){const l=this['deps']['processes']['listSuggestions'](d['process']['dir'],{'status':'pending'});for(const m of l){g['push']({'id':m['id'],'kind':m['kind'],...m['stage']?{'stage':m['stage']}:{},...m['objects']?.['length']?{'objects':m['objects']}:{},'title':m['title'],...m['detail']?{'detail':m['detail']}:{},'risk':m['kind']==='incentive'?'high':m['kind']==='advance_stage'||m['kind']==='register_object'||m['kind']==='complete_goal'||m['kind']==='note'?'none':'low','suggestion_id':m['id'],...m['origin']?{'origin':m['origin']}:{}});}}const h=g['some'](n=>n['kind']==='complete_goal');!h&&d['stage']==='monitoring'&&g['push']({'id':'engine:complete-check','kind':'complete_goal','title':'Verify\x20completion\x20conditions\x20on\x20chain','detail':'The\x20engine\x20re-checks\x20the\x20goal-type\x20completion\x20conjunction;\x20completion\x20only\x20lands\x20when\x20chain\x20conditions\x20hold.','risk':'none','origin':{'source':'engine'}});const i=pursueTick(d,g,Date['now']());f['push'](...i['notes']);const j=[],k=[];for(const n of i['items']){if(n['action']!=='execute'){const p=g['find'](q=>q['id']===n['candidate_id']);if(n['action']==='ask_user'&&p&&!p['suggestion_id']&&d['process'])try{this['deps']['processes']['addSuggestion'](d['process']['dir'],{'kind':p['kind'],...p['stage']?{'stage':p['stage']}:{},'title':p['title'],...p['detail']?{'detail':p['detail']+'\x20(pursue:\x20'+n['reason']+')'}:{'detail':n['reason']}});}catch{f['push']('ask_user\x20suggestion\x20could\x20not\x20be\x20recorded\x20for\x20\x27'+p['title']+'\x27');}continue;}const o=g['find'](q=>q['id']===n['candidate_id']);if(!o)continue;if(o['kind']==='onchain_operation'){k['push']({'candidate_id':o['id'],'title':o['title'],'reason':n['reason']});continue;}if(o['suggestion_id'])try{const q=await this['resolveSuggestion'](a,b,o['suggestion_id'],{'decision':'confirm','apply':!![]});j['push']({'candidate_id':o['id'],'outcome':q['applied']?'applied\x20(suggestion\x20confirmed)':'not\x20applied:\x20'+(q['apply_error']??'unknown')});}catch(r){j['push']({'candidate_id':o['id'],'outcome':'failed:\x20'+(r instanceof Error?r['message']:String(r))});}else{if(o['id']==='engine:complete-check')try{const t=await this['complete'](a,b,{});t['completed']?j['push']({'candidate_id':o['id'],'outcome':'goal\x20completed\x20(chain\x20conditions\x20verified)'}):j['push']({'candidate_id':o['id'],'outcome':'conditions\x20unmet\x20—\x20keep\x20waiting:\x20'+(t['verify_report']['missing']['join'](';\x20')||'no\x20evidence\x20yet')});}catch(u){j['push']({'candidate_id':o['id'],'outcome':'completion\x20check\x20failed:\x20'+(u instanceof Error?u['message']:String(u))});}}}return this['emitProcessEvent'](d,'pursue_tick','pursue\x20tick:\x20'+i['action']+'\x20('+i['items']['length']+'\x20candidate(s),\x20'+j['length']+'\x20applied)',{'data':{'action':i['action'],'items':i['items']['map'](v=>({'candidate_id':v['candidate_id'],'action':v['action']})),'applied':j['map'](v=>v['candidate_id'])}}),{'action':i['action'],'items':i['items'],'applied':j,'authorized':k,'boundary_status':i['boundary_status'],'notes':f};}async['nextSteps'](a,b){const c=await this['mustGet'](a,b);let d;if(c['process'])try{const e=this['deps']['processes']['listSuggestions'](c['process']['dir'],{'status':'pending'}),f=this['deps']['processes']['listProblems'](c['process']['dir'],{'status':'open'});d={'pending_suggestions':{'count':e['length'],'top':e['slice'](0x0,0x3)['map'](g=>g['title'])},'open_problems':{'count':f['length'],'top':f['slice'](0x0,0x3)['map'](g=>g['title'])}};}catch{d=undefined;}return{'goal':c,'steps':nextStepsForGoal(c,d)};}['emitSuggestionEvent'](a,b,c,d){if(!a['process'])return;try{this['deps']['processes']['appendEvent'](a['process']['dir'],{'timestamp':new Date()['toISOString'](),'event':b,'reason':c['kind']+'\x20\x27'+c['title']+'\x27\x20('+c['id']+')','data':{'suggestion_id':c['id'],'kind':c['kind'],...c['stage']?{'stage':c['stage']}:{},...d?{'note':d}:{}}});}catch{}}async['list'](a,b={}){const [c,d]=await Promise['all']([this['deps']['store']['list'](a,b),this['deps']['store']['counts'](a)]);return{'goals':c,'counts':d};}async['mustGet'](a,b){const c=await this['deps']['store']['get'](a,b);if(!c)throw new Error('goal\x20not\x20found:\x20'+b);return c;}}export const goalEngine=new GoalEngine({'store':goalStore,'subscriptionStore':subscriptionStore,'createIntent':createIntent,'removeIntent':removeIntent,'listLocalAccounts':listLocalAccounts,'evaluateCompletion':(a,b)=>evaluateGoalCompletion(a,b),'processes':{'rootDir':processesRootDir,'initProcess':initProcess,'loadManifest':loadManifest,'saveManifest':saveManifest,'loadStageState':loadStageState,'appendEvent':appendEvent,'addFeedback':addFeedback,'listProblems':listProblems,'listFeedback':listFeedback,'readEvents':readEvents,'addSuggestion':addSuggestion,'updateSuggestion':updateSuggestion,'listSuggestions':listSuggestions,'removeDir':deleteProcessDir},'recordSignature':recordSignature});