@chendb888/dsh-project-steward 0.0.0-stage → 0.1.1
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.
- package/CHANGELOG.md +50 -0
- package/README.md +64 -2
- package/client.js +417 -0
- package/cordis.patch.yml +7 -0
- package/docs/images/cover.png +0 -0
- package/docs/images/icon.png +0 -0
- package/docs/images/update-0.1.0.png +0 -0
- package/icon.svg +14 -0
- package/index.js +24 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +6 -0
- package/package.json +47 -3
- package/src/channel-import.js +97 -0
- package/src/checkers/index.js +113 -0
- package/src/collector-sched.js +119 -0
- package/src/collectors/index.js +101 -0
- package/src/docs-tools.js +44 -0
- package/src/docs.js +254 -0
- package/src/inspect.js +54 -0
- package/src/listing-tools.js +70 -0
- package/src/listing.js +122 -0
- package/src/market/analyze.js +159 -0
- package/src/market/discover.js +52 -0
- package/src/market/features.js +118 -0
- package/src/market/tools.js +34 -0
- package/src/ops-tools.js +70 -0
- package/src/ops.js +65 -0
- package/src/pipeline-tools.js +46 -0
- package/src/pipeline.js +195 -0
- package/src/publish/index.js +51 -0
- package/src/registry.js +121 -0
- package/src/routes.js +185 -0
- package/src/schemas.js +220 -0
- package/src/service.js +113 -0
- package/src/store.js +229 -0
- package/src/templates.js +68 -0
- package/src/tools.js +74 -0
package/index.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// 项目管家 · Host 入口(apply 形式)。M1 组装 service + tools + inspect。
|
|
2
|
+
// 后续任务在此挂载 pipeline/listing/ops/collector/market 与 @Remote。
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
import { StewardService } from './src/service.js'
|
|
5
|
+
import { registerStewardTools } from './src/tools.js'
|
|
6
|
+
import { buildInspect } from './src/inspect.js'
|
|
7
|
+
import { registerRoutes } from './src/routes.js'
|
|
8
|
+
|
|
9
|
+
export const inject = ['tools', 'webServer']
|
|
10
|
+
|
|
11
|
+
export function apply(ctx, config = {}) {
|
|
12
|
+
const dataDir = config.dataDir || join(process.cwd(), 'data')
|
|
13
|
+
const service = new StewardService({ dataDir, collectIntervalMinutes: config.collectIntervalMinutes ?? 60, confirmGates: config.confirmGates ?? false })
|
|
14
|
+
|
|
15
|
+
const disposers = []
|
|
16
|
+
disposers.push(registerStewardTools(ctx, service))
|
|
17
|
+
registerRoutes(ctx, service)
|
|
18
|
+
|
|
19
|
+
// 定时运营采集(R9/R13:默认 60min)
|
|
20
|
+
service.collector.start(config.collectIntervalMinutes ?? 60)
|
|
21
|
+
disposers.push(() => service.collector.stop())
|
|
22
|
+
|
|
23
|
+
return () => { for (const d of disposers) { try { d() } catch {} } }
|
|
24
|
+
}
|
package/locale/en.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "Project steward",
|
|
4
|
+
"description": "Run your software projects like a department store: categorized shelves show each listed product's downloads, views, comments and revenue; fully automated release and listing; scheduled operations collection; a resident mini-bar always visible; competitor comparison and market-gap discovery.",
|
|
5
|
+
"detail": "docs/DETAIL.md"
|
|
6
|
+
}
|
|
7
|
+
}
|
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,50 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chendb888/dsh-project-steward",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "项目管家:软件项目发布/上架/运营统一管家——百货分区货架、常驻迷你条、全自动发布、定时采集、市场情报",
|
|
6
|
+
"meta": {
|
|
7
|
+
"title": "项目管家",
|
|
8
|
+
"description": "像百货商店一样经营你的软件项目:分区货架展示上架商品的下载/浏览/留言/收入,全自动发布上架,定时采集运营数据,常驻迷你条随时可见,竞品对比与市场空白发现。"
|
|
9
|
+
},
|
|
10
|
+
"icon": "./icon.svg",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": "./index.js",
|
|
13
|
+
"./client": "./client.js",
|
|
14
|
+
"./package.json": "./package.json",
|
|
15
|
+
"./locale/*.json": "./locale/*.json"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"index.js",
|
|
19
|
+
"client.js",
|
|
20
|
+
"cordis.patch.yml",
|
|
21
|
+
"icon.svg",
|
|
22
|
+
"README.md",
|
|
23
|
+
"CHANGELOG.md",
|
|
24
|
+
"docs/images/*.png",
|
|
25
|
+
"locale/*.json",
|
|
26
|
+
"src/**/*.js"
|
|
27
|
+
],
|
|
28
|
+
"scripts": {
|
|
29
|
+
"test": "node --test"
|
|
30
|
+
},
|
|
31
|
+
"dependencies": {
|
|
32
|
+
"zod": "^3.25.76"
|
|
33
|
+
},
|
|
34
|
+
"dsh": {
|
|
35
|
+
"bundle": {
|
|
36
|
+
"patch": "./cordis.patch.yml"
|
|
37
|
+
},
|
|
38
|
+
"client": {
|
|
39
|
+
"platform": "web",
|
|
40
|
+
"immediately": true,
|
|
41
|
+
"inject": [
|
|
42
|
+
"@deepseek-ai/dsh-client-ui-conversation"
|
|
43
|
+
]
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
"repository": {
|
|
47
|
+
"type": "git",
|
|
48
|
+
"url": "https://github.com/chendb888/dsh-project-steward.git"
|
|
49
|
+
}
|
|
6
50
|
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// M16 · 从发布渠道扫描导入已上架商品(R33)。扫描平台(npm/GitHub/DSH市场),不扫本地硬盘。
|
|
2
|
+
import { existsSync, readdirSync } from 'node:fs'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
import { spawnSync } from 'node:child_process'
|
|
5
|
+
import { genId, storeError } from './store.js'
|
|
6
|
+
|
|
7
|
+
const defaultFetch = (...a) => globalThis.fetch(...a)
|
|
8
|
+
const now = () => new Date().toISOString()
|
|
9
|
+
|
|
10
|
+
export class ChannelImport {
|
|
11
|
+
constructor(service, opts = {}) {
|
|
12
|
+
this.service = service
|
|
13
|
+
this.store = service.store
|
|
14
|
+
this.fetch = opts.fetch || defaultFetch
|
|
15
|
+
this.account = opts.account || 'chendb888'
|
|
16
|
+
this.scanRoots = opts.scanRoots || ['E:\\']
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// 扫描发布渠道,发现已上架商品(不扫本地文件作为来源;本地仅用于匹配 rootPath)
|
|
20
|
+
async scan(opts = {}) {
|
|
21
|
+
const account = opts.account || this.account
|
|
22
|
+
const found = []
|
|
23
|
+
// npm:按维护者搜索
|
|
24
|
+
try {
|
|
25
|
+
const r = await this.fetch(`https://registry.npmjs.org/-/v1/search?text=maintainer:${account}&size=50`)
|
|
26
|
+
const j = await r.json()
|
|
27
|
+
for (const o of j.objects || []) {
|
|
28
|
+
const p = o.package || {}
|
|
29
|
+
if (p.name?.includes('0.0.0-stage') || p.version === '0.0.0-stage') continue
|
|
30
|
+
found.push({ source: 'npm', channelId: 'ch-npmjs', name: p.name, version: p.version, url: p.links?.npm || `https://npmjs.com/package/${p.name}`, description: p.description || '', date: p.date })
|
|
31
|
+
}
|
|
32
|
+
} catch {}
|
|
33
|
+
// GitHub:用户仓库
|
|
34
|
+
try {
|
|
35
|
+
const r = spawnSync('gh', ['api', `users/${account}/repos`, '--jq', '.[] | {name:.name,full_name:.full_name,url:.html_url,description:.description,pushed_at:.pushed_at,stars:.stargazers_count}', '--paginate'], { encoding: 'utf8', timeout: 30000 })
|
|
36
|
+
if (r.status === 0) {
|
|
37
|
+
for (const line of (r.stdout || '').split('\n').filter(Boolean)) {
|
|
38
|
+
try { const g = JSON.parse(line); found.push({ source: 'github', channelId: 'ch-github', name: g.full_name, version: null, url: g.url, description: g.description || '', date: g.pushed_at, stars: g.stars }) } catch {}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
} catch {}
|
|
42
|
+
// 去重(同名优先 npm)+ 标记已纳管
|
|
43
|
+
const existing = this.service.listProjects()
|
|
44
|
+
const seen = new Set()
|
|
45
|
+
const candidates = []
|
|
46
|
+
for (const f of found) {
|
|
47
|
+
const key = f.name.toLowerCase()
|
|
48
|
+
if (seen.has(key)) continue
|
|
49
|
+
seen.add(key)
|
|
50
|
+
const matched = existing.find(p => p.remote === f.url || p.name === f.name || f.name.includes(p.name))
|
|
51
|
+
candidates.push({ ...f, alreadyRegistered: !!matched, matchedProjectId: matched?.id || null, localRoot: this._matchLocal(f.name) })
|
|
52
|
+
}
|
|
53
|
+
return candidates
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
_matchLocal(name) {
|
|
57
|
+
const short = name.split('/').pop()
|
|
58
|
+
for (const root of this.scanRoots) {
|
|
59
|
+
try {
|
|
60
|
+
for (const d of readdirSync(root, { withFileTypes: true })) {
|
|
61
|
+
if (d.isDirectory() && (d.name === short || d.name.includes(short) || short.includes(d.name))) {
|
|
62
|
+
const full = join(root, d.name)
|
|
63
|
+
if (existsSync(join(full, 'package.json')) || existsSync(join(full, '.git'))) return full
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
} catch {}
|
|
67
|
+
}
|
|
68
|
+
return null
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// 导入一个渠道商品为纳管项目 + 上架记录
|
|
72
|
+
async importProduct(candidate, actor = 'user') {
|
|
73
|
+
const rootPath = candidate.localRoot || candidate.url // 无本地源时用 remote URL 占位
|
|
74
|
+
let project = this.service.listProjects().find(p => p.remote === candidate.url || p.name === candidate.name)
|
|
75
|
+
if (!project) {
|
|
76
|
+
const type = candidate.source === 'npm' ? 'dsh-plugin' : 'research'
|
|
77
|
+
project = await this.service.registerProject({ name: candidate.name, rootPath, type, remote: candidate.url, notes: candidate.description, tags: [candidate.source] }, actor)
|
|
78
|
+
}
|
|
79
|
+
// 记录版本(npm 有 version)
|
|
80
|
+
let releaseId = null
|
|
81
|
+
if (candidate.version) {
|
|
82
|
+
const rel = await this.store.create('releases', { id: genId('rel'), projectId: project.id, runId: 'run-channel-import', version: candidate.version, changelog: candidate.description || ('imported ' + candidate.version), artifacts: [], releasedAt: candidate.date || now() }, actor, 'release-import').catch(() => null)
|
|
83
|
+
releaseId = rel?.id
|
|
84
|
+
}
|
|
85
|
+
// 上架记录(listed)
|
|
86
|
+
let listing = null
|
|
87
|
+
if (releaseId && candidate.channelId) {
|
|
88
|
+
const exists = this.store.list('listings').find(l => l.projectId === project.id && l.channelId === candidate.channelId && l.releaseId === releaseId)
|
|
89
|
+
if (!exists) {
|
|
90
|
+
listing = await this.service.listing.createListing({ projectId: project.id, channelId: candidate.channelId, releaseId }, actor).catch(() => null)
|
|
91
|
+
if (listing) await this.service.listing.transitionListing(listing.id, 'submitted', { actor, note: '渠道导入', waive: true }).catch(() => {})
|
|
92
|
+
if (listing) await this.service.listing.transitionListing(listing.id, 'listed', { actor, platformUrl: candidate.url, note: '已上架(渠道扫描导入)' }).catch(() => {})
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return { project, releaseId, listingId: listing?.id || null }
|
|
96
|
+
}
|
|
97
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// M4 · 7 个自动检查器(07 M4)。每个 (project, run, io?) => Evidence。
|
|
2
|
+
// io 可注入以便测试:{ exists, readFile, git, glob, scan }。
|
|
3
|
+
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
import { spawnSync } from 'node:child_process'
|
|
6
|
+
|
|
7
|
+
const now = () => new Date().toISOString()
|
|
8
|
+
const ev = (summary, extra = {}) => ({ kind: 'check', summary, at: now(), ...extra })
|
|
9
|
+
|
|
10
|
+
const defaultIo = {
|
|
11
|
+
exists: p => existsSync(p),
|
|
12
|
+
readFile: p => { try { return readFileSync(p, 'utf8') } catch { return '' } },
|
|
13
|
+
git: (root, args) => {
|
|
14
|
+
try { const r = spawnSync('git', ['-C', root, ...args], { encoding: 'utf8', timeout: 15000 }); return { code: r.status ?? 1, out: (r.stdout || '') + (r.stderr || '') } }
|
|
15
|
+
catch (e) { return { code: 1, out: String(e.message || e) } }
|
|
16
|
+
},
|
|
17
|
+
glob: (root, pattern) => {
|
|
18
|
+
// 简易 glob:仅支持 dir/*.ext 形式
|
|
19
|
+
const m = pattern.match(/^([^*]+)\*\.(\w+)$/)
|
|
20
|
+
if (!m) return []
|
|
21
|
+
const dir = join(root, m[1].replace(/[\\/]$/, ''))
|
|
22
|
+
if (!existsSync(dir)) return []
|
|
23
|
+
try { return readdirSync(dir).filter(f => f.endsWith('.' + m[2])).map(f => join(dir, f)) } catch { return [] }
|
|
24
|
+
},
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export const checkers = {
|
|
28
|
+
'git-clean': (project, run, io = defaultIo) => {
|
|
29
|
+
const r = io.git(project.rootPath, ['status', '--porcelain'])
|
|
30
|
+
if (r.code !== 0) return ev(`git 检查失败:${r.out.slice(0, 200)}`, { exitCode: r.code })
|
|
31
|
+
const lines = r.out.trim().split('\n').filter(Boolean)
|
|
32
|
+
if (lines.length === 0) return ev('git 工作区干净', { exitCode: 0 })
|
|
33
|
+
return ev(`git 工作区有 ${lines.length} 处未提交改动`, { exitCode: 1, outputTail: lines.slice(0, 20).join('\n') })
|
|
34
|
+
},
|
|
35
|
+
|
|
36
|
+
'version-consistency': (project, run, io = defaultIo) => {
|
|
37
|
+
const root = project.rootPath
|
|
38
|
+
const versions = []
|
|
39
|
+
const pkg = io.readFile(join(root, 'package.json'))
|
|
40
|
+
if (pkg) { try { versions.push(['package.json', JSON.parse(pkg).version]) } catch {} }
|
|
41
|
+
const godot = io.readFile(join(root, 'project.godot'))
|
|
42
|
+
if (godot) { const m = godot.match(/config\/version\s*=\s*"([^"]+)"/); if (m) versions.push(['project.godot', m[1]]) }
|
|
43
|
+
const target = run?.version
|
|
44
|
+
if (target) versions.push(['run.version', target])
|
|
45
|
+
const vals = versions.map(v => v[1]).filter(Boolean)
|
|
46
|
+
if (vals.length === 0) return ev('未找到版本声明', { exitCode: 1 })
|
|
47
|
+
const consistent = vals.every(v => v === vals[0])
|
|
48
|
+
const detail = versions.map(([f, v]) => `${f}=${v}`).join(', ')
|
|
49
|
+
return consistent ? ev(`版本一致:${detail}`, { exitCode: 0 }) : ev(`版本不一致:${detail}`, { exitCode: 1 })
|
|
50
|
+
},
|
|
51
|
+
|
|
52
|
+
'changelog-nonempty': (project, run, io = defaultIo) => {
|
|
53
|
+
const cl = io.readFile(join(project.rootPath, 'CHANGELOG.md'))
|
|
54
|
+
if (!cl.trim()) return ev('CHANGELOG.md 缺失或为空', { exitCode: 1 })
|
|
55
|
+
if (run?.version && !cl.includes(run.version)) return ev(`CHANGELOG 未含版本 ${run.version}`, { exitCode: 1 })
|
|
56
|
+
return ev('CHANGELOG 非空且含当前版本', { exitCode: 0 })
|
|
57
|
+
},
|
|
58
|
+
|
|
59
|
+
'artifact-exists': (project, run, io = defaultIo) => {
|
|
60
|
+
const pattern = run?.artifactGlob || 'build/*.exe'
|
|
61
|
+
const files = io.glob(project.rootPath, pattern)
|
|
62
|
+
if (files.length === 0) return ev(`未找到产物 ${pattern}`, { exitCode: 1 })
|
|
63
|
+
return ev(`找到 ${files.length} 个产物`, { exitCode: 0, files })
|
|
64
|
+
},
|
|
65
|
+
|
|
66
|
+
'export-presets-exist': (project, run, io = defaultIo) => {
|
|
67
|
+
const p = join(project.rootPath, 'export_presets.cfg')
|
|
68
|
+
if (!io.exists(p)) return ev('export_presets.cfg 不存在', { exitCode: 1 })
|
|
69
|
+
const content = io.readFile(p)
|
|
70
|
+
const count = (content.match(/\[preset\.\d+\]/g) || []).length
|
|
71
|
+
return count > 0 ? ev(`含 ${count} 个导出预设`, { exitCode: 0 }) : ev('export_presets.cfg 无预设', { exitCode: 1 })
|
|
72
|
+
},
|
|
73
|
+
|
|
74
|
+
'test-exit': (project, run, io = defaultIo) => {
|
|
75
|
+
// cli 别名:实际由 pipeline 以子进程跑测试命令;此处给静态判定占位
|
|
76
|
+
return ev('test-exit 由 cli 步骤执行(见 pipeline)', { exitCode: 0 })
|
|
77
|
+
},
|
|
78
|
+
|
|
79
|
+
'config-secrets-check': (project, run, io = defaultIo) => {
|
|
80
|
+
const root = project.rootPath
|
|
81
|
+
const targets = ['.env', 'config.json', 'config.js', 'settings.json', 'cordis.patch.yml']
|
|
82
|
+
const hits = []
|
|
83
|
+
const patterns = [/sk-[A-Za-z0-9]{20,}/, /AKIA[0-9A-Z]{16}/, /password\s*[:=]\s*['"][^'"]{6,}['"]/i]
|
|
84
|
+
const scanFile = (rel) => {
|
|
85
|
+
const content = io.readFile(join(root, rel))
|
|
86
|
+
if (!content) return
|
|
87
|
+
content.split('\n').forEach((line, i) => {
|
|
88
|
+
if (patterns.some(p => p.test(line))) hits.push(`${rel}:${i + 1}`)
|
|
89
|
+
})
|
|
90
|
+
}
|
|
91
|
+
for (const t of targets) if (io.exists(join(root, t))) scanFile(t)
|
|
92
|
+
if (hits.length) return ev(`发现疑似明文密钥 ${hits.length} 处(只报位置)`, { exitCode: 1, outputTail: hits.join('\n') })
|
|
93
|
+
return ev('未发现明文密钥', { exitCode: 0 })
|
|
94
|
+
},
|
|
95
|
+
|
|
96
|
+
// FR2.9/R29 发布说明硬门禁:README 必备(功能+安装+版本更新说明)
|
|
97
|
+
'readme-exists': (project, run, io = defaultIo) => {
|
|
98
|
+
const root = project.rootPath
|
|
99
|
+
const candidates = ['README.md', 'readme.md', 'README.MD', 'README']
|
|
100
|
+
const found = candidates.find(f => io.exists(join(root, f)))
|
|
101
|
+
if (!found) return ev('缺少 README(发布说明硬门禁 FR2.9)', { exitCode: 1 })
|
|
102
|
+
const content = io.readFile(join(root, found))
|
|
103
|
+
if (content.trim().length < 50) return ev(`README 过简(${content.trim().length} 字符),需含功能/安装/版本说明`, { exitCode: 1 })
|
|
104
|
+
if (run?.version && !content.includes(run.version)) return ev(`README 未含当前版本 ${run.version} 的更新说明`, { exitCode: 1 })
|
|
105
|
+
return ev(`README 齐备(${found},${content.length} 字符)`, { exitCode: 0, files: [join(root, found)] })
|
|
106
|
+
},
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function runChecker(name, project, run, io) {
|
|
110
|
+
const fn = checkers[name]
|
|
111
|
+
if (!fn) return ev(`未知检查器 ${name}`, { exitCode: 1 })
|
|
112
|
+
return fn(project, run, io)
|
|
113
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// M13 · Collector 调度(07 M13 / 0.5):定时采集+退避+stale+增量事件+紧急推送。
|
|
2
|
+
import { CollectRun } from './schemas.js'
|
|
3
|
+
import { genId } from './store.js'
|
|
4
|
+
import { adapters as defaultAdapters } from './collectors/index.js'
|
|
5
|
+
|
|
6
|
+
const now = () => new Date().toISOString()
|
|
7
|
+
|
|
8
|
+
export class Collector {
|
|
9
|
+
constructor(service, opts = {}) {
|
|
10
|
+
this.service = service
|
|
11
|
+
this.store = service.store
|
|
12
|
+
this.adapters = opts.adapters || defaultAdapters
|
|
13
|
+
this.io = opts.io || {}
|
|
14
|
+
this.timer = opts.timer || { setInterval: (fn, ms) => setInterval(fn, ms), clearInterval: id => clearInterval(id) }
|
|
15
|
+
this.intervalMs = (opts.intervalMinutes ?? 60) * 60000
|
|
16
|
+
this._handle = null
|
|
17
|
+
this._failCount = {}
|
|
18
|
+
this._seen = {}
|
|
19
|
+
this.onUrgent = opts.onUrgent || (() => {})
|
|
20
|
+
this.sleep = opts.sleep || sleep
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
start(minutes) {
|
|
24
|
+
if (minutes != null) this.intervalMs = minutes * 60000
|
|
25
|
+
this.stop()
|
|
26
|
+
this._handle = this.timer.setInterval(() => { this.collectNow().catch(() => {}) }, this.intervalMs)
|
|
27
|
+
return this._handle
|
|
28
|
+
}
|
|
29
|
+
stop() { if (this._handle != null) { this.timer.clearInterval(this._handle); this._handle = null } }
|
|
30
|
+
|
|
31
|
+
async collectNow(channelId) {
|
|
32
|
+
let channels = this.store.list('channels').filter(c => c.status === 'active')
|
|
33
|
+
if (channelId) channels = channels.filter(c => c.id === channelId)
|
|
34
|
+
const runs = []
|
|
35
|
+
// 并发≤3
|
|
36
|
+
for (let i = 0; i < channels.length; i += 3) {
|
|
37
|
+
const batch = channels.slice(i, i + 3)
|
|
38
|
+
const rs = await Promise.all(batch.map(c => this._collectChannel(c)))
|
|
39
|
+
runs.push(...rs)
|
|
40
|
+
}
|
|
41
|
+
return runs
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async _collectChannel(channel) {
|
|
45
|
+
const run = { id: genId('cr'), channelId: channel.id, listingIds: [], startedAt: now(), status: 'running', metricsWritten: 0, newComments: 0, newPayments: 0, staleMarked: false }
|
|
46
|
+
const listings = this.store.list('listings').filter(l => l.channelId === channel.id && l.status === 'listed')
|
|
47
|
+
run.listingIds = listings.map(l => l.id)
|
|
48
|
+
const adapter = this.adapters[channel.category]
|
|
49
|
+
if (!adapter || listings.length === 0) {
|
|
50
|
+
run.status = 'ok'; run.finishedAt = now()
|
|
51
|
+
await this.store.create('collect-runs', CollectRun.parse(run), 'collector', 'collect')
|
|
52
|
+
return run
|
|
53
|
+
}
|
|
54
|
+
const items = listings.map(l => {
|
|
55
|
+
const proj = this.service.getProject(l.projectId) || {}
|
|
56
|
+
const meta = deriveMeta(proj)
|
|
57
|
+
return { id: l.id, name: l.platformUrl || l.id, pkgName: l.pkgName || meta.pkgName, repo: l.repo || meta.repo, healthUrl: l.healthUrl || meta.healthUrl }
|
|
58
|
+
})
|
|
59
|
+
let result, lastErr
|
|
60
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
61
|
+
try { result = await adapter.fetch(items, channel.credentialRef, this.io); lastErr = null; break }
|
|
62
|
+
catch (e) { lastErr = e; await this.sleep(backoff(attempt)) }
|
|
63
|
+
}
|
|
64
|
+
if (lastErr) {
|
|
65
|
+
run.status = 'failed'; run.error = String(lastErr.message || lastErr); run.staleMarked = true
|
|
66
|
+
this._failCount[channel.id] = (this._failCount[channel.id] || 0) + 1
|
|
67
|
+
if (this._failCount[channel.id] >= 3) this.onUrgent({ kind: 'collect-stale', channelId: channel.id, reason: run.error, consecutiveFailures: this._failCount[channel.id] })
|
|
68
|
+
run.finishedAt = now()
|
|
69
|
+
await this.store.create('collect-runs', CollectRun.parse(run), 'collector', 'collect')
|
|
70
|
+
this.service._broadcast({ type: 'steward/collect-stale', channelId: channel.id, reason: run.error })
|
|
71
|
+
return run
|
|
72
|
+
}
|
|
73
|
+
this._failCount[channel.id] = 0
|
|
74
|
+
// 写指标
|
|
75
|
+
const today = new Date().toISOString().slice(0, 10)
|
|
76
|
+
for (const l of listings) {
|
|
77
|
+
const m = result.metrics?.[l.id]
|
|
78
|
+
if (m && Object.keys(m).length) {
|
|
79
|
+
await this.service.ops.addMetric({ projectId: l.projectId, channelId: channel.id, date: today, metrics: m }, 'collector', 'collector')
|
|
80
|
+
run.metricsWritten++
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
// 增量留言/付款
|
|
84
|
+
const seenKey = channel.id
|
|
85
|
+
const prev = this._seen[seenKey] || { comments: [], payments: [] }
|
|
86
|
+
const newComments = (result.comments || []).filter(c => !prev.comments.includes(c.id || c.text))
|
|
87
|
+
const newPayments = (result.payments || []).filter(p => !prev.payments.includes(p.id))
|
|
88
|
+
this._seen[seenKey] = { comments: (result.comments || []).map(c => c.id || c.text), payments: (result.payments || []).map(p => p.id) }
|
|
89
|
+
for (const c of newComments) {
|
|
90
|
+
await this.service.ops.addEvent({ projectId: listings[0].projectId, kind: 'comment', severity: 'info', text: c.text || '新留言', listingId: listings[0].id }, 'collector')
|
|
91
|
+
run.newComments++
|
|
92
|
+
}
|
|
93
|
+
for (const p of newPayments) {
|
|
94
|
+
await this.service.ops.addEvent({ projectId: listings[0].projectId, kind: 'payment', severity: 'info', text: `新付款 ${p.amount || ''}`, listingId: listings[0].id }, 'collector')
|
|
95
|
+
run.newPayments++
|
|
96
|
+
this.onUrgent({ kind: 'payment', channelId: channel.id, amount: p.amount })
|
|
97
|
+
}
|
|
98
|
+
run.status = 'ok'; run.finishedAt = now()
|
|
99
|
+
await this.store.create('collect-runs', CollectRun.parse(run), 'collector', 'collect')
|
|
100
|
+
this.service._broadcast({ type: 'steward/collect-updated', channelId: channel.id, metricsWritten: run.metricsWritten, newComments: run.newComments, newPayments: run.newPayments })
|
|
101
|
+
return run
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const sleep = ms => new Promise(r => setTimeout(r, ms))
|
|
106
|
+
const backoff = attempt => Math.min(1000 * 2 ** attempt, 8000)
|
|
107
|
+
|
|
108
|
+
// 从项目元数据推导采集所需的包名/仓库/健康地址
|
|
109
|
+
function deriveMeta(proj) {
|
|
110
|
+
const out = {}
|
|
111
|
+
const remote = proj.remote || ''
|
|
112
|
+
const gh = remote.match(/github\.com[/:]([^/]+\/[^/]+?)(?:\.git)?$/)
|
|
113
|
+
if (gh) out.repo = gh[1]
|
|
114
|
+
const notes = (proj.notes || '') + ' ' + (proj.name || '')
|
|
115
|
+
const pkg = notes.match(/@[\w.-]+\/[\w.-]+/) || notes.match(/\b(dsh-[\w-]+)\b/)
|
|
116
|
+
if (pkg) out.pkgName = pkg[0]
|
|
117
|
+
if (proj.healthUrl) out.healthUrl = proj.healthUrl
|
|
118
|
+
return out
|
|
119
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// M13 · 采集适配器(07 M13)。可注入 fetch 以便测试(不真实联网)。
|
|
2
|
+
// 接口:{ channelCategory, fetch(listings, credRef?, io?) => { metrics, comments[], payments[] } }
|
|
3
|
+
import { spawnSync } from 'node:child_process'
|
|
4
|
+
const defaultFetch = (...a) => globalThis.fetch(...a)
|
|
5
|
+
let _ghToken = null
|
|
6
|
+
function ghToken() {
|
|
7
|
+
if (_ghToken !== null) return _ghToken
|
|
8
|
+
try { const r = spawnSync('gh', ['auth', 'token'], { encoding: 'utf8', timeout: 10000 }); _ghToken = r.status === 0 ? (r.stdout || '').trim() : '' } catch { _ghToken = '' }
|
|
9
|
+
return _ghToken
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export const adapters = {
|
|
13
|
+
'npm-registry': {
|
|
14
|
+
channelCategory: 'npm-registry',
|
|
15
|
+
async fetch(listings, credRef, io = {}) {
|
|
16
|
+
const f = io.fetch || defaultFetch
|
|
17
|
+
const metrics = {}
|
|
18
|
+
for (const l of listings) {
|
|
19
|
+
const pkg = l.pkgName || l.name
|
|
20
|
+
if (!pkg) continue
|
|
21
|
+
try {
|
|
22
|
+
const r = await f(`https://api.npmjs.org/downloads/point/last-month/${encodeURIComponent(pkg)}`)
|
|
23
|
+
const j = await r.json()
|
|
24
|
+
metrics[l.id] = { downloads: j.downloads || 0 }
|
|
25
|
+
} catch { metrics[l.id] = { downloads: 0 } }
|
|
26
|
+
}
|
|
27
|
+
return { metrics, comments: [], payments: [] }
|
|
28
|
+
},
|
|
29
|
+
},
|
|
30
|
+
'source-repo': {
|
|
31
|
+
channelCategory: 'source-repo',
|
|
32
|
+
async fetch(listings, credRef, io = {}) {
|
|
33
|
+
const f = io.fetch || defaultFetch
|
|
34
|
+
const token = credRef?.token || (io.noGh ? '' : ghToken())
|
|
35
|
+
const auth = token ? { Authorization: `Bearer ${token}` } : {}
|
|
36
|
+
const metrics = {}
|
|
37
|
+
for (const l of listings) {
|
|
38
|
+
const repo = l.repo
|
|
39
|
+
if (!repo) continue
|
|
40
|
+
const m = { stars: 0, forks: 0, watchers: 0, issues: 0, views: 0, viewUniques: 0, clones: 0, cloneUniques: 0 }
|
|
41
|
+
try {
|
|
42
|
+
const r = await f(`https://api.github.com/repos/${repo}`, { headers: auth })
|
|
43
|
+
const j = await r.json()
|
|
44
|
+
m.stars = j.stargazers_count || 0; m.forks = j.forks_count || 0; m.watchers = j.subscribers_count || 0; m.issues = j.open_issues_count || 0
|
|
45
|
+
} catch {}
|
|
46
|
+
// 浏览量(页面访问,与下载分开)+ 克隆量,需鉴权 traffic API
|
|
47
|
+
if (token) {
|
|
48
|
+
try { const v = await (await f(`https://api.github.com/repos/${repo}/traffic/views`, { headers: auth })).json(); m.views = v.count || 0; m.viewUniques = v.uniques || 0 } catch {}
|
|
49
|
+
try { const c = await (await f(`https://api.github.com/repos/${repo}/traffic/clones`, { headers: auth })).json(); m.clones = c.count || 0; m.cloneUniques = c.uniques || 0 } catch {}
|
|
50
|
+
}
|
|
51
|
+
metrics[l.id] = m
|
|
52
|
+
}
|
|
53
|
+
return { metrics, comments: [], payments: [] }
|
|
54
|
+
},
|
|
55
|
+
},
|
|
56
|
+
'game-store': {
|
|
57
|
+
channelCategory: 'game-store',
|
|
58
|
+
async fetch(listings, credRef, io = {}) {
|
|
59
|
+
// itch/Steam 占位:v1 返回空指标(需 butler/Steamworks 凭据接入)
|
|
60
|
+
const metrics = {}
|
|
61
|
+
for (const l of listings) metrics[l.id] = {}
|
|
62
|
+
return { metrics, comments: [], payments: [] }
|
|
63
|
+
},
|
|
64
|
+
},
|
|
65
|
+
'mirror': {
|
|
66
|
+
channelCategory: 'mirror',
|
|
67
|
+
async fetch(listings, credRef, io = {}) {
|
|
68
|
+
const f = io.fetch || defaultFetch
|
|
69
|
+
const metrics = {}
|
|
70
|
+
for (const l of listings) {
|
|
71
|
+
const pkg = l.pkgName || l.name
|
|
72
|
+
if (!pkg) continue
|
|
73
|
+
try {
|
|
74
|
+
const r = await f(`https://registry.npmmirror.com/${encodeURIComponent(pkg)}`)
|
|
75
|
+
const j = await r.json()
|
|
76
|
+
metrics[l.id] = { downloads: j.downloads || 0 }
|
|
77
|
+
} catch { metrics[l.id] = {} }
|
|
78
|
+
}
|
|
79
|
+
return { metrics, comments: [], payments: [] }
|
|
80
|
+
},
|
|
81
|
+
},
|
|
82
|
+
'web-deploy': {
|
|
83
|
+
channelCategory: 'web-deploy',
|
|
84
|
+
async fetch(listings, credRef, io = {}) {
|
|
85
|
+
const f = io.fetch || defaultFetch
|
|
86
|
+
const metrics = {}
|
|
87
|
+
for (const l of listings) {
|
|
88
|
+
const url = l.healthUrl
|
|
89
|
+
if (!url) continue
|
|
90
|
+
try {
|
|
91
|
+
const r = await f(url)
|
|
92
|
+
const j = await r.json()
|
|
93
|
+
metrics[l.id] = { healthy: j.ok || j.ready ? 1 : 0 }
|
|
94
|
+
} catch { metrics[l.id] = { healthy: 0 } }
|
|
95
|
+
}
|
|
96
|
+
return { metrics, comments: [], payments: [] }
|
|
97
|
+
},
|
|
98
|
+
},
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function adapterFor(category) { return adapters[category] || null }
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// M15 · 项目说明 Agent 工具(FR7.5)。
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
const ok = data => ({ ok: true, data })
|
|
4
|
+
const fail = e => ({ ok: false, error: { code: e.code || 'ERROR', message: String(e.message || e) } })
|
|
5
|
+
const guard = (schema, args, fn) => { const p = schema.safeParse(args || {}); if (!p.success) return fail({ code: 'INVALID_INPUT', message: p.error.issues.map(i => `${i.path.join('.')}: ${i.message}`).join('; ') }); return Promise.resolve(fn(p.data)).then(ok, fail) }
|
|
6
|
+
const need = service => { if (!service.docs) throw { code: 'NOT_READY', message: 'docs 未挂载' }; return service.docs }
|
|
7
|
+
|
|
8
|
+
const idSchema = z.object({ projectId: z.string() })
|
|
9
|
+
const channelSchema = z.object({ projectId: z.string(), channelId: z.string() })
|
|
10
|
+
|
|
11
|
+
export function buildDocsTools(service) {
|
|
12
|
+
return [
|
|
13
|
+
{
|
|
14
|
+
name: 'steward_doc_check',
|
|
15
|
+
description: '核对项目说明齐备性(README/CHANGELOG/description/版本说明)。只读。',
|
|
16
|
+
parameters: { type: 'object', properties: { projectId: { type: 'string' } }, required: ['projectId'], additionalProperties: false },
|
|
17
|
+
execute: async args => guard(idSchema, args, d => need(service).docCheck(d.projectId)),
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
name: 'steward_doc_scaffold',
|
|
21
|
+
description: '生成项目 README+CHANGELOG 模板(仅补缺失,不覆盖已有)。',
|
|
22
|
+
parameters: { type: 'object', properties: { projectId: { type: 'string' }, force: { type: 'boolean' } }, required: ['projectId'], additionalProperties: false },
|
|
23
|
+
execute: async args => guard(idSchema.extend({ force: z.boolean().optional() }), args, d => need(service).docScaffold(d.projectId, { force: d.force })),
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
name: 'steward_doc_complete',
|
|
27
|
+
description: '按对应商店规则完成项目说明(npm README/description;GitHub description+topics;DSH市场 locale meta+DETAIL+icon)。',
|
|
28
|
+
parameters: { type: 'object', properties: { projectId: { type: 'string' }, channelId: { type: 'string' } }, required: ['projectId', 'channelId'], additionalProperties: false },
|
|
29
|
+
execute: async args => guard(channelSchema, args, d => need(service).docCompleteChannel(d.projectId, d.channelId)),
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
name: 'steward_maintenance_report',
|
|
33
|
+
description: '维护巡检报告:所有项目说明齐备性+版本一致性。只读。',
|
|
34
|
+
parameters: { type: 'object', properties: {}, additionalProperties: false },
|
|
35
|
+
execute: async () => ok(need(service).maintenanceReport()),
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
name: 'steward_doc_update_image',
|
|
39
|
+
description: '生成某版本更新位置标注图(界面示意+红框标注+图例,SVG→PNG,推GitHub)。FR7.7 全项目文档标准。',
|
|
40
|
+
parameters: { type: 'object', properties: { projectId: { type: 'string' }, version: { type: 'string' } }, required: ['projectId', 'version'], additionalProperties: false },
|
|
41
|
+
execute: async args => guard(z.object({ projectId: z.string(), version: z.string() }), args, d => need(service).generateUpdateImage(d.projectId, d.version)),
|
|
42
|
+
},
|
|
43
|
+
]
|
|
44
|
+
}
|