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.
package/lib/panel.js ADDED
@@ -0,0 +1,126 @@
1
+ /**
2
+ * 面板数据:把磁盘上的记录整理成 Plugins 页「最近变更」面板吃的 JSON。
3
+ *
4
+ * 为什么要有这条通道:
5
+ * `/aftermath report` 是会话命令,必须有会话才能执行;插件详情页没有会话,
6
+ * 所以面板不能复用命令,只能走 Host 自己注册的 HTTP 路由。
7
+ *
8
+ * 约束:
9
+ * - 纯函数,不碰 I/O,方便单测;
10
+ * - 只放路径、大小、时间与归因档位,不放文件内容;
11
+ * - 体积可控(默认 8 轮、每轮 20 条变更),面板不是审计工具。
12
+ */
13
+ import { maskPath } from './report.js';
14
+
15
+ export const PANEL_PATH = '/aftermath/recent';
16
+
17
+ const MAX_TURNS = 8;
18
+ const MAX_CHANGES = 20;
19
+ const MAX_OUTSIDE = 10;
20
+
21
+ const CONFIDENCE_ORDER = ['certain', 'likely', 'window', 'unattributed'];
22
+
23
+ function clock(ms) {
24
+ if (!Number.isFinite(ms) || ms <= 0) return null;
25
+ return new Date(ms).toISOString();
26
+ }
27
+
28
+ function trimChange(change, mask) {
29
+ const attr = change?.attribution || {};
30
+ const abs = change?.abs || (change?.root && change?.rel ? `${change.root}\\${change.rel}` : change?.rel || '');
31
+ return {
32
+ kind: change?.kind || 'unknown',
33
+ path: maskPath(abs || '', mask),
34
+ rel: change?.rel || '',
35
+ size: Number.isFinite(change?.after?.size) ? change.after.size : Number.isFinite(change?.before?.size) ? change.before.size : null,
36
+ mtime: clock(change?.kind === 'deleted' ? change?.before?.mtime : change?.after?.mtime),
37
+ confidence: CONFIDENCE_ORDER.includes(attr.confidence) ? attr.confidence : 'unattributed',
38
+ how: attr.how || null,
39
+ tool: attr.tool || null,
40
+ verb: attr.verb || null,
41
+ };
42
+ }
43
+
44
+ function trimTurn(record, mask) {
45
+ const counts = record?.counts || {};
46
+ const changes = Array.isArray(record?.changes) ? record.changes : [];
47
+ const shown = changes.slice(0, MAX_CHANGES).map((change) => trimChange(change, mask));
48
+ return {
49
+ turn: Number.isInteger(record?.turn) ? record.turn : null,
50
+ at: clock(record?.at),
51
+ session: record?.session || null,
52
+ kind: record?.kind === 'quiet' ? 'quiet' : 'changes',
53
+ total: Number.isFinite(counts.total) ? counts.total : changes.length,
54
+ counts: {
55
+ created: counts.created || 0,
56
+ deleted: counts.deleted || 0,
57
+ modified: counts.modified || 0,
58
+ moved: counts.moved || 0,
59
+ confidence: CONFIDENCE_ORDER.reduce((acc, key) => {
60
+ acc[key] = counts.confidence?.[key] || 0;
61
+ return acc;
62
+ }, {}),
63
+ },
64
+ changes: shown,
65
+ changesTruncated: changes.length > shown.length,
66
+ callsTruncated: record?.callsTruncated === true,
67
+ scanMs: Number.isFinite(record?.health?.scanMs) ? record.health.scanMs : null,
68
+ };
69
+ }
70
+
71
+ /**
72
+ * @param {object} input
73
+ * @param {Array} input.records 最近若干轮记录(新到旧或旧到新皆可,输出统一按新的在前)
74
+ * @param {Array} input.roots 观测根 [{id, path, exists}]
75
+ * @param {object} input.config 归一化后的配置
76
+ * @param {string} input.version 插件版本
77
+ * @param {number} [input.now] 生成时刻
78
+ * @param {number} [input.todayTurns] 今天记录轮数
79
+ * @param {number} [input.todayChanges] 今天变更总数
80
+ */
81
+ export function buildPanelPayload(input = {}) {
82
+ const records = Array.isArray(input.records) ? input.records.filter(Boolean) : [];
83
+ const roots = Array.isArray(input.roots) ? input.roots : [];
84
+ const config = input.config || {};
85
+ const mask = config.maskHome !== false;
86
+
87
+ const turns = records
88
+ .slice(0, MAX_TURNS)
89
+ .map((record) => trimTurn(record, mask));
90
+
91
+ const latest = records[0] || null;
92
+ const outside = Array.isArray(latest?.outside) ? latest.outside.slice(0, MAX_OUTSIDE) : [];
93
+
94
+ return {
95
+ plugin: 'dsh-aftermath',
96
+ version: typeof input.version === 'string' ? input.version : null,
97
+ generatedAt: clock(Number.isFinite(input.now) ? input.now : Date.now()),
98
+ enabled: config.enabled !== false,
99
+ maskHome: mask,
100
+ roots: roots.map((root) => ({
101
+ id: root?.id || null,
102
+ path: maskPath(root?.path || '', mask),
103
+ exists: root?.exists !== false,
104
+ })),
105
+ totals: {
106
+ todayTurns: Number.isFinite(input.todayTurns) ? input.todayTurns : turns.length,
107
+ todayChanges: Number.isFinite(input.todayChanges)
108
+ ? input.todayChanges
109
+ : turns.reduce((sum, turn) => sum + (turn.total || 0), 0),
110
+ },
111
+ latestTurn: turns[0] || null,
112
+ turns,
113
+ outside: outside.map((item) => ({
114
+ path: maskPath(item?.path || '', mask),
115
+ count: Number.isFinite(item?.count) ? item.count : 1,
116
+ tools: Array.isArray(item?.tools) ? item.tools.slice(0, 4) : [],
117
+ })),
118
+ };
119
+ }
120
+
121
+ /** 面板路由的响应头:本地只读数据,不缓存、不许内嵌到别处。 */
122
+ export const PANEL_HEADERS = {
123
+ 'content-type': 'application/json; charset=utf-8',
124
+ 'cache-control': 'no-store',
125
+ 'x-content-type-options': 'nosniff',
126
+ };
package/lib/report.js ADDED
@@ -0,0 +1,428 @@
1
+ /**
2
+ * 报告渲染。纯字符串拼装,无 I/O,方便单测与后续换 UI。
3
+ *
4
+ * 输出的底线:不确定的事不说成确定的。
5
+ * - certain/likely/window/unattributed 四档全部显式标注;
6
+ * - 归因不到就写“shell 行为,无法逐文件归因”,并列出本轮命令原文供人自己看。
7
+ */
8
+ import { CONFIDENCE_LABEL, CONFIDENCE_MARK, CONFIDENCE_ORDER, confidenceLabel, summarizeConfidence } from './attribution.js';
9
+ import { detectSymptoms } from './symptoms.js';
10
+ import { homeDir } from './config.js';
11
+
12
+ const KIND_LABEL = {
13
+ created: '新建',
14
+ deleted: '删除',
15
+ modified: '修改',
16
+ moved: '移动',
17
+ };
18
+
19
+ function formatSize(bytes) {
20
+ if (typeof bytes !== 'number' || bytes < 0) return '—';
21
+ if (bytes < 1024) return `${bytes} B`;
22
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
23
+ if (bytes < 1024 * 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
24
+ return `${(bytes / 1024 / 1024 / 1024).toFixed(2)} GB`;
25
+ }
26
+
27
+ function pad2(n) {
28
+ return String(n).padStart(2, '0');
29
+ }
30
+
31
+ /** 路径归一化,只用于比较:统一分隔符、去尾斜杠、大小写不敏感。 */
32
+ function normalizeForCompare(value) {
33
+ return String(value ?? '').replace(/\//g, '\\').replace(/\\+$/, '').toLowerCase();
34
+ }
35
+
36
+ /** path 是否落在 rootPath 之下(含等于)。 */
37
+ function isUnder(pathValue, rootPath) {
38
+ const p = normalizeForCompare(pathValue);
39
+ const r = normalizeForCompare(rootPath);
40
+ if (!p || !r) return false;
41
+ return p === r || p.startsWith(`${r}\\`);
42
+ }
43
+
44
+ /**
45
+ * 本轮命令里提到、但不在任何观测根之下的绝对路径。
46
+ *
47
+ * 这是唯一能覆盖“根外发生了什么”的线索:不扫盘,只读命令行文本,
48
+ * 所以它说的是“命令提到过”,不是“磁盘上真的变了”。
49
+ */
50
+ /**
51
+ * 空设备不是文件。旧记录里已经存了 `\dev\null` 这类噪声,读的时候一并丢掉。
52
+ * 只比对最后一段名字:`\/dev\/null`、`\\dev\\null`、`NUL` 都算空设备。
53
+ */
54
+ const DEVICE_NAMES = new Set(['null', 'stdout', 'stderr', 'tty', 'nul', 'con', 'prn', '$null']);
55
+
56
+ function isDeviceLike(value) {
57
+ const raw = String(value || '').trim().toLowerCase();
58
+ if (!raw) return false;
59
+ if (DEVICE_NAMES.has(raw)) return true;
60
+ const name = raw.split(/[\\/]+/).filter(Boolean).pop() || '';
61
+ return DEVICE_NAMES.has(name);
62
+ }
63
+
64
+ export function outsideRootPaths(record) {
65
+ const calls = Array.isArray(record?.calls) ? record.calls : [];
66
+ const roots = Array.isArray(record?.roots) ? record.roots : [];
67
+ const rootPaths = roots.map((root) => root?.path).filter((p) => typeof p === 'string' && p);
68
+ const map = new Map();
69
+ for (const call of calls) {
70
+ const paths = Array.isArray(call?.paths) ? call.paths : [];
71
+ if (paths.length === 0) continue;
72
+ const label = `${call.name || 'tool'}${call.verb ? ` · ${call.verb}` : ''}`;
73
+ for (const raw of paths) {
74
+ if (typeof raw !== 'string' || !raw) continue;
75
+ if (isDeviceLike(raw)) continue;
76
+ if (rootPaths.some((rootPath) => isUnder(raw, rootPath))) continue;
77
+ const key = normalizeForCompare(raw);
78
+ if (!key) continue;
79
+ let item = map.get(key);
80
+ if (!item) {
81
+ item = { path: raw, count: 0, tools: [], at: call.at ?? null };
82
+ map.set(key, item);
83
+ }
84
+ item.count += 1;
85
+ if (!item.tools.includes(label)) item.tools.push(label);
86
+ }
87
+ }
88
+ return [...map.values()];
89
+ }
90
+
91
+ function formatClock(ms) {
92
+ if (typeof ms !== 'number' || !Number.isFinite(ms) || ms <= 0) return '—';
93
+ const d = new Date(ms);
94
+ return `${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`;
95
+ }
96
+
97
+ function formatDay(ms) {
98
+ if (typeof ms !== 'number' || !Number.isFinite(ms) || ms <= 0) return '—';
99
+ const d = new Date(ms);
100
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${formatClock(ms)}`;
101
+ }
102
+
103
+ export function maskPath(p, enabled) {
104
+ if (!enabled) return p;
105
+ const home = homeDir();
106
+ if (!home) return p;
107
+ const text = String(p ?? '');
108
+ const lower = text.toLowerCase();
109
+ const homeLower = home.toLowerCase();
110
+ // 必须有分隔符边界:C:\Users\Al 不能把 C:\Users\Alice 打成 ~ice
111
+ if (lower === homeLower) return '~';
112
+ return lower.startsWith(`${homeLower}\\`) ? `~${text.slice(home.length)}` : text;
113
+ }
114
+
115
+ /** 命令原文里也可能带家目录路径,一并打码。 */
116
+ function maskText(text, enabled) {
117
+ if (!enabled) return text;
118
+ const home = homeDir();
119
+ const raw = String(text ?? '');
120
+ if (!home || !raw) return raw;
121
+ const body = home.replace(/[.*+?^${}()|[\]\]]/g, '\\$&');
122
+ return raw.replace(new RegExp(`${body}(?=$|[\\/\\s"'])`, 'gi'), '~');
123
+ }
124
+
125
+ function cell(text) {
126
+ return String(text ?? '').replace(/\|/g, '\\|').replace(/\r?\n/g, ' ');
127
+ }
128
+
129
+ function absOfChange(change) {
130
+ if (change.abs) return change.abs;
131
+ if (change.root && change.rel) return `${change.root}\\${change.rel}`;
132
+ return change.rel || '';
133
+ }
134
+
135
+ /**
136
+ * 会话短标:宿主默认把 session.id 编成 `session-N`,前缀 `session-` 无区分度,
137
+ * 只保留编号成 `#N`;人为标记(unknown/anonymous/manual-scan)原样保留;
138
+ * 其余任意 id(含 uuid)取前 8 位。
139
+ */
140
+ function shortSession(id) {
141
+ const s = String(id ?? '');
142
+ if (!s) return '—';
143
+ if (s === 'unknown' || s === 'anonymous' || s === 'manual-scan') return s;
144
+ if (s.startsWith('session-')) {
145
+ // 形如 session-01c4eb63-06ec-4084-... 只取第一段,别把整串 UUID 摊在标题里
146
+ const rest = s.slice(8);
147
+ const head = rest.split('-')[0] || rest;
148
+ return `#${head.slice(0, 8)}`;
149
+ }
150
+ const compact = s.replace(/[^0-9a-zA-Z_-]/g, '');
151
+ return compact.slice(0, 8) || s.slice(0, 8);
152
+ }
153
+
154
+ export function renderChatLine(record) {
155
+ const counts = record?.counts || {};
156
+ const total = counts.total || 0;
157
+ if (total === 0) {
158
+ const mutating = (Array.isArray(record?.calls) ? record.calls : []).filter((call) => call.mutating).length;
159
+ if (mutating > 0) {
160
+ return `本轮观测根内没有文件变更,但执行过 ${mutating} 条写操作——改动可能落在观测根之外。\n/aftermath report 看它碰过哪些路径。`;
161
+ }
162
+ return '本轮未观测到文件变更。';
163
+ }
164
+ const parts = [];
165
+ for (const kind of ['deleted', 'created', 'modified', 'moved']) {
166
+ const n = counts[kind] || 0;
167
+ if (n > 0) parts.push(`${KIND_LABEL[kind]} ${n}`);
168
+ }
169
+ const weak = (counts.confidence?.window || 0) + (counts.confidence?.unattributed || 0);
170
+ const tail = weak > 0 ? `,其中 ${weak} 处仅时间窗可对应` : '';
171
+ return `本轮观测到 ${total} 处文件变更(${parts.join(' · ')})${tail}。\n/aftermath report 看逐条明细与归因。`;
172
+ }
173
+
174
+ /**
175
+ * 报告健康度:这份报告本身可信到什么程度。
176
+ * 只说能算出来的事实(耗时、覆盖量、区间可用性、截断),不评价、不给分。
177
+ */
178
+ function renderHealth(record) {
179
+ const health = record?.health;
180
+ if (!health || typeof health !== 'object') return [];
181
+ const confidence = record?.counts?.confidence || {};
182
+ const total = ['certain', 'likely', 'window', 'unattributed'].reduce((sum, key) => sum + (confidence[key] || 0), 0);
183
+ const pct = (n) => (total > 0 ? `${Math.round((n / total) * 100)}%` : '—');
184
+ const intervals = health.intervals || {};
185
+
186
+ const lines = [];
187
+ lines.push('## 报告健康度');
188
+ lines.push('');
189
+ if (Number.isFinite(health.scanMs)) {
190
+ lines.push(`- 快照耗时:本轮结束这次扫描 ${health.scanMs} ms,覆盖 ${health.roots ?? 0} 个根 / ${health.scanned ?? 0} 个条目`);
191
+ }
192
+ if (total > 0) {
193
+ const parts = ['certain', 'likely', 'window', 'unattributed']
194
+ .map((key) => `${CONFIDENCE_MARK[key]}${CONFIDENCE_LABEL[key]} ${confidence[key] || 0}(${pct(confidence[key] || 0)})`);
195
+ lines.push(`- 归因分布:${parts.join(' · ')}`);
196
+ }
197
+ if ((confidence.window || 0) > 0) {
198
+ const weakList = (record?.changes || []).filter((c) => c?.attribution?.confidence === 'window');
199
+ const inInterval = weakList.filter((c) => String(c?.attribution?.how || '').startsWith('call-interval')).length;
200
+ if (weakList.length > 0) {
201
+ lines.push(`- 时间证据:${inInterval} 处 mtime 落在某次调用的起止区间内,${weakList.length - inInterval} 处只落在整轮宽窗`);
202
+ }
203
+ }
204
+ if (Number.isFinite(intervals.timed)) {
205
+ if (intervals.timed > 0) {
206
+ const open = Math.max(0, intervals.timed - (intervals.closed ?? 0));
207
+ const openNote = open > 0 ? `,其中 ${open} 次没等到结果、区间按回合结束时刻封口` : '';
208
+ const overlapNote = intervals.overlaps > 0
209
+ ? `;${intervals.overlaps} 对区间重叠,重叠时取最窄的那个`
210
+ : '';
211
+ if (Number(health.ambiguousResults) > 0) {
212
+ lines.push(`- 配对歧义:${health.ambiguousResults} 次结果是并行回来、无法唯一确定归属,这些调用的结束时刻不可靠`);
213
+ }
214
+ lines.push(
215
+ `- 调用区间:${intervals.calls ?? 0} 次调用、${intervals.mutating ?? 0} 次写操作,`
216
+ + `${intervals.closed ?? 0}/${intervals.timed} 拿到起止时刻(容差 ${intervals.slackMs ?? 0} ms)${openNote}${overlapNote}`,
217
+ );
218
+ } else {
219
+ lines.push('- 调用区间:本轮没有可用的调用时刻,时间证据只到回合宽窗这一级');
220
+ }
221
+ }
222
+ if (Array.isArray(intervals.unknownTools) && intervals.unknownTools.length > 0) {
223
+ const names = intervals.unknownTools.slice(0, 5).join(', ');
224
+ const more = intervals.unknownTools.length > 5 ? '…' : '';
225
+ lines.push(`- 未知工具:${intervals.unknownTools.length} 种工具名不在已知写/读名单里(${names}${more}),写操作靠命令内容判定`);
226
+ }
227
+ if (record?.callsTruncated) {
228
+ lines.push('- 调用列表:本轮调用太多,只保留了写操作和最近 20 条只读调用');
229
+ }
230
+ if (health.truncated) {
231
+ lines.push(`- 未列全:本次只列出前 ${health.listed ?? 0} 条,其余 ${Math.max(0, (health.changed ?? 0) + (record?.counts?.moved || 0) - (health.listed ?? 0))} 条未逐条展开`);
232
+ }
233
+ lines.push('');
234
+ return lines;
235
+ }
236
+
237
+ export function renderTurnReport(record, options = {}) {
238
+ const maskHome = options.maskHome !== false;
239
+ const changes = Array.isArray(record?.changes) ? record.changes : [];
240
+ const roots = Array.isArray(record?.roots) ? record.roots : [];
241
+ const counts = record?.counts || {};
242
+ const confidence = counts.confidence || summarizeConfidence(changes);
243
+
244
+ const lines = [];
245
+ lines.push(`# 第 ${record?.turn ?? '?'} 轮 · ${formatDay(record?.at)} · 会话 ${shortSession(record?.session)}`);
246
+ lines.push('');
247
+
248
+ const incomplete = roots.filter((root) => root.complete === false || root.ok === false);
249
+ if (incomplete.length > 0) {
250
+ const names = incomplete.map((root) => root.id || '?').join('、');
251
+ lines.push(`> **本轮观测不完整**(${names} 没扫全):这些根下的变更没有列出来,也没有算成删除。`);
252
+ lines.push('> 常见原因:条目数超上限、某个子目录读不到。可以在设置里加大上限或缩小观测范围。');
253
+ lines.push('');
254
+ }
255
+
256
+ if (changes.length === 0) {
257
+ lines.push(`观测范围内没有文件变更(${roots.map((r) => maskPath(r.path, maskHome)).join('、') || '无可用根'})。`);
258
+ const mutating = (Array.isArray(record?.calls) ? record.calls : []).filter((call) => call.mutating);
259
+ if (mutating.length > 0) {
260
+ lines.push('');
261
+ lines.push(`不过这一轮执行过 ${mutating.length} 条写操作;观测根内没有变化,意味着改动可能落在根外。命令原文:`);
262
+ lines.push('');
263
+ for (const call of mutating.slice(0, 5)) {
264
+ lines.push(`- \`${cell(call.name || 'tool')}\` ${cell(call.excerpt || '')}`);
265
+ }
266
+ if (mutating.length > 5) lines.push(`- ……另有 ${mutating.length - 5} 条未列出`);
267
+ } else {
268
+ lines.push('');
269
+ lines.push('这一轮也没有执行过写操作(可能只是问了几句或读了文件)。');
270
+ }
271
+ lines.push('');
272
+ } else {
273
+ const parts = [];
274
+ for (const kind of ['deleted', 'created', 'modified', 'moved']) {
275
+ const n = counts[kind] || 0;
276
+ if (n > 0) parts.push(`${KIND_LABEL[kind]} ${n}`);
277
+ }
278
+ lines.push(`共 ${counts.total ?? changes.length} 处变更:${parts.join(' · ')}`);
279
+ lines.push('');
280
+ lines.push(
281
+ `归因:${CONFIDENCE_ORDER.map((key) => `${CONFIDENCE_MARK[key]}${CONFIDENCE_LABEL[key]} ${confidence[key] || 0}`).join(' · ')}`,
282
+ );
283
+ lines.push('');
284
+
285
+ const byRoot = new Map();
286
+ for (const change of changes) {
287
+ const key = change.rootId || change.root || '?';
288
+ if (!byRoot.has(key)) byRoot.set(key, []);
289
+ byRoot.get(key).push(change);
290
+ }
291
+
292
+ for (const [rootId, list] of byRoot) {
293
+ const root = roots.find((r) => r.id === rootId) || { id: rootId, path: list[0]?.root };
294
+ lines.push(`## ${rootId}(${maskPath(root.path || '', maskHome)})`);
295
+ lines.push('');
296
+ lines.push('| 变更 | 条目 | 大小 | mtime | 归因 | 依据 |');
297
+ lines.push('| --- | --- | --- | --- | --- | --- |');
298
+ for (const change of list) {
299
+ const attr = change.attribution || { confidence: 'unattributed' };
300
+ const { mark, label } = confidenceLabel(attr);
301
+ // 删除没有"发生时间",这个时间只是它生前的 mtime,必须标出来,否则会被当成删除时刻
302
+ const when = change.kind === 'deleted'
303
+ ? `删除前 ${formatClock(change.before?.mtime)}`
304
+ : formatClock(change.after?.mtime);
305
+ const size = change.kind === 'deleted' ? change.before?.size : change.after?.size;
306
+ const basis = attr.tool
307
+ ? `${attr.tool}${attr.verb ? ` · ${attr.verb}` : ''}${attr.how ? ` (${attr.how})` : ''}`
308
+ : attr.how || '—';
309
+ lines.push(
310
+ `| ${KIND_LABEL[change.kind] || change.kind} | ${cell(change.rel)} | ${formatSize(size)} | ${when} | ${mark}${label} | ${cell(basis)} |`,
311
+ );
312
+ }
313
+ lines.push('');
314
+ }
315
+
316
+ const moved = changes.filter((change) => change.kind === 'moved');
317
+ if (moved.length > 0) {
318
+ lines.push('## 移走候选(启发式:同名 + 同大小 + 时间接近)');
319
+ lines.push('');
320
+ for (const change of moved) {
321
+ const delta = Number.isFinite(change.mtimeDeltaMs) ? `,mtime 差 ${change.mtimeDeltaMs} ms` : '';
322
+ lines.push(`- ${cell(change.movedFrom)} → ${cell(change.rel)}${delta}`);
323
+ }
324
+ lines.push('');
325
+ }
326
+
327
+ const weak = changes.filter((change) => {
328
+ const key = change.attribution?.confidence;
329
+ return key === 'window' || key === 'unattributed' || !key;
330
+ });
331
+ if (weak.length > 0) {
332
+ lines.push('## 归因不到的部分');
333
+ lines.push('');
334
+ lines.push(`${weak.length} 处变更只能落到时间窗或无法归因。这类变更通常来自 shell / pwsh 的间接行为,`);
335
+ lines.push('**无法逐文件归因**——本插件不做这种断言。以下是本轮执行过的命令原文,供你自己比对:');
336
+ lines.push('');
337
+ for (const call of (record.calls || []).slice(0, 5)) {
338
+ lines.push(`- \`${cell(call.name || 'tool')}\` ${cell(call.excerpt || '')}`);
339
+ }
340
+ if ((record.calls || []).length === 0) lines.push('- (本轮没有工具调用记录)');
341
+ lines.push('');
342
+ }
343
+ }
344
+
345
+ const outside = outsideRootPaths(record);
346
+ if (outside.length > 0) {
347
+ lines.push('## 命令提到、但不在观测根内的路径');
348
+ lines.push('');
349
+ lines.push('这些路径出现在本轮命令里,但不在观测范围内;插件没看过它们的磁盘状态,下面只来自命令行文本。');
350
+ lines.push('');
351
+ for (const item of outside.slice(0, 20)) {
352
+ const times = item.count > 1 ? ` ×${item.count}` : '';
353
+ lines.push(`- \`${cell(maskPath(item.path, maskHome))}\`${times} · ${cell(item.tools.slice(0, 3).join('、'))}`);
354
+ }
355
+ if (outside.length > 20) lines.push(`- ……另有 ${outside.length - 20} 条未列出`);
356
+ lines.push('');
357
+ }
358
+
359
+ for (const line of renderHealth(record)) lines.push(line);
360
+
361
+ const skipped = Array.isArray(record?.skipped) ? record.skipped : [];
362
+ if (skipped.length > 0) {
363
+ lines.push('## 跳过的根(读不到 ≠ 被删光)');
364
+ lines.push('');
365
+ for (const item of skipped) lines.push(`- ${item.id || '?'}:${item.reason || 'unreadable'}`);
366
+ lines.push('');
367
+ }
368
+
369
+ const symptoms = options.symptoms === false
370
+ ? []
371
+ : detectSymptoms(changes, { roots });
372
+ if (symptoms.length > 0) {
373
+ lines.push('## 你看到的现象可能对应');
374
+ lines.push('');
375
+ for (const symptom of symptoms.slice(0, 3)) {
376
+ lines.push(`### ${symptom.title}`);
377
+ lines.push('');
378
+ lines.push(`命中理由:${symptom.because}`);
379
+ if (symptom.note) lines.push(`说明:${symptom.note}`);
380
+ lines.push('');
381
+ for (const check of symptom.checks || []) {
382
+ lines.push(`- ${check.label}`);
383
+ lines.push('');
384
+ lines.push('```powershell');
385
+ lines.push(check.command);
386
+ lines.push('```');
387
+ lines.push('');
388
+ }
389
+ }
390
+ }
391
+
392
+ lines.push('---');
393
+ lines.push('只记录路径、大小、时间,不读文件内容;不自动还原、不代为执行任何命令。');
394
+ return lines.join('\n');
395
+ }
396
+
397
+ export function renderHistory(records, options = {}) {
398
+ const list = Array.isArray(records) ? records : [];
399
+ if (list.length === 0) return '还没有历史记录。跑一轮对话后再来看。';
400
+ const lines = [];
401
+ lines.push(`# 最近 ${list.length} 轮变更`);
402
+ lines.push('');
403
+ lines.push('| 时间 | 会话 | 轮 | 变更 | 主要归因 |');
404
+ lines.push('| --- | --- | --- | --- | --- |');
405
+ for (const record of list) {
406
+ const counts = record.counts || {};
407
+ const parts = [];
408
+ for (const kind of ['deleted', 'created', 'modified', 'moved']) {
409
+ const n = counts[kind] || 0;
410
+ if (n > 0) parts.push(`${KIND_LABEL[kind]}${n}`);
411
+ }
412
+ const confidence = counts.confidence || {};
413
+ const top = CONFIDENCE_ORDER
414
+ .filter((key) => (confidence[key] || 0) > 0)
415
+ .map((key) => `${CONFIDENCE_MARK[key]}${confidence[key]}`)
416
+ .join(' ');
417
+ const mutating = (Array.isArray(record.calls) ? record.calls : []).filter((c) => c.mutating).length;
418
+ const changeCell = parts.length > 0
419
+ ? parts.join(' ')
420
+ : mutating > 0 ? `0(写过 ${mutating} 条命令,根外?)` : '无';
421
+ lines.push(
422
+ `| ${formatDay(record.at)} | ${shortSession(record.session)} | ${record.turn ?? '?'} | ${changeCell} | ${top || '—'} |`,
423
+ );
424
+ }
425
+ lines.push('');
426
+ lines.push('要逐条明细:`/aftermath report --last 1`');
427
+ return lines.join('\n');
428
+ }