cladogram 0.5.5-beta.9 → 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 (56) hide show
  1. package/README.md +106 -80
  2. package/bin/clado.js +35 -3
  3. package/docs/agent-context.md +63 -0
  4. package/docs/agent-reference.md +219 -0
  5. package/docs/release.md +123 -0
  6. package/package.json +5 -3
  7. package/plugins/agent/index.js +2485 -2982
  8. package/plugins/agent/settings.js +3592 -0
  9. package/plugins/agent/style.css +1441 -1315
  10. package/plugins/brand/index.js +84 -466
  11. package/plugins/brand/style.css +39 -172
  12. package/plugins/directory/index.js +10 -10
  13. package/plugins/view-controls/index.js +6 -1
  14. package/plugins/view-controls/style.css +41 -30
  15. package/skills/clado/SKILL.md +4 -2
  16. package/src/agent/automations.js +454 -0
  17. package/src/agent/clado-tools.js +792 -0
  18. package/src/agent/pi-bridge.js +2559 -0
  19. package/src/agent/pi-config.js +2411 -0
  20. package/src/agent/pi-hooks-perms.js +621 -0
  21. package/src/html/app-css.js +69 -1
  22. package/src/html/canvas-chain.js +32 -6
  23. package/src/html/canvas-focus.js +19 -13
  24. package/src/html/canvas-live-diff.js +1373 -0
  25. package/src/html/canvas-ui.css +503 -2
  26. package/src/html/canvas-wires.js +5 -1
  27. package/src/html/page.js +4 -2
  28. package/src/html/plugin-assets.js +5 -1
  29. package/src/html/plugin-ui.css +159 -134
  30. package/src/html/plugin-ui.js +3 -2
  31. package/src/html/runtime-api.js +152 -10
  32. package/src/html/runtime.js +546 -37
  33. package/src/server/agent.js +862 -1566
  34. package/src/server/assets/library-canvas.js +256 -9
  35. package/src/server/assets/library.css +951 -11
  36. package/src/server/assets/library.html +39 -4
  37. package/src/server/assets/library.js +1445 -224
  38. package/src/server/code-inspect.js +183 -0
  39. package/src/server/mcp.js +90 -22
  40. package/src/server/plugin-registry.js +671 -9
  41. package/src/server/plugins.js +1 -1
  42. package/src/server/workspace-hub.js +50 -0
  43. package/src/server/workspace.js +554 -39
  44. package/src/workspace/graph-snapshot.js +695 -0
  45. package/src/workspace/service.js +201 -9
  46. package/src/agent/commands.js +0 -204
  47. package/src/agent/context.js +0 -445
  48. package/src/agent/executors.js +0 -213
  49. package/src/agent/mcp-client.js +0 -308
  50. package/src/agent/probe.js +0 -234
  51. package/src/agent/providers/anthropic.js +0 -220
  52. package/src/agent/providers/index.js +0 -235
  53. package/src/agent/providers/openai.js +0 -146
  54. package/src/agent/runtime.js +0 -995
  55. package/src/agent/sessions.js +0 -336
  56. package/src/agent/skills.js +0 -190
@@ -9,6 +9,7 @@ import { editContent, paragraphs, paragraphLocations, contentLocation } from './
9
9
  import { markdownLinks } from '../core/links.js';
10
10
  import { blockMedia, findTargetLineOffset, formatTargetPoint, mediaBlockByIndex, mediaLinkLocations, mediaLinkTitle, mediaPointFits, mediaTargetPoint } from '../core/media-links.js';
11
11
  import { sortDiagnostics, summarizeDiagnostics } from '../core/diagnostics.js';
12
+ import { buildDocumentGraph, buildWorkspaceGraph } from './graph-snapshot.js';
12
13
 
13
14
  const copySnapshot = state => ({ ...state, documents: new Map(state.documents), templates: new Map(state.templates) });
14
15
  const required = (value, name) => { if (value === undefined || value === null || value === '') fail('缺少参数:' + name); return value; };
@@ -196,17 +197,79 @@ function fullDiagnostics(ctx, state, templateScope = 'project-template') {
196
197
  }
197
198
  return sortDiagnostics(list);
198
199
  }
199
- function checkWriteBase(state, op, workspaceGuarded) {
200
+ function extractTagsFromCardSource(text) {
201
+ const tags = new Set();
202
+ for (const m of String(text || '').matchAll(/\{#([a-zA-Z0-9_-]+)(?:\s+\.([a-zA-Z0-9_-]+))?\}/g)) {
203
+ tags.add(m[2] ? `#${m[1]}.${m[2]}` : `#${m[1]}`);
204
+ }
205
+ return tags;
206
+ }
207
+
208
+ function rootCardSnapshots(source, file) {
209
+ const map = new Map();
210
+ if (typeof source !== 'string' || !source.trim()) return map;
211
+ try {
212
+ const tree = treeOf(source, file);
213
+ for (const r of records(tree)) {
214
+ if (r.parent && r.parent.length) continue;
215
+ const title = String(r.node?.title || r.path?.[0] || '').trim();
216
+ if (!title) continue;
217
+ const start = r.node?.location?.startLine ?? 0;
218
+ const end = r.node?.location?.endLine ?? 0;
219
+ const lines = source.replace(/\r\n?/g, '\n').split('\n');
220
+ const slice = (start > 0 && end >= start) ? lines.slice(start - 1, end).join('\n') : String(r.node?.content || '');
221
+ map.set(title, { hash: versionOf(slice), tags: extractTagsFromCardSource(slice) });
222
+ }
223
+ } catch {}
224
+ return map;
225
+ }
226
+
227
+ function diffDocumentCards(file, beforeSource, afterSource) {
228
+ const beforeMap = rootCardSnapshots(beforeSource, file);
229
+ const afterMap = rootCardSnapshots(afterSource, file);
230
+ const changes = [];
231
+ const touchedCards = new Set();
232
+
233
+ for (const [card, after] of afterMap.entries()) {
234
+ const before = beforeMap.get(card);
235
+ if (!before) {
236
+ touchedCards.add(card);
237
+ changes.push({ file, card, action: 'created', addedTags: [...after.tags], removedTags: [] });
238
+ } else if (before.hash !== after.hash) {
239
+ touchedCards.add(card);
240
+ const addedTags = [...after.tags].filter(t => !before.tags.has(t));
241
+ const removedTags = [...before.tags].filter(t => !after.tags.has(t));
242
+ changes.push({ file, card, action: 'updated', addedTags, removedTags });
243
+ }
244
+ }
245
+ for (const [card, before] of beforeMap.entries()) {
246
+ if (!afterMap.has(card)) {
247
+ touchedCards.add(card);
248
+ changes.push({ file, card, action: 'deleted', addedTags: [], removedTags: [...before.tags] });
249
+ }
250
+ }
251
+ return { changes, touchedCards };
252
+ }
253
+
254
+ function checkWriteBase(state, op, workspaceGuarded, rebaseHelper) {
200
255
  const { type, file, node, expectedFileVersion, expectedNodeVersion, position } = op;
256
+ let rebased = false;
201
257
  if (type.startsWith('template.')) {
202
258
  if (expectedFileVersion !== undefined || expectedNodeVersion !== undefined) fail('模板写入使用 expectedWorkspaceVersion。');
203
259
  if (!workspaceGuarded) required(op.expectedWorkspaceVersion, 'expectedWorkspaceVersion');
204
- return;
260
+ return { rebased };
205
261
  }
206
262
  if (expectedFileVersion !== undefined) {
207
263
  const source = state.documents.get(file);
208
264
  const currentVersion = source === undefined ? null : versionOf(source);
209
- if (expectedFileVersion !== currentVersion) fail('文档已变化,请重新读取目标文档。', 409, { code: 'FILE_VERSION_CONFLICT', currentVersion });
265
+ if (expectedFileVersion !== currentVersion) {
266
+ const canRebase = typeof rebaseHelper === 'function' && rebaseHelper(state, op, currentVersion);
267
+ if (canRebase) {
268
+ rebased = true;
269
+ } else {
270
+ fail('文档已变化,请重新读取目标文档。', 409, { code: 'FILE_VERSION_CONFLICT', currentVersion });
271
+ }
272
+ }
210
273
  }
211
274
  if (expectedNodeVersion !== undefined) {
212
275
  if (!node || !/^(node\.(insert|update|rename|move|delete)|link\.(connect|disconnect))$/.test(type)) fail('expectedNodeVersion 需要修改现有节点或它的链接。');
@@ -215,14 +278,15 @@ function checkWriteBase(state, op, workspaceGuarded) {
215
278
  if (expectedNodeVersion !== currentVersion) fail('节点已变化,请重新读取目标节点。', 409, { code: 'NODE_VERSION_CONFLICT', currentVersion, location: record.node.location });
216
279
  }
217
280
  if (!workspaceGuarded && type === 'node.move' && op.index !== undefined && op.targetFile && op.targetFile !== file) fail('跨文档按序号移动需要 expectedWorkspaceVersion。', 400, { code: 'WRITE_BASE_REQUIRED' });
218
- if (workspaceGuarded || expectedFileVersion !== undefined) return;
281
+ if (workspaceGuarded || expectedFileVersion !== undefined) return { rebased };
219
282
  const needsFileVersion = type === 'node.create' && op.index !== undefined || type === 'node.move' && op.index !== undefined || type === 'link.connect' && op.targetPoint && op.targetPoint.kind !== 'line';
220
283
  if (needsFileVersion) fail('按同级序号或目标段落编号写入,需要 expectedFileVersion。', 400, { code: 'WRITE_BASE_REQUIRED' });
221
- if (expectedNodeVersion !== undefined) return;
284
+ if (expectedNodeVersion !== undefined) return { rebased };
222
285
  const safeWithoutVersion = ['document.create', 'document.copy', 'node.create'].includes(type) ||
223
286
  type === 'node.update' && position?.anchor !== undefined ||
224
287
  ['node.insert', 'link.connect'].includes(type) && position?.paragraph === undefined && !op.sourcePoint;
225
288
  if (!safeWithoutVersion) fail('此操作需要目标版本,请使用 expectedFileVersion;节点操作也可使用 expectedNodeVersion。', 400, { code: 'WRITE_BASE_REQUIRED' });
289
+ return { rebased };
226
290
  }
227
291
  function applyOperation(ctx, state, op) {
228
292
  const type = required(op.type, 'type'), before = new Map(state.documents);
@@ -403,6 +467,92 @@ function applyOperation(ctx, state, op) {
403
467
  export function createWorkspaceService(scope, { documentRoot, readSelection } = {}) {
404
468
  scope = resolve(scope);
405
469
  const diagnosticCache = new Map();
470
+ const revisionJournal = new Map(); // `${workspace}::${file}` -> Array<{ fromVersion, toVersion, touchedCards: Set<string> }>
471
+ const idempotencyCache = new Map(); // `${workspace}::${tool}::${key}` -> { ts, result }
472
+ const IDEMPOTENCY_TTL_MS = 5 * 60 * 1000;
473
+
474
+ function recordFileRevision(ws, file, fromVersion, toVersion, touchedCards) {
475
+ if (!file || !fromVersion || !toVersion || fromVersion === toVersion) return;
476
+ const jKey = `${ws}::${file}`;
477
+ let list = revisionJournal.get(jKey);
478
+ if (!list) {
479
+ list = [];
480
+ revisionJournal.set(jKey, list);
481
+ }
482
+ list.push({ fromVersion, toVersion, touchedCards: new Set(touchedCards || []) });
483
+ if (list.length > 48) list.splice(0, list.length - 48);
484
+ }
485
+
486
+ function canAutoRebaseCardOp(ws, state, op, currentVersion) {
487
+ const { type, file, node, expectedFileVersion, expectedNodeVersion } = op;
488
+ if (!file || !expectedFileVersion || !currentVersion) return false;
489
+ if (!/^(node\.(create|insert|update|rename|move|delete)|link\.(connect|disconnect))$/.test(type)) return false;
490
+ // Index-sensitive sibling insertion/move or paragraph-indexed target points cannot safely skip file version check
491
+ if (op.index !== undefined) return false;
492
+ if (op.targetPoint && op.targetPoint.kind !== 'line') return false;
493
+ // 1. If caller also supplied expectedNodeVersion and target node's version is unchanged, target card was untouched!
494
+ if (expectedNodeVersion !== undefined && Array.isArray(node) && node.length) {
495
+ try {
496
+ const rec = findNode(getTree(state, file), node);
497
+ if (nodeVersion(rec) === expectedNodeVersion) return true;
498
+ } catch {
499
+ return false;
500
+ }
501
+ }
502
+ // 2. Otherwise inspect revisionJournal chain expectedFileVersion -> ... -> currentVersion
503
+ const targetCards = new Set();
504
+ if (Array.isArray(node) && node.length) targetCards.add(String(node[0] || '').trim());
505
+ if (Array.isArray(op.parent) && op.parent.length) targetCards.add(String(op.parent[0] || '').trim());
506
+ if (type === 'link.connect' && Array.isArray(op.targetNode) && op.targetNode.length && (!op.targetFile || op.targetFile === file)) {
507
+ targetCards.add(String(op.targetNode[0] || '').trim());
508
+ }
509
+ targetCards.delete('');
510
+ if (!targetCards.size && type !== 'node.create') return false;
511
+
512
+ const list = revisionJournal.get(`${ws}::${file}`) || [];
513
+ let cursor = expectedFileVersion;
514
+ const visited = new Set([cursor]);
515
+ while (cursor !== currentVersion) {
516
+ const step = list.find(entry => entry.fromVersion === cursor && !visited.has(entry.toVersion));
517
+ if (!step) return false;
518
+ for (const tc of targetCards) {
519
+ if (step.touchedCards.has(tc)) return false;
520
+ }
521
+ cursor = step.toVersion;
522
+ visited.add(cursor);
523
+ }
524
+ if (Array.isArray(node) && node.length) {
525
+ try { findNode(getTree(state, file), node); } catch { return false; }
526
+ }
527
+ return true;
528
+ }
529
+
530
+ function readIdempotentResult(ws, tool, key) {
531
+ if (!key || typeof key !== 'string') return null;
532
+ const clean = key.trim();
533
+ if (!clean) return null;
534
+ const now = Date.now();
535
+ const hit = idempotencyCache.get(`${ws}::${tool}::${clean}`);
536
+ if (!hit) return null;
537
+ if (now - hit.ts > IDEMPOTENCY_TTL_MS) {
538
+ idempotencyCache.delete(`${ws}::${tool}::${clean}`);
539
+ return null;
540
+ }
541
+ return { ...hit.result, idempotentReplay: true };
542
+ }
543
+
544
+ function storeIdempotentResult(ws, tool, key, result) {
545
+ if (!key || typeof key !== 'string') return;
546
+ const clean = key.trim();
547
+ if (!clean) return;
548
+ const now = Date.now();
549
+ idempotencyCache.set(`${ws}::${tool}::${clean}`, { ts: now, result });
550
+ if (idempotencyCache.size > 500) {
551
+ const oldestKey = idempotencyCache.keys().next().value;
552
+ if (oldestKey) idempotencyCache.delete(oldestKey);
553
+ }
554
+ }
555
+
406
556
  function templateLayers(ctx, user) {
407
557
  const contexts = ancestorTemplateContexts(ctx.workspace, user);
408
558
  const ancestor = mergeAncestorTemplates(contexts);
@@ -454,12 +604,20 @@ export function createWorkspaceService(scope, { documentRoot, readSelection } =
454
604
  }
455
605
  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 })) };
456
606
  if (args.action === 'validate') { const diagnostics = validate(state, state.documents.keys(), true); return { ...common, valid: !diagnostics.some(d => d.severity === 'error'), diagnostics }; }
607
+ if (args.action === 'graph') {
608
+ if (args.file) {
609
+ safeFile(ctx.documents, args.file);
610
+ if (!state.documents.has(args.file)) fail('文档不存在:' + args.file, 404);
611
+ return { ...common, ...buildDocumentGraph(args.file, state.documents) };
612
+ }
613
+ return { ...common, ...buildWorkspaceGraph(state.documents) };
614
+ }
457
615
  if (args.action === 'search') {
458
616
  const query = required(args.query, 'query').toLowerCase(), hits = [];
459
617
  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) });
460
618
  return { ...common, total: hits.length, nodes: hits.slice(args.offset || 0, (args.offset || 0) + (args.limit || 50)) };
461
619
  }
462
- fail('workspace action 支持 init / inspect / validate / search / selection / workspaces。');
620
+ fail('workspace action 支持 init / inspect / validate / search / selection / workspaces / graph。');
463
621
  }
464
622
  if (tool === 'clado_templates' && ['list', 'read'].includes(args.action)) {
465
623
  const scope = args.scope || 'project', visible = scope === 'user' ? { templates: new Map(), userTemplates: userState.templates, userTemplateRoot: user.templates } : state;
@@ -495,6 +653,7 @@ export function createWorkspaceService(scope, { documentRoot, readSelection } =
495
653
  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 }; }) };
496
654
  if (tool === 'clado_documents' && args.action === 'read') {
497
655
  safeFile(ctx.documents, args.file); const source = state.documents.get(args.file); if (source === undefined) fail('文档不存在。', 404);
656
+ if (args.view === 'graph') return { ...common, ...buildDocumentGraph(args.file, state.documents) };
498
657
  const item = treeOf(source, args.file), all = records(item), identity = { ...common, file: args.file, version: item.version, title: item.doc.title };
499
658
  if (args.view === 'source') return { ...identity, source };
500
659
  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 };
@@ -531,15 +690,22 @@ export function createWorkspaceService(scope, { documentRoot, readSelection } =
531
690
  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) };
532
691
  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 }];
533
692
  if (!Array.isArray(operations) || !operations.length || operations.length > 100) fail('operations 需要1–100个操作。');
693
+ if (!args.dryRun && args.idempotencyKey) {
694
+ const replayed = readIdempotentResult(ctx.workspace, tool, args.idempotencyKey);
695
+ if (replayed) return replayed;
696
+ }
534
697
  const expectedVersion = args.expectedWorkspaceVersion;
535
698
  if (expectedVersion !== undefined && expectedVersion !== state.version) fail('工作区已变化,请重新读取再提交。', 409, { code: 'VERSION_CONFLICT', currentVersion: state.version });
536
699
  const candidate = copySnapshot(state);
537
700
  const results = [];
701
+ let anyRebased = false;
702
+ const rebaseCheck = (st, op, curVer) => canAutoRebaseCardOp(ctx.workspace, st, op, curVer);
538
703
  for (let i = 0; i < operations.length; i++) {
539
704
  try {
540
705
  const op = operations[i];
541
706
  if (op.file !== undefined) safeFile(ctx.documents, op.file);
542
- checkWriteBase(candidate, op, expectedVersion !== undefined);
707
+ const checkRes = checkWriteBase(candidate, op, expectedVersion !== undefined, rebaseCheck);
708
+ if (checkRes?.rebased) anyRebased = true;
543
709
  const feedback = applyOperation(ctx, candidate, op);
544
710
  remapResults(results, op); results.push(receipt(op, i, feedback));
545
711
  } catch (error) {
@@ -552,9 +718,35 @@ export function createWorkspaceService(scope, { documentRoot, readSelection } =
552
718
  const diagnostics = validate(candidate, changedFiles);
553
719
  if (diagnostics.some(d => d.severity === 'error')) fail('整批校验失败,未保存任何操作。', 422, { diagnostics, previewDiagnostics: fullDiagnostics(ctx, candidate) });
554
720
  const locations = resolveResults(candidate, results);
555
- 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 };
721
+ if (args.dryRun) return { ...common, dryRun: true, ...(anyRebased ? { rebased: 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 };
722
+ const cardChanges = [];
723
+ for (const file of changedFiles) {
724
+ const beforeSrc = state.documents.get(file);
725
+ const afterSrc = candidate.documents.get(file);
726
+ const { changes: fileCardDiffs, touchedCards } = diffDocumentCards(file, beforeSrc, afterSrc);
727
+ if (fileCardDiffs.length) cardChanges.push(...fileCardDiffs);
728
+ if (beforeSrc !== undefined && afterSrc !== undefined) {
729
+ recordFileRevision(ctx.workspace, file, versionOf(beforeSrc), versionOf(afterSrc), touchedCards);
730
+ }
731
+ }
732
+ for (const file of state.documents.keys()) {
733
+ if (!candidate.documents.has(file)) {
734
+ const { changes: delDiffs } = diffDocumentCards(file, state.documents.get(file), '');
735
+ if (delDiffs.length) cardChanges.push(...delDiffs);
736
+ }
737
+ }
556
738
  const changes = commit(ctx, state, candidate, state.version);
557
- return { ...common, workspaceVersion: snapshot(ctx).version, changes, results: locations, diagnostics };
739
+ const finalResult = {
740
+ ...common,
741
+ workspaceVersion: snapshot(ctx).version,
742
+ changes,
743
+ results: locations,
744
+ diagnostics,
745
+ ...(anyRebased ? { rebased: true } : {}),
746
+ ...(cardChanges.length ? { cardChanges } : {}),
747
+ };
748
+ if (args.idempotencyKey) storeIdempotentResult(ctx.workspace, tool, args.idempotencyKey, finalResult);
749
+ return finalResult;
558
750
  };
559
751
  return await lockedAsync(ctx, () => needsUserLock ? lockedAsync(user, execute) : execute());
560
752
  }
@@ -1,204 +0,0 @@
1
- /**
2
- * Clado 斜杠命令体系(Slash Commands, `/xxx`):
3
- * - 内置 4 条高频命令(/arch、/test、/diff、/dispatch),统一收编原先写死的工作流入口;
4
- * - 支持工作区(.clado/commands/<name>.md)、全局(~/.clado/commands/<name>.md)与插件(<pluginDir>/commands/<name>.md)自定义命令;
5
- * - 支持 YAML Frontmatter(description / skill / workflow / persona)与 `{{args}}` 参数插值。
6
- */
7
-
8
- import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
9
- import { join } from 'node:path';
10
- import YAML from 'yaml';
11
- import { userTemplatePaths } from '../skill/templates.js';
12
-
13
- const CMD_RE = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/;
14
-
15
- export const BUILTIN_COMMANDS = Object.freeze([
16
- Object.freeze({
17
- name: 'arch',
18
- description: '读取源码并在画布中梳理系统架构与调用链',
19
- workflow: 'design',
20
- persona: 'architect',
21
- prompt: '请先用代码探针核对真实源码结构,再用画布工具梳理或更新架构设计与调用链:{{args}}',
22
- scope: 'builtin',
23
- }),
24
- Object.freeze({
25
- name: 'test',
26
- description: '基于当前画布或源码生成脑图测试用例',
27
- workflow: 'qa',
28
- persona: 'qa',
29
- prompt: '请阅读当前画布与相关源码,按 test-cases 模板生成覆盖正常流、边界与异常流的脑图测试用例:{{args}}',
30
- scope: 'builtin',
31
- }),
32
- Object.freeze({
33
- name: 'diff',
34
- description: '读取本地 Git Diff,对照画布设计逐项验收与归档',
35
- workflow: 'audit',
36
- persona: 'auditor',
37
- prompt: '请调用 probe_git_diff 读取本地真实代码变更,对照画布契约逐项验收并指出遗漏或偏离项:{{args}}',
38
- scope: 'builtin',
39
- }),
40
- Object.freeze({
41
- name: 'dispatch',
42
- description: '打包当前架构规格并派发给外部 ACP 执行器落地编码',
43
- workflow: 'dispatch',
44
- persona: 'coder',
45
- prompt: '{{args}}',
46
- scope: 'builtin',
47
- }),
48
- ]);
49
-
50
- function globalCommandsDir() {
51
- return join(userTemplatePaths().state, 'commands');
52
- }
53
-
54
- function workspaceCommandsDir(workspace) {
55
- return workspace ? join(workspace, '.clado', 'commands') : '';
56
- }
57
-
58
- export function parseCommandMarkdown(raw, fallbackName = '') {
59
- const text = String(raw || '').replace(/\r\n/g, '\n');
60
- let meta = {};
61
- let body = text.trim();
62
-
63
- const fm = text.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
64
- if (fm) {
65
- try {
66
- const parsed = YAML.parse(fm[1]);
67
- if (parsed && typeof parsed === 'object') meta = parsed;
68
- } catch {}
69
- body = fm[2].trim();
70
- }
71
-
72
- return {
73
- name: typeof meta.name === 'string' && CMD_RE.test(meta.name.trim()) ? meta.name.trim() : fallbackName,
74
- description: typeof meta.description === 'string' && meta.description.trim()
75
- ? meta.description.trim()
76
- : (body.split('\n')[0] || '自定义斜杠命令').slice(0, 100),
77
- skill: typeof meta.skill === 'string' ? meta.skill.trim() : '',
78
- workflow: typeof meta.workflow === 'string' ? meta.workflow.trim() : '',
79
- persona: typeof meta.persona === 'string' ? meta.persona.trim() : '',
80
- prompt: body,
81
- };
82
- }
83
-
84
- export function serializeCommandMarkdown({ description = '', skill = '', workflow = '', persona = '', prompt = '' }) {
85
- const fm = {};
86
- if (description) fm.description = String(description).trim();
87
- if (skill) fm.skill = String(skill).trim();
88
- if (workflow) fm.workflow = String(workflow).trim();
89
- if (persona) fm.persona = String(persona).trim();
90
- const header = Object.keys(fm).length ? `---\n${YAML.stringify(fm).trim()}\n---\n\n` : '';
91
- return `${header}${String(prompt || '').trim()}\n`;
92
- }
93
-
94
- function scanCommandsInDir(dir, scope, pluginId = '') {
95
- if (!dir || !existsSync(dir)) return [];
96
- const items = [];
97
- let entries = [];
98
- try {
99
- entries = readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
100
- } catch {
101
- return [];
102
- }
103
- for (const entry of entries) {
104
- if (entry.name.startsWith('.') || !/\.md$/i.test(entry.name)) continue;
105
- const slug = entry.name.replace(/\.md$/i, '');
106
- if (!CMD_RE.test(slug)) continue;
107
- const full = join(dir, entry.name);
108
- try {
109
- const st = lstatSync(full);
110
- if (!st.isFile() || st.isSymbolicLink()) continue;
111
- const parsed = parseCommandMarkdown(readFileSync(full, 'utf8'), slug);
112
- items.push({
113
- ...parsed,
114
- name: parsed.name || slug,
115
- scope,
116
- ...(pluginId ? { pluginId } : {}),
117
- });
118
- } catch {}
119
- }
120
- return items;
121
- }
122
-
123
- export function listCommands(workspace, { pluginDirs = [] } = {}) {
124
- const merged = new Map();
125
- for (const cmd of BUILTIN_COMMANDS) merged.set(cmd.name, { ...cmd });
126
-
127
- for (const p of pluginDirs || []) {
128
- if (!p?.dir) continue;
129
- for (const cmd of scanCommandsInDir(join(p.dir, 'commands'), 'plugin', p.id || '')) {
130
- merged.set(cmd.name, cmd);
131
- }
132
- }
133
- for (const cmd of scanCommandsInDir(globalCommandsDir(), 'global')) {
134
- merged.set(cmd.name, cmd);
135
- }
136
- for (const cmd of scanCommandsInDir(workspaceCommandsDir(workspace), 'workspace')) {
137
- merged.set(cmd.name, cmd);
138
- }
139
-
140
- return [...merged.values()];
141
- }
142
-
143
- export function saveCommand(workspace, { name, description = '', prompt = '', skill = '', workflow = '', persona = '', scope = 'workspace' } = {}) {
144
- const cleanName = String(name || '')
145
- .trim()
146
- .replace(/^\/+/, '')
147
- .toLowerCase();
148
- if (!CMD_RE.test(cleanName)) {
149
- throw new Error('命令名仅支持英文字母、数字、连字符或下划线(如 review、api-spec)。');
150
- }
151
- const cleanPrompt = String(prompt || '').trim();
152
- if (!cleanPrompt) throw new Error('命令提示词模板不能为空。');
153
-
154
- const baseDir = scope === 'global' || !workspace ? globalCommandsDir() : workspaceCommandsDir(workspace);
155
- mkdirSync(baseDir, { recursive: true, mode: 0o700 });
156
- const filePath = join(baseDir, `${cleanName}.md`);
157
- writeFileSync(filePath, serializeCommandMarkdown({ description, skill, workflow, persona, prompt: cleanPrompt }), 'utf8');
158
- return {
159
- name: cleanName,
160
- description: String(description || cleanPrompt.slice(0, 80)).trim(),
161
- skill: String(skill || '').trim(),
162
- workflow: String(workflow || '').trim(),
163
- persona: String(persona || '').trim(),
164
- prompt: cleanPrompt,
165
- scope: scope === 'global' || !workspace ? 'global' : 'workspace',
166
- };
167
- }
168
-
169
- export function deleteCommand(workspace, { name, scope = 'workspace' } = {}) {
170
- const cleanName = String(name || '').trim().replace(/^\/+/, '').toLowerCase();
171
- if (!CMD_RE.test(cleanName)) return false;
172
- const baseDir = scope === 'global' || !workspace ? globalCommandsDir() : workspaceCommandsDir(workspace);
173
- const filePath = join(baseDir, `${cleanName}.md`);
174
- if (!existsSync(filePath)) return false;
175
- rmSync(filePath, { force: true });
176
- return true;
177
- }
178
-
179
- export function expandSlashCommand(workspace, rawInput = '', { pluginDirs = [] } = {}) {
180
- const text = String(rawInput || '').trim();
181
- const m = text.match(/^\/([a-zA-Z0-9][a-zA-Z0-9_-]{0,47})(?:\s+([\s\S]*))?$/);
182
- if (!m) return null;
183
-
184
- const cmdName = m[1].toLowerCase();
185
- const args = (m[2] || '').trim();
186
- const cmd = listCommands(workspace, { pluginDirs }).find(c => c.name.toLowerCase() === cmdName);
187
- if (!cmd) return null;
188
-
189
- let expanded = cmd.prompt || '';
190
- if (expanded.includes('{{args}}')) {
191
- expanded = expanded.replace(/\{\{args\}\}/g, args || '(当前画布与项目上下文)');
192
- } else if (args) {
193
- expanded = expanded ? `${expanded}\n\n补充参数:${args}` : args;
194
- }
195
-
196
- return {
197
- command: cmd,
198
- args,
199
- prompt: expanded.trim() || text,
200
- workflow: cmd.workflow || '',
201
- persona: cmd.persona || '',
202
- skill: cmd.skill || '',
203
- };
204
- }