@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.
@@ -0,0 +1,159 @@
1
+ // M14 · Market 分析:多维对比 + 优势研判 + 市场空白(03§6b / FR6)。
2
+ import { MarketReport, MarketGap, Verdict } from '../schemas.js'
3
+ import { genId, storeError } from '../store.js'
4
+ import { discoverCompetitors } from './discover.js'
5
+ import { buildComparison } from './features.js'
6
+ import { readFileSync } from 'node:fs'
7
+ import { join } from 'node:path'
8
+
9
+ const now = () => new Date().toISOString()
10
+ const defaultFetch = (...a) => globalThis.fetch(...a)
11
+ const median = arr => { if (!arr.length) return 0; const s = [...arr].sort((a, b) => a - b); const m = Math.floor(s.length / 2); return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2 }
12
+
13
+ export class Market {
14
+ constructor(service, opts = {}) {
15
+ this.service = service
16
+ this.store = service.store
17
+ this.discover = opts.discover || discoverCompetitors
18
+ this.fetch = opts.fetch
19
+ this.demandSignals = opts.demandSignals || {}
20
+ }
21
+
22
+ async scan(projectId, actor = 'agent') {
23
+ const projects = projectId ? [this.service.getProject(projectId)].filter(Boolean) : this.service.listProjects()
24
+ const reports = []
25
+ for (const p of projects) reports.push(await this.compare(p.id, actor))
26
+ return reports
27
+ }
28
+
29
+ async compare(projectId, actor = 'agent') {
30
+ const project = this.service.getProject(projectId)
31
+ if (!project) throw storeError('NOT_FOUND', `项目 ${projectId} 不存在`)
32
+ let competitors
33
+ const existing = this.store.readMarketReport(projectId)
34
+ const raw = await this.discover(project, { fetch: this.fetch })
35
+ competitors = raw.map(c => ({
36
+ id: c.id || genId('mc'), projectId, name: c.name, url: c.url,
37
+ stars: c.stars, downloads: c.downloads, price: c.price, lastUpdate: c.lastUpdate || c.date,
38
+ features: c.features || c.tags || [], tags: c.tags || [], rating: c.rating, fetchedAt: c.fetchedAt || now(),
39
+ }))
40
+ // 本项目热度(取最新 metrics)
41
+ const ms = this.store.list('metrics').filter(m => m.projectId === projectId)
42
+ const myStars = ms.reduce((a, m) => a + (m.metrics.views || 0), 0)
43
+ const myDownloads = ms.reduce((a, m) => a + (m.metrics.downloads || 0), 0)
44
+ const compStars = median(competitors.map(c => c.stars || 0))
45
+ const compDownloads = median(competitors.map(c => c.downloads || 0))
46
+ // 多维评分(0–1,缺失标 unknown→0.5 中性,不臆断)
47
+ const score = (mine, theirs) => theirs > 0 ? Math.min(1, mine / theirs) : 0.5
48
+ const dimensions = {
49
+ popularity: round(score(myStars, compStars)),
50
+ downloads: round(score(myDownloads, compDownloads)),
51
+ activity: project.lastReleaseAt ? 0.7 : 0.4,
52
+ differentiation: round(uniqueFeatureRatio(project, competitors)),
53
+ }
54
+ const avg = round(Object.values(dimensions).reduce((a, b) => a + b, 0) / Object.values(dimensions).length)
55
+ const crowded = competitors.length >= 5
56
+ let verdict
57
+ if (avg >= 0.6 || dimensions.differentiation >= 0.6) verdict = 'worth-continuing'
58
+ else if (crowded && avg < 0.35) verdict = 'red-ocean-caution'
59
+ else verdict = 'needs-differentiation'
60
+ const strengths = [], weaknesses = []
61
+ if (dimensions.popularity >= 0.6) strengths.push('热度领先同类中位数')
62
+ if (dimensions.differentiation >= 0.6) strengths.push('具备差异化特性')
63
+ if (dimensions.downloads < 0.4) weaknesses.push('下载量低于同类中位数')
64
+ if (crowded) weaknesses.push(`同类竞品 ${competitors.length} 个,市场拥挤`)
65
+ if (!project.lastReleaseAt) weaknesses.push('尚无发布记录')
66
+ const summary = `对比 ${competitors.length} 个同类竞品,综合得分 ${avg}。研判:${verdictLabel(verdict)}。证据驱动,供店主决策,不替决策。`
67
+ // R32:按本项目功能逐项对比 + 多维雷达图
68
+ let featureComparison
69
+ try {
70
+ const myReadme = readFileSync(join(project.rootPath, 'README.md'), 'utf8')
71
+ featureComparison = await buildComparison(project, myReadme, competitors, { fetch: this.fetch, limit: 5 })
72
+ // 注入我的真实热度到雷达首系列
73
+ if (featureComparison.radar?.series?.[0]) {
74
+ featureComparison.radar.series[0].values[1] = round(Math.min(1, myStars / Math.max(1, compStars)))
75
+ }
76
+ } catch { featureComparison = undefined }
77
+ const report = MarketReport.parse({
78
+ projectId, competitors: competitors.map(stripPrivate), dimensions, verdict,
79
+ strengths, weaknesses, summary, generatedAt: now(), source: 'auto', featureComparison,
80
+ })
81
+ this.store.writeMarketReport(report)
82
+ this.service._broadcast({ type: 'steward/changed', entity: 'market-report', entityId: projectId, action: 'compare' })
83
+ return report
84
+ }
85
+
86
+ async gaps(channelIds, actor = 'agent', opts = {}) {
87
+ // R34:真实市场空白研判——按细分 niche 实搜平台供给+需求代理+竞争强度,多因子打分(非简单比值)。
88
+ const f = this.fetch || defaultFetch
89
+ const niches = opts.niches || this._defaultNiches()
90
+ // R36:每次重算清空旧空白记录(避免旧假数据/重复累积残留)
91
+ this.store.data['market-gaps'].clear()
92
+ this.store._writeCollection('market-gaps')
93
+ const gaps = []
94
+ for (const niche of niches.slice(0, opts.limit || 8)) {
95
+ const probe = await this._probeNiche(niche, f)
96
+ const supply = probe.npmTotal + probe.ghTotal
97
+ const demand = probe.topStarsSum // 需求代理:头部产品 star 总量(已被验证的兴趣)
98
+ const competition = probe.avgStars // 竞争强度:头部平均 star
99
+ const demandFactor = Math.min(1, demand / 1000)
100
+ const scarcityFactor = 1 / Math.log10(supply + 10)
101
+ const weaknessFactor = 1 - Math.min(1, competition / 500)
102
+ const gapScore = round(demandFactor * scarcityFactor * weaknessFactor * 100, 1)
103
+ const verdict = gapScore >= 25 ? '空白机会显著' : gapScore >= 10 ? '潜在机会' : demand < 50 ? '需求未验证' : '竞争饱和'
104
+ const gap = MarketGap.parse({
105
+ id: genId('mg'), category: niche, niche, channelIds: [],
106
+ supplyCount: supply, demandSignal: demand, competition: round(competition, 1), gapScore,
107
+ demandBasis: `npm 供给 ${probe.npmTotal} + GitHub 供给 ${probe.ghTotal};头部 star 合计 ${demand},平均 ${round(competition, 1)}`,
108
+ opportunity: `「${niche}」${verdict}:市场供给 ${supply} 个,头部需求信号 ${demand} star,竞争强度 ${round(competition, 1)}。${gapScore >= 10 ? '供给相对稀缺或 incumbent 较弱,可切入。' : '需求未验证或竞争饱和,慎入。'}`,
109
+ examples: probe.evidence.map(e => e.name), evidence: probe.evidence, fetchedAt: now(),
110
+ })
111
+ await this.store.create('market-gaps', gap, actor, 'market-gap')
112
+ gaps.push(gap)
113
+ }
114
+ return gaps.sort((a, b) => b.gapScore - a.gapScore)
115
+ }
116
+
117
+ _defaultNiches() {
118
+ // 结合本店项目领域 + 通用热门细分
119
+ const base = ['dsh plugin', 'project board kanban', 'insurance claim assistant', 'cargo insurance', 'underwriting assistant', 'godot strategy game', 'ai agent tool', 'llm workflow automation']
120
+ const fromProjects = this.service.listProjects().flatMap(p => (p.tags || []).slice(0, 1))
121
+ return [...new Set([...fromProjects, ...base])]
122
+ }
123
+
124
+ async _probeNiche(niche, f) {
125
+ let npmTotal = 0, ghTotal = 0, topStarsSum = 0, avgStars = 0
126
+ const evidence = []
127
+ try {
128
+ const r = await f(`https://registry.npmjs.org/-/v1/search?text=${encodeURIComponent(niche)}&size=5`)
129
+ const j = await r.json()
130
+ npmTotal = j.total || 0
131
+ for (const o of (j.objects || []).slice(0, 3)) {
132
+ const p = o.package || {}
133
+ evidence.push({ name: p.name, url: p.links?.npm, downloads: undefined })
134
+ }
135
+ } catch {}
136
+ try {
137
+ const r = await f(`https://api.github.com/search/repositories?q=${encodeURIComponent(niche)}&per_page=5&sort=stars`, { headers: { Accept: 'application/vnd.github+json' } })
138
+ const j = await r.json()
139
+ ghTotal = j.total_count || 0
140
+ const items = j.items || []
141
+ const stars = items.map(x => x.stargazers_count || 0)
142
+ topStarsSum = stars.slice(0, 3).reduce((a, b) => a + b, 0)
143
+ avgStars = stars.length ? stars.reduce((a, b) => a + b, 0) / stars.length : 0
144
+ for (const x of items.slice(0, 3)) evidence.push({ name: x.full_name, stars: x.stargazers_count, url: x.html_url })
145
+ } catch {}
146
+ return { npmTotal, ghTotal, topStarsSum, avgStars, evidence: evidence.slice(0, 5) }
147
+ }
148
+ }
149
+
150
+ function uniqueFeatureRatio(project, competitors) {
151
+ const myTags = new Set(project.tags || [])
152
+ if (!myTags.size) return 0.5
153
+ const compTags = new Set(competitors.flatMap(c => c.tags || []))
154
+ const unique = [...myTags].filter(t => !compTags.has(t)).length
155
+ return unique / myTags.size
156
+ }
157
+ function stripPrivate(c) { const { _description, ...rest } = c; return rest }
158
+ function round(n) { return Math.round(n * 100) / 100 }
159
+ function verdictLabel(v) { return { 'worth-continuing': '值得继续', 'needs-differentiation': '需差异化', 'red-ocean-caution': '红海慎入' }[v] }
@@ -0,0 +1,52 @@
1
+ // M14 · 竞品发现适配器(03§6b / 07)。可注入 fetch 测试不联网。竞品文本为不可信数据。
2
+ const defaultFetch = (...a) => globalThis.fetch(...a)
3
+ const now = () => new Date().toISOString()
4
+
5
+ export async function discoverCompetitors(project, opts = {}) {
6
+ const f = opts.fetch || defaultFetch
7
+ const out = []
8
+ const keyword = opts.keyword || project.name
9
+ if (project.type === 'dsh-plugin' || project.type === 'web-app' || project.type === 'engine') {
10
+ // npm search
11
+ try {
12
+ const r = await f(`https://registry.npmjs.org/-/v1/search?text=${encodeURIComponent(keyword)}&size=10`)
13
+ const j = await r.json()
14
+ for (const o of j.objects || []) {
15
+ const p = o.package || {}
16
+ if (p.name === project.name) continue
17
+ out.push({ name: p.name, url: p.links?.npm || `https://npmjs.com/package/${p.name}`, description: p.description || '', keywords: p.keywords || [], date: p.date })
18
+ }
19
+ } catch {}
20
+ // GitHub topic/search
21
+ try {
22
+ const r = await f(`https://api.github.com/search/repositories?q=${encodeURIComponent(keyword)}&per_page=10`, { headers: opts.githubToken ? { Authorization: `Bearer ${opts.githubToken}` } : {} })
23
+ const j = await r.json()
24
+ for (const repo of j.items || []) {
25
+ out.push({ name: repo.full_name, url: repo.html_url, stars: repo.stargazers_count, downloads: repo.forks_count, description: repo.description || '', tags: repo.topics || [], lastUpdate: repo.pushed_at })
26
+ }
27
+ } catch {}
28
+ } else if (project.type === 'game') {
29
+ // itch/Steam 标签浏览占位(需 API/凭据)
30
+ try {
31
+ const r = await f(`https://itch.io/api/1/x/games?search=${encodeURIComponent(keyword)}`)
32
+ const j = await r.json()
33
+ for (const g of j.games || []) out.push({ name: g.title, url: g.url, description: g.short_text || '', tags: g.tags || [] })
34
+ } catch {}
35
+ }
36
+ // 标准化为 MarketCompetitor 形状(去重 by url)
37
+ const seen = new Set()
38
+ const competitors = []
39
+ for (const c of out) {
40
+ if (!c.url || seen.has(c.url)) continue
41
+ seen.add(c.url)
42
+ competitors.push({
43
+ id: `mc-${Date.now().toString(36)}-${competitors.length.toString(36).padStart(4, '0')}`,
44
+ projectId: project.id, name: c.name, url: c.url,
45
+ stars: c.stars, downloads: c.downloads, price: c.price,
46
+ lastUpdate: c.lastUpdate || c.date, features: c.keywords || c.tags || [],
47
+ tags: c.tags || [], rating: c.rating, fetchedAt: now(),
48
+ _description: c.description,
49
+ })
50
+ }
51
+ return competitors
52
+ }
@@ -0,0 +1,118 @@
1
+ // M14 · 功能逐项对比 + 多维雷达图数据(R32)。按本项目功能逐项对比竞品。
2
+ const defaultFetch = (...a) => globalThis.fetch(...a)
3
+
4
+ // 能力关键词字典(中英),用于从 README/描述识别功能
5
+ export const CAPS = {
6
+ '看板/任务管理': ['看板', '任务', 'task', 'board', 'kanban', 'todo'],
7
+ '进度/ETA': ['进度', 'eta', 'progress', '燃尽', 'burndown', '百分比'],
8
+ '依赖图/DAG': ['依赖', 'dag', '关键路径', 'critical path', 'dependency'],
9
+ '代码下钻/diff': ['代码', 'code', 'diff', '编辑卡', '下钻'],
10
+ '导游/解说': ['导游', 'guide', '解说', '因果'],
11
+ '语音交互': ['语音', 'voice', 'speech', '播报', 'tts'],
12
+ '实时刷新': ['实时', 'real-time', 'realtime', '即时', 'live'],
13
+ '蓝图/结构化': ['蓝图', 'blueprint', '结构化', '分解'],
14
+ '甘特图': ['甘特', 'gantt'],
15
+ '数据可视化': ['可视化', 'chart', '图表', 'svg', '可视化'],
16
+ '人工确认闸门': ['确认', '闸门', '审批', 'confirm', '证据'],
17
+ '重启恢复': ['重启', '恢复', 'fork', '重放', 'replay'],
18
+ }
19
+
20
+ export function detectCaps(text) {
21
+ const t = (text || '').toLowerCase()
22
+ const present = {}
23
+ for (const [cap, kws] of Object.entries(CAPS)) {
24
+ present[cap] = kws.some(k => t.includes(k.toLowerCase()))
25
+ }
26
+ return present
27
+ }
28
+
29
+ // 提取本项目 README 的功能特性 bullet 标题(按我的功能逐项对比)
30
+ export function extractMyFeatures(readme) {
31
+ const feats = []
32
+ const sec = (readme || '').split(/##\s*功能特性|##\s*Features/i)[1]
33
+ if (sec) {
34
+ const body = sec.split(/\n##\s/)[0]
35
+ for (const line of body.split('\n')) {
36
+ const m = line.match(/^[-*]\s*\*\*(.+?)\*\*/) || line.match(/^[-*]\s*(.+?)[::]/)
37
+ if (m) feats.push(m[1].trim())
38
+ }
39
+ }
40
+ return feats
41
+ }
42
+
43
+ async function fetchCompetitorText(c, f) {
44
+ try {
45
+ // npm 包(name 不含 / 或含 scope)→ registry readme
46
+ if (!c.url?.includes('github.com') && c.name) {
47
+ const r = await f(`https://registry.npmjs.org/${encodeURIComponent(c.name)}`)
48
+ const j = await r.json()
49
+ if (j.readme) return j.readme
50
+ }
51
+ // GitHub repo → raw README
52
+ const gh = c.url?.match(/github\.com\/([^/]+\/[^/]+)/)
53
+ if (gh) {
54
+ for (const br of ['main', 'master']) {
55
+ const r = await f(`https://raw.githubusercontent.com/${gh[1]}/${br}/README.md`)
56
+ if (r.ok) return await r.text()
57
+ }
58
+ }
59
+ } catch {}
60
+ return c._description || ''
61
+ }
62
+
63
+ const recencyScore = iso => { if (!iso) return 0.3; const days = (Date.now() - Date.parse(iso)) / 86400000; return Math.max(0.1, Math.min(1, 1 - days / 180)) }
64
+
65
+ // 构建功能逐项对比矩阵 + 雷达图数据
66
+ export async function buildComparison(project, myReadme, competitors, opts = {}) {
67
+ const f = opts.fetch || defaultFetch
68
+ const top = competitors.slice(0, opts.limit || 5)
69
+ const myCaps = detectCaps(myReadme + ' ' + (project.notes || '') + ' ' + (project.tags || []).join(' '))
70
+ const myFeatures = extractMyFeatures(myReadme)
71
+ // 对比维度:本项目拥有的能力 + 竞品额外能力(取并集,但优先我的功能)
72
+ const myCapNames = Object.keys(myCaps).filter(k => myCaps[k])
73
+ const compTexts = []
74
+ for (const c of top) compTexts.push({ c, text: await fetchCompetitorText(c, f) })
75
+ const compCaps = compTexts.map(({ c, text }) => ({ c, caps: detectCaps(text + ' ' + (c.tags || []).join(' ')), textLen: (text || '').length }))
76
+ // 矩阵行:我的功能能力(逐项)+ 竞品独有高频能力
77
+ const allCapNames = Object.keys(CAPS)
78
+ const rows = myCapNames.length ? myCapNames : allCapNames.filter(k => myCaps[k])
79
+ const matrix = [
80
+ { name: project.name + '(我的)', isMine: true, caps: myCaps, stars: null, downloads: null },
81
+ ...compCaps.map(({ c, caps }) => ({ name: c.name, isMine: false, caps, stars: c.stars, downloads: c.downloads, url: c.url })),
82
+ ]
83
+ // 雷达维度(0–1):功能广度/热度/活跃度/文档质量/差异化
84
+ const maxStars = Math.max(1, ...compCaps.map(x => x.c.stars || 0))
85
+ const maxDl = Math.max(1, ...compCaps.map(x => x.c.downloads || 0))
86
+ const myCapCount = myCapNames.length
87
+ const radarDimensions = ['功能广度', '热度', '活跃度', '文档质量', '差异化']
88
+ const series = []
89
+ // 我的系列
90
+ const myUnique = myCapNames.filter(k => !compCaps.some(x => x.caps[k])).length
91
+ series.push({
92
+ name: project.name, isMine: true,
93
+ values: [
94
+ round(myCapCount / allCapNames.length),
95
+ 0.5, // 我的热度需 metrics,下方 analyze 注入
96
+ recencyScore(project.lastReleaseAt),
97
+ round(Math.min(1, (myReadme || '').length / 2000)),
98
+ round(myCapCount ? myUnique / myCapCount : 0.5),
99
+ ],
100
+ })
101
+ for (const { c, caps, textLen } of compCaps) {
102
+ const capCount = Object.keys(caps).filter(k => caps[k]).length
103
+ const unique = Object.keys(caps).filter(k => caps[k] && !myCaps[k]).length
104
+ series.push({
105
+ name: c.name, isMine: false,
106
+ values: [
107
+ round(capCount / allCapNames.length),
108
+ round(Math.min(1, (c.stars || 0) / maxStars)),
109
+ recencyScore(c.lastUpdate),
110
+ round(Math.min(1, textLen / 2000)),
111
+ round(capCount ? unique / capCount : 0),
112
+ ],
113
+ })
114
+ }
115
+ return { myFeatures, rows, matrix, radar: { dimensions: radarDimensions, series } }
116
+ }
117
+
118
+ const round = n => Math.round(n * 100) / 100
@@ -0,0 +1,34 @@
1
+ // M14 · market_* Agent 工具(06§2)。集成时由 lead 并入 buildTools。
2
+ import { inputs } from '../schemas.js'
3
+
4
+ const ok = data => ({ ok: true, data })
5
+ const fail = e => ({ ok: false, error: { code: e.code || 'ERROR', message: String(e.message || e) } })
6
+ const guard = (schema, args, fn) => {
7
+ const p = schema.safeParse(args || {})
8
+ if (!p.success) return fail({ code: 'INVALID_INPUT', message: p.error.issues.map(i => `${i.path.join('.')}: ${i.message}`).join('; ') })
9
+ return Promise.resolve(fn(p.data)).then(ok, fail)
10
+ }
11
+ const need = service => { if (!service.market) throw { code: 'NOT_READY', message: 'market 未挂载' }; return service.market }
12
+
13
+ export function buildMarketTools(service) {
14
+ return [
15
+ {
16
+ name: 'steward_market_scan',
17
+ description: '竞品发现+对比(缺省全项目)。',
18
+ parameters: { type: 'object', properties: { projectId: { type: 'string' } }, additionalProperties: false },
19
+ execute: async args => guard(inputs.marketScan, args, d => need(service).scan(d.projectId, 'agent')),
20
+ },
21
+ {
22
+ name: 'steward_market_compare',
23
+ description: '单项目竞品对比+优势研判(worth-continuing/needs-differentiation/red-ocean-caution)。',
24
+ parameters: { type: 'object', properties: { projectId: { type: 'string' } }, required: ['projectId'], additionalProperties: false },
25
+ execute: async args => guard(inputs.marketCompare, args, d => need(service).compare(d.projectId, 'agent')),
26
+ },
27
+ {
28
+ name: 'steward_market_gaps',
29
+ description: '市场空白发现(供给×需求→gapScore 排序)。',
30
+ parameters: { type: 'object', properties: { channelIds: { type: 'array', items: { type: 'string' } } }, additionalProperties: false },
31
+ execute: async args => guard(inputs.marketGaps, args, d => need(service).gaps(d.channelIds, 'agent')),
32
+ },
33
+ ]
34
+ }
@@ -0,0 +1,70 @@
1
+ // M6/M13 · ops/collect Agent 工具(06§2)。集成时由 lead 并入 buildTools。
2
+ import { inputs } from './schemas.js'
3
+
4
+ const ok = data => ({ ok: true, data })
5
+ const fail = e => ({ ok: false, error: { code: e.code || 'ERROR', message: String(e.message || e) } })
6
+ const guard = (schema, args, fn) => {
7
+ const p = schema.safeParse(args || {})
8
+ if (!p.success) return fail({ code: 'INVALID_INPUT', message: p.error.issues.map(i => `${i.path.join('.')}: ${i.message}`).join('; ') })
9
+ return Promise.resolve(fn(p.data)).then(ok, fail)
10
+ }
11
+
12
+ export function buildOpsTools(service) {
13
+ const ops = () => { if (!service.ops) throw { code: 'NOT_READY', message: 'ops 未挂载' }; return service.ops }
14
+ const col = () => { if (!service.collector) throw { code: 'NOT_READY', message: 'collector 未挂载' }; return service.collector }
15
+ return [
16
+ {
17
+ name: 'steward_metric_add',
18
+ description: '录入运营指标快照(同日同键冲突需 overwrite)。',
19
+ parameters: { type: 'object', properties: { projectId: { type: 'string' }, channelId: { type: 'string' }, date: { type: 'string' }, metrics: { type: 'object' }, overwrite: { type: 'boolean' } }, required: ['projectId', 'date', 'metrics'], additionalProperties: false },
20
+ execute: async args => guard(inputs.metricAdd, args, d => ops().addMetric(d, 'agent')),
21
+ },
22
+ {
23
+ name: 'steward_event_add',
24
+ description: '记录运营事件(incident/notice/complaint/milestone/comment/payment)。',
25
+ parameters: { type: 'object', properties: { projectId: { type: 'string' }, kind: { type: 'string' }, severity: { type: 'string' }, text: { type: 'string' }, listingId: { type: 'string' } }, required: ['projectId', 'kind', 'severity', 'text'], additionalProperties: false },
26
+ execute: async args => guard(inputs.eventAdd, args, d => ops().addEvent(d, 'agent')),
27
+ },
28
+ {
29
+ name: 'steward_reminder_add',
30
+ description: '创建到期提醒,返回 suggestedSchedule(由 Agent 调 schedule_create 后 bind)。',
31
+ parameters: { type: 'object', properties: { projectId: { type: 'string' }, kind: { type: 'string' }, dueAt: { type: 'string' }, leadDays: { type: 'integer' }, note: { type: 'string' } }, required: ['projectId', 'kind', 'dueAt', 'note'], additionalProperties: false },
32
+ execute: async args => guard(inputs.reminderAdd, args, d => ops().addReminder(d, 'agent')),
33
+ },
34
+ {
35
+ name: 'steward_reminder_bind',
36
+ description: '把 DSH schedule 任务 id 绑定到提醒。',
37
+ parameters: { type: 'object', properties: { reminderId: { type: 'string' }, scheduleId: { type: 'string' } }, required: ['reminderId', 'scheduleId'], additionalProperties: false },
38
+ execute: async args => guard(inputs.reminderBind, args, d => ops().bindSchedule(d.reminderId, d.scheduleId, 'agent')),
39
+ },
40
+ {
41
+ name: 'steward_comment_list',
42
+ description: '查看留言(kind=comment 事件)。只读。',
43
+ parameters: { type: 'object', properties: { projectId: { type: 'string' }, listingId: { type: 'string' }, limit: { type: 'integer' } }, additionalProperties: false },
44
+ execute: async args => ok(ops().commentList(args || {})),
45
+ },
46
+ {
47
+ name: 'steward_collect',
48
+ description: '手动触发运营数据采集(默认全 active 渠道)。',
49
+ parameters: { type: 'object', properties: { channelId: { type: 'string' } }, additionalProperties: false },
50
+ execute: async args => Promise.resolve(col().collectNow(args?.channelId)).then(ok, fail),
51
+ },
52
+ {
53
+ name: 'steward_collect_interval',
54
+ description: '调整定时采集间隔(分钟,5–1440)。',
55
+ parameters: { type: 'object', properties: { minutes: { type: 'integer' } }, required: ['minutes'], additionalProperties: false },
56
+ execute: async args => {
57
+ const m = args.minutes
58
+ if (!Number.isInteger(m) || m < 5 || m > 1440) return fail({ code: 'INVALID_INPUT', message: 'minutes 须 5–1440' })
59
+ col().start(m)
60
+ return ok({ intervalMinutes: m })
61
+ },
62
+ },
63
+ {
64
+ name: 'steward_store_summary',
65
+ description: '全店经营汇总:总下载/浏览/留言/收入 + 逐商品。只读。',
66
+ parameters: { type: 'object', properties: {}, additionalProperties: false },
67
+ execute: async () => ok(service.storeSummary()),
68
+ },
69
+ ]
70
+ }
package/src/ops.js ADDED
@@ -0,0 +1,65 @@
1
+ // M6 · Ops:指标/事件/提醒(07 M6)。
2
+ import { MetricSnapshot, OpsEvent, Reminder } from './schemas.js'
3
+ import { genId, storeError } from './store.js'
4
+
5
+ const now = () => new Date().toISOString()
6
+
7
+ export class Ops {
8
+ constructor(service) { this.service = service; this.store = service.store }
9
+
10
+ async addMetric({ projectId, channelId, date, metrics, overwrite }, actor = 'agent', source = 'manual') {
11
+ if (!this.service.getProject(projectId)) throw storeError('NOT_FOUND', `项目 ${projectId} 不存在`)
12
+ const existing = this.store.list('metrics').find(m => m.projectId === projectId && (m.channelId || null) === (channelId || null) && m.date === date)
13
+ if (existing) {
14
+ if (source === 'collector') {
15
+ return this.store.update('metrics', existing.id, d => { d.metrics = { ...d.metrics, ...metrics }; d.source = 'collector'; d.createdAt = now() }, actor, 'metric-collect-overwrite')
16
+ }
17
+ if (!overwrite) throw storeError('DUPLICATE', `同日同键指标已存在(需 overwrite)`)
18
+ return this.store.update('metrics', existing.id, d => { d.metrics = metrics; d.createdAt = now() }, actor, 'metric-overwrite')
19
+ }
20
+ const m = { id: genId('m'), projectId, channelId, date, metrics, source, createdAt: now() }
21
+ return this.store.create('metrics', MetricSnapshot.parse(m), actor, 'metric-add')
22
+ }
23
+
24
+ listMetrics(projectId, channelId, range) {
25
+ let arr = this.store.list('metrics').filter(m => m.projectId === projectId)
26
+ if (channelId) arr = arr.filter(m => m.channelId === channelId)
27
+ if (range?.from) arr = arr.filter(m => m.date >= range.from)
28
+ if (range?.to) arr = arr.filter(m => m.date <= range.to)
29
+ return arr.sort((a, b) => a.date.localeCompare(b.date))
30
+ }
31
+
32
+ async addEvent({ projectId, kind, severity, text, listingId }, actor = 'agent') {
33
+ const e = { id: genId('ev'), projectId, listingId, kind, severity, text, at: now() }
34
+ return this.store.create('events', OpsEvent.parse(e), actor, 'event-add')
35
+ }
36
+
37
+ commentList({ projectId, listingId, limit = 50 } = {}) {
38
+ let arr = this.store.list('events').filter(e => e.kind === 'comment')
39
+ if (projectId) arr = arr.filter(e => e.projectId === projectId)
40
+ if (listingId) arr = arr.filter(e => e.listingId === listingId)
41
+ return arr.sort((a, b) => b.at.localeCompare(a.at)).slice(0, limit)
42
+ }
43
+
44
+ async addReminder({ projectId, kind, dueAt, leadDays = 3, note }, actor = 'agent') {
45
+ if (Date.parse(dueAt) <= Date.now()) throw storeError('INVALID_INPUT', 'dueAt 须为未来时间')
46
+ if (leadDays < 0 || leadDays > 30) throw storeError('INVALID_INPUT', 'leadDays 须 0–30')
47
+ const r = { id: genId('rm'), projectId, kind, dueAt, leadDays, note, status: 'active' }
48
+ const created = await this.store.create('reminders', Reminder.parse(r), actor, 'reminder-add')
49
+ const fireAt = new Date(Date.parse(dueAt) - leadDays * 86400000).toISOString()
50
+ const suggestedSchedule = {
51
+ title: `项目管家提醒:${note}`.slice(0, 120),
52
+ prompt: `项目管家到期提醒:项目 ${projectId} 的「${note}」将于 ${dueAt} 到期(提前 ${leadDays} 天)。请检查并处理。`,
53
+ rrule: `DTSTART:${fireAt.replace(/[-:]/g, '').replace(/\.\d{3}/, '')}\nRRULE:FREQ=DAILY;COUNT=1`,
54
+ target: 'this_session',
55
+ }
56
+ return { reminder: created, suggestedSchedule }
57
+ }
58
+
59
+ async bindSchedule(reminderId, scheduleId, actor = 'agent') {
60
+ return this.store.update('reminders', reminderId, d => { d.scheduleId = scheduleId }, actor, 'reminder-bind')
61
+ }
62
+ async dismissReminder(reminderId, actor = 'agent') {
63
+ return this.store.update('reminders', reminderId, d => { d.status = 'dismissed' }, actor, 'reminder-dismiss')
64
+ }
65
+ }
@@ -0,0 +1,46 @@
1
+ // M3 · release_* Agent 工具(06§2)。集成时由 lead 并入 buildTools。
2
+ import { inputs } from './schemas.js'
3
+
4
+ const ok = data => ({ ok: true, data })
5
+ const fail = e => ({ ok: false, error: { code: e.code || 'ERROR', message: String(e.message || e) } })
6
+ const guard = (schema, args, fn) => {
7
+ const p = schema.safeParse(args || {})
8
+ if (!p.success) return fail({ code: 'INVALID_INPUT', message: p.error.issues.map(i => `${i.path.join('.')}: ${i.message}`).join('; ') })
9
+ return Promise.resolve(fn(p.data)).then(ok, fail)
10
+ }
11
+ const need = service => { if (!service.pipeline) throw { code: 'NOT_READY', message: 'pipeline 未挂载' }; return service.pipeline }
12
+
13
+ export function buildPipelineTools(service) {
14
+ return [
15
+ {
16
+ name: 'steward_release_start',
17
+ description: '发起全自动发布 run(版本缺省自动 bump patch)。',
18
+ parameters: { type: 'object', properties: { projectId: { type: 'string' }, version: { type: 'string' }, templateId: { type: 'string' } }, required: ['projectId'], additionalProperties: false },
19
+ execute: async args => guard(inputs.releaseStart, args, d => need(service).startRun(d, 'agent')),
20
+ },
21
+ {
22
+ name: 'steward_release_step',
23
+ description: '执行 run 的某步骤(全自动默认放行;谨慎模式需 confirm)。',
24
+ parameters: { type: 'object', properties: { runId: { type: 'string' }, stepName: { type: 'string' }, confirm: { type: 'boolean' } }, required: ['runId', 'stepName'], additionalProperties: false },
25
+ execute: async args => guard(inputs.releaseStep, args, d => need(service).executeStep(d.runId, d.stepName, { confirm: d.confirm }, 'agent')),
26
+ },
27
+ {
28
+ name: 'steward_release_manual',
29
+ description: '回填 manual 步骤结果(passed/failed + note)。',
30
+ parameters: { type: 'object', properties: { runId: { type: 'string' }, stepName: { type: 'string' }, result: { type: 'string', enum: ['passed', 'failed'] }, note: { type: 'string' } }, required: ['runId', 'stepName', 'result', 'note'], additionalProperties: false },
31
+ execute: async args => guard(inputs.releaseManual, args, d => need(service).completeManualStep(d.runId, d.stepName, d.result, d.note, 'agent')),
32
+ },
33
+ {
34
+ name: 'steward_release_waive',
35
+ description: '豁免某失败步骤(G4,必填 reason)。',
36
+ parameters: { type: 'object', properties: { runId: { type: 'string' }, stepName: { type: 'string' }, reason: { type: 'string' } }, required: ['runId', 'stepName', 'reason'], additionalProperties: false },
37
+ execute: async args => guard(inputs.releaseWaive, args, d => need(service).waiveStep(d.runId, d.stepName, d.reason, 'agent')),
38
+ },
39
+ {
40
+ name: 'steward_release_cancel',
41
+ description: '取消 run(必填 reason,项目阶段回退 developing)。',
42
+ parameters: { type: 'object', properties: { runId: { type: 'string' }, reason: { type: 'string' } }, required: ['runId', 'reason'], additionalProperties: false },
43
+ execute: async args => guard(inputs.releaseCancel, args, d => need(service).cancelRun(d.runId, d.reason, 'agent')),
44
+ },
45
+ ]
46
+ }