@kangyishuai/dsh-casefile 0.5.0 → 0.6.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/README.md +6 -3
- package/README.zh-CN.md +6 -3
- package/lib/actions.js +207 -8
- package/lib/client.js +16 -0
- package/lib/core/autonomy.js +143 -0
- package/lib/core/bundle.js +136 -0
- package/lib/core/checks.js +56 -5
- package/lib/core/model.js +2 -0
- package/lib/core/png.js +33 -0
- package/lib/core/report.js +142 -0
- package/lib/core/store.js +7 -0
- package/lib/service.js +73 -8
- package/lib/tools.js +61 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -138,12 +138,15 @@ Config is read from the `casefile` row in `cordis.patch.yml`. Do not edit the pr
|
|
|
138
138
|
|
|
139
139
|
## Compatibility
|
|
140
140
|
|
|
141
|
-
| Plugin
|
|
142
|
-
|
|
|
143
|
-
| 0.1.x
|
|
141
|
+
| Plugin | Verified on DSH | What was run |
|
|
142
|
+
| ----------- | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
143
|
+
| 0.1.x–0.2.x | 0.2.2-rc.3 (macOS, desktop + web) | 138 → 177 unit tests; 52-assertion web end-to-end smoke on a throwaway DSH home; **14-assertion desktop read-only regression on a real Electron renderer (CDP)**; `pnpm gate casefile` 4/4 steps green. |
|
|
144
|
+
| 0.3.x–0.5.x | same | 172 → 177 unit tests; adds `case_access` (sign-in wait), `case_app` (app-bundle first hop), artifact archiving, and project `archive`/`drop`; **exercised on 8 real projects** (local macOS app, sign-in-gated page, external-collector ingestion). |
|
|
144
145
|
|
|
145
146
|
Host APIs used here were verified by runtime inspection; the findings are recorded in `docs/runtime/0.2.2-rc.3.md` §10 (including two pitfalls: a missed `declareRemote` silently 404s only that endpoint, and `agentPresets` cannot be composed from bundle names).
|
|
146
147
|
|
|
148
|
+
Four target kinds were exercised in real tasks: **a local macOS app bundle** (Info.plist, signature surface, binary inventory — the binary layer needs REA + Ghidra, see `docs/runtime/0.2.2-rc.3.md` §13–§14), **a sign-in-gated web page** (`case_access await-login`, structure-only capture), **external-collector artifacts** (`producer` + `artifactPath` archiving), and **an app's own release package** (survey → spec → acceptance, closed end to end).
|
|
149
|
+
|
|
147
150
|
## Side effects & risks
|
|
148
151
|
|
|
149
152
|
- **Files it writes:** only under the data root above. It never writes into the investigated project, never modifies the REA binary, and never edits the profile.
|
package/README.zh-CN.md
CHANGED
|
@@ -138,12 +138,15 @@ casefile/
|
|
|
138
138
|
|
|
139
139
|
## 兼容性
|
|
140
140
|
|
|
141
|
-
| 插件
|
|
142
|
-
|
|
|
143
|
-
| 0.1.x | 0.2.2-rc.3(macOS,桌面版 + web) | 138 项单元测试;临时 DSH_HOME 上 52 项 web 端到端冒烟;**真实 Electron 渲染进程上 14 项桌面只读回归(CDP)**;`pnpm gate casefile` 4/4 步全绿。
|
|
141
|
+
| 插件 | 已在哪个 DSH 上验证 | 跑了什么 |
|
|
142
|
+
| ----------- | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
143
|
+
| 0.1.x–0.2.x | 0.2.2-rc.3(macOS,桌面版 + web) | 138 → 177 项单元测试;临时 DSH_HOME 上 52 项 web 端到端冒烟;**真实 Electron 渲染进程上 14 项桌面只读回归(CDP)**;`pnpm gate casefile` 4/4 步全绿。 |
|
|
144
|
+
| 0.3.x–0.5.x | 同上 | 172 → 177 项单元测试;新增 `case_access`(等登录)、`case_app`(应用包第一跳)、产物归档、项目 `archive`/`drop`;**在 8 个真实项目上跑通**(含本机 macOS 应用、登录态网页、外部采集器摄入)。 |
|
|
144
145
|
|
|
145
146
|
本插件用到的宿主 API 都经过运行时勘察,结论记在 `docs/runtime/0.2.2-rc.3.md` §10(含两个坑:漏一条 `declareRemote` 只会让那一个端点静默 404;`agentPresets` 不能用 bundle 名组合)。
|
|
146
147
|
|
|
148
|
+
真实任务里验证过的四类目标:**本机 macOS 应用包**(Info.plist/签名面/二进制库存,二进制层需 REA + Ghidra,见 `docs/runtime/0.2.2-rc.3.md` §13–§14)、**登录态网页**(`case_access await-login` + 只取结构)、**外部采集器产物**(`producer` + `artifactPath` 归档)、**应用自身发布包**(mas 包勘察 → 规格 → 验收闭环)。
|
|
149
|
+
|
|
147
150
|
## 副作用与风险
|
|
148
151
|
|
|
149
152
|
- **写哪些文件:** 只写上面的数据根。不写被调查的项目、不改 REA 二进制、不编辑 profile。
|
package/lib/actions.js
CHANGED
|
@@ -8,7 +8,14 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
|
8
8
|
import { join } from "node:path";
|
|
9
9
|
import { parseArchitectures, summarizeAppBundle } from "./core/app-bundle.js";
|
|
10
10
|
import { buildAttestation } from "./core/attestation.js";
|
|
11
|
+
import {
|
|
12
|
+
evaluateBudget,
|
|
13
|
+
evaluateUnlock,
|
|
14
|
+
normalizeAutonomy,
|
|
15
|
+
normalizeBudget,
|
|
16
|
+
} from "./core/autonomy.js";
|
|
11
17
|
import { buildSpecPack, redactPack, renderSpecMarkdown, writeSpecPack } from "./core/brief.js";
|
|
18
|
+
import { buildBundle } from "./core/bundle.js";
|
|
12
19
|
import { createCheckers } from "./core/checks.js";
|
|
13
20
|
import { hashTree, shortDigest } from "./core/digest.js";
|
|
14
21
|
import { awaitLogin } from "./core/login-wait.js";
|
|
@@ -29,6 +36,7 @@ import {
|
|
|
29
36
|
buildReport,
|
|
30
37
|
computeCoverage,
|
|
31
38
|
evaluateClose,
|
|
39
|
+
renderReportHtml,
|
|
32
40
|
renderReportMarkdown,
|
|
33
41
|
} from "./core/report.js";
|
|
34
42
|
import {
|
|
@@ -97,6 +105,26 @@ export function createActions(options) {
|
|
|
97
105
|
};
|
|
98
106
|
const checkers = createCheckers({ runner: checkerRunner });
|
|
99
107
|
|
|
108
|
+
/**
|
|
109
|
+
* 把 Info.plist(XML 或二进制)转成 JSON 对象。
|
|
110
|
+
* @param {string} plistPath
|
|
111
|
+
* @returns {Promise<Record<string, any>>}
|
|
112
|
+
*/
|
|
113
|
+
const readPlistAsJson = async (/** @type {string} */ plistPath) => {
|
|
114
|
+
if (runner != null) {
|
|
115
|
+
const result = await runner(`plutil -convert json -o - ${JSON.stringify(plistPath)}`);
|
|
116
|
+
const text = String(result?.stdout ?? "").trim();
|
|
117
|
+
if (text !== "") return JSON.parse(text);
|
|
118
|
+
}
|
|
119
|
+
// 没有 runner 或 plutil 没输出:只在文件本身就是 JSON 形式时接受
|
|
120
|
+
const raw = readFileSync(plistPath, "utf8").trim();
|
|
121
|
+
if (raw.startsWith("{")) return JSON.parse(raw);
|
|
122
|
+
throw new CasefileInputError(
|
|
123
|
+
"invalid-input",
|
|
124
|
+
"无法解析 Info.plist:它可能是 XML 或二进制,需要在 macOS 上用 plutil 转换(runner 不可用)",
|
|
125
|
+
);
|
|
126
|
+
};
|
|
127
|
+
|
|
100
128
|
/**
|
|
101
129
|
* @param {string} projectId
|
|
102
130
|
* @returns {Record<string, any>}
|
|
@@ -176,6 +204,8 @@ export function createActions(options) {
|
|
|
176
204
|
const data = store.readAll(project.id);
|
|
177
205
|
return {
|
|
178
206
|
project,
|
|
207
|
+
// 面板要显示当前自主性级别(L3 是危险状态,必须看得见)
|
|
208
|
+
autonomy: normalizeAutonomy(project.autonomy),
|
|
179
209
|
stats: projectStats(project, data),
|
|
180
210
|
claims: data.claims,
|
|
181
211
|
evidence: data.evidence,
|
|
@@ -1126,6 +1156,32 @@ export function createActions(options) {
|
|
|
1126
1156
|
if (typeof command !== "string" || command.trim() === "") {
|
|
1127
1157
|
throw new CasefileInputError("invalid-input", "runCycle 需要 command(构建命令)");
|
|
1128
1158
|
}
|
|
1159
|
+
// L3 无人值守:预算与"任一失败即停"在循环前/后强制生效,不可由调用方放宽。
|
|
1160
|
+
const autonomy = normalizeAutonomy(project.autonomy);
|
|
1161
|
+
/** @type {{ maxRounds: number, maxBuilds: number, maxWallClockMs: number } | null} */
|
|
1162
|
+
let budget = null;
|
|
1163
|
+
if (autonomy.level === "L3") {
|
|
1164
|
+
budget = normalizeBudget(autonomy.budget);
|
|
1165
|
+
const existing = store.readAll(project.id).builds;
|
|
1166
|
+
const preStop = evaluateBudget({
|
|
1167
|
+
builds: existing,
|
|
1168
|
+
startedAt: autonomy.unlockedAt,
|
|
1169
|
+
budget,
|
|
1170
|
+
});
|
|
1171
|
+
if (preStop.stop) {
|
|
1172
|
+
store.audit(project.id, {
|
|
1173
|
+
actor: "agent",
|
|
1174
|
+
action: "autonomy/stop",
|
|
1175
|
+
target: project.id,
|
|
1176
|
+
detail: { reason: preStop.reason, ...preStop.detail },
|
|
1177
|
+
});
|
|
1178
|
+
throw Object.assign(new Error(`L3 停止:${preStop.reason}`), {
|
|
1179
|
+
code: "autonomy-stop",
|
|
1180
|
+
reason: preStop.reason,
|
|
1181
|
+
detail: preStop.detail,
|
|
1182
|
+
});
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1129
1185
|
const loop = await this.advanceLoop(project.id, {
|
|
1130
1186
|
command,
|
|
1131
1187
|
cwd: input?.cwd,
|
|
@@ -1158,6 +1214,78 @@ export function createActions(options) {
|
|
|
1158
1214
|
return { ...overview, summary: summarizeOverview(overview) };
|
|
1159
1215
|
},
|
|
1160
1216
|
|
|
1217
|
+
// ---------- 自主性阶梯 ----------
|
|
1218
|
+
|
|
1219
|
+
/**
|
|
1220
|
+
* 解锁 / 降级自主性。L3 有硬条件,不满足就拒绝并列出 blocker。
|
|
1221
|
+
* @param {string} projectId
|
|
1222
|
+
* @param {{ level?: string, budget?: Record<string, any> | null }} input
|
|
1223
|
+
* @returns {Promise<Record<string, any>>}
|
|
1224
|
+
*/
|
|
1225
|
+
async setAutonomy(projectId, input) {
|
|
1226
|
+
const project = requireProject(projectId);
|
|
1227
|
+
const level = String(input?.level ?? "L3");
|
|
1228
|
+
if (!["L0", "L1", "L2", "L3"].includes(level)) {
|
|
1229
|
+
throw new CasefileInputError("invalid-input", `未知级别:${level}`);
|
|
1230
|
+
}
|
|
1231
|
+
if (level !== "L3") {
|
|
1232
|
+
// 降级永远允许且立即生效:这是"停"的开关。
|
|
1233
|
+
const next = store.updateProject(project.id, {
|
|
1234
|
+
autonomy: { level, unlockedAt: null, budget: null },
|
|
1235
|
+
});
|
|
1236
|
+
store.audit(project.id, {
|
|
1237
|
+
actor: "agent",
|
|
1238
|
+
action: "autonomy/lock",
|
|
1239
|
+
target: project.id,
|
|
1240
|
+
detail: { level },
|
|
1241
|
+
});
|
|
1242
|
+
return { project: next, autonomy: normalizeAutonomy(next.autonomy) };
|
|
1243
|
+
}
|
|
1244
|
+
const data = store.readAll(project.id);
|
|
1245
|
+
const unlock = evaluateUnlock({
|
|
1246
|
+
project,
|
|
1247
|
+
obligations: data.obligations,
|
|
1248
|
+
budget: input?.budget,
|
|
1249
|
+
});
|
|
1250
|
+
if (!unlock.ok) {
|
|
1251
|
+
throw Object.assign(new Error(`L3 解锁被拒绝:${unlock.blockers.join("、")}`), {
|
|
1252
|
+
code: "autonomy-blocked",
|
|
1253
|
+
blockers: unlock.blockers,
|
|
1254
|
+
});
|
|
1255
|
+
}
|
|
1256
|
+
const next = store.updateProject(project.id, {
|
|
1257
|
+
autonomy: {
|
|
1258
|
+
level: "L3",
|
|
1259
|
+
unlockedAt: nowIso(),
|
|
1260
|
+
budget: unlock.budget,
|
|
1261
|
+
},
|
|
1262
|
+
});
|
|
1263
|
+
store.audit(project.id, {
|
|
1264
|
+
actor: "agent",
|
|
1265
|
+
action: "autonomy/unlock",
|
|
1266
|
+
target: project.id,
|
|
1267
|
+
detail: { level, budget: unlock.budget, obligations: data.obligations.length },
|
|
1268
|
+
});
|
|
1269
|
+
return { project: next, autonomy: normalizeAutonomy(next.autonomy) };
|
|
1270
|
+
},
|
|
1271
|
+
|
|
1272
|
+
/**
|
|
1273
|
+
* 当前自主性状态(含 L3 前置条件检查,便于面板展示"为什么不能升")。
|
|
1274
|
+
* @param {string} projectId
|
|
1275
|
+
* @returns {Promise<Record<string, any>>}
|
|
1276
|
+
*/
|
|
1277
|
+
async autonomyStatus(projectId) {
|
|
1278
|
+
const project = requireProject(projectId);
|
|
1279
|
+
const data = store.readAll(project.id);
|
|
1280
|
+
const autonomy = normalizeAutonomy(project.autonomy);
|
|
1281
|
+
const unlock = evaluateUnlock({
|
|
1282
|
+
project,
|
|
1283
|
+
obligations: data.obligations,
|
|
1284
|
+
budget: autonomy.budget,
|
|
1285
|
+
});
|
|
1286
|
+
return { autonomy, unlock: { ok: unlock.ok, blockers: unlock.blockers } };
|
|
1287
|
+
},
|
|
1288
|
+
|
|
1161
1289
|
// ---------- 等登录(人机协作) ----------
|
|
1162
1290
|
|
|
1163
1291
|
/**
|
|
@@ -1227,8 +1355,9 @@ export function createActions(options) {
|
|
|
1227
1355
|
if (!existsSync(plistPath)) {
|
|
1228
1356
|
throw new CasefileInputError("invalid-input", `不是 macOS 应用包:缺 ${plistPath}`);
|
|
1229
1357
|
}
|
|
1230
|
-
|
|
1231
|
-
|
|
1358
|
+
// Info.plist 可能是 XML(实测 Bob.app 就是),也可能是二进制;统一交给 plutil 转 JSON。
|
|
1359
|
+
// 直接 JSON.parse 会在 XML 上炸——真实使用一轮就踩到了。
|
|
1360
|
+
const plist = await readPlistAsJson(plistPath);
|
|
1232
1361
|
const executableName =
|
|
1233
1362
|
typeof plist.CFBundleExecutable === "string" ? plist.CFBundleExecutable : null;
|
|
1234
1363
|
const executablePath =
|
|
@@ -1348,7 +1477,17 @@ export function createActions(options) {
|
|
|
1348
1477
|
* @param {string} projectId
|
|
1349
1478
|
* @returns {Promise<Record<string, any>>}
|
|
1350
1479
|
*/
|
|
1351
|
-
|
|
1480
|
+
/**
|
|
1481
|
+
* 导出报告。
|
|
1482
|
+
* @param {string} projectId
|
|
1483
|
+
* @param {{ format?: "md" | "html" | "both" }} [options]
|
|
1484
|
+
* @returns {Promise<Record<string, any>>}
|
|
1485
|
+
*/
|
|
1486
|
+
async exportReport(projectId, options = {}) {
|
|
1487
|
+
const format = options?.format ?? "md";
|
|
1488
|
+
if (!["md", "html", "both"].includes(format)) {
|
|
1489
|
+
throw new CasefileInputError("invalid-input", `format 只能是 md / html / both:${format}`);
|
|
1490
|
+
}
|
|
1352
1491
|
const project = requireProject(projectId);
|
|
1353
1492
|
const data = store.readAll(project.id);
|
|
1354
1493
|
const current = latestBuild(data.builds);
|
|
@@ -1361,11 +1500,21 @@ export function createActions(options) {
|
|
|
1361
1500
|
const report = buildReport({ project, data, coverage, stop });
|
|
1362
1501
|
const stamp = String(report.generatedAt).replace(/[:.]/g, "-");
|
|
1363
1502
|
const dir = join(store.projectDir(project.id), "reports", stamp);
|
|
1364
|
-
const md = join(dir, "report.md");
|
|
1365
|
-
const json = join(dir, "report.json");
|
|
1366
1503
|
mkdirSync(dir, { recursive: true });
|
|
1367
|
-
|
|
1368
|
-
|
|
1504
|
+
/** @type {string[]} */
|
|
1505
|
+
const files = [];
|
|
1506
|
+
if (format === "md" || format === "both") {
|
|
1507
|
+
writeFileSync(join(dir, "report.md"), `${renderReportMarkdown(report)}\n`, "utf8");
|
|
1508
|
+
files.push("report.md");
|
|
1509
|
+
}
|
|
1510
|
+
if (format === "html" || format === "both") {
|
|
1511
|
+
writeFileSync(join(dir, "report.html"), `${renderReportHtml(report)}\n`, "utf8");
|
|
1512
|
+
files.push("report.html");
|
|
1513
|
+
} else {
|
|
1514
|
+
// md 模式保持旧行为:仍然写 report.json 供程序消费
|
|
1515
|
+
}
|
|
1516
|
+
writeFileSync(join(dir, "report.json"), `${JSON.stringify(report, null, 2)}\n`, "utf8");
|
|
1517
|
+
files.push("report.json");
|
|
1369
1518
|
store.audit(project.id, {
|
|
1370
1519
|
actor: "agent",
|
|
1371
1520
|
action: "report/export",
|
|
@@ -1377,12 +1526,62 @@ export function createActions(options) {
|
|
|
1377
1526
|
});
|
|
1378
1527
|
return {
|
|
1379
1528
|
path: dir,
|
|
1380
|
-
files
|
|
1529
|
+
files,
|
|
1381
1530
|
coverage,
|
|
1382
1531
|
summary: `报告已写入 ${dir}(覆盖率 ${(coverage.ratio * 100).toFixed(0)}%)`,
|
|
1383
1532
|
};
|
|
1384
1533
|
},
|
|
1385
1534
|
|
|
1535
|
+
/**
|
|
1536
|
+
* 导出机器可读证据包(全量账本,确定性、可校验)。
|
|
1537
|
+
* @param {string} projectId
|
|
1538
|
+
* @param {{ redact?: boolean }} [options]
|
|
1539
|
+
* @returns {Promise<Record<string, any>>}
|
|
1540
|
+
*/
|
|
1541
|
+
async exportBundle(projectId, options = {}) {
|
|
1542
|
+
const project = requireProject(projectId);
|
|
1543
|
+
const data = store.readAll(project.id);
|
|
1544
|
+
const coverage = computeCoverage(data.obligations);
|
|
1545
|
+
const build = buildBundle({
|
|
1546
|
+
project,
|
|
1547
|
+
evidence: data.evidence,
|
|
1548
|
+
claims: data.claims,
|
|
1549
|
+
obligations: data.obligations,
|
|
1550
|
+
checks: data.checks,
|
|
1551
|
+
unknowns: data.unknowns,
|
|
1552
|
+
coverage,
|
|
1553
|
+
counts: {
|
|
1554
|
+
evidence: data.evidence.length,
|
|
1555
|
+
claims: data.claims.length,
|
|
1556
|
+
obligations: data.obligations.length,
|
|
1557
|
+
checks: data.checks.length,
|
|
1558
|
+
unknowns: data.unknowns.length,
|
|
1559
|
+
},
|
|
1560
|
+
redact: options?.redact !== false,
|
|
1561
|
+
});
|
|
1562
|
+
const stamp = String(build.generatedAt).replace(/[:.]/g, "-");
|
|
1563
|
+
const dir = join(store.projectDir(project.id), "bundles", stamp);
|
|
1564
|
+
mkdirSync(dir, { recursive: true });
|
|
1565
|
+
const file = join(dir, "bundle.json");
|
|
1566
|
+
writeFileSync(file, `${JSON.stringify(build, null, 2)}\n`, "utf8");
|
|
1567
|
+
store.audit(project.id, {
|
|
1568
|
+
actor: "agent",
|
|
1569
|
+
action: "bundle/export",
|
|
1570
|
+
target: dir,
|
|
1571
|
+
detail: {
|
|
1572
|
+
digest: build.integrity.digest.slice(0, 16),
|
|
1573
|
+
redacted: options?.redact !== false,
|
|
1574
|
+
},
|
|
1575
|
+
});
|
|
1576
|
+
return {
|
|
1577
|
+
path: dir,
|
|
1578
|
+
files: ["bundle.json"],
|
|
1579
|
+
integrity: build.integrity.digest,
|
|
1580
|
+
generatedAt: build.generatedAt,
|
|
1581
|
+
summary: `证据包已写入 ${dir}(integrity ${build.integrity.digest.slice(0, 16)})`,
|
|
1582
|
+
};
|
|
1583
|
+
},
|
|
1584
|
+
|
|
1386
1585
|
// ---------- 规格包 ----------
|
|
1387
1586
|
|
|
1388
1587
|
/**
|
package/lib/client.js
CHANGED
|
@@ -83,6 +83,9 @@ window.__ModuleLoader__.load({
|
|
|
83
83
|
"blocker.failedObligations": "有失败的义务",
|
|
84
84
|
"blocker.blockedObligations": "有阻塞的义务",
|
|
85
85
|
"blocker.coverageBelow": "覆盖率不足",
|
|
86
|
+
"autonomy.label": "自主性",
|
|
87
|
+
"autonomy.hint":
|
|
88
|
+
"L3 无人值守仅对 scope=selected 且义务全带检查配方的项目开放;任一失败即停。",
|
|
86
89
|
"wait.title": "案卷:等待登录",
|
|
87
90
|
"wait.hint": "请在弹出的浏览器窗口里完成登录;就绪后会自动继续。",
|
|
88
91
|
"wait.elapsed": "已等待 {seconds}s",
|
|
@@ -175,6 +178,9 @@ window.__ModuleLoader__.load({
|
|
|
175
178
|
"blocker.failedObligations": "failed obligations",
|
|
176
179
|
"blocker.blockedObligations": "blocked obligations",
|
|
177
180
|
"blocker.coverageBelow": "coverage below target",
|
|
181
|
+
"autonomy.label": "Autonomy",
|
|
182
|
+
"autonomy.hint":
|
|
183
|
+
"L3 unattended runs are limited to scope=selected projects whose obligations all carry check recipes; any failure stops the loop.",
|
|
178
184
|
"wait.title": "Casefile: waiting for sign-in",
|
|
179
185
|
"wait.hint":
|
|
180
186
|
"Finish signing in in the browser window; it continues automatically once ready.",
|
|
@@ -1096,6 +1102,16 @@ window.__ModuleLoader__.load({
|
|
|
1096
1102
|
h("h2", null, text(t, "panel.title")),
|
|
1097
1103
|
h("span", { className: "cf-sub" }, text(t, "panel.subtitle")),
|
|
1098
1104
|
h("span", { className: "cf-grow" }),
|
|
1105
|
+
h(
|
|
1106
|
+
"span",
|
|
1107
|
+
{
|
|
1108
|
+
className: "cf-muted",
|
|
1109
|
+
"data-casefile-autonomy": detail?.autonomy?.level || "L2",
|
|
1110
|
+
title: text(t, "autonomy.hint"),
|
|
1111
|
+
style: { marginRight: 8 },
|
|
1112
|
+
},
|
|
1113
|
+
`${text(t, "autonomy.label")} ${detail?.autonomy?.level || "L2"}`,
|
|
1114
|
+
),
|
|
1099
1115
|
h(
|
|
1100
1116
|
"button",
|
|
1101
1117
|
{
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// core/autonomy.js:自主性阶梯(L0–L3)的解锁与预算判定。
|
|
3
|
+
//
|
|
4
|
+
// 为什么要有这一层:`runCycle` 已经能自动跑"构建→检查→关闭义务",但**谁能让它
|
|
5
|
+
// 无人值守地跑**必须有硬条件,否则就是"全自动复刻"——那是明确不做的非目标。
|
|
6
|
+
//
|
|
7
|
+
// 硬规则(写死,不可配置放宽):
|
|
8
|
+
// 1. 只有 `scope: "selected"` 的项目能升到 L3;
|
|
9
|
+
// 2. 只有 existence / structure / behavior / visual 四类义务允许 L3;
|
|
10
|
+
// `coverage`(覆盖率硬门)与 `regression`(回归门)永远人工复核;
|
|
11
|
+
// 3. 每条义务必须有**可执行的检查配方**(`check`),否则"没人验"会被自动跑成绿灯;
|
|
12
|
+
// 4. 必须有预算上限;预算耗尽或任一轮 fail/unknown 立即停。
|
|
13
|
+
|
|
14
|
+
export const AUTONOMY_LEVELS = /** @type {const} */ (["L0", "L1", "L2", "L3"]);
|
|
15
|
+
|
|
16
|
+
/** L3 允许自动关闭的义务种类。 */
|
|
17
|
+
export const L3_ALLOWED_KINDS = /** @type {const} */ ([
|
|
18
|
+
"existence",
|
|
19
|
+
"structure",
|
|
20
|
+
"behavior",
|
|
21
|
+
"visual",
|
|
22
|
+
]);
|
|
23
|
+
|
|
24
|
+
export const AUTONOMY_DEFAULT_BUDGET = {
|
|
25
|
+
maxRounds: 5,
|
|
26
|
+
maxBuilds: 20,
|
|
27
|
+
maxWallClockMs: 30 * 60 * 1000,
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 归一化预算:缺项用默认值,非法值报错。
|
|
32
|
+
* @param {Record<string, any> | null | undefined} raw
|
|
33
|
+
* @returns {{ maxRounds: number, maxBuilds: number, maxWallClockMs: number }}
|
|
34
|
+
*/
|
|
35
|
+
export function normalizeBudget(raw) {
|
|
36
|
+
/** @param {"maxRounds" | "maxBuilds" | "maxWallClockMs"} key */
|
|
37
|
+
const pick = (key) => {
|
|
38
|
+
const value = raw?.[key];
|
|
39
|
+
if (value == null) return AUTONOMY_DEFAULT_BUDGET[key];
|
|
40
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
|
41
|
+
throw Object.assign(new Error(`预算 ${key} 必须是正数`), { code: "invalid-input" });
|
|
42
|
+
}
|
|
43
|
+
return Math.floor(value);
|
|
44
|
+
};
|
|
45
|
+
return {
|
|
46
|
+
maxRounds: pick("maxRounds"),
|
|
47
|
+
maxBuilds: pick("maxBuilds"),
|
|
48
|
+
maxWallClockMs: pick("maxWallClockMs"),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* 判断能否解锁到 L3。
|
|
54
|
+
* @param {{
|
|
55
|
+
* project: Record<string, any>,
|
|
56
|
+
* obligations: Record<string, any>[],
|
|
57
|
+
* budget?: Record<string, any> | null,
|
|
58
|
+
* }} input
|
|
59
|
+
* @returns {{ ok: boolean, blockers: string[], budget: { maxRounds: number, maxBuilds: number, maxWallClockMs: number } }}
|
|
60
|
+
*/
|
|
61
|
+
export function evaluateUnlock(input) {
|
|
62
|
+
/** @type {string[]} */
|
|
63
|
+
const blockers = [];
|
|
64
|
+
const project = input.project ?? {};
|
|
65
|
+
if (project.scope !== "selected") {
|
|
66
|
+
blockers.push("scope-not-selected");
|
|
67
|
+
}
|
|
68
|
+
const obligations = Array.isArray(input.obligations) ? input.obligations : [];
|
|
69
|
+
if (obligations.length === 0) {
|
|
70
|
+
blockers.push("no-obligations");
|
|
71
|
+
}
|
|
72
|
+
const disallowed = obligations.filter((item) => !L3_ALLOWED_KINDS.includes(item.kind));
|
|
73
|
+
if (disallowed.length > 0) {
|
|
74
|
+
blockers.push(
|
|
75
|
+
`kind-not-allowed:${[...new Set(disallowed.map((item) => item.kind))].join(",")}`,
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
const withoutCheck = obligations.filter((item) => item.check == null);
|
|
79
|
+
if (withoutCheck.length > 0) {
|
|
80
|
+
blockers.push(`obligation-without-check:${withoutCheck.length}`);
|
|
81
|
+
}
|
|
82
|
+
if (project.state === "archived") {
|
|
83
|
+
blockers.push("project-archived");
|
|
84
|
+
}
|
|
85
|
+
let budget = AUTONOMY_DEFAULT_BUDGET;
|
|
86
|
+
try {
|
|
87
|
+
budget = normalizeBudget(input.budget);
|
|
88
|
+
} catch {
|
|
89
|
+
blockers.push("invalid-budget");
|
|
90
|
+
}
|
|
91
|
+
return { ok: blockers.length === 0, blockers, budget };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* 按预算判停。
|
|
96
|
+
* @param {{
|
|
97
|
+
* builds: Record<string, any>[],
|
|
98
|
+
* startedAt: string | null,
|
|
99
|
+
* nowMs?: number,
|
|
100
|
+
* budget: { maxRounds: number, maxBuilds: number, maxWallClockMs: number },
|
|
101
|
+
* lastVerdict?: string | null,
|
|
102
|
+
* }} input
|
|
103
|
+
* @returns {{ stop: boolean, reason: string | null, detail: Record<string, any> }}
|
|
104
|
+
*/
|
|
105
|
+
export function evaluateBudget(input) {
|
|
106
|
+
const builds = Array.isArray(input.builds) ? input.builds : [];
|
|
107
|
+
const budget = input.budget ?? AUTONOMY_DEFAULT_BUDGET;
|
|
108
|
+
const nowMs = typeof input.nowMs === "number" ? input.nowMs : Date.now();
|
|
109
|
+
const startedMs = input.startedAt == null ? null : Date.parse(input.startedAt);
|
|
110
|
+
const elapsedMs =
|
|
111
|
+
startedMs == null || !Number.isFinite(startedMs) ? 0 : Math.max(0, nowMs - startedMs);
|
|
112
|
+
const detail = {
|
|
113
|
+
builds: builds.length,
|
|
114
|
+
budgetBuilds: budget.maxBuilds,
|
|
115
|
+
elapsedMs,
|
|
116
|
+
budgetMs: budget.maxWallClockMs,
|
|
117
|
+
};
|
|
118
|
+
// 任何一轮 fail/unknown 立即停:无人值守时"失败"必须交回给人,不能刷灯。
|
|
119
|
+
if (input.lastVerdict === "fail" || input.lastVerdict === "unknown") {
|
|
120
|
+
return { stop: true, reason: `l3-${input.lastVerdict}`, detail };
|
|
121
|
+
}
|
|
122
|
+
if (builds.length >= budget.maxBuilds) {
|
|
123
|
+
return { stop: true, reason: "l3-budget-builds", detail };
|
|
124
|
+
}
|
|
125
|
+
if (elapsedMs >= budget.maxWallClockMs) {
|
|
126
|
+
return { stop: true, reason: "l3-budget-time", detail };
|
|
127
|
+
}
|
|
128
|
+
return { stop: false, reason: null, detail };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* 归一化项目上的 autonomy 字段。
|
|
133
|
+
* @param {Record<string, any> | null | undefined} raw
|
|
134
|
+
* @returns {{ level: "L0" | "L1" | "L2" | "L3", unlockedAt: string | null, budget: { maxRounds: number, maxBuilds: number, maxWallClockMs: number } }}
|
|
135
|
+
*/
|
|
136
|
+
export function normalizeAutonomy(raw) {
|
|
137
|
+
const level = raw && AUTONOMY_LEVELS.includes(raw.level) ? raw.level : "L2";
|
|
138
|
+
return {
|
|
139
|
+
level,
|
|
140
|
+
unlockedAt: typeof raw?.unlockedAt === "string" ? raw.unlockedAt : null,
|
|
141
|
+
budget: normalizeBudget(raw?.budget ?? null),
|
|
142
|
+
};
|
|
143
|
+
}
|
|
@@ -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
|
+
}
|
package/lib/core/checks.js
CHANGED
|
@@ -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
|
-
|
|
67
|
-
|
|
68
|
-
|
|
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 {
|
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
|
package/lib/core/report.js
CHANGED
|
@@ -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("&", "&")
|
|
370
|
+
.replaceAll("<", "<")
|
|
371
|
+
.replaceAll(">", ">")
|
|
372
|
+
.replaceAll('"', """)
|
|
373
|
+
.replaceAll("'", "'");
|
|
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();
|
package/lib/service.js
CHANGED
|
@@ -70,6 +70,8 @@ function fail(error) {
|
|
|
70
70
|
"project-exists",
|
|
71
71
|
"not-found",
|
|
72
72
|
"confirm-required",
|
|
73
|
+
"autonomy-blocked",
|
|
74
|
+
"autonomy-stop",
|
|
73
75
|
"project-not-found",
|
|
74
76
|
"obligationTooTall",
|
|
75
77
|
"coverage-not-met",
|
|
@@ -99,18 +101,36 @@ export class CasefileService extends TypertRemoteService {
|
|
|
99
101
|
this.accessWait = null;
|
|
100
102
|
// casefile 自己起子进程读系统信息(plutil/lipo);这类只读命令不走会话终端,
|
|
101
103
|
// 避免污染用户 shell 历史,也不需要交互。
|
|
104
|
+
// casefile 自己起子进程读系统信息 / 跑 checker 命令。**不要**因为非零退出就 reject:
|
|
105
|
+
// checker 需要拿到「退出码是多少」来判定 fail,reject 会把它变成 internal 错误。
|
|
106
|
+
// 只有 spawn 级别失败(命令不存在 / 无权限)才算真的无法执行。
|
|
102
107
|
this.runner = async (/** @type {string} */ command, /** @type {any} */ options) => {
|
|
103
108
|
const { exec } = await import("node:child_process");
|
|
104
109
|
return await new Promise((resolve, reject) => {
|
|
105
|
-
exec(
|
|
106
|
-
|
|
107
|
-
|
|
110
|
+
exec(
|
|
111
|
+
command,
|
|
112
|
+
{ timeout: options?.timeoutMs ?? 15000, cwd: options?.cwd, maxBuffer: 8 * 1024 * 1024 },
|
|
113
|
+
(error, stdout, stderr) => {
|
|
114
|
+
const code = /** @type {any} */ (error)?.code;
|
|
115
|
+
// exec 把「命令不存在 / 不可执行」报成退出码 127 / 126(数字,不是 ENOENT 字符串),
|
|
116
|
+
// 且此时没有任何输出。这不是"命令跑了但失败",而是"根本没跑起来"。
|
|
117
|
+
const spawnFailed =
|
|
118
|
+
typeof code === "string"
|
|
119
|
+
? /ENOENT|EACCES|EPERM/u.test(code)
|
|
120
|
+
: (code === 127 || code === 126) && !stdout && !stderr;
|
|
121
|
+
if (spawnFailed) {
|
|
122
|
+
reject(error);
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
const killed = Boolean(error && /** @type {any} */ (error).killed === true);
|
|
108
126
|
resolve({
|
|
127
|
+
exitCode: killed ? null : typeof code === "number" ? code : error ? 1 : 0,
|
|
109
128
|
stdout: String(stdout ?? ""),
|
|
110
129
|
stderr: String(stderr ?? ""),
|
|
111
|
-
|
|
130
|
+
killed,
|
|
112
131
|
});
|
|
113
|
-
|
|
132
|
+
},
|
|
133
|
+
);
|
|
114
134
|
});
|
|
115
135
|
};
|
|
116
136
|
this.actions = createActions(this.actionOptions());
|
|
@@ -328,7 +348,10 @@ export class CasefileService extends TypertRemoteService {
|
|
|
328
348
|
this.store.listBuilderSessions().has(String(sessionId ?? "")),
|
|
329
349
|
closeProject: (projectId, options) => this.actions.closeProject(projectId, options),
|
|
330
350
|
closePreview: (projectId, options) => this.actions.closePreview(projectId, options),
|
|
331
|
-
exportReport: (projectId) => this.actions.exportReport(projectId),
|
|
351
|
+
exportReport: (projectId, options) => this.actions.exportReport(projectId, options),
|
|
352
|
+
exportBundle: (projectId, options) => this.actions.exportBundle(projectId, options),
|
|
353
|
+
setAutonomy: (projectId, input) => this.actions.setAutonomy(projectId, input),
|
|
354
|
+
autonomyStatus: (projectId) => this.actions.autonomyStatus(projectId),
|
|
332
355
|
advanceLoop: (projectId, input) => this.actions.advanceLoop(projectId, input),
|
|
333
356
|
startBuilder: (projectId, input) => this.actions.startBuilder(projectId, input),
|
|
334
357
|
awaitBuilder: (projectId, input) => this.actions.awaitBuilder(projectId, input),
|
|
@@ -644,11 +667,50 @@ export class CasefileService extends TypertRemoteService {
|
|
|
644
667
|
|
|
645
668
|
/**
|
|
646
669
|
* @param {string} projectId
|
|
670
|
+
* @param {{ level?: string, budget?: Record<string, any> | null }} input
|
|
671
|
+
* @returns {Promise<Record<string, any>>}
|
|
672
|
+
*/
|
|
673
|
+
async setAutonomy(projectId, input) {
|
|
674
|
+
try {
|
|
675
|
+
return await this.actions.setAutonomy(projectId, input ?? {});
|
|
676
|
+
} catch (error) {
|
|
677
|
+
fail(error);
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
/**
|
|
682
|
+
* @param {string} projectId
|
|
683
|
+
* @returns {Promise<Record<string, any>>}
|
|
684
|
+
*/
|
|
685
|
+
async autonomyStatus(projectId) {
|
|
686
|
+
try {
|
|
687
|
+
return await this.actions.autonomyStatus(projectId);
|
|
688
|
+
} catch (error) {
|
|
689
|
+
fail(error);
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
/**
|
|
694
|
+
* @param {string} projectId
|
|
695
|
+
* @param {{ redact?: boolean }} [options]
|
|
696
|
+
* @returns {Promise<Record<string, any>>}
|
|
697
|
+
*/
|
|
698
|
+
async exportBundle(projectId, options) {
|
|
699
|
+
try {
|
|
700
|
+
return await this.actions.exportBundle(projectId, options ?? {});
|
|
701
|
+
} catch (error) {
|
|
702
|
+
fail(error);
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
/**
|
|
707
|
+
* @param {string} projectId
|
|
708
|
+
* @param {{ format?: "md" | "html" | "both" }} [options]
|
|
647
709
|
* @returns {Promise<Record<string, any>>}
|
|
648
710
|
*/
|
|
649
|
-
async exportReport(projectId) {
|
|
711
|
+
async exportReport(projectId, options) {
|
|
650
712
|
try {
|
|
651
|
-
return await this.actions.exportReport(projectId);
|
|
713
|
+
return await this.actions.exportReport(projectId, options);
|
|
652
714
|
} catch (error) {
|
|
653
715
|
fail(error);
|
|
654
716
|
}
|
|
@@ -831,6 +893,9 @@ declareRemote(CasefileService, "awaitLogin");
|
|
|
831
893
|
declareRemote(CasefileService, "runCycle");
|
|
832
894
|
declareRemote(CasefileService, "closeProject");
|
|
833
895
|
declareRemote(CasefileService, "exportReport");
|
|
896
|
+
declareRemote(CasefileService, "exportBundle");
|
|
897
|
+
declareRemote(CasefileService, "setAutonomy");
|
|
898
|
+
declareRemote(CasefileService, "autonomyStatus");
|
|
834
899
|
declareRemote(CasefileService, "advanceLoop");
|
|
835
900
|
declareRemote(CasefileService, "startBuilder");
|
|
836
901
|
declareRemote(CasefileService, "awaitBuilder");
|
package/lib/tools.js
CHANGED
|
@@ -173,6 +173,30 @@ export function buildToolDefinitions(handlers, projectOf) {
|
|
|
173
173
|
patch: { type: "object", description: "update 时的字段(title/authTier/scope/state)" },
|
|
174
174
|
minCoverage: { type: "number", description: "close 时的覆盖率下限(默认 1)" },
|
|
175
175
|
reason: { type: "string", description: "archive 时的原因(进审计)" },
|
|
176
|
+
format: {
|
|
177
|
+
type: "string",
|
|
178
|
+
enum: ["md", "html", "both"],
|
|
179
|
+
description: "report 时的输出格式:md(默认)/ html(单文件、可外发归档)/ both",
|
|
180
|
+
},
|
|
181
|
+
level: {
|
|
182
|
+
type: "string",
|
|
183
|
+
enum: ["L0", "L1", "L2", "L3"],
|
|
184
|
+
description: "autonomy 动作的目标级别;L3 需 scope=selected 且义务全有检查配方",
|
|
185
|
+
},
|
|
186
|
+
budget: {
|
|
187
|
+
type: "object",
|
|
188
|
+
additionalProperties: false,
|
|
189
|
+
description: "L3 预算:maxRounds / maxBuilds / maxWallClockMs,缺项用默认",
|
|
190
|
+
properties: {
|
|
191
|
+
maxRounds: { type: "integer" },
|
|
192
|
+
maxBuilds: { type: "integer" },
|
|
193
|
+
maxWallClockMs: { type: "integer" },
|
|
194
|
+
},
|
|
195
|
+
},
|
|
196
|
+
redact: {
|
|
197
|
+
type: "boolean",
|
|
198
|
+
description: "bundle 时是否脱敏(默认 true)",
|
|
199
|
+
},
|
|
176
200
|
confirm: {
|
|
177
201
|
type: "boolean",
|
|
178
202
|
description: "drop 时必须传 true:把整个项目目录移进 trash(可手动移回)",
|
|
@@ -235,6 +259,30 @@ export function buildToolDefinitions(handlers, projectOf) {
|
|
|
235
259
|
summary: `项目已关闭(覆盖率 ${(preview.coverage.ratio * 100).toFixed(0)}%)`,
|
|
236
260
|
};
|
|
237
261
|
}
|
|
262
|
+
case "autonomy": {
|
|
263
|
+
if (args.level == null) {
|
|
264
|
+
const status = await handlers.autonomyStatus(projectId(args, exec));
|
|
265
|
+
return {
|
|
266
|
+
autonomy: status.autonomy,
|
|
267
|
+
unlock: status.unlock,
|
|
268
|
+
summary: `当前 ${status.autonomy.level}${status.unlock.ok ? "(可升 L3)" : `(不可升 L3:${status.unlock.blockers.join("、")})`}`,
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
const updated = await handlers.setAutonomy(projectId(args, exec), {
|
|
272
|
+
level: args.level,
|
|
273
|
+
budget: args.budget,
|
|
274
|
+
});
|
|
275
|
+
return {
|
|
276
|
+
...updated,
|
|
277
|
+
summary: `自主性已设为 ${updated.autonomy.level}`,
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
case "bundle": {
|
|
281
|
+
const bundle = await handlers.exportBundle(projectId(args, exec), {
|
|
282
|
+
redact: args.redact,
|
|
283
|
+
});
|
|
284
|
+
return bundle;
|
|
285
|
+
}
|
|
238
286
|
case "archive": {
|
|
239
287
|
const archived = await handlers.archiveProject(projectId(args, exec), {
|
|
240
288
|
reason: args.reason,
|
|
@@ -251,7 +299,13 @@ export function buildToolDefinitions(handlers, projectOf) {
|
|
|
251
299
|
};
|
|
252
300
|
}
|
|
253
301
|
case "report": {
|
|
254
|
-
|
|
302
|
+
const exported = await handlers.exportReport(projectId(args, exec), {
|
|
303
|
+
format: args.format,
|
|
304
|
+
});
|
|
305
|
+
return {
|
|
306
|
+
...exported,
|
|
307
|
+
summary: `报告已写入 ${exported.path}(${(exported.files ?? []).join(" / ")})`,
|
|
308
|
+
};
|
|
255
309
|
}
|
|
256
310
|
default:
|
|
257
311
|
throw Object.assign(new Error(`未知 action:${String(args.action)}`), {
|
|
@@ -536,6 +590,12 @@ export function buildToolDefinitions(handlers, projectOf) {
|
|
|
536
590
|
items: { type: "string" },
|
|
537
591
|
description: "挂到哪些功能上(用于按功能覆盖率)",
|
|
538
592
|
},
|
|
593
|
+
claimIds: {
|
|
594
|
+
type: "array",
|
|
595
|
+
items: { type: "string" },
|
|
596
|
+
description:
|
|
597
|
+
"这条义务验证的是哪些结论(交接给其他 agent 时用来判断「哪条结论还没人验」)",
|
|
598
|
+
},
|
|
539
599
|
},
|
|
540
600
|
required: ["statement"],
|
|
541
601
|
},
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kangyishuai/dsh-casefile",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Evidence-first reverse-engineering workbench on top of REA: observations become citable evidence, a handoff spec pack, and recomputable acceptance checks. No bridge, no engine.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dsh",
|