sillyspec 3.20.5 → 3.20.7

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.
Files changed (37) hide show
  1. package/.claude/CLAUDE.md +23 -0
  2. package/.claude/skills/sillyspec-archive/SKILL.md +86 -21
  3. package/.claude/skills/sillyspec-auto/SKILL.md +98 -83
  4. package/.claude/skills/sillyspec-brainstorm/SKILL.md +78 -44
  5. package/.claude/skills/sillyspec-doctor/SKILL.md +61 -31
  6. package/.claude/skills/sillyspec-execute/SKILL.md +90 -30
  7. package/.claude/skills/sillyspec-explore/SKILL.md +96 -109
  8. package/.claude/skills/sillyspec-export/SKILL.md +4 -0
  9. package/.claude/skills/sillyspec-init/SKILL.md +7 -0
  10. package/.claude/skills/sillyspec-plan/SKILL.md +74 -21
  11. package/.claude/skills/sillyspec-propose/SKILL.md +61 -21
  12. package/.claude/skills/sillyspec-quick/SKILL.md +84 -21
  13. package/.claude/skills/sillyspec-scan/SKILL.md +74 -21
  14. package/.claude/skills/sillyspec-state/SKILL.md +11 -1
  15. package/.claude/skills/sillyspec-status/SKILL.md +55 -21
  16. package/.claude/skills/sillyspec-verify/SKILL.md +82 -21
  17. package/.claude/skills/sillyspec-workspace/SKILL.md +12 -0
  18. package/CLAUDE.md +4 -0
  19. package/docs/sillyspec/file-lifecycle/platform-workflows-sync.md +5 -0
  20. package/docs/sillyspec/file-lifecycle/stage-artifacts.md +3 -3
  21. package/docs/sillyspec/file-lifecycle.md +17 -5
  22. package/docs/worktree-isolation.md +1 -1
  23. package/package.json +2 -2
  24. package/src/doctor-diagnostics.js +575 -0
  25. package/src/hooks/worktree-guard.js +111 -111
  26. package/src/index.js +158 -86
  27. package/src/progress.js +68 -0
  28. package/src/quick-recommend.js +115 -0
  29. package/src/run.js +272 -51
  30. package/src/stage-contract.js +23 -5
  31. package/src/stages/quick.js +36 -26
  32. package/src/sync.js +14 -3
  33. package/src/worktree.js +69 -28
  34. package/test/decision-ref-version.mjs +85 -0
  35. package/test/platform-scan-p0.test.mjs +18 -7
  36. package/test/quick-recommend.test.mjs +146 -0
  37. package/test/stage-contract.test.mjs +5 -3
@@ -0,0 +1,575 @@
1
+ /**
2
+ * doctor-diagnostics.js — 结构化项目自检(平台模式状态分裂检测)
3
+ *
4
+ * 为什么需要这个模块:
5
+ * 现状 doctor 阶段是 prompt 驱动的 bash 清单,假设单一本地 .sillyspec/,
6
+ * 看不见平台模式下的本地/平台状态分裂(孤儿 db、changes 历史断裂、pointer
7
+ * 失效静默回退)。本模块补这一层:
8
+ * - 维度化检测(D1 多 db / D2 pointer / D3 changes 分裂 / D4 change↔db 一致)
9
+ * - 结构化 JSON 输出(sillyspec doctor --json),agent 可直接解析
10
+ * - safe_actions:只描述建议动作与风险等级,绝不自动执行
11
+ *
12
+ * 安全约束(硬性):
13
+ * - 所有检测只读。DB 以内存副本打开,不调用 export/writeFileSync,不跑建表/迁移,
14
+ * close 后丢弃——绝不写回原 db 文件。
15
+ * - 不删除/移动任何文件;orphan db 仅报告,处理交给后续 --dump-db / --confirm 流程。
16
+ *
17
+ * 风格对齐 scan-postcheck.js:checks 用 CHECK_SEVERITY,formatter 产出 schema_version JSON,
18
+ * writer 落盘到 <authoritySpecDir>/.runtime/。
19
+ */
20
+ import initSqlJs from 'sql.js';
21
+ import { existsSync, statSync, readFileSync, readdirSync, mkdirSync, writeFileSync, unlinkSync } from 'fs';
22
+ import { join } from 'path';
23
+ import { CHECK_SEVERITY } from './constants.js';
24
+
25
+ // db 角色标签
26
+ const DB_ROLE = {
27
+ AUTHORITY: 'authority', // pointer 指向 / 当前权威
28
+ ORPHAN: 'orphan', // 有内容但非权威 → pointer 失效时会静默读到它(定时炸弹)
29
+ EMPTY_REMNANT: 'empty_remnant', // 0 字节或不可读的历史占位
30
+ };
31
+
32
+ // ── pointer 解析 ───────────────────────────────────────────────────────
33
+
34
+ function resolvePointer(cwd) {
35
+ const pointerPath = join(cwd, '.sillyspec-platform.json');
36
+ if (!existsSync(pointerPath)) return { present: false, path: pointerPath };
37
+ try {
38
+ const ptr = JSON.parse(readFileSync(pointerPath, 'utf8'));
39
+ return {
40
+ present: true,
41
+ path: pointerPath,
42
+ specRoot: ptr.specRoot || null,
43
+ runtimeRoot: ptr.runtimeRoot || null,
44
+ workspaceId: ptr.workspaceId || null,
45
+ savedAt: ptr.savedAt || null,
46
+ corrupted: !ptr.specRoot,
47
+ };
48
+ } catch (e) {
49
+ return { present: true, path: pointerPath, specRoot: null, corrupted: true, error: e.message };
50
+ }
51
+ }
52
+
53
+ // ── DB 只读探测 ────────────────────────────────────────────────────────
54
+
55
+ /**
56
+ * 只读打开一个 db 文件,提取诊断信号。绝不写回。
57
+ * 返回 null 表示文件不存在。
58
+ */
59
+ async function probeDb(dbPath, SQL) {
60
+ if (!existsSync(dbPath)) return null;
61
+ const st = statSync(dbPath);
62
+ const base = { path: dbPath, exists: true, size: st.size, mtime: st.mtime.toISOString() };
63
+ if (st.size === 0) {
64
+ return { ...base, readable: false, reason: '0 字节文件(历史占位)' };
65
+ }
66
+ let db = null;
67
+ try {
68
+ const buf = readFileSync(dbPath);
69
+ db = new SQL.Database(buf); // 内存副本
70
+ const pick = (sql, fallback = null) => {
71
+ try {
72
+ const r = db.exec(sql);
73
+ return r.length ? r[0].values[0][0] : fallback;
74
+ } catch { return fallback; }
75
+ };
76
+ const pickCol = (sql) => {
77
+ try {
78
+ const r = db.exec(sql);
79
+ return r.length ? r[0].values.map((row) => row[0]) : [];
80
+ } catch { return []; }
81
+ };
82
+ return {
83
+ ...base,
84
+ readable: true,
85
+ schema_version: pick('SELECT schema_version FROM project LIMIT 1'),
86
+ change_count: pick('SELECT count(*) FROM changes', 0),
87
+ active_changes: pickCol("SELECT name FROM changes WHERE status='active'"),
88
+ last_active: pick('SELECT MAX(last_active) FROM changes'),
89
+ };
90
+ } catch (e) {
91
+ return { ...base, readable: false, reason: `打开失败: ${e.message}` };
92
+ } finally {
93
+ if (db) {
94
+ try { db.close(); } catch { /* noop */ }
95
+ }
96
+ }
97
+ }
98
+
99
+ function summarizeActive(changes) {
100
+ // 完整列表交给 changes_split 维度做对比;db 摘要里只给 count + 前 3 个 sample
101
+ return { count: changes.length, sample: changes.slice(0, 3) };
102
+ }
103
+
104
+ // ── D1 多 db 探测与权威判定 ────────────────────────────────────────────
105
+
106
+ async function detectMultiDb(cwd, pointer, SQL) {
107
+ const localSpec = join(cwd, '.sillyspec');
108
+ const candidates = [
109
+ { path: join(localSpec, 'sillyspec.db'), kind: 'local_root' },
110
+ { path: join(localSpec, '.runtime', 'sillyspec.db'), kind: 'local_runtime' },
111
+ ];
112
+ if (pointer.specRoot) {
113
+ candidates.push({ path: join(pointer.specRoot, '.runtime', 'sillyspec.db'), kind: 'platform_runtime' });
114
+ candidates.push({ path: join(pointer.specRoot, 'sillyspec.db'), kind: 'platform_root' });
115
+ }
116
+
117
+ const dbs = [];
118
+ for (const c of candidates) {
119
+ const probed = await probeDb(c.path, SQL);
120
+ if (!probed) continue;
121
+ dbs.push({ kind: c.kind, ...probed });
122
+ }
123
+
124
+ // 权威判定:pointer 在 → platform_runtime 为权威;否则 local_runtime
125
+ const authorityKind = pointer.present && pointer.specRoot ? 'platform_runtime' : 'local_runtime';
126
+ for (const d of dbs) {
127
+ if (!d.readable) d.role = DB_ROLE.EMPTY_REMNANT;
128
+ else if (d.kind === authorityKind) d.role = DB_ROLE.AUTHORITY;
129
+ else d.role = DB_ROLE.ORPHAN;
130
+ }
131
+
132
+ const orphans = dbs.filter((d) => d.role === DB_ROLE.ORPHAN);
133
+ const authorities = dbs.filter((d) => d.role === DB_ROLE.AUTHORITY);
134
+ const remnants = dbs.filter((d) => d.role === DB_ROLE.EMPTY_REMNANT);
135
+
136
+ const findings = [];
137
+ let pass = true;
138
+ let severity = null;
139
+ const safeActions = [];
140
+
141
+ if (orphans.length > 0) {
142
+ pass = false;
143
+ severity = CHECK_SEVERITY.FAILED;
144
+ for (const o of orphans) {
145
+ findings.push(
146
+ `孤儿 db [${o.kind}] ${o.path}:${o.size}B,${o.change_count} changes,最后写入 ${o.last_active || '?'};` +
147
+ `pointer 指向 ${authorityKind},此 db 无人读——pointer 失效时 resolvePlatformSpecDir 会静默回退到这个过期状态`
148
+ );
149
+ safeActions.push({
150
+ dimension: 'multi_db',
151
+ action: 'dump_and_classify_orphan_db',
152
+ target: o.path,
153
+ risk: 'read_only',
154
+ rationale: `孤儿 db 含 ${o.change_count} 个 change 的进度但已无人读;先 dump 到 .runtime/doctor-dumps/ 再决定导入/归档,绝不直接删除`,
155
+ next_step: '后续实现 sillyspec doctor --dump-db --path <path> 后可直接执行',
156
+ });
157
+ }
158
+ }
159
+ if (authorities.length === 0 && dbs.some((d) => d.readable)) {
160
+ pass = false;
161
+ severity = CHECK_SEVERITY.FAILED;
162
+ findings.push(`未找到权威 db(期望 ${authorityKind},但该位置无有效 db),却存在其它可读 db——状态真相源缺失`);
163
+ }
164
+ for (const r of remnants) {
165
+ findings.push(`空占位 db [${r.kind}] ${r.path}:${r.size}B——历史遗留,建议清理`);
166
+ safeActions.push({
167
+ dimension: 'multi_db',
168
+ action: 'remove_empty_remnant',
169
+ target: r.path,
170
+ risk: 'confirm_required',
171
+ rationale: '0 字节占位文件,无数据,可安全删除',
172
+ next_step: 'sillyspec doctor --cleanup-remnant --path <path>(需 --confirm)',
173
+ });
174
+ }
175
+ if (pass && findings.length === 0) {
176
+ findings.push(`db 状态健康:权威为 ${authorityKind},无孤儿`);
177
+ }
178
+
179
+ return {
180
+ name: 'multi_db',
181
+ label: '多 db 探测与权威判定',
182
+ pass,
183
+ severity,
184
+ findings,
185
+ safe_actions: safeActions,
186
+ dbs: dbs.map((d) => ({
187
+ kind: d.kind,
188
+ role: d.role,
189
+ path: d.path,
190
+ size: d.size,
191
+ mtime: d.mtime,
192
+ readable: d.readable,
193
+ schema_version: d.schema_version,
194
+ change_count: d.change_count,
195
+ last_active: d.last_active,
196
+ active: d.readable ? summarizeActive(d.active_changes) : null,
197
+ })),
198
+ };
199
+ }
200
+
201
+ // ── D2 pointer 健康 ───────────────────────────────────────────────────
202
+
203
+ function detectPointerHealth(pointer) {
204
+ if (!pointer.present) {
205
+ return {
206
+ name: 'pointer_health',
207
+ label: '平台指针健康',
208
+ pass: true,
209
+ severity: null,
210
+ findings: ['无平台 pointer,本地模式(无平台分裂风险)'],
211
+ safe_actions: [],
212
+ };
213
+ }
214
+ const findings = [];
215
+ let pass = true;
216
+ let severity = null;
217
+ if (pointer.corrupted) {
218
+ return {
219
+ name: 'pointer_health',
220
+ label: '平台指针健康',
221
+ pass: false,
222
+ severity: CHECK_SEVERITY.FAILED,
223
+ findings: [`pointer 损坏: ${pointer.error || '缺少 specRoot 字段'}——建议删除后重跑平台 scan`],
224
+ safe_actions: [{ dimension: 'pointer_health', action: 'recreate_pointer', risk: 'confirm_required', rationale: 'pointer 损坏,需重建', next_step: 'sillyspec platform pointer --cleanup 后重新 scan' }],
225
+ };
226
+ }
227
+ const reachable = !!pointer.specRoot && existsSync(pointer.specRoot);
228
+ if (!reachable) {
229
+ pass = false;
230
+ severity = CHECK_SEVERITY.FAILED;
231
+ findings.push(
232
+ `pointer.specRoot 不可达: ${pointer.specRoot}(daemon 未起?已迁移?)——` +
233
+ `resolvePlatformSpecDir 当前会静默回退到本地孤儿 db,这是危险行为(建议改 fail-closed)`
234
+ );
235
+ }
236
+ const authDb = pointer.specRoot ? join(pointer.specRoot, '.runtime', 'sillyspec.db') : null;
237
+ if (authDb && !existsSync(authDb)) {
238
+ pass = false;
239
+ severity = severity || CHECK_SEVERITY.WARNING;
240
+ findings.push(`权威 db 不存在: ${authDb}`);
241
+ }
242
+ if (pass) findings.push(`pointer 正常,specRoot 可达`);
243
+ return {
244
+ name: 'pointer_health',
245
+ label: '平台指针健康',
246
+ pass,
247
+ severity,
248
+ findings,
249
+ safe_actions: [],
250
+ pointer: { specRoot: pointer.specRoot, runtimeRoot: pointer.runtimeRoot, reachable, savedAt: pointer.savedAt },
251
+ };
252
+ }
253
+
254
+ // ── D3 本地/平台 changes 分裂 ──────────────────────────────────────────
255
+
256
+ function listChanges(specRoot) {
257
+ const dir = join(specRoot, 'changes');
258
+ if (!existsSync(dir)) return [];
259
+ try {
260
+ return readdirSync(dir, { withFileTypes: true })
261
+ .filter((d) => d.isDirectory() && d.name !== 'archive')
262
+ .map((d) => d.name);
263
+ } catch {
264
+ return [];
265
+ }
266
+ }
267
+
268
+ function detectChangesSplit(cwd, pointer) {
269
+ const localChanges = listChanges(join(cwd, '.sillyspec'));
270
+ const findings = [];
271
+ let pass = true;
272
+ let severity = null;
273
+ const dim = {
274
+ name: 'changes_split',
275
+ label: '本地/平台 changes 分裂',
276
+ local: localChanges,
277
+ safe_actions: [],
278
+ };
279
+
280
+ if (!(pointer.present && pointer.specRoot && existsSync(pointer.specRoot))) {
281
+ dim.platform = [];
282
+ dim.findings = ['无可达平台 specRoot,仅本地 changes(无分裂可比较)'];
283
+ return { ...dim, pass: true, severity: null };
284
+ }
285
+
286
+ const platformChanges = listChanges(pointer.specRoot);
287
+ dim.platform = platformChanges;
288
+ const platformSet = new Set(platformChanges);
289
+ const localSet = new Set(localChanges);
290
+ dim.local_only = localChanges.filter((c) => !platformSet.has(c));
291
+ dim.platform_only = platformChanges.filter((c) => !localSet.has(c));
292
+ dim.intersection = localChanges.filter((c) => platformSet.has(c));
293
+
294
+ const lo = dim.local_only.length;
295
+ const po = dim.platform_only.length;
296
+ const ix = dim.intersection.length;
297
+
298
+ if (lo > 0 && po > 0 && ix === 0) {
299
+ pass = false;
300
+ severity = CHECK_SEVERITY.FAILED;
301
+ findings.push(
302
+ `严重分裂:本地 ${localChanges.length} 个 changes 与平台 ${platformChanges.length} 个 零交集——` +
303
+ `本地→平台模式切换时迁移未完成,变更历史断裂(6月在本地、7月在平台各走各的)`
304
+ );
305
+ dim.safe_actions.push({
306
+ dimension: 'changes_split',
307
+ action: 'migrate_local_changes',
308
+ risk: 'confirm_required',
309
+ rationale: `本地 ${lo} 个变更平台没有,需决定逐个导入进度 or 归档;属于数据迁移,必须逐项确认`,
310
+ next_step: '后续实现 sillyspec doctor --merge-local-to-platform(带 --confirm)',
311
+ });
312
+ } else if (lo > 3 || po > 3) {
313
+ pass = false;
314
+ severity = CHECK_SEVERITY.WARNING;
315
+ findings.push(`部分分裂:local_only ${lo},platform_only ${po},intersection ${ix}`);
316
+ } else {
317
+ findings.push(`本地/平台 changes 基本同步(intersection ${ix},local_only ${lo},platform_only ${po})`);
318
+ }
319
+
320
+ return { ...dim, pass, severity, findings };
321
+ }
322
+
323
+ // ── D4 change↔db 一致性(针对权威 db + 权威 changes 目录)──────────────
324
+
325
+ function detectChangeDbConsistency(cwd, pointer, multiDb) {
326
+ const auth = (multiDb.dbs || []).find((d) => d.role === DB_ROLE.AUTHORITY);
327
+ if (!auth) {
328
+ return {
329
+ name: 'change_db_consistency',
330
+ label: 'change↔db 一致性',
331
+ pass: true,
332
+ severity: null,
333
+ findings: ['无权威 db,跳过一致性校验'],
334
+ safe_actions: [],
335
+ };
336
+ }
337
+ const authoritySpecRoot = pointer.present && pointer.specRoot ? pointer.specRoot : join(cwd, '.sillyspec');
338
+ const dirChanges = listChanges(authoritySpecRoot);
339
+ const dbActive = auth.active || { count: 0, sample: [] };
340
+ // active.count 是权威 db 的 active change 数;但 listChanges 给的是目录数,两者口径要对齐
341
+ // 这里用 active_changes 全量需从 probe 取——summary 只给了 count/sample,
342
+ // 所以用 count 与目录数做粗对齐,细对齐留给后续 dump。
343
+ const dirCount = dirChanges.length;
344
+ const dbCount = dbActive.count;
345
+ const findings = [];
346
+ let pass = true;
347
+ let severity = null;
348
+ // 仅当差异显著才告警(口径不完全可比,避免误报)
349
+ if (Math.abs(dirCount - dbCount) > Math.max(2, dirCount * 0.2)) {
350
+ pass = false;
351
+ severity = CHECK_SEVERITY.WARNING;
352
+ findings.push(
353
+ `权威 db active changes (${dbCount}) 与 changes/ 目录数 (${dirCount}) 差异显著——` +
354
+ `可能存在孤儿目录(有目录无 db 记录)或幽灵记录(db 有记录无目录),需 dump 后细对齐`
355
+ );
356
+ } else {
357
+ findings.push(`权威 db active changes (${dbCount}) 与 changes/ 目录数 (${dirCount}) 基本一致`);
358
+ }
359
+ return {
360
+ name: 'change_db_consistency',
361
+ label: 'change↔db 一致性',
362
+ pass,
363
+ severity,
364
+ findings,
365
+ safe_actions: [],
366
+ authority_spec_root: authoritySpecRoot,
367
+ dir_count: dirCount,
368
+ db_active_count: dbCount,
369
+ };
370
+ }
371
+
372
+ // ── 主入口 ────────────────────────────────────────────────────────────
373
+
374
+ export async function runDoctorDiagnostics({ cwd }) {
375
+ const pointer = resolvePointer(cwd);
376
+ const SQL = await initSqlJs(); // 复用单个 WASM 实例,避免每个 db 重新初始化遗留 handle
377
+ const multiDb = await detectMultiDb(cwd, pointer, SQL);
378
+ const pointerHealth = detectPointerHealth(pointer);
379
+ const changesSplit = detectChangesSplit(cwd, pointer);
380
+ const changeDb = detectChangeDbConsistency(cwd, pointer, multiDb);
381
+
382
+ const dimensions = [multiDb, pointerHealth, changesSplit, changeDb];
383
+
384
+ // 权威 specDir(用于落盘诊断结果)
385
+ const authoritySpecDir =
386
+ pointer.present && pointer.specRoot && existsSync(pointer.specRoot)
387
+ ? pointer.specRoot
388
+ : existsSync(join(cwd, '.sillyspec'))
389
+ ? join(cwd, '.sillyspec')
390
+ : null;
391
+
392
+ return {
393
+ dimensions,
394
+ pointer_summary: pointer.present
395
+ ? { present: true, specRoot: pointer.specRoot, corrupted: !!pointer.corrupted, savedAt: pointer.savedAt }
396
+ : { present: false },
397
+ dbs_summary: multiDb.dbs,
398
+ authoritySpecDir,
399
+ };
400
+ }
401
+
402
+ /**
403
+ * 转结构化 JSON(sillyspec doctor --json 输出 + 落盘格式)。
404
+ * severity 口径对齐 scan-postcheck:CHECK_SEVERITY.FAILED → 'critical'。
405
+ */
406
+ export function formatDoctorJson(result, meta = {}) {
407
+ const dims = result.dimensions;
408
+ const critical = dims.filter((d) => d.severity === CHECK_SEVERITY.FAILED).length;
409
+ const warning = dims.filter((d) => d.severity === CHECK_SEVERITY.WARNING).length;
410
+ const overallStatus = critical > 0 ? 'failed' : warning > 0 ? 'warning' : 'pass';
411
+
412
+ const safeActions = [];
413
+ for (const d of dims) {
414
+ for (const a of d.safe_actions || []) safeActions.push({ dimension: d.name, ...a });
415
+ }
416
+
417
+ return {
418
+ schema_version: 1,
419
+ generated_at: new Date().toISOString(),
420
+ tool: 'sillyspec-doctor',
421
+ overall_status: overallStatus,
422
+ summary: { critical, warning, total_dimensions: dims.length },
423
+ ...(meta.source_root ? { source_root: meta.source_root } : {}),
424
+ ...(result.authoritySpecDir ? { authority_spec_dir: result.authoritySpecDir } : {}),
425
+ pointer: result.pointer_summary,
426
+ dbs: result.dbs_summary.map((d) => ({
427
+ kind: d.kind,
428
+ role: d.role,
429
+ path: d.path,
430
+ size: d.size,
431
+ mtime: d.mtime,
432
+ change_count: d.change_count,
433
+ last_active: d.last_active,
434
+ })),
435
+ dimensions: dims.map((d) => {
436
+ const out = {
437
+ name: d.name,
438
+ label: d.label,
439
+ pass: d.pass,
440
+ severity: d.severity === CHECK_SEVERITY.FAILED ? 'critical' : d.severity,
441
+ evidence: (d.findings || []).join('; '),
442
+ };
443
+ if (d.name === 'changes_split') {
444
+ out.local_count = d.local.length;
445
+ out.platform_count = d.platform.length;
446
+ out.local_only_count = (d.local_only || []).length;
447
+ out.platform_only_count = (d.platform_only || []).length;
448
+ out.intersection_count = (d.intersection || []).length;
449
+ out.local_only_sample = (d.local_only || []).slice(0, 8);
450
+ out.platform_only_sample = (d.platform_only || []).slice(0, 8);
451
+ }
452
+ return out;
453
+ }),
454
+ safe_actions: safeActions,
455
+ };
456
+ }
457
+
458
+ /**
459
+ * 落盘到 <authoritySpecDir>/.runtime/doctor-diagnosis.json(对齐 scan-postcheck.writeStructuredResult)。
460
+ */
461
+ export function writeDoctorDiagnosis(json, specDir) {
462
+ if (!specDir) return null;
463
+ try {
464
+ const runtimeDir = join(specDir, '.runtime');
465
+ mkdirSync(runtimeDir, { recursive: true });
466
+ const outPath = join(runtimeDir, 'doctor-diagnosis.json');
467
+ writeFileSync(outPath, JSON.stringify(json, null, 2) + '\n');
468
+ return outPath;
469
+ } catch (e) {
470
+ console.warn(`⚠️ doctor-diagnosis.json 写入失败: ${e.message}`);
471
+ return null;
472
+ }
473
+ }
474
+
475
+ // ── 执行流:安全清理 + 取证 dump ───────────────────────────────────────
476
+ //
477
+ // 让 doctor --json 输出的 safe_actions 真正可执行。安全约束不变:
478
+ // cleanup 只删 0 字节空占位(probeDb 判定 empty_remnant),绝不碰有内容的 db;
479
+ // dump 纯只读。destructive 操作必须 --confirm。
480
+
481
+ /**
482
+ * 清理 0 字节空占位 db(历史遗留)。默认 dry-run,--confirm 才真删。
483
+ * 只删 size===0 的文件;有内容的 db 一律不动。
484
+ */
485
+ export async function cleanupRemnantDbs({ cwd, confirm = false }) {
486
+ const pointer = resolvePointer(cwd);
487
+ const localSpec = join(cwd, '.sillyspec');
488
+ const candidates = [
489
+ join(localSpec, 'sillyspec.db'),
490
+ join(localSpec, '.runtime', 'sillyspec.db'),
491
+ ];
492
+ if (pointer.specRoot) {
493
+ candidates.push(join(pointer.specRoot, '.runtime', 'sillyspec.db'));
494
+ candidates.push(join(pointer.specRoot, 'sillyspec.db'));
495
+ }
496
+ const remnants = [];
497
+ for (const p of candidates) {
498
+ if (!existsSync(p)) continue;
499
+ try {
500
+ const st = statSync(p);
501
+ if (st.size === 0) remnants.push({ path: p, size: 0, mtime: st.mtime.toISOString() });
502
+ } catch { /* stat 失败跳过 */ }
503
+ }
504
+ const deleted = [];
505
+ const errors = [];
506
+ if (confirm) {
507
+ for (const r of remnants) {
508
+ try {
509
+ unlinkSync(r.path);
510
+ deleted.push(r.path);
511
+ } catch (e) {
512
+ errors.push({ path: r.path, error: e.message });
513
+ }
514
+ }
515
+ }
516
+ return {
517
+ action: confirm ? 'deleted' : 'dry_run',
518
+ would_delete: remnants,
519
+ deleted,
520
+ errors,
521
+ count: remnants.length,
522
+ };
523
+ }
524
+
525
+ /**
526
+ * 把任意 db 文件的内容 dump 成 JSON(schema_version + 全量 changes + stages)。
527
+ * 落盘到 <authoritySpecDir>/.runtime/doctor-dumps/dump-<ts>.json。纯只读。
528
+ */
529
+ export async function dumpDb({ dbPath, cwd }) {
530
+ const pointer = resolvePointer(cwd);
531
+ const authoritySpecDir = (pointer.present && pointer.specRoot && existsSync(pointer.specRoot))
532
+ ? pointer.specRoot
533
+ : (existsSync(join(cwd, '.sillyspec')) ? join(cwd, '.sillyspec') : null);
534
+ if (!existsSync(dbPath)) {
535
+ return { ok: false, error: `db 文件不存在: ${dbPath}`, path: dbPath };
536
+ }
537
+ const st = statSync(dbPath);
538
+ const meta = { path: dbPath, size: st.size, mtime: st.mtime.toISOString(), dumped_at: new Date().toISOString() };
539
+ if (st.size === 0) {
540
+ return writeDump({ ok: true, meta, note: '0 字节文件,无表数据', changes: [], stages: [] }, authoritySpecDir);
541
+ }
542
+ let db = null;
543
+ try {
544
+ const SQL = await initSqlJs();
545
+ db = new SQL.Database(readFileSync(dbPath));
546
+ const rows = (sql) => {
547
+ try { const r = db.exec(sql); return r.length ? r[0].values : []; } catch { return []; }
548
+ };
549
+ const sv = rows('SELECT schema_version FROM project LIMIT 1');
550
+ const schemaVersion = sv.length ? sv[0][0] : null;
551
+ const changes = rows('SELECT name, current_stage, status, created_at, last_active FROM changes ORDER BY last_active DESC')
552
+ .map((r) => ({ name: r[0], current_stage: r[1], status: r[2], created_at: r[3], last_active: r[4] }));
553
+ const stages = rows('SELECT c.name, s.stage, s.status, s.started_at, s.completed_at FROM stages s JOIN changes c ON s.change_id = c.id ORDER BY c.name, s.stage')
554
+ .map((r) => ({ change: r[0], stage: r[1], status: r[2], started_at: r[3], completed_at: r[4] }));
555
+ return writeDump({ ok: true, meta, schema_version: schemaVersion, changes, stages }, authoritySpecDir);
556
+ } catch (e) {
557
+ return writeDump({ ok: false, meta, error: `读取失败: ${e.message}` }, authoritySpecDir);
558
+ } finally {
559
+ if (db) { try { db.close(); } catch { /* noop */ } }
560
+ }
561
+ }
562
+
563
+ function writeDump(result, authoritySpecDir) {
564
+ if (!authoritySpecDir) return result; // 无处落盘也把内容返回给调用方
565
+ try {
566
+ const outDir = join(authoritySpecDir, '.runtime', 'doctor-dumps');
567
+ mkdirSync(outDir, { recursive: true });
568
+ const ts = new Date().toISOString().replace(/[:.]/g, '-');
569
+ const outPath = join(outDir, `dump-${ts}.json`);
570
+ writeFileSync(outPath, JSON.stringify(result, null, 2) + '\n');
571
+ return { ...result, written_to: outPath };
572
+ } catch (e) {
573
+ return { ...result, dump_write_error: e.message };
574
+ }
575
+ }