sillyspec 3.20.2 → 3.20.3

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 (208) hide show
  1. package/.claude/skills/sillyspec-archive/SKILL.md +1 -5
  2. package/.claude/skills/sillyspec-auto/SKILL.md +2 -8
  3. package/.claude/skills/sillyspec-brainstorm/SKILL.md +1 -28
  4. package/.claude/skills/sillyspec-commit/SKILL.md +3 -4
  5. package/.claude/skills/sillyspec-continue/SKILL.md +4 -5
  6. package/.claude/skills/sillyspec-doctor/SKILL.md +3 -12
  7. package/.claude/skills/sillyspec-execute/SKILL.md +2 -15
  8. package/.claude/skills/sillyspec-explore/SKILL.md +1 -14
  9. package/.claude/skills/sillyspec-plan/SKILL.md +36 -5
  10. package/.claude/skills/sillyspec-propose/SKILL.md +0 -4
  11. package/.claude/skills/sillyspec-quick/SKILL.md +1 -5
  12. package/.claude/skills/sillyspec-resume/SKILL.md +66 -23
  13. package/.claude/skills/sillyspec-scan/SKILL.md +1 -5
  14. package/.claude/skills/sillyspec-state/SKILL.md +8 -8
  15. package/.claude/skills/sillyspec-status/SKILL.md +1 -5
  16. package/.claude/skills/sillyspec-verify/SKILL.md +1 -5
  17. package/.claude/skills/sillyspec-workspace/SKILL.md +3 -11
  18. package/.sillyspec/changes/archive/2026-04-08-derive-state/design.md +97 -0
  19. package/.sillyspec/changes/archive/2026-04-08-derive-state/plan.md +51 -0
  20. package/.sillyspec/changes/archive/2026-04-08-derive-state/proposal.md +29 -0
  21. package/.sillyspec/changes/archive/2026-04-08-derive-state/requirements.md +34 -0
  22. package/.sillyspec/changes/archive/2026-04-08-derive-state/tasks.md +13 -0
  23. package/.sillyspec/changes/archive/2026-04-08-derive-state/verify-result.md +43 -0
  24. package/.sillyspec/changes/auto-mode/design.md +50 -0
  25. package/.sillyspec/changes/auto-mode/proposal.md +19 -0
  26. package/.sillyspec/changes/auto-mode/requirements.md +21 -0
  27. package/.sillyspec/changes/auto-mode/tasks.md +7 -0
  28. package/.sillyspec/changes/brainstorm-archive/2026-04-05-dashboard-design.md +206 -0
  29. package/.sillyspec/changes/brainstorm-archive/2026-04-05-unified-docs-design.md +199 -0
  30. package/.sillyspec/changes/dashboard/design.md +219 -0
  31. package/.sillyspec/changes/dashboard/design.md.braindraft +206 -0
  32. package/.sillyspec/changes/run-command-design/design.md +1230 -0
  33. package/.sillyspec/changes/unified-docs-design/design.md +199 -0
  34. package/.sillyspec/docs/sillyspec/scan/.gitkeep +0 -0
  35. package/.sillyspec/knowledge/INDEX.md +8 -0
  36. package/.sillyspec/knowledge/uncategorized.md +3 -0
  37. package/.sillyspec/plans/2026-04-05-dashboard.md +737 -0
  38. package/.sillyspec/projects/sillyspec.yaml +3 -0
  39. package/README.md +11 -13
  40. package/SKILL.md +40 -44
  41. package/dist/steps/brainstorm/01-load-context.md +30 -0
  42. package/dist/steps/brainstorm/02-reuse-check.md +6 -0
  43. package/dist/steps/brainstorm/03-prototype-analysis.md +11 -0
  44. package/dist/steps/brainstorm/04-module-split.md +23 -0
  45. package/dist/steps/brainstorm/05-dialog-explore.md +8 -0
  46. package/dist/steps/brainstorm/06-propose-approaches.md +3 -0
  47. package/dist/steps/brainstorm/07-present-design.md +3 -0
  48. package/dist/steps/brainstorm/08-write-design.md +21 -0
  49. package/dist/steps/brainstorm/09-self-review.md +15 -0
  50. package/dist/steps/brainstorm/10-user-confirm.md +3 -0
  51. package/dist/steps/brainstorm/11-output-spec.md +7 -0
  52. package/dist/steps/brainstorm/manifest.yaml +26 -0
  53. package/dist/steps/execute/01-load-context.md +41 -0
  54. package/dist/steps/execute/02-scan-conventions.md +47 -0
  55. package/dist/steps/execute/03-skill-mcp.md +19 -0
  56. package/dist/steps/execute/04-assign-task.md +22 -0
  57. package/dist/steps/execute/04b-prompt-template.md +54 -0
  58. package/dist/steps/execute/05-write-test.md +7 -0
  59. package/dist/steps/execute/06-write-code.md +8 -0
  60. package/dist/steps/execute/07-run-test.md +26 -0
  61. package/dist/steps/execute/08-fix-issues.md +28 -0
  62. package/dist/steps/execute/09-next-task.md +33 -0
  63. package/dist/steps/execute/manifest.yaml +28 -0
  64. package/dist/steps/plan/01-load-context.md +22 -0
  65. package/dist/steps/plan/02-anchor-confirm.md +1 -0
  66. package/dist/steps/plan/03-expand-tasks.md +33 -0
  67. package/dist/steps/plan/04-mark-order.md +15 -0
  68. package/dist/steps/plan/05-e2e-planning.md +17 -0
  69. package/dist/steps/plan/06-self-check.md +16 -0
  70. package/dist/steps/plan/07-save.md +1 -0
  71. package/dist/steps/plan/manifest.yaml +18 -0
  72. package/dist/steps/scan/01-env-detect.md +51 -0
  73. package/dist/steps/scan/02-tech-stack.md +16 -0
  74. package/dist/steps/scan/03-conventions.md +16 -0
  75. package/dist/steps/scan/04-structure.md +19 -0
  76. package/dist/steps/scan/05-quality.md +18 -0
  77. package/dist/steps/scan/06-complete.md +49 -0
  78. package/dist/steps/scan/manifest.yaml +16 -0
  79. package/dist/steps/verify/01-load-specs.md +28 -0
  80. package/dist/steps/verify/02-check-tasks.md +1 -0
  81. package/dist/steps/verify/03-check-design.md +6 -0
  82. package/dist/steps/verify/04-run-tests.md +7 -0
  83. package/dist/steps/verify/05-e2e-tests.md +27 -0
  84. package/dist/steps/verify/05b-e2e-fix.md +33 -0
  85. package/dist/steps/verify/06-code-quality.md +25 -0
  86. package/dist/steps/verify/07-lint-check.md +27 -0
  87. package/dist/steps/verify/08-output-report.md +14 -0
  88. package/dist/steps/verify/manifest.yaml +22 -0
  89. package/package.json +1 -7
  90. package/packages/dashboard/dist/assets/{index-Bq_Z2hne.js → index-D1EVTLmc.js} +1264 -1264
  91. package/packages/dashboard/dist/assets/index-DGe8CqeP.css +1 -0
  92. package/packages/dashboard/dist/index.html +2 -2
  93. package/packages/dashboard/package-lock.json +6 -6
  94. package/packages/dashboard/server/executor.js +1 -1
  95. package/packages/dashboard/server/index.js +18 -98
  96. package/packages/dashboard/server/parser.js +71 -139
  97. package/packages/dashboard/server/watcher.js +6 -14
  98. package/packages/dashboard/src/App.vue +185 -418
  99. package/packages/dashboard/src/components/ActionBar.vue +1 -10
  100. package/packages/dashboard/src/components/CommandPalette.vue +1 -5
  101. package/packages/dashboard/src/components/DocPreview.vue +8 -105
  102. package/packages/dashboard/src/components/DocTree.vue +19 -75
  103. package/packages/dashboard/src/components/PipelineStage.vue +2 -22
  104. package/packages/dashboard/src/components/PipelineView.vue +5 -32
  105. package/packages/dashboard/src/components/ProjectOverview.vue +139 -113
  106. package/packages/dashboard/src/components/StageBadge.vue +3 -17
  107. package/packages/dashboard/src/components/StepCard.vue +2 -7
  108. package/packages/dashboard/src/composables/useDashboard.js +0 -28
  109. package/src/derive.js +147 -0
  110. package/src/index.js +40 -688
  111. package/src/init.js +63 -119
  112. package/src/migrate.js +7 -7
  113. package/src/progress.js +248 -1474
  114. package/src/run.js +302 -3008
  115. package/src/setup.js +64 -2
  116. package/src/stages/archive.js +17 -123
  117. package/src/stages/brainstorm.js +48 -454
  118. package/src/stages/doctor.js +46 -99
  119. package/src/stages/execute.js +59 -420
  120. package/src/stages/index.js +18 -12
  121. package/src/stages/plan.js +189 -492
  122. package/src/stages/propose.js +11 -70
  123. package/src/stages/quick.js +13 -52
  124. package/src/stages/scan.js +68 -485
  125. package/src/stages/status.js +1 -1
  126. package/src/stages/verify.js +16 -203
  127. package/src/step.js +543 -0
  128. package/.claude/skills/sillyspec-knowledge/SKILL.md +0 -270
  129. package/.husky/pre-push +0 -13
  130. package/CLAUDE.md +0 -18
  131. package/docs/brainstorm-plan-contract.md +0 -64
  132. package/docs/plan-execute-contract.md +0 -123
  133. package/docs/platform-scan-protocol.md +0 -298
  134. package/docs/revision-mode.md +0 -115
  135. package/docs/sillyspec/file-lifecycle/known-implementation-gaps.md +0 -99
  136. package/docs/sillyspec/file-lifecycle/platform-workflows-sync.md +0 -218
  137. package/docs/sillyspec/file-lifecycle/stage-artifacts.md +0 -167
  138. package/docs/sillyspec/file-lifecycle/storage-and-state.md +0 -148
  139. package/docs/sillyspec/file-lifecycle/worktree-and-guard.md +0 -193
  140. package/docs/sillyspec/file-lifecycle.md +0 -125
  141. package/docs/workflow-contract-regression.md +0 -106
  142. package/docs/worktree-isolation.md +0 -252
  143. package/packages/dashboard/dist/assets/index-O2W5RV4z.css +0 -1
  144. package/packages/dashboard/dist/prototype-dashboard.html +0 -836
  145. package/packages/dashboard/dist/prototype-overview.html +0 -256
  146. package/packages/dashboard/public/prototype-dashboard.html +0 -836
  147. package/packages/dashboard/public/prototype-overview.html +0 -256
  148. package/packages/dashboard/src/components/HResizeHandle.vue +0 -48
  149. package/packages/dashboard/src/components/ProjectCard.vue +0 -187
  150. package/packages/dashboard/src/components/VResizeHandle.vue +0 -61
  151. package/packages/dashboard/src/composables/useLayout.js +0 -131
  152. package/src/brainstorm-postcheck.js +0 -158
  153. package/src/change-list.js +0 -52
  154. package/src/change-risk-profile.js +0 -352
  155. package/src/classify-change.js +0 -73
  156. package/src/constants.js +0 -70
  157. package/src/contract-matrix.js +0 -278
  158. package/src/db.js +0 -201
  159. package/src/endpoint-extractor.js +0 -315
  160. package/src/hooks/claude-pre-tool-use.cjs +0 -125
  161. package/src/hooks/worktree-guard.js +0 -761
  162. package/src/knowledge-match.js +0 -130
  163. package/src/modules.js +0 -482
  164. package/src/scan-postcheck.js +0 -383
  165. package/src/stage-contract.js +0 -700
  166. package/src/stages/brainstorm-auto.js +0 -229
  167. package/src/stages/explore.js +0 -34
  168. package/src/stages/knowledge.js +0 -498
  169. package/src/stages/plan-postcheck.js +0 -513
  170. package/src/sync.js +0 -497
  171. package/src/task-review.js +0 -346
  172. package/src/workflow.js +0 -785
  173. package/src/worktree-apply.js +0 -549
  174. package/src/worktree.js +0 -932
  175. package/templates/workflows/archive-impact.yaml +0 -79
  176. package/templates/workflows/scan-docs.yaml +0 -132
  177. package/test/brainstorm-plan-contract.test.mjs +0 -273
  178. package/test/check-syntax.mjs +0 -26
  179. package/test/cli-top-level-aliases.test.mjs +0 -174
  180. package/test/contract-artifacts.test.mjs +0 -323
  181. package/test/decision-supersede.test.mjs +0 -277
  182. package/test/knowledge-match.test.mjs +0 -231
  183. package/test/plan-execute-contract.test.mjs +0 -330
  184. package/test/plan-optimization.test.mjs +0 -572
  185. package/test/platform-artifacts.test.mjs +0 -190
  186. package/test/platform-failure-samples.test.mjs +0 -199
  187. package/test/platform-recovery-chain.test.mjs +0 -179
  188. package/test/platform-recovery.test.mjs +0 -167
  189. package/test/platform-scan-p0.test.mjs +0 -175
  190. package/test/revision-v1.test.mjs +0 -1145
  191. package/test/run-sanitize-project-name.test.mjs +0 -51
  192. package/test/run-scan-postcheck-fail.test.mjs +0 -64
  193. package/test/run-scan-project-parse.test.mjs +0 -200
  194. package/test/run-tests.mjs +0 -48
  195. package/test/scan-docs-yaml-placeholders.test.mjs +0 -84
  196. package/test/scan-knowledge.test.mjs +0 -175
  197. package/test/scan-paths.test.mjs +0 -68
  198. package/test/scan-postcheck-project-priority.test.mjs +0 -85
  199. package/test/scan-postcheck.test.mjs +0 -197
  200. package/test/scan-workflow-anyfailed-block.test.mjs +0 -52
  201. package/test/spec-dir.test.mjs +0 -206
  202. package/test/stage-contract-failed-post-check.test.mjs +0 -102
  203. package/test/stage-contract.test.mjs +0 -299
  204. package/test/stage-definitions.test.mjs +0 -39
  205. package/test/wait-gates.test.mjs +0 -501
  206. package/test/workflow-spec-base.test.mjs +0 -142
  207. package/test/worktree-guard.test.mjs +0 -136
  208. package/test/worktree-native-overlay.test.mjs +0 -188
package/src/progress.js CHANGED
@@ -1,53 +1,24 @@
1
1
  /**
2
2
  * SillySpec ProgressManager — 进度恢复管理
3
3
  *
4
- * 纯 Node.js,无外部依赖。支持多变更并行。
4
+ * 纯 Node.js,无外部依赖。管理 .sillyspec/.runtime/progress.json。
5
5
  *
6
- * 存储结构:
7
- * .sillyspec/.runtime/sillyspec.db — SQLite 数据库(权威状态源)
8
- * .sillyspec/.runtime/global.json — 全局状态缓存(项目名、活跃变更列表)
9
- * .sillyspec/.runtime/gate-status.json — worktree-guard 门禁状态缓存
10
- *
11
- * 历史迁移:v1/v2 使用 progress.json 文件,v3 已全部迁移至 SQLite。
6
+ * Schema v2: { project, currentStage, stages: { [name]: { status, steps, startedAt, completedAt } }, lastActive }
12
7
  */
13
8
 
14
- import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, unlinkSync } from 'fs';
15
- import { join, basename, dirname, resolve } from 'path';
16
- import { DB } from './db.js';
17
-
18
- // 默认规范目录名(相对于 cwd)
19
- const SPEC_DIR_NAME = '.sillyspec';
20
- const RUNTIME_SUBDIR = '.runtime';
21
-
22
- /**
23
- * 向上查找含 .sillyspec 目录的祖先目录,类似 git 找 .git 的逻辑。
24
- * 找到则返回 <祖先>/.sillyspec,否则 fallback 到 <cwd>/.sillyspec。
25
- */
26
- export function resolveSpecDir(startDir) {
27
- let dir = resolve(startDir);
28
- while (true) {
29
- const candidate = join(dir, SPEC_DIR_NAME);
30
- if (existsSync(candidate)) return candidate;
31
- const parent = dirname(dir);
32
- if (parent === dir) break; // 到达根目录
33
- dir = parent;
34
- }
35
- return join(resolve(startDir), SPEC_DIR_NAME);
36
- }
37
- const CHANGES_SUBDIR = 'changes';
38
- const GLOBAL_FILE = 'global.json';
39
- const CURRENT_VERSION = 3;
40
- const VALID_STAGES = ['scan', 'brainstorm', 'plan', 'execute', 'verify', 'archive', 'quick', 'explore'];
41
- const VALID_STATUSES = ['pending', 'in-progress', 'completed', 'failed', 'blocked', 'waiting', 'stale'];
9
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, readdirSync, unlinkSync } from 'fs';
10
+ import { join, resolve, dirname, basename } from 'path';
11
+ import { fileURLToPath } from 'url';
42
12
 
43
- // Stage statuses (superset of step statuses)
44
- const VALID_STAGE_STATUSES = ['pending', 'in-progress', 'completed', 'failed', 'blocked', 'revising', 'stale'];
13
+ const __filename = fileURLToPath(import.meta.url);
14
+ const __dirname = dirname(__filename);
15
+ const RUNTIME_DIR = '.sillyspec/.runtime';
16
+ const PROGRESS_FILE = 'progress.json';
17
+ const BACKUP_FILE = 'progress.json.bak';
45
18
 
46
- // Main flow stage order (for downstream cascade)
47
- // 完整主流程顺序(含 scan),用于下游 cascade
48
- const STAGE_ORDER = ['scan', 'brainstorm', 'plan', 'execute', 'verify', 'archive'];
49
- // 主流程阶段(不含 scan/quick/explore 等辅助阶段)
50
- const MAIN_FLOW_ORDER = STAGE_ORDER;
19
+ const CURRENT_VERSION = 2;
20
+ const VALID_STAGES = ['brainstorm', 'plan', 'execute', 'verify', 'scan', 'quick', 'archive', 'status', 'doctor'];
21
+ const VALID_STATUSES = ['pending', 'in-progress', 'completed', 'failed', 'blocked'];
51
22
 
52
23
  const STAGE_LABELS = {
53
24
  brainstorm: '🧠 需求探索',
@@ -56,8 +27,9 @@ const STAGE_LABELS = {
56
27
  verify: '🔍 验证确认',
57
28
  scan: '🔍 代码扫描',
58
29
  quick: '⚡ 快速任务',
59
- explore: '🧭 自由探索',
60
30
  archive: '📦 归档变更',
31
+ status: '📊 状态查看',
32
+ doctor: '🩺 项目自检',
61
33
  };
62
34
 
63
35
  function emptyStage() {
@@ -70,39 +42,43 @@ function makeInitialProgress(project) {
70
42
  return { _version: CURRENT_VERSION, project: project || '', currentStage: '', currentChange: null, stages, lastActive: null };
71
43
  }
72
44
 
73
- function makeInitialGlobal(project) {
74
- return { _version: CURRENT_VERSION, project: project || '', activeChanges: [] };
75
- }
76
-
77
45
  // ── ProgressManager ──
78
46
 
79
47
  export class ProgressManager {
80
- /**
81
- * @param {object} [opts]
82
- * @param {string} [opts.specDir] - 规范目录绝对路径(默认 cwd/.sillyspec)
83
- */
84
- constructor(opts = {}) {
85
- this._customSpecDir = opts.specDir || null;
86
- }
48
+ // ── 核心读写 ──
87
49
 
88
- // ── 路径工具 ──
89
-
90
- /** 获取 specDir(优先自定义,否则向上查找含 .sillyspec 的目录,fallback 到 cwd/.sillyspec) */
91
- _getSpecDir(cwd) {
92
- if (this._customSpecDir) return this._customSpecDir;
93
- return resolveSpecDir(cwd);
50
+ _path(cwd, ...parts) {
51
+ return join(cwd, RUNTIME_DIR, ...parts);
94
52
  }
95
53
 
96
- _runtimePath(cwd, ...parts) {
97
- return join(this._getSpecDir(cwd), RUNTIME_SUBDIR, ...parts);
54
+ read(cwd) {
55
+ const progressPath = this._path(cwd, PROGRESS_FILE);
56
+ const backupPath = this._path(cwd, BACKUP_FILE);
57
+
58
+ for (const p of [progressPath, backupPath]) {
59
+ if (!existsSync(p)) continue;
60
+ const parsed = this._parseWithRecovery(readFileSync(p, 'utf8'));
61
+ if (parsed) {
62
+ if (p === backupPath) {
63
+ console.log('⚠️ progress.json 损坏,已从备份恢复');
64
+ writeFileSync(progressPath, JSON.stringify(parsed, null, 2) + '\n');
65
+ }
66
+ return parsed;
67
+ }
68
+ }
69
+ return null;
98
70
  }
99
71
 
100
- _changePath(cwd, changeName, ...parts) {
101
- return join(this._getSpecDir(cwd), CHANGES_SUBDIR, changeName, ...parts);
72
+ _write(cwd, data) {
73
+ const progressPath = this._path(cwd, PROGRESS_FILE);
74
+ const tmpPath = progressPath + '.tmp';
75
+ this._ensureDir(cwd);
76
+ writeFileSync(tmpPath, JSON.stringify(data, null, 2) + '\n');
77
+ renameSync(tmpPath, progressPath);
102
78
  }
103
79
 
104
- _ensureRuntimeDir(cwd) {
105
- const runtimeDir = this._runtimePath(cwd);
80
+ _ensureDir(cwd) {
81
+ const runtimeDir = this._path(cwd);
106
82
  if (!existsSync(runtimeDir)) {
107
83
  mkdirSync(runtimeDir, { recursive: true });
108
84
  for (const d of ['artifacts', 'history', 'logs', 'templates']) {
@@ -111,875 +87,183 @@ export class ProgressManager {
111
87
  }
112
88
  }
113
89
 
114
- /** 懒初始化 DB 连接,缓存在实例上 */
115
- async _ensureDB(cwd) {
116
- if (!this._db) {
117
- this._db = new DB(this._runtimePath(cwd, 'sillyspec.db'));
118
- await this._db.init();
119
- }
120
- return this._db;
121
- }
122
-
123
- _ensureChangeDir(cwd, changeName) {
124
- const dir = this._changePath(cwd, changeName);
125
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
126
- return dir;
127
- }
128
-
129
- // ── 全局状态 ──
130
-
131
- async readGlobal(cwd) {
132
- // SQL: SELECT FROM project + changes
133
- const db = await this._ensureDB(cwd);
134
- const sqlDb = db.getDb();
135
-
136
- // 读取 project 行(id=1)
137
- const rows = sqlDb.exec('SELECT name, schema_version FROM project WHERE id = 1');
138
- if (!rows || rows.length === 0 || rows[0].values.length === 0) return null;
139
- const [name, schemaVersion] = rows[0].values[0];
140
-
141
- // 读取 active 变更列表
142
- const changeRows = sqlDb.exec("SELECT name FROM changes WHERE status = 'active' ORDER BY name");
143
- const activeChanges = changeRows && changeRows.length > 0
144
- ? changeRows[0].values.map(r => r[0])
145
- : [];
146
-
147
- return {
148
- _version: schemaVersion,
149
- project: name,
150
- activeChanges,
151
- };
152
- }
153
-
154
- async writeGlobal(cwd, data) {
155
- // SQL: UPDATE project + UPSERT changes status
156
- const db = await this._ensureDB(cwd);
157
- db.transaction((sqlDb) => {
158
- const now = new Date().toISOString();
159
-
160
- // UPSERT project 行
161
- sqlDb.run(`
162
- INSERT INTO project (id, name, schema_version, created_at, updated_at)
163
- VALUES (1, ?, ?, ?, ?)
164
- ON CONFLICT(id) DO UPDATE SET
165
- name = excluded.name,
166
- schema_version = excluded.schema_version,
167
- updated_at = excluded.updated_at
168
- `, [data.project || '', data._version || CURRENT_VERSION, now, now]);
169
-
170
- // 同步 changes 表:确保 activeChanges 列表中的变更存在且为 active,
171
- // 不在列表中的设为 archived
172
- const activeChanges = data.activeChanges || [];
173
- for (const cn of activeChanges) {
174
- sqlDb.run(`
175
- INSERT INTO changes (name, status, created_at, last_active)
176
- VALUES (?, 'active', ?, ?)
177
- ON CONFLICT(name) DO UPDATE SET status = 'active', last_active = excluded.last_active
178
- `, [cn, now, now]);
179
- }
180
- if (activeChanges.length > 0) {
181
- sqlDb.run(`
182
- UPDATE changes SET status = 'archived'
183
- WHERE status = 'active' AND name NOT IN (${activeChanges.map(() => '?').join(',')})
184
- `, activeChanges);
185
- } else {
186
- // 没有活跃变更,将所有 active 归档
187
- sqlDb.run("UPDATE changes SET status = 'archived' WHERE status = 'active'");
188
- }
189
- });
190
- }
191
-
192
- // ── 变更级别状态 ──
193
-
194
- /**
195
- * 读取指定变更的 progress(SQL 版)
196
- * @param {string} cwd
197
- * @param {string|null} changeName - 变更名,null 时尝试自动检测
198
- * @returns {Promise<object|null>} 与 SQLite 查询结果一致的 JS 对象
199
- */
200
- async read(cwd, changeName = null) {
201
- // 自动检测变更名
202
- if (!changeName) {
203
- const changes = await this.listChanges(cwd);
204
- if (changes.length === 1) {
205
- changeName = changes[0];
206
- } else {
207
- // 多个或零个活跃变更,无法确定
208
- return null;
209
- }
210
- }
211
-
212
- const db = await this._ensureDB(cwd);
213
- const sqlDb = db.getDb();
214
-
215
- // 1. 从 changes 表获取基本信息
216
- const changeRows = sqlDb.exec('SELECT id, name, current_stage, no_worktree, last_active FROM changes WHERE name = ?', [changeName]);
217
- if (!changeRows || changeRows.length === 0 || changeRows[0].values.length === 0) return null;
218
- const [changeId, cName, currentStage, noWorktree, lastActive] = changeRows[0].values[0];
219
-
220
- // 2. 从 stages 表获取所有阶段(含 revision 列)
221
- const stageRows = sqlDb.exec('SELECT id, stage, status, started_at, completed_at, revision, reopened_from_step, reopened_at, stale_reason FROM stages WHERE change_id = ? ORDER BY id', [changeId]);
222
- const stageMap = {};
223
- const stageIds = [];
224
- if (stageRows && stageRows.length > 0) {
225
- for (const [sId, stage, status, startedAt, completedAt, revision, reopenedFromStep, reopenedAt, staleReason] of stageRows[0].values) {
226
- stageMap[stage] = { _dbId: sId, status, startedAt, completedAt,
227
- ...(revision ? { revision } : {}),
228
- ...(reopenedFromStep ? { reopenedFromStep } : {}),
229
- ...(reopenedAt ? { reopenedAt } : {}),
230
- ...(staleReason ? { staleReason } : {}),
231
- };
232
- stageIds.push(sId);
233
- }
234
- }
235
-
236
- // 3. 从 steps 表获取所有步骤
237
- let stepRows = null;
238
- if (stageIds.length > 0) {
239
- const placeholders = stageIds.map(() => '?').join(',');
240
- stepRows = sqlDb.exec(
241
- `SELECT stage_id, name, status, output, completed_at, ordering, wait_reason, wait_options, wait_answer, waited_at, wait_answers, wait_round, max_wait_rounds FROM steps WHERE stage_id IN (${placeholders}) ORDER BY stage_id, ordering`,
242
- stageIds
243
- );
244
- }
245
- // 按阶段分组步骤
246
- const stepsByStage = {};
247
- if (stepRows && stepRows.length > 0) {
248
- for (const row of stepRows[0].values) {
249
- const [stageId, name, status, output, completedAt, ordering, waitReason, waitOptions, waitAnswer, waitedAt, waitAnswersJson, waitRound, maxWaitRounds] = row;
250
- if (!stepsByStage[stageId]) stepsByStage[stageId] = [];
251
- let waitAnswers = null;
252
- if (waitAnswersJson) {
253
- try { waitAnswers = JSON.parse(waitAnswersJson); } catch {}
254
- }
255
- stepsByStage[stageId].push({
256
- name, status, output, completedAt,
257
- ...(waitReason ? { waitReason } : {}),
258
- ...(waitOptions ? { waitOptions } : {}),
259
- ...(waitAnswer ? { waitAnswer } : {}),
260
- ...(waitedAt ? { waitedAt } : {}),
261
- ...(waitAnswers ? { waitAnswers } : {}),
262
- ...(waitRound != null ? { waitRound } : {}),
263
- ...(maxWaitRounds != null ? { maxWaitRounds } : {}),
264
- });
265
- }
266
- }
267
-
268
- // 4. 从 batch_progress 表获取批量进度
269
- const batchRows = sqlDb.exec('SELECT total, completed, failed, skipped FROM batch_progress WHERE change_id = ?', [changeId]);
270
- let batchProgress = undefined;
271
- if (batchRows && batchRows.length > 0 && batchRows[0].values.length > 0) {
272
- const [total, completed, failed, skipped] = batchRows[0].values[0];
273
- batchProgress = { total, completed, failed, skipped };
274
- }
275
-
276
- // 5. 获取项目名
277
- const projectRows = sqlDb.exec('SELECT name FROM project WHERE id = 1');
278
- const projectName = (projectRows && projectRows.length > 0 && projectRows[0].values.length > 0)
279
- ? projectRows[0].values[0][0]
280
- : '';
281
-
282
- // 6. 组装为兼容对象
283
- const stages = {};
284
- // 先填充所有 VALID_STAGES
285
- for (const s of VALID_STAGES) {
286
- stages[s] = emptyStage();
287
- }
288
- // 用 DB 数据覆盖
289
- for (const [stage, info] of Object.entries(stageMap)) {
290
- const steps = (stepsByStage[info._dbId] || []).map(s => ({
291
- name: s.name,
292
- status: s.status,
293
- output: s.output,
294
- completedAt: s.completedAt,
295
- ...(s.waitReason ? { waitReason: s.waitReason } : {}),
296
- ...(s.waitOptions ? { waitOptions: s.waitOptions } : {}),
297
- ...(s.waitAnswer ? { waitAnswer: s.waitAnswer } : {}),
298
- ...(s.waitedAt ? { waitedAt: s.waitedAt } : {}),
299
- ...(s.waitAnswers ? { waitAnswers: s.waitAnswers } : {}),
300
- ...(s.waitRound != null ? { waitRound: s.waitRound } : {}),
301
- ...(s.maxWaitRounds != null ? { maxWaitRounds: s.maxWaitRounds } : {}),
302
- }));
303
- stages[stage] = {
304
- status: info.status,
305
- steps,
306
- startedAt: info.startedAt,
307
- completedAt: info.completedAt,
308
- // Revision v1 fields
309
- ...(info.revision ? { revision: info.revision } : {}),
310
- ...(info.reopenedFromStep ? { reopenedFromStep: info.reopenedFromStep } : {}),
311
- ...(info.reopenedAt ? { reopenedAt: info.reopenedAt } : {}),
312
- ...(info.staleReason ? { staleReason: info.staleReason } : {}),
313
- };
314
- }
315
-
316
- const result = {
317
- _version: 3,
318
- project: projectName,
319
- currentChange: cName,
320
- currentStage: currentStage || '',
321
- lastActive: lastActive || null,
322
- stages,
323
- };
324
-
325
- // noWorktree
326
- if (noWorktree) result.noWorktree = true;
327
-
328
- // batchProgress(仅在 DB 中有记录时才包含)
329
- if (batchProgress) result.batchProgress = batchProgress;
330
-
331
- return result;
332
- }
333
-
334
- /**
335
- * 写入指定变更的 progress
336
- * @param {string} cwd
337
- * @param {object} data
338
- * @param {string|null} changeName - 从 data.currentChange 推导,或显式传入
339
- */
340
- async _write(cwd, data, changeName = null) {
341
- const cn = changeName || data.currentChange;
342
- if (!cn) {
343
- console.warn('⚠️ _write: 无变更名,跳过写入');
344
- return;
345
- }
346
-
347
- const db = await this._ensureDB(cwd);
348
- db.transaction((sqlDb) => {
349
- // 1. 更新 changes 表
350
- const now = new Date().toISOString();
351
- const noWorktree = data.noWorktree ? 1 : 0;
352
- sqlDb.run(
353
- 'UPDATE changes SET current_stage = ?, last_active = ?, no_worktree = ? WHERE name = ?',
354
- [data.currentStage || '', now, noWorktree, cn]
355
- );
356
-
357
- // 2. 获取 change_id
358
- const changeRow = sqlDb.exec('SELECT id FROM changes WHERE name = ?', [cn]);
359
- if (!changeRow || changeRow.length === 0 || changeRow[0].values.length === 0) return;
360
- const changeId = changeRow[0].values[0][0];
361
-
362
- // 3. 遍历 stages,UPSERT stages 表和 steps 表
363
- if (data.stages && typeof data.stages === 'object') {
364
- for (const [stageName, stageData] of Object.entries(data.stages)) {
365
- // UPSERT stages 行(含 revision 列)
366
- sqlDb.run(
367
- `INSERT INTO stages (change_id, stage, status, started_at, completed_at, revision, reopened_from_step, reopened_at, stale_reason)
368
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
369
- ON CONFLICT(change_id, stage) DO UPDATE SET
370
- status = excluded.status,
371
- started_at = excluded.started_at,
372
- completed_at = excluded.completed_at,
373
- revision = COALESCE(excluded.revision, stages.revision),
374
- reopened_from_step = excluded.reopened_from_step,
375
- reopened_at = excluded.reopened_at,
376
- stale_reason = excluded.stale_reason`,
377
- [changeId, stageName, stageData.status || 'pending', stageData.startedAt || null, stageData.completedAt || null,
378
- stageData.revision || 0, stageData.reopenedFromStep || null, stageData.reopenedAt || null, stageData.staleReason || null]
379
- );
380
-
381
- // 获取 stage_id
382
- const stageRow = sqlDb.exec('SELECT id FROM stages WHERE change_id = ? AND stage = ?', [changeId, stageName]);
383
- if (!stageRow || stageRow.length === 0 || stageRow[0].values.length === 0) continue;
384
- const stageId = stageRow[0].values[0][0];
385
-
386
- // 收集 data 中的步骤名
387
- const stepNames = new Set();
388
- if (Array.isArray(stageData.steps)) {
389
- for (let i = 0; i < stageData.steps.length; i++) {
390
- const step = stageData.steps[i];
391
- stepNames.add(step.name);
392
- // UPSERT 步骤(先删再插,steps 表无 UNIQUE 约束)
393
- sqlDb.run('DELETE FROM steps WHERE stage_id = ? AND name = ?', [stageId, step.name]);
394
- sqlDb.run(
395
- 'INSERT INTO steps (stage_id, name, status, output, completed_at, ordering, wait_reason, wait_options, wait_answer, waited_at, wait_answers, wait_round, max_wait_rounds) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
396
- [stageId, step.name, step.status || 'pending', step.output || null, step.completedAt || null, i,
397
- step.waitReason ?? null, step.waitOptions ?? null, step.waitAnswer ?? null, step.waitedAt ?? null,
398
- Array.isArray(step.waitAnswers) ? JSON.stringify(step.waitAnswers) : null,
399
- step.waitRound ?? null, step.maxWaitRounds ?? null]
400
- );
401
- }
402
- }
403
-
404
- // 删除 data 中不存在的多余步骤
405
- if (stepNames.size > 0) {
406
- const namePlaceholders = [...stepNames].map(() => '?').join(',');
407
- sqlDb.run(
408
- `DELETE FROM steps WHERE stage_id = ? AND name NOT IN (${namePlaceholders})`,
409
- [stageId, ...stepNames]
410
- );
411
- } else {
412
- // data 中没有步骤,清空该阶段所有步骤
413
- sqlDb.run('DELETE FROM steps WHERE stage_id = ?', [stageId]);
414
- }
415
- }
416
- }
417
-
418
- // 4. UPSERT batch_progress
419
- if (data.batchProgress && typeof data.batchProgress === 'object') {
420
- sqlDb.run(
421
- `INSERT INTO batch_progress (change_id, total, completed, failed, skipped)
422
- VALUES (?, ?, ?, ?, ?)
423
- ON CONFLICT(change_id) DO UPDATE SET
424
- total = excluded.total,
425
- completed = excluded.completed,
426
- failed = excluded.failed,
427
- skipped = excluded.skipped`,
428
- [changeId, data.batchProgress.total || 0, data.batchProgress.completed || 0, data.batchProgress.failed || 0, data.batchProgress.skipped || 0]
429
- );
430
- }
431
- });
432
-
433
- await this._updateGateStatus(cwd);
434
- }
435
-
436
- // ── 变更管理 ──
437
-
438
- /**
439
- * 列出所有活跃变更名
440
- * SQL: SELECT name FROM changes WHERE status = 'active'
441
- */
442
- async listChanges(cwd) {
443
- const db = await this._ensureDB(cwd);
444
- const sqlDb = db.getDb();
445
- const rows = sqlDb.exec("SELECT name FROM changes WHERE status = 'active' ORDER BY name");
446
- if (!rows || rows.length === 0) return [];
447
- return rows[0].values.map(r => r[0]);
448
- }
449
-
450
- /**
451
- * 注册变更到活跃列表
452
- * SQL: INSERT OR IGNORE → 若已 archived 则 UPDATE status='active'
453
- */
454
- async registerChange(cwd, changeName) {
455
- if (!changeName) {
456
- console.warn('⚠️ registerChange: changeName 为空,跳过');
457
- return;
458
- }
459
- const db = await this._ensureDB(cwd);
460
- db.transaction((sqlDb) => {
461
- const now = new Date().toISOString();
462
- // 尝试插入新行
463
- sqlDb.run(
464
- `INSERT OR IGNORE INTO changes (name, created_at, last_active)
465
- VALUES (?, ?, ?)`,
466
- [changeName, now, now]
467
- );
468
- // 注意:不复活已归档的变更——归档是不可逆操作
469
- // 如果变更已存在且为 archived,保持 archived 状态不变
470
- });
471
- }
472
-
473
- /**
474
- * 更新变更的隔离状态
475
- * @param {string} cwd - 项目根目录
476
- * @param {string} changeName - 变更名
477
- * @param {{ status: string, mode?: string, reason?: string }} isolation
478
- */
479
- async updateChangeIsolation(cwd, changeName, isolation) {
480
- const db = await this._ensureDB(cwd);
481
- const sqlDb = db.getDb();
482
- try {
483
- sqlDb.run(
484
- `UPDATE changes SET isolation_status = ?, isolation_mode = ?, isolation_reason = ?, last_active = ? WHERE name = ?`,
485
- [isolation.status, isolation.mode || null, isolation.reason || null, new Date().toISOString(), changeName]
486
- );
487
- db._save();
488
- } catch (err) {
489
- console.warn('⚠️ 更新 isolation 状态失败:', err.message);
490
- }
491
- }
492
-
493
- /**
494
- * 读取变更的隔离状态
495
- * @param {string} cwd - 项目根目录
496
- * @param {string} changeName - 变更名
497
- * @returns {{ status: string|null, mode: string|null, reason: string|null }|null}
498
- */
499
- async readChangeIsolation(cwd, changeName) {
500
- const db = await this._ensureDB(cwd);
501
- const sqlDb = db.getDb();
502
- try {
503
- const rows = sqlDb.exec(
504
- `SELECT isolation_status, isolation_mode, isolation_reason FROM changes WHERE name = ?`,
505
- [changeName]
506
- );
507
- if (!rows || rows.length === 0 || rows[0].values.length === 0) return null;
508
- const [status, mode, reason] = rows[0].values[0];
509
- return { status: status || null, mode: mode || null, reason: reason || null };
510
- } catch {
511
- return null;
512
- }
90
+ _backup(cwd) {
91
+ const p = this._path(cwd, PROGRESS_FILE);
92
+ if (existsSync(p)) renameSync(p, this._path(cwd, BACKUP_FILE));
513
93
  }
514
94
 
515
- async _updatePlatformLastSync(cwd, changeName) {
516
- if (!changeName) return;
517
- const db = await this._ensureDB(cwd);
518
- db.transaction((sqlDb) => {
519
- sqlDb.run(
520
- 'UPDATE changes SET platform_last_sync = ?, platform_sync_enabled = 1 WHERE name = ?',
521
- [new Date().toISOString(), changeName]
522
- );
523
- });
524
- }
525
-
526
- async _updateApprovalStatus(cwd, changeName, status, reason = null) {
527
- if (!changeName || !status) return;
528
- const db = await this._ensureDB(cwd);
529
- db.transaction((sqlDb) => {
530
- const rows = sqlDb.exec('SELECT id FROM changes WHERE name = ?', [changeName]);
531
- if (!rows || rows.length === 0 || rows[0].values.length === 0) return;
532
- const changeId = rows[0].values[0][0];
533
- const now = new Date().toISOString();
534
- sqlDb.run(
535
- `INSERT INTO approvals (change_id, status, requested_at, approved_at, rejection_reason)
536
- VALUES (?, ?, ?, ?, ?)
537
- ON CONFLICT(change_id) DO UPDATE SET
538
- status = excluded.status,
539
- approved_at = excluded.approved_at,
540
- rejection_reason = excluded.rejection_reason`,
541
- [
542
- changeId,
543
- status,
544
- now,
545
- status === 'approved' ? now : null,
546
- status === 'rejected' ? reason : null,
547
- ]
548
- );
549
- });
550
- }
95
+ // ── CLI 命令 ──
551
96
 
552
- /**
553
- * 重命名变更:同步更新 DB + 目录
554
- * @param {string} cwd - 项目根目录
555
- * @param {string} oldName - 旧变更名
556
- * @param {string} newName - 新变更名
557
- */
558
- async renameChange(cwd, oldName, newName) {
559
- if (!oldName || !newName) {
560
- console.warn('⚠️ renameChange: 旧名或新名为空,跳过');
561
- return;
562
- }
563
- if (oldName === newName) {
564
- console.warn('⚠️ renameChange: 新旧名称相同,跳过');
565
- return;
566
- }
567
- const db = await this._ensureDB(cwd);
568
- // 检查旧名是否存在
569
- const existing = db.transaction((sqlDb) => {
570
- const row = sqlDb.exec(`SELECT name, status FROM changes WHERE name = ?`, [oldName]);
571
- if (!row || !row[0] || row[0].values.length === 0) return null;
572
- return { name: row[0].values[0][0], status: row[0].values[0][1] };
573
- });
574
- if (!existing) {
575
- console.error(`❌ 变更 ${oldName} 不存在`);
576
- return;
577
- }
578
- // 检查新名是否已存在
579
- const conflict = db.transaction((sqlDb) => {
580
- const row = sqlDb.exec(`SELECT name FROM changes WHERE name = ?`, [newName]);
581
- return row && row[0] && row[0].values.length > 0;
582
- });
583
- if (conflict) {
584
- console.error(`❌ 变更 ${newName} 已存在`);
585
- return;
586
- }
587
- // 重命名目录
588
- const oldDir = this._changePath(cwd, oldName);
589
- const newDir = this._changePath(cwd, newName);
590
- if (existsSync(oldDir)) {
591
- renameSync(oldDir, newDir);
592
- } else {
593
- mkdirSync(newDir, { recursive: true });
594
- }
595
- // 更新 DB
596
- const now = new Date().toISOString();
597
- db.transaction((sqlDb) => {
598
- sqlDb.run(`UPDATE changes SET name = ?, last_active = ? WHERE name = ?`, [newName, now, oldName]);
599
- });
600
- console.log(`✅ 变更已重命名:${oldName} → ${newName}`);
601
- }
97
+ init(cwd) {
98
+ this._ensureDir(cwd);
99
+ const progressPath = this._path(cwd, PROGRESS_FILE);
602
100
 
603
- /**
604
- * 从活跃列表移除变更(归档时调用,不物理删除)
605
- * SQL: UPDATE changes SET status = 'archived'
606
- */
607
- async unregisterChange(cwd, changeName) {
608
- if (!changeName) {
609
- console.warn('⚠️ unregisterChange: changeName 为空,跳过');
610
- return;
101
+ if (existsSync(progressPath)) {
102
+ console.log(`ℹ️ progress.json 已存在,跳过`);
103
+ return this.read(cwd);
611
104
  }
612
- const db = await this._ensureDB(cwd);
613
- db.transaction((sqlDb) => {
614
- const now = new Date().toISOString();
615
- sqlDb.run(
616
- `UPDATE changes SET status = 'archived', last_active = ? WHERE name = ?`,
617
- [now, changeName]
618
- );
619
- });
620
- }
621
-
622
- // ── CLI 命令 ──
623
105
 
624
- async init(cwd) {
625
- this._ensureRuntimeDir(cwd);
626
-
627
- // 初始化 DB(如不存在则创建文件 + 建表)
628
- const db = await this._ensureDB(cwd);
629
- db.transaction((sqlDb) => {
630
- const now = new Date().toISOString();
631
- const projectName = basename(cwd) || 'project';
632
-
633
- // 检查 project id=1 是否已存在
634
- const existing = sqlDb.exec('SELECT id FROM project WHERE id = 1');
635
- if (!existing || existing.length === 0 || existing[0].values.length === 0) {
636
- sqlDb.run(
637
- `INSERT INTO project (id, name, schema_version, created_at, updated_at)
638
- VALUES (1, ?, ?, ?, ?)`,
639
- [projectName, CURRENT_VERSION, now, now]
640
- );
641
- console.log(`✅ 已创建全局状态文件(SQLite)`);
642
- } else {
643
- console.log(`ℹ️ 全局状态文件已存在,跳过`);
644
- }
645
- });
106
+ const project = basename(cwd);
107
+ const data = makeInitialProgress(project);
108
+ this._write(cwd, data);
109
+ console.log(`✅ 已创建 ${join(RUNTIME_DIR, PROGRESS_FILE)}`);
646
110
 
647
111
  // 创建 user-inputs.md
648
- const inputsPath = this._runtimePath(cwd, 'user-inputs.md');
112
+ const inputsPath = this._path(cwd, 'user-inputs.md');
649
113
  if (!existsSync(inputsPath)) {
650
114
  writeFileSync(inputsPath, '# 用户输入记录\n\n> 每步完成时由 AI 自动追加,记录用户所有原话。\n\n');
651
115
  }
652
116
 
653
117
  this._ensureGitignore(cwd);
654
- return await this.readGlobal(cwd);
655
- }
656
-
657
- /**
658
- * 初始化指定变更的 progress
659
- * SQL: INSERT changes + 批量 INSERT stages
660
- */
661
- async initChange(cwd, changeName) {
662
- if (!changeName) {
663
- console.warn('⚠️ initChange: changeName 为空,跳过');
664
- return null;
665
- }
666
- this._ensureChangeDir(cwd, changeName);
667
-
668
- const db = await this._ensureDB(cwd);
669
- db.transaction((sqlDb) => {
670
- const now = new Date().toISOString();
671
-
672
- // 检查变更是否已存在
673
- const existing = sqlDb.exec('SELECT id FROM changes WHERE name = ?', [changeName]);
674
- if (!existing || existing.length === 0 || existing[0].values.length === 0) {
675
- // 插入 changes 行
676
- sqlDb.run(
677
- `INSERT INTO changes (name, current_stage, status, created_at, last_active)
678
- VALUES (?, 'scan', 'active', ?, ?)`,
679
- [changeName, now, now]
680
- );
681
- }
682
-
683
- // 获取 change_id
684
- const changeRow = sqlDb.exec('SELECT id FROM changes WHERE name = ?', [changeName]);
685
- const changeId = changeRow[0].values[0][0];
686
-
687
- // 批量插入 9 个阶段(INSERT OR IGNORE 跳过已存在的)
688
- const allStages = ['scan', 'brainstorm', 'plan', 'execute', 'verify', 'archive', 'quick', 'explore'];
689
- for (const stage of allStages) {
690
- sqlDb.run(
691
- `INSERT OR IGNORE INTO stages (change_id, stage, status)
692
- VALUES (?, ?, 'pending')`,
693
- [changeId, stage]
694
- );
695
- }
696
- });
697
-
698
- // 不再需要写文件:read() 已改为 SQL
699
- return await this.read(cwd, changeName);
118
+ return data;
700
119
  }
701
120
 
702
- async setStage(cwd, stage, changeName = null) {
121
+ setStage(cwd, stage) {
703
122
  if (!VALID_STAGES.includes(stage)) {
704
123
  console.log(`❌ 未知阶段: ${stage},可选: ${VALID_STAGES.join(', ')}`);
705
124
  return;
706
125
  }
707
126
 
708
- const db = await this._ensureDB(cwd);
709
- const now = new Date().toISOString();
710
-
711
- // 获取变更名
712
- let cn = changeName;
713
- if (!cn) {
714
- const changes = await this.listChanges(cwd);
715
- if (changes.length === 1) cn = changes[0];
716
- if (!cn) { console.log('❌ 无法确定当前变更,请指定 --change <name>'); return; }
717
- }
718
-
719
- db.transaction((sqlDb) => {
720
- // 确保 change 存在
721
- const changeRow = sqlDb.exec('SELECT id, current_stage FROM changes WHERE name = ?', [cn]);
722
- if (!changeRow || changeRow.length === 0 || changeRow[0].values.length === 0) return;
127
+ const data = this._readOrInit(cwd);
128
+ if (!data) return;
723
129
 
724
- const changeId = changeRow[0].values[0][0];
725
-
726
- // UPDATE changes.current_stage + last_active
727
- sqlDb.run('UPDATE changes SET current_stage = ?, last_active = ? WHERE name = ?', [stage, now, cn]);
728
-
729
- // 确保 stages 行存在(INSERT OR IGNORE)
730
- sqlDb.run(
731
- 'INSERT OR IGNORE INTO stages (change_id, stage, status) VALUES (?, ?, "pending")',
732
- [changeId, stage]
733
- );
130
+ if (!data.stages[stage]) data.stages[stage] = emptyStage();
131
+ const stageData = data.stages[stage];
734
132
 
735
- // UPDATE stages.status in-progress(仅当仍为 pending 时)
736
- sqlDb.run(
737
- "UPDATE stages SET status = 'in-progress', started_at = ? WHERE change_id = ? AND stage = ? AND status = 'pending'",
738
- [now, changeId, stage]
739
- );
740
- });
133
+ data.currentStage = stage;
134
+ if (stageData.status === 'pending') {
135
+ stageData.status = 'in-progress';
136
+ stageData.startedAt = new Date().toLocaleString('zh-CN',{hour12:false});
137
+ }
138
+ data.lastActive = new Date().toLocaleString('zh-CN',{hour12:false});
741
139
 
742
- // read() 已改为 SQL,直接通过 SQL 查询即可,无需 _write
743
- console.log(`✅ 当前阶段已设为: ${STAGE_LABELS[stage] || stage}`);
140
+ this._backup(cwd);
141
+ this._write(cwd, data);
142
+ console.log(`✅ 当前阶段已设为: ${STAGE_LABELS[stage] || stage} (${stageData.status})`);
744
143
  }
745
144
 
746
- async addStep(cwd, stage, stepName, changeName = null) {
145
+ addStep(cwd, stage, stepName) {
747
146
  if (!stepName) { console.log('❌ 请指定步骤名称'); return; }
147
+ const data = this._requireStage(cwd, stage);
148
+ if (!data) return;
748
149
 
749
- const db = await this._ensureDB(cwd);
750
-
751
- // 获取变更名
752
- let cn = changeName;
753
- if (!cn) {
754
- const changes = await this.listChanges(cwd);
755
- if (changes.length === 1) cn = changes[0];
756
- if (!cn) { console.log('❌ 无法确定当前变更,请指定 --change <name>'); return; }
757
- }
758
-
759
- // 查找 stage_id
760
- const sqlDb = db.getDb();
761
- const stageRow = sqlDb.exec(
762
- 'SELECT s.id FROM stages s JOIN changes c ON s.change_id = c.id WHERE c.name = ? AND s.stage = ?',
763
- [cn, stage]
764
- );
765
- if (!stageRow || stageRow.length === 0 || stageRow[0].values.length === 0) {
766
- // stages 行不存在,静默跳过
767
- console.log(`ℹ️ 阶段 ${stage} 不存在`);
768
- return;
769
- }
770
- const stageId = stageRow[0].values[0][0];
771
-
772
- // 重复步骤名检查
773
- const dupRow = sqlDb.exec('SELECT id FROM steps WHERE stage_id = ? AND name = ?', [stageId, stepName]);
774
- if (dupRow && dupRow.length > 0 && dupRow[0].values.length > 0) {
150
+ const stageData = data.stages[stage];
151
+ if (stageData.steps.some(s => s.name === stepName)) {
775
152
  console.log(`ℹ️ 步骤 "${stepName}" 已存在于 ${stage}`);
776
153
  return;
777
154
  }
778
155
 
779
- // INSERT INTO steps(ordering 递增)
780
- db.transaction((tDb) => {
781
- tDb.run(
782
- `INSERT INTO steps (stage_id, name, ordering, status)
783
- VALUES (?, ?, (SELECT COALESCE(MAX(ordering), 0) + 1 FROM steps WHERE stage_id = ?), 'pending')`,
784
- [stageId, stepName, stageId]
785
- );
786
- tDb.run('UPDATE changes SET last_active = ? WHERE name = ?', [new Date().toISOString(), cn]);
787
- });
156
+ stageData.steps.push({ name: stepName, status: 'pending' });
157
+ data.lastActive = new Date().toLocaleString('zh-CN',{hour12:false});
788
158
 
159
+ this._backup(cwd);
160
+ this._write(cwd, data);
789
161
  console.log(`✅ 已添加步骤: ${stage}/${stepName}`);
790
162
  }
791
163
 
792
- async updateStep(cwd, stage, stepName, options = {}, changeName = null) {
164
+ updateStep(cwd, stage, stepName, options = {}) {
793
165
  const { status, output } = options;
794
166
  if (!stepName) { console.log('❌ 请指定步骤名称'); return; }
167
+ const data = this._requireStage(cwd, stage);
168
+ if (!data) return;
795
169
 
796
- const db = await this._ensureDB(cwd);
797
-
798
- // 获取变更名
799
- let cn = changeName;
800
- if (!cn) {
801
- const changes = await this.listChanges(cwd);
802
- if (changes.length === 1) cn = changes[0];
803
- if (!cn) { console.log('❌ 无法确定当前变更,请指定 --change <name>'); return; }
804
- }
170
+ const stageData = data.stages[stage];
171
+ const step = stageData.steps.find(s => s.name === stepName);
172
+ if (!step) { console.log(`❌ 步骤不存在: ${stage}/${stepName}`); return; }
805
173
 
806
- // 状态校验
807
- if (status && !VALID_STATUSES.includes(status)) {
808
- console.log(`❌ 无效状态: ${status},可选: ${VALID_STATUSES.join(', ')}`);
809
- return;
174
+ if (status) {
175
+ if (!VALID_STATUSES.includes(status)) {
176
+ console.log(`❌ 无效状态: ${status},可选: ${VALID_STATUSES.join(', ')}`);
177
+ return;
178
+ }
179
+ step.status = status;
810
180
  }
181
+ if (output !== undefined) step.output = output;
811
182
 
812
- // 查找 step_id:通过 changes → stages → steps JOIN 查询
813
- const sqlDb = db.getDb();
814
- const stepRow = sqlDb.exec(
815
- `SELECT st.id, st.status FROM steps st
816
- JOIN stages sg ON st.stage_id = sg.id
817
- JOIN changes c ON sg.change_id = c.id
818
- WHERE c.name = ? AND sg.stage = ? AND st.name = ?`,
819
- [cn, stage, stepName]
820
- );
821
- if (!stepRow || stepRow.length === 0 || stepRow[0].values.length === 0) {
822
- console.log(`❌ 步骤不存在: ${stage}/${stepName}`);
823
- return;
183
+ // 检查是否所有步骤都 completed
184
+ if (stageData.steps.length > 0 && stageData.steps.every(s => s.status === 'completed')) {
185
+ stageData.status = 'completed';
186
+ stageData.completedAt = new Date().toLocaleString('zh-CN',{hour12:false});
187
+ console.log(`✅ 阶段 ${stage} 所有步骤已完成,阶段已标记为 completed`);
824
188
  }
825
- const stepId = stepRow[0].values[0][0];
826
-
827
- // UPDATE steps
828
- db.transaction((tDb) => {
829
- const now = new Date().toISOString();
830
- if (status) {
831
- tDb.run('UPDATE steps SET status = ?, completed_at = ? WHERE id = ? AND name = ?', [status, now, stepId, stepName]);
832
- }
833
- if (output !== undefined) {
834
- tDb.run('UPDATE steps SET output = ? WHERE id = ? AND name = ?', [output, stepId, stepName]);
835
- }
836
-
837
- // 自动完成检测:同 stage_id 下所有 steps 都 completed 时,标记 stage completed
838
- if (status === 'completed') {
839
- // 获取 stage_id
840
- const stRow = tDb.exec('SELECT stage_id FROM steps WHERE id = ?', [stepId]);
841
- if (stRow && stRow.length > 0 && stRow[0].values.length > 0) {
842
- const stId = stRow[0].values[0][0];
843
- const pendingRows = tDb.exec('SELECT COUNT(*) FROM steps WHERE stage_id = ? AND status != "completed"', [stId]);
844
- if (pendingRows && pendingRows.length > 0 && pendingRows[0].values[0][0] === 0) {
845
- tDb.run('UPDATE stages SET status = "completed", completed_at = ? WHERE id = ?', [now, stId]);
846
- console.log(`✅ 阶段 ${stage} 所有步骤已完成,阶段已标记为 completed`);
847
- }
848
- }
849
- }
850
-
851
- tDb.run('UPDATE changes SET last_active = ? WHERE name = ?', [now, cn]);
852
- });
853
189
 
854
- console.log(`✅ 步骤已更新: ${stage}/${stepName} → ${status || '(仅更新 output)'}`);
190
+ data.lastActive = new Date().toLocaleString('zh-CN',{hour12:false});
191
+ this._backup(cwd);
192
+ this._write(cwd, data);
193
+ console.log(`✅ 步骤已更新: ${stage}/${stepName} → ${status || step.status}`);
855
194
  }
856
195
 
857
- async completeStage(cwd, stage, changeName = null) {
196
+ completeStage(cwd, stage) {
858
197
  if (!VALID_STAGES.includes(stage)) {
859
198
  console.log(`❌ 未知阶段: ${stage}`);
860
199
  return;
861
200
  }
862
201
 
863
- const db = await this._ensureDB(cwd);
864
- const now = new Date().toISOString();
865
-
866
- // 获取变更名
867
- let cn = changeName;
868
- if (!cn) {
869
- const changes = await this.listChanges(cwd);
870
- if (changes.length === 1) cn = changes[0];
871
- if (!cn) { console.log('❌ 无法确定当前变更,请指定 --change <name>'); return; }
872
- }
873
-
874
- db.transaction((sqlDb) => {
875
- const changeRow = sqlDb.exec('SELECT id FROM changes WHERE name = ?', [cn]);
876
- if (!changeRow || changeRow.length === 0 || changeRow[0].values.length === 0) return;
877
- const changeId = changeRow[0].values[0][0];
878
-
879
- // 确保 stages 行存在(阶段不存在时自动创建)
880
- sqlDb.run(
881
- 'INSERT OR IGNORE INTO stages (change_id, stage, status) VALUES (?, ?, "pending")',
882
- [changeId, stage]
883
- );
884
-
885
- // UPDATE stages.status=completed + completed_at
886
- sqlDb.run(
887
- 'UPDATE stages SET status = "completed", completed_at = ? WHERE change_id = ? AND stage = ?',
888
- [now, changeId, stage]
889
- );
890
-
891
- // 将该阶段所有 pending 步骤标记为 completed
892
- const stageRow = sqlDb.exec('SELECT id FROM stages WHERE change_id = ? AND stage = ?', [changeId, stage]);
893
- if (stageRow && stageRow.length > 0 && stageRow[0].values.length > 0) {
894
- const stageId = stageRow[0].values[0][0];
895
- sqlDb.run(
896
- 'UPDATE steps SET status = "completed", completed_at = ? WHERE stage_id = ? AND status = "pending"',
897
- [now, stageId]
898
- );
899
- }
900
-
901
- // UPDATE changes.last_active
902
- sqlDb.run('UPDATE changes SET last_active = ? WHERE name = ?', [now, cn]);
903
- });
904
-
905
- // 写 history 文件(保持文件系统,不变)
906
- const data = await this.read(cwd, cn);
907
- if (data && data.stages && data.stages[stage]) {
908
- const historyDir = this._runtimePath(cwd, 'history');
909
- mkdirSync(historyDir, { recursive: true });
910
- const ts = now.replace(/[:.TZ-]/g, '');
911
- const stageData = data.stages[stage];
912
- writeFileSync(
913
- join(historyDir, `${cn}-${stage}-${ts}.json`),
914
- JSON.stringify({ change: cn, stage, data: stageData, completedAt: now }, null, 2) + '\n'
915
- );
916
- }
202
+ const data = this._readOrInit(cwd);
203
+ if (!data) return;
917
204
 
918
- console.log(`✅ 阶段 ${stage} 已标记为完成(不自动推进,下一步由你决定)`);
919
- }
205
+ if (!data.stages[stage]) data.stages[stage] = emptyStage();
206
+ const stageData = data.stages[stage];
207
+ stageData.status = 'completed';
208
+ stageData.completedAt = new Date().toLocaleString('zh-CN',{hour12:false});
920
209
 
921
- async show(cwd, changeName = null) {
922
- // 如果指定了变更名,只显示该变更
923
- if (changeName) {
924
- return await this._showChange(cwd, changeName);
210
+ // 标记所有未完成步骤为 completed
211
+ for (const step of stageData.steps) {
212
+ if (step.status === 'pending') step.status = 'completed';
925
213
  }
926
214
 
927
- // 否则显示所有变更
928
- const changes = await this.listChanges(cwd);
929
- if (changes.length === 0) {
930
- console.log('ℹ️ 没有活跃的变更');
931
- return;
215
+ // 推进到下一个未完成阶段
216
+ const idx = VALID_STAGES.indexOf(stage);
217
+ let nextStage = null;
218
+ for (let i = idx + 1; i < VALID_STAGES.length; i++) {
219
+ const s = data.stages[VALID_STAGES[i]];
220
+ if (!s || s.status !== 'completed') {
221
+ nextStage = VALID_STAGES[i];
222
+ break;
223
+ }
932
224
  }
933
225
 
934
- if (changes.length === 1) {
935
- return await this._showChange(cwd, changes[0]);
226
+ if (nextStage) {
227
+ data.currentStage = nextStage;
228
+ if (!data.stages[nextStage]) data.stages[nextStage] = emptyStage();
229
+ if (data.stages[nextStage].status === 'pending') {
230
+ data.stages[nextStage].status = 'in-progress';
231
+ data.stages[nextStage].startedAt = new Date().toLocaleString('zh-CN',{hour12:false});
232
+ }
233
+ console.log(`✅ 阶段 ${stage} 已完成,推进到: ${STAGE_LABELS[nextStage] || nextStage}`);
234
+ } else {
235
+ data.currentStage = stage;
236
+ console.log(`✅ 阶段 ${stage} 已完成(已是最后阶段)`);
936
237
  }
937
238
 
938
- // 多个变更:汇总显示
939
- const global = await this.readGlobal(cwd);
940
- console.log('');
941
- console.log(' ═══════════════════════════════════════');
942
- console.log(` 项目: ${(global?.project) || basename(cwd) || '(未命名)'}`);
943
- console.log(` 活跃变更: ${changes.length} 个`);
944
- console.log(' ═══════════════════════════════════════');
945
- console.log('');
946
-
947
- for (const cn of changes) {
948
- const data = await this.read(cwd, cn);
949
- if (!data) {
950
- console.log(` 📂 ${cn} — (无法读取)`);
951
- continue;
952
- }
953
- const currentStage = data.currentStage || '(无)';
954
- const stageLabel = STAGE_LABELS[data.currentStage] || currentStage;
955
- const lastActive = data.lastActive ? this._timeAgo(data.lastActive) : '未知';
239
+ data.lastActive = new Date().toLocaleString('zh-CN',{hour12:false});
956
240
 
957
- console.log(` 📂 ${cn}`);
958
- console.log(` 当前阶段: ${stageLabel} 最近活跃: ${lastActive}`);
959
- console.log('');
960
- }
241
+ // 归档到 history/
242
+ const historyDir = this._path(cwd, 'history');
243
+ mkdirSync(historyDir, { recursive: true });
244
+ const ts = new Date().toLocaleString('zh-CN',{hour12:false}).replace(/[:.]/g, '-');
245
+ writeFileSync(join(historyDir, `${stage}-${ts}.json`), JSON.stringify({ stage, data: stageData, completedAt: stageData.completedAt }, null, 2) + '\n');
961
246
 
962
- console.log(` 💡 查看详情:sillyspec progress show --change <name>`);
963
- console.log('');
247
+ this._backup(cwd);
248
+ this._write(cwd, data);
964
249
  }
965
250
 
966
- async _showChange(cwd, changeName) {
967
- const data = await this.read(cwd, changeName);
251
+ show(cwd) {
252
+ const data = this.read(cwd);
968
253
  if (!data) {
969
- console.log(`❌ 未找到变更 ${changeName}`);
254
+ console.log('❌ 未找到 progress.json,请先运行 sillyspec progress init');
970
255
  return;
971
256
  }
972
257
 
973
258
  console.log('');
974
259
  console.log(' ═══════════════════════════════════════');
975
- console.log(` 变更: ${changeName}`);
976
260
  console.log(` 项目: ${data.project || '(未命名)'}`);
977
261
  console.log(` 当前阶段: ${STAGE_LABELS[data.currentStage] || data.currentStage || '(无)'}`);
978
262
  console.log(` 最近活跃: ${data.lastActive ? this._timeAgo(data.lastActive) : '未知'}`);
979
263
  console.log(' ═══════════════════════════════════════');
980
264
  console.log('');
981
265
 
982
- const statusIcons = { pending: '⬜', 'in-progress': '🔵', completed: '✅', failed: '❌', blocked: '🚫', waiting: '⏸️', revising: '🔧', stale: '⚠️' };
266
+ const statusIcons = { pending: '⬜', 'in-progress': '🔵', completed: '✅', failed: '❌', blocked: '🚫' };
983
267
 
984
268
  for (const stage of VALID_STAGES) {
985
269
  const stageData = data.stages[stage] || emptyStage();
@@ -989,28 +273,11 @@ export class ProgressManager {
989
273
 
990
274
  console.log(` ${icon} ${label}${isCurrent}`);
991
275
 
992
- // Show revision info
993
- if (stageData.revision && stageData.revision > 0) {
994
- console.log(` 📋 revision: ${stageData.revision}${stageData.reopenedFromStep ? `, from step: ${stageData.reopenedFromStep}` : ''}`);
995
- }
996
- if (stageData.staleReason) {
997
- console.log(` ⚠️ stale: ${stageData.staleReason}`);
998
- if (stage === 'archive') {
999
- console.log(` 📁 已有归档文件仍保留在磁盘上,但不再可信。`);
1000
- }
1001
- }
1002
-
1003
276
  if (stageData.steps && stageData.steps.length > 0) {
1004
277
  for (const step of stageData.steps) {
1005
278
  const si = statusIcons[step.status] || '○';
1006
279
  const out = step.output ? ` — ${step.output.slice(0, 60)}` : '';
1007
- const waitingTag = step.status === 'waiting' ? ' [WAITING]' : ''
1008
- console.log(` ${si} ${step.name}${out}${waitingTag}`);
1009
- if (step.status === 'waiting') {
1010
- if (step.waitReason) console.log(` 原因:${step.waitReason}`);
1011
- if (step.waitOptions) console.log(` 选项:${(() => { try { const p = JSON.parse(step.waitOptions); return Array.isArray(p) ? p.join(', ') : step.waitOptions; } catch { return step.waitOptions; }})()}`);
1012
- if (step.waitedAt) console.log(` 等待时间:${step.waitedAt}`);
1013
- }
280
+ console.log(` ${si} ${step.name}${out}`);
1014
281
  }
1015
282
  }
1016
283
 
@@ -1031,319 +298,16 @@ export class ProgressManager {
1031
298
  }
1032
299
  }
1033
300
 
1034
- // ── Next 建议 ──
1035
- const suggestion = this._getNextSuggestion(data);
1036
- if (suggestion) {
1037
- console.log('');
1038
- console.log(` 💡 ${suggestion.text}`);
1039
- if (suggestion.command) console.log(` ${suggestion.command}`);
1040
- }
1041
-
1042
- console.log('');
1043
- }
1044
-
1045
- /**
1046
- * 根据当前状态给出下一步建议
1047
- * @param {object} data - progress data
1048
- * @returns {{ text: string, command?: string }|null}
1049
- */
1050
- _getNextSuggestion(data) {
1051
- // 找到第一个 revising 阶段
1052
- const revisingStage = STAGE_ORDER.find(s => data.stages[s]?.status === 'revising');
1053
- if (revisingStage) {
1054
- const sd = data.stages[revisingStage];
1055
- return {
1056
- text: `${STAGE_LABELS[revisingStage] || revisingStage} 正在修订中(revision ${sd.revision || 1}),请继续完成修订。`,
1057
- command: `sillyspec run ${revisingStage}`,
1058
- };
1059
- }
1060
-
1061
- // 找到第一个 stale 阶段(上游已修,下游需要重建)
1062
- const staleStage = STAGE_ORDER.find(s => data.stages[s]?.status === 'stale');
1063
- if (staleStage) {
1064
- const sd = data.stages[staleStage];
1065
- return {
1066
- text: `${STAGE_LABELS[staleStage] || staleStage} 已失效(${sd.staleReason || '上游修订'}),需要从第一步重建。`,
1067
- command: `sillyspec run ${staleStage} --reopen --from-step 1`,
1068
- };
1069
- }
1070
-
1071
- // 找到第一个有 pending/waiting/failed 步骤的 in-progress 阶段
1072
- for (const s of STAGE_ORDER) {
1073
- const sd = data.stages[s];
1074
- if (!sd) continue;
1075
- if (sd.status === 'in-progress' && sd.steps) {
1076
- const hasPending = sd.steps.some(st => ['pending', 'waiting', 'failed'].includes(st.status));
1077
- if (hasPending) {
1078
- return {
1079
- text: `${STAGE_LABELS[s] || s} 进行中,继续执行下一步。`,
1080
- command: `sillyspec run ${s}`,
1081
- };
1082
- }
1083
- }
1084
- }
1085
-
1086
- // 找到第一个 pending 主流程阶段
1087
- for (const s of STAGE_ORDER) {
1088
- const sd = data.stages[s];
1089
- if (sd && sd.status === 'pending' && sd.steps && sd.steps.length > 0) {
1090
- // 检查上游是否都 completed
1091
- const idx = STAGE_ORDER.indexOf(s);
1092
- const upstream = STAGE_ORDER.slice(0, idx);
1093
- const upstreamOk = upstream.every(us =>
1094
- data.stages[us]?.status === 'completed' || !data.stages[us] || data.stages[us].status === 'pending'
1095
- );
1096
- if (upstreamOk) {
1097
- return {
1098
- text: `可以开始 ${STAGE_LABELS[s] || s}。`,
1099
- command: `sillyspec run ${s}`,
1100
- };
1101
- }
1102
- }
1103
- }
1104
-
1105
- return null;
1106
- }
1107
-
1108
- async status(cwd, changeName = null) {
1109
- await this.show(cwd, changeName);
1110
- }
1111
-
1112
- /**
1113
- * Revision v1 状态一致性检查
1114
- * 只报告,不自动修复。
1115
- * @param {string} cwd
1116
- * @param {string|null} changeName
1117
- * @returns {{ ok: boolean, issues: string[], warnings: string[] }}
1118
- */
1119
- async checkConsistency(cwd, changeName = null) {
1120
- const data = await this.read(cwd, changeName);
1121
- if (!data) {
1122
- return { ok: false, issues: ['无法读取进度数据'], warnings: [] };
1123
- }
1124
-
1125
- const issues = [];
1126
- const warnings = [];
1127
-
1128
- for (const stageName of STAGE_ORDER) {
1129
- const sd = data.stages[stageName];
1130
- if (!sd) continue;
1131
-
1132
- // a. completed stage 不能有 pending/stale steps
1133
- if (sd.status === 'completed' && sd.steps) {
1134
- const badSteps = sd.steps.filter(s => ['pending', 'stale', 'in-progress'].includes(s.status));
1135
- for (const step of badSteps) {
1136
- issues.push(`${stageName}/${step.name}: step 状态为 ${step.status},但 stage 状态为 completed`);
1137
- }
1138
- }
1139
-
1140
- // b. revising stage 应有 revision > 0 或 reopenedFromStep
1141
- if (sd.status === 'revising') {
1142
- if (!sd.revision || sd.revision < 1) {
1143
- issues.push(`${stageName}: 状态为 revising 但 revision 缺失或为 0`);
1144
- }
1145
- if (!sd.reopenedFromStep) {
1146
- warnings.push(`${stageName}: 状态为 revising 但未记录 reopenedFromStep`);
1147
- }
1148
- }
1149
-
1150
- // c. stale stage 应有 staleReason
1151
- if (sd.status === 'stale') {
1152
- if (!sd.staleReason) {
1153
- warnings.push(`${stageName}: 状态为 stale 但缺少 staleReason`);
1154
- }
1155
- }
1156
-
1157
- // d. 下游 completed 不能出现在上游 stale/revising 之后
1158
- const stageIdx = STAGE_ORDER.indexOf(stageName);
1159
- for (let i = 0; i < stageIdx; i++) {
1160
- const upstream = STAGE_ORDER[i];
1161
- const upData = data.stages[upstream];
1162
- if (upData && (upData.status === 'stale' || upData.status === 'revising')) {
1163
- if (sd.status === 'completed') {
1164
- issues.push(`${stageName}: 状态为 completed,但上游 ${upstream} 状态为 ${upData.status}(下游不应在上游修订/失效时保持 completed)`);
1165
- }
1166
- }
1167
- }
1168
-
1169
- // e. step stale 时 stage 不应是 completed
1170
- if (sd.status === 'completed' && sd.steps) {
1171
- const staleSteps = sd.steps.filter(s => s.status === 'stale');
1172
- for (const step of staleSteps) {
1173
- issues.push(`${stageName}/${step.name}: step 状态为 stale,但 stage 状态为 completed`);
1174
- }
1175
- }
1176
- }
1177
-
1178
- // 输出报告
1179
- console.log('');
1180
- console.log(' ═══════════════════════════════════════');
1181
- console.log(' 状态一致性检查');
1182
- console.log(' ═══════════════════════════════════════');
1183
-
1184
- if (issues.length === 0 && warnings.length === 0) {
1185
- console.log(' ✅ 未发现一致性问题');
1186
- } else {
1187
- if (issues.length > 0) {
1188
- console.log(`\n ❌ 问题 (${issues.length}):`);
1189
- for (const issue of issues) console.log(` - ${issue}`);
1190
- }
1191
- if (warnings.length > 0) {
1192
- console.log(`\n ⚠️ 警告 (${warnings.length}):`);
1193
- for (const w of warnings) console.log(` - ${w}`);
1194
- }
1195
- }
1196
301
  console.log('');
1197
-
1198
- return { ok: issues.length === 0, issues, warnings };
1199
302
  }
1200
303
 
1201
- /**
1202
- * Revision v1.2 状态修复
1203
- * 默认 dry-run,--apply 才真正修改 DB。
1204
- * 只修安全项,不碰产物文件、不 reset/reopen stage。
1205
- *
1206
- * @param {string} cwd
1207
- * @param {object} opts
1208
- * @param {boolean} [opts.apply=false]
1209
- * @param {string|null} [opts.changeName]
1210
- * @returns {{ fixable: object[], manual: string[], applied: object[] }}
1211
- */
1212
- async repairConsistency(cwd, opts = {}) {
1213
- const { apply = false, changeName = null } = opts;
1214
-
1215
- const data = await this.read(cwd, changeName);
1216
- if (!data) {
1217
- console.log('❌ 无法读取进度数据');
1218
- return { fixable: [], manual: ['无法读取进度数据'], applied: [] };
1219
- }
1220
-
1221
- const fixable = []; // { stage, action, description, apply: (data) => void }
1222
- const manual = []; // string
1223
-
1224
- const now = new Date().toLocaleString('zh-CN', { hour12: false });
1225
-
1226
- for (const stageName of STAGE_ORDER) {
1227
- const sd = data.stages[stageName];
1228
- if (!sd) continue;
1229
-
1230
- // Fix a: stale stage 缺 staleReason → 补默认原因
1231
- if (sd.status === 'stale' && !sd.staleReason) {
1232
- const reason = stageName === 'archive'
1233
- ? 'upstream stage revised; existing archive artifacts are preserved but no longer trusted'
1234
- : 'unknown upstream revision';
1235
- fixable.push({
1236
- stage: stageName,
1237
- action: 'set_stale_reason',
1238
- description: `${stageName}: stale 缺 staleReason → 补 "${reason}"`,
1239
- apply: (d) => { d.stages[stageName].staleReason = reason; },
1240
- });
1241
- }
1242
-
1243
- // Fix b: 上游 stale/revising,下游仍 completed → cascade stale
1244
- const stageIdx = STAGE_ORDER.indexOf(stageName);
1245
- for (let i = 0; i < stageIdx; i++) {
1246
- const upstream = STAGE_ORDER[i];
1247
- const upData = data.stages[upstream];
1248
- if (upData && (upData.status === 'stale' || upData.status === 'revising')) {
1249
- if (sd.status === 'completed') {
1250
- const upStatus = upData.status;
1251
- const reason = `upstream ${upstream} is ${upStatus}`;
1252
- fixable.push({
1253
- stage: stageName,
1254
- action: 'cascade_stale',
1255
- description: `${stageName}: completed → stale(上游 ${upstream} 为 ${upStatus})`,
1256
- apply: (d) => {
1257
- d.stages[stageName].status = 'stale';
1258
- d.stages[stageName].staleReason = reason;
1259
- d.stages[stageName].completedAt = null;
1260
- },
1261
- });
1262
- }
1263
- }
1264
- }
1265
-
1266
- // Fix c: archive stale 缺 staleReason(专用文案)
1267
- if (stageName === 'archive' && sd.status === 'stale' && !sd.staleReason) {
1268
- // 已在 Fix a 中处理,这里不重复
1269
- }
1270
-
1271
- // Fix d: revising stage 缺 reopenedAt → 补当前时间
1272
- if (sd.status === 'revising' && !sd.reopenedAt) {
1273
- fixable.push({
1274
- stage: stageName,
1275
- action: 'set_reopened_at',
1276
- description: `${stageName}: revising 缺 reopenedAt → 补当前时间`,
1277
- apply: (d) => { d.stages[stageName].reopenedAt = now; },
1278
- });
1279
- }
1280
-
1281
- // Manual a: completed stage 里有 pending/stale/in-progress steps
1282
- if (sd.status === 'completed' && sd.steps) {
1283
- const badSteps = sd.steps.filter(s => ['pending', 'stale', 'in-progress'].includes(s.status));
1284
- for (const step of badSteps) {
1285
- manual.push(`${stageName}/${step.name}: step 状态为 ${step.status},但 stage 状态为 completed(需手动确认)`);
1286
- }
1287
- }
1288
-
1289
- // Manual b: revising stage 缺 reopenedFromStep
1290
- if (sd.status === 'revising' && !sd.reopenedFromStep) {
1291
- manual.push(`${stageName}: revising 缺 reopenedFromStep(需手动确认修订起始步骤)`);
1292
- }
1293
-
1294
- // Manual c: steps 为空但 stage completed
1295
- if (sd.status === 'completed' && (!sd.steps || sd.steps.length === 0)) {
1296
- manual.push(`${stageName}: completed 但 steps 为空(需手动确认)`);
1297
- }
1298
- }
1299
-
1300
- // 输出报告
1301
- console.log('');
1302
- console.log(' ═══════════════════════════════════════');
1303
- console.log(` 状态修复 ${apply ? '(--apply 模式)' : '(dry-run 模式)'}`);
1304
- console.log(' ═══════════════════════════════════════');
1305
-
1306
- if (fixable.length === 0 && manual.length === 0) {
1307
- console.log(' ✅ 未发现问题,无需修复');
1308
- console.log('');
1309
- return { fixable: [], manual: [], applied: [] };
1310
- }
1311
-
1312
- const applied = [];
1313
-
1314
- if (fixable.length > 0) {
1315
- console.log(`\n 🔧 可自动修复 (${fixable.length}):`);
1316
- for (const item of fixable) {
1317
- console.log(` - ${item.description}`);
1318
- if (apply) {
1319
- item.apply(data);
1320
- applied.push({ stage: item.stage, action: item.action });
1321
- }
1322
- }
1323
- if (!apply) {
1324
- console.log('\n 💡 使用 --apply 执行修复');
1325
- }
1326
- }
1327
-
1328
- if (manual.length > 0) {
1329
- console.log(`\n 👆 需手动处理 (${manual.length}):`);
1330
- for (const m of manual) console.log(` - ${m}`);
1331
- }
1332
-
1333
- if (apply && applied.length > 0) {
1334
- data.lastActive = now;
1335
- await this._write(cwd, data, changeName);
1336
- console.log(`\n ✅ 已修复 ${applied.length} 项`);
1337
- }
1338
-
1339
- console.log('');
1340
-
1341
- return { fixable, manual, applied };
304
+ status(cwd) {
305
+ this.show(cwd);
1342
306
  }
1343
307
 
1344
- async validate(cwd, changeName = null) {
1345
- const data = await this.read(cwd, changeName);
1346
- if (!data) { console.log('❌ 无法读取进度数据'); return false; }
308
+ async validate(cwd, deep = false) {
309
+ const data = this.read(cwd);
310
+ if (!data) { console.log('❌ 无法读取 progress.json'); return false; }
1347
311
 
1348
312
  const errors = [];
1349
313
  if (!data._version || !Number.isInteger(data._version) || data._version < 1) {
@@ -1352,7 +316,7 @@ export class ProgressManager {
1352
316
  if (!data.stages || typeof data.stages !== 'object') errors.push('缺少 stages');
1353
317
  if (!VALID_STAGES.every(s => data.stages[s])) errors.push('缺少阶段定义');
1354
318
 
1355
- if (errors.length === 0) { console.log('✅ 进度数据格式正确'); return true; }
319
+ if (errors.length === 0) { console.log('✅ progress.json 格式正确'); return true; }
1356
320
 
1357
321
  console.log(`⚠️ 发现问题,尝试修复...`);
1358
322
  let fixed = { ...data, stages: { ...data.stages } };
@@ -1369,283 +333,157 @@ export class ProgressManager {
1369
333
  if (!fixed.stages[s]) { fixed.stages[s] = emptyStage(); changed = true; }
1370
334
  }
1371
335
  if (changed) {
1372
- await this._write(cwd, fixed);
1373
- console.log('✅ 已修复');
1374
- }
1375
-
1376
- return true;
1377
- }
1378
-
1379
- /**
1380
- * 重新打开已完成的阶段进入修订模式
1381
- * - 不带 fromStep:只允许存在 pending/stale/waiting/failed 步骤时继续
1382
- * - fromStep:从该步骤起,当前及后续步骤标记 stale/pending
1383
- * - 自动级联标记下游阶段为 stale
1384
- *
1385
- * @param {string} cwd
1386
- * @param {string} stage - 要重开的阶段
1387
- * @param {object} opts
1388
- * @param {string|number} [opts.fromStep] - 步骤名或序号(1-based)
1389
- * @param {string} [opts.changeName]
1390
- * @returns {{ ok: boolean, error?: string }}
1391
- */
1392
- async reopenStage(cwd, stage, opts = {}) {
1393
- const { fromStep, changeName = null } = opts;
1394
-
1395
- const data = await this.read(cwd, changeName);
1396
- if (!data) return { ok: false, error: '无法读取进度数据' };
1397
-
1398
- const stageData = data.stages[stage];
1399
- if (!stageData) return { ok: false, error: `未知阶段: ${stage}` };
1400
-
1401
- const steps = stageData.steps || [];
1402
-
1403
- // 确定 fromStep 对应的 index
1404
- let fromIdx = null;
1405
- if (fromStep != null) {
1406
- if (typeof fromStep === 'number' || /^\d+$/.test(String(fromStep))) {
1407
- fromIdx = parseInt(String(fromStep), 10) - 1; // 1-based → 0-based
1408
- if (fromIdx < 0 || fromIdx >= steps.length) {
1409
- return { ok: false, error: `步骤序号超出范围: ${fromStep}(共 ${steps.length} 步)` };
1410
- }
1411
- } else {
1412
- // 按名称匹配
1413
- fromIdx = steps.findIndex(s => s.name === fromStep);
1414
- if (fromIdx === -1) {
1415
- return { ok: false, error: `步骤不存在: ${fromStep}` };
1416
- }
1417
- }
1418
- }
1419
-
1420
- // 如果不带 fromStep,检查是否存在中断步骤
1421
- if (fromIdx === null) {
1422
- const hasInterrupted = steps.some(s =>
1423
- ['pending', 'stale', 'waiting', 'failed'].includes(s.status)
1424
- );
1425
- if (!hasInterrupted) {
1426
- return { ok: false, error: `阶段 ${stage} 所有步骤均已完成,请使用 --from-step 指定从哪一步开始修订` };
1427
- }
1428
- // 找到第一个中断步骤
1429
- fromIdx = steps.findIndex(s =>
1430
- ['pending', 'stale', 'waiting', 'failed'].includes(s.status)
1431
- );
1432
- }
1433
-
1434
- // 执行重开操作
1435
- const newRevision = (stageData.revision || 0) + 1;
1436
- const fromStepName = steps[fromIdx].name;
1437
- const now = new Date().toLocaleString('zh-CN', { hour12: false });
1438
-
1439
- // 更新步骤状态:fromStep 之前的保持 completed,fromStep 变 pending,之后的变 stale
1440
- for (let i = 0; i < steps.length; i++) {
1441
- if (i === fromIdx) {
1442
- steps[i].status = 'pending';
1443
- steps[i].completedAt = null;
1444
- steps[i].output = null;
1445
- } else if (i > fromIdx) {
1446
- steps[i].status = 'stale';
1447
- steps[i].completedAt = null;
1448
- }
1449
- // i < fromIdx: 保持原状(completed)
1450
- }
1451
-
1452
- stageData.status = 'revising';
1453
- stageData.completedAt = null;
1454
- stageData.revision = newRevision;
1455
- stageData.reopenedFromStep = `${fromIdx + 1}: ${fromStepName}`; // 存 "index: name" 格式
1456
- stageData.reopenedAt = now;
1457
- stageData.steps = steps;
1458
-
1459
- data.lastActive = now;
1460
- data.currentStage = stage;
1461
-
1462
- await this._write(cwd, data, changeName);
1463
-
1464
- // 级联标记下游阶段为 stale
1465
- const downstreamStages = this._getDownstreamStages(stage);
1466
- if (downstreamStages.length > 0) {
1467
- const data2 = await this.read(cwd, changeName); // 重新读取以获取最新状态
1468
- if (data2) {
1469
- for (const ds of downstreamStages) {
1470
- if (data2.stages[ds] && data2.stages[ds].status === 'completed') {
1471
- data2.stages[ds].status = 'stale';
1472
- data2.stages[ds].staleReason = `上游阶段 ${stage} 已修订 (revision ${newRevision})`;
1473
- data2.stages[ds].completedAt = null;
336
+ this._backup(cwd);
337
+ this._write(cwd, fixed);
338
+ console.log('✅ 已修复并备份');
339
+ }
340
+
341
+ if (deep) {
342
+ try {
343
+ const { deriveState } = await import('./derive.js');
344
+ const result = deriveState(cwd, { mode: 'full', fix: true, pm: this, progress: this.read(cwd) });
345
+ if (result.issues.length > 0) {
346
+ console.log(`\n📋 deriveState 深度校验(${result.issues.length} 项):`);
347
+ for (const issue of result.issues) {
348
+ const icon = issue.severity === 'issue' ? '🔴' : issue.severity === 'warning' ? '🟡' : '⚪';
349
+ console.log(` ${icon} ${issue.stage} step ${issue.step}: ${issue.message}`);
1474
350
  }
351
+ if (result.fixed > 0) console.log(` 🔧 已自动修复 ${result.fixed} 项`);
352
+ } else {
353
+ console.log('✅ deriveState 深度校验通过,无不一致');
1475
354
  }
1476
- await this._write(cwd, data2, changeName);
355
+ } catch (e) {
356
+ console.log(`⚠️ deriveState 校验失败: ${e.message}`);
1477
357
  }
1478
358
  }
1479
359
 
1480
- return { ok: true, revision: newRevision, fromStep: fromStepName };
360
+ return true;
1481
361
  }
1482
362
 
1483
- /**
1484
- * 获取指定阶段的下游主流程阶段列表
1485
- * @param {string} stage
1486
- * @returns {string[]}
1487
- */
1488
- _getDownstreamStages(stage) {
1489
- const idx = MAIN_FLOW_ORDER.indexOf(stage);
1490
- if (idx === -1) return [];
1491
- return MAIN_FLOW_ORDER.slice(idx + 1);
1492
- }
363
+ reset(cwd, stage) {
364
+ this._ensureDir(cwd);
365
+ this._backup(cwd);
1493
366
 
1494
- async reset(cwd, stage, changeName = null) {
1495
367
  if (stage) {
1496
- const data = await this.read(cwd, changeName);
1497
- if (!data) { console.log('❌ 无法读取进度数据'); return; }
368
+ const data = this.read(cwd);
369
+ if (!data) { console.log('❌ 无法读取 progress.json'); return; }
1498
370
  if (!data.stages[stage]) { console.log(`❌ 未知阶段: ${stage}`); return; }
1499
371
  data.stages[stage] = emptyStage();
1500
372
  data.lastActive = new Date().toLocaleString('zh-CN',{hour12:false});
1501
- await this._write(cwd, data);
373
+ this._write(cwd, data);
1502
374
  console.log(`✅ 已重置阶段: ${stage}`);
1503
375
  } else {
1504
- // 重置所有变更或指定变更
1505
- if (changeName) {
1506
- // SQL: 删除该变更的所有 stages 和 steps 数据
1507
- const db = await this._ensureDB(cwd);
1508
- db.transaction((sqlDb) => {
1509
- const changeRow = sqlDb.exec('SELECT id FROM changes WHERE name = ?', [changeName]);
1510
- if (changeRow && changeRow.length > 0 && changeRow[0].values.length > 0) {
1511
- const changeId = changeRow[0].values[0][0];
1512
- sqlDb.run('DELETE FROM steps WHERE stage_id IN (SELECT id FROM stages WHERE change_id = ?)', [changeId]);
1513
- sqlDb.run('DELETE FROM stages WHERE change_id = ?', [changeId]);
1514
- sqlDb.run('UPDATE stages SET status = "pending", started_at = NULL, completed_at = NULL WHERE change_id = ?', [changeId]);
1515
- // 重新插入所有阶段
1516
- for (const s of VALID_STAGES) {
1517
- sqlDb.run('INSERT OR IGNORE INTO stages (change_id, stage, status) VALUES (?, ?, "pending")', [changeId, s]);
1518
- }
1519
- }
1520
- });
1521
- console.log(`✅ 已重置变更 ${changeName} 的进度`);
1522
- } else {
1523
- const changes = await this.listChanges(cwd);
1524
- const db = await this._ensureDB(cwd);
1525
- db.transaction((sqlDb) => {
1526
- for (const cn of changes) {
1527
- const changeRow = sqlDb.exec('SELECT id FROM changes WHERE name = ?', [cn]);
1528
- if (changeRow && changeRow.length > 0 && changeRow[0].values.length > 0) {
1529
- const changeId = changeRow[0].values[0][0];
1530
- sqlDb.run('DELETE FROM steps WHERE stage_id IN (SELECT id FROM stages WHERE change_id = ?)', [changeId]);
1531
- sqlDb.run('UPDATE stages SET status = "pending", started_at = NULL, completed_at = NULL WHERE change_id = ?', [changeId]);
1532
- }
1533
- }
1534
- });
1535
- console.log('✅ 已重置所有变更的进度');
1536
- }
376
+ const p = this._path(cwd, PROGRESS_FILE);
377
+ const backup = this._path(cwd, BACKUP_FILE);
378
+ let didReset = false;
379
+ if (existsSync(p)) { unlinkSync(p); didReset = true; }
380
+ if (existsSync(backup)) { unlinkSync(backup); didReset = true; }
381
+ if (didReset) console.log(' 已重置所有进度(备份已保留)');
382
+ else console.log('ℹ️ 无进度文件可重置');
1537
383
  }
1538
384
  }
1539
385
 
386
+ complete(cwd, stage) {
387
+ this.completeStage(cwd, stage);
388
+ }
389
+
1540
390
  // ── 内部辅助 ──
1541
391
 
1542
- async _readOrInit(cwd, changeName = null) {
1543
- let data = await this.read(cwd, changeName);
392
+ _readOrInit(cwd) {
393
+ let data = this.read(cwd);
1544
394
  if (!data) {
1545
- // 尝试自动检测变更名
1546
- if (!changeName) {
1547
- const changes = await this.listChanges(cwd);
1548
- if (changes.length === 1) changeName = changes[0];
1549
- }
1550
- if (changeName) {
1551
- // 确保变更在 DB 中已初始化
1552
- const db = await this._ensureDB(cwd);
1553
- db.transaction((sqlDb) => {
1554
- const now = new Date().toISOString();
1555
- sqlDb.run(
1556
- 'INSERT OR IGNORE INTO changes (name, current_stage, status, created_at, last_active) VALUES (?, "scan", "active", ?, ?)',
1557
- [changeName, now, now]
1558
- );
1559
- const changeRow = sqlDb.exec('SELECT id FROM changes WHERE name = ?', [changeName]);
1560
- if (changeRow && changeRow.length > 0 && changeRow[0].values.length > 0) {
1561
- const changeId = changeRow[0].values[0][0];
1562
- for (const s of VALID_STAGES) {
1563
- sqlDb.run('INSERT OR IGNORE INTO stages (change_id, stage, status) VALUES (?, ?, "pending")', [changeId, s]);
1564
- }
1565
- }
1566
- });
1567
- await this.registerChange(cwd, changeName);
1568
- }
1569
- if (!data) {
1570
- data = await this.read(cwd, changeName);
1571
- }
1572
- if (!data) {
1573
- console.log('❌ 无法确定当前变更,请指定 --change <name>');
395
+ this._ensureDir(cwd);
396
+ const progressPath = this._path(cwd, PROGRESS_FILE);
397
+ if (!existsSync(progressPath)) {
398
+ data = makeInitialProgress(basename(cwd));
399
+ this._write(cwd, data);
400
+ } else {
401
+ console.log('❌ progress.json 损坏,请运行 sillyspec progress validate');
1574
402
  return null;
1575
403
  }
1576
404
  }
1577
405
  return data;
1578
406
  }
1579
407
 
1580
- async _requireStage(cwd, stage, changeName = null) {
408
+ _requireStage(cwd, stage) {
1581
409
  if (!VALID_STAGES.includes(stage)) {
1582
410
  console.log(`❌ 未知阶段: ${stage},可选: ${VALID_STAGES.join(', ')}`);
1583
411
  return null;
1584
412
  }
1585
- const data = await this._readOrInit(cwd, changeName);
413
+ const data = this._readOrInit(cwd);
1586
414
  if (!data) return null;
1587
415
  if (!data.stages[stage]) data.stages[stage] = emptyStage();
1588
416
  return data;
1589
417
  }
1590
418
 
419
+ _parseWithRecovery(jsonString) {
420
+ try { return JSON.parse(jsonString); } catch {}
421
+
422
+ let fixed = jsonString.replace(/,\s*([}\]])/g, '$1');
423
+ fixed = fixed.replace(/([{,]\s*)'([^']+)'(\s*:)/g, '$1"$2"$3');
424
+ fixed = fixed.replace(/:\s*'([^']*)'([,}\]])/g, ':"$1"$2');
425
+ try { return JSON.parse(fixed); } catch {}
426
+
427
+ const lastBrace = fixed.lastIndexOf('}');
428
+ if (lastBrace > 0) {
429
+ let open = 0;
430
+ for (const ch of fixed.substring(0, lastBrace + 1)) {
431
+ if (ch === '{') open++;
432
+ if (ch === '}') open--;
433
+ }
434
+ try { return JSON.parse(fixed.substring(0, lastBrace + 1) + '}'.repeat(Math.max(0, open))); } catch {}
435
+ }
436
+ return null;
437
+ }
438
+
1591
439
  _timeAgo(dateStr) {
1592
440
  if (!dateStr) return '未知';
1593
441
  let ts = Date.parse(dateStr);
1594
442
  if (isNaN(ts)) {
1595
- const m = dateStr.match(/(\d{4})[\/-](\d{1,2})[\/-](\d{1,2})[\s,]+(\d{1,2}):(\d{2})(?::(\d{2}))?/);
1596
- if (m) ts = new Date(+m[1], +m[2]-1, +m[3], +m[4], +m[5], +(m[6]||0)).getTime();
443
+ // fallback: 解析 zh-CN toLocaleString 格式 "2024/1/1 12:00:00"
444
+ const m = String(dateStr).match(/(\d{4})\/(\d{1,2})\/(\d{1,2})[\s]+(\d{1,2}):(\d{1,2}):(\d{1,2})/);
445
+ if (m) {
446
+ ts = new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]).getTime();
447
+ }
1597
448
  }
1598
449
  if (isNaN(ts)) return dateStr;
1599
450
  const diff = Date.now() - ts;
1600
- const minutes = Math.floor(diff / 60000);
1601
- if (minutes < 1) return '刚刚';
1602
- if (minutes < 60) return `${minutes} 分钟前`;
1603
- const hours = Math.floor(minutes / 60);
1604
- if (hours < 24) return `${hours} 小时前`;
1605
- return `${Math.floor(hours / 24)} 天前`;
451
+ const m2 = Math.floor(diff / 60000);
452
+ if (m2 < 1) return '刚刚';
453
+ if (m2 < 60) return `${m2} 分钟前`;
454
+ const h = Math.floor(m2 / 60);
455
+ if (h < 24) return `${h} 小时前`;
456
+ return `${Math.floor(h / 24)} 天前`;
1606
457
  }
1607
458
 
1608
459
  // ── 批量进度 ──
1609
460
 
1610
- async updateBatchProgress(cwd, batchData, changeName = null) {
1611
- const cn = changeName || null;
461
+ updateBatchProgress(cwd, batchData) {
462
+ const data = this._readOrInit(cwd);
463
+ if (!data) return;
1612
464
 
1613
- const db = await this._ensureDB(cwd);
1614
- db.transaction((sqlDb) => {
1615
- // 获取 change_id
1616
- let changeId = null;
1617
- if (cn) {
1618
- const row = sqlDb.exec('SELECT id FROM changes WHERE name = ?', [cn]);
1619
- if (row && row.length > 0 && row[0].values.length > 0) changeId = row[0].values[0][0];
1620
- }
1621
- if (!changeId) {
1622
- // 尝试从唯一活跃变更获取
1623
- const rows = sqlDb.exec("SELECT id FROM changes WHERE status = 'active'");
1624
- if (rows && rows.length > 0 && rows[0].values.length === 1) changeId = rows[0].values[0][0];
1625
- }
1626
- if (!changeId) return;
1627
-
1628
- sqlDb.run(
1629
- `INSERT INTO batch_progress (change_id, total, completed, failed, skipped)
1630
- VALUES (?, ?, ?, ?, ?)
1631
- ON CONFLICT(change_id) DO UPDATE SET
1632
- total = excluded.total,
1633
- completed = excluded.completed,
1634
- failed = excluded.failed,
1635
- skipped = excluded.skipped`,
1636
- [changeId, batchData.total || 0, batchData.completed || 0, batchData.failed || 0, batchData.skipped || 0]
1637
- );
1638
- });
465
+ if (!data.batchProgress) {
466
+ data.batchProgress = { total: 0, completed: 0, failed: 0, skipped: 0 };
467
+ }
468
+ if (batchData.total !== undefined) data.batchProgress.total = batchData.total;
469
+ if (batchData.completed !== undefined) data.batchProgress.completed = batchData.completed;
470
+ if (batchData.failed !== undefined) data.batchProgress.failed = batchData.failed;
471
+ if (batchData.skipped !== undefined) data.batchProgress.skipped = batchData.skipped;
472
+
473
+ data.lastActive = new Date().toLocaleString('zh-CN', { hour12: false });
474
+ this._backup(cwd);
475
+ this._write(cwd, data);
1639
476
  }
1640
477
 
1641
- async readBatchProgress(cwd, changeName = null) {
1642
- const data = await this.read(cwd, changeName);
478
+ readBatchProgress(cwd) {
479
+ const data = this.read(cwd);
1643
480
  return data?.batchProgress || null;
1644
481
  }
1645
482
 
1646
483
  _renderBatchProgress(batchProgress) {
1647
484
  if (!batchProgress || !batchProgress.total) return null;
1648
485
  const { total, completed = 0, failed = 0, skipped = 0 } = batchProgress;
486
+ const done = Math.min(completed + failed + skipped, total);
1649
487
  const barLen = 20;
1650
488
  const filled = Math.round((completed / total) * barLen);
1651
489
  const bar = '█'.repeat(filled) + '░'.repeat(barLen - filled);
@@ -1656,71 +494,7 @@ export class ProgressManager {
1656
494
  return `📊 批量进度: ${bar} ${completed}/${total}${suffix}`;
1657
495
  }
1658
496
 
1659
- /**
1660
- * 更新 gate-status.json,供 worktree-guard hook 读取
1661
- * 从 SQLite 查询所有处于 execute/quick 阶段的活跃变更,生成或删除 gate-status.json
1662
- */
1663
- async _updateGateStatus(cwd) {
1664
- const db = await this._ensureDB(cwd);
1665
- const sqlDb = db.getDb();
1666
-
1667
- // SQL 查询:所有处于 execute/quick 阶段的活跃变更
1668
- const rows = sqlDb.exec(
1669
- `SELECT name, current_stage, no_worktree FROM changes
1670
- WHERE status = 'active' AND current_stage IN ('execute', 'quick')`
1671
- );
1672
-
1673
- const gatePath = this._runtimePath(cwd, 'gate-status.json');
1674
-
1675
- if (!rows || rows.length === 0 || rows[0].values.length === 0) {
1676
- // 无 execute/quick 阶段的活跃变更,删除 gate-status
1677
- if (existsSync(gatePath)) {
1678
- try { unlinkSync(gatePath); } catch {}
1679
- }
1680
- return;
1681
- }
1682
-
1683
- let gateStage = null;
1684
- let hasNoWorktree = false;
1685
- const activeChanges = [];
1686
-
1687
- for (const [name, stage, noWorktree] of rows[0].values) {
1688
- if (!stage) continue;
1689
- // 优先取 execute,其次 quick
1690
- if (gateStage !== 'execute' || stage === 'execute') {
1691
- gateStage = stage;
1692
- }
1693
- activeChanges.push(name);
1694
- if (noWorktree === 1) hasNoWorktree = true;
1695
- }
1696
-
1697
- if (!gateStage) {
1698
- // current_stage 为 NULL 的边界情况,等同于无 execute/quick
1699
- if (existsSync(gatePath)) {
1700
- try { unlinkSync(gatePath); } catch {}
1701
- }
1702
- return;
1703
- }
1704
-
1705
- try {
1706
- this._ensureRuntimeDir(cwd);
1707
- const gateData = {
1708
- stage: gateStage,
1709
- changes: activeChanges,
1710
- updatedAt: new Date().toISOString(),
1711
- ...(hasNoWorktree ? { noWorktree: true } : {}),
1712
- };
1713
- const tmpPath = gatePath + '.tmp';
1714
- writeFileSync(tmpPath, JSON.stringify(gateData, null, 2) + '\n');
1715
- renameSync(tmpPath, gatePath);
1716
- } catch (err) {
1717
- console.warn('⚠️ 写入 gate-status.json 失败:', err.message);
1718
- }
1719
- }
1720
-
1721
497
  _ensureGitignore(cwd) {
1722
- // 外部 specDir 不需要修改项目 .gitignore
1723
- if (this._customSpecDir) return;
1724
498
  const gitignorePath = join(cwd, '.gitignore');
1725
499
  const rule = '.sillyspec/.runtime/';
1726
500
  if (existsSync(gitignorePath)) {