@rowansenne/workflow-run 0.27.0 → 0.29.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.
- package/CHANGELOG.md +23 -0
- package/README.md +97 -27
- package/bin/lib/artifact-context.mjs +2 -0
- package/bin/lib/doctor.mjs +1 -1
- package/bin/lib/install.mjs +1 -1
- package/create-release-md-doc/SKILL.md.tpl +4 -5
- package/create-tech-md-doc/SKILL.md.tpl +4 -6
- package/dev/SKILL.md.tpl +22 -14
- package/dev/agents/openai.yaml +2 -0
- package/dev/references/bug.md +6 -3
- package/dev/references/clarify.md +1 -1
- package/dev/references/delivery-template.md +2 -2
- package/dev/references/delivery.md +11 -9
- package/dev/references/implementation.md +5 -1
- package/dev/references/plan-template.md +8 -12
- package/dev/references/planning.md +8 -4
- package/dev/references/preflight.md +3 -3
- package/dev/references/requirement-template.md +32 -0
- package/dev/skill.json +10 -2
- package/nacos-config/SKILL.md.tpl +42 -0
- package/nacos-config/package.json +7 -0
- package/nacos-config/references/connection.md +47 -0
- package/nacos-config/scripts/config.mjs +288 -0
- package/nacos-config/skill.json +9 -0
- package/package.json +6 -2
- package/project-review/SKILL.md.tpl +4 -3
- package/project-review/references/reporting.md +8 -8
- package/project-review/references/review-method.md +1 -1
- package/project-review/skill.json +2 -1
- package/workflow/SKILL.md.tpl +14 -9
- package/workflow/lib/artifact-finalize.mjs +156 -0
- package/workflow/lib/artifact-model.mjs +2 -2
- package/workflow/lib/code-snapshot.mjs +55 -0
- package/workflow/lib/meta-store.mjs +4 -2
- package/workflow/lib/path-match.mjs +21 -0
- package/workflow/lib/requirements.mjs +12 -7
- package/workflow/lib/run-gates.mjs +153 -0
- package/workflow/lib/runs.mjs +58 -14
- package/workflow/lib/workspace-read.mjs +3 -1
- package/workflow/references/architecture.md +51 -3
- package/workflow/references/capabilities.md +4 -2
- package/workflow/references/execution.md +105 -0
- package/workflow/references/requirements.md +15 -13
- package/workflow/references/runs.md +16 -11
- package/workflow/references/status.md +1 -0
- package/workflow/references/templates.md +2 -2
- package/workflow/scripts/artifact.mjs +39 -0
- package/workflow/scripts/pr-desc.mjs +2 -2
- package/workflow/scripts/review-handoff.mjs +59 -0
- package/workflow/scripts/review-scope.mjs +2 -21
- package/workflow/scripts/run.mjs +6 -8
- package/workflow/scripts/template.mjs +3 -2
- package/workflow/scripts/view.mjs +1 -1
- package/workflow/skill.json +2 -1
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// 文件发布与 meta 更新之间用同一 meta.json 中的待办恢复;不声称多个文件可一次原子提交。
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { FILES, parseBranch } from './artifact-model.mjs';
|
|
6
|
+
import { hash, assertWorkingBranch } from './code-snapshot.mjs';
|
|
7
|
+
import { layout } from './project.mjs';
|
|
8
|
+
import { readRun, assertRunVersion, applyCheckpoint } from './runs.mjs';
|
|
9
|
+
import { isDev, coreSteps, applyDevEvidence, assertRequirement, assertPlanBasis, assertReview, assertDelivery, reviewEvidence } from './run-gates.mjs';
|
|
10
|
+
import { updateMeta } from './meta-store.mjs';
|
|
11
|
+
import { OLD_DIR, indexArtifacts } from './requirements.mjs';
|
|
12
|
+
|
|
13
|
+
export const ARTIFACT_TEMPLATES = {
|
|
14
|
+
requirement: ['dev', 'requirement-template.md'],
|
|
15
|
+
plan: ['dev', 'plan-template.md'], review: ['project-review', 'report.md'], delivery: ['dev', 'delivery-template.md'],
|
|
16
|
+
tech: ['create-tech-md-doc', 'template.md'], release: ['create-release-md-doc', 'template.md'],
|
|
17
|
+
};
|
|
18
|
+
const allowed = { feature: ['requirement', 'plan', 'review', 'delivery'], bug: ['requirement', 'plan', 'review', 'delivery'], review: ['review'], tech: ['tech'], release: ['release'] };
|
|
19
|
+
const relative = (root, file) => path.relative(root, file).split(path.sep).join('/');
|
|
20
|
+
const fileHash = (file) => fs.existsSync(file) ? hash(fs.readFileSync(file)) : null;
|
|
21
|
+
|
|
22
|
+
export function resumeFinalization(root, { branch, id }) {
|
|
23
|
+
const { req } = readRun(root, branch, id);
|
|
24
|
+
let result;
|
|
25
|
+
updateMeta(path.join(req.abs, 'meta.json'), (meta) => {
|
|
26
|
+
const p = meta.pending_finalization;
|
|
27
|
+
if (!p || p.run_id !== id) throw new Error('没有该运行待恢复的产物收尾');
|
|
28
|
+
const run = meta.runs[id];
|
|
29
|
+
assertRunVersion(run, branch, p.revision);
|
|
30
|
+
if (isDev(run)) assertWorkingBranch(root, run);
|
|
31
|
+
const staged = path.resolve(root, p.staged);
|
|
32
|
+
if (fileHash(staged) !== p.hash) throw new Error('收尾草稿缺失或已变化,保留待办;请恢复原草稿后重试');
|
|
33
|
+
const file = path.join(req.abs, `${FILES[p.kind]}.md`);
|
|
34
|
+
const current = fileHash(file);
|
|
35
|
+
if (current !== p.before && current !== p.hash) throw new Error('正式产物在收尾中断后被其他操作修改,请先核对并恢复;不会覆盖');
|
|
36
|
+
// 中断期间代码/报告也可能变化:发布前重新检查本轮门禁。
|
|
37
|
+
applyDevEvidence(root, req, p.run, p.checkpoint, p.run.updated_at, { [p.kind]: fs.readFileSync(staged, 'utf8') });
|
|
38
|
+
if (p.kind === 'plan') assertPlanBasis(root, req, p.run, { plan: fs.readFileSync(staged, 'utf8') });
|
|
39
|
+
if (p.kind === 'review' || (isDev(p.run) && p.kind === 'delivery')) {
|
|
40
|
+
if (p.kind === 'review') assertReview(root, req, p.run, { review: fs.readFileSync(staged, 'utf8') });
|
|
41
|
+
else assertDelivery(root, req, p.run);
|
|
42
|
+
}
|
|
43
|
+
if (current !== p.hash) {
|
|
44
|
+
if (p.previous) {
|
|
45
|
+
const archive = path.resolve(root, p.previous);
|
|
46
|
+
fs.mkdirSync(path.dirname(archive), { recursive: true });
|
|
47
|
+
if (fs.existsSync(archive) && fileHash(archive) !== p.before) throw new Error('归档版本已存在且内容不同,停止以免覆盖历史');
|
|
48
|
+
fs.copyFileSync(file, archive);
|
|
49
|
+
}
|
|
50
|
+
const tmp = path.join(req.abs, `.${FILES[p.kind]}.${p.id}.tmp`);
|
|
51
|
+
fs.writeFileSync(tmp, fs.readFileSync(staged));
|
|
52
|
+
fs.renameSync(tmp, file);
|
|
53
|
+
}
|
|
54
|
+
const versions = { ...(meta.versions ?? {}), [p.kind]: p.version };
|
|
55
|
+
const artifacts = indexArtifacts(req.abs, versions);
|
|
56
|
+
const latest = Object.fromEntries(Object.keys(FILES).map((k) => [k, artifacts.filter((a) => a.kind === k).at(-1)?.file ?? null]));
|
|
57
|
+
const { pending_finalization, ...rest } = meta;
|
|
58
|
+
result = { ok: true, path: relative(root, file), cite: layout(root).ref(file), previous: p.previous, version: p.version, lint: p.run.artifacts[p.kind].lint, run: p.run };
|
|
59
|
+
return { ...rest, versions, artifacts, latest, runs: { ...meta.runs, [id]: p.run }, updated: p.run.updated_at };
|
|
60
|
+
}, { root, allowFinalization: true });
|
|
61
|
+
return result;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function abortFinalization(root, { branch, id }) {
|
|
65
|
+
const { req } = readRun(root, branch, id);
|
|
66
|
+
updateMeta(path.join(req.abs, 'meta.json'), (meta) => {
|
|
67
|
+
const p = meta.pending_finalization;
|
|
68
|
+
if (!p || p.run_id !== id) throw new Error('没有该运行待取消的产物收尾');
|
|
69
|
+
assertRunVersion(meta.runs[id], branch, p.revision);
|
|
70
|
+
const file = path.join(req.abs, `${FILES[p.kind]}.md`);
|
|
71
|
+
const current = fileHash(file);
|
|
72
|
+
if (current !== p.before && current !== p.hash) throw new Error('正式文件已被其他操作修改,先人工核对,不会覆盖');
|
|
73
|
+
if (current === p.hash && p.before !== p.hash) {
|
|
74
|
+
if (p.before === null) fs.unlinkSync(file);
|
|
75
|
+
else {
|
|
76
|
+
const archive = path.resolve(root, p.previous);
|
|
77
|
+
if (fileHash(archive) !== p.before) throw new Error('原版本归档缺失,不能安全取消');
|
|
78
|
+
const tmp = path.join(req.abs, `.${FILES[p.kind]}.${p.id}.tmp`);
|
|
79
|
+
fs.copyFileSync(archive, tmp); fs.renameSync(tmp, file);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const { pending_finalization, ...rest } = meta;
|
|
83
|
+
return rest;
|
|
84
|
+
}, { root, allowFinalization: true });
|
|
85
|
+
return { ok: true, aborted: true, run_id: id };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function finalizeArtifact(root, { branch, id, revision, kind, text, input = {}, packet = null, result = null }, check) {
|
|
89
|
+
if (!FILES[kind] || typeof text !== 'string') throw new Error('需要有效的产物 kind 和草稿正文');
|
|
90
|
+
const { req } = readRun(root, branch, id);
|
|
91
|
+
const file = path.join(req.abs, `${FILES[kind]}.md`);
|
|
92
|
+
const wikiRecord = (s) => /^<!-- md-to-wiki: [^\n]*-->/.exec(s)?.[0] ?? null;
|
|
93
|
+
const existingWiki = fs.existsSync(file) ? wikiRecord(fs.readFileSync(file, 'utf8')) : null;
|
|
94
|
+
const draftWiki = wikiRecord(text);
|
|
95
|
+
if (existingWiki && draftWiki && existingWiki !== draftWiki) throw new Error('新版必须保留原 wiki 页面记录;页面变更由 wiki 发布流程处理');
|
|
96
|
+
if (existingWiki && !draftWiki) text = `${existingWiki}\n${text}`;
|
|
97
|
+
const digest = hash(text);
|
|
98
|
+
const key = hash(JSON.stringify({ id, revision, kind, digest, input, packet, result }));
|
|
99
|
+
let repeated = null;
|
|
100
|
+
updateMeta(path.join(req.abs, 'meta.json'), (meta) => {
|
|
101
|
+
const current = meta.runs[id];
|
|
102
|
+
if (current.last_finalization === key && !meta.pending_finalization) {
|
|
103
|
+
if (fileHash(path.join(req.abs, `${FILES[kind]}.md`)) !== digest) throw new Error('已收尾产物后来被修改,请用当前 revision 发起新的收尾');
|
|
104
|
+
repeated = { ok: true, already_finalized: true, path: `${req.dir}/${FILES[kind]}.md`, run: current }; return meta;
|
|
105
|
+
}
|
|
106
|
+
if (meta.pending_finalization) {
|
|
107
|
+
if (meta.pending_finalization.key !== key) throw new Error(`已有待完成收尾,先运行 artifact.mjs resume --id ${meta.pending_finalization.run_id}`);
|
|
108
|
+
return meta;
|
|
109
|
+
}
|
|
110
|
+
assertRunVersion(current, branch, revision);
|
|
111
|
+
if (isDev(current)) assertWorkingBranch(root, current);
|
|
112
|
+
if (!allowed[current.kind]?.includes(kind)) throw new Error('该产物种类不属于当前运行');
|
|
113
|
+
if (parseBranch(text) !== branch) throw new Error('草稿元信息的分支必须与运行分支一致');
|
|
114
|
+
const lint = check(text);
|
|
115
|
+
if (!lint?.ok) throw new Error(`草稿自检失败:${lint?.errors?.join(';') || '模板不可用'}`);
|
|
116
|
+
const at = new Date().toISOString();
|
|
117
|
+
const run = structuredClone(current);
|
|
118
|
+
// 文档收尾只能登记当前步骤,不能在一次落盘中跳到下游或替用户作确认。
|
|
119
|
+
if (Object.keys(input).some((k) => !['steps', 'status', 'waiting_for', 'reason', 'context'].includes(k))) throw new Error('收尾 checkpoint 只接受 steps / status / waiting_for / reason / context;阶段和用户选择用 run.mjs save');
|
|
120
|
+
const expectedStep = isDev(run) ? (kind === 'requirement' ? (run.kind === 'feature' ? 'F3' : 'B3') : kind === 'plan' ? (run.kind === 'feature' ? 'F4' : 'B4') : kind === 'review' ? (run.kind === 'feature' ? 'F7' : 'B5') : (run.kind === 'feature' ? 'F8' : 'B5')) : ({ review: 'R7', tech: 'T4', release: 'L4' })[run.kind];
|
|
121
|
+
if (run.stage !== expectedStep || Object.keys(input.steps ?? {}).some((s) => s !== expectedStep)) throw new Error(`产物应在 ${expectedStep} 收尾,只能更新该步骤`);
|
|
122
|
+
let requirement = null;
|
|
123
|
+
if (kind === 'plan') {
|
|
124
|
+
requirement = assertRequirement(root, req, run);
|
|
125
|
+
if (run.steps[run.kind === 'feature' ? 'F3' : 'B3'].status !== 'completed') throw new Error('需求文档尚未完成,不能收尾方案');
|
|
126
|
+
}
|
|
127
|
+
if (isDev(run) && kind === 'delivery') assertDelivery(root, req, run);
|
|
128
|
+
if ((fs.existsSync(file) ? wikiRecord(fs.readFileSync(file, 'utf8')) : null) !== existingWiki) throw new Error('wiki 发布记录在收尾期间变化,请重新读取后重试');
|
|
129
|
+
const before = fileHash(file);
|
|
130
|
+
const oldVersion = meta.versions?.[kind] ?? 1;
|
|
131
|
+
const version = before === null ? 1 : oldVersion + (before === digest ? 0 : 1);
|
|
132
|
+
const previous = before !== null && before !== digest ? relative(root, path.join(root, OLD_DIR, path.relative(path.join(root, 'workflow-run/docs/requirements'), req.abs), `${FILES[kind]}_v${oldVersion}.md`)) : null;
|
|
133
|
+
run.artifacts = { ...(run.artifacts ?? {}), [kind]: { hash: digest, version, path: relative(root, file), previous, lint, at,
|
|
134
|
+
...(requirement ? { requirement: { hash: requirement.hash, version: requirement.version } } : {}) } };
|
|
135
|
+
if ((kind === 'plan' && (current.artifacts?.plan?.hash !== digest || current.artifacts?.plan?.requirement?.hash !== requirement.hash))
|
|
136
|
+
|| (kind === 'requirement' && current.artifacts?.requirement?.hash !== digest)) {
|
|
137
|
+
run.plan_approval = null; run.implementation = null; run.validation = null; run.review = null; run.decision = null;
|
|
138
|
+
if (kind === 'requirement') for (const step of coreSteps(run).slice(1)) run.steps[step] = { status: 'pending' };
|
|
139
|
+
}
|
|
140
|
+
applyCheckpoint(run, input, at, false);
|
|
141
|
+
if (kind === 'review') {
|
|
142
|
+
run.review = reviewEvidence(root, req, run, packet, result, { review: text });
|
|
143
|
+
run.decision = null;
|
|
144
|
+
}
|
|
145
|
+
applyDevEvidence(root, req, run, input, at, { [kind]: text });
|
|
146
|
+
run.history.at(-1).artifact = { kind, hash: digest, version };
|
|
147
|
+
run.revision++; run.updated_at = at; run.last_finalization = key;
|
|
148
|
+
const op = randomUUID();
|
|
149
|
+
const staged = path.join(root, 'workflow-run/tmp/finalize', `${op}.md`);
|
|
150
|
+
fs.mkdirSync(path.dirname(staged), { recursive: true });
|
|
151
|
+
fs.writeFileSync(staged, text, { flag: 'wx' });
|
|
152
|
+
return { ...meta, pending_finalization: { id: op, key, run_id: id, revision, kind, before, hash: digest, version, previous, staged: relative(root, staged), run, packet, checkpoint: input } };
|
|
153
|
+
}, { root, allowFinalization: true });
|
|
154
|
+
if (repeated) return repeated;
|
|
155
|
+
return resumeFinalization(root, { branch, id });
|
|
156
|
+
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// 正式需求产物的统一纯模型;不扫描目录、不修改状态。
|
|
2
2
|
import { sections, section, tableRows, listItems, meta, isEmpty } from './document-model.mjs';
|
|
3
3
|
|
|
4
|
-
export const FILES = { plan: 'plan', delivery: 'delivery', review: 'review', tech: 'tech-doc', release: 'release-doc' };
|
|
5
|
-
export const LABELS = { plan: '方案', delivery: '交付说明', review: '审查报告', tech: '技术方案', release: '上线方案' };
|
|
4
|
+
export const FILES = { requirement: 'requirement', plan: 'plan', delivery: 'delivery', review: 'review', tech: 'tech-doc', release: 'release-doc' };
|
|
5
|
+
export const LABELS = { requirement: '需求文档', plan: '方案', delivery: '交付说明', review: '审查报告', tech: '技术方案', release: '上线方案' };
|
|
6
6
|
export const KINDS = Object.keys(FILES).map((kind) => ({ kind, label: LABELS[kind] }));
|
|
7
7
|
|
|
8
8
|
// 文件名 → { kind, version };不是需求目录里的产物返回 null
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// 证据绑定到 Git 基线、HEAD 及工作区内容;不输出文件正文,也不把工作流自己的产出算作代码变化。
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { spawnSync } from 'node:child_process';
|
|
5
|
+
import { createHash } from 'node:crypto';
|
|
6
|
+
import { matchGlob } from './path-match.mjs';
|
|
7
|
+
|
|
8
|
+
export const hash = (value) => createHash('sha256').update(value).digest('hex');
|
|
9
|
+
const INTERNAL = ['workflow-run/**', '.docnexus/**', '.codegraph/**', '.agents/skills/**', '.claude/skills/**', '.qwen/skills/**', '.codebuddy/skills/**'];
|
|
10
|
+
const git = (root, args, encoding = 'utf8') => {
|
|
11
|
+
const r = spawnSync('git', args, { cwd: root, encoding, maxBuffer: 256 * 1024 * 1024 });
|
|
12
|
+
if (r.status !== 0) throw new Error(`代码快照失败:git ${args[0]}:${r.stderr?.toString().trim() || r.error?.message}`);
|
|
13
|
+
return r.stdout;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export function assertWorkingBranch(root, run) {
|
|
17
|
+
const top = git(root, ['rev-parse', '--show-toplevel']).trim();
|
|
18
|
+
if (fs.realpathSync.native(top) !== fs.realpathSync.native(root)) throw new Error('请在业务 Git 项目根生成证据');
|
|
19
|
+
const branch = git(root, ['symbolic-ref', '--short', 'HEAD']).trim();
|
|
20
|
+
if (branch !== run.branch) throw new Error('代码快照必须在运行所属的实际工作分支生成,请先切换分支');
|
|
21
|
+
return branch;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function codeSnapshot(root, run) {
|
|
25
|
+
const branch = assertWorkingBranch(root, run);
|
|
26
|
+
const head = git(root, ['rev-parse', 'HEAD']).trim();
|
|
27
|
+
const base = run.scope?.base || 'main';
|
|
28
|
+
const baseCommit = git(root, ['rev-parse', '--verify', `${base}^{commit}`]).trim();
|
|
29
|
+
const mergeBase = git(root, ['merge-base', baseCommit, head]).trim();
|
|
30
|
+
const exclude = [...INTERNAL, ...(run.scope?.exclude ?? [])];
|
|
31
|
+
const names = new Set([
|
|
32
|
+
...git(root, ['ls-files', '--cached', '--others', '--exclude-standard', '-z']).split('\0'),
|
|
33
|
+
...git(root, ['ls-tree', '-r', '--name-only', '-z', mergeBase]).split('\0'),
|
|
34
|
+
].filter((p) => p && !exclude.some((g) => matchGlob(p, g))));
|
|
35
|
+
const entries = [...names].sort().map((file) => {
|
|
36
|
+
const abs = path.join(root, file);
|
|
37
|
+
let stat;
|
|
38
|
+
try { stat = fs.lstatSync(abs); } catch (e) { if (e.code === 'ENOENT') return [file, 'deleted']; throw e; }
|
|
39
|
+
if (stat.isSymbolicLink()) return [file, 'symlink', fs.readlinkSync(abs)];
|
|
40
|
+
// dirty 标记不能代表具体内容;脏子模块须先处理,不能复用含糊的证据。
|
|
41
|
+
if (stat.isDirectory()) {
|
|
42
|
+
if (git(abs, ['status', '--porcelain', '--untracked-files=all']).trim()) throw new Error(`子模块/嵌套仓库有未提交内容,先处理后生成快照:${file}`);
|
|
43
|
+
return [file, 'submodule', git(abs, ['rev-parse', 'HEAD']).trim()];
|
|
44
|
+
}
|
|
45
|
+
return [file, stat.mode & 0o111 ? 'executable' : 'file', hash(fs.readFileSync(abs))];
|
|
46
|
+
});
|
|
47
|
+
const snapshot = { branch, base, base_commit: baseCommit, merge_base: mergeBase, head, scope: run.scope, files: entries.length };
|
|
48
|
+
return { ...snapshot, digest: hash(JSON.stringify({ ...snapshot, entries })) };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function assertSnapshot(root, run, snapshot) {
|
|
52
|
+
const current = codeSnapshot(root, run);
|
|
53
|
+
if (!snapshot?.digest || snapshot.digest !== current.digest) throw new Error('代码或基线已变化,原验证/审查证据已失效;重新生成快照、验证并审查');
|
|
54
|
+
return current;
|
|
55
|
+
}
|
|
@@ -92,13 +92,15 @@ function acquire(lock) {
|
|
|
92
92
|
throw busy(lock);
|
|
93
93
|
}
|
|
94
94
|
|
|
95
|
-
export function updateMeta(file, update, { root = process.cwd() } = {}) {
|
|
95
|
+
export function updateMeta(file, update, { root = process.cwd(), allowFinalization = false } = {}) {
|
|
96
96
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
97
97
|
const lock = lockPath(root, file);
|
|
98
98
|
const release = acquire(lock);
|
|
99
99
|
const tmp = path.join(path.dirname(lock), `${path.basename(file)}.${randomUUID()}.tmp`);
|
|
100
100
|
try {
|
|
101
|
-
const
|
|
101
|
+
const current = readMeta(file);
|
|
102
|
+
if (current.pending_finalization && !allowFinalization) throw new Error(`产物收尾尚未完成,先运行 artifact.mjs resume --id ${current.pending_finalization.run_id}`);
|
|
103
|
+
const next = update(current);
|
|
102
104
|
const text = `${JSON.stringify(next, null, 2)}\n`;
|
|
103
105
|
if (!fs.existsSync(file) || fs.readFileSync(file, 'utf8') !== text) {
|
|
104
106
|
fs.writeFileSync(tmp, text);
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// ---------------------------------------------------------------- glob
|
|
2
|
+
// ** 跨目录、* 不跨 /、? 单个字符、{a,b} 展开(括号里同样支持这些写法);不含 / 的模式匹配文件名(同 .gitignore)。不区分大小写。
|
|
3
|
+
// 没有闭合的 { 按普通字符处理(画像里写错也不会卡住)
|
|
4
|
+
function globSource(glob) {
|
|
5
|
+
let re = '';
|
|
6
|
+
for (let i = 0; i < glob.length; i++) {
|
|
7
|
+
const c = glob[i];
|
|
8
|
+
const end = c === '{' ? glob.indexOf('}', i) : -1;
|
|
9
|
+
if (c === '*' && glob[i + 1] === '*') {
|
|
10
|
+
const slash = glob[i + 2] === '/';
|
|
11
|
+
re += slash ? '(?:.*/)?' : '.*';
|
|
12
|
+
i += slash ? 2 : 1;
|
|
13
|
+
} else if (c === '*') re += '[^/]*';
|
|
14
|
+
else if (c === '?') re += '[^/]';
|
|
15
|
+
else if (end > i) { re += `(?:${glob.slice(i + 1, end).split(',').map(globSource).join('|')})`; i = end; }
|
|
16
|
+
else re += c.replace(/[.+^$(){}|[\]\\]/g, '\\$&');
|
|
17
|
+
}
|
|
18
|
+
return re;
|
|
19
|
+
}
|
|
20
|
+
export const globToRegExp = (glob) => new RegExp(`^${globSource(glob)}$`, 'i');
|
|
21
|
+
export const matchGlob = (p, glob) => globToRegExp(glob).test(glob.includes('/') ? p : p.split('/').pop());
|
|
@@ -22,6 +22,15 @@ export const OLD_DIR = `${TMP_DIR}/old-artifacts`;
|
|
|
22
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
23
|
const versionsOf = (dirAbs) => readJson(path.join(dirAbs, 'meta.json'))?.versions ?? {};
|
|
24
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
|
+
|
|
25
34
|
// 按目录里的文件重建 meta.json(保留需求名、分支、创建时间)
|
|
26
35
|
// bump:写完新版后(sync <path>)确认新版本——和 path 时归档的上一版副本内容不同就把版本号加一,返回归档了哪些
|
|
27
36
|
export function sync(root, dirRel, { bump = false } = {}) {
|
|
@@ -40,12 +49,7 @@ export function sync(root, dirRel, { bump = false } = {}) {
|
|
|
40
49
|
archived.push({ kind, version: v, file: relOf(root, arc) });
|
|
41
50
|
}
|
|
42
51
|
}
|
|
43
|
-
const artifacts =
|
|
44
|
-
const p = parseFile(name);
|
|
45
|
-
if (!p) return null;
|
|
46
|
-
const text = fs.readFileSync(path.join(dir, name), 'utf8');
|
|
47
|
-
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) };
|
|
48
|
-
}).filter(Boolean).sort((a, b) => Object.keys(FILES).indexOf(a.kind) - Object.keys(FILES).indexOf(b.kind) || a.version - b.version);
|
|
52
|
+
const artifacts = indexArtifacts(dir, versions);
|
|
49
53
|
const branches = old.branches ?? []; // 绑定只由 bind 更新;文档头不隐式修改需求归属。
|
|
50
54
|
const latest = Object.fromEntries(Object.keys(FILES).map((k) => [k, artifacts.filter((a) => a.kind === k).at(-1)?.file ?? null]));
|
|
51
55
|
// 内容没变就不写(meta.json 随需求目录提交,避免无谓的改动);产物有变化才更新 updated
|
|
@@ -67,7 +71,7 @@ export function which(root, branch) {
|
|
|
67
71
|
if (!L.ok) return notReady(L);
|
|
68
72
|
const r = find(root, branch, L);
|
|
69
73
|
const where = L.mode === 'repo' ? { mode: 'repo', repo: L.repo_rel, project: L.project } : { mode: 'project', project: L.project };
|
|
70
|
-
if (r) return { bound: true, ...where, branch, name: r.name, dir: r.dir, meta: sync(root, r.dir) };
|
|
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) };
|
|
71
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 }));
|
|
72
76
|
// 其他项目已有的需求(跨服务需求,本项目可以用同一个名字加入);文档仓库里常见,随代码提交时一般没有
|
|
73
77
|
const mine = new Set(requirements(root, L).map((x) => x.slug));
|
|
@@ -118,6 +122,7 @@ export function nextPath(root, kind, branch) {
|
|
|
118
122
|
if (!L.ok) return { code: 2, out: notReady(L) };
|
|
119
123
|
const r = find(root, branch, L);
|
|
120
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}` } };
|
|
121
126
|
const abs = path.join(r.abs, `${FILES[kind]}.md`);
|
|
122
127
|
let v = 1; let previous = null; let record = null;
|
|
123
128
|
if (fs.existsSync(abs)) {
|
|
@@ -0,0 +1,153 @@
|
|
|
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' ? ['F3', 'F4', 'F5', 'F6', 'F7', 'F8'] : ['B3', '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 assertRequirement(root, req, run, contents) {
|
|
19
|
+
return receipt(root, req, run, 'requirement', contents);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function assertPlanBasis(root, req, run, contents) {
|
|
23
|
+
const requirement = assertRequirement(root, req, run, contents);
|
|
24
|
+
const plan = receipt(root, req, run, 'plan', contents);
|
|
25
|
+
if (plan.requirement?.hash !== requirement.hash || plan.requirement.version !== requirement.version) throw new Error('方案依据的需求版本已变化,请根据当前 requirement.md 重新收尾方案');
|
|
26
|
+
return plan;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function assertPlan(root, req, run, contents) {
|
|
30
|
+
assertWorkingBranch(root, run);
|
|
31
|
+
const plan = assertPlanBasis(root, req, run, contents);
|
|
32
|
+
if (run.size !== 'S' && (run.plan_approval?.hash !== plan.hash || run.plan_approval.version !== plan.version)) throw new Error('M / L 方案尚未由用户确认,或确认后方案已变化;先记录 approval.confirmed');
|
|
33
|
+
return plan;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function assertValidation(root, req, run, contents) {
|
|
37
|
+
const plan = assertPlan(root, req, run, contents);
|
|
38
|
+
if (run.implementation?.plan !== plan.hash) throw new Error('尚未通过方案门禁进入实现,请先进入 F5;bug 保存 implement: true');
|
|
39
|
+
assertSnapshot(root, run, run.validation?.snapshot);
|
|
40
|
+
return run.validation;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function assertReview(root, req, run, contents) {
|
|
44
|
+
const validation = isDev(run) ? assertValidation(root, req, run, contents) : null;
|
|
45
|
+
const report = receipt(root, req, run, 'review', contents);
|
|
46
|
+
if (!run.review || run.review.report_hash !== report.hash || run.review.report_version !== report.version
|
|
47
|
+
|| run.review.inputs !== hash(JSON.stringify(reviewInputs(run)))
|
|
48
|
+
|| (validation && run.review.snapshot.digest !== validation.snapshot.digest)) throw new Error('缺少对应本轮验证和报告版本的审查证据,请重新审查');
|
|
49
|
+
if (!validation) assertSnapshot(root, run, run.review.snapshot);
|
|
50
|
+
return run.review;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function assertDelivery(root, req, run, contents) {
|
|
54
|
+
const review = assertReview(root, req, run, contents);
|
|
55
|
+
const decision = run.decision;
|
|
56
|
+
if (decision?.action !== 'deliver' || decision.confirmed !== true || decision.report_hash !== review.report_hash
|
|
57
|
+
|| decision.report_version !== review.report_version || decision.code !== review.snapshot.digest) throw new Error('进入交付前必须由用户明确选择本轮报告的交付;旧交付选择不再有效');
|
|
58
|
+
const serious = review.result.findings.filter((f) => f.scope !== 'outside' && ['CRITICAL', 'HIGH'].includes(f.severity) && f.verification === 'confirmed');
|
|
59
|
+
if (serious.some((f) => !decision.accepted_risks?.includes(f.id))) throw new Error('严重遗留风险必须逐项说明并取得用户明确接受,记录 accepted_risks 中的问题 id');
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function applyDevEvidence(root, req, run, patch, at, contents = {}) {
|
|
63
|
+
if (!isDev(run)) return;
|
|
64
|
+
for (const step of coreSteps(run)) if (run.steps[step].status === 'skipped') throw new Error(`完整 dev 核心步骤不能跳过:${step}`);
|
|
65
|
+
if (patch.approval !== undefined) {
|
|
66
|
+
if (patch.approval?.confirmed !== true) throw new Error('approval 必须记录用户明确确认:confirmed: true');
|
|
67
|
+
const plan = assertPlanBasis(root, req, run, contents);
|
|
68
|
+
run.plan_approval = { hash: plan.hash, version: plan.version, at };
|
|
69
|
+
}
|
|
70
|
+
const implementing = patch.implement === true || (run.kind === 'feature' && patch.stage === 'F5');
|
|
71
|
+
if (patch.implement !== undefined && patch.implement !== true) throw new Error('implement 只接受 true');
|
|
72
|
+
if (implementing) {
|
|
73
|
+
if (run.kind === 'feature' && run.steps.F4.status !== 'completed') throw new Error('方案步骤 F4 尚未完成,不能进入实现');
|
|
74
|
+
if (run.kind === 'bug' && run.stage !== 'B4') throw new Error('bug 只能在 B4 进入实现');
|
|
75
|
+
const plan = assertPlan(root, req, run, contents);
|
|
76
|
+
run.implementation = { plan: plan.hash, at };
|
|
77
|
+
}
|
|
78
|
+
if (patch.validation !== undefined) {
|
|
79
|
+
if (run.stage !== (run.kind === 'feature' ? 'F6' : 'B4')) throw new Error('请在 F6/B4 验证阶段记录 validation');
|
|
80
|
+
const plan = assertPlan(root, req, run, contents);
|
|
81
|
+
if (run.implementation?.plan !== plan.hash) throw new Error('先通过方案门禁进入实现,再记录验证');
|
|
82
|
+
const v = patch.validation;
|
|
83
|
+
if (!Array.isArray(v?.checks) || !v.checks.length || v.checks.some((c) => !c.command?.trim()
|
|
84
|
+
|| !['passed', 'failed', 'unverified'].includes(c.result) || (c.result !== 'passed' && !c.reason?.trim()))) throw new Error('validation.checks 需要命令/操作、passed / failed / unverified;失败或未验证须写 reason');
|
|
85
|
+
const snapshot = assertSnapshot(root, run, v.snapshot);
|
|
86
|
+
run.validation = { snapshot, checks: v.checks, at };
|
|
87
|
+
run.review = null; run.decision = null;
|
|
88
|
+
if (run.kind === 'feature') for (const step of ['F7', 'F8']) run.steps[step] = { status: 'pending' };
|
|
89
|
+
}
|
|
90
|
+
if (patch.decision?.action === 'deliver') {
|
|
91
|
+
if (run.kind === 'feature' && run.steps.F7.status !== 'completed') throw new Error('审查步骤 F7 尚未完成,不能选择交付');
|
|
92
|
+
const review = assertReview(root, req, run, contents);
|
|
93
|
+
run.decision = { ...run.decision, code: review.snapshot.digest, report_hash: review.report_hash, report_version: review.report_version };
|
|
94
|
+
assertDelivery(root, req, run, contents);
|
|
95
|
+
}
|
|
96
|
+
const completed = (s) => patch.steps?.[s]?.status === 'completed';
|
|
97
|
+
const requirementStep = run.kind === 'feature' ? 'F3' : 'B3';
|
|
98
|
+
if (completed(requirementStep)) assertRequirement(root, req, run, contents);
|
|
99
|
+
if (patch.stage === (run.kind === 'feature' ? 'F4' : 'B4')) {
|
|
100
|
+
assertRequirement(root, req, run, contents);
|
|
101
|
+
if (run.steps[requirementStep].status !== 'completed') throw new Error('需求文档尚未完成,不能进入方案/修复阶段');
|
|
102
|
+
}
|
|
103
|
+
if (run.kind === 'feature') {
|
|
104
|
+
if (completed('F4')) receipt(root, req, run, 'plan', contents);
|
|
105
|
+
if (patch.stage === 'F6' || completed('F5')) {
|
|
106
|
+
const plan = assertPlan(root, req, run, contents);
|
|
107
|
+
if (run.implementation?.plan !== plan.hash) throw new Error('尚未通过方案门禁进入实现');
|
|
108
|
+
}
|
|
109
|
+
if (patch.stage === 'F7' || completed('F6')) {
|
|
110
|
+
if (run.steps.F5.status !== 'completed') throw new Error('实现步骤 F5 尚未完成');
|
|
111
|
+
assertValidation(root, req, run, contents);
|
|
112
|
+
if (patch.stage === 'F7' && run.steps.F6.status !== 'completed') throw new Error('验证步骤 F6 尚未完成');
|
|
113
|
+
}
|
|
114
|
+
if (completed('F7')) assertReview(root, req, run, contents);
|
|
115
|
+
if (patch.stage === 'F8' || completed('F8')) assertDelivery(root, req, run, contents);
|
|
116
|
+
if (completed('F8')) receipt(root, req, run, 'delivery', contents);
|
|
117
|
+
} else {
|
|
118
|
+
if (completed('B4') || patch.stage === 'B5') {
|
|
119
|
+
assertValidation(root, req, run, contents);
|
|
120
|
+
if (patch.stage === 'B5' && run.steps.B4.status !== 'completed') throw new Error('修复与验证步骤 B4 尚未完成');
|
|
121
|
+
}
|
|
122
|
+
if (completed('B5')) { assertDelivery(root, req, run, contents); receipt(root, req, run, 'delivery', contents); }
|
|
123
|
+
}
|
|
124
|
+
const event = run.history.at(-1);
|
|
125
|
+
if (patch.approval) event.approval = run.plan_approval;
|
|
126
|
+
if (patch.validation) event.validation = run.validation;
|
|
127
|
+
if (patch.decision) event.decision = run.decision;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export function reviewInputs(run) {
|
|
131
|
+
const facts = Object.fromEntries(['summary', 'acceptance', 'decisions', 'scope', 'baseline'].filter((k) => run.context[k] !== undefined).map((k) => [k, run.context[k]]));
|
|
132
|
+
return { facts, requirement: run.artifacts?.requirement ?? null, scope: run.scope, plan: run.artifacts?.plan ?? null, validation: run.validation ?? null };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function reviewEvidence(root, req, run, packet, result, contents) {
|
|
136
|
+
if (!packet || packet.run_id !== run.id || packet.revision > run.revision || packet.inputs !== hash(JSON.stringify(reviewInputs(run)))) throw new Error('审查交接材料不属于当前运行内容,请重新生成 handoff');
|
|
137
|
+
const snapshot = assertSnapshot(root, run, packet.snapshot);
|
|
138
|
+
if (isDev(run)) assertValidation(root, req, run, contents);
|
|
139
|
+
if (result?.run_id !== run.id || result.code !== snapshot.digest || result.inputs !== packet.inputs) throw new Error('审查结果的运行、代码版本或交接内容不匹配,请返回本轮审查结果');
|
|
140
|
+
if (!Array.isArray(result?.findings) || !Array.isArray(result?.coverage?.reviewed) || !Array.isArray(result?.coverage?.uncovered)) throw new Error('审查结果需要 findings 和 coverage.reviewed / uncovered');
|
|
141
|
+
const covered = [...result.coverage.reviewed, ...result.coverage.uncovered];
|
|
142
|
+
const expected = packet.scope.review.map((f) => f.path);
|
|
143
|
+
if (new Set(covered).size !== covered.length || expected.length !== covered.length || expected.some((p) => !covered.includes(p))) throw new Error('审查覆盖范围必须逐文件对应交接材料,未审完的放入 uncovered');
|
|
144
|
+
const ids = new Set();
|
|
145
|
+
for (const f of result.findings) {
|
|
146
|
+
if (!f.id || ids.has(f.id) || !['CRITICAL', 'HIGH', 'MEDIUM', 'LOW'].includes(f.severity) || !['confirmed', 'pending'].includes(f.verification)
|
|
147
|
+
|| (f.scope !== undefined && !['in_scope', 'outside'].includes(f.scope))
|
|
148
|
+
|| !f.file || !Number.isInteger(f.line) || f.line < 1 || !f.summary?.trim()) throw new Error('审查问题需要唯一 id、severity、verification、file、正整数 line 与 summary');
|
|
149
|
+
ids.add(f.id);
|
|
150
|
+
}
|
|
151
|
+
const report = receipt(root, req, run, 'review', contents);
|
|
152
|
+
return { snapshot, inputs: packet.inputs, report_hash: report.hash, report_version: report.version, result, at: new Date().toISOString() };
|
|
153
|
+
}
|
package/workflow/lib/runs.mjs
CHANGED
|
@@ -6,6 +6,9 @@ import { find, requirements } from './requirement-read.mjs';
|
|
|
6
6
|
import { parseBranch } from './artifact-model.mjs';
|
|
7
7
|
import { updateMeta } from './meta-store.mjs';
|
|
8
8
|
import { loadWorkspace } from './workspace-read.mjs';
|
|
9
|
+
import { readProfile } from './project.mjs';
|
|
10
|
+
import { isDev, coreSteps, applyDevEvidence, assertReview, assertDelivery, receipt } from './run-gates.mjs';
|
|
11
|
+
import { codeSnapshot } from './code-snapshot.mjs';
|
|
9
12
|
|
|
10
13
|
export const FLOWS = {
|
|
11
14
|
feature: ['Step0', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8'],
|
|
@@ -27,19 +30,30 @@ export function allRuns(root, workspace = loadWorkspace(root)) {
|
|
|
27
30
|
|
|
28
31
|
export const branchRuns = (root, branch, workspace) => allRuns(root, workspace).filter((run) => run.branch === branch);
|
|
29
32
|
|
|
30
|
-
export function runState(root, branch, workspace = loadWorkspace(root)) {
|
|
33
|
+
export function runState(root, branch, workspace = loadWorkspace(root), id = null) {
|
|
31
34
|
const runs = branchRuns(root, branch, workspace);
|
|
32
|
-
const current = runs.filter((r) => !terminal(r.status)).at(-1) ?? runs.at(-1) ?? null;
|
|
33
|
-
|
|
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}`
|
|
34
37
|
: current.status === 'blocked' ? `处理阻塞:${current.reason}`
|
|
35
38
|
: terminal(current.status) ? `${STATUS_LABELS[current.status]}:${current.kind}(${current.id})`
|
|
36
39
|
: `继续 ${current.stage}(${current.kind},运行 ${current.id})`;
|
|
37
|
-
|
|
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 } : {}) };
|
|
38
52
|
}
|
|
39
53
|
|
|
40
|
-
function applyCheckpoint(run, patch, at, reopen = true) {
|
|
54
|
+
export function applyCheckpoint(run, patch, at, reopen = true) {
|
|
41
55
|
if (!object(patch)) throw new Error('checkpoint 必须是 JSON 对象');
|
|
42
|
-
const allowed = ['stage', 'status', 'size', 'waiting_for', 'reason', 'steps', 'context', 'decision'];
|
|
56
|
+
const allowed = ['stage', 'status', 'size', 'waiting_for', 'reason', 'steps', 'context', 'decision', 'approval', 'implement', 'validation', 'scope'];
|
|
43
57
|
for (const key of Object.keys(patch)) if (!allowed.includes(key)) throw new Error(`不支持修改字段:${key}`);
|
|
44
58
|
if (patch.status !== undefined && !['running', 'waiting_user', 'blocked'].includes(patch.status)) throw new Error('save 的状态只支持 running / waiting_user / blocked;完成用 complete,取消用 cancel');
|
|
45
59
|
if (patch.size !== undefined) {
|
|
@@ -54,6 +68,12 @@ function applyCheckpoint(run, patch, at, reopen = true) {
|
|
|
54
68
|
if (reopen && patch.stage && (stages.indexOf(stage) < stages.indexOf(run.stage) || (status === 'running' && done(run.steps[stage].status)))) {
|
|
55
69
|
for (const name of stages.slice(stages.indexOf(stage))) run.steps[name] = { status: 'pending' };
|
|
56
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
|
+
}
|
|
57
77
|
}
|
|
58
78
|
if (patch.steps !== undefined) {
|
|
59
79
|
if (!object(patch.steps)) throw new Error('steps 必须是对象');
|
|
@@ -64,12 +84,18 @@ function applyCheckpoint(run, patch, at, reopen = true) {
|
|
|
64
84
|
run.steps[name] = { ...value, updated_at: at, completed_at: value.status === 'completed' ? (run.steps[name].completed_at ?? at) : null };
|
|
65
85
|
}
|
|
66
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
|
+
}
|
|
67
92
|
if (patch.context !== undefined) {
|
|
68
93
|
if (!object(patch.context)) throw new Error('context 必须是对象');
|
|
69
94
|
run.context = { ...run.context, ...patch.context };
|
|
70
95
|
}
|
|
71
96
|
if (patch.decision !== undefined) {
|
|
72
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 数组');
|
|
73
99
|
run.decision = { ...patch.decision, at };
|
|
74
100
|
}
|
|
75
101
|
run.stage = stage;
|
|
@@ -94,25 +120,39 @@ export function startRun(root, { branch, kind = 'feature', size = null, input =
|
|
|
94
120
|
const runs = meta.runs ?? {};
|
|
95
121
|
selected = Object.values(runs).find((r) => r.branch === branch && r.kind === kind && !terminal(r.status));
|
|
96
122
|
if (selected) { resumed = true; return meta; }
|
|
123
|
+
const profile = readProfile(root).profile;
|
|
97
124
|
const at = timestamp(); const id = randomUUID();
|
|
98
125
|
selected = applyCheckpoint({ id, kind, size, branch, revision: 1, status: 'running', stage: FLOWS[kind][0],
|
|
99
126
|
created_at: at, updated_at: at, completed_at: null, steps: Object.fromEntries(FLOWS[kind].map((s) => [s, { status: 'pending' }])),
|
|
100
|
-
|
|
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);
|
|
101
130
|
return { ...meta, runs: { ...runs, [id]: selected }, updated: at };
|
|
102
131
|
}, { root });
|
|
103
132
|
return { ok: true, resumed, dir: req.dir, run: selected };
|
|
104
133
|
}
|
|
105
134
|
|
|
106
|
-
export function
|
|
107
|
-
if (!branch || !id || !['save', 'complete', 'cancel'].includes(action)) throw new Error('需要当前分支、运行 id 和有效动作');
|
|
135
|
+
export function readRun(root, branch, id) {
|
|
108
136
|
const req = requirements(root).find((r) => Object.hasOwn(r.meta.runs ?? {}, id));
|
|
109
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);
|
|
110
152
|
let result;
|
|
111
153
|
updateMeta(path.join(req.abs, 'meta.json'), (meta) => {
|
|
112
154
|
const run = structuredClone(meta.runs[id]);
|
|
113
|
-
|
|
114
|
-
if (!Number.isInteger(revision) || run.revision !== revision) throw new Error(`运行版本冲突,重新读取状态后使用 --expect-revision ${run.revision}`);
|
|
115
|
-
if (terminal(run.status)) throw new Error('运行已结束,不再修改;新的工作请 start 新运行');
|
|
155
|
+
assertRunVersion(run, branch, revision);
|
|
116
156
|
const at = timestamp();
|
|
117
157
|
if (action === 'cancel') {
|
|
118
158
|
if (!input.reason?.trim()) throw new Error('取消运行需要 reason');
|
|
@@ -120,14 +160,18 @@ export function changeRun(root, { branch, id, revision, input = {}, action = 'sa
|
|
|
120
160
|
run.history.push({ at, stage: run.stage, status: 'cancelled', reason: input.reason });
|
|
121
161
|
} else {
|
|
122
162
|
applyCheckpoint(run, input, at, action !== 'complete');
|
|
163
|
+
applyDevEvidence(root, req, run, input, at);
|
|
123
164
|
if (action === 'complete') {
|
|
124
165
|
const steps = FLOWS[run.kind];
|
|
125
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('还有未完成步骤、待用户决定或阻塞,不能标记已完成');
|
|
126
167
|
if (['feature', 'bug'].includes(run.kind)) {
|
|
127
|
-
const required = run
|
|
168
|
+
const required = coreSteps(run);
|
|
169
|
+
assertDelivery(root, req, run);
|
|
170
|
+
receipt(root, req, run, 'delivery');
|
|
128
171
|
if (required.some((s) => run.steps[s].status !== 'completed') || run.decision?.action !== 'deliver' || !run.decision.confirmed) throw new Error('完整 dev 流程必须完成方案、实现、验证、审查和交付,且用户已选择交付');
|
|
129
172
|
}
|
|
130
|
-
|
|
173
|
+
if (run.kind === 'review') assertReview(root, req, run);
|
|
174
|
+
const files = { feature: ['requirement.md', 'plan.md', 'review.md', 'delivery.md'], bug: ['requirement.md', 'plan.md', 'review.md', 'delivery.md'], review: ['review.md'], tech: ['tech-doc.md'], release: ['release-doc.md'] };
|
|
131
175
|
for (const name of files[run.kind] ?? []) {
|
|
132
176
|
const file = path.join(req.abs, name);
|
|
133
177
|
if (!fs.existsSync(file) || parseBranch(fs.readFileSync(file, 'utf8')) !== branch) throw new Error(`缺少当前分支的产物:${name}`);
|
|
@@ -103,7 +103,9 @@ export function loadWorkspace(root, { allProjects = false, allBranches = false }
|
|
|
103
103
|
diagnostics.push({ code: 'invalid_run', path: `${req.dir}/meta.json`, message: `运行 ${id} 结构无效,不能恢复` });
|
|
104
104
|
continue;
|
|
105
105
|
}
|
|
106
|
-
|
|
106
|
+
const pending = req.meta.pending_finalization;
|
|
107
|
+
runs.push({ ...run, requirement: req.name, dir: req.dir, project: req.project,
|
|
108
|
+
...(pending?.run_id === id ? { pending_finalization: { kind: pending.kind, id: pending.id } } : {}) });
|
|
107
109
|
}
|
|
108
110
|
}
|
|
109
111
|
artifacts.sort(byArtifactDate);
|