sillyspec 3.22.2 → 3.22.4

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