@kangyishuai/dsh-casefile 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/actions.js CHANGED
@@ -18,6 +18,7 @@ import { buildSpecPack, redactPack, renderSpecMarkdown, writeSpecPack } from "./
18
18
  import { buildBundle } from "./core/bundle.js";
19
19
  import { createCheckers } from "./core/checks.js";
20
20
  import { hashTree, shortDigest } from "./core/digest.js";
21
+ import { validateIngestPayload } from "./core/ingest.js";
21
22
  import { awaitLogin } from "./core/login-wait.js";
22
23
  import { gradeCapabilities } from "./core/manifest.js";
23
24
  import {
@@ -273,7 +274,8 @@ export function createActions(options) {
273
274
  : null;
274
275
  const record = normalizeEvidence({
275
276
  ...input,
276
- artifact: archived,
277
+ // 外部摄入时,同一份报告可以同时是多条证据的出处:允许直接传入已归档对象。
278
+ artifact: archived ?? input?.artifact ?? null,
277
279
  sessionId: input?.sessionId ?? sessionOf(exec) ?? null,
278
280
  });
279
281
  store.appendRecord(project.id, "evidence", record);
@@ -1214,6 +1216,115 @@ export function createActions(options) {
1214
1216
  return { ...overview, summary: summarizeOverview(overview) };
1215
1217
  },
1216
1218
 
1219
+ // ---------- 外部报告摄入 ----------
1220
+
1221
+ /**
1222
+ * 摄入外部 agent 的产出(通用契约)。只记录、不背书:authority=external。
1223
+ * @param {string} projectId
1224
+ * @param {any} payload
1225
+ * @param {{ dryRun?: boolean }} [options]
1226
+ * @returns {Promise<Record<string, any>>}
1227
+ */
1228
+ async ingestReport(projectId, payload, options = {}) {
1229
+ const project = requireProject(projectId);
1230
+ const normalized = validateIngestPayload(payload);
1231
+ const dryRun = options?.dryRun === true;
1232
+
1233
+ // 报告本体若有路径,归档进项目目录(/tmp 会过期,过期就没法复算)
1234
+ const archived =
1235
+ normalized.source.reportPath == null
1236
+ ? null
1237
+ : store.archiveArtifact(project.id, normalized.source.reportPath);
1238
+
1239
+ if (dryRun) {
1240
+ return {
1241
+ dryRun: true,
1242
+ source: normalized.source,
1243
+ wouldCreate: {
1244
+ evidence: normalized.evidence.length,
1245
+ claims: normalized.claims.length,
1246
+ unknowns: normalized.unknowns.length,
1247
+ artifact: archived,
1248
+ },
1249
+ summary: `预演:将写入 ${normalized.evidence.length} 证据 / ${normalized.claims.length} 结论 / ${normalized.unknowns.length} 未知项`,
1250
+ };
1251
+ }
1252
+
1253
+ const producer = {
1254
+ tool: normalized.source.tool,
1255
+ version: normalized.source.version,
1256
+ mode: normalized.source.mode,
1257
+ outputKind: "external-report",
1258
+ accessConfirmedByUser: true,
1259
+ confirmationNote: "外部 agent 产出,casefile 只记录与引用;其判断归原工具,casefile 不背书",
1260
+ };
1261
+
1262
+ /** @type {string[]} */
1263
+ const evidenceIds = [];
1264
+ for (const item of normalized.evidence) {
1265
+ const record = await this.addEvidence(project.id, {
1266
+ summary: item.summary,
1267
+ kind: item.kind,
1268
+ authority: item.authority,
1269
+ confidence: "observed",
1270
+ limitations: item.limitations,
1271
+ refs: item.refs,
1272
+ ...(item.artifactPath == null ? {} : { artifactPath: item.artifactPath }),
1273
+ ...(archived == null ? {} : { artifact: archived }),
1274
+ producer,
1275
+ });
1276
+ evidenceIds.push(record.id);
1277
+ }
1278
+
1279
+ /** @type {string[]} */
1280
+ const claimIds = [];
1281
+ for (const item of normalized.claims) {
1282
+ const record = await this.addClaim(project.id, {
1283
+ text: item.text,
1284
+ kind: item.kind,
1285
+ status: item.status,
1286
+ limitations: item.limitations,
1287
+ evidenceIds: item.evidenceIndexes.map(
1288
+ (/** @type {number} */ index) => evidenceIds[index],
1289
+ ),
1290
+ });
1291
+ claimIds.push(record.id);
1292
+ }
1293
+
1294
+ /** @type {string[]} */
1295
+ const unknownIds = [];
1296
+ for (const item of normalized.unknowns) {
1297
+ const record = await this.addUnknown(project.id, {
1298
+ text: item.text,
1299
+ severity: item.severity,
1300
+ });
1301
+ unknownIds.push(record.id);
1302
+ }
1303
+
1304
+ store.audit(project.id, {
1305
+ actor: "agent",
1306
+ action: "ingest/external-report",
1307
+ target: project.id,
1308
+ detail: {
1309
+ tool: producer.tool,
1310
+ version: producer.version,
1311
+ evidence: evidenceIds.length,
1312
+ claims: claimIds.length,
1313
+ unknowns: unknownIds.length,
1314
+ artifactDigest: archived?.sha256 ?? null,
1315
+ },
1316
+ });
1317
+
1318
+ return {
1319
+ source: normalized.source,
1320
+ evidenceIds,
1321
+ claimIds,
1322
+ unknownIds: unknownIds.filter((item) => item !== ""),
1323
+ artifact: archived,
1324
+ summary: `已摄入 ${evidenceIds.length} 证据 / ${claimIds.length} 结论 / ${unknownIds.length} 未知项(来源 ${producer.tool})`,
1325
+ };
1326
+ },
1327
+
1217
1328
  // ---------- 自主性阶梯 ----------
1218
1329
 
1219
1330
  /**
@@ -0,0 +1,213 @@
1
+ // @ts-check
2
+ // core/ingest.js:外部 agent 产出报告的**通用摄入契约**。
3
+ //
4
+ // 为什么需要:Craft / 其他逆向 agent 会产出自己的报告。casefile 的立场是
5
+ // "只记录、不背书"——所以这里只接受**已经成形的结论与证据描述**,不解释对方语义,
6
+ // 也不把它的判断当成自己的判断(authority 固定 external、producer 记录来源)。
7
+ //
8
+ // 契约形状(版本 1):
9
+ // {
10
+ // sources: { tool, version?, mode?, producedAt?, reportPath? },
11
+ // evidence: [ { summary, kind?, authority?, limitations?, refs?, artifactPath? } ],
12
+ // claims: [ { text, kind?, status?, evidenceIds?: number[] , limitations?, refs? } ],
13
+ // unknowns: [ { text, severity? } ]
14
+ // }
15
+ // claims.evidenceIds 用**数组下标**引用本次 payload 里的 evidence,摄入时映射成真实 id。
16
+ // 下标越界直接报错——宁可拒绝,也不能静默丢引用(那会让结论变成无出处)。
17
+
18
+ /** 摄入契约版本;形状变化时递增。 */
19
+ export const INGEST_VERSION = 1;
20
+
21
+ const EVIDENCE_KINDS = [
22
+ "structure",
23
+ "behavior",
24
+ "string",
25
+ "screen",
26
+ "network",
27
+ "artifact",
28
+ "other",
29
+ ];
30
+ const CLAIM_KINDS = ["structure", "behavior", "string", "other"];
31
+ const CLAIM_STATUS = ["observed", "derived", "inferred"];
32
+ const SEVERITIES = ["low", "medium", "high"];
33
+ const PRODUCER_MODES = ["headful", "headless", "api", "archive", "manual", "stealth", "unknown"];
34
+
35
+ /**
36
+ * @param {unknown} value
37
+ * @param {string} field
38
+ * @returns {string}
39
+ */
40
+ function needText(value, field) {
41
+ if (typeof value !== "string" || value.trim() === "") {
42
+ throw Object.assign(new Error(`${field} 必须是非空字符串`), { code: "invalid-input" });
43
+ }
44
+ return value.trim();
45
+ }
46
+
47
+ /**
48
+ * @param {unknown} value
49
+ * @param {readonly string[]} allowed
50
+ * @param {string} field
51
+ * @param {string} fallback
52
+ * @returns {string}
53
+ */
54
+ function oneOf(value, allowed, field, fallback) {
55
+ if (value == null) return fallback;
56
+ const text = String(value);
57
+ if (!allowed.includes(text)) {
58
+ throw Object.assign(new Error(`${field} 只能是 ${allowed.join(" / ")}:${text}`), {
59
+ code: "invalid-input",
60
+ });
61
+ }
62
+ return text;
63
+ }
64
+
65
+ /**
66
+ * @param {unknown} value
67
+ * @param {string} field
68
+ * @returns {string[]}
69
+ */
70
+ function textList(value, field) {
71
+ if (value == null) return [];
72
+ if (!Array.isArray(value)) {
73
+ throw Object.assign(new Error(`${field} 必须是字符串数组`), { code: "invalid-input" });
74
+ }
75
+ return value.map((/** @type {any} */ item, /** @type {number} */ index) =>
76
+ needText(item, `${field}[${index}]`),
77
+ );
78
+ }
79
+
80
+ /**
81
+ * 校验并归一化摄入 payload。
82
+ * @param {any} raw
83
+ * @returns {{
84
+ * version: number,
85
+ * source: { tool: string, version: string | null, mode: string, producedAt: string | null, reportPath: string | null },
86
+ * evidence: Array<Record<string, any>>,
87
+ * claims: Array<Record<string, any>>,
88
+ * unknowns: Array<Record<string, any>>,
89
+ * }}
90
+ */
91
+ export function validateIngestPayload(raw) {
92
+ if (raw == null || typeof raw !== "object" || Array.isArray(raw)) {
93
+ throw Object.assign(new Error("payload 必须是对象"), { code: "invalid-input" });
94
+ }
95
+ const version = raw.version == null ? INGEST_VERSION : Number(raw.version);
96
+ if (version !== INGEST_VERSION) {
97
+ throw Object.assign(
98
+ new Error(`不支持的摄入契约版本:${String(raw.version)}(当前 ${INGEST_VERSION})`),
99
+ {
100
+ code: "invalid-input",
101
+ },
102
+ );
103
+ }
104
+
105
+ const sourceRaw = raw.source ?? raw.sources ?? {};
106
+ const source = {
107
+ tool: needText(sourceRaw?.tool, "source.tool"),
108
+ version: sourceRaw?.version == null ? null : needText(sourceRaw.version, "source.version"),
109
+ mode: oneOf(sourceRaw?.mode, PRODUCER_MODES, "source.mode", "unknown"),
110
+ producedAt:
111
+ sourceRaw?.producedAt == null ? null : needText(sourceRaw.producedAt, "source.producedAt"),
112
+ reportPath:
113
+ sourceRaw?.reportPath == null ? null : needText(sourceRaw.reportPath, "source.reportPath"),
114
+ };
115
+
116
+ const evidenceRaw = Array.isArray(raw.evidence) ? raw.evidence : [];
117
+ const evidence = evidenceRaw.map((/** @type {any} */ item, /** @type {number} */ index) => ({
118
+ summary: needText(item?.summary, `evidence[${index}].summary`),
119
+ kind: oneOf(item?.kind, EVIDENCE_KINDS, `evidence[${index}].kind`, "other"),
120
+ authority: "external",
121
+ limitations: textList(item?.limitations, `evidence[${index}].limitations`),
122
+ refs: textList(item?.refs, `evidence[${index}].refs`),
123
+ artifactPath:
124
+ item?.artifactPath == null
125
+ ? null
126
+ : needText(item.artifactPath, `evidence[${index}].artifactPath`),
127
+ }));
128
+
129
+ const claimsRaw = Array.isArray(raw.claims) ? raw.claims : [];
130
+ const claims = claimsRaw.map((/** @type {any} */ item, /** @type {number} */ index) => {
131
+ /** @type {number[]} */
132
+ let mapped = [];
133
+ if (item?.evidenceIds != null) {
134
+ if (!Array.isArray(item.evidenceIds)) {
135
+ throw Object.assign(new Error(`claims[${index}].evidenceIds 必须是数组下标`), {
136
+ code: "invalid-input",
137
+ });
138
+ }
139
+ mapped = item.evidenceIds.map((/** @type {any} */ value, /** @type {number} */ at) => {
140
+ const num = Number(value);
141
+ if (!Number.isInteger(num) || num < 0 || num >= evidence.length) {
142
+ throw Object.assign(
143
+ new Error(
144
+ `claims[${index}].evidenceIds[${at}] 越界:${String(value)}(本次只有 ${evidence.length} 条证据)`,
145
+ ),
146
+ { code: "invalid-input" },
147
+ );
148
+ }
149
+ return num;
150
+ });
151
+ }
152
+ return {
153
+ text: needText(item?.text, `claims[${index}].text`),
154
+ kind: oneOf(item?.kind, CLAIM_KINDS, `claims[${index}].kind`, "structure"),
155
+ status: oneOf(item?.status, CLAIM_STATUS, `claims[${index}].status`, "observed"),
156
+ limitations: textList(item?.limitations, `claims[${index}].limitations`),
157
+ refs: textList(item?.refs, `claims[${index}].refs`),
158
+ evidenceIndexes: [...new Set(mapped)],
159
+ };
160
+ });
161
+
162
+ const unknownsRaw = Array.isArray(raw.unknowns) ? raw.unknowns : [];
163
+ const unknowns = unknownsRaw.map((/** @type {any} */ item, /** @type {number} */ index) => ({
164
+ text: needText(item?.text, `unknowns[${index}].text`),
165
+ severity: oneOf(item?.severity, SEVERITIES, `unknowns[${index}].severity`, "low"),
166
+ }));
167
+
168
+ return { version, source, evidence, claims, unknowns };
169
+ }
170
+
171
+ /**
172
+ * 契约说明(`case_ingest schema` 直接返回它,方便别的 agent 生成正确格式)。
173
+ * @returns {Record<string, any>}
174
+ */
175
+ export function describeIngestSchema() {
176
+ return {
177
+ version: INGEST_VERSION,
178
+ shape: {
179
+ source: {
180
+ tool: "string (必填)",
181
+ version: "string?",
182
+ mode: PRODUCER_MODES,
183
+ producedAt: "ISO string?",
184
+ reportPath: "绝对路径?",
185
+ },
186
+ evidence: [
187
+ {
188
+ summary: "string (必填)",
189
+ kind: EVIDENCE_KINDS,
190
+ limitations: "string[]",
191
+ refs: "string[]",
192
+ artifactPath: "绝对路径?",
193
+ },
194
+ ],
195
+ claims: [
196
+ {
197
+ text: "string (必填)",
198
+ kind: CLAIM_KINDS,
199
+ status: CLAIM_STATUS,
200
+ evidenceIds: "数字下标数组(引用本次 evidence)",
201
+ limitations: "string[]",
202
+ },
203
+ ],
204
+ unknowns: [{ text: "string (必填)", severity: SEVERITIES }],
205
+ },
206
+ rules: [
207
+ "authority 固定为 external:casefile 只记录、不背书",
208
+ "claims.evidenceIds 用数组下标;越界直接报错,不静默丢引用",
209
+ "source.reportPath 若给出,会归档进项目目录并记录 sha256(/tmp 会过期)",
210
+ "所有 limitations 原样保留:对方没说的不确定性,casefile 不替它补",
211
+ ],
212
+ };
213
+ }
package/lib/service.js CHANGED
@@ -350,6 +350,8 @@ export class CasefileService extends TypertRemoteService {
350
350
  closePreview: (projectId, options) => this.actions.closePreview(projectId, options),
351
351
  exportReport: (projectId, options) => this.actions.exportReport(projectId, options),
352
352
  exportBundle: (projectId, options) => this.actions.exportBundle(projectId, options),
353
+ ingestReport: (projectId, payload, options) =>
354
+ this.actions.ingestReport(projectId, payload, options),
353
355
  setAutonomy: (projectId, input) => this.actions.setAutonomy(projectId, input),
354
356
  autonomyStatus: (projectId) => this.actions.autonomyStatus(projectId),
355
357
  advanceLoop: (projectId, input) => this.actions.advanceLoop(projectId, input),
@@ -665,6 +667,20 @@ export class CasefileService extends TypertRemoteService {
665
667
  }
666
668
  }
667
669
 
670
+ /**
671
+ * @param {string} projectId
672
+ * @param {any} payload
673
+ * @param {{ dryRun?: boolean }} [options]
674
+ * @returns {Promise<Record<string, any>>}
675
+ */
676
+ async ingestReport(projectId, payload, options) {
677
+ try {
678
+ return await this.actions.ingestReport(projectId, payload, options ?? {});
679
+ } catch (error) {
680
+ fail(error);
681
+ }
682
+ }
683
+
668
684
  /**
669
685
  * @param {string} projectId
670
686
  * @param {{ level?: string, budget?: Record<string, any> | null }} input
@@ -894,6 +910,7 @@ declareRemote(CasefileService, "runCycle");
894
910
  declareRemote(CasefileService, "closeProject");
895
911
  declareRemote(CasefileService, "exportReport");
896
912
  declareRemote(CasefileService, "exportBundle");
913
+ declareRemote(CasefileService, "ingestReport");
897
914
  declareRemote(CasefileService, "setAutonomy");
898
915
  declareRemote(CasefileService, "autonomyStatus");
899
916
  declareRemote(CasefileService, "advanceLoop");
package/lib/tools.js CHANGED
@@ -7,6 +7,7 @@
7
7
  // 让模型读到稳定错误码并自行纠正;
8
8
  // - 每个工具都接受 projectId;省略时用「本会话最近打开的项目」(由 service 维护)。
9
9
 
10
+ import { describeIngestSchema } from "./core/ingest.js";
10
11
  import { renderToolResult, TOOL_OUTPUT_SCHEMA } from "./tool-schema.js";
11
12
 
12
13
  /** 六个工具名(文档、测试、冒烟共用)。 */
@@ -19,6 +20,7 @@ export const TOOL_NAMES = /** @type {const} */ ({
19
20
  obligation: "case_obligation",
20
21
  access: "case_access",
21
22
  app: "case_app",
23
+ ingest: "case_ingest",
22
24
  build: "case_build",
23
25
  check: "case_check",
24
26
  brief: "case_brief",
@@ -746,6 +748,46 @@ export function buildToolDefinitions(handlers, projectOf) {
746
748
  },
747
749
  },
748
750
 
751
+ {
752
+ name: TOOL_NAMES.ingest,
753
+ description:
754
+ "外部报告摄入:ingest 把别的 agent(如 Craft)产出的报告按通用契约写进案卷(只记录、不背书);schema 返回契约说明,便于对方生成正确格式。",
755
+ parameters: {
756
+ type: "object",
757
+ additionalProperties: false,
758
+ properties: {
759
+ action: { type: "string", enum: ["ingest", "schema"] },
760
+ projectId: PROJECT_ID,
761
+ dryRun: { type: "boolean", description: "ingest 时只预演,不写盘" },
762
+ payload: {
763
+ type: "object",
764
+ description:
765
+ "契约见 action=schema 的返回;claims.evidenceIds 用本次 evidence 的数组下标",
766
+ },
767
+ },
768
+ required: ["action"],
769
+ },
770
+ output: { schema: TOOL_OUTPUT_SCHEMA, render: renderToolResult },
771
+ /** @param {any} args @param {any} exec */
772
+ async execute(args, exec) {
773
+ return run(async () => {
774
+ await assertWriter(exec);
775
+ const action = assertAction(args.action, ["ingest", "schema"]);
776
+ if (action === "schema") {
777
+ return { schema: describeIngestSchema(), summary: "摄入契约 v1(见 schema 字段)" };
778
+ }
779
+ if (args.payload == null) {
780
+ throw Object.assign(new Error("ingest 需要 payload(契约见 action=schema)"), {
781
+ code: "invalid-input",
782
+ });
783
+ }
784
+ return await handlers.ingestReport(projectId(args, exec), args.payload, {
785
+ dryRun: args.dryRun,
786
+ });
787
+ });
788
+ },
789
+ },
790
+
749
791
  {
750
792
  name: TOOL_NAMES.build,
751
793
  description:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kangyishuai/dsh-casefile",
3
- "version": "0.6.0",
3
+ "version": "0.7.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",