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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +50 -47
  2. package/bin/clado.js +34 -2
  3. package/docs/agent-context.md +63 -0
  4. package/docs/agent-reference.md +219 -0
  5. package/docs/release.md +116 -0
  6. package/package.json +3 -1
  7. package/plugins/agent/index.js +2429 -723
  8. package/plugins/agent/settings.js +3592 -0
  9. package/plugins/agent/style.css +1327 -94
  10. package/plugins/view-controls/index.js +0 -11
  11. package/plugins/view-controls/style.css +7 -14
  12. package/skills/clado/SKILL.md +4 -2
  13. package/src/agent/automations.js +454 -0
  14. package/src/agent/clado-tools.js +597 -104
  15. package/src/agent/pi-bridge.js +2184 -112
  16. package/src/agent/pi-config.js +1889 -108
  17. package/src/agent/pi-hooks-perms.js +621 -0
  18. package/src/html/app-css.js +69 -1
  19. package/src/html/canvas-chain.js +32 -6
  20. package/src/html/canvas-focus.js +19 -13
  21. package/src/html/canvas-live-diff.js +1373 -0
  22. package/src/html/canvas-ui.css +503 -2
  23. package/src/html/canvas-wires.js +5 -1
  24. package/src/html/page.js +4 -2
  25. package/src/html/plugin-assets.js +5 -1
  26. package/src/html/plugin-ui.css +1 -1
  27. package/src/html/runtime-api.js +152 -10
  28. package/src/html/runtime.js +546 -37
  29. package/src/server/agent.js +594 -37
  30. package/src/server/assets/library-canvas.js +256 -9
  31. package/src/server/assets/library.css +567 -12
  32. package/src/server/assets/library.html +2 -0
  33. package/src/server/assets/library.js +1028 -32
  34. package/src/server/code-inspect.js +183 -0
  35. package/src/server/mcp.js +90 -22
  36. package/src/server/plugin-registry.js +664 -2
  37. package/src/server/workspace.js +551 -25
  38. package/src/workspace/graph-snapshot.js +695 -0
  39. package/src/workspace/service.js +201 -9
@@ -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
  }