@chendb888/dsh-project-steward 0.0.0-stage → 0.1.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.
@@ -0,0 +1,195 @@
1
+ // M3 · Pipeline:run 状态机 + 执行器 + 闸门 + 阻断(03§7.2 / 07 M3)。
2
+ // 全自动 R8:G2 默认放行;G4(豁免/取消)需显式 reason;readOnly 硬拒绝。
3
+ import { RunStatus, StepStatus } from './schemas.js'
4
+ import { genId, storeError } from './store.js'
5
+ import { runChecker } from './checkers/index.js'
6
+ import { templateFor } from './templates.js'
7
+ import { executePublish } from './publish/index.js'
8
+ import { spawnSync } from 'node:child_process'
9
+ import { readFileSync } from 'node:fs'
10
+ import { join } from 'node:path'
11
+
12
+ const now = () => new Date().toISOString()
13
+ const ALLOWED_STAGE = ['developing', 'releasing', 'operating']
14
+ const DONE_STEP = ['passed', 'skipped', 'waived']
15
+
16
+ function defaultRunCmd(command, cwd) {
17
+ try {
18
+ const r = spawnSync(command, { cwd, encoding: 'utf8', timeout: 600000, shell: true })
19
+ return { code: r.status ?? 1, out: ((r.stdout || '') + (r.stderr || '')).slice(-4096) }
20
+ } catch (e) { return { code: 1, out: String(e.message || e) } }
21
+ }
22
+
23
+ export class Pipeline {
24
+ constructor(service, opts = {}) {
25
+ this.service = service
26
+ this.store = service.store
27
+ this.dryRun = opts.dryRun ?? true
28
+ this.confirmGates = opts.confirmGates ?? false
29
+ this.io = opts.io
30
+ this.runCmd = opts.runCmd || defaultRunCmd
31
+ }
32
+
33
+ _emit(e) { this.service._broadcast(e) }
34
+ getRun(id) { return this.store.readRun(id) }
35
+ listRuns(projectId) { const r = this.store.listRuns(); return projectId ? r.filter(x => x.projectId === projectId) : r }
36
+
37
+ _latestVersion(projectId) {
38
+ const rels = this.store.list('releases').filter(r => r.projectId === projectId)
39
+ if (!rels.length) return null
40
+ return rels.map(r => r.version).sort(semverCompare).pop()
41
+ }
42
+
43
+ async startRun({ projectId, version, templateId, allowRegression, reason }, actor = 'agent') {
44
+ const project = this.service.getProject(projectId)
45
+ if (!project) throw storeError('NOT_FOUND', `项目 ${projectId} 不存在`)
46
+ if (!ALLOWED_STAGE.includes(project.stage)) throw storeError('ILLEGAL_STAGE', `项目阶段 ${project.stage} 不允许发起发布`)
47
+ if (this.listRuns(projectId).some(r => r.status === 'running' || r.status === 'blocked')) throw storeError('RUN_IN_PROGRESS', '已有进行中的 run')
48
+ // 版本:缺省自动 bump patch(R21)
49
+ const latest = this._latestVersion(projectId)
50
+ let ver = version
51
+ if (!ver) ver = latest ? bumpPatch(latest) : '0.1.0'
52
+ if (latest && semverCompare(ver, latest) <= 0 && !allowRegression) throw storeError('VERSION_REGRESSION', `版本 ${ver} 不高于最近 ${latest}(需 allowRegression+reason)`)
53
+ if (latest && semverCompare(ver, latest) <= 0 && allowRegression && !reason) throw storeError('INVALID_INPUT', '版本倒退豁免需 reason')
54
+ const tpl = (templateId && this.store.get('templates', templateId)) || templateFor(project.type, this.store.list('templates'))
55
+ if (!tpl) throw storeError('NOT_FOUND', `无 ${project.type} 类型模板`)
56
+ const run = {
57
+ id: genId('run'), projectId, version: ver, templateId: tpl.id, status: 'running',
58
+ steps: tpl.steps.map(sd => ({ name: sd.name, kind: sd.kind, status: 'pending', _def: sd })),
59
+ startedAt: now(),
60
+ }
61
+ this.store.writeRun(run)
62
+ await this.service.transitionStage(projectId, 'releasing', actor, 'startRun').catch(() => {})
63
+ this._emit({ type: 'steward/changed', entity: 'run', entityId: run.id, action: 'start' })
64
+ return run
65
+ }
66
+
67
+ async executeStep(runId, stepName, { confirm } = {}, actor = 'agent') {
68
+ const run = this.store.readRun(runId)
69
+ if (!run) throw storeError('NOT_FOUND', `run ${runId} 不存在`)
70
+ if (run.status === 'done' || run.status === 'cancelled') throw storeError('ILLEGAL_TRANSITION', `run 已 ${run.status}`)
71
+ const step = run.steps.find(s => s.name === stepName)
72
+ if (!step) throw storeError('NOT_FOUND', `步骤 ${stepName} 不存在`)
73
+ const def = step._def || {}
74
+ const project = this.service.getProject(run.projectId)
75
+ const channel = this._channelFor(def)
76
+ step.status = 'running'; step.startedAt = now()
77
+
78
+ let evidence
79
+ if (step.kind === 'auto-check') {
80
+ evidence = runChecker(def.checker, project, run, this.io)
81
+ step.status = evidence.exitCode === 0 ? 'passed' : 'failed'
82
+ } else if (step.kind === 'cli') {
83
+ if (this.confirmGates && !confirm) { step.status = 'pending'; throw storeError('CONFIRM_REQUIRED', `cli 步骤需 confirm:${def.command}`) }
84
+ const cmd = (def.command || '').replace(/\{root\}/g, project.rootPath).replace(/\{version\}/g, run.version)
85
+ const r = this.runCmd(cmd, project.rootPath)
86
+ evidence = { kind: 'command', summary: `cli ${r.code === 0 ? '成功' : '失败'}:${cmd}`, exitCode: r.code, outputTail: r.out, command: cmd, at: now() }
87
+ step.status = r.code === 0 ? 'passed' : 'failed'
88
+ } else if (step.kind === 'auto-publish') {
89
+ if (this.confirmGates && !confirm) { step.status = 'pending'; throw storeError('CONFIRM_REQUIRED', `发布步骤需 confirm:${def.publishAction}`) }
90
+ evidence = executePublish(def.publishAction, { project, run, channel, dryRun: this.dryRun })
91
+ if (evidence.code === 'ILLEGAL_ON_PROTECTED') { step.status = 'failed'; step.evidence = evidence; this._block(run, step); this.store.writeRun(run); throw storeError('ILLEGAL_ON_PROTECTED', evidence.summary) }
92
+ step.status = evidence.exitCode === 0 ? 'passed' : 'failed'
93
+ } else if (step.kind === 'manual') {
94
+ step.evidence = { kind: 'manual', summary: def.guide || '等待人工回填', at: now() }
95
+ this.store.writeRun(run)
96
+ return step // running,等 completeManualStep
97
+ }
98
+ step.evidence = evidence
99
+ step.finishedAt = now()
100
+ if (step.status === 'failed' && def.blocking !== false) this._block(run, step)
101
+ else await this._maybeComplete(run, actor)
102
+ this.store.writeRun(run)
103
+ return step
104
+ }
105
+
106
+ async completeManualStep(runId, stepName, result, note, actor = 'user') {
107
+ const run = this.store.readRun(runId)
108
+ if (!run) throw storeError('NOT_FOUND', `run ${runId} 不存在`)
109
+ const step = run.steps.find(s => s.name === stepName)
110
+ if (!step || step.kind !== 'manual') throw storeError('INVALID_INPUT', '非 manual 步骤')
111
+ step.status = result === 'passed' ? 'passed' : 'failed'
112
+ step.evidence = { kind: 'manual', summary: note || (result === 'passed' ? '人工完成' : '人工失败'), at: now() }
113
+ step.finishedAt = now()
114
+ if (step.status === 'failed' && (step._def?.blocking !== false)) this._block(run, step)
115
+ else await this._maybeComplete(run, actor)
116
+ this.store.writeRun(run)
117
+ return step
118
+ }
119
+
120
+ async waiveStep(runId, stepName, reason, actor = 'user') {
121
+ if (!reason) throw storeError('INVALID_INPUT', '豁免需 reason(G4)')
122
+ const run = this.store.readRun(runId)
123
+ if (!run) throw storeError('NOT_FOUND', `run ${runId} 不存在`)
124
+ const step = run.steps.find(s => s.name === stepName)
125
+ if (!step) throw storeError('NOT_FOUND', `步骤 ${stepName} 不存在`)
126
+ if (step._def?.waivable === false) throw storeError('ILLEGAL_TRANSITION', '该步骤不可豁免')
127
+ step.status = 'waived'; step.waiveReason = reason; step.finishedAt = now()
128
+ if (run.status === 'blocked' && !run.steps.some(s => s.status === 'failed')) run.status = 'running'
129
+ await this._maybeComplete(run, actor)
130
+ this.store.writeRun(run)
131
+ this._emit({ type: 'steward/changed', entity: 'run', entityId: runId, action: 'waive', reason })
132
+ return step
133
+ }
134
+
135
+ async cancelRun(runId, reason, actor = 'user') {
136
+ if (!reason) throw storeError('INVALID_INPUT', '取消需 reason')
137
+ const run = this.store.readRun(runId)
138
+ if (!run) throw storeError('NOT_FOUND', `run ${runId} 不存在`)
139
+ run.status = 'cancelled'; run.cancelReason = reason; run.finishedAt = now()
140
+ this.store.writeRun(run)
141
+ await this.service.transitionStage(run.projectId, 'developing', actor, 'run cancelled').catch(() => {})
142
+ return run
143
+ }
144
+
145
+ _channelFor(def) {
146
+ const cat = def.publishAction ? (publishCategory(def.publishAction)) : null
147
+ if (!cat) return null
148
+ return this.store.list('channels').find(c => c.category === cat) || null
149
+ }
150
+
151
+ _block(run, step) {
152
+ run.status = 'blocked'
153
+ this._emit({ type: 'steward/run-blocked', runId: run.id, projectId: run.projectId, stepName: step.name })
154
+ }
155
+
156
+ async _maybeComplete(run, actor) {
157
+ if (run.status === 'blocked') return
158
+ if (!run.steps.every(s => DONE_STEP.includes(s.status))) return
159
+ run.status = 'done'; run.finishedAt = now()
160
+ const project = this.service.getProject(run.projectId)
161
+ const files = run.steps.flatMap(s => s.evidence?.files || [])
162
+ const release = {
163
+ id: genId('rel'), projectId: run.projectId, runId: run.id, version: run.version,
164
+ changelog: extractChangelog(project, run.version), artifacts: files.map(p => ({ path: p })), releasedAt: now(),
165
+ }
166
+ await this.store.create('releases', release, actor, 'release')
167
+ await this.service.transitionStage(run.projectId, 'operating', actor, 'run done').catch(() => {})
168
+ this._emit({ type: 'steward/run-finished', runId: run.id, projectId: run.projectId, status: 'done', version: run.version })
169
+ }
170
+ }
171
+
172
+ function publishCategory(action) {
173
+ const map = { 'npm-publish': 'npm-registry', 'mirror-verify': 'mirror', 'github-push': 'source-repo', 'github-release': 'source-repo', 'market-pr': 'plugin-market', 'itch-butler': 'game-store', 'docker-push': 'container-registry', 'web-deploy': 'web-deploy' }
174
+ return map[action]
175
+ }
176
+ function extractChangelog(project, version) {
177
+ try {
178
+ const cl = readFileSync(join(project.rootPath, 'CHANGELOG.md'), 'utf8')
179
+ const idx = cl.indexOf(version)
180
+ if (idx >= 0) return cl.slice(idx, idx + 500).trim()
181
+ return cl.slice(0, 500).trim() || `release ${version}`
182
+ } catch { return `release ${version}` }
183
+ }
184
+ export function semverCompare(a, b) {
185
+ const pa = String(a).split('.').map(n => parseInt(n, 10) || 0)
186
+ const pb = String(b).split('.').map(n => parseInt(n, 10) || 0)
187
+ for (let i = 0; i < 3; i++) { if ((pa[i] || 0) !== (pb[i] || 0)) return (pa[i] || 0) - (pb[i] || 0) }
188
+ return 0
189
+ }
190
+ export function bumpPatch(v) {
191
+ const p = String(v).split('.').map(n => parseInt(n, 10) || 0)
192
+ while (p.length < 3) p.push(0)
193
+ p[2] += 1
194
+ return p.join('.')
195
+ }
@@ -0,0 +1,51 @@
1
+ // M3 · auto-publish 对外发布执行链(07)。默认 dry-run(安全);真实执行需显式 enable + 凭据。
2
+ // 每动作返回 Evidence;结果可驱动 listing 迁移(hook)。
3
+ import { spawnSync } from 'node:child_process'
4
+
5
+ const now = () => new Date().toISOString()
6
+ const ev = (summary, extra = {}) => ({ kind: 'command', summary, at: now(), ...extra })
7
+
8
+ function runCmd(cmd, args, cwd) {
9
+ try {
10
+ const r = spawnSync(cmd, args, { cwd, encoding: 'utf8', timeout: 120000, shell: false })
11
+ const out = ((r.stdout || '') + (r.stderr || '')).slice(-4096)
12
+ return { code: r.status ?? 1, out }
13
+ } catch (e) { return { code: 1, out: String(e.message || e) } }
14
+ }
15
+
16
+ export const publishActions = {
17
+ 'npm-publish': { channelCategory: 'npm-registry', label: 'npm 发布' },
18
+ 'mirror-verify': { channelCategory: 'mirror', label: '镜像同步核验' },
19
+ 'github-push': { channelCategory: 'source-repo', label: 'GitHub 推送' },
20
+ 'github-release': { channelCategory: 'source-repo', label: 'GitHub Release' },
21
+ 'market-pr': { channelCategory: 'plugin-market', label: '市场 PR 提交/更新' },
22
+ 'itch-butler': { channelCategory: 'game-store', label: 'itch butler 上传' },
23
+ 'docker-push': { channelCategory: 'container-registry', label: 'Docker 推送' },
24
+ 'web-deploy': { channelCategory: 'web-deploy', label: 'Web 部署' },
25
+ }
26
+
27
+ // opts: { dryRun=true, credentials?, io? }
28
+ export function executePublish(action, { project, run, channel, dryRun = true, credentials } = {}) {
29
+ const meta = publishActions[action]
30
+ if (!meta) return ev(`未知发布动作 ${action}`, { exitCode: 1 })
31
+ // 受保护实例守卫
32
+ if (channel?.readOnly) {
33
+ const e = ev(`受保护实例只读,拒绝发布动作 ${action}`, { exitCode: 1 })
34
+ e.code = 'ILLEGAL_ON_PROTECTED'
35
+ return e
36
+ }
37
+ if (dryRun) {
38
+ return ev(`[dry-run] ${meta.label}:${project.name}@${run.version}(未真实执行)`, { exitCode: 0, command: `${action} ${project.name}@${run.version}`, dryRun: true })
39
+ }
40
+ // 真实执行(v1 仅 npm-publish / github-push 落地,其余需后续凭据接入)
41
+ const root = project.rootPath
42
+ if (action === 'npm-publish') {
43
+ const r = runCmd('npm', ['publish', '--registry=https://registry.npmjs.org', '--access=public'], root)
44
+ return ev(`npm publish ${r.code === 0 ? '成功' : '失败'}`, { exitCode: r.code, outputTail: r.out, command: 'npm publish --registry=https://registry.npmjs.org' })
45
+ }
46
+ if (action === 'github-push') {
47
+ const r = runCmd('git', ['push'], root)
48
+ return ev(`git push ${r.code === 0 ? '成功' : '失败'}`, { exitCode: r.code, outputTail: r.out, command: 'git push' })
49
+ }
50
+ return ev(`${meta.label}:真实执行待凭据接入(当前 dry-run 替代)`, { exitCode: 0, dryRun: true })
51
+ }
@@ -0,0 +1,121 @@
1
+ // 项目管家 · M2 Registry:项目注册表 + 生命周期阶段机 + 用户自选目录扫描(07 M2)
2
+ import { readdirSync, existsSync, statSync, readFileSync } from 'node:fs'
3
+ import { join, resolve } from 'node:path'
4
+ import { Project, stageTransitions } from './schemas.js'
5
+ import { genId, storeError } from './store.js'
6
+
7
+ const DEFAULT_EXCLUDE = new Set([
8
+ 'Games', 'SteamLibrary', 'WeGameApps', 'Program Files', 'Program Files (x86)', 'ProgramData',
9
+ 'Users', 'WeChat', 'douyin', 'hihun', 'Netease', 'DockerData', '.pnpm-store', 'qycache',
10
+ 'images', 'Bin', 'AndrowsData', 'Comfy-Desktop', 'DK4PK.Green.Edition', '309376410',
11
+ '迅雷下载', '达讯文件', '保单识别', 'node_modules', '.git', 'dist', 'build', '.cache',
12
+ ])
13
+ const isExcluded = (name, extra = []) => {
14
+ if (DEFAULT_EXCLUDE.has(name)) return true
15
+ if (name.startsWith('node-') || name.startsWith('Resource.') || name.startsWith('6.19')) return true
16
+ return extra.includes(name)
17
+ }
18
+
19
+ function detectType(dir) {
20
+ const has = f => existsSync(join(dir, f))
21
+ const evidence = []
22
+ if (has('cordis.patch.yml') && has('package.json')) { evidence.push('cordis.patch.yml', 'package.json'); return { type: 'dsh-plugin', evidence } }
23
+ if (has('project.godot')) { evidence.push('project.godot'); return { type: 'game', evidence } }
24
+ if (has('package.json')) {
25
+ evidence.push('package.json')
26
+ try {
27
+ const pkg = JSON.parse(readFileSafe(join(dir, 'package.json')))
28
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies }
29
+ if (deps && (deps.react || deps.vue || deps.next || deps.vite || deps.express || deps.fastify)) return { type: 'web-app', evidence }
30
+ } catch {}
31
+ return { type: 'web-app', evidence }
32
+ }
33
+ if (has('.git') || has('README.md')) { if (has('.git')) evidence.push('.git'); if (has('README.md')) evidence.push('README.md'); return { type: 'research', evidence } }
34
+ return null
35
+ }
36
+ function readFileSafe(p) { try { return readFileSync(p, 'utf8') } catch { return '' } }
37
+
38
+ export class Registry {
39
+ constructor(store) { this.store = store }
40
+
41
+ _normalizeRoot(rootPath) {
42
+ const r = resolve(rootPath)
43
+ if (!existsSync(r)) throw storeError('PATH_NOT_FOUND', `路径不存在:${r}`)
44
+ return r
45
+ }
46
+ _dupCheck(rootPath, exceptId) {
47
+ const lower = rootPath.toLowerCase().replace(/[\\/]+$/, '')
48
+ for (const p of this.store.list('projects')) {
49
+ if (p.id === exceptId) continue
50
+ if (p.rootPath.toLowerCase().replace(/[\\/]+$/, '') === lower) throw storeError('DUPLICATE', `根路径已登记:${p.name} (${p.id})`)
51
+ }
52
+ }
53
+
54
+ async register(input, actor = 'user') {
55
+ const rootPath = this._normalizeRoot(input.rootPath)
56
+ this._dupCheck(rootPath)
57
+ const now = new Date().toISOString()
58
+ const project = {
59
+ id: genId('p'), name: input.name, rootPath, type: input.type,
60
+ stage: 'developing', owner: input.owner || 'me', remote: input.remote,
61
+ tags: input.tags || [], notes: input.notes, templateId: input.templateId,
62
+ createdAt: now, updatedAt: now,
63
+ }
64
+ return this.store.create('projects', Project.parse(project), actor, 'register')
65
+ }
66
+
67
+ get(id) { return this.store.get('projects', id) }
68
+ list(filter) { return this.store.list('projects', filter) }
69
+
70
+ async update(id, patch, actor = 'user') {
71
+ return this.store.update('projects', id, d => {
72
+ Object.assign(d, patch, { updatedAt: new Date().toISOString() })
73
+ if (patch.rootPath) { d.rootPath = this._normalizeRoot(patch.rootPath); this._dupCheck(d.rootPath, id) }
74
+ }, actor, 'update')
75
+ }
76
+
77
+ async transitionStage(id, to, actor = 'user', reason) {
78
+ const p = this.get(id)
79
+ if (!p) throw storeError('NOT_FOUND', `项目 ${id} 不存在`)
80
+ const allowed = stageTransitions[p.stage] || []
81
+ if (!allowed.includes(to)) throw storeError('ILLEGAL_TRANSITION', `项目阶段不允许 ${p.stage} → ${to}`)
82
+ return this.store.update('projects', id, d => { d.stage = to; d.updatedAt = new Date().toISOString() }, actor, 'transition', reason)
83
+ }
84
+
85
+ // 用户自选目录扫描(R11/R15):BFS 深度≤2,特征识别,排除表,候选不落盘
86
+ scanCandidates(roots, opts = {}) {
87
+ const extraExclude = opts.exclude || []
88
+ const maxDepth = opts.maxDepth ?? 2
89
+ const candidates = []
90
+ const seen = new Set()
91
+ const existingRoots = new Set(this.store.list('projects').map(p => p.rootPath.toLowerCase().replace(/[\\/]+$/, '')))
92
+
93
+ const walk = (dir, depth) => {
94
+ let entries
95
+ try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return }
96
+ for (const ent of entries) {
97
+ if (!ent.isDirectory()) continue
98
+ if (isExcluded(ent.name, extraExclude)) continue
99
+ const full = join(dir, ent.name)
100
+ const key = full.toLowerCase().replace(/[\\/]+$/, '')
101
+ if (seen.has(key)) continue
102
+ seen.add(key)
103
+ const det = detectType(full)
104
+ if (det) {
105
+ candidates.push({
106
+ rootPath: full, name: ent.name, suggestedType: det.type, evidence: det.evidence,
107
+ alreadyRegistered: existingRoots.has(key),
108
+ })
109
+ // 命中特征即停(不再深入该项目内部)
110
+ continue
111
+ }
112
+ if (depth < maxDepth) walk(full, depth + 1)
113
+ }
114
+ }
115
+ for (const root of roots) {
116
+ const r = resolve(root)
117
+ if (existsSync(r) && statSync(r).isDirectory()) walk(r, 1)
118
+ }
119
+ return candidates
120
+ }
121
+ }
package/src/routes.js ADDED
@@ -0,0 +1,185 @@
1
+ // M5 · webServer 路由:供 Client 货架看板读取台账(只读为主 + 受控写)。
2
+ function sendJson(res, code, obj) {
3
+ res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8' })
4
+ res.end(JSON.stringify(obj))
5
+ }
6
+ function sameOrigin(req) {
7
+ const origin = req.headers.origin
8
+ if (!origin) return true
9
+ try { return new URL(origin).host === req.headers.host } catch { return false }
10
+ }
11
+ function query(req) { return new URL(req.url, 'http://localhost').searchParams }
12
+ async function body(req) {
13
+ const chunks = []
14
+ for await (const c of req) chunks.push(c)
15
+ try { return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}') } catch { return {} }
16
+ }
17
+
18
+ export function registerRoutes(ctx, service) {
19
+ const reg = (path, handler) => ctx.effect(() => {
20
+ try { return ctx.webServer.register({ kind: 'exact', path, handler }) }
21
+ catch { return () => {} }
22
+ })
23
+ const guard = (req, res) => { if (!sameOrigin(req)) { sendJson(res, 403, { error: 'cross-origin' }); return false } return true }
24
+
25
+ reg('/project-steward/api/overview', (req, res) => { if (!guard(req, res)) return; sendJson(res, 200, service.overview()) })
26
+ reg('/project-steward/api/summary', (req, res) => { if (!guard(req, res)) return; sendJson(res, 200, service.storeSummary()) })
27
+ reg('/project-steward/api/projects', (req, res) => {
28
+ if (!guard(req, res)) return
29
+ const q = query(req)
30
+ const filter = {}
31
+ if (q.get('type')) filter.type = q.get('type')
32
+ if (q.get('stage')) filter.stage = q.get('stage')
33
+ const projects = service.listProjects(filter).map(p => {
34
+ const listings = service.store.list('listings').filter(l => l.projectId === p.id)
35
+ const metrics = service.store.list('metrics').filter(m => m.projectId === p.id)
36
+ const latest = latestByChannel(metrics)
37
+ const sum = { downloads: 0, views: 0, comments: 0, revenue: 0 }
38
+ for (const m of latest) { sum.downloads += m.metrics.downloads || 0; sum.views += m.metrics.views || 0; sum.comments += m.metrics.comments || 0; sum.revenue += m.metrics.revenue || 0 }
39
+ const lastRelease = service.store.list('releases').filter(r => r.projectId === p.id).sort((a, b) => b.releasedAt.localeCompare(a.releasedAt))[0]
40
+ return { ...p, listings, metrics: sum, lastRelease, channels: listings.map(l => ({ channelId: l.channelId, status: l.status, platformUrl: l.platformUrl })) }
41
+ })
42
+ sendJson(res, 200, { projects, channels: service.store.list('channels') })
43
+ })
44
+ reg('/project-steward/api/project', (req, res) => {
45
+ if (!guard(req, res)) return
46
+ const id = query(req).get('id')
47
+ const p = service.getProject(id)
48
+ if (!p) return sendJson(res, 404, { error: 'not-found' })
49
+ sendJson(res, 200, {
50
+ project: p,
51
+ releases: service.store.list('releases').filter(r => r.projectId === id),
52
+ listings: service.store.list('listings').filter(l => l.projectId === id),
53
+ metrics: service.ops.listMetrics(id),
54
+ events: service.store.list('events').filter(e => e.projectId === id).sort((a, b) => b.at.localeCompare(a.at)).slice(0, 50),
55
+ reminders: service.store.list('reminders').filter(r => r.projectId === id),
56
+ runs: service.pipeline.listRuns(id),
57
+ marketReport: service.store.readMarketReport(id) || null,
58
+ })
59
+ })
60
+ reg('/project-steward/api/channels', (req, res) => { if (!guard(req, res)) return; sendJson(res, 200, { channels: service.listing.listChannels() }) })
61
+ reg('/project-steward/api/market/gaps', async (req, res) => {
62
+ if (!guard(req, res)) return
63
+ if (req.method === 'POST') {
64
+ try { const b = await body(req); const gaps = await service.market.gaps(b.channelIds, 'user'); sendJson(res, 200, { ok: true, gaps }) }
65
+ catch (e) { sendJson(res, 200, { ok: false, error: { code: e.code || 'ERROR', message: String(e.message || e) } }) }
66
+ } else {
67
+ sendJson(res, 200, { gaps: service.store.list('market-gaps').sort((a, b) => b.gapScore - a.gapScore) })
68
+ }
69
+ })
70
+ reg('/project-steward/api/market/report', (req, res) => { if (!guard(req, res)) return; sendJson(res, 200, { report: service.store.readMarketReport(query(req).get('id')) || null }) })
71
+ reg('/project-steward/api/market/report', (req, res) => { if (!guard(req, res)) return; sendJson(res, 200, { report: service.store.readMarketReport(query(req).get('id')) || null }) })
72
+
73
+ // 受控写
74
+ reg('/project-steward/api/collect', async (req, res) => {
75
+ if (!guard(req, res)) return
76
+ const b = await body(req)
77
+ try { const runs = await service.collector.collectNow(b.channelId); sendJson(res, 200, { ok: true, runs }) }
78
+ catch (e) { sendJson(res, 200, { ok: false, error: { code: e.code || 'ERROR', message: String(e.message || e) } }) }
79
+ })
80
+ reg('/project-steward/api/market/scan', async (req, res) => {
81
+ if (!guard(req, res)) return
82
+ const b = await body(req)
83
+ try { const reports = await service.market.scan(b.projectId); sendJson(res, 200, { ok: true, reports }) }
84
+ catch (e) { sendJson(res, 200, { ok: false, error: { code: e.code || 'ERROR', message: String(e.message || e) } }) }
85
+ })
86
+ reg('/project-steward/api/release/start', async (req, res) => {
87
+ if (!guard(req, res)) return
88
+ const b = await body(req)
89
+ try { const run = await service.pipeline.startRun(b, 'user'); sendJson(res, 200, { ok: true, run }) }
90
+ catch (e) { sendJson(res, 200, { ok: false, error: { code: e.code || 'ERROR', message: String(e.message || e) } }) }
91
+ })
92
+ reg('/project-steward/api/scan', async (req, res) => {
93
+ if (!guard(req, res)) return
94
+ const b = await body(req)
95
+ try {
96
+ const roots = Array.isArray(b.roots) && b.roots.length ? b.roots : ['E:\\']
97
+ const candidates = service.scanCandidates(roots, { exclude: b.exclude })
98
+ sendJson(res, 200, { ok: true, candidates })
99
+ } catch (e) { sendJson(res, 200, { ok: false, error: { code: e.code || 'ERROR', message: String(e.message || e) } }) }
100
+ })
101
+ reg('/project-steward/api/register', async (req, res) => {
102
+ if (!guard(req, res)) return
103
+ const b = await body(req)
104
+ try { const project = await service.registerProject(b, 'user'); sendJson(res, 200, { ok: true, project }) }
105
+ catch (e) { sendJson(res, 200, { ok: false, error: { code: e.code || 'ERROR', message: String(e.message || e) } }) }
106
+ })
107
+ reg('/project-steward/api/release/record', async (req, res) => {
108
+ if (!guard(req, res)) return
109
+ const b = await body(req)
110
+ try {
111
+ const { genId } = await import('./store.js')
112
+ const rel = { id: genId('rel'), projectId: b.projectId, runId: b.runId || 'run-manual-record', version: b.version, changelog: b.changelog || ('release ' + b.version), artifacts: b.artifacts || [], releasedAt: b.releasedAt || new Date().toISOString() }
113
+ const release = await service.store.create('releases', rel, 'user', 'release-record')
114
+ sendJson(res, 200, { ok: true, release })
115
+ } catch (e) { sendJson(res, 200, { ok: false, error: { code: e.code || 'ERROR', message: String(e.message || e) } }) }
116
+ })
117
+ reg('/project-steward/api/listing/create', async (req, res) => {
118
+ if (!guard(req, res)) return
119
+ const b = await body(req)
120
+ try { const listing = await service.listing.createListing(b, 'user'); sendJson(res, 200, { ok: true, listing }) }
121
+ catch (e) { sendJson(res, 200, { ok: false, error: { code: e.code || 'ERROR', message: String(e.message || e) } }) }
122
+ })
123
+ reg('/project-steward/api/listing/update', async (req, res) => {
124
+ if (!guard(req, res)) return
125
+ const b = await body(req)
126
+ try { const listing = await service.listing.transitionListing(b.listingId, b.to, { actor: 'user', note: b.note, platformUrl: b.platformUrl, waive: b.waive }); sendJson(res, 200, { ok: true, listing }) }
127
+ catch (e) { sendJson(res, 200, { ok: false, error: { code: e.code || 'ERROR', message: String(e.message || e) } }) }
128
+ })
129
+ reg('/project-steward/api/doc/check', (req, res) => {
130
+ if (!guard(req, res)) return
131
+ try { sendJson(res, 200, { ok: true, check: service.docs.docCheck(query(req).get('id')) }) }
132
+ catch (e) { sendJson(res, 200, { ok: false, error: { code: e.code || 'ERROR', message: String(e.message || e) } }) }
133
+ })
134
+ reg('/project-steward/api/doc/channel-check', (req, res) => {
135
+ if (!guard(req, res)) return
136
+ const q = query(req)
137
+ try { sendJson(res, 200, { ok: true, check: service.docs.channelCheck(q.get('id'), q.get('channel')) }) }
138
+ catch (e) { sendJson(res, 200, { ok: false, error: { code: e.code || 'ERROR', message: String(e.message || e) } }) }
139
+ })
140
+ reg('/project-steward/api/doc/complete', async (req, res) => {
141
+ if (!guard(req, res)) return
142
+ const b = await body(req)
143
+ try { sendJson(res, 200, { ok: true, result: service.docs.docCompleteChannel(b.projectId, b.channelId, b) }) }
144
+ catch (e) { sendJson(res, 200, { ok: false, error: { code: e.code || 'ERROR', message: String(e.message || e) } }) }
145
+ })
146
+ reg('/project-steward/api/doc/scaffold', async (req, res) => {
147
+ if (!guard(req, res)) return
148
+ const b = await body(req)
149
+ try { sendJson(res, 200, { ok: true, result: service.docs.docScaffold(b.projectId, b) }) }
150
+ catch (e) { sendJson(res, 200, { ok: false, error: { code: e.code || 'ERROR', message: String(e.message || e) } }) }
151
+ })
152
+ reg('/project-steward/api/doc/update-image', async (req, res) => {
153
+ if (!guard(req, res)) return
154
+ const b = await body(req)
155
+ try { sendJson(res, 200, { ok: true, result: service.docs.generateUpdateImage(b.projectId, b.version, b) }) }
156
+ catch (e) { sendJson(res, 200, { ok: false, error: { code: e.code || 'ERROR', message: String(e.message || e) } }) }
157
+ })
158
+ reg('/project-steward/api/maintenance', (req, res) => {
159
+ if (!guard(req, res)) return
160
+ try { sendJson(res, 200, { ok: true, report: service.docs.maintenanceReport() }) }
161
+ catch (e) { sendJson(res, 200, { ok: false, error: { code: e.code || 'ERROR', message: String(e.message || e) } }) }
162
+ })
163
+ reg('/project-steward/api/channel/scan', async (req, res) => {
164
+ if (!guard(req, res)) return
165
+ const b = await body(req)
166
+ try { sendJson(res, 200, { ok: true, candidates: await service.channelImport.scan(b) }) }
167
+ catch (e) { sendJson(res, 200, { ok: false, error: { code: e.code || 'ERROR', message: String(e.message || e) } }) }
168
+ })
169
+ reg('/project-steward/api/channel/import', async (req, res) => {
170
+ if (!guard(req, res)) return
171
+ const b = await body(req)
172
+ try { sendJson(res, 200, { ok: true, result: await service.channelImport.importProduct(b.candidate, 'user') }) }
173
+ catch (e) { sendJson(res, 200, { ok: false, error: { code: e.code || 'ERROR', message: String(e.message || e) } }) }
174
+ })
175
+ }
176
+
177
+ function latestByChannel(metrics) {
178
+ const map = new Map()
179
+ for (const m of metrics) {
180
+ const key = m.channelId || '_'
181
+ const cur = map.get(key)
182
+ if (!cur || m.date > cur.date) map.set(key, m)
183
+ }
184
+ return [...map.values()]
185
+ }