@kangyishuai/dsh-casefile 0.5.1 → 0.7.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,136 @@
1
+ // @ts-check
2
+ // core/bundle.js:机器可读的「证据包」——给另一个 agent 读,也给自己复盘。
3
+ //
4
+ // 与 spec pack 的区别:
5
+ // - spec pack(brief.js)只含**被选中的结论**,面向"交给编码 agent 去复刻";
6
+ // - bundle 含**全量账本**(证据/结论/义务/检查/未知项/产物),面向"把这段调查
7
+ // 完整交接出去,或过几个月自己回看"。
8
+ //
9
+ // 硬要求:**确定性**。同一份数据导出两次必须字节一致,否则"可复算"就是空话。
10
+ // 所以 generatedAt 不由 Date.now() 决定,而是取数据自身的最大时间戳。
11
+
12
+ import { createHash } from "node:crypto";
13
+
14
+ import { redactPack } from "./brief.js";
15
+
16
+ export const BUNDLE_SCHEMA = "casefile.bundle/1";
17
+
18
+ /**
19
+ * 递归排序对象键,得到可复现的 JSON 形状。
20
+ * @param {any} value
21
+ * @returns {any}
22
+ */
23
+ export function canonicalize(value) {
24
+ if (Array.isArray(value)) return value.map(canonicalize);
25
+ if (value && typeof value === "object") {
26
+ /** @type {Record<string, any>} */
27
+ const out = {};
28
+ for (const key of Object.keys(value).sort()) out[key] = canonicalize(value[key]);
29
+ return out;
30
+ }
31
+ return value;
32
+ }
33
+
34
+ /**
35
+ * 对任意值算完整性摘要(先规范化,再 sha256)。
36
+ * @param {any} value
37
+ * @returns {string}
38
+ */
39
+ export function digestOf(value) {
40
+ return createHash("sha256")
41
+ .update(JSON.stringify(canonicalize(value)))
42
+ .digest("hex");
43
+ }
44
+
45
+ /**
46
+ * 从记录里找最大的时间戳,作为确定性 generatedAt。
47
+ * 找不到就退回项目 updatedAt;两者都没有才用传入的 fallback。
48
+ * @param {Record<string, any>[]} records
49
+ * @returns {string | null}
50
+ */
51
+ function latestTimestamp(records) {
52
+ /** @type {string | null} */
53
+ let latest = null;
54
+ for (const record of records) {
55
+ for (const key of ["observedAt", "createdAt", "updatedAt", "endedAt", "generatedAt"]) {
56
+ const value = record?.[key];
57
+ if (typeof value !== "string") continue;
58
+ if (latest == null || value > latest) latest = value;
59
+ }
60
+ }
61
+ return latest;
62
+ }
63
+
64
+ /**
65
+ * 组装 bundle。
66
+ * @param {{
67
+ * project: Record<string, any>,
68
+ * evidence: Record<string, any>[],
69
+ * claims: Record<string, any>[],
70
+ * obligations: Record<string, any>[],
71
+ * checks: Record<string, any>[],
72
+ * unknowns: Record<string, any>[],
73
+ * coverage?: Record<string, any>,
74
+ * counts?: Record<string, any>,
75
+ * redact?: boolean,
76
+ * }} input
77
+ * @returns {Record<string, any>}
78
+ */
79
+ export function buildBundle(input) {
80
+ const all = [
81
+ ...input.evidence,
82
+ ...input.claims,
83
+ ...input.obligations,
84
+ ...input.checks,
85
+ ...input.unknowns,
86
+ ];
87
+ const generatedAt =
88
+ latestTimestamp(all) ?? input.project?.updatedAt ?? "1970-01-01T00:00:00.000Z";
89
+
90
+ const artifacts = input.evidence
91
+ .map((item) => item.artifact)
92
+ .filter((item) => item && typeof item === "object")
93
+ .map((item) => ({
94
+ sha256: item.sha256,
95
+ file: item.file,
96
+ bytes: item.bytes,
97
+ originalName: item.originalName ?? null,
98
+ }))
99
+ .sort((a, b) => String(a.sha256).localeCompare(String(b.sha256)));
100
+
101
+ /** @type {Record<string, any>} */
102
+ const body = {
103
+ schema: BUNDLE_SCHEMA,
104
+ generatedAt,
105
+ project: {
106
+ id: input.project.id,
107
+ title: input.project.title,
108
+ target: input.project.target ?? null,
109
+ authTier: input.project.authTier,
110
+ scope: input.project.scope,
111
+ state: input.project.state,
112
+ reaVersion: input.project.reaVersion ?? null,
113
+ capabilityHash: input.project.capabilityHash ?? null,
114
+ closedAt: input.project.closedAt ?? null,
115
+ },
116
+ counts: input.counts ?? null,
117
+ coverage: input.coverage ?? null,
118
+ claims: input.claims,
119
+ evidence: input.evidence,
120
+ obligations: input.obligations,
121
+ checks: input.checks,
122
+ unknowns: input.unknowns,
123
+ artifacts,
124
+ };
125
+
126
+ const redacted = input.redact === false ? body : redactPack(body);
127
+ // integrity 覆盖「除 integrity 自身以外」的全部内容,便于接收方校验。
128
+ return {
129
+ ...redacted,
130
+ integrity: {
131
+ algorithm: "sha256",
132
+ canonical: "json-sorted-keys-v1",
133
+ digest: digestOf(redacted),
134
+ },
135
+ };
136
+ }
@@ -11,7 +11,7 @@ import { createHash } from "node:crypto";
11
11
  import { existsSync, readFileSync, statSync } from "node:fs";
12
12
  import { promisify } from "node:util";
13
13
 
14
- import { comparePng } from "./png.js";
14
+ import { assessPngInformation, comparePng, decodePng } from "./png.js";
15
15
 
16
16
  /**
17
17
  * @typedef {{ name: string, version: string, run: (input: any) => Promise<any> }} Checker
@@ -63,10 +63,28 @@ export function createBuildChecker(options = {}) {
63
63
  */
64
64
  async run(input) {
65
65
  const startedAt = new Date().toISOString();
66
- const result = await runner(String(input.command), {
67
- cwd: input.cwd,
68
- timeoutMs: input.timeoutMs,
69
- });
66
+ /** @type {any} */
67
+ let result;
68
+ try {
69
+ result = await runner(String(input.command), {
70
+ cwd: input.cwd,
71
+ timeoutMs: input.timeoutMs,
72
+ });
73
+ } catch (error) {
74
+ // 命令根本没跑起来(不存在 / 不可执行)→ unknown,不能判成"构建失败"。
75
+ return {
76
+ verdict: "unknown",
77
+ detail: {
78
+ reason: "runner-error",
79
+ message: String(/** @type {any} */ (error)?.message ?? error),
80
+ },
81
+ startedAt,
82
+ endedAt: new Date().toISOString(),
83
+ exitCode: null,
84
+ stdout: "",
85
+ stderr: "",
86
+ };
87
+ }
70
88
  const endedAt = new Date().toISOString();
71
89
  if (result.killed === true || result.exitCode === null) {
72
90
  return {
@@ -378,6 +396,39 @@ export function createWebChecker(options = {}) {
378
396
  stderr: "",
379
397
  };
380
398
  }
399
+ // 先判"图有没有信息量":空白/纯色截图即使两张一模一样也必须 fail,
400
+ // 否则"渲染失败输出白图"会拿到 1.0 相似度而绿灯(spec 假成功防护清单第 5 条)。
401
+ /** @type {{ blank: boolean, uniqueColors: number, dominantRatio: number } | null} */
402
+ let referenceInfo = null;
403
+ /** @type {{ blank: boolean, uniqueColors: number, dominantRatio: number } | null} */
404
+ let candidateInfo = null;
405
+ try {
406
+ // 必须两张都解码成功才做空白判定:否则「候选图是坏 PNG」会被
407
+ // 误报成 blank-image,而正确结论是 unknown(无法判定)。
408
+ const referenceImage = decodePng(reference);
409
+ const candidateImage = decodePng(candidate);
410
+ referenceInfo = assessPngInformation(referenceImage);
411
+ candidateInfo = assessPngInformation(candidateImage);
412
+ } catch {
413
+ // 解码失败交给下面的 comparePng 统一报 screenshot-invalid
414
+ }
415
+ if (referenceInfo?.blank === true || candidateInfo?.blank === true) {
416
+ const side = referenceInfo?.blank === true ? "reference" : "candidate";
417
+ return {
418
+ verdict: "fail",
419
+ detail: {
420
+ reason: "blank-image",
421
+ side,
422
+ reference: referenceInfo,
423
+ candidate: candidateInfo,
424
+ },
425
+ startedAt,
426
+ endedAt: new Date().toISOString(),
427
+ exitCode: null,
428
+ stdout: "",
429
+ stderr: "",
430
+ };
431
+ }
381
432
  /** @type {ReturnType<typeof comparePng>} */
382
433
  let compared;
383
434
  try {
@@ -0,0 +1,213 @@
1
+ // @ts-check
2
+ // core/ingest.js:外部 agent 产出报告的**通用摄入契约**。
3
+ //
4
+ // 为什么需要:Craft / 其他逆向 agent 会产出自己的报告。casefile 的立场是
5
+ // "只记录、不背书"——所以这里只接受**已经成形的结论与证据描述**,不解释对方语义,
6
+ // 也不把它的判断当成自己的判断(authority 固定 external、producer 记录来源)。
7
+ //
8
+ // 契约形状(版本 1):
9
+ // {
10
+ // sources: { tool, version?, mode?, producedAt?, reportPath? },
11
+ // evidence: [ { summary, kind?, authority?, limitations?, refs?, artifactPath? } ],
12
+ // claims: [ { text, kind?, status?, evidenceIds?: number[] , limitations?, refs? } ],
13
+ // unknowns: [ { text, severity? } ]
14
+ // }
15
+ // claims.evidenceIds 用**数组下标**引用本次 payload 里的 evidence,摄入时映射成真实 id。
16
+ // 下标越界直接报错——宁可拒绝,也不能静默丢引用(那会让结论变成无出处)。
17
+
18
+ /** 摄入契约版本;形状变化时递增。 */
19
+ export const INGEST_VERSION = 1;
20
+
21
+ const EVIDENCE_KINDS = [
22
+ "structure",
23
+ "behavior",
24
+ "string",
25
+ "screen",
26
+ "network",
27
+ "artifact",
28
+ "other",
29
+ ];
30
+ const CLAIM_KINDS = ["structure", "behavior", "string", "other"];
31
+ const CLAIM_STATUS = ["observed", "derived", "inferred"];
32
+ const SEVERITIES = ["low", "medium", "high"];
33
+ const PRODUCER_MODES = ["headful", "headless", "api", "archive", "manual", "stealth", "unknown"];
34
+
35
+ /**
36
+ * @param {unknown} value
37
+ * @param {string} field
38
+ * @returns {string}
39
+ */
40
+ function needText(value, field) {
41
+ if (typeof value !== "string" || value.trim() === "") {
42
+ throw Object.assign(new Error(`${field} 必须是非空字符串`), { code: "invalid-input" });
43
+ }
44
+ return value.trim();
45
+ }
46
+
47
+ /**
48
+ * @param {unknown} value
49
+ * @param {readonly string[]} allowed
50
+ * @param {string} field
51
+ * @param {string} fallback
52
+ * @returns {string}
53
+ */
54
+ function oneOf(value, allowed, field, fallback) {
55
+ if (value == null) return fallback;
56
+ const text = String(value);
57
+ if (!allowed.includes(text)) {
58
+ throw Object.assign(new Error(`${field} 只能是 ${allowed.join(" / ")}:${text}`), {
59
+ code: "invalid-input",
60
+ });
61
+ }
62
+ return text;
63
+ }
64
+
65
+ /**
66
+ * @param {unknown} value
67
+ * @param {string} field
68
+ * @returns {string[]}
69
+ */
70
+ function textList(value, field) {
71
+ if (value == null) return [];
72
+ if (!Array.isArray(value)) {
73
+ throw Object.assign(new Error(`${field} 必须是字符串数组`), { code: "invalid-input" });
74
+ }
75
+ return value.map((/** @type {any} */ item, /** @type {number} */ index) =>
76
+ needText(item, `${field}[${index}]`),
77
+ );
78
+ }
79
+
80
+ /**
81
+ * 校验并归一化摄入 payload。
82
+ * @param {any} raw
83
+ * @returns {{
84
+ * version: number,
85
+ * source: { tool: string, version: string | null, mode: string, producedAt: string | null, reportPath: string | null },
86
+ * evidence: Array<Record<string, any>>,
87
+ * claims: Array<Record<string, any>>,
88
+ * unknowns: Array<Record<string, any>>,
89
+ * }}
90
+ */
91
+ export function validateIngestPayload(raw) {
92
+ if (raw == null || typeof raw !== "object" || Array.isArray(raw)) {
93
+ throw Object.assign(new Error("payload 必须是对象"), { code: "invalid-input" });
94
+ }
95
+ const version = raw.version == null ? INGEST_VERSION : Number(raw.version);
96
+ if (version !== INGEST_VERSION) {
97
+ throw Object.assign(
98
+ new Error(`不支持的摄入契约版本:${String(raw.version)}(当前 ${INGEST_VERSION})`),
99
+ {
100
+ code: "invalid-input",
101
+ },
102
+ );
103
+ }
104
+
105
+ const sourceRaw = raw.source ?? raw.sources ?? {};
106
+ const source = {
107
+ tool: needText(sourceRaw?.tool, "source.tool"),
108
+ version: sourceRaw?.version == null ? null : needText(sourceRaw.version, "source.version"),
109
+ mode: oneOf(sourceRaw?.mode, PRODUCER_MODES, "source.mode", "unknown"),
110
+ producedAt:
111
+ sourceRaw?.producedAt == null ? null : needText(sourceRaw.producedAt, "source.producedAt"),
112
+ reportPath:
113
+ sourceRaw?.reportPath == null ? null : needText(sourceRaw.reportPath, "source.reportPath"),
114
+ };
115
+
116
+ const evidenceRaw = Array.isArray(raw.evidence) ? raw.evidence : [];
117
+ const evidence = evidenceRaw.map((/** @type {any} */ item, /** @type {number} */ index) => ({
118
+ summary: needText(item?.summary, `evidence[${index}].summary`),
119
+ kind: oneOf(item?.kind, EVIDENCE_KINDS, `evidence[${index}].kind`, "other"),
120
+ authority: "external",
121
+ limitations: textList(item?.limitations, `evidence[${index}].limitations`),
122
+ refs: textList(item?.refs, `evidence[${index}].refs`),
123
+ artifactPath:
124
+ item?.artifactPath == null
125
+ ? null
126
+ : needText(item.artifactPath, `evidence[${index}].artifactPath`),
127
+ }));
128
+
129
+ const claimsRaw = Array.isArray(raw.claims) ? raw.claims : [];
130
+ const claims = claimsRaw.map((/** @type {any} */ item, /** @type {number} */ index) => {
131
+ /** @type {number[]} */
132
+ let mapped = [];
133
+ if (item?.evidenceIds != null) {
134
+ if (!Array.isArray(item.evidenceIds)) {
135
+ throw Object.assign(new Error(`claims[${index}].evidenceIds 必须是数组下标`), {
136
+ code: "invalid-input",
137
+ });
138
+ }
139
+ mapped = item.evidenceIds.map((/** @type {any} */ value, /** @type {number} */ at) => {
140
+ const num = Number(value);
141
+ if (!Number.isInteger(num) || num < 0 || num >= evidence.length) {
142
+ throw Object.assign(
143
+ new Error(
144
+ `claims[${index}].evidenceIds[${at}] 越界:${String(value)}(本次只有 ${evidence.length} 条证据)`,
145
+ ),
146
+ { code: "invalid-input" },
147
+ );
148
+ }
149
+ return num;
150
+ });
151
+ }
152
+ return {
153
+ text: needText(item?.text, `claims[${index}].text`),
154
+ kind: oneOf(item?.kind, CLAIM_KINDS, `claims[${index}].kind`, "structure"),
155
+ status: oneOf(item?.status, CLAIM_STATUS, `claims[${index}].status`, "observed"),
156
+ limitations: textList(item?.limitations, `claims[${index}].limitations`),
157
+ refs: textList(item?.refs, `claims[${index}].refs`),
158
+ evidenceIndexes: [...new Set(mapped)],
159
+ };
160
+ });
161
+
162
+ const unknownsRaw = Array.isArray(raw.unknowns) ? raw.unknowns : [];
163
+ const unknowns = unknownsRaw.map((/** @type {any} */ item, /** @type {number} */ index) => ({
164
+ text: needText(item?.text, `unknowns[${index}].text`),
165
+ severity: oneOf(item?.severity, SEVERITIES, `unknowns[${index}].severity`, "low"),
166
+ }));
167
+
168
+ return { version, source, evidence, claims, unknowns };
169
+ }
170
+
171
+ /**
172
+ * 契约说明(`case_ingest schema` 直接返回它,方便别的 agent 生成正确格式)。
173
+ * @returns {Record<string, any>}
174
+ */
175
+ export function describeIngestSchema() {
176
+ return {
177
+ version: INGEST_VERSION,
178
+ shape: {
179
+ source: {
180
+ tool: "string (必填)",
181
+ version: "string?",
182
+ mode: PRODUCER_MODES,
183
+ producedAt: "ISO string?",
184
+ reportPath: "绝对路径?",
185
+ },
186
+ evidence: [
187
+ {
188
+ summary: "string (必填)",
189
+ kind: EVIDENCE_KINDS,
190
+ limitations: "string[]",
191
+ refs: "string[]",
192
+ artifactPath: "绝对路径?",
193
+ },
194
+ ],
195
+ claims: [
196
+ {
197
+ text: "string (必填)",
198
+ kind: CLAIM_KINDS,
199
+ status: CLAIM_STATUS,
200
+ evidenceIds: "数字下标数组(引用本次 evidence)",
201
+ limitations: "string[]",
202
+ },
203
+ ],
204
+ unknowns: [{ text: "string (必填)", severity: SEVERITIES }],
205
+ },
206
+ rules: [
207
+ "authority 固定为 external:casefile 只记录、不背书",
208
+ "claims.evidenceIds 用数组下标;越界直接报错,不静默丢引用",
209
+ "source.reportPath 若给出,会归档进项目目录并记录 sha256(/tmp 会过期)",
210
+ "所有 limitations 原样保留:对方没说的不确定性,casefile 不替它补",
211
+ ],
212
+ };
213
+ }
package/lib/core/model.js CHANGED
@@ -412,6 +412,8 @@ export function normalizeObligation(input) {
412
412
  checkIds: idList(input?.checkIds, "checkIds"),
413
413
  evidenceIds: idList(input?.evidenceIds, "evidenceIds"),
414
414
  featureIds: idList(input?.featureIds, "featureIds"),
415
+ // 义务验证的是哪条结论:交接给别的 agent 时,「哪条结论还没人验」是最常被问的问题。
416
+ claimIds: idList(input?.claimIds, "claimIds"),
415
417
  ownerDigest:
416
418
  input?.ownerDigest == null ? null : text(input.ownerDigest, "ownerDigest", { max: 128 }),
417
419
  check,
package/lib/core/png.js CHANGED
@@ -143,6 +143,39 @@ export function compareImages(a, b) {
143
143
  };
144
144
  }
145
145
 
146
+ /**
147
+ * 判一张图「有没有信息量」——用来挡"截图空白/纯色却判通过"的假成功。
148
+ *
149
+ * 判定:颜色种类很少 **且** 单一颜色占比极高 → 视为空白。
150
+ * 阈值刻意保守(0.995 / 8 色),因为误判正常截图的代价比漏判高:
151
+ * 一个带小图标的页面会有几十种颜色、主色占比也不会到 99.5%。
152
+ *
153
+ * @param {ReturnType<typeof decodePng>} image
154
+ * @returns {{ blank: boolean, uniqueColors: number, dominantRatio: number }}
155
+ */
156
+ export function assessPngInformation(image) {
157
+ const pixels = image.width * image.height;
158
+ if (pixels <= 0) return { blank: true, uniqueColors: 0, dominantRatio: 1 };
159
+ /** @type {Map<number, number>} */
160
+ const counts = new Map();
161
+ for (let i = 0; i < pixels; i += 1) {
162
+ const at = i * image.channels;
163
+ // 只按 RGB 归并(忽略 alpha),避免同一颜色因 alpha 差异被当成多色
164
+ const key =
165
+ ((image.data[at] ?? 0) << 16) | ((image.data[at + 1] ?? 0) << 8) | (image.data[at + 2] ?? 0);
166
+ counts.set(key, (counts.get(key) ?? 0) + 1);
167
+ }
168
+ let dominant = 0;
169
+ for (const value of counts.values()) if (value > dominant) dominant = value;
170
+ const dominantRatio = dominant / pixels;
171
+ const uniqueColors = counts.size;
172
+ return {
173
+ blank: dominantRatio >= 0.995 && uniqueColors <= 8,
174
+ uniqueColors,
175
+ dominantRatio,
176
+ };
177
+ }
178
+
146
179
  /**
147
180
  * 比较两个 PNG 文件的内容(Buffer 入参,便于测试与调用方复用)。
148
181
  * @param {Buffer} reference
@@ -358,3 +358,145 @@ export function renderReportMarkdown(report) {
358
358
  lines.push("");
359
359
  return lines.join("\n");
360
360
  }
361
+
362
+ /**
363
+ * HTML 转义。报告内容来自用户输入(标题、义务文本、路径),必须转义。
364
+ * @param {unknown} value
365
+ * @returns {string}
366
+ */
367
+ export function escapeHtml(value) {
368
+ return String(value ?? "")
369
+ .replaceAll("&", "&amp;")
370
+ .replaceAll("<", "&lt;")
371
+ .replaceAll(">", "&gt;")
372
+ .replaceAll('"', "&quot;")
373
+ .replaceAll("'", "&#39;");
374
+ }
375
+
376
+ /**
377
+ * 把报告渲染成**单文件 HTML**(内联样式、零外部资源),用于外发与存档。
378
+ * 样式刻意简单:归档件十年后打开也应该是这个样子,不依赖任何 CDN。
379
+ * @param {Record<string, any>} report
380
+ * @returns {string}
381
+ */
382
+ export function renderReportHtml(report) {
383
+ const r = report ?? {};
384
+ const project = r.project ?? {};
385
+ const counts = r.counts ?? {};
386
+ const coverage = r.coverage ?? {};
387
+ const e = escapeHtml;
388
+ /**
389
+ * @param {unknown[]} cells
390
+ * @param {string} [tag]
391
+ * @returns {string}
392
+ */
393
+ const row = (cells, tag = "td") =>
394
+ `<tr>${cells.map((cell) => `<${tag}>${cell}</${tag}>`).join("")}</tr>`;
395
+ /**
396
+ * @param {string} title
397
+ * @param {string} body
398
+ * @returns {string}
399
+ */
400
+ const section = (title, body) =>
401
+ body === "" ? "" : `<section><h2>${e(title)}</h2>${body}</section>`;
402
+
403
+ const summary = `
404
+ <dl>
405
+ <dt>项目</dt><dd>${e(project.title ?? project.id)} <span class="muted">(${e(project.id)})</span></dd>
406
+ <dt>目标</dt><dd>${e(project.target?.ref ?? "")} <span class="muted">${e(project.target?.kind ?? "")}</span></dd>
407
+ <dt>授权档</dt><dd>${e(project.authTier ?? "")}</dd>
408
+ <dt>状态</dt><dd>${e(project.state ?? "")}</dd>
409
+ <dt>覆盖率</dt><dd><strong>${(Number(coverage.ratio ?? 0) * 100).toFixed(0)}%</strong> <span class="muted">(${e(coverage.pass ?? 0)}/${e(coverage.total ?? 0)})</span></dd>
410
+ <dt>生成时间</dt><dd>${e(r.generatedAt ?? "")}</dd>
411
+ </dl>`;
412
+
413
+ const countsTable = `<table><thead><tr><th>项</th><th>数量</th></tr></thead><tbody>${Object.entries(
414
+ counts,
415
+ )
416
+ .map(([key, value]) => row([e(key), e(value)]))
417
+ .join("")}</tbody></table>`;
418
+
419
+ const obligations = Array.isArray(r.obligations)
420
+ ? `<table><thead><tr><th>状态</th><th>义务</th><th>种类</th><th>检查数</th></tr></thead><tbody>${r.obligations
421
+ .map((item) =>
422
+ row([e(item.status), e(item.statement), e(item.kind), e(item.checkIds?.length ?? 0)]),
423
+ )
424
+ .join("")}</tbody></table>`
425
+ : "";
426
+
427
+ const checks = Array.isArray(r.checks)
428
+ ? `<table><thead><tr><th>结论</th><th>checker</th><th>实现</th><th>时间</th></tr></thead><tbody>${r.checks
429
+ .map((item) =>
430
+ row([e(item.verdict), e(item.checker), e(item.implementationDigest), e(item.createdAt)]),
431
+ )
432
+ .join("")}</tbody></table>`
433
+ : "";
434
+
435
+ const producers =
436
+ Array.isArray(r.producers) && r.producers.length > 0
437
+ ? `<table><thead><tr><th>工具</th><th>版本</th><th>获取方式</th><th>产物</th><th>用户已确认</th></tr></thead><tbody>${r.producers
438
+ .map((item) =>
439
+ row([
440
+ e(item.tool ?? "未知"),
441
+ e(item.version ?? "—"),
442
+ e(item.mode ?? "—"),
443
+ e(item.outputKind ?? "—"),
444
+ e(item.accessConfirmedByUser === true ? "是" : "未记录"),
445
+ ]),
446
+ )
447
+ .join(
448
+ "",
449
+ )}</tbody></table><p class="note">casefile 不采集、不规避访问控制:以上生产者由操作者选择并执行,责任归操作者。</p>`
450
+ : "";
451
+
452
+ const unknowns =
453
+ Array.isArray(r.unknowns) && r.unknowns.length > 0
454
+ ? `<ul>${r.unknowns.map((item) => `<li>${e(item.text ?? item)}</li>`).join("")}</ul>`
455
+ : '<p class="muted">没有未解决的未知项。</p>';
456
+
457
+ const stop = r.stop
458
+ ? `<p>停止条件:<strong>${e(r.stop.reason ?? "")}</strong>${r.stop.stop === true ? "(已停止)" : ""}</p>`
459
+ : "";
460
+
461
+ return `<!doctype html>
462
+ <html lang="zh-CN">
463
+ <head>
464
+ <meta charset="utf-8">
465
+ <meta name="viewport" content="width=device-width, initial-scale=1">
466
+ <title>案卷报告 · ${e(project.title ?? project.id ?? "")}</title>
467
+ <style>
468
+ :root { color-scheme: light; }
469
+ body { margin: 0; padding: 32px 20px 64px; background: #faf9f6; color: #1c1c1e;
470
+ font: 14px/1.6 -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", sans-serif; }
471
+ .wrap { max-width: 900px; margin: 0 auto; }
472
+ h1 { font-size: 22px; margin: 0 0 4px; }
473
+ h2 { font-size: 15px; margin: 28px 0 10px; padding-bottom: 6px; border-bottom: 1px solid #e6e3dc; }
474
+ .sub { color: #6b6b70; font-size: 12px; margin-bottom: 24px; }
475
+ .muted { color: #6b6b70; font-size: 12px; }
476
+ .note { color: #6b6b70; font-size: 12px; margin-top: 6px; }
477
+ dl { display: grid; grid-template-columns: 96px 1fr; gap: 6px 12px; margin: 0; padding: 16px;
478
+ background: #fff; border: 1px solid #e6e3dc; border-radius: 10px; }
479
+ dt { color: #6b6b70; }
480
+ dd { margin: 0; }
481
+ table { width: 100%; border-collapse: collapse; background: #fff; border: 1px solid #e6e3dc;
482
+ border-radius: 10px; overflow: hidden; font-size: 13px; }
483
+ th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid #f0ede7; vertical-align: top; }
484
+ th { background: #f4f1ea; font-weight: 600; }
485
+ tr:last-child td { border-bottom: 0; }
486
+ ul { margin: 0; padding-left: 20px; }
487
+ footer { margin-top: 32px; color: #6b6b70; font-size: 12px; }
488
+ </style>
489
+ </head>
490
+ <body><div class="wrap">
491
+ <h1>案卷报告 · ${e(project.title ?? project.id ?? "")}</h1>
492
+ <p class="sub">casefile 生成的只读归档件;数据来自项目记录,不重新采集。</p>
493
+ ${section("概览", summary)}
494
+ ${section("计数", countsTable)}
495
+ ${section("义务", obligations)}
496
+ ${section("检查", checks)}
497
+ ${section("证据生产者", producers)}
498
+ ${section("未知项", unknowns)}
499
+ ${section("循环状态", stop)}
500
+ <footer>本报告不评估目标安全性;只陈述静态分析与验收记录。<br>生成器:@kangyishuai/dsh-casefile</footer>
501
+ </div></body></html>`;
502
+ }
package/lib/core/store.js CHANGED
@@ -368,6 +368,13 @@ export class CaseStore {
368
368
  }
369
369
  if (patch.state != null) next.state = String(patch.state).slice(0, 32);
370
370
  if (patch.reaVersion != null) next.reaVersion = String(patch.reaVersion).slice(0, 64);
371
+ if (patch.autonomy != null && typeof patch.autonomy === "object") {
372
+ next.autonomy = {
373
+ level: String(patch.autonomy.level ?? "L2").slice(0, 4),
374
+ unlockedAt: patch.autonomy.unlockedAt ?? null,
375
+ budget: patch.autonomy.budget ?? null,
376
+ };
377
+ }
371
378
  if (patch.capabilityHash != null)
372
379
  next.capabilityHash = String(patch.capabilityHash).slice(0, 128);
373
380
  next.updatedAt = nowIso();