@kangyishuai/dsh-casefile 0.0.0-stage → 0.1.1

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/lib/actions.js ADDED
@@ -0,0 +1,1269 @@
1
+ // @ts-check
2
+ // actions.js:casefile 的全部业务动作(纯 Node,不 import 宿主包,可单测)。
3
+ //
4
+ // 分工:service.js 只做「数据根解析 + Remote 声明 + 会话记忆」;本文件承载
5
+ // 项目/证据/结论/功能/未知项/规格包的实际逻辑,tools.js 与 Remote 共用同一份实现。
6
+
7
+ import { mkdirSync, writeFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { buildAttestation } from "./core/attestation.js";
10
+ import { buildSpecPack, redactPack, renderSpecMarkdown, writeSpecPack } from "./core/brief.js";
11
+ import { createCheckers } from "./core/checks.js";
12
+ import { hashTree, shortDigest } from "./core/digest.js";
13
+ import { gradeCapabilities } from "./core/manifest.js";
14
+ import {
15
+ CasefileInputError,
16
+ newId,
17
+ normalizeClaim,
18
+ normalizeEvidence,
19
+ normalizeFeature,
20
+ normalizeObligation,
21
+ normalizeUnknown,
22
+ nowIso,
23
+ projectStats,
24
+ } from "./core/model.js";
25
+ import { buildOverview, summarizeOverview } from "./core/overview.js";
26
+ import {
27
+ buildReport,
28
+ computeCoverage,
29
+ evaluateClose,
30
+ renderReportMarkdown,
31
+ } from "./core/report.js";
32
+ import {
33
+ evaluateStop,
34
+ findStaleObligations,
35
+ latestBuild,
36
+ nextRound,
37
+ normalizeBuildRun,
38
+ summarizeRuns,
39
+ } from "./core/runs.js";
40
+ import { CaseStoreError } from "./core/store.js";
41
+
42
+ /** 业务错误:带稳定 code(由 service 映射成 RemoteError / 工具错误)。 */
43
+ export class CasefileActionError extends Error {
44
+ /**
45
+ * @param {string} code
46
+ * @param {string} message
47
+ */
48
+ constructor(code, message) {
49
+ super(message);
50
+ this.name = "CasefileActionError";
51
+ this.code = code;
52
+ }
53
+ }
54
+
55
+ /**
56
+ * 造一组动作。
57
+ * @param {{
58
+ * store: import("./core/store.js").CaseStore,
59
+ * currentProject?: Map<string, string>,
60
+ * dataRoot?: string,
61
+ * runner?: (command: string, options?: Record<string, any>) => Promise<Record<string, any>>,
62
+ * sessions?: {
63
+ * create(input: { cwd: string }): Promise<{ sessionId: string }>,
64
+ * prompt(input: { sessionId: string, text: string }): Promise<void>,
65
+ * wait(input: { sessionId: string, timeoutMs?: number }): Promise<{ reason: string, output?: any }>,
66
+ * },
67
+ * }} options
68
+ */
69
+ export function createActions(options) {
70
+ const store = options.store;
71
+ const currentProject = options.currentProject ?? new Map();
72
+ const dataRoot = options.dataRoot ?? store.rootDir;
73
+ const sessions = options.sessions;
74
+ const checkers = createCheckers(
75
+ /** @type {any} */ (options.runner ? { runner: options.runner } : {}),
76
+ );
77
+
78
+ /**
79
+ * @param {string} projectId
80
+ * @returns {Record<string, any>}
81
+ */
82
+ const requireProject = (projectId) => {
83
+ const id = String(projectId ?? "");
84
+ const project = store.getProject(id);
85
+ if (!project) throw new CaseStoreError("project-not-found", `项目不存在:${id || "(空)"}`);
86
+ return project;
87
+ };
88
+
89
+ /**
90
+ * @param {any} exec
91
+ * @returns {string | undefined}
92
+ */
93
+ const sessionOf = (exec) => {
94
+ const id = exec?.agent?.id;
95
+ return typeof id === "string" && id !== "" ? id : undefined;
96
+ };
97
+
98
+ return {
99
+ // ---------- 会话记忆 ----------
100
+
101
+ /**
102
+ * @param {any} exec
103
+ * @param {string} projectId
104
+ */
105
+ remember(exec, projectId) {
106
+ const sessionId = sessionOf(exec);
107
+ if (sessionId) currentProject.set(sessionId, projectId);
108
+ },
109
+
110
+ /**
111
+ * @param {any} exec
112
+ * @returns {string | undefined}
113
+ */
114
+ recall(exec) {
115
+ const sessionId = sessionOf(exec);
116
+ return sessionId ? currentProject.get(sessionId) : undefined;
117
+ },
118
+
119
+ // ---------- 项目 ----------
120
+
121
+ /** @returns {Promise<any[]>} */
122
+ async listProjects() {
123
+ return store.listProjects().map((project) => {
124
+ const data = store.readAll(project.id);
125
+ return projectStats(project, data);
126
+ });
127
+ },
128
+
129
+ /**
130
+ * @param {Record<string, any>} input
131
+ * @param {any} [exec]
132
+ * @returns {Promise<Record<string, any>>}
133
+ */
134
+ async openProject(input, exec) {
135
+ const project = store.createProject(input ?? {});
136
+ if (exec) this.remember(exec, project.id);
137
+ return project;
138
+ },
139
+
140
+ /**
141
+ * @param {string} projectId
142
+ * @returns {Promise<Record<string, any>>}
143
+ */
144
+ async detail(projectId) {
145
+ const project = requireProject(projectId);
146
+ const data = store.readAll(project.id);
147
+ return {
148
+ project,
149
+ stats: projectStats(project, data),
150
+ claims: data.claims,
151
+ evidence: data.evidence,
152
+ features: data.features,
153
+ unknowns: data.unknowns,
154
+ obligations: data.obligations,
155
+ builds: data.builds,
156
+ checks: data.checks,
157
+ attestations: data.attestations,
158
+ };
159
+ },
160
+
161
+ /**
162
+ * @param {string} projectId
163
+ * @param {Record<string, any>} patch
164
+ * @returns {Promise<Record<string, any>>}
165
+ */
166
+ async updateProject(projectId, patch) {
167
+ return store.updateProject(projectId, patch ?? {});
168
+ },
169
+
170
+ /**
171
+ * @param {string} projectId
172
+ * @param {ReturnType<typeof import("./core/manifest.js").diffCapabilities>} capabilities
173
+ * @returns {Promise<Record<string, any>>}
174
+ */
175
+ async status(projectId, capabilities) {
176
+ const detail = await this.detail(projectId);
177
+ return { ...detail, capabilities: gradeCapabilities(capabilities) };
178
+ },
179
+
180
+ /**
181
+ * @param {ReturnType<typeof import("./core/manifest.js").diffCapabilities>} capabilities
182
+ * @returns {Promise<Record<string, any>>}
183
+ */
184
+ async diagnose(capabilities) {
185
+ return {
186
+ dataRoot,
187
+ projects: store.listProjects().length,
188
+ rea: {
189
+ availableTools: capabilities.availableReaTools,
190
+ present: capabilities.present,
191
+ missingRequired: capabilities.missingRequired,
192
+ missingOptional: capabilities.missingOptional,
193
+ capabilityHash: capabilities.capabilityHash,
194
+ },
195
+ grade: gradeCapabilities(capabilities),
196
+ };
197
+ },
198
+
199
+ // ---------- 证据 ----------
200
+
201
+ /**
202
+ * @param {string} projectId
203
+ * @param {Record<string, any>} input
204
+ * @param {any} [exec]
205
+ * @returns {Promise<Record<string, any>>}
206
+ */
207
+ async addEvidence(projectId, input, exec) {
208
+ const project = requireProject(projectId);
209
+ const record = normalizeEvidence({
210
+ ...input,
211
+ sessionId: input?.sessionId ?? sessionOf(exec) ?? null,
212
+ });
213
+ store.appendRecord(project.id, "evidence", record);
214
+ store.touch(project.id);
215
+ store.audit(project.id, {
216
+ actor: "agent",
217
+ action: "evidence/add",
218
+ target: record.id,
219
+ detail: { kind: record.kind, confidence: record.confidence },
220
+ });
221
+ return record;
222
+ },
223
+
224
+ /**
225
+ * @param {string} projectId
226
+ * @param {Record<string, any>} [filter]
227
+ * @returns {Promise<any[]>}
228
+ */
229
+ async listEvidence(projectId, filter = {}) {
230
+ requireProject(projectId);
231
+ return store.readRecords(projectId, "evidence").filter((item) => {
232
+ if (filter?.kind && item.kind !== filter.kind) return false;
233
+ if (filter?.confidence && item.confidence !== filter.confidence) return false;
234
+ if (filter?.claimId && !(item.claimIds ?? []).includes(filter.claimId)) return false;
235
+ return true;
236
+ });
237
+ },
238
+
239
+ /**
240
+ * @param {string} projectId
241
+ * @param {string} evidenceId
242
+ * @returns {Promise<Record<string, any>>}
243
+ */
244
+ async showEvidence(projectId, evidenceId) {
245
+ requireProject(projectId);
246
+ const found = store.readRecords(projectId, "evidence").find((item) => item.id === evidenceId);
247
+ if (!found) throw new CaseStoreError("not-found", `证据不存在:${evidenceId}`);
248
+ return found;
249
+ },
250
+
251
+ // ---------- 结论 ----------
252
+
253
+ /**
254
+ * @param {string} projectId
255
+ * @param {Record<string, any>} input
256
+ * @returns {Promise<Record<string, any>>}
257
+ */
258
+ async addClaim(projectId, input) {
259
+ const project = requireProject(projectId);
260
+ const record = normalizeClaim(input);
261
+ store.appendRecord(project.id, "claims", record);
262
+ store.touch(project.id);
263
+ store.audit(project.id, {
264
+ actor: "agent",
265
+ action: "claim/add",
266
+ target: record.id,
267
+ detail: { kind: record.kind, status: record.status },
268
+ });
269
+ return record;
270
+ },
271
+
272
+ /**
273
+ * @param {string} projectId
274
+ * @param {Record<string, any>} [filter]
275
+ * @returns {Promise<any[]>}
276
+ */
277
+ async listClaims(projectId, filter = {}) {
278
+ requireProject(projectId);
279
+ return store.readRecords(projectId, "claims").filter((item) => {
280
+ if (typeof filter?.selected === "boolean" && item.selected !== filter.selected)
281
+ return false;
282
+ if (filter?.status && item.status !== filter.status) return false;
283
+ if (filter?.featureId && !(item.featureIds ?? []).includes(filter.featureId)) return false;
284
+ return true;
285
+ });
286
+ },
287
+
288
+ /**
289
+ * @param {string} projectId
290
+ * @param {string} query
291
+ * @returns {Promise<any[]>}
292
+ */
293
+ async searchClaims(projectId, query) {
294
+ requireProject(projectId);
295
+ const needle = String(query ?? "").toLowerCase();
296
+ if (needle === "") return [];
297
+ return store.readRecords(projectId, "claims").filter((item) => {
298
+ const haystack = `${item.text ?? ""} ${(item.limitations ?? []).join(" ")}`.toLowerCase();
299
+ return haystack.includes(needle);
300
+ });
301
+ },
302
+
303
+ /**
304
+ * 勾选/取消结论(append-only:追加同 id 的新记录,读时后者胜)。
305
+ * @param {string} projectId
306
+ * @param {string[]} claimIds
307
+ * @param {boolean} selected
308
+ * @returns {Promise<any[]>}
309
+ */
310
+ async selectClaims(projectId, claimIds, selected) {
311
+ const project = requireProject(projectId);
312
+ const wanted = new Set((Array.isArray(claimIds) ? claimIds : []).map(String));
313
+ if (wanted.size === 0) {
314
+ throw new CasefileInputError("invalid-input", "claimIds 不能为空");
315
+ }
316
+ const rows = store.readRecords(project.id, "claims");
317
+ /** @type {any[]} */
318
+ const updated = [];
319
+ for (const claim of rows) {
320
+ if (!wanted.has(claim.id)) continue;
321
+ const next = { ...claim, selected: selected === true };
322
+ store.appendRecord(project.id, "claims", next);
323
+ updated.push(next);
324
+ }
325
+ if (updated.length === 0) {
326
+ throw new CaseStoreError("not-found", `没有匹配的结论:${[...wanted].join("、")}`);
327
+ }
328
+ store.touch(project.id);
329
+ store.audit(project.id, {
330
+ actor: "agent",
331
+ action: "claim/select",
332
+ target: [...wanted].join(","),
333
+ detail: { selected: selected === true, count: updated.length },
334
+ });
335
+ return updated;
336
+ },
337
+
338
+ // ---------- 功能 / 未知项 ----------
339
+
340
+ /**
341
+ * @param {string} projectId
342
+ * @param {Record<string, any>} input
343
+ * @returns {Promise<Record<string, any>>}
344
+ */
345
+ async addFeature(projectId, input) {
346
+ const project = requireProject(projectId);
347
+ const record = normalizeFeature(input);
348
+ store.appendRecord(project.id, "features", record);
349
+ store.touch(project.id);
350
+ store.audit(project.id, {
351
+ actor: "agent",
352
+ action: "feature/add",
353
+ target: record.id,
354
+ detail: { name: record.name },
355
+ });
356
+ return record;
357
+ },
358
+
359
+ /**
360
+ * @param {string} projectId
361
+ * @returns {Promise<any[]>}
362
+ */
363
+ async listFeatures(projectId) {
364
+ requireProject(projectId);
365
+ return store.readRecords(projectId, "features");
366
+ },
367
+
368
+ /**
369
+ * @param {string} projectId
370
+ * @param {Record<string, any>} input
371
+ * @returns {Promise<Record<string, any>>}
372
+ */
373
+ async addUnknown(projectId, input) {
374
+ const project = requireProject(projectId);
375
+ const record = normalizeUnknown(input);
376
+ store.appendRecord(project.id, "unknowns", record);
377
+ store.touch(project.id);
378
+ store.audit(project.id, {
379
+ actor: "agent",
380
+ action: "unknown/add",
381
+ target: record.id,
382
+ detail: { severity: record.severity },
383
+ });
384
+ return record;
385
+ },
386
+
387
+ /**
388
+ * @param {string} projectId
389
+ * @returns {Promise<any[]>}
390
+ */
391
+ async listUnknowns(projectId) {
392
+ requireProject(projectId);
393
+ return store.readRecords(projectId, "unknowns");
394
+ },
395
+
396
+ /**
397
+ * @param {string} projectId
398
+ * @param {string} unknownId
399
+ * @param {string} [note]
400
+ * @returns {Promise<Record<string, any>>}
401
+ */
402
+ async resolveUnknown(projectId, unknownId, note) {
403
+ const project = requireProject(projectId);
404
+ const found = store.readRecords(project.id, "unknowns").find((item) => item.id === unknownId);
405
+ if (!found) throw new CaseStoreError("not-found", `未知项不存在:${unknownId}`);
406
+ /** @type {any} */
407
+ const next = {
408
+ ...found,
409
+ status: "resolved",
410
+ note: note == null ? (found.note ?? "") : String(note).slice(0, 2000),
411
+ resolvedAt: nowIso(),
412
+ };
413
+ store.appendRecord(project.id, "unknowns", next);
414
+ store.touch(project.id);
415
+ store.audit(project.id, { actor: "agent", action: "unknown/resolve", target: next.id });
416
+ return next;
417
+ },
418
+
419
+ // ---------- 义务与检查 ----------
420
+
421
+ /**
422
+ * @param {string} projectId
423
+ * @param {Record<string, any>} input
424
+ * @returns {Promise<Record<string, any>>}
425
+ */
426
+ async addObligation(projectId, input) {
427
+ const project = requireProject(projectId);
428
+ const record = normalizeObligation(input);
429
+ store.appendRecord(project.id, "obligations", record);
430
+ store.touch(project.id);
431
+ store.audit(project.id, {
432
+ actor: "agent",
433
+ action: "obligation/add",
434
+ target: record.id,
435
+ detail: { kind: record.kind, authorityRequired: record.authorityRequired },
436
+ });
437
+ return record;
438
+ },
439
+
440
+ /**
441
+ * @param {string} projectId
442
+ * @returns {Promise<any[]>}
443
+ */
444
+ async listObligations(projectId) {
445
+ requireProject(projectId);
446
+ return store.readRecords(projectId, "obligations");
447
+ },
448
+
449
+ /**
450
+ * 记录一次检查结果(M1 只落账;执行 checkers 是 M2)。
451
+ * @param {string} projectId
452
+ * @param {Record<string, any>} input
453
+ * @returns {Promise<Record<string, any>>}
454
+ */
455
+ async addCheck(projectId, input) {
456
+ const project = requireProject(projectId);
457
+ const verdict = String(input?.verdict ?? "");
458
+ if (!["pass", "fail", "unknown"].includes(verdict)) {
459
+ throw new CasefileInputError(
460
+ "invalid-input",
461
+ `verdict 必须是 pass | fail | unknown,收到 ${JSON.stringify(input?.verdict)}`,
462
+ );
463
+ }
464
+ const record = {
465
+ id: newId("check"),
466
+ obligationId: String(input?.obligationId ?? ""),
467
+ checker: String(input?.checker ?? "manual"),
468
+ checkerVersion: String(input?.checkerVersion ?? "1"),
469
+ verdict,
470
+ implementationDigest:
471
+ input?.implementationDigest == null ? null : String(input.implementationDigest),
472
+ originalDigest: input?.originalDigest == null ? null : String(input.originalDigest),
473
+ evidenceFetchedAt:
474
+ input?.evidenceFetchedAt == null ? nowIso() : String(input.evidenceFetchedAt),
475
+ detail: input?.detail == null ? "" : String(input.detail).slice(0, 2000),
476
+ at: nowIso(),
477
+ };
478
+ store.appendRecord(project.id, "checks", record);
479
+ store.touch(project.id);
480
+ store.audit(project.id, {
481
+ actor: "agent",
482
+ action: "check/add",
483
+ target: record.id,
484
+ detail: { obligationId: record.obligationId, verdict },
485
+ });
486
+ return record;
487
+ },
488
+
489
+ /**
490
+ * @param {string} projectId
491
+ * @param {string} [obligationId]
492
+ * @returns {Promise<any[]>}
493
+ */
494
+ async listChecks(projectId, obligationId) {
495
+ requireProject(projectId);
496
+ const rows = store.readRecords(projectId, "checks");
497
+ return obligationId == null
498
+ ? rows
499
+ : rows.filter((item) => item.obligationId === obligationId);
500
+ },
501
+
502
+ /**
503
+ * 关闭义务的硬门(spec/03-acceptance.md §1.3):
504
+ * 必须有 fresh 的 PASS 检查,且实现/原件 digest 与义务绑定的一致。
505
+ * @param {string} projectId
506
+ * @param {string} obligationId
507
+ * @param {{ checkId?: string, note?: string }} [input]
508
+ * @returns {Promise<Record<string, any>>}
509
+ */
510
+ async closeObligation(projectId, obligationId, input = {}) {
511
+ const project = requireProject(projectId);
512
+ const obligations = store.readRecords(project.id, "obligations");
513
+ const obligation = obligations.find((item) => item.id === obligationId);
514
+ if (!obligation) {
515
+ throw new CaseStoreError("not-found", `义务不存在:${obligationId}`);
516
+ }
517
+ if (obligation.status === "pass") return obligation;
518
+ const checks = store
519
+ .readRecords(project.id, "checks")
520
+ .filter((item) => item.obligationId === obligationId);
521
+ /** @type {string[]} */
522
+ const blockers = [];
523
+ const fresh = checks.filter((item) => {
524
+ const age = Date.now() - Date.parse(item.evidenceFetchedAt ?? 0);
525
+ return Number.isFinite(age) && age >= 0 && age <= 24 * 3600 * 1000;
526
+ });
527
+ const chosen =
528
+ input.checkId == null
529
+ ? fresh.filter((item) => item.verdict === "pass").at(-1)
530
+ : checks.find((item) => item.id === input.checkId);
531
+ if (!chosen) {
532
+ // 没有可用的 PASS:如果存在检查,用最近一条的结论作为原因,便于用户看懂。
533
+ const latest = checks.at(-1);
534
+ if (!latest) blockers.push("no-fresh-check");
535
+ else if (latest.verdict === "pass") blockers.push("stale-check");
536
+ else blockers.push(`check-${latest.verdict}`);
537
+ } else if (chosen.verdict !== "pass") {
538
+ blockers.push(`check-${chosen.verdict}`);
539
+ } else if (!fresh.includes(chosen)) {
540
+ blockers.push("stale-check");
541
+ }
542
+ if (chosen && obligation.ownerDigest != null) {
543
+ if (chosen.implementationDigest !== obligation.ownerDigest) {
544
+ blockers.push("implementation-mismatch");
545
+ }
546
+ }
547
+ if (blockers.length > 0) {
548
+ throw new CasefileActionError(
549
+ "obligationTooTall",
550
+ `义务 ${obligationId} 还不能关闭:${blockers.join("、")}`,
551
+ );
552
+ }
553
+ /** @type {any} */
554
+ if (!chosen) throw new CasefileActionError("obligationTooTall", "缺少可用检查");
555
+ /** @type {any} */
556
+ const next = {
557
+ ...obligation,
558
+ status: "pass",
559
+ checkIds: [...(obligation.checkIds ?? []), chosen.id],
560
+ closedBy: "agent",
561
+ closedAt: nowIso(),
562
+ note: input.note == null ? "" : String(input.note).slice(0, 2000),
563
+ version: Number(obligation.version ?? 1) + 1,
564
+ };
565
+ store.appendRecord(project.id, "obligations", next);
566
+ store.touch(project.id);
567
+ store.audit(project.id, {
568
+ actor: "agent",
569
+ action: "obligation/close",
570
+ target: next.id,
571
+ detail: { checkId: chosen.id },
572
+ });
573
+ return next;
574
+ },
575
+
576
+ /**
577
+ * @param {string} projectId
578
+ * @param {string} obligationId
579
+ * @param {string} [note]
580
+ * @returns {Promise<Record<string, any>>}
581
+ */
582
+ async reopenObligation(projectId, obligationId, note) {
583
+ const project = requireProject(projectId);
584
+ const obligations = store.readRecords(project.id, "obligations");
585
+ const obligation = obligations.find((item) => item.id === obligationId);
586
+ if (!obligation) throw new CaseStoreError("not-found", `义务不存在:${obligationId}`);
587
+ /** @type {any} */
588
+ const next = {
589
+ ...obligation,
590
+ status: "open",
591
+ note: note == null ? (obligation.note ?? "") : String(note).slice(0, 2000),
592
+ version: Number(obligation.version ?? 1) + 1,
593
+ };
594
+ store.appendRecord(project.id, "obligations", next);
595
+ store.touch(project.id);
596
+ store.audit(project.id, { actor: "agent", action: "obligation/reopen", target: next.id });
597
+ return next;
598
+ },
599
+
600
+ // ---------- 构建 / 验收 ----------
601
+
602
+ /**
603
+ * 起一轮构建:跑命令、算实现 digest、落 BuildRun,并按新 digest 重算 stale。
604
+ * @param {string} projectId
605
+ * @param {{ command: string, cwd?: string, round?: number, timeoutMs?: number }} input
606
+ * @returns {Promise<Record<string, any>>}
607
+ */
608
+ async startBuild(projectId, input) {
609
+ const project = requireProject(projectId);
610
+ const builds = store.readRecords(project.id, "builds");
611
+ const requestedRound = Number(input?.round);
612
+ const round =
613
+ Number.isInteger(requestedRound) && requestedRound > 0 ? requestedRound : nextRound(builds);
614
+ const startedAt = nowIso();
615
+ const buildChecker = checkers.get("build");
616
+ if (!buildChecker) throw new CasefileActionError("internal", "build checker 未注册");
617
+ const result = await buildChecker.run({
618
+ command: input?.command,
619
+ cwd: input?.cwd,
620
+ timeoutMs: input?.timeoutMs,
621
+ });
622
+ let implementationDigest = null;
623
+ const implementationDir = input?.cwd == null ? null : String(input.cwd);
624
+ if (implementationDir !== null) {
625
+ try {
626
+ implementationDigest = hashTree(implementationDir).digest;
627
+ } catch (error) {
628
+ /** @type {any} */
629
+ const anyError = error;
630
+ throw new CasefileInputError(
631
+ "invalid-input",
632
+ `无法计算实现 digest:${anyError?.message ?? String(error)}`,
633
+ );
634
+ }
635
+ }
636
+ const build = normalizeBuildRun({
637
+ round,
638
+ command: String(input.command),
639
+ cwd: input?.cwd ?? null,
640
+ status:
641
+ result.verdict === "pass" ? "pass" : result.verdict === "unknown" ? "error" : "fail",
642
+ exitCode: result.exitCode ?? null,
643
+ implementationDigest,
644
+ startedAt,
645
+ endedAt: result.endedAt,
646
+ detail: JSON.stringify(result.detail ?? {}),
647
+ });
648
+ store.appendRecord(project.id, "builds", build);
649
+ store.touch(project.id);
650
+ store.audit(project.id, {
651
+ actor: "agent",
652
+ action: "build/run",
653
+ target: build.id,
654
+ detail: {
655
+ round: build.round,
656
+ status: build.status,
657
+ digest: shortDigest(implementationDigest),
658
+ },
659
+ });
660
+ const stale = await this.refreshStaleness(project.id);
661
+ return { build, stale, ...summarizeRuns(this.readRunData(project.id)) };
662
+ },
663
+
664
+ /**
665
+ * 跑一条 checker 并落 CheckResult(绑定当前构建的实现 digest)。
666
+ * @param {string} projectId
667
+ * @param {{
668
+ * obligationId: string, checker: string, command?: string, cwd?: string,
669
+ * expect?: Record<string, any>, timeoutMs?: number,
670
+ * reference?: string, candidate?: string, minSimilarity?: number, allowSizeMismatch?: boolean,
671
+ * jsonPath?: string,
672
+ * }} input
673
+ * @returns {Promise<Record<string, any>>}
674
+ */
675
+ async runCheck(projectId, input) {
676
+ const project = requireProject(projectId);
677
+ const obligationId = String(input?.obligationId ?? "");
678
+ const obligations = store.readRecords(project.id, "obligations");
679
+ const obligation = obligations.find((item) => item.id === obligationId);
680
+ if (!obligation) throw new CaseStoreError("not-found", `义务不存在:${obligationId}`);
681
+ const checkerName = String(input?.checker ?? "cli");
682
+ const checker = checkers.get(checkerName);
683
+ if (!checker) {
684
+ throw new CasefileInputError(
685
+ "invalid-input",
686
+ `未知 checker:${checkerName}(可用:${[...checkers.keys()].join("、")})`,
687
+ );
688
+ }
689
+ const builds = store.readRecords(project.id, "builds");
690
+ const current = latestBuild(builds);
691
+ if (!current) {
692
+ throw new CasefileInputError(
693
+ "invalid-input",
694
+ "还没有构建记录:先 case_build 起一轮构建,检查结果才能绑定实现 digest",
695
+ );
696
+ }
697
+ const result = await checker.run({
698
+ command: input?.command,
699
+ cwd: input?.cwd,
700
+ timeoutMs: input?.timeoutMs,
701
+ expect: input?.expect ?? {},
702
+ reference: input?.reference,
703
+ candidate: input?.candidate,
704
+ minSimilarity: input?.minSimilarity,
705
+ allowSizeMismatch: input?.allowSizeMismatch,
706
+ jsonPath: input?.jsonPath,
707
+ });
708
+ const checkedAt = nowIso();
709
+ const record = {
710
+ id: newId("check"),
711
+ obligationId,
712
+ checker: checker.name,
713
+ checkerVersion: checker.version,
714
+ verdict: result.verdict,
715
+ implementationDigest: current.implementationDigest ?? null,
716
+ originalDigest: project.capabilityHash ?? null,
717
+ evidenceFetchedAt: checkedAt,
718
+ detail: JSON.stringify(result.detail ?? {}),
719
+ exitCode: result.exitCode ?? null,
720
+ stdout: result.stdout ?? "",
721
+ stderr: result.stderr ?? "",
722
+ at: checkedAt,
723
+ };
724
+ store.appendRecord(project.id, "checks", record);
725
+ store.touch(project.id);
726
+ store.audit(project.id, {
727
+ actor: "agent",
728
+ action: "check/run",
729
+ target: record.id,
730
+ detail: { obligationId, checker: checkerName, verdict: record.verdict },
731
+ });
732
+ return { check: record, obligation: obligation.id };
733
+ },
734
+
735
+ /**
736
+ * 依据最新构建 digest 重开已失效的已关闭义务。
737
+ * @param {string} projectId
738
+ * @returns {Promise<any[]>}
739
+ */
740
+ async refreshStaleness(projectId) {
741
+ const project = requireProject(projectId);
742
+ const data = store.readAll(project.id);
743
+ const current = latestBuild(data.builds);
744
+ const stale = findStaleObligations({
745
+ obligations: data.obligations,
746
+ checks: data.checks,
747
+ implementationDigest: current?.implementationDigest ?? null,
748
+ originalDigest: project.capabilityHash ?? null,
749
+ });
750
+ /** @type {any[]} */
751
+ const reopened = [];
752
+ for (const entry of stale) {
753
+ const obligation = data.obligations.find(
754
+ (/** @type {any} */ item) => item.id === entry.obligationId,
755
+ );
756
+ if (!obligation) continue;
757
+ const next = {
758
+ ...obligation,
759
+ status: "open",
760
+ note: `stale: ${entry.reasons.join(",")}`,
761
+ version: Number(obligation.version ?? 1) + 1,
762
+ };
763
+ store.appendRecord(project.id, "obligations", next);
764
+ reopened.push({ obligationId: next.id, reasons: entry.reasons });
765
+ store.audit(project.id, {
766
+ actor: "agent",
767
+ action: "obligation/stale",
768
+ target: next.id,
769
+ detail: { reasons: entry.reasons },
770
+ });
771
+ }
772
+ if (reopened.length > 0) store.touch(project.id);
773
+ return reopened;
774
+ },
775
+
776
+ /**
777
+ * 读审计日志(只读)。
778
+ * @param {string} projectId
779
+ * @returns {any[]}
780
+ */
781
+ readAudit(projectId) {
782
+ const project = requireProject(projectId);
783
+ return store.readAudit(project.id);
784
+ },
785
+
786
+ /** @param {string} projectId */
787
+ readRunData(projectId) {
788
+ const data = store.readAll(projectId);
789
+ return { builds: data.builds, checks: data.checks, obligations: data.obligations };
790
+ },
791
+
792
+ /**
793
+ * 循环状态:轮次、停止条件、未关闭义务。
794
+ * @param {string} projectId
795
+ * @param {Record<string, any>} [stop]
796
+ * @returns {Promise<Record<string, any>>}
797
+ */
798
+ async loopStatus(projectId, stop) {
799
+ const project = requireProject(projectId);
800
+ const data = store.readAll(project.id);
801
+ const summary = summarizeRuns({
802
+ builds: data.builds,
803
+ checks: data.checks,
804
+ obligations: data.obligations,
805
+ });
806
+ const verdict = evaluateStop({
807
+ builds: data.builds,
808
+ checks: data.checks,
809
+ openObligations: summary.obligations.open,
810
+ stop,
811
+ });
812
+ return {
813
+ ...summary,
814
+ stop: verdict,
815
+ openObligations: data.obligations.filter((item) => item.status === "open"),
816
+ };
817
+ },
818
+
819
+ // ---------- 自动循环(M3) ----------
820
+
821
+ /**
822
+ * 跑一轮自动循环:构建 → 对带 recipe 的未关闭义务逐个检查 → 通过就关闭 → 停止条件。
823
+ * 不猜「像不像」:只跑义务自带的 check recipe,没有 recipe 的义务保持 open 并列入 needsRecipe。
824
+ * @param {string} projectId
825
+ * @param {{
826
+ * command: string, cwd?: string, round?: number, timeoutMs?: number,
827
+ * maxRounds?: number, stop?: Record<string, any>,
828
+ * }} input
829
+ * @returns {Promise<Record<string, any>>}
830
+ */
831
+ async advanceLoop(projectId, input) {
832
+ const project = requireProject(projectId);
833
+ const requestedMax = Number(input?.maxRounds);
834
+ const maxRounds = Number.isInteger(requestedMax) && requestedMax > 0 ? requestedMax : 1;
835
+ /** @type {any[]} */
836
+ const rounds = [];
837
+ for (let index = 0; index < maxRounds; index += 1) {
838
+ const build = await this.startBuild(project.id, {
839
+ command: input?.command,
840
+ cwd: input?.cwd,
841
+ timeoutMs: input?.timeoutMs,
842
+ });
843
+ /** @type {any[]} */
844
+ const opened = store
845
+ .readRecords(project.id, "obligations")
846
+ .filter((item) => item.status === "open");
847
+ const withRecipe = opened.filter((item) => item.check != null);
848
+ const needsRecipe = opened.filter((item) => item.check == null).map((item) => item.id);
849
+ /** @type {any[]} */
850
+ const checked = [];
851
+ // 构建失败时不做检查:在坏实现上跑检查没有意义,也容易产生误导性的绿灯。
852
+ if (build.build.status === "pass") {
853
+ for (const obligation of withRecipe) {
854
+ const recipe = obligation.check;
855
+ const result = await this.runCheck(project.id, {
856
+ obligationId: obligation.id,
857
+ checker: recipe.checker,
858
+ command: recipe.command,
859
+ cwd: recipe.cwd ?? input?.cwd,
860
+ expect: recipe.expect ?? {},
861
+ timeoutMs: recipe.timeoutMs,
862
+ });
863
+ let closed = null;
864
+ if (result.check.verdict === "pass") {
865
+ closed = await this.closeObligation(project.id, obligation.id, {
866
+ checkId: result.check.id,
867
+ note: "advanceLoop",
868
+ });
869
+ }
870
+ checked.push({
871
+ obligationId: obligation.id,
872
+ verdict: result.check.verdict,
873
+ status: closed ? "pass" : "open",
874
+ });
875
+ }
876
+ }
877
+ const status = await this.loopStatus(project.id, input?.stop);
878
+ rounds.push({
879
+ round: build.build.round,
880
+ buildStatus: build.build.status,
881
+ checked,
882
+ needsRecipe,
883
+ openObligations: status.obligations.open,
884
+ stop: status.stop,
885
+ });
886
+ if (status.stop.stop) break;
887
+ if (status.obligations.open === 0) break;
888
+ }
889
+ const final = await this.loopStatus(project.id, input?.stop);
890
+ return {
891
+ rounds,
892
+ closed: final.obligations.pass,
893
+ open: final.obligations.open,
894
+ stop: final.stop,
895
+ openObligations: final.openObligations,
896
+ summary: `跑了 ${rounds.length} 轮;关闭 ${final.obligations.pass} 条;停止条件 ${final.stop.reason}`,
897
+ };
898
+ },
899
+
900
+ // ---------- builder 会话(M2.5) ----------
901
+
902
+ /**
903
+ * 起一个 builder 会话:只把 spec pack 投喂给它,不让它拿到原件工具。
904
+ * 说明:DSH 的 agent preset 目前无法用 bundle 名组合(见 runtime §10.7),
905
+ * 因此这里用「独立会话 + 只投喂规格」做信息流隔离,而不是工具白名单。
906
+ * @param {string} projectId
907
+ * @param {{
908
+ * cwd: string, prompt?: string, featureIds?: string[], timeoutMs?: number,
909
+ * allowResearchTier?: boolean, reason?: string,
910
+ * }} input
911
+ * @returns {Promise<Record<string, any>>}
912
+ */
913
+ async startBuilder(projectId, input) {
914
+ const project = requireProject(projectId);
915
+ if (!sessions) {
916
+ throw new CasefileActionError(
917
+ "builder-unavailable",
918
+ "会话服务不可用:宿主里没有 sessionController(headless 组合可能没有)",
919
+ );
920
+ }
921
+ const cwd = String(input?.cwd ?? "").trim();
922
+ if (cwd === "") throw new CasefileInputError("invalid-input", "cwd 不能为空");
923
+ // 授权档闸门:research 档默认不允许「复刻」这种高争议动作,必须显式覆盖并留审计。
924
+ if (project.authTier === "research" && input?.allowResearchTier !== true) {
925
+ throw new CasefileActionError(
926
+ "auth-tier-blocked",
927
+ `项目授权档是 research:默认不许起复刻构建。确认有权复刻后,用 allowResearchTier 显式覆盖(会写审计)。`,
928
+ );
929
+ }
930
+ if (project.authTier === "research" && input?.allowResearchTier === true) {
931
+ store.audit(project.id, {
932
+ actor: "agent",
933
+ action: "auth/research-override",
934
+ target: project.id,
935
+ detail: { reason: String(input?.reason ?? "").slice(0, 500) },
936
+ });
937
+ }
938
+ const data = store.readAll(project.id);
939
+ const pack = buildSpecPack({
940
+ project,
941
+ ...data,
942
+ ...(Array.isArray(input?.featureIds) && input.featureIds.length > 0
943
+ ? {
944
+ claims: data.claims.filter((item) =>
945
+ input.featureIds?.some((id) => (item.featureIds ?? []).includes(id)),
946
+ ),
947
+ }
948
+ : {}),
949
+ });
950
+ if (pack.claims.length === 0) {
951
+ throw new CasefileActionError(
952
+ "nothing-selected",
953
+ "没有选中的结论:builder 需要至少一条规格,先勾选结论",
954
+ );
955
+ }
956
+ const prompt =
957
+ typeof input?.prompt === "string" && input.prompt.trim() !== ""
958
+ ? input.prompt
959
+ : [
960
+ "你在做一次「按规格复刻」的构建任务。",
961
+ "",
962
+ "只允许依据下面的规格包实现,不要读取或寻找原始目标;规格里没写的不要臆测。",
963
+ "",
964
+ "```markdown",
965
+ renderSpecMarkdown(redactPack(pack)),
966
+ "```",
967
+ "",
968
+ "完成后简述你实现了哪些功能、哪些做不到(以 UNKNOWN 记录原因)。",
969
+ ].join("\n");
970
+ const created = await sessions.create({ cwd });
971
+ const sessionId = String(created.sessionId);
972
+ await sessions.prompt({ sessionId, text: prompt });
973
+ const record = {
974
+ id: newId("builder"),
975
+ sessionId,
976
+ cwd,
977
+ round: nextRound(store.readRecords(project.id, "builds")),
978
+ startedAt: nowIso(),
979
+ featureIds: Array.isArray(input?.featureIds) ? input.featureIds.map(String) : [],
980
+ claims: pack.claims.length,
981
+ };
982
+ store.appendRecord(project.id, "builds", {
983
+ id: `builder-${record.id}`,
984
+ round: record.round,
985
+ command: `builder-session:${sessionId}`,
986
+ cwd,
987
+ status: "running",
988
+ exitCode: null,
989
+ implementationDigest: null,
990
+ startedAt: record.startedAt,
991
+ endedAt: null,
992
+ detail: `投喂 ${pack.claims.length} 条结论`,
993
+ artifacts: [],
994
+ builderSessionId: sessionId,
995
+ });
996
+ const attestation = buildAttestation({
997
+ project,
998
+ prompt,
999
+ pack,
1000
+ sessionId,
1001
+ builderId: record.id,
1002
+ override: input?.allowResearchTier === true,
1003
+ reason: input?.reason,
1004
+ });
1005
+ store.appendRecord(project.id, "attestations", attestation);
1006
+ store.touch(project.id);
1007
+ store.audit(project.id, {
1008
+ actor: "agent",
1009
+ action: "builder/start",
1010
+ target: sessionId,
1011
+ detail: {
1012
+ round: record.round,
1013
+ claims: pack.claims.length,
1014
+ cleanRoomInstruction: attestation.cleanRoomInstruction,
1015
+ promptDigest: attestation.shortPromptDigest,
1016
+ },
1017
+ });
1018
+ return {
1019
+ builder: record,
1020
+ promptLength: prompt.length,
1021
+ attestation: {
1022
+ promptDigest: attestation.shortPromptDigest,
1023
+ cleanRoomInstruction: attestation.cleanRoomInstruction,
1024
+ toolIsolation: attestation.toolIsolation,
1025
+ },
1026
+ };
1027
+ },
1028
+
1029
+ /**
1030
+ * 等 builder 会话停下(idle / 需要输入 / 超时)。
1031
+ * @param {string} projectId
1032
+ * @param {{ sessionId: string, timeoutMs?: number }} input
1033
+ * @returns {Promise<Record<string, any>>}
1034
+ */
1035
+ async awaitBuilder(projectId, input) {
1036
+ requireProject(projectId);
1037
+ if (!sessions) {
1038
+ throw new CasefileActionError("builder-unavailable", "会话服务不可用");
1039
+ }
1040
+ const sessionId = String(input?.sessionId ?? "");
1041
+ if (sessionId === "") throw new CasefileInputError("invalid-input", "sessionId 不能为空");
1042
+ const result = await sessions.wait({ sessionId, timeoutMs: input?.timeoutMs });
1043
+ return {
1044
+ sessionId,
1045
+ reason: result.reason,
1046
+ output: result.output ?? null,
1047
+ stopped: result.reason === "idle" || result.reason === "input-required",
1048
+ };
1049
+ },
1050
+
1051
+ /**
1052
+ * 端到端一轮:起 builder(可选)→ 等它停 → 构建 → 检查 → 关闭 → 报告停止条件。
1053
+ * 这是 spec 里「builder 停下 → 自动 build → 自动 check」的落点。
1054
+ * @param {string} projectId
1055
+ * @param {{
1056
+ * builder?: {
1057
+ * cwd: string, prompt?: string, featureIds?: string[], timeoutMs?: number,
1058
+ * allowResearchTier?: boolean, reason?: string,
1059
+ * },
1060
+ * command?: string, cwd?: string, maxRounds?: number, timeoutMs?: number,
1061
+ * stop?: Record<string, any>,
1062
+ * }} input
1063
+ * @returns {Promise<Record<string, any>>}
1064
+ */
1065
+ async runCycle(projectId, input) {
1066
+ const project = requireProject(projectId);
1067
+ /** @type {Record<string, any> | null} */
1068
+ let builder = null;
1069
+ if (input?.builder != null) {
1070
+ const started = await this.startBuilder(project.id, {
1071
+ cwd: input.builder.cwd,
1072
+ prompt: input.builder.prompt,
1073
+ featureIds: input.builder.featureIds,
1074
+ allowResearchTier: input.builder.allowResearchTier,
1075
+ reason: input.builder.reason,
1076
+ });
1077
+ const awaited = await this.awaitBuilder(project.id, {
1078
+ sessionId: started.builder.sessionId,
1079
+ timeoutMs: input.builder.timeoutMs ?? 120_000,
1080
+ });
1081
+ builder = {
1082
+ sessionId: started.builder.sessionId,
1083
+ claims: started.builder.claims,
1084
+ reason: awaited.reason,
1085
+ };
1086
+ }
1087
+ const command = input?.command;
1088
+ if (typeof command !== "string" || command.trim() === "") {
1089
+ throw new CasefileInputError("invalid-input", "runCycle 需要 command(构建命令)");
1090
+ }
1091
+ const loop = await this.advanceLoop(project.id, {
1092
+ command,
1093
+ cwd: input?.cwd,
1094
+ maxRounds: input?.maxRounds,
1095
+ timeoutMs: input?.timeoutMs,
1096
+ stop: input?.stop,
1097
+ });
1098
+ return {
1099
+ builder,
1100
+ loop,
1101
+ stop: loop.stop,
1102
+ summary: `${builder ? `builder ${builder.reason};` : ""}${loop.summary}`,
1103
+ };
1104
+ },
1105
+
1106
+ // ---------- 跨项目总览(M4) ----------
1107
+
1108
+ /**
1109
+ * 所有项目的只读总览。
1110
+ * @returns {Promise<Record<string, any>>}
1111
+ */
1112
+ async overview() {
1113
+ const projects = store.listProjects();
1114
+ /** @type {Record<string, any>} */
1115
+ const dataById = {};
1116
+ for (const project of projects) {
1117
+ dataById[project.id] = store.readAll(project.id);
1118
+ }
1119
+ const overview = buildOverview(projects, dataById);
1120
+ return { ...overview, summary: summarizeOverview(overview) };
1121
+ },
1122
+
1123
+ // ---------- 覆盖率 / 关闭 / 报告(M3 收尾) ----------
1124
+
1125
+ /**
1126
+ * 项目覆盖率与关闭闸门状态(只读预览,不写状态)。
1127
+ * @param {string} projectId
1128
+ * @param {{ minCoverage?: number, maxCheckAgeMs?: number }} [options]
1129
+ * @returns {Promise<Record<string, any>>}
1130
+ */
1131
+ async closePreview(projectId, options = {}) {
1132
+ const project = requireProject(projectId);
1133
+ const data = store.readAll(project.id);
1134
+ const current = latestBuild(data.builds);
1135
+ const verdict = evaluateClose({
1136
+ obligations: data.obligations,
1137
+ unknowns: data.unknowns,
1138
+ checks: data.checks,
1139
+ implementationDigest: current?.implementationDigest ?? null,
1140
+ minCoverage: options.minCoverage,
1141
+ maxCheckAgeMs: options.maxCheckAgeMs,
1142
+ });
1143
+ return { project: project.id, ...verdict };
1144
+ },
1145
+
1146
+ /**
1147
+ * 关闭项目(硬门不通过就拒绝,且写审计)。
1148
+ * @param {string} projectId
1149
+ * @param {{ minCoverage?: number, note?: string }} [options]
1150
+ * @returns {Promise<Record<string, any>>}
1151
+ */
1152
+ async closeProject(projectId, options = {}) {
1153
+ const project = requireProject(projectId);
1154
+ if (project.state === "closed") return { project, alreadyClosed: true };
1155
+ const preview = await this.closePreview(project.id, options);
1156
+ if (!preview.ok) {
1157
+ throw Object.assign(new Error(`项目还不能关闭:${preview.blockers.join("、")}`), {
1158
+ code: "coverage-not-met",
1159
+ blockers: preview.blockers,
1160
+ });
1161
+ }
1162
+ const next = {
1163
+ ...project,
1164
+ state: "closed",
1165
+ closedAt: nowIso(),
1166
+ coverage: preview.coverage,
1167
+ note: options?.note == null ? "" : String(options.note).slice(0, 2000),
1168
+ };
1169
+ store.writeJson(join(store.projectDir(project.id), "project.json"), next);
1170
+ store.audit(project.id, {
1171
+ actor: "agent",
1172
+ action: "project/close",
1173
+ target: project.id,
1174
+ detail: { coverage: preview.coverage.ratio.toFixed(2) },
1175
+ });
1176
+ return { project: next, coverage: preview.coverage };
1177
+ },
1178
+
1179
+ /**
1180
+ * 导出验收报告(md + json)。
1181
+ * @param {string} projectId
1182
+ * @returns {Promise<Record<string, any>>}
1183
+ */
1184
+ async exportReport(projectId) {
1185
+ const project = requireProject(projectId);
1186
+ const data = store.readAll(project.id);
1187
+ const current = latestBuild(data.builds);
1188
+ const coverage = computeCoverage(data.obligations);
1189
+ const stop = evaluateStop({
1190
+ builds: data.builds,
1191
+ checks: data.checks,
1192
+ openObligations: coverage.open,
1193
+ });
1194
+ const report = buildReport({ project, data, coverage, stop });
1195
+ const stamp = String(report.generatedAt).replace(/[:.]/g, "-");
1196
+ const dir = join(store.projectDir(project.id), "reports", stamp);
1197
+ const md = join(dir, "report.md");
1198
+ const json = join(dir, "report.json");
1199
+ mkdirSync(dir, { recursive: true });
1200
+ writeFileSync(md, `${renderReportMarkdown(report)}\n`, "utf8");
1201
+ writeFileSync(json, `${JSON.stringify(report, null, 2)}\n`, "utf8");
1202
+ store.audit(project.id, {
1203
+ actor: "agent",
1204
+ action: "report/export",
1205
+ target: dir,
1206
+ detail: {
1207
+ coverage: coverage.ratio.toFixed(2),
1208
+ digest: shortDigest(current?.implementationDigest),
1209
+ },
1210
+ });
1211
+ return {
1212
+ path: dir,
1213
+ files: ["report.md", "report.json"],
1214
+ coverage,
1215
+ summary: `报告已写入 ${dir}(覆盖率 ${(coverage.ratio * 100).toFixed(0)}%)`,
1216
+ };
1217
+ },
1218
+
1219
+ // ---------- 规格包 ----------
1220
+
1221
+ /**
1222
+ * @param {string} projectId
1223
+ * @param {{ redact?: boolean, redactOptions?: Record<string, any> }} [options]
1224
+ * @returns {Promise<Record<string, any>>}
1225
+ */
1226
+ async exportSpecPack(projectId, options = {}) {
1227
+ const project = requireProject(projectId);
1228
+ const data = store.readAll(project.id);
1229
+ const pack = buildSpecPack({ project, ...data });
1230
+ if (pack.claims.length === 0) {
1231
+ throw new CasefileActionError(
1232
+ "nothing-selected",
1233
+ "没有选中的结论:先勾选要导出的结论(case_claim select)",
1234
+ );
1235
+ }
1236
+ const written = writeSpecPack({
1237
+ projectDir: store.projectDir(project.id),
1238
+ pack,
1239
+ redact: options?.redact !== false,
1240
+ redactOptions: {
1241
+ home: process.env.HOME ?? process.env.USERPROFILE,
1242
+ cwd: process.cwd(),
1243
+ extraPaths: [dataRoot],
1244
+ ...(options?.redactOptions ?? {}),
1245
+ },
1246
+ });
1247
+ store.audit(project.id, {
1248
+ actor: "agent",
1249
+ action: "spec/export",
1250
+ target: written.dir,
1251
+ detail: { claims: pack.claims.length, redact: options?.redact !== false },
1252
+ });
1253
+ return {
1254
+ data: {
1255
+ path: written.dir,
1256
+ files: written.files.map((file) => file.split("/").slice(-1)[0]),
1257
+ claims: pack.claims.length,
1258
+ evidence: pack.evidence.length,
1259
+ features: pack.features.length,
1260
+ openUnknowns: pack.unknowns.length,
1261
+ integrity: shortDigest(pack.integrity),
1262
+ },
1263
+ summary: `规格包已写入 ${written.dir}(${pack.claims.length} 条结论 / ${pack.unknowns.length} 个未知项)`,
1264
+ };
1265
+ },
1266
+ };
1267
+ }
1268
+
1269
+ /** @typedef {ReturnType<typeof createActions>} CasefileActions */