@rowansenne/workflow-run 0.26.1 → 0.28.0

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 (71) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +68 -38
  3. package/bin/lib/artifact-context.mjs +46 -0
  4. package/bin/lib/docnexus.mjs +4 -4
  5. package/bin/lib/doctor.mjs +1 -2
  6. package/bin/lib/install.mjs +1 -1
  7. package/bin/lib/uninstall.mjs +3 -0
  8. package/bin/workflow-run.mjs +20 -29
  9. package/code-graph/SKILL.md.tpl +2 -7
  10. package/create-release-md-doc/SKILL.md.tpl +12 -13
  11. package/create-tech-md-doc/SKILL.md.tpl +12 -13
  12. package/database-query/SKILL.md.tpl +2 -0
  13. package/database-query/skill.json +2 -2
  14. package/dev/SKILL.md.tpl +42 -116
  15. package/dev/references/bug.md +32 -0
  16. package/dev/references/delivery-template.md +6 -6
  17. package/dev/references/delivery.md +50 -0
  18. package/dev/references/implementation.md +23 -0
  19. package/dev/references/plan-template.md +5 -3
  20. package/dev/references/planning.md +45 -0
  21. package/dev/references/preflight.md +35 -0
  22. package/dev/skill.json +2 -2
  23. package/md-to-wiki/SKILL.md.tpl +5 -1
  24. package/md-to-wiki/skill.json +2 -2
  25. package/package.json +2 -2
  26. package/project-review/SKILL.md.tpl +46 -72
  27. package/project-review/references/report.md.tpl +4 -4
  28. package/project-review/references/reporting.md +48 -0
  29. package/project-review/references/review-method.md +56 -0
  30. package/project-review/references/verification.md +30 -0
  31. package/shared/prd-fetch.md +1 -1
  32. package/workflow/SKILL.md.tpl +16 -16
  33. package/workflow/lib/artifact-finalize.mjs +144 -0
  34. package/workflow/lib/artifact-model.mjs +83 -0
  35. package/workflow/lib/capabilities.mjs +80 -0
  36. package/workflow/lib/code-snapshot.mjs +55 -0
  37. package/workflow/lib/document-model.mjs +86 -0
  38. package/workflow/lib/meta-store.mjs +114 -0
  39. package/workflow/lib/path-match.mjs +21 -0
  40. package/workflow/lib/project.mjs +218 -0
  41. package/workflow/lib/requirement-read.mjs +68 -0
  42. package/workflow/lib/requirements.mjs +224 -0
  43. package/workflow/lib/run-gates.mjs +136 -0
  44. package/workflow/lib/runs.mjs +188 -0
  45. package/workflow/lib/workspace-read.mjs +122 -0
  46. package/workflow/references/architecture.md +53 -0
  47. package/workflow/references/capabilities.md +39 -0
  48. package/workflow/references/codegraph.md +3 -3
  49. package/workflow/references/docnexus.md +1 -1
  50. package/workflow/references/execution.md +95 -0
  51. package/workflow/references/requirements.md +36 -25
  52. package/workflow/references/runs.md +100 -0
  53. package/workflow/references/status.md +7 -3
  54. package/workflow/references/templates.md +11 -14
  55. package/workflow/scripts/artifact.mjs +39 -0
  56. package/workflow/scripts/artifacts.mjs +21 -80
  57. package/workflow/scripts/doc-sections.mjs +2 -55
  58. package/workflow/scripts/docnexus-layout.mjs +2 -24
  59. package/workflow/scripts/knowledge.mjs +4 -2
  60. package/workflow/scripts/lint-doc.mjs +2 -35
  61. package/workflow/scripts/meta-store.mjs +2 -0
  62. package/workflow/scripts/pr-desc.mjs +8 -6
  63. package/workflow/scripts/report.mjs +20 -68
  64. package/workflow/scripts/requirement.mjs +9 -402
  65. package/workflow/scripts/resolve.mjs +22 -190
  66. package/workflow/scripts/review-handoff.mjs +59 -0
  67. package/workflow/scripts/review-scope.mjs +4 -22
  68. package/workflow/scripts/run.mjs +35 -0
  69. package/workflow/scripts/tables.mjs +1 -1
  70. package/workflow/scripts/template.mjs +2 -6
  71. package/workflow/scripts/view.mjs +41 -21
@@ -0,0 +1,224 @@
1
+ // 需求绑定、产物版本与索引写入;调用只读查询和底层原子存储。
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { spawnSync } from 'node:child_process';
5
+ import { updateMeta } from './meta-store.mjs';
6
+ import { FILES, LABELS, parseFile, parseBranch, parseWiki, parseDocnexus, headerDate } from './artifact-model.mjs';
7
+ import { HOME, REQ_DIR, TMP_DIR, dirName, profileDir, layout, setConfig } from './project.mjs';
8
+ import { requirements, repoRequirements, find } from './requirement-read.mjs';
9
+ import { loadWorkspace } from './workspace-read.mjs';
10
+ const git = (cwd, args) => spawnSync('git', args, { cwd, encoding: 'utf8' });
11
+ const readJson = (f) => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return null; } };
12
+ const relOf = (root, abs) => path.relative(root, abs).split(path.sep).join('/');
13
+ const toPosix = (p) => p.split(path.sep).join('/');
14
+ const now = () => new Date().toISOString();
15
+ const isDir = (p) => { try { return fs.statSync(p).isDirectory(); } catch { return false; } };
16
+ const skipDir = (d) => !d.isDirectory() || d.name.startsWith('.');
17
+
18
+ // 同种产物只留最新版,文件名固定(review.md、tech-doc.md …),文档里的引用不会失效。版本号记在 meta.json 的 versions。
19
+ // path 时把当前版复制到 workflow-run/tmp/old-artifacts/<需求目录(相对 requirements/)>/<种类>_v<N>.md(不提交),
20
+ // 写完 sync <path> 时新版内容和这份副本不同才算新版本(versions 加一);没写就放弃的话版本号不变
21
+ export const OLD_DIR = `${TMP_DIR}/old-artifacts`;
22
+ const archivePath = (root, dirAbs, kind, v) => path.join(root, OLD_DIR, path.relative(path.join(root, REQ_DIR), dirAbs), `${FILES[kind]}_v${v}.md`);
23
+ const versionsOf = (dirAbs) => readJson(path.join(dirAbs, 'meta.json'))?.versions ?? {};
24
+
25
+ export function indexArtifacts(dir, versions = {}) {
26
+ return fs.readdirSync(dir).map((name) => {
27
+ const p = parseFile(name);
28
+ if (!p) return null;
29
+ const text = fs.readFileSync(path.join(dir, name), 'utf8');
30
+ return { kind: p.kind, version: name === `${FILES[p.kind]}.md` ? versions[p.kind] ?? 1 : p.version, file: name, branch: parseBranch(text), date: headerDate(text), wiki: parseWiki(text), docnexus: parseDocnexus(text) };
31
+ }).filter(Boolean).sort((a, b) => Object.keys(FILES).indexOf(a.kind) - Object.keys(FILES).indexOf(b.kind) || a.version - b.version);
32
+ }
33
+
34
+ // 按目录里的文件重建 meta.json(保留需求名、分支、创建时间)
35
+ // bump:写完新版后(sync <path>)确认新版本——和 path 时归档的上一版副本内容不同就把版本号加一,返回归档了哪些
36
+ export function sync(root, dirRel, { bump = false } = {}) {
37
+ const dir = path.resolve(root, dirRel);
38
+ const f = path.join(dir, 'meta.json');
39
+ const archived = [];
40
+ const result = updateMeta(f, (old) => {
41
+ const versions = { ...(old.versions ?? {}) };
42
+ if (bump) {
43
+ for (const kind of Object.keys(FILES)) {
44
+ const cur = path.join(dir, `${FILES[kind]}.md`);
45
+ const v = versions[kind] ?? 1;
46
+ const arc = archivePath(root, dir, kind, v);
47
+ if (!fs.existsSync(cur) || !fs.existsSync(arc) || fs.readFileSync(arc).equals(fs.readFileSync(cur))) continue;
48
+ versions[kind] = v + 1;
49
+ archived.push({ kind, version: v, file: relOf(root, arc) });
50
+ }
51
+ }
52
+ const artifacts = indexArtifacts(dir, versions);
53
+ const branches = old.branches ?? []; // 绑定只由 bind 更新;文档头不隐式修改需求归属。
54
+ const latest = Object.fromEntries(Object.keys(FILES).map((k) => [k, artifacts.filter((a) => a.kind === k).at(-1)?.file ?? null]));
55
+ // 内容没变就不写(meta.json 随需求目录提交,避免无谓的改动);产物有变化才更新 updated
56
+ const changed = JSON.stringify(old.artifacts ?? null) !== JSON.stringify(artifacts) || JSON.stringify(old.branches ?? null) !== JSON.stringify(branches);
57
+ const meta = {
58
+ ...old,
59
+ name: old.name ?? path.basename(dir), named_by: old.named_by ?? 'user', ...(old.project ? { project: old.project } : {}), branches, base: old.base ?? null,
60
+ created: old.created ?? now(), updated: changed || !old.updated ? now() : old.updated, latest, ...(Object.keys(versions).length ? { versions } : {}), artifacts,
61
+ };
62
+ return meta;
63
+ }, { root });
64
+ return bump ? { ...result, archived } : result;
65
+ }
66
+
67
+ const notReady = (L) => ({ ok: false, mode: L.mode, ...(L.need_project ? { need_project: true, suggested_project: L.suggested_project } : {}), hint: L.hint });
68
+
69
+ export function which(root, branch) {
70
+ const L = layout(root);
71
+ if (!L.ok) return notReady(L);
72
+ const r = find(root, branch, L);
73
+ const where = L.mode === 'repo' ? { mode: 'repo', repo: L.repo_rel, project: L.project } : { mode: 'project', project: L.project };
74
+ if (r) return { bound: true, ...where, branch, name: r.name, dir: r.dir, meta: r.meta.pending_finalization ? r.meta : sync(root, r.dir) };
75
+ const recent = requirements(root, L).sort((a, b) => String(b.updated).localeCompare(String(a.updated))).slice(0, 5).map(({ name, dir, branches, updated }) => ({ name, dir, branches, updated }));
76
+ // 其他项目已有的需求(跨服务需求,本项目可以用同一个名字加入);文档仓库里常见,随代码提交时一般没有
77
+ const mine = new Set(requirements(root, L).map((x) => x.slug));
78
+ const others = repoRequirements(root, L).filter((x) => !mine.has(x.slug)).sort((a, b) => String(b.updated).localeCompare(String(a.updated))).slice(0, 10).map((x) => ({ name: x.name, projects: x.projects.map((p) => p.project), updated: x.updated }));
79
+ return {
80
+ bound: false, ...where, branch, suggested_name: branch ? dirName(branch.replace(/\//g, '-')) : null, recent, ...(others.length || L.mode === 'repo' ? { other_projects: others } : {}),
81
+ hint: `当前分支还没有绑定需求:问用户这个需求叫什么(给出 suggested_name 作为默认;也可以选 recent 里已有的需求继续${others.length || L.mode === 'repo' ? ',或加入 other_projects 里其他服务已有的需求' : ''}),然后运行 bind --name <需求名>;用户不给就运行 bind(按分支名生成)。`,
82
+ };
83
+ }
84
+
85
+ export function bind(root, { name = null, branch, base = null }) {
86
+ const L = layout(root);
87
+ if (!L.ok) return notReady(L);
88
+ if (!branch) return { ok: false, error: '无法确定当前分支(detached HEAD?),请用 --branch 指定' };
89
+ const named = name != null && String(name).trim() !== '';
90
+ const display = named ? String(name).trim() : branch.replace(/\//g, '-');
91
+ // 同名需求沿用(按所有项目找,跨服务的需求共用一个目录);目录名被别的需求占了就加 -2、-3
92
+ const pool = repoRequirements(root, L).map((r) => ({ slug: r.slug, name: r.name }));
93
+ const target = pool.find((r) => r.name === display) ?? null;
94
+ let slug = target?.slug;
95
+ if (!slug) {
96
+ slug = dirName(display);
97
+ for (let i = 2; pool.some((r) => r.slug === slug) || isDir(L.reqDir(slug)); i++) slug = `${dirName(display)}-${i}`;
98
+ }
99
+ // 随代码提交时项目名是自动取的:第一次落盘时写进 profile.json 固定下来,之后改了 git 远端名也不会换目录
100
+ // (只在项目里装过 skills、有 profile.json 时写;直接从安装包运行脚本时不写)
101
+ if (!L.project_configured && fs.existsSync(path.join(profileDir(root), 'profile.json'))) setConfig(root, { project: L.project });
102
+ const dir = L.reqDir(slug);
103
+ const existedHere = isDir(dir);
104
+ fs.mkdirSync(dir, { recursive: true });
105
+ const f = path.join(dir, 'meta.json');
106
+ const meta = updateMeta(f, (old) => {
107
+ const value = Object.keys(old).length ? old : { name: target?.name ?? display, named_by: named ? 'user' : 'branch', project: L.project, branches: [], base, created: now() };
108
+ if (!value.branches.includes(branch)) value.branches.push(branch);
109
+ if (base && !value.base) value.base = base;
110
+ value.updated = now();
111
+ return value;
112
+ }, { root });
113
+ const rel = relOf(root, dir);
114
+ return { ok: true, mode: L.mode, created: !existedHere, joined: !!target && !existedHere, name: meta.name, named_by: meta.named_by, dir: rel, project: L.project, branches: sync(root, rel).branches };
115
+ }
116
+
117
+ // 本次落盘路径:文件名固定(review.md …),已有时先把当前版复制到 tmp/old-artifacts/<种类>_v<N>.md(previous,复审对照用),
118
+ // 并带上它第一行的 wiki 发布记录;新版直接写到 path(覆盖当前版),写完 sync <path> 确认版本号
119
+ export function nextPath(root, kind, branch) {
120
+ if (!FILES[kind]) return { code: 1, out: { ok: false, error: `未知产物种类「${kind}」:${Object.keys(FILES).join(' / ')}` } };
121
+ const L = layout(root);
122
+ if (!L.ok) return { code: 2, out: notReady(L) };
123
+ const r = find(root, branch, L);
124
+ if (!r) return { code: 2, out: { ok: false, ...which(root, branch) } };
125
+ if (r.meta.pending_finalization) return { code: 1, out: { ok: false, hint: `产物收尾尚未完成,先运行 artifact.mjs resume --id ${r.meta.pending_finalization.run_id}` } };
126
+ const abs = path.join(r.abs, `${FILES[kind]}.md`);
127
+ let v = 1; let previous = null; let record = null;
128
+ if (fs.existsSync(abs)) {
129
+ const cur = versionsOf(r.abs)[kind] ?? 1;
130
+ const arc = archivePath(root, r.abs, kind, cur);
131
+ fs.mkdirSync(path.dirname(arc), { recursive: true });
132
+ fs.copyFileSync(abs, arc);
133
+ v = cur + 1; previous = relOf(root, arc);
134
+ record = /^<!-- md-to-wiki: [^\n]*-->/.exec(fs.readFileSync(abs, 'utf8'))?.[0] ?? null;
135
+ }
136
+ return { code: 0, out: { ok: true, mode: L.mode, name: r.name, dir: r.dir, path: relOf(root, abs), cite: L.ref(abs), version: v, previous, wiki_record: record } };
137
+ }
138
+
139
+ export function list(root) {
140
+ const workspace = loadWorkspace(root);
141
+ return workspace.requirements.map((r) => {
142
+ const artifacts = workspace.artifacts.filter((a) => a.requirement === r.slug && a.project === r.project).sort((a, b) => a.version - b.version);
143
+ const latest = Object.fromEntries(Object.keys(FILES).map((kind) => [kind, artifacts.filter((a) => a.kind === kind).at(-1)?.path.split('/').at(-1) ?? null]));
144
+ return { name: r.name, dir: r.dir, branches: r.branches, named_by: r.meta.named_by, created: r.meta.created, artifacts: artifacts.length, latest,
145
+ ...(!r.valid ? { diagnostics: workspace.diagnostics.filter((d) => d.path.startsWith(r.dir + '/')) } : {}) };
146
+ }).sort((a, b) => String(b.created).localeCompare(String(a.created)));
147
+ }
148
+
149
+ // ------------------------------------------------------------------ 文档仓库的提交提示
150
+ // 当前需求(或给定目录)在文档仓库里未提交的改动;项目模式下产物随代码提交,不单独提示
151
+ export function pending(root, branch, dirRel = null) {
152
+ const L = layout(root);
153
+ if (L.mode === 'project') return { mode: 'project', commit_prompt: false, note: `产物在项目仓库的 ${HOME}/ 里,随代码一起提交` };
154
+ if (!L.ok) return notReady(L);
155
+ const abs = dirRel ? path.resolve(root, dirRel) : find(root, branch, L)?.abs;
156
+ if (!abs) return { ok: false, mode: 'repo', error: '当前分支没有绑定需求' };
157
+ const inRepo = toPosix(path.relative(L.repo, abs));
158
+ const top = git(L.repo, ['rev-parse', '--show-toplevel']);
159
+ if (top.status !== 0) return { ok: true, mode: 'repo', repo: L.repo_rel, is_git: false, files: [], commit_prompt: L.commit_prompt, note: '文档仓库还不是 git 仓库,产物只保存在本地' };
160
+ const st = git(L.repo, ['-c', 'core.quotePath=false', 'status', '--porcelain', '--untracked-files=all', '--', inRepo]);
161
+ const files = st.stdout.split('\n').filter(Boolean).map((l) => l.slice(3));
162
+ const meta = readJson(path.join(abs, 'meta.json')) ?? {};
163
+ const kinds = [...new Set(files.map((f) => parseFile(path.basename(f))?.kind).filter(Boolean))].map((k) => LABELS[k]);
164
+ const message = `docs(${meta.name ?? path.basename(path.dirname(abs))}): ${L.project}${kinds.length ? ` ${kinds.join('、')}` : ' 更新产物'}`;
165
+ // DocNexus 也在这个文档仓库里(workflow-run/docnexus/):知识库的改动单独列出,单独提交,提交信息写沉淀了什么
166
+ const kn = isDir(path.join(L.repo, 'docnexus', 'library'))
167
+ ? git(L.repo, ['-c', 'core.quotePath=false', 'status', '--porcelain', '--untracked-files=all', '--', 'docnexus']).stdout.split('\n').filter(Boolean).map((l) => l.slice(3))
168
+ : [];
169
+ return {
170
+ ok: true, mode: 'repo', repo: L.repo_rel, is_git: true, project: L.project, dir: relOf(root, abs), files, commit_prompt: L.commit_prompt,
171
+ suggested_message: files.length ? message : null,
172
+ commands: files.length ? [`git -C ${JSON.stringify(L.repo_rel)} add -- ${JSON.stringify(inRepo)}`, `git -C ${JSON.stringify(L.repo_rel)} commit -m ${JSON.stringify(message)}`] : [],
173
+ ...(kn.length ? { knowledge_files: kn, knowledge_commands: [`git -C ${JSON.stringify(L.repo_rel)} add -- docnexus`, `git -C ${JSON.stringify(L.repo_rel)} commit -m "knowledge: <沉淀了什么>"`] } : {}),
174
+ };
175
+ }
176
+
177
+ // ------------------------------------------------------------------ 旧结构迁移
178
+ // 旧版本随代码提交时没有 <项目名>/ 这一层:文件直接放在 docs/requirements/<需求>/ 下。
179
+ // 列出这样的需求目录(目录里直接有文件的;隐藏文件不算)
180
+ export function legacyRequirements(root) {
181
+ const base = path.join(root, REQ_DIR);
182
+ if (!isDir(base)) return [];
183
+ return fs.readdirSync(base, { withFileTypes: true }).filter((d) => !skipDir(d)).map((d) => d.name)
184
+ .filter((slug) => fs.readdirSync(path.join(base, slug), { withFileTypes: true }).some((e) => e.isFile() && !e.name.startsWith('.')));
185
+ }
186
+
187
+ // 把旧结构的需求目录挪到 <需求>/<项目名>/:被 git 跟踪的用 git mv(保留历史),其余直接移动;
188
+ // tmp/old-artifacts/<需求>/ 下归档的上一版也一起挪,复审对照还能找到。
189
+ // 目标里已有同名文件时这个需求整个跳过,留给用户处理。项目名没配置时按 layout 自动取的写进 profile.json。
190
+ // 返回 { project, moved: [{ from, to }], skipped: [{ dir, reason }] }
191
+ export function migrateLayout(root) {
192
+ const L = layout(root);
193
+ const slugs = legacyRequirements(root);
194
+ if (!slugs.length) return { project: L.project, moved: [], skipped: [] };
195
+ if (!L.project) return { project: null, moved: [], skipped: slugs.map((s) => ({ dir: `${REQ_DIR}/${s}`, reason: '还没配置项目名' })) };
196
+ const repoOf = (abs) => (L.mode === 'repo' ? L.repo : root);
197
+ const tracked = (abs) => git(repoOf(abs), ['ls-files', '--error-unmatch', '--', path.relative(repoOf(abs), abs)]).status === 0;
198
+ const moved = []; const skipped = [];
199
+ const move = (from, to, useGit) => {
200
+ fs.mkdirSync(path.dirname(to), { recursive: true });
201
+ const cwd = repoOf(from);
202
+ if (useGit && tracked(from) && git(cwd, ['mv', '--', path.relative(cwd, from), path.relative(cwd, to)]).status === 0) return;
203
+ fs.renameSync(from, to);
204
+ };
205
+ for (const slug of slugs) {
206
+ const dir = path.join(L.base, slug);
207
+ const files = fs.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile() && !e.name.startsWith('.')).map((e) => e.name);
208
+ const target = path.join(dir, L.project);
209
+ const clash = files.filter((f) => fs.existsSync(path.join(target, f)));
210
+ if (clash.length) { skipped.push({ dir: relOf(root, dir), reason: `${relOf(root, target)} 里已有 ${clash.join('、')}` }); continue; }
211
+ for (const f of files) {
212
+ move(path.join(dir, f), path.join(target, f), true);
213
+ moved.push({ from: relOf(root, path.join(dir, f)), to: relOf(root, path.join(target, f)) });
214
+ }
215
+ const m = readJson(path.join(target, 'meta.json'));
216
+ if (m && m.project !== L.project) fs.writeFileSync(path.join(target, 'meta.json'), `${JSON.stringify({ ...m, project: L.project }, null, 2)}\n`);
217
+ const old = path.join(root, OLD_DIR, slug);
218
+ if (isDir(old)) {
219
+ for (const e of fs.readdirSync(old, { withFileTypes: true })) if (e.isFile()) move(path.join(old, e.name), path.join(old, L.project, e.name), false);
220
+ }
221
+ }
222
+ if (moved.length && !L.project_configured && fs.existsSync(path.join(profileDir(root), 'profile.json'))) setConfig(root, { project: L.project });
223
+ return { project: L.project, moved, skipped };
224
+ }
@@ -0,0 +1,136 @@
1
+ // dev 的关键门禁与证据约束;不执行测试,也不代替用户作确认。
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { FILES, parseBranch } from './artifact-model.mjs';
5
+ import { hash, assertSnapshot, assertWorkingBranch } from './code-snapshot.mjs';
6
+
7
+ export const isDev = (run) => ['feature', 'bug'].includes(run.kind);
8
+ export const coreSteps = (run) => run.kind === 'feature' ? ['F4', 'F5', 'F6', 'F7', 'F8'] : ['B4', 'B5'];
9
+
10
+ export function receipt(root, req, run, kind, contents = {}) {
11
+ const record = run.artifacts?.[kind];
12
+ const file = path.join(req.abs, `${FILES[kind]}.md`);
13
+ const text = contents[kind] ?? (fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null);
14
+ if (!record || text === null || record.hash !== hash(text) || parseBranch(text) !== run.branch) throw new Error(`缺少本次运行已收尾的当前分支产物,或内容已变化:${FILES[kind]}.md;请运行 artifact.mjs finalize`);
15
+ return record;
16
+ }
17
+
18
+ export function assertPlan(root, req, run, contents) {
19
+ assertWorkingBranch(root, run);
20
+ const plan = receipt(root, req, run, 'plan', contents);
21
+ if (run.size !== 'S' && (run.plan_approval?.hash !== plan.hash || run.plan_approval.version !== plan.version)) throw new Error('M / L 方案尚未由用户确认,或确认后方案已变化;先记录 approval.confirmed');
22
+ return plan;
23
+ }
24
+
25
+ export function assertValidation(root, req, run, contents) {
26
+ const plan = assertPlan(root, req, run, contents);
27
+ if (run.implementation?.plan !== plan.hash) throw new Error('尚未通过方案门禁进入实现,请先进入 F5;bug 保存 implement: true');
28
+ assertSnapshot(root, run, run.validation?.snapshot);
29
+ return run.validation;
30
+ }
31
+
32
+ export function assertReview(root, req, run, contents) {
33
+ const validation = isDev(run) ? assertValidation(root, req, run, contents) : null;
34
+ const report = receipt(root, req, run, 'review', contents);
35
+ if (!run.review || run.review.report_hash !== report.hash || run.review.report_version !== report.version
36
+ || run.review.inputs !== hash(JSON.stringify(reviewInputs(run)))
37
+ || (validation && run.review.snapshot.digest !== validation.snapshot.digest)) throw new Error('缺少对应本轮验证和报告版本的审查证据,请重新审查');
38
+ if (!validation) assertSnapshot(root, run, run.review.snapshot);
39
+ return run.review;
40
+ }
41
+
42
+ export function assertDelivery(root, req, run, contents) {
43
+ const review = assertReview(root, req, run, contents);
44
+ const decision = run.decision;
45
+ if (decision?.action !== 'deliver' || decision.confirmed !== true || decision.report_hash !== review.report_hash
46
+ || decision.report_version !== review.report_version || decision.code !== review.snapshot.digest) throw new Error('进入交付前必须由用户明确选择本轮报告的交付;旧交付选择不再有效');
47
+ const serious = review.result.findings.filter((f) => f.scope !== 'outside' && ['CRITICAL', 'HIGH'].includes(f.severity) && f.verification === 'confirmed');
48
+ if (serious.some((f) => !decision.accepted_risks?.includes(f.id))) throw new Error('严重遗留风险必须逐项说明并取得用户明确接受,记录 accepted_risks 中的问题 id');
49
+ }
50
+
51
+ export function applyDevEvidence(root, req, run, patch, at, contents = {}) {
52
+ if (!isDev(run)) return;
53
+ for (const step of coreSteps(run)) if (run.steps[step].status === 'skipped') throw new Error(`完整 dev 核心步骤不能跳过:${step}`);
54
+ if (patch.approval !== undefined) {
55
+ if (patch.approval?.confirmed !== true) throw new Error('approval 必须记录用户明确确认:confirmed: true');
56
+ const plan = receipt(root, req, run, 'plan', contents);
57
+ run.plan_approval = { hash: plan.hash, version: plan.version, at };
58
+ }
59
+ const implementing = patch.implement === true || (run.kind === 'feature' && patch.stage === 'F5');
60
+ if (patch.implement !== undefined && patch.implement !== true) throw new Error('implement 只接受 true');
61
+ if (implementing) {
62
+ if (run.kind === 'feature' && run.steps.F4.status !== 'completed') throw new Error('方案步骤 F4 尚未完成,不能进入实现');
63
+ if (run.kind === 'bug' && run.stage !== 'B4') throw new Error('bug 只能在 B4 进入实现');
64
+ const plan = assertPlan(root, req, run, contents);
65
+ run.implementation = { plan: plan.hash, at };
66
+ }
67
+ if (patch.validation !== undefined) {
68
+ if (run.stage !== (run.kind === 'feature' ? 'F6' : 'B4')) throw new Error('请在 F6/B4 验证阶段记录 validation');
69
+ const plan = assertPlan(root, req, run, contents);
70
+ if (run.implementation?.plan !== plan.hash) throw new Error('先通过方案门禁进入实现,再记录验证');
71
+ const v = patch.validation;
72
+ if (!Array.isArray(v?.checks) || !v.checks.length || v.checks.some((c) => !c.command?.trim()
73
+ || !['passed', 'failed', 'unverified'].includes(c.result) || (c.result !== 'passed' && !c.reason?.trim()))) throw new Error('validation.checks 需要命令/操作、passed / failed / unverified;失败或未验证须写 reason');
74
+ const snapshot = assertSnapshot(root, run, v.snapshot);
75
+ run.validation = { snapshot, checks: v.checks, at };
76
+ run.review = null; run.decision = null;
77
+ if (run.kind === 'feature') for (const step of ['F7', 'F8']) run.steps[step] = { status: 'pending' };
78
+ }
79
+ if (patch.decision?.action === 'deliver') {
80
+ if (run.kind === 'feature' && run.steps.F7.status !== 'completed') throw new Error('审查步骤 F7 尚未完成,不能选择交付');
81
+ const review = assertReview(root, req, run, contents);
82
+ run.decision = { ...run.decision, code: review.snapshot.digest, report_hash: review.report_hash, report_version: review.report_version };
83
+ assertDelivery(root, req, run, contents);
84
+ }
85
+ const completed = (s) => patch.steps?.[s]?.status === 'completed';
86
+ if (run.kind === 'feature') {
87
+ if (completed('F4')) receipt(root, req, run, 'plan', contents);
88
+ if (patch.stage === 'F6' || completed('F5')) {
89
+ const plan = assertPlan(root, req, run, contents);
90
+ if (run.implementation?.plan !== plan.hash) throw new Error('尚未通过方案门禁进入实现');
91
+ }
92
+ if (patch.stage === 'F7' || completed('F6')) {
93
+ if (run.steps.F5.status !== 'completed') throw new Error('实现步骤 F5 尚未完成');
94
+ assertValidation(root, req, run, contents);
95
+ if (patch.stage === 'F7' && run.steps.F6.status !== 'completed') throw new Error('验证步骤 F6 尚未完成');
96
+ }
97
+ if (completed('F7')) assertReview(root, req, run, contents);
98
+ if (patch.stage === 'F8' || completed('F8')) assertDelivery(root, req, run, contents);
99
+ if (completed('F8')) receipt(root, req, run, 'delivery', contents);
100
+ } else {
101
+ if (completed('B4') || patch.stage === 'B5') {
102
+ assertValidation(root, req, run, contents);
103
+ if (patch.stage === 'B5' && run.steps.B4.status !== 'completed') throw new Error('修复与验证步骤 B4 尚未完成');
104
+ }
105
+ if (completed('B5')) { assertDelivery(root, req, run, contents); receipt(root, req, run, 'delivery', contents); }
106
+ }
107
+ const event = run.history.at(-1);
108
+ if (patch.approval) event.approval = run.plan_approval;
109
+ if (patch.validation) event.validation = run.validation;
110
+ if (patch.decision) event.decision = run.decision;
111
+ }
112
+
113
+ export function reviewInputs(run) {
114
+ const facts = Object.fromEntries(['summary', 'acceptance', 'decisions', 'scope', 'baseline'].filter((k) => run.context[k] !== undefined).map((k) => [k, run.context[k]]));
115
+ return { facts, scope: run.scope, plan: run.artifacts?.plan ?? null, validation: run.validation ?? null };
116
+ }
117
+
118
+ export function reviewEvidence(root, req, run, packet, result, contents) {
119
+ if (!packet || packet.run_id !== run.id || packet.revision > run.revision || packet.inputs !== hash(JSON.stringify(reviewInputs(run)))) throw new Error('审查交接材料不属于当前运行内容,请重新生成 handoff');
120
+ const snapshot = assertSnapshot(root, run, packet.snapshot);
121
+ if (isDev(run)) assertValidation(root, req, run, contents);
122
+ if (result?.run_id !== run.id || result.code !== snapshot.digest || result.inputs !== packet.inputs) throw new Error('审查结果的运行、代码版本或交接内容不匹配,请返回本轮审查结果');
123
+ if (!Array.isArray(result?.findings) || !Array.isArray(result?.coverage?.reviewed) || !Array.isArray(result?.coverage?.uncovered)) throw new Error('审查结果需要 findings 和 coverage.reviewed / uncovered');
124
+ const covered = [...result.coverage.reviewed, ...result.coverage.uncovered];
125
+ const expected = packet.scope.review.map((f) => f.path);
126
+ if (new Set(covered).size !== covered.length || expected.length !== covered.length || expected.some((p) => !covered.includes(p))) throw new Error('审查覆盖范围必须逐文件对应交接材料,未审完的放入 uncovered');
127
+ const ids = new Set();
128
+ for (const f of result.findings) {
129
+ if (!f.id || ids.has(f.id) || !['CRITICAL', 'HIGH', 'MEDIUM', 'LOW'].includes(f.severity) || !['confirmed', 'pending'].includes(f.verification)
130
+ || (f.scope !== undefined && !['in_scope', 'outside'].includes(f.scope))
131
+ || !f.file || !Number.isInteger(f.line) || f.line < 1 || !f.summary?.trim()) throw new Error('审查问题需要唯一 id、severity、verification、file、正整数 line 与 summary');
132
+ ids.add(f.id);
133
+ }
134
+ const report = receipt(root, req, run, 'review', contents);
135
+ return { snapshot, inputs: packet.inputs, report_hash: report.hash, report_version: report.version, result, at: new Date().toISOString() };
136
+ }
@@ -0,0 +1,188 @@
1
+ // 运行状态服务:阶段、完成校验和 revision;不依赖命令入口。
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { find, requirements } from './requirement-read.mjs';
6
+ import { parseBranch } from './artifact-model.mjs';
7
+ import { updateMeta } from './meta-store.mjs';
8
+ import { loadWorkspace } from './workspace-read.mjs';
9
+ import { readProfile } from './project.mjs';
10
+ import { isDev, applyDevEvidence, assertReview, assertDelivery, receipt } from './run-gates.mjs';
11
+ import { codeSnapshot } from './code-snapshot.mjs';
12
+
13
+ export const FLOWS = {
14
+ feature: ['Step0', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8'],
15
+ bug: ['Step0', 'B1', 'B2', 'B3', 'B4', 'B5'],
16
+ review: ['R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'R7'],
17
+ tech: ['T0', 'T1', 'T2', 'T3', 'T4'],
18
+ release: ['L0', 'L1', 'L2', 'L3', 'L4'],
19
+ wiki: ['W0', 'W1', 'W2'],
20
+ };
21
+ export const STATUS_LABELS = { running: '进行中', waiting_user: '等待用户', blocked: '受阻', completed: '已完成', cancelled: '已取消' };
22
+ const terminal = (s) => s === 'completed' || s === 'cancelled';
23
+ const done = (s) => s === 'completed' || s === 'skipped';
24
+ const object = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
25
+ const timestamp = () => new Date().toISOString();
26
+
27
+ export function allRuns(root, workspace = loadWorkspace(root)) {
28
+ return workspace.runs.filter((run) => run.project === workspace.layout.project).map(({ project, ...run }) => run);
29
+ }
30
+
31
+ export const branchRuns = (root, branch, workspace) => allRuns(root, workspace).filter((run) => run.branch === branch);
32
+
33
+ export function runState(root, branch, workspace = loadWorkspace(root), id = null) {
34
+ const runs = branchRuns(root, branch, workspace);
35
+ const current = id ? runs.find((r) => r.id === id) ?? null : runs.filter((r) => !terminal(r.status)).at(-1) ?? runs.at(-1) ?? null;
36
+ let next = !current ? null : current.pending_finalization ? `先恢复产物收尾:artifact.mjs resume --id ${current.id}` : current.status === 'waiting_user' ? `等待用户:${current.waiting_for}`
37
+ : current.status === 'blocked' ? `处理阻塞:${current.reason}`
38
+ : terminal(current.status) ? `${STATUS_LABELS[current.status]}:${current.kind}(${current.id})`
39
+ : `继续 ${current.stage}(${current.kind},运行 ${current.id})`;
40
+ let freshness = null;
41
+ if (current && (isDev(current) || current.kind === 'review') && !terminal(current.status) && (current.validation || current.review)) {
42
+ try {
43
+ const snapshot = codeSnapshot(root, current);
44
+ freshness = { validation: current.validation ? snapshot.digest === current.validation.snapshot.digest : null, review: current.review ? current.review.snapshot.digest === snapshot.digest : null };
45
+ if ((freshness.validation === false || freshness.review === false) && !current.pending_finalization) next = isDev(current) ? '代码或基线已变化:回到验证阶段,重新验证、审查并取得交付选择' : '代码或基线已变化:重新审查并生成报告';
46
+ } catch (e) {
47
+ freshness = { validation: false, review: false, reason: e.message };
48
+ if (!current.pending_finalization) next = `核对证据失败:${e.message}`;
49
+ }
50
+ }
51
+ return { branch, current, runs, next, ...(freshness ? { freshness } : {}), ...(workspace.diagnostics.length ? { diagnostics: workspace.diagnostics } : {}) };
52
+ }
53
+
54
+ export function applyCheckpoint(run, patch, at, reopen = true) {
55
+ if (!object(patch)) throw new Error('checkpoint 必须是 JSON 对象');
56
+ const allowed = ['stage', 'status', 'size', 'waiting_for', 'reason', 'steps', 'context', 'decision', 'approval', 'implement', 'validation', 'scope'];
57
+ for (const key of Object.keys(patch)) if (!allowed.includes(key)) throw new Error(`不支持修改字段:${key}`);
58
+ if (patch.status !== undefined && !['running', 'waiting_user', 'blocked'].includes(patch.status)) throw new Error('save 的状态只支持 running / waiting_user / blocked;完成用 complete,取消用 cancel');
59
+ if (patch.size !== undefined) {
60
+ if (!['S', 'M', 'L'].includes(patch.size)) throw new Error('size 必须是 S / M / L');
61
+ run.size = patch.size;
62
+ }
63
+ const stages = FLOWS[run.kind];
64
+ const stage = patch.stage ?? run.stage;
65
+ if (!stages.includes(stage)) throw new Error(`无效阶段:${stage}`);
66
+ const status = patch.status ?? run.status;
67
+ // 回到已完成的阶段时,后续完成标记失效;历史 checkpoint 仍保留。
68
+ if (reopen && patch.stage && (stages.indexOf(stage) < stages.indexOf(run.stage) || (status === 'running' && done(run.steps[stage].status)))) {
69
+ for (const name of stages.slice(stages.indexOf(stage))) run.steps[name] = { status: 'pending' };
70
+ run.decision = null;
71
+ if (isDev(run)) {
72
+ const index = stages.indexOf(stage);
73
+ if (run.kind === 'bug' || index <= stages.indexOf('F7')) run.review = null;
74
+ if (run.kind === 'bug' || index <= stages.indexOf('F6')) run.validation = null;
75
+ if (run.kind === 'bug' || index <= stages.indexOf('F4')) run.implementation = null;
76
+ }
77
+ }
78
+ if (patch.steps !== undefined) {
79
+ if (!object(patch.steps)) throw new Error('steps 必须是对象');
80
+ for (const [name, value] of Object.entries(patch.steps)) {
81
+ if (!stages.includes(name) || !object(value)) throw new Error(`无效步骤:${name}`);
82
+ if (!['pending', 'in_progress', 'completed', 'skipped'].includes(value.status)) throw new Error(`无效步骤状态:${name}`);
83
+ if (value.status === 'skipped' && !value.reason?.trim()) throw new Error(`跳过 ${name} 必须注明 reason`);
84
+ run.steps[name] = { ...value, updated_at: at, completed_at: value.status === 'completed' ? (run.steps[name].completed_at ?? at) : null };
85
+ }
86
+ }
87
+ if (patch.scope !== undefined) {
88
+ if (!object(patch.scope) || typeof patch.scope.base !== 'string' || !patch.scope.base.trim() || !Array.isArray(patch.scope.exclude) || patch.scope.exclude.some((v) => typeof v !== 'string')) throw new Error('scope 需要 base 和 exclude 字符串数组');
89
+ if (run.validation && JSON.stringify(run.scope) !== JSON.stringify(patch.scope)) throw new Error('调整审查范围前先回退到实现/验证阶段,使旧证据失效');
90
+ run.scope = patch.scope;
91
+ }
92
+ if (patch.context !== undefined) {
93
+ if (!object(patch.context)) throw new Error('context 必须是对象');
94
+ run.context = { ...run.context, ...patch.context };
95
+ }
96
+ if (patch.decision !== undefined) {
97
+ if (!object(patch.decision) || !['fix', 'deliver'].includes(patch.decision.action) || patch.decision.confirmed !== true) throw new Error('decision 必须记录用户明确确认的 fix / deliver');
98
+ if (patch.decision.accepted_risks !== undefined && (!Array.isArray(patch.decision.accepted_risks) || patch.decision.accepted_risks.some((v) => typeof v !== 'string'))) throw new Error('accepted_risks 必须是已明确接受的问题 id 数组');
99
+ run.decision = { ...patch.decision, at };
100
+ }
101
+ run.stage = stage;
102
+ run.status = status;
103
+ run.waiting_for = status === 'waiting_user' ? (patch.waiting_for ?? run.waiting_for) : null;
104
+ run.reason = status === 'blocked' ? (patch.reason ?? run.reason) : null;
105
+ if (status === 'waiting_user' && !run.waiting_for?.trim()) throw new Error('等待用户时必须填写 waiting_for');
106
+ if (status === 'blocked' && !run.reason?.trim()) throw new Error('阻塞时必须填写 reason');
107
+ if (status === 'running' && run.steps[stage].status === 'pending') run.steps[stage] = { status: 'in_progress', updated_at: at };
108
+ run.updated_at = at;
109
+ run.history.push({ at, stage, status, steps: patch.steps ?? {}, ...(patch.decision ? { decision: run.decision } : {}) });
110
+ return run;
111
+ }
112
+
113
+ export function startRun(root, { branch, kind = 'feature', size = null, input = {}, dir = null }) {
114
+ if (!branch || !FLOWS[kind]) throw new Error('start 需要有效分支及 kind:feature / bug / review / tech / release / wiki');
115
+ if (['feature', 'bug'].includes(kind) && !['S', 'M', 'L'].includes(size)) throw new Error('完整 dev 流程需要 size:S / M / L;快速通道不创建运行记录');
116
+ const req = dir ? requirements(root).find((r) => r.abs === path.resolve(root, dir)) : find(root, branch);
117
+ if (!req || !req.branches.includes(branch)) throw new Error('当前分支尚未绑定指定需求,先确认需求名并运行 requirement.mjs bind;快速通道不要调用 start');
118
+ let selected; let resumed = false;
119
+ updateMeta(path.join(req.abs, 'meta.json'), (meta) => {
120
+ const runs = meta.runs ?? {};
121
+ selected = Object.values(runs).find((r) => r.branch === branch && r.kind === kind && !terminal(r.status));
122
+ if (selected) { resumed = true; return meta; }
123
+ const profile = readProfile(root).profile;
124
+ const at = timestamp(); const id = randomUUID();
125
+ selected = applyCheckpoint({ id, kind, size, branch, revision: 1, status: 'running', stage: FLOWS[kind][0],
126
+ created_at: at, updated_at: at, completed_at: null, steps: Object.fromEntries(FLOWS[kind].map((s) => [s, { status: 'pending' }])),
127
+ scope: { base: meta.base || profile?.main_branch || 'main', exclude: Array.isArray(profile?.review?.exclude) ? profile.review.exclude.filter((v) => typeof v === 'string') : [] },
128
+ artifacts: {}, context: {}, waiting_for: null, reason: null, decision: null, history: [] }, input, at);
129
+ applyDevEvidence(root, req, selected, input, at);
130
+ return { ...meta, runs: { ...runs, [id]: selected }, updated: at };
131
+ }, { root });
132
+ return { ok: true, resumed, dir: req.dir, run: selected };
133
+ }
134
+
135
+ export function readRun(root, branch, id) {
136
+ const req = requirements(root).find((r) => Object.hasOwn(r.meta.runs ?? {}, id));
137
+ if (!req) throw new Error(`找不到运行:${id}`);
138
+ const run = req.meta.runs[id];
139
+ if (run.branch !== branch) throw new Error('运行属于其他分支,请切换到对应分支后恢复,不要修改原运行的分支');
140
+ return { req, run };
141
+ }
142
+
143
+ export function assertRunVersion(run, branch, revision) {
144
+ if (run.branch !== branch) throw new Error('运行属于其他分支,请切换到对应分支后恢复,不要修改原运行的分支');
145
+ if (!Number.isInteger(revision) || run.revision !== revision) throw new Error(`运行版本冲突,重新读取状态后使用 --expect-revision ${run.revision}`);
146
+ if (terminal(run.status)) throw new Error('运行已结束,不再修改;新的工作请 start 新运行');
147
+ }
148
+
149
+ export function changeRun(root, { branch, id, revision, input = {}, action = 'save' }) {
150
+ if (!branch || !id || !['save', 'complete', 'cancel'].includes(action)) throw new Error('需要当前分支、运行 id 和有效动作');
151
+ const { req } = readRun(root, branch, id);
152
+ let result;
153
+ updateMeta(path.join(req.abs, 'meta.json'), (meta) => {
154
+ const run = structuredClone(meta.runs[id]);
155
+ assertRunVersion(run, branch, revision);
156
+ const at = timestamp();
157
+ if (action === 'cancel') {
158
+ if (!input.reason?.trim()) throw new Error('取消运行需要 reason');
159
+ run.status = 'cancelled'; run.reason = input.reason; run.waiting_for = null; run.ended_at = at;
160
+ run.history.push({ at, stage: run.stage, status: 'cancelled', reason: input.reason });
161
+ } else {
162
+ applyCheckpoint(run, input, at, action !== 'complete');
163
+ applyDevEvidence(root, req, run, input, at);
164
+ if (action === 'complete') {
165
+ const steps = FLOWS[run.kind];
166
+ if (run.status !== 'running' || run.stage !== steps.at(-1) || !steps.every((s) => done(run.steps[s].status)) || run.steps[steps.at(-1)].status !== 'completed') throw new Error('还有未完成步骤、待用户决定或阻塞,不能标记已完成');
167
+ if (['feature', 'bug'].includes(run.kind)) {
168
+ const required = run.kind === 'feature' ? ['F4', 'F5', 'F6', 'F7', 'F8'] : ['B4', 'B5'];
169
+ assertDelivery(root, req, run);
170
+ receipt(root, req, run, 'delivery');
171
+ if (required.some((s) => run.steps[s].status !== 'completed') || run.decision?.action !== 'deliver' || !run.decision.confirmed) throw new Error('完整 dev 流程必须完成方案、实现、验证、审查和交付,且用户已选择交付');
172
+ }
173
+ if (run.kind === 'review') assertReview(root, req, run);
174
+ const files = { feature: ['plan.md', 'review.md', 'delivery.md'], bug: ['plan.md', 'review.md', 'delivery.md'], review: ['review.md'], tech: ['tech-doc.md'], release: ['release-doc.md'] };
175
+ for (const name of files[run.kind] ?? []) {
176
+ const file = path.join(req.abs, name);
177
+ if (!fs.existsSync(file) || parseBranch(fs.readFileSync(file, 'utf8')) !== branch) throw new Error(`缺少当前分支的产物:${name}`);
178
+ }
179
+ run.status = 'completed'; run.completed_at = at; run.waiting_for = null; run.reason = null;
180
+ run.history.push({ at, stage: run.stage, status: 'completed' });
181
+ }
182
+ }
183
+ run.updated_at = at; run.revision++;
184
+ result = run;
185
+ return { ...meta, runs: { ...meta.runs, [id]: run }, updated: at };
186
+ }, { root });
187
+ return { ok: true, dir: req.dir, run: result };
188
+ }