cladogram 0.3.1 → 0.5.2

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 (70) hide show
  1. package/README.md +57 -365
  2. package/bin/clado.js +126 -72
  3. package/package.json +11 -8
  4. package/skills/clado/SKILL.md +123 -747
  5. package/src/core/links.js +37 -0
  6. package/src/core/media-links.js +99 -0
  7. package/src/core/parse.js +81 -82
  8. package/src/html/app-css.js +51 -75
  9. package/src/html/canvas-card.js +65 -0
  10. package/src/html/canvas-chain.js +231 -0
  11. package/src/html/canvas-focus.js +175 -0
  12. package/src/html/canvas-ui.css +38 -0
  13. package/src/html/canvas-ui.js +40 -0
  14. package/src/html/canvas-wires.js +73 -0
  15. package/src/html/media-anchors.js +212 -0
  16. package/src/html/mindmap-connectors.js +78 -0
  17. package/src/html/mindmap-media.js +39 -0
  18. package/src/html/page.js +23 -4
  19. package/src/html/runtime-api.js +51 -0
  20. package/src/html/runtime-fixes.js +32 -0
  21. package/src/html/runtime.js +322 -272
  22. package/src/server/assets/library-canvas.js +96 -0
  23. package/src/server/assets/library.css +9 -0
  24. package/src/server/assets/library.html +20 -0
  25. package/src/server/assets/library.js +127 -0
  26. package/src/server/assets/tree.js +26 -0
  27. package/src/server/export.js +53 -0
  28. package/src/server/mcp.js +108 -0
  29. package/src/server/workspace.js +84 -0
  30. package/src/skill/install.js +16 -18
  31. package/src/skill/targets.js +28 -12
  32. package/src/skill/templates.js +60 -0
  33. package/src/util/version.js +3 -0
  34. package/src/workspace/content.js +72 -0
  35. package/src/workspace/documents.js +65 -0
  36. package/src/workspace/references.js +101 -0
  37. package/src/workspace/service.js +457 -0
  38. package/src/workspace/storage.js +169 -0
  39. package/src/workspace/tree.js +66 -0
  40. package/templates/business-flow.mdc +29 -0
  41. package/templates/call-chain.mdc +62 -0
  42. package/templates/data-design.mdc +35 -0
  43. package/templates/mind-expansion.mdc +52 -0
  44. package/templates/requirement-overview.mdc +29 -0
  45. package/templates/system-state.mdc +29 -0
  46. package/examples/showcase/README.md +0 -115
  47. package/examples/showcase/baseline.md +0 -365
  48. package/examples/showcase/build.sh +0 -48
  49. package/examples/showcase/calls.md +0 -136
  50. package/examples/showcase/fulfill-cn.md +0 -351
  51. package/examples/showcase/fulfill.md +0 -271
  52. package/examples/showcase/index.md +0 -187
  53. package/examples/showcase/order.md +0 -195
  54. package/examples/showcase/promo.md +0 -580
  55. package/examples/showcase/refund.md +0 -966
  56. package/examples/showcase/seckill.md +0 -787
  57. package/skills/clado/examples/01-/351/234/200/346/261/202/346/240/221.md +0 -32
  58. package/skills/clado/examples/02-/346/225/260/346/215/256/350/241/250.md +0 -44
  59. package/skills/clado/examples/03-/346/216/245/345/217/243/346/270/205/345/215/225.md +0 -51
  60. package/skills/clado/examples/04-/346/226/271/346/263/225/351/223/276.md +0 -70
  61. package/skills/clado/examples/05-/346/216/245/345/217/243/350/260/203/347/224/250.md +0 -58
  62. package/skills/clado/examples/06-/350/260/203/347/224/250/351/223/276.md +0 -49
  63. package/skills/clado/examples/07-/346/213/206/346/226/207/346/241/243/index.md +0 -38
  64. package/skills/clado/examples/07-/346/213/206/346/226/207/346/241/243/refund.md +0 -33
  65. package/skills/clado/examples/07-/346/213/206/346/226/207/346/241/243/seckill.md +0 -56
  66. package/skills/clado/examples/08-/347/234/237/345/256/236/350/247/204/346/250/241//346/216/245/345/217/243/345/245/221/347/272/246.md +0 -122
  67. package/skills/clado/examples/08-/347/234/237/345/256/236/350/247/204/346/250/241//346/225/205/351/232/234/345/244/215/347/233/230.md +0 -99
  68. package/skills/clado/examples/08-/347/234/237/345/256/236/350/247/204/346/250/241//350/260/203/347/224/250/351/223/276.md +0 -219
  69. package/skills/clado/examples/build.sh +0 -44
  70. package/skills/clado/references/diagnostics.md +0 -129
@@ -0,0 +1,457 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { parseDocument, splitFrontMatter } from '../core/parse.js';
4
+ import { versionOf } from './documents.js';
5
+ import { treeOf, records, findNode, siblings, samePath, insidePath, checkTitle, checkBody, serializeTree, withMetadata } from './tree.js';
6
+ import { ancestorTemplateContexts, contextFor, initialize, locked, mergeAncestorTemplates, snapshot, safeFile, fail, commit, userTemplateContext } from './storage.js';
7
+ import { allReferences, linkHref, resolveReference, rewriteReferences } from './references.js';
8
+ import { editContent, paragraphs, paragraphLocations, contentLocation } from './content.js';
9
+ import { markdownLinks } from '../core/links.js';
10
+ import { blockMedia, mediaLinkLocations, mediaLinkTitle, mediaPointFits, mediaTargetPoint, tableBlock } from '../core/media-links.js';
11
+ import { sortDiagnostics, summarizeDiagnostics } from '../core/diagnostics.js';
12
+
13
+ const copySnapshot = state => ({ ...state, documents: new Map(state.documents), templates: new Map(state.templates) });
14
+ const required = (value, name) => { if (value === undefined || value === null || value === '') fail('缺少参数:' + name); return value; };
15
+ const publicNode = (record, includeContent = true) => ({ path: record.path, parent: record.parent, index: record.index, title: record.node.title, level: record.node.level ?? record.path.length, location: record.node.location, children: record.node.children.map(n => [...record.path, n.title]), ...(includeContent ? { content: record.node.content, paragraphs: paragraphLocations(record.node.content, record.node.location.bodyStartLine) } : {}) });
16
+
17
+ function locatedReferences(documents) {
18
+ const trees = new Map(), indexes = new Map();
19
+ return allReferences(documents).map(ref => {
20
+ if (!trees.has(ref.file)) trees.set(ref.file, treeOf(documents.get(ref.file), ref.file));
21
+ const record = findNode(trees.get(ref.file), ref.node), key = JSON.stringify([ref.file, ref.node]);
22
+ const linkIndex = (indexes.get(key) || 0) + 1; indexes.set(key, linkIndex);
23
+ const { media, ...reference } = ref;
24
+ const point = mediaTargetPoint(ref.link.title);
25
+ const targetPoint = point && ref.target.path && targetMediaPoint(findNode(treeOf(documents.get(ref.target.file), ref.target.file), ref.target.path), point);
26
+ return { ...reference, linkIndex, href: ref.link.target, sourceText: record.node.content.slice(ref.link.start, ref.link.end), location: contentLocation(record.node.content, ref.link.start, ref.link.end, record.node.location.bodyStartLine), ...(media?.valid ? { sourcePoint: publicMediaPoint(record, media) } : {}), ...(targetPoint ? { targetPoint } : {}) };
27
+ });
28
+ }
29
+
30
+ function targetMediaPoint(record, point) {
31
+ const block = tableBlock(record.node.content, point.table);
32
+ if (!block || point.row > block.rows) return null;
33
+ return publicMediaPoint(record, { ...block, point: { kind: 'table', row: point.row } });
34
+ }
35
+
36
+ function publicMediaPoint(record, media) {
37
+ const { paragraph, startLine } = contentLocation(record.node.content, media.blockStart, media.blockEnd, record.node.location.bodyStartLine);
38
+ const offset = media.point.kind === 'code' ? media.point.line : media.point.kind === 'table' ? media.point.row + 1 : 0;
39
+ return { ...media.point, paragraph, ...(media.point.kind === 'mermaid' ? { blockStartLine: startLine } : { documentLine: startLine + offset }) };
40
+ }
41
+
42
+ function remapResults(results, op) {
43
+ for (const result of results) {
44
+ if (result.kind !== 'document' || result.file !== op.file || result.deleted) continue;
45
+ if (op.type === 'document.rename') result.file = op.newFile;
46
+ if (op.type === 'document.delete') result.deleted = true;
47
+ if (!result.node || !op.node || !insidePath(result.node, op.node)) continue;
48
+ if (op.type === 'node.rename') result.node = [...op.node.slice(0, -1), op.title, ...result.node.slice(op.node.length)];
49
+ if (op.type === 'node.move') { result.file = op.targetFile || op.file; result.node = [...(op.parent || []), op.node.at(-1), ...result.node.slice(op.node.length)]; }
50
+ if (op.type === 'node.delete') result.deleted = true;
51
+ }
52
+ }
53
+
54
+ function receipt(op, operationIndex, feedback = {}) {
55
+ if (op.type.startsWith('template.')) return { operationIndex, type: op.type, kind: 'template', file: op.templateId + '.mdc' };
56
+ const result = { operationIndex, type: op.type, kind: 'document', file: ['document.rename','document.copy'].includes(op.type) ? op.newFile : op.type === 'node.move' ? op.targetFile || op.file : op.file };
57
+ if (op.type === 'node.create') result.node = [...(op.parent || []), op.title];
58
+ else if (op.node) result.node = op.type === 'node.rename' ? [...op.node.slice(0, -1), op.title] : op.type === 'node.move' ? [...(op.parent || []), op.node.at(-1)] : op.node;
59
+ if (op.type.endsWith('.delete')) result.deleted = true;
60
+ return { ...result, ...feedback };
61
+ }
62
+
63
+ function resolveResults(state, results) {
64
+ return results.map(({ contentText, contentRange, contentBodyVersion, mediaLinkOnly, ...result }) => {
65
+ if (result.kind === 'template') return { ...result, deleted: !state.templates.has(result.file), ...(state.templates.has(result.file) ? { version: versionOf(state.templates.get(result.file)) } : {}) };
66
+ if (result.deleted || !state.documents.has(result.file)) return { ...result, deleted: true };
67
+ const source = state.documents.get(result.file), tree = treeOf(source, result.file), located = { ...result, version: versionOf(source) };
68
+ if (!result.node) return { ...located, location: { startLine: 1, endLine: source.split('\n').length }, ...(['document.create','document.copy','document.update'].includes(result.type) ? { nodes: records(tree).map(r => ({ path: r.path, index: r.index, location: r.node.location, paragraphs: paragraphLocations(r.node.content, r.node.location.bodyStartLine).map(({ preview, ...position }) => position) })) } : {}) };
69
+ const record = records(tree).find(r => samePath(r.path, result.node));
70
+ if (!record) return { ...located, deleted: true, locationStatus: 'node_no_longer_exists' };
71
+ Object.assign(located, { index: record.index, location: record.node.location, paragraphs: paragraphLocations(record.node.content, record.node.location.bodyStartLine) });
72
+ if (contentText) {
73
+ const unchanged = contentRange && versionOf(record.node.content) === contentBodyVersion && record.node.content.slice(contentRange.start, contentRange.end) === contentText;
74
+ const start = unchanged ? contentRange.start : record.node.content.indexOf(contentText);
75
+ if (start < 0) located.contentLocationStatus = 'changed_by_later_operation';
76
+ else if (!unchanged && record.node.content.indexOf(contentText, start + 1) >= 0) located.contentLocationStatus = 'multiple_matches';
77
+ else {
78
+ located.contentLocationStatus = 'exact';
79
+ located.contentLocation = contentLocation(record.node.content, start, start + contentText.length, record.node.location.bodyStartLine);
80
+ if (mediaLinkOnly) {
81
+ const links = markdownLinks(record.node.content);
82
+ const link = links.find(ref => ref.start === start);
83
+ const point = mediaLinkLocations(record.node.content, links).get(start);
84
+ if (point?.valid) located.sourcePoint = publicMediaPoint(record, point);
85
+ const targetPoint = mediaTargetPoint(link?.title), target = link && resolveReference(link.target, result.file, state.documents);
86
+ if (targetPoint && target?.path) located.targetPoint = targetMediaPoint(findNode(getTree(state, target.file), target.path), targetPoint);
87
+ }
88
+ }
89
+ }
90
+ return located;
91
+ });
92
+ }
93
+
94
+ function templateInfo(ctx, state, id) {
95
+ if (typeof id !== 'string' || !/^[a-zA-Z0-9][\w-]{0,63}$/.test(id)) fail('templateId 使用字母、数字、短横线或下划线,以字母/数字开头,最多64字符。');
96
+ const file = id + '.mdc';
97
+ const source = state.templates.get(file) ?? state.ancestorTemplates?.get(file) ?? state.userTemplates?.get(file) ?? null;
98
+ if (source === null) fail('模板不存在。', 404);
99
+ const { meta, body, had, errors } = splitFrontMatter(source);
100
+ if (!had || errors.length || meta.id !== id || !['name','version','purpose','organization'].every(key => typeof meta[key] === 'string' && meta[key].trim()) || !['hard_constraints','soft_constraints'].every(key => Array.isArray(meta[key]) && meta[key].every(item => typeof item === 'string'))) fail('模板需要有效头部:id、name、version、purpose、hard_constraints、soft_constraints、organization,且id与文件名一致。', 422, { source, version: versionOf(source) });
101
+ const origin = state.templates.has(file) ? 'project' : state.ancestorTemplates?.has(file) ? 'ancestor' : 'user';
102
+ const templateRoot = origin === 'ancestor' ? state.ancestorOrigins.get(file) : origin === 'project' ? ctx.templates : state.userTemplateRoot;
103
+ return { id, origin, templateRoot, version: versionOf(source), metadata: meta, source, starter: body.trim(), prompt: [meta.name, meta.purpose, '必须遵守:', ...meta.hard_constraints.map(x => '- ' + x), '推荐:', ...meta.soft_constraints.map(x => '- ' + x), '组织方式:', meta.organization].join('\n') };
104
+ }
105
+ function getTree(state, file) {
106
+ required(file, 'file'); if (!state.documents.has(file)) fail('文档不存在:' + file, 404);
107
+ const tree = treeOf(state.documents.get(file), file);
108
+ if (tree.diagnostics.some(d => d.severity === 'error')) fail('先用文档 update 修复解析错误,再操作节点。', 422, { diagnostics: tree.diagnostics });
109
+ return tree;
110
+ }
111
+ function validate(state, files = state.documents.keys(), strict = false) {
112
+ const diagnostics = [], trees = new Map();
113
+ for (const file of files) {
114
+ if (!state.documents.has(file)) continue;
115
+ const { diagnostics: list } = parseDocument(state.documents.get(file), { path: file, requireCardConnections: strict });
116
+ const tree = treeOf(state.documents.get(file), file), seen = new Set();
117
+ const all = records(tree); trees.set(file, all);
118
+ diagnostics.push(...list.map(d => {
119
+ if (!d.line) return d;
120
+ const owner = all.find(r => r.node.location.headingLine === d.line) || all.find(r => r.node.location.bodyStartLine !== null && d.line >= r.node.location.bodyStartLine && d.line <= r.node.location.bodyEndLine);
121
+ if (!owner) return d;
122
+ const block = paragraphLocations(owner.node.content, owner.node.location.bodyStartLine).find(p => d.line >= p.startLine && d.line <= p.endLine);
123
+ return { ...d, node: owner.path, ...(block ? { paragraph: block.index } : {}) };
124
+ }));
125
+ for (const record of records(tree)) {
126
+ const key = JSON.stringify(record.path);
127
+ if (seen.has(key)) diagnostics.push({ severity: 'error', code: 'MD_DUPLICATE_NODE', path: file, node: record.path, line: record.node.location.headingLine, message: '同一父节点下标题重复:' + record.path.join(' / ') });
128
+ seen.add(key);
129
+ }
130
+ }
131
+ for (const ref of allReferences(state.documents)) {
132
+ const point = mediaTargetPoint(ref.link.title);
133
+ if (!ref.target.missing && !point) continue;
134
+ if (point && !ref.target.missing && ref.target.path) {
135
+ if (!trees.has(ref.target.file)) trees.set(ref.target.file, records(treeOf(state.documents.get(ref.target.file), ref.target.file)));
136
+ const target = trees.get(ref.target.file).find(r => samePath(r.path, ref.target.path));
137
+ if (target && targetMediaPoint(target, point)) continue;
138
+ }
139
+ if (!trees.has(ref.file)) trees.set(ref.file, records(treeOf(state.documents.get(ref.file), ref.file)));
140
+ const owners = trees.get(ref.file).filter(r => samePath(r.path, ref.node));
141
+ const location = owners.length === 1 ? contentLocation(owners[0].node.content, ref.link.start, ref.link.end, owners[0].node.location.bodyStartLine) : null;
142
+ diagnostics.push({ severity: 'warn', code: ref.target.missing ? 'MD_LINK_UNRESOLVED' : 'MD_MEDIA_LINK_TARGET', path: ref.file, node: ref.node, ...(location ? { line: location.startLine, paragraph: location.paragraph, location } : { nodeAmbiguous: true }), message: (ref.target.missing ? '链接目标未找到或不唯一:' : '连线目标的表格行不存在:') + ref.link.target });
143
+ }
144
+ return diagnostics;
145
+ }
146
+ function fullDiagnostics(ctx, state, templateScope = 'project-template') {
147
+ const list = validate(state, state.documents.keys(), true).map(d => ({ ...d, scope: 'document' }));
148
+ for (const [kind, templates] of [[templateScope, state.templates], ['user-template', state.userTemplates || new Map()]]) {
149
+ for (const [file, source] of templates) {
150
+ try { templateInfo(ctx, { templates: new Map([[file, source]]) }, file.slice(0, -4)); }
151
+ catch (error) { list.push({ severity: 'error', code: 'MDC_TEMPLATE_INVALID', scope: kind, path: file, line: 1, message: error.message }); }
152
+ }
153
+ }
154
+ for (const [file, source] of state.ancestorTemplates || []) {
155
+ if (state.templates.has(file)) continue;
156
+ try { templateInfo(ctx, { templates: new Map([[file, source]]) }, file.slice(0, -4)); }
157
+ catch (error) { list.push({ severity: 'error', code: 'MDC_TEMPLATE_INVALID', scope: 'ancestor-template', path: file, templateRoot: state.ancestorOrigins.get(file), line: 1, message: error.message }); }
158
+ }
159
+ return sortDiagnostics(list);
160
+ }
161
+ function applyOperation(ctx, state, op) {
162
+ const type = required(op.type, 'type'), before = new Map(state.documents);
163
+ if (op.position !== undefined && !['node.insert','node.update','link.connect'].includes(type)) fail('position 仅用于 node.insert/node.update/link.connect。');
164
+ if (op.linkIndex !== undefined && type !== 'link.disconnect') fail('linkIndex 仅用于 link.disconnect;请用 list 读取引用编号。');
165
+ if ((op.sourcePoint !== undefined || op.targetPoint !== undefined) && type !== 'link.connect') fail('sourcePoint/targetPoint 仅用于 link.connect。');
166
+ if (op.from !== undefined && type !== 'template.pull') fail('from 仅用于 template.pull。');
167
+ if (op.scope !== undefined && !type.startsWith('template.')) fail('scope 仅用于模板;文档和节点由 workspace 指定范围。');
168
+ if (type.startsWith('template.')) {
169
+ if (op.scope === 'user') fail('用户模板修改请单独调用 clado_templates scope:user,不放入项目批次。');
170
+ const id = required(op.templateId, 'templateId'), file = id + '.mdc'; safeFile(ctx.templates, file, 'template');
171
+ if (type === 'template.delete') { if (!state.templates.has(file)) fail('该范围内没有此模板副本。', 404); state.templates.delete(file); return; }
172
+ if (type === 'template.pull') {
173
+ const source = (op.from === 'user' ? undefined : state.ancestorTemplates?.get(file)) ?? (op.from === 'ancestor' ? undefined : state.userTemplates?.get(file));
174
+ if (source === undefined) fail('所选来源没有此模板。', 404);
175
+ if (state.templates.has(file) && state.templates.get(file) !== source && !op.overwrite) fail('项目模板已有不同内容;确认替换后使用 overwrite:true。', 409);
176
+ state.templates.set(file, source); templateInfo(ctx, state, id); return;
177
+ }
178
+ const exists = state.templates.has(file) || state.ancestorTemplates?.has(file) || state.userTemplates?.has(file);
179
+ if (type === 'template.create' && exists) fail('模板已存在,请使用 update 创建当前范围的覆盖,或换一个 templateId。', 409);
180
+ if (type === 'template.update' && !exists) fail('模板不存在。', 404);
181
+ if (!['template.create', 'template.update'].includes(type)) fail('不支持的模板操作。');
182
+ let source = op.source;
183
+ if (source === undefined && type === 'template.create') {
184
+ const base = templateInfo(ctx, state, required(op.baseTemplateId, 'baseTemplateId(或提供完整source)'));
185
+ source = withMetadata(base.starter, { ...base.metadata, id, name: op.name || id, ...(op.purpose ? { purpose: op.purpose } : {}) });
186
+ }
187
+ state.templates.set(file, required(source, 'source')); templateInfo(ctx, state, id); return;
188
+ }
189
+ const file = required(op.file, 'file'); safeFile(ctx.documents, file);
190
+ if (type === 'document.create') {
191
+ if (!/\.mdc$/i.test(file)) fail('新文档使用 .mdc;旧 .md 无需改名即可读取和修改。');
192
+ if (state.documents.has(file)) fail('文档已存在,未覆盖。', 409);
193
+ const title = required(op.title, 'title'); checkTitle(title);
194
+ const template = templateInfo(ctx, state, required(op.templateId, 'templateId'));
195
+ const body = op.source ?? template.starter.replaceAll('{{title}}', title);
196
+ if (splitFrontMatter(body.replace(/^\uFEFF/, '')).had) fail('create 的 source 只传正文,模板头部由服务写入。');
197
+ state.documents.set(file, withMetadata(body, { ...template.metadata, title })); return;
198
+ }
199
+ if (!state.documents.has(file)) fail('文档不存在:' + file, 404);
200
+ if (type === 'document.copy') {
201
+ const newFile = required(op.newFile, 'newFile'); safeFile(ctx.documents, newFile);
202
+ if (!/\.mdc$/i.test(newFile)) fail('新复制的文档使用 .mdc。');
203
+ if (state.documents.has(newFile)) fail('目标文档已存在,未覆盖。', 409);
204
+ state.documents.set(newFile, state.documents.get(file));
205
+ rewriteReferences(before, state.documents, { file, newFile, copy: true }); return;
206
+ }
207
+ if (type === 'document.update') {
208
+ const source = required(op.source, 'source');
209
+ state.documents.set(file, op.metadata ? withMetadata(source, op.metadata) : source); return;
210
+ }
211
+ if (type === 'document.rename') {
212
+ const newFile = required(op.newFile, 'newFile'); safeFile(ctx.documents, newFile);
213
+ if (newFile === file) return;
214
+ if (state.documents.has(newFile)) fail('目标文档已存在。', 409);
215
+ state.documents.set(newFile, state.documents.get(file)); state.documents.delete(file);
216
+ rewriteReferences(before, state.documents, { file, newFile }); return;
217
+ }
218
+ if (type === 'document.delete') {
219
+ state.documents.delete(file); rewriteReferences(before, state.documents, { file, deleted: true }, op.unlink === true); return;
220
+ }
221
+ const tree = getTree(state, file);
222
+ if (type === 'node.create') {
223
+ checkTitle(op.title); checkBody(op.content ?? '');
224
+ const parent = op.parent || [], into = siblings(tree, parent);
225
+ const level = parent.length ? findNode(tree, parent).node.level + 1 : 1;
226
+ if (level > 6) fail('节点最多 L6。');
227
+ if (into.some(n => n.title === op.title)) fail('同一父节点下已有此标题。', 409);
228
+ const index = op.index ?? into.length;
229
+ if (!Number.isInteger(index) || index < 0 || index > into.length) fail('index 超出同级节点范围。');
230
+ into.splice(index, 0, { title: op.title, content: op.content || '', level, children: [] });
231
+ state.documents.set(file, serializeTree(tree)); return { contentText: (op.content || '').trim(), contentRange: { start: 0, end: (op.content || '').trim().length }, contentBodyVersion: versionOf((op.content || '').trim()) };
232
+ }
233
+ const record = findNode(tree, required(op.node, 'node'));
234
+ if (type === 'node.update' || type === 'node.insert') {
235
+ if (typeof op.content !== 'string') fail('content 必须为文字,多行正文直接传入。');
236
+ if (type === 'node.insert' && !op.content.trim()) fail('插入内容不能为空。');
237
+ if (type === 'node.update' && op.position && op.position.mode !== 'replace') fail('update 的 position 只支持 replace;插入正文请用 insert。');
238
+ if (type === 'node.insert' && op.position?.mode === 'replace') fail('替换正文请用 update,insert 支持 append/prepend/before/after。');
239
+ const edited = op.position || type === 'node.insert' ? editContent(record.node.content, op.content, op.position) : { content: op.content };
240
+ checkBody(edited.content); record.node.content = edited.content;
241
+ const start = edited.start === undefined ? 0 : edited.start + op.content.length - op.content.trimStart().length;
242
+ state.documents.set(file, serializeTree(tree)); return { contentText: op.content.trim(), contentRange: { start, end: start + op.content.trim().length }, contentBodyVersion: versionOf(edited.content.trim()), ...(op.position || type === 'node.insert' ? { placement: op.position || { mode: 'append' } } : {}) };
243
+ }
244
+ if (type === 'node.rename') {
245
+ checkTitle(op.title);
246
+ if (siblings(tree, record.parent).some(n => n !== record.node && n.title === op.title)) fail('同一父节点下已有此标题。', 409);
247
+ record.node.title = op.title; state.documents.set(file, serializeTree(tree));
248
+ rewriteReferences(before, state.documents, { file, path: record.path, newPath: [...record.parent, op.title] }); return;
249
+ }
250
+ if (type === 'node.move') {
251
+ const parent = op.parent || [], targetFile = op.targetFile || file;
252
+ safeFile(ctx.documents, targetFile);
253
+ const targetTree = targetFile === file ? tree : getTree(state, targetFile);
254
+ if (targetFile === file && insidePath(parent, record.path)) fail('不能把节点移动到自己或后代下面。');
255
+ const into = siblings(targetTree, parent);
256
+ if (into.some(n => n !== record.node && n.title === record.node.title)) fail('目标父节点下已有此标题。', 409);
257
+ const from = siblings(tree, record.parent); from.splice(from.indexOf(record.node), 1);
258
+ const index = op.index ?? into.length; if (!Number.isInteger(index) || index < 0 || index > into.length) fail('index 超出同级节点范围。');
259
+ const level = parent.length ? findNode(targetTree, parent).node.level + 1 : 1, delta = level - record.node.level;
260
+ const relevel = node => { node.level += delta; node.children.forEach(relevel); }; relevel(record.node);
261
+ into.splice(index, 0, record.node); state.documents.set(file, serializeTree(tree));
262
+ if (targetFile !== file) state.documents.set(targetFile, serializeTree(targetTree));
263
+ rewriteReferences(before, state.documents, { file, newFile: targetFile, path: record.path, newPath: [...parent, record.node.title] }); return;
264
+ }
265
+ if (type === 'node.delete') {
266
+ if (record.node.children.length && !op.recursive) fail('节点有后代;删除整棵子树需要 recursive:true。');
267
+ const into = siblings(tree, record.parent); into.splice(into.indexOf(record.node), 1);
268
+ state.documents.set(file, serializeTree(tree));
269
+ rewriteReferences(before, state.documents, { file, path: record.path, deleted: true }, op.unlink === true); return;
270
+ }
271
+ if (type === 'link.connect') {
272
+ const targetFile = op.targetFile || file; safeFile(ctx.documents, targetFile);
273
+ const targetTree = getTree(state, targetFile), targetPath = op.targetNode;
274
+ const targetRecord = targetPath ? findNode(targetTree, targetPath) : null;
275
+ if (targetFile === file && !targetPath) fail('同文档连线需要指定 targetNode。');
276
+ if (targetFile === file && samePath(record.path, targetPath)) fail('不创建自连。');
277
+ const href = linkHref(file, targetFile, targetPath), resolved = resolveReference(href, file, state.documents);
278
+ if (!resolved || resolved.missing || !samePath(resolved.path, targetPath || null)) fail('目标标题路径与其他节点冲突,无法生成唯一链接;请调整同名标题。', 409, { code: 'AMBIGUOUS_LINK_TARGET' });
279
+ const label = op.label || targetPath?.at(-1) || targetTree.doc.title;
280
+ if (/[\r\n\[\]]/.test(label)) fail('label 需要单行文字,不能含方括号。');
281
+ let placement = op.position;
282
+ if (op.targetPoint && !op.sourcePoint) fail('targetPoint 需要同时指定 sourcePoint。');
283
+ if (op.sourcePoint) {
284
+ if (targetFile !== file) fail('精确线端点要连接同一画布内的节点。');
285
+ if (op.position || op.before || op.after) fail('sourcePoint 已经确定位置,独立连线标注不接受 position、before 或 after。');
286
+ const block = paragraphs(record.node.content)[op.sourcePoint.paragraph - 1];
287
+ if (!block || !mediaPointFits(blockMedia(block.text), op.sourcePoint)) fail('指定段落中找不到这个代码行、表格行或 Mermaid 节点。', 422, { code: 'INVALID_MEDIA_SOURCE' });
288
+ placement = { mode: 'after', paragraph: block.index };
289
+ }
290
+ let title = op.sourcePoint ? mediaLinkTitle(op.sourcePoint) : '';
291
+ if (op.targetPoint) {
292
+ const blocks = paragraphs(targetRecord.node.content).slice(0, op.targetPoint.paragraph);
293
+ const last = blocks.at(-1);
294
+ if (last?.index !== op.targetPoint.paragraph || !mediaPointFits(blockMedia(last.text), op.targetPoint)) fail('目标段落中找不到这个表格数据行。', 422, { code: 'INVALID_MEDIA_TARGET' });
295
+ const table = blocks.filter(block => blockMedia(block.text)?.kind === 'table').length;
296
+ title += ';to:' + table + ':' + op.targetPoint.row;
297
+ }
298
+ const linkText = '[' + label + '](<' + href + '>' + (title ? ' "' + title + '"' : '') + ')';
299
+ const text = (op.before || '') + linkText + (op.after || '');
300
+ const edited = editContent(record.node.content, text, placement);
301
+ const expectedStart = edited.start + (op.before || '').length;
302
+ const links = markdownLinks(edited.content);
303
+ if (!links.some(link => link.start === expectedStart && link.target === href)) fail('该位置不能生成独立可解析的链接:不能插入代码或现有链接内部;替换旧链接时请把完整 sourceText 用作 anchor。');
304
+ if (op.sourcePoint && !mediaLinkLocations(edited.content, links).get(expectedStart)?.valid) fail('无法将链接绑定到指定内容。', 422, { code: 'INVALID_MEDIA_SOURCE' });
305
+ checkBody(edited.content); record.node.content = edited.content;
306
+ state.documents.set(file, serializeTree(tree)); return { contentText: linkText, contentRange: { start: expectedStart, end: expectedStart + linkText.length }, contentBodyVersion: versionOf(edited.content), placement: placement || { mode: 'append' }, mediaLinkOnly: !!op.sourcePoint };
307
+ }
308
+ if (type === 'link.disconnect') {
309
+ const matching = locatedReferences(before).filter(r => r.file === file && samePath(r.node, record.path) && (op.linkIndex === undefined || r.linkIndex === op.linkIndex) && (op.linkIndex !== undefined && op.targetFile === undefined && op.targetNode === undefined || r.target.file === (op.targetFile || file) && samePath(r.target.path, op.targetNode || null)));
310
+ if (!matching.length) fail('找不到这条链接。', 404);
311
+ for (const ref of matching.sort((a, b) => b.link.start - a.link.start)) record.node.content = record.node.content.slice(0, ref.link.start) + (ref.link.title?.startsWith('clado:') ? '' : ref.label) + record.node.content.slice(ref.link.end);
312
+ state.documents.set(file, serializeTree(tree)); return;
313
+ }
314
+ fail('不支持的操作:' + type);
315
+ }
316
+
317
+ export function createWorkspaceService(scope, { documentRoot } = {}) {
318
+ scope = resolve(scope);
319
+ const diagnosticCache = new Map();
320
+ function templateLayers(ctx, user) {
321
+ const contexts = ancestorTemplateContexts(ctx.workspace, user);
322
+ const ancestor = mergeAncestorTemplates(contexts);
323
+ return { ancestorRoots: contexts.map(context => context.templates), ancestorTemplates: ancestor.templates, ancestorOrigins: ancestor.origins, userTemplateRoot: user.templates };
324
+ }
325
+ function diagnostics(args) {
326
+ try {
327
+ const ctx = contextFor(scope, args?.workspace, documentRoot);
328
+ if (!existsSync(ctx.documents)) fail('工作区尚未初始化,无法检查全部文档。', 404);
329
+ const user = userTemplateContext();
330
+ const layers = templateLayers(ctx, user);
331
+ const collect = () => {
332
+ const state = snapshot(ctx), userState = snapshot(user), { ancestorRoots, ancestorTemplates, ancestorOrigins } = layers;
333
+ const ancestorVersion = versionOf(JSON.stringify([...ancestorTemplates].map(([file, source]) => [file, ancestorOrigins.get(file), versionOf(source)])));
334
+ const key = JSON.stringify([ctx.workspace, ctx.documents, ctx.templates, user.templates, state.version, userState.version, ancestorRoots, ancestorVersion]);
335
+ if (diagnosticCache.has(key)) return diagnosticCache.get(key);
336
+ const all = fullDiagnostics(ctx, { ...state, ...layers, userTemplates: userState.templates }), summary = summarizeDiagnostics(all);
337
+ const report = { diagnosticSummary: summary, diagnosticsComplete: true, valid: summary.error === 0, diagnosticsVersion: { workspace: state.version, userTemplates: userState.version, ancestorTemplates: ancestorVersion }, diagnosticsScope: { workspace: ctx.workspace, documentRoot: ctx.documents, projectTemplateRoot: ctx.templates, ancestorTemplateRoots: ancestorRoots, userTemplateRoot: user.templates }, diagnostics: all };
338
+ diagnosticCache.clear(); diagnosticCache.set(key, report); return report;
339
+ };
340
+ return locked(ctx, () => ctx.state === user.state ? collect() : locked(user, collect));
341
+ } catch (error) {
342
+ return { diagnostics: [], diagnosticSummary: null, diagnosticsComplete: false, valid: null, diagnosticFailure: { message: error.message, status: error.status || 500 } };
343
+ }
344
+ }
345
+ function invoke(tool, args) {
346
+ const ctx = contextFor(scope, args.workspace, documentRoot);
347
+ if (tool === 'clado_workspace' && args.action === 'init') initialize(ctx);
348
+ if (!existsSync(ctx.documents)) fail('工作区尚未初始化,请先调用 clado_workspace action:init。', 404);
349
+ if (args.from !== undefined && (tool !== 'clado_templates' || args.action !== 'pull')) fail('from 仅用于 template.pull。');
350
+ const user = userTemplateContext();
351
+ const layers = templateLayers(ctx, user);
352
+ const run = () => {
353
+ const userState = snapshot(user), { ancestorRoots } = layers;
354
+ const state = { ...snapshot(ctx), ...layers, userTemplates: userState.templates };
355
+ const common = { workspace: ctx.workspace, workspaceVersion: state.version, userTemplateRoot: user.templates, userTemplateVersion: userState.version };
356
+ if (tool === 'clado_workspace') {
357
+ if (args.action === 'init' || args.action === 'inspect') return { ...common, documentRoot: ctx.documents, templateRoot: ctx.templates, ancestorTemplateRoots: ancestorRoots, documents: [...state.documents].map(([file, source]) => ({ file, version: versionOf(source), title: parseDocument(source).doc.title })) };
358
+ if (args.action === 'validate') { const diagnostics = validate(state, state.documents.keys(), true); return { ...common, valid: !diagnostics.some(d => d.severity === 'error'), diagnostics }; }
359
+ if (args.action === 'search') {
360
+ const query = required(args.query, 'query').toLowerCase(), hits = [];
361
+ for (const [file, source] of state.documents) for (const record of records(treeOf(source, file))) if ((file + '\n' + record.node.title + '\n' + record.node.content).toLowerCase().includes(query)) hits.push({ file, ...publicNode(record, args.includeContent === true) });
362
+ return { ...common, total: hits.length, nodes: hits.slice(args.offset || 0, (args.offset || 0) + (args.limit || 50)) };
363
+ }
364
+ fail('workspace action 支持 init / inspect / validate / search。');
365
+ }
366
+ if (tool === 'clado_templates' && ['list', 'read'].includes(args.action)) {
367
+ const scope = args.scope || 'project', visible = scope === 'user' ? { templates: new Map(), userTemplates: userState.templates, userTemplateRoot: user.templates } : state;
368
+ if (args.action === 'read') {
369
+ const info = templateInfo(ctx, visible, args.templateId);
370
+ const identity = { id: info.id, name: info.metadata.name, templateVersion: info.metadata.version, origin: info.origin, templateRoot: info.templateRoot, version: info.version };
371
+ if (args.view === 'full') return { ...common, scope, ...identity, ...info };
372
+ return { ...common, scope, ...identity, ...(args.view === 'source' ? { source: info.source } : { prompt: info.prompt }) };
373
+ }
374
+ const ids = new Set([...visible.templates.keys(), ...(visible.ancestorTemplates?.keys() || []), ...visible.userTemplates.keys()].map(f => f.replace(/\.mdc$/, '')));
375
+ return { ...common, scope, templates: [...ids].sort().map(id => { try { const t = templateInfo(ctx, visible, id); return { id, name: t.metadata.name, templateVersion: t.metadata.version, version: t.version, origin: t.origin, templateRoot: t.templateRoot, purpose: t.metadata.purpose }; } catch (error) { return { id, valid: false, error: error.message }; } }) };
376
+ }
377
+ if (tool === 'clado_templates' && (args.scope === 'user' || args.action === 'push')) {
378
+ if (args.action === 'pull') fail('pull 写入当前项目,通过 from 选择来源,无需 scope:user。');
379
+ const expected = required(args.expectedUserTemplateVersion, 'expectedUserTemplateVersion');
380
+ if (expected !== userState.version) fail('用户模板库已变化,请重新读取后提交。', 409, { code: 'USER_TEMPLATE_VERSION_CONFLICT', currentVersion: userState.version });
381
+ const candidate = copySnapshot(userState);
382
+ if (args.action === 'push') {
383
+ if (required(args.expectedWorkspaceVersion, 'expectedWorkspaceVersion') !== state.version) fail('工作区已变化,请重新读取后提交。', 409, { code: 'VERSION_CONFLICT', currentVersion: state.version });
384
+ const file = required(args.templateId, 'templateId') + '.mdc'; safeFile(user.templates, file, 'template');
385
+ const source = state.templates.get(file); if (source === undefined) fail('项目中没有该模板副本,请先 pull 或 create。', 404);
386
+ if (candidate.templates.has(file) && candidate.templates.get(file) !== source && !args.overwrite) fail('用户级已有不同模板;确认同步后使用 overwrite:true。', 409);
387
+ candidate.templates.set(file, source); templateInfo(user, candidate, args.templateId);
388
+ } else {
389
+ if (!['create','update','delete'].includes(args.action)) fail('用户模板支持 list/read/create/update/delete。');
390
+ try { applyOperation(user, candidate, { ...args, scope: 'project', type: 'template.' + args.action }); }
391
+ catch (error) { error.details = { ...error.details, previewDiagnostics: fullDiagnostics(user, candidate, 'user-template') }; throw error; }
392
+ }
393
+ if (args.dryRun) return { ...common, dryRun: true, scope: 'user', previewDiagnostics: fullDiagnostics(user, candidate, 'user-template'), changedTemplates: [...new Set([...userState.templates.keys(), ...candidate.templates.keys()])].filter(file => userState.templates.get(file) !== candidate.templates.get(file)) };
394
+ const changes = commit(user, userState, candidate, expected);
395
+ return { ...common, scope: 'user', userTemplateVersion: snapshot(user).version, changes };
396
+ }
397
+ if (tool === 'clado_documents' && args.action === 'list') return { ...common, documents: [...state.documents].filter(([file, source]) => !args.query || (file + source).toLowerCase().includes(args.query.toLowerCase())).map(([file, source]) => { const item = treeOf(source, file); return { file, title: item.doc.title, version: item.version, hasHeader: splitFrontMatter(source).had, cards: item.doc.cards.length, diagnostics: item.diagnostics }; }) };
398
+ if (tool === 'clado_documents' && args.action === 'read') {
399
+ safeFile(ctx.documents, args.file); const source = state.documents.get(args.file); if (source === undefined) fail('文档不存在。', 404);
400
+ const item = treeOf(source, args.file), all = records(item), identity = { ...common, file: args.file, version: item.version, title: item.doc.title };
401
+ if (args.view === 'source') return { ...identity, source };
402
+ if (args.view === 'summary') return { ...identity, cards: item.doc.cards.length, nodeCount: all.length, hasHeader: splitFrontMatter(source).had, templateId: item.doc.meta.id || null, templateVersion: item.doc.meta.version || null };
403
+ if (args.view === 'nodes') return { ...identity, nodes: all.map(r => publicNode(r)) };
404
+ return { ...identity, source, metadata: item.doc.meta, diagnostics: item.diagnostics, nodes: all.map(r => publicNode(r)) };
405
+ }
406
+ if (tool === 'clado_nodes' && ['read', 'query'].includes(args.action)) {
407
+ const tree = getTree(state, args.file), record = findNode(tree, args.node), all = records(tree);
408
+ if (args.action === 'read') return { ...common, file: args.file, ...publicNode(record) };
409
+ let found;
410
+ switch (args.relation) {
411
+ case 'parent': found = all.filter(r => samePath(r.path, record.parent)); break;
412
+ case 'children': found = all.filter(r => samePath(r.parent, record.path)); break;
413
+ case 'ancestors': found = all.filter(r => r.path.length < record.path.length && insidePath(record.path, r.path)); break;
414
+ case 'descendants': found = all.filter(r => r.path.length > record.path.length && insidePath(r.path, record.path) && (!args.depth || r.path.length - record.path.length <= args.depth)); break;
415
+ case 'siblings': found = all.filter(r => samePath(r.parent, record.parent) && !samePath(r.path, record.path)); break;
416
+ case 'upstream': case 'downstream': {
417
+ const refs = allReferences(state.documents).filter(r => !r.target.missing && r.target.path), frontier = [{ file: args.file, path: record.path }], seen = new Set([JSON.stringify(frontier[0])]), hits = [];
418
+ for (let depth = 0; frontier.length && depth < (args.depth || 1); depth++) {
419
+ const current = frontier.splice(0);
420
+ for (const source of current) for (const ref of refs) {
421
+ const from = { file: ref.file, path: ref.node }, to = ref.target;
422
+ const a = args.relation === 'downstream' ? from : to, b = args.relation === 'downstream' ? to : from;
423
+ if (a.file !== source.file || !insidePath(a.path, source.path)) continue;
424
+ const key = JSON.stringify({ file: b.file, path: b.path }); if (seen.has(key)) continue; seen.add(key); hits.push(b); frontier.push(b);
425
+ }
426
+ }
427
+ return { ...common, total: hits.length, nodes: hits.slice(args.offset || 0, (args.offset || 0) + (args.limit || 50)).map(h => ({ file: h.file, ...publicNode(findNode(getTree(state, h.file), h.path), args.includeContent === true) })) };
428
+ }
429
+ default: fail('需要 relation:parent/children/ancestors/descendants/siblings/upstream/downstream。');
430
+ }
431
+ return { ...common, total: found.length, nodes: found.slice(args.offset || 0, (args.offset || 0) + (args.limit || 50)).map(r => publicNode(r, args.includeContent === true)) };
432
+ }
433
+ if (tool === 'clado_links' && args.action === 'list') return { ...common, links: locatedReferences(state.documents).filter(r => (!args.file || r.file === args.file) && (!args.node || samePath(r.node, args.node))).map(({ link, ...ref }) => ref) };
434
+ const operations = tool === 'clado_batch' ? args.operations : [{ ...args, type: ({ clado_documents: 'document.', clado_nodes: 'node.', clado_links: 'link.', clado_templates: 'template.' }[tool] || fail('没有这个工具。')) + args.action }];
435
+ if (!Array.isArray(operations) || !operations.length || operations.length > 100) fail('operations 需要1–100个操作。');
436
+ const expectedVersion = required(args.expectedWorkspaceVersion, 'expectedWorkspaceVersion');
437
+ if (expectedVersion !== state.version) fail('工作区已变化,请重新读取再提交。', 409, { code: 'VERSION_CONFLICT', currentVersion: state.version });
438
+ const candidate = copySnapshot(state);
439
+ const results = [];
440
+ for (let i = 0; i < operations.length; i++) {
441
+ try {
442
+ const feedback = applyOperation(ctx, candidate, operations[i]);
443
+ remapResults(results, operations[i]); results.push(receipt(operations[i], i, feedback));
444
+ } catch (error) { error.details = { ...error.details, operationIndex: i, previewDiagnostics: fullDiagnostics(ctx, candidate) }; throw error; }
445
+ }
446
+ const changedFiles = new Set([...candidate.documents.keys()].filter(file => candidate.documents.get(file) !== state.documents.get(file)));
447
+ const diagnostics = validate(candidate, changedFiles);
448
+ if (diagnostics.some(d => d.severity === 'error')) fail('整批校验失败,未保存任何操作。', 422, { diagnostics, previewDiagnostics: fullDiagnostics(ctx, candidate) });
449
+ const locations = resolveResults(candidate, results);
450
+ if (args.dryRun) return { ...common, dryRun: true, results: locations, previewDiagnostics: fullDiagnostics(ctx, candidate), changedFiles: [...changedFiles], changedTemplates: [...new Set([...state.templates.keys(), ...candidate.templates.keys()])].filter(file => state.templates.get(file) !== candidate.templates.get(file)), diagnostics };
451
+ const changes = commit(ctx, state, candidate, expectedVersion);
452
+ return { ...common, workspaceVersion: snapshot(ctx).version, changes, results: locations, diagnostics };
453
+ };
454
+ return locked(ctx, () => ctx.state === user.state ? run() : locked(user, run));
455
+ }
456
+ return Object.assign(invoke, { diagnostics });
457
+ }