cladogram 0.6.0-beta.1 → 0.6.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +50 -47
  2. package/bin/clado.js +34 -2
  3. package/docs/agent-context.md +63 -0
  4. package/docs/agent-reference.md +219 -0
  5. package/docs/release.md +116 -0
  6. package/package.json +3 -1
  7. package/plugins/agent/index.js +2429 -723
  8. package/plugins/agent/settings.js +3592 -0
  9. package/plugins/agent/style.css +1327 -94
  10. package/plugins/view-controls/index.js +0 -11
  11. package/plugins/view-controls/style.css +7 -14
  12. package/skills/clado/SKILL.md +4 -2
  13. package/src/agent/automations.js +454 -0
  14. package/src/agent/clado-tools.js +597 -104
  15. package/src/agent/pi-bridge.js +2184 -112
  16. package/src/agent/pi-config.js +1889 -108
  17. package/src/agent/pi-hooks-perms.js +621 -0
  18. package/src/html/app-css.js +69 -1
  19. package/src/html/canvas-chain.js +32 -6
  20. package/src/html/canvas-focus.js +19 -13
  21. package/src/html/canvas-live-diff.js +1373 -0
  22. package/src/html/canvas-ui.css +503 -2
  23. package/src/html/canvas-wires.js +5 -1
  24. package/src/html/page.js +4 -2
  25. package/src/html/plugin-assets.js +5 -1
  26. package/src/html/plugin-ui.css +1 -1
  27. package/src/html/runtime-api.js +152 -10
  28. package/src/html/runtime.js +546 -37
  29. package/src/server/agent.js +594 -37
  30. package/src/server/assets/library-canvas.js +256 -9
  31. package/src/server/assets/library.css +567 -12
  32. package/src/server/assets/library.html +2 -0
  33. package/src/server/assets/library.js +1028 -32
  34. package/src/server/code-inspect.js +183 -0
  35. package/src/server/mcp.js +90 -22
  36. package/src/server/plugin-registry.js +664 -2
  37. package/src/server/workspace.js +551 -25
  38. package/src/workspace/graph-snapshot.js +695 -0
  39. package/src/workspace/service.js +201 -9
@@ -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,
@@ -24,140 +156,328 @@ export function createCladoPiTools({
24
156
  events = null,
25
157
  emit = () => {},
26
158
  waitForUserAnswer = null,
159
+ sessionOps = null,
160
+ automationOps = null,
161
+ onCardChanges = null,
27
162
  }) {
28
163
  const runMcp = async (tool, input = {}) => {
29
164
  if (!workspaceService) throw new Error('Clado workspaceService 未就绪。');
30
- return workspaceService(tool, { workspace, ...input });
165
+ const res = await workspaceService(tool, { workspace, ...input });
166
+ if (res && typeof onCardChanges === 'function' && (Array.isArray(res.cardChanges) || ['create', 'update', 'delete', 'insert', 'rename', 'move', 'connect', 'disconnect'].includes(input.action))) {
167
+ try { onCardChanges(tool, res); } catch {}
168
+ }
169
+ return res;
170
+ };
171
+
172
+ const inspectGraphCheck = async file => {
173
+ if (!file) return null;
174
+ try {
175
+ const g = await runMcp('clado_documents', { action: 'read', file, view: 'graph' });
176
+ return summarizeGraphCheck(g);
177
+ } catch {
178
+ return null;
179
+ }
180
+ };
181
+
182
+ const currentFileVersion = async file => {
183
+ if (!file) return undefined;
184
+ try {
185
+ const summary = await runMcp('clado_documents', { action: 'read', file, view: 'summary' });
186
+ return summary?.version;
187
+ } catch {
188
+ return undefined;
189
+ }
31
190
  };
32
191
 
33
192
  return [
34
193
  defineTool({
35
194
  name: 'clado_list',
36
195
  label: '列出画布',
37
- description: '列出当前 Clado 工作区中的所有空间画布(.md/.mdc 文档)及卡片数量。',
196
+ description: '列出当前 Clado 工作区中的所有空间画布(.md/.mdc 文档)、卡片数量与诊断摘要。',
38
197
  promptSnippet: '列出工作区所有 Clado 画布文档',
39
198
  parameters: {
40
199
  type: 'object',
41
- properties: {},
200
+ properties: {
201
+ query: { type: 'string', description: '可选:按文件名或正文关键字过滤' },
202
+ },
42
203
  },
43
- async execute() {
44
- const res = await runMcp('clado_documents', { action: 'list' });
45
- return textResult(res);
204
+ async execute(_id, params = {}) {
205
+ try {
206
+ const res = await runMcp('clado_documents', {
207
+ action: 'list',
208
+ ...(params.query ? { query: params.query } : {}),
209
+ });
210
+ return textResult(res);
211
+ } catch (err) {
212
+ return errorResult('clado_list', err);
213
+ }
214
+ },
215
+ }),
216
+
217
+ defineTool({
218
+ name: 'clado_graph',
219
+ label: '读取画布拓扑树',
220
+ description: '像浏览器读取 DOM 树一样读取 Clado 画布实际渲染出来的「卡片模式网状拓扑与节点树」:返回从左到右列布局、端到端调用链路、跨卡连线明细、完整卡片/小节/语义 Tag 树、孤立卡片清单、未解析断链和诊断结果。写完或修改画布后强烈建议调用此工具复核连线质量。',
221
+ promptSnippet: '读取画布实际连出来的卡片网络、列布局、语义 Tag、孤立卡与断链(Clado 的 DOM 树)',
222
+ parameters: {
223
+ type: 'object',
224
+ properties: {
225
+ file: { type: 'string', description: '可选:指定画布文件名(如 arch.md);省略时返回整个工作区所有画布的拓扑总览与跨文档连线。' },
226
+ },
227
+ },
228
+ async execute(_id, params = {}) {
229
+ try {
230
+ const res = params.file
231
+ ? await runMcp('clado_documents', { action: 'read', file: params.file, view: 'graph' })
232
+ : await runMcp('clado_workspace', { action: 'graph' });
233
+ const text = res.treeText || JSON.stringify(res, null, 2);
234
+ return textResult(text, res);
235
+ } catch (err) {
236
+ return errorResult('clado_graph', err);
237
+ }
238
+ },
239
+ }),
240
+
241
+ defineTool({
242
+ name: 'clado_templates',
243
+ label: '读取画布模板',
244
+ description: '列出当前工作区可用的 Clado 画布模板(如 call-chain、business-flow、requirement-overview、data-design、test-cases、system-state、mind-expansion),或读取指定模板的写作规范与约束。',
245
+ promptSnippet: '列出或读取 Clado 内置/项目画布模板规范',
246
+ parameters: {
247
+ type: 'object',
248
+ properties: {
249
+ action: { type: 'string', enum: ['list', 'read'], description: '默认 list' },
250
+ templateId: { type: 'string', description: 'action 为 read 时必填,例如 call-chain / business-flow / data-design / requirement-overview / test-cases' },
251
+ },
252
+ },
253
+ async execute(_id, params = {}) {
254
+ try {
255
+ const action = params.action === 'read' ? 'read' : 'list';
256
+ const res = await runMcp('clado_templates', {
257
+ action,
258
+ ...(action === 'read' ? { templateId: params.templateId, view: 'prompt' } : {}),
259
+ });
260
+ return textResult(res);
261
+ } catch (err) {
262
+ return errorResult('clado_templates', err);
263
+ }
46
264
  },
47
265
  }),
48
266
 
49
267
  defineTool({
50
268
  name: 'clado_read',
51
269
  label: '读取画布',
52
- description: '读取指定画布的完整结构(卡片列表、标题路径、正文、语义标签与连线关系)。',
53
- promptSnippet: '读取 Clado 画布的卡片、标签与连线结构',
270
+ description: '读取指定画布的内容与结构(含 version、节点列表、正文或源码),并附带简要拓扑状态。',
271
+ promptSnippet: '读取 Clado 画布的正文、节点路径与版本号',
54
272
  parameters: {
55
273
  type: 'object',
56
274
  properties: {
57
275
  file: { type: 'string', description: '画布相对路径,如 payment-arch.md' },
58
- view: { type: 'string', enum: ['outline', 'full'], description: 'outline 仅目录结构,full 返回完整卡片正文' },
276
+ view: { type: 'string', enum: ['full', 'nodes', 'source', 'summary', 'graph', 'outline'], description: '默认 full;nodes/outline 仅节点树,source 原始文本,summary 概要,graph 拓扑树快照' },
59
277
  },
60
278
  required: ['file'],
61
279
  },
62
280
  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);
281
+ try {
282
+ const mappedView = params.view === 'outline' ? 'nodes' : (params.view || 'full');
283
+ const res = await runMcp('clado_documents', {
284
+ action: 'read',
285
+ file: params.file,
286
+ view: mappedView,
287
+ });
288
+ if (mappedView === 'graph') {
289
+ return textResult(res.treeText || JSON.stringify(res, null, 2), res);
290
+ }
291
+ const graphCheck = await inspectGraphCheck(params.file);
292
+ return textResult({ ...res, ...(graphCheck ? { graphCheck } : {}) });
293
+ } catch (err) {
294
+ return errorResult('clado_read', err);
295
+ }
69
296
  },
70
297
  }),
71
298
 
72
299
  defineTool({
73
300
  name: 'clado_create',
74
301
  label: '新建画布',
75
- description: '在当前工作区创建一张新的 Clado 空间画布文档(Markdown 格式,支持卡片标题、语义标签与卡片连线)。',
76
- promptSnippet: '新建一张 Clado 空间画布文档',
302
+ description: '在当前工作区一次性创建一张完整的 Clado 空间画布文档(.md 或 .mdc)。请先规划好 3–5 列从左到右的单向流,一次性写出全部 # L1 卡片、正文与克制的正向跨卡内链 [文字](目标卡片标题) / [文字](#tagId)——不要逐张创建空卡后再乱补线,严禁尾连头反向回环,单卡出度建议 1–3 条。写入后自动返回渲染拓扑体检 graphCheck。',
303
+ promptSnippet: '一次性新建完整的单向流 Clado 空间画布文档并返回拓扑体检',
77
304
  parameters: {
78
305
  type: 'object',
79
306
  properties: {
80
307
  file: { type: 'string', description: '新画布文件名(如 arch-overview.md)' },
81
308
  title: { type: 'string', description: '可选:画布标题(留空将自动从首行 # 标题或文件名推导)' },
82
- templateId: { type: 'string', description: '可选:模板 ID(留空自动选用工作区默认模板)' },
83
- content: { type: 'string', description: 'Markdown 正文(支持 # 卡片标题、## 子节与语义标签/连线)' },
309
+ templateId: { type: 'string', description: '可选:模板 ID(如 call-chain / business-flow / requirement-overview / data-design / test-cases / system-state / mind-expansion)' },
310
+ content: { type: 'string', description: 'Markdown 正文(不要包含 front matter;使用 # 卡片、## 子节、语义 Tag {#id .color} 与克制的正向跨卡内链 [文字](目标卡片标题) 或 [文字](#tagId))' },
84
311
  },
85
312
  required: ['file', 'content'],
86
313
  },
87
314
  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';
315
+ try {
316
+ const rawBody = String(params.content || '').replace(/^\uFEFF/, '');
317
+ const source = rawBody.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '');
318
+ const headingMatch = source.match(/^#\s+(.+)$/m);
319
+ const title = String(params.title || headingMatch?.[1] || params.file.replace(/\.mdc?$/i, '')).trim().slice(0, 80);
320
+ let templateId = params.templateId;
321
+ if (!templateId) {
322
+ try {
323
+ const tplList = await runMcp('clado_templates', { action: 'list' });
324
+ const validTpls = (tplList?.templates || []).filter(t => t.valid !== false);
325
+ templateId = validTpls.find(t => t.id === 'call-chain')?.id
326
+ || validTpls.find(t => t.id === 'requirement-overview')?.id
327
+ || validTpls[0]?.id
328
+ || 'call-chain';
329
+ } catch {
330
+ templateId = 'call-chain';
331
+ }
99
332
  }
333
+ const res = await runMcp('clado_documents', {
334
+ action: 'create',
335
+ file: params.file,
336
+ title,
337
+ templateId,
338
+ source,
339
+ });
340
+ const graphCheck = await inspectGraphCheck(params.file);
341
+ return textResult({ ok: true, file: params.file, templateId, ...res, ...(graphCheck ? { graphCheck } : {}) });
342
+ } catch (err) {
343
+ return errorResult('clado_create', err);
344
+ }
345
+ },
346
+ }),
347
+
348
+ defineTool({
349
+ name: 'clado_update',
350
+ label: '更新画布全文',
351
+ description: '更新已存在画布的完整 Markdown 内容(自动保留原有 YAML 规则头,若 content 未带 front matter 会自动复用原头部)。适合整体规划与一次性重构单向流画布;写入后自动返回渲染拓扑体检 graphCheck。',
352
+ promptSnippet: '整体更新一张已有 Clado 画布的 Markdown 内容并返回拓扑体检',
353
+ parameters: {
354
+ type: 'object',
355
+ properties: {
356
+ file: { type: 'string', description: '已存在的画布文件名' },
357
+ content: { type: 'string', description: '新的完整 Markdown 正文(可省略 YAML front matter,工具会自动保留原规则头)' },
358
+ expectedFileVersion: { type: 'string', description: '可选:文档 version,留空时自动读取当前版本' },
359
+ },
360
+ required: ['file', 'content'],
361
+ },
362
+ async execute(_id, params) {
363
+ try {
364
+ const existing = await runMcp('clado_documents', { action: 'read', file: params.file, view: 'full' });
365
+ const expectedFileVersion = params.expectedFileVersion || existing.version;
366
+ const rawBody = String(params.content || '').replace(/^\uFEFF/, '');
367
+ const incomingHasFm = splitFrontMatter(rawBody).had;
368
+ const payload = {
369
+ action: 'update',
370
+ file: params.file,
371
+ source: rawBody,
372
+ expectedFileVersion,
373
+ ...(!incomingHasFm && existing.metadata && Object.keys(existing.metadata).length
374
+ ? { metadata: existing.metadata }
375
+ : {}),
376
+ };
377
+ const res = await runMcp('clado_documents', payload);
378
+ const graphCheck = await inspectGraphCheck(params.file);
379
+ return textResult({ ok: true, file: params.file, ...res, ...(graphCheck ? { graphCheck } : {}) });
380
+ } catch (err) {
381
+ return errorResult('clado_update', err);
100
382
  }
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
383
  },
110
384
  }),
111
385
 
112
386
  defineTool({
113
387
  name: 'clado_nodes',
114
388
  label: '编辑画布卡片',
115
- description: '批量增删改指定画布上的卡片与子节(使用 clado_batch operations),自动刷新前端实时画布。',
116
- promptSnippet: '增删改 Clado 画布上的卡片节点与内容',
389
+ description: '局部微调已有画布上的卡片与子节(支持 node.create / node.insert / node.update / node.rename / node.move / node.delete 及 link.connect / link.disconnect)。新建或大幅重构画布请优先用 clado_create / clado_update 一次性连线落图,不要一张张建空卡再回头连线。',
390
+ promptSnippet: '精准微调已有 Clado 画布上的卡片、小节或连线并返回拓扑体检',
117
391
  parameters: {
118
392
  type: 'object',
119
393
  properties: {
120
394
  file: { type: 'string', description: '目标画布文件名' },
395
+ expectedFileVersion: { type: 'string', description: '可选:文件版本号(省略时自动读取当前版本)' },
121
396
  operations: {
122
397
  type: 'array',
123
- description: '节点变更操作数组,每项包含 type (node.create/node.update/node.delete/node.rename/node.move)、file、node 等字段',
398
+ description: '操作数组。节点路径 node/parent/targetNode 必须是标题数组,例如 ["订单网关", "参数校验"]。每项含 type (node.create/node.insert/node.update/node.rename/node.move/node.delete/link.connect/link.disconnect) 与对应字段。',
124
399
  items: { type: 'object' },
125
400
  },
126
401
  },
127
402
  required: ['file', 'operations'],
128
403
  },
129
404
  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);
405
+ try {
406
+ const normalizeType = op => {
407
+ const raw = String(op?.type || op?.op || 'node.update').trim();
408
+ if (raw.includes('.')) return raw;
409
+ if (['connect', 'disconnect', 'add', 'remove'].includes(raw)) {
410
+ return 'link.' + (raw === 'add' ? 'connect' : raw === 'remove' ? 'disconnect' : raw);
411
+ }
412
+ return 'node.' + raw;
413
+ };
414
+ const fileVersion = params.expectedFileVersion || await currentFileVersion(params.file);
415
+ const ops = (params.operations || []).map(op => {
416
+ const { op: _legacyOp, ...rest } = op || {};
417
+ const type = normalizeType(op);
418
+ const hasVersion = rest.expectedFileVersion || rest.expectedNodeVersion || rest.expectedWorkspaceVersion;
419
+ return {
420
+ file: params.file,
421
+ ...rest,
422
+ type,
423
+ ...(!hasVersion && fileVersion && (rest.file || params.file) === params.file
424
+ ? { expectedFileVersion: fileVersion }
425
+ : {}),
426
+ };
427
+ });
428
+ const res = await runMcp('clado_batch', { operations: ops });
429
+ const graphCheck = await inspectGraphCheck(params.file);
430
+ return textResult({ ok: true, file: params.file, ...res, ...(graphCheck ? { graphCheck } : {}) });
431
+ } catch (err) {
432
+ return errorResult('clado_nodes', err);
433
+ }
137
434
  },
138
435
  }),
139
436
 
140
437
  defineTool({
141
438
  name: 'clado_links',
142
439
  label: '查看或编辑画布连线',
143
- description: '列出或在画布卡片之间创建/删除依赖连线。',
144
- promptSnippet: '查看或编辑画布卡片之间的依赖连线',
440
+ description: '列出或在已有画布卡片之间建立/断开依赖连线(action: list / connect / disconnect)。严守克制单向流原则:只连真实下一步执行/数据流,绝不画尾连头反向回环、双向互连或跨层捷径;用于局部微调或删除多余/回环连线。',
441
+ promptSnippet: '列出、建立或断开画布卡片之间的正向跨卡连线(严禁回环)',
145
442
  parameters: {
146
443
  type: 'object',
147
444
  properties: {
148
- action: { type: 'string', enum: ['list', 'add', 'remove'], description: '默认 list' },
445
+ action: { type: 'string', enum: ['list', 'connect', 'disconnect', 'add', 'remove'], description: '默认 list;connect 建立连线(兼容 add),disconnect 断开连线(兼容 remove)' },
149
446
  file: { type: 'string', description: '目标画布文件名' },
150
- node: { type: 'array', items: { type: 'string' } },
151
- targetFile: { type: 'string' },
152
- targetNode: { type: 'array', items: { type: 'string' } },
447
+ node: { type: 'array', items: { type: 'string' }, description: '源节点标题路径数组,例如 ["订单入口", "核心流程"]' },
448
+ targetFile: { type: 'string', description: '可选:跨文档目标文件名(同画布连线请省略)' },
449
+ targetNode: { type: 'array', items: { type: 'string' }, description: '目标卡片或小节标题路径数组,例如 ["账务服务"] 或 ["账务服务", "幂等落账"]' },
450
+ label: { type: 'string', description: '可选:连线显示文字' },
451
+ before: { type: 'string', description: '可选:连线前附加文字' },
452
+ after: { type: 'string', description: '可选:连线后附加文字' },
453
+ position: { type: 'object', description: '可选:{mode:"append"|"prepend"|"before"|"after"|"replace", paragraph?, anchor?}' },
454
+ linkIndex: { type: 'number', description: '仅 disconnect 使用:links.list 返回的节点内引用编号(从 1 开始)' },
455
+ sourcePoint: { type: 'object', description: '可选同画布精确起点:{kind:"code",paragraph,line} / {kind:"table",paragraph,row} / {kind:"mermaid",paragraph,nodeId}' },
456
+ targetPoint: { type: 'object', description: '可选精确落点' },
457
+ expectedFileVersion: { type: 'string', description: '可选:文件版本号(省略时自动读取)' },
458
+ expectedNodeVersion: { type: 'string', description: '可选:节点版本号' },
153
459
  },
154
460
  },
155
- async execute(_id, params) {
156
- const res = await runMcp('clado_links', {
157
- action: params.action || 'list',
158
- ...params,
159
- });
160
- return textResult(res);
461
+ async execute(_id, params = {}) {
462
+ try {
463
+ const rawAction = params.action || 'list';
464
+ const action = rawAction === 'add' ? 'connect' : rawAction === 'remove' ? 'disconnect' : rawAction;
465
+ const needsVersion = action === 'disconnect' || Boolean(params.sourcePoint || params.targetPoint || params.position?.paragraph);
466
+ const expectedFileVersion = params.expectedFileVersion
467
+ || (needsVersion && !params.expectedNodeVersion && params.file ? await currentFileVersion(params.file) : undefined);
468
+ const res = await runMcp('clado_links', {
469
+ ...params,
470
+ action,
471
+ ...(expectedFileVersion ? { expectedFileVersion } : {}),
472
+ });
473
+ if (action === 'connect' || action === 'disconnect') {
474
+ const graphCheck = await inspectGraphCheck(params.file);
475
+ return textResult({ ok: true, ...res, ...(graphCheck ? { graphCheck } : {}) });
476
+ }
477
+ return textResult(res);
478
+ } catch (err) {
479
+ return errorResult('clado_links', err);
480
+ }
161
481
  },
162
482
  }),
163
483
 
@@ -168,8 +488,12 @@ export function createCladoPiTools({
168
488
  promptSnippet: '查看画布上的便签与独立组件',
169
489
  parameters: { type: 'object', properties: {} },
170
490
  async execute() {
171
- const objects = stateDir ? listCanvasObjects(stateDir) : [];
172
- return textResult({ objects });
491
+ try {
492
+ const objects = stateDir ? listCanvasObjects(stateDir) : [];
493
+ return textResult({ objects });
494
+ } catch (err) {
495
+ return errorResult('canvas_objects_list', err);
496
+ }
173
497
  },
174
498
  }),
175
499
 
@@ -192,20 +516,24 @@ export function createCladoPiTools({
192
516
  required: ['title', 'body'],
193
517
  },
194
518
  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 });
519
+ try {
520
+ if (!stateDir) return errorResult('canvas_objects_upsert', new Error('当前工作区不支持画布对象持久化。'));
521
+ const saved = saveCanvasObject(stateDir, {
522
+ ...(params.id ? { id: params.id } : {}),
523
+ kind: params.kind || 'sticky_note',
524
+ title: params.title,
525
+ data: {
526
+ body: params.body,
527
+ color: params.color || 'amber',
528
+ },
529
+ x: typeof params.x === 'number' ? params.x : 340,
530
+ y: typeof params.y === 'number' ? params.y : 140,
531
+ });
532
+ events?.emit(workspace, 'objects.updated', { action: 'save', object: saved });
533
+ return textResult({ ok: true, object: saved });
534
+ } catch (err) {
535
+ return errorResult('canvas_objects_upsert', err);
536
+ }
209
537
  },
210
538
  }),
211
539
 
@@ -221,10 +549,15 @@ export function createCladoPiTools({
221
549
  required: ['id'],
222
550
  },
223
551
  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 });
552
+ try {
553
+ if (!stateDir) return errorResult('canvas_objects_delete', new Error('当前工作区不支持画布对象持久化。'));
554
+ const deleted = deleteCanvasObject(stateDir, params.id);
555
+ if (!deleted) return errorResult('canvas_objects_delete', new Error(`找不到画布对象:${params.id}`), '请先调用 canvas_objects_list 确认对象 ID。');
556
+ events?.emit(workspace, 'objects.updated', { action: 'delete', id: params.id });
557
+ return textResult({ ok: true, deleted, id: params.id });
558
+ } catch (err) {
559
+ return errorResult('canvas_objects_delete', err);
560
+ }
228
561
  },
229
562
  }),
230
563
 
@@ -242,9 +575,13 @@ export function createCladoPiTools({
242
575
  required: ['file'],
243
576
  },
244
577
  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 });
578
+ try {
579
+ emit({ type: 'focus', file: params.file, heading: params.heading || '' });
580
+ events?.emit(workspace, 'canvas.focus', { file: params.file, heading: params.heading || '' });
581
+ return textResult({ ok: true, focused: params });
582
+ } catch (err) {
583
+ return errorResult('canvas_focus', err);
584
+ }
248
585
  },
249
586
  }),
250
587
 
@@ -274,26 +611,182 @@ export function createCladoPiTools({
274
611
  required: ['question'],
275
612
  },
276
613
  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: '用户暂未开启交互确认,请按最稳妥方案继续。' });
614
+ try {
615
+ const questionId = 'q_' + toolCallId.slice(0, 12);
616
+ const options = Array.isArray(params.options)
617
+ ? params.options.map((o, idx) => ({
618
+ id: String(o?.id || ('opt_' + (idx + 1))),
619
+ label: String(o?.label || '').trim(),
620
+ description: String(o?.description || '').trim(),
621
+ })).filter(o => o.label)
622
+ : [];
623
+ emit({
624
+ type: 'ask_user',
625
+ questionId,
626
+ question: String(params.question || ''),
627
+ options,
628
+ });
629
+ if (!waitForUserAnswer) {
630
+ return textResult({ questionId, answer: '用户暂未开启交互确认,请按最稳妥方案继续。' });
631
+ }
632
+ const answer = await waitForUserAnswer(questionId, signal);
633
+ return textResult({ questionId, answer });
634
+ } catch (err) {
635
+ return errorResult('ask_user', err);
293
636
  }
294
- const answer = await waitForUserAnswer(questionId, signal);
295
- return textResult({ questionId, answer });
296
637
  },
297
638
  }),
639
+
640
+ ...(sessionOps ? [
641
+ defineTool({
642
+ name: 'clado_session_list',
643
+ label: '列出主会话',
644
+ description: '列出当前工作空间内所有主会话(角色、状态、最近活跃时间、消息数与摘要),支持传 sinceMinutes(如 20)只看最近 N 分钟内活跃的会话。',
645
+ promptSnippet: '列出工作区主会话(支持 sinceMinutes 过滤最近活跃会话)',
646
+ parameters: {
647
+ type: 'object',
648
+ properties: {
649
+ sinceMinutes: { type: 'number', description: '可选:仅返回最近 N 分钟内活跃过的会话(例如 20)' },
650
+ includeArchived: { type: 'boolean', description: '是否包含已归档会话,默认 false' },
651
+ },
652
+ },
653
+ async execute(_id, params = {}) {
654
+ try {
655
+ const list = await sessionOps.list({
656
+ sinceMinutes: Number(params.sinceMinutes) || 0,
657
+ includeArchived: Boolean(params.includeArchived),
658
+ });
659
+ return textResult({
660
+ currentSessionId: sessionOps.currentSessionId || '',
661
+ count: list.length,
662
+ sessions: list.map(s => ({
663
+ id: s.id,
664
+ title: s.title,
665
+ roleId: s.roleId,
666
+ phase: s.phase,
667
+ status: s.status,
668
+ updatedAt: s.updatedAt,
669
+ messageCount: s.messageCount ?? 0,
670
+ summaryBadge: s.summaryBadge || '',
671
+ lastMessagePreview: s.lastMessagePreview || '',
672
+ })),
673
+ });
674
+ } catch (err) {
675
+ return errorResult('clado_session_list', err);
676
+ }
677
+ },
678
+ }),
679
+
680
+ defineTool({
681
+ name: 'clado_session_read',
682
+ label: '读取会话记录',
683
+ description: '读取工作区中指定主会话的最近 N 轮对话摘要与工具调用记录,用于跨角色同步上下文与协作排查。',
684
+ promptSnippet: '读取指定主会话的最近对话与工具记录',
685
+ parameters: {
686
+ type: 'object',
687
+ properties: {
688
+ sessionId: { type: 'string', description: '目标主会话 ID(可先通过 clado_session_list 获取)' },
689
+ limit: { type: 'number', description: '返回最近多少条消息,默认 12,最大 60' },
690
+ },
691
+ required: ['sessionId'],
692
+ },
693
+ async execute(_id, params = {}) {
694
+ try {
695
+ const transcript = await sessionOps.read({
696
+ sessionId: params.sessionId,
697
+ limit: Number(params.limit) || 12,
698
+ });
699
+ if (!transcript) return errorResult('clado_session_read', new Error(`找不到会话:${params.sessionId}`));
700
+ return textResult(transcript);
701
+ } catch (err) {
702
+ return errorResult('clado_session_read', err);
703
+ }
704
+ },
705
+ }),
706
+
707
+ defineTool({
708
+ name: 'clado_session_open',
709
+ label: '拉起主会话',
710
+ description: '按指定角色 ID 拉起一个新的平等主会话,或复用该角色最近活跃的主会话,供后续通过 clado_session_send 协作交流。',
711
+ promptSnippet: '按角色拉起或复用另一个主会话',
712
+ parameters: {
713
+ type: 'object',
714
+ properties: {
715
+ roleId: { type: 'string', description: '目标角色 ID(如 architect / developer / tester / archivist 或自定义角色 ID)' },
716
+ title: { type: 'string', description: '可选:自定义会话标题' },
717
+ reuseLatest: { type: 'boolean', description: '是否优先复用该角色最近会话(默认 true;设 false 强制新建)' },
718
+ },
719
+ required: ['roleId'],
720
+ },
721
+ async execute(_id, params = {}) {
722
+ try {
723
+ const res = await sessionOps.open({
724
+ roleId: params.roleId,
725
+ title: params.title || '',
726
+ reuseLatest: params.reuseLatest !== false,
727
+ });
728
+ return textResult(res);
729
+ } catch (err) {
730
+ return errorResult('clado_session_open', err);
731
+ }
732
+ },
733
+ }),
734
+
735
+ defineTool({
736
+ name: 'clado_session_send',
737
+ label: '跨会话发消息',
738
+ description: '向工作区中的另一个主会话注入协作消息。若对方空闲则自动唤醒运行;若对方正在运行则以中途插话(steer)方式平滑送达。支持 wait:true 等待对方本轮答复摘要,内置无进展防打转熔断。',
739
+ promptSnippet: '向另一个主会话发送协作消息(唤醒或插话)',
740
+ parameters: {
741
+ type: 'object',
742
+ properties: {
743
+ targetSessionId: { type: 'string', description: '目标主会话 ID(与 targetRoleId 二选一)' },
744
+ targetRoleId: { type: 'string', description: '目标角色 ID(若未传 targetSessionId,则自动定位/拉起该角色主会话)' },
745
+ message: { type: 'string', description: '要发送给对方的清晰协作消息、任务或问题' },
746
+ wait: { type: 'boolean', description: '是否同步等待对方本轮执行完成并返回答复摘要(默认 false,异步唤醒不阻塞)' },
747
+ },
748
+ required: ['message'],
749
+ },
750
+ async execute(_id, params = {}) {
751
+ try {
752
+ const res = await sessionOps.send({
753
+ targetSessionId: params.targetSessionId || '',
754
+ targetRoleId: params.targetRoleId || '',
755
+ message: params.message,
756
+ wait: Boolean(params.wait),
757
+ });
758
+ return textResult(res);
759
+ } catch (err) {
760
+ return errorResult('clado_session_send', err);
761
+ }
762
+ },
763
+ }),
764
+ ] : []),
765
+
766
+ ...(automationOps ? [
767
+ defineTool({
768
+ name: 'clado_automations',
769
+ label: '定时与事件订阅',
770
+ description: '管理当前工作区的周期定时唤醒任务(支持 onlyIfActive 无活跃零消耗跳过)与 6 大类系统事件订阅触发规则(会话/卡片/Tag/代码/记忆/人类操作)。',
771
+ promptSnippet: '查看或管理工作区定时唤醒与事件订阅规则',
772
+ parameters: {
773
+ type: 'object',
774
+ properties: {
775
+ action: { type: 'string', enum: ['list', 'save', 'delete', 'pause', 'resume', 'run_now', 'events_catalog'], description: '操作类型' },
776
+ ruleId: { type: 'string', description: 'delete / run_now 时的规则 ID' },
777
+ rule: { type: 'object', description: 'save 时的规则配置对象' },
778
+ },
779
+ required: ['action'],
780
+ },
781
+ async execute(_id, params = {}) {
782
+ try {
783
+ const res = await automationOps.handle(params);
784
+ return textResult(res);
785
+ } catch (err) {
786
+ return errorResult('clado_automations', err);
787
+ }
788
+ },
789
+ }),
790
+ ] : []),
298
791
  ];
299
792
  }