@wowok/agent-mcp 2.4.1 → 2.5.0

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 (348) hide show
  1. package/dist/config/runtime.d.ts +4 -0
  2. package/dist/config/runtime.js +29 -5
  3. package/dist/harness/auto-escalation.d.ts +27 -0
  4. package/dist/harness/auto-escalation.js +68 -0
  5. package/dist/index.d.ts +2 -2
  6. package/dist/index.js +29 -1621
  7. package/dist/knowledge/allocation-confirm.d.ts +115 -0
  8. package/dist/knowledge/allocation-confirm.js +534 -0
  9. package/dist/knowledge/allocation-context.d.ts +58 -0
  10. package/dist/knowledge/allocation-context.js +249 -0
  11. package/dist/knowledge/allocation-ledger.d.ts +67 -0
  12. package/dist/knowledge/allocation-ledger.js +463 -0
  13. package/dist/knowledge/allocation-puzzle.d.ts +135 -0
  14. package/dist/knowledge/allocation-puzzle.js +298 -0
  15. package/dist/knowledge/allocation-risk.d.ts +78 -0
  16. package/dist/knowledge/allocation-risk.js +568 -0
  17. package/dist/knowledge/allocation-templates.d.ts +38 -0
  18. package/dist/knowledge/allocation-templates.js +970 -0
  19. package/dist/knowledge/allocation-translation.d.ts +72 -0
  20. package/dist/knowledge/allocation-translation.js +585 -0
  21. package/dist/knowledge/arb-risk.d.ts +37 -0
  22. package/dist/knowledge/arb-risk.js +210 -0
  23. package/dist/knowledge/arbitration-confirm.d.ts +135 -0
  24. package/dist/knowledge/arbitration-confirm.js +559 -0
  25. package/dist/knowledge/arbitration-context.d.ts +81 -0
  26. package/dist/knowledge/arbitration-context.js +505 -0
  27. package/dist/knowledge/arbitration-ledger.d.ts +62 -0
  28. package/dist/knowledge/arbitration-ledger.js +521 -0
  29. package/dist/knowledge/arbitration-puzzle.d.ts +84 -0
  30. package/dist/knowledge/arbitration-puzzle.js +304 -0
  31. package/dist/knowledge/arbitration-risk.d.ts +112 -0
  32. package/dist/knowledge/arbitration-risk.js +433 -0
  33. package/dist/knowledge/arbitration-templates.d.ts +38 -0
  34. package/dist/knowledge/arbitration-templates.js +276 -0
  35. package/dist/knowledge/arbitration-translation.d.ts +91 -0
  36. package/dist/knowledge/arbitration-translation.js +487 -0
  37. package/dist/knowledge/bridge-risk.d.ts +36 -0
  38. package/dist/knowledge/bridge-risk.js +263 -0
  39. package/dist/knowledge/contact-risk.d.ts +32 -0
  40. package/dist/knowledge/contact-risk.js +200 -0
  41. package/dist/knowledge/demand-confirm.d.ts +32 -0
  42. package/dist/knowledge/demand-confirm.js +206 -0
  43. package/dist/knowledge/demand-risk.d.ts +30 -0
  44. package/dist/knowledge/demand-risk.js +240 -0
  45. package/dist/knowledge/demand-translation.d.ts +55 -0
  46. package/dist/knowledge/demand-translation.js +354 -0
  47. package/dist/knowledge/deployment-scanner.d.ts +63 -0
  48. package/dist/knowledge/deployment-scanner.js +762 -0
  49. package/dist/knowledge/examples-scanner-cli.d.ts +1 -0
  50. package/dist/knowledge/examples-scanner-cli.js +26 -0
  51. package/dist/knowledge/examples-scanner.d.ts +121 -0
  52. package/dist/knowledge/examples-scanner.js +825 -0
  53. package/dist/knowledge/flywheel-loop.d.ts +3 -0
  54. package/dist/knowledge/flywheel-loop.js +32 -3
  55. package/dist/knowledge/glossary.js +3 -1
  56. package/dist/knowledge/guard-confirm.d.ts +86 -0
  57. package/dist/knowledge/guard-confirm.js +406 -0
  58. package/dist/knowledge/guard-context.d.ts +56 -0
  59. package/dist/knowledge/guard-context.js +287 -0
  60. package/dist/knowledge/guard-design-patterns.d.ts +37 -0
  61. package/dist/knowledge/guard-design-patterns.js +257 -0
  62. package/dist/knowledge/guard-ledger.js +14 -0
  63. package/dist/knowledge/guard-lint.d.ts +1 -0
  64. package/dist/knowledge/guard-lint.js +83 -3
  65. package/dist/knowledge/guard-migration.d.ts +48 -0
  66. package/dist/knowledge/guard-migration.js +228 -0
  67. package/dist/knowledge/guard-puzzle.js +3 -2
  68. package/dist/knowledge/guard-risk.d.ts +3 -1
  69. package/dist/knowledge/guard-risk.js +832 -64
  70. package/dist/knowledge/guard-templates.d.ts +1 -0
  71. package/dist/knowledge/guard-templates.js +278 -2
  72. package/dist/knowledge/guard-translation.js +6 -5
  73. package/dist/knowledge/index.d.ts +342 -0
  74. package/dist/knowledge/index.js +344 -0
  75. package/dist/knowledge/machine-confirm.d.ts +102 -0
  76. package/dist/knowledge/machine-confirm.js +559 -0
  77. package/dist/knowledge/machine-context.d.ts +160 -0
  78. package/dist/knowledge/machine-context.js +812 -0
  79. package/dist/knowledge/machine-ledger.d.ts +41 -0
  80. package/dist/knowledge/machine-ledger.js +315 -0
  81. package/dist/knowledge/machine-puzzle.d.ts +206 -0
  82. package/dist/knowledge/machine-puzzle.js +494 -0
  83. package/dist/knowledge/machine-risk.d.ts +75 -0
  84. package/dist/knowledge/machine-risk.js +644 -0
  85. package/dist/knowledge/machine-templates.d.ts +92 -0
  86. package/dist/knowledge/machine-templates.js +1592 -0
  87. package/dist/knowledge/machine-topology.d.ts +57 -0
  88. package/dist/knowledge/machine-topology.js +234 -0
  89. package/dist/knowledge/machine-translation.d.ts +96 -0
  90. package/dist/knowledge/machine-translation.js +513 -0
  91. package/dist/knowledge/mcp-schema-audit-cli.d.ts +1 -0
  92. package/dist/knowledge/mcp-schema-audit-cli.js +45 -0
  93. package/dist/knowledge/mcp-schema-audit.d.ts +90 -0
  94. package/dist/knowledge/mcp-schema-audit.js +772 -0
  95. package/dist/knowledge/onchain-constants.d.ts +4 -0
  96. package/dist/knowledge/onchain-constants.js +35 -0
  97. package/dist/knowledge/order-confirm.d.ts +115 -0
  98. package/dist/knowledge/order-confirm.js +573 -0
  99. package/dist/knowledge/order-context.d.ts +66 -0
  100. package/dist/knowledge/order-context.js +390 -0
  101. package/dist/knowledge/order-ledger.d.ts +69 -0
  102. package/dist/knowledge/order-ledger.js +341 -0
  103. package/dist/knowledge/order-puzzle.d.ts +159 -0
  104. package/dist/knowledge/order-puzzle.js +255 -0
  105. package/dist/knowledge/order-risk.d.ts +66 -0
  106. package/dist/knowledge/order-risk.js +653 -0
  107. package/dist/knowledge/order-templates.d.ts +50 -0
  108. package/dist/knowledge/order-templates.js +368 -0
  109. package/dist/knowledge/order-translation.d.ts +78 -0
  110. package/dist/knowledge/order-translation.js +550 -0
  111. package/dist/knowledge/passport-confirm.d.ts +130 -0
  112. package/dist/knowledge/passport-confirm.js +531 -0
  113. package/dist/knowledge/passport-context.d.ts +59 -0
  114. package/dist/knowledge/passport-context.js +306 -0
  115. package/dist/knowledge/passport-ledger.d.ts +48 -0
  116. package/dist/knowledge/passport-ledger.js +282 -0
  117. package/dist/knowledge/passport-puzzle.d.ts +108 -0
  118. package/dist/knowledge/passport-puzzle.js +333 -0
  119. package/dist/knowledge/passport-risk.d.ts +70 -0
  120. package/dist/knowledge/passport-risk.js +450 -0
  121. package/dist/knowledge/passport-templates.d.ts +40 -0
  122. package/dist/knowledge/passport-templates.js +568 -0
  123. package/dist/knowledge/passport-translation.d.ts +68 -0
  124. package/dist/knowledge/passport-translation.js +516 -0
  125. package/dist/knowledge/payment-risk.d.ts +33 -0
  126. package/dist/knowledge/payment-risk.js +182 -0
  127. package/dist/knowledge/permission-confirm.d.ts +110 -0
  128. package/dist/knowledge/permission-confirm.js +426 -0
  129. package/dist/knowledge/permission-context.d.ts +58 -0
  130. package/dist/knowledge/permission-context.js +224 -0
  131. package/dist/knowledge/permission-ledger.d.ts +38 -0
  132. package/dist/knowledge/permission-ledger.js +403 -0
  133. package/dist/knowledge/permission-puzzle.d.ts +122 -0
  134. package/dist/knowledge/permission-puzzle.js +173 -0
  135. package/dist/knowledge/permission-risk.d.ts +76 -0
  136. package/dist/knowledge/permission-risk.js +411 -0
  137. package/dist/knowledge/permission-templates.d.ts +38 -0
  138. package/dist/knowledge/permission-templates.js +234 -0
  139. package/dist/knowledge/permission-translation.d.ts +57 -0
  140. package/dist/knowledge/permission-translation.js +350 -0
  141. package/dist/knowledge/personal-risk.d.ts +36 -0
  142. package/dist/knowledge/personal-risk.js +212 -0
  143. package/dist/knowledge/progress-confirm.d.ts +108 -0
  144. package/dist/knowledge/progress-confirm.js +456 -0
  145. package/dist/knowledge/progress-context.d.ts +123 -0
  146. package/dist/knowledge/progress-context.js +452 -0
  147. package/dist/knowledge/progress-ledger.d.ts +63 -0
  148. package/dist/knowledge/progress-ledger.js +327 -0
  149. package/dist/knowledge/progress-puzzle.d.ts +82 -0
  150. package/dist/knowledge/progress-puzzle.js +219 -0
  151. package/dist/knowledge/progress-risk.d.ts +74 -0
  152. package/dist/knowledge/progress-risk.js +461 -0
  153. package/dist/knowledge/progress-templates.d.ts +38 -0
  154. package/dist/knowledge/progress-templates.js +228 -0
  155. package/dist/knowledge/progress-translation.d.ts +52 -0
  156. package/dist/knowledge/progress-translation.js +401 -0
  157. package/dist/knowledge/proof-confirm.d.ts +31 -0
  158. package/dist/knowledge/proof-confirm.js +187 -0
  159. package/dist/knowledge/proof-risk.d.ts +33 -0
  160. package/dist/knowledge/proof-risk.js +207 -0
  161. package/dist/knowledge/proof-translation.d.ts +52 -0
  162. package/dist/knowledge/proof-translation.js +283 -0
  163. package/dist/knowledge/registrar-risk.d.ts +34 -0
  164. package/dist/knowledge/registrar-risk.js +217 -0
  165. package/dist/knowledge/repository-confirm.d.ts +36 -0
  166. package/dist/knowledge/repository-confirm.js +242 -0
  167. package/dist/knowledge/repository-risk.d.ts +40 -0
  168. package/dist/knowledge/repository-risk.js +312 -0
  169. package/dist/knowledge/repository-translation.d.ts +58 -0
  170. package/dist/knowledge/repository-translation.js +422 -0
  171. package/dist/knowledge/resource-risk.d.ts +32 -0
  172. package/dist/knowledge/resource-risk.js +157 -0
  173. package/dist/knowledge/reward-confirm.d.ts +113 -0
  174. package/dist/knowledge/reward-confirm.js +496 -0
  175. package/dist/knowledge/reward-context.d.ts +127 -0
  176. package/dist/knowledge/reward-context.js +504 -0
  177. package/dist/knowledge/reward-ledger.d.ts +96 -0
  178. package/dist/knowledge/reward-ledger.js +502 -0
  179. package/dist/knowledge/reward-puzzle.d.ts +97 -0
  180. package/dist/knowledge/reward-puzzle.js +288 -0
  181. package/dist/knowledge/reward-risk.d.ts +84 -0
  182. package/dist/knowledge/reward-risk.js +545 -0
  183. package/dist/knowledge/reward-translation.d.ts +58 -0
  184. package/dist/knowledge/reward-translation.js +501 -0
  185. package/dist/knowledge/safety-rules.js +11 -3
  186. package/dist/knowledge/scenario-modes.d.ts +53 -0
  187. package/dist/knowledge/scenario-modes.js +302 -0
  188. package/dist/knowledge/service-confirm.d.ts +152 -0
  189. package/dist/knowledge/service-confirm.js +699 -0
  190. package/dist/knowledge/service-context.d.ts +66 -0
  191. package/dist/knowledge/service-context.js +403 -0
  192. package/dist/knowledge/service-ledger.d.ts +71 -0
  193. package/dist/knowledge/service-ledger.js +609 -0
  194. package/dist/knowledge/service-puzzle.d.ts +158 -0
  195. package/dist/knowledge/service-puzzle.js +236 -0
  196. package/dist/knowledge/service-risk.d.ts +108 -0
  197. package/dist/knowledge/service-risk.js +615 -0
  198. package/dist/knowledge/service-templates.d.ts +39 -0
  199. package/dist/knowledge/service-templates.js +418 -0
  200. package/dist/knowledge/service-translation.d.ts +103 -0
  201. package/dist/knowledge/service-translation.js +622 -0
  202. package/dist/knowledge/tools-reference.d.ts +17 -0
  203. package/dist/knowledge/tools-reference.js +151 -0
  204. package/dist/knowledge/treasury-confirm.d.ts +133 -0
  205. package/dist/knowledge/treasury-confirm.js +512 -0
  206. package/dist/knowledge/treasury-context.d.ts +64 -0
  207. package/dist/knowledge/treasury-context.js +363 -0
  208. package/dist/knowledge/treasury-ledger.d.ts +42 -0
  209. package/dist/knowledge/treasury-ledger.js +300 -0
  210. package/dist/knowledge/treasury-puzzle.d.ts +163 -0
  211. package/dist/knowledge/treasury-puzzle.js +216 -0
  212. package/dist/knowledge/treasury-risk.d.ts +86 -0
  213. package/dist/knowledge/treasury-risk.js +440 -0
  214. package/dist/knowledge/treasury-templates.d.ts +38 -0
  215. package/dist/knowledge/treasury-templates.js +316 -0
  216. package/dist/knowledge/treasury-translation.d.ts +78 -0
  217. package/dist/knowledge/treasury-translation.js +498 -0
  218. package/dist/knowledge/util-risk.d.ts +30 -0
  219. package/dist/knowledge/util-risk.js +135 -0
  220. package/dist/project/business-puzzle.d.ts +47 -0
  221. package/dist/project/business-puzzle.js +372 -0
  222. package/dist/project/deployment-doc.d.ts +61 -0
  223. package/dist/project/deployment-doc.js +432 -0
  224. package/dist/project/graph.d.ts +1 -0
  225. package/dist/project/graph.js +27 -1
  226. package/dist/project/index.d.ts +1 -0
  227. package/dist/project/index.js +39 -2
  228. package/dist/project/namespace.d.ts +11 -1
  229. package/dist/project/namespace.js +27 -2
  230. package/dist/project/query.d.ts +2 -0
  231. package/dist/project/query.js +56 -15
  232. package/dist/project/risk-aggregator.d.ts +50 -0
  233. package/dist/project/risk-aggregator.js +280 -0
  234. package/dist/project/substep-trace.d.ts +130 -0
  235. package/dist/project/substep-trace.js +332 -0
  236. package/dist/rules.d.ts +12 -0
  237. package/dist/rules.js +9 -0
  238. package/dist/schema/call/allocation.d.ts +44 -44
  239. package/dist/schema/call/arbitration.d.ts +141 -141
  240. package/dist/schema/call/base.d.ts +386 -386
  241. package/dist/schema/call/base.js +6 -6
  242. package/dist/schema/call/bridge-handler.d.ts +5 -2
  243. package/dist/schema/call/bridge.d.ts +159 -159
  244. package/dist/schema/call/contact.d.ts +110 -110
  245. package/dist/schema/call/demand.d.ts +76 -76
  246. package/dist/schema/call/handler.d.ts +2 -3
  247. package/dist/schema/call/handler.js +1 -1
  248. package/dist/schema/call/machine.d.ts +96 -96
  249. package/dist/schema/call/order.d.ts +98 -110
  250. package/dist/schema/call/permission-handler.d.ts +5 -0
  251. package/dist/schema/call/permission-handler.js +54 -0
  252. package/dist/schema/call/permission.d.ts +108 -108
  253. package/dist/schema/call/personal.d.ts +14 -14
  254. package/dist/schema/call/progress.d.ts +57 -72
  255. package/dist/schema/call/progress.js +7 -4
  256. package/dist/schema/call/proof.d.ts +18 -18
  257. package/dist/schema/call/proof.js +12 -7
  258. package/dist/schema/call/repository.d.ts +154 -154
  259. package/dist/schema/call/reward.d.ts +55 -55
  260. package/dist/schema/call/semantic.js +1 -1
  261. package/dist/schema/call/service.d.ts +238 -238
  262. package/dist/schema/call/treasury.d.ts +93 -93
  263. package/dist/schema/config/index.d.ts +178 -5
  264. package/dist/schema/config/index.js +52 -1
  265. package/dist/schema/local/index.d.ts +3554 -836
  266. package/dist/schema/local/index.js +2 -1
  267. package/dist/schema/messenger/index.d.ts +162 -162
  268. package/dist/schema/operations.d.ts +1102 -1118
  269. package/dist/schema/operations.js +7 -1
  270. package/dist/schema/project/index.d.ts +1392 -6
  271. package/dist/schema/project/index.js +426 -2
  272. package/dist/schema/query/index.d.ts +818 -818
  273. package/dist/schema/query/index.js +15 -9
  274. package/dist/schema/schema-query/index.d.ts +23 -3
  275. package/dist/schema/schema-query/index.js +13 -2
  276. package/dist/schema/sync-layer4.d.ts +21 -0
  277. package/dist/schema/sync-layer4.js +261 -0
  278. package/dist/schema/trust/index.d.ts +26 -26
  279. package/dist/schema/utils/guard-query-utils.d.ts +7 -0
  280. package/dist/schema/utils/guard-query-utils.js +14 -1
  281. package/dist/schemas/account_operation.output.json +718 -0
  282. package/dist/schemas/bridge_operation.output.json +1 -1
  283. package/dist/schemas/config_operation.output.json +173 -0
  284. package/dist/schemas/index.json +9 -1
  285. package/dist/schemas/local_info_operation.output.json +718 -0
  286. package/dist/schemas/local_mark_operation.output.json +718 -0
  287. package/dist/schemas/messenger_operation.output.json +1 -1
  288. package/dist/schemas/onchain_events.output.json +1 -1
  289. package/dist/schemas/onchain_operations.output.json +5 -4
  290. package/dist/schemas/onchain_operations.schema.json +1813 -333
  291. package/dist/schemas/onchain_operations_allocation.schema.json +9 -11
  292. package/dist/schemas/onchain_operations_arbitration.schema.json +2 -1
  293. package/dist/schemas/onchain_operations_contact.schema.json +2 -1
  294. package/dist/schemas/onchain_operations_demand.schema.json +2 -1
  295. package/dist/schemas/onchain_operations_gen_passport.schema.json +878 -872
  296. package/dist/schemas/onchain_operations_gen_proof.schema.json +273 -0
  297. package/dist/schemas/onchain_operations_guard.schema.json +584 -70
  298. package/dist/schemas/onchain_operations_machine.schema.json +4 -6
  299. package/dist/schemas/onchain_operations_order.schema.json +13 -9
  300. package/dist/schemas/onchain_operations_payment.schema.json +2 -1
  301. package/dist/schemas/onchain_operations_permission.schema.json +2 -1
  302. package/dist/schemas/onchain_operations_personal.schema.json +2 -1
  303. package/dist/schemas/onchain_operations_progress.schema.json +14 -10
  304. package/dist/schemas/onchain_operations_proof.schema.json +699 -0
  305. package/dist/schemas/onchain_operations_repository.schema.json +2 -1
  306. package/dist/schemas/onchain_operations_reward.schema.json +2 -1
  307. package/dist/schemas/onchain_operations_service.schema.json +4 -6
  308. package/dist/schemas/onchain_operations_treasury.schema.json +2 -1
  309. package/dist/schemas/onchain_table_data.output.json +6 -12
  310. package/dist/schemas/onchain_table_data.schema.json +32 -1
  311. package/dist/schemas/project_operation.output.json +879 -0
  312. package/dist/schemas/project_operation.schema.json +473 -2
  313. package/dist/schemas/query_toolkit.output.json +14906 -6
  314. package/dist/schemas/schema_query.output.json +38 -1
  315. package/dist/telemetry/index.d.ts +1 -1
  316. package/dist/tools/handlers/bridge.d.ts +1 -0
  317. package/dist/tools/handlers/bridge.js +1 -0
  318. package/dist/tools/handlers/config.d.ts +2 -0
  319. package/dist/tools/handlers/config.js +74 -0
  320. package/dist/tools/handlers/file-export.d.ts +3 -0
  321. package/dist/tools/handlers/file-export.js +90 -0
  322. package/dist/tools/handlers/local.d.ts +3 -0
  323. package/dist/tools/handlers/local.js +38 -0
  324. package/dist/tools/handlers/messenger.d.ts +16 -0
  325. package/dist/tools/handlers/messenger.js +188 -0
  326. package/dist/tools/handlers/onchain.d.ts +2 -0
  327. package/dist/tools/handlers/onchain.js +248 -0
  328. package/dist/tools/handlers/project.d.ts +2 -0
  329. package/dist/tools/handlers/project.js +293 -0
  330. package/dist/tools/handlers/query.d.ts +5 -0
  331. package/dist/tools/handlers/query.js +256 -0
  332. package/dist/tools/handlers/schema-query.d.ts +2 -0
  333. package/dist/tools/handlers/schema-query.js +93 -0
  334. package/dist/tools/handlers/trust.d.ts +2 -0
  335. package/dist/tools/handlers/trust.js +194 -0
  336. package/dist/tools/handlers/wip.d.ts +2 -0
  337. package/dist/tools/handlers/wip.js +44 -0
  338. package/dist/tools/index.d.ts +13 -0
  339. package/dist/tools/index.js +526 -0
  340. package/dist/tools/rules-hook.d.ts +2 -0
  341. package/dist/tools/rules-hook.js +23 -0
  342. package/dist/tools/shared.d.ts +20 -0
  343. package/dist/tools/shared.js +130 -0
  344. package/dist/tools/types.d.ts +35 -0
  345. package/dist/tools/types.js +1 -0
  346. package/dist/tools/wrap.d.ts +14 -0
  347. package/dist/tools/wrap.js +267 -0
  348. package/package.json +20 -6
@@ -0,0 +1,825 @@
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 json = JSON.parse(raw);
98
+ if (json && typeof json === 'object' && 'operation_type' in json) {
99
+ blocks.push({ lineStart: i + 1, raw, json: json });
100
+ }
101
+ }
102
+ catch {
103
+ }
104
+ i = j + 1;
105
+ }
106
+ else {
107
+ i++;
108
+ }
109
+ }
110
+ return blocks;
111
+ }
112
+ function extractDefinedGuardNames(mdPath) {
113
+ const blocks = extractJsonBlocks(mdPath);
114
+ const names = new Set();
115
+ for (const b of blocks) {
116
+ if (b.json.operation_type !== 'guard')
117
+ continue;
118
+ const data = b.json.data;
119
+ if (!data)
120
+ continue;
121
+ const namedNew = data.namedNew;
122
+ const name = namedNew?.name;
123
+ if (name)
124
+ names.add(name);
125
+ }
126
+ return names;
127
+ }
128
+ export function loadAllExamples(examplesDir = EXAMPLES_DIR) {
129
+ const result = [];
130
+ if (!fs.existsSync(examplesDir))
131
+ return result;
132
+ const entries = fs.readdirSync(examplesDir, { withFileTypes: true });
133
+ for (const entry of entries) {
134
+ if (!entry.isDirectory())
135
+ continue;
136
+ const subdir = path.join(examplesDir, entry.name);
137
+ const subEntries = fs.readdirSync(subdir, { withFileTypes: true });
138
+ for (const sub of subEntries) {
139
+ if (!sub.isFile())
140
+ continue;
141
+ const fullPath = path.join(subdir, sub.name);
142
+ const relativePath = `${entry.name}/${sub.name}`;
143
+ if (sub.name.endsWith('.md')) {
144
+ const machineOps = extractMachineOpsFromMarkdown(fullPath);
145
+ const progressOps = extractProgressOpsFromMarkdown(fullPath);
146
+ const definedGuards = extractDefinedGuardNames(fullPath);
147
+ if (machineOps.length === 0 && progressOps.length === 0 && definedGuards.size === 0)
148
+ continue;
149
+ const businessDescription = machineOps[0]?.op.data.description;
150
+ result.push({
151
+ example_name: entry.name,
152
+ relative_path: relativePath,
153
+ absolute_path: fullPath,
154
+ machine_ops: machineOps,
155
+ progress_ops: progressOps,
156
+ defined_guard_names: definedGuards,
157
+ business_description: businessDescription,
158
+ });
159
+ }
160
+ else if (sub.name.endsWith('.json') && sub.name.includes('machine')) {
161
+ const raw = fs.readFileSync(fullPath, 'utf-8');
162
+ try {
163
+ const arr = JSON.parse(raw);
164
+ if (!Array.isArray(arr) || arr.length === 0)
165
+ continue;
166
+ const machineName = path.basename(sub.name, '.json');
167
+ result.push({
168
+ example_name: entry.name,
169
+ relative_path: relativePath,
170
+ absolute_path: fullPath,
171
+ machine_ops: [{
172
+ op: {
173
+ operation_type: "machine",
174
+ data: {
175
+ object: { name: machineName, replaceExistName: false },
176
+ node: { op: "add", nodes: arr },
177
+ publish: false,
178
+ },
179
+ env: { network: "testnet" },
180
+ },
181
+ line_start: 0,
182
+ }],
183
+ progress_ops: [],
184
+ defined_guard_names: new Set(),
185
+ business_description: `(standalone JSON: ${machineName})`,
186
+ });
187
+ }
188
+ catch {
189
+ }
190
+ }
191
+ }
192
+ }
193
+ return result;
194
+ }
195
+ function extractMachineOpsFromMarkdown(mdPath) {
196
+ const blocks = extractJsonBlocks(mdPath);
197
+ const result = [];
198
+ for (const b of blocks) {
199
+ if (b.json.operation_type !== 'machine')
200
+ continue;
201
+ try {
202
+ const op = b.json;
203
+ if (!op.data)
204
+ continue;
205
+ const hasNodes = op.data.node?.nodes && Array.isArray(op.data.node.nodes);
206
+ const hasPublish = op.data.publish === true;
207
+ if (!hasNodes && !hasPublish)
208
+ continue;
209
+ result.push({ op, line_start: b.lineStart });
210
+ }
211
+ catch {
212
+ }
213
+ }
214
+ return result;
215
+ }
216
+ function extractProgressOpsFromMarkdown(mdPath) {
217
+ const blocks = extractJsonBlocks(mdPath);
218
+ const result = [];
219
+ for (const b of blocks) {
220
+ const json = b.json;
221
+ const data = json.data;
222
+ if (!data)
223
+ continue;
224
+ const progress = data.progress;
225
+ if (!progress)
226
+ continue;
227
+ const operation = progress.operation;
228
+ if (!operation || !operation.next_node_name || !operation.forward)
229
+ continue;
230
+ try {
231
+ result.push({
232
+ operation_type: json.operation_type,
233
+ data: {
234
+ object: data.object,
235
+ progress: { operation: { next_node_name: operation.next_node_name, forward: operation.forward } },
236
+ submission: data.submission,
237
+ },
238
+ env: { account: json.env?.account, network: json.env?.network },
239
+ _source_line: b.lineStart,
240
+ });
241
+ }
242
+ catch {
243
+ }
244
+ }
245
+ return result;
246
+ }
247
+ export function analyzeSchemaConsistency(_example) {
248
+ return [];
249
+ }
250
+ export function analyzeThresholdIssues(example) {
251
+ const findings = [];
252
+ for (const { op, line_start } of example.machine_ops) {
253
+ if (!op.data.node?.nodes)
254
+ continue;
255
+ const { nodes, pairs } = nodeDefsToMachine(op.data.node.nodes);
256
+ const machineName = getMachineName(op);
257
+ const entryPairs = pairs.filter((p) => p.prev_node === "");
258
+ const hasCompetingEntries = entryPairs.length > 1;
259
+ for (const pair of pairs) {
260
+ if (pair.prev_node === "" && pair.threshold === 0) {
261
+ const forwardCount = pair.forwards.length;
262
+ const isLegitimate = forwardCount === 1 ||
263
+ hasCompetingEntries;
264
+ if (isLegitimate)
265
+ continue;
266
+ findings.push({
267
+ example: example.example_name,
268
+ source_file: example.relative_path,
269
+ line: line_start,
270
+ machine_name: machineName,
271
+ category: "design",
272
+ severity: "medium",
273
+ title: "Entry pair with threshold=0 and multiple Forwards (potential permission bypass)",
274
+ detail: `Pair (prev="", next="${pair.next_node}") has threshold=0 with ${forwardCount} Forwards. ` +
275
+ `With threshold=0, ANY single Forward fires → migration, potentially bypassing other Forwards' ` +
276
+ `permission checks. Set threshold ≥ 1 so ALL intended Forwards must agree. ` +
277
+ `(Note: single-Forward Pairs and competing-OR Pairs with threshold=0 are NOT flagged — they are legitimate.)`,
278
+ rule_id: "R-M3-09",
279
+ 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).`,
280
+ });
281
+ }
282
+ }
283
+ for (const pair of pairs) {
284
+ const totalWeight = pair.forwards.reduce((sum, f) => sum + f.weight, 0);
285
+ if (pair.threshold > totalWeight) {
286
+ findings.push({
287
+ example: example.example_name,
288
+ source_file: example.relative_path,
289
+ line: line_start,
290
+ machine_name: machineName,
291
+ category: "design",
292
+ severity: "critical",
293
+ title: "Threshold exceeds total forward weight (unreachable)",
294
+ 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.`,
295
+ rule_id: "R-M2-06",
296
+ fix: `Reduce threshold to ≤ ${totalWeight} or add more forwards with weight.`,
297
+ });
298
+ }
299
+ }
300
+ }
301
+ return findings;
302
+ }
303
+ export function analyzeNetworkSafety(example) {
304
+ const findings = [];
305
+ for (const { op, line_start } of example.machine_ops) {
306
+ const machineName = getMachineName(op);
307
+ const isPublish = op.data.publish === true;
308
+ const network = op.env.network;
309
+ if (isPublish && network === "mainnet") {
310
+ findings.push({
311
+ example: example.example_name,
312
+ source_file: example.relative_path,
313
+ line: line_start,
314
+ machine_name: machineName,
315
+ category: "runtime",
316
+ severity: "critical",
317
+ title: "Direct mainnet publish without testnet test",
318
+ detail: `Machine "${machineName}" is published directly to mainnet. Per R-M4-02, must test on testnet first.`,
319
+ rule_id: "R-M4-02",
320
+ fix: `Set env.network to "testnet" for first publish, run end-to-end test, then re-publish on mainnet.`,
321
+ });
322
+ }
323
+ }
324
+ return findings;
325
+ }
326
+ export function analyzeConfirmationBypass(example) {
327
+ const findings = [];
328
+ for (const { op, line_start } of example.machine_ops) {
329
+ const machineName = getMachineName(op);
330
+ const isPublish = op.data.publish === true;
331
+ const confirmed = op.env.confirmed === true;
332
+ if (isPublish && confirmed) {
333
+ findings.push({
334
+ example: example.example_name,
335
+ source_file: example.relative_path,
336
+ line: line_start,
337
+ machine_name: machineName,
338
+ category: "runtime",
339
+ severity: "medium",
340
+ title: "confirmed=true bypasses user confirmation prompt",
341
+ 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).`,
342
+ rule_id: "R-M4-04",
343
+ fix: `Show Phase 1 (without confirmed=true) and Phase 2 (with confirmed=true) as separate steps in the example.`,
344
+ });
345
+ }
346
+ }
347
+ return findings;
348
+ }
349
+ export function analyzeGuardReferences(example) {
350
+ const findings = [];
351
+ const defined = example.defined_guard_names;
352
+ for (const { op, line_start } of example.machine_ops) {
353
+ if (!op.data.node?.nodes)
354
+ continue;
355
+ const machineName = getMachineName(op);
356
+ const isPublish = op.data.publish === true;
357
+ for (const nodeDef of op.data.node.nodes) {
358
+ for (const pair of nodeDef.pairs) {
359
+ for (const fwd of pair.forwards) {
360
+ let guardName;
361
+ if (typeof fwd.guard === 'string') {
362
+ guardName = fwd.guard;
363
+ }
364
+ else if (fwd.guard && typeof fwd.guard === 'object') {
365
+ const g = fwd.guard;
366
+ if (typeof g.guard === 'string')
367
+ guardName = g.guard;
368
+ }
369
+ if (!guardName)
370
+ continue;
371
+ if (!defined.has(guardName)) {
372
+ findings.push({
373
+ example: example.example_name,
374
+ source_file: example.relative_path,
375
+ line: line_start,
376
+ machine_name: machineName,
377
+ category: "runtime",
378
+ severity: isPublish ? "critical" : "high",
379
+ title: `Guard "${guardName}" referenced but not defined in example`,
380
+ 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."}`,
381
+ rule_id: isPublish ? "R-M4-03" : "R-M2-01",
382
+ fix: `Add a guard creation step (operation_type="guard") with name="${guardName}" BEFORE the machine creation step.`,
383
+ });
384
+ }
385
+ }
386
+ }
387
+ }
388
+ }
389
+ return findings;
390
+ }
391
+ export function analyzeCrossMachineDeps(example, guardResolutions = new Map()) {
392
+ const findings = [];
393
+ const allDeps = [];
394
+ for (const { op, line_start } of example.machine_ops) {
395
+ if (!op.data.node?.nodes)
396
+ continue;
397
+ const { nodes, pairs } = nodeDefsToMachine(op.data.node.nodes);
398
+ const machineId = getMachineName(op);
399
+ const deps = identifyCrossMachineDependency(machineId, { nodes, pairs }, guardResolutions);
400
+ allDeps.push(...deps);
401
+ if (deps.length > 0) {
402
+ findings.push({
403
+ example: example.example_name,
404
+ source_file: example.relative_path,
405
+ line: line_start,
406
+ machine_name: machineId,
407
+ category: "cross_machine",
408
+ severity: "info",
409
+ title: `Machine declares ${deps.length} cross-Machine dependencies`,
410
+ 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('; '),
411
+ rule_id: "P-M3",
412
+ });
413
+ }
414
+ }
415
+ const cycles = detectCrossMachineCycle(allDeps);
416
+ for (const cycle of cycles) {
417
+ findings.push({
418
+ example: example.example_name,
419
+ source_file: example.relative_path,
420
+ line: 0,
421
+ machine_name: "(project-level)",
422
+ category: "cross_machine",
423
+ severity: "critical",
424
+ title: "Cross-Machine dependency cycle detected",
425
+ detail: `Cycle: ${cycle.join(' → ')}`,
426
+ rule_id: "R-M2-07",
427
+ fix: `Break the cycle by removing one of the dependencies in the cycle.`,
428
+ });
429
+ }
430
+ return { deps: allDeps, cycles, findings };
431
+ }
432
+ export function analyzeRoundTrip(example) {
433
+ const findings = [];
434
+ for (const { op, line_start } of example.machine_ops) {
435
+ if (!op.data.node?.nodes)
436
+ continue;
437
+ const { nodes, pairs } = nodeDefsToMachine(op.data.node.nodes);
438
+ const machineName = getMachineName(op);
439
+ const topo = analyzeTopology(nodes, pairs);
440
+ if (topo.has_cycles) {
441
+ findings.push({
442
+ example: example.example_name,
443
+ source_file: example.relative_path,
444
+ line: line_start,
445
+ machine_name: machineName,
446
+ category: "round_trip",
447
+ severity: "critical",
448
+ title: "Topology analysis: cycle detected (DAG violation)",
449
+ detail: `Machine "${machineName}" has cycles: ${JSON.stringify(topo.cycle_nodes)}`,
450
+ rule_id: "R-M1-03",
451
+ fix: `Remove cycles — Machine must be a DAG.`,
452
+ });
453
+ }
454
+ const ctx = {
455
+ network: op.env.network === "mainnet" ? "mainnet" : "testnet",
456
+ testnet_test_passed: op.env.network !== "mainnet",
457
+ published_services: new Set(),
458
+ published_guards: new Set(),
459
+ published_permissions: new Set(),
460
+ published_machines: new Set(),
461
+ published_arbitrations: new Set(),
462
+ published_rewards: new Set(),
463
+ published_allocators: new Set(),
464
+ published_repositories: new Set(),
465
+ };
466
+ for (const pair of pairs) {
467
+ for (const fwd of pair.forwards) {
468
+ if (fwd.guard)
469
+ ctx.published_guards.add(fwd.guard);
470
+ }
471
+ }
472
+ const machineJson = {
473
+ nodes,
474
+ pairs,
475
+ b_published: op.data.publish === true,
476
+ };
477
+ const assessment = assessMachineRisks(machineJson, ctx);
478
+ const criticalRisks = assessment.detected_risks.filter((r) => r.severity === "critical");
479
+ if (criticalRisks.length > 0) {
480
+ for (const r of criticalRisks) {
481
+ findings.push({
482
+ example: example.example_name,
483
+ source_file: example.relative_path,
484
+ line: line_start,
485
+ machine_name: machineName,
486
+ category: "round_trip",
487
+ severity: "critical",
488
+ title: `Risk assessment: ${r.rule_id} (${r.severity})`,
489
+ detail: r.detail,
490
+ rule_id: r.rule_id,
491
+ });
492
+ }
493
+ }
494
+ const checklist = { nodes, pairs, name: machineName };
495
+ const checklistResult = runStaticChecklist(checklist);
496
+ const failedItems = checklistResult.failed_items.filter((i) => ["C-01", "C-03", "C-06", "C-10"].includes(i.id));
497
+ for (const item of failedItems) {
498
+ findings.push({
499
+ example: example.example_name,
500
+ source_file: example.relative_path,
501
+ line: line_start,
502
+ machine_name: machineName,
503
+ category: "round_trip",
504
+ severity: "high",
505
+ title: `Checklist ${item.id} failed: ${item.description}`,
506
+ detail: item.detail ?? `(no detail)`,
507
+ rule_id: item.id,
508
+ });
509
+ }
510
+ for (const node of nodes) {
511
+ const outgoing = pairs.filter((p) => p.prev_node === node.name);
512
+ const nodeForExpl = {
513
+ name: node.name,
514
+ pairs: outgoing,
515
+ all_pairs: pairs,
516
+ };
517
+ const explained = explainNode(nodeForExpl);
518
+ if (!explained.name || explained.pairs.length !== outgoing.length) {
519
+ findings.push({
520
+ example: example.example_name,
521
+ source_file: example.relative_path,
522
+ line: line_start,
523
+ machine_name: machineName,
524
+ category: "round_trip",
525
+ severity: "medium",
526
+ title: `Round-trip mismatch for node "${node.name}"`,
527
+ detail: `explainNode produced inconsistent output: name="${explained.name}", pairs_count=${explained.pairs.length} (expected ${outgoing.length})`,
528
+ rule_id: "RT-001",
529
+ });
530
+ }
531
+ }
532
+ }
533
+ return findings;
534
+ }
535
+ export function analyzeProgressOps(example) {
536
+ const findings = [];
537
+ const validForwardPairs = new Set();
538
+ let machineName = "(none)";
539
+ for (const { op } of example.machine_ops) {
540
+ if (!op.data.node?.nodes)
541
+ continue;
542
+ machineName = getMachineName(op);
543
+ const { pairs } = nodeDefsToMachine(op.data.node.nodes);
544
+ for (const pair of pairs) {
545
+ validForwardPairs.add(`${pair.next_node}::${pair.forwards.map((f) => f.name).join("|")}`);
546
+ for (const fwd of pair.forwards) {
547
+ validForwardPairs.add(`${pair.next_node}::${fwd.name}`);
548
+ }
549
+ }
550
+ }
551
+ for (const progressOp of example.progress_ops) {
552
+ const op = progressOp.data.progress?.operation;
553
+ if (!op)
554
+ continue;
555
+ const key = `${op.next_node_name}::${op.forward}`;
556
+ const valid = validForwardPairs.has(key);
557
+ if (!valid) {
558
+ const forwardExists = [...validForwardPairs].some((k) => k.endsWith(`::${op.forward}`));
559
+ if (!forwardExists) {
560
+ findings.push({
561
+ example: example.example_name,
562
+ source_file: example.relative_path,
563
+ line: progressOp._source_line ?? 0,
564
+ machine_name: machineName,
565
+ category: "progress",
566
+ severity: "high",
567
+ title: `Progress references unknown forward "${op.forward}"`,
568
+ detail: `Progress op references forward "${op.forward}" but no such forward exists in machine "${machineName}".`,
569
+ rule_id: "R-M3-04",
570
+ fix: `Verify forward name matches one defined in the Machine.`,
571
+ });
572
+ }
573
+ else {
574
+ findings.push({
575
+ example: example.example_name,
576
+ source_file: example.relative_path,
577
+ line: progressOp._source_line ?? 0,
578
+ machine_name: machineName,
579
+ category: "progress",
580
+ severity: "medium",
581
+ title: `Progress forward "${op.forward}" doesn't lead to "${op.next_node_name}"`,
582
+ detail: `Forward "${op.forward}" exists but doesn't target node "${op.next_node_name}".`,
583
+ rule_id: "R-M3-05",
584
+ fix: `Correct next_node_name to match the forward's target.`,
585
+ });
586
+ }
587
+ }
588
+ }
589
+ return findings;
590
+ }
591
+ export function analyzePublishStep(example) {
592
+ const findings = [];
593
+ const hasPublish = example.machine_ops.some(({ op }) => op.data.publish === true);
594
+ const hasProgress = example.progress_ops.length > 0;
595
+ if (hasProgress && !hasPublish) {
596
+ findings.push({
597
+ example: example.example_name,
598
+ source_file: example.relative_path,
599
+ line: 0,
600
+ machine_name: "(file-level)",
601
+ category: "runtime",
602
+ severity: "high",
603
+ title: "Progress operations present but no `publish: true` step",
604
+ 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).`,
605
+ rule_id: "R-M4-01",
606
+ fix: `Add a publish step (or set data.publish=true on the machine creation operation).`,
607
+ });
608
+ }
609
+ return findings;
610
+ }
611
+ export function analyzeRiskRuleCoverage(example) {
612
+ const ruleCounts = new Map();
613
+ let totalFindings = 0;
614
+ const allFindings = [
615
+ ...analyzeSchemaConsistency(example),
616
+ ...analyzeThresholdIssues(example),
617
+ ...analyzeNetworkSafety(example),
618
+ ...analyzeConfirmationBypass(example),
619
+ ...analyzeGuardReferences(example),
620
+ ...analyzeRoundTrip(example),
621
+ ...analyzeProgressOps(example),
622
+ ...analyzePublishStep(example),
623
+ ];
624
+ for (const f of allFindings) {
625
+ if (f.rule_id) {
626
+ ruleCounts.set(f.rule_id, (ruleCounts.get(f.rule_id) ?? 0) + 1);
627
+ totalFindings++;
628
+ }
629
+ }
630
+ return { ruleCounts, totalFindings };
631
+ }
632
+ export function scanAllExamples(examplesDir = EXAMPLES_DIR) {
633
+ const examples = loadAllExamples(examplesDir);
634
+ const findingsByExample = new Map();
635
+ const findingsByCategory = new Map();
636
+ const findingsBySeverity = new Map();
637
+ const riskRuleCoverage = new Map();
638
+ let totalFindings = 0;
639
+ for (const example of examples) {
640
+ const exampleFindings = [];
641
+ exampleFindings.push(...analyzeSchemaConsistency(example));
642
+ exampleFindings.push(...analyzeThresholdIssues(example));
643
+ exampleFindings.push(...analyzeNetworkSafety(example));
644
+ exampleFindings.push(...analyzeConfirmationBypass(example));
645
+ exampleFindings.push(...analyzeGuardReferences(example));
646
+ const crossMachine = analyzeCrossMachineDeps(example);
647
+ exampleFindings.push(...crossMachine.findings);
648
+ exampleFindings.push(...analyzeRoundTrip(example));
649
+ exampleFindings.push(...analyzeProgressOps(example));
650
+ exampleFindings.push(...analyzePublishStep(example));
651
+ findingsByExample.set(example.relative_path, exampleFindings);
652
+ for (const f of exampleFindings) {
653
+ const catList = findingsByCategory.get(f.category) ?? [];
654
+ catList.push(f);
655
+ findingsByCategory.set(f.category, catList);
656
+ const sevList = findingsBySeverity.get(f.severity) ?? [];
657
+ sevList.push(f);
658
+ findingsBySeverity.set(f.severity, sevList);
659
+ if (f.rule_id) {
660
+ riskRuleCoverage.set(f.rule_id, (riskRuleCoverage.get(f.rule_id) ?? 0) + 1);
661
+ }
662
+ totalFindings++;
663
+ }
664
+ }
665
+ return {
666
+ examples,
667
+ findings_by_example: findingsByExample,
668
+ findings_by_category: findingsByCategory,
669
+ findings_by_severity: findingsBySeverity,
670
+ total_findings: totalFindings,
671
+ risk_rule_coverage: riskRuleCoverage,
672
+ };
673
+ }
674
+ export function formatScanReport(result) {
675
+ const lines = [];
676
+ lines.push('# Examples Scan Report — d:\\wowok\\docs\\examples');
677
+ lines.push('');
678
+ lines.push('> Auto-generated by `examples-scanner.ts` — comprehensive scan of all');
679
+ lines.push('> machine/progress JSON in 5 example directories for design and runtime problems.');
680
+ lines.push('');
681
+ lines.push('## Summary');
682
+ lines.push('');
683
+ lines.push(`- **Examples scanned**: ${result.examples.length}`);
684
+ lines.push(`- **Total findings**: ${result.total_findings}`);
685
+ lines.push('');
686
+ lines.push('### Findings by Severity');
687
+ lines.push('');
688
+ lines.push('| Severity | Count |');
689
+ lines.push('|----------|-------|');
690
+ const sevOrder = ["critical", "high", "medium", "low", "info"];
691
+ for (const sev of sevOrder) {
692
+ const count = result.findings_by_severity.get(sev)?.length ?? 0;
693
+ lines.push(`| ${sev} | ${count} |`);
694
+ }
695
+ lines.push('');
696
+ lines.push('### Findings by Category');
697
+ lines.push('');
698
+ lines.push('| Category | Count |');
699
+ lines.push('|----------|-------|');
700
+ const catOrder = [
701
+ "schema_consistency", "design", "runtime",
702
+ "cross_machine", "round_trip", "progress", "risk_rule",
703
+ ];
704
+ for (const cat of catOrder) {
705
+ const count = result.findings_by_category.get(cat)?.length ?? 0;
706
+ lines.push(`| ${cat} | ${count} |`);
707
+ }
708
+ lines.push('');
709
+ lines.push('### Risk Rule Coverage (which rules fired across examples)');
710
+ lines.push('');
711
+ lines.push('| Rule ID | Total Hits |');
712
+ lines.push('|---------|-----------|');
713
+ const sortedRules = [...result.risk_rule_coverage.entries()].sort((a, b) => a[0].localeCompare(b[0]));
714
+ for (const [ruleId, count] of sortedRules) {
715
+ lines.push(`| ${ruleId} | ${count} |`);
716
+ }
717
+ lines.push('');
718
+ lines.push('## Per-Example Findings');
719
+ lines.push('');
720
+ for (const example of result.examples) {
721
+ const findings = result.findings_by_example.get(example.relative_path) ?? [];
722
+ lines.push(`### ${example.example_name} — \`${example.relative_path}\``);
723
+ lines.push('');
724
+ lines.push(`- **Source**: \`${example.relative_path}\``);
725
+ lines.push(`- **Machine operations**: ${example.machine_ops.length}`);
726
+ lines.push(`- **Progress operations**: ${example.progress_ops.length}`);
727
+ lines.push(`- **Defined guards**: ${example.defined_guard_names.size}`);
728
+ if (example.business_description) {
729
+ lines.push(`- **Business description**: ${example.business_description}`);
730
+ }
731
+ lines.push(`- **Findings**: ${findings.length}`);
732
+ lines.push('');
733
+ if (findings.length === 0) {
734
+ lines.push('✅ No issues detected.');
735
+ lines.push('');
736
+ continue;
737
+ }
738
+ const bySev = new Map();
739
+ for (const f of findings) {
740
+ const list = bySev.get(f.severity) ?? [];
741
+ list.push(f);
742
+ bySev.set(f.severity, list);
743
+ }
744
+ for (const sev of sevOrder) {
745
+ const sevFindings = bySev.get(sev) ?? [];
746
+ if (sevFindings.length === 0)
747
+ continue;
748
+ lines.push(`#### ${sev.toUpperCase()} (${sevFindings.length})`);
749
+ lines.push('');
750
+ for (const f of sevFindings) {
751
+ lines.push(`- **[${f.rule_id ?? "—"}] ${f.title}** (line ${f.line})`);
752
+ lines.push(` - ${f.detail}`);
753
+ if (f.fix) {
754
+ lines.push(` - **Fix**: ${f.fix}`);
755
+ }
756
+ lines.push('');
757
+ }
758
+ }
759
+ }
760
+ lines.push('## Cross-Cutting Patterns');
761
+ lines.push('');
762
+ const schemaFindings = result.findings_by_category.get("schema_consistency") ?? [];
763
+ if (schemaFindings.length === 0) {
764
+ lines.push('### Schema Consistency — No Issues (camelCase is canonical)');
765
+ lines.push('');
766
+ lines.push('The previous SCHEMA-001/002/003/004 rules have been REMOVED (2026-07-19).');
767
+ lines.push('');
768
+ lines.push('**Reason**: Verification against MCP schema (`d:\\wowok\\agent\\mcp\\src`) confirmed that:');
769
+ lines.push('- `MachineForwardSchema` accepts `namedOperator`, `permissionIndex` (camelCase)');
770
+ lines.push('- `MachineForwardGuardSchema` is an OBJECT `{ guard: string, retained_submission?: number[] }` (NOT a flat string)');
771
+ lines.push('- `NamedObjectSchema` accepts `replaceExistName`, `onChain` (camelCase)');
772
+ lines.push('');
773
+ lines.push('Source examples using camelCase are therefore CORRECT per MCP schema — the previous rules were false positives.');
774
+ lines.push('');
775
+ }
776
+ const thresholdFindings = (result.findings_by_category.get("design") ?? []).filter((f) => f.rule_id === "R-M3-09");
777
+ if (thresholdFindings.length > 0) {
778
+ lines.push('### Threshold=0 on Multi-Forward Entry Pairs (R-M3-09)');
779
+ lines.push('');
780
+ lines.push(`Found ${thresholdFindings.length} multi-Forward entry pairs with threshold=0 across examples.`);
781
+ lines.push('');
782
+ lines.push('**Detection logic** (refined 2026-07-19):');
783
+ lines.push('- Single-Forward Pair with threshold=0 → **NOT flagged** (legitimate: single execution triggers migration regardless of threshold)');
784
+ lines.push('- Competing-OR Pairs (multiple Pairs share prev_node="") with threshold=0 → **NOT flagged** (legitimate OR semantics)');
785
+ lines.push('- Multi-Forward Pair with threshold=0 AND no competing siblings → **FLAGGED** (potential permission bypass: any single Forward fires → migration)');
786
+ lines.push('');
787
+ const affectedFiles = [...new Set(thresholdFindings.map((f) => f.source_file))];
788
+ lines.push(`**Affected source files**: ${affectedFiles.map((p) => `\`${p}\``).join(', ')}.`);
789
+ lines.push('');
790
+ 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).');
791
+ lines.push('');
792
+ }
793
+ else {
794
+ lines.push('### Threshold=0 on Entry Pairs — No Issues');
795
+ lines.push('');
796
+ lines.push('All entry pairs with threshold=0 fall into legitimate categories (single-Forward or competing-OR).');
797
+ lines.push('');
798
+ }
799
+ const mainnetFindings = (result.findings_by_category.get("runtime") ?? []).filter((f) => f.rule_id === "R-M4-02");
800
+ if (mainnetFindings.length > 0) {
801
+ lines.push('### Direct Mainnet Publish (R-M4-02)');
802
+ lines.push('');
803
+ lines.push(`Found ${mainnetFindings.length} examples publishing directly to mainnet without testnet test.`);
804
+ lines.push('');
805
+ lines.push('**Affected examples**: MyShop, MyShop_Advanced.');
806
+ lines.push('');
807
+ lines.push('**Fix**: Add a testnet publish step before mainnet, or change the network to testnet for examples.');
808
+ lines.push('');
809
+ }
810
+ lines.push('## Recommendations for Linter & Cognition Closure');
811
+ lines.push('');
812
+ lines.push('Based on the findings, the following linter rules and cognition improvements are recommended:');
813
+ lines.push('');
814
+ 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.');
815
+ 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.');
816
+ 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.');
817
+ lines.push('4. **Add lint rule** for `confirmed: true` + `publish: true` combination without showing the Phase 1 confirmation prompt first.');
818
+ 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).');
819
+ lines.push('');
820
+ lines.push('---');
821
+ lines.push('');
822
+ lines.push('*End of report.*');
823
+ return lines.join('\n');
824
+ }
825
+ export const EXAMPLES_SCANNER_VERSION = "1.0.0";