@wowok/agent-mcp 2.3.16 → 2.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/dist/customer/index.d.ts +9 -0
  2. package/dist/customer/index.js +9 -0
  3. package/dist/customer/industry-risks.d.ts +4 -0
  4. package/dist/customer/industry-risks.js +45 -31
  5. package/dist/customer/order-monitor.js +57 -57
  6. package/dist/customer/order-strategy.js +89 -89
  7. package/dist/customer/post-purchase.js +97 -97
  8. package/dist/customer/reminder-system.js +26 -26
  9. package/dist/customer/risk-assessment.js +46 -46
  10. package/dist/customer/types.d.ts +4 -4
  11. package/dist/customer/types.js +4 -4
  12. package/dist/customer/user-preferences.d.ts +3 -0
  13. package/dist/customer/user-preferences.js +59 -50
  14. package/dist/experience/intent-distill.js +6 -6
  15. package/dist/experience/realtime-feedback.js +17 -0
  16. package/dist/index.js +360 -273
  17. package/dist/knowledge/acquisition-flywheel.d.ts +3 -0
  18. package/dist/knowledge/acquisition-flywheel.js +73 -64
  19. package/dist/knowledge/arbitration-trust.js +10 -10
  20. package/dist/knowledge/demand-matching.js +8 -8
  21. package/dist/knowledge/dynamic-pricing.js +18 -18
  22. package/dist/knowledge/flywheel-loop.js +11 -11
  23. package/dist/knowledge/glossary.js +22 -22
  24. package/dist/knowledge/guard-ledger.d.ts +19 -0
  25. package/dist/knowledge/guard-ledger.js +246 -0
  26. package/dist/knowledge/guard-lint.d.ts +76 -0
  27. package/dist/knowledge/guard-lint.js +590 -0
  28. package/dist/knowledge/guard-puzzle.d.ts +188 -0
  29. package/dist/knowledge/guard-puzzle.js +804 -0
  30. package/dist/knowledge/guard-risk.d.ts +67 -0
  31. package/dist/knowledge/guard-risk.js +1046 -0
  32. package/dist/knowledge/guard-templates.d.ts +37 -0
  33. package/dist/knowledge/guard-templates.js +329 -0
  34. package/dist/knowledge/guard-translation.d.ts +58 -0
  35. package/dist/knowledge/guard-translation.js +1118 -0
  36. package/dist/knowledge/index.d.ts +17 -0
  37. package/dist/knowledge/index.js +17 -0
  38. package/dist/knowledge/industry-evolution.js +29 -29
  39. package/dist/knowledge/industry-generalizer.js +52 -52
  40. package/dist/knowledge/industry-registry.d.ts +1 -2
  41. package/dist/knowledge/industry-registry.js +43 -36
  42. package/dist/knowledge/intent-metrics.js +67 -67
  43. package/dist/knowledge/process-model.js +80 -80
  44. package/dist/knowledge/reputation-rules.js +9 -9
  45. package/dist/knowledge/reward-templates.js +51 -51
  46. package/dist/knowledge/safety-rules.js +63 -2
  47. package/dist/knowledge/tool-constraints.js +17 -11
  48. package/dist/knowledge/trust-metrics.js +26 -26
  49. package/dist/safety/confirm-gate.d.ts +4 -2
  50. package/dist/safety/confirm-gate.js +48 -4
  51. package/dist/schema/call/allocation.d.ts +24 -14
  52. package/dist/schema/call/arbitration.d.ts +142 -132
  53. package/dist/schema/call/base.d.ts +901 -43
  54. package/dist/schema/call/base.js +77 -13
  55. package/dist/schema/call/bridge-handler.js +15 -2
  56. package/dist/schema/call/bridge.d.ts +795 -27
  57. package/dist/schema/call/bridge.js +37 -0
  58. package/dist/schema/call/contact.d.ts +10 -0
  59. package/dist/schema/call/demand.d.ts +94 -84
  60. package/dist/schema/call/guard.d.ts +229 -46
  61. package/dist/schema/call/guard.js +50 -0
  62. package/dist/schema/call/handler.js +46 -14
  63. package/dist/schema/call/machine.d.ts +158 -138
  64. package/dist/schema/call/order.d.ts +10 -0
  65. package/dist/schema/call/payment.d.ts +10 -0
  66. package/dist/schema/call/permission.d.ts +314 -304
  67. package/dist/schema/call/personal.d.ts +10 -0
  68. package/dist/schema/call/progress.d.ts +10 -0
  69. package/dist/schema/call/proof.d.ts +20 -0
  70. package/dist/schema/call/repository.d.ts +32 -22
  71. package/dist/schema/call/reward.d.ts +10 -0
  72. package/dist/schema/call/semantic.d.ts +9 -2
  73. package/dist/schema/call/semantic.js +617 -25
  74. package/dist/schema/call/service.d.ts +20 -10
  75. package/dist/schema/call/treasury.d.ts +10 -0
  76. package/dist/schema/config/index.d.ts +18 -0
  77. package/dist/schema/config/index.js +17 -0
  78. package/dist/schema/index.d.ts +6 -0
  79. package/dist/schema/index.js +5 -0
  80. package/dist/schema/local/index.d.ts +9 -9
  81. package/dist/schema/local/index.js +9 -0
  82. package/dist/schema/local/wip.d.ts +39 -19
  83. package/dist/schema/local/wip.js +5 -5
  84. package/dist/schema/messenger/index.d.ts +376 -55
  85. package/dist/schema/messenger/index.js +19 -19
  86. package/dist/schema/operations.d.ts +1881 -681
  87. package/dist/schema/operations.js +91 -96
  88. package/dist/schema/project/index.d.ts +21 -0
  89. package/dist/schema/project/index.js +32 -0
  90. package/dist/schema/query/index.d.ts +1074 -168
  91. package/dist/schema/query/index.js +8 -8
  92. package/dist/schema/schema-query/index.d.ts +33 -0
  93. package/dist/schema/schema-query/index.js +36 -0
  94. package/dist/schema/schema-version.d.ts +25 -0
  95. package/dist/schema/schema-version.js +76 -0
  96. package/dist/schema/trust/index.d.ts +407 -0
  97. package/dist/schema/trust/index.js +113 -0
  98. package/dist/schema/utils/guard-parser.js +4 -4
  99. package/dist/schema/utils/node-parser.js +14 -14
  100. package/dist/schemas/bridge_operation.output.json +233 -9
  101. package/dist/schemas/bridge_operation.schema.json +67 -8
  102. package/dist/schemas/config_operation.output.json +18 -0
  103. package/dist/schemas/config_operation.schema.json +34 -0
  104. package/dist/schemas/guard-node-schema.json +82 -0
  105. package/dist/schemas/guard2file.schema.json +8 -0
  106. package/dist/schemas/index.json +19 -1
  107. package/dist/schemas/machineNode2file.schema.json +8 -0
  108. package/dist/schemas/messenger_operation.output.json +236 -10
  109. package/dist/schemas/onchain_events.output.json +718 -0
  110. package/dist/schemas/onchain_operations.output.json +286 -11
  111. package/dist/schemas/onchain_operations.schema.json +19 -16
  112. package/dist/schemas/onchain_operations_allocation.schema.json +8 -0
  113. package/dist/schemas/onchain_operations_arbitration.schema.json +8 -0
  114. package/dist/schemas/onchain_operations_contact.schema.json +8 -0
  115. package/dist/schemas/onchain_operations_demand.schema.json +8 -0
  116. package/dist/schemas/onchain_operations_gen_passport.schema.json +16 -0
  117. package/dist/schemas/onchain_operations_guard.schema.json +11 -16
  118. package/dist/schemas/onchain_operations_machine.schema.json +8 -0
  119. package/dist/schemas/onchain_operations_order.schema.json +8 -0
  120. package/dist/schemas/onchain_operations_payment.schema.json +8 -0
  121. package/dist/schemas/onchain_operations_permission.schema.json +8 -0
  122. package/dist/schemas/onchain_operations_personal.schema.json +8 -0
  123. package/dist/schemas/onchain_operations_progress.schema.json +8 -0
  124. package/dist/schemas/onchain_operations_repository.schema.json +8 -0
  125. package/dist/schemas/onchain_operations_reward.schema.json +8 -0
  126. package/dist/schemas/onchain_operations_service.schema.json +8 -0
  127. package/dist/schemas/onchain_operations_treasury.schema.json +8 -0
  128. package/dist/schemas/onchain_table_data.output.json +718 -0
  129. package/dist/schemas/project_operation.output.json +18 -0
  130. package/dist/schemas/project_operation.schema.json +42 -0
  131. package/dist/schemas/query_toolkit.schema.json +360 -368
  132. package/dist/schemas/schema_query.schema.json +6 -3
  133. package/dist/schemas/trust_score.output.json +327 -0
  134. package/dist/schemas/trust_score.schema.json +46 -0
  135. package/dist/schemas/wip_file.output.json +24 -1
  136. package/package.json +2 -2
@@ -0,0 +1,804 @@
1
+ export function checkPuzzleCompleteness(puzzle) {
2
+ const dimensions = {
3
+ intent: isIntentComplete(puzzle.intent),
4
+ binding: isBindingComplete(puzzle.binding),
5
+ data_sources: isDataSourcesComplete(puzzle.data_sources),
6
+ query: isQueryComplete(puzzle.queries),
7
+ logic: isLogicComplete(puzzle.logic),
8
+ constraints: isConstraintsComplete(puzzle.constraints),
9
+ };
10
+ const missing = Object.keys(dimensions).filter((k) => !dimensions[k]);
11
+ const missing_details = [];
12
+ if (!dimensions.intent) {
13
+ missing_details.push("A. Intent: protected action, validation rule, or failure conditions not clarified");
14
+ }
15
+ if (!dimensions.binding) {
16
+ missing_details.push("B. Binding: Host Object, binding field, or circular reference mode not determined");
17
+ }
18
+ if (!dimensions.data_sources) {
19
+ missing_details.push("C. Data sources: data sources not declared by 4 classifications (on-chain constant / witness-derived / submitted object / system context)");
20
+ }
21
+ if (!dimensions.query) {
22
+ missing_details.push("D. Query: query instruction not determined (if the Guard needs to query on-chain data)");
23
+ }
24
+ if (!dimensions.logic) {
25
+ missing_details.push("E. Logic: computation tree root or rely composition not designed");
26
+ }
27
+ if (!dimensions.constraints) {
28
+ missing_details.push("F. Constraints: creation-time 10 + runtime 6 constraint checks not completed");
29
+ }
30
+ const complete = missing.length === 0;
31
+ const next_step = recommendNextStep(puzzle, missing);
32
+ return { dimensions, missing, missing_details, complete, next_step };
33
+ }
34
+ function isIntentComplete(intent) {
35
+ return !!intent && !!intent.action && !!intent.rule_sentence && intent.failure_conditions.length > 0;
36
+ }
37
+ function isBindingComplete(binding) {
38
+ return !!binding && !!binding.host_object && !!binding.binding_field;
39
+ }
40
+ function isDataSourcesComplete(data_sources) {
41
+ if (!data_sources)
42
+ return false;
43
+ const hasType1 = data_sources.on_chain_constants.length > 0;
44
+ const hasType2 = data_sources.witness_derived.length > 0;
45
+ const hasType3Obj = data_sources.submitted_objects.length > 0;
46
+ const hasType3Val = data_sources.submitted_values.length > 0;
47
+ const hasType4 = data_sources.system_contexts.length > 0;
48
+ if (!hasType1 && !hasType2 && !hasType3Obj && !hasType3Val && !hasType4) {
49
+ return false;
50
+ }
51
+ const unboundedSubmission = data_sources.submitted_objects.some((e) => !e.binding_constraint);
52
+ if (unboundedSubmission)
53
+ return false;
54
+ return true;
55
+ }
56
+ function isQueryComplete(queries) {
57
+ return true;
58
+ }
59
+ function isLogicComplete(logic) {
60
+ return !!logic && !!logic.root && logic.root.return_type === "Bool";
61
+ }
62
+ function isConstraintsComplete(constraints) {
63
+ if (!constraints)
64
+ return false;
65
+ return Object.values(constraints).every((v) => v === true);
66
+ }
67
+ function recommendNextStep(puzzle, missing) {
68
+ if (missing.includes("intent")) {
69
+ return {
70
+ round: "R1",
71
+ action: "Capture validation intent",
72
+ questions: [
73
+ "What action do you want to protect? (buy/forward/claim/vote/dispute/write/allocate)",
74
+ "Describe the validation rule in one sentence",
75
+ "List the conditions under which the Guard should FAIL",
76
+ ],
77
+ };
78
+ }
79
+ if (missing.includes("binding")) {
80
+ return {
81
+ round: "R5",
82
+ action: "Determine binding target",
83
+ questions: [
84
+ "Which Host Object will the Guard bind to? (Service/Machine/Arbitration/Reward/Repository)",
85
+ "Which field will it bind to? (buy_guard/order_allocators/Forward.guard/...)",
86
+ "Does the Guard need to reference the Host Object? (circular reference mode)",
87
+ ],
88
+ };
89
+ }
90
+ if (missing.includes("data_sources")) {
91
+ return {
92
+ round: "R2",
93
+ action: "Declare data sources by 4 classifications",
94
+ questions: [
95
+ "Type1 (on-chain constant): Which already-published on-chain objects does the Guard need to query? (Service/Machine/Reward addresses)",
96
+ "Type2 (witness-derived): Do you need to derive Progress/Machine/Service from Order/Arb? (choose witness 100-108)",
97
+ "Type3 (submitted object): Which object addresses does the caller need to submit? (Order/Reward/Progress) — constraint rules must be designed",
98
+ "Type3 (submitted value): Which scalar values does the caller need to submit? (amount/weight/node name)",
99
+ "Type4 (system context): Do you need Signer (identity) / Clock (time) / Guard (self-reference)?",
100
+ "Do you need to query EntityRegistrar(0xaab) or EntityLinker(0xaaa)?",
101
+ ],
102
+ };
103
+ }
104
+ if (missing.includes("query")) {
105
+ return {
106
+ round: "R3",
107
+ action: "Design query nodes",
108
+ questions: [
109
+ "Which on-chain objects does the Guard need to query?",
110
+ "Which instruction ID does each query use? (look up from GUARDQUERY)",
111
+ "Do you need convert_witness to convert objects? (linked to Type2 declaration)",
112
+ ],
113
+ };
114
+ }
115
+ if (missing.includes("logic")) {
116
+ return {
117
+ round: "R3",
118
+ action: "Design computation tree",
119
+ questions: [
120
+ "What is the root node? (must return Bool)",
121
+ "Which data source nodes are there? (by 4 classifications: identifier/context/query)",
122
+ "Which intermediate conversion nodes are there? (calc_*/convert_*/vec_*)",
123
+ "Do you need rely to compose with other Guards?",
124
+ ],
125
+ };
126
+ }
127
+ if (missing.includes("constraints")) {
128
+ return {
129
+ round: "R6",
130
+ action: "Pre-creation review",
131
+ questions: ["Run the creation-time 10 + runtime 6 constraint checklist"],
132
+ };
133
+ }
134
+ return {
135
+ round: "R7",
136
+ action: "Prepare for on-chain creation",
137
+ questions: ["All dimensions are complete; ready to generate the semantic confirmation text"],
138
+ };
139
+ }
140
+ export function generateConfirmationText(puzzle) {
141
+ if (!puzzle.intent || !puzzle.binding || !puzzle.data_sources || !puzzle.logic) {
142
+ return "[Puzzle incomplete] Cannot generate confirmation text; please complete all dimensions first";
143
+ }
144
+ const lines = [];
145
+ lines.push("═══════════════════════════════════════════════════════");
146
+ lines.push(" Guard Semantic Confirmation Report (User Review Edition)");
147
+ lines.push("═══════════════════════════════════════════════════════");
148
+ lines.push("");
149
+ lines.push("[Intent]");
150
+ lines.push(`Protected action: ${puzzle.intent.action}`);
151
+ lines.push(`Validation rule: ${puzzle.intent.rule_sentence}`);
152
+ lines.push("Failure conditions:");
153
+ puzzle.intent.failure_conditions.forEach((c, i) => {
154
+ lines.push(` ${i + 1}. ${c}`);
155
+ });
156
+ lines.push("");
157
+ lines.push("[Binding]");
158
+ lines.push(`Host Object: ${puzzle.binding.host_object}`);
159
+ if (puzzle.binding.host_object_name) {
160
+ lines.push(`Host Object name: ${puzzle.binding.host_object_name}`);
161
+ }
162
+ lines.push(`Binding field: ${puzzle.binding.binding_field}`);
163
+ lines.push(`Circular reference: ${puzzle.binding.circular_reference ? "Yes (Guard references Host Object)" : "No"}`);
164
+ lines.push(`Host Object state: ${puzzle.binding.host_object_state}`);
165
+ lines.push("");
166
+ lines.push("[Data sources (4 classifications)]");
167
+ printDataSources(lines, puzzle.data_sources);
168
+ lines.push("");
169
+ if (puzzle.queries && puzzle.queries.length > 0) {
170
+ lines.push("[Query instructions]");
171
+ lines.push("┌──────┬──────────────────────────┬────────────┬──────────┬──────────┐");
172
+ lines.push("│ ID │ Query instruction │ Target obj │ Params │ Return │");
173
+ lines.push("├──────┼──────────────────────────┼────────────┼──────────┼──────────┤");
174
+ puzzle.queries.forEach((q) => {
175
+ const id = String(q.query_id).padEnd(4);
176
+ const name = q.query_name.length > 24 ? q.query_name.slice(0, 23) + "…" : q.query_name.padEnd(24);
177
+ const obj = q.object_type.padEnd(10);
178
+ const params = (q.parameters.length === 0 ? "(none)" : q.parameters.join(",")).padEnd(8);
179
+ const ret = q.return_type.padEnd(8);
180
+ lines.push(`│ ${id} │ ${name} │ ${obj} │ ${params} │ ${ret} │`);
181
+ });
182
+ lines.push("└──────┴──────────────────────────┴────────────┴──────────┴──────────┘");
183
+ lines.push("");
184
+ }
185
+ lines.push("[Computation tree]");
186
+ lines.push(`root: ${puzzle.logic.root.node_type} (returns: ${puzzle.logic.root.return_type})`);
187
+ lines.push(` ${puzzle.logic.root.description}`);
188
+ if (puzzle.logic.root.children) {
189
+ printLogicTree(lines, puzzle.logic.root.children, 1);
190
+ }
191
+ lines.push("");
192
+ if (puzzle.logic.rely) {
193
+ lines.push("[rely composition]");
194
+ lines.push(`Dependent Guards: ${puzzle.logic.rely.guards.join(", ")}`);
195
+ lines.push(`Logic: ${puzzle.logic.rely.logic_or ? "OR (any passes)" : "AND (all must pass)"}`);
196
+ lines.push(`rep verification: ${puzzle.logic.rely.rep_verified.every((v) => v) ? "all passed" : "some unverified"}`);
197
+ lines.push("");
198
+ }
199
+ if (puzzle.constraints) {
200
+ lines.push("[Constraint checklist (creation-time 22 + runtime 11 = 33; MCP layer static check 16)]");
201
+ const creationChecks = [
202
+ ["01", "All identifiers exist in the table", puzzle.constraints.pitfall_01_identifiers_in_table],
203
+ ["02", "Comparison node types are compatible", puzzle.constraints.pitfall_02_type_compatibility],
204
+ ["03", "Query instruction ID and parameter count are correct", puzzle.constraints.pitfall_03_query_instruction_valid],
205
+ ["04", "convert_witness type is correct", puzzle.constraints.pitfall_04_witness_correct],
206
+ ["05", "Time-lock tests use small values", puzzle.constraints.pitfall_05_time_lock_test_safe],
207
+ ["06", "Old Guard exported before iteration", puzzle.constraints.pitfall_06_exported_before_recreate],
208
+ ["07", "root returns Bool", puzzle.constraints.pitfall_07_root_returns_bool],
209
+ ["08", "rely dependency rep=true", puzzle.constraints.pitfall_08_rely_rep_true],
210
+ ["09", "voting_guard GuardIdentifier numeric", puzzle.constraints.pitfall_09_voting_weight_numeric],
211
+ ["10", "Arbitration not paused", puzzle.constraints.pitfall_10_arbitration_not_paused],
212
+ ];
213
+ const runtimeChecks = [
214
+ ["R1", "Guard immutable=true to verify", puzzle.constraints.runtime_01_guard_immutable],
215
+ ["R2", "submission type bytes match table declaration", puzzle.constraints.runtime_02_submission_type_match],
216
+ ["R3", "b_submission=true entry found in submission", puzzle.constraints.runtime_03_submission_complete],
217
+ ["R4", "submission total bytes ≤ 256", puzzle.constraints.runtime_04_submission_size],
218
+ ["R5", "witness derivation source object has related field", puzzle.constraints.runtime_05_witness_source_valid],
219
+ ["R6", "query target object exists and types match", puzzle.constraints.runtime_06_query_object_valid],
220
+ ];
221
+ lines.push(" Creation-time constraints:");
222
+ creationChecks.forEach(([num, desc, pass]) => {
223
+ lines.push(` ${pass ? "✓" : "✗"} [${num}] ${desc}`);
224
+ });
225
+ lines.push(" Runtime constraints:");
226
+ runtimeChecks.forEach(([num, desc, pass]) => {
227
+ lines.push(` ${pass ? "✓" : "✗"} [${num}] ${desc}`);
228
+ });
229
+ lines.push("");
230
+ }
231
+ lines.push("[Risk warnings]");
232
+ lines.push(" ⚠ Guard cannot be modified or deleted after creation (CREATE-only)");
233
+ lines.push(" ⚠ On-chain execution will consume gas");
234
+ lines.push(" ⚠ To modify after creation: export → edit → create new → rebind");
235
+ lines.push("");
236
+ lines.push("[Test plan (gen_passport static test)]");
237
+ lines.push(" Expected pass scenario: submit data meeting conditions → PASS → Passport generated");
238
+ lines.push(" Expected fail scenario: submit data not meeting conditions → FAIL → verify logic direction");
239
+ lines.push("");
240
+ lines.push("[Post-creation actions (important)]");
241
+ lines.push(" 1. Use guard2file to export the Guard backup (JSON file) for later rebuild or migration");
242
+ lines.push(" 2. Record the Guard object ID for subsequent binding and invocation");
243
+ lines.push(" 3. If the Guard binds to a Host Object, ensure the Host Object is published after Guard creation");
244
+ lines.push(" 4. Verify the Guard logic direction via gen_passport static test");
245
+ lines.push("");
246
+ const allCreationPass = creationChecksForReadiness(puzzle);
247
+ lines.push("[Creation readiness signal]");
248
+ lines.push(` Puzzle completeness: ${allCreationPass ? "✓ All passed — ready for on-chain CREATE" : "✗ Some items not passed — please fix first"}`);
249
+ lines.push("");
250
+ lines.push("═══════════════════════════════════════════════════════");
251
+ lines.push(" Please review the Guard semantic confirmation report above");
252
+ lines.push(" After confirming no issues, reply \"confirm creation\" to execute on-chain CREATE");
253
+ lines.push(" If modifications are needed, please point out the parts to adjust");
254
+ lines.push("═══════════════════════════════════════════════════════");
255
+ return lines.join("\n");
256
+ }
257
+ function creationChecksForReadiness(puzzle) {
258
+ if (!puzzle.intent || !puzzle.binding || !puzzle.data_sources || !puzzle.logic || !puzzle.constraints) {
259
+ return false;
260
+ }
261
+ const c = puzzle.constraints;
262
+ const creationPass = c.pitfall_01_identifiers_in_table &&
263
+ c.pitfall_02_type_compatibility &&
264
+ c.pitfall_03_query_instruction_valid &&
265
+ c.pitfall_04_witness_correct &&
266
+ c.pitfall_05_time_lock_test_safe &&
267
+ c.pitfall_06_exported_before_recreate &&
268
+ c.pitfall_07_root_returns_bool &&
269
+ c.pitfall_08_rely_rep_true &&
270
+ c.pitfall_09_voting_weight_numeric &&
271
+ c.pitfall_10_arbitration_not_paused;
272
+ const runtimePass = c.runtime_01_guard_immutable &&
273
+ c.runtime_02_submission_type_match &&
274
+ c.runtime_03_submission_complete &&
275
+ c.runtime_04_submission_size &&
276
+ c.runtime_05_witness_source_valid &&
277
+ c.runtime_06_query_object_valid;
278
+ return creationPass && runtimePass;
279
+ }
280
+ function printDataSources(lines, ds) {
281
+ if (ds.on_chain_constants.length > 0) {
282
+ lines.push(" Type1 — On-chain constant objects (OnChainConstant, b_submission=false):");
283
+ ds.on_chain_constants.forEach((e) => {
284
+ const sysMark = e.is_system_address ? " [system address]" : "";
285
+ lines.push(` [id=${e.identifier}] ${e.object_type}(${e.object_address})${sysMark} — ${e.name}`);
286
+ });
287
+ }
288
+ if (ds.witness_derived.length > 0) {
289
+ lines.push(" Type2 — Witness-derived objects (WitnessDerived, convert_witness 100-108):");
290
+ ds.witness_derived.forEach((e) => {
291
+ const srcKind = e.source_b_submission ? "submitted" : "constant";
292
+ lines.push(` [id=${e.identifier}] ${e.source_type}(${srcKind}) → ${e.target_type} via ${e.witness_name}(${e.witness_type}) — ${e.name}`);
293
+ });
294
+ }
295
+ if (ds.submitted_objects.length > 0) {
296
+ lines.push(" Type3 — Submitted objects (SubmittedObject, b_submission=true):");
297
+ ds.submitted_objects.forEach((e) => {
298
+ lines.push(` [id=${e.identifier}] ${e.expected_object_type}(${e.value_type}) — ${e.name}`);
299
+ if (e.binding_constraint) {
300
+ lines.push(` Constraint: ${e.binding_constraint}`);
301
+ }
302
+ });
303
+ }
304
+ if (ds.submitted_values.length > 0) {
305
+ lines.push(" Type3 — Submitted values (SubmittedValue, b_submission=true, scalar):");
306
+ ds.submitted_values.forEach((e) => {
307
+ lines.push(` [id=${e.identifier}] ${e.value_type} — ${e.name}`);
308
+ if (e.binding_constraint) {
309
+ lines.push(` Constraint: ${e.binding_constraint}`);
310
+ }
311
+ });
312
+ }
313
+ if (ds.system_contexts.length > 0) {
314
+ lines.push(" Type4 — System contexts (SystemContext, not in table):");
315
+ ds.system_contexts.forEach((e) => {
316
+ lines.push(` context(${e.context_type}) — ${e.usage}`);
317
+ });
318
+ }
319
+ if (ds.on_chain_constants.length === 0 &&
320
+ ds.witness_derived.length === 0 &&
321
+ ds.submitted_objects.length === 0 &&
322
+ ds.submitted_values.length === 0 &&
323
+ ds.system_contexts.length === 0) {
324
+ lines.push(" (No data sources declared)");
325
+ }
326
+ }
327
+ function printLogicTree(lines, nodes, depth) {
328
+ const indent = " ".repeat(depth + 1);
329
+ nodes.forEach((node, i) => {
330
+ const prefix = i === nodes.length - 1 ? "└── " : "├── ";
331
+ lines.push(`${indent}${prefix}${node.node_type} (${node.return_type}) — ${node.description}`);
332
+ if (node.references_identifier !== undefined) {
333
+ lines.push(`${indent} → table[${node.references_identifier}]`);
334
+ }
335
+ if (node.query) {
336
+ lines.push(`${indent} → query(${node.query.query_id}: ${node.query.query_name})`);
337
+ }
338
+ if (node.children) {
339
+ printLogicTree(lines, node.children, depth + 1);
340
+ }
341
+ });
342
+ }
343
+ export function initPuzzleFromIntent(intent) {
344
+ return {
345
+ current_round: "R1",
346
+ intent: {
347
+ action: intent.action ?? "custom",
348
+ rule_sentence: intent.rule_sentence ?? "",
349
+ failure_conditions: intent.failure_conditions ?? [],
350
+ },
351
+ };
352
+ }
353
+ export function inferBindingFromAction(action) {
354
+ const map = {
355
+ buy: { host_object: "Service", binding_field: "buy_guard" },
356
+ forward: { host_object: "Machine", binding_field: "Forward.guard" },
357
+ allocate: { host_object: "Service", binding_field: "order_allocators" },
358
+ claim_reward: { host_object: "Reward", binding_field: "guard" },
359
+ vote: { host_object: "Arbitration", binding_field: "voting_guard" },
360
+ dispute: { host_object: "Arbitration", binding_field: "usage_guard" },
361
+ write_repository: { host_object: "Repository", binding_field: "write_guard" },
362
+ submit_progress: { host_object: "Progress", binding_field: "submission" },
363
+ gen_passport: { host_object: "Standalone", binding_field: "none" },
364
+ custom: {},
365
+ };
366
+ return map[action] ?? {};
367
+ }
368
+ export function emptyDataSources() {
369
+ return {
370
+ on_chain_constants: [],
371
+ witness_derived: [],
372
+ submitted_objects: [],
373
+ submitted_values: [],
374
+ system_contexts: [],
375
+ };
376
+ }
377
+ export const WITNESS_NAME_MAP = {
378
+ 100: { name: "TypeOrderProgress", source: "Order", target: "Progress" },
379
+ 101: { name: "TypeOrderMachine", source: "Order", target: "Machine" },
380
+ 102: { name: "TypeOrderService", source: "Order", target: "Service" },
381
+ 103: { name: "TypeProgressMachine", source: "Progress", target: "Machine" },
382
+ 104: { name: "TypeArbOrder", source: "Arb", target: "Order" },
383
+ 105: { name: "TypeArbArbitration", source: "Arb", target: "Arbitration" },
384
+ 106: { name: "TypeArbProgress", source: "Arb", target: "Progress" },
385
+ 107: { name: "TypeArbMachine", source: "Arb", target: "Machine" },
386
+ 108: { name: "TypeArbService", source: "Arb", target: "Service" },
387
+ };
388
+ export function getWitnessInfo(witness_type) {
389
+ return WITNESS_NAME_MAP[witness_type];
390
+ }
391
+ function traverseRoot(node, collectors) {
392
+ if (!node)
393
+ return;
394
+ if (node.type === "identifier" && typeof node.identifier === "number") {
395
+ collectors.referencedIdentifiers.add(node.identifier);
396
+ }
397
+ if (node.type === "context" && node.context) {
398
+ collectors.contexts.add(node.context);
399
+ }
400
+ if (node.type === "query" && node.object) {
401
+ const objId = node.object.identifier;
402
+ collectors.referencedIdentifiers.add(objId);
403
+ const witnessCode = node.object.convert_witness;
404
+ if (typeof witnessCode === "number" && witnessCode >= 100 && witnessCode <= 108) {
405
+ collectors.witnessCodes.push({ code: witnessCode, objectIdentifier: objId });
406
+ }
407
+ collectors.queries.push({
408
+ query: node.query ?? "",
409
+ objectIdentifier: objId,
410
+ convertWitness: witnessCode,
411
+ parametersCount: node.parameters?.length ?? 0,
412
+ });
413
+ if (node.parameters) {
414
+ for (const param of node.parameters) {
415
+ traverseRoot(param, collectors);
416
+ }
417
+ }
418
+ }
419
+ if (node.nodes) {
420
+ for (const child of node.nodes) {
421
+ traverseRoot(child, collectors);
422
+ }
423
+ }
424
+ if (node.node) {
425
+ traverseRoot(node.node, collectors);
426
+ }
427
+ if (node.nodeLeft) {
428
+ traverseRoot(node.nodeLeft, collectors);
429
+ }
430
+ if (node.nodeRight) {
431
+ traverseRoot(node.nodeRight, collectors);
432
+ }
433
+ }
434
+ function buildLogicTree(node) {
435
+ if (!node)
436
+ return undefined;
437
+ const logicNode = {
438
+ node_type: node.type,
439
+ return_type: inferNodeType(node.type),
440
+ description: describeNode(node),
441
+ };
442
+ if (node.type === "identifier" && typeof node.identifier === "number") {
443
+ logicNode.references_identifier = node.identifier;
444
+ }
445
+ if (node.type === "query" && node.object) {
446
+ logicNode.query = {
447
+ query_id: typeof node.query === "number" ? node.query : 0,
448
+ query_name: typeof node.query === "string" ? node.query : String(node.query ?? ""),
449
+ object_type: "",
450
+ parameters: [],
451
+ return_type: "",
452
+ purpose: "",
453
+ };
454
+ if (node.object.convert_witness) {
455
+ const wInfo = getWitnessInfo(node.object.convert_witness);
456
+ if (wInfo) {
457
+ logicNode.query.witness = {
458
+ witness_type: node.object.convert_witness,
459
+ witness_name: wInfo.name,
460
+ source_type: wInfo.source,
461
+ target_type: wInfo.target,
462
+ scenario: "",
463
+ };
464
+ }
465
+ }
466
+ }
467
+ if (node.nodes) {
468
+ const children = node.nodes
469
+ .map((c) => buildLogicTree(c))
470
+ .filter((c) => c !== undefined);
471
+ if (children.length > 0) {
472
+ logicNode.children = children;
473
+ }
474
+ }
475
+ if (node.node) {
476
+ const child = buildLogicTree(node.node);
477
+ if (child) {
478
+ logicNode.children = [child];
479
+ }
480
+ }
481
+ if (node.nodeLeft) {
482
+ const child = buildLogicTree(node.nodeLeft);
483
+ if (child) {
484
+ logicNode.children = [...(logicNode.children ?? []), child];
485
+ }
486
+ }
487
+ if (node.nodeRight) {
488
+ const child = buildLogicTree(node.nodeRight);
489
+ if (child) {
490
+ logicNode.children = [...(logicNode.children ?? []), child];
491
+ }
492
+ }
493
+ return logicNode;
494
+ }
495
+ function inferNodeType(nodeType) {
496
+ const boolTypes = [
497
+ "logic_equal", "logic_not", "logic_and", "logic_or",
498
+ "logic_as_u256_greater", "logic_as_u256_lesser", "logic_as_u256_equal",
499
+ "logic_as_u256_greater_or_equal", "logic_as_u256_lesser_or_equal",
500
+ "logic_string_contains", "logic_string_nocase_contains", "logic_string_nocase_equal",
501
+ "calc_string_contains", "calc_string_nocase_contains", "calc_string_nocase_equal",
502
+ "vec_contains_bool", "vec_contains_address", "vec_contains_string",
503
+ "vec_contains_string_nocase", "vec_contains_number",
504
+ "query_reward_record_exists",
505
+ ];
506
+ if (boolTypes.includes(nodeType))
507
+ return "Bool";
508
+ const u256Types = [
509
+ "calc_number_add", "calc_number_subtract", "calc_number_multiply",
510
+ "calc_number_divide", "calc_number_mod",
511
+ "convert_address_number", "convert_string_number",
512
+ ];
513
+ if (u256Types.includes(nodeType))
514
+ return "U256";
515
+ const u64Types = [
516
+ "calc_string_length", "calc_string_indexof", "calc_string_nocase_indexof",
517
+ "vec_length", "vec_indexof_bool", "vec_indexof_address", "vec_indexof_string",
518
+ "vec_indexof_string_nocase", "vec_indexof_number",
519
+ "query_reward_record_count",
520
+ "query_progress_history_session_count",
521
+ "query_progress_history_session_forward_count",
522
+ "query_progress_history_session_forward_retained_submission_count",
523
+ ];
524
+ if (u64Types.includes(nodeType))
525
+ return "U64";
526
+ const addressTypes = ["convert_number_address"];
527
+ if (addressTypes.includes(nodeType))
528
+ return "Address";
529
+ const stringTypes = ["convert_number_string"];
530
+ if (stringTypes.includes(nodeType))
531
+ return "String";
532
+ const safeTypes = ["convert_safe_u8", "convert_safe_u16", "convert_safe_u32", "convert_safe_u64", "convert_safe_u128", "convert_safe_u256"];
533
+ if (safeTypes.includes(nodeType)) {
534
+ return nodeType.replace("convert_safe_", "U");
535
+ }
536
+ if (nodeType === "value_type")
537
+ return "U8";
538
+ if (nodeType === "query")
539
+ return "query_defined";
540
+ if (nodeType === "identifier")
541
+ return "table_defined";
542
+ if (nodeType === "context")
543
+ return "context_defined";
544
+ return "unknown";
545
+ }
546
+ function describeNode(node) {
547
+ switch (node.type) {
548
+ case "identifier":
549
+ return `Reference to table[${node.identifier ?? "?"}]`;
550
+ case "context":
551
+ return `System context: ${node.context ?? "?"}`;
552
+ case "query":
553
+ return `Query instruction ${node.query ?? "?"} (target: table[${node.object?.identifier ?? "?"}])`;
554
+ case "logic_equal":
555
+ return "Equality comparison (==)";
556
+ case "logic_not":
557
+ return "Logical NOT (!)";
558
+ case "logic_and":
559
+ return "Logical AND";
560
+ case "logic_or":
561
+ return "Logical OR";
562
+ case "logic_as_u256_greater":
563
+ return "Numeric greater than (>)";
564
+ case "logic_as_u256_lesser":
565
+ return "Numeric less than (<)";
566
+ case "logic_as_u256_equal":
567
+ return "Numeric equality (==)";
568
+ case "logic_as_u256_greater_or_equal":
569
+ return "Numeric greater than or equal (>=)";
570
+ case "logic_as_u256_lesser_or_equal":
571
+ return "Numeric less than or equal (<=)";
572
+ case "calc_number_add":
573
+ return "Numeric addition (+)";
574
+ case "calc_number_subtract":
575
+ return "Numeric subtraction (-)";
576
+ case "calc_number_multiply":
577
+ return "Numeric multiplication (*)";
578
+ case "calc_number_divide":
579
+ return "Numeric division (/)";
580
+ case "calc_number_mod":
581
+ return "Numeric modulo (%)";
582
+ case "vec_contains_address":
583
+ return "Whitelist check (vec_contains_address)";
584
+ case "vec_length":
585
+ return "Vector length";
586
+ case "convert_safe_u64":
587
+ return "Safe conversion to U64";
588
+ default:
589
+ return node.type;
590
+ }
591
+ }
592
+ function deriveConstraints(table, root, rely, collectors) {
593
+ const pitfall01 = Array.from(collectors.referencedIdentifiers).every((id) => table.some((t) => t.identifier === id));
594
+ const pitfall02 = root !== undefined;
595
+ const pitfall03 = true;
596
+ const pitfall04 = collectors.witnessCodes.every((w) => w.code >= 100 && w.code <= 108);
597
+ const pitfall05 = true;
598
+ const pitfall06 = true;
599
+ const pitfall07 = root !== undefined;
600
+ const pitfall08 = rely ? rely.guards.length <= 4 : true;
601
+ const pitfall09 = true;
602
+ const pitfall10 = true;
603
+ const runtime01 = true;
604
+ const runtime02 = true;
605
+ const runtime03 = true;
606
+ const submissionEntries = table.filter((t) => t.b_submission);
607
+ const runtime04 = submissionEntries.length <= 256;
608
+ const runtime05 = true;
609
+ const runtime06 = true;
610
+ return {
611
+ pitfall_01_identifiers_in_table: pitfall01,
612
+ pitfall_02_type_compatibility: pitfall02,
613
+ pitfall_03_query_instruction_valid: pitfall03,
614
+ pitfall_04_witness_correct: pitfall04,
615
+ pitfall_05_time_lock_test_safe: pitfall05,
616
+ pitfall_06_exported_before_recreate: pitfall06,
617
+ pitfall_07_root_returns_bool: pitfall07,
618
+ pitfall_08_rely_rep_true: pitfall08,
619
+ pitfall_09_voting_weight_numeric: pitfall09,
620
+ pitfall_10_arbitration_not_paused: pitfall10,
621
+ runtime_01_guard_immutable: runtime01,
622
+ runtime_02_submission_type_match: runtime02,
623
+ runtime_03_submission_complete: runtime03,
624
+ runtime_04_submission_size: runtime04,
625
+ runtime_05_witness_source_valid: runtime05,
626
+ runtime_06_query_object_valid: runtime06,
627
+ };
628
+ }
629
+ export function derivePuzzleFromCallData(input) {
630
+ const table = input.table ?? [];
631
+ const root = input.root;
632
+ const rely = input.rely;
633
+ const bindingHint = input.binding_hint;
634
+ const collectors = {
635
+ referencedIdentifiers: new Set(),
636
+ queries: [],
637
+ contexts: new Set(),
638
+ witnessCodes: [],
639
+ };
640
+ if (root) {
641
+ traverseRoot(root, collectors);
642
+ }
643
+ let intent;
644
+ if (bindingHint) {
645
+ intent = {
646
+ action: bindingHint.action,
647
+ rule_sentence: bindingHint.rule_sentence ?? "",
648
+ failure_conditions: bindingHint.failure_conditions ?? [],
649
+ };
650
+ }
651
+ let binding;
652
+ if (bindingHint) {
653
+ binding = {
654
+ host_object: bindingHint.host_object,
655
+ binding_field: bindingHint.binding_field,
656
+ circular_reference: bindingHint.circular_reference ?? false,
657
+ host_object_state: "unknown",
658
+ };
659
+ }
660
+ const witnessCodesByIdentifier = new Map();
661
+ for (const w of collectors.witnessCodes) {
662
+ witnessCodesByIdentifier.set(w.objectIdentifier, w.code);
663
+ }
664
+ const onChainConstants = [];
665
+ const witnessDerived = [];
666
+ const submittedObjects = [];
667
+ const submittedValues = [];
668
+ for (const item of table) {
669
+ const isReferencedByQuery = collectors.referencedIdentifiers.has(item.identifier);
670
+ const witnessCode = witnessCodesByIdentifier.get(item.identifier);
671
+ if (witnessCode !== undefined) {
672
+ const wInfo = getWitnessInfo(witnessCode);
673
+ if (wInfo) {
674
+ witnessDerived.push({
675
+ identifier: item.identifier,
676
+ source_type: wInfo.source,
677
+ witness_type: witnessCode,
678
+ witness_name: wInfo.name,
679
+ target_type: wInfo.target,
680
+ source_b_submission: item.b_submission,
681
+ name: item.name || `${wInfo.source}→${wInfo.target} via ${wInfo.name}`,
682
+ });
683
+ continue;
684
+ }
685
+ }
686
+ if (!item.b_submission) {
687
+ const valueStr = typeof item.value === "string" ? item.value.toLowerCase() : "";
688
+ const isSystemAddr = valueStr === "0xaab" || valueStr === "0xaaa";
689
+ onChainConstants.push({
690
+ identifier: item.identifier,
691
+ object_address: typeof item.value === "string" ? item.value : String(item.value ?? ""),
692
+ object_type: item.object_type ?? "",
693
+ name: item.name || `constant #${item.identifier}`,
694
+ is_system_address: isSystemAddr,
695
+ });
696
+ }
697
+ else {
698
+ const valueTypeStr = typeof item.value_type === "string"
699
+ ? item.value_type.toLowerCase()
700
+ : String(item.value_type);
701
+ if (valueTypeStr === "address") {
702
+ submittedObjects.push({
703
+ identifier: item.identifier,
704
+ expected_object_type: item.object_type ?? "",
705
+ value_type: "Address",
706
+ name: item.name || `submitted object #${item.identifier}`,
707
+ binding_constraint: item.object_type
708
+ ? `must be an on-chain object address of type ${item.object_type}`
709
+ : "must be a valid on-chain object address",
710
+ });
711
+ }
712
+ else {
713
+ submittedValues.push({
714
+ identifier: item.identifier,
715
+ value_type: typeof item.value_type === "string" ? item.value_type : String(item.value_type),
716
+ name: item.name || `submitted value #${item.identifier}`,
717
+ binding_constraint: `value type must be ${item.value_type}`,
718
+ });
719
+ }
720
+ }
721
+ }
722
+ const systemContexts = [];
723
+ for (const ctxType of collectors.contexts) {
724
+ const usageMap = {
725
+ Signer: "Current transaction signer address verification",
726
+ Clock: "On-chain timestamp (used for time-lock/time-window)",
727
+ Guard: "Guard self object ID self-reference",
728
+ };
729
+ systemContexts.push({
730
+ context_type: ctxType,
731
+ usage: usageMap[ctxType] ?? "",
732
+ });
733
+ }
734
+ const dataSources = {
735
+ on_chain_constants: onChainConstants,
736
+ witness_derived: witnessDerived,
737
+ submitted_objects: submittedObjects,
738
+ submitted_values: submittedValues,
739
+ system_contexts: systemContexts,
740
+ };
741
+ const queries = collectors.queries.map((q) => {
742
+ const wInfo = q.convertWitness !== undefined ? getWitnessInfo(q.convertWitness) : undefined;
743
+ return {
744
+ query_id: typeof q.query === "number" ? q.query : 0,
745
+ query_name: typeof q.query === "string" ? q.query : String(q.query),
746
+ object_type: "",
747
+ parameters: [],
748
+ return_type: "",
749
+ witness: wInfo ? {
750
+ witness_type: q.convertWitness,
751
+ witness_name: wInfo.name,
752
+ source_type: wInfo.source,
753
+ target_type: wInfo.target,
754
+ scenario: "",
755
+ } : undefined,
756
+ purpose: "",
757
+ };
758
+ });
759
+ let logic;
760
+ if (root) {
761
+ const logicRoot = buildLogicTree(root);
762
+ if (logicRoot) {
763
+ logicRoot.return_type = "Bool";
764
+ let logicRely;
765
+ if (rely && rely.guards.length > 0) {
766
+ logicRely = {
767
+ guards: rely.guards,
768
+ logic_or: rely.logic_or ?? false,
769
+ rep_verified: rely.guards.map(() => true),
770
+ };
771
+ }
772
+ logic = { root: logicRoot, rely: logicRely };
773
+ }
774
+ }
775
+ const constraints = deriveConstraints(table, root, rely, collectors);
776
+ const puzzle = {
777
+ current_round: "R7",
778
+ intent,
779
+ binding,
780
+ data_sources: dataSources,
781
+ queries,
782
+ logic,
783
+ constraints,
784
+ };
785
+ return puzzle;
786
+ }
787
+ export function getPuzzleStatusBooleans(puzzle) {
788
+ const completeness = checkPuzzleCompleteness(puzzle);
789
+ return {
790
+ intent: completeness.dimensions.intent,
791
+ binding: completeness.dimensions.binding,
792
+ data: completeness.dimensions.data_sources,
793
+ query: completeness.dimensions.query,
794
+ logic: completeness.dimensions.logic,
795
+ constraints: completeness.dimensions.constraints,
796
+ };
797
+ }
798
+ export function getPendingQuestions(puzzle) {
799
+ const completeness = checkPuzzleCompleteness(puzzle);
800
+ if (completeness.complete) {
801
+ return [];
802
+ }
803
+ return completeness.next_step.questions;
804
+ }