cladogram 0.6.0-beta.5 → 0.6.0-beta.7

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.
@@ -197,17 +197,79 @@ function fullDiagnostics(ctx, state, templateScope = 'project-template') {
197
197
  }
198
198
  return sortDiagnostics(list);
199
199
  }
200
- 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) {
201
255
  const { type, file, node, expectedFileVersion, expectedNodeVersion, position } = op;
256
+ let rebased = false;
202
257
  if (type.startsWith('template.')) {
203
258
  if (expectedFileVersion !== undefined || expectedNodeVersion !== undefined) fail('模板写入使用 expectedWorkspaceVersion。');
204
259
  if (!workspaceGuarded) required(op.expectedWorkspaceVersion, 'expectedWorkspaceVersion');
205
- return;
260
+ return { rebased };
206
261
  }
207
262
  if (expectedFileVersion !== undefined) {
208
263
  const source = state.documents.get(file);
209
264
  const currentVersion = source === undefined ? null : versionOf(source);
210
- 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
+ }
211
273
  }
212
274
  if (expectedNodeVersion !== undefined) {
213
275
  if (!node || !/^(node\.(insert|update|rename|move|delete)|link\.(connect|disconnect))$/.test(type)) fail('expectedNodeVersion 需要修改现有节点或它的链接。');
@@ -216,14 +278,15 @@ function checkWriteBase(state, op, workspaceGuarded) {
216
278
  if (expectedNodeVersion !== currentVersion) fail('节点已变化,请重新读取目标节点。', 409, { code: 'NODE_VERSION_CONFLICT', currentVersion, location: record.node.location });
217
279
  }
218
280
  if (!workspaceGuarded && type === 'node.move' && op.index !== undefined && op.targetFile && op.targetFile !== file) fail('跨文档按序号移动需要 expectedWorkspaceVersion。', 400, { code: 'WRITE_BASE_REQUIRED' });
219
- if (workspaceGuarded || expectedFileVersion !== undefined) return;
281
+ if (workspaceGuarded || expectedFileVersion !== undefined) return { rebased };
220
282
  const needsFileVersion = type === 'node.create' && op.index !== undefined || type === 'node.move' && op.index !== undefined || type === 'link.connect' && op.targetPoint && op.targetPoint.kind !== 'line';
221
283
  if (needsFileVersion) fail('按同级序号或目标段落编号写入,需要 expectedFileVersion。', 400, { code: 'WRITE_BASE_REQUIRED' });
222
- if (expectedNodeVersion !== undefined) return;
284
+ if (expectedNodeVersion !== undefined) return { rebased };
223
285
  const safeWithoutVersion = ['document.create', 'document.copy', 'node.create'].includes(type) ||
224
286
  type === 'node.update' && position?.anchor !== undefined ||
225
287
  ['node.insert', 'link.connect'].includes(type) && position?.paragraph === undefined && !op.sourcePoint;
226
288
  if (!safeWithoutVersion) fail('此操作需要目标版本,请使用 expectedFileVersion;节点操作也可使用 expectedNodeVersion。', 400, { code: 'WRITE_BASE_REQUIRED' });
289
+ return { rebased };
227
290
  }
228
291
  function applyOperation(ctx, state, op) {
229
292
  const type = required(op.type, 'type'), before = new Map(state.documents);
@@ -404,6 +467,92 @@ function applyOperation(ctx, state, op) {
404
467
  export function createWorkspaceService(scope, { documentRoot, readSelection } = {}) {
405
468
  scope = resolve(scope);
406
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
+
407
556
  function templateLayers(ctx, user) {
408
557
  const contexts = ancestorTemplateContexts(ctx.workspace, user);
409
558
  const ancestor = mergeAncestorTemplates(contexts);
@@ -541,15 +690,22 @@ export function createWorkspaceService(scope, { documentRoot, readSelection } =
541
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) };
542
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 }];
543
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
+ }
544
697
  const expectedVersion = args.expectedWorkspaceVersion;
545
698
  if (expectedVersion !== undefined && expectedVersion !== state.version) fail('工作区已变化,请重新读取再提交。', 409, { code: 'VERSION_CONFLICT', currentVersion: state.version });
546
699
  const candidate = copySnapshot(state);
547
700
  const results = [];
701
+ let anyRebased = false;
702
+ const rebaseCheck = (st, op, curVer) => canAutoRebaseCardOp(ctx.workspace, st, op, curVer);
548
703
  for (let i = 0; i < operations.length; i++) {
549
704
  try {
550
705
  const op = operations[i];
551
706
  if (op.file !== undefined) safeFile(ctx.documents, op.file);
552
- checkWriteBase(candidate, op, expectedVersion !== undefined);
707
+ const checkRes = checkWriteBase(candidate, op, expectedVersion !== undefined, rebaseCheck);
708
+ if (checkRes?.rebased) anyRebased = true;
553
709
  const feedback = applyOperation(ctx, candidate, op);
554
710
  remapResults(results, op); results.push(receipt(op, i, feedback));
555
711
  } catch (error) {
@@ -562,9 +718,35 @@ export function createWorkspaceService(scope, { documentRoot, readSelection } =
562
718
  const diagnostics = validate(candidate, changedFiles);
563
719
  if (diagnostics.some(d => d.severity === 'error')) fail('整批校验失败,未保存任何操作。', 422, { diagnostics, previewDiagnostics: fullDiagnostics(ctx, candidate) });
564
720
  const locations = resolveResults(candidate, results);
565
- 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
+ }
566
738
  const changes = commit(ctx, state, candidate, state.version);
567
- 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;
568
750
  };
569
751
  return await lockedAsync(ctx, () => needsUserLock ? lockedAsync(user, execute) : execute());
570
752
  }