dsh-aftermath 0.0.0-stage → 0.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,641 @@
1
+ /**
2
+ * 归因:把磁盘上的“后果”对回到具体的工具调用上。
3
+ *
4
+ * 原则:
5
+ * - 只认证据,不做推断式断言。证据不足就降级,降到最低叫 unattributed(明说归不了因)。
6
+ * - 只读调用不解释任何变更:`Get-Content C:\...\a.txt` 提到了那个文件,不等于它改过。
7
+ * - 时间证据永远只能是 `window`,因为它解释不了“谁干的”。
8
+ * - 时间证据分两级:先比“这次调用自己的起止区间”(窄、几乎不会错配),
9
+ * 区间全不命中才退回整个回合的宽窗(宽,只说明“这一轮里有人动过”)。
10
+ */
11
+ import path from 'node:path';
12
+ import { homeDir, expandHome } from './config.js';
13
+
14
+ export const CONFIDENCE_ORDER = ['certain', 'likely', 'window', 'unattributed'];
15
+
16
+ export const CONFIDENCE_LABEL = {
17
+ certain: '确定',
18
+ likely: '很可能',
19
+ window: '时间窗内',
20
+ unattributed: '无法归因',
21
+ };
22
+
23
+ export const CONFIDENCE_MARK = {
24
+ certain: '✔',
25
+ likely: '◐',
26
+ window: '○',
27
+ unattributed: '?',
28
+ };
29
+
30
+ /**
31
+ * 时间窗这一档内部还有强弱之分,渲染时不能一律写成「时间窗内」:
32
+ * 命中某次调用的起止区间,比只落在整轮宽窗里要硬得多。
33
+ * 这些标签只用于展示,不改变 confidence 的取值集合。
34
+ */
35
+ export const HOW_LABEL = {
36
+ 'call-interval': '区间内',
37
+ 'call-interval-open': '区间内·未封口',
38
+ 'turn-window': '时间窗内',
39
+ 'mutating-call-in-turn': '时间窗内·无发生时间',
40
+ };
41
+
42
+ /** 渲染一行归因时用的标记与文字:优先按 how 细分,未知 how 退回四档标签。 */
43
+ export function confidenceLabel(attribution) {
44
+ const confidence = attribution?.confidence;
45
+ const mark = CONFIDENCE_MARK[confidence] || '?';
46
+ const how = attribution?.how;
47
+ const label = HOW_LABEL[how] || CONFIDENCE_LABEL[confidence] || '无法归因';
48
+ return { mark, label };
49
+ }
50
+
51
+ /** 明确会改文件的工具:命中即视为写操作,哪怕参数里没有 shell 动词。 */
52
+ const WRITE_TOOLS = new Set([
53
+ 'write', 'edit', 'multiedit', 'multi_edit', 'apply_patch', 'edit_file', 'write_file',
54
+ 'create_file', 'str_replace', 'str_replace_editor', 'notebook_edit', 'insert', 'patch',
55
+ ]);
56
+
57
+ /** 明确只读的工具:它们提到路径也不构成改动证据。 */
58
+ const READ_TOOLS = new Set([
59
+ 'read', 'grep', 'glob', 'ls', 'list', 'list_dir', 'view', 'search', 'find',
60
+ 'web_fetch', 'web_search', 'vision_describe', 'vision_ocr', 'vision_bootstrap',
61
+ 'vision_detect', 'vision_ground', 'vision_colors', 'vision_crop', 'vision_pixel_diff',
62
+ 'office_convert', 'office_render', 'todo_write', 'job_list', 'job_output', 'acp_status',
63
+ ]);
64
+
65
+ /** 会改变文件系统的 shell 动词。表里没有的动词不会被当成写操作。 */
66
+ const MUTATING_VERBS = [
67
+ 'remove-item', 'move-item', 'copy-item', 'rename-item', 'new-item', 'set-content',
68
+ 'add-content', 'clear-content', 'set-itemproperty', 'remove-itemproperty',
69
+ 'robocopy', 'xcopy', 'icacls', 'takeown', 'attrib', 'cipher', 'expand-archive',
70
+ 'compress-archive', 'tee', 'dd', 'rsync', 'install', '7z',
71
+ 'out-file', 'tee-object', 'export-csv', 'export-clixml',
72
+ 'del', 'erase', 'rmdir', 'rd', 'mkdir', 'md', 'move', 'copy', 'ren', 'rename',
73
+ 'rm', 'mv', 'cp', 'ln', 'touch', 'truncate', 'unlink', 'chmod', 'chown',
74
+ 'ri', 'ni', 'mi',
75
+ 'unzip', 'untar', 'tar', 'expand', 'compact', 'mklink',
76
+ 'git', 'npm', 'pnpm', 'npx', 'pip',
77
+ ];
78
+
79
+ /**
80
+ * 脚本宿主:`powershell -c "Get-Content x"` 和 `powershell -c "Remove-Item x"`
81
+ * 长得一模一样,它们本身说明不了改不改文件。所以先看里面的动词,
82
+ * 只有写、读都对不上时才保守地算写(宿主理论上什么都能干)。
83
+ */
84
+ const SCRIPT_HOSTS = ['pwsh', 'powershell', 'cmd', 'bash', 'sh', 'zsh', 'wsl', 'node', 'python', 'python3'];
85
+
86
+ /** 只读动词:出现它、且这条命令里没有任何写动词时,不构成改动证据。 */
87
+ const READ_VERBS = [
88
+ 'get-content', 'get-childitem', 'get-item', 'get-itemproperty', 'test-path', 'resolve-path',
89
+ 'select-string', 'measure-object', 'get-process', 'get-service', 'where-object', 'sort-object',
90
+ 'cat', 'head', 'tail', 'less', 'more', 'type', 'dir', 'ls', 'where', 'which', 'grep', 'find',
91
+ ];
92
+
93
+ const escapeVerbs = (list) => list.map((v) => v.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')).join('|');
94
+ const VERB_PREFIX = `(?:^|[\\s;&|("'\`])`;
95
+ const VERB_SUFFIX = `(?=[\\s;&|)"'\`]|$)`;
96
+
97
+ const MUTATING_RE = new RegExp(`${VERB_PREFIX}(${escapeVerbs(MUTATING_VERBS)})${VERB_SUFFIX}`, 'i');
98
+ const READ_VERB_RE = new RegExp(`${VERB_PREFIX}(${escapeVerbs(READ_VERBS)})${VERB_SUFFIX}`, 'i');
99
+ const SCRIPT_HOST_RE = new RegExp(`${VERB_PREFIX}(${escapeVerbs(SCRIPT_HOSTS)})${VERB_SUFFIX}`, 'i');
100
+
101
+ const PATH_KEYS = [
102
+ 'command', 'cmd', 'script', 'code', 'path', 'file', 'file_path', 'filePath', 'filepath',
103
+ 'target', 'source', 'destination', 'dest', 'src', 'dst', 'from', 'to', 'old_path',
104
+ 'new_path', 'oldPath', 'newPath', 'pattern', 'glob', 'input', 'uri', 'url',
105
+ 'output_path', 'out_path', 'outputPath',
106
+ ];
107
+
108
+ const PATH_ARRAY_KEYS = ['paths', 'files', 'targets', 'sources'];
109
+
110
+ /** 引号内的整段内容(允许含空格)。 */
111
+ const QUOTED_RE = /"([^"]*)"|'([^']*)'|`([^`]*)`/g;
112
+ /** 裸 token:到空白为止,允许 * ? 交给 glob 判定。 */
113
+ /** 裸 token:左边必须是分隔符,否则 `https://` 里的 `s://` 会被当成盘符。 */
114
+ const BARE_PATH_RE = /(?:^|[^a-zA-Z0-9_.\-\/])([a-zA-Z]:[\\/][^"'`<>|;\r\n\s]*)/g;
115
+ const HOME_PATH_RE = /(?:%USERPROFILE%|%HOMEDRIVE%%HOMEPATH%)[\\/][^"'`<>|;\r\n\s]*/gi;
116
+ const TILDE_PATH_RE = /(?:^|[\s"'(])(~[\\/][^"'`<>|;\r\n\s]*)/gm;
117
+ const BARE_NAME_RE = /(?:^|[\s"'(])([^\\/\s"'`<>|;,*?]+\.[a-zA-Z0-9]{1,8})(?=[\s"')]|$)/gm;
118
+ /** 输出重定向:> file / >> file / 2> file / &> file,目标可能紧贴操作符。 */
119
+ /** MSYS / Git Bash 的绝对路径:/c/Users/... 这种。 */
120
+ const MSYS_PATH_RE = /(?:^|[\s"'(])(\/[a-zA-Z](?:\/[^"'`<>|;\r\n\s]*)?)/g;
121
+ /** 空设备/伪设备:不是真实文件,不该进证据。 */
122
+ const DEVICE_PATH_RE = /^(?:\/dev\/(?:null|stdout|stderr|tty|fd\/\d+)|nul|con|prn|\$null)$/i;
123
+ const REDIRECT_RE = /(?:^|[\s;&|])(\d?>>?|&>>?)\s*(?:"([^"]*)"|'([^']*)'|([^\s;&|<>]+))/g;
124
+
125
+ const MAX_BLOB = 12000;
126
+ const MAX_TOKENS = 80;
127
+ const MAX_TOKEN_LEN = 400;
128
+ /** 回合级宽窗:调用开始前 3s 到结束后 8s(拿不到调用结束时间时的兜底)。 */
129
+ const WINDOW_BEFORE_MS = 3000;
130
+ const WINDOW_AFTER_MS = 8000;
131
+ /** 调用区间归因的默认容差;配置项 intervalSlackMs 可改。 */
132
+ export const DEFAULT_SLACK_MS = 1500;
133
+
134
+ /**
135
+ * 命令原文落盘前把敏感值打码。只脱「值」,键名和命令其余部分保留,
136
+ * 让归因自查用的原文仍然可读。这是卫生措施,不是安全边界——会话日志里
137
+ * 本来就有完整命令;aftermath 只是别再多留一份明文。
138
+ */
139
+ const SECRET_PATTERNS = [
140
+ // Authorization 头(含可选的 Bearer):curl -H "Authorization: Bearer <token>"
141
+ [/(Authorization\s*:\s*)(?:Bearer\s+)?[A-Za-z0-9._~+/=-]+/gi, '$1[redacted]'],
142
+ // 裸 Bearer token(不在 Authorization 后面时):Bearer <token>
143
+ [/\b(Bearer)\s+[A-Za-z0-9._~+/=-]+/g, '$1 [redacted]'],
144
+ // 选项形式:/password xxx、--token=xxx、-p xxx。值可空格/等号/冒号分隔。
145
+ [/(((?:--?|\/)(?:password|passwd|pwd|secret|token|api[-_]?key|access[-_]?key))(?:=|\s+|:))\s*[^\s"'`]+/gi, '$1[redacted]'],
146
+ // 键值形式:password=xxx、token:xxx。用 = 或 : 与裸命令区分,不含 pwd。
147
+ [/(^|[\s"'`])((?:password|passwd|secret|token|api[-_]?key|access[-_]?key)[=:])[^\s"'`]+/gi, '$1$2[redacted]'],
148
+ // 固定前缀密钥:GitHub PAT、AWS access key、OpenAI/Anthropic 的 sk-
149
+ [/\bgh[po]_[A-Za-z0-9]{16,}\b/g, 'gh?_ [redacted]'],
150
+ [/\bAKIA[0-9A-Z]{16}\b/g, 'AKIA[redacted]'],
151
+ [/\bsk-[A-Za-z0-9_-]{12,}\b/g, 'sk-[redacted]'],
152
+ ];
153
+
154
+ export function redactSecrets(text) {
155
+ let out = String(text || '');
156
+ for (const [pattern, replacement] of SECRET_PATTERNS) {
157
+ out = out.replace(pattern, replacement);
158
+ }
159
+ return out;
160
+ }
161
+
162
+ export function normalizePath(p) {
163
+ if (typeof p !== 'string') return '';
164
+ let s = expandHome(p.trim());
165
+ if (!s) return '';
166
+ s = s.replace(/\//g, '\\');
167
+ s = path.win32.normalize(s);
168
+ if (s.length > 3 && s.endsWith('\\')) s = s.slice(0, -1);
169
+ return s;
170
+ }
171
+
172
+ export function samePath(a, b) {
173
+ return normalizePath(a).toLowerCase() === normalizePath(b).toLowerCase();
174
+ }
175
+
176
+ function collectStrings(value, out, depth) {
177
+ if (depth > 3 || out.length > 200) return;
178
+ if (typeof value === 'string') {
179
+ out.push(value);
180
+ return;
181
+ }
182
+ if (Array.isArray(value)) {
183
+ for (const item of value.slice(0, 50)) collectStrings(item, out, depth + 1);
184
+ return;
185
+ }
186
+ if (value && typeof value === 'object') {
187
+ for (const key of PATH_KEYS) {
188
+ if (key in value) collectStrings(value[key], out, depth + 1);
189
+ }
190
+ for (const key of PATH_ARRAY_KEYS) {
191
+ if (key in value) collectStrings(value[key], out, depth + 1);
192
+ }
193
+ }
194
+ }
195
+
196
+ function parseArguments(raw) {
197
+ if (typeof raw !== 'string' || !raw.trim()) return null;
198
+ try {
199
+ return JSON.parse(raw);
200
+ } catch {
201
+ return null;
202
+ }
203
+ }
204
+
205
+ /** 从一条 tool/call 里抽证据。纯函数。 */
206
+ export function extractEvidence(call) {
207
+ const args = parseArguments(call?.arguments);
208
+ const pieces = [];
209
+ if (args && typeof args === 'object') collectStrings(args, pieces, 0);
210
+ // 只有参数不是 JSON 时才退回扫原文。参数能解析、但里面没有命令/路径键的调用
211
+ // (compress 的 content、write 的 content、prompt 这类载荷文本)一律不参与:
212
+ // 摘要文本里出现 "Out-File" 和某个桌面路径,会把它抬到"确定"档——实测发生过。
213
+ if (pieces.length === 0 && args === null && typeof call?.arguments === 'string') pieces.push(call.arguments);
214
+
215
+ let blob = pieces.join('\n');
216
+ if (blob.length > MAX_BLOB) blob = blob.slice(0, MAX_BLOB);
217
+
218
+ const absPaths = [];
219
+ const globs = [];
220
+ /** 相对路径(`> out.txt` 这种):能当 basename 证据,但不能冒充绝对路径对外展示 */
221
+ const relPaths = [];
222
+ const basenames = [];
223
+ const seen = new Set();
224
+
225
+ const push = (raw) => {
226
+ const token = String(raw || '').trim().replace(/[.,;:)\]}]+$/, '');
227
+ if (!token || token.length > MAX_TOKEN_LEN) return;
228
+ // 空设备不是文件:`2>/dev/null`、`>NUL`、`>$null` 在命令里到处都是,记下来只是噪声
229
+ if (DEVICE_PATH_RE.test(token)) return;
230
+ // URL 不是本地路径:https://host/x 里的 `s://` 会被误当成 S: 盘
231
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(token)) return;
232
+ // 形状校验:命令里的 `0`、`A:.`、`..`、纯标点都会被正则捞出来,但它们不是路径。
233
+ // 落进证据会把「命令提到、但不在观测根内的路径」塞满噪声。
234
+ if (/^\d+$/.test(token)) return;
235
+ if (/^[a-zA-Z]:[.\\/]?$/.test(token)) return;
236
+ if (/^[.\-_—]+$/.test(token)) return;
237
+ const absoluteish = /^[a-zA-Z]:[\\/]/.test(token)
238
+ // ~ 后必须跟磁盘分隔符;`~$VAR`、`~user` 不是可解析路径(会被 homeDir() 拼错)
239
+ || /^~[\\/]/.test(token)
240
+ || /^%/.test(token)
241
+ || /^\/[a-zA-Z](?:\/|$)/.test(token)
242
+ || /\\/.test(token);
243
+ if (!absoluteish && !token.includes('/') && !/[*?]/.test(token)) {
244
+ // 纯名字(`out.txt`)留给 basename 匹配,不当绝对路径对外展示
245
+ const nameKey = token.toLowerCase();
246
+ if (nameKey.length >= 3 && !relPaths.some((item) => item.name.toLowerCase() === nameKey)) {
247
+ relPaths.push({ raw: token, name: token });
248
+ }
249
+ return;
250
+ }
251
+ if (absPaths.length + globs.length >= MAX_TOKENS) return;
252
+ const expanded = token
253
+ .replace(/^%USERPROFILE%/i, homeDir())
254
+ .replace(/^~/, homeDir())
255
+ // Git Bash / MSYS 的 /c/Users/... 也是绝对路径,换成 C:\Users\...
256
+ .replace(/^\/([a-zA-Z])(?=\/|$)/, (_match, drive) => `${drive.toUpperCase()}:`);
257
+ const norm = normalizePath(expanded);
258
+ // `/c` 这种只有盘符的写法(MSYS 的 C: 根)翻译后是 `C:.`,不是文件路径
259
+ if (/^[a-zA-Z]:\.?$/.test(norm)) return;
260
+ if (!norm) return;
261
+ const key = norm.toLowerCase();
262
+ if (seen.has(key)) return;
263
+ seen.add(key);
264
+ if (/[*?]/.test(norm)) globs.push({ raw: token, pattern: norm, regex: globToRegex(norm) });
265
+ else absPaths.push({ raw: token, path: norm, lower: norm.toLowerCase() });
266
+ };
267
+
268
+ // 1) 引号内的整段优先("C:\a b\c.txt" 这种带空格的路径只有它认得)
269
+ let rest = blob;
270
+ const quotedRanges = [];
271
+ for (const match of blob.matchAll(QUOTED_RE)) {
272
+ const content = (match[1] ?? match[2] ?? match[3] ?? '').trim();
273
+ if (!content) continue;
274
+ if (/^[a-zA-Z]:[\\/]/.test(content) || /^%USERPROFILE%/i.test(content) || /^~[\\/]/.test(content)) {
275
+ push(content);
276
+ quotedRanges.push([match.index, match.index + match[0].length]);
277
+ }
278
+ }
279
+ if (quotedRanges.length > 0) {
280
+ let out = '';
281
+ let cursor = 0;
282
+ for (const [start, end] of quotedRanges) {
283
+ out += rest.slice(cursor, start) + ' ';
284
+ cursor = end;
285
+ }
286
+ rest = out + rest.slice(cursor);
287
+ }
288
+
289
+ // 2) 引号外的裸 token
290
+ for (const match of rest.matchAll(BARE_PATH_RE)) push(match[1]);
291
+ for (const match of rest.matchAll(HOME_PATH_RE)) push(match[0]);
292
+ for (const match of rest.matchAll(TILDE_PATH_RE)) push(match[1]);
293
+ for (const match of rest.matchAll(MSYS_PATH_RE)) push(match[1]);
294
+
295
+ // 3) 只有文件名(无分隔符)时单独记一份,用于“本轮唯一文件名”级归因
296
+ for (const match of blob.matchAll(BARE_NAME_RE)) {
297
+ const name = match[1];
298
+ if (!name) continue;
299
+ const lower = name.toLowerCase();
300
+ if (lower.length < 3 || lower.length > 200) continue;
301
+ if (!basenames.includes(lower)) basenames.push(lower);
302
+ }
303
+
304
+ // 3b) 输出重定向。`printf x > a.txt`、`echo hi >> log`、`cmd 2> err.txt` 都会改磁盘,
305
+ // 但命令词本身(printf/echo/dir)不在动词表里,漏掉它们会让这类调用丢掉区间证据。
306
+ // 操作符在引号里(`echo "a > b"`)是文本,目标本身可以是引号包着的路径。
307
+ const quoteRanges = [];
308
+ for (const match of blob.matchAll(QUOTED_RE)) quoteRanges.push([match.index, match.index + match[0].length]);
309
+ const inQuotes = (index) => quoteRanges.some(([start, end]) => index >= start && index < end);
310
+
311
+ const redirects = [];
312
+ for (const match of blob.matchAll(REDIRECT_RE)) {
313
+ const opIndex = match.index + match[0].indexOf(match[1]);
314
+ if (inQuotes(opIndex)) continue;
315
+ const target = String(match[2] ?? match[3] ?? match[4] ?? '').trim();
316
+ if (!target) continue;
317
+ redirects.push({ op: match[1], raw: target });
318
+ push(target);
319
+ }
320
+
321
+ const excerptSource = typeof args?.command === 'string'
322
+ ? args.command
323
+ : typeof args?.cmd === 'string'
324
+ ? args.cmd
325
+ : typeof args?.script === 'string'
326
+ ? args.script
327
+ : typeof args?.file_path === 'string'
328
+ ? args.file_path
329
+ : blob;
330
+ const excerpt = redactSecrets(String(excerptSource || '').replace(/\s+/g, ' ').trim()).slice(0, 180);
331
+
332
+ const name = typeof call?.name === 'string' && call.name ? call.name.toLowerCase() : 'unknown';
333
+ const verbMatch = MUTATING_RE.exec(blob);
334
+ const readVerbMatch = READ_VERB_RE.exec(blob);
335
+ const hostMatch = SCRIPT_HOST_RE.exec(blob);
336
+
337
+ // 分类优先级:写工具表 → 读工具表 → shell 写动词 → 重定向 → 只读动词 → 脚本宿主。
338
+ // 脚本宿主排在最后:它能干任何事,只有写、读都对不上时才保守地算写。
339
+ let mutating = false;
340
+ let source = 'none';
341
+ let verb = null;
342
+ if (WRITE_TOOLS.has(name)) {
343
+ mutating = true;
344
+ source = 'tool';
345
+ verb = `tool:${name}`;
346
+ } else if (READ_TOOLS.has(name)) {
347
+ source = 'read';
348
+ } else if (verbMatch) {
349
+ mutating = true;
350
+ source = 'shell';
351
+ verb = verbMatch[1].toLowerCase();
352
+ } else if (redirects.length > 0) {
353
+ mutating = true;
354
+ source = 'redirect';
355
+ verb = redirects[0].op;
356
+ } else if (readVerbMatch) {
357
+ source = 'read';
358
+ verb = readVerbMatch[1].toLowerCase();
359
+ } else if (hostMatch) {
360
+ mutating = true;
361
+ source = 'shell';
362
+ verb = hostMatch[1].toLowerCase();
363
+ }
364
+
365
+ return {
366
+ callId: call?.callId ?? null,
367
+ name,
368
+ at: typeof call?.at === 'number' ? call.at : null,
369
+ /** 调用开始时刻 = tool/call 的 time。 */
370
+ startAt: typeof call?.at === 'number' ? call.at : null,
371
+ /** 调用结束时刻 = tool/result 的 time;没等到结果就是 null。 */
372
+ endAt: typeof call?.endAt === 'number' ? call.endAt : null,
373
+ step: Number.isInteger(call?.step) ? call.step : null,
374
+ parseable: args !== null,
375
+ mutating,
376
+ readOnly: !mutating,
377
+ source,
378
+ verb,
379
+ absPaths,
380
+ globs,
381
+ relPaths,
382
+ basenames,
383
+ redirects,
384
+ excerpt,
385
+ };
386
+ }
387
+
388
+ /**
389
+ * glob → 正则。`*` 和 `?` 不跨目录分隔符:`C:\a\*.txt` 只命中 a 这一层,
390
+ * 否则会把 `C:\a\sub\c.txt` 也当成证据,直接抬到「确定」。
391
+ * `**` 才是跨目录。
392
+ */
393
+ export function globToRegex(pattern) {
394
+ const DOUBLE = '\u0001';
395
+ const escaped = String(pattern)
396
+ .replace(/\*\*/g, DOUBLE)
397
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
398
+ .replace(/\*/g, '[^\\\\]*')
399
+ .replace(/\?/g, '[^\\\\]')
400
+ .split(DOUBLE)
401
+ .join('.*');
402
+ return new RegExp(`^${escaped}$`, 'i');
403
+ }
404
+
405
+ function isUnder(childLower, parentLower) {
406
+ if (childLower === parentLower) return false;
407
+ const prefix = parentLower.endsWith('\\') ? parentLower : `${parentLower}\\`;
408
+ return childLower.startsWith(prefix);
409
+ }
410
+
411
+ function basenameLower(rel) {
412
+ const idx = Math.max(rel.lastIndexOf('\\'), rel.lastIndexOf('/'));
413
+ return (idx >= 0 ? rel.slice(idx + 1) : rel).toLowerCase();
414
+ }
415
+
416
+ function changeAbsPath(change) {
417
+ if (change.abs) return change.abs;
418
+ return path.win32.normalize(path.join(change.root, change.rel));
419
+ }
420
+
421
+ function changeTimeHint(change) {
422
+ if (change.kind === 'created' || change.kind === 'modified') {
423
+ const t = change.after?.mtime;
424
+ return typeof t === 'number' && t > 0 ? t : null;
425
+ }
426
+ return null; // deleted 只有旧 mtime,不能当“发生时间”用
427
+ }
428
+
429
+ function stamp(change, confidence, how, evidence, index) {
430
+ return {
431
+ ...change,
432
+ attribution: {
433
+ confidence,
434
+ how,
435
+ callIndex: typeof index === 'number' ? index : -1,
436
+ tool: evidence?.name ?? null,
437
+ verb: evidence?.verb ?? null,
438
+ excerpt: evidence?.excerpt ?? null,
439
+ },
440
+ };
441
+ }
442
+
443
+ /**
444
+ * 把一次调用折成一个时间区间:`[开始 - 容差, 结束 + 容差]`。
445
+ * 拿不到结束时间时退到回合结束时刻,再拿不到就退到固定宽窗。
446
+ */
447
+ function intervalOf(evidence, slackMs, turnEndAt) {
448
+ if (evidence.startAt === null) return null;
449
+ const start = evidence.startAt - slackMs;
450
+ const endRaw = evidence.endAt ?? turnEndAt ?? evidence.startAt + WINDOW_AFTER_MS;
451
+ const end = Math.max(start, endRaw + slackMs);
452
+ return { evidence, start, end, width: end - start, open: evidence.endAt === null };
453
+ }
454
+
455
+ function buildIntervals(evidences, slackMs, turnEndAt) {
456
+ const out = [];
457
+ for (const evidence of evidences) {
458
+ const interval = intervalOf(evidence, slackMs, turnEndAt);
459
+ if (interval) out.push(interval);
460
+ }
461
+ return out;
462
+ }
463
+
464
+ /** 命中多个区间时取最窄的那个——窄区间更可能是真正干这活的调用。 */
465
+ function narrowestIntervalAt(intervals, moment) {
466
+ let best = null;
467
+ for (const interval of intervals) {
468
+ if (moment < interval.start || moment > interval.end) continue;
469
+ if (!best || interval.width < best.width) best = interval;
470
+ }
471
+ return best;
472
+ }
473
+
474
+ /** 整个回合的宽窗:最早一次调用开始之前,到最晚一次调用结束之后。 */
475
+ function turnSpan(intervals) {
476
+ if (intervals.length === 0) return null;
477
+ let start = Infinity;
478
+ let end = -Infinity;
479
+ for (const interval of intervals) {
480
+ if (interval.start < start) start = interval.start;
481
+ if (interval.end > end) end = interval.end;
482
+ }
483
+ return { start: start - WINDOW_BEFORE_MS, end: end + WINDOW_AFTER_MS };
484
+ }
485
+
486
+ /**
487
+ * 区间统计,写进报告健康度:有没有拿到结束时间、有多少区间彼此重叠。
488
+ * 重叠多说明本轮并行调用密集,此时“区间命中”也可能不止一个候选。
489
+ */
490
+ export function analyzeIntervals(calls, options = {}) {
491
+ const slackMs = Number.isFinite(options.slackMs) ? Math.max(0, options.slackMs) : DEFAULT_SLACK_MS;
492
+ const turnEndAt = Number.isFinite(options.turnEndAt) ? options.turnEndAt : null;
493
+ const evidences = (calls || [])
494
+ .map((call) => {
495
+ try {
496
+ return extractEvidence(call);
497
+ } catch {
498
+ return null;
499
+ }
500
+ })
501
+ .filter(Boolean);
502
+ const usable = evidences.filter((e) => e.mutating);
503
+ // 工具名不在已知写/读/脚本宿主名单里的调用:写操作只能靠命令内容判定,
504
+ // 宿主新增/改名的写工具会静默落到这里。列出来比混在 mutating 里更诚实。
505
+ const knownNames = new Set([...WRITE_TOOLS, ...READ_TOOLS, ...SCRIPT_HOSTS]);
506
+ const unknownTools = [...new Set(
507
+ evidences
508
+ .map((e) => e.name)
509
+ .filter((n) => n !== 'unknown' && !knownNames.has(n)),
510
+ )];
511
+ const intervals = buildIntervals(usable, slackMs, turnEndAt);
512
+ let overlaps = 0;
513
+ for (let i = 0; i < intervals.length; i += 1) {
514
+ for (let j = i + 1; j < intervals.length; j += 1) {
515
+ const a = intervals[i];
516
+ const b = intervals[j];
517
+ if (a.start <= b.end && b.start <= a.end) overlaps += 1;
518
+ }
519
+ }
520
+ return {
521
+ calls: evidences.length,
522
+ mutating: usable.length,
523
+ timed: intervals.length,
524
+ closed: intervals.filter((interval) => !interval.open).length,
525
+ overlaps,
526
+ slackMs,
527
+ unknownTools,
528
+ };
529
+ }
530
+
531
+ /**
532
+ * 给每条变更盖归因戳。
533
+ * @param {Array} changes 来自 diff.toChangeList
534
+ * @param {Array} calls 本轮的原始 tool/call({callId,name,arguments,at,step,endAt})
535
+ * @param {object} options {slackMs 区间容差, turnEndAt 回合结束时刻}
536
+ */
537
+ export function attributeChanges(changes, calls, options = {}) {
538
+ const slackMs = Number.isFinite(options.slackMs) ? Math.max(0, options.slackMs) : DEFAULT_SLACK_MS;
539
+ const turnEndAt = Number.isFinite(options.turnEndAt) ? options.turnEndAt : null;
540
+ const evidences = (calls || [])
541
+ .map((call) => {
542
+ try {
543
+ return extractEvidence(call);
544
+ } catch {
545
+ return null;
546
+ }
547
+ })
548
+ .filter(Boolean);
549
+
550
+ // 只读调用没有资格解释变更,先整个剔掉。
551
+ const usable = evidences.filter((e) => e.mutating);
552
+ const withPath = usable.filter((e) => e.absPaths.length > 0 || e.globs.length > 0);
553
+ const intervals = buildIntervals(usable, slackMs, turnEndAt);
554
+ const span = turnSpan(intervals);
555
+
556
+ const basenameCount = new Map();
557
+ for (const change of changes || []) {
558
+ const name = basenameLower(change.rel);
559
+ basenameCount.set(name, (basenameCount.get(name) || 0) + 1);
560
+ }
561
+
562
+ return (changes || []).map((change) => {
563
+ const abs = changeAbsPath(change);
564
+ const absLower = abs.toLowerCase();
565
+ const name = basenameLower(change.rel);
566
+
567
+ // 1) 绝对路径 / glob 直接命中 → certain
568
+ for (const evidence of withPath) {
569
+ for (const token of evidence.absPaths) {
570
+ if (token.lower === absLower) return stamp(change, 'certain', 'exact-path', evidence, evidences.indexOf(evidence));
571
+ }
572
+ for (const glob of evidence.globs) {
573
+ if (glob.regex.test(abs)) return stamp(change, 'certain', 'glob-path', evidence, evidences.indexOf(evidence));
574
+ }
575
+ }
576
+
577
+ // 2) 落在“被写调用指向的目录”之下 → likely
578
+ for (const evidence of withPath) {
579
+ for (const token of evidence.absPaths) {
580
+ if (isUnder(absLower, token.lower)) {
581
+ return stamp(change, 'likely', 'under-changed-dir', evidence, evidences.indexOf(evidence));
582
+ }
583
+ }
584
+ }
585
+
586
+ // 3) 只出现文件名,且本轮该文件名唯一 → likely
587
+ if ((basenameCount.get(name) || 0) === 1) {
588
+ for (const evidence of usable) {
589
+ if (evidence.basenames.includes(name)) {
590
+ return stamp(change, 'likely', 'basename', evidence, evidences.indexOf(evidence));
591
+ }
592
+ }
593
+ }
594
+
595
+ // 4a) 落在某一次调用自己的起止区间内 → window,依据具体到那次调用
596
+ const hint = changeTimeHint(change);
597
+ if (hint !== null) {
598
+ const hit = narrowestIntervalAt(intervals, hint);
599
+ if (hit) {
600
+ return stamp(
601
+ change,
602
+ 'window',
603
+ hit.open ? 'call-interval-open' : 'call-interval',
604
+ hit.evidence,
605
+ evidences.indexOf(hit.evidence),
606
+ );
607
+ }
608
+ // 4b) 区间没命中,只说明落在整个回合的宽窗里 → 更弱,但仍标明是时间证据
609
+ if (span && hint >= span.start && hint <= span.end) {
610
+ return stamp(change, 'window', 'turn-window', usable[0], evidences.indexOf(usable[0]));
611
+ }
612
+ }
613
+ // 4c) 删除拿不到发生时间,只能要求“本轮存在写调用”
614
+ if (usable.length > 0) {
615
+ return stamp(change, 'window', 'mutating-call-in-turn', usable[0], evidences.indexOf(usable[0]));
616
+ }
617
+
618
+ // 5) 归不了就是归不了
619
+ return {
620
+ ...change,
621
+ attribution: {
622
+ confidence: 'unattributed',
623
+ how: evidences.length === 0 ? 'no-tool-calls' : 'no-mutating-evidence',
624
+ callIndex: -1,
625
+ tool: null,
626
+ verb: null,
627
+ excerpt: null,
628
+ },
629
+ };
630
+ });
631
+ }
632
+
633
+ export function summarizeConfidence(changes) {
634
+ const counts = { certain: 0, likely: 0, window: 0, unattributed: 0 };
635
+ for (const change of changes || []) {
636
+ const key = change?.attribution?.confidence;
637
+ if (key && key in counts) counts[key] += 1;
638
+ else counts.unattributed += 1;
639
+ }
640
+ return counts;
641
+ }