@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
package/bin/lims.mjs ADDED
@@ -0,0 +1,1639 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * 亿检链运营助手 CLI
5
+ * 用法: lims <command> [options]
6
+ *
7
+ * 命令:
8
+ * article 文章管理(上传、列表、发布)
9
+ * course 课程管理(上传、列表、发布)
10
+ * feedback 提交反馈
11
+ * health 健康检查
12
+ */
13
+
14
+ import { readFileSync, writeFileSync, existsSync } from 'fs';
15
+ import { resolve, basename } from 'path';
16
+
17
+ import '../lib/env.mjs'; // ★ 仓库根 .env → process.env(仅补缺失项,不覆盖已存在变量)
18
+
19
+
20
+ /** 从本地文件读取文章正文;失败时抛出友好错误 */
21
+ function readContentFile(p) {
22
+ const abs = resolve(process.cwd(), p);
23
+ try {
24
+ return readFileSync(abs, 'utf-8');
25
+ } catch (e) {
26
+ throw new Error(`❌ --content-file 读取失败: ${abs}\n ${e.message}`);
27
+ }
28
+ }
29
+
30
+ import { LimsClient } from '../lib/client.mjs';
31
+ import { ArticleManager, POST_TYPES, POST_TYPE_LABELS, DEFAULT_POST_TYPE } from '../lib/articles.mjs';
32
+ import { CourseManager } from '../lib/courses.mjs';
33
+ import { FeedbackManager } from '../lib/feedback.mjs';
34
+ import { MarketplaceManager, ASSET_TYPES, ASSET_TYPE_LABELS, ASSET_STATUSES, PRICE_TYPE_LABELS } from '../lib/marketplace.mjs';
35
+ import { VersionManager, KNOWN_PRODUCT_IDS } from '../lib/versions.mjs';
36
+ import { MaterialManager, MATERIAL_TYPES, MATERIAL_TYPE_LABELS } from '../lib/materials.mjs';
37
+ import { SiteManager, BLOCK_TYPES, SITE_SCHEMA_VERSION, collectStrings, replaceInStrings } from '../lib/site.mjs';
38
+ import { DaoManager, DAO_PROFILE_FIELDS, DAO_PROFILE_FIELD_LABELS } from '../lib/dao.mjs';
39
+
40
+ const COMMANDS = {
41
+ article: '文章管理:list, create, publish, delete',
42
+ course: '课程管理:list, create, publish, delete, categories',
43
+ feedback: '提交反馈或查看反馈列表',
44
+ marketplace: '应用市场:list, stats, get, create, update, publish, remove, categories',
45
+ version: '产品版本发布:list, get, create, release, sync-s3, add-asset, publish, manifest, remove, summary, health',
46
+ upload: '上传素材(图片/视频/文件)到亿检链素材库',
47
+ site: '站点设计:pages, get, export, draft, apply, publish, settings, public, check, replace-brand, types',
48
+ dao: 'DAO 档案:profile(读取 / 更新 name / description / detail 等字段)',
49
+ health: '检查 API 服务状态',
50
+ };
51
+
52
+ function printUsage() {
53
+ console.log(`
54
+ ╔══════════════════════════════════════════╗
55
+ ║ 亿检链运营助手 (lims) ║
56
+ ║ 亿检链平台 运营操作 CLI 工具 ║
57
+ ╚══════════════════════════════════════════╝
58
+
59
+ 用法: lims <command> [子命令] [选项]
60
+
61
+ 命令:
62
+ article list 列出文章
63
+ article create 创建文章草稿
64
+ article publish <postId> 发布文章
65
+ article upload 上传文章(创建并可选发布)
66
+
67
+ course list 列出课程
68
+ course create 创建课程
69
+ course publish <courseId> 发布课程
70
+ course upload 上传课程(创建并可选发布)
71
+ course categories 列出课程分类
72
+
73
+ feedback submit 提交反馈
74
+ feedback list 查看反馈列表
75
+
76
+ marketplace list 列出应用市场资产(--admin 查看管理端含草稿)
77
+ marketplace stats 统计资产(按类型/状态)
78
+ marketplace get <uuid> 查看资产详情
79
+ marketplace create 新建资产(上架应用)
80
+ marketplace update <uuid> 编辑资产
81
+ marketplace publish <uuid> 上架(active)
82
+ marketplace unpublish <uuid> 下架(inactive)
83
+ marketplace draft <uuid> 转草稿(draft)
84
+ marketplace featured <uuid> 设置精选
85
+ marketplace remove <uuid> 删除资产(仅 draft)
86
+ marketplace categories 查看类目聚合
87
+
88
+ version list 列出产品版本(--product-key clawdao)
89
+ version get <uuid> 查看版本详情
90
+ version create 创建版本(--notes '<h2>更新说明</h2>...')
91
+ version release 一键发布(创建 + 同步 S3)
92
+ version sync-s3 从 S3 同步资产到版本(精确:--product-id --version-id;或自动:--product-key --version)
93
+ version add-asset 登记单个下载资产(--product-key --version-id --name --url [--platform --size --content-type])
94
+ version publish <uuid> 发布版本
95
+ version update <uuid> 更新版本(--isLatest / --title / --prerelease / --notes / --notes-file)
96
+ version manifest <uuid> Manifest 预览(--action generate)
97
+ version summary --product-key <key> 发布摘要
98
+ version health Download-assets 健康检查
99
+ version remove <uuid> 删除版本(--force 硬删)
100
+
101
+ upload <file>... 上传一个或多个本地文件到素材库
102
+ --type image|video|file(默认 image)
103
+ --json 输出机器可读 JSON(供脚本拼装)
104
+ --json-only 仅输出 URL(每行一个)
105
+
106
+ site pages 列出站点页面
107
+ site get <slug> 查看页面区块(--json 看全文)
108
+ site export <slug> --out site/home.json 导出页面区块
109
+ site draft <slug> --file f 保存草稿(线上不变)
110
+ site apply <slug> --file f [--publish] [--site] 存草稿并发布
111
+ site create --slug x --title y [--file f] 新建页面
112
+ site publish <slug> | --site 发布页面 / 整站
113
+ site unpublish <slug> 下线页面
114
+ site delete <slug> 删除页面
115
+ site settings [--file f] 查看 / 更新站点设置
116
+ site public <slug> 回读公开端内容
117
+ site check [--pages all] [--forbid 觉知岛] 禁用词回读校验
118
+ site replace-brand --from A --to B [--pages all] [--publish]
119
+ site set-block --type SiteHeaderNav --file f [--pages all] [--publish]
120
+ site types 列出区块类型
121
+
122
+ dao profile 查看 DAO 档案(简介 / 详细介绍等)
123
+ dao profile --file site/dao-profile.json 用文件更新档案(--dry-run 只预览)
124
+ dao profile --detail @detail.md 用文件内容单独更新某个字段
125
+ dao profile --forbid 觉知,觉醒,龙虾岛 档案禁用词残留检查(有命中退出码 1)
126
+
127
+ health 检查 API 连接
128
+
129
+ 环境变量:
130
+ DDN_HUB_BASE_URL API 地址(默认: https://limschain.com)
131
+ DDN_HUB_AUTH_TOKEN 认证令牌
132
+ DDN_HUB_DAO_ID DAO ID
133
+
134
+ 示例:
135
+ lims health
136
+ lims article list --postType news
137
+ lims article create --title "标题" --content "内容" --postType news
138
+ lims article publish 42
139
+ lims article upload --title "T" --content "C" --publish
140
+ lims course list
141
+ lims course create --title "课程名"
142
+ lims feedback submit --title "建议" --content "详情"
143
+ lims upload ./cover.png # 上传单张图片
144
+ lims upload ./a.png ./b.png # 批量上传(去重)
145
+ lims upload ./a.png --json # JSON 输出(拼装给 --images 用)
146
+ lims site pages # 站点页面列表
147
+ lims site apply home --file site/club-home.json
148
+ lims site check --pages all --forbid 觉知岛
149
+ lims dao profile # 查看 DAO 档案
150
+ lims dao profile --file site/dao-profile.json --dry-run
151
+ `);
152
+ }
153
+
154
+ function parseArgs(args) {
155
+ const options = {};
156
+ for (let i = 0; i < args.length; i++) {
157
+ const arg = args[i];
158
+ if (arg.startsWith('--')) {
159
+ const key = arg.slice(2);
160
+ const camelKey = key.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
161
+ if (i + 1 < args.length && !args[i + 1].startsWith('--')) {
162
+ options[key] = args[i + 1];
163
+ options[camelKey] = args[i + 1];
164
+ i++;
165
+ } else {
166
+ options[key] = true;
167
+ options[camelKey] = true;
168
+ }
169
+ }
170
+ }
171
+ return options;
172
+ }
173
+
174
+ function resolveReadmeOption(value) {
175
+ const v = String(value);
176
+ if (!v.startsWith('@')) return { ok: true, readme: v };
177
+ const fp = v.slice(1);
178
+ if (!existsSync(fp)) return { ok: false, message: `README 文件不存在: ${fp}` };
179
+ return { ok: true, readme: readFileSync(fp, 'utf-8') };
180
+ }
181
+
182
+ /** 解析 --extra-data JSON;缺省或非法时返回 undefined(调用方自行报错) */
183
+ function parseExtraData(value) {
184
+ if (!value || value === true) return undefined;
185
+ try { return JSON.parse(String(value)); }
186
+ catch { return undefined; }
187
+ }
188
+
189
+ function getClient() {
190
+ // 不打印 token 信息到日志
191
+ const client = new LimsClient();
192
+ const config = client.getConfig();
193
+ return client;
194
+ }
195
+
196
+ async function main() {
197
+ const args = process.argv.slice(2);
198
+
199
+ if (args.length === 0) {
200
+ printUsage();
201
+ process.exit(0);
202
+ }
203
+
204
+ const command = args[0];
205
+
206
+ switch (command) {
207
+ case 'article':
208
+ await handleArticle(args.slice(1));
209
+ break;
210
+ case 'course':
211
+ await handleCourse(args.slice(1));
212
+ break;
213
+ case 'feedback':
214
+ await handleFeedback(args.slice(1));
215
+ break;
216
+ case 'marketplace':
217
+ await handleMarketplace(args.slice(1));
218
+ break;
219
+ case 'version':
220
+ await handleVersion(args.slice(1));
221
+ break;
222
+ case 'upload':
223
+ await handleUpload(args.slice(1));
224
+ break;
225
+ case 'site':
226
+ await handleSite(args.slice(1));
227
+ break;
228
+ case 'dao':
229
+ await handleDao(args.slice(1));
230
+ break;
231
+ case 'health':
232
+ await handleHealth();
233
+ break;
234
+ case 'help':
235
+ case '--help':
236
+ printUsage();
237
+ break;
238
+ default:
239
+ console.error(`未知命令: ${command}\n`);
240
+ printUsage();
241
+ process.exit(1);
242
+ }
243
+ }
244
+
245
+ // ===== 文章操作 =====
246
+
247
+ async function handleArticle(args) {
248
+ const sub = args[0];
249
+ const opts = parseArgs(args.slice(1));
250
+ const article = new ArticleManager(getClient());
251
+
252
+ switch (sub) {
253
+ case 'list': {
254
+ // ★ postType 白名单校验(仅当用户显式传了值时)
255
+ if (opts.postType && !POST_TYPES.includes(opts.postType)) {
256
+ return console.error(`❌ --postType "${opts.postType}" 不合法。合法值:${POST_TYPES.map((t) => `${t}(${POST_TYPE_LABELS[t]})`).join(' / ')}`);
257
+ }
258
+ const result = await article.list({
259
+ postType: opts.postType,
260
+ status: opts.status,
261
+ search: opts.search,
262
+ page: opts.page ? parseInt(opts.page) : 1,
263
+ limit: opts.limit ? parseInt(opts.limit) : 10,
264
+ });
265
+ if (!result.ok) return printError(result);
266
+ console.log(`\n📄 文章列表 (共 ${result.total} 篇):\n`);
267
+ for (const item of (result.items || [])) {
268
+ const ptLabel = POST_TYPE_LABELS[item.postType] || item.postType || '未分类';
269
+ console.log(` [${item.id}] ${item.title || '(无标题)'}`);
270
+ console.log(` 类型: ${ptLabel} | 状态: ${item.status} | 更新: ${item.updatedAt || '-'}`);
271
+ console.log();
272
+ }
273
+ break;
274
+ }
275
+ case 'create': {
276
+ if (!opts.title) return console.error('❌ 请指定 --title');
277
+ // ★ postType 白名单校验(ddn-hub 升级后只有 news / help / article)
278
+ const createPostType = opts.postType || DEFAULT_POST_TYPE;
279
+ if (!POST_TYPES.includes(createPostType)) {
280
+ return console.error(`❌ --postType "${opts.postType}" 不合法。合法值:${POST_TYPES.map((t) => `${t}(${POST_TYPE_LABELS[t]})`).join(' / ')}`);
281
+ }
282
+ let extraData;
283
+ try { if (opts.extraData) extraData = JSON.parse(opts.extraData); }
284
+ catch (e) { return console.error('❌ --extra-data 必须是合法 JSON: ' + e.message); }
285
+ let tags;
286
+ if (opts.tags) tags = opts.tags.split(',').map(s => s.trim()).filter(Boolean);
287
+ const result = await article.create({
288
+ title: opts.title,
289
+ content: opts.content || opts.body,
290
+ contentMarkdown: opts.contentFile ? readContentFile(opts.contentFile) : undefined,
291
+ postType: createPostType,
292
+ summary: opts.summary,
293
+ description: opts.description,
294
+ categoryId: opts.categoryId ? parseInt(opts.categoryId, 10) : undefined,
295
+ tags,
296
+ coverImage: opts.coverImage,
297
+ extraData,
298
+ body: opts.body,
299
+ slug: opts.slug,
300
+ });
301
+ if (!result.ok) return printError(result);
302
+ const id = result.data?.id;
303
+ console.log(`\n✅ 草稿已创建 (ID: ${id})`);
304
+ console.log(` 标题: ${opts.title}`);
305
+ console.log(` 类型: ${createPostType} (${POST_TYPE_LABELS[createPostType]})`);
306
+ console.log(` 发布: lims article publish ${id}\n`);
307
+ break;
308
+ }
309
+ case 'update': {
310
+ const postId = args[1];
311
+ if (!postId || isNaN(parseInt(postId))) return console.error('❌ 请指定文章 ID: lims article update <postId>');
312
+ if (!opts.contentFile) return console.error('❌ 请指定 --content-file <path>');
313
+ const md = readContentFile(opts.contentFile);
314
+ // ★ 只改正文:content / contentMarkdown 一起发;keepHead 保留 H1(不外发给服务端)
315
+ const result = await article.update(parseInt(postId), {
316
+ content: md,
317
+ contentMarkdown: md,
318
+ keepHead: opts.keepHead === true || opts.keepHead === 'true',
319
+ });
320
+ if (!result.ok) return printError(result);
321
+ console.log(`\n✅ 文章 ${postId} 正文已更新\n`);
322
+ if (result.message && !String(result.message).includes('请求成功')) {
323
+ console.log(` ${result.message}\n`);
324
+ }
325
+ break;
326
+ }
327
+ case 'publish': {
328
+ const postId = args[1];
329
+ if (!postId || isNaN(parseInt(postId))) return console.error('❌ 请指定文章 ID: lims article publish <postId>');
330
+ const result = await article.publish(parseInt(postId), {
331
+ platform: opts.platform === true || opts.platform === 'true',
332
+ extraData: parseExtraData(opts.extraData),
333
+ reviewComment: opts.reviewComment,
334
+ });
335
+ if (!result.ok) return printError(result);
336
+ console.log(`\n✅ 文章 ${postId} 已发布\n`);
337
+ if (result.message && !String(result.message).includes('请求成功')) {
338
+ console.log(` ${result.message}\n`);
339
+ }
340
+ break;
341
+ }
342
+ case 'upload': {
343
+ if (!opts.title) return console.error('❌ 请指定 --title');
344
+ // ★ postType 白名单校验(ddn-hub 升级后只有 news / help / article)
345
+ const uploadPostType = opts.postType || DEFAULT_POST_TYPE;
346
+ if (!POST_TYPES.includes(uploadPostType)) {
347
+ return console.error(`❌ --postType "${opts.postType}" 不合法。合法值:${POST_TYPES.map((t) => `${t}(${POST_TYPE_LABELS[t]})`).join(' / ')}`);
348
+ }
349
+ const shouldPublish = opts.publish === true || opts.publish === 'true';
350
+ let extraData;
351
+ try { if (opts.extraData) extraData = JSON.parse(opts.extraData); }
352
+ catch (e) { return console.error('❌ --extra-data 必须是合法 JSON: ' + e.message); }
353
+ let tags;
354
+ if (opts.tags) tags = opts.tags.split(',').map(s => s.trim()).filter(Boolean);
355
+ const result = await article.upload({
356
+ title: opts.title,
357
+ content: opts.content || opts.body,
358
+ contentMarkdown: opts.contentFile ? readContentFile(opts.contentFile) : undefined,
359
+ postType: uploadPostType,
360
+ summary: opts.summary,
361
+ description: opts.description,
362
+ categoryId: opts.categoryId ? parseInt(opts.categoryId, 10) : undefined,
363
+ tags,
364
+ coverImage: opts.coverImage,
365
+ extraData,
366
+ publish: shouldPublish,
367
+ slug: opts.slug,
368
+ });
369
+ if (!result.ok) return printError(result);
370
+ console.log(`\n✅ ${result.message}`);
371
+ if (result.data?.postId) {
372
+ console.log(` ID: ${result.data.postId}`);
373
+ console.log(` 类型: ${uploadPostType} (${POST_TYPE_LABELS[uploadPostType]})`);
374
+ }
375
+ console.log();
376
+ break;
377
+ }
378
+ default:
379
+ console.error(`
380
+ 文章管理子命令:
381
+ lims article list [--postType ${POST_TYPES.join('|')}] [--status draft] [--search keyword]
382
+ lims article create --title "标题" [--content "内容"|--content-file path] [--postType ${POST_TYPES.join('|')}] \
383
+ [--description "简介"] [--tags "a,b,c"] [--cover-image URL] [--slug my-article-slug] \
384
+ [--category-id 12] [--extra-data '{"category":"模型","subcategory":"指南"}']
385
+ lims article publish <postId> [--platform] [--extra-data '{"category":"智能体升级日志"}']
386
+ lims article update <postId> --content-file <path> [--keep-head]
387
+ # 只改正文(租户侧 403 自动走平台侧兜底);--keep-head 保留 markdown 首行 H1
388
+ lims article upload --title "标题" [--content "内容"|--content-file path] [--publish] \
389
+ [--postType ${POST_TYPES.join('|')}] \
390
+ [--description "简介"] [--tags "a,b,c"] [--cover-image URL] [--slug my-article-slug] \
391
+ [--category-id 12] [--extra-data '{"category":"模型","subcategory":"指南"}']
392
+
393
+ postType 取值(ddn-hub 升级后):
394
+ ${POST_TYPES.map((t) => ` - ${t.padEnd(8)} ${POST_TYPE_LABELS[t]}`).join('\n')}
395
+ 默认: ${DEFAULT_POST_TYPE}
396
+ `);
397
+ }
398
+ }
399
+
400
+ // ===== 课程操作 =====
401
+
402
+ async function handleCourse(args) {
403
+ const sub = args[0];
404
+ const opts = parseArgs(args.slice(1));
405
+ const course = new CourseManager(getClient());
406
+
407
+ switch (sub) {
408
+ case 'list': {
409
+ const result = await course.list({
410
+ keyword: opts.keyword,
411
+ status: opts.status,
412
+ page: opts.page ? parseInt(opts.page) : 1,
413
+ pageSize: opts.pageSize ? parseInt(opts.pageSize) : 10,
414
+ });
415
+ if (!result.ok) return printError(result);
416
+ console.log(`\n📚 课程列表 (共 ${result.total} 门):\n`);
417
+ for (const item of (result.items || [])) {
418
+ console.log(` [${item.id || item.uuid}] ${item.title || '(无标题)'}`);
419
+ console.log(` 状态: ${item.status === 1 ? '已发布' : '草稿'} | 价格: ${item.price || 0}`);
420
+ console.log();
421
+ }
422
+ break;
423
+ }
424
+ case 'categories': {
425
+ const result = await course.listCategories();
426
+ if (!result.ok) return printError(result);
427
+ const items = result.data?.items || result.data?.list || [];
428
+ console.log(`\n📂 课程分类:\n`);
429
+ for (const cat of items) {
430
+ console.log(` [${cat.uuid}] ${cat.name}`);
431
+ }
432
+ console.log();
433
+ break;
434
+ }
435
+ case 'create': {
436
+ if (!opts.title) return console.error('❌ 请指定 --title');
437
+ const result = await course.create({
438
+ title: opts.title,
439
+ description: opts.description,
440
+ coverImage: opts.coverImage,
441
+ categoryUuid: opts.categoryUuid,
442
+ teacherUuid: opts.teacherUuid,
443
+ price: opts.price ? parseFloat(opts.price) : undefined,
444
+ status: opts.publish ? 'published' : 'draft',
445
+ });
446
+ if (!result.ok) return printError(result);
447
+ const id = result.data?.id || result.data?.uuid;
448
+ console.log(`\n✅ 课程已创建 (ID: ${id})`);
449
+ console.log(` 标题: ${opts.title}`);
450
+ console.log(` 状态: ${opts.publish ? '已发布' : '草稿'}`);
451
+ console.log(` 发布: lims course publish ${id}\n`);
452
+ break;
453
+ }
454
+ case 'publish': {
455
+ const courseId = args[1];
456
+ if (!courseId) return console.error('❌ 请指定课程 ID: lims course publish <courseId>');
457
+ const result = await course.publish(courseId);
458
+ if (!result.ok) return printError(result);
459
+ console.log(`\n✅ 课程 ${courseId} 已发布\n`);
460
+ break;
461
+ }
462
+ case 'upload': {
463
+ if (!opts.title) return console.error('❌ 请指定 --title');
464
+ const shouldPublish = opts.publish === true || opts.publish === 'true';
465
+ const result = await course.upload({
466
+ title: opts.title,
467
+ description: opts.description,
468
+ coverImage: opts.coverImage,
469
+ categoryUuid: opts.categoryUuid,
470
+ teacherUuid: opts.teacherUuid,
471
+ price: opts.price ? parseFloat(opts.price) : 0,
472
+ publish: shouldPublish,
473
+ });
474
+ if (!result.ok) return printError(result);
475
+ console.log(`\n✅ ${result.message}`);
476
+ if (result.data?.courseId) {
477
+ console.log(` ID: ${result.data.courseId}`);
478
+ }
479
+ console.log();
480
+ break;
481
+ }
482
+ default:
483
+ console.error(`
484
+ 课程管理子命令:
485
+ lims course list [--keyword xxx] [--status published]
486
+ lims course create --title "课程名" [--description "描述"] [--price 0] [--publish]
487
+ lims course publish <courseId>
488
+ lims course upload --title "课程名" --description "描述" [--publish]
489
+ lims course categories
490
+ `);
491
+ }
492
+ }
493
+
494
+ // ===== 反馈操作 =====
495
+
496
+ async function handleFeedback(args) {
497
+ const sub = args[0];
498
+ const opts = parseArgs(args.slice(1));
499
+ const feedback = new FeedbackManager(getClient());
500
+
501
+ switch (sub) {
502
+ case 'submit': {
503
+ if (!opts.title) return console.error('❌ 请指定反馈 --title');
504
+ const result = await feedback.submit({
505
+ title: opts.title,
506
+ content: opts.content || '',
507
+ type: opts.type || 'suggestion',
508
+ contact: opts.contact,
509
+ });
510
+ if (!result.ok) return printError(result);
511
+ console.log(`\n✅ 反馈已提交: "${opts.title}"\n`);
512
+ break;
513
+ }
514
+ case 'list': {
515
+ const result = await feedback.list({
516
+ type: opts.type,
517
+ status: opts.status,
518
+ page: opts.page ? parseInt(opts.page) : 1,
519
+ limit: opts.limit ? parseInt(opts.limit) : 20,
520
+ });
521
+ if (!result.ok) return printError(result);
522
+ console.log(`\n💬 反馈列表 (共 ${result.total} 条):\n`);
523
+ for (const item of (result.items || [])) {
524
+ console.log(` [${item.id}] ${item.title}`);
525
+ console.log(` 类型: ${item.feedbackType || item.postType} | 状态: ${item.status}`);
526
+ console.log();
527
+ }
528
+ break;
529
+ }
530
+ default:
531
+ console.error(`
532
+ 反馈子命令:
533
+ lims feedback submit --title "反馈标题" [--content "详情"] [--type suggestion|bug|feature]
534
+ lims feedback list [--type suggestion]
535
+ `);
536
+ }
537
+ }
538
+
539
+ // ===== 应用市场操作 =====
540
+
541
+ function assetLine(item) {
542
+ const type = ASSET_TYPE_LABELS[item.type] || item.type || 'unknown';
543
+ const price = PRICE_TYPE_LABELS[item.priceType] || item.priceType || '-';
544
+ const featured = item.isFeatured ? ' ⭐' : '';
545
+ const rating = item.rating ? ` | ⭐${Number(item.rating).toFixed(1)}` : '';
546
+ const downloads = item.downloadCount ? ` | ↓${item.downloadCount}` : '';
547
+ // README 是详情页正文:为空时详情页只会显示空状态,这里直接标出来
548
+ const readmeLen = String(item.readme || '').trim().length;
549
+ const readme = readmeLen > 0
550
+ ? ` | README: ${readmeLen >= 1000 ? `${(readmeLen / 1000).toFixed(1)}KB` : `${readmeLen}字符`}`
551
+ : ' | README: ❌缺失';
552
+ return ` [${type}] ${item.name}${featured}\n 状态: ${item.status} | 定价: ${price} | 版本: ${item.version || '-'}${rating}${downloads}${readme}\n UUID: ${item.uuid}`;
553
+ }
554
+
555
+ async function handleMarketplace(args) {
556
+ const sub = args[0];
557
+ const opts = parseArgs(args.slice(1));
558
+ const mp = new MarketplaceManager(getClient());
559
+ const isAdmin = opts.admin === true || opts.admin === 'true';
560
+
561
+ switch (sub) {
562
+ case 'list': {
563
+ const result = isAdmin
564
+ ? await mp.listAdmin({ type: opts.type, status: opts.status, keyword: opts.keyword, page: opts.page ? parseInt(opts.page) : 1, pageSize: opts.pageSize ? parseInt(opts.pageSize) : 20 })
565
+ : await mp.list({ type: opts.type, keyword: opts.keyword, category: opts.category, tag: opts.tag, sort: opts.sort, page: opts.page ? parseInt(opts.page) : 1, pageSize: opts.pageSize ? parseInt(opts.pageSize) : 20 });
566
+ if (!result.ok) return printError(result);
567
+ const title = isAdmin ? '管理端资产' : '应用市场资产';
568
+ console.log(`\n🧩 ${title} (共 ${result.total} 个):\n`);
569
+ for (const item of (result.items || [])) {
570
+ console.log(assetLine(item));
571
+ console.log();
572
+ }
573
+ if (result.totalPages > 1) console.log(` … 第 ${result.page}/${result.totalPages} 页(共 ${result.total} 个)`);
574
+ break;
575
+ }
576
+ case 'stats': {
577
+ const result = await mp.stats();
578
+ if (!result.ok) return printError(result);
579
+ console.log(`\n📊 应用市场统计 (共 ${result.total} 个资产):\n`);
580
+ // 上架应用清单优先展示(关键信息前置)
581
+ const active = (result.items || []).filter((i) => i.status === 'active');
582
+ console.log(' 上架应用 (active):');
583
+ if (active.length === 0) {
584
+ console.log(' (暂无已上架资产)');
585
+ } else {
586
+ for (const item of active) {
587
+ console.log(` [${ASSET_TYPE_LABELS[item.type] || item.type}] ${item.name}${item.isFeatured ? ' ⭐' : ''}`);
588
+ }
589
+ }
590
+ console.log('\n 按类型:');
591
+ for (const [t, n] of Object.entries(result.byType).sort((a, b) => b[1] - a[1])) {
592
+ console.log(` ${ASSET_TYPE_LABELS[t] || t}: ${n}`);
593
+ }
594
+ console.log('\n 按状态:');
595
+ for (const [s, n] of Object.entries(result.byStatus).sort((a, b) => b[1] - a[1])) {
596
+ console.log(` ${s}: ${n}`);
597
+ }
598
+ console.log();
599
+ break;
600
+ }
601
+ case 'get': {
602
+ const uuid = args[1];
603
+ if (!uuid) return console.error('❌ 请指定资产 UUID: lims marketplace get <uuid>');
604
+ const result = await mp.get(uuid);
605
+ if (!result.ok) return printError(result);
606
+ const a = result.data || {};
607
+ console.log(`\n📦 资产详情: ${a.name}\n`);
608
+ console.log(` UUID: ${a.uuid}`);
609
+ console.log(` 类型: ${ASSET_TYPE_LABELS[a.type] || a.type}`);
610
+ console.log(` Slug: ${a.slug}`);
611
+ console.log(` 状态: ${a.status}`);
612
+ console.log(` 定价: ${PRICE_TYPE_LABELS[a.priceType] || a.priceType}${a.price ? ` (¥${a.price})` : ''}${a.pointsCost ? ` (${a.pointsCost}积分)` : ''}`);
613
+ console.log(` 版本: ${a.version || '-'}${a.minVersion ? ` (最低 ${a.minVersion})` : ''}`);
614
+ console.log(` 作者: ${a.author || '-'}`);
615
+ console.log(` 类目: ${a.category || '-'}`);
616
+ console.log(` 标签: ${(a.tags || []).join(', ') || '-'}`);
617
+ console.log(` 评分: ${a.rating ? `⭐${Number(a.rating).toFixed(1)} (${a.ratingCount || 0}人)` : '-'}`);
618
+ console.log(` 下载: ${a.downloadCount || 0}`);
619
+ console.log(` 精选: ${a.isFeatured ? '✅ 是' : '否'}`);
620
+ if (a.sourceUrl) console.log(` 源码: ${a.sourceUrl}`);
621
+ if (a.configUrl) console.log(` 配置: ${a.configUrl}`);
622
+ if (a.description) console.log(` 描述: ${a.description}`);
623
+ console.log();
624
+ break;
625
+ }
626
+ case 'create': {
627
+ if (!opts.name) return console.error('❌ 请指定 --name(资产名称)');
628
+ if (!opts.type) return console.error(`❌ 请指定 --type(${ASSET_TYPES.join(' / ')})`);
629
+ // README 支持两种方式:直接传 markdown 文本,或传文件路径(@file 语法)
630
+ let readme;
631
+ if (opts.readme !== undefined) {
632
+ const resolved = resolveReadmeOption(opts.readme);
633
+ if (!resolved.ok) return console.error(`❌ ${resolved.message}`);
634
+ readme = resolved.readme;
635
+ }
636
+ const result = await mp.create({
637
+ type: opts.type,
638
+ slug: opts.slug || opts.name.trim().toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, ''),
639
+ name: opts.name,
640
+ description: opts.description,
641
+ icon: opts.icon,
642
+ category: opts.category,
643
+ author: opts.author,
644
+ version: opts.version,
645
+ sourceUrl: opts.sourceUrl,
646
+ configUrl: opts.configUrl,
647
+ priceType: opts.priceType,
648
+ price: opts.price !== undefined ? parseFloat(opts.price) : undefined,
649
+ pointsCost: opts.pointsCost !== undefined ? parseInt(opts.pointsCost) : undefined,
650
+ isFeatured: opts.featured === 'true' || opts.featured === true ? true : undefined,
651
+ tags: opts.tags ? opts.tags.split(',').map((s) => s.trim()).filter(Boolean) : undefined,
652
+ license: opts.license,
653
+ readme,
654
+ });
655
+ if (!result.ok) return printError(result);
656
+ const a = result.data || {};
657
+ console.log(`\n✅ 资产已创建`);
658
+ console.log(` UUID: ${a.uuid || result.data?.uuid}`);
659
+ console.log(` 名称: ${opts.name}`);
660
+ console.log(` 类型: ${opts.type} | Slug: ${a.slug || opts.slug || ''}`);
661
+ console.log(` License: ${opts.license || '(未提供)'} | README: ${readme ? `${readme.length} 字符` : '(未提供)'}`);
662
+ if (!opts.license || !readme) {
663
+ console.warn(`\n⚠️ 上架规范要求 README + License(见 docs/MARKETPLACE-GUIDELINES.md)`);
664
+ console.warn(` 补齐: lims marketplace update ${a.uuid || '<uuid>'} --license "MIT" --readme "@README.md"\n`);
665
+ }
666
+ console.log(` 上架: lims marketplace publish ${a.uuid || ''}\n`);
667
+ break;
668
+ }
669
+ case 'update': {
670
+ const uuid = args[1];
671
+ if (!uuid) return console.error('❌ 请指定资产 UUID: lims marketplace update <uuid> --name "新名称"');
672
+ const updates = {};
673
+ for (const f of ['type', 'slug', 'name', 'description', 'icon', 'category', 'author', 'version', 'sourceUrl', 'configUrl', 'priceType', 'license']) {
674
+ if (opts[f] !== undefined) updates[f] = opts[f];
675
+ }
676
+ if (opts.price !== undefined) updates.price = parseFloat(opts.price);
677
+ if (opts.pointsCost !== undefined) updates.pointsCost = parseInt(opts.pointsCost);
678
+ if (opts.tags !== undefined) updates.tags = opts.tags.split(',').map((s) => s.trim()).filter(Boolean);
679
+ if (opts.featured === 'true' || opts.featured === true) updates.isFeatured = true;
680
+ if (opts.featured === 'false') updates.isFeatured = false;
681
+ // README 支持两种方式:直接传 markdown 文本,或传文件路径(@file 语法)
682
+ if (opts.readme !== undefined) {
683
+ const resolved = resolveReadmeOption(opts.readme);
684
+ if (!resolved.ok) return console.error(`❌ ${resolved.message}`);
685
+ updates.readme = resolved.readme;
686
+ }
687
+ if (Object.keys(updates).length === 0) {
688
+ return console.error('❌ 没有需要更新的字段,例如: --name / --description / --price / --category / --readme / --license');
689
+ }
690
+ const result = await mp.update(uuid, updates);
691
+ if (!result.ok) return printError(result);
692
+ console.log(`\n✅ 资产 ${uuid} 已更新: ${Object.keys(updates).join(', ')}\n`);
693
+ break;
694
+ }
695
+ case 'publish':
696
+ case 'unpublish':
697
+ case 'draft':
698
+ case 'archive': {
699
+ const uuid = args[1];
700
+ if (!uuid) return console.error(`❌ 请指定资产 UUID: lims marketplace ${sub} <uuid>`);
701
+ const statusMap = { publish: 'active', unpublish: 'inactive', draft: 'draft', archive: 'archived' };
702
+ const target = statusMap[sub];
703
+ const result = await mp.updateStatus(uuid, target);
704
+ if (!result.ok) return printError(result);
705
+ const label = { active: '已上架 🚀', inactive: '已下架', draft: '已转草稿', archived: '已归档' }[target];
706
+ console.log(`\n✅ 资产 ${uuid} ${label}\n`);
707
+ break;
708
+ }
709
+ case 'featured':
710
+ case 'unfeatured': {
711
+ const uuid = args[1];
712
+ if (!uuid) return console.error(`❌ 请指定资产 UUID: lims marketplace ${sub} <uuid>`);
713
+ const on = sub === 'featured';
714
+ const result = await mp.setFeatured(uuid, on);
715
+ if (!result.ok) return printError(result);
716
+ console.log(`\n✅ 资产 ${uuid} ${on ? '已设为精选 ⭐' : '已取消精选'}\n`);
717
+ break;
718
+ }
719
+ case 'remove': {
720
+ const uuid = args[1];
721
+ if (!uuid) return console.error('❌ 请指定资产 UUID: lims marketplace remove <uuid>');
722
+ const confirm = opts.yes === true || opts.yes === 'true';
723
+ if (!confirm) {
724
+ console.log('\n⚠️ 删除不可恢复,确认请加 --yes');
725
+ return;
726
+ }
727
+ const result = await mp.remove(uuid);
728
+ if (!result.ok) return printError(result);
729
+ console.log(`\n✅ 资产 ${uuid} 已删除\n`);
730
+ break;
731
+ }
732
+ case 'categories': {
733
+ const result = await mp.categories();
734
+ if (!result.ok) return printError(result);
735
+ console.log('\n🗂️ 应用市场类目聚合:\n');
736
+ for (const c of (result.items || [])) {
737
+ console.log(` [${ASSET_TYPE_LABELS[c.type] || c.type}] ${c.category} (${c.count})`);
738
+ }
739
+ console.log();
740
+ break;
741
+ }
742
+ default:
743
+ console.error(`
744
+ 应用市场子命令:
745
+ lims marketplace list [--type app|skill|mcp|prompt|employee|plugin|template] [--status] [--keyword] [--sort] [--admin]
746
+ lims marketplace stats
747
+ lims marketplace get <uuid>
748
+ lims marketplace create --name "名称" --type app --slug xxx [--description] [--icon] [--category] [--priceType free|points|paid] [--price] [--featured]
749
+ [--author] [--version] [--sourceUrl] [--tags "a,b"] [--license MIT] [--readme "@README.md"]
750
+ lims marketplace update <uuid> --name "新名称" [--description] [--price] [--category] ...
751
+ lims marketplace publish <uuid> 上架
752
+ lims marketplace unpublish <uuid> 下架
753
+ lims marketplace draft <uuid> 转草稿
754
+ lims marketplace featured <uuid> 设置精选
755
+ lims marketplace unfeatured <uuid> 取消精选
756
+ lims marketplace remove <uuid> --yes 删除
757
+ lims marketplace categories
758
+ `);
759
+ }
760
+ }
761
+
762
+ // ===== 健康检查 =====
763
+
764
+ async function handleHealth() {
765
+ const client = getClient();
766
+ const result = await client.healthCheck();
767
+ const config = client.getConfig();
768
+
769
+ console.log(`\n🔍 亿检链 API 连接诊断\n`);
770
+ console.log(` API 地址: ${config.baseUrl}`);
771
+ console.log(` 认证令牌: ${config.authToken ? '✅ 已设置' : '❌ 未设置'}`);
772
+ console.log(` DAO ID: ${config.daoId ? `✅ ${config.daoId}` : '❌ 未设置'}`);
773
+
774
+ if (result.ok) {
775
+ console.log(` 连接状态: ✅ 正常 (${result.message})`);
776
+ } else {
777
+ console.log(` 连接状态: ❌ 失败`);
778
+ console.log(` 错误: ${result.message}`);
779
+ }
780
+ console.log();
781
+ }
782
+
783
+ // ===== 产品版本发布 =====
784
+
785
+ async function handleVersion(args) {
786
+ const subcommand = args[0];
787
+ const opts = parseArgs(args.slice(1));
788
+ const client = new LimsClient();
789
+ const vm = new VersionManager(client);
790
+
791
+ switch (subcommand) {
792
+ case 'list': {
793
+ const productKey = opts.productKey || opts.product;
794
+ const productId = opts.productId || (productKey && KNOWN_PRODUCT_IDS[productKey]);
795
+ if (!productKey && !productId) {
796
+ console.error('❌ 需要 --product-key 或 --product-id(已知 productKey:' + Object.keys(KNOWN_PRODUCT_IDS).join(', ') + ')');
797
+ process.exit(2);
798
+ }
799
+ const result = await vm.list({ productId, productKey, status: opts.status, releaseSource: opts.source, page: parseInt(opts.page || '1'), pageSize: parseInt(opts.pageSize || '20') });
800
+ printListResult(result, '版本', (v) => ` [${v.version || '?'}] ${v.title || ''}\n id=${v.id} | status=${v.status} | isLatest=${v.isLatest} | assets=${(v.assets||[]).length}\n releaseAt=${v.releaseAt || v.createdAt || ''}`);
801
+ break;
802
+ }
803
+ case 'get': {
804
+ if (!opts.id) { console.error('❌ 需要 --id <versionId>'); process.exit(2); }
805
+ const result = await vm.get(opts.id);
806
+ if (result.ok) printDetailResult(result, '版本', (v) => ` ${v.version} (${v.status}) - isLatest=${v.isLatest}\n UUID: ${v.id}\n productId: ${v.productId}\n releaseAt: ${v.releaseAt}\n assets: ${(v.assets||[]).length} 个`);
807
+ else printError(result);
808
+ break;
809
+ }
810
+ case 'create': {
811
+ // 整理版本字段 → POST 创建
812
+ if (!opts.version) { console.error('❌ 需要 --version(如 1.0.27)'); process.exit(2); }
813
+ const productId = opts.productId || (opts.productKey && KNOWN_PRODUCT_IDS[opts.productKey]);
814
+ if (!productId) { console.error('❌ 需要 --product-key 或 --product-id'); process.exit(2); }
815
+ const releaseNotes = opts.notes
816
+ ? { zh: [opts.notes], en: [] }
817
+ : (opts.notesFile
818
+ ? { zh: [readFileSync(opts.notesFile, 'utf-8')], en: [] }
819
+ : undefined);
820
+ const result = await vm.create({
821
+ productId,
822
+ version: opts.version,
823
+ title: opts.title,
824
+ releaseNotes,
825
+ isPrerelease: opts.prerelease === 'true' || opts.prerelease === true,
826
+ isLatest: opts.latest !== 'false' && opts.latest !== false,
827
+ releaseSource: opts.source || 'manual',
828
+ });
829
+ if (result.ok) {
830
+ console.log(`✅ 版本创建成功`);
831
+ console.log(` id: ${result.data?.id}`);
832
+ console.log(` version: ${result.data?.version}`);
833
+ console.log(` status: ${result.data?.status || 'draft'}`);
834
+ } else {
835
+ printError(result);
836
+ }
837
+ break;
838
+ }
839
+ case 'sync-s3': {
840
+ // 同步 S3 资产到产品版本(“同步s3”按钮后端)
841
+ // 两种调用模式:
842
+ // A) 精确:--product-id <uuid> + --version-id <uuid> (最稳,跳过自动查找)
843
+ // B) 自动:--product-key <slug> + --version <semver> (会自动查 draft / published 等所有状态)
844
+ if (opts.versionId) {
845
+ // 模式 A:精确模式,必须同时有 productId 或 productKey
846
+ if (!opts.productId && !opts.productKey) {
847
+ console.error('❌ --version-id 必须配合 --product-id 或 --product-key 使用');
848
+ process.exit(2);
849
+ }
850
+ } else {
851
+ // 模式 B:自动查找模式
852
+ if (!opts.productKey) { console.error('❌ 需要 --product-key(如 clawdao)'); process.exit(2); }
853
+ if (!opts.version) { console.error('❌ 需要 --version(如 1.0.27)'); process.exit(2); }
854
+ }
855
+ const dryRun = opts.dryRun === 'true' || opts.dryRun === true;
856
+ const modeLabel = opts.versionId ? `精确(productId=${opts.productId || '(by productKey)'}, versionId=${opts.versionId.slice(0, 8)}...)` : `自动(productKey=${opts.productKey}, version=${opts.version})`;
857
+ console.log(`☁️ 同步 S3 → ${modeLabel}${dryRun ? ' (DRY-RUN)' : ''}`);
858
+ const result = await vm.syncFromS3({
859
+ productId: opts.productId,
860
+ versionId: opts.versionId,
861
+ productKey: opts.productKey,
862
+ version: opts.version,
863
+ // ★ 修复:库侧入参名是 s3Prefix,曾只传 prefix 导致 --prefix 静默失效;
864
+ // 两个都传,防止将来任一侧改名再次静默失灵。
865
+ s3Prefix: opts.prefix,
866
+ prefix: opts.prefix,
867
+ dryRun,
868
+ });
869
+ if (result.ok) {
870
+ // dryRun 是客户端本地 diff 预览(不发写请求),不能报“同步成功”
871
+ const isPreview = dryRun || result.data?.dryRun === true;
872
+ console.log(isPreview ? `✅ S3 同步预览(DRY-RUN,未写入任何资产)` : `✅ S3 同步成功`);
873
+ console.log(` message: ${result.message}`);
874
+ if (isPreview && result.data) {
875
+ console.log(` 将新增: ${result.data.created} 个`);
876
+ console.log(` 将跳过: ${result.data.skipped} 个(已存在)`);
877
+ }
878
+ if (result.data) console.log(` data: ${JSON.stringify(result.data, null, 2)}`);
879
+ } else {
880
+ printError(result);
881
+ }
882
+ break;
883
+ }
884
+ case 'add-asset': {
885
+ // 登记下载资产(文件已在 S3,平台侧补「文件 ↔ 版本」对应关系)
886
+ const productId = opts.productId || (opts.productKey && KNOWN_PRODUCT_IDS[opts.productKey]);
887
+ if (!productId) { console.error('❌ 需要 --product-key 或 --product-id'); process.exit(2); }
888
+ if (!opts.versionId) { console.error('❌ 需要 --version-id <uuid>'); process.exit(2); }
889
+ if (!opts.name) { console.error('❌ 需要 --name <文件名>'); process.exit(2); }
890
+ if (!opts.url) { console.error('❌ 需要 --url <下载地址>'); process.exit(2); }
891
+ const result = await vm.createDownloadAsset({
892
+ productId,
893
+ versionId: opts.versionId,
894
+ name: opts.name,
895
+ downloadUrl: opts.url,
896
+ platform: opts.platform,
897
+ arch: opts.arch,
898
+ contentType: opts.contentType,
899
+ size: opts.size ? Number(opts.size) : undefined,
900
+ checksum: opts.checksum,
901
+ isPrimary: opts.primary === 'true' ? true : undefined,
902
+ });
903
+ if (result.ok) {
904
+ console.log(`✅ 资产已登记: ${opts.name}`);
905
+ console.log(` id: ${result.data?.id || result.data?.data?.id || '(未返回)'}`);
906
+ } else {
907
+ printError(result);
908
+ }
909
+ break;
910
+ }
911
+ case 'publish': {
912
+ if (!opts.id) { console.error('❌ 需要 --id <versionId>'); process.exit(2); }
913
+ const result = await vm.publish(opts.id);
914
+ if (result.ok) console.log(`✅ 版本 ${opts.id} 已发布`);
915
+ else printError(result);
916
+ break;
917
+ }
918
+ case 'update': {
919
+ // 更新版本(可改 title / isLatest / isPrerelease / notes 等)
920
+ if (!opts.id) { console.error('❌ 需要 --id <versionId>'); process.exit(2); }
921
+ const body = {};
922
+ if (opts.title !== undefined) body.title = opts.title;
923
+ if (opts.isLatest === 'true' || opts.isLatest === true) body.isLatest = true;
924
+ if (opts.isLatest === 'false' || opts.isLatest === false) body.isLatest = false;
925
+ if (opts.prerelease === 'true' || opts.prerelease === true) body.isPrerelease = true;
926
+ if (opts.prerelease === 'false' || opts.prerelease === false) body.isPrerelease = false;
927
+ if (opts.latest === 'false' || opts.latest === false) body.isLatest = false; // 兼容 --latest false 别名
928
+ if (opts.notes !== undefined) body.releaseNotes = opts.notes;
929
+ if (opts.notesFile !== undefined) body.releaseNotes = readFileSync(opts.notesFile, 'utf-8');
930
+ if (opts.sortOrder !== undefined) body.sortOrder = parseInt(opts.sortOrder, 10);
931
+ if (Object.keys(body).length === 0) {
932
+ console.error('❌ 没有需要更新的字段,例如: --title / --isLatest true|false / --prerelease true|false / --notes / --notes-file');
933
+ process.exit(2);
934
+ }
935
+ const result = await vm.update(opts.id, body);
936
+ if (result.ok) {
937
+ console.log(`✅ 版本 ${opts.id} 已更新: ${Object.keys(body).join(', ')}`);
938
+ if (result.data) console.log(` data: ${JSON.stringify(result.data)}`);
939
+ } else {
940
+ printError(result);
941
+ }
942
+ break;
943
+ }
944
+ case 'manifest': {
945
+ const action = opts.action || 'preview';
946
+ if (!opts.id) { console.error('❌ 需要 --id <versionId>'); process.exit(2); }
947
+ const result = action === 'generate'
948
+ ? await vm.generateManifest(opts.id)
949
+ : await vm.previewManifest(opts.id);
950
+ if (result.ok) {
951
+ console.log(`✅ Manifest ${action === 'generate' ? '已生成' : '预览'}:`);
952
+ console.log(JSON.stringify(result.data, null, 2));
953
+ } else printError(result);
954
+ break;
955
+ }
956
+ case 'summary': {
957
+ if (!opts.productKey) { console.error('❌ 需要 --product-key'); process.exit(2); }
958
+ const result = await vm.downloadSummary(opts.productKey);
959
+ if (result.ok) console.log(JSON.stringify(result.data, null, 2));
960
+ else printError(result);
961
+ break;
962
+ }
963
+ case 'health': {
964
+ const result = await vm.healthCheck();
965
+ if (result.ok) console.log(`✅ Download-assets 服务健康: ${result.message}`);
966
+ else printError(result);
967
+ break;
968
+ }
969
+ case 'release': {
970
+ // 一键完整流程:整理字段 + POST 创建 + 同步 S3
971
+ if (!opts.version) { console.error('❌ 需要 --version'); process.exit(2); }
972
+ const productKey = opts.productKey || 'clawdao';
973
+ const productId = opts.productId || KNOWN_PRODUCT_IDS[productKey];
974
+ if (!productId) { console.error(`❌ 未知 productKey "${productKey}",请用 --product-id`); process.exit(2); }
975
+ const releaseNotes = opts.notes
976
+ ? { zh: [opts.notes], en: [] }
977
+ : opts.notesFile
978
+ ? { zh: [readFileSync(opts.notesFile, 'utf-8')], en: [] }
979
+ : undefined;
980
+ console.log(`🚀 一键发布流程`);
981
+ console.log(` productKey: ${productKey}`);
982
+ console.log(` version: ${opts.version}`);
983
+ console.log(` syncS3: ${opts['no-sync'] ? '否' : '是'}`);
984
+ const result = await vm.release({
985
+ productKey,
986
+ productId,
987
+ version: opts.version,
988
+ title: opts.title,
989
+ releaseNotes,
990
+ isPrerelease: opts.prerelease === 'true',
991
+ syncS3: !opts['no-sync'],
992
+ s3Prefix: opts.prefix,
993
+ dryRun: opts.dryRun === 'true',
994
+ });
995
+ if (result.ok) {
996
+ console.log(`✅ 发布流程完成`);
997
+ for (const s of result.steps) console.log(` [${s.ok ? '✓' : '✗'}] ${s.step}: ${s.message}`);
998
+ if (result.versionId) console.log(` versionId: ${result.versionId}`);
999
+ } else {
1000
+ console.error(`❌ 发布流程失败于某个环节`);
1001
+ for (const s of result.steps) console.error(` [${s.ok ? '✓' : '✗'}] ${s.step}: ${s.message}`);
1002
+ printError(result);
1003
+ }
1004
+ break;
1005
+ }
1006
+ case 'remove':
1007
+ case 'rm': {
1008
+ if (!opts.id) { console.error('❌ 需要 --id'); process.exit(2); }
1009
+ const result = opts.force === 'true'
1010
+ ? await vm.removeForce(opts.id)
1011
+ : await vm.remove(opts.id);
1012
+ if (result.ok) console.log(`✅ 版本 ${opts.id} 已删除${opts.force === 'true' ? '(硬删)' : ''}`);
1013
+ else printError(result);
1014
+ break;
1015
+ }
1016
+ default:
1017
+ console.log(`
1018
+ 产品版本发布(lims version):
1019
+
1020
+ lims version list 列出版本(--product-key clawdao)
1021
+ lims version get --id <uuid> 版本详情
1022
+ lims version create 创建版本
1023
+ --product-key clawdao --version 1.0.27
1024
+ --notes '<h2>v1.0.27 更新说明</h2>...' (HTML 字符串)
1025
+ [--notes-file <path>] (从文件读取,适合长 md)
1026
+ [--title '标题'] [--prerelease true]
1027
+ lims version release 一键发布(创建 + 同步 S3)
1028
+ --product-key clawdao --version 1.0.27
1029
+ --notes '...' [--notes-file <path>] [--no-sync]
1030
+ lims version update --id <uuid> 更新版本(--isLatest true|false / --title / --prerelease / --notes / --notes-file)
1031
+ lims version sync-s3 同步 S3 资产到版本(“同步s3”按钮)
1032
+ 自动模式 --product-key clawdao --version 1.0.27
1033
+ 精确模式 --product-id <uuid> --version-id <uuid> (跳过自动查找,draft 也行)
1034
+
1035
+ lims version add-asset 登记单个下载资产(文件已在 S3 时用)
1036
+ --product-key clawdao --version-id <uuid> --name ClawDao_1.0.34_aarch64.dmg
1037
+ --url https://s3.limschain.com/clawdao/1.0.34/ClawDao_1.0.34_aarch64.dmg
1038
+ [--platform macOS] [--size 63193946] [--content-type application/x-apple-diskimage] [--arch aarch64]
1039
+ [--prefix path/] [--dryRun true]
1040
+ lims version publish --id <uuid> 发布版本
1041
+ lims version manifest --id <uuid> Manifest 预览(--action generate 生成)
1042
+ lims version summary --product-key X 发布摘要
1043
+ lims version health Download-assets 健康检查
1044
+ lims version remove --id <uuid> 删除(--force 硬删)
1045
+
1046
+ 已知 productKey:${Object.keys(KNOWN_PRODUCT_IDS).join(', ')}
1047
+ `);
1048
+ }
1049
+ }
1050
+
1051
+ // ===== 素材上传 =====
1052
+
1053
+ async function handleUpload(args) {
1054
+ // 支持两种调用形态:
1055
+ // lims upload <file1> [file2 ...] [--type image] [--json] [--json-only] [--filename <name>]
1056
+ // lims upload --check (仅健康检查)
1057
+ const opts = parseArgs(args);
1058
+ const files = [];
1059
+ for (const a of args) {
1060
+ if (a.startsWith('--')) break;
1061
+ files.push(a);
1062
+ }
1063
+
1064
+ const mm = new MaterialManager(getClient());
1065
+
1066
+ // 健康检查模式
1067
+ if (opts.check === true || opts.check === 'true') {
1068
+ const h = mm.health();
1069
+ console.log(`\n🩺 素材上传健康检查\n`);
1070
+ if (h.ok) {
1071
+ console.log(` ✅ ${h.message}`);
1072
+ console.log(` baseUrl: ${h.config.baseUrl}`);
1073
+ console.log(` auth: ${h.config.hasAuthToken ? '已设置' : '❌'}`);
1074
+ console.log(` dao: ${h.config.hasDaoId ? h.config.daoId : '❌'}`);
1075
+ } else {
1076
+ console.log(` ❌ ${h.message}`);
1077
+ }
1078
+ console.log();
1079
+ process.exit(h.ok ? 0 : 1);
1080
+ }
1081
+
1082
+ if (files.length === 0) {
1083
+ console.error(`❌ 请指定要上传的文件路径,例如: lims upload ./cover.png`);
1084
+ console.error(` 支持 image / video / file,通过 --type 选择(默认 image)`);
1085
+ console.error(` 可选 --json 输出结构化结果,--json-only 仅输出 URL 列表`);
1086
+ process.exit(2);
1087
+ }
1088
+
1089
+ const type = (typeof opts.type === 'string' && opts.type) || 'image';
1090
+ if (!MATERIAL_TYPES.includes(type)) {
1091
+ console.error(`❌ --type 必须是 ${MATERIAL_TYPES.join(' / ')}`);
1092
+ process.exit(2);
1093
+ }
1094
+
1095
+ const wantJson = opts.json === true || opts.json === 'true';
1096
+ const wantJsonOnly = opts['json-only'] === true || opts['json-only'] === 'true';
1097
+
1098
+ // 批量上传(自动去重)
1099
+ const result = await mm.uploadBatch(files, { type });
1100
+
1101
+ if (wantJsonOnly) {
1102
+ // 仅打印 URL,每行一个;失败时按 stderr 输出,最后用退出码区分
1103
+ for (const url of result.map.values()) console.log(url);
1104
+ for (const f of result.failures) console.error(`❌ ${f.path}: ${f.message}`);
1105
+ process.exit(result.failures.length === 0 ? 0 : 1);
1106
+ }
1107
+
1108
+ if (wantJson) {
1109
+ // JSON 输出(含 ok + map + failures),便于 jq 处理或脚本拼装
1110
+ const payload = {
1111
+ ok: result.ok,
1112
+ message: result.message,
1113
+ type,
1114
+ count: result.map.size,
1115
+ files: Array.from(result.map.entries()).map(([path, url]) => ({ path, url })),
1116
+ failures: result.failures,
1117
+ };
1118
+ console.log(JSON.stringify(payload, null, 2));
1119
+ process.exit(result.ok ? 0 : 1);
1120
+ }
1121
+
1122
+ // 人类可读输出
1123
+ console.log(`\n📤 素材上传(type=${type})\n`);
1124
+ for (const [path, url] of result.map.entries()) {
1125
+ console.log(` ✅ ${basename(path)}`);
1126
+ console.log(` ${path}`);
1127
+ console.log(` → ${url}\n`);
1128
+ }
1129
+ for (const f of result.failures) {
1130
+ console.log(` ❌ ${basename(f.path)}: ${f.message}`);
1131
+ }
1132
+ console.log(` ${result.message}\n`);
1133
+ process.exit(result.ok ? 0 : 1);
1134
+ }
1135
+
1136
+ // ===== 站点设计(Design Studio)=====
1137
+
1138
+ /** 读取区块 JSON 文件(支持 {blocks} / {title,blocks} / [blocks] 三种形态) */
1139
+ function readBlocksFile(path) {
1140
+ if (!path || path === true) throw new Error('缺少 --file <json>');
1141
+ const abs = resolve(process.cwd(), String(path));
1142
+ if (!existsSync(abs)) throw new Error(`文件不存在: ${abs}`);
1143
+ let parsed;
1144
+ try {
1145
+ parsed = JSON.parse(readFileSync(abs, 'utf-8'));
1146
+ } catch (e) {
1147
+ throw new Error(`JSON 解析失败: ${abs}\n ${e.message}`);
1148
+ }
1149
+ if (Array.isArray(parsed)) return { title: undefined, blocks: parsed };
1150
+ if (parsed && Array.isArray(parsed.blocks)) {
1151
+ return { title: parsed.title, blocks: parsed.blocks, slug: parsed.slug };
1152
+ }
1153
+ throw new Error('JSON 必须是区块数组,或包含 blocks 数组的对象');
1154
+ }
1155
+
1156
+ /** 校验区块结构:type 必须在区块库内,id 唯一 */
1157
+ function validateBlocks(blocks) {
1158
+ const errors = [];
1159
+ const ids = new Set();
1160
+ blocks.forEach((b, i) => {
1161
+ if (!b || typeof b !== 'object') return errors.push(`[${i}] 不是对象`);
1162
+ if (!b.type) errors.push(`[${i}] 缺少 type`);
1163
+ else if (!BLOCK_TYPES[b.type]) errors.push(`[${i}] 未知区块类型 ${b.type}`);
1164
+ if (!b.props || typeof b.props !== 'object') errors.push(`[${i}] 缺少 props`);
1165
+ if (b.id) {
1166
+ if (ids.has(b.id)) errors.push(`[${i}] id 重复: ${b.id}`);
1167
+ ids.add(b.id);
1168
+ }
1169
+ });
1170
+ return errors;
1171
+ }
1172
+
1173
+ /** 拆出非选项参数(跳过 --key value 中的 value) */
1174
+ function splitPositional(args) {
1175
+ const positional = [];
1176
+ for (let i = 0; i < args.length; i++) {
1177
+ const a = args[i];
1178
+ if (a.startsWith('--')) {
1179
+ if (i + 1 < args.length && !args[i + 1].startsWith('--')) i++;
1180
+ continue;
1181
+ }
1182
+ positional.push(a);
1183
+ }
1184
+ return positional;
1185
+ }
1186
+
1187
+ async function handleSite(args) {
1188
+ const sub = args[0];
1189
+ const opts = parseArgs(args.slice(1));
1190
+ const positional = splitPositional(args.slice(1));
1191
+ const site = new SiteManager(getClient());
1192
+ const wantJson = opts.json === true || opts.json === 'true';
1193
+
1194
+ if (!site.getDaoId()) {
1195
+ console.error('❌ 需要 DDN_HUB_DAO_ID(站点 id 与 DAO id 相同)');
1196
+ process.exit(2);
1197
+ }
1198
+
1199
+ switch (sub) {
1200
+ case 'types': {
1201
+ console.log(`\n🧩 站点区块类型(schemaVersion=${SITE_SCHEMA_VERSION}):\n`);
1202
+ for (const [type, label] of Object.entries(BLOCK_TYPES)) {
1203
+ console.log(` ${type.padEnd(18)} ${label}`);
1204
+ }
1205
+ console.log();
1206
+ return;
1207
+ }
1208
+
1209
+ case 'pages': {
1210
+ const result = await site.listPages();
1211
+ if (!result.ok) return printError(result);
1212
+ if (wantJson) return console.log(JSON.stringify(result.items, null, 2));
1213
+ console.log(`\n📄 站点页面(${result.items.length} 个):\n`);
1214
+ for (const p of result.items) {
1215
+ const state = p.hasPublished ? '✅已发布' : '⚪未发布';
1216
+ console.log(` ${String(p.slug).padEnd(20)} ${state} ${p.title || ''}`);
1217
+ }
1218
+ console.log();
1219
+ return;
1220
+ }
1221
+
1222
+ case 'get':
1223
+ case 'export': {
1224
+ const slug = positional[0] || opts.slug;
1225
+ if (!slug) { console.error('❌ 用法: lims site get <slug>'); process.exit(2); }
1226
+ const result = await site.getPage(String(slug));
1227
+ if (!result.ok) return printError(result);
1228
+ if (sub === 'export' || wantJson) {
1229
+ const payload = { slug: String(slug), title: result.page?.title || null, blocks: result.blocks };
1230
+ const text = JSON.stringify(payload, null, 2);
1231
+ if (opts.out && opts.out !== true) {
1232
+ writeFileSync(resolve(process.cwd(), String(opts.out)), text + '\n');
1233
+ console.log(`✅ 已导出 ${result.blocks.length} 个区块 → ${opts.out}`);
1234
+ } else {
1235
+ console.log(text);
1236
+ }
1237
+ return;
1238
+ }
1239
+ console.log(`\n🧱 ${result.page?.title || slug}(${slug})· ${result.blocks.length} 个区块`);
1240
+ console.log(` 草稿: ${result.hasDraft ? '有' : '无'} / 已发布: ${result.hasPublished ? '有' : '无'}\n`);
1241
+ result.blocks.forEach((b, i) => {
1242
+ const head = b.props?.title || b.props?.text || b.props?.logoText || b.props?.copyright || '';
1243
+ console.log(` ${String(i + 1).padStart(2)}. ${String(b.type).padEnd(16)} ${String(head).replace(/<[^>]+>/g, '').slice(0, 60)}`);
1244
+ });
1245
+ console.log();
1246
+ return;
1247
+ }
1248
+
1249
+ case 'draft':
1250
+ case 'apply': {
1251
+ const fileBlocks = readBlocksFile(opts.file);
1252
+ const slug = positional[0] || opts.slug || fileBlocks.slug;
1253
+ if (!slug) { console.error('❌ 用法: lims site draft <slug> --file <json>'); process.exit(2); }
1254
+ const errors = validateBlocks(fileBlocks.blocks);
1255
+ if (errors.length) {
1256
+ console.error('❌ 区块校验失败:');
1257
+ for (const e of errors) console.error(` ${e}`);
1258
+ process.exit(2);
1259
+ }
1260
+ const current = await site.getPage(String(slug));
1261
+ const title = fileBlocks.title || current.page?.title;
1262
+ const saved = await site.saveDraft(String(slug), { title, blocks: fileBlocks.blocks });
1263
+ if (!saved.ok) return printError(saved);
1264
+ console.log(`✅ 草稿已保存:${slug} · ${fileBlocks.blocks.length} 个区块`);
1265
+ if (sub === 'apply' || opts.publish === true || opts.publish === 'true') {
1266
+ const published = await site.publishPage(String(slug));
1267
+ if (!published.ok) return printError(published);
1268
+ console.log(`✅ 页面已发布:${slug}`);
1269
+ if (opts.site === true || opts.site === 'true') {
1270
+ const sitePublished = await site.publishSite();
1271
+ if (!sitePublished.ok) return printError(sitePublished);
1272
+ console.log('✅ 整站已发布');
1273
+ }
1274
+ }
1275
+ return;
1276
+ }
1277
+
1278
+ case 'create': {
1279
+ const fileBlocks = readBlocksFile(opts.file);
1280
+ const slug = opts.slug && opts.slug !== true ? String(opts.slug) : fileBlocks.slug;
1281
+ const title = opts.title && opts.title !== true ? String(opts.title) : fileBlocks.title;
1282
+ if (!slug) { console.error('❌ 需要 --slug'); process.exit(2); }
1283
+ const errors = validateBlocks(fileBlocks.blocks || []);
1284
+ if (errors.length) {
1285
+ console.error('❌ 区块校验失败:');
1286
+ for (const e of errors) console.error(` ${e}`);
1287
+ process.exit(2);
1288
+ }
1289
+ const result = await site.createPage({ slug, title, blocks: fileBlocks.blocks || [] });
1290
+ if (!result.ok) return printError(result);
1291
+ console.log(`✅ 页面已创建:${slug}`);
1292
+ return;
1293
+ }
1294
+
1295
+ case 'publish': {
1296
+ if (opts.site === true || opts.site === 'true') {
1297
+ const result = await site.publishSite();
1298
+ if (!result.ok) return printError(result);
1299
+ console.log('✅ 整站已发布');
1300
+ return;
1301
+ }
1302
+ const slug = positional[0] || opts.slug;
1303
+ if (!slug) { console.error('❌ 用法: lims site publish <slug> | lims site publish --site'); process.exit(2); }
1304
+ const result = await site.publishPage(String(slug));
1305
+ if (!result.ok) return printError(result);
1306
+ console.log(`✅ 页面已发布:${slug}`);
1307
+ return;
1308
+ }
1309
+
1310
+ case 'unpublish': {
1311
+ const slug = positional[0] || opts.slug;
1312
+ if (!slug) { console.error('❌ 用法: lims site unpublish <slug>'); process.exit(2); }
1313
+ const result = await site.unpublishPage(String(slug));
1314
+ if (!result.ok) return printError(result);
1315
+ console.log(`✅ 页面已下线:${slug}`);
1316
+ return;
1317
+ }
1318
+
1319
+ case 'delete': {
1320
+ const slug = positional[0] || opts.slug;
1321
+ if (!slug) { console.error('❌ 用法: lims site delete <slug>'); process.exit(2); }
1322
+ const result = await site.deletePage(String(slug));
1323
+ if (!result.ok) return printError(result);
1324
+ console.log(`✅ 页面已删除:${slug}`);
1325
+ return;
1326
+ }
1327
+
1328
+ case 'settings': {
1329
+ if (opts.file) {
1330
+ const abs = resolve(process.cwd(), String(opts.file));
1331
+ let payload;
1332
+ try { payload = JSON.parse(readFileSync(abs, 'utf-8')); }
1333
+ catch (e) { console.error(`❌ 读取设置失败: ${e.message}`); process.exit(2); }
1334
+ const settings = payload.settings || payload;
1335
+ const result = await site.updateSettings(settings);
1336
+ if (!result.ok) return printError(result);
1337
+ console.log(`✅ 站点设置已更新:${JSON.stringify(settings)}`);
1338
+ return;
1339
+ }
1340
+ const result = await site.getSettings();
1341
+ if (!result.ok) return printError(result);
1342
+ console.log(JSON.stringify({ schemaVersion: result.schemaVersion, settings: result.settings }, null, 2));
1343
+ return;
1344
+ }
1345
+
1346
+ case 'public': {
1347
+ const slug = positional[0] || opts.slug || 'home';
1348
+ const result = await site.publicGetPage(String(slug), opts.domain && opts.domain !== true ? String(opts.domain) : undefined);
1349
+ if (!result.ok) return printError(result);
1350
+ if (wantJson) return console.log(JSON.stringify({ slug: result.slug, title: result.title, blocks: result.blocks }, null, 2));
1351
+ console.log(`\n🌐 公开端 ${result.slug}(${result.title || '-'})· ${result.blocks.length} 个区块`);
1352
+ result.blocks.forEach((b, i) => {
1353
+ const head = b.props?.title || b.props?.text || b.props?.logoText || b.props?.copyright || '';
1354
+ console.log(` ${String(i + 1).padStart(2)}. ${String(b.type).padEnd(16)} ${String(head).replace(/<[^>]+>/g, '').slice(0, 60)}`);
1355
+ });
1356
+ console.log();
1357
+ return;
1358
+ }
1359
+
1360
+ case 'check': {
1361
+ // 回读校验:公开端 + 管理端内容里是否还有禁用词
1362
+ const forbid = String(opts.forbid || opts.from || '觉知岛').split(',').filter(Boolean);
1363
+ const pages = opts.pages && opts.pages !== true && !String(opts.pages).includes('all')
1364
+ ? String(opts.pages).split(',')
1365
+ : (await site.listPages()).items.map((p) => p.slug);
1366
+ let bad = 0;
1367
+ const rows = [];
1368
+ for (const slug of pages) {
1369
+ const pub = await site.publicGetPage(String(slug));
1370
+ const admin = await site.getPage(String(slug));
1371
+ const hits = [];
1372
+ for (const src of [
1373
+ { label: 'public', blocks: pub.ok ? pub.blocks : [] },
1374
+ { label: 'admin', blocks: admin.ok ? admin.blocks : [] },
1375
+ ]) {
1376
+ for (const s of collectStrings(src.blocks)) {
1377
+ for (const word of forbid) {
1378
+ if (s.text.includes(word)) hits.push(`${src.label}${s.path} 命中「${word}」`);
1379
+ }
1380
+ }
1381
+ }
1382
+ if (hits.length) bad += 1;
1383
+ rows.push({ slug, ok: hits.length === 0, hits });
1384
+ }
1385
+ if (wantJson) return console.log(JSON.stringify(rows, null, 2));
1386
+ for (const r of rows) {
1387
+ console.log(` ${r.ok ? '✅' : '❌'} ${r.slug}${r.ok ? '' : '\n ' + r.hits.slice(0, 6).join('\n ')}`);
1388
+ }
1389
+ console.log(`\n${bad === 0 ? '✅ 全部页面无残留' : `❌ ${bad} 个页面仍有残留`}\n`);
1390
+ process.exit(bad === 0 ? 0 : 1);
1391
+ }
1392
+
1393
+ case 'set-block': {
1394
+ const type = opts.type && opts.type !== true ? String(opts.type) : null;
1395
+ if (!type) { console.error('❌ 用法: lims site set-block --type SiteHeaderNav --file props.json [--pages all] [--publish]'); process.exit(2); }
1396
+ const abs = resolve(process.cwd(), String(opts.file || ''));
1397
+ let payload;
1398
+ try { payload = JSON.parse(readFileSync(abs, 'utf-8')); }
1399
+ catch (e) { console.error(`❌ 读取 props 失败: ${e.message}`); process.exit(2); }
1400
+ const props = payload.props || payload;
1401
+ if (!props || typeof props !== 'object' || Array.isArray(props)) {
1402
+ console.error('❌ props 必须是对象');
1403
+ process.exit(2);
1404
+ }
1405
+ const pages = opts.pages && opts.pages !== true ? String(opts.pages).split(',') : ['all'];
1406
+ const publish = opts.publish === true || opts.publish === 'true';
1407
+ const result = await site.setBlockProps(type, props, { pages, publish });
1408
+ if (wantJson) console.log(JSON.stringify(result, null, 2));
1409
+ else {
1410
+ for (const r of result.report || []) {
1411
+ console.log(` ${r.ok ? '✅' : '❌'} ${r.slug}${r.skipped ? ' 跳过' : ''}${r.published ? '(已发布)' : ''}${r.message ? ` ${r.message}` : ''}`);
1412
+ }
1413
+ console.log(`\n${result.ok ? '✅' : '❌'} ${result.message}\n`);
1414
+ }
1415
+ process.exit(result.ok ? 0 : 1);
1416
+ break;
1417
+ }
1418
+
1419
+ case 'replace-brand': {
1420
+ const from = opts.from;
1421
+ const to = opts.to;
1422
+ if (!from || from === true || to === undefined || to === true) {
1423
+ console.error('❌ 用法: lims site replace-brand --from 觉知岛 --to ClawDao [--pages all|home,concept] [--publish]');
1424
+ process.exit(2);
1425
+ }
1426
+ const pages = opts.pages && opts.pages !== true ? String(opts.pages).split(',') : ['all'];
1427
+ const publish = opts.publish === true || opts.publish === 'true';
1428
+ const result = await site.replaceBrand({ replacements: [[String(from), String(to)]], pages, publish });
1429
+ if (wantJson) console.log(JSON.stringify(result, null, 2));
1430
+ else {
1431
+ for (const r of result.report || []) {
1432
+ console.log(` ${r.ok ? '✅' : '❌'} ${r.slug} ${r.hits ? `替换 ${r.hits} 处` : '无命中'}${r.published ? '(已发布)' : ''}${r.message ? ` ${r.message}` : ''}`);
1433
+ }
1434
+ console.log(`\n${result.ok ? '✅' : '❌'} ${result.message}\n`);
1435
+ }
1436
+ process.exit(result.ok ? 0 : 1);
1437
+ break;
1438
+ }
1439
+
1440
+ default:
1441
+ console.error(`未知 site 子命令: ${sub ?? '(空)'}
1442
+ `);
1443
+ console.error(`可用子命令:
1444
+ pages 列出页面
1445
+ get <slug> 查看页面区块(--json)
1446
+ export <slug> [--out f] 导出页面区块 JSON
1447
+ draft <slug> --file f 保存草稿
1448
+ apply <slug> --file f [--publish] [--site] 保存草稿并发布
1449
+ create --slug x --title y [--file f] 新建页面
1450
+ publish <slug> | --site 发布页面 / 整站
1451
+ unpublish <slug> 下线页面
1452
+ delete <slug> 删除页面
1453
+ settings [--file f] 查看 / 更新站点设置
1454
+ public <slug> 回读公开端内容
1455
+ check [--pages all] [--forbid 觉知岛] 禁用词回读校验
1456
+ replace-brand --from A --to B [--pages all] [--publish] 批量品牌替换
1457
+ set-block --type SiteHeaderNav --file f [--pages all] [--publish] 批量覆盖某类区块 props
1458
+ types 列出区块类型
1459
+ `);
1460
+ process.exit(1);
1461
+ }
1462
+ }
1463
+
1464
+ // ===== DAO 档案 =====
1465
+
1466
+ /** `--description @detail.md` 形式:@ 前缀从文件读取文本 */
1467
+ function resolveTextOption(value) {
1468
+ const v = String(value);
1469
+ if (!v.startsWith('@')) return v;
1470
+ const abs = resolve(process.cwd(), v.slice(1));
1471
+ if (!existsSync(abs)) throw new Error(`文件不存在: ${abs}`);
1472
+ return readFileSync(abs, 'utf-8');
1473
+ }
1474
+
1475
+ function readProfileFile(path) {
1476
+ const abs = resolve(process.cwd(), String(path));
1477
+ if (!existsSync(abs)) throw new Error(`文件不存在: ${abs}`);
1478
+ let parsed;
1479
+ try { parsed = JSON.parse(readFileSync(abs, 'utf-8')); }
1480
+ catch (e) { throw new Error(`JSON 解析失败: ${abs}\n ${e.message}`); }
1481
+ const source = parsed && typeof parsed === 'object' && parsed.profile ? parsed.profile : parsed;
1482
+ if (!source || typeof source !== 'object' || Array.isArray(source)) {
1483
+ throw new Error('档案 JSON 必须是对象,或包含 profile 对象');
1484
+ }
1485
+ return source;
1486
+ }
1487
+
1488
+ async function handleDao(args) {
1489
+ const sub = args[0] || 'profile';
1490
+ const opts = parseArgs(args.slice(1));
1491
+ const dao = new DaoManager(getClient());
1492
+ const wantJson = opts.json === true || opts.json === 'true';
1493
+
1494
+ if (sub !== 'profile') {
1495
+ console.error(`未知 dao 子命令: ${sub}\n`);
1496
+ console.error(`可用子命令:
1497
+ profile [--json [--full]] 读取档案
1498
+ profile --file f [--dry-run] 用文件更新档案
1499
+ profile --description "..." --detail @f.md 单独改某个字段
1500
+ profile --forbid 觉知,觉醒,龙虾岛 禁用词残留检查
1501
+ `);
1502
+ process.exit(1);
1503
+ }
1504
+
1505
+ if (!dao.getDaoId()) {
1506
+ console.error('❌ 需要 DDN_HUB_DAO_ID 才能读写 DAO 档案');
1507
+ process.exit(2);
1508
+ }
1509
+
1510
+ // 1) 纯读取(或禁用词检查)
1511
+ const writeFlags = ['file', 'name', 'description', 'detail', 'category', 'logoUrl', 'bannerUrl', 'motionDescription']
1512
+ .filter((k) => opts[k] !== undefined);
1513
+ if (writeFlags.length === 0) {
1514
+ if (opts.forbid !== undefined) {
1515
+ const words = String(opts.forbid === true ? '' : opts.forbid).split(',').map((s) => s.trim()).filter(Boolean);
1516
+ const result = await dao.scanForbidden(words);
1517
+ if (!result.ok) return printError(result);
1518
+ if (wantJson) console.log(JSON.stringify({ ok: true, hits: result.hits }, null, 2));
1519
+ else console.log(`\n${result.hits.length === 0 ? '✅ 档案无禁用词' : `❌ 命中 ${result.hits.length} 处`}`);
1520
+ if (!wantJson && result.hits.length) for (const h of result.hits) console.log(` ${h.field} 命中「${h.word}」`);
1521
+ if (!wantJson) console.log();
1522
+ process.exit(result.hits.length === 0 ? 0 : 1);
1523
+ }
1524
+
1525
+ const result = await dao.getProfile();
1526
+ if (!result.ok) return printError(result);
1527
+ if (wantJson) {
1528
+ // 默认只输出档案白名单字段;--full 才输出完整记录(敏感字段已打码)
1529
+ if (opts.full === true || opts.full === 'true') return console.log(JSON.stringify(result.profile, null, 2));
1530
+ const picked = {};
1531
+ for (const key of DAO_PROFILE_FIELDS) {
1532
+ if (result.profile?.[key] !== undefined) picked[key] = result.profile[key];
1533
+ }
1534
+ return console.log(JSON.stringify(picked, null, 2));
1535
+ }
1536
+ const p = result.profile || {};
1537
+ console.log(`\n🗂 DAO 档案 ${String(p.name || '')}(domain=${p.domain || '-'} / id=${p.id || dao.getDaoId()})\n`);
1538
+ for (const key of DAO_PROFILE_FIELDS) {
1539
+ const value = p[key];
1540
+ const label = DAO_PROFILE_FIELD_LABELS[key] || key;
1541
+ if (value === undefined || value === null || value === '') continue;
1542
+ let text = typeof value === 'string' ? value : JSON.stringify(value);
1543
+ if (text.length > 400) text = `${text.slice(0, 400)}…(${text.length} 字,--json 看全文)`;
1544
+ console.log(` ${label}(${key}):`);
1545
+ for (const line of text.split(/\r?\n/)) console.log(` ${line}`);
1546
+ console.log();
1547
+ }
1548
+ return;
1549
+ }
1550
+
1551
+ // 2) 写入
1552
+ let patch = {};
1553
+ if (opts.file !== undefined) {
1554
+ try { patch = { ...readProfileFile(opts.file) }; }
1555
+ catch (e) { console.error(`❌ 读取档案文件失败: ${e.message}`); process.exit(2); }
1556
+ }
1557
+ for (const key of ['name', 'description', 'detail', 'category', 'logoUrl', 'bannerUrl', 'motionDescription']) {
1558
+ if (opts[key] === undefined) continue;
1559
+ try { patch[key] = resolveTextOption(opts[key]); }
1560
+ catch (e) { console.error(`❌ --${key} 读取失败: ${e.message}`); process.exit(2); }
1561
+ }
1562
+
1563
+ const dryRun = opts.dryRun === true || opts['dry-run'] === true;
1564
+ const updated = await dao.updateProfile(patch, { dryRun });
1565
+ if (!updated.ok) return printError(updated);
1566
+
1567
+ if (updated.ignored?.length && !wantJson) {
1568
+ console.log(`\n⚠️ 已忽略非档案字段: ${updated.ignored.join(', ')}`);
1569
+ }
1570
+
1571
+ if (dryRun) {
1572
+ const current = await dao.getProfile();
1573
+ console.log(`\ndry-run:将写入 ${updated.keys.join(', ')}(未提交请求)\n`);
1574
+ for (const [key, value] of Object.entries(updated.patch)) {
1575
+ const before = current.ok ? current.profile?.[key] : undefined;
1576
+ const text = typeof value === 'string' ? value : JSON.stringify(value);
1577
+ console.log(` ${DAO_PROFILE_FIELD_LABELS[key] || key}(${key}):`);
1578
+ console.log(` 现在: ${JSON.stringify(before)?.slice(0, 120) ?? '(空)'}`);
1579
+ console.log(` 写入: ${JSON.stringify(text)?.slice(0, 120)}`);
1580
+ console.log();
1581
+ }
1582
+ return;
1583
+ }
1584
+
1585
+ // 3) 回读校验
1586
+ const verified = await dao.verify(updated.patch);
1587
+ if (wantJson) {
1588
+ console.log(JSON.stringify({ ok: verified.ok, keys: updated.keys, mismatched: verified.mismatched || [] }, null, 2));
1589
+ process.exit(verified.ok ? 0 : 1);
1590
+ }
1591
+ console.log(`\n${verified.ok ? '✅' : '❌'} 档案已更新并回读确认:${updated.keys.join(', ')}`);
1592
+ if (!verified.ok) {
1593
+ for (const m of verified.mismatched || []) {
1594
+ console.log(` ✗ ${m.key}: 期望 ${JSON.stringify(m.expected).slice(0, 80)} / 实际 ${JSON.stringify(m.actual).slice(0, 80)}`);
1595
+ }
1596
+ }
1597
+ console.log();
1598
+ process.exit(verified.ok ? 0 : 1);
1599
+ }
1600
+
1601
+ // ===== 工具函数 =====
1602
+
1603
+ function printListResult(result, title, formatter) {
1604
+ if (!result.ok) { printError(result); return; }
1605
+ const items = result.items || [];
1606
+ console.log(`\n📋 ${title}列表(${result.total || items.length} 项):\n`);
1607
+ if (items.length === 0) { console.log(' (空)\n'); return; }
1608
+ for (const item of items) console.log(formatter(item));
1609
+ if (result.totalPages && result.totalPages > 1) {
1610
+ console.log(`\n 📄 页 ${result.page || 1} / ${result.totalPages}(每页 ${result.pageSize || items.length})`);
1611
+ }
1612
+ console.log();
1613
+ }
1614
+
1615
+ function printDetailResult(result, title, formatter) {
1616
+ if (!result.ok) { printError(result); return; }
1617
+ console.log(`\n📦 ${title}详情:\n`);
1618
+ if (typeof result.data === 'object' && result.data !== null) {
1619
+ console.log(formatter(result.data));
1620
+ }
1621
+ console.log();
1622
+ }
1623
+
1624
+ function printError(result) {
1625
+ console.error(`\n❌ 操作失败:`);
1626
+ if (result.error) {
1627
+ console.error(` 类型: ${result.error.kind}`);
1628
+ }
1629
+ // ★ 修复:message 为 undefined 时给出有意义兜底,而不是打印 'undefined'
1630
+ const msg = result.message || result.error?.message || '(未提供错误消息)';
1631
+ console.error(` 消息: ${msg}`);
1632
+ if (result.statusCode) console.error(` HTTP 状态码: ${result.statusCode}`);
1633
+ console.error();
1634
+ }
1635
+
1636
+ main().catch((err) => {
1637
+ console.error('❌ 运行错误:', err.message);
1638
+ process.exit(1);
1639
+ });