@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,843 +1 @@
1
- import * as fs from 'fs';
2
- import * as path from 'path';
3
- import { analyzeTopology, } from "./machine-topology.js";
4
- import { assessMachineRisks, } from "./machine-risk.js";
5
- import { runStaticChecklist, } from "./machine-confirm.js";
6
- import { explainNode, } from "./machine-translation.js";
7
- import { identifyCrossMachineDependency, detectCrossMachineCycle, } from "./machine-context.js";
8
- export function getMachineName(op) {
9
- if (typeof op.data.object === 'string')
10
- return op.data.object;
11
- return op.data.object.name;
12
- }
13
- const EXAMPLES_DIR = path.resolve('d:/wowok/docs/examples');
14
- export function nodeDefsToMachine(nodeDefs) {
15
- const nodes = [];
16
- const pairs = [];
17
- const seenNodeNames = new Set();
18
- for (const nodeDef of nodeDefs) {
19
- if (!seenNodeNames.has(nodeDef.name)) {
20
- nodes.push({ name: nodeDef.name });
21
- seenNodeNames.add(nodeDef.name);
22
- }
23
- for (const p of nodeDef.pairs) {
24
- pairs.push({
25
- prev_node: p.prev_node,
26
- next_node: nodeDef.name,
27
- threshold: p.threshold,
28
- forwards: p.forwards.map((f) => normalizeForward(f)),
29
- });
30
- }
31
- }
32
- return { nodes, pairs };
33
- }
34
- function normalizeForward(f) {
35
- const namedOp = f.named_operator ?? f.namedOperator;
36
- const permIdx = f.permission_index ?? f.permissionIndex;
37
- let guard;
38
- if (typeof f.guard === 'string') {
39
- guard = f.guard;
40
- }
41
- else if (f.guard && typeof f.guard === 'object') {
42
- const g = f.guard;
43
- if (typeof g.guard === 'string')
44
- guard = g.guard;
45
- }
46
- let retained;
47
- if (f.retained_submission !== undefined && f.retained_submission !== null) {
48
- if (typeof f.retained_submission === 'string') {
49
- retained = f.retained_submission;
50
- }
51
- else if (Array.isArray(f.retained_submission)) {
52
- retained = f.retained_submission;
53
- }
54
- else if (typeof f.retained_submission === 'object') {
55
- const r = f.retained_submission;
56
- if (r.retained_submission !== undefined) {
57
- retained = r.retained_submission;
58
- }
59
- }
60
- }
61
- else if (f.guard && typeof f.guard === 'object') {
62
- const g = f.guard;
63
- if (g.retained_submission !== undefined && g.retained_submission !== null) {
64
- if (Array.isArray(g.retained_submission)) {
65
- retained = g.retained_submission;
66
- }
67
- else if (typeof g.retained_submission === 'string') {
68
- retained = g.retained_submission;
69
- }
70
- }
71
- }
72
- return {
73
- name: f.name,
74
- weight: f.weight,
75
- named_operator: namedOp,
76
- permission_index: permIdx,
77
- guard,
78
- retained_submission: retained,
79
- };
80
- }
81
- function extractJsonBlocks(mdPath) {
82
- const content = fs.readFileSync(mdPath, 'utf-8');
83
- const lines = content.split('\n');
84
- const blocks = [];
85
- let i = 0;
86
- while (i < lines.length) {
87
- const line = lines[i];
88
- if (line.trim().startsWith('```json')) {
89
- const blockLines = [];
90
- let j = i + 1;
91
- while (j < lines.length && !lines[j].trim().startsWith('```')) {
92
- blockLines.push(lines[j]);
93
- j++;
94
- }
95
- const raw = blockLines.join('\n');
96
- try {
97
- const parsed = JSON.parse(raw);
98
- let json = null;
99
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
100
- const p = parsed;
101
- if (p.tool === 'onchain_operations' && p.data && typeof p.data === 'object'
102
- && !Array.isArray(p.data)) {
103
- const inner = p.data;
104
- if (typeof inner.operation_type === 'string') {
105
- json = {
106
- operation_type: inner.operation_type,
107
- data: inner.data,
108
- ...(inner.env !== undefined ? { env: inner.env } : {}),
109
- };
110
- }
111
- }
112
- else if (typeof p.operation_type === 'string') {
113
- json = p;
114
- }
115
- }
116
- if (json && typeof json.operation_type === 'string') {
117
- blocks.push({ lineStart: i + 1, raw, json });
118
- }
119
- }
120
- catch {
121
- }
122
- i = j + 1;
123
- }
124
- else {
125
- i++;
126
- }
127
- }
128
- return blocks;
129
- }
130
- function extractDefinedGuardNames(mdPath) {
131
- const blocks = extractJsonBlocks(mdPath);
132
- const names = new Set();
133
- for (const b of blocks) {
134
- if (b.json.operation_type !== 'guard')
135
- continue;
136
- const data = b.json.data;
137
- if (!data)
138
- continue;
139
- const namedNew = data.namedNew;
140
- const name = namedNew?.name;
141
- if (name)
142
- names.add(name);
143
- }
144
- return names;
145
- }
146
- export function loadAllExamples(examplesDir = EXAMPLES_DIR) {
147
- const result = [];
148
- if (!fs.existsSync(examplesDir))
149
- return result;
150
- const entries = fs.readdirSync(examplesDir, { withFileTypes: true });
151
- for (const entry of entries) {
152
- if (!entry.isDirectory())
153
- continue;
154
- const subdir = path.join(examplesDir, entry.name);
155
- const subEntries = fs.readdirSync(subdir, { withFileTypes: true });
156
- for (const sub of subEntries) {
157
- if (!sub.isFile())
158
- continue;
159
- const fullPath = path.join(subdir, sub.name);
160
- const relativePath = `${entry.name}/${sub.name}`;
161
- if (sub.name.endsWith('.md')) {
162
- const machineOps = extractMachineOpsFromMarkdown(fullPath);
163
- const progressOps = extractProgressOpsFromMarkdown(fullPath);
164
- const definedGuards = extractDefinedGuardNames(fullPath);
165
- if (machineOps.length === 0 && progressOps.length === 0 && definedGuards.size === 0)
166
- continue;
167
- const businessDescription = machineOps[0]?.op.data.description;
168
- result.push({
169
- example_name: entry.name,
170
- relative_path: relativePath,
171
- absolute_path: fullPath,
172
- machine_ops: machineOps,
173
- progress_ops: progressOps,
174
- defined_guard_names: definedGuards,
175
- business_description: businessDescription,
176
- });
177
- }
178
- else if (sub.name.endsWith('.json') && sub.name.includes('machine')) {
179
- const raw = fs.readFileSync(fullPath, 'utf-8');
180
- try {
181
- const arr = JSON.parse(raw);
182
- if (!Array.isArray(arr) || arr.length === 0)
183
- continue;
184
- const machineName = path.basename(sub.name, '.json');
185
- result.push({
186
- example_name: entry.name,
187
- relative_path: relativePath,
188
- absolute_path: fullPath,
189
- machine_ops: [{
190
- op: {
191
- operation_type: "machine",
192
- data: {
193
- object: { name: machineName, replaceExistName: false },
194
- node: { op: "add", nodes: arr },
195
- publish: false,
196
- },
197
- env: { network: "testnet" },
198
- },
199
- line_start: 0,
200
- }],
201
- progress_ops: [],
202
- defined_guard_names: new Set(),
203
- business_description: `(standalone JSON: ${machineName})`,
204
- });
205
- }
206
- catch {
207
- }
208
- }
209
- }
210
- }
211
- return result;
212
- }
213
- function extractMachineOpsFromMarkdown(mdPath) {
214
- const blocks = extractJsonBlocks(mdPath);
215
- const result = [];
216
- for (const b of blocks) {
217
- if (b.json.operation_type !== 'machine')
218
- continue;
219
- try {
220
- const op = b.json;
221
- if (!op.data)
222
- continue;
223
- const hasNodes = op.data.node?.nodes && Array.isArray(op.data.node.nodes);
224
- const hasPublish = op.data.publish === true;
225
- if (!hasNodes && !hasPublish)
226
- continue;
227
- result.push({ op, line_start: b.lineStart });
228
- }
229
- catch {
230
- }
231
- }
232
- return result;
233
- }
234
- function extractProgressOpsFromMarkdown(mdPath) {
235
- const blocks = extractJsonBlocks(mdPath);
236
- const result = [];
237
- for (const b of blocks) {
238
- const json = b.json;
239
- const data = json.data;
240
- if (!data)
241
- continue;
242
- const progress = data.progress;
243
- if (!progress)
244
- continue;
245
- const operation = progress.operation;
246
- if (!operation || !operation.next_node_name || !operation.forward)
247
- continue;
248
- try {
249
- result.push({
250
- operation_type: json.operation_type,
251
- data: {
252
- object: data.object,
253
- progress: { operation: { next_node_name: operation.next_node_name, forward: operation.forward } },
254
- submission: data.submission,
255
- },
256
- env: { account: json.env?.account, network: json.env?.network },
257
- _source_line: b.lineStart,
258
- });
259
- }
260
- catch {
261
- }
262
- }
263
- return result;
264
- }
265
- export function analyzeSchemaConsistency(_example) {
266
- return [];
267
- }
268
- export function analyzeThresholdIssues(example) {
269
- const findings = [];
270
- for (const { op, line_start } of example.machine_ops) {
271
- if (!op.data.node?.nodes)
272
- continue;
273
- const { nodes, pairs } = nodeDefsToMachine(op.data.node.nodes);
274
- const machineName = getMachineName(op);
275
- const entryPairs = pairs.filter((p) => p.prev_node === "");
276
- const hasCompetingEntries = entryPairs.length > 1;
277
- for (const pair of pairs) {
278
- if (pair.prev_node === "" && pair.threshold === 0) {
279
- const forwardCount = pair.forwards.length;
280
- const isLegitimate = forwardCount === 1 ||
281
- hasCompetingEntries;
282
- if (isLegitimate)
283
- continue;
284
- findings.push({
285
- example: example.example_name,
286
- source_file: example.relative_path,
287
- line: line_start,
288
- machine_name: machineName,
289
- category: "design",
290
- severity: "medium",
291
- title: "Entry pair with threshold=0 and multiple Forwards (potential permission bypass)",
292
- detail: `Pair (prev="", next="${pair.next_node}") has threshold=0 with ${forwardCount} Forwards. ` +
293
- `With threshold=0, ANY single Forward fires → migration, potentially bypassing other Forwards' ` +
294
- `permission checks. Set threshold ≥ 1 so ALL intended Forwards must agree. ` +
295
- `(Note: single-Forward Pairs and competing-OR Pairs with threshold=0 are NOT flagged — they are legitimate.)`,
296
- rule_id: "R-M3-09",
297
- fix: `Set threshold=1 (or higher) on entry pair targeting "${pair.next_node}" if Forwards represent AND semantics; keep threshold=0 if OR semantics is intended (then consider splitting into competing Pairs).`,
298
- });
299
- }
300
- }
301
- for (const pair of pairs) {
302
- const totalWeight = pair.forwards.reduce((sum, f) => sum + f.weight, 0);
303
- if (pair.threshold > totalWeight) {
304
- findings.push({
305
- example: example.example_name,
306
- source_file: example.relative_path,
307
- line: line_start,
308
- machine_name: machineName,
309
- category: "design",
310
- severity: "critical",
311
- title: "Threshold exceeds total forward weight (unreachable)",
312
- detail: `Pair (prev="${pair.prev_node}", next="${pair.next_node}") has threshold=${pair.threshold} but total forward weight=${totalWeight}. This pair can NEVER be satisfied — workflow dead-ends here.`,
313
- rule_id: "R-M2-06",
314
- fix: `Reduce threshold to ≤ ${totalWeight} or add more forwards with weight.`,
315
- });
316
- }
317
- }
318
- }
319
- return findings;
320
- }
321
- export function analyzeNetworkSafety(example) {
322
- const findings = [];
323
- for (const { op, line_start } of example.machine_ops) {
324
- const machineName = getMachineName(op);
325
- const isPublish = op.data.publish === true;
326
- const network = op.env.network;
327
- if (isPublish && network === "mainnet") {
328
- findings.push({
329
- example: example.example_name,
330
- source_file: example.relative_path,
331
- line: line_start,
332
- machine_name: machineName,
333
- category: "runtime",
334
- severity: "critical",
335
- title: "Direct mainnet publish without testnet test",
336
- detail: `Machine "${machineName}" is published directly to mainnet. Per R-M4-02, must test on testnet first.`,
337
- rule_id: "R-M4-02",
338
- fix: `Set env.network to "testnet" for first publish, run end-to-end test, then re-publish on mainnet.`,
339
- });
340
- }
341
- }
342
- return findings;
343
- }
344
- export function analyzeConfirmationBypass(example) {
345
- const findings = [];
346
- for (const { op, line_start } of example.machine_ops) {
347
- const machineName = getMachineName(op);
348
- const isPublish = op.data.publish === true;
349
- const confirmed = op.env.confirmed === true;
350
- if (isPublish && confirmed) {
351
- findings.push({
352
- example: example.example_name,
353
- source_file: example.relative_path,
354
- line: line_start,
355
- machine_name: machineName,
356
- category: "runtime",
357
- severity: "medium",
358
- title: "confirmed=true bypasses user confirmation prompt",
359
- detail: `Machine "${machineName}" is published with env.confirmed=true. This bypasses the ConfirmGate user-confirmation step. Examples should demonstrate the two-step confirmation flow (Phase 1 prompt → Phase 2 confirmed=true).`,
360
- rule_id: "R-M4-04",
361
- fix: `Show Phase 1 (without confirmed=true) and Phase 2 (with confirmed=true) as separate steps in the example.`,
362
- });
363
- }
364
- }
365
- return findings;
366
- }
367
- export function analyzeGuardReferences(example) {
368
- const findings = [];
369
- const defined = example.defined_guard_names;
370
- for (const { op, line_start } of example.machine_ops) {
371
- if (!op.data.node?.nodes)
372
- continue;
373
- const machineName = getMachineName(op);
374
- const isPublish = op.data.publish === true;
375
- for (const nodeDef of op.data.node.nodes) {
376
- for (const pair of nodeDef.pairs) {
377
- for (const fwd of pair.forwards) {
378
- let guardName;
379
- if (typeof fwd.guard === 'string') {
380
- guardName = fwd.guard;
381
- }
382
- else if (fwd.guard && typeof fwd.guard === 'object') {
383
- const g = fwd.guard;
384
- if (typeof g.guard === 'string')
385
- guardName = g.guard;
386
- }
387
- if (!guardName)
388
- continue;
389
- if (!defined.has(guardName)) {
390
- findings.push({
391
- example: example.example_name,
392
- source_file: example.relative_path,
393
- line: line_start,
394
- machine_name: machineName,
395
- category: "runtime",
396
- severity: isPublish ? "critical" : "high",
397
- title: `Guard "${guardName}" referenced but not defined in example`,
398
- detail: `Forward "${fwd.name}" references Guard "${guardName}" but no operation_type="guard" with name="${guardName}" appears earlier in ${example.relative_path}. ${isPublish ? "Publishing will fail at runtime." : "Will fail at machine creation."}`,
399
- rule_id: isPublish ? "R-M4-03" : "R-M2-01",
400
- fix: `Add a guard creation step (operation_type="guard") with name="${guardName}" BEFORE the machine creation step.`,
401
- });
402
- }
403
- }
404
- }
405
- }
406
- }
407
- return findings;
408
- }
409
- export function analyzeCrossMachineDeps(example, guardResolutions = new Map()) {
410
- const findings = [];
411
- const allDeps = [];
412
- for (const { op, line_start } of example.machine_ops) {
413
- if (!op.data.node?.nodes)
414
- continue;
415
- const { nodes, pairs } = nodeDefsToMachine(op.data.node.nodes);
416
- const machineId = getMachineName(op);
417
- const deps = identifyCrossMachineDependency(machineId, { nodes, pairs }, guardResolutions);
418
- allDeps.push(...deps);
419
- if (deps.length > 0) {
420
- findings.push({
421
- example: example.example_name,
422
- source_file: example.relative_path,
423
- line: line_start,
424
- machine_name: machineId,
425
- category: "cross_machine",
426
- severity: "info",
427
- title: `Machine declares ${deps.length} cross-Machine dependencies`,
428
- detail: deps.map((d) => `Forward "${d.dependency.machine_a_forward}" depends on Machine "${d.machine_b_id}" reaching node "${d.dependency.machine_b_node}"`).join('; '),
429
- rule_id: "P-M3",
430
- });
431
- }
432
- }
433
- const cycles = detectCrossMachineCycle(allDeps);
434
- for (const cycle of cycles) {
435
- findings.push({
436
- example: example.example_name,
437
- source_file: example.relative_path,
438
- line: 0,
439
- machine_name: "(project-level)",
440
- category: "cross_machine",
441
- severity: "critical",
442
- title: "Cross-Machine dependency cycle detected",
443
- detail: `Cycle: ${cycle.join(' → ')}`,
444
- rule_id: "R-M2-07",
445
- fix: `Break the cycle by removing one of the dependencies in the cycle.`,
446
- });
447
- }
448
- return { deps: allDeps, cycles, findings };
449
- }
450
- export function analyzeRoundTrip(example) {
451
- const findings = [];
452
- for (const { op, line_start } of example.machine_ops) {
453
- if (!op.data.node?.nodes)
454
- continue;
455
- const { nodes, pairs } = nodeDefsToMachine(op.data.node.nodes);
456
- const machineName = getMachineName(op);
457
- const topo = analyzeTopology(nodes, pairs);
458
- if (topo.has_cycles) {
459
- findings.push({
460
- example: example.example_name,
461
- source_file: example.relative_path,
462
- line: line_start,
463
- machine_name: machineName,
464
- category: "round_trip",
465
- severity: "critical",
466
- title: "Topology analysis: cycle detected (DAG violation)",
467
- detail: `Machine "${machineName}" has cycles: ${JSON.stringify(topo.cycle_nodes)}`,
468
- rule_id: "R-M1-03",
469
- fix: `Remove cycles — Machine must be a DAG.`,
470
- });
471
- }
472
- const ctx = {
473
- network: op.env.network === "mainnet" ? "mainnet" : "testnet",
474
- testnet_test_passed: op.env.network !== "mainnet",
475
- published_services: new Set(),
476
- published_guards: new Set(),
477
- published_permissions: new Set(),
478
- published_machines: new Set(),
479
- published_arbitrations: new Set(),
480
- published_rewards: new Set(),
481
- published_allocators: new Set(),
482
- published_repositories: new Set(),
483
- };
484
- for (const pair of pairs) {
485
- for (const fwd of pair.forwards) {
486
- if (fwd.guard)
487
- ctx.published_guards.add(fwd.guard);
488
- }
489
- }
490
- const machineJson = {
491
- nodes,
492
- pairs,
493
- b_published: op.data.publish === true,
494
- };
495
- const assessment = assessMachineRisks(machineJson, ctx);
496
- const criticalRisks = assessment.detected_risks.filter((r) => r.severity === "critical");
497
- if (criticalRisks.length > 0) {
498
- for (const r of criticalRisks) {
499
- findings.push({
500
- example: example.example_name,
501
- source_file: example.relative_path,
502
- line: line_start,
503
- machine_name: machineName,
504
- category: "round_trip",
505
- severity: "critical",
506
- title: `Risk assessment: ${r.rule_id} (${r.severity})`,
507
- detail: r.detail,
508
- rule_id: r.rule_id,
509
- });
510
- }
511
- }
512
- const checklist = { nodes, pairs, name: machineName };
513
- const checklistResult = runStaticChecklist(checklist);
514
- const failedItems = checklistResult.failed_items.filter((i) => ["C-01", "C-03", "C-06", "C-10"].includes(i.id));
515
- for (const item of failedItems) {
516
- findings.push({
517
- example: example.example_name,
518
- source_file: example.relative_path,
519
- line: line_start,
520
- machine_name: machineName,
521
- category: "round_trip",
522
- severity: "high",
523
- title: `Checklist ${item.id} failed: ${item.description}`,
524
- detail: item.detail ?? `(no detail)`,
525
- rule_id: item.id,
526
- });
527
- }
528
- for (const node of nodes) {
529
- const outgoing = pairs.filter((p) => p.prev_node === node.name);
530
- const nodeForExpl = {
531
- name: node.name,
532
- pairs: outgoing,
533
- all_pairs: pairs,
534
- };
535
- const explained = explainNode(nodeForExpl);
536
- if (!explained.name || explained.pairs.length !== outgoing.length) {
537
- findings.push({
538
- example: example.example_name,
539
- source_file: example.relative_path,
540
- line: line_start,
541
- machine_name: machineName,
542
- category: "round_trip",
543
- severity: "medium",
544
- title: `Round-trip mismatch for node "${node.name}"`,
545
- detail: `explainNode produced inconsistent output: name="${explained.name}", pairs_count=${explained.pairs.length} (expected ${outgoing.length})`,
546
- rule_id: "RT-001",
547
- });
548
- }
549
- }
550
- }
551
- return findings;
552
- }
553
- export function analyzeProgressOps(example) {
554
- const findings = [];
555
- const validForwardPairs = new Set();
556
- let machineName = "(none)";
557
- for (const { op } of example.machine_ops) {
558
- if (!op.data.node?.nodes)
559
- continue;
560
- machineName = getMachineName(op);
561
- const { pairs } = nodeDefsToMachine(op.data.node.nodes);
562
- for (const pair of pairs) {
563
- validForwardPairs.add(`${pair.next_node}::${pair.forwards.map((f) => f.name).join("|")}`);
564
- for (const fwd of pair.forwards) {
565
- validForwardPairs.add(`${pair.next_node}::${fwd.name}`);
566
- }
567
- }
568
- }
569
- for (const progressOp of example.progress_ops) {
570
- const op = progressOp.data.progress?.operation;
571
- if (!op)
572
- continue;
573
- const key = `${op.next_node_name}::${op.forward}`;
574
- const valid = validForwardPairs.has(key);
575
- if (!valid) {
576
- const forwardExists = [...validForwardPairs].some((k) => k.endsWith(`::${op.forward}`));
577
- if (!forwardExists) {
578
- findings.push({
579
- example: example.example_name,
580
- source_file: example.relative_path,
581
- line: progressOp._source_line ?? 0,
582
- machine_name: machineName,
583
- category: "progress",
584
- severity: "high",
585
- title: `Progress references unknown forward "${op.forward}"`,
586
- detail: `Progress op references forward "${op.forward}" but no such forward exists in machine "${machineName}".`,
587
- rule_id: "R-M3-04",
588
- fix: `Verify forward name matches one defined in the Machine.`,
589
- });
590
- }
591
- else {
592
- findings.push({
593
- example: example.example_name,
594
- source_file: example.relative_path,
595
- line: progressOp._source_line ?? 0,
596
- machine_name: machineName,
597
- category: "progress",
598
- severity: "medium",
599
- title: `Progress forward "${op.forward}" doesn't lead to "${op.next_node_name}"`,
600
- detail: `Forward "${op.forward}" exists but doesn't target node "${op.next_node_name}".`,
601
- rule_id: "R-M3-05",
602
- fix: `Correct next_node_name to match the forward's target.`,
603
- });
604
- }
605
- }
606
- }
607
- return findings;
608
- }
609
- export function analyzePublishStep(example) {
610
- const findings = [];
611
- const hasPublish = example.machine_ops.some(({ op }) => op.data.publish === true);
612
- const hasProgress = example.progress_ops.length > 0;
613
- if (hasProgress && !hasPublish) {
614
- findings.push({
615
- example: example.example_name,
616
- source_file: example.relative_path,
617
- line: 0,
618
- machine_name: "(file-level)",
619
- category: "runtime",
620
- severity: "high",
621
- title: "Progress operations present but no `publish: true` step",
622
- detail: `Example has ${example.progress_ops.length} progress operations but no machine operation with publish=true. Progress::new will fail at runtime (machine not published).`,
623
- rule_id: "R-M4-01",
624
- fix: `Add a publish step (or set data.publish=true on the machine creation operation).`,
625
- });
626
- }
627
- return findings;
628
- }
629
- export function analyzeRiskRuleCoverage(example) {
630
- const ruleCounts = new Map();
631
- let totalFindings = 0;
632
- const allFindings = [
633
- ...analyzeSchemaConsistency(example),
634
- ...analyzeThresholdIssues(example),
635
- ...analyzeNetworkSafety(example),
636
- ...analyzeConfirmationBypass(example),
637
- ...analyzeGuardReferences(example),
638
- ...analyzeRoundTrip(example),
639
- ...analyzeProgressOps(example),
640
- ...analyzePublishStep(example),
641
- ];
642
- for (const f of allFindings) {
643
- if (f.rule_id) {
644
- ruleCounts.set(f.rule_id, (ruleCounts.get(f.rule_id) ?? 0) + 1);
645
- totalFindings++;
646
- }
647
- }
648
- return { ruleCounts, totalFindings };
649
- }
650
- export function scanAllExamples(examplesDir = EXAMPLES_DIR) {
651
- const examples = loadAllExamples(examplesDir);
652
- const findingsByExample = new Map();
653
- const findingsByCategory = new Map();
654
- const findingsBySeverity = new Map();
655
- const riskRuleCoverage = new Map();
656
- let totalFindings = 0;
657
- for (const example of examples) {
658
- const exampleFindings = [];
659
- exampleFindings.push(...analyzeSchemaConsistency(example));
660
- exampleFindings.push(...analyzeThresholdIssues(example));
661
- exampleFindings.push(...analyzeNetworkSafety(example));
662
- exampleFindings.push(...analyzeConfirmationBypass(example));
663
- exampleFindings.push(...analyzeGuardReferences(example));
664
- const crossMachine = analyzeCrossMachineDeps(example);
665
- exampleFindings.push(...crossMachine.findings);
666
- exampleFindings.push(...analyzeRoundTrip(example));
667
- exampleFindings.push(...analyzeProgressOps(example));
668
- exampleFindings.push(...analyzePublishStep(example));
669
- findingsByExample.set(example.relative_path, exampleFindings);
670
- for (const f of exampleFindings) {
671
- const catList = findingsByCategory.get(f.category) ?? [];
672
- catList.push(f);
673
- findingsByCategory.set(f.category, catList);
674
- const sevList = findingsBySeverity.get(f.severity) ?? [];
675
- sevList.push(f);
676
- findingsBySeverity.set(f.severity, sevList);
677
- if (f.rule_id) {
678
- riskRuleCoverage.set(f.rule_id, (riskRuleCoverage.get(f.rule_id) ?? 0) + 1);
679
- }
680
- totalFindings++;
681
- }
682
- }
683
- return {
684
- examples,
685
- findings_by_example: findingsByExample,
686
- findings_by_category: findingsByCategory,
687
- findings_by_severity: findingsBySeverity,
688
- total_findings: totalFindings,
689
- risk_rule_coverage: riskRuleCoverage,
690
- };
691
- }
692
- export function formatScanReport(result) {
693
- const lines = [];
694
- lines.push('# Examples Scan Report — d:\\wowok\\docs\\examples');
695
- lines.push('');
696
- lines.push('> Auto-generated by `examples-scanner.ts` — comprehensive scan of all');
697
- lines.push('> machine/progress JSON in 5 example directories for design and runtime problems.');
698
- lines.push('');
699
- lines.push('## Summary');
700
- lines.push('');
701
- lines.push(`- **Examples scanned**: ${result.examples.length}`);
702
- lines.push(`- **Total findings**: ${result.total_findings}`);
703
- lines.push('');
704
- lines.push('### Findings by Severity');
705
- lines.push('');
706
- lines.push('| Severity | Count |');
707
- lines.push('|----------|-------|');
708
- const sevOrder = ["critical", "high", "medium", "low", "info"];
709
- for (const sev of sevOrder) {
710
- const count = result.findings_by_severity.get(sev)?.length ?? 0;
711
- lines.push(`| ${sev} | ${count} |`);
712
- }
713
- lines.push('');
714
- lines.push('### Findings by Category');
715
- lines.push('');
716
- lines.push('| Category | Count |');
717
- lines.push('|----------|-------|');
718
- const catOrder = [
719
- "schema_consistency", "design", "runtime",
720
- "cross_machine", "round_trip", "progress", "risk_rule",
721
- ];
722
- for (const cat of catOrder) {
723
- const count = result.findings_by_category.get(cat)?.length ?? 0;
724
- lines.push(`| ${cat} | ${count} |`);
725
- }
726
- lines.push('');
727
- lines.push('### Risk Rule Coverage (which rules fired across examples)');
728
- lines.push('');
729
- lines.push('| Rule ID | Total Hits |');
730
- lines.push('|---------|-----------|');
731
- const sortedRules = [...result.risk_rule_coverage.entries()].sort((a, b) => a[0].localeCompare(b[0]));
732
- for (const [ruleId, count] of sortedRules) {
733
- lines.push(`| ${ruleId} | ${count} |`);
734
- }
735
- lines.push('');
736
- lines.push('## Per-Example Findings');
737
- lines.push('');
738
- for (const example of result.examples) {
739
- const findings = result.findings_by_example.get(example.relative_path) ?? [];
740
- lines.push(`### ${example.example_name} — \`${example.relative_path}\``);
741
- lines.push('');
742
- lines.push(`- **Source**: \`${example.relative_path}\``);
743
- lines.push(`- **Machine operations**: ${example.machine_ops.length}`);
744
- lines.push(`- **Progress operations**: ${example.progress_ops.length}`);
745
- lines.push(`- **Defined guards**: ${example.defined_guard_names.size}`);
746
- if (example.business_description) {
747
- lines.push(`- **Business description**: ${example.business_description}`);
748
- }
749
- lines.push(`- **Findings**: ${findings.length}`);
750
- lines.push('');
751
- if (findings.length === 0) {
752
- lines.push('✅ No issues detected.');
753
- lines.push('');
754
- continue;
755
- }
756
- const bySev = new Map();
757
- for (const f of findings) {
758
- const list = bySev.get(f.severity) ?? [];
759
- list.push(f);
760
- bySev.set(f.severity, list);
761
- }
762
- for (const sev of sevOrder) {
763
- const sevFindings = bySev.get(sev) ?? [];
764
- if (sevFindings.length === 0)
765
- continue;
766
- lines.push(`#### ${sev.toUpperCase()} (${sevFindings.length})`);
767
- lines.push('');
768
- for (const f of sevFindings) {
769
- lines.push(`- **[${f.rule_id ?? "—"}] ${f.title}** (line ${f.line})`);
770
- lines.push(` - ${f.detail}`);
771
- if (f.fix) {
772
- lines.push(` - **Fix**: ${f.fix}`);
773
- }
774
- lines.push('');
775
- }
776
- }
777
- }
778
- lines.push('## Cross-Cutting Patterns');
779
- lines.push('');
780
- const schemaFindings = result.findings_by_category.get("schema_consistency") ?? [];
781
- if (schemaFindings.length === 0) {
782
- lines.push('### Schema Consistency — No Issues (camelCase is canonical)');
783
- lines.push('');
784
- lines.push('The previous SCHEMA-001/002/003/004 rules have been REMOVED (2026-07-19).');
785
- lines.push('');
786
- lines.push('**Reason**: Verification against MCP schema (`d:\\wowok\\agent\\mcp\\src`) confirmed that:');
787
- lines.push('- `MachineForwardSchema` accepts `namedOperator`, `permissionIndex` (camelCase)');
788
- lines.push('- `MachineForwardGuardSchema` is an OBJECT `{ guard: string, retained_submission?: number[] }` (NOT a flat string)');
789
- lines.push('- `NamedObjectSchema` accepts `replaceExistName`, `onChain` (camelCase)');
790
- lines.push('');
791
- lines.push('Source examples using camelCase are therefore CORRECT per MCP schema — the previous rules were false positives.');
792
- lines.push('');
793
- }
794
- const thresholdFindings = (result.findings_by_category.get("design") ?? []).filter((f) => f.rule_id === "R-M3-09");
795
- if (thresholdFindings.length > 0) {
796
- lines.push('### Threshold=0 on Multi-Forward Entry Pairs (R-M3-09)');
797
- lines.push('');
798
- lines.push(`Found ${thresholdFindings.length} multi-Forward entry pairs with threshold=0 across examples.`);
799
- lines.push('');
800
- lines.push('**Detection logic** (refined 2026-07-19):');
801
- lines.push('- Single-Forward Pair with threshold=0 → **NOT flagged** (legitimate: single execution triggers migration regardless of threshold)');
802
- lines.push('- Competing-OR Pairs (multiple Pairs share prev_node="") with threshold=0 → **NOT flagged** (legitimate OR semantics)');
803
- lines.push('- Multi-Forward Pair with threshold=0 AND no competing siblings → **FLAGGED** (potential permission bypass: any single Forward fires → migration)');
804
- lines.push('');
805
- const affectedFiles = [...new Set(thresholdFindings.map((f) => f.source_file))];
806
- lines.push(`**Affected source files**: ${affectedFiles.map((p) => `\`${p}\``).join(', ')}.`);
807
- lines.push('');
808
- lines.push('**Fix**: Set threshold=1 (or higher) if Forwards represent AND semantics; keep threshold=0 only if OR semantics is intended (then consider splitting into competing Pairs).');
809
- lines.push('');
810
- }
811
- else {
812
- lines.push('### Threshold=0 on Entry Pairs — No Issues');
813
- lines.push('');
814
- lines.push('All entry pairs with threshold=0 fall into legitimate categories (single-Forward or competing-OR).');
815
- lines.push('');
816
- }
817
- const mainnetFindings = (result.findings_by_category.get("runtime") ?? []).filter((f) => f.rule_id === "R-M4-02");
818
- if (mainnetFindings.length > 0) {
819
- lines.push('### Direct Mainnet Publish (R-M4-02)');
820
- lines.push('');
821
- lines.push(`Found ${mainnetFindings.length} examples publishing directly to mainnet without testnet test.`);
822
- lines.push('');
823
- lines.push('**Affected examples**: MyShop, MyShop_Advanced.');
824
- lines.push('');
825
- lines.push('**Fix**: Add a testnet publish step before mainnet, or change the network to testnet for examples.');
826
- lines.push('');
827
- }
828
- lines.push('## Recommendations for Linter & Cognition Closure');
829
- lines.push('');
830
- lines.push('Based on the findings, the following linter rules and cognition improvements are recommended:');
831
- lines.push('');
832
- lines.push('1. **REMOVED SCHEMA-001/002/003/004** (2026-07-19): These rules incorrectly assumed SDK snake_case as the standard. MCP schema actually accepts camelCase (`namedOperator`, `permissionIndex`, `replaceExistName`) and nested Guard object form. Examples are correct as-is.');
833
- lines.push('2. **REFACTORED R-M3-02 → R-M3-09** (2026-07-19, then 2026-07-20): Original R-M3-02 (threshold=0) conflicted with machine-risk.ts\'s R-M3-02 (permissionIndex out of bounds). Initially renamed to R-M3-06, but that also collided with machine-risk.ts\'s R-M3-06 (Permission game imbalance). Final rename: R-M3-09. Logic also refined: single-Forward and competing-OR threshold=0 cases are now exempt.');
834
- lines.push('3. **Reinforce R-M4-03**: Guard must be created before Machine publish. Examples should include guard creation step (operation_type="guard") with matching name before machine creation.');
835
- lines.push('4. **Add lint rule** for `confirmed: true` + `publish: true` combination without showing the Phase 1 confirmation prompt first.');
836
- lines.push('5. **IMPLEMENTED**: R-M3-08 (permissionIndex < 1000) rule added to machine-risk.ts, and C-11 checklist item added to machine-confirm.ts (2026-07-20). Both enforce the on-chain USER_DEFINED_PERM_INDEX_START = 1000 hard constraint (see doc 06 §4.4).');
837
- lines.push('');
838
- lines.push('---');
839
- lines.push('');
840
- lines.push('*End of report.*');
841
- return lines.join('\n');
842
- }
843
- export const EXAMPLES_SCANNER_VERSION = "1.0.0";
1
+ import*as a85a from'fs';import*as a85b from'path';import{analyzeTopology}from'./machine-topology.js';import{assessMachineRisks}from'./machine-risk.js';import{runStaticChecklist}from'./machine-confirm.js';import{explainNode}from'./machine-translation.js';import{identifyCrossMachineDependency,detectCrossMachineCycle}from'./machine-context.js';export function getMachineName(a){if(typeof a['data']['object']==='string')return a['data']['object'];return a['data']['object']['name'];}const EXAMPLES_DIR=a85b['resolve']('d:/wowok/docs/examples');export function nodeDefsToMachine(a){const b=[],c=[],d=new Set();for(const e of a){!d['has'](e['name'])&&(b['push']({'name':e['name']}),d['add'](e['name']));for(const f of e['pairs']){c['push']({'prev_node':f['prev_node'],'next_node':e['name'],'threshold':f['threshold'],'forwards':f['forwards']['map'](g=>normalizeForward(g))});}}return{'nodes':b,'pairs':c};}function normalizeForward(a){const b=a['named_operator']??a['namedOperator'],c=a['permission_index']??a['permissionIndex'];let d;if(typeof a['guard']==='string')d=a['guard'];else{if(a['guard']&&typeof a['guard']==='object'){const h=a['guard'];if(typeof h['guard']==='string')d=h['guard'];}}let e;if(a['retained_submission']!==undefined&&a['retained_submission']!==null){if(typeof a['retained_submission']==='string')e=a['retained_submission'];else{if(Array['isArray'](a['retained_submission']))e=a['retained_submission'];else{if(typeof a['retained_submission']==='object'){const i=a['retained_submission'];i['retained_submission']!==undefined&&(e=i['retained_submission']);}}}}else{if(a['guard']&&typeof a['guard']==='object'){const j=a['guard'];if(j['retained_submission']!==undefined&&j['retained_submission']!==null){if(Array['isArray'](j['retained_submission']))e=j['retained_submission'];else typeof j['retained_submission']==='string'&&(e=j['retained_submission']);}}}return{'name':a['name'],'weight':a['weight'],'named_operator':b,'permission_index':c,'guard':d,'retained_submission':e};}function extractJsonBlocks(a){const b=a85a['readFileSync'](a,'utf-8'),c=b['split']('\x0a'),d=[];let e=0x0;while(e<c['length']){const f=c[e];if(f['trim']()['startsWith']('```json')){const g=[];let h=e+0x1;while(h<c['length']&&!c[h]['trim']()['startsWith']('```')){g['push'](c[h]),h++;}const k=g['join']('\x0a');try{const l=JSON['parse'](k);let m=null;if(l&&typeof l==='object'&&!Array['isArray'](l)){const n=l;if(n['tool']==='onchain_operations'&&n['data']&&typeof n['data']==='object'&&!Array['isArray'](n['data'])){const o=n['data'];typeof o['operation_type']==='string'&&(m={'operation_type':o['operation_type'],'data':o['data'],...o['env']!==undefined?{'env':o['env']}:{}});}else typeof n['operation_type']==='string'&&(m=n);}m&&typeof m['operation_type']==='string'&&d['push']({'lineStart':e+0x1,'raw':k,'json':m});}catch{}e=h+0x1;}else e++;}return d;}function extractDefinedGuardNames(a){const c=extractJsonBlocks(a),d=new Set();for(const e of c){if(e['json']['operation_type']!=='guard')continue;const f=e['json']['data'];if(!f)continue;const g=f['namedNew'],h=g?.['name'];if(h)d['add'](h);}return d;}export function loadAllExamples(a=EXAMPLES_DIR){const b=[];if(!a85a['existsSync'](a))return b;const c=a85a['readdirSync'](a,{'withFileTypes':!![]});for(const d of c){if(!d['isDirectory']())continue;const e=a85b['join'](a,d['name']),f=a85a['readdirSync'](e,{'withFileTypes':!![]});for(const g of f){if(!g['isFile']())continue;const h=a85b['join'](e,g['name']),i=d['name']+'/'+g['name'];if(g['name']['endsWith']('.md')){const j=extractMachineOpsFromMarkdown(h),k=extractProgressOpsFromMarkdown(h),l=extractDefinedGuardNames(h);if(j['length']===0x0&&k['length']===0x0&&l['size']===0x0)continue;const m=j[0x0]?.['op']['data']['description'];b['push']({'example_name':d['name'],'relative_path':i,'absolute_path':h,'machine_ops':j,'progress_ops':k,'defined_guard_names':l,'business_description':m});}else{if(g['name']['endsWith']('.json')&&g['name']['includes']('machine')){const n=a85a['readFileSync'](h,'utf-8');try{const o=JSON['parse'](n);if(!Array['isArray'](o)||o['length']===0x0)continue;const p=a85b['basename'](g['name'],'.json');b['push']({'example_name':d['name'],'relative_path':i,'absolute_path':h,'machine_ops':[{'op':{'operation_type':'machine','data':{'object':{'name':p,'replaceExistName':![]},'node':{'op':'add','nodes':o},'publish':![]},'env':{'network':'testnet'}},'line_start':0x0}],'progress_ops':[],'defined_guard_names':new Set(),'business_description':'(standalone\x20JSON:\x20'+p+')'});}catch{}}}}}return b;}function extractMachineOpsFromMarkdown(a){const c=extractJsonBlocks(a),d=[];for(const e of c){if(e['json']['operation_type']!=='machine')continue;try{const f=e['json'];if(!f['data'])continue;const g=f['data']['node']?.['nodes']&&Array['isArray'](f['data']['node']['nodes']),h=f['data']['publish']===!![];if(!g&&!h)continue;d['push']({'op':f,'line_start':e['lineStart']});}catch{}}return d;}function extractProgressOpsFromMarkdown(a){const c=extractJsonBlocks(a),d=[];for(const e of c){const f=e['json'],g=f['data'];if(!g)continue;const h=g['progress'];if(!h)continue;const i=h['operation'];if(!i||!i['next_node_name']||!i['forward'])continue;try{d['push']({'operation_type':f['operation_type'],'data':{'object':g['object'],'progress':{'operation':{'next_node_name':i['next_node_name'],'forward':i['forward']}},'submission':g['submission']},'env':{'account':f['env']?.['account'],'network':f['env']?.['network']},'_source_line':e['lineStart']});}catch{}}return d;}export function analyzeSchemaConsistency(a){return[];}export function analyzeThresholdIssues(a){const b=[];for(const {op:c,line_start:d}of a['machine_ops']){if(!c['data']['node']?.['nodes'])continue;const {nodes:e,pairs:f}=nodeDefsToMachine(c['data']['node']['nodes']),g=getMachineName(c),h=f['filter'](j=>j['prev_node']===''),i=h['length']>0x1;for(const j of f){if(j['prev_node']===''&&j['threshold']===0x0){const k=j['forwards']['length'],l=k===0x1||i;if(l)continue;b['push']({'example':a['example_name'],'source_file':a['relative_path'],'line':d,'machine_name':g,'category':'design','severity':'medium','title':'Entry\x20pair\x20with\x20threshold=0\x20and\x20multiple\x20Forwards\x20(potential\x20permission\x20bypass)','detail':'Pair\x20(prev=\x22\x22,\x20next=\x22'+j['next_node']+'\x22)\x20has\x20threshold=0\x20with\x20'+k+'\x20Forwards.\x20'+'With\x20threshold=0,\x20ANY\x20single\x20Forward\x20fires\x20→\x20migration,\x20potentially\x20bypassing\x20other\x20Forwards\x27\x20'+'permission\x20checks.\x20Set\x20threshold\x20≥\x201\x20so\x20ALL\x20intended\x20Forwards\x20must\x20agree.\x20'+'(Note:\x20single-Forward\x20Pairs\x20and\x20competing-OR\x20Pairs\x20with\x20threshold=0\x20are\x20NOT\x20flagged\x20—\x20they\x20are\x20legitimate.)','rule_id':'R-M3-09','fix':'Set\x20threshold=1\x20(or\x20higher)\x20on\x20entry\x20pair\x20targeting\x20\x22'+j['next_node']+'\x22\x20if\x20Forwards\x20represent\x20AND\x20semantics;\x20keep\x20threshold=0\x20if\x20OR\x20semantics\x20is\x20intended\x20(then\x20consider\x20splitting\x20into\x20competing\x20Pairs).'});}}for(const m of f){const n=m['forwards']['reduce']((o,p)=>o+p['weight'],0x0);m['threshold']>n&&b['push']({'example':a['example_name'],'source_file':a['relative_path'],'line':d,'machine_name':g,'category':'design','severity':'critical','title':'Threshold\x20exceeds\x20total\x20forward\x20weight\x20(unreachable)','detail':'Pair\x20(prev=\x22'+m['prev_node']+'\x22,\x20next=\x22'+m['next_node']+'\x22)\x20has\x20threshold='+m['threshold']+'\x20but\x20total\x20forward\x20weight='+n+'.\x20This\x20pair\x20can\x20NEVER\x20be\x20satisfied\x20—\x20workflow\x20dead-ends\x20here.','rule_id':'R-M2-06','fix':'Reduce\x20threshold\x20to\x20≤\x20'+n+'\x20or\x20add\x20more\x20forwards\x20with\x20weight.'});}}return b;}export function analyzeNetworkSafety(a){const b=[];for(const {op:c,line_start:d}of a['machine_ops']){const e=getMachineName(c),f=c['data']['publish']===!![],g=c['env']['network'];f&&g==='mainnet'&&b['push']({'example':a['example_name'],'source_file':a['relative_path'],'line':d,'machine_name':e,'category':'runtime','severity':'critical','title':'Direct\x20mainnet\x20publish\x20without\x20testnet\x20test','detail':'Machine\x20\x22'+e+'\x22\x20is\x20published\x20directly\x20to\x20mainnet.\x20Per\x20R-M4-02,\x20must\x20test\x20on\x20testnet\x20first.','rule_id':'R-M4-02','fix':'Set\x20env.network\x20to\x20\x22testnet\x22\x20for\x20first\x20publish,\x20run\x20end-to-end\x20test,\x20then\x20re-publish\x20on\x20mainnet.'});}return b;}export function analyzeConfirmationBypass(a){const b=[];for(const {op:c,line_start:d}of a['machine_ops']){const e=getMachineName(c),f=c['data']['publish']===!![],g=c['env']['confirmed']===!![];f&&g&&b['push']({'example':a['example_name'],'source_file':a['relative_path'],'line':d,'machine_name':e,'category':'runtime','severity':'medium','title':'confirmed=true\x20bypasses\x20user\x20confirmation\x20prompt','detail':'Machine\x20\x22'+e+'\x22\x20is\x20published\x20with\x20env.confirmed=true.\x20This\x20bypasses\x20the\x20ConfirmGate\x20user-confirmation\x20step.\x20Examples\x20should\x20demonstrate\x20the\x20two-step\x20confirmation\x20flow\x20(Phase\x201\x20prompt\x20→\x20Phase\x202\x20confirmed=true).','rule_id':'R-M4-04','fix':'Show\x20Phase\x201\x20(without\x20confirmed=true)\x20and\x20Phase\x202\x20(with\x20confirmed=true)\x20as\x20separate\x20steps\x20in\x20the\x20example.'});}return b;}export function analyzeGuardReferences(a){const b=[],c=a['defined_guard_names'];for(const {op:d,line_start:e}of a['machine_ops']){if(!d['data']['node']?.['nodes'])continue;const f=getMachineName(d),h=d['data']['publish']===!![];for(const i of d['data']['node']['nodes']){for(const j of i['pairs']){for(const k of j['forwards']){let l;if(typeof k['guard']==='string')l=k['guard'];else{if(k['guard']&&typeof k['guard']==='object'){const m=k['guard'];if(typeof m['guard']==='string')l=m['guard'];}}if(!l)continue;!c['has'](l)&&b['push']({'example':a['example_name'],'source_file':a['relative_path'],'line':e,'machine_name':f,'category':'runtime','severity':h?'critical':'high','title':'Guard\x20\x22'+l+'\x22\x20referenced\x20but\x20not\x20defined\x20in\x20example','detail':'Forward\x20\x22'+k['name']+'\x22\x20references\x20Guard\x20\x22'+l+'\x22\x20but\x20no\x20operation_type=\x22guard\x22\x20with\x20name=\x22'+l+'\x22\x20appears\x20earlier\x20in\x20'+a['relative_path']+'.\x20'+(h?'Publishing\x20will\x20fail\x20at\x20runtime.':'Will\x20fail\x20at\x20machine\x20creation.'),'rule_id':h?'R-M4-03':'R-M2-01','fix':'Add\x20a\x20guard\x20creation\x20step\x20(operation_type=\x22guard\x22)\x20with\x20name=\x22'+l+'\x22\x20BEFORE\x20the\x20machine\x20creation\x20step.'});}}}}return b;}export function analyzeCrossMachineDeps(a,b=new Map()){const c=[],d=[];for(const {op:f,line_start:g}of a['machine_ops']){if(!f['data']['node']?.['nodes'])continue;const {nodes:h,pairs:i}=nodeDefsToMachine(f['data']['node']['nodes']),j=getMachineName(f),k=identifyCrossMachineDependency(j,{'nodes':h,'pairs':i},b);d['push'](...k),k['length']>0x0&&c['push']({'example':a['example_name'],'source_file':a['relative_path'],'line':g,'machine_name':j,'category':'cross_machine','severity':'info','title':'Machine\x20declares\x20'+k['length']+'\x20cross-Machine\x20dependencies','detail':k['map'](l=>'Forward\x20\x22'+l['dependency']['machine_a_forward']+'\x22\x20depends\x20on\x20Machine\x20\x22'+l['machine_b_id']+'\x22\x20reaching\x20node\x20\x22'+l['dependency']['machine_b_node']+'\x22')['join'](';\x20'),'rule_id':'P-M3'});}const e=detectCrossMachineCycle(d);for(const l of e){c['push']({'example':a['example_name'],'source_file':a['relative_path'],'line':0x0,'machine_name':'(project-level)','category':'cross_machine','severity':'critical','title':'Cross-Machine\x20dependency\x20cycle\x20detected','detail':'Cycle:\x20'+l['join']('\x20→\x20'),'rule_id':'R-M2-07','fix':'Break\x20the\x20cycle\x20by\x20removing\x20one\x20of\x20the\x20dependencies\x20in\x20the\x20cycle.'});}return{'deps':d,'cycles':e,'findings':c};}export function analyzeRoundTrip(a){const b=[];for(const {op:c,line_start:d}of a['machine_ops']){if(!c['data']['node']?.['nodes'])continue;const {nodes:e,pairs:f}=nodeDefsToMachine(c['data']['node']['nodes']),g=getMachineName(c),h=analyzeTopology(e,f);h['has_cycles']&&b['push']({'example':a['example_name'],'source_file':a['relative_path'],'line':d,'machine_name':g,'category':'round_trip','severity':'critical','title':'Topology\x20analysis:\x20cycle\x20detected\x20(DAG\x20violation)','detail':'Machine\x20\x22'+g+'\x22\x20has\x20cycles:\x20'+JSON['stringify'](h['cycle_nodes']),'rule_id':'R-M1-03','fix':'Remove\x20cycles\x20—\x20Machine\x20must\x20be\x20a\x20DAG.'});const i={'network':c['env']['network']==='mainnet'?'mainnet':'testnet','testnet_test_passed':c['env']['network']!=='mainnet','published_services':new Set(),'published_guards':new Set(),'published_permissions':new Set(),'published_machines':new Set(),'published_arbitrations':new Set(),'published_rewards':new Set(),'published_allocators':new Set(),'published_repositories':new Set()};for(const p of f){for(const q of p['forwards']){if(q['guard'])i['published_guards']['add'](q['guard']);}}const j={'nodes':e,'pairs':f,'b_published':c['data']['publish']===!![]},k=assessMachineRisks(j,i),l=k['detected_risks']['filter'](s=>s['severity']==='critical');if(l['length']>0x0)for(const s of l){b['push']({'example':a['example_name'],'source_file':a['relative_path'],'line':d,'machine_name':g,'category':'round_trip','severity':'critical','title':'Risk\x20assessment:\x20'+s['rule_id']+'\x20('+s['severity']+')','detail':s['detail'],'rule_id':s['rule_id']});}const m={'nodes':e,'pairs':f,'name':g},n=runStaticChecklist(m),o=n['failed_items']['filter'](t=>['C-01','C-03','C-06','C-10']['includes'](t['id']));for(const t of o){b['push']({'example':a['example_name'],'source_file':a['relative_path'],'line':d,'machine_name':g,'category':'round_trip','severity':'high','title':'Checklist\x20'+t['id']+'\x20failed:\x20'+t['description'],'detail':t['detail']??'(no\x20detail)','rule_id':t['id']});}for(const u of e){const v=f['filter'](y=>y['prev_node']===u['name']),w={'name':u['name'],'pairs':v,'all_pairs':f},x=explainNode(w);(!x['name']||x['pairs']['length']!==v['length'])&&b['push']({'example':a['example_name'],'source_file':a['relative_path'],'line':d,'machine_name':g,'category':'round_trip','severity':'medium','title':'Round-trip\x20mismatch\x20for\x20node\x20\x22'+u['name']+'\x22','detail':'explainNode\x20produced\x20inconsistent\x20output:\x20name=\x22'+x['name']+'\x22,\x20pairs_count='+x['pairs']['length']+'\x20(expected\x20'+v['length']+')','rule_id':'RT-001'});}}return b;}export function analyzeProgressOps(a){const b=[],c=new Set();let d='(none)';for(const {op:e}of a['machine_ops']){if(!e['data']['node']?.['nodes'])continue;d=getMachineName(e);const {pairs:f}=nodeDefsToMachine(e['data']['node']['nodes']);for(const g of f){c['add'](g['next_node']+'::'+g['forwards']['map'](h=>h['name'])['join']('|'));for(const h of g['forwards']){c['add'](g['next_node']+'::'+h['name']);}}}for(const i of a['progress_ops']){const j=i['data']['progress']?.['operation'];if(!j)continue;const k=j['next_node_name']+'::'+j['forward'],l=c['has'](k);if(!l){const m=[...c]['some'](n=>n['endsWith']('::'+j['forward']));!m?b['push']({'example':a['example_name'],'source_file':a['relative_path'],'line':i['_source_line']??0x0,'machine_name':d,'category':'progress','severity':'high','title':'Progress\x20references\x20unknown\x20forward\x20\x22'+j['forward']+'\x22','detail':'Progress\x20op\x20references\x20forward\x20\x22'+j['forward']+'\x22\x20but\x20no\x20such\x20forward\x20exists\x20in\x20machine\x20\x22'+d+'\x22.','rule_id':'R-M3-04','fix':'Verify\x20forward\x20name\x20matches\x20one\x20defined\x20in\x20the\x20Machine.'}):b['push']({'example':a['example_name'],'source_file':a['relative_path'],'line':i['_source_line']??0x0,'machine_name':d,'category':'progress','severity':'medium','title':'Progress\x20forward\x20\x22'+j['forward']+'\x22\x20doesn\x27t\x20lead\x20to\x20\x22'+j['next_node_name']+'\x22','detail':'Forward\x20\x22'+j['forward']+'\x22\x20exists\x20but\x20doesn\x27t\x20target\x20node\x20\x22'+j['next_node_name']+'\x22.','rule_id':'R-M3-05','fix':'Correct\x20next_node_name\x20to\x20match\x20the\x20forward\x27s\x20target.'});}}return b;}export function analyzePublishStep(a){const b=[],c=a['machine_ops']['some'](({op:e})=>e['data']['publish']===!![]),d=a['progress_ops']['length']>0x0;return d&&!c&&b['push']({'example':a['example_name'],'source_file':a['relative_path'],'line':0x0,'machine_name':'(file-level)','category':'runtime','severity':'high','title':'Progress\x20operations\x20present\x20but\x20no\x20`publish:\x20true`\x20step','detail':'Example\x20has\x20'+a['progress_ops']['length']+'\x20progress\x20operations\x20but\x20no\x20machine\x20operation\x20with\x20publish=true.\x20Progress::new\x20will\x20fail\x20at\x20runtime\x20(machine\x20not\x20published).','rule_id':'R-M4-01','fix':'Add\x20a\x20publish\x20step\x20(or\x20set\x20data.publish=true\x20on\x20the\x20machine\x20creation\x20operation).'}),b;}export function analyzeRiskRuleCoverage(a){const b=new Map();let c=0x0;const d=[...analyzeSchemaConsistency(a),...analyzeThresholdIssues(a),...analyzeNetworkSafety(a),...analyzeConfirmationBypass(a),...analyzeGuardReferences(a),...analyzeRoundTrip(a),...analyzeProgressOps(a),...analyzePublishStep(a)];for(const e of d){e['rule_id']&&(b['set'](e['rule_id'],(b['get'](e['rule_id'])??0x0)+0x1),c++);}return{'ruleCounts':b,'totalFindings':c};}export function scanAllExamples(a=EXAMPLES_DIR){const b=loadAllExamples(a),c=new Map(),d=new Map(),e=new Map(),g=new Map();let h=0x0;for(const i of b){const j=[];j['push'](...analyzeSchemaConsistency(i)),j['push'](...analyzeThresholdIssues(i)),j['push'](...analyzeNetworkSafety(i)),j['push'](...analyzeConfirmationBypass(i)),j['push'](...analyzeGuardReferences(i));const k=analyzeCrossMachineDeps(i);j['push'](...k['findings']),j['push'](...analyzeRoundTrip(i)),j['push'](...analyzeProgressOps(i)),j['push'](...analyzePublishStep(i)),c['set'](i['relative_path'],j);for(const l of j){const m=d['get'](l['category'])??[];m['push'](l),d['set'](l['category'],m);const n=e['get'](l['severity'])??[];n['push'](l),e['set'](l['severity'],n),l['rule_id']&&g['set'](l['rule_id'],(g['get'](l['rule_id'])??0x0)+0x1),h++;}}return{'examples':b,'findings_by_example':c,'findings_by_category':d,'findings_by_severity':e,'total_findings':h,'risk_rule_coverage':g};}export function formatScanReport(a){const b=[];b['push']('#\x20Examples\x20Scan\x20Report\x20—\x20d:\x5cwowok\x5cdocs\x5cexamples'),b['push'](''),b['push']('>\x20Auto-generated\x20by\x20`examples-scanner.ts`\x20—\x20comprehensive\x20scan\x20of\x20all'),b['push']('>\x20machine/progress\x20JSON\x20in\x205\x20example\x20directories\x20for\x20design\x20and\x20runtime\x20problems.'),b['push'](''),b['push']('##\x20Summary'),b['push'](''),b['push']('-\x20**Examples\x20scanned**:\x20'+a['examples']['length']),b['push']('-\x20**Total\x20findings**:\x20'+a['total_findings']),b['push'](''),b['push']('###\x20Findings\x20by\x20Severity'),b['push'](''),b['push']('|\x20Severity\x20|\x20Count\x20|'),b['push']('|----------|-------|');const c=['critical','high','medium','low','info'];for(const j of c){const k=a['findings_by_severity']['get'](j)?.['length']??0x0;b['push']('|\x20'+j+'\x20|\x20'+k+'\x20|');}b['push'](''),b['push']('###\x20Findings\x20by\x20Category'),b['push'](''),b['push']('|\x20Category\x20|\x20Count\x20|'),b['push']('|----------|-------|');const d=['schema_consistency','design','runtime','cross_machine','round_trip','progress','risk_rule'];for(const l of d){const m=a['findings_by_category']['get'](l)?.['length']??0x0;b['push']('|\x20'+l+'\x20|\x20'+m+'\x20|');}b['push'](''),b['push']('###\x20Risk\x20Rule\x20Coverage\x20(which\x20rules\x20fired\x20across\x20examples)'),b['push'](''),b['push']('|\x20Rule\x20ID\x20|\x20Total\x20Hits\x20|'),b['push']('|---------|-----------|');const e=[...a['risk_rule_coverage']['entries']()]['sort']((n,o)=>n[0x0]['localeCompare'](o[0x0]));for(const [n,o]of e){b['push']('|\x20'+n+'\x20|\x20'+o+'\x20|');}b['push'](''),b['push']('##\x20Per-Example\x20Findings'),b['push']('');for(const p of a['examples']){const q=a['findings_by_example']['get'](p['relative_path'])??[];b['push']('###\x20'+p['example_name']+'\x20—\x20`'+p['relative_path']+'`'),b['push'](''),b['push']('-\x20**Source**:\x20`'+p['relative_path']+'`'),b['push']('-\x20**Machine\x20operations**:\x20'+p['machine_ops']['length']),b['push']('-\x20**Progress\x20operations**:\x20'+p['progress_ops']['length']),b['push']('-\x20**Defined\x20guards**:\x20'+p['defined_guard_names']['size']);p['business_description']&&b['push']('-\x20**Business\x20description**:\x20'+p['business_description']);b['push']('-\x20**Findings**:\x20'+q['length']),b['push']('');if(q['length']===0x0){b['push']('✅\x20No\x20issues\x20detected.'),b['push']('');continue;}const r=new Map();for(const s of q){const t=r['get'](s['severity'])??[];t['push'](s),r['set'](s['severity'],t);}for(const u of c){const v=r['get'](u)??[];if(v['length']===0x0)continue;b['push']('####\x20'+u['toUpperCase']()+'\x20('+v['length']+')'),b['push']('');for(const w of v){b['push']('-\x20**['+(w['rule_id']??'—')+']\x20'+w['title']+'**\x20(line\x20'+w['line']+')'),b['push']('\x20\x20-\x20'+w['detail']),w['fix']&&b['push']('\x20\x20-\x20**Fix**:\x20'+w['fix']),b['push']('');}}}b['push']('##\x20Cross-Cutting\x20Patterns'),b['push']('');const g=a['findings_by_category']['get']('schema_consistency')??[];g['length']===0x0&&(b['push']('###\x20Schema\x20Consistency\x20—\x20No\x20Issues\x20(camelCase\x20is\x20canonical)'),b['push'](''),b['push']('The\x20previous\x20SCHEMA-001/002/003/004\x20rules\x20have\x20been\x20REMOVED\x20(2026-07-19).'),b['push'](''),b['push']('**Reason**:\x20Verification\x20against\x20MCP\x20schema\x20(`d:\x5cwowok\x5cagent\x5cmcp\x5csrc`)\x20confirmed\x20that:'),b['push']('-\x20`MachineForwardSchema`\x20accepts\x20`namedOperator`,\x20`permissionIndex`\x20(camelCase)'),b['push']('-\x20`MachineForwardGuardSchema`\x20is\x20an\x20OBJECT\x20`{\x20guard:\x20string,\x20retained_submission?:\x20number[]\x20}`\x20(NOT\x20a\x20flat\x20string)'),b['push']('-\x20`NamedObjectSchema`\x20accepts\x20`replaceExistName`,\x20`onChain`\x20(camelCase)'),b['push'](''),b['push']('Source\x20examples\x20using\x20camelCase\x20are\x20therefore\x20CORRECT\x20per\x20MCP\x20schema\x20—\x20the\x20previous\x20rules\x20were\x20false\x20positives.'),b['push'](''));const h=(a['findings_by_category']['get']('design')??[])['filter'](x=>x['rule_id']==='R-M3-09');if(h['length']>0x0){b['push']('###\x20Threshold=0\x20on\x20Multi-Forward\x20Entry\x20Pairs\x20(R-M3-09)'),b['push'](''),b['push']('Found\x20'+h['length']+'\x20multi-Forward\x20entry\x20pairs\x20with\x20threshold=0\x20across\x20examples.'),b['push'](''),b['push']('**Detection\x20logic**\x20(refined\x202026-07-19):'),b['push']('-\x20Single-Forward\x20Pair\x20with\x20threshold=0\x20→\x20**NOT\x20flagged**\x20(legitimate:\x20single\x20execution\x20triggers\x20migration\x20regardless\x20of\x20threshold)'),b['push']('-\x20Competing-OR\x20Pairs\x20(multiple\x20Pairs\x20share\x20prev_node=\x22\x22)\x20with\x20threshold=0\x20→\x20**NOT\x20flagged**\x20(legitimate\x20OR\x20semantics)'),b['push']('-\x20Multi-Forward\x20Pair\x20with\x20threshold=0\x20AND\x20no\x20competing\x20siblings\x20→\x20**FLAGGED**\x20(potential\x20permission\x20bypass:\x20any\x20single\x20Forward\x20fires\x20→\x20migration)'),b['push']('');const x=[...new Set(h['map'](y=>y['source_file']))];b['push']('**Affected\x20source\x20files**:\x20'+x['map'](y=>'`'+y+'`')['join'](',\x20')+'.'),b['push'](''),b['push']('**Fix**:\x20Set\x20threshold=1\x20(or\x20higher)\x20if\x20Forwards\x20represent\x20AND\x20semantics;\x20keep\x20threshold=0\x20only\x20if\x20OR\x20semantics\x20is\x20intended\x20(then\x20consider\x20splitting\x20into\x20competing\x20Pairs).'),b['push']('');}else b['push']('###\x20Threshold=0\x20on\x20Entry\x20Pairs\x20—\x20No\x20Issues'),b['push'](''),b['push']('All\x20entry\x20pairs\x20with\x20threshold=0\x20fall\x20into\x20legitimate\x20categories\x20(single-Forward\x20or\x20competing-OR).'),b['push']('');const i=(a['findings_by_category']['get']('runtime')??[])['filter'](y=>y['rule_id']==='R-M4-02');return i['length']>0x0&&(b['push']('###\x20Direct\x20Mainnet\x20Publish\x20(R-M4-02)'),b['push'](''),b['push']('Found\x20'+i['length']+'\x20examples\x20publishing\x20directly\x20to\x20mainnet\x20without\x20testnet\x20test.'),b['push'](''),b['push']('**Affected\x20examples**:\x20MyShop,\x20MyShop_Advanced.'),b['push'](''),b['push']('**Fix**:\x20Add\x20a\x20testnet\x20publish\x20step\x20before\x20mainnet,\x20or\x20change\x20the\x20network\x20to\x20testnet\x20for\x20examples.'),b['push']('')),b['push']('##\x20Recommendations\x20for\x20Linter\x20&\x20Cognition\x20Closure'),b['push'](''),b['push']('Based\x20on\x20the\x20findings,\x20the\x20following\x20linter\x20rules\x20and\x20cognition\x20improvements\x20are\x20recommended:'),b['push'](''),b['push']('1.\x20**REMOVED\x20SCHEMA-001/002/003/004**\x20(2026-07-19):\x20These\x20rules\x20incorrectly\x20assumed\x20SDK\x20snake_case\x20as\x20the\x20standard.\x20MCP\x20schema\x20actually\x20accepts\x20camelCase\x20(`namedOperator`,\x20`permissionIndex`,\x20`replaceExistName`)\x20and\x20nested\x20Guard\x20object\x20form.\x20Examples\x20are\x20correct\x20as-is.'),b['push']('2.\x20**REFACTORED\x20R-M3-02\x20→\x20R-M3-09**\x20(2026-07-19,\x20then\x202026-07-20):\x20Original\x20R-M3-02\x20(threshold=0)\x20conflicted\x20with\x20machine-risk.ts\x27s\x20R-M3-02\x20(permissionIndex\x20out\x20of\x20bounds).\x20Initially\x20renamed\x20to\x20R-M3-06,\x20but\x20that\x20also\x20collided\x20with\x20machine-risk.ts\x27s\x20R-M3-06\x20(Permission\x20game\x20imbalance).\x20Final\x20rename:\x20R-M3-09.\x20Logic\x20also\x20refined:\x20single-Forward\x20and\x20competing-OR\x20threshold=0\x20cases\x20are\x20now\x20exempt.'),b['push']('3.\x20**Reinforce\x20R-M4-03**:\x20Guard\x20must\x20be\x20created\x20before\x20Machine\x20publish.\x20Examples\x20should\x20include\x20guard\x20creation\x20step\x20(operation_type=\x22guard\x22)\x20with\x20matching\x20name\x20before\x20machine\x20creation.'),b['push']('4.\x20**Add\x20lint\x20rule**\x20for\x20`confirmed:\x20true`\x20+\x20`publish:\x20true`\x20combination\x20without\x20showing\x20the\x20Phase\x201\x20confirmation\x20prompt\x20first.'),b['push']('5.\x20**IMPLEMENTED**:\x20R-M3-08\x20(permissionIndex\x20<\x201000)\x20rule\x20added\x20to\x20machine-risk.ts,\x20and\x20C-11\x20checklist\x20item\x20added\x20to\x20machine-confirm.ts\x20(2026-07-20).\x20Both\x20enforce\x20the\x20on-chain\x20USER_DEFINED_PERM_INDEX_START\x20=\x201000\x20hard\x20constraint\x20(see\x20doc\x2006\x20§4.4).'),b['push'](''),b['push']('---'),b['push'](''),b['push']('*End\x20of\x20report.*'),b['join']('\x0a');}export const EXAMPLES_SCANNER_VERSION='1.0.0';