@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,823 +1 @@
1
- import * as fs from 'fs';
2
- import { MAX_NODE_COUNT, USER_DEFINED_PERM_INDEX_START, } from "./onchain-constants.js";
3
- import { traceSubsteps, } from "../project/substep-trace.js";
4
- import { aggregateProjectRisks, } from "../project/risk-aggregator.js";
5
- function add(findings, check_id, severity, message, location, suggestion) {
6
- findings.push({ check_id, severity, message, location, suggestion });
7
- }
8
- function fromDeploymentDocInput(input) {
9
- const version = input.version ?? "v1";
10
- const namespace_tag = `${input.project_prefix}_${version}`;
11
- const topological_order = input.steps.map((s) => s.entry_id);
12
- const testnet_blocks = [];
13
- const mainnet_blocks = [];
14
- for (const step of input.steps) {
15
- const phase = step.network_phase;
16
- if (phase === "both" || phase === "testnet")
17
- testnet_blocks.push(synthesizeBlock(step, input, "testnet"));
18
- if (phase === "both" || phase === "mainnet")
19
- mainnet_blocks.push(synthesizeBlock(step, input, "mainnet"));
20
- }
21
- const testnet_verification = new Map();
22
- for (let i = 1; i <= 11; i++)
23
- testnet_verification.set(`V-T-${String(i).padStart(2, "0")}`, false);
24
- const mainnet_verification = new Map();
25
- for (let i = 1; i <= 5; i++)
26
- mainnet_verification.set(`V-M-${String(i).padStart(2, "0")}`, false);
27
- const completeness_checklist = new Map();
28
- for (let i = 1; i <= 20; i++)
29
- completeness_checklist.set(`D-${String(i).padStart(2, "0")}`, false);
30
- return {
31
- project_name: input.project_prefix, version, namespace_tag,
32
- objects: input.objects ?? [], edges: input.edges ?? [],
33
- steps: input.steps ?? [], scenarios: input.scenarios ?? [],
34
- testnet_blocks, mainnet_blocks,
35
- testnet_verification, mainnet_verification,
36
- completeness_checklist, topological_order,
37
- };
38
- }
39
- function synthesizeBlock(step, input, network) {
40
- const obj = input.objects.find((o) => o.entry_id === step.entry_id);
41
- const name = obj?.name ?? `${step.object_type}_${step.step}`;
42
- const replaceExistName = network === "testnet";
43
- const tag = network === "testnet" ? "T" : "M";
44
- return {
45
- step: step.step,
46
- operation_type: step.object_type,
47
- data: {
48
- object: { name, replaceExistName },
49
- description: `${step.operation} ${step.object_type} (step ${step.step})`,
50
- },
51
- env: {
52
- account: `${input.project_prefix}_merchant_${network}`,
53
- network, replaceExistName, confirmed: true,
54
- },
55
- substeps: [{
56
- id: `${tag}${step.step}.1`,
57
- name: `${step.operation} ${step.object_type}`,
58
- inputs: [],
59
- outputs: [`${tag}${step.step}.output`],
60
- }],
61
- };
62
- }
63
- function parseDeploymentMarkdown(mdPath) {
64
- const content = fs.readFileSync(mdPath, "utf-8");
65
- const lines = content.split("\n");
66
- const objects = parseTable(lines, "Object List", (r) => ({
67
- entry_id: r["entry_id"] ?? "",
68
- object_type: r["object_type"],
69
- name: r["name"] ?? "",
70
- reused_from: r["reused_from"] || undefined,
71
- publish_required: r["publish_required"] === "true",
72
- description: r["description"] || undefined,
73
- })).filter((o) => o.entry_id && o.name);
74
- const edges = parseTable(lines, "Dependency Edges", (r) => ({
75
- from: r["from"] ?? "",
76
- to: r["to"] ?? "",
77
- edge_kind: r["edge_kind"] ?? "",
78
- field_path: r["field_path"] ?? "",
79
- required_at_publish: r["required_at_publish"] === "true",
80
- })).filter((e) => e.from && e.to);
81
- const scenarios = parseTable(lines, "Scenario Matrix", (r) => ({
82
- scenario_id: r["scenario_id"] ?? "",
83
- description: r["description"] ?? "",
84
- primary_object: r["primary_object"] ?? "",
85
- supporting_objects: (r["supporting_objects"] ?? "").split(",").map((s) => s.trim()).filter(Boolean),
86
- test_step_refs: r["test_step_refs"] ? r["test_step_refs"].split(",").map((s) => s.trim()).filter(Boolean) : undefined,
87
- })).filter((s) => s.scenario_id);
88
- const steps = parseTable(lines, "Topological Execution Plan", (r) => {
89
- const phase = r["network_phase"] === "testnet" || r["network_phase"] === "mainnet" || r["network_phase"] === "both"
90
- ? r["network_phase"]
91
- : "both";
92
- return {
93
- step: parseInt(r["step"] ?? "0", 10) || 0,
94
- object_type: r["object_type"],
95
- operation: r["operation"] ?? "",
96
- substep_count: parseInt(r["substep_count"] ?? "0", 10) || 0,
97
- depends_on: (r["depends_on"] ?? "").replace(/[\[\]]/g, "").split(",").map((s) => s.trim()).filter(Boolean).map((n) => parseInt(n, 10) || 0),
98
- entry_id: r["entry_id"] ?? "",
99
- network_phase: phase,
100
- };
101
- }).filter((s) => s.step > 0);
102
- const allBlocks = extractJsonBlocks(lines);
103
- const testnet_blocks = [];
104
- const mainnet_blocks = [];
105
- for (const b of allBlocks) {
106
- if (b.env?.network === "mainnet")
107
- mainnet_blocks.push(b);
108
- else
109
- testnet_blocks.push(b);
110
- }
111
- const testnet_verification = parseStatusMap(lines, "V-T-");
112
- const mainnet_verification = parseStatusMap(lines, "V-M-");
113
- const completeness_checklist = parseStatusMap(lines, "D-", "Completeness Checklist");
114
- const meta = parseMetaTable(lines);
115
- const project_name = meta.get("project_name") ?? deriveProjectFromPath(mdPath);
116
- const version = meta.get("version") ?? "v1";
117
- const namespace_tag = meta.get("namespace tag") ?? meta.get("namespace_tag") ?? `${project_name}_${version}`;
118
- const topological_order = steps.map((s) => s.entry_id);
119
- return {
120
- project_name, version, namespace_tag,
121
- objects, edges, steps, scenarios,
122
- testnet_blocks, mainnet_blocks,
123
- testnet_verification, mainnet_verification,
124
- completeness_checklist, topological_order,
125
- };
126
- }
127
- function parseTable(lines, headerHint, mapper) {
128
- return parseMarkdownTable(lines, headerHint).map(mapper);
129
- }
130
- function parseMarkdownTable(lines, headerHint) {
131
- const rows = [];
132
- for (let i = 0; i < lines.length; i++) {
133
- if (!lines[i].includes(headerHint))
134
- continue;
135
- let headerIdx = -1;
136
- for (let k = i; k < Math.min(i + 10, lines.length); k++) {
137
- if (lines[k].trim().startsWith("|") && lines[k].includes("|")) {
138
- headerIdx = k;
139
- break;
140
- }
141
- }
142
- if (headerIdx === -1)
143
- break;
144
- const headers = splitTableRow(lines[headerIdx]);
145
- let rowIdx = headerIdx + 1;
146
- if (rowIdx < lines.length && /^\s*\|[\s-:|]+\|\s*$/.test(lines[rowIdx]))
147
- rowIdx++;
148
- while (rowIdx < lines.length && lines[rowIdx].trim().startsWith("|")) {
149
- const cells = splitTableRow(lines[rowIdx]);
150
- if (cells.length === 0)
151
- break;
152
- const row = {};
153
- for (let h = 0; h < headers.length; h++)
154
- row[headers[h].trim()] = (cells[h] ?? "").trim();
155
- rows.push(row);
156
- rowIdx++;
157
- }
158
- break;
159
- }
160
- return rows;
161
- }
162
- function splitTableRow(line) {
163
- const trimmed = line.trim();
164
- if (!trimmed.startsWith("|"))
165
- return [];
166
- return trimmed.slice(1, trimmed.endsWith("|") ? -1 : undefined).split("|");
167
- }
168
- function parseStatusMap(lines, prefix, hint) {
169
- const result = new Map();
170
- const rows = hint ? parseMarkdownTable(lines, hint) : parseMarkdownTable(lines, "Verification Checklist");
171
- for (const r of rows) {
172
- const id = r["verification_id"] ?? r["check_id"] ?? "";
173
- if (!id.startsWith(prefix))
174
- continue;
175
- const status = (r["status"] ?? "").trim();
176
- result.set(id, status.includes("✅") || status.toLowerCase().includes("pass"));
177
- }
178
- return result;
179
- }
180
- function parseMetaTable(lines) {
181
- const result = new Map();
182
- for (const r of parseMarkdownTable(lines, "Project Metadata")) {
183
- const key = r["field"] ?? "";
184
- const value = r["value"] ?? "";
185
- if (key)
186
- result.set(key.trim(), value.trim());
187
- }
188
- return result;
189
- }
190
- function extractJsonBlocks(lines) {
191
- const blocks = [];
192
- let i = 0;
193
- while (i < lines.length) {
194
- if (lines[i].trim().startsWith("```json")) {
195
- const body = [];
196
- let j = i + 1;
197
- while (j < lines.length && !lines[j].trim().startsWith("```")) {
198
- body.push(lines[j]);
199
- j++;
200
- }
201
- try {
202
- const parsed = JSON.parse(body.join("\n"));
203
- if (parsed && typeof parsed === "object" && "operation_type" in parsed) {
204
- const env = (parsed.env ?? {});
205
- const data = (parsed.data ?? {});
206
- const substepsRaw = parsed.substeps;
207
- const substeps = Array.isArray(substepsRaw) ? substepsRaw.map(normalizeSubstep) : undefined;
208
- blocks.push({
209
- step: typeof parsed.step === "number" ? parsed.step : 0,
210
- operation_type: String(parsed.operation_type ?? ""),
211
- data,
212
- env: {
213
- network: typeof env.network === "string" ? env.network : undefined,
214
- replaceExistName: typeof env.replaceExistName === "boolean" ? env.replaceExistName : undefined,
215
- forceClaim: typeof env.forceClaim === "boolean" ? env.forceClaim : undefined,
216
- confirmed: typeof env.confirmed === "boolean" ? env.confirmed : undefined,
217
- ...env,
218
- },
219
- substeps,
220
- });
221
- }
222
- }
223
- catch { }
224
- i = j + 1;
225
- }
226
- else {
227
- i++;
228
- }
229
- }
230
- return blocks;
231
- }
232
- function normalizeSubstep(raw) {
233
- if (!raw || typeof raw !== "object")
234
- return { id: "", inputs: [], outputs: [] };
235
- const s = raw;
236
- return {
237
- id: String(s.id ?? ""),
238
- name: typeof s.name === "string" ? s.name : undefined,
239
- inputs: Array.isArray(s.inputs) ? s.inputs.map(String) : [],
240
- outputs: Array.isArray(s.outputs) ? s.outputs.map(String) : [],
241
- };
242
- }
243
- function deriveProjectFromPath(mdPath) {
244
- const base = mdPath.split(/[\\/]/).pop() ?? "project";
245
- return base.replace(/_v\d+_deployment\.md$/i, "").replace(/\.md$/i, "");
246
- }
247
- function* walkPermissionIndices(value) {
248
- if (value === null || value === undefined || typeof value !== "object")
249
- return;
250
- if (Array.isArray(value)) {
251
- for (const v of value)
252
- yield* walkPermissionIndices(v);
253
- return;
254
- }
255
- const obj = value;
256
- if (typeof obj.permissionIndex === "number")
257
- yield obj.permissionIndex;
258
- if (typeof obj.permission_index === "number")
259
- yield obj.permission_index;
260
- if (typeof obj.index === "number" && obj.__isPermission === true)
261
- yield obj.index;
262
- for (const v of Object.values(obj))
263
- yield* walkPermissionIndices(v);
264
- }
265
- function countMachineNodes(block) {
266
- const node = block.data?.node;
267
- const nodes = node?.nodes;
268
- return Array.isArray(nodes) ? nodes.length : 0;
269
- }
270
- function deriveEntryIdFromBlock(block, doc) {
271
- const obj = block.data.object;
272
- let name;
273
- if (typeof obj === "string")
274
- name = obj;
275
- else if (obj && typeof obj === "object") {
276
- const o = obj;
277
- if (typeof o.name === "string")
278
- name = o.name;
279
- }
280
- if (!name)
281
- return undefined;
282
- return doc.objects.find((o) => o.name === name)?.entry_id;
283
- }
284
- export function analyzeObjectDependencyCompleteness(input) {
285
- const findings = [];
286
- try {
287
- const doc = normalizeInput(input);
288
- if (!doc) {
289
- add(findings, "D-01", "critical", "No deployment document provided (need document_path or deployment_doc)");
290
- return findings;
291
- }
292
- const definedIds = new Set(doc.objects.map((o) => o.entry_id));
293
- const referencedIds = new Set();
294
- for (const e of doc.edges) {
295
- referencedIds.add(e.from);
296
- referencedIds.add(e.to);
297
- }
298
- for (const ref of referencedIds) {
299
- if (ref.endsWith(":*"))
300
- continue;
301
- if (!definedIds.has(ref)) {
302
- add(findings, "D-01", "critical", `Object '${ref}' is referenced in §1.2 but not defined in §1.1`, "§1.2 Dependency Edges", `Add '${ref}' to §1.1 Object List or remove the reference.`);
303
- }
304
- }
305
- for (const e of doc.edges) {
306
- const fromOk = definedIds.has(e.from) || e.from.endsWith(":*");
307
- const toOk = definedIds.has(e.to) || e.to.endsWith(":*");
308
- if (!fromOk || !toOk) {
309
- add(findings, "D-02", "critical", `Dangling dependency: ${e.from} → ${e.to} (edge_kind='${e.edge_kind}')`, "§1.2 Dependency Edges", "Create the missing object or remove the edge.");
310
- }
311
- }
312
- for (const g of doc.objects.filter((o) => o.object_type === "guard")) {
313
- const hasCreate = doc.testnet_blocks.some((b) => b.operation_type === "guard" &&
314
- b.data.object?.name === g.name);
315
- const hasGenPassport = doc.testnet_blocks.some((b) => b.operation_type === "passport" || b.data.gen_passport === true || b.data.object === g.name);
316
- if (!hasCreate)
317
- add(findings, "D-08", "critical", `Guard '${g.entry_id}' has no create step in §3.2`, `§3.2 (guard: ${g.name})`, `Add a guard creation JSON block for '${g.name}'.`);
318
- if (!hasGenPassport)
319
- add(findings, "D-08", "critical", `Guard '${g.entry_id}' has no gen_passport step in §3.2`, `§3.2 (guard: ${g.name})`, `Add a passport/gen_passport JSON block after the guard creation step.`);
320
- }
321
- }
322
- catch (err) {
323
- add(findings, "D-01", "warning", `analyzeObjectDependencyCompleteness failed: ${err.message}`);
324
- }
325
- return findings;
326
- }
327
- export function analyzeSubstepCoherence(input) {
328
- const findings = [];
329
- try {
330
- const doc = normalizeInput(input);
331
- if (!doc)
332
- return [];
333
- for (const network of ["testnet", "mainnet"]) {
334
- const substeps = collectSubsteps(network === "testnet" ? doc.testnet_blocks : doc.mainnet_blocks, network);
335
- const result = traceSubsteps({
336
- project_prefix: doc.project_name, version: doc.version, network, substeps,
337
- });
338
- emitCoherenceFindings(result, network, findings);
339
- }
340
- }
341
- catch (err) {
342
- add(findings, "D-10", "warning", `analyzeSubstepCoherence failed: ${err.message}`);
343
- }
344
- return findings;
345
- }
346
- function collectSubsteps(blocks, network) {
347
- const records = [];
348
- const tag = network === "testnet" ? "T" : "M";
349
- for (const block of blocks) {
350
- if (!block.substeps)
351
- continue;
352
- const parentStep = `${tag}${block.step}`;
353
- for (const s of block.substeps) {
354
- if (!s.id)
355
- continue;
356
- records.push({
357
- step_id: s.id, parent_step: parentStep,
358
- object_type: block.operation_type,
359
- entry_id: "", operation_type: block.operation_type, network,
360
- input: { data: block.data, input_refs: s.inputs },
361
- timestamp: 0, status: "PENDING",
362
- dependencies: {
363
- input_refs: s.inputs,
364
- output_refs: s.outputs.map((field_path) => ({ substep_id: s.id, field_path })),
365
- },
366
- });
367
- }
368
- }
369
- return records;
370
- }
371
- function emitCoherenceFindings(result, network, findings) {
372
- for (const d of result.dangling_inputs) {
373
- add(findings, "D-10", "critical", `[${network}] Dangling input: substep '${d.substep_id}' references missing '${d.missing_ref}'`, `${network} §substeps`, `Ensure '${d.missing_ref}' is produced by an earlier substep.`);
374
- }
375
- for (const c of result.circular_refs) {
376
- add(findings, "D-10", "critical", `[${network}] Circular reference: ${c.cycle.join(" → ")}`, `${network} §substeps`, "Break the cycle by removing one dependency.");
377
- }
378
- for (const m of result.missing_outputs) {
379
- add(findings, "D-10", "warning", `[${network}] Missing output: substep '${m.substep_id}' did not produce '${m.expected_field}'`, `${network} §substeps`, `Ensure '${m.substep_id}' produces '${m.expected_field}'.`);
380
- }
381
- for (const b of result.cross_step_breaks) {
382
- add(findings, "D-10", "critical", `[${network}] Cross-step break: failed step '${b.source_step}' blocks '${b.target_step}'`, `${network} §substeps`, `Fix step '${b.source_step}' or adjust the dependency.`);
383
- }
384
- }
385
- export function analyzeNetworkConsistency(input) {
386
- const findings = [];
387
- try {
388
- const doc = normalizeInput(input);
389
- if (!doc)
390
- return [];
391
- const testnetBlocks = doc.testnet_blocks;
392
- const mainnetBlocks = doc.mainnet_blocks;
393
- const expectedOrder = doc.topological_order;
394
- if (expectedOrder.length > 0 && testnetBlocks.length > 0) {
395
- for (let i = 0; i < testnetBlocks.length; i++) {
396
- const expected = expectedOrder[i];
397
- if (!expected)
398
- break;
399
- const blockEntryId = deriveEntryIdFromBlock(testnetBlocks[i], doc);
400
- if (blockEntryId && blockEntryId !== expected) {
401
- add(findings, "D-04", "critical", `testnet step ${testnetBlocks[i].step} order mismatch: expected '${expected}', got '${blockEntryId}'`, "§3.2 testnet JSON Operation Sequence", "Reorder testnet JSON blocks to match §2 topological order.");
402
- break;
403
- }
404
- }
405
- }
406
- for (const b of testnetBlocks) {
407
- if (b.env.network !== "testnet")
408
- add(findings, "D-05", "critical", `testnet step ${b.step} env.network is '${b.env.network ?? "(missing)"}', expected 'testnet'`, `§3.2 step ${b.step}`, "Set env.network = 'testnet' on all §3.2 JSON blocks.");
409
- }
410
- for (const b of testnetBlocks) {
411
- if (b.env.replaceExistName !== true)
412
- add(findings, "D-06", "critical", `testnet step ${b.step} env.replaceExistName is '${b.env.replaceExistName ?? "(missing)"}', expected true`, `§3.2 step ${b.step}`, "Set env.replaceExistName = true on all §3.2 JSON blocks (testnet allows overwrite).");
413
- }
414
- if (testnetBlocks.length !== mainnetBlocks.length) {
415
- add(findings, "D-11", "critical", `mainnet step count (${mainnetBlocks.length}) != testnet step count (${testnetBlocks.length})`, "§3.2 vs §4.2", "Ensure mainnet JSON blocks correspond 1:1 with testnet blocks.");
416
- }
417
- else {
418
- for (let i = 0; i < mainnetBlocks.length; i++) {
419
- const t = testnetBlocks[i];
420
- const m = mainnetBlocks[i];
421
- if (t.step !== m.step)
422
- add(findings, "D-11", "critical", `mainnet step ${m.step} does not match testnet step ${t.step}`, `§4.2 step ${m.step}`, "Ensure mainnet step numbers match testnet.");
423
- if (t.operation_type !== m.operation_type)
424
- add(findings, "D-11", "critical", `step ${m.step} operation_type mismatch: testnet='${t.operation_type}', mainnet='${m.operation_type}'`, `§4.2 step ${m.step}`, "Align mainnet operation_type with testnet.");
425
- }
426
- }
427
- for (const b of mainnetBlocks) {
428
- if (b.env.network !== "mainnet")
429
- add(findings, "D-12", "critical", `mainnet step ${b.step} env.network is '${b.env.network ?? "(missing)"}', expected 'mainnet'`, `§4.2 step ${b.step}`, "Set env.network = 'mainnet' on all §4.2 JSON blocks.");
430
- }
431
- for (const b of mainnetBlocks) {
432
- if (b.env.replaceExistName !== false && !b.env.forceClaim)
433
- add(findings, "D-13", "critical", `mainnet step ${b.step} env.replaceExistName is '${b.env.replaceExistName ?? "(missing)"}', expected false (or set forceClaim=true)`, `§4.2 step ${b.step}`, "Set env.replaceExistName = false on all §4.2 JSON blocks (mainnet must not overwrite).");
434
- }
435
- }
436
- catch (err) {
437
- add(findings, "D-04", "warning", `analyzeNetworkConsistency failed: ${err.message}`);
438
- }
439
- return findings;
440
- }
441
- const NAME_REGEX = /^[a-z][a-z0-9_]{2,63}$/;
442
- export function analyzeNamingConvention(input) {
443
- const findings = [];
444
- try {
445
- const doc = normalizeInput(input);
446
- if (!doc)
447
- return [];
448
- const prefix = doc.project_name;
449
- const versionSuffix = `_${doc.version}`;
450
- for (const obj of doc.objects) {
451
- if (obj.reused_from)
452
- continue;
453
- if (!NAME_REGEX.test(obj.name)) {
454
- add(findings, "NAMING-01", "warning", `Object '${obj.entry_id}' name '${obj.name}' does not match ${NAME_REGEX}`, `§1.1 (${obj.entry_id})`, `Rename to match ^[a-z][a-z0-9_]{2,63}$ and start with project prefix '${prefix}'.`);
455
- }
456
- else if (prefix && !obj.name.startsWith(`${prefix}_`)) {
457
- add(findings, "NAMING-01", "warning", `Object '${obj.entry_id}' name '${obj.name}' does not start with project prefix '${prefix}_'`, `§1.1 (${obj.entry_id})`, `Rename to start with '${prefix}_'.`);
458
- }
459
- if (versionSuffix && !obj.name.endsWith(versionSuffix)) {
460
- add(findings, "NAMING-02", "warning", `Object '${obj.entry_id}' name '${obj.name}' is missing version suffix '${versionSuffix}'`, `§1.1 (${obj.entry_id})`, `Append '${versionSuffix}' to the name.`);
461
- }
462
- }
463
- }
464
- catch (err) {
465
- add(findings, "NAMING-01", "warning", `analyzeNamingConvention failed: ${err.message}`);
466
- }
467
- return findings;
468
- }
469
- export function analyzePermissionIndexRange(input) {
470
- const findings = [];
471
- try {
472
- const doc = normalizeInput(input);
473
- if (!doc)
474
- return [];
475
- const allBlocks = [...doc.testnet_blocks, ...doc.mainnet_blocks];
476
- for (const block of allBlocks) {
477
- for (const idx of walkPermissionIndices(block.data)) {
478
- if (idx < USER_DEFINED_PERM_INDEX_START)
479
- add(findings, "D-07", "critical", `permissionIndex ${idx} < ${USER_DEFINED_PERM_INDEX_START} (USER_DEFINED_PERM_INDEX_START) in step ${block.step} (${block.operation_type})`, `${block.env.network ?? "?"} step ${block.step}`, `Use a permissionIndex >= ${USER_DEFINED_PERM_INDEX_START}.`);
480
- }
481
- }
482
- for (const block of allBlocks) {
483
- if (block.operation_type !== "machine")
484
- continue;
485
- const count = countMachineNodes(block);
486
- if (count > MAX_NODE_COUNT)
487
- add(findings, "D-09", "critical", `Machine in step ${block.step} has ${count} nodes > MAX_NODE_COUNT (${MAX_NODE_COUNT})`, `${block.env.network ?? "?"} step ${block.step}`, `Reduce node count to <= ${MAX_NODE_COUNT} or split into multiple Machines.`);
488
- }
489
- }
490
- catch (err) {
491
- add(findings, "D-07", "warning", `analyzePermissionIndexRange failed: ${err.message}`);
492
- }
493
- return findings;
494
- }
495
- const REQUIRED_SCENARIO_KEYWORDS = ["normal_order", "refund", "dispute", "machine_publish", "service_publish"];
496
- export function analyzeScenarioCoverage(input) {
497
- const findings = [];
498
- try {
499
- const doc = normalizeInput(input);
500
- if (!doc)
501
- return [];
502
- const coveredKeywords = new Set();
503
- for (const s of doc.scenarios) {
504
- const text = `${s.scenario_id} ${s.description}`.toLowerCase();
505
- for (const kw of REQUIRED_SCENARIO_KEYWORDS) {
506
- if (text.includes(kw.toLowerCase()))
507
- coveredKeywords.add(kw);
508
- }
509
- }
510
- if (coveredKeywords.size < 3) {
511
- const missing = REQUIRED_SCENARIO_KEYWORDS.filter((k) => !coveredKeywords.has(k));
512
- add(findings, "D-03", "warning", `Scenario matrix covers ${coveredKeywords.size}/${REQUIRED_SCENARIO_KEYWORDS.length} required keywords; missing: ${missing.join(", ")}`, "§1.3 Scenario Matrix", "Add scenarios covering the missing keywords (normal_order, refund, dispute, machine_publish, service_publish).");
513
- }
514
- const definedIds = new Set(doc.objects.map((o) => o.entry_id));
515
- for (const s of doc.scenarios) {
516
- const refs = [s.primary_object, ...s.supporting_objects];
517
- for (const ref of refs) {
518
- if (ref.endsWith(":*"))
519
- continue;
520
- if (!definedIds.has(ref))
521
- add(findings, "D-03", "warning", `Scenario '${s.scenario_id}' references undefined object '${ref}'`, `§1.3 (${s.scenario_id})`, `Add '${ref}' to §1.1 or fix the scenario reference.`);
522
- }
523
- }
524
- }
525
- catch (err) {
526
- add(findings, "D-03", "warning", `analyzeScenarioCoverage failed: ${err.message}`);
527
- }
528
- return findings;
529
- }
530
- const TESTNET_VERIFICATION_ITEMS = ["V-T-01", "V-T-02", "V-T-03", "V-T-04", "V-T-05", "V-T-06", "V-T-07", "V-T-08", "V-T-09", "V-T-10", "V-T-11"];
531
- const MAINNET_VERIFICATION_ITEMS = ["V-M-01", "V-M-02", "V-M-03", "V-M-04", "V-M-05"];
532
- const COMPLETENESS_CHECK_IDS = Array.from({ length: 20 }, (_, i) => `D-${String(i + 1).padStart(2, "0")}`);
533
- export function analyzeVerificationChecklist(input) {
534
- const findings = [];
535
- try {
536
- const doc = normalizeInput(input);
537
- if (!doc)
538
- return [];
539
- for (const id of TESTNET_VERIFICATION_ITEMS) {
540
- if (!doc.testnet_verification.has(id))
541
- add(findings, "D-14", "warning", `testnet verification item '${id}' is missing from §3.3`, "§3.3 testnet Verification Checklist", `Add row '${id}' to §3.3.`);
542
- }
543
- for (const id of MAINNET_VERIFICATION_ITEMS) {
544
- if (!doc.mainnet_verification.has(id))
545
- add(findings, "D-15", "warning", `mainnet verification item '${id}' is missing from §4.3`, "§4.3 mainnet Verification Checklist", `Add row '${id}' to §4.3.`);
546
- }
547
- for (const id of COMPLETENESS_CHECK_IDS) {
548
- if (!doc.completeness_checklist.has(id))
549
- add(findings, "D-18", "warning", `completeness checklist item '${id}' is missing from §6`, "§6 Completeness Checklist", `Add row '${id}' to §6.`);
550
- }
551
- }
552
- catch (err) {
553
- add(findings, "D-14", "warning", `analyzeVerificationChecklist failed: ${err.message}`);
554
- }
555
- return findings;
556
- }
557
- export function analyzeDeployableReadiness(input) {
558
- const findings = [];
559
- try {
560
- const riskResult = resolveRiskResult(input);
561
- if (!riskResult) {
562
- add(findings, "D-16", "info", "Risk aggregation result not available; D-16/D-17 skipped (provide project_graph with puzzles, or set deployment_doc.risk_status).", undefined, "Run C2 risk-aggregator first, or provide deployment_doc.risk_status.");
563
- return findings;
564
- }
565
- const criticalCount = riskResult.severity_summary.CRITICAL ?? 0;
566
- if (criticalCount > 0) {
567
- const ruleIds = riskResult.findings.filter((f) => f.severity === "CRITICAL").map((f) => f.risk_rule_id).join(", ");
568
- add(findings, "D-16", "critical", `${criticalCount} CRITICAL risk(s) remain: ${ruleIds}`, "C2 risk-aggregator output", "Return to stage 2 (business puzzle) and fix all CRITICAL risks before deploying.");
569
- }
570
- const confirmedHighs = new Set(input.user_confirmed_high_risks ?? []);
571
- const unconfirmedHighs = riskResult.findings.filter((f) => f.severity === "HIGH" && !confirmedHighs.has(f.risk_rule_id));
572
- if (unconfirmedHighs.length > 0) {
573
- const ruleIds = unconfirmedHighs.map((f) => f.risk_rule_id).join(", ");
574
- add(findings, "D-17", "critical", `${unconfirmedHighs.length} unconfirmed HIGH risk(s): ${ruleIds}`, "C2 risk-aggregator output", "User must confirm each HIGH risk (ACCEPT_AND_PROCEED) or fix them.");
575
- }
576
- }
577
- catch (err) {
578
- add(findings, "D-16", "warning", `analyzeDeployableReadiness failed: ${err.message}`);
579
- }
580
- return findings;
581
- }
582
- function resolveRiskResult(input) {
583
- const pg = input.project_graph;
584
- if (pg && typeof pg === "object") {
585
- const obj = pg;
586
- if (typeof obj.severity_summary === "object" && Array.isArray(obj.findings)) {
587
- return pg;
588
- }
589
- if (typeof obj.project_prefix === "string" && typeof obj.puzzles === "object") {
590
- try {
591
- return aggregateProjectRisks(pg);
592
- }
593
- catch { }
594
- }
595
- }
596
- const dd = input.deployment_doc;
597
- if (dd && dd.risk_status) {
598
- const critical = dd.risk_critical_count ?? 0;
599
- const high = dd.risk_high_count ?? 0;
600
- const findings = [];
601
- for (let i = 0; i < critical; i++)
602
- findings.push({
603
- risk_rule_id: `R-CRITICAL-${i}`, object_type: "service", entry_id: "*",
604
- severity: "CRITICAL",
605
- message: "(synthesized from deployment_doc.risk_critical_count)",
606
- fix_suggestion: "See C2 risk-aggregator report for details.",
607
- });
608
- for (let i = 0; i < high; i++)
609
- findings.push({
610
- risk_rule_id: `R-HIGH-${i}`, object_type: "service", entry_id: "*",
611
- severity: "HIGH",
612
- message: "(synthesized from deployment_doc.risk_high_count)",
613
- fix_suggestion: "See C2 risk-aggregator report for details.",
614
- });
615
- return {
616
- namespace: { prefix: dd.project_prefix, version: dd.version, industry: dd.industry },
617
- findings,
618
- severity_summary: { CRITICAL: critical, HIGH: high, MEDIUM: 0, LOW: 0, INFO: 0 },
619
- status: dd.risk_status,
620
- calibrated_at: Date.now(),
621
- warnings: [],
622
- };
623
- }
624
- return undefined;
625
- }
626
- function extractMachinePairs(block) {
627
- const data = block.data;
628
- if (!data)
629
- return [];
630
- const node = data.node;
631
- if (!node || typeof node !== "object")
632
- return [];
633
- const nodes = node.nodes;
634
- if (!Array.isArray(nodes))
635
- return [];
636
- return nodes.filter((n) => {
637
- if (!n || typeof n !== "object")
638
- return false;
639
- const pairs = n.pairs;
640
- return Array.isArray(pairs);
641
- }).flatMap((n) => n.pairs ?? []);
642
- }
643
- export function analyzeMachineAndServiceReadiness(input) {
644
- const findings = [];
645
- try {
646
- const doc = normalizeInput(input);
647
- if (!doc)
648
- return [];
649
- const allBlocks = [...doc.testnet_blocks, ...doc.mainnet_blocks];
650
- for (const block of allBlocks) {
651
- if (block.operation_type !== "machine")
652
- continue;
653
- const pairs = extractMachinePairs(block);
654
- if (pairs.length === 0)
655
- continue;
656
- const entryPairs = pairs.filter((p) => p.prev_node === "");
657
- for (const pair of entryPairs) {
658
- const forwardsLen = Array.isArray(pair.forwards) ? pair.forwards.length : 0;
659
- if (forwardsLen === 0) {
660
- add(findings, "D-19", "critical", `Machine in step ${block.step} (${block.env.network ?? "?"}) has an entry node (prev_node="") with no forwards. ` +
661
- `Progress created from this Machine will be permanently stuck at current="" (P0-2 root cause).`, `${block.env.network ?? "?"} step ${block.step}`, `Add at least one forward to the entry node's pairs. Example: pairs: [{prev_node: "", forwards: [{next_node: "Ordered", ...}]}]`);
662
- }
663
- }
664
- }
665
- const serviceBlocks = allBlocks.filter((b) => b.operation_type === "service");
666
- if (serviceBlocks.length > 0) {
667
- const blocksWithFundAdd = serviceBlocks.filter((b) => {
668
- const data = b.data;
669
- return data?.compensation_fund_add != null;
670
- });
671
- if (blocksWithFundAdd.length === 0) {
672
- add(findings, "D-20", "warning", `No Service block in the deployment doc includes a compensation_fund_add step. ` +
673
- `Without deposit, arbitration rulings that award refunds to buyers cannot be paid out from the Service. ` +
674
- `Industries like freelance may not require this (info), but rental/travel/education typically do.`, "§3.2 / §4.2 Service blocks", `Add a compensation_fund_add step for the Service (e.g., data.compensation_fund_add = {balance: <amount>}). ` +
675
- `Recommended: 3-10× the max single-order amount, depending on industry (subscription: 3×, retail: 5×, rental: 10×). See P1-1 evaluation rule.`);
676
- }
677
- }
678
- }
679
- catch (err) {
680
- add(findings, "D-19", "warning", `analyzeMachineAndServiceReadiness failed: ${err.message}`);
681
- }
682
- return findings;
683
- }
684
- export function scanDeployment(input) {
685
- const allFindings = [
686
- ...analyzeObjectDependencyCompleteness(input),
687
- ...analyzeSubstepCoherence(input),
688
- ...analyzeNetworkConsistency(input),
689
- ...analyzeNamingConvention(input),
690
- ...analyzePermissionIndexRange(input),
691
- ...analyzeScenarioCoverage(input),
692
- ...analyzeVerificationChecklist(input),
693
- ...analyzeDeployableReadiness(input),
694
- ...analyzeMachineAndServiceReadiness(input),
695
- ];
696
- return {
697
- project_name: input.project_name,
698
- document_path: input.document_path,
699
- overall_readiness: computeReadiness(allFindings),
700
- findings: allFindings,
701
- coverage: computeCoverage(input),
702
- checks: computeChecks(allFindings),
703
- scanned_at: Date.now(),
704
- scanner_version: DEPLOYMENT_SCANNER_VERSION,
705
- };
706
- }
707
- function computeChecks(findings) {
708
- const has = (id) => findings.some((f) => f.check_id === id);
709
- return {
710
- D01_object_defined: has("D-01") ? "fail" : "pass",
711
- D02_dependency_complete: has("D-02") ? "fail" : "pass",
712
- D03_scenario_covered: has("D-03") ? "fail" : "pass",
713
- D04_testnet_topo_order: has("D-04") ? "fail" : "pass",
714
- D05_testnet_network: has("D-05") ? "fail" : "pass",
715
- D06_testnet_replace: has("D-06") ? "fail" : "pass",
716
- D07_permission_index: has("D-07") ? "fail" : "pass",
717
- D08_guard_gen_passport: has("D-08") ? "fail" : "pass",
718
- D09_machine_node_count: has("D-09") ? "fail" : "pass",
719
- D10_substep_coherence: has("D-10") ? "fail" : "pass",
720
- D11_mainnet_testnet_match: has("D-11") ? "fail" : "pass",
721
- D12_mainnet_network: has("D-12") ? "fail" : "pass",
722
- D13_mainnet_replace: has("D-13") ? "fail" : "pass",
723
- D14_testnet_verification: has("D-14") ? "fail" : "pass",
724
- D15_mainnet_verification: has("D-15") ? "fail" : "pass",
725
- D16_no_critical_risk: has("D-16") ? "fail" : "pass",
726
- D17_no_high_risk: has("D-17") ? "fail" : "pass",
727
- D18_completeness_checklist: has("D-18") ? "fail" : "pass",
728
- D19_machine_entry_forward: has("D-19") ? "fail" : "pass",
729
- D20_service_compensation_fund: has("D-20") ? "fail" : "pass",
730
- };
731
- }
732
- function computeCoverage(input) {
733
- const doc = normalizeInput(input);
734
- if (!doc) {
735
- return { objects_defined: 0, objects_with_scenario: 0, testnet_steps: 0, mainnet_steps: 0, verification_items: 0 };
736
- }
737
- const scenarioObjectIds = new Set();
738
- for (const s of doc.scenarios) {
739
- scenarioObjectIds.add(s.primary_object);
740
- for (const o of s.supporting_objects)
741
- scenarioObjectIds.add(o);
742
- }
743
- const objects_with_scenario = doc.objects.filter((o) => scenarioObjectIds.has(o.entry_id) || scenarioObjectIds.has(`${o.object_type}:*`)).length;
744
- return {
745
- objects_defined: doc.objects.length,
746
- objects_with_scenario,
747
- testnet_steps: doc.testnet_blocks.length,
748
- mainnet_steps: doc.mainnet_blocks.length,
749
- verification_items: doc.testnet_verification.size + doc.mainnet_verification.size,
750
- };
751
- }
752
- function computeReadiness(findings) {
753
- const dFindings = findings.filter((f) => f.check_id.startsWith("D-"));
754
- if (dFindings.some((f) => f.severity === "critical"))
755
- return "blocked";
756
- if (dFindings.some((f) => f.severity === "warning"))
757
- return "warnings";
758
- return "ready";
759
- }
760
- function normalizeInput(input) {
761
- if (input.deployment_doc)
762
- return fromDeploymentDocInput(input.deployment_doc);
763
- if (input.document_path) {
764
- if (!fs.existsSync(input.document_path))
765
- return undefined;
766
- return parseDeploymentMarkdown(input.document_path);
767
- }
768
- return undefined;
769
- }
770
- export function isReady(scan) {
771
- return scan.overall_readiness === "ready";
772
- }
773
- export function isBlocked(scan) {
774
- return scan.overall_readiness === "blocked";
775
- }
776
- export function summarizeScan(scan) {
777
- const L = [];
778
- L.push(`# Deployment Scan Report — ${scan.project_name}`, "");
779
- L.push(`- **Overall readiness**: ${scan.overall_readiness}`);
780
- L.push(`- **Scanned at**: ${new Date(scan.scanned_at).toISOString()}`);
781
- L.push(`- **Scanner version**: ${scan.scanner_version}`);
782
- if (scan.document_path)
783
- L.push(`- **Document**: ${scan.document_path}`);
784
- L.push("", "## Coverage", "", "| Metric | Count |", "|--------|-------|");
785
- L.push(`| Objects defined | ${scan.coverage.objects_defined} |`);
786
- L.push(`| Objects with scenario | ${scan.coverage.objects_with_scenario} |`);
787
- L.push(`| testnet steps | ${scan.coverage.testnet_steps} |`);
788
- L.push(`| mainnet steps | ${scan.coverage.mainnet_steps} |`);
789
- L.push(`| verification items | ${scan.coverage.verification_items} |`, "");
790
- L.push("## Checks (D-01 ~ D-20)", "", "| Check ID | Status |", "|----------|--------|");
791
- const entries = Object.entries(scan.checks);
792
- for (const [id, status] of entries)
793
- L.push(`| ${id} | ${status === "pass" ? "✅ pass" : "❌ fail"} |`);
794
- L.push("", `## Findings (${scan.findings.length})`, "");
795
- if (scan.findings.length === 0) {
796
- L.push("✅ No issues detected.", "");
797
- }
798
- else {
799
- const bySeverity = new Map();
800
- for (const f of scan.findings) {
801
- const list = bySeverity.get(f.severity) ?? [];
802
- list.push(f);
803
- bySeverity.set(f.severity, list);
804
- }
805
- for (const sev of ["critical", "warning", "info"]) {
806
- const list = bySeverity.get(sev);
807
- if (!list || list.length === 0)
808
- continue;
809
- L.push(`### ${sev.toUpperCase()} (${list.length})`, "");
810
- for (const f of list) {
811
- L.push(`- **[${f.check_id}]** ${f.message}`);
812
- if (f.location)
813
- L.push(` - Location: ${f.location}`);
814
- if (f.suggestion)
815
- L.push(` - Suggestion: ${f.suggestion}`);
816
- L.push("");
817
- }
818
- }
819
- }
820
- L.push("---", "", "*End of report.*");
821
- return L.join("\n");
822
- }
823
- export const DEPLOYMENT_SCANNER_VERSION = "2.0.0";
1
+ import*as a82a from'fs';import{MAX_NODE_COUNT,USER_DEFINED_PERM_INDEX_START}from'./onchain-constants.js';import{traceSubsteps}from'../project/substep-trace.js';import{aggregateProjectRisks}from'../project/risk-aggregator.js';function add(a,b,c,d,e,f){a['push']({'check_id':b,'severity':c,'message':d,'location':e,'suggestion':f});}function fromDeploymentDocInput(a){const b=a['version']??'v1',c=a['project_prefix']+'_'+b,d=a['steps']['map'](k=>k['entry_id']),e=[],f=[];for(const k of a['steps']){const l=k['network_phase'];if(l==='both'||l==='testnet')e['push'](synthesizeBlock(k,a,'testnet'));if(l==='both'||l==='mainnet')f['push'](synthesizeBlock(k,a,'mainnet'));}const g=new Map();for(let m=0x1;m<=0xb;m++)g['set']('V-T-'+String(m)['padStart'](0x2,'0'),![]);const h=new Map();for(let n=0x1;n<=0x5;n++)h['set']('V-M-'+String(n)['padStart'](0x2,'0'),![]);const j=new Map();for(let o=0x1;o<=0x14;o++)j['set']('D-'+String(o)['padStart'](0x2,'0'),![]);return{'project_name':a['project_prefix'],'version':b,'namespace_tag':c,'objects':a['objects']??[],'edges':a['edges']??[],'steps':a['steps']??[],'scenarios':a['scenarios']??[],'testnet_blocks':e,'mainnet_blocks':f,'testnet_verification':g,'mainnet_verification':h,'completeness_checklist':j,'topological_order':d};}function synthesizeBlock(a,b,c){const d=b['objects']['find'](h=>h['entry_id']===a['entry_id']),e=d?.['name']??a['object_type']+'_'+a['step'],f=c==='testnet',g=c==='testnet'?'T':'M';return{'step':a['step'],'operation_type':a['object_type'],'data':{'object':{'name':e,'replaceExistName':f},'description':a['operation']+'\x20'+a['object_type']+'\x20(step\x20'+a['step']+')'},'env':{'account':b['project_prefix']+'_merchant_'+c,'network':c,'replaceExistName':f,'confirmed':!![]},'substeps':[{'id':''+g+a['step']+'.1','name':a['operation']+'\x20'+a['object_type'],'inputs':[],'outputs':[''+g+a['step']+'.output']}]};}function parseDeploymentMarkdown(a){const c=a82a['readFileSync'](a,'utf-8'),d=c['split']('\x0a'),e=parseTable(d,'Object\x20List',t=>({'entry_id':t['entry_id']??'','object_type':t['object_type'],'name':t['name']??'','reused_from':t['reused_from']||undefined,'publish_required':t['publish_required']==='true','description':t['description']||undefined}))['filter'](t=>t['entry_id']&&t['name']),f=parseTable(d,'Dependency\x20Edges',t=>({'from':t['from']??'','to':t['to']??'','edge_kind':t['edge_kind']??'','field_path':t['field_path']??'','required_at_publish':t['required_at_publish']==='true'}))['filter'](t=>t['from']&&t['to']),g=parseTable(d,'Scenario\x20Matrix',t=>({'scenario_id':t['scenario_id']??'','description':t['description']??'','primary_object':t['primary_object']??'','supporting_objects':(t['supporting_objects']??'')['split'](',')['map'](u=>u['trim']())['filter'](Boolean),'test_step_refs':t['test_step_refs']?t['test_step_refs']['split'](',')['map'](u=>u['trim']())['filter'](Boolean):undefined}))['filter'](t=>t['scenario_id']),h=parseTable(d,'Topological\x20Execution\x20Plan',t=>{const u=t['network_phase']==='testnet'||t['network_phase']==='mainnet'||t['network_phase']==='both'?t['network_phase']:'both';return{'step':parseInt(t['step']??'0',0xa)||0x0,'object_type':t['object_type'],'operation':t['operation']??'','substep_count':parseInt(t['substep_count']??'0',0xa)||0x0,'depends_on':(t['depends_on']??'')['replace'](/[\[\]]/g,'')['split'](',')['map'](v=>v['trim']())['filter'](Boolean)['map'](v=>parseInt(v,0xa)||0x0),'entry_id':t['entry_id']??'','network_phase':u};})['filter'](t=>t['step']>0x0),i=extractJsonBlocks(d),j=[],k=[];for(const t of i){if(t['env']?.['network']==='mainnet')k['push'](t);else j['push'](t);}const l=parseStatusMap(d,'V-T-'),m=parseStatusMap(d,'V-M-'),n=parseStatusMap(d,'D-','Completeness\x20Checklist'),o=parseMetaTable(d),p=o['get']('project_name')??deriveProjectFromPath(a),q=o['get']('version')??'v1',r=o['get']('namespace\x20tag')??o['get']('namespace_tag')??p+'_'+q,s=h['map'](u=>u['entry_id']);return{'project_name':p,'version':q,'namespace_tag':r,'objects':e,'edges':f,'steps':h,'scenarios':g,'testnet_blocks':j,'mainnet_blocks':k,'testnet_verification':l,'mainnet_verification':m,'completeness_checklist':n,'topological_order':s};}function parseTable(a,b,c){return parseMarkdownTable(a,b)['map'](c);}function parseMarkdownTable(a,b){const c=[];for(let d=0x0;d<a['length'];d++){if(!a[d]['includes'](b))continue;let e=-0x1;for(let j=d;j<Math['min'](d+0xa,a['length']);j++){if(a[j]['trim']()['startsWith']('|')&&a[j]['includes']('|')){e=j;break;}}if(e===-0x1)break;const f=splitTableRow(a[e]);let g=e+0x1;if(g<a['length']&&/^\s*\|[\s-:|]+\|\s*$/['test'](a[g]))g++;while(g<a['length']&&a[g]['trim']()['startsWith']('|')){const l=splitTableRow(a[g]);if(l['length']===0x0)break;const m={};for(let n=0x0;n<f['length'];n++)m[f[n]['trim']()]=(l[n]??'')['trim']();c['push'](m),g++;}break;}return c;}function splitTableRow(a){const b=a['trim']();if(!b['startsWith']('|'))return[];return b['slice'](0x1,b['endsWith']('|')?-0x1:undefined)['split']('|');}function parseStatusMap(a,b,c){const d=new Map(),e=c?parseMarkdownTable(a,c):parseMarkdownTable(a,'Verification\x20Checklist');for(const f of e){const g=f['verification_id']??f['check_id']??'';if(!g['startsWith'](b))continue;const h=(f['status']??'')['trim']();d['set'](g,h['includes']('✅')||h['toLowerCase']()['includes']('pass'));}return d;}function parseMetaTable(a){const b=new Map();for(const c of parseMarkdownTable(a,'Project\x20Metadata')){const d=c['field']??'',e=c['value']??'';if(d)b['set'](d['trim'](),e['trim']());}return b;}function extractJsonBlocks(a){const b=[];let c=0x0;while(c<a['length']){if(a[c]['trim']()['startsWith']('```json')){const d=[];let e=c+0x1;while(e<a['length']&&!a[e]['trim']()['startsWith']('```')){d['push'](a[e]),e++;}try{const f=JSON['parse'](d['join']('\x0a'));if(f&&typeof f==='object'&&'operation_type'in f){const g=f['env']??{},h=f['data']??{},k=f['substeps'],l=Array['isArray'](k)?k['map'](normalizeSubstep):undefined;b['push']({'step':typeof f['step']==='number'?f['step']:0x0,'operation_type':String(f['operation_type']??''),'data':h,'env':{'network':typeof g['network']==='string'?g['network']:undefined,'replaceExistName':typeof g['replaceExistName']==='boolean'?g['replaceExistName']:undefined,'forceClaim':typeof g['forceClaim']==='boolean'?g['forceClaim']:undefined,'confirmed':typeof g['confirmed']==='boolean'?g['confirmed']:undefined,...g},'substeps':l});}}catch{}c=e+0x1;}else c++;}return b;}function normalizeSubstep(a){if(!a||typeof a!=='object')return{'id':'','inputs':[],'outputs':[]};const b=a;return{'id':String(b['id']??''),'name':typeof b['name']==='string'?b['name']:undefined,'inputs':Array['isArray'](b['inputs'])?b['inputs']['map'](String):[],'outputs':Array['isArray'](b['outputs'])?b['outputs']['map'](String):[]};}function deriveProjectFromPath(a){const b=a['split'](/[\\/]/)['pop']()??'project';return b['replace'](/_v\d+_deployment\.md$/i,'')['replace'](/\.md$/i,'');}function*walkPermissionIndices(a){if(a===null||a===undefined||typeof a!=='object')return;if(Array['isArray'](a)){for(const c of a)yield*walkPermissionIndices(c);return;}const b=a;if(typeof b['permissionIndex']==='number')yield b['permissionIndex'];if(typeof b['permission_index']==='number')yield b['permission_index'];if(typeof b['index']==='number'&&b['__isPermission']===!![])yield b['index'];for(const d of Object['values'](b))yield*walkPermissionIndices(d);}function countMachineNodes(a){const b=a['data']?.['node'],c=b?.['nodes'];return Array['isArray'](c)?c['length']:0x0;}function deriveEntryIdFromBlock(a,b){const c=a['data']['object'];let d;if(typeof c==='string')d=c;else{if(c&&typeof c==='object'){const e=c;if(typeof e['name']==='string')d=e['name'];}}if(!d)return undefined;return b['objects']['find'](f=>f['name']===d)?.['entry_id'];}export function analyzeObjectDependencyCompleteness(a){const b=[];try{const c=normalizeInput(a);if(!c)return add(b,'D-01','critical','No\x20deployment\x20document\x20provided\x20(need\x20document_path\x20or\x20deployment_doc)'),b;const d=new Set(c['objects']['map'](h=>h['entry_id'])),f=new Set();for(const h of c['edges']){f['add'](h['from']),f['add'](h['to']);}for(const i of f){if(i['endsWith'](':*'))continue;!d['has'](i)&&add(b,'D-01','critical','Object\x20\x27'+i+'\x27\x20is\x20referenced\x20in\x20§1.2\x20but\x20not\x20defined\x20in\x20§1.1','§1.2\x20Dependency\x20Edges','Add\x20\x27'+i+'\x27\x20to\x20§1.1\x20Object\x20List\x20or\x20remove\x20the\x20reference.');}for(const j of c['edges']){const k=d['has'](j['from'])||j['from']['endsWith'](':*'),l=d['has'](j['to'])||j['to']['endsWith'](':*');(!k||!l)&&add(b,'D-02','critical','Dangling\x20dependency:\x20'+j['from']+'\x20→\x20'+j['to']+'\x20(edge_kind=\x27'+j['edge_kind']+'\x27)','§1.2\x20Dependency\x20Edges','Create\x20the\x20missing\x20object\x20or\x20remove\x20the\x20edge.');}for(const m of c['objects']['filter'](n=>n['object_type']==='guard')){const n=c['testnet_blocks']['some'](p=>p['operation_type']==='guard'&&p['data']['object']?.['name']===m['name']),o=c['testnet_blocks']['some'](p=>p['operation_type']==='passport'||p['data']['gen_passport']===!![]||p['data']['object']===m['name']);if(!n)add(b,'D-08','critical','Guard\x20\x27'+m['entry_id']+'\x27\x20has\x20no\x20create\x20step\x20in\x20§3.2','§3.2\x20(guard:\x20'+m['name']+')','Add\x20a\x20guard\x20creation\x20JSON\x20block\x20for\x20\x27'+m['name']+'\x27.');if(!o)add(b,'D-08','critical','Guard\x20\x27'+m['entry_id']+'\x27\x20has\x20no\x20gen_passport\x20step\x20in\x20§3.2','§3.2\x20(guard:\x20'+m['name']+')','Add\x20a\x20passport/gen_passport\x20JSON\x20block\x20after\x20the\x20guard\x20creation\x20step.');}}catch(p){add(b,'D-01','warning','analyzeObjectDependencyCompleteness\x20failed:\x20'+p['message']);}return b;}export function analyzeSubstepCoherence(a){const b=[];try{const c=normalizeInput(a);if(!c)return[];for(const d of['testnet','mainnet']){const e=collectSubsteps(d==='testnet'?c['testnet_blocks']:c['mainnet_blocks'],d),f=traceSubsteps({'project_prefix':c['project_name'],'version':c['version'],'network':d,'substeps':e});emitCoherenceFindings(f,d,b);}}catch(g){add(b,'D-10','warning','analyzeSubstepCoherence\x20failed:\x20'+g['message']);}return b;}function collectSubsteps(a,b){const c=[],d=b==='testnet'?'T':'M';for(const e of a){if(!e['substeps'])continue;const f=''+d+e['step'];for(const g of e['substeps']){if(!g['id'])continue;c['push']({'step_id':g['id'],'parent_step':f,'object_type':e['operation_type'],'entry_id':'','operation_type':e['operation_type'],'network':b,'input':{'data':e['data'],'input_refs':g['inputs']},'timestamp':0x0,'status':'PENDING','dependencies':{'input_refs':g['inputs'],'output_refs':g['outputs']['map'](h=>({'substep_id':g['id'],'field_path':h}))}});}}return c;}function emitCoherenceFindings(a,e,f){for(const g of a['dangling_inputs']){add(f,'D-10','critical','['+e+']\x20Dangling\x20input:\x20substep\x20\x27'+g['substep_id']+'\x27\x20references\x20missing\x20\x27'+g['missing_ref']+'\x27',e+'\x20§substeps','Ensure\x20\x27'+g['missing_ref']+'\x27\x20is\x20produced\x20by\x20an\x20earlier\x20substep.');}for(const h of a['circular_refs']){add(f,'D-10','critical','['+e+']\x20Circular\x20reference:\x20'+h['cycle']['join']('\x20→\x20'),e+'\x20§substeps','Break\x20the\x20cycle\x20by\x20removing\x20one\x20dependency.');}for(const i of a['missing_outputs']){add(f,'D-10','warning','['+e+']\x20Missing\x20output:\x20substep\x20\x27'+i['substep_id']+'\x27\x20did\x20not\x20produce\x20\x27'+i['expected_field']+'\x27',e+'\x20§substeps','Ensure\x20\x27'+i['substep_id']+'\x27\x20produces\x20\x27'+i['expected_field']+'\x27.');}for(const j of a['cross_step_breaks']){add(f,'D-10','critical','['+e+']\x20Cross-step\x20break:\x20failed\x20step\x20\x27'+j['source_step']+'\x27\x20blocks\x20\x27'+j['target_step']+'\x27',e+'\x20§substeps','Fix\x20step\x20\x27'+j['source_step']+'\x27\x20or\x20adjust\x20the\x20dependency.');}}export function analyzeNetworkConsistency(a){const c=[];try{const d=normalizeInput(a);if(!d)return[];const e=d['testnet_blocks'],f=d['mainnet_blocks'],g=d['topological_order'];if(g['length']>0x0&&e['length']>0x0)for(let h=0x0;h<e['length'];h++){const j=g[h];if(!j)break;const k=deriveEntryIdFromBlock(e[h],d);if(k&&k!==j){add(c,'D-04','critical','testnet\x20step\x20'+e[h]['step']+'\x20order\x20mismatch:\x20expected\x20\x27'+j+'\x27,\x20got\x20\x27'+k+'\x27','§3.2\x20testnet\x20JSON\x20Operation\x20Sequence','Reorder\x20testnet\x20JSON\x20blocks\x20to\x20match\x20§2\x20topological\x20order.');break;}}for(const l of e){if(l['env']['network']!=='testnet')add(c,'D-05','critical','testnet\x20step\x20'+l['step']+'\x20env.network\x20is\x20\x27'+(l['env']['network']??'(missing)')+'\x27,\x20expected\x20\x27testnet\x27','§3.2\x20step\x20'+l['step'],'Set\x20env.network\x20=\x20\x27testnet\x27\x20on\x20all\x20§3.2\x20JSON\x20blocks.');}for(const n of e){if(n['env']['replaceExistName']!==!![])add(c,'D-06','critical','testnet\x20step\x20'+n['step']+'\x20env.replaceExistName\x20is\x20\x27'+(n['env']['replaceExistName']??'(missing)')+'\x27,\x20expected\x20true','§3.2\x20step\x20'+n['step'],'Set\x20env.replaceExistName\x20=\x20true\x20on\x20all\x20§3.2\x20JSON\x20blocks\x20(testnet\x20allows\x20overwrite).');}if(e['length']!==f['length'])add(c,'D-11','critical','mainnet\x20step\x20count\x20('+f['length']+')\x20!=\x20testnet\x20step\x20count\x20('+e['length']+')','§3.2\x20vs\x20§4.2','Ensure\x20mainnet\x20JSON\x20blocks\x20correspond\x201:1\x20with\x20testnet\x20blocks.');else for(let o=0x0;o<f['length'];o++){const p=e[o],q=f[o];if(p['step']!==q['step'])add(c,'D-11','critical','mainnet\x20step\x20'+q['step']+'\x20does\x20not\x20match\x20testnet\x20step\x20'+p['step'],'§4.2\x20step\x20'+q['step'],'Ensure\x20mainnet\x20step\x20numbers\x20match\x20testnet.');if(p['operation_type']!==q['operation_type'])add(c,'D-11','critical','step\x20'+q['step']+'\x20operation_type\x20mismatch:\x20testnet=\x27'+p['operation_type']+'\x27,\x20mainnet=\x27'+q['operation_type']+'\x27','§4.2\x20step\x20'+q['step'],'Align\x20mainnet\x20operation_type\x20with\x20testnet.');}for(const r of f){if(r['env']['network']!=='mainnet')add(c,'D-12','critical','mainnet\x20step\x20'+r['step']+'\x20env.network\x20is\x20\x27'+(r['env']['network']??'(missing)')+'\x27,\x20expected\x20\x27mainnet\x27','§4.2\x20step\x20'+r['step'],'Set\x20env.network\x20=\x20\x27mainnet\x27\x20on\x20all\x20§4.2\x20JSON\x20blocks.');}for(const s of f){if(s['env']['replaceExistName']!==![]&&!s['env']['forceClaim'])add(c,'D-13','critical','mainnet\x20step\x20'+s['step']+'\x20env.replaceExistName\x20is\x20\x27'+(s['env']['replaceExistName']??'(missing)')+'\x27,\x20expected\x20false\x20(or\x20set\x20forceClaim=true)','§4.2\x20step\x20'+s['step'],'Set\x20env.replaceExistName\x20=\x20false\x20on\x20all\x20§4.2\x20JSON\x20blocks\x20(mainnet\x20must\x20not\x20overwrite).');}}catch(u){add(c,'D-04','warning','analyzeNetworkConsistency\x20failed:\x20'+u['message']);}return c;}const NAME_REGEX=/^[a-z][a-z0-9_]{2,63}$/;export function analyzeNamingConvention(a){const b=[];try{const c=normalizeInput(a);if(!c)return[];const d=c['project_name'],e='_'+c['version'];for(const f of c['objects']){if(f['reused_from'])continue;if(!NAME_REGEX['test'](f['name']))add(b,'NAMING-01','warning','Object\x20\x27'+f['entry_id']+'\x27\x20name\x20\x27'+f['name']+'\x27\x20does\x20not\x20match\x20'+NAME_REGEX,'§1.1\x20('+f['entry_id']+')','Rename\x20to\x20match\x20^[a-z][a-z0-9_]{2,63}$\x20and\x20start\x20with\x20project\x20prefix\x20\x27'+d+'\x27.');else d&&!f['name']['startsWith'](d+'_')&&add(b,'NAMING-01','warning','Object\x20\x27'+f['entry_id']+'\x27\x20name\x20\x27'+f['name']+'\x27\x20does\x20not\x20start\x20with\x20project\x20prefix\x20\x27'+d+'_\x27','§1.1\x20('+f['entry_id']+')','Rename\x20to\x20start\x20with\x20\x27'+d+'_\x27.');e&&!f['name']['endsWith'](e)&&add(b,'NAMING-02','warning','Object\x20\x27'+f['entry_id']+'\x27\x20name\x20\x27'+f['name']+'\x27\x20is\x20missing\x20version\x20suffix\x20\x27'+e+'\x27','§1.1\x20('+f['entry_id']+')','Append\x20\x27'+e+'\x27\x20to\x20the\x20name.');}}catch(g){add(b,'NAMING-01','warning','analyzeNamingConvention\x20failed:\x20'+g['message']);}return b;}export function analyzePermissionIndexRange(a){const b=[];try{const c=normalizeInput(a);if(!c)return[];const d=[...c['testnet_blocks'],...c['mainnet_blocks']];for(const e of d){for(const f of walkPermissionIndices(e['data'])){if(f<USER_DEFINED_PERM_INDEX_START)add(b,'D-07','critical','permissionIndex\x20'+f+'\x20<\x20'+USER_DEFINED_PERM_INDEX_START+'\x20(USER_DEFINED_PERM_INDEX_START)\x20in\x20step\x20'+e['step']+'\x20('+e['operation_type']+')',(e['env']['network']??'?')+'\x20step\x20'+e['step'],'Use\x20a\x20permissionIndex\x20>=\x20'+USER_DEFINED_PERM_INDEX_START+'.');}}for(const g of d){if(g['operation_type']!=='machine')continue;const h=countMachineNodes(g);if(h>MAX_NODE_COUNT)add(b,'D-09','critical','Machine\x20in\x20step\x20'+g['step']+'\x20has\x20'+h+'\x20nodes\x20>\x20MAX_NODE_COUNT\x20('+MAX_NODE_COUNT+')',(g['env']['network']??'?')+'\x20step\x20'+g['step'],'Reduce\x20node\x20count\x20to\x20<=\x20'+MAX_NODE_COUNT+'\x20or\x20split\x20into\x20multiple\x20Machines.');}}catch(i){add(b,'D-07','warning','analyzePermissionIndexRange\x20failed:\x20'+i['message']);}return b;}const REQUIRED_SCENARIO_KEYWORDS=['normal_order','refund','dispute','machine_publish','service_publish'];export function analyzeScenarioCoverage(a){const b=[];try{const c=normalizeInput(a);if(!c)return[];const d=new Set();for(const f of c['scenarios']){const g=(f['scenario_id']+'\x20'+f['description'])['toLowerCase']();for(const h of REQUIRED_SCENARIO_KEYWORDS){if(g['includes'](h['toLowerCase']()))d['add'](h);}}if(d['size']<0x3){const i=REQUIRED_SCENARIO_KEYWORDS['filter'](j=>!d['has'](j));add(b,'D-03','warning','Scenario\x20matrix\x20covers\x20'+d['size']+'/'+REQUIRED_SCENARIO_KEYWORDS['length']+'\x20required\x20keywords;\x20missing:\x20'+i['join'](',\x20'),'§1.3\x20Scenario\x20Matrix','Add\x20scenarios\x20covering\x20the\x20missing\x20keywords\x20(normal_order,\x20refund,\x20dispute,\x20machine_publish,\x20service_publish).');}const e=new Set(c['objects']['map'](j=>j['entry_id']));for(const j of c['scenarios']){const k=[j['primary_object'],...j['supporting_objects']];for(const l of k){if(l['endsWith'](':*'))continue;if(!e['has'](l))add(b,'D-03','warning','Scenario\x20\x27'+j['scenario_id']+'\x27\x20references\x20undefined\x20object\x20\x27'+l+'\x27','§1.3\x20('+j['scenario_id']+')','Add\x20\x27'+l+'\x27\x20to\x20§1.1\x20or\x20fix\x20the\x20scenario\x20reference.');}}}catch(m){add(b,'D-03','warning','analyzeScenarioCoverage\x20failed:\x20'+m['message']);}return b;}const TESTNET_VERIFICATION_ITEMS=['V-T-01','V-T-02','V-T-03','V-T-04','V-T-05','V-T-06','V-T-07','V-T-08','V-T-09','V-T-10','V-T-11'],MAINNET_VERIFICATION_ITEMS=['V-M-01','V-M-02','V-M-03','V-M-04','V-M-05'],COMPLETENESS_CHECK_IDS=Array['from']({'length':0x14},(a,b)=>'D-'+String(b+0x1)['padStart'](0x2,'0'));export function analyzeVerificationChecklist(a){const b=[];try{const c=normalizeInput(a);if(!c)return[];for(const d of TESTNET_VERIFICATION_ITEMS){if(!c['testnet_verification']['has'](d))add(b,'D-14','warning','testnet\x20verification\x20item\x20\x27'+d+'\x27\x20is\x20missing\x20from\x20§3.3','§3.3\x20testnet\x20Verification\x20Checklist','Add\x20row\x20\x27'+d+'\x27\x20to\x20§3.3.');}for(const e of MAINNET_VERIFICATION_ITEMS){if(!c['mainnet_verification']['has'](e))add(b,'D-15','warning','mainnet\x20verification\x20item\x20\x27'+e+'\x27\x20is\x20missing\x20from\x20§4.3','§4.3\x20mainnet\x20Verification\x20Checklist','Add\x20row\x20\x27'+e+'\x27\x20to\x20§4.3.');}for(const f of COMPLETENESS_CHECK_IDS){if(!c['completeness_checklist']['has'](f))add(b,'D-18','warning','completeness\x20checklist\x20item\x20\x27'+f+'\x27\x20is\x20missing\x20from\x20§6','§6\x20Completeness\x20Checklist','Add\x20row\x20\x27'+f+'\x27\x20to\x20§6.');}}catch(g){add(b,'D-14','warning','analyzeVerificationChecklist\x20failed:\x20'+g['message']);}return b;}export function analyzeDeployableReadiness(a){const b=[];try{const c=resolveRiskResult(a);if(!c)return add(b,'D-16','info','Risk\x20aggregation\x20result\x20not\x20available;\x20D-16/D-17\x20skipped\x20(provide\x20project_graph\x20with\x20puzzles,\x20or\x20set\x20deployment_doc.risk_status).',undefined,'Run\x20C2\x20risk-aggregator\x20first,\x20or\x20provide\x20deployment_doc.risk_status.'),b;const d=c['severity_summary']['CRITICAL']??0x0;if(d>0x0){const g=c['findings']['filter'](h=>h['severity']==='CRITICAL')['map'](h=>h['risk_rule_id'])['join'](',\x20');add(b,'D-16','critical',d+'\x20CRITICAL\x20risk(s)\x20remain:\x20'+g,'C2\x20risk-aggregator\x20output','Return\x20to\x20stage\x202\x20(business\x20puzzle)\x20and\x20fix\x20all\x20CRITICAL\x20risks\x20before\x20deploying.');}const e=new Set(a['user_confirmed_high_risks']??[]),f=c['findings']['filter'](h=>h['severity']==='HIGH'&&!e['has'](h['risk_rule_id']));if(f['length']>0x0){const h=f['map'](i=>i['risk_rule_id'])['join'](',\x20');add(b,'D-17','critical',f['length']+'\x20unconfirmed\x20HIGH\x20risk(s):\x20'+h,'C2\x20risk-aggregator\x20output','User\x20must\x20confirm\x20each\x20HIGH\x20risk\x20(ACCEPT_AND_PROCEED)\x20or\x20fix\x20them.');}}catch(i){add(b,'D-16','warning','analyzeDeployableReadiness\x20failed:\x20'+i['message']);}return b;}function resolveRiskResult(a){const b=a['project_graph'];if(b&&typeof b==='object'){const d=b;if(typeof d['severity_summary']==='object'&&Array['isArray'](d['findings']))return b;if(typeof d['project_prefix']==='string'&&typeof d['puzzles']==='object')try{return aggregateProjectRisks(b);}catch{}}const c=a['deployment_doc'];if(c&&c['risk_status']){const e=c['risk_critical_count']??0x0,f=c['risk_high_count']??0x0,g=[];for(let h=0x0;h<e;h++)g['push']({'risk_rule_id':'R-CRITICAL-'+h,'object_type':'service','entry_id':'*','severity':'CRITICAL','message':'(synthesized\x20from\x20deployment_doc.risk_critical_count)','fix_suggestion':'See\x20C2\x20risk-aggregator\x20report\x20for\x20details.'});for(let j=0x0;j<f;j++)g['push']({'risk_rule_id':'R-HIGH-'+j,'object_type':'service','entry_id':'*','severity':'HIGH','message':'(synthesized\x20from\x20deployment_doc.risk_high_count)','fix_suggestion':'See\x20C2\x20risk-aggregator\x20report\x20for\x20details.'});return{'namespace':{'prefix':c['project_prefix'],'version':c['version'],'industry':c['industry']},'findings':g,'severity_summary':{'CRITICAL':e,'HIGH':f,'MEDIUM':0x0,'LOW':0x0,'INFO':0x0},'status':c['risk_status'],'calibrated_at':Date['now'](),'warnings':[]};}return undefined;}function extractMachinePairs(a){const b=a['data'];if(!b)return[];const c=b['node'];if(!c||typeof c!=='object')return[];const d=c['nodes'];if(!Array['isArray'](d))return[];return d['filter'](e=>{if(!e||typeof e!=='object')return![];const f=e['pairs'];return Array['isArray'](f);})['flatMap'](e=>e['pairs']??[]);}export function analyzeMachineAndServiceReadiness(a){const b=[];try{const c=normalizeInput(a);if(!c)return[];const d=[...c['testnet_blocks'],...c['mainnet_blocks']];for(const f of d){if(f['operation_type']!=='machine')continue;const g=extractMachinePairs(f);if(g['length']===0x0)continue;const h=g['filter'](i=>i['prev_node']==='');for(const i of h){const j=Array['isArray'](i['forwards'])?i['forwards']['length']:0x0;j===0x0&&add(b,'D-19','critical','Machine\x20in\x20step\x20'+f['step']+'\x20('+(f['env']['network']??'?')+')\x20has\x20an\x20entry\x20node\x20(prev_node=\x22\x22)\x20with\x20no\x20forwards.\x20'+'Progress\x20created\x20from\x20this\x20Machine\x20will\x20be\x20permanently\x20stuck\x20at\x20current=\x22\x22\x20(P0-2\x20root\x20cause).',(f['env']['network']??'?')+'\x20step\x20'+f['step'],'Add\x20at\x20least\x20one\x20forward\x20to\x20the\x20entry\x20node\x27s\x20pairs.\x20Example:\x20pairs:\x20[{prev_node:\x20\x22\x22,\x20forwards:\x20[{next_node:\x20\x22Ordered\x22,\x20...}]}]');}}const e=d['filter'](k=>k['operation_type']==='service');if(e['length']>0x0){const k=e['filter'](l=>{const m=l['data'];return m?.['compensation_fund_add']!=null;});k['length']===0x0&&add(b,'D-20','warning','No\x20Service\x20block\x20in\x20the\x20deployment\x20doc\x20includes\x20a\x20compensation_fund_add\x20step.\x20'+'Without\x20deposit,\x20arbitration\x20rulings\x20that\x20award\x20refunds\x20to\x20buyers\x20cannot\x20be\x20paid\x20out\x20from\x20the\x20Service.\x20'+'Industries\x20like\x20freelance\x20may\x20not\x20require\x20this\x20(info),\x20but\x20rental/travel/education\x20typically\x20do.','§3.2\x20/\x20§4.2\x20Service\x20blocks','Add\x20a\x20compensation_fund_add\x20step\x20for\x20the\x20Service\x20(e.g.,\x20data.compensation_fund_add\x20=\x20{balance:\x20<amount>}).\x20'+'Recommended:\x203-10×\x20the\x20max\x20single-order\x20amount,\x20depending\x20on\x20industry\x20(subscription:\x203×,\x20retail:\x205×,\x20rental:\x2010×).\x20See\x20P1-1\x20evaluation\x20rule.');}}catch(l){add(b,'D-19','warning','analyzeMachineAndServiceReadiness\x20failed:\x20'+l['message']);}return b;}export function scanDeployment(a){const b=[...analyzeObjectDependencyCompleteness(a),...analyzeSubstepCoherence(a),...analyzeNetworkConsistency(a),...analyzeNamingConvention(a),...analyzePermissionIndexRange(a),...analyzeScenarioCoverage(a),...analyzeVerificationChecklist(a),...analyzeDeployableReadiness(a),...analyzeMachineAndServiceReadiness(a)];return{'project_name':a['project_name'],'document_path':a['document_path'],'overall_readiness':computeReadiness(b),'findings':b,'coverage':computeCoverage(a),'checks':computeChecks(b),'scanned_at':Date['now'](),'scanner_version':DEPLOYMENT_SCANNER_VERSION};}function computeChecks(a){const b=c=>a['some'](d=>d['check_id']===c);return{'D01_object_defined':b('D-01')?'fail':'pass','D02_dependency_complete':b('D-02')?'fail':'pass','D03_scenario_covered':b('D-03')?'fail':'pass','D04_testnet_topo_order':b('D-04')?'fail':'pass','D05_testnet_network':b('D-05')?'fail':'pass','D06_testnet_replace':b('D-06')?'fail':'pass','D07_permission_index':b('D-07')?'fail':'pass','D08_guard_gen_passport':b('D-08')?'fail':'pass','D09_machine_node_count':b('D-09')?'fail':'pass','D10_substep_coherence':b('D-10')?'fail':'pass','D11_mainnet_testnet_match':b('D-11')?'fail':'pass','D12_mainnet_network':b('D-12')?'fail':'pass','D13_mainnet_replace':b('D-13')?'fail':'pass','D14_testnet_verification':b('D-14')?'fail':'pass','D15_mainnet_verification':b('D-15')?'fail':'pass','D16_no_critical_risk':b('D-16')?'fail':'pass','D17_no_high_risk':b('D-17')?'fail':'pass','D18_completeness_checklist':b('D-18')?'fail':'pass','D19_machine_entry_forward':b('D-19')?'fail':'pass','D20_service_compensation_fund':b('D-20')?'fail':'pass'};}function computeCoverage(a){const b=normalizeInput(a);if(!b)return{'objects_defined':0x0,'objects_with_scenario':0x0,'testnet_steps':0x0,'mainnet_steps':0x0,'verification_items':0x0};const c=new Set();for(const e of b['scenarios']){c['add'](e['primary_object']);for(const f of e['supporting_objects'])c['add'](f);}const d=b['objects']['filter'](g=>c['has'](g['entry_id'])||c['has'](g['object_type']+':*'))['length'];return{'objects_defined':b['objects']['length'],'objects_with_scenario':d,'testnet_steps':b['testnet_blocks']['length'],'mainnet_steps':b['mainnet_blocks']['length'],'verification_items':b['testnet_verification']['size']+b['mainnet_verification']['size']};}function computeReadiness(a){const b=a['filter'](c=>c['check_id']['startsWith']('D-'));if(b['some'](c=>c['severity']==='critical'))return'blocked';if(b['some'](c=>c['severity']==='warning'))return'warnings';return'ready';}function normalizeInput(a){if(a['deployment_doc'])return fromDeploymentDocInput(a['deployment_doc']);if(a['document_path']){if(!a82a['existsSync'](a['document_path']))return undefined;return parseDeploymentMarkdown(a['document_path']);}return undefined;}export function isReady(a){return a['overall_readiness']==='ready';}export function isBlocked(a){return a['overall_readiness']==='blocked';}export function summarizeScan(a){const b=[];b['push']('#\x20Deployment\x20Scan\x20Report\x20—\x20'+a['project_name'],''),b['push']('-\x20**Overall\x20readiness**:\x20'+a['overall_readiness']),b['push']('-\x20**Scanned\x20at**:\x20'+new Date(a['scanned_at'])['toISOString']()),b['push']('-\x20**Scanner\x20version**:\x20'+a['scanner_version']);if(a['document_path'])b['push']('-\x20**Document**:\x20'+a['document_path']);b['push']('','##\x20Coverage','','|\x20Metric\x20|\x20Count\x20|','|--------|-------|'),b['push']('|\x20Objects\x20defined\x20|\x20'+a['coverage']['objects_defined']+'\x20|'),b['push']('|\x20Objects\x20with\x20scenario\x20|\x20'+a['coverage']['objects_with_scenario']+'\x20|'),b['push']('|\x20testnet\x20steps\x20|\x20'+a['coverage']['testnet_steps']+'\x20|'),b['push']('|\x20mainnet\x20steps\x20|\x20'+a['coverage']['mainnet_steps']+'\x20|'),b['push']('|\x20verification\x20items\x20|\x20'+a['coverage']['verification_items']+'\x20|',''),b['push']('##\x20Checks\x20(D-01\x20~\x20D-20)','','|\x20Check\x20ID\x20|\x20Status\x20|','|----------|--------|');const c=Object['entries'](a['checks']);for(const [d,e]of c)b['push']('|\x20'+d+'\x20|\x20'+(e==='pass'?'✅\x20pass':'❌\x20fail')+'\x20|');b['push']('','##\x20Findings\x20('+a['findings']['length']+')','');if(a['findings']['length']===0x0)b['push']('✅\x20No\x20issues\x20detected.','');else{const g=new Map();for(const h of a['findings']){const i=g['get'](h['severity'])??[];i['push'](h),g['set'](h['severity'],i);}for(const j of['critical','warning','info']){const k=g['get'](j);if(!k||k['length']===0x0)continue;b['push']('###\x20'+j['toUpperCase']()+'\x20('+k['length']+')','');for(const l of k){b['push']('-\x20**['+l['check_id']+']**\x20'+l['message']);if(l['location'])b['push']('\x20\x20-\x20Location:\x20'+l['location']);if(l['suggestion'])b['push']('\x20\x20-\x20Suggestion:\x20'+l['suggestion']);b['push']('');}}}return b['push']('---','','*End\x20of\x20report.*'),b['join']('\x0a');}export const DEPLOYMENT_SCANNER_VERSION='2.0.0';