Repository navigation
Expand file tree
/
Copy pathaudit.js
More file actions
1265 lines (1175 loc) · 66.4 KB
/
Copy pathaudit.js
File metadata and controls
1265 lines (1175 loc) · 66.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* 开源项目质检引擎 —— 九维度自动扫描。
*
* 评分标准不是这里发明的,照搬 project-maturity-audit skill(~/dev/github/agent/):
* 九个维度、0-10 分、"陌生人会不会 10 秒内 star 这个项目"的视角。两边必须同一套标准,
* 否则面板给 7 分、skill 给 4 分,人就不知道该信谁了。
*
* ## 这里只做客观项,主观项留给 skill
*
* 「README 首屏 10 秒能不能讲清楚」这种要模型读了才知道,API 判不了。
* 所以分工是:本引擎做**广度扫描 + 趋势追踪**(一键扫 20 个仓库、可定时、能看
* 上次 62 分这次 78 分),skill 做**深度诊断 + 修复**(读 README、给整改方案)。
* 每个维度的 `manual` 字段标出哪些项没法自动判,面板上提示"这几项要跑 skill"。
*
* ## 每条结论都带证据
*
* skill 的铁律是「每个 claim 要有命令输出/文件/状态码支撑,不给含糊的表扬或指责」。
* 这里同样:evidence 和 gaps 里写的是实际查到的东西(topics 几个、CI 什么状态、
* 哪个文件缺),不写"文档有待完善"这种没法行动的话。
*/
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime.js'
import 'dayjs/locale/zh-cn.js'
dayjs.extend(relativeTime)
dayjs.locale('zh-cn')
import { SCORE_HINT, SCORE_LABELS } from './score-labels.js'
const GH = 'https://api.github.com'
// tags API 一次取多少个。GitHub 不保证按时间或版本排序 —— golang/go 取前 10 个
// 拿到的全是 2012 年的 weekly.*,于是被判「没有版本 tag」。取样开大能救小项目,
// 但对上千个 tag 的仓库依然可能全都取不到版本号,所以还要配合「取样是否已满」判定。
const TAG_SAMPLE = 100
/** 评分基准,照搬 SKILL.md「评分基准」一节 */
export const SCORE_BANDS = [
{ min: 9, label: SCORE_LABELS[0], hint: SCORE_HINT },
{ min: 6, label: SCORE_LABELS[1], hint: SCORE_HINT },
{ min: 3, label: SCORE_LABELS[2], hint: SCORE_HINT },
{ min: 0, label: SCORE_LABELS[3], hint: SCORE_HINT },
]
export const bandOf = (score) => SCORE_BANDS.find((b) => score >= b.min) || SCORE_BANDS[SCORE_BANDS.length - 1]
export async function gh(path, token, { raw = false } = {}) {
const url = `${GH}${path}`
/*
* 每次尝试都要独立的新 options:AbortSignal.timeout() 是一次性的,
* 若把 signal 固化在共享 options 里,重试会拿着已 abort 的信号立刻失败。
*
* 加显式超时是必要的 —— 之前 GitHub API 调用完全不设上限,实测审计
* typora-Bloom-theme 时会挂到运行时默认超时("The operation timed out."),
* 整条审计因此失败;一次审计要串几十个请求,任何一次挂住都会拖死整仓。
*/
const buildOptions = () => ({
headers: {
Accept: raw ? 'application/vnd.github.raw' : 'application/vnd.github+json',
'User-Agent': 'github-accounts-manager',
...(token ? { Authorization: `token ${token}` } : {}),
},
signal: AbortSignal.timeout(15000),
})
/*
* 只有两类「重发一次就可能过」的传输层故障才值得重试,其余照原样抛:
* · TLS 证书验证瞬断(Bun fetch 偶发 UNKNOWN_CERTIFICATE_VERIFICATION_ERROR)
* · 连接/读取超时(TimeoutError,含上面 15s 上限)
* 都只重试一次、同 URL,绝不关闭证书校验。
* 重试仍失败时抛低敏描述,别让上层把它误报成「API 限额」。
*
* ⚠️ 一次尝试必须包含「读响应体」这一步:15s 信号管的是整个请求生命周期,
* 大仓库的 README/contents(raw)常在 body 读取阶段才超时。之前只把 fetch
* 包进重试,res.json()/text() 留在 try 外面,那种超时会直接冒到调用方 ——
* 实测 typora-Bloom-theme 就是这样整仓审计失败的。
*/
const retryable = (e) =>
(e?.name === 'TypeError' && e?.code === 'UNKNOWN_CERTIFICATE_VERIFICATION_ERROR') ||
e?.name === 'TimeoutError'
const describe = (error) => {
if (!retryable(error)) return error
if (error?.name === 'TimeoutError') return new Error('GitHub API 请求超时')
return new Error('GitHub API 请求失败(TLS 证书验证)')
}
const attempt = async () => {
const res = await fetch(url, buildOptions())
if (!res.ok) return { ok: false, status: res.status, data: null }
return { ok: true, status: res.status, data: raw ? await res.text() : await res.json() }
}
try {
return await attempt()
} catch (error) {
if (!retryable(error)) throw error
await new Promise((resolve) => setTimeout(resolve, 300))
try {
return await attempt()
} catch (retryError) {
throw describe(retryError)
}
}
}
/**
* 读某个提交里的社区文件(LICENSE / CONTRIBUTING 等)。
* GitHub 的 community/profile 只描述默认分支,PR 报告必须自己按 ref 读,
* 否则 PR 里新增的 LICENSE 会被算成缺失。
*/
async function readCommunityFiles(sourcePath, token, rootEntries) {
const entries = rootEntries.map((entry) => ({ path: entry.name, type: entry.type }))
for (const dir of ['.github', 'docs']) {
if (!rootEntries.some((entry) => entry.name === dir && entry.type === 'dir')) continue
const result = await gh(sourcePath(`contents/${dir}`), token)
if (!result.ok || !Array.isArray(result.data) || result.data.length >= 1000) throw new Error(`PR head ${dir} directory unavailable or possibly truncated (HTTP ${result.status})`)
for (const entry of result.data) entries.push({ path: `${dir}/${entry.name}`, type: entry.type })
}
const hasFile = (pattern) => entries.some((entry) => entry.type === 'file' && pattern.test(entry.path))
let issueTemplate = hasFile(/^(?:\.github\/)?issue_template\.md$/i)
if (!issueTemplate && entries.some((entry) => entry.type === 'dir' && entry.path === '.github/ISSUE_TEMPLATE')) {
const templates = await gh(sourcePath('contents/.github/ISSUE_TEMPLATE'), token)
if (!templates.ok || !Array.isArray(templates.data) || templates.data.length >= 1000) throw new Error(`PR head issue templates unavailable or possibly truncated (HTTP ${templates.status})`)
issueTemplate = templates.data.some((entry) => entry.type === 'file' && /\.(?:md|ya?ml)$/i.test(entry.name) && !/^config\.ya?ml$/i.test(entry.name))
}
return {
license: hasFile(/^(?:(?:\.github|docs)\/)?(?:license|licence|copying)(?:[._-][\w.-]+)?$/i),
contributing: hasFile(/^(?:(?:\.github|docs)\/)?contributing(?:[._-][\w.-]+)?$/i),
issue_template: issueTemplate,
}
}
/** 项目类型决定某些维度的及格线(skill 里每维都有「类型特有检查」) */
export function detectType(files, dirs, pkg, repo, owner) {
const identity = `${repo.description || ''} ${(repo.topics || []).join(' ')}`.toLowerCase()
if (repo.name.toLowerCase() === owner.toLowerCase() && /github-profile|profile readme/.test(identity)) return 'profile'
if (!pkg && dirs.length >= 8 && /image-hosting|image hosting|asset|cdn|图床|素材|静态资源/.test(identity)) return 'asset'
const has = (n) => files.some((f) => f.toLowerCase() === n.toLowerCase())
// SKILL.md 可随库/插件/CLI 一起提供给 Agent,不意味着仓库本身是 skill。
// 只有公开发布的可执行入口或库入口/主题证据,才优先于 SKILL.md;private 工具包不算产品。
const publicPackage = pkg && pkg.private !== true
if (publicPackage && pkg.bin) return 'cli'
if (publicPackage && (files.some((f) => /^(theme|themes)$/i.test(f)) || /theme/i.test(pkg.name || ''))) return 'theme'
if (publicPackage && (pkg.main || pkg.exports)) return 'library'
if (has('SKILL.md')) return 'skill'
if (pkg?.bin) return 'cli'
if (files.some((f) => /^(theme|themes)$/i.test(f)) || /theme/i.test(pkg?.name || '')) return 'theme'
if (pkg?.main || pkg?.exports) return 'library'
if (files.some((f) => /^(index\.html|public|src)$/i.test(f))) return 'app'
return 'other'
}
/** 不同仓库角色对应的可核实维度;不适用不等于项目欠账。 */
const INAPPLICABLE_DIMS = {
asset: new Set(['distribution', 'release', 'quality', 'community', 'docs']),
profile: new Set(['distribution', 'release', 'quality', 'docs'])
}
function excludeInapplicableDimensions(dims, type) {
const excluded = INAPPLICABLE_DIMS[type]
if (!excluded) return dims
return dims.map((dim) => excluded.has(dim.key)
? {
...dim,
score: null,
unverifiable: 10,
evidence: [],
gaps: [],
manual: [`${type === 'asset' ? '资产' : 'GitHub Profile'}仓库不按软件交付维度评分,未计入总分`]
}
: dim)
}
const clamp = (n) => Math.max(0, Math.min(10, Math.round(n * 10) / 10))
/**
* 门面描述的两个通用信号。
*
* 判据刻意只认「有没有把用途和受众说清楚」,不认任何行业词 ——
* 把 secret-manager 这类词写死成全局必需项,等于逼每个项目都套密钥管理的词表;
* 主题分类是各品类自己的事,这里只判描述是否可读懂、能被搜到。
*
* 使用中英文用途/对象词作为保守的词面信号,不等价于语义理解。
* 词表会有盲区;报告需让用户核对,并保留人工判据。
*/
const words = (list) => new RegExp(`\\b(?:${list})(?:s|ing|ment|er)?\\b`, 'i')
const DESCRIPTION_PURPOSE = words([
'for', 'to', 'manage', 'builder', 'build', 'creator', 'create', 'creation', 'tool', 'platform',
'library', 'framework', 'service', 'cli', 'app', 'protect', 'automation', 'automate', 'help',
'enable', 'encrypt', 'encryption', 'store', 'storage', 'deploy', 'deployment', 'run', 'sync',
'convert', 'monitor', 'secure', 'securing', 'simplify', 'simplifies', 'provide', 'turn', 'translate',
'parse', 'parsing', 'generate', 'search', 'scan', 'watch', 'notify', 'publish', 'export',
'import', 'backup', 'migrate', 'optimize', 'render', 'analyze', 'test'
].join('|'))
const DESCRIPTION_AUDIENCE = words([
'developer', 'engineer', 'user', 'operator', 'organization', 'company', 'team', 'agent',
'project', 'business', 'workflow', 'machine', 'device', 'server', 'file', 'database',
'package', 'api', 'key', 'credential', 'password', 'secret', 'certificate', 'configuration',
'environment', 'code', 'browser',
'flashcard', 'paragraph', 'document', 'image', 'video', 'note', 'email', 'test', 'markdown',
'pdf', 'table', 'application', 'student', 'teacher', 'writer', 'photographer', 'musician', 'dotenv'
].join('|'))
const DESCRIPTION_PURPOSE_ZH = /管理|用于|帮助|工具|平台|服务|应用|框架|库|保护|自动化|构建|创建|面向|支持|提供|加密|存储|部署|运行|同步|转换|监控|简化|翻成|转为|转成|把.{0,8}变成/
const DESCRIPTION_AUDIENCE_ZH = /开发者|团队|用户|企业|组织|运维|工程师|智能体|工作流|项目|密钥|证书|配置|环境|数据库|文件|浏览器|程序包|接口|凭证|密码|代码|服务器|设备|卡片|段落|文档|笔记|邮件|图片|视频|表格|学生|老师|写作者|摄影师/
/** 描述是否同时交代用途与受众/场景;只检查通用信号,不要求特定行业词。 */
export function assessDescription(description) {
const text = String(description || '').trim()
if (!text) return { present: false, purpose: false, audience: false, pass: false }
const purpose = DESCRIPTION_PURPOSE.test(text) || DESCRIPTION_PURPOSE_ZH.test(text)
const audience = DESCRIPTION_AUDIENCE.test(text) || DESCRIPTION_AUDIENCE_ZH.test(text)
return { present: true, purpose, audience, pass: purpose && audience }
}
/** Topics 有一定数量且覆盖可从描述中观察到的词类;不按仓库类型硬编码必需词。 */
export function assessTopics(topics, description = '') {
const normalized = [...new Set((Array.isArray(topics) ? topics : []).map((t) => String(t).trim().toLowerCase()).filter(Boolean))]
const descWords = String(description || '').toLowerCase().split(/[^a-z]+/).filter((w) => w.length >= 4)
const descTerms = descWords.filter((w) => !new Set(['open', 'source', 'tool', 'tools', 'with', 'from', 'that', 'this', 'your', 'into', 'using', 'based', 'help', 'helps', 'make', 'made', 'fast', 'easy', 'secure']).has(w))
const stem = (word) => word.replace(/s$/, '')
const matching = normalized.filter((topic) => topic.split('-').some((word) => descTerms.some((term) => stem(term) === stem(word))))
const coverage = normalized.length ? matching.length / normalized.length : 0
const enough = normalized.length >= 6
const comparable = /[a-z]{4,}/i.test(String(description || '')) && descTerms.length > 0
const relevant = normalized.length > 0 && matching.length >= 1
return { count: normalized.length, enough, matching, coverage, comparable, relevant, pass: enough && relevant }
}
/**
* 2025 年起各大 AI 服务商陆续公开爬虫 UA,站方在 robots.txt 里用 Disallow
* 声明「别把我的内容抓去喂模型」。这里做保守解析:
* · 按 User-agent 分组,组内有非空 Disallow 即视为屏蔽该 UA;
* · 没有单列规则时按 `*` 组算(站点常用它一刀切屏蔽所有 AI 爬虫);
* · 返回被屏蔽的爬虫名列表,空数组 = 全部放行。
* 不做 Allow 覆盖等精细语义 —— 那是浏览器该干的事,这里只需要一个方向正确的信号。
*/
const AI_CRAWLER_UAS = [
'gptbot', 'claudebot', 'claude-web', 'perplexitybot', 'google-extended', 'ccbot'
]
function robotsBlocksAiBots(text) {
const groups = new Map()
let current = null
for (const raw of String(text).split(/\r?\n/)) {
const m = raw.match(/^\s*(user-agent|disallow|allow)\s*:\s*(.*?)\s*$/i)
if (!m) continue
const [, key, val] = m
const k = key.toLowerCase()
if (k === 'user-agent') {
current = val.toLowerCase()
if (!groups.has(current)) groups.set(current, [])
} else if (current) {
groups.get(current).push(`${k}:${val.trim()}`)
}
}
return AI_CRAWLER_UAS.filter((bot) => {
/*
* 按 robots 协议的真实语义判,两条以前都错了:
*
* ① **有自己的分组就只看自己的**,不回落到 `*`。
* 原来写的是 `groups.get(bot) || groups.get('*')`,只在 bot 完全没出现时
* 才回落 —— 但 `||` 对空数组不成立,bot 分组存在却没规则时仍会落到 `*`。
* 更常见的写法是「`*` 里 Disallow 某些目录,再给每个 AI bot 单独 Allow: /」,
* 那种站会被判成全屏蔽。
*
* ② **Allow 优先于 Disallow**(同一分组内更具体的规则胜出;
* `Allow: /` 是最宽的放行,直接压过任何 Disallow)。
* 原来只看 disallow、完全无视 allow。
*
* 2026-08-28 实测误判:webkubor.online 的 robots.txt 给 11 个 AI 爬虫
* 逐个写了 `Allow: /`,却被报成屏蔽了其中 4 个。
*/
const own = groups.get(bot)
const rules = (own && own.length) ? own : (groups.get('*') || [])
const allowsAll = rules.some((r) => r.startsWith('allow:') && r.slice('allow:'.length).trim() === '/')
if (allowsAll) return false
return rules.some((r) => r.startsWith('disallow:') && r.slice('disallow:'.length).trim() !== '')
})
}
/**
* 暴露给 page 引擎复用:同一份 robots.txt 语义解读不要在两处重写,免得一边修了一边忘改。
* 这函数是纯函数、无副作用 —— import 即用,不需要 await。
*/
export { robotsBlocksAiBots }
/** SPA 的 history fallback 会对任何路径都返回 index.html(HTTP 200)。
* 那不算「有 robots.txt / llms.txt」,只是壳。真 HTML 页从开头就是
* `<!DOCTYPE html>` / `<html>`;robots.txt 等纯文本以注释或规则开头。
* 只查前 200 字符 —— Cloudflare 托管 robots.txt 结尾会内嵌一段 HTML,
* 全文件扫描会把真 robots.txt 误判成 SPA 壳。 */
function looksLikeHtml(text) {
return /<!doctype\s+html|<html[\s>]/i.test(String(text).slice(0, 200))
}
/** llms.txt 是纯文本清单,规范要求首个标题行是 `# 项目名`。
* 长度 >50 且非 HTML 且带 markdown 标题才认。 */
function isRealLlmsTxt(text) {
if (looksLikeHtml(text)) return false
const t = String(text).trim()
return t.length > 50 && /^#{1,3}\s+\S/m.test(t)
}
/**
* 读外部站点的响应体,失败返回 null。
*
* fetch 拿到 headers 不等于拿到内容:慢站/大文件常在 **body 读取阶段** 才撞上
* AbortSignal 超时。那种 TimeoutError 如果没人接,会从 auditProject 冒出去,
* 把「某个外部官网慢」升级成「整仓审计失败」—— 实测 typora-Bloom-theme 的官网
* 就是这样让整个仓库拿不到分数(约 10s 后抛 TimeoutError,无 stack)。
* 读不到就按「抓取失败 / 无法核实」处理,这是量具的盲区,不是项目的错。
*/
export async function readBodyText(res) {
try {
return await res.text()
} catch {
return null
}
}
/**
* 维度评分收口 —— 「查不到」的判据不算项目的错。
*
* 每个维度满分 10,由若干判据分摊。但有些判据对某类项目根本无从核实:
* 质量护栏的 test/lint 判据读的是 package.json,Rust 项目没有这个文件 ——
* 那不代表它没测试(`cargo test` 不需要声明),只代表本引擎看不到。
* 同理:无清单文件时查不了 registry;README 取不到时判不了文档结构;
* traffic 需要 push 权限,公共服务永远读不到。
*
* 原先这些都当成「不满足」扣分,于是非 JS、非 npm 的项目被系统性压低 ——
* 实测 19 个知名项目里 CPython 4.8、golang/go 5.7,而它们显然不是差项目。
*
* 所以:把无法核实的分值 unv 从分母里去掉,用剩下能核实的部分归一化回 10 分制。
* 「查到了但不满足」仍然扣分 —— 否则弱项会被伪装成「判不了」,分数就失去意义了。
* 全维都无从核实时返回 null,该维不进总分平均。
*/
function normalizeDim(score, unv) {
const denom = 10 - unv
// 剩下能核实的判据不足 2 分,等于这一维基本没量到东西,不给分数
if (denom < 2) return null
return clamp((score / denom) * 10)
}
/**
* 各生态的清单文件 → 包名 → registry 查询地址。
*
* SKILL.md 写的标准是「是否发布到 registry(npm/PyPI/crates/…)」,但引擎原先
* 只查 npm:没有 package.json 就直接判「不是 npm 包,也没看到其它 registry 的痕迹」。
* 于是 Rust / Go / Python 项目在分发这一维天花板只有 4 分 —— 实测 19 个知名项目
* 有 15 个被判「分发薄弱」,其中包括 CPython。那不是事实,是引擎只会看一个生态。
*/
const MANIFESTS = [
{
file: /^package\.json$/i,
eco: 'npm',
pick: (t) => JSON.parse(t)?.name,
url: (n) => `https://registry.npmjs.org/${encodeURIComponent(n)}`
},
{
file: /^Cargo\.toml$/i,
eco: 'crates.io',
pick: (t) => (t.match(/^\s*name\s*=\s*"([^"]+)"/m) || [])[1],
url: (n) => `https://crates.io/api/v1/crates/${encodeURIComponent(n)}`
},
{
file: /^pyproject\.toml$/i,
eco: 'PyPI',
pick: (t) => (t.match(/^\s*name\s*=\s*"?([A-Za-z0-9._-]+)"?/m) || [])[1],
url: (n) => `https://pypi.org/pypi/${encodeURIComponent(n)}/json`
},
{
file: /^setup\.py$/i,
eco: 'PyPI',
pick: (t) => (t.match(/name\s*=\s*["']([A-Za-z0-9._-]+)["']/) || [])[1],
url: (n) => `https://pypi.org/pypi/${encodeURIComponent(n)}/json`
},
{
file: /^composer\.json$/i,
eco: 'Packagist',
pick: (t) => {
const name = JSON.parse(t)?.name
return typeof name === 'string' && name.length <= 214 && /^[a-z0-9_.-]+\/[a-z0-9_.-]+$/i.test(name) ? name : null
},
url: (n) => `https://repo.packagist.org/packages/${n.split('/').map(encodeURIComponent).join('/')}.json`
},
{
file: /\.gemspec$/i,
eco: 'RubyGems',
pick: (t) => (t.match(/\.name\s*=\s*["']([^"']+)["']/) || [])[1],
url: (n) => `https://rubygems.org/api/v1/gems/${encodeURIComponent(n)}.json`
}
]
/** README 里的安装命令 —— 「陌生人能不能装上」最直接的证据,且不用多打一次 API */
const INSTALL_HINTS = [
{ re: /\b(?:npm|pnpm|yarn|bun)[ \t]+(?:i|install|add)[ \t]+(?:(?:-[DSPOgE]|--(?:save-dev|save-prod|save-optional|global|exact|dev))[ \t]+)*[@\w][\w./@-]*/i, how: 'npm 系安装命令' },
{ re: /\bpip3?\s+install\s+[\w.[\]-]+/i, how: 'pip 安装命令' },
{ re: /\b(?:uv|pipx)\s+(?:pip\s+)?install\s+[\w.-]+/i, how: 'uv/pipx 安装命令' },
{ re: /\bcargo\s+(?:add|install)\s+[\w-]+/i, how: 'cargo 安装命令' },
{ re: /\bgo\s+(?:get|install)\s+[\w./-]+/i, how: 'go install 命令' },
{ re: /\bbrew\s+(?:install|tap)\s+[\w./-]+/i, how: 'Homebrew 安装命令' },
{ re: /\bgem\s+install\s+[\w-]+/i, how: 'gem 安装命令' },
{ re: /\bcomposer\s+require\s+[\w./-]+/i, how: 'composer 安装命令' },
{ re: /\bdocker\s+(?:pull|run)\s+[\w./:-]+/i, how: 'Docker 镜像' },
{ re: /\b(?:apt|apt-get|dnf|yum|pacman|apk)\s+(?:install|add|-S)\s+[\w.-]+/i, how: '系统包管理器安装命令' },
{ re: /\bcurl\s+[^\n|]*\|\s*(?:sh|bash)/i, how: '一行式安装脚本' },
{ re: /\bnpx\s+[@\w][\w./@-]*/i, how: 'npx 直接运行' },
{ re: /\bdsh\s+plugin(?:\s+--profile\s+[\w-]+)?\s+add\s+[@\w][\w./@-]*/i, how: 'DSH 插件安装命令' }
]
// 图形界面安装路径不是 shell 命令;只在同一行明确出现宿主、插件、搜索和安装时识别。
const DSH_GUI_INSTALL = /(?:DeepSeek\s+Harness|\bDSH\b)[^\n]{0,100}(?:插件|plugins?)[^\n]{0,80}(?:搜索|search)[^\n]{0,120}(?:安装|install)/i
// 只识别同一 shell 代码块中依次克隆目标仓库、进入默认目录、安装依赖;
// 单独的 npm install 不证明路径完整。仍需人工执行以验证命令有效。
function hasCloneInstallPath(readme, repository) {
const escape = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const repo = repository.split('/')[1]
const clone = new RegExp(`^\\s*(?:\\$\\s*)?git\\s+clone\\s+https://github\\.com/${escape(repository)}(?:\\.git)?\\s*(?:#.*)?$`, 'i')
const enter = new RegExp(`^\\s*(?:\\$\\s*)?cd\\s+(?:\\./)?${escape(repo)}/?\\s*(?:#.*)?$`, 'i')
const install = /^\s*(?:\$\s*)?(?:(?:npm|pnpm|bun)\s+(?:install|ci)|yarn(?:\s+install)?)\s*(?:#.*)?$/i
for (const match of readme.matchAll(/^```(?:sh|bash|shell|zsh)?[ \t]*\r?\n([\s\S]*?)^```[ \t]*$/gmi)) {
let stage = 0
for (const line of match[1].split(/\r?\n/)) {
if (stage === 0 && clone.test(line)) stage = 1
else if (stage === 1 && enter.test(line)) stage = 2
else if (stage === 2 && install.test(line)) return true
else if (stage > 0 && /^\s*(?:\$\s*)?cd(?:\s|$)/i.test(line)) stage = 0
}
}
return false
}
// Actions 里不全是工程质量信号:自动关闭陈旧讨论、同步标签、定时提醒都可能失败,
// 但不能因此给项目贴上「红 CI」标签。只让明确承担构建/验证/发布职责的工作流参与判分。
const ENGINEERING_WORKFLOW = /(?:^|[\s:_/.-])(?:ci|test|tests|build|lint|typecheck|check|verify|publish|release|deploy)(?:$|[\s:_/.-])/i
/**
* 跑一次完整质检。
* @param {{owner:string, repo:string, token?:string, source?:{repository:string, sha:string}}} opts
* source pins repository-file reads to an immutable PR head; repository metadata remains live.
*/
export async function auditProject({ owner, repo, token, source }) {
const full = `${owner}/${repo}`
if (source && (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(source.repository || '') || !/^[a-f0-9]{40}$/i.test(source.sha || ''))) {
throw new Error('PR source must be an owner/repository and a full 40-character commit SHA')
}
const sourceFull = source?.repository || full
const sourcePath = (path) => `/repos/${sourceFull}/${path}${source ? `?ref=${encodeURIComponent(source.sha)}` : ''}`
// 一轮并发把要用的都拉下来。GitHub 带 token 是 5000 次/小时,
// 20 个仓库 × 8 次 = 160 次,一天扫几十轮都不会撞限额。
const [repoRes, community, readmeRes, contentsRes, releases, tags, runs, openIssues] = await Promise.all([
gh(`/repos/${full}`, token),
gh(`/repos/${full}/community/profile`, token),
gh(sourcePath('readme'), token, { raw: true }),
gh(sourcePath('contents'), token),
gh(`/repos/${full}/releases?per_page=5`, token),
gh(`/repos/${full}/tags?per_page=${TAG_SAMPLE}`, token),
gh(`/repos/${full}/actions/runs?per_page=5`, token),
gh(`/repos/${full}/issues?state=open&per_page=30`, token),
])
/*
* errorStatus 会原样成为 API 响应码,必须跟错误性质走(404 = 目标不存在,
* 429 = 被限流,400 = 请求问题,503 = 上游故障)。绝不给 502:本服务部署在
* Cloudflare 后面,代理会把 502 的响应体整个换成自己的错误页,「仓库不存在」
* 这种用户能自救的信息就永远到不了用户眼前,线上只剩一句 error code: 502。
*/
if (!repoRes.ok) {
const s = repoRes.status
const errorStatus = s === 404 || s === 410 ? 404 : s === 403 || s === 429 ? 429 : s < 500 ? 400 : 503
return { error: `仓库读取失败 HTTP ${s}`, errorStatus, score: null }
}
// In a PR report an inaccessible head is not an empty project and must never receive a score.
if (source && (!contentsRes.ok || !Array.isArray(contentsRes.data) || contentsRes.data.length >= 1000)) {
const s = contentsRes.status
const errorStatus = s === 404 || s === 410 ? 404 : s === 403 || s === 429 ? 429 : s < 500 ? 400 : 503
return { error: `PR head content unavailable or possibly truncated (HTTP ${s})`, errorStatus: contentsRes.ok ? 400 : errorStatus, score: null }
}
if (source && !readmeRes.ok && readmeRes.status !== 404) {
throw new Error(`PR head README unavailable (HTTP ${readmeRes.status})`)
}
if (source) {
for (const [name, result] of [['releases', releases], ['tags', tags], ['actions', runs], ['issues', openIssues]]) {
if (!result.ok) throw new Error(`Live ${name} metadata unavailable (HTTP ${result.status})`)
}
if (!Array.isArray(releases.data) || !Array.isArray(tags.data) || !Array.isArray(runs.data?.workflow_runs) || !Array.isArray(openIssues.data)) {
throw new Error('Live repository metadata has an unexpected shape')
}
}
const r = repoRes.data
const readme = readmeRes.ok ? readmeRes.data : ''
const entries = contentsRes.ok && Array.isArray(contentsRes.data) ? contentsRes.data : []
const files = entries.map((f) => f.name)
const dirs = entries.filter((f) => f.type === 'dir').map((f) => f.name)
const hasFile = (re) => files.some((f) => re.test(f))
// community/profile 只反映默认分支的文件状态;PR 报告必须改读该提交的内容,
// 否则会把「PR 里刚补上的 LICENSE」继续判成「没有 LICENSE」。
const cf = source ? await readCommunityFiles(sourcePath, token, entries) : (community.ok ? community.data?.files || {} : {})
let hasIssueTemplate = !!cf.issue_template
if (!hasIssueTemplate && !source) {
if (dirs.includes('.github') || files.includes('.github')) {
const it = await gh(sourcePath('contents/.github/ISSUE_TEMPLATE'), token)
if (it.ok && Array.isArray(it.data) && it.data.length > 0) hasIssueTemplate = true
}
if (!hasIssueTemplate) {
hasIssueTemplate = hasFile(/^issue_template(?:\.md)?$/i)
}
}
// package.json 要单独取内容(contents 列表只给文件名)
let pkg = null
if (files.includes('package.json')) {
const p = await gh(sourcePath('contents/package.json'), token, { raw: true })
if (source && !p.ok) throw new Error(`PR head package.json unavailable (HTTP ${p.status})`)
if (p.ok) {
try { pkg = JSON.parse(p.data) } catch (error) {
if (source) throw new Error('PR head package.json cannot be parsed', { cause: error })
/* 默认分支报告保持既有兼容行为 */
}
}
}
const type = detectType(files, dirs, pkg, r, owner)
const dims = []
// ① 门面 —— 权重最高,决定 10 秒去留
{
const ev = [], gaps = []
const topics = r.topics || []
const descriptionCheck = assessDescription(r.description)
const topicCheck = assessTopics(topics, r.description)
descriptionCheck.present ? ev.push(`description: "${String(r.description).trim().slice(0, 50)}"`) : gaps.push('description 空着 —— 搜索结果里就是一片空白')
if (descriptionCheck.present && descriptionCheck.pass) ev.push('description 检测到用途与对象词面信号(语义是否清楚仍需人工核实)')
topics.length >= 6 ? ev.push(`topics ${topics.length} 个`) : gaps.push(`topics 只有 ${topics.length} 个(建议 ≥6,作为 GitHub 分类与发现信号)`)
if (topics.length && topicCheck.comparable) {
if (topicCheck.relevant) ev.push(`topics 与 description 有关键词对应:${topicCheck.matching.slice(0, 5).join(', ')}`)
// 没有词面交集不能推出语义无关(同义词、缩写都可能造成盲区)。
}
r.homepage ? ev.push(`homepage: ${r.homepage}`) : gaps.push('homepage 未配置')
const manual = ['README 首屏 10 秒清晰度', 'Social Preview 是否已在 Settings 上传 2:1 图', 'logo 是否 1:1 透明底', '中英文品类词是否覆盖目标用户搜索用语(词面信号不能代替语义理解)', 'topics 是否过期(需核对当前实现/可选后端,不能只凭 topic 名或文件缺失推断)']
let score = 2
let unv = 0
let badges = 0
let imgs = 0
if (readme) {
// README 的图片有两种同样合法的写法:Markdown `![]()` 与 HTML `<img>`。
// 只认前者会把许多精心排版的项目(尤其是居中 banner / badge 表格)误判成
// 「没有图片、没有徽章」,让门面分数失真。
const markdownBadges = readme.match(/!\[[^\]]*\]\(https:\/\/img\.shields\.io[^)]*\)/g) || []
const htmlImages = readme.match(/<img\b[^>]*\bsrc\s*=\s*["'][^"']+["'][^>]*>/gi) || []
const htmlBadges = htmlImages.filter((tag) => /\bsrc\s*=\s*["']https:\/\/img\.shields\.io\//i.test(tag))
badges = markdownBadges.length + htmlBadges.length
if (badges >= 4 && badges <= 6) ev.push(`徽章 ${badges} 个(4-6 为宜)`)
else if (badges > 6) gaps.push(`徽章 ${badges} 个,超过 6 个反而稀释可信度`)
else gaps.push(`徽章 ${badges} 个(应 4-6 个:CI/license/版本/下载量)`)
imgs = (readme.match(/!\[[^\]]*\]\([^)]+\)/g) || []).length + htmlImages.length
imgs > 0 ? ev.push(`README 含 ${imgs} 张图`) : gaps.push('README 没有任何图片')
} else {
// README 取不到(不存在 / 私有 / API 失败)—— 徽章和配图无从判断
unv += 3
manual.push('README 取不到,徽章与配图判不了 —— 这 3 分已从满分中剔除')
}
if (descriptionCheck.present && !descriptionCheck.pass) {
unv += 1
manual.push('description 未检测到完整用途/对象词面信号,需人工核实(可能是词表盲区)—— 这 1 分已从满分中剔除')
}
if (topics.length && !topicCheck.relevant) {
unv += 1
manual.push('topics 未检测到与 description 的关键词对应,需人工核实类目相关性(含跨语言/同义词盲区)—— 这 1 分已从满分中剔除')
}
if (descriptionCheck.present) score += 1
if (descriptionCheck.pass) score += 1
if (topics.length >= 6) score += 1
if (topicCheck.relevant) score += 1
if (r.homepage) score += 1
if (badges >= 4 && badges <= 6) score += 1.5
if (imgs > 0) score += 1.5
dims.push({
key: 'facade', name: '门面', score: normalizeDim(score, unv), unverifiable: unv,
evidence: ev, gaps, manual,
})
}
// ② 分发 —— 「好代码没人看」的分水岭
//
// 五条独立证据,任一条成立都说明「陌生人拿得到」:
// registry 发布(+4) · README 有安装命令(+3) · release 带可下载产物(+2)
// · README 带 demo 动图/视频(+1.5) · 头部 badges(+0.5)
// 都不看 star —— 用 star 证明分发是循环论证。
//
// 后两条是「发布物料」:launch 打法里所有渠道复用的同一份东西
// (docs/launch-playbook.md)。gap 文本直接给该做的事,不写空话。
{
const ev = [], gaps = []
const manual = [
'awesome-list / marketplace 收录情况',
'HN/Reddit/V2EX/掘金首发帖',
'social preview(Settings → Social preview,1280×640)API 读不到,转发卡片是否得体只能人工核对',
]
let score = 0
let unv = 0
// ── registry:按清单文件挑对应生态,不再假设人人都发 npm
const m = MANIFESTS.find((x) => files.some((f) => x.file.test(f)))
if (!m && !source) {
// 根目录没有清单时,常见单仓多语言布局把清单放在子目录 ——
// kyvault 的 Cargo.toml 在 rust/ 下,实测被判「查不到 registry」,
// 可它明明发布在 crates.io。对顶层已有的目录做一次有界的探测,
// 探测不到再按「本引擎看不到」剔除,不多打 API。
const NESTED = [
{ dir: 'rust', file: 'rust/Cargo.toml', eco: 'crates.io', pick: (t) => (t.match(/^\s*name\s*=\s*"([^"]+)"/m) || [])[1], url: (n) => `https://crates.io/api/v1/crates/${encodeURIComponent(n)}` },
{ dir: 'python', file: 'python/pyproject.toml', eco: 'pypi', pick: (t) => (t.match(/^\s*name\s*=\s*"([^"]+)"/m) || [])[1], url: (n) => `https://pypi.org/pypi/${encodeURIComponent(n)}/json` },
]
for (const n of NESTED) {
if (!dirs.includes(n.dir)) continue
try {
const text = (await gh(`/repos/${full}/contents/${n.file}`, token, { raw: true })).data
const name = text && n.pick(text)
if (!name) continue
const res = await fetch(n.url(name), {
headers: { 'User-Agent': 'scorecard-audit (+https://scorecard.supercli.site)' },
signal: AbortSignal.timeout(5000)
}).catch(() => null)
if (res?.ok) {
ev.push(`${n.eco} 已发布:${name}(清单在 ${n.dir}/)`)
score += 4
} else {
gaps.push(`${n.dir}/${n.file.split('/').pop()} 声明了 ${name},但 ${n.eco} 上查不到 —— 没发布`)
}
break
} catch { /* 子目录清单读不到不算项目欠账 */ }
}
}
if (!m && !ev.some((x) => x.includes('已发布'))) {
// 探测后仍查不到 registry,不代表没有分发渠道。
// CPython 走 python.org 安装包、Go 走 go.dev、很多项目走系统包管理器,
// 这些本引擎都看不到。把这 4 分从满分里剔除,而不是判它「没发布」。
unv += 4
manual.push('根目录与常见子目录都没有认得的包清单,查不到 registry 记录 —— 这 4 分已从满分中剔除,请自行核对官网/系统包管理器渠道')
}
if (m && source) {
unv += 4
manual.push('PR 评分不向第三方 registry 发送提交中的包名;发布状态需另行核验,这 4 分未计入')
}
if (m && !source) {
const fname = files.find((f) => m.file.test(f))
let name = null
try {
// package.json 已经取过内容,别再打一次
let text
if (m.eco === 'npm' && pkg) text = JSON.stringify(pkg)
else {
const manifest = await gh(sourcePath(`contents/${encodeURIComponent(fname)}`), token, { raw: true })
if (source && !manifest.ok) throw new Error(`PR head manifest unavailable (HTTP ${manifest.status})`)
text = manifest.data
}
if (text) name = m.pick(text)
} catch (error) {
if (source) throw new Error('PR head manifest cannot be read or parsed', { cause: error })
/* 清单文件格式坏不该让整次质检失败 */
}
if (m.eco === 'npm' && pkg?.private) {
ev.push('package.json 标了 private,不走 registry')
score += 2
} else if (name) {
// crates.io / Packagist 不带 UA 会拒;加超时并在 npm 官方源超时时回退公共镜像验证,防止网络偶发抖动误判「没发布」
let res = await fetch(m.url(name), {
headers: { 'User-Agent': 'scorecard-audit (+https://scorecard.supercli.site)' },
signal: AbortSignal.timeout(5000)
}).catch(() => null)
if (!res?.ok && m.eco === 'npm') {
res = await fetch(`https://registry.npmmirror.com/${encodeURIComponent(name)}`, {
signal: AbortSignal.timeout(5000)
}).catch(() => null)
}
if (res?.ok) {
ev.push(`${m.eco} 已发布:${name}`)
score += 4
} else {
gaps.push(`${fname} 声明了 ${name},但 ${m.eco} 上查不到 —— 没发布`)
}
}
}
// ── README 安装命令:最贴近「陌生人能不能装上」的证据
if (!readme) {
unv += 3
manual.push('README 取不到,判不了安装说明 —— 这 3 分已从满分中剔除')
} else {
const hits = INSTALL_HINTS.filter((h) => h.re.test(readme))
if (hits.length) {
ev.push(`README 给了安装方式:${hits.slice(0, 3).map((h) => h.how).join('、')}`)
score += 3
} else if (hasCloneInstallPath(readme, full)) {
ev.push('README 给出克隆目标仓库并安装依赖的步骤')
manual.push('实际执行克隆、依赖安装与启动命令,核实当前环境可用')
score += 3
} else if (DSH_GUI_INSTALL.test(readme)) {
ev.push('README 给出 DSH 插件界面搜索和安装路径')
manual.push('核实图形界面中的搜索、安装和宿主版本是否与说明一致')
score += 3
} else {
gaps.push('README 里找不到一条可以照抄的安装命令或已识别的界面安装路径')
}
}
// ── release 产物:官方下载渠道,公开可读,不需要任何权限
const relAssets = releases.ok && Array.isArray(releases.data)
? releases.data.reduce((n, x) => n + (x.assets?.length || 0), 0)
: 0
if (relAssets > 0) {
ev.push(`最近的 release 带 ${relAssets} 个可下载产物`)
score += 2
}
if (r.homepage) { score += 1; ev.push('有 homepage 可导流') } else { gaps.push('没有 demo/官网链接') }
if ((r.topics || []).length >= 6) score += 0.5
// ── 发布物料:README 里的 demo 动图/视频。
// 一份物料三处复用(README / 社媒 / 落地页),是 launch 打法里性价比最高的
// 一件;终端项目用 vhs 一键录,GUI 项目用 Screen Studio。
const DEMO_ASSET = /(?:src|href)=["'][^"']*\.(?:gif|mp4|webm)(?:[?#]["']|["'])|asciinema|vhs|demo\.(?:gif|mp4|webm)|screencast|tapes\/|\.tape\b/i
if (readme && DEMO_ASSET.test(readme)) {
ev.push('README 带演示动图/视频')
score += 1.5
} else if (readme) {
gaps.push('README 没有 demo 动图/视频 —— launch 物料里最通用的一份,README、社媒、落地页三处复用(终端项目 vhs 录制,GUI 用 Screen Studio)')
}
// ── 头部 badges:license / 版本 / build,项目状态一眼可见
if (readme && /img\.shields\.io|badge\.fury\.io|travis-ci|circleci|github\.com\/[^/]+\/[^/]+\/(?:actions|workflows)\/badge/i.test(readme)) {
ev.push('README 头部带 badges')
score += 0.5
} else if (readme) {
gaps.push('README 没有任何 badges(license / 版本 / build)—— 发布状态一眼可见,shields.io 三个图标就够')
}
// 一条证据都没有时才算真的「拿不到」
if (!ev.length) {
gaps.push('看不到任何分发渠道:registry、安装命令、release 产物都没有')
manual.push('是否通过官网/系统包管理器等本引擎看不到的渠道分发')
}
dims.push({
key: 'distribution', name: '分发', score: normalizeDim(score + 1, unv), unverifiable: unv,
evidence: ev, gaps, manual,
})
}
// ③ 发布工程
{
const ev = [], gaps = []
let score = 1
let tagUnknown = 0 // tag 取样判不准时要剔除的分值
// 判据的意图是「用户能不能固定一个版本」,不是「tag 是否严格符合 semver 规范」。
// 原正则只认 v1.2.3 / 1.2.3,于是 Go 官方仓库的 go1.21.0 被判成「没有 semver tag」——
// 一个每三个月发一版、tag 排得整整齐齐的项目,因为前缀不合口味就丢 3 分。
// 常见的等价写法:go1.21.0(Go)、release-1.2.3、r1.2.3、RELEASE.2024-01-01。
const tagList = tags.ok ? tags.data : []
const versioned = tagList.filter((t) => /^(?:v|go|r|rel(?:ease)?[-_/]?)?\d+\.\d+/i.test(t.name))
if (versioned.length) {
ev.push(`版本 tag ${versioned.length} 个,最新 ${versioned[0].name}`)
score += 3
} else if (tagList.length >= TAG_SAMPLE) {
// 取样满了说明 tag 还有更多没看到,而 GitHub 不保证返回顺序 ——
// 「这 100 个里没有版本号」推不出「这个项目没有版本 tag」。
tagUnknown = 3
ev.push(`tag 超过 ${TAG_SAMPLE} 个,取样里没有版本号格式的(GitHub 不按版本序返回,判不准)`)
} else if (tagList.length) {
gaps.push(`${tagList.length} 个 tag 里没有可固定版本号的 —— 用户无法锁定版本`)
} else {
gaps.push('没有任何 tag —— 用户无法锁定版本')
}
const rel = releases.ok ? releases.data : []
if (rel.length) { ev.push(`GitHub Release ${rel.length} 个,最新 ${rel[0].tag_name}`); score += 2 }
else gaps.push('没有 GitHub Release')
hasFile(/^CHANGELOG/i) ? (score += 2, ev.push('有 CHANGELOG')) : gaps.push('没有 CHANGELOG —— 升级的人不知道变了什么')
const manual = ['Release 资产直链是否真的 200', '仓库里有没有误提交 dist/build 产物']
let unv = tagUnknown
if (tagUnknown) manual.push(`版本 tag 是否规范(tag 太多,取样判不准)—— 这 ${tagUnknown} 分已从满分中剔除`)
const runList = runs.ok ? runs.data?.workflow_runs || [] : []
const engineeringRuns = runList.filter((run) => ENGINEERING_WORKFLOW.test(run.name || ''))
if (engineeringRuns.length) {
ev.push(`最近 ${runList.length} 条 Actions 记录中,仅按默认分支的工作流检查已完成结果(仅为样本)`)
// PR 的 head_branch 可能与默认分支同名;不能据此把 PR 的失败归给默认分支。
const defaultRuns = engineeringRuns.filter(run => r.default_branch && run.head_branch === r.default_branch && typeof run.event === 'string' && run.event.length > 0 && !['pull_request', 'pull_request_target'].includes(run.event) && (!run.head_repository?.full_name || run.head_repository.full_name.toLowerCase() === full.toLowerCase()))
const otherFailures = engineeringRuns.filter(run => !defaultRuns.includes(run) && run.status === 'completed' && ['failure', 'timed_out', 'startup_failure'].includes(run.conclusion))
for (const run of otherFailures) manual.push(`其他分支、PR 或来源未确认的历史工作流 ${run.conclusion}(${run.name},${run.head_branch || '分支未知'}),未计入默认分支评分`)
// 按 workflow 分组,只比较每条 workflow 最近完成的记录;跳过/取消不是失败。
const latestCompleted = new Map()
for (const run of defaultRuns) {
if (run.status !== 'completed') continue
const key = run.workflow_id ?? run.name
if (!latestCompleted.has(key)) latestCompleted.set(key, run)
}
const completed = [...latestCompleted.values()]
const success = completed.filter(run => run.conclusion === 'success')
const failure = completed.filter(run => ['failure', 'timed_out', 'startup_failure'].includes(run.conclusion))
const unknown = completed.filter(run => run.conclusion !== 'success' && !['failure', 'timed_out', 'startup_failure'].includes(run.conclusion))
if (defaultRuns[0] && defaultRuns[0].status !== 'completed') ev.push(`默认分支 CI 正在运行(${defaultRuns[0].name})`)
for (const run of success) ev.push(`CI 最近完成一次 success(${run.name})`)
for (const run of failure) gaps.push(`工作流最近完成一次 ${run.conclusion}(${run.name}),请检查该次运行`)
for (const run of unknown) manual.push(`工作流最近完成一次 ${run.conclusion || 'unknown'}(${run.name}),无法据此判断通过或失败`)
if (failure.length) score += 0.5
else if (success.length) score += 2
else {
unv += 2
if (!completed.length) manual.push('样本中没有可确认的默认分支 CI 完成记录,这 2 分已从满分中剔除')
}
} else if (runList.length) {
// 有 Actions 记录、但没有可识别的工程工作流时,是我们的判断盲区,不是项目的失败。
unv += 2
manual.push(`最近 Actions(${runList.map((run) => run.name).filter(Boolean).join('、')})不属于可识别的构建/验证/发布流程 —— 这 2 分已从满分中剔除`)
} else {
// 没有 Actions 记录不等于没有 CI —— 可能跑在 Travis / CircleCI / GitLab CI / Jenkins 上,
// 那些的运行状态本引擎读不到。根目录有对应配置就判为「看不到」而非「没有」。
const external = files.filter((f) =>
/^(\.travis\.yml|\.circleci|Jenkinsfile|azure-pipelines\.ya?ml|\.gitlab-ci\.yml|appveyor\.yml|\.drone\.yml|\.buildkite)$/i.test(f)
)
if (external.length) {
ev.push(`CI 配置在 ${external[0]}(外部服务,运行状态本引擎读不到)`)
unv += 2
manual.push(`${external[0]} 的最近一次构建是否绿 —— 这 2 分已从满分中剔除`)
} else {
gaps.push('没有 CI 运行记录')
}
}
dims.push({
key: 'release', name: '发布工程', score: normalizeDim(score, unv), unverifiable: unv,
evidence: ev, gaps, manual,
})
}
// ④ 质量护栏
{
const ev = [], gaps = []
const manual = ['测试是否真在 CI 里跑', 'commit message 是否守 conventional commits']
let score = 1
let unv = 0
// test / lint 判据原先只读 package.json.scripts —— 那是 JS 生态的表达方式。
// Rust 的 `cargo test`、Go 的 `go test`、Python 的 pytest 都不需要在清单里声明,
// 所以「没有 package.json」不等于「没有测试」,只等于本引擎看不到。
const scripts = pkg?.scripts || {}
if (pkg) {
scripts.test ? (score += 3, ev.push(`有 test 脚本:${scripts.test.slice(0, 40)}`)) : gaps.push('package.json 没有 test 脚本')
;(scripts.lint || scripts.typecheck) ? (score += 2, ev.push('有 lint/typecheck 脚本')) : gaps.push('没有 lint/typecheck')
} else {
// 换个能核实的角度:这些文件的存在本身就是测试/静态检查的声明
const cfgs = files.filter((f) =>
/^(Makefile|justfile|tox\.ini|pytest\.ini|noxfile\.py|\.pre-commit-config\.yaml|rustfmt\.toml|clippy\.toml|\.golangci\.ya?ml|\.eslintrc|\.ruff\.toml)$/i.test(f)
)
if (cfgs.length) {
score += 3
ev.push(`非 JS 项目,测试/检查入口来自:${cfgs.slice(0, 3).join('、')}`)
unv += 2 // 还剩 lint/typecheck 那部分判不准
} else {
unv += 5
manual.push('没有 package.json,本引擎读不到测试/lint 的声明方式(cargo test / go test / pytest 都无需声明)—— 这 5 分已从满分中剔除')
}
}
hasFile(/^\.github$/) ? (score += 2, ev.push('有 .github(CI 配置)')) : gaps.push('没有 .github 目录')
if (files.some((f) => /^(test|tests|__tests__|spec)$/i.test(f))) { score += 2; ev.push('有独立测试目录') }
dims.push({
key: 'quality', name: '质量护栏', score: normalizeDim(score, unv), unverifiable: unv,
evidence: ev, gaps, manual,
})
}
// ⑤ 社区卫生 —— open issue 积压会造成「项目已死」的错觉
{
const ev = [], gaps = []
let score = 1
cf.license ? (score += 3, ev.push(source ? 'LICENSE: 提交中存在许可证文件(类型需核实)' : `LICENSE: ${r.license?.spdx_id || '有'}`)) : gaps.push('没有 LICENSE —— 公司用户直接过滤掉')
cf.contributing ? (score += 1.5, ev.push('有 CONTRIBUTING')) : gaps.push('没有 CONTRIBUTING')
hasIssueTemplate ? (score += 1, ev.push('有 issue 模板')) : gaps.push('没有 issue 模板')
const issues = (openIssues.ok ? openIssues.data : []).filter((i) => !i.pull_request)
const now = Date.now()
const stale = issues.filter((i) => dayjs().diff(dayjs(i.created_at), 'day') > 30)
if (!issues.length) { ev.push('没有 open issue'); score += 1.5 }
else if (stale.length) gaps.push(`${stale.length} 个 open issue 超 30 天没动(共 ${issues.length} 个)—— 口碑杀手`)
else { ev.push(`${issues.length} 个 open issue,都在 30 天内`); score += 1.5 }
const days = dayjs().diff(dayjs(r.pushed_at), 'day')
if (days <= 90) { ev.push(`${dayjs(r.pushed_at).fromNow()}有提交`); score += 2 }
else gaps.push(`最后一次提交在${dayjs(r.pushed_at).fromNow()} —— 看起来已停更`)
// 这一维的判据(license / contributing / issue 模板 / issue 时效 / 最后提交)
// 全部来自 GitHub API,没有「读不到」的情况,所以 unv 恒为 0。
dims.push({ key: 'community', name: '社区卫生', score: normalizeDim(score, 0), unverifiable: 0, evidence: ev, gaps, manual: [] })
}
// ⑥ 文档
{
const ev = [], gaps = []
let score = 1
// 匹配「标题行里包含关键词」,不是「关键词紧跟 #」。
// 真实标题很少是光秃秃的 `## 安装` —— typora-Bloom-theme 写的是 `## 快速安装`,
// 早先那版正则要求关键词紧接 #,于是把一个有完整安装说明的 README 判成「没有安装章节」。
// 误报比漏报更伤:面板一旦冤枉过一次,人就不信它了。
const manual = ['死链全量体检']
let unv = 0
const sec = (words) => new RegExp(`^#{1,4}[^\\n]*(${words})`, 'im').test(readme)
if (!readme) {
// 这一维几乎全靠 README —— 取不到就整维无结论,不进总分平均。
// 给 0 分是错的:那是在说「这个项目文档很差」,而我们其实什么都没读到。
unv += 8.5
manual.push('README 取不到,文档结构完全判不了 —— 该维不计入总分')
} else {
if (readme.length > 800) { ev.push(`README ${readme.length} 字符`); score += 2 }
else gaps.push(`README 只有 ${readme.length} 字符,撑不起「这是什么、怎么装、怎么用」`)
sec('\\binstall(?:ation)?\\b|安装|部署|上手|(?:快速|一分钟|一键)接入') ? (score += 2, ev.push('有安装章节')) : gaps.push('README 没有安装章节')
if (sec('usage|quick\\s*start|getting\\s*started|快速(?:开始|上手|安装)|(?:快速|一分钟|一键)接入|使用|用法|怎么用')) {
score += 2; ev.push('有快速开始/使用章节')
} else if (DSH_GUI_INSTALL.test(readme) && /(?:重启|restart)[^\n]{0,80}(?:点|点击|打开|click|open)/i.test(readme)) {
unv += 2; manual.push('安装说明中包含后续操作,需人工核实能否完成首次使用 —— 这 2 分未计入')
} else gaps.push('README 没有快速开始')
if (sec('\\bapi\\b|配置|config|options|参数|选项|自定义')) {
score += 1.5; ev.push('有 API/配置章节')
} else if (/\[[^\]\n]*(?:\bapi\b|配置参考|configuration reference)[^\]\n]*\]\((?:https?:\/\/|\.{1,2}\/|\/)[^)\s]+\)/i.test(readme)) {
score += 1.5; ev.push('README 链接到 API/配置参考')
manual.push('核实 API/配置参考链接可访问且内容与版本一致')
} else if (type === 'theme') {
unv += 1.5; manual.push('主题的图形配置与使用说明需人工核实 —— API/配置章节这 1.5 分未计入')
} else gaps.push('没有 API/配置参考')
sec('faq|troubleshoot|常见问题|故障|排查|问题') ? (score += 1, ev.push('有 FAQ/故障排查')) : gaps.push('README 未识别出 FAQ/故障排查章节(可人工核对相关案例)')
}
// AGENTS.md / llms.txt 归入 ⑨ AI 可读性单独打分,这里只留 SKILL.md,
// 否则同一个文件在文档维和 AI 维被算两次分。
if (hasFile(/^SKILL\.md$/i)) { score += 0.5; ev.push('有 SKILL.md(agent 可读文档,加分项)') }
dims.push({
key: 'docs', name: '文档', score: normalizeDim(score, unv), unverifiable: unv,
evidence: ev, gaps, manual,
})
}
// ⑦ 安全
{
const ev = [], gaps = []
let score = 4 // 没发现问题不等于安全,但也不该默认按最差算
hasFile(/^SECURITY\.md$/i) ? (score += 3, ev.push('有 SECURITY.md')) : gaps.push('没有 SECURITY.md')
if (hasFile(/^\.env$/)) { score -= 4; gaps.push('⚠️ 仓库根目录有 .env —— 立刻检查是否含明文密钥') }
if (hasFile(/^(\.gitignore)$/)) { score += 2; ev.push('有 .gitignore') } else gaps.push('没有 .gitignore')
if (pkg?.dependencies && Object.keys(pkg.dependencies).length) ev.push(`${Object.keys(pkg.dependencies).length} 个运行时依赖`)
dims.push({
key: 'security', name: '安全', score: normalizeDim(score, 0), unverifiable: 0, evidence: ev, gaps,
manual: ['git history 明文密钥扫描', 'npm audit / 等价依赖审计'],
})
}
// ⑧ 度量 —— 没有度量就没有反馈闭环
{
const ev = [], gaps = []
let score = 0
r.stargazers_count > 0 ? ev.push(`${r.stargazers_count} star`) : gaps.push('0 star —— 没有任何外部信号')
if (r.stargazers_count >= 50) score += 4
else if (r.stargazers_count >= 10) score += 2.5
else if (r.stargazers_count >= 1) score += 1
const manual = ['npm 下载量趋势', '官网埋点']
// traffic 需要该仓库的 push 权限。作为公共服务,本引擎对别人的仓库永远没有
// 这个权限 —— 所以它 401 是「我们看不到」,不是「项目没有度量」。
// 原先把它记成 gap 并扣 3 分,等于每个被质检的项目都无谓损失 3 分,
// 衡量的是我们的权限而不是项目本身。改为归入 manual,不扣分。
let unv = 0
const traffic = source ? null : await gh(`/repos/${full}/traffic/views`, token)
if (traffic?.ok) {
ev.push(`近两周 ${traffic.data.count} 次浏览 / ${traffic.data.uniques} 独立访客`)
score += 2
} else {
unv += 2
manual.push(source ? 'PR 公开报告不读取私有仓库流量统计,这 2 分未计入' : '近两周 traffic(需仓库 push 权限,公共质检读不到 —— 请自己在 Insights → Traffic 看)')
}
// 替代信号:release 产物下载量。公开可读,不需要任何权限,
// 而且比 traffic 更能说明「真的有人在用」。
const downloads = releases.ok && Array.isArray(releases.data)
? releases.data.reduce((n, x) => n + (x.assets || []).reduce((m, a) => m + (a.download_count || 0), 0), 0)
: 0
if (downloads > 0) {
ev.push(`最近 release 累计下载 ${downloads.toLocaleString('en-US')} 次`)
score += downloads >= 1000 ? 2 : 1
}