@wowok/agent-mcp 2.6.0 → 2.6.3
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.
- package/README.md +5 -3
- package/dist/customer/info-puzzle.d.ts +1 -1
- package/dist/customer/info-puzzle.js +4 -2
- package/dist/customer/risk-assessment.js +26 -4
- package/dist/customer/types.d.ts +2 -0
- package/dist/examples/guard-template-balance-check.json +38 -0
- package/dist/examples/guard-template-time-lock.json +39 -0
- package/dist/examples/machine-template-7node-rental.json +114 -0
- package/dist/examples/rental-ziroom-machine-create.json +137 -0
- package/dist/examples/rental-ziroom-permission-create.json +35 -0
- package/dist/examples/rental-ziroom-service-create.json +80 -0
- package/dist/examples/retail-myshop-service-create.json +88 -0
- package/dist/extensions/capability-manifest.d.ts +125 -0
- package/dist/extensions/capability-manifest.js +594 -0
- package/dist/extensions/constraint-registry.d.ts +24 -0
- package/dist/extensions/constraint-registry.js +196 -0
- package/dist/extensions/index.d.ts +12 -0
- package/dist/extensions/index.js +6 -0
- package/dist/extensions/metric-registry.d.ts +26 -0
- package/dist/extensions/metric-registry.js +257 -0
- package/dist/extensions/mode-evaluator.d.ts +15 -0
- package/dist/extensions/mode-evaluator.js +170 -0
- package/dist/extensions/modes.d.ts +2 -0
- package/dist/extensions/modes.js +493 -0
- package/dist/extensions/registry.d.ts +50 -0
- package/dist/extensions/registry.js +662 -0
- package/dist/extensions/types.d.ts +219 -0
- package/dist/extensions/types.js +1 -0
- package/dist/index.js +50 -0
- package/dist/knowledge/deployment-scanner.d.ts +3 -0
- package/dist/knowledge/deployment-scanner.js +64 -3
- package/dist/knowledge/fund-layer.d.ts +72 -0
- package/dist/knowledge/fund-layer.js +420 -0
- package/dist/knowledge/guard-render.d.ts +57 -0
- package/dist/knowledge/guard-render.js +700 -0
- package/dist/knowledge/guard-risk.d.ts +13 -0
- package/dist/knowledge/guard-risk.js +57 -0
- package/dist/knowledge/guard-submission-prompt.d.ts +31 -0
- package/dist/knowledge/guard-submission-prompt.js +171 -0
- package/dist/knowledge/guard-templates.js +278 -0
- package/dist/knowledge/machine-ledger.js +1 -1
- package/dist/knowledge/machine-render.d.ts +41 -0
- package/dist/knowledge/machine-render.js +565 -0
- package/dist/knowledge/machine-templates.js +24 -5
- package/dist/knowledge/reward-confirm.js +2 -2
- package/dist/knowledge/reward-puzzle.js +1 -1
- package/dist/knowledge/reward-risk.js +9 -9
- package/dist/knowledge/reward-templates.js +2 -2
- package/dist/knowledge/service-confirm.d.ts +15 -6
- package/dist/knowledge/service-confirm.js +119 -11
- package/dist/knowledge/service-context.js +1 -1
- package/dist/knowledge/service-ledger.js +1 -1
- package/dist/knowledge/service-risk.d.ts +1 -1
- package/dist/knowledge/service-risk.js +3 -3
- package/dist/knowledge/service-templates.js +2 -2
- package/dist/knowledge/service-translation.d.ts +1 -1
- package/dist/knowledge/service-translation.js +7 -7
- package/dist/knowledge/tool-constraints.js +6 -2
- package/dist/project/deployment-bridge.d.ts +1 -1
- package/dist/project/deployment-bridge.js +31 -7
- package/dist/project/deployment-doc.d.ts +3 -0
- package/dist/project/deployment-doc.js +76 -14
- package/dist/project/edit-planner.d.ts +123 -0
- package/dist/project/edit-planner.js +1371 -0
- package/dist/project/evaluation.d.ts +2 -0
- package/dist/project/evaluation.js +873 -88
- package/dist/project/graph-builder.d.ts +4 -1
- package/dist/project/graph-builder.js +132 -62
- package/dist/project/graph.d.ts +1 -0
- package/dist/project/handlers.d.ts +317 -6
- package/dist/project/handlers.js +1171 -19
- package/dist/project/stage-gate.d.ts +4 -0
- package/dist/project/stage-gate.js +64 -5
- package/dist/project/task-tracker.d.ts +26 -0
- package/dist/project/task-tracker.js +78 -0
- package/dist/safety/preview.js +16 -0
- package/dist/schema/call/allocation.d.ts +16 -16
- package/dist/schema/call/allocation.js +2 -2
- package/dist/schema/call/arbitration.js +19 -6
- package/dist/schema/call/base.d.ts +21 -13
- package/dist/schema/call/base.js +27 -6
- package/dist/schema/call/bridge.d.ts +5 -5
- package/dist/schema/call/bridge.js +3 -1
- package/dist/schema/call/contact.js +2 -2
- package/dist/schema/call/demand.d.ts +23 -31
- package/dist/schema/call/demand.js +2 -2
- package/dist/schema/call/guard.js +2 -2
- package/dist/schema/call/machine.d.ts +1976 -752
- package/dist/schema/call/machine.js +50 -4
- package/dist/schema/call/order.d.ts +149 -228
- package/dist/schema/call/order.js +4 -3
- package/dist/schema/call/payment.d.ts +183 -3
- package/dist/schema/call/payment.js +21 -3
- package/dist/schema/call/permission.js +2 -2
- package/dist/schema/call/personal.d.ts +241 -52
- package/dist/schema/call/progress.d.ts +53 -61
- package/dist/schema/call/progress.js +18 -4
- package/dist/schema/call/repository.d.ts +23 -31
- package/dist/schema/call/repository.js +2 -2
- package/dist/schema/call/reward.js +3 -3
- package/dist/schema/call/semantic.d.ts +1 -1
- package/dist/schema/call/semantic.js +37 -2
- package/dist/schema/call/service.d.ts +275 -127
- package/dist/schema/call/service.js +89 -13
- package/dist/schema/call/treasury.js +3 -3
- package/dist/schema/common/index.d.ts +13 -2
- package/dist/schema/common/index.js +80 -15
- package/dist/schema/local/index.d.ts +32 -35
- package/dist/schema/local/index.js +28 -6
- package/dist/schema/messenger/index.d.ts +274 -46
- package/dist/schema/operations.d.ts +1264 -544
- package/dist/schema/operations.js +65 -7
- package/dist/schema/project/index.d.ts +2846 -167
- package/dist/schema/project/index.js +570 -16
- package/dist/schema/query/index.d.ts +922 -349
- package/dist/schema/query/index.js +205 -42
- package/dist/schema/schema-query/index.d.ts +65 -3
- package/dist/schema/schema-query/index.js +38 -5
- package/dist/schema/utils/node-parser.js +20 -4
- package/dist/schema/utils/object-type-utils.d.ts +12 -0
- package/dist/schema/utils/object-type-utils.js +35 -0
- package/dist/schema/utils/permission-machine-check.d.ts +49 -0
- package/dist/schema/utils/permission-machine-check.js +121 -0
- package/dist/schema/utils/skills-recommendation.d.ts +2 -0
- package/dist/schema/utils/skills-recommendation.js +76 -0
- package/dist/schema-query/index.d.ts +20 -1
- package/dist/schema-query/index.js +306 -4
- package/dist/schemas/account_operation.output.json +7 -1
- package/dist/schemas/account_operation.schema.json +3 -3
- package/dist/schemas/bridge_operation.output.json +6 -0
- package/dist/schemas/bridge_operation.schema.json +1 -1
- package/dist/schemas/guard-templates.json +379 -0
- package/dist/schemas/guard2file.schema.json +1 -1
- package/dist/schemas/index.json +1 -1
- package/dist/schemas/local_info_operation.output.json +6 -0
- package/dist/schemas/local_mark_operation.output.json +7 -1
- package/dist/schemas/local_mark_operation.schema.json +1 -1
- package/dist/schemas/machineNode2file.schema.json +1 -1
- package/dist/schemas/messenger_operation.schema.json +4 -4
- package/dist/schemas/onchain_events.output.json +1 -1
- package/dist/schemas/onchain_operations.output.json +2820 -0
- package/dist/schemas/onchain_operations.schema.json +444 -330
- package/dist/schemas/onchain_operations_allocation.schema.json +37 -28
- package/dist/schemas/onchain_operations_arbitration.schema.json +16 -14
- package/dist/schemas/onchain_operations_contact.schema.json +10 -10
- package/dist/schemas/onchain_operations_demand.schema.json +10 -10
- package/dist/schemas/onchain_operations_gen_passport.schema.json +16 -16
- package/dist/schemas/onchain_operations_gen_proof.schema.json +2 -2
- package/dist/schemas/onchain_operations_guard.schema.json +2 -2
- package/dist/schemas/onchain_operations_machine.schema.json +43 -35
- package/dist/schemas/onchain_operations_order.schema.json +72 -78
- package/dist/schemas/onchain_operations_payment.schema.json +141 -111
- package/dist/schemas/onchain_operations_permission.schema.json +3 -3
- package/dist/schemas/onchain_operations_personal.schema.json +7 -7
- package/dist/schemas/onchain_operations_progress.schema.json +9 -9
- package/dist/schemas/onchain_operations_proof.schema.json +8 -8
- package/dist/schemas/onchain_operations_repository.schema.json +10 -10
- package/dist/schemas/onchain_operations_reward.schema.json +14 -14
- package/dist/schemas/onchain_operations_service.schema.json +119 -48
- package/dist/schemas/onchain_operations_treasury.schema.json +11 -11
- package/dist/schemas/onchain_table_data.output.json +33 -25
- package/dist/schemas/onchain_table_data.schema.json +22 -21
- package/dist/schemas/project_operation.output.json +2194 -23
- package/dist/schemas/project_operation.schema.json +84 -6
- package/dist/schemas/query_toolkit.output.json +108 -80
- package/dist/schemas/query_toolkit.schema.json +12 -12
- package/dist/schemas/schema_query.output.json +70 -3
- package/dist/schemas/schema_query.schema.json +18 -3
- package/dist/schemas/wowok_buildin_info.output.json +81 -8
- package/dist/schemas/wowok_buildin_info.schema.json +46 -2
- package/dist/tools/handlers/local.js +20 -5
- package/dist/tools/handlers/onchain.js +594 -6
- package/dist/tools/handlers/project.js +76 -4
- package/dist/tools/handlers/query.js +27 -0
- package/dist/tools/handlers/schema-query.js +43 -1
- package/dist/tools/handlers/task-status.d.ts +170 -0
- package/dist/tools/handlers/task-status.js +55 -0
- package/dist/tools/handlers/wip.js +47 -1
- package/dist/tools/index.d.ts +8 -0
- package/dist/tools/index.js +387 -12
- package/dist/tools/retry.d.ts +8 -0
- package/dist/tools/retry.js +85 -0
- package/dist/tools/wip-deploy-assist.d.ts +28 -0
- package/dist/tools/wip-deploy-assist.js +278 -0
- package/package.json +2 -2
- package/dist/schemas/guard-node-examples.md +0 -199
|
@@ -0,0 +1,1371 @@
|
|
|
1
|
+
import { randomUUID, createHash } from "node:crypto";
|
|
2
|
+
import { LocalProject, LocalMark, query_objects, query_table } from "@wowok/wowok";
|
|
3
|
+
import { parseMachineTreeIndented, } from "../knowledge/machine-render.js";
|
|
4
|
+
import { parseGuardTreeIndented, parseGuardTableJSON, } from "../knowledge/guard-render.js";
|
|
5
|
+
const PLAN_TTL_MS = 10 * 60 * 1000;
|
|
6
|
+
const planStore = new Map();
|
|
7
|
+
function cleanupExpiredPlans() {
|
|
8
|
+
const now = Date.now();
|
|
9
|
+
for (const [id, plan] of planStore) {
|
|
10
|
+
if (now > plan.expires_at) {
|
|
11
|
+
planStore.delete(id);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
const localProject = LocalProject.Instance();
|
|
16
|
+
async function resolveProjectId(v) {
|
|
17
|
+
if (v.project_id)
|
|
18
|
+
return v.project_id;
|
|
19
|
+
if (v.project) {
|
|
20
|
+
const p = await localProject.getProjectByPrefix(v.project);
|
|
21
|
+
if (!p)
|
|
22
|
+
throw new Error(`Project not found by prefix: ${v.project}`);
|
|
23
|
+
return p.id;
|
|
24
|
+
}
|
|
25
|
+
throw new Error("Either 'project_id' or 'project' (prefix) is required for this action");
|
|
26
|
+
}
|
|
27
|
+
async function resolveObjectAddress(v) {
|
|
28
|
+
if (v.object_address) {
|
|
29
|
+
const addr = v.object_address;
|
|
30
|
+
const isHexAddress = /^0x[0-9a-fA-F]{32,64}$/.test(addr);
|
|
31
|
+
const isDraftSentinel = addr.startsWith("draft:");
|
|
32
|
+
if (!isHexAddress && !isDraftSentinel) {
|
|
33
|
+
throw new Error(`Invalid object_address format: '${addr.slice(0, 40)}'. ` +
|
|
34
|
+
`Expected a valid Sui address (0x + 32-64 hex chars) or 'draft:<name>' sentinel.`);
|
|
35
|
+
}
|
|
36
|
+
return addr;
|
|
37
|
+
}
|
|
38
|
+
if (v.object_name_add) {
|
|
39
|
+
const mark = await LocalMark.Instance().get(v.object_name_add);
|
|
40
|
+
if (mark?.address)
|
|
41
|
+
return mark.address;
|
|
42
|
+
throw new Error(`LocalMark name not found: ${v.object_name_add}`);
|
|
43
|
+
}
|
|
44
|
+
throw new Error("Either 'object_address' or 'object_name_add' is required");
|
|
45
|
+
}
|
|
46
|
+
function sha256(text) {
|
|
47
|
+
return createHash("sha256").update(text, "utf8").digest("hex");
|
|
48
|
+
}
|
|
49
|
+
function diffMachine(oldNodes, oldEdges, newNodes, newEdges) {
|
|
50
|
+
const added = [];
|
|
51
|
+
const removed = [];
|
|
52
|
+
const modified = [];
|
|
53
|
+
const oldNodeNames = new Set(oldNodes.map(n => n.name));
|
|
54
|
+
const newNodeNames = new Set(newNodes.map(n => n.name));
|
|
55
|
+
for (const name of newNodeNames) {
|
|
56
|
+
if (!oldNodeNames.has(name))
|
|
57
|
+
added.push(`node: ${name}`);
|
|
58
|
+
}
|
|
59
|
+
for (const name of oldNodeNames) {
|
|
60
|
+
if (!newNodeNames.has(name))
|
|
61
|
+
removed.push(`node: ${name}`);
|
|
62
|
+
}
|
|
63
|
+
const oldEdgeMap = new Map();
|
|
64
|
+
for (const e of oldEdges)
|
|
65
|
+
oldEdgeMap.set(`${e.from}->${e.to}`, e);
|
|
66
|
+
const newEdgeMap = new Map();
|
|
67
|
+
for (const e of newEdges)
|
|
68
|
+
newEdgeMap.set(`${e.from}->${e.to}`, e);
|
|
69
|
+
for (const [key, newEdge] of newEdgeMap) {
|
|
70
|
+
if (!oldEdgeMap.has(key)) {
|
|
71
|
+
added.push(`edge: ${key}`);
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
const oldEdge = oldEdgeMap.get(key);
|
|
75
|
+
if (oldEdge.threshold !== newEdge.threshold) {
|
|
76
|
+
modified.push(`edge ${key}: threshold ${oldEdge.threshold} -> ${newEdge.threshold}`);
|
|
77
|
+
}
|
|
78
|
+
const oldFwdNames = new Set(oldEdge.forwards.map(f => f.name));
|
|
79
|
+
const newFwdNames = new Set(newEdge.forwards.map(f => f.name));
|
|
80
|
+
for (const fname of newFwdNames) {
|
|
81
|
+
if (!oldFwdNames.has(fname)) {
|
|
82
|
+
added.push(`forward: ${key} / ${fname}`);
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
const oldFwd = oldEdge.forwards.find(f => f.name === fname);
|
|
86
|
+
const newFwd = newEdge.forwards.find(f => f.name === fname);
|
|
87
|
+
const changes = [];
|
|
88
|
+
if (oldFwd.guard !== newFwd.guard)
|
|
89
|
+
changes.push(`guard ${oldFwd.guard} -> ${newFwd.guard}`);
|
|
90
|
+
if (oldFwd.permission_index !== newFwd.permission_index)
|
|
91
|
+
changes.push(`perm ${oldFwd.permission_index} -> ${newFwd.permission_index}`);
|
|
92
|
+
if (oldFwd.named_operator !== newFwd.named_operator)
|
|
93
|
+
changes.push(`op ${oldFwd.named_operator} -> ${newFwd.named_operator}`);
|
|
94
|
+
if (oldFwd.weight !== newFwd.weight)
|
|
95
|
+
changes.push(`weight ${oldFwd.weight} -> ${newFwd.weight}`);
|
|
96
|
+
if (changes.length > 0) {
|
|
97
|
+
modified.push(`forward ${key} / ${fname}: ${changes.join(", ")}`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
for (const fname of oldFwdNames) {
|
|
102
|
+
if (!newFwdNames.has(fname)) {
|
|
103
|
+
removed.push(`forward: ${key} / ${fname}`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
for (const key of oldEdgeMap.keys()) {
|
|
109
|
+
if (!newEdgeMap.has(key))
|
|
110
|
+
removed.push(`edge: ${key}`);
|
|
111
|
+
}
|
|
112
|
+
const summary = `${added.length} added, ${removed.length} removed, ${modified.length} modified`;
|
|
113
|
+
return { added, removed, modified, summary };
|
|
114
|
+
}
|
|
115
|
+
function diffGuard(oldRoot, newRoot, oldTable, newTable) {
|
|
116
|
+
const added = [];
|
|
117
|
+
const removed = [];
|
|
118
|
+
const modified = [];
|
|
119
|
+
function walk(oldNode, newNode, path) {
|
|
120
|
+
if (!oldNode && newNode) {
|
|
121
|
+
added.push(`node: ${path} (${newNode.type})`);
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
if (oldNode && !newNode) {
|
|
125
|
+
removed.push(`node: ${path} (${oldNode.type})`);
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (!oldNode || !newNode)
|
|
129
|
+
return;
|
|
130
|
+
if (oldNode.type !== newNode.type) {
|
|
131
|
+
modified.push(`node ${path}: type ${oldNode.type} -> ${newNode.type}`);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
if (oldNode.type === "identifier" && newNode.type === "identifier") {
|
|
135
|
+
if (oldNode.identifier !== newNode.identifier) {
|
|
136
|
+
modified.push(`node ${path}: identifier ${oldNode.identifier} -> ${newNode.identifier}`);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if (oldNode.type === "context" && newNode.type === "context") {
|
|
140
|
+
if (oldNode.context !== newNode.context) {
|
|
141
|
+
modified.push(`node ${path}: context ${oldNode.context} -> ${newNode.context}`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if (oldNode.type === "query" && newNode.type === "query") {
|
|
145
|
+
if (oldNode.query !== newNode.query) {
|
|
146
|
+
modified.push(`node ${path}: query ${oldNode.query} -> ${newNode.query}`);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const oldChildren = getGuardChildren(oldNode);
|
|
150
|
+
const newChildren = getGuardChildren(newNode);
|
|
151
|
+
const maxLen = Math.max(oldChildren.length, newChildren.length);
|
|
152
|
+
for (let i = 0; i < maxLen; i++) {
|
|
153
|
+
walk(oldChildren[i]?.node, newChildren[i]?.node, `${path}.${newChildren[i]?.label ?? oldChildren[i]?.label ?? i}`);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
walk(oldRoot, newRoot, "root");
|
|
157
|
+
const oldTableMap = new Map(oldTable.map(t => [t.identifier, t]));
|
|
158
|
+
const newTableMap = new Map(newTable.map(t => [t.identifier, t]));
|
|
159
|
+
for (const [id, newEntry] of newTableMap) {
|
|
160
|
+
if (!oldTableMap.has(id)) {
|
|
161
|
+
added.push(`table: id[${id}]`);
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
const oldEntry = oldTableMap.get(id);
|
|
165
|
+
const changes = [];
|
|
166
|
+
if (oldEntry.value_type !== newEntry.value_type)
|
|
167
|
+
changes.push(`type ${oldEntry.value_type} -> ${newEntry.value_type}`);
|
|
168
|
+
if (oldEntry.b_submission !== newEntry.b_submission)
|
|
169
|
+
changes.push(`submission ${oldEntry.b_submission} -> ${newEntry.b_submission}`);
|
|
170
|
+
if (JSON.stringify(oldEntry.value) !== JSON.stringify(newEntry.value))
|
|
171
|
+
changes.push(`value changed`);
|
|
172
|
+
if (changes.length > 0)
|
|
173
|
+
modified.push(`table id[${id}]: ${changes.join(", ")}`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
for (const id of oldTableMap.keys()) {
|
|
177
|
+
if (!newTableMap.has(id))
|
|
178
|
+
removed.push(`table: id[${id}]`);
|
|
179
|
+
}
|
|
180
|
+
const summary = `${added.length} added, ${removed.length} removed, ${modified.length} modified`;
|
|
181
|
+
return { added, removed, modified, summary };
|
|
182
|
+
}
|
|
183
|
+
function getGuardChildren(node) {
|
|
184
|
+
const children = [];
|
|
185
|
+
if (node.nodes)
|
|
186
|
+
node.nodes.forEach((c, i) => children.push({ node: c, label: `child[${i}]` }));
|
|
187
|
+
if (node.node)
|
|
188
|
+
children.push({ node: node.node, label: "child" });
|
|
189
|
+
if (node.nodeLeft)
|
|
190
|
+
children.push({ node: node.nodeLeft, label: "left" });
|
|
191
|
+
if (node.nodeRight)
|
|
192
|
+
children.push({ node: node.nodeRight, label: "right" });
|
|
193
|
+
if (node.parameters)
|
|
194
|
+
node.parameters.forEach((c, i) => children.push({ node: c, label: `param[${i}]` }));
|
|
195
|
+
if (node.historyIdx)
|
|
196
|
+
children.push({ node: node.historyIdx, label: "historyIdx" });
|
|
197
|
+
if (node.sessionIdx)
|
|
198
|
+
children.push({ node: node.sessionIdx, label: "sessionIdx" });
|
|
199
|
+
if (node.forwardIdx)
|
|
200
|
+
children.push({ node: node.forwardIdx, label: "forwardIdx" });
|
|
201
|
+
if (node.where)
|
|
202
|
+
children.push({ node: node.where, label: "where" });
|
|
203
|
+
if (node.find)
|
|
204
|
+
children.push({ node: node.find, label: "find" });
|
|
205
|
+
if (node.objectLeft)
|
|
206
|
+
children.push({ node: node.objectLeft, label: "objLeft" });
|
|
207
|
+
if (node.objectRight)
|
|
208
|
+
children.push({ node: node.objectRight, label: "objRight" });
|
|
209
|
+
if (node.recipient)
|
|
210
|
+
children.push({ node: node.recipient, label: "recipient" });
|
|
211
|
+
return children;
|
|
212
|
+
}
|
|
213
|
+
function validateMachine(nodes, edges) {
|
|
214
|
+
const warnings = [];
|
|
215
|
+
const blocking_errors = [];
|
|
216
|
+
const hasEntry = edges.some(e => e.from === "");
|
|
217
|
+
if (!hasEntry) {
|
|
218
|
+
blocking_errors.push({
|
|
219
|
+
id: "E-01",
|
|
220
|
+
description: "No entry forward found (no edge with from=''). Every Machine must have at least one entry forward.",
|
|
221
|
+
impact: "The Machine cannot start — no way to create the first Progress entry.",
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
const nodeNames = new Set(nodes.map(n => n.name));
|
|
225
|
+
for (const edge of edges) {
|
|
226
|
+
if (edge.from && !nodeNames.has(edge.from)) {
|
|
227
|
+
blocking_errors.push({
|
|
228
|
+
id: "E-02",
|
|
229
|
+
description: `Edge ${edge.from}->${edge.to} references unknown source node '${edge.from}'.`,
|
|
230
|
+
impact: "The on-chain Machine will reject this — all edge endpoints must exist as nodes.",
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
if (!nodeNames.has(edge.to)) {
|
|
234
|
+
blocking_errors.push({
|
|
235
|
+
id: "E-02",
|
|
236
|
+
description: `Edge ${edge.from}->${edge.to} references unknown target node '${edge.to}'.`,
|
|
237
|
+
impact: "The on-chain Machine will reject this — all edge endpoints must exist as nodes.",
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
if (nodes.length > 200) {
|
|
242
|
+
blocking_errors.push({
|
|
243
|
+
id: "E-03",
|
|
244
|
+
description: `Node count ${nodes.length} exceeds on-chain MAX_NODE_COUNT (200).`,
|
|
245
|
+
impact: "The on-chain Machine will reject this — split the workflow into multiple Machines.",
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
const nodesWithIncoming = new Set(edges.filter(e => e.from !== "").map(e => e.to));
|
|
249
|
+
const entryNodes = new Set(edges.filter(e => e.from === "").map(e => e.to));
|
|
250
|
+
for (const node of nodes) {
|
|
251
|
+
if (!nodesWithIncoming.has(node.name) && !entryNodes.has(node.name)) {
|
|
252
|
+
warnings.push({
|
|
253
|
+
id: "W-01",
|
|
254
|
+
description: `Node '${node.name}' has no incoming edges and is not an entry node (unreachable).`,
|
|
255
|
+
impact: "This node will never be reached during workflow execution.",
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
for (const edge of edges) {
|
|
260
|
+
if (edge.from === edge.to && edge.from !== "") {
|
|
261
|
+
warnings.push({
|
|
262
|
+
id: "W-02",
|
|
263
|
+
description: `Self-loop detected on node '${edge.from}' (revision cycle).`,
|
|
264
|
+
impact: "This is intentional for revision workflows, but ensure there's an exit forward to break the cycle.",
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
return { warnings, blocking_errors };
|
|
269
|
+
}
|
|
270
|
+
function validateGuard(root, table) {
|
|
271
|
+
const warnings = [];
|
|
272
|
+
const blocking_errors = [];
|
|
273
|
+
if (!root) {
|
|
274
|
+
blocking_errors.push({
|
|
275
|
+
id: "E-01",
|
|
276
|
+
description: "Guard tree has no root node.",
|
|
277
|
+
impact: "The on-chain Guard will reject this — every Guard must have a root computation node.",
|
|
278
|
+
});
|
|
279
|
+
return { warnings, blocking_errors };
|
|
280
|
+
}
|
|
281
|
+
const tableIds = new Set(table.map(t => t.identifier));
|
|
282
|
+
const referencedIds = new Set();
|
|
283
|
+
function collectIds(node) {
|
|
284
|
+
if (node.type === "identifier" && typeof node.identifier === "number") {
|
|
285
|
+
referencedIds.add(node.identifier);
|
|
286
|
+
}
|
|
287
|
+
for (const child of getGuardChildren(node)) {
|
|
288
|
+
collectIds(child.node);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
collectIds(root);
|
|
292
|
+
for (const id of referencedIds) {
|
|
293
|
+
if (!tableIds.has(id)) {
|
|
294
|
+
blocking_errors.push({
|
|
295
|
+
id: "E-02",
|
|
296
|
+
description: `Identifier ${id} is referenced in the tree but not defined in the table.`,
|
|
297
|
+
impact: "The on-chain Guard will reject this — all identifier references must have a table entry.",
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
if (table.length > 256) {
|
|
302
|
+
blocking_errors.push({
|
|
303
|
+
id: "E-03",
|
|
304
|
+
description: `Table size ${table.length} exceeds on-chain MAX_TABLE_SIZE (256).`,
|
|
305
|
+
impact: "The on-chain Guard will reject this — reduce the number of table entries.",
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
const submissionSlots = table.filter(t => t.b_submission);
|
|
309
|
+
for (const slot of submissionSlots) {
|
|
310
|
+
if (!referencedIds.has(slot.identifier)) {
|
|
311
|
+
const label = slot.name ? `'${slot.name}' (id=${slot.identifier})` : `id=${slot.identifier}`;
|
|
312
|
+
warnings.push({
|
|
313
|
+
id: "W-01",
|
|
314
|
+
description: `Submission slot ${label} is declared in the table but never referenced by any identifier node in the tree.`,
|
|
315
|
+
impact: "This slot is dead — submitting a value for it has no effect on the guard result. Remove it or add an identifier reference.",
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
for (const entry of table) {
|
|
320
|
+
if (!referencedIds.has(entry.identifier)) {
|
|
321
|
+
if (entry.b_submission)
|
|
322
|
+
continue;
|
|
323
|
+
const label = entry.name ? `'${entry.name}' (id=${entry.identifier})` : `id=${entry.identifier}`;
|
|
324
|
+
warnings.push({
|
|
325
|
+
id: "W-02",
|
|
326
|
+
description: `Table entry ${label} is declared but never referenced by any identifier node in the tree.`,
|
|
327
|
+
impact: "This entry is orphaned — it consumes table space without affecting the guard result. Remove it to reduce table size.",
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
function maxDepth(node, depth) {
|
|
332
|
+
if (depth > 16)
|
|
333
|
+
return depth;
|
|
334
|
+
const children = getGuardChildren(node);
|
|
335
|
+
if (children.length === 0)
|
|
336
|
+
return depth;
|
|
337
|
+
return Math.max(...children.map(c => maxDepth(c.node, depth + 1)));
|
|
338
|
+
}
|
|
339
|
+
const depth = maxDepth(root, 1);
|
|
340
|
+
if (depth > 16) {
|
|
341
|
+
warnings.push({
|
|
342
|
+
id: "W-03",
|
|
343
|
+
description: `Guard tree depth ${depth} exceeds 16 (heuristic threshold for on-chain recursion safety).`,
|
|
344
|
+
impact: "Deep trees may hit on-chain stack/gas limits or fail audit. Consider flattening logic (e.g. split into multiple guards connected via rely) or simplifying nested computations.",
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
return { warnings, blocking_errors };
|
|
348
|
+
}
|
|
349
|
+
function prepareMachineCall(objectName, objectAddress, nodes, edges) {
|
|
350
|
+
const nodeMap = new Map();
|
|
351
|
+
for (const node of nodes) {
|
|
352
|
+
nodeMap.set(node.name, {
|
|
353
|
+
name: node.name,
|
|
354
|
+
description: node.description ?? null,
|
|
355
|
+
pairs: [],
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
for (const edge of edges) {
|
|
359
|
+
if (!nodeMap.has(edge.to)) {
|
|
360
|
+
nodeMap.set(edge.to, { name: edge.to, description: null, pairs: [] });
|
|
361
|
+
}
|
|
362
|
+
nodeMap.get(edge.to).pairs.push({
|
|
363
|
+
prev_node: edge.from,
|
|
364
|
+
threshold: edge.threshold,
|
|
365
|
+
forwards: edge.forwards.map(f => ({
|
|
366
|
+
name: f.name,
|
|
367
|
+
weight: f.weight,
|
|
368
|
+
namedOperator: f.named_operator ?? "",
|
|
369
|
+
permissionIndex: f.permission_index ?? 0,
|
|
370
|
+
guard: f.guard ? { guard: f.guard } : null,
|
|
371
|
+
retained_submission: f.retained_submission ?? null,
|
|
372
|
+
})),
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
const nodeList = Array.from(nodeMap.values());
|
|
376
|
+
const jsonContent = JSON.stringify(nodeList, null, 2);
|
|
377
|
+
return {
|
|
378
|
+
operation_type: "machine",
|
|
379
|
+
data: {
|
|
380
|
+
namedNew: { name: objectName ?? objectAddress },
|
|
381
|
+
node: {
|
|
382
|
+
json_or_markdown: jsonContent,
|
|
383
|
+
},
|
|
384
|
+
bReplace: true,
|
|
385
|
+
},
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
function prepareGuardCall(objectName, objectAddress, root, table, rely) {
|
|
389
|
+
const data = {
|
|
390
|
+
namedNew: { name: objectName ?? objectAddress },
|
|
391
|
+
root: {
|
|
392
|
+
type: "inline_json",
|
|
393
|
+
json: JSON.stringify(root, null, 2),
|
|
394
|
+
},
|
|
395
|
+
table: table.map(t => ({
|
|
396
|
+
identifier: t.identifier,
|
|
397
|
+
b_submission: t.b_submission,
|
|
398
|
+
value_type: typeof t.value_type === "string" ? t.value_type : t.value_type,
|
|
399
|
+
value: t.value,
|
|
400
|
+
name: t.name,
|
|
401
|
+
})),
|
|
402
|
+
};
|
|
403
|
+
if (rely && Array.isArray(rely.guards) && rely.guards.length > 0) {
|
|
404
|
+
data.rely = {
|
|
405
|
+
guards: rely.guards,
|
|
406
|
+
logic_or: rely.logic_or,
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
return {
|
|
410
|
+
operation_type: "guard",
|
|
411
|
+
data,
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
export async function handlePlanObjectEdit(v) {
|
|
415
|
+
cleanupExpiredPlans();
|
|
416
|
+
const projectId = await resolveProjectId(v);
|
|
417
|
+
const objectAddress = await resolveObjectAddress(v);
|
|
418
|
+
const objectKind = v.object_kind;
|
|
419
|
+
const editFormat = v.edit_format ?? "tree_outline";
|
|
420
|
+
const editedContent = v.edited_content;
|
|
421
|
+
if (!objectKind) {
|
|
422
|
+
throw new Error("'object_kind' is required for plan_object_edit (must be 'machine' or 'guard')");
|
|
423
|
+
}
|
|
424
|
+
if (!editedContent) {
|
|
425
|
+
throw new Error("'edited_content' is required for plan_object_edit");
|
|
426
|
+
}
|
|
427
|
+
const project = await localProject.getProject(projectId);
|
|
428
|
+
if (!project)
|
|
429
|
+
throw new Error(`Project not found (id: ${projectId})`);
|
|
430
|
+
let objectName = null;
|
|
431
|
+
try {
|
|
432
|
+
const mark = await LocalMark.Instance().get(objectAddress);
|
|
433
|
+
objectName = mark?.name ?? null;
|
|
434
|
+
}
|
|
435
|
+
catch {
|
|
436
|
+
}
|
|
437
|
+
const network = (project.network ?? "testnet");
|
|
438
|
+
let parsedResult;
|
|
439
|
+
if (objectKind === "machine") {
|
|
440
|
+
parsedResult = parseMachineTreeIndented(editedContent);
|
|
441
|
+
}
|
|
442
|
+
else {
|
|
443
|
+
parsedResult = parseGuardTreeIndented(editedContent);
|
|
444
|
+
}
|
|
445
|
+
if (!parsedResult.success || !parsedResult.data) {
|
|
446
|
+
const plan = {
|
|
447
|
+
plan_id: randomUUID(),
|
|
448
|
+
object_kind: objectKind,
|
|
449
|
+
object_address: objectAddress,
|
|
450
|
+
object_name: objectName,
|
|
451
|
+
expected_hash: sha256(editedContent),
|
|
452
|
+
edited_content: editedContent,
|
|
453
|
+
edit_format: editFormat,
|
|
454
|
+
diff: { added: [], removed: [], modified: [], summary: "parse failed — no diff computed" },
|
|
455
|
+
warnings: [],
|
|
456
|
+
blocking_errors: [{
|
|
457
|
+
id: "E-PARSE",
|
|
458
|
+
description: `Failed to parse edited content: ${parsedResult.errors.join("; ")}`,
|
|
459
|
+
impact: "The edited content is malformed and cannot be applied. Fix the syntax and try again.",
|
|
460
|
+
}],
|
|
461
|
+
can_apply: false,
|
|
462
|
+
prepared_call: null,
|
|
463
|
+
created_at: Date.now(),
|
|
464
|
+
expires_at: Date.now() + PLAN_TTL_MS,
|
|
465
|
+
summary: `Parse failed — ${parsedResult.errors.length} error(s)`,
|
|
466
|
+
};
|
|
467
|
+
planStore.set(plan.plan_id, plan);
|
|
468
|
+
return {
|
|
469
|
+
action: "plan_object_edit",
|
|
470
|
+
plan_id: plan.plan_id,
|
|
471
|
+
object_kind: plan.object_kind,
|
|
472
|
+
object_address: plan.object_address,
|
|
473
|
+
object_name: plan.object_name,
|
|
474
|
+
expected_hash: plan.expected_hash,
|
|
475
|
+
diff: plan.diff,
|
|
476
|
+
warnings: plan.warnings,
|
|
477
|
+
blocking_errors: plan.blocking_errors,
|
|
478
|
+
can_apply: plan.can_apply,
|
|
479
|
+
prepared_call: plan.prepared_call,
|
|
480
|
+
expires_at: new Date(plan.expires_at).toISOString(),
|
|
481
|
+
summary: plan.summary,
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
const stateHash = sha256(JSON.stringify(parsedResult.data) + editedContent);
|
|
485
|
+
if (objectKind === "machine") {
|
|
486
|
+
const newNodes = parsedResult.data.nodes;
|
|
487
|
+
const newEdges = parsedResult.data.edges;
|
|
488
|
+
let oldNodes = [];
|
|
489
|
+
let oldEdges = [];
|
|
490
|
+
try {
|
|
491
|
+
const currentResult = await fetchCurrentMachine(objectAddress, network);
|
|
492
|
+
oldNodes = currentResult.nodes;
|
|
493
|
+
oldEdges = currentResult.edges;
|
|
494
|
+
}
|
|
495
|
+
catch {
|
|
496
|
+
}
|
|
497
|
+
const diff = diffMachine(oldNodes, oldEdges, newNodes, newEdges);
|
|
498
|
+
const validation = validateMachine(newNodes, newEdges);
|
|
499
|
+
const canApply = validation.blocking_errors.length === 0;
|
|
500
|
+
const preparedCall = canApply ? prepareMachineCall(objectName, objectAddress, newNodes, newEdges) : null;
|
|
501
|
+
const plan = {
|
|
502
|
+
plan_id: randomUUID(),
|
|
503
|
+
object_kind: objectKind,
|
|
504
|
+
object_address: objectAddress,
|
|
505
|
+
object_name: objectName,
|
|
506
|
+
expected_hash: stateHash,
|
|
507
|
+
edited_content: editedContent,
|
|
508
|
+
edit_format: editFormat,
|
|
509
|
+
diff,
|
|
510
|
+
warnings: validation.warnings,
|
|
511
|
+
blocking_errors: validation.blocking_errors,
|
|
512
|
+
can_apply: canApply,
|
|
513
|
+
prepared_call: preparedCall,
|
|
514
|
+
created_at: Date.now(),
|
|
515
|
+
expires_at: Date.now() + PLAN_TTL_MS,
|
|
516
|
+
summary: `Machine edit: ${diff.summary}. ${validation.blocking_errors.length} blocking error(s), ${validation.warnings.length} warning(s).`,
|
|
517
|
+
};
|
|
518
|
+
planStore.set(plan.plan_id, plan);
|
|
519
|
+
return {
|
|
520
|
+
action: "plan_object_edit",
|
|
521
|
+
plan_id: plan.plan_id,
|
|
522
|
+
object_kind: plan.object_kind,
|
|
523
|
+
object_address: plan.object_address,
|
|
524
|
+
object_name: plan.object_name,
|
|
525
|
+
expected_hash: plan.expected_hash,
|
|
526
|
+
diff: plan.diff,
|
|
527
|
+
warnings: plan.warnings,
|
|
528
|
+
blocking_errors: plan.blocking_errors,
|
|
529
|
+
can_apply: plan.can_apply,
|
|
530
|
+
prepared_call: plan.prepared_call,
|
|
531
|
+
expires_at: new Date(plan.expires_at).toISOString(),
|
|
532
|
+
summary: plan.summary,
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
const newRoot = parsedResult.data;
|
|
536
|
+
let newTable = [];
|
|
537
|
+
const tableJson = parseGuardTableJSON(editedContent);
|
|
538
|
+
if (tableJson && tableJson.length > 0) {
|
|
539
|
+
newTable = tableJson;
|
|
540
|
+
}
|
|
541
|
+
else {
|
|
542
|
+
const tableMatch = editedContent.match(/##\s*Table[^\n]*\n([\s\S]*?)(?=\n##\s|$)/i);
|
|
543
|
+
if (tableMatch) {
|
|
544
|
+
const tableLines = tableMatch[1].split("\n").filter(l => l.trim().startsWith("| "));
|
|
545
|
+
for (const line of tableLines.slice(2)) {
|
|
546
|
+
const cells = line.split("|").map(c => c.trim()).filter(Boolean);
|
|
547
|
+
if (cells.length >= 4) {
|
|
548
|
+
newTable.push({
|
|
549
|
+
identifier: parseInt(cells[0], 10),
|
|
550
|
+
b_submission: cells[1] === "true",
|
|
551
|
+
value_type: cells[2],
|
|
552
|
+
value: cells[3] === "-" ? undefined : cells[3],
|
|
553
|
+
name: cells[4] === "-" ? undefined : cells[4],
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
let oldRoot = null;
|
|
560
|
+
let oldTable = [];
|
|
561
|
+
let oldRely = null;
|
|
562
|
+
try {
|
|
563
|
+
const currentResult = await fetchCurrentGuard(objectAddress, network);
|
|
564
|
+
oldRoot = currentResult.root;
|
|
565
|
+
oldTable = currentResult.table;
|
|
566
|
+
oldRely = currentResult.rely;
|
|
567
|
+
}
|
|
568
|
+
catch {
|
|
569
|
+
}
|
|
570
|
+
const diff = diffGuard(oldRoot ?? newRoot, newRoot, oldTable, newTable);
|
|
571
|
+
const validation = validateGuard(newRoot, newTable);
|
|
572
|
+
const canApply = validation.blocking_errors.length === 0;
|
|
573
|
+
const preparedCall = canApply ? prepareGuardCall(objectName, objectAddress, newRoot, newTable, oldRely) : null;
|
|
574
|
+
const plan = {
|
|
575
|
+
plan_id: randomUUID(),
|
|
576
|
+
object_kind: objectKind,
|
|
577
|
+
object_address: objectAddress,
|
|
578
|
+
object_name: objectName,
|
|
579
|
+
expected_hash: stateHash,
|
|
580
|
+
edited_content: editedContent,
|
|
581
|
+
edit_format: editFormat,
|
|
582
|
+
diff,
|
|
583
|
+
warnings: validation.warnings,
|
|
584
|
+
blocking_errors: validation.blocking_errors,
|
|
585
|
+
can_apply: canApply,
|
|
586
|
+
prepared_call: preparedCall,
|
|
587
|
+
created_at: Date.now(),
|
|
588
|
+
expires_at: Date.now() + PLAN_TTL_MS,
|
|
589
|
+
summary: `Guard edit: ${diff.summary}. ${validation.blocking_errors.length} blocking error(s), ${validation.warnings.length} warning(s).`,
|
|
590
|
+
};
|
|
591
|
+
planStore.set(plan.plan_id, plan);
|
|
592
|
+
return {
|
|
593
|
+
action: "plan_object_edit",
|
|
594
|
+
plan_id: plan.plan_id,
|
|
595
|
+
object_kind: plan.object_kind,
|
|
596
|
+
object_address: plan.object_address,
|
|
597
|
+
object_name: plan.object_name,
|
|
598
|
+
expected_hash: plan.expected_hash,
|
|
599
|
+
diff: plan.diff,
|
|
600
|
+
warnings: plan.warnings,
|
|
601
|
+
blocking_errors: plan.blocking_errors,
|
|
602
|
+
can_apply: plan.can_apply,
|
|
603
|
+
prepared_call: plan.prepared_call,
|
|
604
|
+
expires_at: new Date(plan.expires_at).toISOString(),
|
|
605
|
+
summary: plan.summary,
|
|
606
|
+
};
|
|
607
|
+
}
|
|
608
|
+
export async function handleApplyObjectEdit(v) {
|
|
609
|
+
cleanupExpiredPlans();
|
|
610
|
+
const planId = v.plan_id;
|
|
611
|
+
const expectedHash = v.expected_hash;
|
|
612
|
+
if (!planId) {
|
|
613
|
+
throw new Error("'plan_id' is required for apply_object_edit");
|
|
614
|
+
}
|
|
615
|
+
if (!expectedHash) {
|
|
616
|
+
throw new Error("'expected_hash' is required for apply_object_edit");
|
|
617
|
+
}
|
|
618
|
+
const plan = planStore.get(planId);
|
|
619
|
+
if (!plan) {
|
|
620
|
+
return {
|
|
621
|
+
action: "apply_object_edit",
|
|
622
|
+
plan_id: planId,
|
|
623
|
+
applied: false,
|
|
624
|
+
hash_match: false,
|
|
625
|
+
prepared_call: null,
|
|
626
|
+
error: `Plan not found (id: ${planId}). The plan may have expired (10-minute TTL) or never existed.`,
|
|
627
|
+
next_step: "Re-run plan_object_edit to create a new plan.",
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
if (Date.now() > plan.expires_at) {
|
|
631
|
+
planStore.delete(planId);
|
|
632
|
+
return {
|
|
633
|
+
action: "apply_object_edit",
|
|
634
|
+
plan_id: planId,
|
|
635
|
+
applied: false,
|
|
636
|
+
hash_match: false,
|
|
637
|
+
prepared_call: null,
|
|
638
|
+
error: `Plan expired at ${new Date(plan.expires_at).toISOString()}. Plans have a 10-minute TTL.`,
|
|
639
|
+
next_step: "Re-run plan_object_edit to create a new plan.",
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
const hashMatch = plan.expected_hash === expectedHash;
|
|
643
|
+
if (!hashMatch) {
|
|
644
|
+
return {
|
|
645
|
+
action: "apply_object_edit",
|
|
646
|
+
plan_id: planId,
|
|
647
|
+
applied: false,
|
|
648
|
+
hash_match: false,
|
|
649
|
+
prepared_call: null,
|
|
650
|
+
error: `Hash mismatch — the on-chain state may have changed between plan and apply, or the edited_content was modified. Expected: ${plan.expected_hash}, got: ${expectedHash}.`,
|
|
651
|
+
next_step: "Re-run plan_object_edit to create a fresh plan based on the current on-chain state.",
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
if (!plan.can_apply) {
|
|
655
|
+
return {
|
|
656
|
+
action: "apply_object_edit",
|
|
657
|
+
plan_id: planId,
|
|
658
|
+
applied: false,
|
|
659
|
+
hash_match: true,
|
|
660
|
+
prepared_call: null,
|
|
661
|
+
error: `Plan has ${plan.blocking_errors.length} blocking error(s). Fix them before applying: ${plan.blocking_errors.map(e => e.description).join("; ")}`,
|
|
662
|
+
next_step: "Fix the blocking errors in the edited content, then re-run plan_object_edit.",
|
|
663
|
+
};
|
|
664
|
+
}
|
|
665
|
+
return {
|
|
666
|
+
action: "apply_object_edit",
|
|
667
|
+
plan_id: planId,
|
|
668
|
+
applied: true,
|
|
669
|
+
hash_match: true,
|
|
670
|
+
prepared_call: plan.prepared_call,
|
|
671
|
+
error: null,
|
|
672
|
+
next_step: "Pass the prepared_call to onchain_operations to execute the edit on-chain. Review the call data before executing — it will modify the on-chain object.",
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
async function fetchCurrentMachine(machineAddress, network) {
|
|
676
|
+
const allFieldObjectIds = [];
|
|
677
|
+
let cursor = undefined;
|
|
678
|
+
for (;;) {
|
|
679
|
+
const tableResult = await query_table({
|
|
680
|
+
parent: machineAddress,
|
|
681
|
+
cursor: cursor ?? undefined,
|
|
682
|
+
network,
|
|
683
|
+
});
|
|
684
|
+
if (!tableResult?.items || tableResult.items.length === 0)
|
|
685
|
+
break;
|
|
686
|
+
for (const item of tableResult.items) {
|
|
687
|
+
if (item.object)
|
|
688
|
+
allFieldObjectIds.push(item.object);
|
|
689
|
+
}
|
|
690
|
+
if (!tableResult.hasNextPage || !tableResult.nextCursor)
|
|
691
|
+
break;
|
|
692
|
+
cursor = tableResult.nextCursor;
|
|
693
|
+
}
|
|
694
|
+
const nodeMap = new Map();
|
|
695
|
+
const edges = [];
|
|
696
|
+
if (allFieldObjectIds.length > 0) {
|
|
697
|
+
const BATCH = 50;
|
|
698
|
+
for (let i = 0; i < allFieldObjectIds.length; i += BATCH) {
|
|
699
|
+
const batch = allFieldObjectIds.slice(i, i + BATCH);
|
|
700
|
+
const nodeQueryResult = await query_objects({
|
|
701
|
+
objects: batch,
|
|
702
|
+
network,
|
|
703
|
+
});
|
|
704
|
+
for (const obj of nodeQueryResult?.objects ?? []) {
|
|
705
|
+
if (obj.type === "TableItem_MachineNode") {
|
|
706
|
+
const nodeObj = obj;
|
|
707
|
+
const nodeName = nodeObj.name;
|
|
708
|
+
if (!nodeName)
|
|
709
|
+
continue;
|
|
710
|
+
if (!nodeMap.has(nodeName)) {
|
|
711
|
+
nodeMap.set(nodeName, { name: nodeName, description: null });
|
|
712
|
+
}
|
|
713
|
+
const pairs = Array.isArray(nodeObj.value) ? nodeObj.value : [];
|
|
714
|
+
for (const pair of pairs) {
|
|
715
|
+
if (!pair || typeof pair !== "object")
|
|
716
|
+
continue;
|
|
717
|
+
const from = typeof pair.prev_node === "string" ? pair.prev_node : "";
|
|
718
|
+
const to = nodeName;
|
|
719
|
+
const threshold = typeof pair.threshold === "number" ? pair.threshold : 1;
|
|
720
|
+
const forwardsRaw = Array.isArray(pair.forwards) ? pair.forwards : [];
|
|
721
|
+
const forwards = forwardsRaw.map((f) => ({
|
|
722
|
+
name: f.name ?? "",
|
|
723
|
+
weight: f.weight ?? 1,
|
|
724
|
+
named_operator: f.namedOperator ?? null,
|
|
725
|
+
permission_index: f.permissionIndex ?? null,
|
|
726
|
+
guard: f.guard?.guard ?? f.guard ?? null,
|
|
727
|
+
retained_submission: f.retained_submission ?? null,
|
|
728
|
+
}));
|
|
729
|
+
edges.push({ from, to, threshold, forwards });
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
for (const edge of edges) {
|
|
736
|
+
if (!nodeMap.has(edge.from))
|
|
737
|
+
nodeMap.set(edge.from, { name: edge.from, description: null });
|
|
738
|
+
if (!nodeMap.has(edge.to))
|
|
739
|
+
nodeMap.set(edge.to, { name: edge.to, description: null });
|
|
740
|
+
}
|
|
741
|
+
return { nodes: Array.from(nodeMap.values()), edges };
|
|
742
|
+
}
|
|
743
|
+
async function fetchCurrentGuard(guardAddress, network) {
|
|
744
|
+
const queryResult = await query_objects({
|
|
745
|
+
objects: [guardAddress],
|
|
746
|
+
network,
|
|
747
|
+
});
|
|
748
|
+
const guardData = queryResult?.objects?.[0] ?? null;
|
|
749
|
+
if (!guardData) {
|
|
750
|
+
throw new Error(`Guard ${guardAddress} not found on ${network}`);
|
|
751
|
+
}
|
|
752
|
+
const root = guardData.root ?? guardData.data?.root ?? null;
|
|
753
|
+
const table = guardData.table ?? guardData.data?.table ?? [];
|
|
754
|
+
const relies = guardData.relies ?? guardData.data?.relies ?? null;
|
|
755
|
+
const reliesLogicAnd = guardData.relies_logic_and ?? guardData.data?.relies_logic_and ?? null;
|
|
756
|
+
let rely = null;
|
|
757
|
+
if (Array.isArray(relies) && relies.length > 0) {
|
|
758
|
+
rely = {
|
|
759
|
+
guards: relies,
|
|
760
|
+
logic_or: typeof reliesLogicAnd === "boolean" ? !reliesLogicAnd : undefined,
|
|
761
|
+
};
|
|
762
|
+
}
|
|
763
|
+
return {
|
|
764
|
+
root: root,
|
|
765
|
+
table: Array.isArray(table) ? table.map((t) => ({
|
|
766
|
+
identifier: t.identifier,
|
|
767
|
+
name: t.name,
|
|
768
|
+
value_type: t.value_type,
|
|
769
|
+
b_submission: t.b_submission,
|
|
770
|
+
value: t.value,
|
|
771
|
+
})) : [],
|
|
772
|
+
rely,
|
|
773
|
+
};
|
|
774
|
+
}
|
|
775
|
+
function parsePatchOperation(opStr) {
|
|
776
|
+
const parts = opStr.trim().split(/\s+/);
|
|
777
|
+
if (parts.length < 2)
|
|
778
|
+
return null;
|
|
779
|
+
const [cmd, subcmd, ...rest] = parts;
|
|
780
|
+
if (cmd === "add" && subcmd === "node" && rest.length >= 1) {
|
|
781
|
+
return { type: "add_node", args: rest, raw: opStr };
|
|
782
|
+
}
|
|
783
|
+
if (cmd === "remove" && subcmd === "node" && rest.length >= 1) {
|
|
784
|
+
return { type: "remove_node", args: rest, raw: opStr };
|
|
785
|
+
}
|
|
786
|
+
if (cmd === "add" && subcmd === "edge" && rest.length >= 2) {
|
|
787
|
+
return { type: "add_edge", args: rest, raw: opStr };
|
|
788
|
+
}
|
|
789
|
+
if (cmd === "remove" && subcmd === "edge" && rest.length >= 2) {
|
|
790
|
+
return { type: "remove_edge", args: rest, raw: opStr };
|
|
791
|
+
}
|
|
792
|
+
if (cmd === "add" && subcmd === "forward" && rest.length >= 3) {
|
|
793
|
+
return { type: "add_forward", args: rest, raw: opStr };
|
|
794
|
+
}
|
|
795
|
+
if (cmd === "remove" && subcmd === "forward" && rest.length >= 3) {
|
|
796
|
+
return { type: "remove_forward", args: rest, raw: opStr };
|
|
797
|
+
}
|
|
798
|
+
if (cmd === "set" && subcmd === "threshold" && rest.length >= 3) {
|
|
799
|
+
return { type: "set_threshold", args: rest, raw: opStr };
|
|
800
|
+
}
|
|
801
|
+
if (cmd === "set" && subcmd === "guard" && rest.length >= 4) {
|
|
802
|
+
return { type: "set_guard", args: rest, raw: opStr };
|
|
803
|
+
}
|
|
804
|
+
if (cmd === "set" && subcmd === "permission" && rest.length >= 4) {
|
|
805
|
+
return { type: "set_permission", args: rest, raw: opStr };
|
|
806
|
+
}
|
|
807
|
+
if (cmd === "set" && subcmd === "operator" && rest.length >= 4) {
|
|
808
|
+
return { type: "set_operator", args: rest, raw: opStr };
|
|
809
|
+
}
|
|
810
|
+
if (cmd === "set" && subcmd === "weight" && rest.length >= 4) {
|
|
811
|
+
return { type: "set_weight", args: rest, raw: opStr };
|
|
812
|
+
}
|
|
813
|
+
if (cmd === "set" && subcmd === "retained_submission" && rest.length >= 4) {
|
|
814
|
+
return { type: "set_retained_submission", args: rest, raw: opStr };
|
|
815
|
+
}
|
|
816
|
+
if (cmd === "set" && subcmd === "description" && rest.length >= 2) {
|
|
817
|
+
return { type: "set_description", args: rest, raw: opStr };
|
|
818
|
+
}
|
|
819
|
+
return null;
|
|
820
|
+
}
|
|
821
|
+
function applyPatchOperation(op, nodes, edges) {
|
|
822
|
+
switch (op.type) {
|
|
823
|
+
case "add_node": {
|
|
824
|
+
const name = op.args[0];
|
|
825
|
+
if (nodes.some(n => n.name === name)) {
|
|
826
|
+
return { success: false, error: `Node '${name}' already exists` };
|
|
827
|
+
}
|
|
828
|
+
nodes.push({ name, description: null });
|
|
829
|
+
return { success: true };
|
|
830
|
+
}
|
|
831
|
+
case "remove_node": {
|
|
832
|
+
const name = op.args[0];
|
|
833
|
+
const idx = nodes.findIndex(n => n.name === name);
|
|
834
|
+
if (idx === -1) {
|
|
835
|
+
return { success: false, error: `Node '${name}' not found` };
|
|
836
|
+
}
|
|
837
|
+
const hasEdges = edges.some(e => e.from === name || e.to === name);
|
|
838
|
+
if (hasEdges) {
|
|
839
|
+
return { success: false, error: `Node '${name}' has edges — remove them first` };
|
|
840
|
+
}
|
|
841
|
+
nodes.splice(idx, 1);
|
|
842
|
+
return { success: true };
|
|
843
|
+
}
|
|
844
|
+
case "add_edge": {
|
|
845
|
+
const [from, to] = op.args;
|
|
846
|
+
if (!nodes.some(n => n.name === to)) {
|
|
847
|
+
return { success: false, error: `Target node '${to}' not found` };
|
|
848
|
+
}
|
|
849
|
+
if (from !== "" && !nodes.some(n => n.name === from)) {
|
|
850
|
+
return { success: false, error: `Source node '${from}' not found` };
|
|
851
|
+
}
|
|
852
|
+
if (edges.some(e => e.from === from && e.to === to)) {
|
|
853
|
+
return { success: false, error: `Edge '${from}->${to}' already exists` };
|
|
854
|
+
}
|
|
855
|
+
edges.push({ from, to, threshold: 1, forwards: [] });
|
|
856
|
+
return { success: true };
|
|
857
|
+
}
|
|
858
|
+
case "remove_edge": {
|
|
859
|
+
const [from, to] = op.args;
|
|
860
|
+
const idx = edges.findIndex(e => e.from === from && e.to === to);
|
|
861
|
+
if (idx === -1) {
|
|
862
|
+
return { success: false, error: `Edge '${from}->${to}' not found` };
|
|
863
|
+
}
|
|
864
|
+
edges.splice(idx, 1);
|
|
865
|
+
return { success: true };
|
|
866
|
+
}
|
|
867
|
+
case "add_forward": {
|
|
868
|
+
const [from, to, fwdName] = op.args;
|
|
869
|
+
const edge = edges.find(e => e.from === from && e.to === to);
|
|
870
|
+
if (!edge) {
|
|
871
|
+
return { success: false, error: `Edge '${from}->${to}' not found` };
|
|
872
|
+
}
|
|
873
|
+
if (edge.forwards.some(f => f.name === fwdName)) {
|
|
874
|
+
return { success: false, error: `Forward '${fwdName}' already exists on edge '${from}->${to}'` };
|
|
875
|
+
}
|
|
876
|
+
edge.forwards.push({
|
|
877
|
+
name: fwdName,
|
|
878
|
+
weight: 1,
|
|
879
|
+
named_operator: null,
|
|
880
|
+
permission_index: null,
|
|
881
|
+
guard: null,
|
|
882
|
+
retained_submission: null,
|
|
883
|
+
});
|
|
884
|
+
return { success: true };
|
|
885
|
+
}
|
|
886
|
+
case "remove_forward": {
|
|
887
|
+
const [from, to, fwdName] = op.args;
|
|
888
|
+
const edge = edges.find(e => e.from === from && e.to === to);
|
|
889
|
+
if (!edge) {
|
|
890
|
+
return { success: false, error: `Edge '${from}->${to}' not found` };
|
|
891
|
+
}
|
|
892
|
+
const idx = edge.forwards.findIndex(f => f.name === fwdName);
|
|
893
|
+
if (idx === -1) {
|
|
894
|
+
return { success: false, error: `Forward '${fwdName}' not found on edge '${from}->${to}'` };
|
|
895
|
+
}
|
|
896
|
+
edge.forwards.splice(idx, 1);
|
|
897
|
+
return { success: true };
|
|
898
|
+
}
|
|
899
|
+
case "set_threshold": {
|
|
900
|
+
const [from, to, valStr] = op.args;
|
|
901
|
+
const val = parseInt(valStr, 10);
|
|
902
|
+
if (isNaN(val) || val < 1) {
|
|
903
|
+
return { success: false, error: `Invalid threshold value: ${valStr}` };
|
|
904
|
+
}
|
|
905
|
+
const edge = edges.find(e => e.from === from && e.to === to);
|
|
906
|
+
if (!edge) {
|
|
907
|
+
return { success: false, error: `Edge '${from}->${to}' not found` };
|
|
908
|
+
}
|
|
909
|
+
edge.threshold = val;
|
|
910
|
+
return { success: true };
|
|
911
|
+
}
|
|
912
|
+
case "set_guard": {
|
|
913
|
+
const [from, to, fwdName, guardAddr] = op.args;
|
|
914
|
+
const edge = edges.find(e => e.from === from && e.to === to);
|
|
915
|
+
if (!edge) {
|
|
916
|
+
return { success: false, error: `Edge '${from}->${to}' not found` };
|
|
917
|
+
}
|
|
918
|
+
const fwd = edge.forwards.find(f => f.name === fwdName);
|
|
919
|
+
if (!fwd) {
|
|
920
|
+
return { success: false, error: `Forward '${fwdName}' not found on edge '${from}->${to}'` };
|
|
921
|
+
}
|
|
922
|
+
fwd.guard = guardAddr === "none" ? null : guardAddr;
|
|
923
|
+
return { success: true };
|
|
924
|
+
}
|
|
925
|
+
case "set_permission": {
|
|
926
|
+
const [from, to, fwdName, permStr] = op.args;
|
|
927
|
+
const edge = edges.find(e => e.from === from && e.to === to);
|
|
928
|
+
if (!edge) {
|
|
929
|
+
return { success: false, error: `Edge '${from}->${to}' not found` };
|
|
930
|
+
}
|
|
931
|
+
const fwd = edge.forwards.find(f => f.name === fwdName);
|
|
932
|
+
if (!fwd) {
|
|
933
|
+
return { success: false, error: `Forward '${fwdName}' not found on edge '${from}->${to}'` };
|
|
934
|
+
}
|
|
935
|
+
const perm = parseInt(permStr, 10);
|
|
936
|
+
if (isNaN(perm) || perm < 0) {
|
|
937
|
+
return { success: false, error: `Invalid permission index: ${permStr} (must be a non-negative integer)` };
|
|
938
|
+
}
|
|
939
|
+
fwd.permission_index = perm;
|
|
940
|
+
return { success: true };
|
|
941
|
+
}
|
|
942
|
+
case "set_operator": {
|
|
943
|
+
const [from, to, fwdName, ...opRest] = op.args;
|
|
944
|
+
const namedOperator = opRest.join(" ");
|
|
945
|
+
const edge = edges.find(e => e.from === from && e.to === to);
|
|
946
|
+
if (!edge) {
|
|
947
|
+
return { success: false, error: `Edge '${from}->${to}' not found` };
|
|
948
|
+
}
|
|
949
|
+
const fwd = edge.forwards.find(f => f.name === fwdName);
|
|
950
|
+
if (!fwd) {
|
|
951
|
+
return { success: false, error: `Forward '${fwdName}' not found on edge '${from}->${to}'` };
|
|
952
|
+
}
|
|
953
|
+
if (namedOperator === "none") {
|
|
954
|
+
fwd.named_operator = null;
|
|
955
|
+
}
|
|
956
|
+
else {
|
|
957
|
+
fwd.named_operator = namedOperator;
|
|
958
|
+
}
|
|
959
|
+
return { success: true };
|
|
960
|
+
}
|
|
961
|
+
case "set_weight": {
|
|
962
|
+
const [from, to, fwdName, weightStr] = op.args;
|
|
963
|
+
const edge = edges.find(e => e.from === from && e.to === to);
|
|
964
|
+
if (!edge) {
|
|
965
|
+
return { success: false, error: `Edge '${from}->${to}' not found` };
|
|
966
|
+
}
|
|
967
|
+
const fwd = edge.forwards.find(f => f.name === fwdName);
|
|
968
|
+
if (!fwd) {
|
|
969
|
+
return { success: false, error: `Forward '${fwdName}' not found on edge '${from}->${to}'` };
|
|
970
|
+
}
|
|
971
|
+
const weight = parseInt(weightStr, 10);
|
|
972
|
+
if (isNaN(weight) || weight < 1) {
|
|
973
|
+
return { success: false, error: `Invalid weight: ${weightStr} (must be a positive integer)` };
|
|
974
|
+
}
|
|
975
|
+
fwd.weight = weight;
|
|
976
|
+
return { success: true };
|
|
977
|
+
}
|
|
978
|
+
case "set_retained_submission": {
|
|
979
|
+
const [from, to, fwdName, indicesStr] = op.args;
|
|
980
|
+
const edge = edges.find(e => e.from === from && e.to === to);
|
|
981
|
+
if (!edge) {
|
|
982
|
+
return { success: false, error: `Edge '${from}->${to}' not found` };
|
|
983
|
+
}
|
|
984
|
+
const fwd = edge.forwards.find(f => f.name === fwdName);
|
|
985
|
+
if (!fwd) {
|
|
986
|
+
return { success: false, error: `Forward '${fwdName}' not found on edge '${from}->${to}'` };
|
|
987
|
+
}
|
|
988
|
+
if (indicesStr === "none") {
|
|
989
|
+
fwd.retained_submission = null;
|
|
990
|
+
return { success: true };
|
|
991
|
+
}
|
|
992
|
+
const indices = indicesStr.split(",").map(s => {
|
|
993
|
+
const n = parseInt(s.trim(), 10);
|
|
994
|
+
if (isNaN(n) || n < 0)
|
|
995
|
+
return -1;
|
|
996
|
+
return n;
|
|
997
|
+
});
|
|
998
|
+
if (indices.some(n => n < 0)) {
|
|
999
|
+
return { success: false, error: `Invalid retained_submission indices: ${indicesStr} (must be comma-separated non-negative integers or 'none')` };
|
|
1000
|
+
}
|
|
1001
|
+
fwd.retained_submission = indices;
|
|
1002
|
+
return { success: true };
|
|
1003
|
+
}
|
|
1004
|
+
case "set_description": {
|
|
1005
|
+
const [nodeName, ...descParts] = op.args;
|
|
1006
|
+
const node = nodes.find(n => n.name === nodeName);
|
|
1007
|
+
if (!node) {
|
|
1008
|
+
return { success: false, error: `Node '${nodeName}' not found` };
|
|
1009
|
+
}
|
|
1010
|
+
const desc = descParts.join(" ");
|
|
1011
|
+
node.description = desc === "none" ? null : desc;
|
|
1012
|
+
return { success: true };
|
|
1013
|
+
}
|
|
1014
|
+
default:
|
|
1015
|
+
return { success: false, error: `Unknown operation type: ${op.type}` };
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
export async function handlePatchMachineNodes(v) {
|
|
1019
|
+
const projectId = await resolveProjectId(v);
|
|
1020
|
+
const machineAddress = await resolveObjectAddress(v);
|
|
1021
|
+
const operations = v.patch_operations ?? [];
|
|
1022
|
+
if (operations.length === 0) {
|
|
1023
|
+
throw new Error("'patch_operations' is required for patch_machine_nodes (non-empty array)");
|
|
1024
|
+
}
|
|
1025
|
+
const project = await localProject.getProject(projectId);
|
|
1026
|
+
if (!project)
|
|
1027
|
+
throw new Error(`Project not found (id: ${projectId})`);
|
|
1028
|
+
let machineName = null;
|
|
1029
|
+
try {
|
|
1030
|
+
const mark = await LocalMark.Instance().get(machineAddress);
|
|
1031
|
+
machineName = mark?.name ?? null;
|
|
1032
|
+
}
|
|
1033
|
+
catch {
|
|
1034
|
+
}
|
|
1035
|
+
const network = (project.network ?? "testnet");
|
|
1036
|
+
const current = await fetchCurrentMachine(machineAddress, network);
|
|
1037
|
+
const oldNodes = current.nodes.map(n => ({ ...n }));
|
|
1038
|
+
const oldEdges = current.edges.map(e => ({
|
|
1039
|
+
...e,
|
|
1040
|
+
forwards: e.forwards.map(f => ({ ...f })),
|
|
1041
|
+
}));
|
|
1042
|
+
const operationsFailed = [];
|
|
1043
|
+
let operationsApplied = 0;
|
|
1044
|
+
for (const opStr of operations) {
|
|
1045
|
+
const op = parsePatchOperation(opStr);
|
|
1046
|
+
if (!op) {
|
|
1047
|
+
operationsFailed.push({
|
|
1048
|
+
operation: opStr,
|
|
1049
|
+
error: "Invalid operation format. See patch_operations schema for supported formats.",
|
|
1050
|
+
});
|
|
1051
|
+
continue;
|
|
1052
|
+
}
|
|
1053
|
+
const result = applyPatchOperation(op, current.nodes, current.edges);
|
|
1054
|
+
if (result.success) {
|
|
1055
|
+
operationsApplied++;
|
|
1056
|
+
}
|
|
1057
|
+
else {
|
|
1058
|
+
operationsFailed.push({
|
|
1059
|
+
operation: opStr,
|
|
1060
|
+
error: result.error ?? "Unknown error",
|
|
1061
|
+
});
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
const diff = diffMachine(oldNodes, oldEdges, current.nodes, current.edges);
|
|
1065
|
+
const validation = validateMachine(current.nodes, current.edges);
|
|
1066
|
+
const blocking_errors = [];
|
|
1067
|
+
for (const fail of operationsFailed) {
|
|
1068
|
+
blocking_errors.push({
|
|
1069
|
+
id: "E-OP",
|
|
1070
|
+
description: `Operation '${fail.operation}' failed: ${fail.error}`,
|
|
1071
|
+
impact: "This operation was not applied. The patch cannot be executed on-chain until all operations succeed.",
|
|
1072
|
+
});
|
|
1073
|
+
}
|
|
1074
|
+
for (const be of validation.blocking_errors) {
|
|
1075
|
+
blocking_errors.push(be);
|
|
1076
|
+
}
|
|
1077
|
+
const canApply = blocking_errors.length === 0;
|
|
1078
|
+
const preparedCall = canApply
|
|
1079
|
+
? prepareMachineCall(machineName, machineAddress, current.nodes, current.edges)
|
|
1080
|
+
: null;
|
|
1081
|
+
const summary = `Patch: ${operationsApplied} applied, ${operationsFailed.length} failed. ${diff.summary}.`;
|
|
1082
|
+
return {
|
|
1083
|
+
action: "patch_machine_nodes",
|
|
1084
|
+
machine_address: machineAddress,
|
|
1085
|
+
machine_name: machineName,
|
|
1086
|
+
operations_applied: operationsApplied,
|
|
1087
|
+
operations_failed: operationsFailed,
|
|
1088
|
+
patched_nodes: current.nodes,
|
|
1089
|
+
patched_edges: current.edges,
|
|
1090
|
+
diff,
|
|
1091
|
+
warnings: validation.warnings,
|
|
1092
|
+
blocking_errors: blocking_errors.length > 0 ? blocking_errors : [],
|
|
1093
|
+
can_apply: canApply,
|
|
1094
|
+
prepared_call: preparedCall,
|
|
1095
|
+
summary,
|
|
1096
|
+
};
|
|
1097
|
+
}
|
|
1098
|
+
function parseGuardPatchOperation(opStr) {
|
|
1099
|
+
const parts = opStr.trim().split(/\s+/);
|
|
1100
|
+
if (parts.length < 2)
|
|
1101
|
+
return null;
|
|
1102
|
+
const [cmd, subcmd, ...rest] = parts;
|
|
1103
|
+
if (cmd === "add" && subcmd === "table" && rest.length >= 4) {
|
|
1104
|
+
return { type: "add_table", args: rest, raw: opStr };
|
|
1105
|
+
}
|
|
1106
|
+
if (cmd === "remove" && subcmd === "table" && rest.length >= 1) {
|
|
1107
|
+
return { type: "remove_table", args: rest, raw: opStr };
|
|
1108
|
+
}
|
|
1109
|
+
if (cmd === "set" && subcmd === "table_value" && rest.length >= 2) {
|
|
1110
|
+
return { type: "set_table_value", args: rest, raw: opStr };
|
|
1111
|
+
}
|
|
1112
|
+
if (cmd === "set" && subcmd === "table_name" && rest.length >= 2) {
|
|
1113
|
+
return { type: "set_table_name", args: rest, raw: opStr };
|
|
1114
|
+
}
|
|
1115
|
+
if (cmd === "set" && subcmd === "table_submission" && rest.length >= 2) {
|
|
1116
|
+
return { type: "set_table_submission", args: rest, raw: opStr };
|
|
1117
|
+
}
|
|
1118
|
+
if (cmd === "set" && subcmd === "root" && rest.length >= 1) {
|
|
1119
|
+
return { type: "set_root", args: rest, raw: opStr };
|
|
1120
|
+
}
|
|
1121
|
+
if (cmd === "set" && subcmd === "rely" && rest.length >= 1) {
|
|
1122
|
+
return { type: "set_rely", args: rest, raw: opStr };
|
|
1123
|
+
}
|
|
1124
|
+
return null;
|
|
1125
|
+
}
|
|
1126
|
+
function tryParseJSON(s) {
|
|
1127
|
+
try {
|
|
1128
|
+
return JSON.parse(s);
|
|
1129
|
+
}
|
|
1130
|
+
catch {
|
|
1131
|
+
return undefined;
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
function applyGuardPatchOperation(op, context) {
|
|
1135
|
+
switch (op.type) {
|
|
1136
|
+
case "add_table": {
|
|
1137
|
+
const [idStr, name, valueTypeStr, bSubStr, ...valueParts] = op.args;
|
|
1138
|
+
const identifier = parseInt(idStr, 10);
|
|
1139
|
+
if (isNaN(identifier) || identifier < 0) {
|
|
1140
|
+
return { success: false, error: `Invalid table identifier: ${idStr} (must be a non-negative integer)` };
|
|
1141
|
+
}
|
|
1142
|
+
if (context.table.some(t => t.identifier === identifier)) {
|
|
1143
|
+
return { success: false, error: `Table identifier ${identifier} already exists` };
|
|
1144
|
+
}
|
|
1145
|
+
const b_submission = bSubStr === "true";
|
|
1146
|
+
const value_type = /^[0-9]+$/.test(valueTypeStr)
|
|
1147
|
+
? parseInt(valueTypeStr, 10)
|
|
1148
|
+
: valueTypeStr;
|
|
1149
|
+
let value = undefined;
|
|
1150
|
+
if (valueParts.length > 0) {
|
|
1151
|
+
const valueStr = valueParts.join(" ");
|
|
1152
|
+
if (valueStr !== "none") {
|
|
1153
|
+
value = tryParseJSON(valueStr);
|
|
1154
|
+
if (value === undefined) {
|
|
1155
|
+
value = valueStr;
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
context.table.push({
|
|
1160
|
+
identifier,
|
|
1161
|
+
name: name === "none" ? undefined : name,
|
|
1162
|
+
value_type,
|
|
1163
|
+
b_submission,
|
|
1164
|
+
value,
|
|
1165
|
+
});
|
|
1166
|
+
return { success: true };
|
|
1167
|
+
}
|
|
1168
|
+
case "remove_table": {
|
|
1169
|
+
const [idStr] = op.args;
|
|
1170
|
+
const identifier = parseInt(idStr, 10);
|
|
1171
|
+
if (isNaN(identifier)) {
|
|
1172
|
+
return { success: false, error: `Invalid table identifier: ${idStr}` };
|
|
1173
|
+
}
|
|
1174
|
+
const idx = context.table.findIndex(t => t.identifier === identifier);
|
|
1175
|
+
if (idx === -1) {
|
|
1176
|
+
return { success: false, error: `Table identifier ${identifier} not found` };
|
|
1177
|
+
}
|
|
1178
|
+
context.table.splice(idx, 1);
|
|
1179
|
+
return { success: true };
|
|
1180
|
+
}
|
|
1181
|
+
case "set_table_value": {
|
|
1182
|
+
const [idStr, ...valueParts] = op.args;
|
|
1183
|
+
const identifier = parseInt(idStr, 10);
|
|
1184
|
+
if (isNaN(identifier)) {
|
|
1185
|
+
return { success: false, error: `Invalid table identifier: ${idStr}` };
|
|
1186
|
+
}
|
|
1187
|
+
const entry = context.table.find(t => t.identifier === identifier);
|
|
1188
|
+
if (!entry) {
|
|
1189
|
+
return { success: false, error: `Table identifier ${identifier} not found` };
|
|
1190
|
+
}
|
|
1191
|
+
const valueStr = valueParts.join(" ");
|
|
1192
|
+
if (valueStr === "none") {
|
|
1193
|
+
entry.value = undefined;
|
|
1194
|
+
}
|
|
1195
|
+
else {
|
|
1196
|
+
const parsed = tryParseJSON(valueStr);
|
|
1197
|
+
entry.value = parsed !== undefined ? parsed : valueStr;
|
|
1198
|
+
}
|
|
1199
|
+
return { success: true };
|
|
1200
|
+
}
|
|
1201
|
+
case "set_table_name": {
|
|
1202
|
+
const [idStr, name, ...rest] = op.args;
|
|
1203
|
+
const identifier = parseInt(idStr, 10);
|
|
1204
|
+
if (isNaN(identifier)) {
|
|
1205
|
+
return { success: false, error: `Invalid table identifier: ${idStr}` };
|
|
1206
|
+
}
|
|
1207
|
+
const entry = context.table.find(t => t.identifier === identifier);
|
|
1208
|
+
if (!entry) {
|
|
1209
|
+
return { success: false, error: `Table identifier ${identifier} not found` };
|
|
1210
|
+
}
|
|
1211
|
+
const fullName = rest.length > 0 ? [name, ...rest].join(" ") : name;
|
|
1212
|
+
entry.name = fullName === "none" ? undefined : fullName;
|
|
1213
|
+
return { success: true };
|
|
1214
|
+
}
|
|
1215
|
+
case "set_table_submission": {
|
|
1216
|
+
const [idStr, bSubStr] = op.args;
|
|
1217
|
+
const identifier = parseInt(idStr, 10);
|
|
1218
|
+
if (isNaN(identifier)) {
|
|
1219
|
+
return { success: false, error: `Invalid table identifier: ${idStr}` };
|
|
1220
|
+
}
|
|
1221
|
+
const entry = context.table.find(t => t.identifier === identifier);
|
|
1222
|
+
if (!entry) {
|
|
1223
|
+
return { success: false, error: `Table identifier ${identifier} not found` };
|
|
1224
|
+
}
|
|
1225
|
+
if (bSubStr !== "true" && bSubStr !== "false") {
|
|
1226
|
+
return { success: false, error: `Invalid b_submission value: ${bSubStr} (must be 'true' or 'false')` };
|
|
1227
|
+
}
|
|
1228
|
+
entry.b_submission = bSubStr === "true";
|
|
1229
|
+
return { success: true };
|
|
1230
|
+
}
|
|
1231
|
+
case "set_root": {
|
|
1232
|
+
const jsonStr = op.args.join(" ");
|
|
1233
|
+
const newRoot = tryParseJSON(jsonStr);
|
|
1234
|
+
if (newRoot === undefined || typeof newRoot !== "object" || newRoot === null) {
|
|
1235
|
+
return { success: false, error: `Invalid root JSON: '${jsonStr.slice(0, 80)}' (must be a valid JSON object)` };
|
|
1236
|
+
}
|
|
1237
|
+
if (typeof newRoot.type !== "string") {
|
|
1238
|
+
return { success: false, error: `Root JSON must have a 'type' field (string). Got: ${JSON.stringify(Object.keys(newRoot)).slice(0, 80)}` };
|
|
1239
|
+
}
|
|
1240
|
+
return { success: true, newRoot: newRoot };
|
|
1241
|
+
}
|
|
1242
|
+
case "set_rely": {
|
|
1243
|
+
const [relyStr] = op.args;
|
|
1244
|
+
if (relyStr === "none") {
|
|
1245
|
+
context.rely = null;
|
|
1246
|
+
return { success: true };
|
|
1247
|
+
}
|
|
1248
|
+
const guards = relyStr.split(",").map(s => s.trim()).filter(s => s.length > 0);
|
|
1249
|
+
if (guards.length === 0) {
|
|
1250
|
+
return { success: false, error: `Invalid rely value: '${relyStr}' (expected 'none' or comma-separated addresses)` };
|
|
1251
|
+
}
|
|
1252
|
+
context.rely = {
|
|
1253
|
+
guards,
|
|
1254
|
+
logic_or: context.rely?.logic_or ?? false,
|
|
1255
|
+
};
|
|
1256
|
+
return { success: true };
|
|
1257
|
+
}
|
|
1258
|
+
default:
|
|
1259
|
+
return { success: false, error: `Unknown Guard patch operation type: ${op.type}` };
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
export async function handlePatchGuardTree(v) {
|
|
1263
|
+
const projectId = await resolveProjectId(v);
|
|
1264
|
+
const guardAddress = await resolveObjectAddress(v);
|
|
1265
|
+
const operations = v.patch_operations ?? [];
|
|
1266
|
+
if (operations.length === 0) {
|
|
1267
|
+
throw new Error("'patch_operations' is required for patch_guard_tree (non-empty array)");
|
|
1268
|
+
}
|
|
1269
|
+
const project = await localProject.getProject(projectId);
|
|
1270
|
+
if (!project)
|
|
1271
|
+
throw new Error(`Project not found (id: ${projectId})`);
|
|
1272
|
+
let guardName = null;
|
|
1273
|
+
try {
|
|
1274
|
+
const mark = await LocalMark.Instance().get(guardAddress);
|
|
1275
|
+
guardName = mark?.name ?? null;
|
|
1276
|
+
}
|
|
1277
|
+
catch {
|
|
1278
|
+
}
|
|
1279
|
+
const network = (project.network ?? "testnet");
|
|
1280
|
+
const current = await fetchCurrentGuard(guardAddress, network);
|
|
1281
|
+
const oldRoot = JSON.parse(JSON.stringify(current.root));
|
|
1282
|
+
const oldTable = current.table.map(t => ({ ...t, value: t.value !== undefined ? JSON.parse(JSON.stringify(t.value)) : undefined }));
|
|
1283
|
+
const oldRely = current.rely ? { ...current.rely, guards: [...current.rely.guards] } : null;
|
|
1284
|
+
const operationsFailed = [];
|
|
1285
|
+
let operationsApplied = 0;
|
|
1286
|
+
let newRoot = current.root;
|
|
1287
|
+
for (const opStr of operations) {
|
|
1288
|
+
const op = parseGuardPatchOperation(opStr);
|
|
1289
|
+
if (!op) {
|
|
1290
|
+
operationsFailed.push({
|
|
1291
|
+
operation: opStr,
|
|
1292
|
+
error: "Invalid Guard patch operation format. See patch_operations schema for supported formats.",
|
|
1293
|
+
});
|
|
1294
|
+
continue;
|
|
1295
|
+
}
|
|
1296
|
+
const result = applyGuardPatchOperation(op, {
|
|
1297
|
+
root: newRoot,
|
|
1298
|
+
table: current.table,
|
|
1299
|
+
rely: current.rely,
|
|
1300
|
+
});
|
|
1301
|
+
if (result.success) {
|
|
1302
|
+
operationsApplied++;
|
|
1303
|
+
if (result.newRoot) {
|
|
1304
|
+
newRoot = result.newRoot;
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
else {
|
|
1308
|
+
operationsFailed.push({
|
|
1309
|
+
operation: opStr,
|
|
1310
|
+
error: result.error ?? "Unknown error",
|
|
1311
|
+
});
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
if (current.rely && Array.isArray(current.rely.guards)) {
|
|
1315
|
+
const resolved = [];
|
|
1316
|
+
for (const g of current.rely.guards) {
|
|
1317
|
+
if (/^0x[0-9a-fA-F]{32,64}$/.test(g)) {
|
|
1318
|
+
resolved.push(g);
|
|
1319
|
+
}
|
|
1320
|
+
else {
|
|
1321
|
+
try {
|
|
1322
|
+
const mark = await LocalMark.Instance().get(g);
|
|
1323
|
+
if (mark?.address) {
|
|
1324
|
+
resolved.push(mark.address);
|
|
1325
|
+
}
|
|
1326
|
+
else {
|
|
1327
|
+
resolved.push(g);
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
catch {
|
|
1331
|
+
resolved.push(g);
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
current.rely.guards = resolved;
|
|
1336
|
+
}
|
|
1337
|
+
const diff = diffGuard(oldRoot, newRoot, oldTable, current.table);
|
|
1338
|
+
const validation = validateGuard(newRoot, current.table);
|
|
1339
|
+
const blocking_errors = [];
|
|
1340
|
+
for (const fail of operationsFailed) {
|
|
1341
|
+
blocking_errors.push({
|
|
1342
|
+
id: "E-OP",
|
|
1343
|
+
description: `Operation '${fail.operation}' failed: ${fail.error}`,
|
|
1344
|
+
impact: "This operation was not applied. The patch cannot be executed on-chain until all operations succeed.",
|
|
1345
|
+
});
|
|
1346
|
+
}
|
|
1347
|
+
for (const be of validation.blocking_errors) {
|
|
1348
|
+
blocking_errors.push(be);
|
|
1349
|
+
}
|
|
1350
|
+
const canApply = blocking_errors.length === 0;
|
|
1351
|
+
const preparedCall = canApply
|
|
1352
|
+
? prepareGuardCall(guardName, guardAddress, newRoot, current.table, current.rely)
|
|
1353
|
+
: null;
|
|
1354
|
+
const summary = `Guard patch: ${operationsApplied} applied, ${operationsFailed.length} failed. ${diff.summary}.`;
|
|
1355
|
+
return {
|
|
1356
|
+
action: "patch_guard_tree",
|
|
1357
|
+
guard_address: guardAddress,
|
|
1358
|
+
guard_name: guardName,
|
|
1359
|
+
operations_applied: operationsApplied,
|
|
1360
|
+
operations_failed: operationsFailed,
|
|
1361
|
+
patched_root: newRoot,
|
|
1362
|
+
patched_table: current.table,
|
|
1363
|
+
patched_rely: current.rely,
|
|
1364
|
+
diff,
|
|
1365
|
+
warnings: validation.warnings,
|
|
1366
|
+
blocking_errors: blocking_errors.length > 0 ? blocking_errors : [],
|
|
1367
|
+
can_apply: canApply,
|
|
1368
|
+
prepared_call: preparedCall,
|
|
1369
|
+
summary,
|
|
1370
|
+
};
|
|
1371
|
+
}
|