@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,432 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 采集亿检链(当前 DAO)**全部文章**并做分层统计,产出大屏用数据。
4
+ *
5
+ * 为什么不用单一列表接口作为口径(实测 2026-11-24):
6
+ * - GET /api/v1/posts?limit=100 → total=25,且漏掉 id=25/26/29/32 等已发布文章
7
+ * - GET /api/v1/posts?status=published → total=25(返回集里混入 status=archived)
8
+ * - GET /api/v1/posts?status=draft → total=21(返回集里混入 status=published)
9
+ * - GET /api/v1/posts?status=archived → total=0(明明有 archived 数据)
10
+ * ⇒ 列表接口的 status 过滤口径不可信、且列表本身有缺漏。
11
+ * 因此本脚本双轨采集并交叉核对:
12
+ * 轨道 A:列表接口(全量分页 + 按 postType 分桶 + 按 status 分桶),只用于「接口 total 对照」
13
+ * 轨道 B:逐 id GET /api/v1/posts/:id(1..maxId 扫描)→ 全量可读文章(主口径)
14
+ *
15
+ * 用法:
16
+ * node scripts/collect-site-articles.mjs # 默认 --max-id 400 --concurrency 6
17
+ * node scripts/collect-site-articles.mjs --max-id 300
18
+ *
19
+ * 产物:
20
+ * outputs/site-articles-all.json 全量文章(原始字段 + 字数/摘要 + 本地化时间)
21
+ * outputs/site-articles-stats.json 分层统计(类别/平台分类/状态×过审/月度/榜单)
22
+ */
23
+
24
+ import { mkdirSync, writeFileSync } from 'node:fs';
25
+ import { resolve, dirname } from 'node:path';
26
+ import { fileURLToPath } from 'node:url';
27
+ import { POST_TYPE_LABELS } from '../lib/articles.mjs';
28
+ import { LimsClient } from '../lib/client.mjs';
29
+
30
+ const __dirname = dirname(fileURLToPath(import.meta.url));
31
+ const ROOT = resolve(__dirname, '..');
32
+
33
+ const args = process.argv.slice(2);
34
+ const getOpt = (name, def) => {
35
+ const i = args.indexOf(`--${name}`);
36
+ return i >= 0 && args[i + 1] && !args[i + 1].startsWith('--') ? args[i + 1] : def;
37
+ };
38
+ const MAX_ID = parseInt(getOpt('max-id', '400'), 10);
39
+ const CONCURRENCY = Math.max(1, parseInt(getOpt('concurrency', '6'), 10));
40
+
41
+ const client = new LimsClient();
42
+ const cfg = client.getConfig();
43
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
44
+
45
+ // ===== 时区:UTC → +08:00 =====
46
+ const TZ_OFFSET_MIN = 8 * 60;
47
+ const toLocal = (iso) => {
48
+ if (!iso) return null;
49
+ const d = new Date(iso);
50
+ if (Number.isNaN(d.getTime())) return null;
51
+ const t = new Date(d.getTime() + TZ_OFFSET_MIN * 60_000);
52
+ const p = (n) => String(n).padStart(2, '0');
53
+ return `${t.getUTCFullYear()}-${p(t.getUTCMonth() + 1)}-${p(t.getUTCDate())} ${p(t.getUTCHours())}:${p(t.getUTCMinutes())}`;
54
+ };
55
+ const monthKeyLocal = (iso) => {
56
+ const s = toLocal(iso);
57
+ return s ? s.slice(0, 7) : null;
58
+ };
59
+
60
+ // ===== 轨道 A:列表接口(可回溯的接口 total)=====
61
+ const listSweep = async (params, label, maxPages = 30) => {
62
+ const collected = [];
63
+ let total = null;
64
+ let pages = 0;
65
+ let pagesUsed = 0;
66
+ for (let page = 1; page <= maxPages; page++) {
67
+ let r = null;
68
+ for (let a = 0; a < 4; a++) {
69
+ r = await client.listPosts({ ...params, page, limit: 100, includeAttributes: false });
70
+ if (r.ok) break;
71
+ await sleep(200 * (a + 1));
72
+ }
73
+ if (!r?.ok) return { label, params, ok: false, message: r?.message, items: collected, total, pagesUsed };
74
+ const d = r.data || {};
75
+ const items = d.items || d.list || [];
76
+ const pg = d.pagination || {};
77
+ total = pg.total ?? d.total ?? items.length;
78
+ collected.push(...items);
79
+ pagesUsed = page;
80
+ if (!pg.hasNext || items.length === 0) break;
81
+ }
82
+ pages = pagesUsed;
83
+ const uniq = new Map(collected.map((i) => [i.id, i]));
84
+ return {
85
+ label,
86
+ params,
87
+ ok: true,
88
+ total,
89
+ pagesUsed: pages,
90
+ rowsReturned: collected.length,
91
+ uniqueIds: uniq.size,
92
+ ids: [...uniq.keys()].sort((a, b) => a - b),
93
+ items: [...uniq.values()],
94
+ };
95
+ };
96
+
97
+ const discoveredTypes = new Set(['news', 'article', 'idea', 'help', 'collected', 'proposal', 'ledger']);
98
+ const sweepNoFilter = await listSweep({}, 'all(no filter)');
99
+ const sweepByType = [];
100
+ for (const t of [...discoveredTypes]) {
101
+ sweepByType.push(await listSweep({ postType: t }, `postType=${t}`));
102
+ }
103
+ const sweepByStatus = [];
104
+ for (const s of ['published', 'draft', 'archived']) {
105
+ sweepByStatus.push(await listSweep({ status: s }, `status=${s}`));
106
+ }
107
+
108
+ // ===== 轨道 B:逐 id 扫描(主口径:ground truth)=====
109
+ const detailMap = new Map();
110
+ const denied = [];
111
+ const missing = [];
112
+ for (let start = 1; start <= MAX_ID; start += CONCURRENCY) {
113
+ const batch = [];
114
+ for (let k = start; k < start + CONCURRENCY && k <= MAX_ID; k++) batch.push(k);
115
+ const results = await Promise.all(batch.map(async (pid) => {
116
+ let last = null;
117
+ for (let a = 0; a < 4; a++) {
118
+ const r = await client.getPost(pid);
119
+ if (r.ok) return { pid, r };
120
+ last = r;
121
+ if (r.statusCode === 404 || /内容不存在/.test(r.message || '')) return { pid, r };
122
+ await sleep(180 * (a + 1) + Math.floor(Math.random() * 120));
123
+ }
124
+ return { pid, r: last };
125
+ }));
126
+ for (const { pid, r } of results) {
127
+ if (r?.ok && r.data) detailMap.set(r.data.id ?? pid, r.data);
128
+ else if (r?.statusCode === 403 || /无权访问/.test(r?.message || '')) denied.push({ id: pid, statusCode: r.statusCode, message: r.message });
129
+ else if (r?.statusCode === 404 || /内容不存在/.test(r?.message || '')) missing.push(pid);
130
+ else denied.push({ id: pid, statusCode: r?.statusCode ?? null, message: r?.message || 'unknown' });
131
+ }
132
+ process.stderr.write(`\r id 扫描 ${Math.min(start + CONCURRENCY - 1, MAX_ID)}/${MAX_ID} 命中 ${detailMap.size} 无权限 ${denied.length} `);
133
+ }
134
+ process.stderr.write('\n');
135
+
136
+ // ===== 分类字典(平台真实分类树,带重试;该接口偶发失败返回空)=====
137
+ let catRes = null;
138
+ for (let a = 0; a < 5; a++) {
139
+ catRes = await client.request({ method: 'GET', path: '/api/v1/cms/categories', query: { page: 1, limit: 200 } });
140
+ if (catRes.ok && (catRes.data?.items || []).length) break;
141
+ await sleep(400 * (a + 1));
142
+ }
143
+ const catItems = catRes?.ok ? (catRes.data?.items || catRes.data || []) : [];
144
+ if (!catItems.length) console.error('⚠️ 分类字典 /api/v1/cms/categories 拉取失败,按分类名的统计将退化为「未分类」');
145
+ const catById = new Map(catItems.map((c) => [c.id, c]));
146
+ const categoryDict = catItems
147
+ .map((c) => ({
148
+ id: c.id,
149
+ name: c.name,
150
+ slug: c.slug ?? null,
151
+ parentId: c.parentId ?? null,
152
+ level: c.level ?? 0,
153
+ status: c.status !== false,
154
+ isSystem: Boolean(c.isSystem),
155
+ color: c.color ?? null,
156
+ path: c.parentId && catById.get(c.parentId) ? `${catById.get(c.parentId).name} / ${c.name}` : c.name,
157
+ }))
158
+ .sort((a, b) => a.id - b.id);
159
+
160
+ // ===== 合并全量(主口径 = 逐 id 扫描 ∪ 列表接口,优先用详情字段)=====
161
+ const allIds = new Set([...detailMap.keys()]);
162
+ for (const sw of [sweepNoFilter, ...sweepByType, ...sweepByStatus]) {
163
+ for (const it of sw.items || []) allIds.add(it.id);
164
+ }
165
+ const listById = new Map();
166
+ for (const sw of [sweepNoFilter, ...sweepByType, ...sweepByStatus]) {
167
+ for (const it of sw.items || []) if (!listById.has(it.id)) listById.set(it.id, it);
168
+ }
169
+
170
+ const countWords = (text) => {
171
+ if (typeof text !== 'string' || !text) return 0;
172
+ const cjk = (text.match(/[\u3400-\u4dbf\u4e00-\u9fff\u3040-\u30ff]/g) || []).length;
173
+ const latin = (text.match(/[A-Za-z0-9]+(?:['-][A-Za-z0-9]+)*/g) || []).length;
174
+ return cjk + latin;
175
+ };
176
+
177
+ /** 标签归一:tagList 可能是 [{id,name,color}],tags 可能是 string[] 或逗号分隔字符串 */
178
+ const normTags = (p) => {
179
+ const toNames = (raw) => {
180
+ if (Array.isArray(raw)) {
181
+ return raw
182
+ .map((t) => (typeof t === 'string' ? t : t?.name ?? t?.tagName ?? t?.title ?? ''))
183
+ .map((s) => String(s).trim())
184
+ .filter(Boolean);
185
+ }
186
+ if (typeof raw === 'string' && raw.trim()) return raw.split(/[,,]+/).map((s) => s.trim()).filter(Boolean);
187
+ return [];
188
+ };
189
+ return [...new Set([...toNames(p.tagList), ...toNames(p.tags)])];
190
+ };
191
+
192
+ /** 作者归一:接口里存在 "moon姐\\n moon姐" 这类重复换行值 */
193
+ const normAuthor = (raw) => {
194
+ if (typeof raw !== 'string') return raw ?? null;
195
+ const cleaned = raw.replace(/\s+/g, ' ').trim();
196
+ if (!cleaned) return null;
197
+ const parts = cleaned.split(' ');
198
+ if (parts.length > 1 && parts.every((x) => x === parts[0])) return parts[0];
199
+ return cleaned;
200
+ };
201
+
202
+ /** postType → 平台分类字典里的真实名字(/api/v1/cms/categories 的 slug 命中),否则退回内置标签 */
203
+ const buildTypeLabels = (dict) => {
204
+ const bySlug = new Map(dict.filter((c) => c.slug).map((c) => [c.slug, c.name]));
205
+ return (postType) => {
206
+ if (!postType) return '未分类';
207
+ return bySlug.get(postType) || POST_TYPE_LABELS[postType] || postType;
208
+ };
209
+ };
210
+
211
+ const typeLabel = buildTypeLabels(categoryDict);
212
+ const items = [...allIds]
213
+ .map((id) => {
214
+ const p = detailMap.get(id) || listById.get(id);
215
+ const content = p.contentMarkdown || p.content || '';
216
+ const cat = p.categoryId != null ? catById.get(p.categoryId) : null;
217
+ const catMeta = categoryDict.find((c) => c.id === cat?.id) || null;
218
+ const createdAt = p.createdAt || p.created_at || null;
219
+ const publishedAt = p.publishedAt || null;
220
+ return {
221
+ id: p.id ?? id,
222
+ slug: p.slug ?? null,
223
+ title: p.title ?? '',
224
+ postType: p.postType ?? null,
225
+ postTypeLabel: typeLabel(p.postType),
226
+ status: p.status ?? null,
227
+ lifecycleState: p.lifecycleState ?? null,
228
+ complianceStatus: p.complianceStatus ?? null,
229
+ visibilityStatus: p.visibilityStatus ?? null,
230
+ categoryId: p.categoryId ?? null,
231
+ categoryName: catMeta?.name ?? cat?.name ?? null,
232
+ categoryPath: catMeta?.path ?? cat?.name ?? null,
233
+ extraCategory: p.extraData?.category ?? null,
234
+ tagList: normTags(p),
235
+ author: normAuthor(p.author),
236
+ userId: p.userId ?? null,
237
+ createdAt,
238
+ createdAtLocal: toLocal(createdAt),
239
+ publishedAt,
240
+ publishedAtLocal: toLocal(publishedAt),
241
+ updatedAt: p.updatedAt || p.updated_at || null,
242
+ views: p.views ?? null,
243
+ likes: p.likes ?? null,
244
+ commentsCount: p.commentsCount ?? null,
245
+ wordCount: countWords(content),
246
+ contentLength: typeof content === 'string' ? content.length : 0,
247
+ excerpt: (p.description || (typeof content === 'string' ? content.replace(/[#>*`!\[\]()\-\n\r]/g, ' ').replace(/\s+/g, ' ').trim() : '')).slice(0, 120),
248
+ hasCover: Boolean(p.coverImage),
249
+ source: detailMap.has(id) ? 'detail' : 'list',
250
+ };
251
+ })
252
+ .sort((a, b) => new Date(b.createdAt || 0) - new Date(a.createdAt || 0) || b.id - a.id);
253
+
254
+ // ===== 统计 =====
255
+ const total = items.length;
256
+ const pct = (n) => (total ? +((n / total) * 100).toFixed(1) : 0);
257
+ const countBy = (fn) => {
258
+ const m = new Map();
259
+ for (const it of items) {
260
+ const k = fn(it);
261
+ m.set(k, (m.get(k) || 0) + 1);
262
+ }
263
+ return [...m.entries()].sort((a, b) => b[1] - a[1] || String(a[0]).localeCompare(String(b[0])));
264
+ };
265
+
266
+ const now = new Date();
267
+ const nowLocal = toLocal(now.toISOString());
268
+
269
+ // 月度趋势:最近 12 个月(含当月),按 +08:00 月份
270
+ const months = [];
271
+ for (let i = 11; i >= 0; i--) {
272
+ const d = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - i, 1));
273
+ months.push(`${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, '0')}`);
274
+ }
275
+ const monthSeries = (field) => {
276
+ const m = new Map(months.map((k) => [k, 0]));
277
+ for (const it of items) {
278
+ const key = monthKeyLocal(it[field]);
279
+ if (key && m.has(key)) m.set(key, m.get(key) + 1);
280
+ }
281
+ return months.map((k) => ({ month: k, count: m.get(k) }));
282
+ };
283
+
284
+ const tagCount = new Map();
285
+ for (const it of items) for (const t of it.tagList) tagCount.set(t, (tagCount.get(t) || 0) + 1);
286
+
287
+ const matrix = new Map(); // `${status}|${compliance}` → count
288
+ const statusSet = new Set();
289
+ const compSet = new Set();
290
+ for (const it of items) {
291
+ const s = it.status || '(null)';
292
+ const c = it.complianceStatus || '(null)';
293
+ statusSet.add(s);
294
+ compSet.add(c);
295
+ const k = `${s}|${c}`;
296
+ matrix.set(k, (matrix.get(k) || 0) + 1);
297
+ }
298
+
299
+ const lenBuckets = [
300
+ { key: '0 字(无正文)', test: (n) => n === 0, count: 0 },
301
+ { key: '1–499 字', test: (n) => n > 0 && n < 500, count: 0 },
302
+ { key: '500–999 字', test: (n) => n >= 500 && n < 1000, count: 0 },
303
+ { key: '1000–1999 字', test: (n) => n >= 1000 && n < 2000, count: 0 },
304
+ { key: '2000–4999 字', test: (n) => n >= 2000 && n < 5000, count: 0 },
305
+ { key: '≥5000 字', test: (n) => n >= 5000, count: 0 },
306
+ ];
307
+ for (const it of items) {
308
+ const b = lenBuckets.find((x) => x.test(it.wordCount));
309
+ if (b) b.count += 1;
310
+ }
311
+
312
+ const trendPublished = monthSeries('publishedAt');
313
+ const trendCreated = monthSeries('createdAt');
314
+ const last30 = items.filter((it) => it.createdAt && now - new Date(it.createdAt) <= 30 * 86400_000).length;
315
+
316
+ const stats = {
317
+ generatedAt: now.toISOString(),
318
+ generatedAtLocal: nowLocal,
319
+ timezone: 'Asia/Shanghai (UTC+08:00)',
320
+ source: {
321
+ baseUrl: cfg.baseUrl,
322
+ daoId: cfg.daoId,
323
+ tokenMasked: cfg.authToken ? `***${String(cfg.authToken).slice(-4)}` : null,
324
+ dataApi: 'GET /api/v1/posts/:id(主口径)+ GET /api/v1/posts(列表对照)',
325
+ categoryApi: 'GET /api/v1/cms/categories',
326
+ idScan: { range: `1..${MAX_ID}`, concurrency: CONCURRENCY, hits: detailMap.size, denied, missingIds: missing.length },
327
+ listSweeps: [sweepNoFilter, ...sweepByType, ...sweepByStatus].map((s) => ({
328
+ label: s.label,
329
+ params: s.params,
330
+ ok: s.ok,
331
+ message: s.ok ? undefined : s.message,
332
+ total: s.total,
333
+ pagesUsed: s.pagesUsed,
334
+ rowsReturned: s.rowsReturned,
335
+ uniqueIds: s.uniqueIds,
336
+ })),
337
+ crossCheck: {
338
+ mainTotal: total,
339
+ listNoFilterTotal: sweepNoFilter.total,
340
+ postTypeUnionTotal: sweepByType.reduce((n, s) => n + (s.ok ? s.uniqueIds : 0), 0),
341
+ postTypeUnionIds: new Set(sweepByType.flatMap((s) => (s.ok ? s.ids : []))).size,
342
+ statusUnionIds: new Set(sweepByStatus.flatMap((s) => (s.ok ? s.ids : []))).size,
343
+ listAllUnionIds: new Set([sweepNoFilter, ...sweepByType, ...sweepByStatus].flatMap((s) => (s.ok ? s.ids : []))).size,
344
+ detailScanIds: detailMap.size,
345
+ idsOnlyInDetailScan: [...detailMap.keys()].filter((id) => !listById.has(id)).sort((a, b) => a - b),
346
+ idsOnlyInList: [...listById.keys()].filter((id) => !detailMap.has(id)).sort((a, b) => a - b),
347
+ deniedCount: denied.length,
348
+ },
349
+ caveats: [
350
+ '列表接口 status 过滤口径不可信:?status=published 返回集含 archived,?status=draft 返回集含 published,?status=archived 返回 0;且列表有缺漏(漏掉 4 条已发布文章)。',
351
+ '因此主口径采用「逐 id 扫描 + 列表并集」,total 以主口径为准,列表接口 total 仅作对照。',
352
+ '被接口以 403「无权访问该内容」拒绝的条目不计入分布,单独列在 source.idScan.denied。',
353
+ ],
354
+ },
355
+ total,
356
+ byPostType: countBy((it) => it.postType || '(null)').map(([k, v]) => ({
357
+ key: k,
358
+ label: k === '(null)' ? '未分类(历史遗留)' : typeLabel(k),
359
+ count: v,
360
+ pct: pct(v),
361
+ })),
362
+ categoryDictFetched: categoryDict.length > 0,
363
+ byStatus: countBy((it) => it.status || '(null)').map(([k, v]) => ({ key: k, count: v, pct: pct(v) })),
364
+ byCompliance: countBy((it) => it.complianceStatus || '(null)').map(([k, v]) => ({ key: k, count: v, pct: pct(v) })),
365
+ byVisibility: countBy((it) => it.visibilityStatus || '(null)').map(([k, v]) => ({ key: k, count: v, pct: pct(v) })),
366
+ statusComplianceMatrix: [...statusSet].sort().map((s) => ({
367
+ status: s,
368
+ cells: [...compSet].sort().map((c) => ({ compliance: c, count: matrix.get(`${s}|${c}`) || 0 })),
369
+ total: items.filter((it) => (it.status || '(null)') === s).length,
370
+ })),
371
+ complianceKeys: [...compSet].sort(),
372
+ byCategoryName: countBy((it) => it.categoryName || '(未分类)').map(([k, v]) => ({ key: k, count: v, pct: pct(v) })),
373
+ byCategoryPath: countBy((it) => it.categoryPath || '(未分类)').map(([k, v]) => ({ key: k, count: v, pct: pct(v) })),
374
+ byExtraCategory: countBy((it) => it.extraCategory || '(未填 category)').map(([k, v]) => ({ key: k, count: v, pct: pct(v) })),
375
+ categoryDict,
376
+ trendPublished,
377
+ trendCreated,
378
+ trendRange: { from: months[0], to: months[months.length - 1], timezone: 'UTC+08:00' },
379
+ tagTop: [...tagCount.entries()].sort((a, b) => b[1] - a[1]).slice(0, 15).map(([tag, count]) => ({ tag, count })),
380
+ byAuthor: countBy((it) => it.author || '(未知)').map(([k, v]) => ({ key: k, count: v, pct: pct(v) })),
381
+ lengthBuckets: lenBuckets.map((b) => ({ key: b.key, count: b.count, pct: pct(b.count) })),
382
+ kpi: {
383
+ total,
384
+ published: items.filter((it) => it.status === 'published').length,
385
+ draft: items.filter((it) => it.status === 'draft').length,
386
+ archived: items.filter((it) => it.status === 'archived').length,
387
+ pendingReview: items.filter((it) => (it.complianceStatus || 'null') !== 'approved').length,
388
+ approved: items.filter((it) => it.complianceStatus === 'approved').length,
389
+ last30Days: last30,
390
+ categoriesUsed: new Set(items.map((it) => it.categoryName).filter(Boolean)).size,
391
+ postTypesUsed: new Set(items.map((it) => it.postType).filter(Boolean)).size,
392
+ tagsUsed: tagCount.size,
393
+ totalWords: items.reduce((n, it) => n + it.wordCount, 0),
394
+ avgWords: total ? Math.round(items.reduce((n, it) => n + it.wordCount, 0) / total) : 0,
395
+ totalViews: items.reduce((n, it) => n + (it.views || 0), 0),
396
+ },
397
+ latest: items
398
+ .filter((it) => it.publishedAt)
399
+ .sort((a, b) => new Date(b.publishedAt) - new Date(a.publishedAt))
400
+ .slice(0, 12)
401
+ .map((it) => ({ id: it.id, title: it.title, postType: it.postTypeLabel, category: it.categoryName, publishedAt: it.publishedAt, publishedAtLocal: it.publishedAtLocal, wordCount: it.wordCount, views: it.views })),
402
+ };
403
+
404
+ // ===== 落盘 =====
405
+ const outDir = resolve(ROOT, 'outputs');
406
+ mkdirSync(outDir, { recursive: true });
407
+ const allPath = resolve(outDir, 'site-articles-all.json');
408
+ const statsPath = resolve(outDir, 'site-articles-stats.json');
409
+ writeFileSync(allPath, JSON.stringify({
410
+ generatedAt: stats.generatedAt,
411
+ generatedAtLocal: nowLocal,
412
+ timezone: stats.timezone,
413
+ daoId: cfg.daoId,
414
+ baseUrl: cfg.baseUrl,
415
+ total,
416
+ note: '主口径=逐 id 扫描 ∪ 列表接口,按 id 去重;正文只保留字数/长度/摘要,避免文件过大',
417
+ items,
418
+ }, null, 2));
419
+ writeFileSync(statsPath, JSON.stringify(stats, null, 2));
420
+
421
+ console.log(JSON.stringify({
422
+ allPath,
423
+ statsPath,
424
+ total,
425
+ kpi: stats.kpi,
426
+ byPostType: stats.byPostType,
427
+ byStatus: stats.byStatus,
428
+ byCompliance: stats.byCompliance,
429
+ crossCheck: stats.source.crossCheck,
430
+ trendPublishedHead: stats.trendPublished.slice(0, 2),
431
+ trendPublishedTail: stats.trendPublished.slice(-2),
432
+ }, null, 2));
@@ -0,0 +1,107 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * scripts/export-ddn-env.mjs — 从 ClawDao 桌面应用同步亿检链凭证到 .env
4
+ *
5
+ * 数据源:~/Library/Application Support/net.ddn.clawdao/store.bin
6
+ * auth_state.ddnHub.{ authToken, platformToken, baseUrl, daoId, daoName, username, roleLabel }
7
+ *
8
+ * 安全说明:
9
+ * - 不向终端打印 token 明文(只显示掩码如 "jwt_***3ab")
10
+ * - 生成的 .env 权限设为 600(仅本用户可读写)
11
+ * - 配合 .gitignore 排除 .env,防止误提交
12
+ *
13
+ * 用法:node scripts/export-ddn-env.mjs [--force]
14
+ */
15
+
16
+ import { readFileSync, writeFileSync, existsSync, chmodSync } from 'fs';
17
+ import { resolve } from 'path';
18
+ import { homedir } from 'os';
19
+
20
+ const ENV_PATH = resolve(process.cwd(), '.env');
21
+ const STORE_CANDIDATES = [
22
+ resolve(homedir(), 'Library/Application Support/net.ddn.clawdao/store.bin'),
23
+ resolve(homedir(), 'Library/Application Support/net.ddn.daoclaw/store.json'),
24
+ ];
25
+
26
+ function findStore() {
27
+ for (const p of STORE_CANDIDATES) {
28
+ if (existsSync(p)) return p;
29
+ }
30
+ return null;
31
+ }
32
+
33
+ function mask(value) {
34
+ if (!value) return '(空)';
35
+ if (value.length <= 8) return '***';
36
+ return value.slice(0, 4) + '***' + value.slice(-3);
37
+ }
38
+
39
+ function load() {
40
+ const storePath = findStore();
41
+ if (!storePath) throw new Error('未找到 ClawDao store 文件');
42
+ let raw;
43
+ try {
44
+ raw = readFileSync(storePath, 'utf-8');
45
+ } catch (e) {
46
+ throw new Error(`读取 ${storePath} 失败: ${e.message}`);
47
+ }
48
+ // store.json 直接是 JSON;store.bin 是 JSON 或带前缀文本
49
+ let json = raw;
50
+ try { json = JSON.parse(raw); } catch {
51
+ const start = raw.indexOf('{');
52
+ if (start < 0) throw new Error('store 文件不是 JSON 格式');
53
+ json = JSON.parse(raw.slice(start));
54
+ }
55
+ const hub = json?.auth_state?.ddnHub;
56
+ if (!hub?.authToken) throw new Error('store 中没有 auth_state.ddnHub.authToken(ClawDao 可能未登录亿检链)');
57
+ return {
58
+ storePath,
59
+ authToken: String(hub.authToken),
60
+ // ★ platformToken 用于 platform/versions 等平台级端点
61
+ // 仅 platform admin 账号的 store.bin 才有此字段
62
+ platformToken: hub.platformToken ? String(hub.platformToken) : '',
63
+ baseUrl: String(hub.baseUrl || 'https://limschain.com'),
64
+ daoId: String(hub.daoId || ''),
65
+ daoName: String(hub.daoName || ''),
66
+ username: String(hub.username || ''),
67
+ roleLabel: String(hub.roleLabel || ''),
68
+ };
69
+ }
70
+
71
+ const force = process.argv.includes('--force');
72
+ if (!force && existsSync(ENV_PATH)) {
73
+ console.log('⚠️ .env 已存在,跳过(如需覆盖请加 --force)');
74
+ process.exit(0);
75
+ }
76
+
77
+ try {
78
+ const info = load();
79
+ const lines = [
80
+ '# 由 scripts/export-ddn-env.mjs 自动生成(' + new Date().toISOString() + ')',
81
+ `DDN_HUB_BASE_URL=${info.baseUrl}`,
82
+ `DDN_HUB_AUTH_TOKEN=${info.authToken}`,
83
+ info.daoId ? `DDN_HUB_DAO_ID=${info.daoId}` : '# DDN_HUB_DAO_ID=(store 中无 daoId,可手动补充)',
84
+ ];
85
+ // ★ platform token(可选)— 仅 platform admin 登录时才会有
86
+ if (info.platformToken) {
87
+ lines.push(`DDN_HUB_PLATFORM_TOKEN=${info.platformToken}`);
88
+ } else {
89
+ lines.push('# DDN_HUB_PLATFORM_TOKEN=(store 中无 platformToken,当前账号可能不是 platform admin)');
90
+ }
91
+ writeFileSync(ENV_PATH, lines.join('\n') + '\n', { mode: 0o600 });
92
+ try { chmodSync(ENV_PATH, 0o600); } catch { /* best-effort */ }
93
+ console.log('✅ 已写入 .env(权限 600)');
94
+ console.log(` 来源: ${info.storePath}`);
95
+ console.log(` baseUrl: ${info.baseUrl}`);
96
+ console.log(` authToken: ${mask(info.authToken)}(已掩码,未明文输出)`);
97
+ console.log(` daoId: ${info.daoId || '(空)'}(${info.daoName || ''})`);
98
+ console.log(` 登录账号: ${info.username || '(空)'}(${info.roleLabel || '无角色'})`);
99
+ if (info.platformToken) {
100
+ console.log(` platformToken: ${mask(info.platformToken)}(已掩码,platform admin)`);
101
+ } else {
102
+ console.log(` platformToken: ❌ 无(store 中无此字段)`);
103
+ }
104
+ } catch (e) {
105
+ console.error(`❌ ${e.message}`);
106
+ process.exit(1);
107
+ }