@kangyishuai/dsh-casefile 0.0.0-stage → 0.1.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.
@@ -0,0 +1,316 @@
1
+ // @ts-check
2
+ // core/report.js:覆盖率、关闭闸门与报告渲染。纯 Node,可单测。
3
+ //
4
+ // 口径(spec/03-acceptance.md §1.3、§5.3):
5
+ // - 覆盖率 = 已关闭义务 /(已关闭 + 未关闭 + 失败 + 阻塞);
6
+ // - 关闭项目的硬门:没有 open / fail 义务、没有未解决未知项、覆盖率达标、检查不过期;
7
+ // - 报告必须写清「这一版对应哪个实现 digest、什么时候采的证据」。
8
+
9
+ import { attestationSummary } from "./attestation.js";
10
+ import { shortDigest } from "./digest.js";
11
+ import { nowIso } from "./model.js";
12
+
13
+ const COUNTED = new Set(["open", "pass", "fail", "blocked"]);
14
+
15
+ /**
16
+ * 算覆盖率。
17
+ * @param {Array<Record<string, any>>} obligations
18
+ * @returns {{ total: number, pass: number, open: number, fail: number, blocked: number, outOfScope: number, ratio: number }}
19
+ */
20
+ export function computeCoverage(obligations) {
21
+ const counted = obligations.filter((/** @type {any} */ item) => COUNTED.has(String(item.status)));
22
+ const pass = counted.filter((/** @type {any} */ item) => item.status === "pass").length;
23
+ const open = counted.filter((/** @type {any} */ item) => item.status === "open").length;
24
+ const fail = counted.filter((/** @type {any} */ item) => item.status === "fail").length;
25
+ const blocked = counted.filter((/** @type {any} */ item) => item.status === "blocked").length;
26
+ const outOfScope = obligations.filter(
27
+ (/** @type {any} */ item) => item.status === "out_of_scope",
28
+ ).length;
29
+ const total = counted.length;
30
+ return {
31
+ total,
32
+ pass,
33
+ open,
34
+ fail,
35
+ blocked,
36
+ outOfScope,
37
+ ratio: total === 0 ? 0 : pass / total,
38
+ };
39
+ }
40
+
41
+ /**
42
+ * 按功能算覆盖率:只统计「显式挂在某功能上的义务」,未挂功能的义务只计入全局。
43
+ * @param {Array<Record<string, any>>} obligations
44
+ * @param {Array<Record<string, any>>} features
45
+ * @returns {Array<{ featureId: string, name: string, total: number, pass: number, open: number, ratio: number }>}
46
+ */
47
+ export function computeCoverageByFeature(obligations, features) {
48
+ return (features ?? []).map((/** @type {any} */ feature) => {
49
+ const mine = (obligations ?? []).filter((/** @type {any} */ item) =>
50
+ (item.featureIds ?? []).includes(feature.id),
51
+ );
52
+ const coverage = computeCoverage(mine);
53
+ return {
54
+ featureId: feature.id,
55
+ name: feature.name,
56
+ total: coverage.total,
57
+ pass: coverage.pass,
58
+ open: coverage.open,
59
+ ratio: coverage.ratio,
60
+ };
61
+ });
62
+ }
63
+
64
+ /**
65
+ * 关闭闸门:返回能不能关闭,以及卡在哪。
66
+ * @param {{
67
+ * obligations: Array<Record<string, any>>,
68
+ * unknowns: Array<Record<string, any>>,
69
+ * checks: Array<Record<string, any>>,
70
+ * implementationDigest?: string | null,
71
+ * minCoverage?: number,
72
+ * maxCheckAgeMs?: number,
73
+ * now?: number,
74
+ * }} input
75
+ * @returns {{ ok: boolean, blockers: string[], coverage: ReturnType<typeof computeCoverage> }}
76
+ */
77
+ export function evaluateClose(input) {
78
+ const now = input.now ?? Date.now();
79
+ const maxAge = input.maxCheckAgeMs ?? 24 * 3600 * 1000;
80
+ const minCoverage = input.minCoverage ?? 1;
81
+ const coverage = computeCoverage(input.obligations ?? []);
82
+ /** @type {string[]} */
83
+ const blockers = [];
84
+ if (coverage.total === 0) blockers.push("no-obligations");
85
+ if (coverage.open > 0) blockers.push(`open-obligations:${coverage.open}`);
86
+ if (coverage.fail > 0) blockers.push(`failed-obligations:${coverage.fail}`);
87
+ if (coverage.blocked > 0) blockers.push(`blocked-obligations:${coverage.blocked}`);
88
+ if (coverage.ratio < minCoverage) {
89
+ blockers.push(`coverage-below:${coverage.ratio.toFixed(2)}<${minCoverage.toFixed(2)}`);
90
+ }
91
+ const openUnknowns = (input.unknowns ?? []).filter(
92
+ (/** @type {any} */ item) => item.status !== "resolved",
93
+ );
94
+ if (openUnknowns.length > 0) blockers.push(`open-unknowns:${openUnknowns.length}`);
95
+ // 检查新鲜度:最近一次完成检查不能超过时效
96
+ const completed = (input.checks ?? []).filter(
97
+ (/** @type {any} */ item) => item.verdict !== "unknown",
98
+ );
99
+ const latest = [...completed]
100
+ .sort((a, b) => String(a.at ?? "").localeCompare(String(b.at ?? "")))
101
+ .at(-1);
102
+ if (!latest) {
103
+ blockers.push("no-checks");
104
+ } else {
105
+ const age = now - Date.parse(latest.evidenceFetchedAt ?? latest.at ?? 0);
106
+ if (!Number.isFinite(age) || age > maxAge) blockers.push("stale-checks");
107
+ if (
108
+ input.implementationDigest != null &&
109
+ latest.implementationDigest != null &&
110
+ latest.implementationDigest !== input.implementationDigest
111
+ ) {
112
+ blockers.push("implementation-mismatch");
113
+ }
114
+ }
115
+ return { ok: blockers.length === 0, blockers, coverage };
116
+ }
117
+
118
+ /**
119
+ * 组装报告对象。
120
+ * @param {{
121
+ * project: Record<string, any>,
122
+ * data: Record<string, any>,
123
+ * coverage?: ReturnType<typeof computeCoverage>,
124
+ * stop?: Record<string, any> | null,
125
+ * generatedAt?: string,
126
+ * }} input
127
+ * @returns {Record<string, any>}
128
+ */
129
+ export function buildReport(input) {
130
+ const data = input.data ?? {};
131
+ const builds = data.builds ?? [];
132
+ const checks = data.checks ?? [];
133
+ const obligations = data.obligations ?? [];
134
+ const coverage = input.coverage ?? computeCoverage(obligations);
135
+ const latestBuild = [...builds].sort(
136
+ (a, b) => (Number(b.round) || 0) - (Number(a.round) || 0),
137
+ )[0];
138
+ return {
139
+ version: 1,
140
+ generatedAt: input.generatedAt ?? nowIso(),
141
+ project: {
142
+ id: input.project.id,
143
+ title: input.project.title,
144
+ state: input.project.state,
145
+ target: input.project.target,
146
+ authTier: input.project.authTier,
147
+ scope: input.project.scope,
148
+ reaVersion: input.project.reaVersion,
149
+ },
150
+ coverage,
151
+ coverageByFeature: computeCoverageByFeature(obligations, data.features ?? []),
152
+ cleanRoom: attestationSummary(data.attestations ?? []),
153
+ counts: {
154
+ evidence: (data.evidence ?? []).length,
155
+ claims: (data.claims ?? []).length,
156
+ selectedClaims: (data.claims ?? []).filter(
157
+ (/** @type {any} */ item) => item.selected === true,
158
+ ).length,
159
+ features: (data.features ?? []).length,
160
+ unknowns: (data.unknowns ?? []).length,
161
+ openUnknowns: (data.unknowns ?? []).filter(
162
+ (/** @type {any} */ item) => item.status !== "resolved",
163
+ ).length,
164
+ obligations: obligations.length,
165
+ checks: checks.length,
166
+ builds: builds.length,
167
+ },
168
+ latestBuild: latestBuild
169
+ ? {
170
+ round: Number(latestBuild.round) || 0,
171
+ status: latestBuild.status,
172
+ command: latestBuild.command,
173
+ implementationDigest: shortDigest(latestBuild.implementationDigest),
174
+ endedAt: latestBuild.endedAt ?? null,
175
+ }
176
+ : null,
177
+ obligations: obligations.map((/** @type {any} */ item) => ({
178
+ id: item.id,
179
+ statement: item.statement,
180
+ kind: item.kind,
181
+ status: item.status,
182
+ provenance: item.source,
183
+ checks: (item.checkIds ?? []).length,
184
+ })),
185
+ checks: checks.map((/** @type {any} */ item) => ({
186
+ id: item.id,
187
+ obligationId: item.obligationId,
188
+ checker: item.checker,
189
+ verdict: item.verdict,
190
+ implementationDigest: shortDigest(item.implementationDigest),
191
+ at: item.evidenceFetchedAt ?? item.at,
192
+ })),
193
+ unknowns: (data.unknowns ?? []).map((/** @type {any} */ item) => ({
194
+ id: item.id,
195
+ text: item.text,
196
+ severity: item.severity,
197
+ status: item.status,
198
+ })),
199
+ stop: input.stop ?? null,
200
+ };
201
+ }
202
+
203
+ /**
204
+ * 渲染成 Markdown。
205
+ * @param {Record<string, any>} report
206
+ * @returns {string}
207
+ */
208
+ export function renderReportMarkdown(report) {
209
+ const lines = [];
210
+ const percent = (report.coverage.ratio * 100).toFixed(0);
211
+ lines.push(`# 验收报告:${report.project.title}`);
212
+ lines.push("");
213
+ lines.push(`- 项目:\`${report.project.id}\``);
214
+ lines.push(`- 状态:${report.project.state}`);
215
+ lines.push(
216
+ `- 目标:${report.project.target?.kind ?? "?"} · ${report.project.target?.ref ?? "?"}`,
217
+ );
218
+ lines.push(`- 授权档:${report.project.authTier}`);
219
+ lines.push(`- 覆盖率:**${percent}%**(${report.coverage.pass}/${report.coverage.total})`);
220
+ lines.push(`- 生成时间:${report.generatedAt}`);
221
+ if (report.latestBuild) {
222
+ lines.push(
223
+ `- 最近构建:第 ${report.latestBuild.round} 轮 · ${report.latestBuild.status} · 实现 \`${report.latestBuild.implementationDigest}\``,
224
+ );
225
+ }
226
+ lines.push("");
227
+ lines.push("## 计数");
228
+ lines.push("");
229
+ lines.push("| 项 | 数量 |");
230
+ lines.push("| --- | --- |");
231
+ for (const [key, value] of Object.entries(report.counts ?? {})) {
232
+ lines.push(`| ${key} | ${value} |`);
233
+ }
234
+ lines.push("");
235
+ if ((report.coverageByFeature ?? []).length > 0) {
236
+ lines.push("## 按功能覆盖率");
237
+ lines.push("");
238
+ lines.push("| 功能 | 覆盖率 | 已关闭/总数 |");
239
+ lines.push("| --- | --- | --- |");
240
+ for (const item of report.coverageByFeature) {
241
+ lines.push(
242
+ `| ${item.name} | ${(item.ratio * 100).toFixed(0)}% | ${item.pass}/${item.total} |`,
243
+ );
244
+ }
245
+ lines.push("");
246
+ }
247
+ lines.push("## 义务");
248
+ lines.push("");
249
+ if ((report.obligations ?? []).length === 0) {
250
+ lines.push("_没有义务。_");
251
+ } else {
252
+ lines.push("| 状态 | 义务 | 种类 | 检查数 |");
253
+ lines.push("| --- | --- | --- | --- |");
254
+ for (const item of report.obligations) {
255
+ lines.push(`| ${item.status} | ${item.statement} | ${item.kind} | ${item.checks} |`);
256
+ }
257
+ }
258
+ lines.push("");
259
+ lines.push("## 检查");
260
+ lines.push("");
261
+ if ((report.checks ?? []).length === 0) {
262
+ lines.push("_没有检查记录。_");
263
+ } else {
264
+ lines.push("| 结论 | checker | 实现 | 时间 |");
265
+ lines.push("| --- | --- | --- | --- |");
266
+ for (const item of report.checks) {
267
+ lines.push(
268
+ `| ${item.verdict} | ${item.checker} | \`${item.implementationDigest}\` | ${item.at} |`,
269
+ );
270
+ }
271
+ }
272
+ lines.push("");
273
+ lines.push("## 未知项");
274
+ lines.push("");
275
+ if ((report.unknowns ?? []).length === 0) {
276
+ lines.push("_没有未知项。_");
277
+ } else {
278
+ for (const item of report.unknowns) {
279
+ lines.push(`- [${item.severity}] ${item.text}(${item.status})`);
280
+ }
281
+ }
282
+ if (report.stop) {
283
+ lines.push("");
284
+ lines.push("## 循环状态");
285
+ lines.push("");
286
+ lines.push(`- 停止条件:${report.stop.reason ?? "unknown"}`);
287
+ const detail = report.stop.detail ?? {};
288
+ lines.push(`- 轮次:${detail.rounds ?? "—"} / 失败:${detail.failures ?? "—"}`);
289
+ }
290
+ if (report.cleanRoom) {
291
+ lines.push("");
292
+ lines.push("## 净室 attestation");
293
+ lines.push("");
294
+ const cr = report.cleanRoom;
295
+ lines.push(`- 时间:${cr.at}`);
296
+ lines.push(`- builder 会话:\`${cr.builderSession}\``);
297
+ lines.push(
298
+ `- 授权档:${cr.authTier}${cr.researchOverride ? "(research 档,已显式覆盖)" : ""}`,
299
+ );
300
+ lines.push(`- 投喂规格:${cr.claimCount} 条结论 / ${cr.evidenceCount} 条证据`);
301
+ lines.push(
302
+ `- 净室指令写入 prompt:${cr.cleanRoomInstruction ? "是" : "**否**(本次投喂未包含该要求)"}`,
303
+ );
304
+ lines.push(`- prompt 摘要:\`${cr.promptDigest}\``);
305
+ lines.push(`- 工具面隔离:${cr.toolIsolation}`);
306
+ lines.push("");
307
+ lines.push(`> ${cr.statement}`);
308
+ }
309
+ lines.push("");
310
+ lines.push("## 声明");
311
+ lines.push("");
312
+ lines.push("- 本报告对应上面「最近构建」的实现 digest;实现或原件变化后,旧结论不再有效。");
313
+ lines.push("- 检查结论来自 casefile 的 checker,`unknown` 表示无法判定,不等于通过。");
314
+ lines.push("");
315
+ return lines.join("\n");
316
+ }
@@ -0,0 +1,211 @@
1
+ // @ts-check
2
+ // core/runs.js:构建/验收运行记录与循环停止条件。纯 Node,可单测。
3
+ //
4
+ // 口径(spec/03-acceptance.md §4–§5):
5
+ // - 每次构建产出一个 BuildRun,带 implementationDigest;
6
+ // - 每次检查产出一个 CheckResult,绑定「实现 digest + 原件 digest + 采集时刻」;
7
+ // - 实现变了 → 依赖它的已关闭义务自动回到 open(stale),不静默保留绿灯。
8
+
9
+ import { shortDigest } from "./digest.js";
10
+ import { newId, nowIso } from "./model.js";
11
+
12
+ /** 构建状态。 */
13
+ export const BUILD_STATUSES = /** @type {const} */ ([
14
+ "running",
15
+ "pass",
16
+ "fail",
17
+ "error",
18
+ "stopped",
19
+ ]);
20
+
21
+ /** 默认停止条件。 */
22
+ export const DEFAULT_STOP = {
23
+ maxRounds: 5,
24
+ maxFailures: 3,
25
+ noProgressRounds: 2,
26
+ };
27
+
28
+ /**
29
+ * 规范化一次构建。
30
+ * @param {Record<string, any>} input
31
+ * @returns {Record<string, any>}
32
+ */
33
+ export function normalizeBuildRun(input) {
34
+ const command = String(input?.command ?? "").trim();
35
+ if (command === "") {
36
+ throw Object.assign(new Error("command 不能为空"), { code: "invalid-input" });
37
+ }
38
+ const status = String(input?.status ?? "running");
39
+ if (!BUILD_STATUSES.includes(/** @type {any} */ (status))) {
40
+ throw Object.assign(new Error(`status 必须是 ${BUILD_STATUSES.join(" | ")}`), {
41
+ code: "invalid-input",
42
+ });
43
+ }
44
+ return {
45
+ id: newId("build"),
46
+ round: Number.isInteger(input?.round) && input.round > 0 ? input.round : 1,
47
+ command,
48
+ cwd: input?.cwd == null ? null : String(input.cwd),
49
+ status,
50
+ exitCode: Number.isInteger(input?.exitCode) ? input.exitCode : null,
51
+ implementationDigest:
52
+ input?.implementationDigest == null ? null : String(input.implementationDigest),
53
+ startedAt: input?.startedAt == null ? nowIso() : String(input.startedAt),
54
+ endedAt: input?.endedAt == null ? null : String(input.endedAt),
55
+ detail: input?.detail == null ? "" : String(input.detail).slice(0, 4000),
56
+ artifacts: Array.isArray(input?.artifacts) ? input.artifacts.map(String) : [],
57
+ };
58
+ }
59
+
60
+ /**
61
+ * 下一轮轮次。
62
+ * @param {Array<Record<string, any>>} builds
63
+ * @returns {number}
64
+ */
65
+ export function nextRound(builds) {
66
+ const max = builds.reduce((acc, item) => Math.max(acc, Number(item.round) || 0), 0);
67
+ return max + 1;
68
+ }
69
+
70
+ /**
71
+ * 最近一次构建(按 round 取最大)。
72
+ * @param {Array<Record<string, any>>} builds
73
+ * @returns {Record<string, any> | undefined}
74
+ */
75
+ export function latestBuild(builds) {
76
+ return [...builds].sort((a, b) => (Number(b.round) || 0) - (Number(a.round) || 0))[0];
77
+ }
78
+
79
+ /**
80
+ * 循环停止条件(spec/03-acceptance.md §5.2)。
81
+ * @param {{
82
+ * builds: Array<Record<string, any>>,
83
+ * checks: Array<Record<string, any>>,
84
+ * openObligations: number,
85
+ * stop?: Partial<typeof DEFAULT_STOP>,
86
+ * }} input
87
+ * @returns {{ stop: boolean, reason: string, detail: Record<string, any> }}
88
+ */
89
+ export function evaluateStop(input) {
90
+ const stop = { ...DEFAULT_STOP, ...(input.stop ?? {}) };
91
+ const builds = input.builds ?? [];
92
+ const checks = input.checks ?? [];
93
+ const rounds = builds.length;
94
+ const failures = builds.filter(
95
+ (item) => item.status === "fail" || item.status === "error",
96
+ ).length;
97
+ const detail = {
98
+ rounds,
99
+ failures,
100
+ openObligations: input.openObligations ?? 0,
101
+ maxRounds: stop.maxRounds,
102
+ maxFailures: stop.maxFailures,
103
+ };
104
+ if (rounds >= stop.maxRounds) {
105
+ return { stop: true, reason: "max-rounds", detail };
106
+ }
107
+ if (failures >= stop.maxFailures) {
108
+ return { stop: true, reason: "max-failures", detail };
109
+ }
110
+ // 连续无进展:最近 N 轮构建都没有产出新的实现 digest
111
+ const recent = [...builds].sort((a, b) => (Number(b.round) || 0) - (Number(a.round) || 0));
112
+ const digests = recent
113
+ .slice(0, stop.noProgressRounds + 1)
114
+ .map((item) => item.implementationDigest)
115
+ .filter((value) => typeof value === "string" && value !== "");
116
+ const noProgress = digests.length >= stop.noProgressRounds + 1 && new Set(digests).size === 1;
117
+ if (noProgress) {
118
+ return {
119
+ stop: true,
120
+ reason: "no-progress",
121
+ detail: { ...detail, digest: shortDigest(digests[0]) },
122
+ };
123
+ }
124
+ if (checks.some((item) => item.verdict === "unknown")) {
125
+ const unknown = checks.filter((item) => item.verdict === "unknown").length;
126
+ return { stop: true, reason: "checker-unknown", detail: { ...detail, unknown } };
127
+ }
128
+ return { stop: false, reason: "continue", detail };
129
+ }
130
+
131
+ /**
132
+ * 判断已关闭的义务是否因实现/原件变化而失效(stale)。
133
+ * @param {{
134
+ * obligations: Array<Record<string, any>>,
135
+ * checks: Array<Record<string, any>>,
136
+ * implementationDigest: string | null,
137
+ * originalDigest: string | null,
138
+ * maxAgeMs?: number,
139
+ * now?: number,
140
+ * }} input
141
+ * @returns {Array<{ obligationId: string, reasons: string[] }>}
142
+ */
143
+ export function findStaleObligations(input) {
144
+ const maxAgeMs = input.maxAgeMs ?? 24 * 3600 * 1000;
145
+ const now = input.now ?? Date.now();
146
+ const byId = new Map((input.checks ?? []).map((/** @type {any} */ item) => [item.id, item]));
147
+ /** @type {Array<{ obligationId: string, reasons: string[] }>} */
148
+ const stale = [];
149
+ for (const obligation of input.obligations ?? []) {
150
+ if (obligation.status !== "pass") continue;
151
+ /** @type {string[]} */
152
+ const reasons = [];
153
+ const closing = (obligation.checkIds ?? [])
154
+ .map((/** @type {any} */ id) => byId.get(id))
155
+ .filter((/** @type {any} */ item) => item !== undefined)
156
+ .at(-1);
157
+ if (!closing) {
158
+ reasons.push("missing-check");
159
+ } else {
160
+ if (
161
+ input.implementationDigest != null &&
162
+ closing.implementationDigest !== input.implementationDigest
163
+ ) {
164
+ reasons.push("implementation-changed");
165
+ }
166
+ if (input.originalDigest != null && closing.originalDigest !== input.originalDigest) {
167
+ reasons.push("original-changed");
168
+ }
169
+ const age = now - Date.parse(closing.evidenceFetchedAt ?? 0);
170
+ if (!Number.isFinite(age) || age > maxAgeMs) reasons.push("check-stale");
171
+ }
172
+ if (reasons.length > 0) stale.push({ obligationId: obligation.id, reasons });
173
+ }
174
+ return stale;
175
+ }
176
+
177
+ /**
178
+ * 运行摘要(工作台/工具输出用)。
179
+ * @param {{ builds: Array<Record<string, any>>, checks: Array<Record<string, any>>, obligations: Array<Record<string, any>> }} input
180
+ * @returns {Record<string, any>}
181
+ */
182
+ export function summarizeRuns(input) {
183
+ const builds = input.builds ?? [];
184
+ const checks = input.checks ?? [];
185
+ const obligations = input.obligations ?? [];
186
+ const last = latestBuild(builds);
187
+ return {
188
+ builds: builds.length,
189
+ lastBuild: last
190
+ ? {
191
+ id: last.id,
192
+ round: last.round,
193
+ status: last.status,
194
+ exitCode: last.exitCode,
195
+ implementationDigest: shortDigest(last.implementationDigest),
196
+ endedAt: last.endedAt,
197
+ }
198
+ : null,
199
+ checks: checks.length,
200
+ verdicts: {
201
+ pass: checks.filter((item) => item.verdict === "pass").length,
202
+ fail: checks.filter((item) => item.verdict === "fail").length,
203
+ unknown: checks.filter((item) => item.verdict === "unknown").length,
204
+ },
205
+ obligations: {
206
+ total: obligations.length,
207
+ open: obligations.filter((item) => item.status === "open").length,
208
+ pass: obligations.filter((item) => item.status === "pass").length,
209
+ },
210
+ };
211
+ }