@wowok/agent-mcp 2.7.1 → 2.7.2

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 (375) hide show
  1. package/dist/config/index.js +1 -1
  2. package/dist/config/runtime.js +1 -238
  3. package/dist/customer/customer-advice.js +1 -130
  4. package/dist/customer/index.js +1 -11
  5. package/dist/customer/industry-risks.js +1 -438
  6. package/dist/customer/info-puzzle.js +1 -681
  7. package/dist/customer/order-monitor.js +1 -328
  8. package/dist/customer/order-strategy.js +1 -373
  9. package/dist/customer/post-purchase.js +1 -351
  10. package/dist/customer/preorder-compare.js +1 -34
  11. package/dist/customer/reminder-system.js +1 -316
  12. package/dist/customer/risk-assessment.js +1 -397
  13. package/dist/customer/types.js +1 -13
  14. package/dist/customer/user-preferences.js +1 -460
  15. package/dist/evaluation/arbitration-game.d.ts +9 -2
  16. package/dist/evaluation/arbitration-game.js +1 -48
  17. package/dist/evaluation/builtins/demand-match.js +1 -153
  18. package/dist/evaluation/builtins/index.js +1 -10
  19. package/dist/evaluation/builtins/service-risk.js +1 -55
  20. package/dist/evaluation/capability.js +1 -13
  21. package/dist/evaluation/composer.js +1 -40
  22. package/dist/evaluation/engine.js +1 -175
  23. package/dist/evaluation/extract.js +1 -115
  24. package/dist/evaluation/game-strategy.d.ts +27 -0
  25. package/dist/evaluation/game-strategy.js +1 -0
  26. package/dist/evaluation/gap.js +1 -100
  27. package/dist/evaluation/index.d.ts +1 -0
  28. package/dist/evaluation/index.js +1 -11
  29. package/dist/evaluation/node-game.d.ts +31 -3
  30. package/dist/evaluation/node-game.js +1 -57
  31. package/dist/evaluation/region.js +1 -36
  32. package/dist/evaluation/types.d.ts +1 -0
  33. package/dist/evaluation/types.js +1 -1
  34. package/dist/evaluation/user-injection.js +1 -27
  35. package/dist/experience/experience-reuse.js +1 -103
  36. package/dist/experience/index.js +1 -5
  37. package/dist/experience/intent-distill.js +1 -83
  38. package/dist/experience/realtime-feedback.js +1 -94
  39. package/dist/experience/types.js +1 -1
  40. package/dist/experience/user-profile.js +1 -171
  41. package/dist/extensions/business-modules.js +1 -287
  42. package/dist/extensions/capability-manifest.js +1 -781
  43. package/dist/extensions/constraint-registry.js +1 -198
  44. package/dist/extensions/index.js +1 -6
  45. package/dist/extensions/metric-registry.js +1 -257
  46. package/dist/extensions/mode-evaluator.js +1 -170
  47. package/dist/extensions/modes.js +1 -499
  48. package/dist/extensions/registry.js +1 -717
  49. package/dist/extensions/types.js +1 -1
  50. package/dist/harness/auto-escalation.js +1 -68
  51. package/dist/harness/checkpoint.js +1 -129
  52. package/dist/harness/index.js +1 -78
  53. package/dist/harness/plan.js +1 -315
  54. package/dist/harness/recover.js +1 -139
  55. package/dist/harness/types.js +1 -1
  56. package/dist/harness/verify.js +1 -237
  57. package/dist/index.js +1 -273
  58. package/dist/intent/enrich.js +1 -67
  59. package/dist/intent/index.js +1 -60
  60. package/dist/intent/matcher.js +1 -81
  61. package/dist/intent/store.js +1 -55
  62. package/dist/intent/types.js +1 -10
  63. package/dist/knowledge/acquisition-flywheel.js +1 -192
  64. package/dist/knowledge/allocation-confirm.js +1 -534
  65. package/dist/knowledge/allocation-context.js +1 -249
  66. package/dist/knowledge/allocation-ledger.js +1 -463
  67. package/dist/knowledge/allocation-puzzle.js +1 -298
  68. package/dist/knowledge/allocation-risk.js +1 -568
  69. package/dist/knowledge/allocation-templates.js +1 -970
  70. package/dist/knowledge/allocation-translation.js +1 -585
  71. package/dist/knowledge/arb-risk.js +1 -210
  72. package/dist/knowledge/arbitration-confirm.js +1 -559
  73. package/dist/knowledge/arbitration-context.js +1 -505
  74. package/dist/knowledge/arbitration-ledger.js +1 -521
  75. package/dist/knowledge/arbitration-puzzle.js +1 -304
  76. package/dist/knowledge/arbitration-risk.js +1 -423
  77. package/dist/knowledge/arbitration-templates.js +1 -276
  78. package/dist/knowledge/arbitration-translation.js +1 -487
  79. package/dist/knowledge/arbitration-trust.js +1 -117
  80. package/dist/knowledge/audit-rules.js +1 -141
  81. package/dist/knowledge/bridge-risk.js +1 -263
  82. package/dist/knowledge/contact-risk.js +1 -200
  83. package/dist/knowledge/contact-templates.js +1 -60
  84. package/dist/knowledge/demand-confirm.js +1 -206
  85. package/dist/knowledge/demand-matching.js +1 -132
  86. package/dist/knowledge/demand-risk.js +1 -240
  87. package/dist/knowledge/demand-translation.js +1 -354
  88. package/dist/knowledge/deployment-scanner.js +1 -823
  89. package/dist/knowledge/dynamic-pricing.js +1 -87
  90. package/dist/knowledge/examples-scanner-cli.js +1 -26
  91. package/dist/knowledge/examples-scanner.js +1 -843
  92. package/dist/knowledge/flywheel-loop.js +1 -404
  93. package/dist/knowledge/fund-layer.js +1 -973
  94. package/dist/knowledge/glossary.js +1 -211
  95. package/dist/knowledge/guard-confirm.js +1 -406
  96. package/dist/knowledge/guard-context.js +1 -287
  97. package/dist/knowledge/guard-design-patterns.js +1 -360
  98. package/dist/knowledge/guard-ledger.js +1 -260
  99. package/dist/knowledge/guard-lint.js +1 -670
  100. package/dist/knowledge/guard-migration.js +1 -228
  101. package/dist/knowledge/guard-puzzle.js +1 -805
  102. package/dist/knowledge/guard-render.js +1 -700
  103. package/dist/knowledge/guard-risk.js +1 -1879
  104. package/dist/knowledge/guard-submission-prompt.js +1 -171
  105. package/dist/knowledge/guard-templates.js +1 -1105
  106. package/dist/knowledge/guard-translation.js +1 -1119
  107. package/dist/knowledge/index.js +1 -436
  108. package/dist/knowledge/industry-evolution.js +1 -323
  109. package/dist/knowledge/industry-generalizer.js +1 -381
  110. package/dist/knowledge/industry-registry.js +1 -174
  111. package/dist/knowledge/intent-metrics.d.ts +4 -3
  112. package/dist/knowledge/intent-metrics.js +1 -566
  113. package/dist/knowledge/machine-confirm.js +1 -559
  114. package/dist/knowledge/machine-context.js +1 -833
  115. package/dist/knowledge/machine-ledger.js +1 -338
  116. package/dist/knowledge/machine-puzzle.js +1 -494
  117. package/dist/knowledge/machine-render.js +1 -565
  118. package/dist/knowledge/machine-risk.js +1 -669
  119. package/dist/knowledge/machine-templates.js +1 -1597
  120. package/dist/knowledge/machine-topology.js +1 -234
  121. package/dist/knowledge/machine-translation.js +1 -513
  122. package/dist/knowledge/mcp-schema-audit-cli.js +1 -45
  123. package/dist/knowledge/mcp-schema-audit.js +1 -777
  124. package/dist/knowledge/onchain-constants.js +1 -35
  125. package/dist/knowledge/order-confirm.js +1 -573
  126. package/dist/knowledge/order-context.js +1 -390
  127. package/dist/knowledge/order-ledger.js +1 -341
  128. package/dist/knowledge/order-puzzle.js +1 -255
  129. package/dist/knowledge/order-risk.js +1 -653
  130. package/dist/knowledge/order-templates.js +1 -368
  131. package/dist/knowledge/order-translation.js +1 -550
  132. package/dist/knowledge/overrides-loader.js +1 -65
  133. package/dist/knowledge/passport-confirm.js +1 -531
  134. package/dist/knowledge/passport-context.js +1 -306
  135. package/dist/knowledge/passport-ledger.js +1 -282
  136. package/dist/knowledge/passport-puzzle.js +1 -333
  137. package/dist/knowledge/passport-risk.js +1 -450
  138. package/dist/knowledge/passport-templates.js +1 -568
  139. package/dist/knowledge/passport-translation.js +1 -516
  140. package/dist/knowledge/payment-risk.js +1 -249
  141. package/dist/knowledge/permission-confirm.js +1 -426
  142. package/dist/knowledge/permission-context.js +1 -224
  143. package/dist/knowledge/permission-ledger.js +1 -403
  144. package/dist/knowledge/permission-puzzle.js +1 -173
  145. package/dist/knowledge/permission-risk.js +1 -411
  146. package/dist/knowledge/permission-templates.js +1 -234
  147. package/dist/knowledge/permission-translation.js +1 -350
  148. package/dist/knowledge/personal-risk.js +1 -212
  149. package/dist/knowledge/process-model.js +1 -160
  150. package/dist/knowledge/progress-confirm.js +1 -456
  151. package/dist/knowledge/progress-context.js +1 -452
  152. package/dist/knowledge/progress-ledger.js +1 -330
  153. package/dist/knowledge/progress-puzzle.js +1 -219
  154. package/dist/knowledge/progress-risk.js +1 -461
  155. package/dist/knowledge/progress-templates.js +1 -228
  156. package/dist/knowledge/progress-translation.js +1 -405
  157. package/dist/knowledge/proof-confirm.js +1 -187
  158. package/dist/knowledge/proof-risk.js +1 -207
  159. package/dist/knowledge/proof-translation.js +1 -283
  160. package/dist/knowledge/registrar-risk.js +1 -217
  161. package/dist/knowledge/repository-confirm.js +1 -286
  162. package/dist/knowledge/repository-risk.js +1 -373
  163. package/dist/knowledge/repository-translation.js +1 -445
  164. package/dist/knowledge/reputation-rules.js +1 -99
  165. package/dist/knowledge/resource-risk.js +1 -157
  166. package/dist/knowledge/reward-confirm.js +1 -526
  167. package/dist/knowledge/reward-context.js +1 -504
  168. package/dist/knowledge/reward-ledger.js +1 -502
  169. package/dist/knowledge/reward-puzzle.js +1 -300
  170. package/dist/knowledge/reward-risk.js +1 -627
  171. package/dist/knowledge/reward-templates.js +1 -197
  172. package/dist/knowledge/reward-translation.js +1 -501
  173. package/dist/knowledge/safety-rules.js +1 -404
  174. package/dist/knowledge/scenario-modes.js +1 -321
  175. package/dist/knowledge/service-confirm.js +1 -807
  176. package/dist/knowledge/service-context.js +1 -403
  177. package/dist/knowledge/service-ledger.js +1 -609
  178. package/dist/knowledge/service-puzzle.js +1 -236
  179. package/dist/knowledge/service-risk.js +1 -651
  180. package/dist/knowledge/service-templates.js +1 -456
  181. package/dist/knowledge/service-translation.js +1 -622
  182. package/dist/knowledge/template-registry.js +1 -353
  183. package/dist/knowledge/tool-constraints.js +1 -195
  184. package/dist/knowledge/tools-reference.js +1 -178
  185. package/dist/knowledge/treasury-confirm.js +1 -512
  186. package/dist/knowledge/treasury-context.js +1 -363
  187. package/dist/knowledge/treasury-ledger.js +1 -300
  188. package/dist/knowledge/treasury-puzzle.js +1 -216
  189. package/dist/knowledge/treasury-risk.js +1 -440
  190. package/dist/knowledge/treasury-templates.js +1 -358
  191. package/dist/knowledge/treasury-translation.js +1 -498
  192. package/dist/knowledge/trust-metrics.js +1 -198
  193. package/dist/knowledge/util-risk.js +1 -135
  194. package/dist/loop-engineering/aggregate.js +1 -132
  195. package/dist/loop-engineering/context-collect.js +1 -83
  196. package/dist/loop-engineering/diagnose.js +1 -273
  197. package/dist/loop-engineering/improve.js +1 -405
  198. package/dist/loop-engineering/index.js +1 -4
  199. package/dist/loop-engineering/pipeline.js +1 -56
  200. package/dist/mode-market/index.js +1 -3
  201. package/dist/mode-market/registry.js +1 -124
  202. package/dist/mode-market/review.js +1 -214
  203. package/dist/mode-market/submission.js +1 -85
  204. package/dist/participation/collaborator-interest.d.ts +23 -0
  205. package/dist/participation/collaborator-interest.js +1 -0
  206. package/dist/participation/customer-interest.d.ts +25 -0
  207. package/dist/participation/customer-interest.js +1 -0
  208. package/dist/participation/merchant-interest.js +1 -100
  209. package/dist/participation/radar-core.d.ts +13 -3
  210. package/dist/participation/radar-core.js +1 -269
  211. package/dist/participation/supplier-interest.d.ts +25 -0
  212. package/dist/participation/supplier-interest.js +1 -0
  213. package/dist/persona/analyzer.js +1 -66
  214. package/dist/persona/bridge.js +1 -86
  215. package/dist/persona/defaults.js +1 -195
  216. package/dist/persona/experience-bridge.js +1 -23
  217. package/dist/persona/index.js +1 -71
  218. package/dist/persona/model.js +1 -111
  219. package/dist/persona/store.js +1 -62
  220. package/dist/persona/types.d.ts +3 -1
  221. package/dist/persona/types.js +1 -5
  222. package/dist/project/business-puzzle.js +1 -383
  223. package/dist/project/context-assembly.js +1 -254
  224. package/dist/project/deployment-bridge.js +1 -120
  225. package/dist/project/deployment-doc.js +1 -1126
  226. package/dist/project/edit-planner.js +1 -1342
  227. package/dist/project/evaluation.js +1 -2011
  228. package/dist/project/game-theory.js +1 -177
  229. package/dist/project/graph-builder.js +1 -656
  230. package/dist/project/graph.js +1 -340
  231. package/dist/project/handlers.js +1 -1784
  232. package/dist/project/index.d.ts +1 -0
  233. package/dist/project/index.js +1 -301
  234. package/dist/project/intent-analyzer.js +1 -149
  235. package/dist/project/machine-nodes.js +1 -36
  236. package/dist/project/merchant-guide.js +1 -264
  237. package/dist/project/migration.js +1 -125
  238. package/dist/project/mode-actions.js +1 -309
  239. package/dist/project/namespace.js +1 -206
  240. package/dist/project/participation-radar.js +1 -428
  241. package/dist/project/pipeline-actions.js +1 -109
  242. package/dist/project/project-store.js +1 -422
  243. package/dist/project/query.js +1 -153
  244. package/dist/project/reverse-mapping.d.ts +34 -0
  245. package/dist/project/reverse-mapping.js +1 -0
  246. package/dist/project/risk-aggregator.js +1 -295
  247. package/dist/project/rollback-policy.js +1 -290
  248. package/dist/project/semantic-assembler.js +1 -345
  249. package/dist/project/semantic-graph.js +1 -292
  250. package/dist/project/stage-gate.js +1 -369
  251. package/dist/project/substep-trace.js +1 -332
  252. package/dist/project/task-tracker.js +1 -78
  253. package/dist/role/derivation.d.ts +18 -0
  254. package/dist/role/derivation.js +1 -0
  255. package/dist/role/index.d.ts +5 -0
  256. package/dist/role/index.js +1 -0
  257. package/dist/role/model.d.ts +8 -0
  258. package/dist/role/model.js +1 -0
  259. package/dist/role/resolution.d.ts +11 -0
  260. package/dist/role/resolution.js +1 -0
  261. package/dist/role/types.d.ts +11 -0
  262. package/dist/role/types.js +1 -0
  263. package/dist/rules.js +1 -52
  264. package/dist/safety/confirm-gate.js +1 -88
  265. package/dist/safety/index.js +1 -3
  266. package/dist/safety/preview.js +1 -52
  267. package/dist/schema/call/allocation.js +1 -34
  268. package/dist/schema/call/arbitration.js +1 -113
  269. package/dist/schema/call/base.d.ts +15 -15
  270. package/dist/schema/call/base.js +1 -370
  271. package/dist/schema/call/bridge-handler.js +1 -265
  272. package/dist/schema/call/bridge.d.ts +7 -7
  273. package/dist/schema/call/bridge.js +1 -458
  274. package/dist/schema/call/contact.js +1 -37
  275. package/dist/schema/call/demand.js +1 -47
  276. package/dist/schema/call/guard.js +1 -161
  277. package/dist/schema/call/handler.js +1 -322
  278. package/dist/schema/call/index.js +1 -20
  279. package/dist/schema/call/machine.js +1 -193
  280. package/dist/schema/call/order.js +1 -35
  281. package/dist/schema/call/payment.js +1 -37
  282. package/dist/schema/call/permission-handler.js +1 -54
  283. package/dist/schema/call/permission.js +1 -105
  284. package/dist/schema/call/personal.js +1 -78
  285. package/dist/schema/call/progress.js +1 -47
  286. package/dist/schema/call/proof.js +1 -33
  287. package/dist/schema/call/repository.js +1 -77
  288. package/dist/schema/call/reward.js +1 -30
  289. package/dist/schema/call/semantic.js +1 -1679
  290. package/dist/schema/call/service.js +1 -184
  291. package/dist/schema/call/treasury.js +1 -71
  292. package/dist/schema/common/index.js +1 -407
  293. package/dist/schema/config/index.js +1 -68
  294. package/dist/schema/evaluation/index.d.ts +213 -16
  295. package/dist/schema/evaluation/index.js +1 -356
  296. package/dist/schema/index.js +1 -17
  297. package/dist/schema/intent-radar/index.d.ts +13 -13
  298. package/dist/schema/intent-radar/index.js +1 -89
  299. package/dist/schema/local/index.d.ts +21 -21
  300. package/dist/schema/local/index.js +1 -927
  301. package/dist/schema/local/wip.js +1 -187
  302. package/dist/schema/messenger/index.d.ts +7 -7
  303. package/dist/schema/messenger/index.js +1 -475
  304. package/dist/schema/operations.d.ts +7 -7
  305. package/dist/schema/operations.js +1 -520
  306. package/dist/schema/persona/index.d.ts +54 -54
  307. package/dist/schema/persona/index.js +1 -148
  308. package/dist/schema/project/index.d.ts +94 -48
  309. package/dist/schema/project/index.js +1 -2057
  310. package/dist/schema/query/index.d.ts +423 -7
  311. package/dist/schema/query/index.js +1 -1646
  312. package/dist/schema/schema-query/index.js +1 -104
  313. package/dist/schema/schema-version.js +1 -76
  314. package/dist/schema/sync-layer4.js +1 -286
  315. package/dist/schema/task-status.js +1 -36
  316. package/dist/schema/trust/index.js +1 -314
  317. package/dist/schema/utils/guard-parser.js +1 -419
  318. package/dist/schema/utils/guard-query-utils.js +1 -46
  319. package/dist/schema/utils/node-parser.js +1 -369
  320. package/dist/schema/utils/object-type-utils.js +1 -35
  321. package/dist/schema/utils/permission-index-utils.js +1 -7
  322. package/dist/schema/utils/permission-machine-check.js +1 -121
  323. package/dist/schema/utils/skills-recommendation.js +1 -77
  324. package/dist/schema-query/index.js +1 -810
  325. package/dist/schemas/account_operation.output.json +5 -2
  326. package/dist/schemas/bridge_operation.output.json +5 -2
  327. package/dist/schemas/evaluation_operation.output.json +112 -7
  328. package/dist/schemas/evaluation_operation.schema.json +93 -6
  329. package/dist/schemas/index.json +1 -1
  330. package/dist/schemas/intent_radar.output.json +4 -1
  331. package/dist/schemas/intent_radar.schema.json +4 -1
  332. package/dist/schemas/local_info_operation.output.json +5 -2
  333. package/dist/schemas/local_mark_operation.output.json +5 -2
  334. package/dist/schemas/messenger_operation.output.json +5 -2
  335. package/dist/schemas/onchain_events.output.json +5 -2
  336. package/dist/schemas/onchain_operations.output.json +5 -2
  337. package/dist/schemas/onchain_operations.schema.json +4 -4
  338. package/dist/schemas/onchain_operations_allocation.schema.json +1 -1
  339. package/dist/schemas/onchain_operations_machine.schema.json +2 -2
  340. package/dist/schemas/onchain_operations_service.schema.json +1 -1
  341. package/dist/schemas/onchain_table_data.output.json +6 -3
  342. package/dist/schemas/persona_operation.output.json +4 -1
  343. package/dist/schemas/persona_operation.schema.json +4 -1
  344. package/dist/schemas/project_operation.output.json +28 -8
  345. package/dist/schemas/query_toolkit.output.json +8 -5
  346. package/dist/schemas/wowok_buildin_info.output.json +132 -0
  347. package/dist/schemas/wowok_buildin_info.schema.json +14 -0
  348. package/dist/telemetry/index.js +1 -112
  349. package/dist/telemetry/redact.js +1 -23
  350. package/dist/telemetry/storage.js +1 -80
  351. package/dist/tools/handlers/bridge.js +1 -1
  352. package/dist/tools/handlers/config.js +1 -74
  353. package/dist/tools/handlers/evaluation.js +1 -123
  354. package/dist/tools/handlers/file-export.js +1 -90
  355. package/dist/tools/handlers/intent-radar.js +1 -76
  356. package/dist/tools/handlers/local.js +1 -53
  357. package/dist/tools/handlers/messenger.js +1 -188
  358. package/dist/tools/handlers/onchain.js +1 -1180
  359. package/dist/tools/handlers/persona.js +1 -89
  360. package/dist/tools/handlers/project.js +1 -211
  361. package/dist/tools/handlers/query.js +1 -434
  362. package/dist/tools/handlers/schema-query.js +1 -176
  363. package/dist/tools/handlers/task-status.js +1 -26
  364. package/dist/tools/handlers/trust.js +1 -380
  365. package/dist/tools/handlers/wip.js +1 -90
  366. package/dist/tools/index.js +1 -1382
  367. package/dist/tools/retry.js +1 -85
  368. package/dist/tools/rules-hook.js +1 -23
  369. package/dist/tools/shared.js +1 -130
  370. package/dist/tools/types.js +1 -1
  371. package/dist/tools/upgrade-check.d.ts +19 -0
  372. package/dist/tools/upgrade-check.js +1 -0
  373. package/dist/tools/wip-deploy-assist.js +1 -306
  374. package/dist/tools/wrap.js +1 -500
  375. package/package.json +4 -2
@@ -1,833 +1 @@
1
- import { MACHINE_LEDGER_VERSION, MACHINE_SCENES_COUNT, findScene, inferSceneFromFlow, } from "./machine-ledger.js";
2
- import { MAX_NODE_COUNT, MAX_NODE_PAIR_COUNT, MAX_FORWARD_COUNT, } from "./onchain-constants.js";
3
- import { MACHINE_TEMPLATES, MACHINE_TEMPLATES_VERSION, getAllTemplates, getTemplatesByScene, suggestTemplateForIntent, } from "./machine-templates.js";
4
- import { SEMANTIC_TO_MACHINE_RULES, MACHINE_CONSTRAINT_RULES, MACHINE_TRANSLATION_VERSION, matchSemanticPattern, } from "./machine-translation.js";
5
- import { MACHINE_RISK_RULES, MACHINE_RISK_VERSION, assessMachineRisks, } from "./machine-risk.js";
6
- import { analyzeTopology, formatTopologySummary, MACHINE_TOPOLOGY_VERSION, } from "./machine-topology.js";
7
- import { initPuzzleFromIntent, initPuzzleFromTemplate, checkPuzzleCompleteness, MACHINE_PUZZLE_VERSION, } from "./machine-puzzle.js";
8
- import { PUBLISH_CHECKLIST, CONFIRMATION_QUESTIONS, MACHINE_CONFIRM_VERSION, progressiveCheck, } from "./machine-confirm.js";
9
- import { GUARD_SCENES, } from "./guard-ledger.js";
10
- export const MACHINE_CONTEXT_VERSION = "1.0.0";
11
- export const MACHINE_VERIFICATION_NOTES = [
12
- {
13
- topic: "bReplace",
14
- judgment: "YES",
15
- verified_semantic: "bReplace acts at the pairs-list level of an ALREADY-EXISTING node, " +
16
- "NOT at the whole-Machine level. bReplace=false merges new pairs into the " +
17
- "existing node's pairs list; bReplace=true replaces that node's pairs list entirely.",
18
- code_reference: "d:\\wowok\\agent\\mcp\\src\\tools\\machine.ts (node ops)",
19
- affected_modes: ["initial_design", "mid_design_review", "pre_publish_check"],
20
- },
21
- {
22
- topic: "um",
23
- judgment: "PARTIAL",
24
- verified_semantic: "um is a Messenger Contact object reference (off-chain session metadata). " +
25
- "It does NOT participate in any on-chain flow logic; omitting it has zero on-chain impact.",
26
- code_reference: "machine.move (no um field in on-chain Machine)",
27
- affected_modes: ["initial_design", "mid_design_review"],
28
- },
29
- {
30
- topic: "consensus_repositories",
31
- judgment: "PARTIAL",
32
- verified_semantic: "consensus_repositories is a declarative-only field. It is NOT consumed by any " +
33
- "on-chain flow logic — it is a hint for off-chain tooling and human auditors.",
34
- code_reference: "machine.move (no consensus_repositories field)",
35
- affected_modes: ["initial_design", "mid_design_review"],
36
- },
37
- {
38
- topic: "namedOperator_assignment",
39
- judgment: "PARTIAL",
40
- verified_semantic: "Move progress::new does NOT accept namedOperator parameter. The MCP/SDK layer " +
41
- "translates the API parameter into a separate namedOperator_add transaction " +
42
- "(requires permission index 221). At runtime, Forward checks namedOperator membership.",
43
- code_reference: "progress.move (progress::new signature) + agent\\mcp\\src\\tools\\progress.ts (namedOperator_add)",
44
- affected_modes: ["initial_design", "mid_design_review", "pre_publish_check"],
45
- },
46
- {
47
- topic: "cross_machine_dependency",
48
- judgment: "PARTIAL",
49
- verified_semantic: "Cross-Machine dependency is INDIRECT: Machine A's Forward Guard queries Machine B's " +
50
- "Progress via convert_witness (TypeOrderProgress=100/103). Machine B must be published " +
51
- "before Progress can be created (progress::new -> assert_published).",
52
- code_reference: "progress.move (progress::new, assert_published) + guard.move (convert_witness)",
53
- affected_modes: ["cross_machine", "pre_publish_check"],
54
- },
55
- {
56
- topic: "first_node_semantics_service_bound",
57
- judgment: "YES",
58
- verified_semantic: "For Service-bound Machines, the entry node (prev_node='' target) represents a " +
59
- "POST-PAYMENT state, because Service.buy() performs quote + buy (payment) + " +
60
- "order_allocation + order_progress ATOMICALLY in a single transaction. The Machine " +
61
- "must NOT include separate 'Order', 'Pay', 'Reserve', or 'Subscribe' nodes — those " +
62
- "actions are handled by the Service layer before the Progress (Machine instance) " +
63
- "is created. All nodes after entry represent ORDER PROCESSING stages (fulfillment, " +
64
- "delivery, confirmation, review, refund), NOT payment actions. Correct entry node " +
65
- "examples: 'Paid', 'DepositPaid', 'Active'. Incorrect: 'OrderCreated', 'Reserved', " +
66
- "'Subscribed'. See machine-ledger.ts first_node_semantics field per scene and " +
67
- "machine-templates.ts example_nodes/example_pairs for the canonical structure.",
68
- code_reference: "ts-sdk\\packages\\wowok\\src\\w\\call\\service.ts (buy: quote -> buy -> order_allocation -> order_progress) " +
69
- "+ machine-ledger.ts (first_node_semantics field) + machine-templates.ts (example_nodes)",
70
- affected_modes: ["initial_design", "mid_design_review", "pre_publish_check"],
71
- },
72
- ];
73
- export function getMachineKnowledgeSnapshot() {
74
- const verifiedYes = MACHINE_VERIFICATION_NOTES.filter((n) => n.judgment === "YES").length;
75
- const verifiedPartial = MACHINE_VERIFICATION_NOTES.filter((n) => n.judgment === "PARTIAL").length;
76
- const verifiedNo = MACHINE_VERIFICATION_NOTES.filter((n) => n.judgment === "NO").length;
77
- return {
78
- version: MACHINE_CONTEXT_VERSION,
79
- modules: {
80
- ledger: MACHINE_LEDGER_VERSION,
81
- templates: MACHINE_TEMPLATES_VERSION,
82
- translation: MACHINE_TRANSLATION_VERSION,
83
- risk: MACHINE_RISK_VERSION,
84
- topology: MACHINE_TOPOLOGY_VERSION,
85
- puzzle: MACHINE_PUZZLE_VERSION,
86
- confirm: MACHINE_CONFIRM_VERSION,
87
- },
88
- counts: {
89
- scenes: MACHINE_SCENES_COUNT,
90
- templates: MACHINE_TEMPLATES.length,
91
- patterns: SEMANTIC_TO_MACHINE_RULES.length,
92
- constraints: MACHINE_CONSTRAINT_RULES.length,
93
- risk_rules: MACHINE_RISK_RULES.length,
94
- puzzle_dimensions: 8,
95
- publish_checklist_items: PUBLISH_CHECKLIST.length,
96
- confirmation_questions: CONFIRMATION_QUESTIONS.length,
97
- verification_notes: MACHINE_VERIFICATION_NOTES.length,
98
- },
99
- verification_summary: {
100
- total_topics: MACHINE_VERIFICATION_NOTES.length,
101
- verified_yes: verifiedYes,
102
- verified_partial: verifiedPartial,
103
- verified_no: verifiedNo,
104
- topics: MACHINE_VERIFICATION_NOTES,
105
- },
106
- guard_bridge: {
107
- available: true,
108
- guard_scenes_count: GUARD_SCENES.length,
109
- },
110
- on_chain_limits: {
111
- max_node_count: 100,
112
- max_node_pair_count: 40,
113
- max_forward_count: 20,
114
- },
115
- };
116
- }
117
- export function injectMachineContext(intent, mode, options = {}) {
118
- const maxTemplates = options.max_templates ?? 3;
119
- const maxConstraints = options.max_constraints ?? 10;
120
- const maxRisks = options.max_risks ?? 10;
121
- const includeNotes = options.include_verification_notes ?? true;
122
- const includeGuardBridge = options.include_guard_bridge ?? mode === "guard_integration";
123
- const matchedScene = inferSceneFromFlow(intent);
124
- let suggestedTemplates = [];
125
- if (matchedScene) {
126
- suggestedTemplates = getTemplatesByScene(matchedScene.id).slice(0, maxTemplates);
127
- }
128
- if (suggestedTemplates.length === 0) {
129
- const intentSuggestion = suggestTemplateForIntent(intent);
130
- if (intentSuggestion) {
131
- suggestedTemplates = [intentSuggestion].slice(0, maxTemplates);
132
- }
133
- }
134
- if (suggestedTemplates.length === 0) {
135
- suggestedTemplates = getAllTemplates().slice(0, maxTemplates);
136
- }
137
- let relevantPatterns = [...SEMANTIC_TO_MACHINE_RULES];
138
- if (options.filter_execution_mode) {
139
- const modeToId = {
140
- "Sequential": "P-M-SEQ",
141
- "Parallel AND": "P-M-AND",
142
- "Parallel OR": "P-M-OR",
143
- "Weighted Voting": "P-M-VOTE",
144
- "Hybrid": "P-M-HYBRID",
145
- };
146
- const expectedId = modeToId[options.filter_execution_mode];
147
- if (expectedId) {
148
- relevantPatterns = relevantPatterns.filter((p) => p.id === expectedId);
149
- }
150
- }
151
- if (options.filter_topology) {
152
- const topoToId = {
153
- "Linear": "P-M-LINEAR",
154
- "ForkMerge": "P-M-FORKMERGE",
155
- "Competing": "P-M-COMPETING",
156
- };
157
- const expectedId = topoToId[options.filter_topology];
158
- if (expectedId) {
159
- relevantPatterns = relevantPatterns.filter((p) => p.id === expectedId);
160
- }
161
- }
162
- relevantPatterns = filterPatternsByMode(relevantPatterns, mode);
163
- let relevantConstraints = filterConstraintsByMode(MACHINE_CONSTRAINT_RULES, mode);
164
- relevantConstraints = relevantConstraints.slice(0, maxConstraints);
165
- let relevantRisks = filterRisksByMode(MACHINE_RISK_RULES, mode);
166
- relevantRisks = relevantRisks.slice(0, maxRisks);
167
- let puzzleState;
168
- let puzzleCompleteness;
169
- if (options.existing_puzzle) {
170
- puzzleState = options.existing_puzzle;
171
- puzzleCompleteness = checkPuzzleCompleteness(options.existing_puzzle);
172
- }
173
- else if (mode === "initial_design" || mode === "intent_match") {
174
- puzzleState = initPuzzleFromIntent(intent);
175
- puzzleCompleteness = checkPuzzleCompleteness(puzzleState);
176
- }
177
- let topologyAnalysis;
178
- if (options.existing_machine_json) {
179
- topologyAnalysis = analyzeTopology(options.existing_machine_json.nodes, options.existing_machine_json.pairs);
180
- }
181
- let riskAssessment;
182
- if (options.existing_machine_json && options.project_context) {
183
- const machineForRisk = {
184
- nodes: options.existing_machine_json.nodes,
185
- pairs: options.existing_machine_json.pairs,
186
- };
187
- riskAssessment = assessMachineRisks(machineForRisk, options.project_context);
188
- }
189
- let progressiveCheckResult;
190
- if (mode === "pre_publish_check" && options.existing_machine_json) {
191
- const machineForConfirm = {
192
- nodes: options.existing_machine_json.nodes,
193
- pairs: options.existing_machine_json.pairs,
194
- template_id: options.existing_machine_json.template_id,
195
- scene_id: options.existing_machine_json.scene_id,
196
- };
197
- progressiveCheckResult = progressiveCheck(machineForConfirm, "R5");
198
- }
199
- let guardBridge;
200
- if (includeGuardBridge && matchedScene) {
201
- guardBridge = buildGuardBridge(matchedScene);
202
- }
203
- let verificationNotes = [];
204
- if (includeNotes) {
205
- verificationNotes = MACHINE_VERIFICATION_NOTES.filter((n) => n.affected_modes.includes(mode));
206
- }
207
- const promptHints = buildPromptHints({
208
- mode,
209
- matched_scene: matchedScene,
210
- suggested_templates: suggestedTemplates,
211
- relevant_patterns: relevantPatterns,
212
- relevant_constraints: relevantConstraints,
213
- relevant_risks: relevantRisks,
214
- puzzle_state: puzzleState,
215
- puzzle_completeness: puzzleCompleteness,
216
- topology_analysis: topologyAnalysis,
217
- risk_assessment: riskAssessment,
218
- progressive_check_result: progressiveCheckResult,
219
- guard_bridge: guardBridge,
220
- verification_notes: verificationNotes,
221
- });
222
- const recommendedNextAction = recommendNextAction(mode, {
223
- matched_scene: matchedScene,
224
- suggested_templates: suggestedTemplates,
225
- puzzle_completeness: puzzleCompleteness,
226
- risk_assessment: riskAssessment,
227
- progressive_check_result: progressiveCheckResult,
228
- });
229
- return {
230
- mode,
231
- version: MACHINE_CONTEXT_VERSION,
232
- matched_scene: matchedScene ?? undefined,
233
- suggested_templates: suggestedTemplates,
234
- relevant_patterns: relevantPatterns,
235
- relevant_constraints: relevantConstraints,
236
- relevant_risks: relevantRisks,
237
- puzzle_state: puzzleState,
238
- puzzle_completeness: puzzleCompleteness,
239
- topology_analysis: topologyAnalysis,
240
- risk_assessment: riskAssessment,
241
- progressive_check_result: progressiveCheckResult,
242
- guard_bridge: guardBridge,
243
- prompt_hints: promptHints,
244
- verification_notes: verificationNotes,
245
- recommended_next_action: recommendedNextAction,
246
- };
247
- }
248
- export function suggestWorkflow(intent) {
249
- const matchedScene = inferSceneFromFlow(intent);
250
- const confidence = matchedScene ? 0.8 : 0.3;
251
- const suggestedTemplates = [];
252
- if (matchedScene) {
253
- const sceneTemplates = getTemplatesByScene(matchedScene.id);
254
- for (const t of sceneTemplates.slice(0, 3)) {
255
- suggestedTemplates.push({
256
- template: t,
257
- rationale: `Template for scene "${matchedScene.name}"`,
258
- });
259
- }
260
- }
261
- if (suggestedTemplates.length === 0) {
262
- const t = suggestTemplateForIntent(intent);
263
- if (t) {
264
- suggestedTemplates.push({
265
- template: t,
266
- rationale: "Intent keyword match",
267
- });
268
- }
269
- }
270
- if (suggestedTemplates.length === 0) {
271
- const all = getAllTemplates();
272
- if (all.length > 0) {
273
- suggestedTemplates.push({
274
- template: all[0],
275
- rationale: "Default (no specific match)",
276
- });
277
- }
278
- }
279
- let initialPuzzle;
280
- if (suggestedTemplates.length > 0) {
281
- const fromTemplate = initPuzzleFromTemplate(suggestedTemplates[0].template.id);
282
- initialPuzzle = fromTemplate ?? initPuzzleFromIntent(intent);
283
- }
284
- else {
285
- initialPuzzle = initPuzzleFromIntent(intent);
286
- }
287
- const matchedPattern = matchSemanticPattern(intent);
288
- const recommendedPattern = matchedPattern ?? null;
289
- let recommendedTopology = null;
290
- if (matchedScene && matchedScene.recommended_topology.length > 0) {
291
- recommendedTopology = matchedScene.recommended_topology[0];
292
- }
293
- const completeness = checkPuzzleCompleteness(initialPuzzle);
294
- const nextStep = completeness.next_step;
295
- return {
296
- matched_scene: matchedScene ?? null,
297
- confidence,
298
- suggested_templates: suggestedTemplates,
299
- initial_puzzle: initialPuzzle,
300
- recommended_pattern: recommendedPattern,
301
- recommended_topology: recommendedTopology,
302
- next_step: nextStep,
303
- };
304
- }
305
- export function buildPromptFromContext(bundle) {
306
- const lines = [];
307
- lines.push(`# Machine Design Context (mode: ${bundle.mode})`);
308
- lines.push("");
309
- lines.push("> Context injected by machine-context.ts. Reflects verified on-chain behavior.");
310
- lines.push("");
311
- if (bundle.matched_scene) {
312
- lines.push("## Matched Scene");
313
- lines.push("");
314
- lines.push(`- **ID**: ${bundle.matched_scene.id}`);
315
- lines.push(`- **Name**: ${bundle.matched_scene.name}`);
316
- lines.push(`- **Scenario**: ${bundle.matched_scene.scenario}`);
317
- lines.push(`- **Industry**: ${bundle.matched_scene.industry.join(", ")}`);
318
- lines.push(`- **Recommended patterns**: ${bundle.matched_scene.recommended_patterns.join(", ")}`);
319
- lines.push(`- **Recommended topology**: ${bundle.matched_scene.recommended_topology.join(", ")}`);
320
- lines.push("");
321
- }
322
- if (bundle.suggested_templates.length > 0) {
323
- lines.push("## Suggested Templates");
324
- lines.push("");
325
- for (const t of bundle.suggested_templates) {
326
- lines.push(`### ${t.id}: ${t.name}`);
327
- lines.push("");
328
- lines.push(`- **Scene**: ${t.scene_id}`);
329
- lines.push(`- **Description**: ${t.description}`);
330
- if (t.parameters.length > 0) {
331
- lines.push(`- **Parameters**:`);
332
- for (const p of t.parameters) {
333
- lines.push(` - \`${p.name}\` (${p.type}): ${p.description}`);
334
- }
335
- }
336
- lines.push("");
337
- }
338
- }
339
- if (bundle.relevant_patterns.length > 0) {
340
- lines.push("## Relevant Patterns");
341
- lines.push("");
342
- for (const p of bundle.relevant_patterns) {
343
- lines.push(`### ${p.id}: ${p.pattern_name}`);
344
- lines.push("");
345
- lines.push(`- **Category**: ${p.category}`);
346
- lines.push(`- **Intent**: ${p.semantic_intent}`);
347
- if (p.match_keywords.length > 0) {
348
- lines.push(`- **Keywords**: ${p.match_keywords.join(", ")}`);
349
- }
350
- lines.push("");
351
- }
352
- }
353
- if (bundle.relevant_constraints.length > 0) {
354
- lines.push("## Relevant Constraints");
355
- lines.push("");
356
- for (const c of bundle.relevant_constraints) {
357
- lines.push(`- **${c.id}** (${c.category}, ${c.on_chain_enforced ? "on-chain" : "off-chain"}): ${c.description}`);
358
- }
359
- lines.push("");
360
- }
361
- if (bundle.relevant_risks.length > 0) {
362
- lines.push("## Relevant Risks");
363
- lines.push("");
364
- for (const r of bundle.relevant_risks) {
365
- lines.push(`- **${r.id}** [${r.severity}] ${r.name}: ${r.description}`);
366
- lines.push(` - Fix: ${r.recommendation}`);
367
- }
368
- lines.push("");
369
- }
370
- if (bundle.puzzle_state && bundle.puzzle_completeness) {
371
- lines.push("## Puzzle State");
372
- lines.push("");
373
- lines.push(`- **Complete**: ${bundle.puzzle_completeness.complete}`);
374
- lines.push(`- **Next step**: ${bundle.puzzle_completeness.next_step}`);
375
- lines.push("");
376
- lines.push("### Per-dimension completeness:");
377
- for (const d of bundle.puzzle_completeness.dimensions) {
378
- const mark = d.complete ? "✓" : "✗";
379
- lines.push(` - ${mark} ${d.dimension}`);
380
- if (!d.complete && d.missing_fields.length > 0) {
381
- lines.push(` - Missing: ${d.missing_fields.join(", ")}`);
382
- }
383
- }
384
- lines.push("");
385
- }
386
- if (bundle.topology_analysis) {
387
- lines.push("## Topology Analysis");
388
- lines.push("");
389
- lines.push("```");
390
- lines.push(formatTopologySummary(bundle.topology_analysis));
391
- lines.push("```");
392
- lines.push("");
393
- }
394
- if (bundle.risk_assessment) {
395
- lines.push("## Risk Assessment");
396
- lines.push("");
397
- lines.push(`- **Overall level**: ${bundle.risk_assessment.overall_level}`);
398
- lines.push(`- **Recommendation**: ${bundle.risk_assessment.recommendation}`);
399
- lines.push(`- **Summary**: ${JSON.stringify(bundle.risk_assessment.summary)}`);
400
- if (bundle.risk_assessment.detected_risks.length > 0) {
401
- lines.push("");
402
- lines.push("### Detected risks:");
403
- for (const r of bundle.risk_assessment.detected_risks) {
404
- lines.push(`- [${r.severity}] ${r.name}: ${r.detail}`);
405
- }
406
- }
407
- lines.push("");
408
- }
409
- if (bundle.progressive_check_result) {
410
- const r = bundle.progressive_check_result;
411
- lines.push("## Progressive Checklist Result (R5)");
412
- lines.push("");
413
- lines.push(`- **Passed**: ${r.passed}`);
414
- if (r.checked_items.length > 0) {
415
- lines.push("");
416
- lines.push("### Checked items:");
417
- for (const item of r.checked_items) {
418
- lines.push(` - [${item.status}] ${item.id}: ${item.description}`);
419
- if (item.detail) {
420
- lines.push(` - ${item.detail}`);
421
- }
422
- }
423
- }
424
- lines.push("");
425
- }
426
- if (bundle.guard_bridge) {
427
- lines.push("## Guard Bridge");
428
- lines.push("");
429
- lines.push(`Machine scene \`${bundle.guard_bridge.machine_scene_id}\` relates to:`);
430
- lines.push("");
431
- for (const m of bundle.guard_bridge.forward_guard_mapping) {
432
- lines.push(`- Forward "${m.forward_purpose}" → Guard scene \`${m.guard_scene_id}\` (${m.guard_scene_name})`);
433
- }
434
- lines.push("");
435
- }
436
- if (bundle.prompt_hints.length > 0) {
437
- lines.push("## Prompt Hints");
438
- lines.push("");
439
- for (const h of bundle.prompt_hints) {
440
- lines.push(`- ${h}`);
441
- }
442
- lines.push("");
443
- }
444
- if (bundle.verification_notes.length > 0) {
445
- lines.push("## Verification Notes (06 §14)");
446
- lines.push("");
447
- lines.push("> These notes reflect code-level verification of on-chain behavior.");
448
- for (const n of bundle.verification_notes) {
449
- lines.push("");
450
- lines.push(`- **${n.topic}** (${n.judgment}): ${n.verified_semantic}`);
451
- lines.push(` - Code reference: \`${n.code_reference}\``);
452
- }
453
- lines.push("");
454
- }
455
- lines.push("## Recommended Next Action");
456
- lines.push("");
457
- lines.push(bundle.recommended_next_action);
458
- lines.push("");
459
- return lines.join("\n");
460
- }
461
- export function getRelatedGuardScenes(machineSceneId) {
462
- const machineScene = findScene(machineSceneId);
463
- if (!machineScene) {
464
- return [];
465
- }
466
- const relatedGuardSceneIds = new Set();
467
- for (const req of machineScene.guard_requirements) {
468
- relatedGuardSceneIds.add(req.scene);
469
- }
470
- return GUARD_SCENES.filter((g) => relatedGuardSceneIds.has(g.id));
471
- }
472
- export function getVerificationNotes(mode) {
473
- if (!mode) {
474
- return MACHINE_VERIFICATION_NOTES;
475
- }
476
- return MACHINE_VERIFICATION_NOTES.filter((n) => n.affected_modes.includes(mode));
477
- }
478
- export function identifyCrossMachineDependency(machineAId, machineJson, guardResolutions, publishedMachineIds) {
479
- const deps = [];
480
- for (const pair of machineJson.pairs) {
481
- const pairId = `${pair.prev_node}->${pair.next_node}`;
482
- for (const forward of pair.forwards) {
483
- if (!forward.guard)
484
- continue;
485
- const resolution = guardResolutions.get(forward.guard);
486
- if (!resolution)
487
- continue;
488
- deps.push({
489
- machine_a_id: machineAId,
490
- machine_b_id: resolution.upstream_machine_id,
491
- machine_b_published: publishedMachineIds
492
- ? publishedMachineIds.has(resolution.upstream_machine_id)
493
- : false,
494
- dependency: {
495
- machine_a_forward: `${pairId}:${forward.name}`,
496
- machine_b_node: resolution.upstream_node_name,
497
- },
498
- guard_query: resolution.guard_query_description,
499
- });
500
- }
501
- }
502
- return deps;
503
- }
504
- export function detectCrossMachineCycle(allDependencies) {
505
- const adj = new Map();
506
- for (const dep of allDependencies) {
507
- if (!adj.has(dep.machine_a_id))
508
- adj.set(dep.machine_a_id, new Set());
509
- adj.get(dep.machine_a_id).add(dep.machine_b_id);
510
- if (!adj.has(dep.machine_b_id))
511
- adj.set(dep.machine_b_id, new Set());
512
- }
513
- const cycles = [];
514
- const WHITE = 0, GRAY = 1, BLACK = 2;
515
- const color = new Map();
516
- for (const node of adj.keys())
517
- color.set(node, WHITE);
518
- const stack = [];
519
- const dfs = (node) => {
520
- color.set(node, GRAY);
521
- stack.push(node);
522
- const neighbors = adj.get(node) ?? new Set();
523
- for (const next of neighbors) {
524
- const nextColor = color.get(next) ?? WHITE;
525
- if (nextColor === GRAY) {
526
- const cycleStart = stack.indexOf(next);
527
- const cycle = stack.slice(cycleStart).concat([next]);
528
- cycles.push(cycle);
529
- }
530
- else if (nextColor === WHITE) {
531
- dfs(next);
532
- }
533
- }
534
- stack.pop();
535
- color.set(node, BLACK);
536
- };
537
- for (const node of adj.keys()) {
538
- if (color.get(node) === WHITE) {
539
- dfs(node);
540
- }
541
- }
542
- return cycles;
543
- }
544
- export function aggregateProjectDependencies(machines, publishedMachineIds) {
545
- const all = [];
546
- for (const m of machines) {
547
- const deps = identifyCrossMachineDependency(m.machine_id, m.machine_json, m.guard_resolutions, publishedMachineIds);
548
- all.push(...deps);
549
- }
550
- return all;
551
- }
552
- function filterPatternsByMode(patterns, mode) {
553
- switch (mode) {
554
- case "cross_machine":
555
- return patterns.filter((p) => p.id === "P-M-CROSS-MACHINE");
556
- case "allocation_integration":
557
- return patterns.filter((p) => p.id === "P-M-ALLOCATION-INTEGRATED");
558
- case "guard_integration":
559
- return patterns.filter((p) => p.match_keywords.some((k) => ["guard", "validation"].some((term) => k.toLowerCase().includes(term.toLowerCase()))) ||
560
- p.semantic_intent.toLowerCase().includes("guard"));
561
- case "post_publish_runtime":
562
- return patterns.filter((p) => p.category === "execution" &&
563
- ["and", "or", "vote", "hybrid"].some((term) => p.pattern_name.toLowerCase().includes(term)));
564
- default:
565
- return patterns;
566
- }
567
- }
568
- function filterConstraintsByMode(constraints, mode) {
569
- switch (mode) {
570
- case "initial_design":
571
- case "intent_match":
572
- return constraints.filter((c) => c.category === "creation");
573
- case "mid_design_review":
574
- return constraints.filter((c) => ["creation", "structure", "node_operation"].includes(c.category));
575
- case "pre_publish_check":
576
- return constraints.filter((c) => ["publish", "structure", "node_operation"].includes(c.category));
577
- case "post_publish_runtime":
578
- return constraints.filter((c) => c.category === "runtime");
579
- case "cross_machine":
580
- return constraints.filter((c) => ["structure", "publish"].includes(c.category));
581
- case "guard_integration":
582
- return constraints.filter((c) => c.description.toLowerCase().includes("guard") ||
583
- c.description.toLowerCase().includes("forward"));
584
- case "allocation_integration":
585
- return constraints.filter((c) => c.description.toLowerCase().includes("allocator") ||
586
- c.description.toLowerCase().includes("terminal") ||
587
- c.description.toLowerCase().includes("allocation"));
588
- default:
589
- return constraints;
590
- }
591
- }
592
- function filterRisksByMode(risks, mode) {
593
- switch (mode) {
594
- case "initial_design":
595
- case "intent_match":
596
- return risks.filter((r) => ["structural", "permission"].includes(r.category));
597
- case "mid_design_review":
598
- return risks.filter((r) => ["structural", "guard_integration", "permission"].includes(r.category));
599
- case "pre_publish_check":
600
- return risks
601
- .slice()
602
- .sort((a, b) => severityRank(b.severity) - severityRank(a.severity));
603
- case "post_publish_runtime":
604
- return risks.filter((r) => r.category === "environment");
605
- case "cross_machine":
606
- return risks.filter((r) => r.category === "guard_integration");
607
- case "guard_integration":
608
- return risks.filter((r) => r.category === "guard_integration");
609
- case "allocation_integration":
610
- return risks.filter((r) => r.description.toLowerCase().includes("allocator") ||
611
- r.description.toLowerCase().includes("allocation") ||
612
- r.description.toLowerCase().includes("terminal"));
613
- default:
614
- return risks;
615
- }
616
- }
617
- function severityRank(s) {
618
- switch (s) {
619
- case "critical": return 5;
620
- case "high": return 4;
621
- case "medium": return 3;
622
- case "low": return 2;
623
- }
624
- }
625
- function buildGuardBridge(machineScene) {
626
- const guardSceneIds = new Set();
627
- const forwardGuardMapping = [];
628
- for (const req of machineScene.guard_requirements) {
629
- guardSceneIds.add(req.scene);
630
- const guardScene = GUARD_SCENES.find((g) => g.id === req.scene);
631
- forwardGuardMapping.push({
632
- forward_purpose: req.purpose,
633
- guard_scene_id: req.scene,
634
- guard_scene_name: guardScene?.name || req.scene,
635
- });
636
- }
637
- const guardScenes = GUARD_SCENES.filter((g) => guardSceneIds.has(g.id));
638
- return {
639
- machine_scene_id: machineScene.id,
640
- guard_scenes: guardScenes,
641
- forward_guard_mapping: forwardGuardMapping,
642
- };
643
- }
644
- function buildPromptHints(ctx) {
645
- const hints = [];
646
- switch (ctx.mode) {
647
- case "initial_design":
648
- case "intent_match":
649
- hints.push("Start by confirming the matched scene and selecting a template.");
650
- if (ctx.matched_scene) {
651
- hints.push(`Scene "${ctx.matched_scene.name}" recommends patterns: ${ctx.matched_scene.recommended_patterns.join(", ")}.`);
652
- if (ctx.matched_scene.first_node_semantics) {
653
- hints.push(`First-node semantics: ${ctx.matched_scene.first_node_semantics}`);
654
- }
655
- }
656
- hints.push("⚠ First node convention: For Service-bound Machines, the entry node (prev_node='' target) MUST represent a POST-PAYMENT state (e.g. 'Paid', 'DepositPaid'). Do NOT add 'Order'/'Pay'/'Reserve'/'Subscribe' nodes — Service.buy() handles payment atomically before Progress is created.");
657
- if (ctx.suggested_templates.length > 0) {
658
- hints.push(`Top template suggestion: ${ctx.suggested_templates[0].id} (${ctx.suggested_templates[0].name}).`);
659
- }
660
- break;
661
- case "mid_design_review":
662
- if (ctx.puzzle_completeness) {
663
- if (ctx.puzzle_completeness.complete) {
664
- hints.push("Puzzle is complete. Proceed to pre-publish check.");
665
- }
666
- else {
667
- hints.push(`Puzzle incomplete. Next step: ${ctx.puzzle_completeness.next_step}`);
668
- }
669
- }
670
- if (ctx.topology_analysis) {
671
- if (ctx.topology_analysis.has_cycles) {
672
- hints.push("⚠ Cycle detected in topology — must fix before publish.");
673
- }
674
- if (ctx.topology_analysis.orphaned_nodes.length > 0) {
675
- hints.push(`⚠ Orphaned nodes: ${ctx.topology_analysis.orphaned_nodes.join(", ")}`);
676
- }
677
- }
678
- break;
679
- case "pre_publish_check":
680
- if (ctx.risk_assessment) {
681
- if (ctx.risk_assessment.overall_level === "critical") {
682
- hints.push("⛔ CRITICAL risk detected — DO NOT publish until resolved.");
683
- }
684
- else if (ctx.risk_assessment.overall_level === "high") {
685
- hints.push("⚠ HIGH risk — fix before publish or override with explicit reason.");
686
- }
687
- hints.push(`Risk recommendation: ${ctx.risk_assessment.recommendation}`);
688
- }
689
- if (ctx.progressive_check_result) {
690
- if (!ctx.progressive_check_result.passed) {
691
- const failed = ctx.progressive_check_result.checked_items
692
- .filter((i) => i.status !== "pass")
693
- .map((i) => i.id);
694
- hints.push(`⛔ Pre-publish checklist FAILED on: ${failed.join(", ") || "see details"}`);
695
- }
696
- else {
697
- hints.push("✓ Pre-publish checklist (R5) passed.");
698
- }
699
- }
700
- hints.push("Run full confirmPublish() with user confirmation before any on-chain publish transaction.");
701
- break;
702
- case "post_publish_runtime":
703
- hints.push("Machine is already published — nodes cannot be modified.");
704
- hints.push("Only progress advancement (Forward execution) is possible.");
705
- if (ctx.topology_analysis) {
706
- hints.push(`Current topology: ${ctx.topology_analysis.within_limits ? "within on-chain limits" : "EXCEEDS limits"}`);
707
- }
708
- break;
709
- case "cross_machine":
710
- hints.push("Cross-Machine dependency is INDIRECT: Machine A queries Machine B's Progress via convert_witness.");
711
- hints.push("Machine B MUST be published before Progress::new can create a Progress for it (assert_published).");
712
- hints.push("Use convert_witness TypeOrderProgress (100) or TypeOrderProgressSession (103) in Guard queries.");
713
- break;
714
- case "guard_integration":
715
- if (ctx.guard_bridge) {
716
- hints.push(`This scene integrates with ${ctx.guard_bridge.guard_scenes.length} Guard scene(s).`);
717
- for (const m of ctx.guard_bridge.forward_guard_mapping) {
718
- hints.push(` - Forward "${m.forward_purpose}" → Guard scene: ${m.guard_scene_name}`);
719
- }
720
- }
721
- hints.push("Forward.guard cannot be modified after Machine publish (immutable).");
722
- hints.push("Use machine_forward_guard scene from guard-ledger.ts for Guard design.");
723
- break;
724
- case "allocation_integration":
725
- hints.push("Terminal nodes map to Service order_allocators.");
726
- hints.push("order_allocators is order-sensitive (first-match-wins).");
727
- hints.push("Each Allocator requires a UNIQUE Guard object (no two allocators may share the same Guard).");
728
- hints.push("order_allocators CANNOT be modified after Service publish (immutable).");
729
- break;
730
- }
731
- for (const n of ctx.verification_notes) {
732
- hints.push(`[Verified ${n.judgment}] ${n.topic}: ${n.verified_semantic}`);
733
- }
734
- hints.push(`On-chain limits: MAX_NODE_COUNT=${MAX_NODE_COUNT}, MAX_NODE_PAIR_COUNT=${MAX_NODE_PAIR_COUNT}, MAX_FORWARD_COUNT=${MAX_FORWARD_COUNT}.`);
735
- return hints;
736
- }
737
- function recommendNextAction(mode, ctx) {
738
- switch (mode) {
739
- case "initial_design":
740
- case "intent_match": {
741
- if (!ctx.matched_scene) {
742
- return "Ask the user to clarify the business scenario — no scene matched.";
743
- }
744
- if (ctx.suggested_templates.length === 0) {
745
- return `Scene "${ctx.matched_scene.name}" matched but no template available — design Machine manually using the scene's recommended patterns.`;
746
- }
747
- return `Present template "${ctx.suggested_templates[0].id}" to user. After user confirms, fill parameters and initialize puzzle.`;
748
- }
749
- case "mid_design_review": {
750
- if (!ctx.puzzle_completeness) {
751
- return "Initialize puzzle state and re-run injection with existing_puzzle option.";
752
- }
753
- if (ctx.puzzle_completeness.complete) {
754
- return "Puzzle complete. Proceed to pre_publish_check mode.";
755
- }
756
- return `Complete missing puzzle dimensions: ${ctx.puzzle_completeness.next_step}`;
757
- }
758
- case "pre_publish_check": {
759
- if (ctx.progressive_check_result && !ctx.progressive_check_result.passed) {
760
- const failedIds = ctx.progressive_check_result.failed_items
761
- .map((i) => i.id)
762
- .join(", ");
763
- return `⛔ Pre-publish checklist FAILED on: ${failedIds || "see checklist result"}. Fix these items before proceeding.`;
764
- }
765
- if (ctx.risk_assessment) {
766
- if (ctx.risk_assessment.overall_level === "critical") {
767
- return "⛔ CRITICAL risk — DO NOT publish. Fix risks first.";
768
- }
769
- if (ctx.risk_assessment.overall_level === "high") {
770
- return "⚠ HIGH risk — fix risks OR obtain explicit user override with reason.";
771
- }
772
- }
773
- return "All checks passed. Present confirmation text to user and obtain explicit approval before publish transaction.";
774
- }
775
- case "post_publish_runtime":
776
- return "Machine is published. Use onchain_operations to execute Forward advancements. Monitor Progress state via query tool.";
777
- case "cross_machine":
778
- return "Design Machine A's Forward.guard to query Machine B's Progress via convert_witness=100. Ensure Machine B is published first.";
779
- case "guard_integration":
780
- return "For each Forward.guard binding, design the Guard using the related Guard scene. Use guard-ledger + guard-templates + guard-puzzle modules.";
781
- case "allocation_integration":
782
- return "Map each terminal node to an Allocator in Service.order_allocators. Each Allocator needs a unique Guard object. Configure sharing.who (prefer Entity over Signer).";
783
- default:
784
- return "Proceed with current task.";
785
- }
786
- }
787
- export const CONTEXT_PRESETS = {
788
- newUserIntent: (intent) => injectMachineContext(intent, "intent_match", {
789
- max_templates: 2,
790
- max_constraints: 5,
791
- max_risks: 3,
792
- include_verification_notes: false,
793
- include_guard_bridge: false,
794
- }),
795
- midDesignReview: (intent, puzzle) => injectMachineContext(intent, "mid_design_review", {
796
- max_templates: 1,
797
- max_constraints: 15,
798
- max_risks: 10,
799
- include_verification_notes: true,
800
- include_guard_bridge: false,
801
- existing_puzzle: puzzle,
802
- }),
803
- prePublishFull: (intent, machineJson, projectContext) => injectMachineContext(intent, "pre_publish_check", {
804
- max_templates: 0,
805
- max_constraints: 20,
806
- max_risks: 39,
807
- include_verification_notes: true,
808
- include_guard_bridge: true,
809
- existing_machine_json: machineJson,
810
- project_context: projectContext,
811
- }),
812
- crossMachine: (intent) => injectMachineContext(intent, "cross_machine", {
813
- max_templates: 2,
814
- max_constraints: 10,
815
- max_risks: 8,
816
- include_verification_notes: true,
817
- include_guard_bridge: true,
818
- }),
819
- guardIntegration: (intent) => injectMachineContext(intent, "guard_integration", {
820
- max_templates: 1,
821
- max_constraints: 10,
822
- max_risks: 8,
823
- include_verification_notes: true,
824
- include_guard_bridge: true,
825
- }),
826
- allocationIntegration: (intent) => injectMachineContext(intent, "allocation_integration", {
827
- max_templates: 1,
828
- max_constraints: 8,
829
- max_risks: 8,
830
- include_verification_notes: false,
831
- include_guard_bridge: false,
832
- }),
833
- };
1
+ import{MACHINE_LEDGER_VERSION,MACHINE_SCENES_COUNT,findScene,inferSceneFromFlow}from'./machine-ledger.js';import{MAX_NODE_COUNT,MAX_NODE_PAIR_COUNT,MAX_FORWARD_COUNT}from'./onchain-constants.js';import{MACHINE_TEMPLATES,MACHINE_TEMPLATES_VERSION,getAllTemplates,getTemplatesByScene,suggestTemplateForIntent}from'./machine-templates.js';import{SEMANTIC_TO_MACHINE_RULES,MACHINE_CONSTRAINT_RULES,MACHINE_TRANSLATION_VERSION,matchSemanticPattern}from'./machine-translation.js';import{MACHINE_RISK_RULES,MACHINE_RISK_VERSION,assessMachineRisks}from'./machine-risk.js';import{analyzeTopology,formatTopologySummary,MACHINE_TOPOLOGY_VERSION}from'./machine-topology.js';import{initPuzzleFromIntent,initPuzzleFromTemplate,checkPuzzleCompleteness,MACHINE_PUZZLE_VERSION}from'./machine-puzzle.js';import{PUBLISH_CHECKLIST,CONFIRMATION_QUESTIONS,MACHINE_CONFIRM_VERSION,progressiveCheck}from'./machine-confirm.js';import{GUARD_SCENES}from'./guard-ledger.js';export const MACHINE_CONTEXT_VERSION='1.0.0';export const MACHINE_VERIFICATION_NOTES=[{'topic':'bReplace','judgment':'YES','verified_semantic':'bReplace\x20acts\x20at\x20the\x20pairs-list\x20level\x20of\x20an\x20ALREADY-EXISTING\x20node,\x20'+'NOT\x20at\x20the\x20whole-Machine\x20level.\x20bReplace=false\x20merges\x20new\x20pairs\x20into\x20the\x20'+'existing\x20node\x27s\x20pairs\x20list;\x20bReplace=true\x20replaces\x20that\x20node\x27s\x20pairs\x20list\x20entirely.','code_reference':'d:\x5cwowok\x5cagent\x5cmcp\x5csrc\x5ctools\x5cmachine.ts\x20(node\x20ops)','affected_modes':['initial_design','mid_design_review','pre_publish_check']},{'topic':'um','judgment':'PARTIAL','verified_semantic':'um\x20is\x20a\x20Messenger\x20Contact\x20object\x20reference\x20(off-chain\x20session\x20metadata).\x20'+'It\x20does\x20NOT\x20participate\x20in\x20any\x20on-chain\x20flow\x20logic;\x20omitting\x20it\x20has\x20zero\x20on-chain\x20impact.','code_reference':'machine.move\x20(no\x20um\x20field\x20in\x20on-chain\x20Machine)','affected_modes':['initial_design','mid_design_review']},{'topic':'consensus_repositories','judgment':'PARTIAL','verified_semantic':'consensus_repositories\x20is\x20a\x20declarative-only\x20field.\x20It\x20is\x20NOT\x20consumed\x20by\x20any\x20'+'on-chain\x20flow\x20logic\x20—\x20it\x20is\x20a\x20hint\x20for\x20off-chain\x20tooling\x20and\x20human\x20auditors.','code_reference':'machine.move\x20(no\x20consensus_repositories\x20field)','affected_modes':['initial_design','mid_design_review']},{'topic':'namedOperator_assignment','judgment':'PARTIAL','verified_semantic':'Move\x20progress::new\x20does\x20NOT\x20accept\x20namedOperator\x20parameter.\x20The\x20MCP/SDK\x20layer\x20'+'translates\x20the\x20API\x20parameter\x20into\x20a\x20separate\x20namedOperator_add\x20transaction\x20'+'(requires\x20permission\x20index\x20221).\x20At\x20runtime,\x20Forward\x20checks\x20namedOperator\x20membership.','code_reference':'progress.move\x20(progress::new\x20signature)\x20+\x20agent\x5cmcp\x5csrc\x5ctools\x5cprogress.ts\x20(namedOperator_add)','affected_modes':['initial_design','mid_design_review','pre_publish_check']},{'topic':'cross_machine_dependency','judgment':'PARTIAL','verified_semantic':'Cross-Machine\x20dependency\x20is\x20INDIRECT:\x20Machine\x20A\x27s\x20Forward\x20Guard\x20queries\x20Machine\x20B\x27s\x20'+'Progress\x20via\x20convert_witness\x20(TypeOrderProgress=100/103).\x20Machine\x20B\x20must\x20be\x20published\x20'+'before\x20Progress\x20can\x20be\x20created\x20(progress::new\x20->\x20assert_published).','code_reference':'progress.move\x20(progress::new,\x20assert_published)\x20+\x20guard.move\x20(convert_witness)','affected_modes':['cross_machine','pre_publish_check']},{'topic':'first_node_semantics_service_bound','judgment':'YES','verified_semantic':'For\x20Service-bound\x20Machines,\x20the\x20entry\x20node\x20(prev_node=\x27\x27\x20target)\x20represents\x20a\x20'+'POST-PAYMENT\x20state,\x20because\x20Service.buy()\x20performs\x20quote\x20+\x20buy\x20(payment)\x20+\x20'+'order_allocation\x20+\x20order_progress\x20ATOMICALLY\x20in\x20a\x20single\x20transaction.\x20The\x20Machine\x20'+'must\x20NOT\x20include\x20separate\x20\x27Order\x27,\x20\x27Pay\x27,\x20\x27Reserve\x27,\x20or\x20\x27Subscribe\x27\x20nodes\x20—\x20those\x20'+'actions\x20are\x20handled\x20by\x20the\x20Service\x20layer\x20before\x20the\x20Progress\x20(Machine\x20instance)\x20'+'is\x20created.\x20All\x20nodes\x20after\x20entry\x20represent\x20ORDER\x20PROCESSING\x20stages\x20(fulfillment,\x20'+'delivery,\x20confirmation,\x20review,\x20refund),\x20NOT\x20payment\x20actions.\x20Correct\x20entry\x20node\x20'+'examples:\x20\x27Paid\x27,\x20\x27DepositPaid\x27,\x20\x27Active\x27.\x20Incorrect:\x20\x27OrderCreated\x27,\x20\x27Reserved\x27,\x20'+'\x27Subscribed\x27.\x20See\x20machine-ledger.ts\x20first_node_semantics\x20field\x20per\x20scene\x20and\x20'+'machine-templates.ts\x20example_nodes/example_pairs\x20for\x20the\x20canonical\x20structure.','code_reference':'ts-sdk\x5cpackages\x5cwowok\x5csrc\x5cw\x5ccall\x5cservice.ts\x20(buy:\x20quote\x20->\x20buy\x20->\x20order_allocation\x20->\x20order_progress)\x20'+'+\x20machine-ledger.ts\x20(first_node_semantics\x20field)\x20+\x20machine-templates.ts\x20(example_nodes)','affected_modes':['initial_design','mid_design_review','pre_publish_check']}];export function getMachineKnowledgeSnapshot(){const a=MACHINE_VERIFICATION_NOTES['filter'](d=>d['judgment']==='YES')['length'],b=MACHINE_VERIFICATION_NOTES['filter'](d=>d['judgment']==='PARTIAL')['length'],c=MACHINE_VERIFICATION_NOTES['filter'](d=>d['judgment']==='NO')['length'];return{'version':MACHINE_CONTEXT_VERSION,'modules':{'ledger':MACHINE_LEDGER_VERSION,'templates':MACHINE_TEMPLATES_VERSION,'translation':MACHINE_TRANSLATION_VERSION,'risk':MACHINE_RISK_VERSION,'topology':MACHINE_TOPOLOGY_VERSION,'puzzle':MACHINE_PUZZLE_VERSION,'confirm':MACHINE_CONFIRM_VERSION},'counts':{'scenes':MACHINE_SCENES_COUNT,'templates':MACHINE_TEMPLATES['length'],'patterns':SEMANTIC_TO_MACHINE_RULES['length'],'constraints':MACHINE_CONSTRAINT_RULES['length'],'risk_rules':MACHINE_RISK_RULES['length'],'puzzle_dimensions':0x8,'publish_checklist_items':PUBLISH_CHECKLIST['length'],'confirmation_questions':CONFIRMATION_QUESTIONS['length'],'verification_notes':MACHINE_VERIFICATION_NOTES['length']},'verification_summary':{'total_topics':MACHINE_VERIFICATION_NOTES['length'],'verified_yes':a,'verified_partial':b,'verified_no':c,'topics':MACHINE_VERIFICATION_NOTES},'guard_bridge':{'available':!![],'guard_scenes_count':GUARD_SCENES['length']},'on_chain_limits':{'max_node_count':0x64,'max_node_pair_count':0x28,'max_forward_count':0x14}};}export function injectMachineContext(a,b,c={}){const d=c['max_templates']??0x3,e=c['max_constraints']??0xa,f=c['max_risks']??0xa,g=c['include_verification_notes']??!![],h=c['include_guard_bridge']??b==='guard_integration',i=inferSceneFromFlow(a);let j=[];i&&(j=getTemplatesByScene(i['id'])['slice'](0x0,d));if(j['length']===0x0){const w=suggestTemplateForIntent(a);w&&(j=[w]['slice'](0x0,d));}j['length']===0x0&&(j=getAllTemplates()['slice'](0x0,d));let k=[...SEMANTIC_TO_MACHINE_RULES];if(c['filter_execution_mode']){const x={'Sequential':'P-M-SEQ','Parallel\x20AND':'P-M-AND','Parallel\x20OR':'P-M-OR','Weighted\x20Voting':'P-M-VOTE','Hybrid':'P-M-HYBRID'},y=x[c['filter_execution_mode']];y&&(k=k['filter'](z=>z['id']===y));}if(c['filter_topology']){const z={'Linear':'P-M-LINEAR','ForkMerge':'P-M-FORKMERGE','Competing':'P-M-COMPETING'},A=z[c['filter_topology']];A&&(k=k['filter'](B=>B['id']===A));}k=filterPatternsByMode(k,b);let l=filterConstraintsByMode(MACHINE_CONSTRAINT_RULES,b);l=l['slice'](0x0,e);let m=filterRisksByMode(MACHINE_RISK_RULES,b);m=m['slice'](0x0,f);let n,o;if(c['existing_puzzle'])n=c['existing_puzzle'],o=checkPuzzleCompleteness(c['existing_puzzle']);else(b==='initial_design'||b==='intent_match')&&(n=initPuzzleFromIntent(a),o=checkPuzzleCompleteness(n));let p;c['existing_machine_json']&&(p=analyzeTopology(c['existing_machine_json']['nodes'],c['existing_machine_json']['pairs']));let q;if(c['existing_machine_json']&&c['project_context']){const B={'nodes':c['existing_machine_json']['nodes'],'pairs':c['existing_machine_json']['pairs']};q=assessMachineRisks(B,c['project_context']);}let r;if(b==='pre_publish_check'&&c['existing_machine_json']){const C={'nodes':c['existing_machine_json']['nodes'],'pairs':c['existing_machine_json']['pairs'],'template_id':c['existing_machine_json']['template_id'],'scene_id':c['existing_machine_json']['scene_id']};r=progressiveCheck(C,'R5');}let s;h&&i&&(s=buildGuardBridge(i));let t=[];g&&(t=MACHINE_VERIFICATION_NOTES['filter'](D=>D['affected_modes']['includes'](b)));const u=buildPromptHints({'mode':b,'matched_scene':i,'suggested_templates':j,'relevant_patterns':k,'relevant_constraints':l,'relevant_risks':m,'puzzle_state':n,'puzzle_completeness':o,'topology_analysis':p,'risk_assessment':q,'progressive_check_result':r,'guard_bridge':s,'verification_notes':t}),v=recommendNextAction(b,{'matched_scene':i,'suggested_templates':j,'puzzle_completeness':o,'risk_assessment':q,'progressive_check_result':r});return{'mode':b,'version':MACHINE_CONTEXT_VERSION,'matched_scene':i??undefined,'suggested_templates':j,'relevant_patterns':k,'relevant_constraints':l,'relevant_risks':m,'puzzle_state':n,'puzzle_completeness':o,'topology_analysis':p,'risk_assessment':q,'progressive_check_result':r,'guard_bridge':s,'prompt_hints':u,'verification_notes':t,'recommended_next_action':v};}export function suggestWorkflow(a){const b=inferSceneFromFlow(a),c=b?0.8:0.3,d=[];if(b){const k=getTemplatesByScene(b['id']);for(const l of k['slice'](0x0,0x3)){d['push']({'template':l,'rationale':'Template\x20for\x20scene\x20\x22'+b['name']+'\x22'});}}if(d['length']===0x0){const m=suggestTemplateForIntent(a);m&&d['push']({'template':m,'rationale':'Intent\x20keyword\x20match'});}if(d['length']===0x0){const n=getAllTemplates();n['length']>0x0&&d['push']({'template':n[0x0],'rationale':'Default\x20(no\x20specific\x20match)'});}let e;if(d['length']>0x0){const o=initPuzzleFromTemplate(d[0x0]['template']['id']);e=o??initPuzzleFromIntent(a);}else e=initPuzzleFromIntent(a);const f=matchSemanticPattern(a),g=f??null;let h=null;b&&b['recommended_topology']['length']>0x0&&(h=b['recommended_topology'][0x0]);const i=checkPuzzleCompleteness(e),j=i['next_step'];return{'matched_scene':b??null,'confidence':c,'suggested_templates':d,'initial_puzzle':e,'recommended_pattern':g,'recommended_topology':h,'next_step':j};}export function buildPromptFromContext(a){const b=[];b['push']('#\x20Machine\x20Design\x20Context\x20(mode:\x20'+a['mode']+')'),b['push'](''),b['push']('>\x20Context\x20injected\x20by\x20machine-context.ts.\x20Reflects\x20verified\x20on-chain\x20behavior.'),b['push']('');a['matched_scene']&&(b['push']('##\x20Matched\x20Scene'),b['push'](''),b['push']('-\x20**ID**:\x20'+a['matched_scene']['id']),b['push']('-\x20**Name**:\x20'+a['matched_scene']['name']),b['push']('-\x20**Scenario**:\x20'+a['matched_scene']['scenario']),b['push']('-\x20**Industry**:\x20'+a['matched_scene']['industry']['join'](',\x20')),b['push']('-\x20**Recommended\x20patterns**:\x20'+a['matched_scene']['recommended_patterns']['join'](',\x20')),b['push']('-\x20**Recommended\x20topology**:\x20'+a['matched_scene']['recommended_topology']['join'](',\x20')),b['push'](''));if(a['suggested_templates']['length']>0x0){b['push']('##\x20Suggested\x20Templates'),b['push']('');for(const e of a['suggested_templates']){b['push']('###\x20'+e['id']+':\x20'+e['name']),b['push'](''),b['push']('-\x20**Scene**:\x20'+e['scene_id']),b['push']('-\x20**Description**:\x20'+e['description']);if(e['parameters']['length']>0x0){b['push']('-\x20**Parameters**:');for(const f of e['parameters']){b['push']('\x20\x20-\x20`'+f['name']+'`\x20('+f['type']+'):\x20'+f['description']);}}b['push']('');}}if(a['relevant_patterns']['length']>0x0){b['push']('##\x20Relevant\x20Patterns'),b['push']('');for(const g of a['relevant_patterns']){b['push']('###\x20'+g['id']+':\x20'+g['pattern_name']),b['push'](''),b['push']('-\x20**Category**:\x20'+g['category']),b['push']('-\x20**Intent**:\x20'+g['semantic_intent']),g['match_keywords']['length']>0x0&&b['push']('-\x20**Keywords**:\x20'+g['match_keywords']['join'](',\x20')),b['push']('');}}if(a['relevant_constraints']['length']>0x0){b['push']('##\x20Relevant\x20Constraints'),b['push']('');for(const i of a['relevant_constraints']){b['push']('-\x20**'+i['id']+'**\x20('+i['category']+',\x20'+(i['on_chain_enforced']?'on-chain':'off-chain')+'):\x20'+i['description']);}b['push']('');}if(a['relevant_risks']['length']>0x0){b['push']('##\x20Relevant\x20Risks'),b['push']('');for(const j of a['relevant_risks']){b['push']('-\x20**'+j['id']+'**\x20['+j['severity']+']\x20'+j['name']+':\x20'+j['description']),b['push']('\x20\x20-\x20Fix:\x20'+j['recommendation']);}b['push']('');}if(a['puzzle_state']&&a['puzzle_completeness']){b['push']('##\x20Puzzle\x20State'),b['push'](''),b['push']('-\x20**Complete**:\x20'+a['puzzle_completeness']['complete']),b['push']('-\x20**Next\x20step**:\x20'+a['puzzle_completeness']['next_step']),b['push'](''),b['push']('###\x20Per-dimension\x20completeness:');for(const k of a['puzzle_completeness']['dimensions']){const l=k['complete']?'✓':'✗';b['push']('\x20\x20-\x20'+l+'\x20'+k['dimension']),!k['complete']&&k['missing_fields']['length']>0x0&&b['push']('\x20\x20\x20\x20-\x20Missing:\x20'+k['missing_fields']['join'](',\x20'));}b['push']('');}a['topology_analysis']&&(b['push']('##\x20Topology\x20Analysis'),b['push'](''),b['push']('```'),b['push'](formatTopologySummary(a['topology_analysis'])),b['push']('```'),b['push'](''));if(a['risk_assessment']){b['push']('##\x20Risk\x20Assessment'),b['push'](''),b['push']('-\x20**Overall\x20level**:\x20'+a['risk_assessment']['overall_level']),b['push']('-\x20**Recommendation**:\x20'+a['risk_assessment']['recommendation']),b['push']('-\x20**Summary**:\x20'+JSON['stringify'](a['risk_assessment']['summary']));if(a['risk_assessment']['detected_risks']['length']>0x0){b['push'](''),b['push']('###\x20Detected\x20risks:');for(const o of a['risk_assessment']['detected_risks']){b['push']('-\x20['+o['severity']+']\x20'+o['name']+':\x20'+o['detail']);}}b['push']('');}if(a['progressive_check_result']){const q=a['progressive_check_result'];b['push']('##\x20Progressive\x20Checklist\x20Result\x20(R5)'),b['push'](''),b['push']('-\x20**Passed**:\x20'+q['passed']);if(q['checked_items']['length']>0x0){b['push'](''),b['push']('###\x20Checked\x20items:');for(const s of q['checked_items']){b['push']('\x20\x20-\x20['+s['status']+']\x20'+s['id']+':\x20'+s['description']),s['detail']&&b['push']('\x20\x20\x20\x20-\x20'+s['detail']);}}b['push']('');}if(a['guard_bridge']){b['push']('##\x20Guard\x20Bridge'),b['push'](''),b['push']('Machine\x20scene\x20`'+a['guard_bridge']['machine_scene_id']+'`\x20relates\x20to:'),b['push']('');for(const u of a['guard_bridge']['forward_guard_mapping']){b['push']('-\x20Forward\x20\x22'+u['forward_purpose']+'\x22\x20→\x20Guard\x20scene\x20`'+u['guard_scene_id']+'`\x20('+u['guard_scene_name']+')');}b['push']('');}if(a['prompt_hints']['length']>0x0){b['push']('##\x20Prompt\x20Hints'),b['push']('');for(const v of a['prompt_hints']){b['push']('-\x20'+v);}b['push']('');}if(a['verification_notes']['length']>0x0){b['push']('##\x20Verification\x20Notes\x20(06\x20§14)'),b['push'](''),b['push']('>\x20These\x20notes\x20reflect\x20code-level\x20verification\x20of\x20on-chain\x20behavior.');for(const w of a['verification_notes']){b['push'](''),b['push']('-\x20**'+w['topic']+'**\x20('+w['judgment']+'):\x20'+w['verified_semantic']),b['push']('\x20\x20-\x20Code\x20reference:\x20`'+w['code_reference']+'`');}b['push']('');}return b['push']('##\x20Recommended\x20Next\x20Action'),b['push'](''),b['push'](a['recommended_next_action']),b['push'](''),b['join']('\x0a');}export function getRelatedGuardScenes(a){const b=findScene(a);if(!b)return[];const c=new Set();for(const d of b['guard_requirements']){c['add'](d['scene']);}return GUARD_SCENES['filter'](e=>c['has'](e['id']));}export function getVerificationNotes(a){if(!a)return MACHINE_VERIFICATION_NOTES;return MACHINE_VERIFICATION_NOTES['filter'](b=>b['affected_modes']['includes'](a));}export function identifyCrossMachineDependency(a,b,c,d){const e=[];for(const f of b['pairs']){const g=f['prev_node']+'->'+f['next_node'];for(const h of f['forwards']){if(!h['guard'])continue;const i=c['get'](h['guard']);if(!i)continue;e['push']({'machine_a_id':a,'machine_b_id':i['upstream_machine_id'],'machine_b_published':d?d['has'](i['upstream_machine_id']):![],'dependency':{'machine_a_forward':g+':'+h['name'],'machine_b_node':i['upstream_node_name']},'guard_query':i['guard_query_description']});}}return e;}export function detectCrossMachineCycle(a){const b=new Map();for(const j of a){if(!b['has'](j['machine_a_id']))b['set'](j['machine_a_id'],new Set());b['get'](j['machine_a_id'])['add'](j['machine_b_id']);if(!b['has'](j['machine_b_id']))b['set'](j['machine_b_id'],new Set());}const c=[],d=0x0,e=0x1,f=0x2,g=new Map();for(const k of b['keys']())g['set'](k,d);const h=[],i=l=>{g['set'](l,e),h['push'](l);const m=b['get'](l)??new Set();for(const n of m){const o=g['get'](n)??d;if(o===e){const p=h['indexOf'](n),q=h['slice'](p)['concat']([n]);c['push'](q);}else o===d&&i(n);}h['pop'](),g['set'](l,f);};for(const l of b['keys']()){g['get'](l)===d&&i(l);}return c;}export function aggregateProjectDependencies(a,b){const c=[];for(const d of a){const e=identifyCrossMachineDependency(d['machine_id'],d['machine_json'],d['guard_resolutions'],b);c['push'](...e);}return c;}function filterPatternsByMode(a,b){switch(b){case'cross_machine':return a['filter'](c=>c['id']==='P-M-CROSS-MACHINE');case'allocation_integration':return a['filter'](c=>c['id']==='P-M-ALLOCATION-INTEGRATED');case'guard_integration':return a['filter'](c=>c['match_keywords']['some'](d=>['guard','validation']['some'](e=>d['toLowerCase']()['includes'](e['toLowerCase']())))||c['semantic_intent']['toLowerCase']()['includes']('guard'));case'post_publish_runtime':return a['filter'](c=>c['category']==='execution'&&['and','or','vote','hybrid']['some'](d=>c['pattern_name']['toLowerCase']()['includes'](d)));default:return a;}}function filterConstraintsByMode(a,b){switch(b){case'initial_design':case'intent_match':return a['filter'](d=>d['category']==='creation');case'mid_design_review':return a['filter'](d=>['creation','structure','node_operation']['includes'](d['category']));case'pre_publish_check':return a['filter'](d=>['publish','structure','node_operation']['includes'](d['category']));case'post_publish_runtime':return a['filter'](d=>d['category']==='runtime');case'cross_machine':return a['filter'](d=>['structure','publish']['includes'](d['category']));case'guard_integration':return a['filter'](d=>d['description']['toLowerCase']()['includes']('guard')||d['description']['toLowerCase']()['includes']('forward'));case'allocation_integration':return a['filter'](d=>d['description']['toLowerCase']()['includes']('allocator')||d['description']['toLowerCase']()['includes']('terminal')||d['description']['toLowerCase']()['includes']('allocation'));default:return a;}}function filterRisksByMode(a,b){switch(b){case'initial_design':case'intent_match':return a['filter'](c=>['structural','permission']['includes'](c['category']));case'mid_design_review':return a['filter'](c=>['structural','guard_integration','permission']['includes'](c['category']));case'pre_publish_check':return a['slice']()['sort']((c,d)=>severityRank(d['severity'])-severityRank(c['severity']));case'post_publish_runtime':return a['filter'](c=>c['category']==='environment');case'cross_machine':return a['filter'](c=>c['category']==='guard_integration');case'guard_integration':return a['filter'](c=>c['category']==='guard_integration');case'allocation_integration':return a['filter'](c=>c['description']['toLowerCase']()['includes']('allocator')||c['description']['toLowerCase']()['includes']('allocation')||c['description']['toLowerCase']()['includes']('terminal'));default:return a;}}function severityRank(a){switch(a){case'critical':return 0x5;case'high':return 0x4;case'medium':return 0x3;case'low':return 0x2;}}function buildGuardBridge(a){const b=new Set(),c=[];for(const e of a['guard_requirements']){b['add'](e['scene']);const f=GUARD_SCENES['find'](h=>h['id']===e['scene']);c['push']({'forward_purpose':e['purpose'],'guard_scene_id':e['scene'],'guard_scene_name':f?.['name']||e['scene']});}const d=GUARD_SCENES['filter'](h=>b['has'](h['id']));return{'machine_scene_id':a['id'],'guard_scenes':d,'forward_guard_mapping':c};}function buildPromptHints(a){const b=[];switch(a['mode']){case'initial_design':case'intent_match':b['push']('Start\x20by\x20confirming\x20the\x20matched\x20scene\x20and\x20selecting\x20a\x20template.');a['matched_scene']&&(b['push']('Scene\x20\x22'+a['matched_scene']['name']+'\x22\x20recommends\x20patterns:\x20'+a['matched_scene']['recommended_patterns']['join'](',\x20')+'.'),a['matched_scene']['first_node_semantics']&&b['push']('First-node\x20semantics:\x20'+a['matched_scene']['first_node_semantics']));b['push']('⚠\x20First\x20node\x20convention:\x20For\x20Service-bound\x20Machines,\x20the\x20entry\x20node\x20(prev_node=\x27\x27\x20target)\x20MUST\x20represent\x20a\x20POST-PAYMENT\x20state\x20(e.g.\x20\x27Paid\x27,\x20\x27DepositPaid\x27).\x20Do\x20NOT\x20add\x20\x27Order\x27/\x27Pay\x27/\x27Reserve\x27/\x27Subscribe\x27\x20nodes\x20—\x20Service.buy()\x20handles\x20payment\x20atomically\x20before\x20Progress\x20is\x20created.');a['suggested_templates']['length']>0x0&&b['push']('Top\x20template\x20suggestion:\x20'+a['suggested_templates'][0x0]['id']+'\x20('+a['suggested_templates'][0x0]['name']+').');break;case'mid_design_review':a['puzzle_completeness']&&(a['puzzle_completeness']['complete']?b['push']('Puzzle\x20is\x20complete.\x20Proceed\x20to\x20pre-publish\x20check.'):b['push']('Puzzle\x20incomplete.\x20Next\x20step:\x20'+a['puzzle_completeness']['next_step']));a['topology_analysis']&&(a['topology_analysis']['has_cycles']&&b['push']('⚠\x20Cycle\x20detected\x20in\x20topology\x20—\x20must\x20fix\x20before\x20publish.'),a['topology_analysis']['orphaned_nodes']['length']>0x0&&b['push']('⚠\x20Orphaned\x20nodes:\x20'+a['topology_analysis']['orphaned_nodes']['join'](',\x20')));break;case'pre_publish_check':if(a['risk_assessment']){if(a['risk_assessment']['overall_level']==='critical')b['push']('⛔\x20CRITICAL\x20risk\x20detected\x20—\x20DO\x20NOT\x20publish\x20until\x20resolved.');else a['risk_assessment']['overall_level']==='high'&&b['push']('⚠\x20HIGH\x20risk\x20—\x20fix\x20before\x20publish\x20or\x20override\x20with\x20explicit\x20reason.');b['push']('Risk\x20recommendation:\x20'+a['risk_assessment']['recommendation']);}if(a['progressive_check_result']){if(!a['progressive_check_result']['passed']){const c=a['progressive_check_result']['checked_items']['filter'](d=>d['status']!=='pass')['map'](d=>d['id']);b['push']('⛔\x20Pre-publish\x20checklist\x20FAILED\x20on:\x20'+(c['join'](',\x20')||'see\x20details'));}else b['push']('✓\x20Pre-publish\x20checklist\x20(R5)\x20passed.');}b['push']('Run\x20full\x20confirmPublish()\x20with\x20user\x20confirmation\x20before\x20any\x20on-chain\x20publish\x20transaction.');break;case'post_publish_runtime':b['push']('Machine\x20is\x20already\x20published\x20—\x20nodes\x20cannot\x20be\x20modified.'),b['push']('Only\x20progress\x20advancement\x20(Forward\x20execution)\x20is\x20possible.');a['topology_analysis']&&b['push']('Current\x20topology:\x20'+(a['topology_analysis']['within_limits']?'within\x20on-chain\x20limits':'EXCEEDS\x20limits'));break;case'cross_machine':b['push']('Cross-Machine\x20dependency\x20is\x20INDIRECT:\x20Machine\x20A\x20queries\x20Machine\x20B\x27s\x20Progress\x20via\x20convert_witness.'),b['push']('Machine\x20B\x20MUST\x20be\x20published\x20before\x20Progress::new\x20can\x20create\x20a\x20Progress\x20for\x20it\x20(assert_published).'),b['push']('Use\x20convert_witness\x20TypeOrderProgress\x20(100)\x20or\x20TypeOrderProgressSession\x20(103)\x20in\x20Guard\x20queries.');break;case'guard_integration':if(a['guard_bridge']){b['push']('This\x20scene\x20integrates\x20with\x20'+a['guard_bridge']['guard_scenes']['length']+'\x20Guard\x20scene(s).');for(const d of a['guard_bridge']['forward_guard_mapping']){b['push']('\x20\x20-\x20Forward\x20\x22'+d['forward_purpose']+'\x22\x20→\x20Guard\x20scene:\x20'+d['guard_scene_name']);}}b['push']('Forward.guard\x20cannot\x20be\x20modified\x20after\x20Machine\x20publish\x20(immutable).'),b['push']('Use\x20machine_forward_guard\x20scene\x20from\x20guard-ledger.ts\x20for\x20Guard\x20design.');break;case'allocation_integration':b['push']('Terminal\x20nodes\x20map\x20to\x20Service\x20order_allocators.'),b['push']('order_allocators\x20is\x20order-sensitive\x20(first-match-wins).'),b['push']('Each\x20Allocator\x20requires\x20a\x20UNIQUE\x20Guard\x20object\x20(no\x20two\x20allocators\x20may\x20share\x20the\x20same\x20Guard).'),b['push']('order_allocators\x20CANNOT\x20be\x20modified\x20after\x20Service\x20publish\x20(immutable).');break;}for(const e of a['verification_notes']){b['push']('[Verified\x20'+e['judgment']+']\x20'+e['topic']+':\x20'+e['verified_semantic']);}return b['push']('On-chain\x20limits:\x20MAX_NODE_COUNT='+MAX_NODE_COUNT+',\x20MAX_NODE_PAIR_COUNT='+MAX_NODE_PAIR_COUNT+',\x20MAX_FORWARD_COUNT='+MAX_FORWARD_COUNT+'.'),b;}function recommendNextAction(a,b){switch(a){case'initial_design':case'intent_match':{if(!b['matched_scene'])return'Ask\x20the\x20user\x20to\x20clarify\x20the\x20business\x20scenario\x20—\x20no\x20scene\x20matched.';if(b['suggested_templates']['length']===0x0)return'Scene\x20\x22'+b['matched_scene']['name']+'\x22\x20matched\x20but\x20no\x20template\x20available\x20—\x20design\x20Machine\x20manually\x20using\x20the\x20scene\x27s\x20recommended\x20patterns.';return'Present\x20template\x20\x22'+b['suggested_templates'][0x0]['id']+'\x22\x20to\x20user.\x20After\x20user\x20confirms,\x20fill\x20parameters\x20and\x20initialize\x20puzzle.';}case'mid_design_review':{if(!b['puzzle_completeness'])return'Initialize\x20puzzle\x20state\x20and\x20re-run\x20injection\x20with\x20existing_puzzle\x20option.';if(b['puzzle_completeness']['complete'])return'Puzzle\x20complete.\x20Proceed\x20to\x20pre_publish_check\x20mode.';return'Complete\x20missing\x20puzzle\x20dimensions:\x20'+b['puzzle_completeness']['next_step'];}case'pre_publish_check':{if(b['progressive_check_result']&&!b['progressive_check_result']['passed']){const c=b['progressive_check_result']['failed_items']['map'](d=>d['id'])['join'](',\x20');return'⛔\x20Pre-publish\x20checklist\x20FAILED\x20on:\x20'+(c||'see\x20checklist\x20result')+'.\x20Fix\x20these\x20items\x20before\x20proceeding.';}if(b['risk_assessment']){if(b['risk_assessment']['overall_level']==='critical')return'⛔\x20CRITICAL\x20risk\x20—\x20DO\x20NOT\x20publish.\x20Fix\x20risks\x20first.';if(b['risk_assessment']['overall_level']==='high')return'⚠\x20HIGH\x20risk\x20—\x20fix\x20risks\x20OR\x20obtain\x20explicit\x20user\x20override\x20with\x20reason.';}return'All\x20checks\x20passed.\x20Present\x20confirmation\x20text\x20to\x20user\x20and\x20obtain\x20explicit\x20approval\x20before\x20publish\x20transaction.';}case'post_publish_runtime':return'Machine\x20is\x20published.\x20Use\x20onchain_operations\x20to\x20execute\x20Forward\x20advancements.\x20Monitor\x20Progress\x20state\x20via\x20query\x20tool.';case'cross_machine':return'Design\x20Machine\x20A\x27s\x20Forward.guard\x20to\x20query\x20Machine\x20B\x27s\x20Progress\x20via\x20convert_witness=100.\x20Ensure\x20Machine\x20B\x20is\x20published\x20first.';case'guard_integration':return'For\x20each\x20Forward.guard\x20binding,\x20design\x20the\x20Guard\x20using\x20the\x20related\x20Guard\x20scene.\x20Use\x20guard-ledger\x20+\x20guard-templates\x20+\x20guard-puzzle\x20modules.';case'allocation_integration':return'Map\x20each\x20terminal\x20node\x20to\x20an\x20Allocator\x20in\x20Service.order_allocators.\x20Each\x20Allocator\x20needs\x20a\x20unique\x20Guard\x20object.\x20Configure\x20sharing.who\x20(prefer\x20Entity\x20over\x20Signer).';default:return'Proceed\x20with\x20current\x20task.';}}export const CONTEXT_PRESETS={'newUserIntent':a=>injectMachineContext(a,'intent_match',{'max_templates':0x2,'max_constraints':0x5,'max_risks':0x3,'include_verification_notes':![],'include_guard_bridge':![]}),'midDesignReview':(a,b)=>injectMachineContext(a,'mid_design_review',{'max_templates':0x1,'max_constraints':0xf,'max_risks':0xa,'include_verification_notes':!![],'include_guard_bridge':![],'existing_puzzle':b}),'prePublishFull':(a,b,c)=>injectMachineContext(a,'pre_publish_check',{'max_templates':0x0,'max_constraints':0x14,'max_risks':0x27,'include_verification_notes':!![],'include_guard_bridge':!![],'existing_machine_json':b,'project_context':c}),'crossMachine':a=>injectMachineContext(a,'cross_machine',{'max_templates':0x2,'max_constraints':0xa,'max_risks':0x8,'include_verification_notes':!![],'include_guard_bridge':!![]}),'guardIntegration':a=>injectMachineContext(a,'guard_integration',{'max_templates':0x1,'max_constraints':0xa,'max_risks':0x8,'include_verification_notes':!![],'include_guard_bridge':!![]}),'allocationIntegration':a=>injectMachineContext(a,'allocation_integration',{'max_templates':0x1,'max_constraints':0x8,'max_risks':0x8,'include_verification_notes':![],'include_guard_bridge':![]})};