@kangyishuai/dsh-casefile 0.2.2 → 0.4.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
@@ -10,6 +10,7 @@ import { buildAttestation } from "./core/attestation.js";
10
10
  import { buildSpecPack, redactPack, renderSpecMarkdown, writeSpecPack } from "./core/brief.js";
11
11
  import { createCheckers } from "./core/checks.js";
12
12
  import { hashTree, shortDigest } from "./core/digest.js";
13
+ import { awaitLogin } from "./core/login-wait.js";
13
14
  import { gradeCapabilities } from "./core/manifest.js";
14
15
  import {
15
16
  CasefileInputError,
@@ -59,6 +60,7 @@ export class CasefileActionError extends Error {
59
60
  * currentProject?: Map<string, string>,
60
61
  * dataRoot?: string,
61
62
  * runner?: (command: string, options?: Record<string, any>) => Promise<Record<string, any>>,
63
+ * onWaitChange?: (state: Record<string, any> | null) => void,
62
64
  * sessions?: {
63
65
  * create(input: { cwd: string }): Promise<{ sessionId: string }>,
64
66
  * prompt(input: { sessionId: string, text: string }): Promise<void>,
@@ -71,6 +73,7 @@ export function createActions(options) {
71
73
  const currentProject = options.currentProject ?? new Map();
72
74
  const dataRoot = options.dataRoot ?? store.rootDir;
73
75
  const sessions = options.sessions;
76
+ const onWaitChange = options.onWaitChange;
74
77
  const checkers = createCheckers(
75
78
  /** @type {any} */ (options.runner ? { runner: options.runner } : {}),
76
79
  );
@@ -206,8 +209,14 @@ export function createActions(options) {
206
209
  */
207
210
  async addEvidence(projectId, input, exec) {
208
211
  const project = requireProject(projectId);
212
+ // 产物接管:/tmp 里的东西会被清理,清了 sha256 就无法复算,项目只能停在 investigating。
213
+ const archived =
214
+ typeof input?.artifactPath === "string" && input.artifactPath.trim() !== ""
215
+ ? store.archiveArtifact(project.id, input.artifactPath)
216
+ : null;
209
217
  const record = normalizeEvidence({
210
218
  ...input,
219
+ artifact: archived,
211
220
  sessionId: input?.sessionId ?? sessionOf(exec) ?? null,
212
221
  });
213
222
  store.appendRecord(project.id, "evidence", record);
@@ -1122,8 +1131,93 @@ export function createActions(options) {
1122
1131
  return { ...overview, summary: summarizeOverview(overview) };
1123
1132
  },
1124
1133
 
1134
+ // ---------- 等登录(人机协作) ----------
1135
+
1136
+ /**
1137
+ * 轮询等用户完成登录。带超时,不假装成功。
1138
+ * @param {string} projectId
1139
+ * @param {{
1140
+ * endpoint: string, urlPrefix?: string, readyJs?: string,
1141
+ * pollMs?: number, timeoutMs?: number,
1142
+ * }} input
1143
+ * @returns {Promise<Record<string, any>>}
1144
+ */
1145
+ async awaitLogin(projectId, input) {
1146
+ const project = requireProject(projectId);
1147
+ const startedAt = nowIso();
1148
+ const endpoint = String(input?.endpoint ?? "").trim();
1149
+ if (endpoint === "") {
1150
+ throw new CasefileInputError(
1151
+ "invalid-input",
1152
+ "endpoint 不能为空(形如 http://127.0.0.1:9223)",
1153
+ );
1154
+ }
1155
+ onWaitChange?.({
1156
+ active: true,
1157
+ projectId: project.id,
1158
+ endpoint,
1159
+ startedAt,
1160
+ hint: "请在弹出的浏览器窗口里完成登录;就绪后会自动继续。",
1161
+ });
1162
+ let result;
1163
+ try {
1164
+ result = await awaitLogin({
1165
+ endpoint,
1166
+ urlPrefix: input?.urlPrefix,
1167
+ readyJs: input?.readyJs,
1168
+ pollMs: input?.pollMs,
1169
+ timeoutMs: input?.timeoutMs,
1170
+ });
1171
+ } finally {
1172
+ onWaitChange?.(null);
1173
+ }
1174
+ store.audit(project.id, {
1175
+ actor: "agent",
1176
+ action: "access/await-login",
1177
+ target: endpoint,
1178
+ detail: { status: result.status, attempts: result.attempts, waitedMs: result.waitedMs },
1179
+ });
1180
+ return result;
1181
+ },
1182
+
1125
1183
  // ---------- 覆盖率 / 关闭 / 报告(M3 收尾) ----------
1126
1184
 
1185
+ /**
1186
+ * 归档项目(非破坏性):误建或暂存的项目收起来,文件都在。
1187
+ * @param {string} projectId
1188
+ * @param {{ reason?: string }} [options]
1189
+ * @returns {Promise<Record<string, any>>}
1190
+ */
1191
+ async archiveProject(projectId, options = {}) {
1192
+ const project = store.archiveProject(projectId, options?.reason);
1193
+ store.audit(project.id, {
1194
+ actor: "agent",
1195
+ action: "project/archive",
1196
+ target: project.id,
1197
+ detail: { reason: String(options?.reason ?? "").slice(0, 200) },
1198
+ });
1199
+ return { project };
1200
+ },
1201
+
1202
+ /**
1203
+ * 丢弃项目:整个目录移进 dataRoot/trash(可手动移回)。
1204
+ * 破坏性,必须 confirm。
1205
+ * @param {string} projectId
1206
+ * @param {{ confirm?: boolean }} [options]
1207
+ * @returns {Promise<Record<string, any>>}
1208
+ */
1209
+ async dropProject(projectId, options = {}) {
1210
+ const project = requireProject(projectId);
1211
+ if (options?.confirm !== true) {
1212
+ throw new CasefileActionError(
1213
+ "confirm-required",
1214
+ `丢弃项目会把 projects/${project.id} 整个移进 trash(可手动移回)。确认请传 confirm: true。`,
1215
+ );
1216
+ }
1217
+ const result = store.dropProject(project.id);
1218
+ return { trashedTo: result.trashedTo, project: result.project };
1219
+ },
1220
+
1127
1221
  /**
1128
1222
  * 项目覆盖率与关闭闸门状态(只读预览,不写状态)。
1129
1223
  * @param {string} projectId
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
+ "wait.title": "案卷:等待登录",
87
+ "wait.hint": "请在弹出的浏览器窗口里完成登录;就绪后会自动继续。",
88
+ "wait.elapsed": "已等待 {seconds}s",
86
89
  "blocker.implementationChanged": "实现已变化",
87
90
  "blocker.originalChanged": "原件已变化",
88
91
  "blocker.checkStale": "检查已过期",
@@ -172,6 +175,10 @@ window.__ModuleLoader__.load({
172
175
  "blocker.failedObligations": "failed obligations",
173
176
  "blocker.blockedObligations": "blocked obligations",
174
177
  "blocker.coverageBelow": "coverage below target",
178
+ "wait.title": "Casefile: waiting for sign-in",
179
+ "wait.hint":
180
+ "Finish signing in in the browser window; it continues automatically once ready.",
181
+ "wait.elapsed": "waiting {seconds}s",
175
182
  "blocker.implementationChanged": "implementation changed",
176
183
  "blocker.originalChanged": "original changed",
177
184
  "blocker.checkStale": "check is stale",
@@ -551,6 +558,81 @@ window.__ModuleLoader__.load({
551
558
  );
552
559
  }
553
560
 
561
+ /**
562
+ * 等待登录横幅:轮询 host 的 accessState。
563
+ * 只在"正在等"时出现,不阻塞任何操作——这是提醒,不是模态框。
564
+ */
565
+ /** @param {{ api: any, t: any }} props */
566
+ function LoginWaitOverlay(props) {
567
+ var ctx = props.api.ctx;
568
+ var t = props.t;
569
+ var state = useState(null);
570
+ var wait = state[0];
571
+ var setWait = state[1];
572
+ var tickState = useState(0);
573
+ var setTick = tickState[1];
574
+
575
+ useEffect(() => {
576
+ var alive = true;
577
+ var poll = () => {
578
+ call(ctx, "accessState")
579
+ .then((value) => {
580
+ if (alive) setWait(value && value.active === true ? value : null);
581
+ })
582
+ .catch(() => {
583
+ if (alive) setWait(null);
584
+ });
585
+ };
586
+ poll();
587
+ var timer = setInterval(() => {
588
+ poll();
589
+ setTick((/** @type {number} */ n) => n + 1);
590
+ }, 2000);
591
+ return () => {
592
+ alive = false;
593
+ clearInterval(timer);
594
+ };
595
+ }, [ctx]);
596
+
597
+ var seconds = 0;
598
+ var started = NaN;
599
+ if (!wait) return null;
600
+ if (typeof wait.startedAt === "string") {
601
+ started = Date.parse(wait.startedAt);
602
+ if (Number.isFinite(started))
603
+ seconds = Math.max(0, Math.round((Date.now() - started) / 1000));
604
+ }
605
+ return h(
606
+ "div",
607
+ {
608
+ className: "cf-loginwait",
609
+ "data-casefile-loginwait": wait.projectId || "1",
610
+ "data-casefile-loginwait-seconds": String(seconds),
611
+ style: {
612
+ position: "fixed",
613
+ right: 20,
614
+ bottom: 20,
615
+ zIndex: 40,
616
+ maxWidth: 380,
617
+ padding: "10px 14px",
618
+ borderRadius: 10,
619
+ background: "var(--dsw-alias-toast-bg)",
620
+ color: "var(--dsw-alias-toast-label)",
621
+ fontSize: 12,
622
+ lineHeight: 1.55,
623
+ boxShadow: "0 6px 24px rgba(0,0,0,.28)",
624
+ },
625
+ },
626
+ h("div", { style: { fontWeight: 600, marginBottom: 2 } }, text(t, "wait.title")),
627
+ h("div", null, wait.hint || text(t, "wait.hint")),
628
+ h(
629
+ "div",
630
+ { style: { marginTop: 4, opacity: 0.72 } },
631
+ text(t, "wait.elapsed", { seconds: seconds }),
632
+ ),
633
+ );
634
+ }
635
+
554
636
  // ---------- 主面板 ----------
555
637
 
556
638
  /**
@@ -1268,6 +1350,19 @@ window.__ModuleLoader__.load({
1268
1350
  ),
1269
1351
  "casefile: settings section",
1270
1352
  );
1353
+
1354
+ c.effect(
1355
+ () =>
1356
+ c.slots.inject("shell.overlay", () =>
1357
+ c.slots.register(
1358
+ { name: "shell.overlay", id: "casefile-loginwait", order: 880, locale: NS },
1359
+ function CasefileLoginWaitOverlay(/** @type {any} */ props) {
1360
+ return h(LoginWaitOverlay, Object.assign({}, props, { api: api, t: t }));
1361
+ },
1362
+ ),
1363
+ ),
1364
+ "casefile: login wait overlay",
1365
+ );
1271
1366
  };
1272
1367
 
1273
1368
  return module.exports;
@@ -0,0 +1,205 @@
1
+ // @ts-check
2
+ // core/login-wait.js:等用户完成登录(轮询 CDP 页面就绪条件)。
3
+ //
4
+ // 为什么需要它:登录态页面要人参与(输账号/扫码/二次验证)。agent 不能干等,
5
+ // 也不能假装成功——所以做成"带超时的轮询 + 明确状态":
6
+ // - ready:就绪判据为真,可以继续采集
7
+ // - timeout:到点还没好,保留现场,调用方决定是否重来
8
+ // - error:端点/页面不可用(不存在、CDP 层失败)
9
+ // 判据用一段 JS 表达式(返回 boolean),由调用方给出——casefile 不猜"登录成功"长什么样。
10
+
11
+ /**
12
+ * @typedef {{
13
+ * status: "ready" | "timeout" | "error",
14
+ * attempts: number,
15
+ * waitedMs: number,
16
+ * pollMs: number,
17
+ * timeoutMs: number,
18
+ * lastValue: boolean | null,
19
+ * hint: string,
20
+ * detail?: string,
21
+ * }} LoginWaitResult
22
+ */
23
+
24
+ /** 默认轮询参数。 */
25
+ export const LOGIN_WAIT_DEFAULTS = {
26
+ pollMs: 2000,
27
+ timeoutMs: 180000,
28
+ readyJs: '!document.querySelector("input[type=password]")',
29
+ };
30
+
31
+ /**
32
+ * 在 CDP 端点上找一个 HTTP(S) 页面 target。
33
+ * @param {string} endpoint 形如 http://127.0.0.1:9223
34
+ * @param {string} [urlPrefix] 只选 URL 以它开头的页面
35
+ * @returns {Promise<{ id: string, url: string } | null>}
36
+ */
37
+ export async function findPageTarget(endpoint, urlPrefix) {
38
+ const base = String(endpoint).replace(/\/+$/, "");
39
+ const response = await fetch(`${base}/json/list`, { signal: AbortSignal.timeout(10000) });
40
+ if (!response.ok) throw new Error(`target discovery failed: HTTP ${response.status}`);
41
+ const targets = await response.json();
42
+ const pages = (Array.isArray(targets) ? targets : []).filter(
43
+ (/** @type {any} */ item) => item?.type === "page" && /^https?:/u.test(String(item.url ?? "")),
44
+ );
45
+ if (pages.length === 0) return null;
46
+ const picked =
47
+ (urlPrefix
48
+ ? pages.find((/** @type {any} */ item) => String(item.url).startsWith(urlPrefix))
49
+ : null) ?? pages[0];
50
+ return { id: String(picked.id), url: String(picked.url) };
51
+ }
52
+
53
+ /**
54
+ * 在页面里求值(一次性 WebSocket,用完即断)。
55
+ * @param {string} wsUrl
56
+ * @param {string} expression
57
+ * @returns {Promise<boolean>}
58
+ */
59
+ async function evaluateOnce(wsUrl, expression) {
60
+ return await new Promise((resolve, reject) => {
61
+ const socket = new WebSocket(wsUrl);
62
+ const timer = setTimeout(() => {
63
+ try {
64
+ socket.close();
65
+ } catch {
66
+ // 关闭失败不影响超时语义
67
+ }
68
+ reject(new Error("evaluate timeout"));
69
+ }, 10000);
70
+ socket.onopen = () => {
71
+ socket.send(
72
+ JSON.stringify({
73
+ id: 1,
74
+ method: "Runtime.evaluate",
75
+ params: { expression, returnByValue: true },
76
+ }),
77
+ );
78
+ };
79
+ socket.onerror = () => {
80
+ clearTimeout(timer);
81
+ reject(new Error("cdp socket error"));
82
+ };
83
+ socket.onmessage = (/** @type {any} */ event) => {
84
+ let message;
85
+ try {
86
+ message = JSON.parse(String(event.data));
87
+ } catch {
88
+ return;
89
+ }
90
+ if (message.id !== 1) return;
91
+ clearTimeout(timer);
92
+ try {
93
+ socket.close();
94
+ } catch {
95
+ // 忽略
96
+ }
97
+ if (message.error) {
98
+ reject(new Error(`cdp error: ${JSON.stringify(message.error)}`));
99
+ return;
100
+ }
101
+ resolve(message.result?.result?.value === true);
102
+ };
103
+ });
104
+ }
105
+
106
+ /**
107
+ * 轮询等登录就绪。
108
+ * @param {{
109
+ * endpoint: string,
110
+ * urlPrefix?: string,
111
+ * readyJs?: string,
112
+ * pollMs?: number,
113
+ * timeoutMs?: number,
114
+ * sleep?: (ms: number) => Promise<void>,
115
+ * probe?: (wsUrl: string, expression: string) => Promise<boolean>,
116
+ * }} input
117
+ * @returns {Promise<LoginWaitResult>}
118
+ */
119
+ export async function awaitLogin(input) {
120
+ const pollMs =
121
+ Number.isInteger(input.pollMs) && Number(input.pollMs) > 0
122
+ ? Number(input.pollMs)
123
+ : LOGIN_WAIT_DEFAULTS.pollMs;
124
+ const timeoutMs =
125
+ Number.isInteger(input.timeoutMs) && Number(input.timeoutMs) > 0
126
+ ? Number(input.timeoutMs)
127
+ : LOGIN_WAIT_DEFAULTS.timeoutMs;
128
+ const readyJs =
129
+ typeof input.readyJs === "string" && input.readyJs.trim() !== ""
130
+ ? input.readyJs
131
+ : LOGIN_WAIT_DEFAULTS.readyJs;
132
+ const sleep = input.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
133
+ const probe = input.probe ?? evaluateOnce;
134
+ const started = Date.now();
135
+ let attempts = 0;
136
+ /** @type {boolean | null} */
137
+ let lastValue = null;
138
+
139
+ while (Date.now() - started < timeoutMs) {
140
+ attempts += 1;
141
+ try {
142
+ const endpoint = String(input.endpoint ?? "").replace(/\/+$/, "");
143
+ const response = await fetch(`${endpoint}/json/list`, { signal: AbortSignal.timeout(10000) });
144
+ if (!response.ok) throw new Error(`target discovery failed: HTTP ${response.status}`);
145
+ const targets = await response.json();
146
+ const pages = (Array.isArray(targets) ? targets : []).filter(
147
+ (/** @type {any} */ item) =>
148
+ item?.type === "page" && /^https?:/u.test(String(item.url ?? "")),
149
+ );
150
+ const wanted = input.urlPrefix;
151
+ const picked =
152
+ (wanted
153
+ ? pages.find((/** @type {any} */ item) => String(item.url).startsWith(wanted))
154
+ : null) ?? pages[0];
155
+ if (!picked) {
156
+ lastValue = null;
157
+ await sleep(pollMs);
158
+ continue;
159
+ }
160
+ lastValue = await probe(String(picked.webSocketDebuggerUrl), readyJs);
161
+ if (lastValue === true) {
162
+ return {
163
+ status: "ready",
164
+ attempts,
165
+ waitedMs: Date.now() - started,
166
+ pollMs,
167
+ timeoutMs,
168
+ lastValue,
169
+ hint: "已就绪:可以继续采集了。",
170
+ };
171
+ }
172
+ } catch (error) {
173
+ const message = error instanceof Error ? error.message : String(error);
174
+ // 端点还没起来 / 页面还没开也属于"等",只有明确不可恢复才报错
175
+ // 端点还没起来(浏览器没启动 / 端口没开)属于可以继续等,不该立刻判失败;
176
+ // 等满 timeoutMs 后由循环出口统一报 timeout。
177
+ if (/ECONNREFUSED|ECONNRESET|fetch failed|target discovery failed/u.test(message)) {
178
+ lastValue = null;
179
+ await sleep(pollMs);
180
+ continue;
181
+ }
182
+ return {
183
+ status: "error",
184
+ attempts,
185
+ waitedMs: Date.now() - started,
186
+ pollMs,
187
+ timeoutMs,
188
+ lastValue,
189
+ hint: "CDP 端点或页面不可用;确认带 --remote-debugging-port 的浏览器已启动并打开了目标页。",
190
+ detail: message.slice(0, 500),
191
+ };
192
+ }
193
+ await sleep(pollMs);
194
+ }
195
+
196
+ return {
197
+ status: "timeout",
198
+ attempts,
199
+ waitedMs: Date.now() - started,
200
+ pollMs,
201
+ timeoutMs,
202
+ lastValue,
203
+ hint: "等待超时:登录还没完成。现场保留,你可以登录后重新调用,或调大 timeoutMs。",
204
+ };
205
+ }
package/lib/core/model.js CHANGED
@@ -71,6 +71,7 @@ export const PROJECT_STATES = /** @type {const} */ ([
71
71
  "reconstructing",
72
72
  "verifying",
73
73
  "closed",
74
+ "archived",
74
75
  ]);
75
76
 
76
77
  /** 项目 id:小写字母数字与连字符,1–64。 */
@@ -219,11 +220,6 @@ export function normalizeProjectInput(input) {
219
220
  };
220
221
  }
221
222
 
222
- /**
223
- * 规范化一条证据(只投影 REA 的结论)。
224
- * @param {Record<string, any>} input
225
- * @returns {Record<string, any>}
226
- */
227
223
  /**
228
224
  * 外部生产者(谁采的、用什么方式采的、用户是否明示确认过)。
229
225
  * casefile 自己不采集:它只记录产出者,责任与合法性归操作者。
@@ -258,6 +254,34 @@ export function normalizeProducer(raw) {
258
254
  return Object.keys(producer).length === 0 ? null : producer;
259
255
  }
260
256
 
257
+ /**
258
+ * 规范化一条证据(只投影 REA 的结论)。
259
+ * @param {Record<string, any>} input
260
+ * @returns {Record<string, any>}
261
+ */
262
+ /**
263
+ * 归档产物元信息(由 store.archiveArtifact 产出,这里只做形状校验)。
264
+ * @param {any} raw
265
+ * @returns {Record<string, any> | null}
266
+ */
267
+ export function normalizeArtifact(raw) {
268
+ if (raw == null) return null;
269
+ if (typeof raw !== "object" || Array.isArray(raw)) {
270
+ throw new CasefileInputError("invalid-input", "artifact 必须是对象");
271
+ }
272
+ const sha256 = text(raw.sha256, "artifact.sha256", { max: 128 });
273
+ const file = text(raw.file, "artifact.file", { max: 400 });
274
+ return {
275
+ sha256,
276
+ bytes: Number.isInteger(raw.bytes) && raw.bytes >= 0 ? raw.bytes : 0,
277
+ file,
278
+ originalName:
279
+ raw.originalName == null
280
+ ? null
281
+ : text(raw.originalName, "artifact.originalName", { max: 200 }),
282
+ };
283
+ }
284
+
261
285
  /**
262
286
  * 规范化一条证据(只投影 REA 的结论)。
263
287
  * @param {Record<string, any>} input
@@ -278,6 +302,7 @@ export function normalizeEvidence(input) {
278
302
  summary: text(input?.summary, "summary", { max: 4000 }),
279
303
  refs: textList(input?.refs, "refs"),
280
304
  producer: normalizeProducer(input?.producer),
305
+ artifact: normalizeArtifact(input?.artifact),
281
306
  claimIds: idList(input?.claimIds, "claimIds"),
282
307
  };
283
308
  }
package/lib/core/store.js CHANGED
@@ -11,6 +11,7 @@
11
11
  // - JSONL append-only,修改用新记录 + supersedes(M0 先只追加);
12
12
  // - 所有路径从 dataRoot 派生,不写死 ~/.dsh(可在临时目录里测)。
13
13
 
14
+ import { createHash } from "node:crypto";
14
15
  import {
15
16
  appendFileSync,
16
17
  existsSync,
@@ -18,9 +19,10 @@ import {
18
19
  readdirSync,
19
20
  readFileSync,
20
21
  renameSync,
22
+ statSync,
21
23
  writeFileSync,
22
24
  } from "node:fs";
23
- import { dirname, join } from "node:path";
25
+ import { basename, dirname, extname, join } from "node:path";
24
26
  import {
25
27
  CasefileInputError,
26
28
  ID_RE,
@@ -305,6 +307,48 @@ export class CaseStore {
305
307
  * @param {Record<string, any>} patch
306
308
  * @returns {Record<string, any>}
307
309
  */
310
+ /**
311
+ * 归档:状态改为 archived,文件保留。误建/待整理的项目用它收起来。
312
+ * @param {string} projectId
313
+ * @param {string} [reason]
314
+ * @returns {Record<string, any>}
315
+ */
316
+ archiveProject(projectId, reason) {
317
+ const project = this.getProject(projectId);
318
+ if (!project) throw new CaseStoreError("project-not-found", `项目不存在:${projectId}`);
319
+ const next = {
320
+ ...project,
321
+ state: "archived",
322
+ archivedAt: new Date().toISOString(),
323
+ archiveReason: reason == null ? "" : String(reason).slice(0, 500),
324
+ };
325
+ this.writeJson(join(this.projectDir(projectId), "project.json"), next);
326
+ return next;
327
+ }
328
+
329
+ /**
330
+ * 丢弃:把整个项目目录移进 `<dataRoot>/trash/`,可手动移回。
331
+ * 破坏性操作,必须显式 confirm。
332
+ * @param {string} projectId
333
+ * @returns {{ trashedTo: string, project: Record<string, any> }}
334
+ */
335
+ dropProject(projectId) {
336
+ const project = this.getProject(projectId);
337
+ if (!project) throw new CaseStoreError("project-not-found", `项目不存在:${projectId}`);
338
+ const trashRoot = join(this.dataRoot, "trash");
339
+ mkdirSync(trashRoot, { recursive: true });
340
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
341
+ const target = join(trashRoot, `${stamp}-${projectId}`);
342
+ renameSync(this.projectDir(projectId), target);
343
+ return { trashedTo: target, project };
344
+ }
345
+
346
+ /**
347
+ * 局部更新项目字段。
348
+ * @param {string} projectId
349
+ * @param {Record<string, any>} patch
350
+ * @returns {Record<string, any>}
351
+ */
308
352
  updateProject(projectId, patch) {
309
353
  const project = this.getProject(projectId);
310
354
  if (!project) throw new CaseStoreError("project-not-found", `项目不存在:${projectId}`);
@@ -364,6 +408,35 @@ export class CaseStore {
364
408
  return candidate;
365
409
  }
366
410
 
411
+ /**
412
+ * 把外部采集产物归档进项目目录,返回归档后的元信息。
413
+ * 目的:/tmp 里的产物会被清理,清了就无法复算 sha256,项目只能停在 investigating。
414
+ * @param {string} projectId
415
+ * @param {string} sourcePath 绝对路径的现成产物
416
+ * @returns {{ sha256: string, bytes: number, file: string, originalName: string }}
417
+ */
418
+ archiveArtifact(projectId, sourcePath) {
419
+ const source = String(sourcePath ?? "").trim();
420
+ if (source === "" || !existsSync(source)) {
421
+ throw new CasefileInputError("invalid-input", `产物不存在:${source || "(空)"}`);
422
+ }
423
+ const stat = statSync(source);
424
+ if (!stat.isFile()) {
425
+ throw new CasefileInputError("invalid-input", `不是普通文件:${source}`);
426
+ }
427
+ const bytes = readFileSync(source);
428
+ const digest = createHash("sha256").update(bytes).digest("hex");
429
+ const dir = join(this.projectDir(projectId), "artifacts");
430
+ mkdirSync(dir, { recursive: true });
431
+ const name = basename(source);
432
+ const ext = extname(name);
433
+ const file = join("artifacts", `${digest.slice(0, 16)}${ext}`);
434
+ const target = join(this.projectDir(projectId), file);
435
+ // 同样的内容只存一份:同一 sha256 已存在就直接复用
436
+ if (!existsSync(target)) writeFileSync(target, bytes);
437
+ return { sha256: digest, bytes: bytes.length, file, originalName: name };
438
+ }
439
+
367
440
  /**
368
441
  * 记录一个 builder 子会话 id(数据根级,不分项目)。
369
442
  * builder 只该收到规格包,不该写账本——写类工具遇到它会拒绝。
package/lib/service.js CHANGED
@@ -65,6 +65,7 @@ function fail(error) {
65
65
  "nothing-selected",
66
66
  "project-exists",
67
67
  "not-found",
68
+ "confirm-required",
68
69
  "project-not-found",
69
70
  "obligationTooTall",
70
71
  "coverage-not-met",
@@ -91,10 +92,14 @@ export class CasefileService extends TypertRemoteService {
91
92
  this.store = new CaseStore({ dataRoot: this.dataRoot, logger: this.logger });
92
93
  /** 会话 → 最近打开的项目(工具省略 projectId 时用)。 @type {Map<string, string>} */
93
94
  this.currentProject = new Map();
95
+ this.accessWait = null;
94
96
  this.actions = createActions({
95
97
  store: this.store,
96
98
  currentProject: this.currentProject,
97
99
  dataRoot: this.dataRoot,
100
+ onWaitChange: (state) => {
101
+ this.accessWait = state;
102
+ },
98
103
  });
99
104
  this.installSessions();
100
105
  this.installTools();
@@ -210,6 +215,10 @@ export class CasefileService extends TypertRemoteService {
210
215
  closeObligation: (projectId, id, input) => this.actions.closeObligation(projectId, id, input),
211
216
  reopenObligation: (projectId, id, note) => this.actions.reopenObligation(projectId, id, note),
212
217
  overview: () => this.actions.overview(),
218
+ awaitLogin: (projectId, input) => this.actions.awaitLogin(projectId, input),
219
+ accessState: () => this.accessState(),
220
+ archiveProject: (projectId, options) => this.actions.archiveProject(projectId, options),
221
+ dropProject: (projectId, options) => this.actions.dropProject(projectId, options),
213
222
  runCycle: (projectId, input) => this.actions.runCycle(projectId, input),
214
223
  isBuilderSession: (sessionId) =>
215
224
  this.store.listBuilderSessions().has(String(sessionId ?? "")),
@@ -459,6 +468,50 @@ export class CasefileService extends TypertRemoteService {
459
468
  }
460
469
  }
461
470
 
471
+ /** @returns {Promise<Record<string, any>>} */
472
+ async accessState() {
473
+ return this.accessWait == null ? { active: false } : { ...this.accessWait };
474
+ }
475
+
476
+ /**
477
+ * @param {string} projectId
478
+ * @param {Record<string, any>} [options]
479
+ * @returns {Promise<Record<string, any>>}
480
+ */
481
+ async archiveProject(projectId, options) {
482
+ try {
483
+ return await this.actions.archiveProject(projectId, options ?? {});
484
+ } catch (error) {
485
+ fail(error);
486
+ }
487
+ }
488
+
489
+ /**
490
+ * @param {string} projectId
491
+ * @param {Record<string, any>} [options]
492
+ * @returns {Promise<Record<string, any>>}
493
+ */
494
+ async dropProject(projectId, options) {
495
+ try {
496
+ return await this.actions.dropProject(projectId, options ?? {});
497
+ } catch (error) {
498
+ fail(error);
499
+ }
500
+ }
501
+
502
+ /**
503
+ * @param {string} projectId
504
+ * @param {Record<string, any>} input
505
+ * @returns {Promise<Record<string, any>>}
506
+ */
507
+ async awaitLogin(projectId, input) {
508
+ try {
509
+ return await this.actions.awaitLogin(projectId, /** @type {any} */ (input));
510
+ } catch (error) {
511
+ fail(error);
512
+ }
513
+ }
514
+
462
515
  /**
463
516
  * @param {string} projectId
464
517
  * @param {Record<string, any>} input
@@ -665,6 +718,10 @@ declareRemote(CasefileService, "listChecks");
665
718
  declareRemote(CasefileService, "closeObligation");
666
719
  declareRemote(CasefileService, "reopenObligation");
667
720
  declareRemote(CasefileService, "overview");
721
+ declareRemote(CasefileService, "accessState");
722
+ declareRemote(CasefileService, "archiveProject");
723
+ declareRemote(CasefileService, "dropProject");
724
+ declareRemote(CasefileService, "awaitLogin");
668
725
  declareRemote(CasefileService, "runCycle");
669
726
  declareRemote(CasefileService, "closeProject");
670
727
  declareRemote(CasefileService, "exportReport");
package/lib/tools.js CHANGED
@@ -17,6 +17,7 @@ export const TOOL_NAMES = /** @type {const} */ ({
17
17
  feature: "case_feature",
18
18
  unknown: "case_unknown",
19
19
  obligation: "case_obligation",
20
+ access: "case_access",
20
21
  build: "case_build",
21
22
  check: "case_check",
22
23
  brief: "case_brief",
@@ -140,7 +141,17 @@ export function buildToolDefinitions(handlers, projectOf) {
140
141
  properties: {
141
142
  action: {
142
143
  type: "string",
143
- enum: ["open", "list", "get", "update", "close", "report", "overview"],
144
+ enum: [
145
+ "open",
146
+ "list",
147
+ "get",
148
+ "update",
149
+ "close",
150
+ "report",
151
+ "overview",
152
+ "archive",
153
+ "drop",
154
+ ],
144
155
  description: "要执行的动作",
145
156
  },
146
157
  projectId: PROJECT_ID,
@@ -160,6 +171,11 @@ export function buildToolDefinitions(handlers, projectOf) {
160
171
  scope: { type: "string", enum: ["all", "selected"] },
161
172
  patch: { type: "object", description: "update 时的字段(title/authTier/scope/state)" },
162
173
  minCoverage: { type: "number", description: "close 时的覆盖率下限(默认 1)" },
174
+ reason: { type: "string", description: "archive 时的原因(进审计)" },
175
+ confirm: {
176
+ type: "boolean",
177
+ description: "drop 时必须传 true:把整个项目目录移进 trash(可手动移回)",
178
+ },
163
179
  },
164
180
  required: ["action"],
165
181
  },
@@ -218,6 +234,21 @@ export function buildToolDefinitions(handlers, projectOf) {
218
234
  summary: `项目已关闭(覆盖率 ${(preview.coverage.ratio * 100).toFixed(0)}%)`,
219
235
  };
220
236
  }
237
+ case "archive": {
238
+ const archived = await handlers.archiveProject(projectId(args, exec), {
239
+ reason: args.reason,
240
+ });
241
+ return { project: archived.project, summary: `项目已归档:${archived.project.id}` };
242
+ }
243
+ case "drop": {
244
+ const dropped = await handlers.dropProject(projectId(args, exec), {
245
+ confirm: args.confirm,
246
+ });
247
+ return {
248
+ trashedTo: dropped.trashedTo,
249
+ summary: `项目已移入 trash:${dropped.trashedTo}`,
250
+ };
251
+ }
221
252
  case "report": {
222
253
  return handlers.exportReport(projectId(args, exec));
223
254
  }
@@ -251,6 +282,11 @@ export function buildToolDefinitions(handlers, projectOf) {
251
282
  description:
252
283
  "产出该证据的工具标识(REA 工具名,或外部工具如 scrapling/StealthyFetcher)",
253
284
  },
285
+ artifactPath: {
286
+ type: "string",
287
+ description:
288
+ "可选:把外部采集产物(HTML/HAR/截图)归档进项目目录并记录 sha256;/tmp 产物会被清理,归档后才能长期复算",
289
+ },
254
290
  producer: {
255
291
  type: "object",
256
292
  additionalProperties: false,
@@ -537,6 +573,52 @@ export function buildToolDefinitions(handlers, projectOf) {
537
573
  },
538
574
  },
539
575
 
576
+ {
577
+ name: TOOL_NAMES.access,
578
+ description:
579
+ "访问协助:await-login 轮询等人完成登录(带超时,就绪/超时/错误三态,不假装成功)。用于登录态页面采集前。",
580
+ parameters: {
581
+ type: "object",
582
+ additionalProperties: false,
583
+ properties: {
584
+ action: { type: "string", enum: ["await-login"] },
585
+ projectId: PROJECT_ID,
586
+ endpoint: { type: "string", description: "CDP 端点,形如 http://127.0.0.1:9223" },
587
+ urlPrefix: { type: "string", description: "只选 URL 以它开头的页面" },
588
+ readyJs: {
589
+ type: "string",
590
+ description: "就绪判据(返回 boolean 的 JS 表达式),默认「页面里没有密码输入框」",
591
+ },
592
+ pollMs: { type: "integer", description: "轮询间隔,默认 2000" },
593
+ timeoutMs: { type: "integer", description: "最长等待,默认 180000(3 分钟)" },
594
+ },
595
+ required: ["action"],
596
+ },
597
+ output: { schema: TOOL_OUTPUT_SCHEMA, render: renderToolResult },
598
+ /** @param {any} args @param {any} exec */
599
+ async execute(args, exec) {
600
+ return run(async () => {
601
+ await assertWriter(exec);
602
+ assertAction(args.action, ["await-login"]);
603
+ const id = projectId(args, exec);
604
+ const result = await handlers.awaitLogin(id, {
605
+ endpoint: args.endpoint,
606
+ urlPrefix: args.urlPrefix,
607
+ readyJs: args.readyJs,
608
+ pollMs: args.pollMs,
609
+ timeoutMs: args.timeoutMs,
610
+ });
611
+ return {
612
+ ...result,
613
+ summary:
614
+ result.status === "ready"
615
+ ? `已就绪(等了 ${result.waitedMs}ms,${result.attempts} 次探测)`
616
+ : `${result.status}:${result.hint}`,
617
+ };
618
+ });
619
+ },
620
+ },
621
+
540
622
  {
541
623
  name: TOOL_NAMES.build,
542
624
  description:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kangyishuai/dsh-casefile",
3
- "version": "0.2.2",
3
+ "version": "0.4.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",