@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/src/schemas.js ADDED
@@ -0,0 +1,220 @@
1
+ // 项目管家 · 实体 zod schema 全集(05_数据字典 的唯一代码映射)
2
+ // tools / remote / inspect 三面共用本模块,防止契约漂移(UT-12)。
3
+ import { z } from 'zod'
4
+
5
+ // ---- 枚举 ----
6
+ export const ProjectType = z.enum(['business-system', 'game', 'dsh-plugin', 'web-app', 'engine', 'research', 'host'])
7
+ export const Stage = z.enum(['planning', 'developing', 'releasing', 'listed', 'operating', 'archived'])
8
+ export const ChannelStatus = z.enum(['candidate', 'active', 'paused', 'removed', 'pending', 'planned'])
9
+ export const ChannelCategory = z.enum([
10
+ 'wechat-mp', 'game-store', 'npm-registry', 'mirror', 'web-deploy', 'customer-delivery',
11
+ 'source-repo', 'plugin-market', 'local-install', 'short-video', 'publishing', 'artifact-dist',
12
+ 'model-community', 'package-registry', 'container-registry', 'content-platform', 'video-platform',
13
+ 'launch-pad', 'app-store', 'browser-store', 'editor-market', 'download-directory', 'paid-column',
14
+ 'package-manager', 'special-readonly', 'other',
15
+ ])
16
+ export const StepKind = z.enum(['auto-check', 'cli', 'auto-publish', 'manual'])
17
+ export const RunStatus = z.enum(['running', 'blocked', 'done', 'cancelled'])
18
+ export const StepStatus = z.enum(['pending', 'running', 'passed', 'failed', 'skipped', 'waived'])
19
+ export const ListingStatus = z.enum(['draft', 'submitted', 'reviewing', 'listed', 'rejected', 'delisted'])
20
+ export const MetricSource = z.enum(['manual', 'collector'])
21
+ export const EventKind = z.enum(['incident', 'notice', 'complaint', 'milestone', 'comment', 'payment'])
22
+ export const Severity = z.enum(['info', 'warn', 'critical'])
23
+ export const ReminderKind = z.enum(['renewal', 'deadline', 'todo'])
24
+ export const ReminderStatus = z.enum(['active', 'fired', 'dismissed'])
25
+ export const Actor = z.enum(['user', 'agent', 'checker', 'system', 'collector'])
26
+ export const CollectStatus = z.enum(['running', 'ok', 'partial', 'failed'])
27
+ export const Verdict = z.enum(['worth-continuing', 'needs-differentiation', 'red-ocean-caution'])
28
+
29
+ const iso = z.string().min(1)
30
+ const id = (prefix) => z.string().regex(new RegExp(`^${prefix}-[a-z0-9]+(?:-[a-z0-9]+)*$`), `id 须为 ${prefix}-<段>[-<段>...](小写字母数字连字符)`)
31
+
32
+ // ---- 内嵌结构 ----
33
+ export const MaterialItem = z.object({
34
+ key: z.string(), label: z.string(),
35
+ kind: z.enum(['file', 'text', 'url', 'bool']), required: z.boolean(),
36
+ })
37
+ export const MaterialState = z.object({
38
+ key: z.string(), ok: z.boolean(), ref: z.string().optional(), checkedAt: iso.optional(),
39
+ })
40
+ export const CredentialRef = z.object({
41
+ kind: z.enum(['file-key', 'gh-cli', 'skill-config', 'server-env']),
42
+ location: z.string(), key: z.string(),
43
+ }).nullable()
44
+ export const Evidence = z.object({
45
+ kind: z.enum(['check', 'command', 'manual']), summary: z.string(),
46
+ exitCode: z.number().int().optional(), outputTail: z.string().max(4096).optional(),
47
+ files: z.array(z.string()).optional(), command: z.string().optional(), at: iso,
48
+ })
49
+ export const StepDef = z.object({
50
+ name: z.string(), kind: StepKind, checker: z.string().optional(), command: z.string().optional(),
51
+ publishAction: z.string().optional(), cwd: z.enum(['project-root', 'steward']).optional(),
52
+ guide: z.string().optional(), blocking: z.boolean().default(true), waivable: z.boolean().default(true),
53
+ })
54
+ export const RunStep = z.object({
55
+ name: z.string(), kind: StepKind, status: StepStatus,
56
+ evidence: Evidence.optional(), waiveReason: z.string().optional(),
57
+ startedAt: iso.optional(), finishedAt: iso.optional(),
58
+ })
59
+ export const Artifact = z.object({ path: z.string(), size: z.number().optional(), sha256: z.string().optional() })
60
+ export const Transition = z.object({ from: ListingStatus, to: ListingStatus, at: iso, actor: Actor, note: z.string().optional() })
61
+
62
+ // ---- 实体 ----
63
+ export const Project = z.object({
64
+ id: id('p'), name: z.string().min(1).max(80), rootPath: z.string().min(1),
65
+ type: ProjectType, stage: Stage, owner: z.string().optional(), remote: z.string().optional(),
66
+ tags: z.array(z.string()).default([]), notes: z.string().optional(), templateId: z.string().optional(),
67
+ createdAt: iso, updatedAt: iso, lastReleaseAt: iso.optional(),
68
+ })
69
+ export const Channel = z.object({
70
+ id: id('ch'), name: z.string().min(1), category: ChannelCategory,
71
+ status: ChannelStatus.default('candidate'), source: z.enum(['seed', 'user', 'catalog']).default('user'),
72
+ grade: z.enum(['A', 'B', 'C', 'X']).optional(), activationCondition: z.string().optional(),
73
+ materialTemplate: z.array(MaterialItem).default([]), credentialRef: CredentialRef.optional(),
74
+ url: z.string().optional(), notes: z.string().optional(),
75
+ readOnly: z.boolean().default(false), operationsPolicy: z.object({
76
+ allowed: z.array(z.string()).default([]), forbidden: z.array(z.string()).default([]),
77
+ }).optional(),
78
+ appliesToTypes: z.array(ProjectType).default([]),
79
+ activatedAt: iso.optional(), removedAt: iso.optional(), removeReason: z.string().optional(),
80
+ })
81
+ export const PipelineTemplate = z.object({
82
+ id: id('tpl'), appliesTo: ProjectType, steps: z.array(StepDef).min(1),
83
+ })
84
+ export const ReleaseRun = z.object({
85
+ id: id('run'), projectId: z.string(), version: z.string(), templateId: z.string(),
86
+ status: RunStatus, steps: z.array(RunStep), startedAt: iso,
87
+ finishedAt: iso.optional(), cancelReason: z.string().optional(),
88
+ })
89
+ export const Release = z.object({
90
+ id: id('rel'), projectId: z.string(), runId: z.string(), version: z.string(),
91
+ changelog: z.string().min(1), artifacts: z.array(Artifact).default([]), releasedAt: iso,
92
+ })
93
+ export const Listing = z.object({
94
+ id: id('lst'), projectId: z.string(), channelId: z.string(), releaseId: z.string(),
95
+ status: ListingStatus, materials: z.array(MaterialState).default([]),
96
+ platformUrl: z.string().optional(), history: z.array(Transition).default([]),
97
+ createdAt: iso, updatedAt: iso,
98
+ })
99
+ export const MetricSnapshot = z.object({
100
+ id: id('m'), projectId: z.string(), channelId: z.string().optional(),
101
+ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), metrics: z.record(z.string(), z.number()),
102
+ source: MetricSource, collectRunId: z.string().optional(), createdAt: iso,
103
+ })
104
+ export const OpsEvent = z.object({
105
+ id: id('ev'), projectId: z.string(), listingId: z.string().optional(),
106
+ kind: EventKind, severity: Severity, text: z.string(), at: iso,
107
+ })
108
+ export const Reminder = z.object({
109
+ id: id('rm'), projectId: z.string(), kind: ReminderKind, dueAt: iso,
110
+ leadDays: z.number().int().min(0).max(30).default(3), note: z.string(),
111
+ scheduleId: z.string().optional(), status: ReminderStatus,
112
+ })
113
+ export const CollectRun = z.object({
114
+ id: id('cr'), channelId: z.string(), listingIds: z.array(z.string()).default([]),
115
+ startedAt: iso, finishedAt: iso.optional(), status: CollectStatus,
116
+ metricsWritten: z.number().int().default(0), newComments: z.number().int().default(0),
117
+ newPayments: z.number().int().default(0), error: z.string().optional(), staleMarked: z.boolean().default(false),
118
+ })
119
+ export const MarketCompetitor = z.object({
120
+ id: id('mc'), projectId: z.string(), name: z.string(), url: z.string(),
121
+ channelId: z.string().optional(), stars: z.number().optional(), downloads: z.number().optional(),
122
+ price: z.string().optional(), lastUpdate: iso.optional(), features: z.array(z.string()).default([]),
123
+ tags: z.array(z.string()).default([]), rating: z.number().min(0).max(5).optional(), fetchedAt: iso,
124
+ })
125
+ export const MarketReport = z.object({
126
+ projectId: z.string(), competitors: z.array(MarketCompetitor).default([]),
127
+ dimensions: z.record(z.string(), z.number()).default({}), verdict: Verdict,
128
+ strengths: z.array(z.string()).default([]), weaknesses: z.array(z.string()).default([]),
129
+ summary: z.string(), generatedAt: iso, source: z.enum(['auto', 'manual']).default('auto'),
130
+ featureComparison: z.object({
131
+ myFeatures: z.array(z.string()).default([]),
132
+ rows: z.array(z.string()).default([]),
133
+ matrix: z.array(z.object({ name: z.string(), isMine: z.boolean().default(false), caps: z.record(z.string(), z.boolean()).default({}), stars: z.number().nullable().optional(), downloads: z.number().nullable().optional(), url: z.string().optional() })).default([]),
134
+ radar: z.object({ dimensions: z.array(z.string()).default([]), series: z.array(z.object({ name: z.string(), isMine: z.boolean().default(false), values: z.array(z.number()).default([]) })).default([]) }).optional(),
135
+ }).optional(),
136
+ })
137
+ export const MarketGap = z.object({
138
+ id: id('mg'), category: z.string(), channelIds: z.array(z.string()).default([]),
139
+ supplyCount: z.number().int(), demandSignal: z.number(), gapScore: z.number(),
140
+ opportunity: z.string(), examples: z.array(z.string()).default([]), fetchedAt: iso,
141
+ niche: z.string().optional(), competition: z.number().optional(),
142
+ demandBasis: z.string().optional(),
143
+ evidence: z.array(z.object({ name: z.string(), stars: z.number().optional(), downloads: z.number().optional(), url: z.string().optional() })).default([]),
144
+ })
145
+ export const JournalEntry = z.object({
146
+ seq: z.number().int().min(1), at: iso, actor: Actor, entity: z.string(), entityId: z.string(),
147
+ action: z.string(), before: z.record(z.string(), z.unknown()).optional(),
148
+ after: z.record(z.string(), z.unknown()).optional(), reason: z.string().optional(),
149
+ })
150
+ export const Meta = z.object({
151
+ schemaVersion: z.number().int().default(1), createdAt: iso, lastJournalSeq: z.number().int().default(0),
152
+ })
153
+
154
+ // ---- 集合文件 schema ----
155
+ export const collections = {
156
+ projects: z.array(Project),
157
+ channels: z.array(Channel),
158
+ templates: z.array(PipelineTemplate),
159
+ releases: z.array(Release),
160
+ listings: z.array(Listing),
161
+ metrics: z.array(MetricSnapshot),
162
+ events: z.array(OpsEvent),
163
+ reminders: z.array(Reminder),
164
+ 'collect-runs': z.array(CollectRun),
165
+ 'market-gaps': z.array(MarketGap),
166
+ }
167
+
168
+ // ---- 工具入参 schema(三面共用)----
169
+ export const inputs = {
170
+ registerProject: z.object({
171
+ name: z.string().min(1).max(80), rootPath: z.string().min(1), type: ProjectType,
172
+ tags: z.array(z.string()).optional(), notes: z.string().optional(), remote: z.string().optional(),
173
+ }),
174
+ releaseStart: z.object({ projectId: z.string(), version: z.string().optional(), templateId: z.string().optional() }),
175
+ releaseStep: z.object({ runId: z.string(), stepName: z.string(), confirm: z.boolean().optional() }),
176
+ releaseManual: z.object({ runId: z.string(), stepName: z.string(), result: z.enum(['passed', 'failed']), note: z.string() }),
177
+ releaseWaive: z.object({ runId: z.string(), stepName: z.string(), reason: z.string().min(1) }),
178
+ releaseCancel: z.object({ runId: z.string(), reason: z.string().min(1) }),
179
+ listingCreate: z.object({ projectId: z.string(), channelId: z.string(), releaseId: z.string() }),
180
+ listingUpdate: z.object({ listingId: z.string(), to: ListingStatus, note: z.string().optional(), platformUrl: z.string().optional() }),
181
+ channelAdd: z.object({ name: z.string().min(1), category: ChannelCategory, materialTemplate: z.array(MaterialItem).optional(), credentialRef: CredentialRef.optional(), url: z.string().optional() }),
182
+ channelUpdate: z.object({ channelId: z.string(), patch: z.record(z.string(), z.unknown()) }),
183
+ channelRemove: z.object({ channelId: z.string(), reason: z.string().min(1) }),
184
+ channelImport: z.object({ candidateIds: z.array(z.string()).min(1) }),
185
+ metricAdd: z.object({ projectId: z.string(), channelId: z.string().optional(), date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), metrics: z.record(z.string(), z.number()), overwrite: z.boolean().optional() }),
186
+ eventAdd: z.object({ projectId: z.string(), kind: EventKind, severity: Severity, text: z.string(), listingId: z.string().optional() }),
187
+ reminderAdd: z.object({ projectId: z.string(), kind: ReminderKind, dueAt: iso, leadDays: z.number().int().min(0).max(30).optional(), note: z.string() }),
188
+ reminderBind: z.object({ reminderId: z.string(), scheduleId: z.string() }),
189
+ marketScan: z.object({ projectId: z.string().optional() }),
190
+ marketCompare: z.object({ projectId: z.string() }),
191
+ marketGaps: z.object({ channelIds: z.array(z.string()).optional() }),
192
+ }
193
+
194
+ // ---- 状态转移表(03§7,代码与文档同源)----
195
+ export const stageTransitions = {
196
+ planning: ['developing'],
197
+ developing: ['releasing', 'archived'],
198
+ releasing: ['listed', 'operating', 'developing'],
199
+ listed: ['operating', 'archived'],
200
+ operating: ['releasing', 'archived'],
201
+ archived: ['developing', 'operating'],
202
+ }
203
+ export const listingTransitions = {
204
+ draft: ['submitted'],
205
+ submitted: ['reviewing', 'listed', 'rejected'],
206
+ reviewing: ['listed', 'rejected'],
207
+ rejected: ['submitted'],
208
+ listed: ['delisted'],
209
+ delisted: ['submitted'],
210
+ }
211
+ export const channelTransitions = {
212
+ candidate: ['active', 'removed'],
213
+ active: ['paused', 'removed'],
214
+ paused: ['active', 'removed'],
215
+ removed: ['candidate'],
216
+ pending: ['active', 'removed'],
217
+ planned: ['active', 'removed'],
218
+ }
219
+
220
+ export const SCHEMA_VERSION = 1
package/src/service.js ADDED
@@ -0,0 +1,113 @@
1
+ // 项目管家 · M7 StewardService:唯一写入口的领域组装(02 M7 / 06§1)
2
+ // 组装 Store + Registry,后续任务挂载 pipeline/listing/ops/collector/market。
3
+ import { Store } from './store.js'
4
+ import { Registry } from './registry.js'
5
+ import { Pipeline } from './pipeline.js'
6
+ import { ListingMgr } from './listing.js'
7
+ import { Ops } from './ops.js'
8
+ import { Collector } from './collector-sched.js'
9
+ import { Market } from './market/analyze.js'
10
+ import { Docs } from './docs.js'
11
+ import { ChannelImport } from './channel-import.js'
12
+
13
+ export class StewardService {
14
+ constructor(opts = {}) {
15
+ this.dataDir = opts.dataDir
16
+ this.listeners = new Set()
17
+ this.store = new Store(this.dataDir, { emit: e => this._broadcast(e) })
18
+ this.registry = new Registry(this.store)
19
+ // 领域模块挂载
20
+ this.ops = new Ops(this)
21
+ this.listing = new ListingMgr(this)
22
+ this.pipeline = new Pipeline(this, { dryRun: opts.dryRun ?? true, confirmGates: opts.confirmGates ?? false })
23
+ this.market = new Market(this, { fetch: opts.fetch })
24
+ this.docs = new Docs(this)
25
+ this.channelImport = new ChannelImport(this)
26
+ this.collector = new Collector(this, { intervalMinutes: opts.collectIntervalMinutes ?? 60, onUrgent: e => this._broadcast({ type: 'steward/urgent', ...e }) })
27
+ }
28
+
29
+ _broadcast(e) { for (const fn of this.listeners) { try { fn(e) } catch {} } }
30
+ onChanged(fn) { this.listeners.add(fn); return () => this.listeners.delete(fn) }
31
+
32
+ // ---- registry 门面 ----
33
+ listProjects(filter) {
34
+ let arr = this.registry.list()
35
+ if (filter?.type) arr = arr.filter(p => p.type === filter.type)
36
+ if (filter?.stage) arr = arr.filter(p => p.stage === filter.stage)
37
+ if (filter?.tag) arr = arr.filter(p => (p.tags || []).includes(filter.tag))
38
+ return arr
39
+ }
40
+ getProject(id) { return this.registry.get(id) }
41
+ registerProject(input, actor) { return this.registry.register(input, actor) }
42
+ updateProject(id, patch, actor) { return this.registry.update(id, patch, actor) }
43
+ transitionStage(id, to, actor, reason) { return this.registry.transitionStage(id, to, actor, reason) }
44
+ scanCandidates(roots, opts) { return this.registry.scanCandidates(roots, opts) }
45
+
46
+ // ---- 聚合投影 ----
47
+ overview() {
48
+ const projects = this.registry.list()
49
+ const byStage = {}, byType = {}
50
+ for (const p of projects) {
51
+ byStage[p.stage] = (byStage[p.stage] || 0) + 1
52
+ byType[p.type] = (byType[p.type] || 0) + 1
53
+ }
54
+ const runs = this.store.listRuns()
55
+ const blockedRuns = runs.filter(r => r.status === 'blocked')
56
+ const reminders = this.store.list('reminders').filter(r => r.status === 'active')
57
+ const now = Date.now()
58
+ const expiredReminders = reminders.filter(r => Date.parse(r.dueAt) < now)
59
+ const listings = this.store.list('listings')
60
+ const rejected = listings.filter(l => l.status === 'rejected')
61
+ const anomalies = [
62
+ ...blockedRuns.map(r => ({ kind: 'blocked-run', ref: r.id, projectId: r.projectId })),
63
+ ...rejected.map(l => ({ kind: 'rejected-listing', ref: l.id, projectId: l.projectId })),
64
+ ...expiredReminders.map(r => ({ kind: 'expired-reminder', ref: r.id, projectId: r.projectId })),
65
+ ]
66
+ const listedListings = listings.filter(l => l.status === 'listed')
67
+ const listedProjects = new Set(listedListings.map(l => l.projectId)).size
68
+ return {
69
+ counts: { projects: projects.length, byStage, byType, listed: listedProjects, listedListings: listedListings.length },
70
+ anomalies,
71
+ recent: this._recentJournal(10),
72
+ }
73
+ }
74
+
75
+ storeSummary() {
76
+ const projects = this.registry.list()
77
+ const metrics = this.store.list('metrics')
78
+ const totals = { downloads: 0, views: 0, comments: 0, revenue: 0 }
79
+ const perProject = []
80
+ for (const p of projects) {
81
+ const ms = metrics.filter(m => m.projectId === p.id)
82
+ const latest = latestByDate(ms)
83
+ const sum = { downloads: 0, views: 0, comments: 0, revenue: 0 }
84
+ for (const m of latest) {
85
+ sum.downloads += m.metrics.downloads || 0
86
+ sum.views += m.metrics.views || 0
87
+ sum.comments += m.metrics.comments || 0
88
+ sum.revenue += m.metrics.revenue || 0
89
+ }
90
+ totals.downloads += sum.downloads; totals.views += sum.views
91
+ totals.comments += sum.comments; totals.revenue += sum.revenue
92
+ perProject.push({ projectId: p.id, name: p.name, type: p.type, stage: p.stage, ...sum })
93
+ }
94
+ return { totals, perProject }
95
+ }
96
+
97
+ _recentJournal(n) {
98
+ try {
99
+ const entries = this.store._readJournal()
100
+ return entries.slice(-n).reverse().map(e => ({ seq: e.seq, at: e.at, actor: e.actor, entity: e.entity, entityId: e.entityId, action: e.action }))
101
+ } catch { return [] }
102
+ }
103
+ }
104
+
105
+ function latestByDate(metrics) {
106
+ const map = new Map()
107
+ for (const m of metrics) {
108
+ const key = m.channelId || '_'
109
+ const cur = map.get(key)
110
+ if (!cur || m.date > cur.date) map.set(key, m)
111
+ }
112
+ return [...map.values()]
113
+ }
package/src/store.js ADDED
@@ -0,0 +1,229 @@
1
+ // 项目管家 · M1 Store:唯一写入口的一致性核心(07 M1)
2
+ // journal append-only 先行 → 集合 tmp+rename 原子替换 → 内存缓存 → 事件。
3
+ // 集合文件是 journal 的物化视图,损坏可重放重建。凭据脱敏。
4
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, renameSync, appendFileSync, readdirSync } from 'node:fs'
5
+ import { join } from 'node:path'
6
+ import { randomBytes } from 'node:crypto'
7
+ import { collections, Meta, SCHEMA_VERSION } from './schemas.js'
8
+
9
+ const SENSITIVE = /token|secret|password|apikey|api_key|auth/i
10
+ const REDACTED = '[redacted]'
11
+
12
+ export function genId(prefix) {
13
+ const t = Date.now().toString(36)
14
+ const r = randomBytes(2).toString('hex').slice(0, 4)
15
+ return `${prefix}-${t}-${r}`
16
+ }
17
+
18
+ export function redact(value) {
19
+ if (Array.isArray(value)) return value.map(redact)
20
+ if (value && typeof value === 'object') {
21
+ const out = {}
22
+ for (const [k, v] of Object.entries(value)) {
23
+ if (SENSITIVE.test(k) && typeof v === 'string') out[k] = REDACTED
24
+ else out[k] = redact(v)
25
+ }
26
+ return out
27
+ }
28
+ return value
29
+ }
30
+
31
+ export class Store {
32
+ constructor(dataDir, opts = {}) {
33
+ this.dataDir = dataDir
34
+ this.emit = opts.emit || (() => {})
35
+ this.queue = Promise.resolve()
36
+ this.data = {} // name -> Map(id -> item)
37
+ this.meta = null
38
+ this.lastSeq = 0
39
+ this.dirty = new Set()
40
+ mkdirSync(dataDir, { recursive: true })
41
+ mkdirSync(join(dataDir, 'runs'), { recursive: true })
42
+ mkdirSync(join(dataDir, 'market'), { recursive: true })
43
+ this._load()
44
+ }
45
+
46
+ _path(name) { return join(this.dataDir, `${name}.json`) }
47
+ _journalPath() { return join(this.dataDir, 'journal.jsonl') }
48
+
49
+ _load() {
50
+ // meta
51
+ const mp = join(this.dataDir, 'meta.json')
52
+ if (existsSync(mp)) {
53
+ try { this.meta = Meta.parse(JSON.parse(readFileSync(mp, 'utf8'))) }
54
+ catch { this.meta = { schemaVersion: SCHEMA_VERSION, createdAt: new Date().toISOString(), lastJournalSeq: 0 } }
55
+ } else {
56
+ this.meta = { schemaVersion: SCHEMA_VERSION, createdAt: new Date().toISOString(), lastJournalSeq: 0 }
57
+ }
58
+ // collections
59
+ for (const name of Object.keys(collections)) {
60
+ this.data[name] = new Map()
61
+ const p = this._path(name)
62
+ if (!existsSync(p)) continue
63
+ try {
64
+ const arr = collections[name].parse(JSON.parse(readFileSync(p, 'utf8')))
65
+ for (const item of arr) this.data[name].set(item.id, item)
66
+ } catch (e) {
67
+ // 隔离损坏文件,标记 dirty 待重放
68
+ const iso = `${name}.corrupt-${Date.now()}.json`
69
+ try { renameSync(p, join(this.dataDir, iso)) } catch {}
70
+ this.dirty.add(name)
71
+ this.emit({ type: 'store/corrupt', name, isolated: iso, error: String(e.message || e) })
72
+ }
73
+ }
74
+ // journal lastSeq
75
+ this.lastSeq = this._readJournalLastSeq()
76
+ if (this.dirty.size) this.rebuildFromJournal()
77
+ }
78
+
79
+ _readJournalLastSeq() {
80
+ const p = this._journalPath()
81
+ if (!existsSync(p)) return 0
82
+ const lines = readFileSync(p, 'utf8').split('\n').filter(Boolean)
83
+ let max = 0
84
+ for (const line of lines) {
85
+ try { const e = JSON.parse(line); if (e.seq > max) max = e.seq } catch {}
86
+ }
87
+ return max
88
+ }
89
+
90
+ _readJournal() {
91
+ const p = this._journalPath()
92
+ if (!existsSync(p)) return []
93
+ const out = []
94
+ const lines = readFileSync(p, 'utf8').split('\n').filter(Boolean)
95
+ for (let i = 0; i < lines.length; i++) {
96
+ try { out.push(JSON.parse(lines[i])) }
97
+ catch (e) { throw new Error(`journal 第 ${i + 1} 行损坏,停止重放:${e.message}`) }
98
+ }
99
+ return out
100
+ }
101
+
102
+ _appendJournal(entry) {
103
+ appendFileSync(this._journalPath(), JSON.stringify(entry) + '\n', 'utf8')
104
+ }
105
+
106
+ _writeCollection(name) {
107
+ const arr = [...this.data[name].values()]
108
+ const p = this._path(name)
109
+ const tmp = `${p}.tmp-${process.pid}-${Date.now()}`
110
+ writeFileSync(tmp, JSON.stringify(arr, null, 2), 'utf8')
111
+ renameSync(tmp, p)
112
+ }
113
+
114
+ _writeMeta() {
115
+ this.meta.lastJournalSeq = this.lastSeq
116
+ const p = join(this.dataDir, 'meta.json')
117
+ const tmp = `${p}.tmp`
118
+ writeFileSync(tmp, JSON.stringify(this.meta, null, 2), 'utf8')
119
+ renameSync(tmp, p)
120
+ }
121
+
122
+ _itemSchema(name) { return collections[name].element }
123
+
124
+ // 串行写队列:保证 journal 先行 + 原子替换不被并发打断
125
+ _enqueue(fn) {
126
+ const run = this.queue.then(fn, fn)
127
+ this.queue = run.then(() => {}, () => {})
128
+ return run
129
+ }
130
+
131
+ get(name, id) { return this.data[name]?.get(id) }
132
+ list(name, filter) {
133
+ const arr = [...(this.data[name]?.values() || [])]
134
+ return filter ? arr.filter(filter) : arr
135
+ }
136
+
137
+ create(name, item, actor = 'system', action = 'create') {
138
+ return this._enqueue(() => {
139
+ const parsed = this._itemSchema(name).parse(item)
140
+ if (this.data[name].has(parsed.id)) throw storeError('DUPLICATE', `${name} ${parsed.id} 已存在`)
141
+ const seq = ++this.lastSeq
142
+ this._appendJournal({ seq, at: new Date().toISOString(), actor, entity: name, entityId: parsed.id, action, after: redact(parsed) })
143
+ this.data[name].set(parsed.id, parsed)
144
+ this._writeCollection(name)
145
+ this._writeMeta()
146
+ this.emit({ type: 'steward/changed', entity: name, entityId: parsed.id, action, seq })
147
+ return parsed
148
+ })
149
+ }
150
+
151
+ // updater: (draft) => void 或返回新对象;在克隆上操作
152
+ update(name, id, updater, actor = 'system', action = 'update', reason) {
153
+ return this._enqueue(() => {
154
+ const before = this.data[name].get(id)
155
+ if (!before) throw storeError('NOT_FOUND', `${name} ${id} 不存在`)
156
+ const draft = structuredClone(before)
157
+ const ret = updater(draft)
158
+ const next = this._itemSchema(name).parse(ret === undefined ? draft : ret)
159
+ next.id = id
160
+ const seq = ++this.lastSeq
161
+ const entry = { seq, at: new Date().toISOString(), actor, entity: name, entityId: id, action, before: redact(before), after: redact(next) }
162
+ if (reason) entry.reason = reason
163
+ this._appendJournal(entry)
164
+ this.data[name].set(id, next)
165
+ this._writeCollection(name)
166
+ this._writeMeta()
167
+ this.emit({ type: 'steward/changed', entity: name, entityId: id, action, seq })
168
+ return next
169
+ })
170
+ }
171
+
172
+ // 软删除(status=removed 等)由调用方经 update 实现;此处提供物理移除仅供重建内部使用
173
+ _set(name, id, item) { this.data[name].set(id, item) }
174
+
175
+ rebuildFromJournal() {
176
+ const entries = this._readJournal()
177
+ for (const name of Object.keys(collections)) this.data[name].clear()
178
+ let maxSeq = 0
179
+ for (const e of entries) {
180
+ maxSeq = Math.max(maxSeq, e.seq)
181
+ const name = e.entity
182
+ if (!this.data[name]) continue
183
+ if (e.action === 'create' && e.after) {
184
+ try { const item = this._itemSchema(name).parse(e.after); this.data[name].set(item.id, item) } catch {}
185
+ } else if (e.after) {
186
+ try { const item = this._itemSchema(name).parse(e.after); this.data[name].set(item.id, item) } catch {}
187
+ }
188
+ }
189
+ this.lastSeq = maxSeq
190
+ for (const name of Object.keys(collections)) this._writeCollection(name)
191
+ this._writeMeta()
192
+ this.dirty.clear()
193
+ this.emit({ type: 'store/rebuilt', seq: maxSeq })
194
+ return { seq: maxSeq, collections: Object.fromEntries(Object.keys(collections).map(n => [n, this.data[n].size])) }
195
+ }
196
+
197
+ // run / market-report 单文件存取
198
+ writeRun(run) {
199
+ const p = join(this.dataDir, 'runs', `${run.id}.json`)
200
+ const tmp = `${p}.tmp`
201
+ writeFileSync(tmp, JSON.stringify(run, null, 2), 'utf8')
202
+ renameSync(tmp, p)
203
+ }
204
+ readRun(id) {
205
+ const p = join(this.dataDir, 'runs', `${id}.json`)
206
+ return existsSync(p) ? JSON.parse(readFileSync(p, 'utf8')) : undefined
207
+ }
208
+ listRuns() {
209
+ const dir = join(this.dataDir, 'runs')
210
+ return readdirSync(dir).filter(f => f.endsWith('.json')).map(f => JSON.parse(readFileSync(join(dir, f), 'utf8')))
211
+ }
212
+ writeMarketReport(report) {
213
+ const p = join(this.dataDir, 'market', `${report.projectId}.json`)
214
+ const tmp = `${p}.tmp`
215
+ writeFileSync(tmp, JSON.stringify(report, null, 2), 'utf8')
216
+ renameSync(tmp, p)
217
+ }
218
+ readMarketReport(projectId) {
219
+ const p = join(this.dataDir, 'market', `${projectId}.json`)
220
+ return existsSync(p) ? JSON.parse(readFileSync(p, 'utf8')) : undefined
221
+ }
222
+ }
223
+
224
+ export function storeError(code, message, details) {
225
+ const e = new Error(message)
226
+ e.code = code
227
+ e.details = details
228
+ return e
229
+ }
@@ -0,0 +1,68 @@
1
+ // M3 · 6 类内置流水线模板(03§3.1)。auto-publish 默认 dry-run(安全)。
2
+ const s = (name, kind, extra = {}) => ({ name, kind, blocking: true, waivable: true, ...extra })
3
+
4
+ export const builtinTemplates = [
5
+ {
6
+ id: 'tpl-dsh-plugin', appliesTo: 'dsh-plugin', steps: [
7
+ s('git-clean', 'auto-check', { checker: 'git-clean' }),
8
+ s('version-consistency', 'auto-check', { checker: 'version-consistency' }),
9
+ s('build', 'cli', { command: 'npm run build --if-present' }),
10
+ s('test', 'cli', { command: 'npm test' }),
11
+ s('changelog-nonempty', 'auto-check', { checker: 'changelog-nonempty' }),
12
+ s('readme-exists', 'auto-check', { checker: 'readme-exists' }),
13
+ s('secrets-check', 'auto-check', { checker: 'config-secrets-check' }),
14
+ s('npm-publish', 'auto-publish', { publishAction: 'npm-publish' }),
15
+ s('mirror-verify', 'auto-publish', { publishAction: 'mirror-verify' }),
16
+ s('github-push', 'auto-publish', { publishAction: 'github-push' }),
17
+ s('market-pr', 'auto-publish', { publishAction: 'market-pr' }),
18
+ ],
19
+ },
20
+ {
21
+ id: 'tpl-game-godot', appliesTo: 'game', steps: [
22
+ s('git-clean', 'auto-check', { checker: 'git-clean' }),
23
+ s('export-presets-exist', 'auto-check', { checker: 'export-presets-exist' }),
24
+ s('headless-export', 'cli', { command: 'godot --headless --export-release "Windows Desktop"' }),
25
+ s('artifact-exists', 'auto-check', { checker: 'artifact-exists' }),
26
+ s('version-consistency', 'auto-check', { checker: 'version-consistency' }),
27
+ s('itch-upload', 'auto-publish', { publishAction: 'itch-butler' }),
28
+ ],
29
+ },
30
+ {
31
+ id: 'tpl-business-system', appliesTo: 'business-system', steps: [
32
+ s('git-clean', 'auto-check', { checker: 'git-clean' }),
33
+ s('test', 'cli', { command: 'npm test' }),
34
+ s('secrets-check', 'auto-check', { checker: 'config-secrets-check' }),
35
+ s('build', 'cli', { command: 'npm run build --if-present' }),
36
+ s('deploy-readonly-guard', 'manual', { guide: '受保护生产实例(阿里云)只读:部署须人工另行执行,管家不触碰。' }),
37
+ ],
38
+ },
39
+ {
40
+ id: 'tpl-web-app', appliesTo: 'web-app', steps: [
41
+ s('git-clean', 'auto-check', { checker: 'git-clean' }),
42
+ s('build', 'cli', { command: 'npm run build' }),
43
+ s('test', 'cli', { command: 'npm test' }),
44
+ s('deploy', 'auto-publish', { publishAction: 'web-deploy' }),
45
+ ],
46
+ },
47
+ {
48
+ id: 'tpl-engine-research', appliesTo: 'engine', steps: [
49
+ s('git-clean', 'auto-check', { checker: 'git-clean' }),
50
+ s('build', 'cli', { command: 'npm run build --if-present' }),
51
+ s('test', 'cli', { command: 'npm test --if-present' }),
52
+ s('artifact-exists', 'auto-check', { checker: 'artifact-exists' }),
53
+ s('github-release', 'auto-publish', { publishAction: 'github-release' }),
54
+ ],
55
+ },
56
+ {
57
+ id: 'tpl-host', appliesTo: 'host', steps: [
58
+ s('version-report', 'auto-check', { checker: 'version-consistency' }),
59
+ s('upgrade-audit-ref', 'manual', { guide: '宿主自身只读:升级走 dsh-upgrade-audit / plugin-fleet-sweep skill,管家不执行。', blocking: false }),
60
+ ],
61
+ },
62
+ ]
63
+ // research 复用 engine 模板
64
+ builtinTemplates.push({ ...builtinTemplates.find(t => t.id === 'tpl-engine-research'), id: 'tpl-research', appliesTo: 'research' })
65
+
66
+ export function templateFor(type, overrides = []) {
67
+ return overrides.find(t => t.appliesTo === type) || builtinTemplates.find(t => t.appliesTo === type)
68
+ }