cladogram 0.5.4 → 0.5.5-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +8 -6
  2. package/bin/clado.js +5 -5
  3. package/docs/release.md +13 -0
  4. package/package.json +1 -1
  5. package/plugins/agent/index.js +458 -25
  6. package/plugins/agent/style.css +299 -8
  7. package/plugins/directory/capabilities.json +1 -1
  8. package/plugins/directory/index.js +57 -2
  9. package/plugins/directory/style.css +11 -0
  10. package/plugins/view-controls/index.js +1 -1
  11. package/plugins/view-controls/style.css +30 -10
  12. package/skills/clado/SKILL.md +17 -16
  13. package/src/agent/executors.js +213 -0
  14. package/src/agent/probe.js +176 -0
  15. package/src/agent/providers/anthropic.js +220 -0
  16. package/src/agent/providers/index.js +52 -0
  17. package/src/agent/providers/openai.js +146 -0
  18. package/src/agent/runtime.js +557 -0
  19. package/src/agent/sessions.js +129 -0
  20. package/src/html/app-css.js +62 -9
  21. package/src/html/canvas-chain.js +2 -1
  22. package/src/html/canvas-ui.css +63 -0
  23. package/src/html/page.js +4 -0
  24. package/src/html/plugin-ui.css +12 -0
  25. package/src/html/plugin-ui.js +8 -2
  26. package/src/html/runtime-api.js +136 -5
  27. package/src/html/runtime.js +160 -290
  28. package/src/html/view-registry.js +95 -0
  29. package/src/html/views/view-cards.js +28 -0
  30. package/src/html/views/view-doc.js +51 -0
  31. package/src/html/views/view-mindmap.js +173 -0
  32. package/src/server/agent.js +335 -17
  33. package/src/server/assets/library-canvas.js +13 -3
  34. package/src/server/assets/library-plugin-bridge.js +2 -2
  35. package/src/server/assets/library-plugins.js +2 -2
  36. package/src/server/assets/library.css +5 -0
  37. package/src/server/assets/library.html +1 -1
  38. package/src/server/assets/library.js +157 -20
  39. package/src/server/events.js +189 -0
  40. package/src/server/export.js +1 -1
  41. package/src/server/mcp.js +16 -16
  42. package/src/server/plugin-capabilities.js +38 -22
  43. package/src/server/plugin-settings.js +27 -1
  44. package/src/server/plugins.js +17 -4
  45. package/src/server/workspace.js +171 -56
  46. package/src/skill/install.js +1 -1
  47. package/src/skill/targets.js +3 -3
  48. package/src/util/update.js +3 -2
  49. package/src/workspace/service.js +23 -15
  50. package/src/workspace/storage.js +88 -20
  51. package/templates/business-flow.mdc +1 -1
  52. package/templates/call-chain.mdc +1 -1
  53. package/templates/data-design.mdc +1 -1
  54. package/templates/test-cases.mdc +47 -0
@@ -157,7 +157,7 @@ export function findTarget(id) {
157
157
  export function ruleBody(skillPath) {
158
158
  return `# clado —— Markdown 三视图工作区
159
159
 
160
- 这个项目用 Clado 维护 Markdown 画布,在脑图、卡片和文档视图中讨论与迭代,也可打包成单个离线 HTML。
160
+ 这个项目用 Clado 维护 Markdown 画布,在卡片、脑图和文档视图中讨论与迭代,也可打包成单个离线 HTML。
161
161
 
162
162
  写或改画布前,先读 Skill 入口:
163
163
 
@@ -176,9 +176,9 @@ export function ruleBody(skillPath) {
176
176
 
177
177
  clado serve
178
178
 
179
- 连接输出的 Streamable HTTP MCP。每次调用提供输出的 workspace,先 clado_workspace inspect,再 clado_templates read 提示词,用 clado_documents create 按模板初始化 .mdc;节点、链接与批量操作也用MCP。正文直接传多行字符串。新建、追加和唯一原文编辑可直接提交;覆盖和删除使用对应的版本。用户提到选中的卡片时通过 clado_workspace selection 读取。模板可在项目 create/update,用 pull 从用户库复制,用 push 同步到用户库;push 同时带 expectedUserTemplateVersion。
179
+ 连接输出的 Streamable HTTP MCP。每次调用提供输出的 workspace,先 clado_workspace inspect,再 clado_templates read 提示词,用 clado_documents create 按模板初始化 .mdc;节点、链接与批量操作也用MCP。跨卡连接优先从具体内容行出发(代码行、表格数据行、Mermaid 节点或步骤正文内的行内链接),避免为凑连线单独追加裸的卡片连卡片。正文直接传多行字符串。新建、追加和唯一原文编辑可直接提交;覆盖和删除使用对应的版本。用户提到选中的卡片时通过 clado_workspace selection 读取。模板可在项目 create/update,用 pull 从用户库复制,用 push 同步到用户库;push 同时带 expectedUserTemplateVersion。
180
180
 
181
- 网页只展示脑图/卡片/文档,保存后自动更新。交付可用 clado build --entry overview.mdc --mode cards;默认生成只读 clado.html。工具不执行文档里的SQL、脚本或发布任务。
181
+ 网页只展示卡片/脑图/文档,保存后自动更新。交付可用 clado build --entry overview.mdc --mode cards;默认生成只读 clado.html。工具不执行文档里的SQL、脚本或发布任务。
182
182
 
183
183
  `;
184
184
  }
@@ -10,9 +10,10 @@ const cacheLifetime = 24 * 60 * 60 * 1000;
10
10
 
11
11
  function updateInfo(latest) {
12
12
  if (typeof latest !== 'string' || !stableVersion.test(latest)) throw new Error('npm 未返回可用的稳定版本。');
13
- const installed = VERSION.split('.').map(Number), remote = latest.split('.').map(Number);
13
+ const [core, pre = ''] = VERSION.split('-');
14
+ const installed = core.split('.').map(Number), remote = latest.split('.').map(Number);
14
15
  const difference = remote.map((part, index) => part - installed[index]).find(value => value !== 0) || 0;
15
- return { current: VERSION, latest, updateAvailable: difference > 0 };
16
+ return { current: VERSION, latest, updateAvailable: difference > 0 || (difference === 0 && Boolean(pre)) };
16
17
  }
17
18
 
18
19
  export async function checkUpdate() {
@@ -3,7 +3,7 @@ import { resolve } from 'node:path';
3
3
  import { parseDocument, splitFrontMatter } from '../core/parse.js';
4
4
  import { versionOf } from './documents.js';
5
5
  import { treeOf, records, findNode, siblings, samePath, insidePath, checkTitle, checkBody, serializeTree, replaceNodeBody, withMetadata } from './tree.js';
6
- import { ancestorTemplateContexts, contextFor, initialize, locked, mergeAncestorTemplates, snapshot, safeFile, fail, commit, userTemplateContext } from './storage.js';
6
+ import { ancestorTemplateContexts, contextFor, discoverWorkspaces, initialize, lockedAsync, mergeAncestorTemplates, snapshot, safeFile, fail, commit, userTemplateContext } from './storage.js';
7
7
  import { allReferences, linkHref, resolveReference, rewriteReferences } from './references.js';
8
8
  import { editContent, paragraphs, paragraphLocations, contentLocation } from './content.js';
9
9
  import { markdownLinks } from '../core/links.js';
@@ -233,7 +233,7 @@ function applyOperation(ctx, state, op) {
233
233
  }
234
234
  const file = required(op.file, 'file'); safeFile(ctx.documents, file);
235
235
  if (type === 'document.create') {
236
- if (!/\.mdc$/i.test(file)) fail('新文档使用 .mdc;旧 .md 无需改名即可读取和修改。');
236
+ if (!/\.mdc?$/i.test(file)) fail('文档扩展名需要 .md 或 .mdc。');
237
237
  if (state.documents.has(file)) fail('文档已存在,未覆盖。', 409);
238
238
  const title = required(op.title, 'title'); checkTitle(title);
239
239
  const template = templateInfo(ctx, state, required(op.templateId, 'templateId'));
@@ -244,7 +244,7 @@ function applyOperation(ctx, state, op) {
244
244
  if (!state.documents.has(file)) fail('文档不存在:' + file, 404);
245
245
  if (type === 'document.copy') {
246
246
  const newFile = required(op.newFile, 'newFile'); safeFile(ctx.documents, newFile);
247
- if (!/\.mdc$/i.test(newFile)) fail('新复制的文档使用 .mdc。');
247
+ if (!/\.mdc?$/i.test(newFile)) fail('复制后的文档扩展名需要 .md 或 .mdc。');
248
248
  if (state.documents.has(newFile)) fail('目标文档已存在,未覆盖。', 409);
249
249
  state.documents.set(newFile, state.documents.get(file));
250
250
  rewriteReferences(before, state.documents, { file, newFile, copy: true }); return;
@@ -371,7 +371,7 @@ export function createWorkspaceService(scope, { documentRoot, readSelection } =
371
371
  const ancestor = mergeAncestorTemplates(contexts);
372
372
  return { ancestorRoots: contexts.map(context => context.templates), ancestorTemplates: ancestor.templates, ancestorOrigins: ancestor.origins, userTemplateRoot: user.templates };
373
373
  }
374
- function diagnostics(args) {
374
+ async function diagnostics(args) {
375
375
  try {
376
376
  const ctx = contextFor(scope, args?.workspace, documentRoot);
377
377
  if (!existsSync(ctx.documents)) fail('工作区尚未初始化,无法检查全部文档。', 404);
@@ -381,30 +381,38 @@ export function createWorkspaceService(scope, { documentRoot, readSelection } =
381
381
  const state = snapshot(ctx), userState = snapshot(user), { ancestorRoots, ancestorTemplates, ancestorOrigins } = layers;
382
382
  const ancestorVersion = versionOf(JSON.stringify([...ancestorTemplates].map(([file, source]) => [file, ancestorOrigins.get(file), versionOf(source)])));
383
383
  const key = JSON.stringify([ctx.workspace, ctx.documents, ctx.templates, user.templates, state.version, userState.version, ancestorRoots, ancestorVersion]);
384
- if (diagnosticCache.has(key)) return diagnosticCache.get(key);
384
+ const cached = diagnosticCache.get(ctx.workspace);
385
+ if (cached?.key === key) return cached.report;
385
386
  const all = fullDiagnostics(ctx, { ...state, ...layers, userTemplates: userState.templates }), summary = summarizeDiagnostics(all);
386
387
  const report = { diagnosticSummary: summary, diagnosticsComplete: true, valid: summary.error === 0, diagnosticsVersion: { workspace: state.version, userTemplates: userState.version, ancestorTemplates: ancestorVersion }, diagnosticsScope: { workspace: ctx.workspace, documentRoot: ctx.documents, projectTemplateRoot: ctx.templates, ancestorTemplateRoots: ancestorRoots, userTemplateRoot: user.templates }, diagnostics: all };
387
- diagnosticCache.clear(); diagnosticCache.set(key, report); return report;
388
+ diagnosticCache.delete(ctx.workspace);
389
+ diagnosticCache.set(ctx.workspace, { key, report });
390
+ if (diagnosticCache.size > 64) diagnosticCache.delete(diagnosticCache.keys().next().value);
391
+ return report;
388
392
  };
389
- return locked(ctx, () => ctx.state === user.state ? collect() : locked(user, collect));
393
+ return await lockedAsync(ctx, collect);
390
394
  } catch (error) {
391
395
  return { diagnostics: [], diagnosticSummary: null, diagnosticsComplete: false, valid: null, diagnosticFailure: { message: error.message, status: error.status || 500 } };
392
396
  }
393
397
  }
394
- function invoke(tool, args) {
398
+ async function invoke(tool, args) {
395
399
  const ctx = contextFor(scope, args.workspace, documentRoot);
396
- if (tool === 'clado_workspace' && args.action === 'init') initialize(ctx);
397
- if (!existsSync(ctx.documents)) fail('工作区尚未初始化,请先调用 clado_workspace action:init。', 404);
400
+ if (tool === 'clado_workspace' && args.action === 'workspaces') {
401
+ return { workspace: ctx.workspace, scope, workspaces: discoverWorkspaces(scope, documentRoot) };
402
+ }
398
403
  if (args.from !== undefined && (tool !== 'clado_templates' || args.action !== 'pull')) fail('from 仅用于 template.pull。');
399
404
  const user = userTemplateContext();
400
- const layers = templateLayers(ctx, user);
401
- const run = () => {
405
+ const needsUserLock = ctx.state !== user.state && tool === 'clado_templates' && (args.scope === 'user' || args.action === 'push');
406
+ const execute = () => {
407
+ if (tool === 'clado_workspace' && args.action === 'init') initialize(ctx, { alreadyLocked: true });
408
+ if (!existsSync(ctx.documents)) fail('工作区尚未初始化,请先调用 clado_workspace action:init。', 404);
409
+ const layers = templateLayers(ctx, user);
402
410
  const userState = snapshot(user), { ancestorRoots } = layers;
403
411
  const state = { ...snapshot(ctx), ...layers, userTemplates: userState.templates };
404
412
  const common = { workspace: ctx.workspace, workspaceVersion: state.version, userTemplateRoot: user.templates, userTemplateVersion: userState.version };
405
413
  if (tool === 'clado_workspace') {
406
414
  if (args.action === 'selection') {
407
- const selection = ctx.workspace === scope ? readSelection?.() : null;
415
+ const selection = readSelection?.(ctx.workspace) || null;
408
416
  return { ...common, ...projectSelection(state, selection) };
409
417
  }
410
418
  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 })) };
@@ -414,7 +422,7 @@ export function createWorkspaceService(scope, { documentRoot, readSelection } =
414
422
  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) });
415
423
  return { ...common, total: hits.length, nodes: hits.slice(args.offset || 0, (args.offset || 0) + (args.limit || 50)) };
416
424
  }
417
- fail('workspace action 支持 init / inspect / validate / search / selection。');
425
+ fail('workspace action 支持 init / inspect / validate / search / selection / workspaces。');
418
426
  }
419
427
  if (tool === 'clado_templates' && ['list', 'read'].includes(args.action)) {
420
428
  const scope = args.scope || 'project', visible = scope === 'user' ? { templates: new Map(), userTemplates: userState.templates, userTemplateRoot: user.templates } : state;
@@ -511,7 +519,7 @@ export function createWorkspaceService(scope, { documentRoot, readSelection } =
511
519
  const changes = commit(ctx, state, candidate, state.version);
512
520
  return { ...common, workspaceVersion: snapshot(ctx).version, changes, results: locations, diagnostics };
513
521
  };
514
- return locked(ctx, () => ctx.state === user.state ? run() : locked(user, run));
522
+ return await lockedAsync(ctx, () => needsUserLock ? lockedAsync(user, execute) : execute());
515
523
  }
516
524
  return Object.assign(invoke, { diagnostics });
517
525
  }
@@ -1,9 +1,12 @@
1
1
  import { readFileSync, writeFileSync, readdirSync, existsSync, mkdirSync, realpathSync, statSync, openSync, closeSync, unlinkSync, renameSync } from 'node:fs';
2
- import { resolve, dirname, join, relative, sep, isAbsolute } from 'node:path';
2
+ import { resolve, dirname, basename, join, relative, sep, isAbsolute } from 'node:path';
3
3
  import { randomBytes } from 'node:crypto';
4
4
  import { DocumentError, versionOf } from './documents.js';
5
5
  import { installUserTemplates, templateName } from '../skill/templates.js';
6
6
 
7
+ const waitBuffer = new Int32Array(new SharedArrayBuffer(4));
8
+ const lockQueues = new Map();
9
+
7
10
  export function userTemplateContext() {
8
11
  const { state, templates } = installUserTemplates({ onlyIfMissing: true });
9
12
  return { workspace: state, documents: null, templates, state };
@@ -21,19 +24,19 @@ export function safeFile(root, file, kind = 'document') {
21
24
  }
22
25
  export function contextFor(scope, workspace, documentRoot) {
23
26
  if (typeof workspace !== 'string' || !isAbsolute(workspace)) fail('每次工具调用必须提供 workspace 的绝对路径。');
24
- const path = resolve(workspace);
25
- if (!contained(scope, path)) fail('工作区超出 serve 启动目录。', 403);
27
+ const scopeRoot = resolve(scope), path = resolve(workspace);
28
+ if (!contained(scopeRoot, path)) fail('工作区超出 serve 启动目录。', 403);
26
29
  let ancestor = path; while (!existsSync(ancestor)) ancestor = dirname(ancestor);
27
- if (!contained(realpathSync(scope), realpathSync(ancestor))) fail('工作区符号链接指向启动目录之外。', 403);
30
+ if (!contained(realpathSync(scopeRoot), realpathSync(ancestor))) fail('工作区符号链接指向启动目录之外。', 403);
28
31
  const state = join(path, '.clado'), templates = join(state, 'templates');
29
- const boundary = existsSync(path) ? realpathSync(path) : realpathSync(scope);
32
+ const boundary = existsSync(path) ? realpathSync(path) : realpathSync(scopeRoot);
30
33
  for (const child of [state, templates]) {
31
34
  let ancestor = child; while (!existsSync(ancestor)) ancestor = dirname(ancestor);
32
35
  if (!contained(boundary, realpathSync(ancestor))) fail('工作区内部目录指向其他工作区。', 403);
33
36
  }
34
- let documents = path === scope && documentRoot ? documentRoot : join(state, 'doc');
37
+ let documents = path === scopeRoot && documentRoot ? documentRoot : join(state, 'doc');
35
38
  const config = join(state, 'workspace.json');
36
- if (!documentRoot && existsSync(config)) {
39
+ if ((path !== scopeRoot || !documentRoot) && existsSync(config)) {
37
40
  const data = JSON.parse(readFileSync(config, 'utf8'));
38
41
  if (!['.', '.clado/doc'].includes(data.documentRoot)) fail('工作区配置无效。', 422);
39
42
  documents = resolve(path, data.documentRoot);
@@ -44,6 +47,34 @@ export function contextFor(scope, workspace, documentRoot) {
44
47
  }
45
48
  return { workspace: path, documents, templates, state };
46
49
  }
50
+ export function discoverWorkspaces(scope, rootDocumentRoot) {
51
+ const root = resolve(scope), items = [], seen = new Set();
52
+ const push = dir => {
53
+ const normalized = resolve(dir);
54
+ if (seen.has(normalized)) return;
55
+ seen.add(normalized);
56
+ try {
57
+ const ctx = contextFor(root, normalized, rootDocumentRoot);
58
+ const id = relative(root, normalized).split(sep).join('/');
59
+ items.push({ id, name: basename(normalized), workspace: ctx.workspace, documentRoot: ctx.documents, documents: fileMap(ctx.documents).size });
60
+ } catch {}
61
+ };
62
+ push(root);
63
+ const walk = (directory, depth = 0) => {
64
+ if (depth > 6 || items.length >= 200 || !existsSync(directory)) return;
65
+ let entries;
66
+ try { entries = readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name)); }
67
+ catch { return; }
68
+ for (const entry of entries) {
69
+ if (!entry.isDirectory() || entry.name.startsWith('.') || ['node_modules', 'dist'].includes(entry.name)) continue;
70
+ const full = join(directory, entry.name);
71
+ if (existsSync(join(full, '.clado', 'workspace.json')) || existsSync(join(full, '.clado', 'doc'))) push(full);
72
+ walk(full, depth + 1);
73
+ }
74
+ };
75
+ walk(root, 0);
76
+ return items;
77
+ }
47
78
  export function ancestorTemplateContexts(workspace, user) {
48
79
  const contexts = [];
49
80
  let directory = dirname(workspace);
@@ -60,7 +91,7 @@ export function ancestorTemplateContexts(workspace, user) {
60
91
  export function mergeAncestorTemplates(contexts) {
61
92
  const templates = new Map(), origins = new Map();
62
93
  for (const context of contexts) {
63
- const files = locked(context, () => templateFiles(context.templates));
94
+ const files = templateFiles(context.templates);
64
95
  for (const [file, source] of files) {
65
96
  if (templates.has(file)) continue;
66
97
  templates.set(file, source);
@@ -69,21 +100,23 @@ export function mergeAncestorTemplates(contexts) {
69
100
  }
70
101
  return { templates, origins };
71
102
  }
72
- export function initialize(ctx) {
103
+ export function initialize(ctx, { alreadyLocked = false } = {}) {
73
104
  const config = join(ctx.state, 'workspace.json');
74
105
  const first = !existsSync(config) || !existsSync(ctx.templates);
75
106
  const user = userTemplateContext();
76
107
  mkdirSync(ctx.workspace, { recursive: true }); mkdirSync(ctx.documents, { recursive: true }); mkdirSync(ctx.templates, { recursive: true });
77
108
  if (!first) return;
78
- const defaults = ctx.state === user.state ? new Map() : locked(user, () => templateFiles(user.templates));
109
+ const defaults = ctx.state === user.state ? new Map() : templateFiles(user.templates);
79
110
  const inherited = mergeAncestorTemplates(ancestorTemplateContexts(ctx.workspace, user)).templates;
80
- locked(ctx, () => {
111
+ const write = () => {
81
112
  for (const [name, source] of new Map([...defaults, ...inherited])) {
82
113
  const file = safeFile(ctx.templates, name, 'template');
83
114
  if (!existsSync(file)) atom(file, source);
84
115
  }
85
116
  if (!existsSync(config)) atom(config, JSON.stringify({ documentRoot: ctx.documents === ctx.workspace ? '.' : '.clado/doc' }, null, 2) + '\n');
86
- });
117
+ };
118
+ if (alreadyLocked) write();
119
+ else locked(ctx, write);
87
120
  }
88
121
  export function templateFiles(root) {
89
122
  const files = new Map();
@@ -132,19 +165,54 @@ function recover(ctx) {
132
165
  }
133
166
  unlinkSync(journal);
134
167
  }
135
- export function locked(ctx, callback) {
136
- if (!existsSync(ctx.state)) mkdirSync(ctx.state, { recursive: true });
137
- const lock = join(ctx.state, '.mcp-lock'); let fd;
138
- try { fd = openSync(lock, 'wx', 0o600); }
168
+ function tryAcquireLock(lock) {
169
+ try { return openSync(lock, 'wx', 0o600); }
139
170
  catch (error) {
140
171
  if (error.code !== 'EEXIST') throw error;
141
172
  let stale = false;
142
- try { const owner = JSON.parse(readFileSync(lock, 'utf8')); if (!Number.isInteger(owner.pid) || owner.pid < 1) throw new Error(); try { process.kill(owner.pid, 0); } catch (e) { stale = e.code === 'ESRCH'; } } catch {}
143
- if (!stale) fail('工作区正在被另一个操作使用,请稍后重新读取。', 409);
144
- unlinkSync(lock); try { fd = openSync(lock, 'wx', 0o600); } catch { fail('工作区正在被另一个操作使用。', 409); }
173
+ try {
174
+ const owner = JSON.parse(readFileSync(lock, 'utf8'));
175
+ if (!Number.isInteger(owner.pid) || owner.pid < 1) throw new Error();
176
+ try { process.kill(owner.pid, 0); } catch (e) { stale = e.code === 'ESRCH'; }
177
+ } catch {}
178
+ if (!stale) return null;
179
+ try { unlinkSync(lock); } catch (e) { if (e.code !== 'ENOENT') return null; }
180
+ try { return openSync(lock, 'wx', 0o600); } catch (e) { if (e.code === 'EEXIST') return null; throw e; }
181
+ }
182
+ }
183
+ export function locked(ctx, callback, { timeoutMs = 1500 } = {}) {
184
+ if (!existsSync(ctx.state)) mkdirSync(ctx.state, { recursive: true });
185
+ const lock = join(ctx.state, '.mcp-lock');
186
+ const deadline = Date.now() + timeoutMs;
187
+ let fd = tryAcquireLock(lock);
188
+ while (fd === null && Date.now() < deadline) {
189
+ Atomics.wait(waitBuffer, 0, 0, 20);
190
+ fd = tryAcquireLock(lock);
145
191
  }
192
+ if (fd === null) fail('工作区正在被另一个操作使用,请稍后重新读取。', 409);
146
193
  try { writeFileSync(fd, JSON.stringify({ pid: process.pid })); recover(ctx); return callback(); }
147
- finally { closeSync(fd); unlinkSync(lock); }
194
+ finally { closeSync(fd); try { unlinkSync(lock); } catch {} }
195
+ }
196
+ export function lockedAsync(ctx, callback, { timeoutMs = 2500 } = {}) {
197
+ const key = resolve(ctx.state);
198
+ const previous = lockQueues.get(key) || Promise.resolve();
199
+ const run = previous.catch(() => {}).then(async () => {
200
+ if (!existsSync(ctx.state)) mkdirSync(ctx.state, { recursive: true });
201
+ const lock = join(ctx.state, '.mcp-lock');
202
+ const deadline = Date.now() + timeoutMs;
203
+ let fd = tryAcquireLock(lock), delay = 15;
204
+ while (fd === null && Date.now() < deadline) {
205
+ await new Promise(r => setTimeout(r, delay));
206
+ delay = Math.min(50, delay + 10);
207
+ fd = tryAcquireLock(lock);
208
+ }
209
+ if (fd === null) fail('工作区正在被另一个操作使用,请稍后重新读取。', 409);
210
+ try { writeFileSync(fd, JSON.stringify({ pid: process.pid })); recover(ctx); return await callback(); }
211
+ finally { closeSync(fd); try { unlinkSync(lock); } catch {} }
212
+ });
213
+ const tail = run.catch(() => {}).finally(() => { if (lockQueues.get(key) === tail) lockQueues.delete(key); });
214
+ lockQueues.set(key, tail);
215
+ return run;
148
216
  }
149
217
  export function commit(ctx, before, after, expectedVersion) {
150
218
  if (expectedVersion !== before.version || snapshot(ctx).version !== before.version) fail('工作区版本已变化,请重新读取并合并后重试。', 409, { code: 'VERSION_CONFLICT', currentVersion: snapshot(ctx).version });
@@ -5,7 +5,7 @@ purpose: 将一个业务场景讲清楚:谁在什么条件下做什么,成
5
5
  hard_constraints:
6
6
  - 一级标题是有明确职责的业务阶段、参与方动作或稳定业务状态,不能用Java类方法冒充业务步骤。
7
7
  - 第一张卡说明触发者、前提和本场景目标;二级标题解释阶段内部动作、条件与结果,三级至六级只展开所属分支。
8
- - 实际进入下一阶段的地方建立内链,文字说明触发条件与携带的信息;主路径、拒绝和提前结束都应可顺着读通。
8
+ - 实际进入下一阶段的地方从具体步骤正文、表格行或流程节点建立内链,文字说明触发条件与携带的信息;避免在卡片末尾单独追加裸的卡片连卡片,主路径、拒绝和提前结束都应可顺着读通。
9
9
  - 每张卡说明谁操作、依据什么、如何反馈、改变哪些业务状态、失败时谁接手;不要只列节点名称。
10
10
  - 层级是包含关系,正文内链才表达流转;每个一级卡应参与真实跨卡关系,单卡豁免。
11
11
  - 同一动作的互斥结果并列写清,不画成同时执行;普通返回用文字说明。
@@ -28,7 +28,7 @@ hard_constraints:
28
28
  - 不另附一份整方法“核心编排”,不把每条逻辑机械翻译成代码,不用一张巨大Mermaid代替方法和逻辑节点。
29
29
  - 持久化按真实技术栈组织;Java/MyBatis使用Repository实现、DAO接口方法和独立Mapper.xml#语句ID卡,XML卡解释SQL、参数绑定与结果映射;其他技术栈不强套这些层次。
30
30
  - 类型、泛型、XML标签和带尖括号的协议占位符放在行内代码或围栏中,避免正文被当作HTML;标题、段落、表格、围栏之间保留空行。
31
- - 多卡画布的每张卡至少参与一条真实跨卡关系;单卡豁免。跨文档跳转用于导航,不代替本画布的连线,不能为消除孤立卡而虚构调用。
31
+ - 多卡画布的每张卡至少参与一条真实跨卡关系;单卡豁免。跨卡连接应从具体内容行出发(优先用代码行、表格数据行、Mermaid节点或步骤正文内的行内链接),避免在卡片末尾单独追加裸的卡片连卡片。跨文档跳转用于导航,不代替本画布的连线,不能为消除孤立卡而虚构调用。
32
32
  soft_constraints:
33
33
  - 文字先说明当前逻辑,局部代码、表格或小图再解释需要精确表达的细节,不要求每个步骤都有图和代码。
34
34
  - 步骤标题优先使用清楚的动作或判断;正文尽量让读者不翻源代码也能理解当前步骤的目的和出口。
@@ -14,7 +14,7 @@ hard_constraints:
14
14
  - DDL与迁移放在所属节点的代码围栏,解释既有数据如何兼容、失败如何识别、如何回退及验证,不能只给建表语句。
15
15
  - SQL参数、字段、状态与接口和方法文档保持一致;调用链链接到本数据契约,而不重复维护另一份定义。
16
16
  - 表格与小型ER图服务当前对象关系,复杂规则用分层文字说明;不要用一张大图替代可修改的节点。
17
- - 多卡画布每张卡需参与真实数据关系或迁移依赖,单卡豁免;不要伪造外键或调用来凑连接。
17
+ - 多卡画布每张卡需参与真实数据关系或迁移依赖,单卡豁免;关系连线优先从字段表格行、DDL/SQL代码行或正文行内说明出发,避免裸的卡片连卡片,不要伪造外键或调用来凑连接。
18
18
  soft_constraints:
19
19
  - 使用“🟩 新增”“🟨 修改”“🟥 删除”标实际变更,“🟦 需求原文”标可追溯的逐字引用,“🟪 特别说明”标重要约束或例外。图标和文字一起写;单纯描述现状时不把已有内容标成新增。
20
20
  - 长解释放表外,使用局部DDL或SQL片段解释关键约束,避免在一个表格单元格里堆多段正文。
@@ -0,0 +1,47 @@
1
+ ---
2
+ id: test-cases
3
+ name: 测试用例脑图
4
+ version: "0.1"
5
+ purpose: 用脑图逐层拆解需求的测试场景,覆盖正常流、边界条件、异常流与回归检查点,方便评审补漏与开发后验收。
6
+ hard_constraints:
7
+ - 一个一级标题代表一个被测模块或核心能力,二级按测试维度分节(正常流、边界条件、异常流、回归检查点),三级及以下落到具体可验证用例。
8
+ - 每条用例必须写清前置条件、触发动作和可观察的预期结果,不能只写一句抽象标题。
9
+ - 每个被测模块至少覆盖正常流、边界条件和异常流三个维度,不得只测主干 happy path。
10
+ - 涉及已有系统改造时,必须结合本地真实代码或调用链画布补齐回归检查点,不凭空编造未核对的字段或接口。
11
+ - 跨文档关联到对应的需求概览、调用链或数据设计文档时,优先在具体用例行内做行内链接,避免孤立卡片和裸卡片连卡片。
12
+ - 多卡画布中每张卡至少参与一条真实跨卡关联(例如前置依赖或上下游链路),单卡豁免。
13
+ soft_constraints:
14
+ - 使用“🟩 新增”“🟨 修改”“🟥 删除”标明本期变更涉及的用例,“🟦 需求原文”标可追溯的逐字引用,“🟪 特别说明”标测试环境或数据准备约束。图标和文字一起写。
15
+ - 优先切到脑图视图评审用例覆盖度,复杂断言数据或参数组合用精简表格表达,避免在单节点塞入大段文字。
16
+ organization: 一级按被测模块/接口分卡,二级固定拆出正常流、边界条件、异常流与回归检查点,三级写具体场景与断言;推荐在脑图视图中展开评审。
17
+ ---
18
+
19
+ # {{title}}
20
+
21
+ 本画布梳理「{{title}}」的核心测试范围与验收标准,建议切到 **脑图视图** 逐层评审覆盖度。
22
+
23
+ ## 正常流
24
+
25
+ ### 🟩 新增:核心主干链路通过
26
+ - **前置条件**:测试账号与基础数据准备就绪,依赖服务返回正常。
27
+ - **操作步骤**:使用合法参数触发主流程。
28
+ - **预期结果**:返回成功状态,核心数据正确落库且状态流转符合设计契约。
29
+
30
+ ## 边界条件
31
+
32
+ ### 🟩 新增:极限值与幂等边界
33
+ - **前置条件**:构造临界输入(如数量为 `0` / 最大上限、重复提交同一请求键)。
34
+ - **操作步骤**:分别提交临界参数与并发重放请求。
35
+ - **预期结果**:参数校验准确拦截非法边界;幂等请求只生效一次,不产生重复数据。
36
+
37
+ ## 异常流
38
+
39
+ ### 🟩 新增:下游失败与回滚保护
40
+ - **前置条件**:模拟下游依赖超时、返回错误码或资源不足。
41
+ - **操作步骤**:触发主流程并观察异常出口。
42
+ - **预期结果**:返回明确错误码,已占用的临时状态或资源正确回滚,不留脏数据。
43
+
44
+ ## 回归检查点
45
+
46
+ ### 🟪 特别说明:存量逻辑不受影响
47
+ - 核对未变更的原有入口与兼容参数行为保持一致,确认无破坏性回归。