cladogram 0.6.0-beta.2 → 0.6.0-beta.4

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.
@@ -0,0 +1,695 @@
1
+ /**
2
+ * Clado Canvas Rendered Tree & Network Topology Snapshot (DOM-tree equivalent for Clado).
3
+ *
4
+ * Computes the exact card-mode network graph, left-to-right columns, end-to-end chains,
5
+ * semantic Tag anchors, mindmap heading tree, isolated cards, unresolved links, and
6
+ * structural diagnostics — giving AI agents full structural sight into what is actually
7
+ * rendered on the Clado canvas.
8
+ */
9
+
10
+ import { contentLength, parseDocument } from '../core/parse.js';
11
+ import { markdownLinks } from '../core/links.js';
12
+ import { extractTagsFromBody } from '../core/tags.js';
13
+ import { versionOf } from './documents.js';
14
+ import { resolveReference } from './references.js';
15
+ import { records, treeOf } from './tree.js';
16
+
17
+ function computeColumns(cards, cardEdges) {
18
+ const ids = cards.map(c => c.id);
19
+ const titleById = new Map(cards.map(c => [c.id, c.title]));
20
+ const outMap = new Map(ids.map(id => [id, []]));
21
+ const inMap = new Map(ids.map(id => [id, []]));
22
+ for (const [a, b] of cardEdges) {
23
+ if (!outMap.has(a) || !inMap.has(b) || a === b) continue;
24
+ outMap.get(a).push(b);
25
+ inMap.get(b).push(a);
26
+ }
27
+
28
+ // Topological longest-path layering (matches Clado's left-to-right card layout)
29
+ const inDeg = new Map(ids.map(id => [id, inMap.get(id).length]));
30
+ const col = new Map(ids.map(id => [id, 0]));
31
+ const queue = ids.filter(id => inDeg.get(id) === 0);
32
+ const visited = new Set();
33
+
34
+ while (queue.length) {
35
+ const u = queue.shift();
36
+ visited.add(u);
37
+ const nextCol = col.get(u) + 1;
38
+ for (const v of outMap.get(u)) {
39
+ if (nextCol > col.get(v)) col.set(v, nextCol);
40
+ inDeg.set(v, inDeg.get(v) - 1);
41
+ if (inDeg.get(v) === 0) queue.push(v);
42
+ }
43
+ }
44
+
45
+ // Handle remaining nodes in cycles deterministically
46
+ const hasCycle = visited.size < ids.length;
47
+ if (hasCycle) {
48
+ for (const id of ids) {
49
+ if (visited.has(id)) continue;
50
+ const preds = inMap.get(id).filter(p => visited.has(p));
51
+ col.set(id, preds.length ? Math.max(...preds.map(p => col.get(p))) + 1 : 0);
52
+ visited.add(id);
53
+ }
54
+ }
55
+
56
+ const maxCol = ids.length ? Math.max(...ids.map(id => col.get(id))) : -1;
57
+ const columns = [];
58
+ for (let c = 0; c <= maxCol; c++) {
59
+ const members = ids.filter(id => col.get(id) === c).map(id => titleById.get(id));
60
+ if (members.length) columns.push({ column: c, cards: members });
61
+ }
62
+ return { columns, outMap, inMap, col, hasCycle };
63
+ }
64
+
65
+ function computeConnectedComponents(ids, cardEdges) {
66
+ const adj = new Map(ids.map(id => [id, new Set()]));
67
+ for (const [a, b] of cardEdges) {
68
+ if (adj.has(a) && adj.has(b)) {
69
+ adj.get(a).add(b);
70
+ adj.get(b).add(a);
71
+ }
72
+ }
73
+ const seen = new Set();
74
+ const components = [];
75
+ for (const id of ids) {
76
+ if (seen.has(id)) continue;
77
+ const comp = [];
78
+ const stack = [id];
79
+ seen.add(id);
80
+ while (stack.length) {
81
+ const cur = stack.pop();
82
+ comp.push(cur);
83
+ for (const nxt of adj.get(cur)) {
84
+ if (!seen.has(nxt)) {
85
+ seen.add(nxt);
86
+ stack.push(nxt);
87
+ }
88
+ }
89
+ }
90
+ components.push(comp);
91
+ }
92
+ return components;
93
+ }
94
+
95
+ function traceChains(cards, outMap, inMap, maxChains = 12, maxDepth = 12) {
96
+ const titleById = new Map(cards.map(c => [c.id, c.title]));
97
+ const entries = cards.filter(c => (inMap.get(c.id)?.length || 0) === 0 && (outMap.get(c.id)?.length || 0) > 0);
98
+ const roots = entries.length ? entries : cards.filter(c => (outMap.get(c.id)?.length || 0) > 0).slice(0, 3);
99
+ const chains = [];
100
+
101
+ const dfs = (id, path, seen) => {
102
+ if (chains.length >= maxChains) return;
103
+ const nexts = outMap.get(id) || [];
104
+ if (!nexts.length || path.length >= maxDepth) {
105
+ if (path.length >= 2) chains.push(path.map(x => titleById.get(x)));
106
+ return;
107
+ }
108
+ let extended = false;
109
+ for (const nxt of nexts) {
110
+ if (chains.length >= maxChains) break;
111
+ if (seen.has(nxt)) {
112
+ chains.push([...path.map(x => titleById.get(x)), `${titleById.get(nxt)} (回环)`]);
113
+ extended = true;
114
+ continue;
115
+ }
116
+ extended = true;
117
+ seen.add(nxt);
118
+ dfs(nxt, [...path, nxt], seen);
119
+ seen.delete(nxt);
120
+ }
121
+ if (!extended && path.length >= 2) chains.push(path.map(x => titleById.get(x)));
122
+ };
123
+
124
+ for (const root of roots) {
125
+ if (chains.length >= maxChains) break;
126
+ dfs(root.id, [root.id], new Set([root.id]));
127
+ }
128
+ return chains;
129
+ }
130
+
131
+ function findBackEdges(cards, outMap, inMap) {
132
+ const titleById = new Map(cards.map(c => [c.id, c.title]));
133
+ const state = new Map(cards.map(c => [c.id, 0])); // 0=unvisited, 1=visiting, 2=visited
134
+ const backEdges = [];
135
+ const seenKey = new Set();
136
+
137
+ // Prefer natural entry cards (inDegree === 0) first so back-edges point from tail back to head
138
+ const ordered = [
139
+ ...cards.filter(c => (inMap.get(c.id)?.length || 0) === 0),
140
+ ...cards.filter(c => (inMap.get(c.id)?.length || 0) > 0),
141
+ ];
142
+
143
+ const dfs = u => {
144
+ state.set(u, 1);
145
+ for (const v of (outMap.get(u) || [])) {
146
+ if (state.get(v) === 1) {
147
+ const key = `${u}->${v}`;
148
+ if (!seenKey.has(key)) {
149
+ seenKey.add(key);
150
+ backEdges.push({ from: titleById.get(u) || u, to: titleById.get(v) || v });
151
+ }
152
+ } else if (state.get(v) === 0) {
153
+ dfs(v);
154
+ }
155
+ }
156
+ state.set(u, 2);
157
+ };
158
+
159
+ for (const c of ordered) {
160
+ if (state.get(c.id) === 0) dfs(c.id);
161
+ }
162
+ return backEdges;
163
+ }
164
+
165
+ function classifyNetworkShape({ cardCount, edgeCount, isolatedCount, branchingCount, convergentCount, hasCycle, componentCount }) {
166
+ if (cardCount === 0) return 'empty';
167
+ if (cardCount === 1) return 'single_card';
168
+ if (edgeCount === 0 || isolatedCount > 0) return 'disconnected';
169
+ if (hasCycle) return 'cyclic_network';
170
+ if (branchingCount > 0 && convergentCount > 0) return 'network_dag';
171
+ if (branchingCount > 0 || convergentCount > 0) return 'branching_tree';
172
+ if (componentCount > 1) return 'multi_chain';
173
+ return 'linear_chain';
174
+ }
175
+
176
+ /**
177
+ * Build a complete rendered-canvas graph & tree snapshot for one document.
178
+ * @param {string} file
179
+ * @param {Map<string, string>} documents
180
+ */
181
+ export function buildDocumentGraph(file, documents) {
182
+ const source = documents.get(file);
183
+ if (source === undefined) return null;
184
+
185
+ const { doc, diagnostics: parseDiags } = parseDocument(source, { path: file, requireCardConnections: true });
186
+ const tree = treeOf(source, file);
187
+ const allRecs = records(tree);
188
+ const version = versionOf(source);
189
+
190
+ const cardById = new Map(doc.cards.map(c => [c.id, c]));
191
+ const cardByTitle = new Map(doc.cards.map(c => [c.title, c]));
192
+
193
+ const detailedEdges = [];
194
+ const unresolvedLinks = [];
195
+ const crossDocLinks = [];
196
+ const nodeLinksByPath = new Map();
197
+ const nodeTagsByPath = new Map();
198
+ const allTags = [];
199
+
200
+ for (const rec of allRecs) {
201
+ const pathKey = JSON.stringify(rec.path);
202
+ const body = rec.node.content || '';
203
+ const baseLine = rec.node.location?.bodyStartLine ?? (rec.node.location?.headingLine + 1);
204
+ const cardTitle = rec.path[0];
205
+ const tags = extractTagsFromBody(body, { cardId: cardTitle, nodeId: rec.path.join(' > '), baseLine });
206
+ if (tags.length) {
207
+ const cleaned = tags.map(t => ({
208
+ id: t.id || null,
209
+ color: t.color,
210
+ text: t.text || '',
211
+ kind: t.kind,
212
+ line: t.line,
213
+ card: cardTitle,
214
+ node: rec.path,
215
+ }));
216
+ nodeTagsByPath.set(pathKey, cleaned);
217
+ allTags.push(...cleaned);
218
+ }
219
+
220
+ const links = markdownLinks(body);
221
+ const resolvedHere = [];
222
+ for (const link of links) {
223
+ const target = resolveReference(link.target, file, documents);
224
+ if (!target) continue; // external http(s)/media link
225
+ const lineNo = baseLine + body.slice(0, link.start).split('\n').length - 1;
226
+ if (target.missing) {
227
+ const broken = {
228
+ fromCard: cardTitle,
229
+ fromNode: rec.path,
230
+ label: link.label,
231
+ href: link.target,
232
+ line: lineNo,
233
+ reason: target.ambiguous ? 'ambiguous' : 'unresolved',
234
+ };
235
+ unresolvedLinks.push(broken);
236
+ resolvedHere.push({ label: link.label, href: link.target, status: broken.reason, line: lineNo });
237
+ continue;
238
+ }
239
+ if (target.file !== file) {
240
+ const cross = {
241
+ fromCard: cardTitle,
242
+ fromNode: rec.path,
243
+ label: link.label,
244
+ targetFile: target.file,
245
+ targetNode: target.path,
246
+ targetTag: target.tagId || null,
247
+ line: lineNo,
248
+ };
249
+ crossDocLinks.push(cross);
250
+ resolvedHere.push({
251
+ label: link.label,
252
+ href: link.target,
253
+ status: 'cross_doc',
254
+ targetFile: target.file,
255
+ targetNode: target.path,
256
+ targetTag: target.tagId || null,
257
+ line: lineNo,
258
+ });
259
+ continue;
260
+ }
261
+ const targetCard = target.path?.[0] || '';
262
+ const edgeKind = target.tagId ? 'tag' : (target.path && target.path.length > 1 ? 'section' : 'card');
263
+ const isCrossCard = Boolean(targetCard && targetCard !== cardTitle);
264
+ const entry = {
265
+ fromCard: cardTitle,
266
+ fromNode: rec.path,
267
+ toCard: targetCard,
268
+ toNode: target.path,
269
+ toTag: target.tagId || null,
270
+ label: link.label,
271
+ href: link.target,
272
+ kind: edgeKind,
273
+ crossCard: isCrossCard,
274
+ line: lineNo,
275
+ };
276
+ if (isCrossCard) detailedEdges.push(entry);
277
+ resolvedHere.push({
278
+ label: link.label,
279
+ href: link.target,
280
+ status: isCrossCard ? 'cross_card' : 'same_card',
281
+ toCard: targetCard,
282
+ toNode: target.path,
283
+ toTag: target.tagId || null,
284
+ kind: edgeKind,
285
+ line: lineNo,
286
+ });
287
+ }
288
+ if (resolvedHere.length) nodeLinksByPath.set(pathKey, resolvedHere);
289
+ }
290
+
291
+ const { columns, outMap, inMap, col, hasCycle } = computeColumns(doc.cards, doc.edges);
292
+ const backEdges = hasCycle ? findBackEdges(doc.cards, outMap, inMap) : [];
293
+ const components = computeConnectedComponents(doc.cards.map(c => c.id), doc.edges);
294
+ const chains = traceChains(doc.cards, outMap, inMap);
295
+
296
+ const isolatedCards = doc.cards.length > 1
297
+ ? doc.cards
298
+ .filter(c => (inMap.get(c.id)?.length || 0) === 0 && (outMap.get(c.id)?.length || 0) === 0)
299
+ .map(c => c.title)
300
+ : [];
301
+
302
+ const entryCards = doc.cards
303
+ .filter(c => (inMap.get(c.id)?.length || 0) === 0 && (outMap.get(c.id)?.length || 0) > 0)
304
+ .map(c => c.title);
305
+
306
+ const terminalCards = doc.cards
307
+ .filter(c => (inMap.get(c.id)?.length || 0) > 0 && (outMap.get(c.id)?.length || 0) === 0)
308
+ .map(c => c.title);
309
+
310
+ const branchingCards = doc.cards
311
+ .filter(c => (outMap.get(c.id)?.length || 0) >= 2)
312
+ .map(c => ({ title: c.title, outDegree: outMap.get(c.id).length }));
313
+
314
+ const overLinkedCards = doc.cards
315
+ .filter(c => (outMap.get(c.id)?.length || 0) > 4)
316
+ .map(c => ({
317
+ title: c.title,
318
+ outDegree: outMap.get(c.id).length,
319
+ outTo: outMap.get(c.id).map(id => cardById.get(id)?.title).filter(Boolean),
320
+ }));
321
+
322
+ const convergentCards = doc.cards
323
+ .filter(c => (inMap.get(c.id)?.length || 0) >= 2)
324
+ .map(c => ({ title: c.title, inDegree: inMap.get(c.id).length }));
325
+
326
+ const edgeDensity = doc.cards.length >= 4
327
+ ? Number((doc.edges.length / doc.cards.length).toFixed(2))
328
+ : 0;
329
+ const isOverDense = doc.cards.length >= 4 && doc.edges.length > Math.ceil(doc.cards.length * 2.2);
330
+
331
+ const networkShape = classifyNetworkShape({
332
+ cardCount: doc.cards.length,
333
+ edgeCount: doc.edges.length,
334
+ isolatedCount: isolatedCards.length,
335
+ branchingCount: branchingCards.length,
336
+ convergentCount: convergentCards.length,
337
+ hasCycle,
338
+ componentCount: components.length,
339
+ });
340
+
341
+ // Build hierarchical card tree
342
+ const buildSubTree = (node, parentPath) => {
343
+ const path = [...parentPath, node.title];
344
+ const pathKey = JSON.stringify(path);
345
+ const rec = allRecs.find(r => JSON.stringify(r.path) === pathKey);
346
+ return {
347
+ title: node.title,
348
+ level: node.d,
349
+ path,
350
+ line: rec?.node.location?.headingLine ?? null,
351
+ words: contentLength(rec?.node.content || ''),
352
+ tags: nodeTagsByPath.get(pathKey) || [],
353
+ links: nodeLinksByPath.get(pathKey) || [],
354
+ children: (node.kids || []).map(k => buildSubTree(k, path)),
355
+ };
356
+ };
357
+
358
+ const cardTrees = doc.cards.map(card => {
359
+ const path = [card.title];
360
+ const pathKey = JSON.stringify(path);
361
+ const rec = allRecs.find(r => JSON.stringify(r.path) === pathKey);
362
+ const outTargets = (outMap.get(card.id) || []).map(id => cardById.get(id)?.title).filter(Boolean);
363
+ const inSources = (inMap.get(card.id) || []).map(id => cardById.get(id)?.title).filter(Boolean);
364
+ return {
365
+ id: card.id,
366
+ title: card.title,
367
+ column: col.get(card.id) ?? 0,
368
+ line: rec?.node.location?.headingLine ?? null,
369
+ words: contentLength(rec?.node.content || ''),
370
+ inDegree: inSources.length,
371
+ outDegree: outTargets.length,
372
+ isolated: isolatedCards.includes(card.title),
373
+ inFrom: inSources,
374
+ outTo: outTargets,
375
+ tags: nodeTagsByPath.get(pathKey) || [],
376
+ links: nodeLinksByPath.get(pathKey) || [],
377
+ children: (card.nodes || []).map(n => buildSubTree(n, path)),
378
+ };
379
+ });
380
+
381
+ const errors = parseDiags.filter(d => d.severity === 'error');
382
+ const warnings = parseDiags.filter(d => d.severity === 'warn');
383
+
384
+ const summary = {
385
+ cardCount: doc.cards.length,
386
+ nodeCount: allRecs.length,
387
+ crossCardEdgeCount: doc.edges.length,
388
+ detailedLinkCount: detailedEdges.length,
389
+ tagCount: allTags.length,
390
+ crossDocLinkCount: crossDocLinks.length,
391
+ componentCount: components.length,
392
+ isolatedCount: isolatedCards.length,
393
+ unresolvedLinkCount: unresolvedLinks.length,
394
+ hasCycle,
395
+ backEdgeCount: backEdges.length,
396
+ overLinkedCount: overLinkedCards.length,
397
+ edgeDensity,
398
+ isOverDense,
399
+ errorCount: errors.length,
400
+ warningCount: warnings.length,
401
+ networkShape,
402
+ healthy: errors.length === 0 && isolatedCards.length === 0 && unresolvedLinks.length === 0 && backEdges.length === 0,
403
+ };
404
+
405
+ const treeText = formatDocumentGraphText({
406
+ file,
407
+ title: doc.title,
408
+ version,
409
+ templateId: doc.meta?.id || null,
410
+ summary,
411
+ columns,
412
+ entryCards,
413
+ terminalCards,
414
+ branchingCards,
415
+ convergentCards,
416
+ chains,
417
+ cardTrees,
418
+ detailedEdges,
419
+ isolatedCards,
420
+ unresolvedLinks,
421
+ backEdges,
422
+ overLinkedCards,
423
+ crossDocLinks,
424
+ errors,
425
+ warnings,
426
+ });
427
+
428
+ return {
429
+ file,
430
+ title: doc.title,
431
+ version,
432
+ templateId: doc.meta?.id || null,
433
+ summary,
434
+ columns,
435
+ entryCards,
436
+ terminalCards,
437
+ branchingCards,
438
+ convergentCards,
439
+ chains,
440
+ cards: cardTrees,
441
+ edges: detailedEdges,
442
+ tags: allTags,
443
+ isolatedCards,
444
+ unresolvedLinks,
445
+ backEdges,
446
+ overLinkedCards,
447
+ crossDocLinks,
448
+ diagnostics: parseDiags,
449
+ treeText,
450
+ };
451
+ }
452
+
453
+ function formatDocumentGraphText(g) {
454
+ const lines = [];
455
+ const shapeLabels = {
456
+ empty: '空画布',
457
+ single_card: '单卡画布',
458
+ disconnected: '存在孤立卡片(未形成连通网)',
459
+ linear_chain: '单一线性链路(建议核对是否存在真实并行分支或汇聚)',
460
+ multi_chain: '多条独立子链',
461
+ branching_tree: '分叉/汇聚树状结构',
462
+ network_dag: '完整有向网状结构(含分叉与汇聚)',
463
+ cyclic_network: '存在反向回环(非法!请删除尾连头或双向互连,保持单向 DAG)',
464
+ };
465
+
466
+ lines.push(`=== Clado 画布拓扑树快照:${g.file} ===`);
467
+ lines.push(`标题: ${g.title || '(无标题)'} | 模板: ${g.templateId || '无'} | 版本: ${g.version.slice(0, 12)}`);
468
+ lines.push(
469
+ `统计: ${g.summary.cardCount} 张卡片 / ${g.summary.nodeCount} 个节点 / `
470
+ + `${g.summary.crossCardEdgeCount} 条跨卡连线 / ${g.summary.tagCount} 个语义Tag / `
471
+ + `${g.summary.crossDocLinkCount} 条跨文档导航`
472
+ );
473
+ lines.push(`拓扑形态: ${shapeLabels[g.summary.networkShape] || g.summary.networkShape} | 健康状态: ${g.summary.healthy ? '正常' : '待修复'}`);
474
+
475
+ if (g.columns.length) {
476
+ lines.push('');
477
+ lines.push('【卡片模式 · 从左到右列布局】');
478
+ for (const c of g.columns) {
479
+ const roleTag = c.column === 0 && g.columns.length > 1 ? ' (入口层)' : (c.column === g.columns.length - 1 && g.columns.length > 1 ? ' (终点层)' : '');
480
+ lines.push(` Col ${c.column}${roleTag}: ${c.cards.map(t => `[${t}]`).join(' | ')}`);
481
+ }
482
+ }
483
+
484
+ if (g.chains.length) {
485
+ lines.push('');
486
+ lines.push('【端到端链路路径】');
487
+ for (const ch of g.chains) {
488
+ lines.push(` • ${ch.join(' ──▶ ')}`);
489
+ }
490
+ }
491
+
492
+ if (g.detailedEdges.length) {
493
+ lines.push('');
494
+ lines.push('【跨卡连线明细】');
495
+ for (const e of g.detailedEdges.slice(0, 60)) {
496
+ const src = e.fromNode.join(' > ');
497
+ const dst = e.toTag ? `${e.toCard}#${e.toTag} (tag)` : (e.toNode.length > 1 ? `${e.toNode.join(' > ')} (section)` : `${e.toCard} (card)`);
498
+ lines.push(` • ${src} --[${e.label}]--> ${dst} (L${e.line})`);
499
+ }
500
+ if (g.detailedEdges.length > 60) lines.push(` ... 其余 ${g.detailedEdges.length - 60} 条连线已省略`);
501
+ }
502
+
503
+ lines.push('');
504
+ lines.push('【完整卡片 / 节点 / Tag 树】');
505
+ const renderNode = (node, indent) => {
506
+ const tagPart = node.tags.length
507
+ ? ' tags: ' + node.tags.map(t => `${t.id ? '#' + t.id : ''}.${t.color}${t.text ? '(' + t.text + ')' : ''}[${t.kind}]`).join(', ')
508
+ : '';
509
+ const linkPart = node.links.length
510
+ ? ' links: ' + node.links.map(l => {
511
+ if (l.status === 'unresolved' || l.status === 'ambiguous') return `[!断链:${l.label}->${l.href}]`;
512
+ if (l.status === 'cross_doc') return `[跨文档:${l.label}->${l.targetFile}${l.targetTag ? '#' + l.targetTag : ''}]`;
513
+ return `[${l.label}->${l.toTag ? '#' + l.toTag : (l.toNode ? l.toNode.join('>') : l.href)}]`;
514
+ }).join(', ')
515
+ : '';
516
+ const hashes = '#'.repeat(node.level);
517
+ lines.push(`${indent}${hashes} ${node.title} (L${node.line ?? '?'}, ${node.words}字)${tagPart}${linkPart}`);
518
+ for (const child of node.children) renderNode(child, indent + ' ');
519
+ };
520
+
521
+ for (const card of g.cardTrees) {
522
+ const flags = [
523
+ `col:${card.column}`,
524
+ `in:${card.inDegree}`,
525
+ `out:${card.outDegree}`,
526
+ ...(card.isolated ? ['⚠孤立卡'] : []),
527
+ ].join(', ');
528
+ const tagPart = card.tags.length
529
+ ? ' tags: ' + card.tags.map(t => `${t.id ? '#' + t.id : ''}.${t.color}${t.text ? '(' + t.text + ')' : ''}[${t.kind}]`).join(', ')
530
+ : '';
531
+ const linkPart = card.links.length
532
+ ? ' links: ' + card.links.map(l => {
533
+ if (l.status === 'unresolved' || l.status === 'ambiguous') return `[!断链:${l.label}->${l.href}]`;
534
+ if (l.status === 'cross_doc') return `[跨文档:${l.label}->${l.targetFile}${l.targetTag ? '#' + l.targetTag : ''}]`;
535
+ return `[${l.label}->${l.toTag ? '#' + l.toTag : (l.toNode ? l.toNode.join('>') : l.href)}]`;
536
+ }).join(', ')
537
+ : '';
538
+ lines.push(`# ${card.title} (${flags}, L${card.line ?? '?'}, ${card.words}字)${tagPart}${linkPart}`);
539
+ for (const child of card.children) renderNode(child, ' ');
540
+ }
541
+
542
+ if (g.crossDocLinks.length) {
543
+ lines.push('');
544
+ lines.push('【跨文档导航】');
545
+ for (const x of g.crossDocLinks) {
546
+ lines.push(` • ${x.fromNode.join(' > ')} --[${x.label}]--> ${x.targetFile}${x.targetTag ? '#' + x.targetTag : (x.targetNode ? '#' + x.targetNode.join('.') : '')}`);
547
+ }
548
+ }
549
+
550
+ if (g.backEdges?.length || g.isolatedCards.length || g.unresolvedLinks.length || g.overLinkedCards?.length || g.summary.isOverDense || g.errors.length || g.warnings.length) {
551
+ lines.push('');
552
+ lines.push('【结构体检与待修复项】');
553
+ if (g.backEdges?.length) {
554
+ lines.push(` [ERROR] 反向回环 / 尾连头 (${g.backEdges.length}): ${g.backEdges.map(e => `${e.from} -> ${e.to}`).join('、')} —— 严禁尾连头或双向互连,请立即删除反向连线,保持从左至右单向有向无环流(DAG)!`);
555
+ }
556
+ if (g.isolatedCards.length) {
557
+ lines.push(` [ERROR] 孤立卡片 (${g.isolatedCards.length}): ${g.isolatedCards.join('、')} —— 未与任何其他卡片连线,请在调用处补充 [说明](目标卡片标题) 或 [说明](#tagId)。`);
558
+ }
559
+ for (const u of g.unresolvedLinks) {
560
+ lines.push(` [WARN] ${u.reason === 'ambiguous' ? '歧义链接' : '未解析断链'} (L${u.line}): ${u.fromNode.join(' > ')} 中的 [${u.label}](${u.href}) 未匹配到任何卡片/小节/Tag。`);
561
+ }
562
+ if (g.overLinkedCards?.length) {
563
+ for (const c of g.overLinkedCards) {
564
+ lines.push(` [WARN] 连线过度发散: 卡片「${c.title}」发出 ${c.outDegree} 条跨卡连线(建议单卡出度 1–3,上限 4),请克制连线,仅保留真实主干执行流!`);
565
+ }
566
+ }
567
+ if (g.summary.isOverDense) {
568
+ lines.push(` [WARN] 连线密度过高 (${g.summary.crossCardEdgeCount} 条线 / ${g.summary.cardCount} 张卡,密度 ${g.summary.edgeDensity}) —— 存在蜘蛛网风险,请剔除概念关联型或跨层捷径连线!`);
569
+ }
570
+ for (const err of g.errors) {
571
+ if (err.code === 'MD_CARD_ISOLATED') continue;
572
+ lines.push(` [ERROR] ${err.code} (L${err.line ?? '?'}): ${err.message}${err.hint ? ' -> ' + err.hint : ''}`);
573
+ }
574
+ for (const w of g.warnings) {
575
+ lines.push(` [WARN] ${w.code} (L${w.line ?? '?'}): ${w.message}`);
576
+ }
577
+ }
578
+
579
+ return lines.join('\n');
580
+ }
581
+
582
+ /**
583
+ * Build workspace-wide graph overview across all canvas documents.
584
+ * @param {Map<string, string>} documents
585
+ */
586
+ export function buildWorkspaceGraph(documents) {
587
+ const files = [...documents.keys()].sort();
588
+ const docs = [];
589
+ const crossDocEdges = [];
590
+
591
+ for (const file of files) {
592
+ const g = buildDocumentGraph(file, documents);
593
+ if (!g) continue;
594
+ docs.push({
595
+ file: g.file,
596
+ title: g.title,
597
+ version: g.version,
598
+ templateId: g.templateId,
599
+ summary: g.summary,
600
+ isolatedCards: g.isolatedCards,
601
+ backEdges: g.backEdges,
602
+ unresolvedLinkCount: g.unresolvedLinks.length,
603
+ columns: g.columns,
604
+ });
605
+ for (const x of g.crossDocLinks) {
606
+ crossDocEdges.push({ fromFile: file, ...x });
607
+ }
608
+ }
609
+
610
+ const lines = [`=== Clado 工作区全部画布拓扑总览 (${docs.length} 份画布) ===`];
611
+ if (!docs.length) {
612
+ lines.push('当前工作区还没有画布文档,请用 clado_create 创建。');
613
+ } else {
614
+ for (const d of docs) {
615
+ const status = d.summary.healthy
616
+ ? 'OK'
617
+ : `待修(回环:${d.summary.backEdgeCount}, 孤立:${d.summary.isolatedCount}, 断链:${d.summary.unresolvedLinkCount}, 错误:${d.summary.errorCount})`;
618
+ lines.push(`- ${d.file} 「${d.title}」: ${d.summary.cardCount}卡 / ${d.summary.crossCardEdgeCount}线 / ${d.summary.tagCount}Tag / 形态:${d.summary.networkShape} [${status}]`);
619
+ if (d.columns.length) {
620
+ lines.push(` 列布局: ${d.columns.map(c => `Col${c.column}[${c.cards.join(', ')}]`).join(' → ')}`);
621
+ }
622
+ if (d.backEdges?.length) {
623
+ lines.push(` ⚠ 反向回环: ${d.backEdges.map(e => `${e.from} -> ${e.to}`).join('、')}`);
624
+ }
625
+ if (d.isolatedCards.length) {
626
+ lines.push(` ⚠ 孤立卡: ${d.isolatedCards.join('、')}`);
627
+ }
628
+ }
629
+ if (crossDocEdges.length) {
630
+ lines.push('');
631
+ lines.push('【画布间跨文档连线】');
632
+ for (const e of crossDocEdges) {
633
+ lines.push(` • ${e.fromFile} (${e.fromCard}) --[${e.label}]--> ${e.targetFile}${e.targetTag ? '#' + e.targetTag : ''}`);
634
+ }
635
+ }
636
+ }
637
+
638
+ return {
639
+ documentCount: docs.length,
640
+ documents: docs,
641
+ crossDocEdges,
642
+ treeText: lines.join('\n'),
643
+ };
644
+ }
645
+
646
+ /**
647
+ * Compact post-write graph health check attached to every mutation tool result.
648
+ * @param {string} file
649
+ * @param {Map<string, string>} documents
650
+ */
651
+ export function buildCompactGraphCheck(file, documents) {
652
+ const g = buildDocumentGraph(file, documents);
653
+ if (!g) return null;
654
+ const issues = [];
655
+ if (g.backEdges.length) {
656
+ issues.push(`有 ${g.backEdges.length} 条反向回环/尾连头连线:${g.backEdges.slice(0, 5).map(e => `${e.from} -> ${e.to}`).join('、')}`);
657
+ }
658
+ if (g.isolatedCards.length) {
659
+ issues.push(`有 ${g.isolatedCards.length} 张孤立卡片未连入网状图:[${g.isolatedCards.join('、')}]`);
660
+ }
661
+ if (g.unresolvedLinks.length) {
662
+ issues.push(`有 ${g.unresolvedLinks.length} 条断链未解析:${g.unresolvedLinks.slice(0, 5).map(u => `[${u.label}](${u.href})@L${u.line}`).join('、')}`);
663
+ }
664
+ const otherErrors = g.diagnostics.filter(d => d.severity === 'error' && d.code !== 'MD_CARD_ISOLATED');
665
+ if (otherErrors.length) {
666
+ issues.push(`有 ${otherErrors.length} 项语法/结构错误:${otherErrors.slice(0, 5).map(e => `${e.code}@L${e.line ?? '?'}: ${e.message}`).join(';')}`);
667
+ }
668
+ const designWarnings = [];
669
+ if (g.overLinkedCards.length) {
670
+ designWarnings.push(`单卡出度过高(${g.overLinkedCards.map(c => `${c.title}:${c.outDegree}条`).join('、')}),请克制连线(建议 1–3 条、最多 4 条)`);
671
+ }
672
+ if (g.summary.isOverDense) {
673
+ designWarnings.push(`整体连线过密(${g.summary.crossCardEdgeCount}条/${g.summary.cardCount}卡,密度 ${g.summary.edgeDensity}),请剔除概念关联型/跨层捷径连线`);
674
+ }
675
+ return {
676
+ file: g.file,
677
+ version: g.version,
678
+ healthy: g.summary.healthy,
679
+ cardCount: g.summary.cardCount,
680
+ crossCardEdgeCount: g.summary.crossCardEdgeCount,
681
+ tagCount: g.summary.tagCount,
682
+ networkShape: g.summary.networkShape,
683
+ columns: g.columns,
684
+ isolatedCards: g.isolatedCards,
685
+ unresolvedLinks: g.unresolvedLinks,
686
+ backEdges: g.backEdges,
687
+ overLinkedCards: g.overLinkedCards,
688
+ errorCount: g.summary.errorCount,
689
+ warningCount: g.summary.warningCount,
690
+ ...(designWarnings.length ? { designWarnings } : {}),
691
+ ...(issues.length
692
+ ? { actionRequired: `⚠️ 画布拓扑体检未通过:${issues.join(';')}。请立即调用 clado_graph 查看连线详情并修复(严禁反向回环、孤立卡与断链)!` }
693
+ : { statusNote: `画布拓扑正常:${g.summary.cardCount} 张卡片、${g.summary.crossCardEdgeCount} 条跨卡连线、0 反向回环、0 孤立卡、0 断链。` }),
694
+ };
695
+ }