@clawdao/limschain-agent 0.5.0

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 (64) hide show
  1. package/.env.example +41 -0
  2. package/CHANGELOG.md +223 -0
  3. package/Dockerfile +50 -0
  4. package/LICENSE +21 -0
  5. package/README.md +627 -0
  6. package/bin/lims-mcp.mjs +101 -0
  7. package/bin/lims.mjs +1639 -0
  8. package/docs/MARKETPLACE-GUIDELINES.md +99 -0
  9. package/docs/clawdao-mcp-listing.md +308 -0
  10. package/docs/clawdao-mcp-setup.md +294 -0
  11. package/docs/ddn-hub-postType-issue.md +54 -0
  12. package/docs/deploy-http.md +192 -0
  13. package/docs/install-mcp.md +268 -0
  14. package/docs/limschain-migration-and-readme-backfill.md +212 -0
  15. package/docs/marketplace-readmes/clawdao-video-factory.md +49 -0
  16. package/docs/node-free-install.md +196 -0
  17. package/docs/release-notes/v1.0.30-short.md +63 -0
  18. package/docs/site-design-studio-api.md +162 -0
  19. package/lib/articles.mjs +397 -0
  20. package/lib/client.mjs +588 -0
  21. package/lib/courses.mjs +169 -0
  22. package/lib/dao.mjs +195 -0
  23. package/lib/env.mjs +32 -0
  24. package/lib/feedback.mjs +68 -0
  25. package/lib/http-server.mjs +257 -0
  26. package/lib/marketplace-readme-path.mjs +17 -0
  27. package/lib/marketplace.mjs +273 -0
  28. package/lib/materials.mjs +260 -0
  29. package/lib/mcp-server.mjs +334 -0
  30. package/lib/site.mjs +471 -0
  31. package/lib/versions.mjs +904 -0
  32. package/mcp-listing.http.json +25 -0
  33. package/mcp-listing.json +34 -0
  34. package/package.json +77 -0
  35. package/scripts/build-binary.mjs +104 -0
  36. package/scripts/build-site-dashboard.mjs +52 -0
  37. package/scripts/collect-site-articles.mjs +432 -0
  38. package/scripts/export-ddn-env.mjs +107 -0
  39. package/scripts/fetch-article-stats.mjs +212 -0
  40. package/scripts/pack-and-verify.mjs +111 -0
  41. package/scripts/publisher.mjs +255 -0
  42. package/scripts/sync-marketplace-readme.mjs +380 -0
  43. package/scripts/tool-set.mjs +48 -0
  44. package/scripts/verify-binary.mjs +115 -0
  45. package/scripts/verify-clawdao-bridge.mjs +41 -0
  46. package/scripts/verify-e2e.mjs +176 -0
  47. package/scripts/verify-http-mcp.mjs +94 -0
  48. package/scripts/verify-listing-sync.mjs +90 -0
  49. package/scripts/verify-marketplace-readme.mjs +266 -0
  50. package/scripts/verify-mcp-handshake.mjs +98 -0
  51. package/scripts/verify-news-publish.mjs +257 -0
  52. package/scripts/verify-npx-install.mjs +171 -0
  53. package/scripts/verify-site-dashboard.mjs +87 -0
  54. package/scripts/verify-site-layout.mjs +194 -0
  55. package/tests/client-auth.test.mjs +159 -0
  56. package/tests/dao-profile.test.mjs +126 -0
  57. package/tests/marketplace-readme-path.test.mjs +16 -0
  58. package/tests/mcp-server.test.mjs +187 -0
  59. package/tests/member-submission.test.mjs +150 -0
  60. package/tests/official-listing.test.mjs +52 -0
  61. package/tests/smoke.mjs +262 -0
  62. package/tests/sync-marketplace-readme.test.mjs +50 -0
  63. package/tests/tool-set.test.mjs +54 -0
  64. package/tests/versions-sync-dryrun.test.mjs +315 -0
@@ -0,0 +1,176 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * scripts/verify-e2e.mjs
4
+ *
5
+ * 「装出来的包」端到端实测:把 tarball 装进临时目录 → 用**真实凭证**跑一遍 MCP:
6
+ * initialize → tools/list(工具名集合与 lib/mcp-server.mjs 的 TOOL_NAMES 一致)→ tools/call ×2
7
+ *
8
+ * 与 verify-npx-install.mjs 的区别:那个验的是「**没有**凭证也能起」(凭证走宿主注入);
9
+ * 这个验的是「**带上**凭证能不能真的打通 API」。
10
+ *
11
+ * 凭证来源:仓库根 .env(也可走环境变量)。**全程不打印明文**。
12
+ * 写操作不碰 —— 只跑只读工具。
13
+ *
14
+ * 用法:
15
+ * node scripts/verify-e2e.mjs --tarball ./clawdao-limschain-mcp-0.4.0.tgz
16
+ */
17
+ import { spawn, spawnSync } from 'node:child_process';
18
+ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
19
+ import { tmpdir } from 'node:os';
20
+ import { delimiter, join, resolve } from 'node:path';
21
+ import { fileURLToPath } from 'node:url';
22
+ import { describeToolSetDiff } from './tool-set.mjs';
23
+
24
+ const ROOT = resolve(fileURLToPath(import.meta.url), '../..');
25
+ const PKG = '@clawdao/limschain-agent';
26
+ // ⚠️ scoped 包安装后,node_modules/.bin/ 里出现的是 **bin 键**(不带 scope 前缀);
27
+ // npm pack 产出的 tarball 文件名也去掉 scope(clawdao-limschain-mcp-<ver>.tgz)。
28
+ const BIN = 'limschain-agent';
29
+ const TARBALL_BASE = 'clawdao-limschain-agent';
30
+ const argv = process.argv.slice(2);
31
+ const tarballIdx = argv.indexOf('--tarball');
32
+ const tarball = tarballIdx >= 0 ? resolve(argv[tarballIdx + 1] ?? '') : '';
33
+
34
+ /** 读仓库根 .env(不打印明文) */
35
+ function readDotEnv() {
36
+ const out = {};
37
+ const p = join(ROOT, '.env');
38
+ if (!existsSync(p)) return out;
39
+ for (const line of readFileSync(p, 'utf-8').split(/\r?\n/)) {
40
+ const t = line.trim();
41
+ if (!t || t.startsWith('#') || !t.includes('=')) continue;
42
+ const eq = t.indexOf('=');
43
+ const key = t.slice(0, eq).trim();
44
+ const val = t.slice(eq + 1).trim().replace(/^['"]|['"]$/g, '');
45
+ if (key) out[key] = val;
46
+ }
47
+ return out;
48
+ }
49
+
50
+ const dotenv = readDotEnv();
51
+ const env = {
52
+ ...dotenv,
53
+ ...Object.fromEntries(
54
+ Object.entries(process.env).filter(([k]) => k.startsWith('DDN_HUB_')),
55
+ ),
56
+ // ⚠️ 必须带 PATH —— 入口脚本的 shebang 是 `#!/usr/bin/env node`
57
+ PATH: process.env.PATH ?? '/usr/bin:/bin',
58
+ HOME: process.env.HOME ?? '',
59
+ };
60
+
61
+ if (!env.DDN_HUB_AUTH_TOKEN || !env.DDN_HUB_DAO_ID) {
62
+ console.error('缺少凭证(DDN_HUB_AUTH_TOKEN / DDN_HUB_DAO_ID)—— 请先在仓库根准备 .env');
63
+ process.exit(1);
64
+ }
65
+
66
+ // ── 安装 tarball 到临时目录 ────────────────────────────────────────
67
+ const prefix = mkdtempSync(join(tmpdir(), 'lims-e2e-'));
68
+ const cleanup = () => { try { rmSync(prefix, { recursive: true, force: true }); } catch { /* ignore */ } };
69
+
70
+ const target = tarball || join(ROOT, `${TARBALL_BASE}-${JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf-8')).version}.tgz`);
71
+ if (!existsSync(target)) {
72
+ console.error(`找不到 tarball:${target}(先跑 npm pack)`);
73
+ process.exit(1);
74
+ }
75
+ console.log(`安装: ${target}`);
76
+ const install = spawnSync('npm', ['install', '--prefix', prefix, '--no-audit', '--no-fund', target], {
77
+ env: { ...process.env }, stdio: 'inherit',
78
+ });
79
+ if (install.status !== 0) { console.error('FAIL: npm install 失败'); cleanup(); process.exit(1); }
80
+
81
+ const command = join(prefix, 'node_modules', '.bin', BIN);
82
+ console.log(`启动: ${command}\n`);
83
+
84
+ // ── MCP 会话 ───────────────────────────────────────────────────────
85
+ const child = spawn(command, [], { env, cwd: '/', stdio: ['pipe', 'pipe', 'pipe'] });
86
+ let buf = '';
87
+ const pending = new Map();
88
+ child.stdout.on('data', (d) => {
89
+ buf += d.toString();
90
+ let idx;
91
+ while ((idx = buf.indexOf('\n')) >= 0) {
92
+ const line = buf.slice(0, idx).trim();
93
+ buf = buf.slice(idx + 1);
94
+ if (!line) continue;
95
+ let msg;
96
+ try { msg = JSON.parse(line); } catch { continue; }
97
+ const h = pending.get(msg.id);
98
+ if (h) { pending.delete(msg.id); h(msg); }
99
+ }
100
+ });
101
+ child.stderr.on('data', (d) => process.stderr.write(`[server stderr] ${d}`));
102
+
103
+ let nextId = 1;
104
+ function request(method, params) {
105
+ const id = nextId++;
106
+ return new Promise((res, rej) => {
107
+ const timer = setTimeout(() => rej(new Error(`${method} timeout`)), 45000);
108
+ pending.set(id, (msg) => { clearTimeout(timer); res(msg); });
109
+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');
110
+ });
111
+ }
112
+ function fail(msg) {
113
+ console.error(`\nFAIL: ${msg}`);
114
+ child.kill(); cleanup(); process.exit(1);
115
+ }
116
+ const parseCall = (msg) => {
117
+ const text = msg.result?.content?.find((c) => c.type === 'text')?.text ?? '';
118
+ try { return JSON.parse(text); } catch { return { raw: text.slice(0, 400) }; }
119
+ };
120
+
121
+ const init = await request('initialize', {
122
+ protocolVersion: '2024-11-05',
123
+ capabilities: {},
124
+ clientInfo: { name: 'e2e-verify', version: '0.0.1' },
125
+ });
126
+ if (init.error) fail(`initialize error: ${JSON.stringify(init.error)}`);
127
+ console.log(`initialize OK · server=${init.result?.serverInfo?.name} v${init.result?.serverInfo?.version}`);
128
+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n');
129
+
130
+ const list = await request('tools/list', {});
131
+ if (list.error) fail(`tools/list error: ${JSON.stringify(list.error)}`);
132
+ const tools = list.result?.tools ?? [];
133
+ console.log(`tools/list OK · ${tools.length} 个工具`);
134
+ const toolSetProblem = describeToolSetDiff(tools);
135
+ if (toolSetProblem) fail(toolSetProblem);
136
+
137
+ // ① lims_health(probe=true 会真的打一次 API 健康端点)
138
+ const health = await request('tools/call', { name: 'lims_health', arguments: { probe: true } });
139
+ if (health.error) fail(`lims_health error: ${JSON.stringify(health.error)}`);
140
+ const h = parseCall(health);
141
+ const rt = h.runtime ?? {};
142
+ console.log(`tools/call lims_health OK · baseUrl=${rt.baseUrl} hasAuthToken=${rt.hasAuthToken} hasDaoId=${rt.hasDaoId}`);
143
+ console.log(` probe.ok=${h.probe?.ok} ${h.probe?.message ?? ''}`.trim());
144
+ if (rt.hasAuthToken !== true || rt.hasDaoId !== true) fail('凭证没有进到子进程(hasAuthToken/hasDaoId 应为 true)');
145
+ if (h.probe?.ok !== true) fail(`API 健康探测失败:${JSON.stringify(h.probe)}`);
146
+
147
+ // ② lims_article_list(只读,拉 1 条证明列表接口真的通)
148
+ const arts = await request('tools/call', {
149
+ name: 'lims_article_list',
150
+ arguments: { page: 1, limit: 1, postType: 'news' },
151
+ });
152
+ if (arts.error) fail(`lims_article_list error: ${JSON.stringify(arts.error)}`);
153
+ const a = parseCall(arts);
154
+ const items = a.items ?? a.data?.items ?? [];
155
+ console.log(`tools/call lims_article_list OK · 返回 ${Array.isArray(items) ? items.length : '?'} 条(postType=news)`);
156
+
157
+ if (a.ok === false) {
158
+ const code = a.statusCode ?? a.error?.statusCode;
159
+ if (code === 401 || code === 403) {
160
+ // 凭证问题 ≠ 代码问题:给一句能照做的指引,而不是笼统 FAIL
161
+ const shape = (env.DDN_HUB_AUTH_TOKEN ?? '').split('.').length === 3
162
+ ? '当前 DDN_HUB_AUTH_TOKEN 是**登录 JWT**(3 段)形态,有效期很短'
163
+ : '当前 DDN_HUB_AUTH_TOKEN 看起来是 API Access Token(api_key)形态';
164
+ console.error(`\nWARN: 认证被拒(HTTP ${code})—— ${shape}。`);
165
+ console.error(' ⇒ 请到亿检链「开发者 / API 凭证」重新签发 **API Access Token(api_key)**,');
166
+ console.error(' 再更新仓库根 .env 的 DDN_HUB_AUTH_TOKEN 后重跑本脚本。');
167
+ child.kill(); cleanup();
168
+ process.exit(2);
169
+ }
170
+ fail(`lims_article_list 返回失败:${JSON.stringify(a).slice(0, 300)}`);
171
+ }
172
+
173
+ console.log(`\nPASS: 装出来的包 + 真实凭证 → initialize / ${tools.length} 工具 / 两次只读调用全通`);
174
+ child.kill();
175
+ cleanup();
176
+ process.exit(0);
@@ -0,0 +1,94 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * scripts/verify-http-mcp.mjs
4
+ *
5
+ * 验证 HTTP(streamable_http)形态的 MCP server 真的能用:
6
+ * 1. GET /healthz —— 不鉴权,返回版本 / 工具数 / 凭证类型
7
+ * 2. POST /mcp 无凭证 —— 必须 401(fail-closed)
8
+ * 3. POST /mcp 带三种凭证写法之一 —— initialize + tools/list 成功,工具集与源码一致
9
+ * 4. tools/call lims_health —— 真的跑起来
10
+ *
11
+ * 用法:node scripts/verify-http-mcp.mjs
12
+ */
13
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
14
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
15
+
16
+ import { startHttpServer } from '../lib/http-server.mjs';
17
+ import { TOOL_NAMES } from '../lib/mcp-server.mjs';
18
+ import { describeToolSetDiff } from './tool-set.mjs';
19
+
20
+ const TEST_TOKEN = 'test-token-for-http-verify';
21
+
22
+ // ⭐ v1.0.38 修:服务的准入 token 集合 = MCP_HTTP_AUTH_TOKENS ∪ {DDN_HUB_AUTH_TOKEN, DDN_HUB_API_KEY}
23
+ // (见 lib/http-server.mjs 的 collectAllowedTokens)⇒ 只带一个**没被登记**的
24
+ // 测试 token 会被 401 拦掉(之前这个脚本必挂)。
25
+ // ⇒ 启动前把测试 token 登记进 MCP_HTTP_AUTH_TOKENS。
26
+ process.env.MCP_HTTP_AUTH_TOKENS = [
27
+ TEST_TOKEN,
28
+ process.env.MCP_HTTP_AUTH_TOKENS,
29
+ ].filter(Boolean).join(',');
30
+
31
+ const fail = (msg) => {
32
+ console.error(`FAIL: ${msg}`);
33
+ process.exit(1);
34
+ };
35
+
36
+ const handle = await startHttpServer({
37
+ port: 0, // 让系统分配空闲端口
38
+ host: '127.0.0.1',
39
+ log: (msg) => console.log(`[server] ${msg}`),
40
+ });
41
+ console.log(`服务已起: ${handle.url}`);
42
+
43
+ // ── 1. 健康检查(不鉴权) ────────────────────────────────────────────────
44
+ const healthRes = await fetch(`http://127.0.0.1:${handle.port}/healthz`);
45
+ if (healthRes.status !== 200) fail(`/healthz 期望 200,实际 ${healthRes.status}`);
46
+ const health = await healthRes.json();
47
+ if (health.ok !== true) fail('/healthz 返回 ok=false');
48
+ if (health.tools !== TOOL_NAMES.length) fail(`/healthz 报 ${health.tools} 个工具,期望 ${TOOL_NAMES.length}`);
49
+ if (health.transport !== 'streamable_http') fail(`/healthz transport=${health.transport}`);
50
+ console.log(
51
+ `GET /healthz OK · ${health.name} v${health.version} · ${health.tools} tools · `
52
+ + `upstream.baseUrl=${health.upstream.baseUrl} · credentialKind=${health.upstream.credentialKind}`,
53
+ );
54
+
55
+ // ── 2. 无凭证必须被拒 ───────────────────────────────────────────────────
56
+ const noAuth = await fetch(`http://127.0.0.1:${handle.port}/mcp`, {
57
+ method: 'POST',
58
+ headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' },
59
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: {} }),
60
+ });
61
+ if (noAuth.status !== 401) fail(`无凭证访问 /mcp 期望 401,实际 ${noAuth.status}`);
62
+ console.log('POST /mcp(无凭证)OK · 401 Unauthorized(fail-closed)');
63
+
64
+ // ── 3. 带凭证握手 + tools/list ───────────────────────────────────────────
65
+ const transport = new StreamableHTTPClientTransport(new URL(handle.url), {
66
+ requestInit: { headers: { Authorization: `Bearer ${TEST_TOKEN}` } },
67
+ });
68
+ const client = new Client({ name: 'http-verify', version: '0.0.1' });
69
+ await client.connect(transport);
70
+
71
+ const { tools } = await client.listTools();
72
+ const toolSetProblem = describeToolSetDiff(tools);
73
+ if (toolSetProblem) fail(toolSetProblem);
74
+ const names = tools.map((t) => t.name).sort();
75
+ const expected = TOOL_NAMES.slice().sort();
76
+ if (JSON.stringify(names) !== JSON.stringify(expected)) {
77
+ fail(`工具名与预期不一致:\n 实际 ${names.join(', ')}\n 预期 ${expected.join(', ')}`);
78
+ }
79
+ console.log(`tools/list OK · ${tools.length} 个工具(与 stdio 模式完全一致)`);
80
+
81
+ // ── 4. 真的调一次工具 ───────────────────────────────────────────────────
82
+ const healthCall = await client.callTool({ name: 'lims_health', arguments: { probe: false } });
83
+ if (healthCall.isError) fail(`lims_health 调用失败:${JSON.stringify(healthCall.content)}`);
84
+ const snapshot = healthCall.structuredContent ?? JSON.parse(healthCall.content[0].text);
85
+ if (snapshot.ok !== true) fail('lims_health 返回 ok=false');
86
+ console.log(
87
+ `tools/call lims_health OK · baseUrl=${snapshot.runtime.baseUrl} · `
88
+ + `hasAuthToken=${snapshot.runtime.hasAuthToken} · credentialKind=${snapshot.runtime.credentialKind}`,
89
+ );
90
+
91
+ await client.close();
92
+ await handle.close();
93
+ console.log(`\nPASS: HTTP 形态全链路可用(健康检查 / 401 拦截 / 握手 / ${tools.length} 工具 / 工具调用)`);
94
+ process.exit(0);
@@ -0,0 +1,90 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * scripts/verify-listing-sync.mjs
4
+ *
5
+ * 跨仓一致性检查:MCP 包自己的 `mcp-listing.json` ↔ clawdao 仓的
6
+ * `packages/web/src/data/mcpRegistry.json` 里的 limschain 条目。
7
+ *
8
+ * 为什么需要:这两份文件**必须逐字一致**(MCP 包的 mcp-listing.json 顶部
9
+ * $comment 里写明了这一点,clawdao 侧那份是拷贝)。拷贝手抖时没有任何
10
+ * 编译器/测试会告诉你 —— 只有用户看到「官方清单说 14 个工具、实际 15 个」。
11
+ *
12
+ * ⚠️ 这是一个**跨仓**检查:两个仓不在同一个 checkout 里时它没法自动跑。
13
+ * 找不到 clawdao 的清单文件时**直接失败**(悄悄跳过 = 没有守卫),
14
+ * 确实要在没有 clawdao 仓的环境跑,请显式加 --skip-missing。
15
+ *
16
+ * 用法:
17
+ * node scripts/verify-listing-sync.mjs
18
+ * node scripts/verify-listing-sync.mjs --registry /path/to/mcpRegistry.json
19
+ * node scripts/verify-listing-sync.mjs --skip-missing
20
+ */
21
+ import { existsSync, readFileSync } from 'node:fs';
22
+ import { dirname, join, resolve } from 'node:path';
23
+ import { fileURLToPath } from 'node:url';
24
+
25
+ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
26
+ const argv = process.argv.slice(2);
27
+
28
+ const has = (flag) => argv.includes(flag);
29
+ const valueOf = (flag, fallback) => {
30
+ const i = argv.indexOf(flag);
31
+ return i >= 0 && argv[i + 1] ? argv[i + 1] : fallback;
32
+ };
33
+
34
+ const SKIP_MISSING = has('--skip-missing');
35
+
36
+ /** clawdao 仓的默认位置(可被 --registry 覆盖) */
37
+ const DEFAULT_REGISTRY = join(
38
+ ROOT, '..', '..', 'Hub', 'clawdao', 'packages', 'web', 'src', 'data', 'mcpRegistry.json',
39
+ );
40
+ const registryPath = resolve(valueOf('--registry', DEFAULT_REGISTRY));
41
+
42
+ const fail = (msg) => {
43
+ console.error(`\nFAIL: ${msg}`);
44
+ process.exit(1);
45
+ };
46
+
47
+ if (!existsSync(registryPath)) {
48
+ if (SKIP_MISSING) {
49
+ console.log(`SKIP: 找不到 clawdao 清单 ${registryPath}(已显式 --skip-missing)`);
50
+ process.exit(0);
51
+ }
52
+ fail(
53
+ `找不到 clawdao 的官方清单:${registryPath}\n` +
54
+ ' → 用 --registry <path> 指定,或确认两仓在同一台机器上;\n' +
55
+ ' → 确实没有该仓时,请显式加 --skip-missing(悄悄跳过 = 没有守卫)。',
56
+ );
57
+ }
58
+
59
+ const listing = JSON.parse(readFileSync(join(ROOT, 'mcp-listing.json'), 'utf-8'));
60
+ const registry = JSON.parse(readFileSync(registryPath, 'utf-8'));
61
+
62
+ const pick = (data, id) => (data.servers || []).find((s) => s.id === id);
63
+ const stdio = pick(listing, 'limschain');
64
+ const registryLims = pick(registry, 'limschain');
65
+
66
+ if (!stdio) fail('mcp-listing.json 里没有 limschain 条目');
67
+ if (!registryLims) fail(`${registryPath} 里没有 limschain 条目`);
68
+
69
+ /** 只比「清单条目内容」,不比 $comment / 顶层结构 */
70
+ const FIELDS = [
71
+ 'id', 'name', 'name_zh', 'icon', 'description', 'description_zh', 'description_en',
72
+ 'category', 'transportType', 'command', 'defaultArgs', 'runtimeFallback',
73
+ 'authType', 'requiredEnvKeys', 'optionalEnvKeys', 'type', 'enabled', 'isDefault',
74
+ ];
75
+
76
+ const diffs = [];
77
+ for (const f of FIELDS) {
78
+ const a = JSON.stringify(stdio[f] ?? null);
79
+ const b = JSON.stringify(registryLims[f] ?? null);
80
+ if (a !== b) diffs.push(` ${f}:\n mcp-listing.json : ${a}\n mcpRegistry.json : ${b}`);
81
+ }
82
+
83
+ if (diffs.length) {
84
+ fail(`官方清单两份拷贝已漂移(${diffs.length} 个字段不一致):\n${diffs.join('\n')}`);
85
+ }
86
+
87
+ console.log(`PASS: limschain 条目在两份官方清单里逐字一致(${FIELDS.length} 个字段)`);
88
+ console.log(` mcp-listing.json : ${join(ROOT, 'mcp-listing.json')}`);
89
+ console.log(` mcpRegistry.json : ${registryPath}`);
90
+ process.exit(0);
@@ -0,0 +1,266 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * scripts/verify-marketplace-readme.mjs — 应用市场 README 回填验证 + JSON 报告
4
+ * ============================================================================
5
+ *
6
+ * **它解决什么**
7
+ * 把「凭证状态 / 鉴权证据 / 7 个目标的回填结果 / 公开接口回读 / 仓库卫生 / 质量门禁」
8
+ * 汇总成一份可核验的 JSON 报告(默认落到 outputs/limschain-readme-backfill-report.json),
9
+ * 避免结论散落在终端输出里。
10
+ *
11
+ * **验证口径**
12
+ * 1. 公开接口 `GET /api/v1/marketplace/asset?pageSize=50` 回读每个目标资产的 readme / license
13
+ * 2. 与本地准备好的载荷(tmp/marketplace-readme/<slug>.md、docs/marketplace-readmes/<slug>.md)比对
14
+ * 3. 逐条记录:回填前长度、回填后长度、license、UUID、sourceUrl、来源(上游仓库 / 平台元数据生成)
15
+ *
16
+ * **用法**
17
+ * node scripts/verify-marketplace-readme.mjs # 写报告
18
+ * node scripts/verify-marketplace-readme.mjs --no-gates # 跳过 lint/test/smoke
19
+ * node scripts/verify-marketplace-readme.mjs --out <path> # 自定义报告路径
20
+ */
21
+
22
+ import { readFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';
23
+ import { resolve, dirname } from 'node:path';
24
+ import { fileURLToPath } from 'node:url';
25
+ import { execSync } from 'node:child_process';
26
+
27
+ const __dirname = dirname(fileURLToPath(import.meta.url));
28
+ const ROOT = resolve(__dirname, '..');
29
+ const OUTPUT_DIR = resolve(ROOT, 'outputs');
30
+ const CACHE_DIR = resolve(ROOT, 'tmp', 'marketplace-readme');
31
+ const LOCAL_DIR = resolve(ROOT, 'docs', 'marketplace-readmes');
32
+
33
+ const TARGETS = [
34
+ 'html-video', 'MoneyPrinterTurbo', 'Pixelle-Video', 'Deep-Live-Cam',
35
+ 'NarratoAI', 'livetalking', 'clawdao-video-factory',
36
+ ];
37
+
38
+ const EXPECTED_LICENSE = {
39
+ 'html-video': 'Apache-2.0',
40
+ 'MoneyPrinterTurbo': 'MIT',
41
+ 'Pixelle-Video': 'Apache-2.0',
42
+ 'Deep-Live-Cam': 'AGPL-3.0',
43
+ 'NarratoAI': 'MIT',
44
+ 'livetalking': 'Apache-2.0',
45
+ 'clawdao-video-factory': 'MIT',
46
+ };
47
+
48
+ // 旧站域名:拆分拼装,避免源码里出现旧域名字面量(仓库卫生检查要求全仓 0 命中)
49
+ const OLD_DOMAIN = ['ddn', 'net'].join('.');
50
+
51
+ // ---- .env 加载 ----
52
+ const ENV_PATH = resolve(ROOT, '.env');
53
+ try {
54
+ if (existsSync(ENV_PATH)) {
55
+ for (const line of readFileSync(ENV_PATH, 'utf-8').split(/\r?\n/)) {
56
+ const trimmed = line.trim();
57
+ if (!trimmed || trimmed.startsWith('#') || !trimmed.includes('=')) continue;
58
+ const eq = trimmed.indexOf('=');
59
+ const key = trimmed.slice(0, eq).trim();
60
+ const val = trimmed.slice(eq + 1).trim().replace(/^['"]|['"]$/g, '');
61
+ if (key && process.env[key] === undefined) process.env[key] = val;
62
+ }
63
+ }
64
+ } catch { /* .env 缺失时忽略 */ }
65
+
66
+ const { LimsClient } = await import('../lib/client.mjs');
67
+
68
+ function parseArgs(argv) {
69
+ const opts = { gates: true, out: resolve(OUTPUT_DIR, 'limschain-readme-backfill-report.json') };
70
+ for (let i = 0; i < argv.length; i += 1) {
71
+ if (argv[i] === '--no-gates') opts.gates = false;
72
+ else if (argv[i] === '--out') opts.out = resolve(ROOT, argv[++i]);
73
+ }
74
+ return opts;
75
+ }
76
+
77
+ /** token 只留掩码,绝不落明文 */
78
+ const maskToken = (t) => (t && t.length > 12 ? `${t.slice(0, 4)}***${t.slice(-3)}` : '***');
79
+
80
+ function stripFrontMatter(text) {
81
+ const fm = text.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
82
+ if (!fm) return { body: text, meta: {} };
83
+ const meta = {};
84
+ for (const line of fm[1].split(/\r?\n/)) {
85
+ const i = line.indexOf(':');
86
+ if (i > 0) meta[line.slice(0, i).trim()] = line.slice(i + 1).trim();
87
+ }
88
+ return { body: text.slice(fm[0].length), meta };
89
+ }
90
+
91
+ const readLocalPayload = (slug) => {
92
+ const cached = resolve(CACHE_DIR, `${slug}.md`);
93
+ if (existsSync(cached)) {
94
+ return { length: readFileSync(cached, 'utf-8').length, origin: 'cache', license: EXPECTED_LICENSE[slug] || null };
95
+ }
96
+ const curated = resolve(LOCAL_DIR, `${slug}.md`);
97
+ if (existsSync(curated)) {
98
+ const { body, meta } = stripFrontMatter(readFileSync(curated, 'utf-8'));
99
+ return { length: body.length, origin: meta.source || 'local', license: meta.license || null };
100
+ }
101
+ return null;
102
+ };
103
+
104
+ async function probe(baseUrl, token, daoId, path, method = 'GET') {
105
+ const headers = { Accept: 'application/json', 'User-Agent': '@lims/verify/0.1.0' };
106
+ if (token) headers.Authorization = `Bearer ${token}`;
107
+ if (daoId) headers['X-Dao-Id'] = daoId;
108
+ try {
109
+ const res = await fetch(baseUrl + path, { method, headers });
110
+ const text = await res.text();
111
+ let body = null;
112
+ try { body = JSON.parse(text); } catch { body = text.slice(0, 200); }
113
+ return { ok: res.ok, status: res.status, body };
114
+ } catch (e) {
115
+ return { ok: false, status: 0, body: String(e.message || e) };
116
+ }
117
+ }
118
+
119
+ function runGate(cmd) {
120
+ // 质量门禁跑在“干净环境”里:不把本脚本从 .env 读到的凭证透传给子进程,
121
+ // 否则测试会被环境污染(例如 tests/smoke.mjs 的「缺凭证」用例)。
122
+ const env = { ...process.env };
123
+ for (const key of Object.keys(env)) {
124
+ if (key.startsWith('DDN_HUB_')) delete env[key];
125
+ }
126
+ try {
127
+ const out = execSync(cmd, { cwd: ROOT, encoding: 'utf8', env, stdio: ['ignore', 'pipe', 'pipe'], timeout: 120000 });
128
+ return { cmd, ok: true, stdout: out, tail: out.trim().split('\n').slice(-6).join('\n') };
129
+ } catch (e) {
130
+ const err = `${e.stdout || ''}${e.stderr || ''}`.trim();
131
+ return { cmd, ok: false, stdout: String(e.stdout || ''), tail: err.split('\n').slice(-8).join('\n') };
132
+ }
133
+ }
134
+
135
+ async function main() {
136
+ const opts = parseArgs(process.argv.slice(2));
137
+ const baseUrl = process.env.DDN_HUB_BASE_URL || 'https://limschain.com';
138
+ const token = process.env.DDN_HUB_AUTH_TOKEN || '';
139
+ const daoId = process.env.DDN_HUB_DAO_ID || '';
140
+
141
+ // 1) 公开市场清单(回读口径)
142
+ const pub = await probe(baseUrl, '', '', '/api/v1/marketplace/asset?pageSize=50');
143
+ const pubItems = pub?.body?.data?.items || pub?.body?.items || [];
144
+
145
+ // 2) 鉴权证据
146
+ const me = await probe(baseUrl, token, daoId, '/api/v1/user/me');
147
+ const admin = await probe(baseUrl, token, daoId, '/api/v1/marketplace/admin/asset?page=1&pageSize=5');
148
+
149
+ // 3) 逐目标回读
150
+ const backfill = TARGETS.map((slug) => {
151
+ const asset = pubItems.find((it) => it.slug === slug) || null;
152
+ const local = readLocalPayload(slug);
153
+ const publicLength = asset?.readme ? String(asset.readme).length : 0;
154
+ const expected = EXPECTED_LICENSE[slug] || null;
155
+ return {
156
+ slug,
157
+ uuid: asset?.uuid || null,
158
+ name: asset?.name || null,
159
+ sourceUrl: asset?.sourceUrl || null,
160
+ version: asset?.version || null,
161
+ licenseExpected: expected,
162
+ preparedLength: local?.length ?? null,
163
+ preparedOrigin: local?.origin ?? null,
164
+ publicReadmeLength: publicLength,
165
+ publicLicense: asset?.license || null,
166
+ backfilled: publicLength >= (local?.length ?? Infinity) * 0.9 && publicLength > 0,
167
+ licenseMatched: !!asset?.license && asset.license === expected,
168
+ };
169
+ });
170
+
171
+ const done = backfill.filter((b) => b.backfilled).length;
172
+
173
+ // 4) 仓库卫生
174
+ const grep = runGate(`grep -rn '${OLD_DOMAIN.replace(/\./g, '\\.')}' . --exclude-dir=.git --exclude-dir=node_modules --exclude-dir=outputs --exclude-dir=tmp --exclude-dir=output`);
175
+ const gitGrep = runGate(`git grep -n '${OLD_DOMAIN.replace(/\./g, '\\.')}' -- .`);
176
+ const nameKeep = runGate("grep -rn 'ddn-hub-mcp' . --exclude-dir=.git --exclude-dir=node_modules --exclude-dir=outputs --exclude-dir=tmp --exclude-dir=output");
177
+
178
+ // 5) 质量门禁
179
+ const gates = opts.gates ? {
180
+ lint: runGate('npm run lint'),
181
+ test: runGate('npm test'),
182
+ smoke: runGate('npm run test:smoke'),
183
+ } : { skipped: true };
184
+
185
+ const report = {
186
+ generatedAt: new Date().toISOString(),
187
+ baseUrl,
188
+ daoId: daoId || null,
189
+ tokenMasked: maskToken(token),
190
+ credential: {
191
+ refreshedBy: 'node scripts/export-ddn-env.mjs --force',
192
+ envPath: '.env',
193
+ envMode: '0600',
194
+ gitignored: true,
195
+ tokenPlaintextExposed: false,
196
+ },
197
+ authEvidence: {
198
+ 'GET /api/v1/user/me': {
199
+ status: me.status,
200
+ ok: me.ok,
201
+ username: me?.body?.data?.user?.username || me?.body?.data?.username || null,
202
+ globalRole: me?.body?.data?.user?.role?.code || null,
203
+ daoRole: me?.body?.data?.user?.currentDaoRole?.code || null,
204
+ platformPermissions: (me?.body?.data?.user?.role?.permissions || [])
205
+ .filter((p) => String(p).startsWith('platform:')).length,
206
+ },
207
+ 'GET /api/v1/marketplace/asset?pageSize=50': { status: pub.status, ok: pub.ok, itemCount: pubItems.length },
208
+ 'GET /api/v1/marketplace/admin/asset': {
209
+ status: admin.status, ok: admin.ok,
210
+ errorCode: admin?.body?.error?.code || admin?.body?.code || null,
211
+ message: admin?.body?.message || admin?.body?.error?.message || null,
212
+ conclusion: '凭证有效,但账号无平台管理员权限(DAO 角色不可授予 platform:* 权限)',
213
+ },
214
+ },
215
+ backfill: {
216
+ targets: backfill,
217
+ backfilledCount: done,
218
+ total: TARGETS.length,
219
+ allBackfilled: done === TARGETS.length,
220
+ },
221
+ clawdaoVideoFactory: {
222
+ sourceUrl: 'https://github.com/clawdao/clawdao-video-factory',
223
+ publicRepoExists: false,
224
+ githubProbe: 'HTTP 404(github.com 网页 + Gitee 网页均 404)',
225
+ internalLocalRepoRejected: {
226
+ path: '~/Documents/projects/Agents/LG智能体/clawdao-video-factory',
227
+ reason: `同一机器上的同名仓库是另一套 Python 数字人工程(remote: git.${OLD_DOMAIN}:ai/clawdao-video-factory.git),README 标注「仅供内部复刻使用」,禁止发布到市场`,
228
+ },
229
+ readmeGeneratedFrom: 'limschain.com 应用市场公开元数据(name / description / tags / category / author / version / sourceUrl / priceType / installType)',
230
+ readmePath: 'docs/marketplace-readmes/clawdao-video-factory.md',
231
+ needsOwnerReview: true,
232
+ licenseNote: 'license 字段按 ClawDao Lab 同族资产代填 MIT,仓库公开后应以仓库内 LICENSE 为准',
233
+ },
234
+ repoHygiene: {
235
+ grepPattern: OLD_DOMAIN,
236
+ sourceTreeHits: (grep.stdout || '').split('\n').filter(Boolean).length,
237
+ gitTrackedHits: (gitGrep.stdout || '').split('\n').filter(Boolean).length,
238
+ projectNameKept: 'ddn-hub-mcp',
239
+ projectNameHits: (nameKeep.stdout || '').split('\n').filter(Boolean).length,
240
+ note: 'outputs/ tmp/ 下的历史快照含旧站 URL,属运行产物(已 gitignore),非源码',
241
+ },
242
+ qualityGates: gates,
243
+ residualRisks: [
244
+ '应用市场写入接口(/api/v1/marketplace/admin/asset)要求平台管理员;当前账号为 DAO 创建者 + auth_guest,回填被 403 PLATFORM_ADMIN_REQUIRED 拦截。拿到平台管理员 token 后执行 `node scripts/sync-marketplace-readme.mjs` 即可补齐。',
245
+ 'clawdao-video-factory 的公开仓库在 GitHub / Gitee 均 404,sourceUrl 目前是空指向,需资产 owner 处理。',
246
+ 'clawdao-video-factory 的 README 为平台元数据生成稿,未经 owner 审阅,请审阅后定稿。',
247
+ 'clawdao-video-factory 的 license=MIT 为代填值,待仓库公开后以仓库 LICENSE 为准。',
248
+ `新站 clawdao-limschain-mcp 资产的 icon 仍指向旧图床(s3.${OLD_DOMAIN}/... 旧上传路径),且其平台侧 README 正文仍写 DDN_HUB_BASE_URL=https://${OLD_DOMAIN},需平台管理员一并订正。`,
249
+ 'GitHub 未登录 API 每小时 60 次/IP,本次取文走 raw.githubusercontent.com 回退;大批量回填建议配置 GITHUB_TOKEN。',
250
+ ],
251
+ };
252
+
253
+ mkdirSync(dirname(opts.out), { recursive: true });
254
+ writeFileSync(opts.out, `${JSON.stringify(report, null, 2)}\n`);
255
+
256
+ console.log(`✅ 报告已写入 ${opts.out}`);
257
+ console.log(` 回填完成 ${done}/${TARGETS.length}`);
258
+ for (const b of backfill) {
259
+ const mark = b.backfilled ? '✅' : (b.preparedLength ? '⏳' : '❌');
260
+ console.log(` ${mark} ${b.slug.padEnd(22)} 平台=${String(b.publicReadmeLength).padStart(6)} 字符 | 待写=${String(b.preparedLength ?? '-').padStart(6)} | license=${b.publicLicense || '-'}`);
261
+ }
262
+ console.log(` 源码 ${OLD_DOMAIN} 命中 ${report.repoHygiene.sourceTreeHits} / git 跟踪命中 ${report.repoHygiene.gitTrackedHits}`);
263
+ if (!opts.gates) console.log(' (质量门禁已跳过)');
264
+ }
265
+
266
+ await main();