@rowansenne/workflow-run 0.35.0 → 0.36.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 (47) hide show
  1. package/CHANGELOG.md +23 -1
  2. package/README.md +2 -0
  3. package/bin/lib/artifact-context.mjs +1 -1
  4. package/bin/lib/docsrepo.mjs +4 -6
  5. package/bin/lib/doctor.mjs +0 -3
  6. package/bin/lib/install.mjs +15 -15
  7. package/create-release-md-doc/SKILL.md.tpl +1 -1
  8. package/create-tech-md-doc/SKILL.md.tpl +1 -1
  9. package/dev/references/delivery.md +3 -3
  10. package/docs/architecture.html +3 -2
  11. package/docs/development.md +10 -4
  12. package/docs/full-install.html +90 -125
  13. package/docs/installation.md +1 -1
  14. package/docs/loan-service-install.html +90 -0
  15. package/docs/team-guide.md +3 -2
  16. package/docs/workflow-control-roadmap.md +144 -0
  17. package/docs/workflow-core-phase-one-report.md +41 -0
  18. package/docs/workflow-core-phase-one.md +317 -0
  19. package/docs/workflows.md +2 -2
  20. package/examples/workflow-core.mjs +26 -0
  21. package/package.json +2 -1
  22. package/project-review/SKILL.md.tpl +1 -1
  23. package/project-review/references/checklist.md.tpl +1 -1
  24. package/project-review/references/reporting.md +2 -2
  25. package/workflow/core/errors.mjs +61 -0
  26. package/workflow/core/index.mjs +286 -0
  27. package/workflow/core/review-handoff.mjs +101 -0
  28. package/workflow/integrations/skill-document-policy.mjs +28 -0
  29. package/workflow/lib/artifact-finalize.mjs +49 -10
  30. package/workflow/lib/code-snapshot.mjs +5 -0
  31. package/workflow/lib/meta-store.mjs +12 -1
  32. package/workflow/lib/project.mjs +165 -14
  33. package/workflow/lib/requirements.mjs +57 -100
  34. package/workflow/lib/review-scope.mjs +262 -0
  35. package/workflow/lib/runs.mjs +11 -1
  36. package/workflow/lib/workspace-read.mjs +13 -4
  37. package/workflow/references/architecture.md +10 -5
  38. package/workflow/references/core-api.md +196 -0
  39. package/workflow/references/execution.md +4 -4
  40. package/workflow/references/profile.md +20 -0
  41. package/workflow/references/requirements.md +12 -12
  42. package/workflow/scripts/artifact.mjs +36 -14
  43. package/workflow/scripts/requirement.mjs +36 -40
  44. package/workflow/scripts/resolve.mjs +2 -2
  45. package/workflow/scripts/review-handoff.mjs +49 -73
  46. package/workflow/scripts/review-scope.mjs +78 -294
  47. package/workflow/scripts/run.mjs +21 -9
@@ -19,7 +19,7 @@
19
19
  交付报告后先判断本次发现里有没有**特别值得记录**的内容:同类问题再次出现(知识库里已有类似沉淀,或本次多处出现)、新确立的编码约定、容易踩的坑。没有 → 不提沉淀,报告的「DocNexus」元信息行写「无需沉淀」;有 → 明确问用户「要不要启动 DocNexus 流程,把本次审查沉淀到 DocNexus?」,并列出建议沉淀的内容;发起询问时将报告元信息改成「未沉淀」,入库成功后再写知识路径。
20
20
  - 用户同意 → 按 DocNexus 入口 skill `docnexus` 的 capture 流程写入;正文只写知识,不写分支、路径;有 facts 时按 `<skills>/workflow/references/docnexus.md`「沉淀的来源」的格式写 provenance;分类用 `node <skills>/workflow/scripts/resolve.mjs category project-review` 的结果作为调用方显式分类封存(见 `<skills>/workflow/references/docnexus.md`「写入 DocNexus 的分类」)。只沉淀问题模式和约定,不沉淀某次审查的逐条清单,也不沉淀「⚠ 待确认」的发现;知识库已有同类沉淀时更新那一篇(带 `--base-version`),不要重复新建。写入成功后把报告的「DocNexus」元信息行改成 `workflow-run/docnexus/library/<path>`(多篇用「、」分隔),并回报给用户。
21
21
  - 用户不同意 → 元信息行保持「未沉淀」。
22
- - 元信息更新后运行 `requirement.mjs sync <报告路径>`。
22
+ - 元信息更新后运行 `requirement.mjs reindex`。它只刷新派生索引,不修复正文 hash 或旧审查证据。
23
23
 
24
24
  ## 第 9 步 — 记录运行反馈(不问用户)
25
25
 
@@ -41,7 +41,7 @@
41
41
  - 报告先写 tmp 草稿,另写结构化结果(findings、coverage);按 execution.md 用 `artifact.mjs finalize --kind review --packet <交接JSON> --result <结果JSON>` 收尾,输出 path / cite / previous。dev 内部只交回草稿与结果,不由子 agent 更新 meta。
42
42
  - 正式报告同时完整交给用户,内容与落盘文件一致;独立 review 将 R7 标 completed 后 complete,dev 内部由主 agent 保存 waiting_user 等选择。
43
43
  - 事实核对仍用 `lint-doc.mjs <草稿> --skill project-review --facts`;错误先修正,无法核实的标待确认。finalize 另校验模板、分支、代码快照与覆盖登记。
44
- - previous 非空时说明旧版已归档,不能替用户删除;独立文档仓库按 requirements.md 运行 pending 后提示提交,dev 内部延后到 F8。已完成报告的沉淀/wiki 元信息更新仍用 sync。
44
+ - previous 非空时说明旧版已归档,不能替用户删除;独立文档仓库按 requirements.md 运行 pending 后提示提交,dev 内部延后到 F8。已完成报告的沉淀/wiki 元信息更新后用 reindex。
45
45
 
46
46
  ## 终端命令
47
47
 
@@ -0,0 +1,61 @@
1
+ export const WORKFLOW_ERROR_CODES = Object.freeze({
2
+ INVALID_ARGUMENT: 'INVALID_ARGUMENT',
3
+ PROJECT_ROOT_INVALID: 'PROJECT_ROOT_INVALID',
4
+ PROJECT_CONFIG_AMBIGUOUS: 'PROJECT_CONFIG_AMBIGUOUS',
5
+ REQUIREMENT_NOT_READY: 'REQUIREMENT_NOT_READY',
6
+ REQUIREMENT_NOT_BOUND: 'REQUIREMENT_NOT_BOUND',
7
+ BRANCH_MISMATCH: 'BRANCH_MISMATCH',
8
+ RUN_NOT_FOUND: 'RUN_NOT_FOUND',
9
+ REVISION_CONFLICT: 'REVISION_CONFLICT',
10
+ RUN_TERMINAL: 'RUN_TERMINAL',
11
+ STAGE_NOT_ALLOWED: 'STAGE_NOT_ALLOWED',
12
+ GATE_REJECTED: 'GATE_REJECTED',
13
+ EVIDENCE_INVALID: 'EVIDENCE_INVALID',
14
+ PENDING_FINALIZATION: 'PENDING_FINALIZATION',
15
+ PENDING_OPERATION_MISMATCH: 'PENDING_OPERATION_MISMATCH',
16
+ STORAGE_ERROR: 'STORAGE_ERROR',
17
+ NOT_IMPLEMENTED: 'NOT_IMPLEMENTED',
18
+ });
19
+
20
+ const knownCodes = new Set(Object.values(WORKFLOW_ERROR_CODES));
21
+
22
+ export class WorkflowError extends Error {
23
+ constructor(code, message, { details, cause } = {}) {
24
+ super(message, cause ? { cause } : undefined);
25
+ this.name = 'WorkflowError';
26
+ this.code = code;
27
+ this.details = details && typeof details === 'object' && !Array.isArray(details) ? details : {};
28
+ }
29
+ }
30
+
31
+ const rules = [
32
+ [/项目存在多个.*workflow 配置目录|profile 来源/, WORKFLOW_ERROR_CODES.PROJECT_CONFIG_AMBIGUOUS],
33
+ [/版本冲突|expect-revision/, WORKFLOW_ERROR_CODES.REVISION_CONFLICT],
34
+ [/找不到运行/, WORKFLOW_ERROR_CODES.RUN_NOT_FOUND],
35
+ [/运行已结束/, WORKFLOW_ERROR_CODES.RUN_TERMINAL],
36
+ [/收尾尚未完成|待完成收尾|pending_finalization/i, WORKFLOW_ERROR_CODES.PENDING_FINALIZATION],
37
+ [/operationId.*(?:不匹配|已消失|已替换)|待办操作.*不匹配/i, WORKFLOW_ERROR_CODES.PENDING_OPERATION_MISMATCH],
38
+ [/尚未绑定|绑定指定需求|先确认需求/, WORKFLOW_ERROR_CODES.REQUIREMENT_NOT_BOUND],
39
+ [/其他分支|实际工作区分支|当前分支.*不一致|不在.*分支/, WORKFLOW_ERROR_CODES.BRANCH_MISMATCH],
40
+ [/无效阶段|不属于当前运行|应在 .* 收尾|该产物种类/, WORKFLOW_ERROR_CODES.STAGE_NOT_ALLOWED],
41
+ [/证据|快照|报告版本|需求版本|方案依据|旧交付|审查结果|审查覆盖/, WORKFLOW_ERROR_CODES.EVIDENCE_INVALID],
42
+ ];
43
+
44
+ export function toWorkflowError(error, fallbackCode = WORKFLOW_ERROR_CODES.GATE_REJECTED) {
45
+ if (error instanceof WorkflowError) return error;
46
+ const message = error instanceof Error ? error.message : String(error);
47
+ const explicitCode = error?.code;
48
+ if (knownCodes.has(explicitCode)) {
49
+ return new WorkflowError(explicitCode, message, { details: error.details, cause: error });
50
+ }
51
+ if (typeof explicitCode === 'string' && /^E[A-Z0-9_]+$/.test(explicitCode)) {
52
+ return new WorkflowError(WORKFLOW_ERROR_CODES.STORAGE_ERROR, message, {
53
+ details: { causeCode: explicitCode, path: error.path ?? null },
54
+ cause: error,
55
+ });
56
+ }
57
+ for (const [pattern, code] of rules) {
58
+ if (pattern.test(message)) return new WorkflowError(code, message, { cause: error });
59
+ }
60
+ return new WorkflowError(fallbackCode, message, { cause: error });
61
+ }
@@ -0,0 +1,286 @@
1
+ import path from 'node:path';
2
+
3
+ import { changeRun, readRun, runState, startRun } from '../lib/runs.mjs';
4
+ import {
5
+ bind as bindRequirement,
6
+ reindex as reindexRequirements,
7
+ which as whichRequirement,
8
+ } from '../lib/requirements.mjs';
9
+ import { abortFinalization, finalizeArtifact, resumeFinalization } from '../lib/artifact-finalize.mjs';
10
+ import { codeSnapshot } from '../lib/code-snapshot.mjs';
11
+ import { WORKFLOW_ERROR_CODES, WorkflowError, toWorkflowError } from './errors.mjs';
12
+ import {
13
+ createCodeHandoff,
14
+ createDocumentHandoff,
15
+ writeReviewPacket,
16
+ } from './review-handoff.mjs';
17
+
18
+ export { WORKFLOW_ERROR_CODES, WorkflowError };
19
+
20
+ const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
21
+ const invalid = (message, details) => {
22
+ throw new WorkflowError(WORKFLOW_ERROR_CODES.INVALID_ARGUMENT, message, { details });
23
+ };
24
+ const invoke = (operation, fallbackCode) => {
25
+ try {
26
+ return operation();
27
+ } catch (error) {
28
+ throw toWorkflowError(error, fallbackCode);
29
+ }
30
+ };
31
+ const requireObject = (value, name) => {
32
+ if (!isObject(value)) invalid(`${name} 必须是对象`);
33
+ return value;
34
+ };
35
+ const requireBranch = (branch) => {
36
+ if (typeof branch !== 'string' || !branch.trim()) invalid('branch 必须是非空字符串');
37
+ return branch;
38
+ };
39
+ const requireRunId = (id) => {
40
+ if (typeof id !== 'string' || !id.trim()) invalid('id 必须是非空字符串');
41
+ return id;
42
+ };
43
+ const requireRevision = (expectedRevision) => {
44
+ if (!Number.isInteger(expectedRevision)) invalid('expectedRevision 必须是整数');
45
+ return expectedRevision;
46
+ };
47
+ const requireInput = (input, name = 'input') => {
48
+ if (input === undefined) return {};
49
+ if (!isObject(input)) invalid(`${name} 必须是对象`);
50
+ return input;
51
+ };
52
+ const requireOperationId = (operationId) => {
53
+ if (typeof operationId !== 'string' || !operationId.trim()) invalid('operationId 必须是非空字符串');
54
+ return operationId;
55
+ };
56
+ const pendingRequest = (value, name) => {
57
+ const { branch, id, expectedRevision, operationId } = requireObject(value, name);
58
+ requireBranch(branch);
59
+ requireRunId(id);
60
+ requireRevision(expectedRevision);
61
+ requireOperationId(operationId);
62
+ return { branch, id, expectedRevision, operationId };
63
+ };
64
+
65
+ function normalizeRoot(root) {
66
+ if (typeof root !== 'string' || !root.trim() || !path.isAbsolute(root)) {
67
+ throw new WorkflowError(
68
+ WORKFLOW_ERROR_CODES.PROJECT_ROOT_INVALID,
69
+ 'root 必须是明确的绝对项目路径',
70
+ );
71
+ }
72
+ return path.resolve(root);
73
+ }
74
+
75
+ export function createWorkflow({ root, documentPolicy } = {}) {
76
+ const projectRoot = normalizeRoot(root);
77
+ if (documentPolicy !== undefined && (typeof documentPolicy !== 'object' || documentPolicy === null || typeof documentPolicy.validate !== 'function')) {
78
+ invalid('documentPolicy 必须提供 validate 方法');
79
+ }
80
+
81
+ return Object.freeze({
82
+ root: projectRoot,
83
+
84
+ requirements: Object.freeze({
85
+ bind(options) {
86
+ const { name = null, branch, base = null } = requireObject(options, 'requirements.bind');
87
+ requireBranch(branch);
88
+ return invoke(
89
+ () => bindRequirement(projectRoot, { name, branch, base }),
90
+ WORKFLOW_ERROR_CODES.REQUIREMENT_NOT_READY,
91
+ );
92
+ },
93
+
94
+ which(options) {
95
+ const { branch } = requireObject(options, 'requirements.which');
96
+ requireBranch(branch);
97
+ return invoke(
98
+ () => whichRequirement(projectRoot, branch),
99
+ WORKFLOW_ERROR_CODES.REQUIREMENT_NOT_READY,
100
+ );
101
+ },
102
+ }),
103
+
104
+ maintenance: Object.freeze({
105
+ reindex(options) {
106
+ const { branch = null, all = false } = requireObject(options, 'maintenance.reindex');
107
+ if (typeof all !== 'boolean') invalid('all 必须是布尔值');
108
+ if (!all) requireBranch(branch);
109
+ return invoke(
110
+ () => reindexRequirements(projectRoot, { branch, all }),
111
+ WORKFLOW_ERROR_CODES.REQUIREMENT_NOT_READY,
112
+ );
113
+ },
114
+ }),
115
+
116
+ runs: Object.freeze({
117
+ start(options) {
118
+ const { branch, kind = 'feature', size = null, input, dir = null } = requireObject(options, 'runs.start');
119
+ requireBranch(branch);
120
+ return invoke(() => startRun(projectRoot, {
121
+ branch,
122
+ kind,
123
+ size,
124
+ input: requireInput(input),
125
+ dir,
126
+ }));
127
+ },
128
+
129
+ status(options) {
130
+ const { branch, id = null } = requireObject(options, 'runs.status');
131
+ requireBranch(branch);
132
+ if (id !== null) requireRunId(id);
133
+ const state = invoke(() => runState(projectRoot, branch, undefined, id));
134
+ if (id !== null && !state.current) {
135
+ throw new WorkflowError(WORKFLOW_ERROR_CODES.RUN_NOT_FOUND, `找不到运行:${id}`, {
136
+ details: { id, branch },
137
+ });
138
+ }
139
+ return state;
140
+ },
141
+
142
+ get(options) {
143
+ const { branch, id } = requireObject(options, 'runs.get');
144
+ requireBranch(branch);
145
+ requireRunId(id);
146
+ const result = invoke(() => readRun(projectRoot, branch, id));
147
+ return { dir: result.req.dir, run: result.run };
148
+ },
149
+
150
+ save(options) {
151
+ const { branch, id, expectedRevision, input } = requireObject(options, 'runs.save');
152
+ requireBranch(branch);
153
+ requireRunId(id);
154
+ requireRevision(expectedRevision);
155
+ return invoke(() => changeRun(projectRoot, {
156
+ branch,
157
+ id,
158
+ revision: expectedRevision,
159
+ input: requireInput(input),
160
+ action: 'save',
161
+ }));
162
+ },
163
+
164
+ complete(options) {
165
+ const { branch, id, expectedRevision, input } = requireObject(options, 'runs.complete');
166
+ requireBranch(branch);
167
+ requireRunId(id);
168
+ requireRevision(expectedRevision);
169
+ return invoke(() => changeRun(projectRoot, {
170
+ branch,
171
+ id,
172
+ revision: expectedRevision,
173
+ input: requireInput(input),
174
+ action: 'complete',
175
+ }));
176
+ },
177
+
178
+ cancel(options) {
179
+ const { branch, id, expectedRevision, reason } = requireObject(options, 'runs.cancel');
180
+ requireBranch(branch);
181
+ requireRunId(id);
182
+ requireRevision(expectedRevision);
183
+ if (typeof reason !== 'string' || !reason.trim()) invalid('reason 必须是非空字符串');
184
+ return invoke(() => changeRun(projectRoot, {
185
+ branch,
186
+ id,
187
+ revision: expectedRevision,
188
+ input: { reason },
189
+ action: 'cancel',
190
+ }));
191
+ },
192
+ }),
193
+
194
+ snapshots: Object.freeze({
195
+ capture(options) {
196
+ const { branch, id } = requireObject(options, 'snapshots.capture');
197
+ requireBranch(branch);
198
+ requireRunId(id);
199
+ return invoke(() => {
200
+ const { req, run } = readRun(projectRoot, branch, id);
201
+ if (req.meta.pending_finalization) {
202
+ throw new WorkflowError(
203
+ WORKFLOW_ERROR_CODES.PENDING_FINALIZATION,
204
+ '先处理待完成的产物收尾,再获取代码快照',
205
+ { details: { runId: id, operationId: req.meta.pending_finalization.id ?? null } },
206
+ );
207
+ }
208
+ return { ok: true, snapshot: codeSnapshot(projectRoot, run) };
209
+ });
210
+ },
211
+ }),
212
+
213
+ artifacts: Object.freeze({
214
+ finalize(options) {
215
+ const {
216
+ branch,
217
+ id,
218
+ expectedRevision,
219
+ kind,
220
+ text,
221
+ input,
222
+ packet = null,
223
+ result = null,
224
+ } = requireObject(options, 'artifacts.finalize');
225
+ requireBranch(branch);
226
+ requireRunId(id);
227
+ requireRevision(expectedRevision);
228
+ if (typeof kind !== 'string' || !kind.trim()) invalid('kind 必须是非空字符串');
229
+ if (typeof text !== 'string') invalid('text 必须是非空正式正文');
230
+ if (!documentPolicy) invalid('正式产物发布必须提供 documentPolicy');
231
+ if (packet !== null && !isObject(packet)) invalid('packet 必须是对象或 null');
232
+ if (result !== null && !isObject(result)) invalid('result 必须是对象或 null');
233
+ const finalized = invoke(() => finalizeArtifact(projectRoot, {
234
+ branch,
235
+ id,
236
+ revision: expectedRevision,
237
+ kind,
238
+ text,
239
+ input: requireInput(input),
240
+ packet,
241
+ result,
242
+ }, (candidate) => documentPolicy.validate({ kind, text: candidate })));
243
+ return { ...finalized, alreadyFinalized: finalized.already_finalized === true };
244
+ },
245
+ resume(options) {
246
+ const request = pendingRequest(options, 'artifacts.resume');
247
+ return invoke(
248
+ () => resumeFinalization(projectRoot, request),
249
+ WORKFLOW_ERROR_CODES.PENDING_FINALIZATION,
250
+ );
251
+ },
252
+ abort(options) {
253
+ const request = pendingRequest(options, 'artifacts.abort');
254
+ return invoke(
255
+ () => abortFinalization(projectRoot, request),
256
+ WORKFLOW_ERROR_CODES.PENDING_FINALIZATION,
257
+ );
258
+ },
259
+ }),
260
+
261
+ reviews: Object.freeze({
262
+ prepare(options) {
263
+ const {
264
+ branch,
265
+ id,
266
+ kind = null,
267
+ text = null,
268
+ depth = '标准',
269
+ capabilities = null,
270
+ } = requireObject(options, 'reviews.prepare');
271
+ requireBranch(branch);
272
+ requireRunId(id);
273
+ if (kind !== null && !['requirement', 'plan'].includes(kind)) invalid('kind 只能是 requirement / plan 或 null');
274
+ if (kind !== null && typeof text !== 'string') invalid('文档审查需要提供 text');
275
+ if (capabilities !== null && !isObject(capabilities)) invalid('capabilities 必须是对象或 null');
276
+ return invoke(() => {
277
+ const packet = kind === null
278
+ ? createCodeHandoff(projectRoot, { branch, id, depth, capabilities })
279
+ : createDocumentHandoff(projectRoot, { branch, id, kind, text });
280
+ const fileName = kind === null ? 'handoff.json' : `${kind}-${packet.inputs}.json`;
281
+ return { ok: true, path: writeReviewPacket(projectRoot, packet, fileName), packet };
282
+ });
283
+ },
284
+ }),
285
+ });
286
+ }
@@ -0,0 +1,101 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ import { readRun } from '../lib/runs.mjs';
6
+ import { readProfile } from '../lib/project.mjs';
7
+ import { snapshotReader, assertSnapshot, assertWorkingBranch, hash } from '../lib/code-snapshot.mjs';
8
+ import { isDev, assertValidation, reviewInputs, documentReviewBasis } from '../lib/run-gates.mjs';
9
+ import { documentReviewStage, documentReviewInputs, requiresDocumentReview } from '../lib/document-review.mjs';
10
+ import { artifactDraft } from '../lib/artifact-finalize.mjs';
11
+ import { scope } from '../lib/review-scope.mjs';
12
+
13
+ const skillsRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
14
+
15
+ export function createCodeHandoff(root, { branch, id, depth = '标准', capabilities = null }) {
16
+ const { req, run } = readRun(root, branch, id);
17
+ if (!['feature', 'bug', 'review'].includes(run.kind) || ['completed', 'cancelled'].includes(run.status)) {
18
+ throw new Error('只有进行中的开发/审查运行可生成交接材料');
19
+ }
20
+ if (req.meta.pending_finalization) throw new Error('先恢复待完成的产物收尾');
21
+ const getSnapshot = snapshotReader(root, run);
22
+ if (isDev(run)) {
23
+ if (run.stage !== (run.kind === 'feature' ? 'F7' : 'B5')) throw new Error('请先完成验证并进入审查阶段');
24
+ assertValidation(root, req, run, undefined, getSnapshot);
25
+ }
26
+ if (!['快审', '标准', '深审'].includes(depth)) throw new Error('审查深度须为快审 / 标准 / 深审');
27
+ const snapshot = getSnapshot();
28
+ const reviewScope = scope(root, { base: run.scope?.base ?? 'main', exclude: run.scope?.exclude ?? [] });
29
+ if (!reviewScope.ok) throw new Error(reviewScope.error);
30
+ assertSnapshot(root, run, snapshot);
31
+ const profile = readProfile(root).profile;
32
+ const inputs = reviewInputs(run);
33
+ return {
34
+ run_id: id,
35
+ revision: run.revision,
36
+ project_root: path.resolve(root),
37
+ skills: skillsRoot,
38
+ branch,
39
+ depth,
40
+ snapshot,
41
+ inputs: hash(JSON.stringify(inputs)),
42
+ scope: reviewScope,
43
+ requirement: req.name,
44
+ facts: inputs.facts,
45
+ requirement_document: run.artifacts?.requirement ?? null,
46
+ plan: run.artifacts?.plan ?? null,
47
+ previous_report: run.artifacts?.review ?? null,
48
+ validation: run.validation ?? null,
49
+ commands: Object.fromEntries(['main_branch', 'build', 'test', 'test_single', 'lint'].map((key) => [key, profile?.[key] ?? null])),
50
+ capabilities,
51
+ result_schema: {
52
+ run_id: id,
53
+ code: snapshot.digest,
54
+ inputs: hash(JSON.stringify(inputs)),
55
+ findings: [{ id: '唯一编号', severity: 'CRITICAL|HIGH|MEDIUM|LOW', verification: 'confirmed|pending', scope: 'in_scope|outside(范围外发现单列)', file: '真实路径', line: 1, summary: '触发条件与影响' }],
56
+ coverage: { reviewed: ['已审文件'], uncovered: ['未审文件'] },
57
+ },
58
+ rules: '独立读代码,按 project-review 第 1~7 步审查;返回报告草稿和结构化结果,不改代码、不生成 delivery.md、不提交、不另建运行;主 agent 负责 finalize。零发现 findings 为空数组,scope.review 中每个文件必须进入 reviewed 或 uncovered。',
59
+ };
60
+ }
61
+
62
+ export function createDocumentHandoff(root, { branch, id, kind, text }) {
63
+ const { req, run } = readRun(root, branch, id);
64
+ if (!requiresDocumentReview(run, kind) || ['completed', 'cancelled'].includes(run.status)) {
65
+ throw new Error('只有需要文档审查的进行中运行可生成此交接');
66
+ }
67
+ if (run.stage !== documentReviewStage(run, kind)) throw new Error(`请在 ${documentReviewStage(run, kind)} 阶段生成文档审查交接`);
68
+ if (req.meta.pending_finalization) throw new Error('先恢复待完成的产物收尾');
69
+ assertWorkingBranch(root, run);
70
+ const basis = documentReviewBasis(root, req, run, kind);
71
+ const basisText = basis ? fs.readFileSync(path.resolve(root, basis.path), 'utf8') : null;
72
+ if (basis && hash(basisText) !== basis.hash) throw new Error('文档审查依据在交接期间变化,请重新收尾后再试');
73
+ const draft = artifactDraft(req, kind, text);
74
+ const draftHash = hash(draft.text);
75
+ const inputs = documentReviewInputs(run, kind, draftHash, basis);
76
+ return {
77
+ run_id: id,
78
+ revision: run.revision,
79
+ project_root: path.resolve(root),
80
+ branch,
81
+ kind,
82
+ inputs,
83
+ draft: { text: draft.text, hash: draftHash },
84
+ basis: basis ? { path: basis.path, hash: basis.hash, version: basis.version, text: basisText } : null,
85
+ result_schema: {
86
+ run_id: id,
87
+ inputs,
88
+ mode: 'independent',
89
+ reviewer: '实际子 agent 标识',
90
+ summary: '审查结论与已复核修订',
91
+ findings: [{ location: '章节或验收编号', evidence: '依据及来源', impact: '实际影响', blocking: false }],
92
+ },
93
+ };
94
+ }
95
+
96
+ export function writeReviewPacket(root, packet, fileName) {
97
+ const file = path.join(root, 'workflow-run/tmp/review', packet.run_id, fileName);
98
+ fs.mkdirSync(path.dirname(file), { recursive: true });
99
+ fs.writeFileSync(file, `${JSON.stringify(packet, null, 2)}\n`);
100
+ return path.relative(root, file).split(path.sep).join('/');
101
+ }
@@ -0,0 +1,28 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ import { resolveTemplate, skillMeta } from '../scripts/resolve.mjs';
5
+ import { lint } from '../scripts/lint-doc.mjs';
6
+ import { ARTIFACT_TEMPLATES } from '../lib/artifact-finalize.mjs';
7
+
8
+ export function createSkillDocumentPolicy(root) {
9
+ return Object.freeze({
10
+ validate({ kind, text }) {
11
+ const [skill, template] = ARTIFACT_TEMPLATES[kind] ?? [];
12
+ if (!skill || !template) {
13
+ return { ok: false, errors: [`不支持的正式产物类型:${kind}`], warnings: [] };
14
+ }
15
+ const resolved = resolveTemplate(root, skill, template);
16
+ if (!resolved.ok) {
17
+ return {
18
+ ok: false,
19
+ errors: [resolved.hint ?? resolved.message ?? `无法解析模板:${skill}/${template}`],
20
+ warnings: [],
21
+ };
22
+ }
23
+ const source = fs.readFileSync(path.resolve(root, resolved.path), 'utf8');
24
+ const rules = skillMeta(skill).templates.find((item) => item.id === template)?.lint;
25
+ return lint(text, source, rules);
26
+ },
27
+ });
28
+ }
@@ -3,7 +3,7 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import { FILES, parseBranch } from './artifact-model.mjs';
6
- import { hash, assertWorkingBranch, snapshotReader } from './code-snapshot.mjs';
6
+ import { canonicalJson, hash, assertWorkingBranch, snapshotReader } from './code-snapshot.mjs';
7
7
  import { layout } from './project.mjs';
8
8
  import { readRun, assertRunVersion, applyCheckpoint } from './runs.mjs';
9
9
  import { isDev, coreSteps, applyDevEvidence, assertRequirement, assertPlanBasis, assertReview, assertDelivery, reviewEvidence, documentReviewBasis } from './run-gates.mjs';
@@ -21,6 +21,45 @@ const allowed = { feature: ['clarification', 'requirement', 'plan', 'review', 'd
21
21
  const relative = (root, file) => path.relative(root, file).split(path.sep).join('/');
22
22
  const fileHash = (file) => fs.existsSync(file) ? hash(fs.readFileSync(file)) : null;
23
23
  const wikiRecord = (s) => /^<!-- md-to-wiki: [^\n]*-->/.exec(s)?.[0] ?? null;
24
+ const pendingError = (code, message, details) => Object.assign(new Error(message), { code, details });
25
+
26
+ function assertPendingRequest(meta, { id, expectedRevision, operationId }) {
27
+ const p = meta.pending_finalization;
28
+ if (!p || p.run_id !== id) {
29
+ if (operationId !== undefined) {
30
+ throw pendingError(
31
+ 'PENDING_OPERATION_MISMATCH',
32
+ `pending operationId 已消失或被替换:请求 ${operationId},当前无匹配待办`,
33
+ { runId: id, requestedOperationId: operationId, currentOperationId: p?.id ?? null },
34
+ );
35
+ }
36
+ throw new Error('没有该运行待处理的产物收尾');
37
+ }
38
+ if (operationId !== undefined && p.id !== operationId) {
39
+ throw pendingError(
40
+ 'PENDING_OPERATION_MISMATCH',
41
+ `pending operationId 不匹配:请求 ${operationId},当前为 ${p.id}`,
42
+ { runId: id, requestedOperationId: operationId, currentOperationId: p.id },
43
+ );
44
+ }
45
+ const runRevision = p.run?.revision ?? p.revision + 1;
46
+ if (expectedRevision !== undefined && expectedRevision !== runRevision) {
47
+ throw pendingError(
48
+ 'REVISION_CONFLICT',
49
+ `运行版本冲突:pending 当前 revision 为 ${runRevision},请求 ${expectedRevision}`,
50
+ { runId: id, operationId: p.id, expectedRevision, runRevision, baseRevision: p.revision },
51
+ );
52
+ }
53
+ const persisted = meta.runs?.[id];
54
+ if (!persisted || persisted.revision !== p.revision) {
55
+ throw pendingError(
56
+ 'REVISION_CONFLICT',
57
+ 'pending 基准 revision 与已保存运行不一致,停止恢复或中止',
58
+ { runId: id, operationId: p.id, runRevision, baseRevision: p.revision, storedRevision: persisted?.revision ?? null },
59
+ );
60
+ }
61
+ return p;
62
+ }
24
63
 
25
64
  export function artifactDraft(req, kind, text) {
26
65
  const file = path.join(req.abs, `${FILES[kind]}.md`);
@@ -30,12 +69,11 @@ export function artifactDraft(req, kind, text) {
30
69
  return { text: existingWiki && !draftWiki ? `${existingWiki}\n${text}` : text, existingWiki };
31
70
  }
32
71
 
33
- export function resumeFinalization(root, { branch, id }) {
72
+ export function resumeFinalization(root, { branch, id, expectedRevision, operationId }) {
34
73
  const { req } = readRun(root, branch, id);
35
74
  let result;
36
75
  updateMeta(path.join(req.abs, 'meta.json'), (meta) => {
37
- const p = meta.pending_finalization;
38
- if (!p || p.run_id !== id) throw new Error('没有该运行待恢复的产物收尾');
76
+ const p = assertPendingRequest(meta, { id, expectedRevision, operationId });
39
77
  const run = meta.runs[id];
40
78
  assertRunVersion(run, branch, p.revision);
41
79
  if (isDev(run)) assertWorkingBranch(root, run);
@@ -69,17 +107,17 @@ export function resumeFinalization(root, { branch, id }) {
69
107
  const artifacts = indexArtifacts(req.abs, versions);
70
108
  const latest = Object.fromEntries(Object.keys(FILES).map((k) => [k, artifacts.filter((a) => a.kind === k).at(-1)?.file ?? null]));
71
109
  const { pending_finalization, ...rest } = meta;
72
- 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 };
110
+ result = { ok: true, operationId: p.id, baseRevision: p.revision, 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 };
73
111
  return { ...rest, versions, artifacts, latest, runs: { ...meta.runs, [id]: p.run }, updated: p.run.updated_at };
74
112
  }, { root, allowFinalization: true });
75
113
  return result;
76
114
  }
77
115
 
78
- export function abortFinalization(root, { branch, id }) {
116
+ export function abortFinalization(root, { branch, id, expectedRevision, operationId }) {
79
117
  const { req } = readRun(root, branch, id);
118
+ let abortedOperationId;
80
119
  updateMeta(path.join(req.abs, 'meta.json'), (meta) => {
81
- const p = meta.pending_finalization;
82
- if (!p || p.run_id !== id) throw new Error('没有该运行待取消的产物收尾');
120
+ const p = assertPendingRequest(meta, { id, expectedRevision, operationId });
83
121
  assertRunVersion(meta.runs[id], branch, p.revision);
84
122
  const file = path.join(req.abs, `${FILES[p.kind]}.md`);
85
123
  const current = fileHash(file);
@@ -94,9 +132,10 @@ export function abortFinalization(root, { branch, id }) {
94
132
  }
95
133
  }
96
134
  const { pending_finalization, ...rest } = meta;
135
+ abortedOperationId = p.id;
97
136
  return rest;
98
137
  }, { root, allowFinalization: true });
99
- return { ok: true, aborted: true, run_id: id };
138
+ return { ok: true, aborted: true, run_id: id, operationId: abortedOperationId };
100
139
  }
101
140
 
102
141
  export function finalizeArtifact(root, { branch, id, revision, kind, text, input = {}, packet = null, result = null }, check) {
@@ -107,7 +146,7 @@ export function finalizeArtifact(root, { branch, id, revision, kind, text, input
107
146
  const { existingWiki } = draft;
108
147
  text = draft.text;
109
148
  const digest = hash(text);
110
- const key = hash(JSON.stringify({ id, revision, kind, digest, input, packet, result }));
149
+ const key = hash(canonicalJson({ id, revision, kind, digest, input, packet, result }));
111
150
  let repeated = null;
112
151
  updateMeta(path.join(req.abs, 'meta.json'), (meta) => {
113
152
  const current = meta.runs[id];
@@ -6,6 +6,11 @@ import { createHash } from 'node:crypto';
6
6
  import { matchGlob } from './path-match.mjs';
7
7
 
8
8
  export const hash = (value) => createHash('sha256').update(value).digest('hex');
9
+ // 幂等请求标识只依赖语义,不依赖调用方构造对象时的键顺序。
10
+ export const canonicalJson = (value) => JSON.stringify(value, (_key, nested) => {
11
+ if (!nested || typeof nested !== 'object' || Array.isArray(nested)) return nested;
12
+ return Object.fromEntries(Object.keys(nested).sort().map((key) => [key, nested[key]]));
13
+ });
9
14
  const INTERNAL = ['workflow-run/**', '.docnexus/**', '.codegraph/**', '.agents/skills/**', '.claude/skills/**', '.qwen/skills/**', '.codebuddy/skills/**'];
10
15
  const git = (root, args, encoding = 'utf8') => {
11
16
  const r = spawnSync('git', args, { cwd: root, encoding, maxBuffer: 256 * 1024 * 1024 });
@@ -99,7 +99,18 @@ export function updateMeta(file, update, { root = process.cwd(), allowFinalizati
99
99
  const tmp = path.join(path.dirname(lock), `${path.basename(file)}.${randomUUID()}.tmp`);
100
100
  try {
101
101
  const current = readMeta(file);
102
- if (current.pending_finalization && !allowFinalization) throw new Error(`产物收尾尚未完成,先运行 artifact.mjs resume --id ${current.pending_finalization.run_id}`);
102
+ if (current.pending_finalization && !allowFinalization) {
103
+ throw Object.assign(
104
+ new Error(`产物收尾尚未完成,先运行 artifact.mjs resume --id ${current.pending_finalization.run_id}`),
105
+ {
106
+ code: 'PENDING_FINALIZATION',
107
+ details: {
108
+ runId: current.pending_finalization.run_id ?? null,
109
+ operationId: current.pending_finalization.id ?? null,
110
+ },
111
+ },
112
+ );
113
+ }
103
114
  const next = update(current);
104
115
  const text = `${JSON.stringify(next, null, 2)}\n`;
105
116
  if (!fs.existsSync(file) || fs.readFileSync(file, 'utf8') !== text) {