cladogram 0.6.0-beta.4 → 0.6.0-beta.6
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.
- package/README.md +50 -47
- package/docs/agent-context.md +3 -2
- package/docs/agent-reference.md +11 -0
- package/docs/release.md +36 -0
- package/package.json +1 -1
- package/plugins/agent/index.js +932 -153
- package/plugins/agent/style.css +142 -33
- package/plugins/view-controls/index.js +0 -11
- package/plugins/view-controls/style.css +0 -7
- package/skills/clado/SKILL.md +4 -2
- package/src/agent/automations.js +474 -0
- package/src/agent/clado-tools.js +160 -1
- package/src/agent/pi-bridge.js +788 -61
- package/src/html/app-css.js +4 -0
- package/src/html/canvas-chain.js +6 -4
- package/src/html/canvas-live-diff.js +208 -91
- package/src/html/canvas-ui.css +3 -10
- package/src/html/runtime-api.js +6 -0
- package/src/html/runtime.js +179 -73
- package/src/server/agent.js +242 -9
- package/src/server/assets/library-canvas.js +4 -0
- package/src/server/assets/library.css +139 -0
- package/src/server/assets/library.js +281 -23
- package/src/server/mcp.js +88 -20
- package/src/server/workspace.js +165 -3
- package/src/workspace/service.js +190 -8
package/src/server/workspace.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createServer } from 'node:http';
|
|
2
2
|
import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
|
|
3
|
-
import { readFileSync, statSync, existsSync, mkdirSync } from 'node:fs';
|
|
3
|
+
import { readFileSync, readdirSync, statSync, existsSync, mkdirSync } from 'node:fs';
|
|
4
4
|
import { dirname, resolve, basename, join, relative, sep, isAbsolute } from 'node:path';
|
|
5
5
|
import { fileURLToPath } from 'node:url';
|
|
6
6
|
import { renderHtml } from '../html/page.js';
|
|
@@ -39,6 +39,7 @@ const resourceTypes = {
|
|
|
39
39
|
};
|
|
40
40
|
const types = { html: 'text/html', css: 'text/css', js: 'text/javascript', json: 'application/json', md: 'text/markdown' };
|
|
41
41
|
const REMOTE_COOKIE = 'clado_remote_token';
|
|
42
|
+
const listWorkspaceFilesCache = new Map();
|
|
42
43
|
|
|
43
44
|
function isTrustedOrigin(req, remote = false) {
|
|
44
45
|
const origin = req.headers.origin;
|
|
@@ -193,6 +194,10 @@ export function createWorkspaceHandler(directory, options = {}) {
|
|
|
193
194
|
const target = resolveTarget(url);
|
|
194
195
|
await options.agent.handleConfig(req, res, target.workspace); return true;
|
|
195
196
|
}
|
|
197
|
+
if (options.agent && url.pathname === '/library/agent/automations' && options.agent.handleAutomations) {
|
|
198
|
+
const target = resolveTarget(url);
|
|
199
|
+
await options.agent.handleAutomations(req, res, url, target.workspace); return true;
|
|
200
|
+
}
|
|
196
201
|
if (options.agent && url.pathname === '/library/agent') {
|
|
197
202
|
const target = resolveTarget(url);
|
|
198
203
|
await options.agent.handle(req, res, target.workspace); return true;
|
|
@@ -402,6 +407,41 @@ export function createWorkspaceHandler(directory, options = {}) {
|
|
|
402
407
|
json(res, 200, readFileGitState(target.workspace, relPath));
|
|
403
408
|
return true;
|
|
404
409
|
}
|
|
410
|
+
if (url.pathname === '/library/workspace-files') {
|
|
411
|
+
const target = resolveTarget(url);
|
|
412
|
+
const q = String(url.searchParams.get('q') || '').trim().toLowerCase();
|
|
413
|
+
const cache = listWorkspaceFilesCache.get(target.workspace);
|
|
414
|
+
const now = Date.now();
|
|
415
|
+
let files;
|
|
416
|
+
if (cache && now - cache.ts < 5000) {
|
|
417
|
+
files = cache.files;
|
|
418
|
+
} else {
|
|
419
|
+
files = [];
|
|
420
|
+
const skipDirs = new Set(['.git', 'node_modules', 'dist', 'build', '.next', '.nuxt', '.cache', 'coverage', '.venv', 'venv', '__pycache__', 'target', 'vendor', '.clado', '.pi']);
|
|
421
|
+
const walk = (dir, depth) => {
|
|
422
|
+
if (depth > 5 || files.length >= 400) return;
|
|
423
|
+
let entries;
|
|
424
|
+
try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
|
|
425
|
+
for (const ent of entries) {
|
|
426
|
+
if (files.length >= 400) break;
|
|
427
|
+
if (ent.name.startsWith('.') && ent.name !== '.env.example') continue;
|
|
428
|
+
if (skipDirs.has(ent.name)) continue;
|
|
429
|
+
const full = join(dir, ent.name);
|
|
430
|
+
if (ent.isDirectory()) {
|
|
431
|
+
walk(full, depth + 1);
|
|
432
|
+
} else if (ent.isFile()) {
|
|
433
|
+
files.push(relative(target.workspace, full).split(sep).join('/'));
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
};
|
|
437
|
+
walk(target.workspace, 0);
|
|
438
|
+
files.sort((a, b) => a.localeCompare(b));
|
|
439
|
+
listWorkspaceFilesCache.set(target.workspace, { ts: now, files });
|
|
440
|
+
}
|
|
441
|
+
const matched = q ? files.filter(f => f.toLowerCase().includes(q)) : files;
|
|
442
|
+
json(res, 200, { files: matched.slice(0, 80), total: matched.length });
|
|
443
|
+
return true;
|
|
444
|
+
}
|
|
405
445
|
if (pluginsEnabled && url.pathname === '/library/plugins.json') {
|
|
406
446
|
const target = resolveTarget(url);
|
|
407
447
|
const values = target.settings?.values() || {};
|
|
@@ -545,7 +585,40 @@ export async function startWorkspace(input, { port = 4317, host = '', remote = f
|
|
|
545
585
|
return current?.expiresAt > Date.now() ? current : null;
|
|
546
586
|
};
|
|
547
587
|
const events = createWorkspaceEvents();
|
|
588
|
+
let agent = null;
|
|
548
589
|
let baseService = createWorkspaceService(workspace, { documentRoot: root, readSelection });
|
|
590
|
+
const emitWorkspaceSystemEvents = (targetWorkspace, tool, input, result, sourceMeta = {}) => {
|
|
591
|
+
if (!agent?.notifySystemEvent || !result || input?.dryRun) return;
|
|
592
|
+
const file = String(input?.file || result?.changes?.[0]?.file || '').trim();
|
|
593
|
+
if (Array.isArray(result.cardChanges) && result.cardChanges.length) {
|
|
594
|
+
for (const ch of result.cardChanges) {
|
|
595
|
+
agent.notifySystemEvent(targetWorkspace, `card.${ch.action}`, {
|
|
596
|
+
file: ch.file,
|
|
597
|
+
card: ch.card,
|
|
598
|
+
addedTags: ch.addedTags,
|
|
599
|
+
removedTags: ch.removedTags,
|
|
600
|
+
...sourceMeta,
|
|
601
|
+
});
|
|
602
|
+
if ((ch.addedTags?.length || 0) > 0 || (ch.removedTags?.length || 0) > 0) {
|
|
603
|
+
agent.notifySystemEvent(targetWorkspace, 'tag.changed', {
|
|
604
|
+
file: ch.file,
|
|
605
|
+
card: ch.card,
|
|
606
|
+
addedTags: ch.addedTags,
|
|
607
|
+
removedTags: ch.removedTags,
|
|
608
|
+
...sourceMeta,
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
if (tool === 'clado_documents') {
|
|
614
|
+
const map = { create: 'doc.created', update: 'doc.updated', rename: 'doc.renamed', delete: 'doc.deleted' };
|
|
615
|
+
const evt = map[input?.action];
|
|
616
|
+
if (evt) agent.notifySystemEvent(targetWorkspace, evt, { file, ...sourceMeta });
|
|
617
|
+
} else if (tool === 'clado_links') {
|
|
618
|
+
if (input?.action === 'connect') agent.notifySystemEvent(targetWorkspace, 'link.connected', { file, card: input?.node?.[0] || '', ...sourceMeta });
|
|
619
|
+
if (input?.action === 'disconnect') agent.notifySystemEvent(targetWorkspace, 'link.disconnected', { file, card: input?.node?.[0] || '', ...sourceMeta });
|
|
620
|
+
}
|
|
621
|
+
};
|
|
549
622
|
const mcpService = async (tool, input = {}) => {
|
|
550
623
|
const result = await baseService(tool, input);
|
|
551
624
|
try {
|
|
@@ -555,8 +628,92 @@ export async function startWorkspace(input, { port = 4317, host = '', remote = f
|
|
|
555
628
|
return result;
|
|
556
629
|
};
|
|
557
630
|
mcpService.diagnostics = (...a) => baseService.diagnostics(...a);
|
|
631
|
+
|
|
632
|
+
const externalMcpService = async (tool, input = {}) => {
|
|
633
|
+
const targetWorkspace = input?.workspace ? resolve(input.workspace) : workspace;
|
|
634
|
+
const isWrite = !input?.dryRun && (
|
|
635
|
+
tool === 'clado_batch'
|
|
636
|
+
|| (tool === 'clado_documents' && ['create', 'copy', 'update', 'rename', 'delete'].includes(input?.action))
|
|
637
|
+
|| (tool === 'clado_nodes' && ['create', 'insert', 'update', 'rename', 'move', 'delete'].includes(input?.action))
|
|
638
|
+
|| (tool === 'clado_links' && ['connect', 'disconnect'].includes(input?.action))
|
|
639
|
+
);
|
|
640
|
+
const mcpCards = [];
|
|
641
|
+
if (Array.isArray(input?.node) && input.node.length) mcpCards.push(String(input.node[0]));
|
|
642
|
+
if (Array.isArray(input?.targetNode) && input.targetNode.length && !input.targetFile) mcpCards.push(String(input.targetNode[0]));
|
|
643
|
+
if (input?.title) mcpCards.push(String(input.title));
|
|
644
|
+
const mcpVerb = input?.action === 'delete' ? '正在删除'
|
|
645
|
+
: input?.action === 'create' ? '正在新建'
|
|
646
|
+
: input?.action === 'connect' ? '正在连线'
|
|
647
|
+
: input?.action === 'disconnect' ? '正在移除连线'
|
|
648
|
+
: '正在编辑';
|
|
649
|
+
const mcpSessionId = 'mcp_external';
|
|
650
|
+
if (isWrite && mcpCards.length) {
|
|
651
|
+
events.emit(targetWorkspace, 'agent.presence', {
|
|
652
|
+
sessionId: mcpSessionId,
|
|
653
|
+
roleId: 'mcp',
|
|
654
|
+
roleName: '外部 MCP',
|
|
655
|
+
tone: 'amber',
|
|
656
|
+
file: String(input?.file || ''),
|
|
657
|
+
cards: [...new Set(mcpCards)],
|
|
658
|
+
label: mcpVerb,
|
|
659
|
+
phase: 'active',
|
|
660
|
+
ts: Date.now(),
|
|
661
|
+
});
|
|
662
|
+
}
|
|
663
|
+
try {
|
|
664
|
+
const result = await mcpService(tool, input);
|
|
665
|
+
if (isWrite) {
|
|
666
|
+
const resultCards = Array.isArray(result?.cardChanges)
|
|
667
|
+
? [...new Set(result.cardChanges.map(c => c.card).filter(Boolean))]
|
|
668
|
+
: [];
|
|
669
|
+
if (resultCards.length) {
|
|
670
|
+
events.emit(targetWorkspace, 'agent.presence', {
|
|
671
|
+
sessionId: mcpSessionId,
|
|
672
|
+
roleId: 'mcp',
|
|
673
|
+
roleName: '外部 MCP',
|
|
674
|
+
tone: 'amber',
|
|
675
|
+
file: String(result.cardChanges[0]?.file || input?.file || ''),
|
|
676
|
+
cards: resultCards,
|
|
677
|
+
label: mcpVerb,
|
|
678
|
+
phase: 'active',
|
|
679
|
+
ts: Date.now(),
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
events.emit(targetWorkspace, 'agent.presence', {
|
|
683
|
+
sessionId: mcpSessionId,
|
|
684
|
+
roleId: 'mcp',
|
|
685
|
+
roleName: '外部 MCP',
|
|
686
|
+
tone: 'amber',
|
|
687
|
+
file: String(input?.file || ''),
|
|
688
|
+
cards: [],
|
|
689
|
+
label: '刚刚编辑了',
|
|
690
|
+
phase: 'afterglow',
|
|
691
|
+
ts: Date.now(),
|
|
692
|
+
});
|
|
693
|
+
emitWorkspaceSystemEvents(targetWorkspace, tool, input, result, { originRoleId: 'mcp', originSessionId: mcpSessionId });
|
|
694
|
+
}
|
|
695
|
+
return result;
|
|
696
|
+
} catch (err) {
|
|
697
|
+
if (isWrite) {
|
|
698
|
+
events.emit(targetWorkspace, 'agent.presence', {
|
|
699
|
+
sessionId: mcpSessionId,
|
|
700
|
+
roleId: 'mcp',
|
|
701
|
+
roleName: '外部 MCP',
|
|
702
|
+
tone: 'amber',
|
|
703
|
+
file: String(input?.file || ''),
|
|
704
|
+
cards: [],
|
|
705
|
+
label: '刚刚编辑了',
|
|
706
|
+
phase: 'afterglow',
|
|
707
|
+
ts: Date.now(),
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
throw err;
|
|
711
|
+
}
|
|
712
|
+
};
|
|
713
|
+
externalMcpService.diagnostics = (...a) => baseService.diagnostics(...a);
|
|
714
|
+
|
|
558
715
|
const liveMcpUrl = () => 'http://127.0.0.1:' + server.address().port + '/mcp';
|
|
559
|
-
|
|
716
|
+
agent = agentName !== 'off' ? (await import('./agent.js')).createAgentHandler({
|
|
560
717
|
workspace: () => workspace,
|
|
561
718
|
mcpUrl: liveMcpUrl,
|
|
562
719
|
workspaceService: mcpService,
|
|
@@ -810,7 +967,12 @@ export async function startWorkspace(input, { port = 4317, host = '', remote = f
|
|
|
810
967
|
scopeName:() => basename(workspace),
|
|
811
968
|
inactivePlugins:() => rootRuntime.inactivePlugins(),
|
|
812
969
|
});
|
|
813
|
-
const mcp = createMcpHandler(
|
|
970
|
+
const mcp = createMcpHandler(externalMcpService, capabilities.invoke, {
|
|
971
|
+
remote: isRemote,
|
|
972
|
+
remoteToken,
|
|
973
|
+
invokeSession: agent ? args => agent.handleMcpSessions(args) : null,
|
|
974
|
+
invokeAutomation: agent ? args => agent.handleMcpAutomations(args) : null,
|
|
975
|
+
});
|
|
814
976
|
const server = createServer(async (req,res) => {
|
|
815
977
|
try { const url = new URL(req.url,'http://127.0.0.1'); if (!await mcp(req,res,url) && !await handle(req,res,url)) { res.writeHead(404);res.end('Not found'); } }
|
|
816
978
|
catch { if (!res.headersSent) res.writeHead(500);res.end('预览请求失败'); }
|
package/src/workspace/service.js
CHANGED
|
@@ -197,17 +197,79 @@ function fullDiagnostics(ctx, state, templateScope = 'project-template') {
|
|
|
197
197
|
}
|
|
198
198
|
return sortDiagnostics(list);
|
|
199
199
|
}
|
|
200
|
-
function
|
|
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)
|
|
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
|
-
|
|
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
|
}
|