cladogram 0.6.0-beta.2 → 0.6.0-beta.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.
@@ -1,12 +1,17 @@
1
1
  /**
2
2
  * Clado Spatial Canvas Tools for Pi 1.x SDK
3
3
  *
4
- * 将 Clado 的空间画布读写、便签/画布组件、相机聚焦与交互式决策卡
5
- * 以原生 Pi ToolDefinition 暴露给每一个 Pi AgentSession。
6
- * 无任何阻塞式权限确认弹窗(遵循 Pi 原生流畅执行哲学)。
4
+ * 将 Clado 的空间画布读写、渲染拓扑树读取(clado_graph)、模板读取、
5
+ * 便签/画布组件、相机聚焦与交互式决策卡以原生 Pi ToolDefinition 暴露给每一个 Pi AgentSession。
6
+ *
7
+ * 关键保障:
8
+ * 1. 所有工具失败均返回 isError: true 与完整结构化诊断 + 修复建议,确保模型与前端都能明确感知失败并自我修复。
9
+ * 2. 所有写操作自动附带渲染后画布拓扑体检(graphCheck),孤立卡/断链/语法错误第一时间反馈给模型。
10
+ * 3. 提供 clado_graph 工具,像浏览器 DOM/Accessibility Tree 一样读取 Clado 实际连出来的卡片网络与节点树。
7
11
  */
8
12
 
9
13
  import { defineTool } from '@earendil-works/pi-coding-agent';
14
+ import { splitFrontMatter } from '../core/parse.js';
10
15
  import { deleteCanvasObject, listCanvasObjects, saveCanvasObject } from '../workspace/objects.js';
11
16
 
12
17
  function textResult(data, details = undefined) {
@@ -17,6 +22,133 @@ function textResult(data, details = undefined) {
17
22
  };
18
23
  }
19
24
 
25
+ function buildErrorHint(toolName, err) {
26
+ const code = err?.details?.code || '';
27
+ const status = err?.status || 0;
28
+ const msg = String(err?.message || '');
29
+ if (toolName === 'clado_create' && status === 409) {
30
+ return '该画布文件已存在:如需重写整张画布请调用 clado_update,如需局部增删改卡片请调用 clado_nodes。';
31
+ }
32
+ if (code === 'FILE_VERSION_CONFLICT' || code === 'NODE_VERSION_CONFLICT' || code === 'VERSION_CONFLICT') {
33
+ return '目标文档或节点已变更:请先调用 clado_read 或 clado_graph 获取最新 version / nodeVersion 后重试。';
34
+ }
35
+ if (code === 'WRITE_BASE_REQUIRED') {
36
+ return '此操作需要传入 expectedFileVersion 或 expectedNodeVersion(可先通过 clado_read 读取)。';
37
+ }
38
+ if (code === 'AMBIGUOUS_LINK_TARGET') {
39
+ return '目标标题在文档中重复导致歧义:请使用唯一的卡片标题或为目标行添加唯一语义 Tag(如 [说明]{#unique-id .blue}),再连到 #unique-id。';
40
+ }
41
+ if (code === 'ANCHOR_AMBIGUOUS' || code === 'ANCHOR_NOT_FOUND') {
42
+ return '正文锚点不存在或不唯一:请调用 clado_read 查看当前精确原文后再传更完整的唯一 anchor。';
43
+ }
44
+ if (status === 404 || msg.includes('不存在')) {
45
+ return '目标文件或节点不存在:请先用 clado_list 确认文件名,或用 clado_graph / clado_read 确认准确的节点标题路径数组。';
46
+ }
47
+ if (status === 422) {
48
+ return '文档结构校验未通过(未保存):请根据上方 diagnostics 中的行号与错误码修正 Markdown 语法(如闭合代码块、修复重复标题或重复 Tag ID)后重新提交。';
49
+ }
50
+ return '请检查上方错误信息与参数格式,修正后重试,切勿忽略失败直接向用户宣称成功。';
51
+ }
52
+
53
+ function formatDiagnosticsLines(diags) {
54
+ if (!Array.isArray(diags) || !diags.length) return [];
55
+ const relevant = diags.filter(d => d && (d.severity === 'error' || d.severity === 'warn')).slice(0, 12);
56
+ return relevant.map(d => {
57
+ const loc = [d.path, d.line ? `L${d.line}` : ''].filter(Boolean).join(':');
58
+ const hint = d.hint ? `(建议:${d.hint})` : '';
59
+ return ` - [${String(d.severity || 'error').toUpperCase()}] ${d.code || 'DIAG'}${loc ? ' @ ' + loc : ''}: ${d.message || ''}${hint}`;
60
+ });
61
+ }
62
+
63
+ function errorResult(toolName, err, customHint = '') {
64
+ const message = err instanceof Error ? err.message : String(err || '未知错误');
65
+ const status = err?.status || 500;
66
+ const code = err?.details?.code || 'CLADO_TOOL_ERROR';
67
+ const lines = [
68
+ `[TOOL_ERROR] ${toolName} 执行失败 (status=${status}, code=${code}): ${message}`,
69
+ ];
70
+ if (err?.details?.file) lines.push(`目标文件: ${err.details.file}`);
71
+ if (Array.isArray(err?.details?.node)) lines.push(`目标节点: ${JSON.stringify(err.details.node)}`);
72
+ if (err?.details?.operationIndex !== undefined) lines.push(`失败步骤序号 (operationIndex): ${err.details.operationIndex}`);
73
+ if (err?.details?.currentVersion) lines.push(`当前最新版本 (currentVersion): ${err.details.currentVersion}`);
74
+
75
+ const diagLines = [
76
+ ...formatDiagnosticsLines(err?.diagnostics),
77
+ ...formatDiagnosticsLines(err?.details?.diagnostics),
78
+ ...formatDiagnosticsLines(err?.details?.previewDiagnostics),
79
+ ];
80
+ const uniqueDiagLines = [...new Set(diagLines)].slice(0, 14);
81
+ if (uniqueDiagLines.length) {
82
+ lines.push('诊断详情:');
83
+ lines.push(...uniqueDiagLines);
84
+ }
85
+ lines.push(`修复建议: ${customHint || buildErrorHint(toolName, err)}`);
86
+
87
+ return {
88
+ isError: true,
89
+ content: [{ type: 'text', text: lines.join('\n') }],
90
+ details: {
91
+ ok: false,
92
+ tool: toolName,
93
+ error: {
94
+ message,
95
+ status,
96
+ code,
97
+ ...(err?.details ? { details: err.details } : {}),
98
+ ...(err?.diagnostics?.length ? { diagnostics: err.diagnostics } : {}),
99
+ },
100
+ },
101
+ };
102
+ }
103
+
104
+ function summarizeGraphCheck(graph) {
105
+ if (!graph) return null;
106
+ const s = graph.summary || {};
107
+ const isolated = graph.isolatedCards || [];
108
+ const unresolved = graph.unresolvedLinks || [];
109
+ const backEdges = graph.backEdges || [];
110
+ const overLinkedCards = graph.overLinkedCards || [];
111
+ const otherErrors = (graph.diagnostics || []).filter(d => d.severity === 'error' && d.code !== 'MD_CARD_ISOLATED');
112
+ const issues = [];
113
+ if (backEdges.length) {
114
+ issues.push(`反向回环/尾连头(${backEdges.length}): ${backEdges.slice(0, 5).map(e => `${e.from} -> ${e.to}`).join('、')}`);
115
+ }
116
+ if (isolated.length) issues.push(`孤立卡片(${isolated.length}): ${isolated.join('、')}`);
117
+ if (unresolved.length) {
118
+ issues.push(`未解析断链(${unresolved.length}): ${unresolved.slice(0, 5).map(u => `[${u.label}](${u.href})@L${u.line}`).join('、')}`);
119
+ }
120
+ if (otherErrors.length) {
121
+ issues.push(`结构错误(${otherErrors.length}): ${otherErrors.slice(0, 5).map(e => `${e.code}@L${e.line ?? '?'}:${e.message}`).join(';')}`);
122
+ }
123
+ const designWarnings = [];
124
+ if (overLinkedCards.length) {
125
+ designWarnings.push(`单卡出度过高(${overLinkedCards.map(c => `${c.title}:${c.outDegree}条`).join('、')}),请克制连线(建议单卡 1–3 条、最多 4 条)`);
126
+ }
127
+ if (s.isOverDense) {
128
+ designWarnings.push(`跨卡连线过密(${s.crossCardEdgeCount}条/${s.cardCount}卡,密度 ${s.edgeDensity}),请删除概念关联型或跨层捷径连线,保持顺滑从左到右的单向流`);
129
+ }
130
+ return {
131
+ file: graph.file,
132
+ version: graph.version,
133
+ healthy: Boolean(s.healthy),
134
+ cardCount: s.cardCount ?? 0,
135
+ crossCardEdgeCount: s.crossCardEdgeCount ?? 0,
136
+ tagCount: s.tagCount ?? 0,
137
+ networkShape: s.networkShape || 'unknown',
138
+ columns: graph.columns || [],
139
+ isolatedCards: isolated,
140
+ unresolvedLinks: unresolved,
141
+ backEdges,
142
+ overLinkedCards,
143
+ errorCount: s.errorCount ?? 0,
144
+ warningCount: s.warningCount ?? 0,
145
+ ...(designWarnings.length ? { designWarnings } : {}),
146
+ ...(issues.length
147
+ ? { actionRequired: `⚠️ 画布拓扑体检未通过:${issues.join(';')}。请立即调用 clado_graph 查看详细连线并修复(严禁反向回环、孤立卡与断链),确保卡片形成从左到右顺滑的单向有向无环网(DAG)后再汇报!` }
148
+ : { statusNote: `画布拓扑健康:${s.cardCount ?? 0} 张卡片、${s.crossCardEdgeCount ?? 0} 条跨卡连线、0 反向回环、0 孤立卡、0 断链。` }),
149
+ };
150
+ }
151
+
20
152
  export function createCladoPiTools({
21
153
  workspace,
22
154
  stateDir,
@@ -30,134 +162,315 @@ export function createCladoPiTools({
30
162
  return workspaceService(tool, { workspace, ...input });
31
163
  };
32
164
 
165
+ const inspectGraphCheck = async file => {
166
+ if (!file) return null;
167
+ try {
168
+ const g = await runMcp('clado_documents', { action: 'read', file, view: 'graph' });
169
+ return summarizeGraphCheck(g);
170
+ } catch {
171
+ return null;
172
+ }
173
+ };
174
+
175
+ const currentFileVersion = async file => {
176
+ if (!file) return undefined;
177
+ try {
178
+ const summary = await runMcp('clado_documents', { action: 'read', file, view: 'summary' });
179
+ return summary?.version;
180
+ } catch {
181
+ return undefined;
182
+ }
183
+ };
184
+
33
185
  return [
34
186
  defineTool({
35
187
  name: 'clado_list',
36
188
  label: '列出画布',
37
- description: '列出当前 Clado 工作区中的所有空间画布(.md/.mdc 文档)及卡片数量。',
189
+ description: '列出当前 Clado 工作区中的所有空间画布(.md/.mdc 文档)、卡片数量与诊断摘要。',
38
190
  promptSnippet: '列出工作区所有 Clado 画布文档',
39
191
  parameters: {
40
192
  type: 'object',
41
- properties: {},
193
+ properties: {
194
+ query: { type: 'string', description: '可选:按文件名或正文关键字过滤' },
195
+ },
42
196
  },
43
- async execute() {
44
- const res = await runMcp('clado_documents', { action: 'list' });
45
- return textResult(res);
197
+ async execute(_id, params = {}) {
198
+ try {
199
+ const res = await runMcp('clado_documents', {
200
+ action: 'list',
201
+ ...(params.query ? { query: params.query } : {}),
202
+ });
203
+ return textResult(res);
204
+ } catch (err) {
205
+ return errorResult('clado_list', err);
206
+ }
207
+ },
208
+ }),
209
+
210
+ defineTool({
211
+ name: 'clado_graph',
212
+ label: '读取画布拓扑树',
213
+ description: '像浏览器读取 DOM 树一样读取 Clado 画布实际渲染出来的「卡片模式网状拓扑与节点树」:返回从左到右列布局、端到端调用链路、跨卡连线明细、完整卡片/小节/语义 Tag 树、孤立卡片清单、未解析断链和诊断结果。写完或修改画布后强烈建议调用此工具复核连线质量。',
214
+ promptSnippet: '读取画布实际连出来的卡片网络、列布局、语义 Tag、孤立卡与断链(Clado 的 DOM 树)',
215
+ parameters: {
216
+ type: 'object',
217
+ properties: {
218
+ file: { type: 'string', description: '可选:指定画布文件名(如 arch.md);省略时返回整个工作区所有画布的拓扑总览与跨文档连线。' },
219
+ },
220
+ },
221
+ async execute(_id, params = {}) {
222
+ try {
223
+ const res = params.file
224
+ ? await runMcp('clado_documents', { action: 'read', file: params.file, view: 'graph' })
225
+ : await runMcp('clado_workspace', { action: 'graph' });
226
+ const text = res.treeText || JSON.stringify(res, null, 2);
227
+ return textResult(text, res);
228
+ } catch (err) {
229
+ return errorResult('clado_graph', err);
230
+ }
231
+ },
232
+ }),
233
+
234
+ defineTool({
235
+ name: 'clado_templates',
236
+ label: '读取画布模板',
237
+ description: '列出当前工作区可用的 Clado 画布模板(如 call-chain、business-flow、requirement-overview、data-design、test-cases、system-state、mind-expansion),或读取指定模板的写作规范与约束。',
238
+ promptSnippet: '列出或读取 Clado 内置/项目画布模板规范',
239
+ parameters: {
240
+ type: 'object',
241
+ properties: {
242
+ action: { type: 'string', enum: ['list', 'read'], description: '默认 list' },
243
+ templateId: { type: 'string', description: 'action 为 read 时必填,例如 call-chain / business-flow / data-design / requirement-overview / test-cases' },
244
+ },
245
+ },
246
+ async execute(_id, params = {}) {
247
+ try {
248
+ const action = params.action === 'read' ? 'read' : 'list';
249
+ const res = await runMcp('clado_templates', {
250
+ action,
251
+ ...(action === 'read' ? { templateId: params.templateId, view: 'prompt' } : {}),
252
+ });
253
+ return textResult(res);
254
+ } catch (err) {
255
+ return errorResult('clado_templates', err);
256
+ }
46
257
  },
47
258
  }),
48
259
 
49
260
  defineTool({
50
261
  name: 'clado_read',
51
262
  label: '读取画布',
52
- description: '读取指定画布的完整结构(卡片列表、标题路径、正文、语义标签与连线关系)。',
53
- promptSnippet: '读取 Clado 画布的卡片、标签与连线结构',
263
+ description: '读取指定画布的内容与结构(含 version、节点列表、正文或源码),并附带简要拓扑状态。',
264
+ promptSnippet: '读取 Clado 画布的正文、节点路径与版本号',
54
265
  parameters: {
55
266
  type: 'object',
56
267
  properties: {
57
268
  file: { type: 'string', description: '画布相对路径,如 payment-arch.md' },
58
- view: { type: 'string', enum: ['outline', 'full'], description: 'outline 仅目录结构,full 返回完整卡片正文' },
269
+ view: { type: 'string', enum: ['full', 'nodes', 'source', 'summary', 'graph', 'outline'], description: '默认 full;nodes/outline 仅节点树,source 原始文本,summary 概要,graph 拓扑树快照' },
59
270
  },
60
271
  required: ['file'],
61
272
  },
62
273
  async execute(_id, params) {
63
- const res = await runMcp('clado_documents', {
64
- action: 'read',
65
- file: params.file,
66
- includeContent: params.view !== 'outline',
67
- });
68
- return textResult(res);
274
+ try {
275
+ const mappedView = params.view === 'outline' ? 'nodes' : (params.view || 'full');
276
+ const res = await runMcp('clado_documents', {
277
+ action: 'read',
278
+ file: params.file,
279
+ view: mappedView,
280
+ });
281
+ if (mappedView === 'graph') {
282
+ return textResult(res.treeText || JSON.stringify(res, null, 2), res);
283
+ }
284
+ const graphCheck = await inspectGraphCheck(params.file);
285
+ return textResult({ ...res, ...(graphCheck ? { graphCheck } : {}) });
286
+ } catch (err) {
287
+ return errorResult('clado_read', err);
288
+ }
69
289
  },
70
290
  }),
71
291
 
72
292
  defineTool({
73
293
  name: 'clado_create',
74
294
  label: '新建画布',
75
- description: '在当前工作区创建一张新的 Clado 空间画布文档(Markdown 格式,支持卡片标题、语义标签与卡片连线)。',
76
- promptSnippet: '新建一张 Clado 空间画布文档',
295
+ description: '在当前工作区一次性创建一张完整的 Clado 空间画布文档(.md 或 .mdc)。请先规划好 3–5 列从左到右的单向流,一次性写出全部 # L1 卡片、正文与克制的正向跨卡内链 [文字](目标卡片标题) / [文字](#tagId)——不要逐张创建空卡后再乱补线,严禁尾连头反向回环,单卡出度建议 1–3 条。写入后自动返回渲染拓扑体检 graphCheck。',
296
+ promptSnippet: '一次性新建完整的单向流 Clado 空间画布文档并返回拓扑体检',
77
297
  parameters: {
78
298
  type: 'object',
79
299
  properties: {
80
300
  file: { type: 'string', description: '新画布文件名(如 arch-overview.md)' },
81
301
  title: { type: 'string', description: '可选:画布标题(留空将自动从首行 # 标题或文件名推导)' },
82
- templateId: { type: 'string', description: '可选:模板 ID(留空自动选用工作区默认模板)' },
83
- content: { type: 'string', description: 'Markdown 正文(支持 # 卡片标题、## 子节与语义标签/连线)' },
302
+ templateId: { type: 'string', description: '可选:模板 ID(如 call-chain / business-flow / requirement-overview / data-design / test-cases / system-state / mind-expansion)' },
303
+ content: { type: 'string', description: 'Markdown 正文(不要包含 front matter;使用 # 卡片、## 子节、语义 Tag {#id .color} 与克制的正向跨卡内链 [文字](目标卡片标题) 或 [文字](#tagId))' },
84
304
  },
85
305
  required: ['file', 'content'],
86
306
  },
87
307
  async execute(_id, params) {
88
- const rawBody = String(params.content || '').replace(/^\uFEFF/, '');
89
- const source = rawBody.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '');
90
- const headingMatch = source.match(/^#\s+(.+)$/m);
91
- const title = String(params.title || headingMatch?.[1] || params.file.replace(/\.mdc?$/i, '')).trim().slice(0, 80);
92
- let templateId = params.templateId;
93
- if (!templateId) {
94
- try {
95
- const tplList = await runMcp('clado_templates', { action: 'list' });
96
- templateId = tplList?.templates?.[0]?.id || 'architecture';
97
- } catch {
98
- templateId = 'architecture';
308
+ try {
309
+ const rawBody = String(params.content || '').replace(/^\uFEFF/, '');
310
+ const source = rawBody.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '');
311
+ const headingMatch = source.match(/^#\s+(.+)$/m);
312
+ const title = String(params.title || headingMatch?.[1] || params.file.replace(/\.mdc?$/i, '')).trim().slice(0, 80);
313
+ let templateId = params.templateId;
314
+ if (!templateId) {
315
+ try {
316
+ const tplList = await runMcp('clado_templates', { action: 'list' });
317
+ const validTpls = (tplList?.templates || []).filter(t => t.valid !== false);
318
+ templateId = validTpls.find(t => t.id === 'call-chain')?.id
319
+ || validTpls.find(t => t.id === 'requirement-overview')?.id
320
+ || validTpls[0]?.id
321
+ || 'call-chain';
322
+ } catch {
323
+ templateId = 'call-chain';
324
+ }
99
325
  }
326
+ const res = await runMcp('clado_documents', {
327
+ action: 'create',
328
+ file: params.file,
329
+ title,
330
+ templateId,
331
+ source,
332
+ });
333
+ const graphCheck = await inspectGraphCheck(params.file);
334
+ return textResult({ ok: true, file: params.file, templateId, ...res, ...(graphCheck ? { graphCheck } : {}) });
335
+ } catch (err) {
336
+ return errorResult('clado_create', err);
337
+ }
338
+ },
339
+ }),
340
+
341
+ defineTool({
342
+ name: 'clado_update',
343
+ label: '更新画布全文',
344
+ description: '更新已存在画布的完整 Markdown 内容(自动保留原有 YAML 规则头,若 content 未带 front matter 会自动复用原头部)。适合整体规划与一次性重构单向流画布;写入后自动返回渲染拓扑体检 graphCheck。',
345
+ promptSnippet: '整体更新一张已有 Clado 画布的 Markdown 内容并返回拓扑体检',
346
+ parameters: {
347
+ type: 'object',
348
+ properties: {
349
+ file: { type: 'string', description: '已存在的画布文件名' },
350
+ content: { type: 'string', description: '新的完整 Markdown 正文(可省略 YAML front matter,工具会自动保留原规则头)' },
351
+ expectedFileVersion: { type: 'string', description: '可选:文档 version,留空时自动读取当前版本' },
352
+ },
353
+ required: ['file', 'content'],
354
+ },
355
+ async execute(_id, params) {
356
+ try {
357
+ const existing = await runMcp('clado_documents', { action: 'read', file: params.file, view: 'full' });
358
+ const expectedFileVersion = params.expectedFileVersion || existing.version;
359
+ const rawBody = String(params.content || '').replace(/^\uFEFF/, '');
360
+ const incomingHasFm = splitFrontMatter(rawBody).had;
361
+ const payload = {
362
+ action: 'update',
363
+ file: params.file,
364
+ source: rawBody,
365
+ expectedFileVersion,
366
+ ...(!incomingHasFm && existing.metadata && Object.keys(existing.metadata).length
367
+ ? { metadata: existing.metadata }
368
+ : {}),
369
+ };
370
+ const res = await runMcp('clado_documents', payload);
371
+ const graphCheck = await inspectGraphCheck(params.file);
372
+ return textResult({ ok: true, file: params.file, ...res, ...(graphCheck ? { graphCheck } : {}) });
373
+ } catch (err) {
374
+ return errorResult('clado_update', err);
100
375
  }
101
- const res = await runMcp('clado_documents', {
102
- action: 'create',
103
- file: params.file,
104
- title,
105
- templateId,
106
- source,
107
- });
108
- return textResult(res);
109
376
  },
110
377
  }),
111
378
 
112
379
  defineTool({
113
380
  name: 'clado_nodes',
114
381
  label: '编辑画布卡片',
115
- description: '批量增删改指定画布上的卡片与子节(使用 clado_batch operations),自动刷新前端实时画布。',
116
- promptSnippet: '增删改 Clado 画布上的卡片节点与内容',
382
+ description: '局部微调已有画布上的卡片与子节(支持 node.create / node.insert / node.update / node.rename / node.move / node.delete 及 link.connect / link.disconnect)。新建或大幅重构画布请优先用 clado_create / clado_update 一次性连线落图,不要一张张建空卡再回头连线。',
383
+ promptSnippet: '精准微调已有 Clado 画布上的卡片、小节或连线并返回拓扑体检',
117
384
  parameters: {
118
385
  type: 'object',
119
386
  properties: {
120
387
  file: { type: 'string', description: '目标画布文件名' },
388
+ expectedFileVersion: { type: 'string', description: '可选:文件版本号(省略时自动读取当前版本)' },
121
389
  operations: {
122
390
  type: 'array',
123
- description: '节点变更操作数组,每项包含 type (node.create/node.update/node.delete/node.rename/node.move)、file、node 等字段',
391
+ description: '操作数组。节点路径 node/parent/targetNode 必须是标题数组,例如 ["订单网关", "参数校验"]。每项含 type (node.create/node.insert/node.update/node.rename/node.move/node.delete/link.connect/link.disconnect) 与对应字段。',
124
392
  items: { type: 'object' },
125
393
  },
126
394
  },
127
395
  required: ['file', 'operations'],
128
396
  },
129
397
  async execute(_id, params) {
130
- const ops = (params.operations || []).map(op => ({
131
- file: params.file,
132
- ...op,
133
- type: op.type || (op.op ? 'node.' + op.op : 'node.update'),
134
- }));
135
- const res = await runMcp('clado_batch', { operations: ops });
136
- return textResult(res);
398
+ try {
399
+ const normalizeType = op => {
400
+ const raw = String(op?.type || op?.op || 'node.update').trim();
401
+ if (raw.includes('.')) return raw;
402
+ if (['connect', 'disconnect', 'add', 'remove'].includes(raw)) {
403
+ return 'link.' + (raw === 'add' ? 'connect' : raw === 'remove' ? 'disconnect' : raw);
404
+ }
405
+ return 'node.' + raw;
406
+ };
407
+ const fileVersion = params.expectedFileVersion || await currentFileVersion(params.file);
408
+ const ops = (params.operations || []).map(op => {
409
+ const { op: _legacyOp, ...rest } = op || {};
410
+ const type = normalizeType(op);
411
+ const hasVersion = rest.expectedFileVersion || rest.expectedNodeVersion || rest.expectedWorkspaceVersion;
412
+ return {
413
+ file: params.file,
414
+ ...rest,
415
+ type,
416
+ ...(!hasVersion && fileVersion && (rest.file || params.file) === params.file
417
+ ? { expectedFileVersion: fileVersion }
418
+ : {}),
419
+ };
420
+ });
421
+ const res = await runMcp('clado_batch', { operations: ops });
422
+ const graphCheck = await inspectGraphCheck(params.file);
423
+ return textResult({ ok: true, file: params.file, ...res, ...(graphCheck ? { graphCheck } : {}) });
424
+ } catch (err) {
425
+ return errorResult('clado_nodes', err);
426
+ }
137
427
  },
138
428
  }),
139
429
 
140
430
  defineTool({
141
431
  name: 'clado_links',
142
432
  label: '查看或编辑画布连线',
143
- description: '列出或在画布卡片之间创建/删除依赖连线。',
144
- promptSnippet: '查看或编辑画布卡片之间的依赖连线',
433
+ description: '列出或在已有画布卡片之间建立/断开依赖连线(action: list / connect / disconnect)。严守克制单向流原则:只连真实下一步执行/数据流,绝不画尾连头反向回环、双向互连或跨层捷径;用于局部微调或删除多余/回环连线。',
434
+ promptSnippet: '列出、建立或断开画布卡片之间的正向跨卡连线(严禁回环)',
145
435
  parameters: {
146
436
  type: 'object',
147
437
  properties: {
148
- action: { type: 'string', enum: ['list', 'add', 'remove'], description: '默认 list' },
438
+ action: { type: 'string', enum: ['list', 'connect', 'disconnect', 'add', 'remove'], description: '默认 list;connect 建立连线(兼容 add),disconnect 断开连线(兼容 remove)' },
149
439
  file: { type: 'string', description: '目标画布文件名' },
150
- node: { type: 'array', items: { type: 'string' } },
151
- targetFile: { type: 'string' },
152
- targetNode: { type: 'array', items: { type: 'string' } },
440
+ node: { type: 'array', items: { type: 'string' }, description: '源节点标题路径数组,例如 ["订单入口", "核心流程"]' },
441
+ targetFile: { type: 'string', description: '可选:跨文档目标文件名(同画布连线请省略)' },
442
+ targetNode: { type: 'array', items: { type: 'string' }, description: '目标卡片或小节标题路径数组,例如 ["账务服务"] 或 ["账务服务", "幂等落账"]' },
443
+ label: { type: 'string', description: '可选:连线显示文字' },
444
+ before: { type: 'string', description: '可选:连线前附加文字' },
445
+ after: { type: 'string', description: '可选:连线后附加文字' },
446
+ position: { type: 'object', description: '可选:{mode:"append"|"prepend"|"before"|"after"|"replace", paragraph?, anchor?}' },
447
+ linkIndex: { type: 'number', description: '仅 disconnect 使用:links.list 返回的节点内引用编号(从 1 开始)' },
448
+ sourcePoint: { type: 'object', description: '可选同画布精确起点:{kind:"code",paragraph,line} / {kind:"table",paragraph,row} / {kind:"mermaid",paragraph,nodeId}' },
449
+ targetPoint: { type: 'object', description: '可选精确落点' },
450
+ expectedFileVersion: { type: 'string', description: '可选:文件版本号(省略时自动读取)' },
451
+ expectedNodeVersion: { type: 'string', description: '可选:节点版本号' },
153
452
  },
154
453
  },
155
- async execute(_id, params) {
156
- const res = await runMcp('clado_links', {
157
- action: params.action || 'list',
158
- ...params,
159
- });
160
- return textResult(res);
454
+ async execute(_id, params = {}) {
455
+ try {
456
+ const rawAction = params.action || 'list';
457
+ const action = rawAction === 'add' ? 'connect' : rawAction === 'remove' ? 'disconnect' : rawAction;
458
+ const needsVersion = action === 'disconnect' || Boolean(params.sourcePoint || params.targetPoint || params.position?.paragraph);
459
+ const expectedFileVersion = params.expectedFileVersion
460
+ || (needsVersion && !params.expectedNodeVersion && params.file ? await currentFileVersion(params.file) : undefined);
461
+ const res = await runMcp('clado_links', {
462
+ ...params,
463
+ action,
464
+ ...(expectedFileVersion ? { expectedFileVersion } : {}),
465
+ });
466
+ if (action === 'connect' || action === 'disconnect') {
467
+ const graphCheck = await inspectGraphCheck(params.file);
468
+ return textResult({ ok: true, ...res, ...(graphCheck ? { graphCheck } : {}) });
469
+ }
470
+ return textResult(res);
471
+ } catch (err) {
472
+ return errorResult('clado_links', err);
473
+ }
161
474
  },
162
475
  }),
163
476
 
@@ -168,8 +481,12 @@ export function createCladoPiTools({
168
481
  promptSnippet: '查看画布上的便签与独立组件',
169
482
  parameters: { type: 'object', properties: {} },
170
483
  async execute() {
171
- const objects = stateDir ? listCanvasObjects(stateDir) : [];
172
- return textResult({ objects });
484
+ try {
485
+ const objects = stateDir ? listCanvasObjects(stateDir) : [];
486
+ return textResult({ objects });
487
+ } catch (err) {
488
+ return errorResult('canvas_objects_list', err);
489
+ }
173
490
  },
174
491
  }),
175
492
 
@@ -192,20 +509,24 @@ export function createCladoPiTools({
192
509
  required: ['title', 'body'],
193
510
  },
194
511
  async execute(_id, params) {
195
- if (!stateDir) return textResult({ error: '当前工作区不支持画布对象持久化。' });
196
- const saved = saveCanvasObject(stateDir, {
197
- ...(params.id ? { id: params.id } : {}),
198
- kind: params.kind || 'sticky_note',
199
- title: params.title,
200
- data: {
201
- body: params.body,
202
- color: params.color || 'amber',
203
- },
204
- x: typeof params.x === 'number' ? params.x : 340,
205
- y: typeof params.y === 'number' ? params.y : 140,
206
- });
207
- events?.emit(workspace, 'objects.updated', { action: 'save', object: saved });
208
- return textResult({ ok: true, object: saved });
512
+ try {
513
+ if (!stateDir) return errorResult('canvas_objects_upsert', new Error('当前工作区不支持画布对象持久化。'));
514
+ const saved = saveCanvasObject(stateDir, {
515
+ ...(params.id ? { id: params.id } : {}),
516
+ kind: params.kind || 'sticky_note',
517
+ title: params.title,
518
+ data: {
519
+ body: params.body,
520
+ color: params.color || 'amber',
521
+ },
522
+ x: typeof params.x === 'number' ? params.x : 340,
523
+ y: typeof params.y === 'number' ? params.y : 140,
524
+ });
525
+ events?.emit(workspace, 'objects.updated', { action: 'save', object: saved });
526
+ return textResult({ ok: true, object: saved });
527
+ } catch (err) {
528
+ return errorResult('canvas_objects_upsert', err);
529
+ }
209
530
  },
210
531
  }),
211
532
 
@@ -221,10 +542,15 @@ export function createCladoPiTools({
221
542
  required: ['id'],
222
543
  },
223
544
  async execute(_id, params) {
224
- if (!stateDir) return textResult({ deleted: false });
225
- const deleted = deleteCanvasObject(stateDir, params.id);
226
- if (deleted) events?.emit(workspace, 'objects.updated', { action: 'delete', id: params.id });
227
- return textResult({ deleted, id: params.id });
545
+ try {
546
+ if (!stateDir) return errorResult('canvas_objects_delete', new Error('当前工作区不支持画布对象持久化。'));
547
+ const deleted = deleteCanvasObject(stateDir, params.id);
548
+ if (!deleted) return errorResult('canvas_objects_delete', new Error(`找不到画布对象:${params.id}`), '请先调用 canvas_objects_list 确认对象 ID。');
549
+ events?.emit(workspace, 'objects.updated', { action: 'delete', id: params.id });
550
+ return textResult({ ok: true, deleted, id: params.id });
551
+ } catch (err) {
552
+ return errorResult('canvas_objects_delete', err);
553
+ }
228
554
  },
229
555
  }),
230
556
 
@@ -242,9 +568,13 @@ export function createCladoPiTools({
242
568
  required: ['file'],
243
569
  },
244
570
  async execute(_id, params) {
245
- emit({ type: 'focus', file: params.file, heading: params.heading || '' });
246
- events?.emit(workspace, 'canvas.focus', { file: params.file, heading: params.heading || '' });
247
- return textResult({ ok: true, focused: params });
571
+ try {
572
+ emit({ type: 'focus', file: params.file, heading: params.heading || '' });
573
+ events?.emit(workspace, 'canvas.focus', { file: params.file, heading: params.heading || '' });
574
+ return textResult({ ok: true, focused: params });
575
+ } catch (err) {
576
+ return errorResult('canvas_focus', err);
577
+ }
248
578
  },
249
579
  }),
250
580
 
@@ -274,25 +604,29 @@ export function createCladoPiTools({
274
604
  required: ['question'],
275
605
  },
276
606
  async execute(toolCallId, params, signal) {
277
- const questionId = 'q_' + toolCallId.slice(0, 12);
278
- const options = Array.isArray(params.options)
279
- ? params.options.map((o, idx) => ({
280
- id: String(o?.id || ('opt_' + (idx + 1))),
281
- label: String(o?.label || '').trim(),
282
- description: String(o?.description || '').trim(),
283
- })).filter(o => o.label)
284
- : [];
285
- emit({
286
- type: 'ask_user',
287
- questionId,
288
- question: String(params.question || ''),
289
- options,
290
- });
291
- if (!waitForUserAnswer) {
292
- return textResult({ questionId, answer: '用户暂未开启交互确认,请按最稳妥方案继续。' });
607
+ try {
608
+ const questionId = 'q_' + toolCallId.slice(0, 12);
609
+ const options = Array.isArray(params.options)
610
+ ? params.options.map((o, idx) => ({
611
+ id: String(o?.id || ('opt_' + (idx + 1))),
612
+ label: String(o?.label || '').trim(),
613
+ description: String(o?.description || '').trim(),
614
+ })).filter(o => o.label)
615
+ : [];
616
+ emit({
617
+ type: 'ask_user',
618
+ questionId,
619
+ question: String(params.question || ''),
620
+ options,
621
+ });
622
+ if (!waitForUserAnswer) {
623
+ return textResult({ questionId, answer: '用户暂未开启交互确认,请按最稳妥方案继续。' });
624
+ }
625
+ const answer = await waitForUserAnswer(questionId, signal);
626
+ return textResult({ questionId, answer });
627
+ } catch (err) {
628
+ return errorResult('ask_user', err);
293
629
  }
294
- const answer = await waitForUserAnswer(questionId, signal);
295
- return textResult({ questionId, answer });
296
630
  },
297
631
  }),
298
632
  ];