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/GUIDE.md +277 -0
- package/LICENSE +21 -0
- package/README.md +220 -2
- package/assets/icon-128.png +0 -0
- package/assets/icon-256.png +0 -0
- package/assets/icon-512.png +0 -0
- package/assets/icon-96.png +0 -0
- package/assets/icon-e-dark.html +26 -0
- package/assets/icon-e-light.html +26 -0
- package/assets/icon-light-512.png +0 -0
- package/assets/icon-light-96.png +0 -0
- package/cordis.patch.yml +3 -0
- package/lib/attribution.js +641 -0
- package/lib/client.js +894 -0
- package/lib/command-registration.js +21 -0
- package/lib/commands.js +379 -0
- package/lib/config.js +237 -0
- package/lib/diff.js +231 -0
- package/lib/index.js +603 -0
- package/lib/panel.js +126 -0
- package/lib/report.js +428 -0
- package/lib/scan.js +186 -0
- package/lib/schema.js +196 -0
- package/lib/store.js +188 -0
- package/lib/symptoms.js +148 -0
- package/lib/version.js +22 -0
- package/package.json +72 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,603 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-aftermath —— 从「后果」倒查「AI 干了什么」。
|
|
3
|
+
*
|
|
4
|
+
* 观测点只有一处:session/event。不用 fs.watch(NTFS 会丢事件),
|
|
5
|
+
* 不用 tools/pre-execute / post-execute(那是改造结果用的,且拿不到全貌)。
|
|
6
|
+
* 每一轮自带前后两份快照做差,"后果"是文件系统的事实,"原因"才是归因的猜测。
|
|
7
|
+
*
|
|
8
|
+
* 稳定性约定:
|
|
9
|
+
* - 每个回调 full try/catch,任何异常只记日志,绝不外抛;
|
|
10
|
+
* - 不使用子进程、不读注册表、不读文件内容、不自动还原;
|
|
11
|
+
* - 不注册系统提示词 section(不碰前缀缓存)。
|
|
12
|
+
*/
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import { DEFAULTS, normalizeConfig, resolveRoots, stateDir } from './config.js';
|
|
16
|
+
import { Config, readField, SCHEMA_SOURCE } from './schema.js';
|
|
17
|
+
import { scanRoots } from './scan.js';
|
|
18
|
+
import { diffSnapshotPair, toChangeList } from './diff.js';
|
|
19
|
+
import { attributeChanges, summarizeConfidence, extractEvidence, analyzeIntervals } from './attribution.js';
|
|
20
|
+
import { appendTurn, ensureDirs, loadBaseline, pruneTurns, readTurns, saveBaseline, saveResolvedConfig, saveSettingsProbe } from './store.js';
|
|
21
|
+
import { renderChatLine, outsideRootPaths } from './report.js';
|
|
22
|
+
import { buildPanelPayload, PANEL_HEADERS, PANEL_PATH } from './panel.js';
|
|
23
|
+
import { installCommands, buildHistoryText } from './commands.js';
|
|
24
|
+
import { VERSION } from './version.js';
|
|
25
|
+
|
|
26
|
+
export const name = 'dsh-aftermath';
|
|
27
|
+
|
|
28
|
+
// 本插件要注册 aftermath_history 工具,因此依赖 `tools` 服务。
|
|
29
|
+
// 之前误留空:Cordis 里访问 ctx.tools 必须先在这里声明,否则 activate
|
|
30
|
+
// 阶段会抛 "cannot get property 'tools' without inject"(工具注册那行的
|
|
31
|
+
// `if (ctx.tools)` 护不住,因为读属性本身就会抛)。
|
|
32
|
+
export const inject = ['tools'];
|
|
33
|
+
|
|
34
|
+
// 行 Config:宿主据此在 Plugins 页提供设置卡片;字段全部 volatile,
|
|
35
|
+
// 改完立即生效(不重启插件,因此不丢当前基线)。拿不到 schemastery 时为
|
|
36
|
+
// undefined——宿主会原样透传配置,插件功能不受影响,只是没有图形界面。
|
|
37
|
+
export { Config };
|
|
38
|
+
|
|
39
|
+
function sessionKey(session) {
|
|
40
|
+
if (!session) return 'unknown';
|
|
41
|
+
if (typeof session.id === 'string') return session.id;
|
|
42
|
+
if (typeof session.sessionId === 'string') return session.sessionId;
|
|
43
|
+
return 'anonymous';
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function toEvent(first, second) {
|
|
47
|
+
if (second && typeof second.type === 'string') return second;
|
|
48
|
+
if (first && typeof first.type === 'string') return first;
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function snapshot(roots, cfg) {
|
|
53
|
+
try {
|
|
54
|
+
return scanRoots(roots, cfg);
|
|
55
|
+
} catch {
|
|
56
|
+
return roots.map((root) => ({
|
|
57
|
+
id: root.id,
|
|
58
|
+
root: root.path,
|
|
59
|
+
ok: false,
|
|
60
|
+
error: 'scan-crashed',
|
|
61
|
+
entries: [],
|
|
62
|
+
count: 0,
|
|
63
|
+
}));
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function sameSnapshot(a, b) {
|
|
68
|
+
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
|
|
69
|
+
for (let i = 0; i < a.length; i += 1) {
|
|
70
|
+
if (a[i].id !== b[i].id) return false;
|
|
71
|
+
const left = a[i].entries || [];
|
|
72
|
+
const right = b[i].entries || [];
|
|
73
|
+
if (left.length !== right.length) return false;
|
|
74
|
+
for (let j = 0; j < left.length; j += 1) {
|
|
75
|
+
if (left[j].rel !== right[j].rel) return false;
|
|
76
|
+
if (left[j].size !== right[j].size) return false;
|
|
77
|
+
if (left[j].mtime !== right[j].mtime) return false;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return true;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function apply(ctx, rawConfig) {
|
|
84
|
+
const raw = rawConfig && typeof rawConfig === 'object' ? rawConfig : {};
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 每次取用前重新读一遍配置。
|
|
88
|
+
* volatile 字段在宿主里是 Volatile 引用(`config.field.get()`),所以这里读到的
|
|
89
|
+
* 永远是「用户此刻在设置卡片里选中的值」,不需要重启插件。
|
|
90
|
+
*/
|
|
91
|
+
const readLiveConfig = () => {
|
|
92
|
+
const picked = {};
|
|
93
|
+
for (const key of Object.keys(DEFAULTS)) {
|
|
94
|
+
const value = readField(raw, key);
|
|
95
|
+
if (value !== undefined) picked[key] = value;
|
|
96
|
+
}
|
|
97
|
+
return normalizeConfig(picked);
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
let cfg = readLiveConfig();
|
|
101
|
+
let roots = resolveRoots(cfg);
|
|
102
|
+
const state = { lastAt: 0, lastError: null, turns: 0, appended: 0 };
|
|
103
|
+
const deps = { ctx, cfg, roots, state };
|
|
104
|
+
|
|
105
|
+
/** 宿主不同版本对 ctx.logger 的形态不一致,取不到就静默丢弃。 */
|
|
106
|
+
const logger = (level, message) => {
|
|
107
|
+
try {
|
|
108
|
+
const log = typeof ctx.logger === 'function' ? ctx.logger('aftermath') : null;
|
|
109
|
+
if (log && typeof log[level] === 'function') log[level](message);
|
|
110
|
+
} catch {
|
|
111
|
+
/* 日志不可用就算了 */
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
/** 刷新 deps 上的活动配置;任何失败都退回上一次的值,绝不让调用方踩空。 */
|
|
116
|
+
const refresh = () => {
|
|
117
|
+
try {
|
|
118
|
+
const next = readLiveConfig();
|
|
119
|
+
const nextRoots = resolveRoots(next);
|
|
120
|
+
cfg = next;
|
|
121
|
+
roots = nextRoots;
|
|
122
|
+
deps.cfg = next;
|
|
123
|
+
deps.roots = nextRoots;
|
|
124
|
+
} catch (error) {
|
|
125
|
+
state.lastError = `读取配置失败:${error?.message || error}`;
|
|
126
|
+
}
|
|
127
|
+
return cfg;
|
|
128
|
+
};
|
|
129
|
+
deps.refresh = refresh;
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* 设置命名空间自检。
|
|
133
|
+
* 宿主只为「导出 schemastery Config 且已激活」的条目提供设置命名空间;拿不到时
|
|
134
|
+
* Plugins 页的卡片只剩一段说明,用户没法改配置,而且没有任何提示说明为什么。
|
|
135
|
+
* 这里把宿主真正看到的命名空间记下来(只有命名空间名和字段名,没有值),
|
|
136
|
+
* 启动时落一份到状态目录,同时供 `/aftermath doctor` 现场查询。
|
|
137
|
+
*/
|
|
138
|
+
deps.settings = null;
|
|
139
|
+
deps.lastProbe = null;
|
|
140
|
+
/**
|
|
141
|
+
* describe() 回来的命名空间视图里,schema 是 toJSON 之后的 {uid, refs} 快照,
|
|
142
|
+
* 没有 dict;字段名只能从值对象(value/user/base)上取,取不到再看 refs。
|
|
143
|
+
*/
|
|
144
|
+
const fieldsOf = (row) => {
|
|
145
|
+
// schema 优先:dict 才是字段名列表(properties 是 JSON Schema 的叫法,schemastery 不用它)
|
|
146
|
+
const refs = row?.schema?.refs;
|
|
147
|
+
const uid = row?.schema?.uid;
|
|
148
|
+
const node = refs && uid !== undefined ? refs[String(uid)] : null;
|
|
149
|
+
const dict = node && (node.dict || node.properties);
|
|
150
|
+
if (dict && typeof dict === 'object' && Object.keys(dict).length > 0) return Object.keys(dict);
|
|
151
|
+
|
|
152
|
+
// 拿不到 schema 快照时退回值对象:注意它只包含宿主实际解析出来的键
|
|
153
|
+
let merged = [];
|
|
154
|
+
for (const bucket of [row?.value, row?.user, row?.base]) {
|
|
155
|
+
if (bucket && typeof bucket === 'object') {
|
|
156
|
+
for (const key of Object.keys(bucket)) if (!merged.includes(key)) merged.push(key);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return merged;
|
|
160
|
+
};
|
|
161
|
+
deps.probeSettings = () => {
|
|
162
|
+
const report = {
|
|
163
|
+
at: new Date().toISOString(),
|
|
164
|
+
plugin: name,
|
|
165
|
+
version: VERSION,
|
|
166
|
+
configExported: typeof Config === 'function',
|
|
167
|
+
schemaSource: SCHEMA_SOURCE,
|
|
168
|
+
namespaces: null,
|
|
169
|
+
ourNamespace: false,
|
|
170
|
+
error: null,
|
|
171
|
+
};
|
|
172
|
+
const settings = deps.settings;
|
|
173
|
+
if (!settings || typeof settings.describe !== 'function') {
|
|
174
|
+
report.error = 'settings 服务不可用:宿主没有提供给这个插件';
|
|
175
|
+
deps.lastProbe = report;
|
|
176
|
+
return report;
|
|
177
|
+
}
|
|
178
|
+
try {
|
|
179
|
+
report.namespaces = settings.describe({ redactSecrets: true }).map((row) => ({
|
|
180
|
+
ns: row?.ns ?? null,
|
|
181
|
+
fields: fieldsOf(row),
|
|
182
|
+
}));
|
|
183
|
+
report.ourNamespace = report.namespaces.some((row) => row.ns === name);
|
|
184
|
+
if (!report.ourNamespace) {
|
|
185
|
+
report.error = `宿主没有为 ${name} 建立设置命名空间:Config ${report.configExported ? '已导出' : '未导出'}`;
|
|
186
|
+
}
|
|
187
|
+
} catch (error) {
|
|
188
|
+
report.error = `describe 失败:${error?.message || error}`;
|
|
189
|
+
}
|
|
190
|
+
deps.lastProbe = report;
|
|
191
|
+
return report;
|
|
192
|
+
};
|
|
193
|
+
/**
|
|
194
|
+
* 启动那一瞬间本插件的 fiber 很可能还没进入 ACTIVE,describe() 自然看不到自己。
|
|
195
|
+
* 所以隔一会儿再探一次,写满最后一次结果;仍然失败就保留,让 /aftermath doctor 说话。
|
|
196
|
+
*/
|
|
197
|
+
const reprobe = () => {
|
|
198
|
+
if (deps.lastProbe?.ourNamespace) return;
|
|
199
|
+
try {
|
|
200
|
+
const report = deps.probeSettings();
|
|
201
|
+
if (report?.namespaces) saveSettingsProbe(report);
|
|
202
|
+
} catch (error) {
|
|
203
|
+
logger('warn', `设置自检重探失败:${error?.message || error}`);
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
try {
|
|
208
|
+
ctx.inject(['settings'], (settingsCtx) => {
|
|
209
|
+
try {
|
|
210
|
+
deps.settings = settingsCtx.get('settings');
|
|
211
|
+
saveSettingsProbe(deps.probeSettings());
|
|
212
|
+
if (!deps.settings) return;
|
|
213
|
+
logger('info', '设置命名空间已就绪');
|
|
214
|
+
const timer = setTimeout(reprobe, 3000);
|
|
215
|
+
if (timer && typeof timer.unref === 'function') timer.unref();
|
|
216
|
+
} catch (error) {
|
|
217
|
+
logger('warn', `设置自检失败:${error?.message || error}`);
|
|
218
|
+
}
|
|
219
|
+
});
|
|
220
|
+
} catch (error) {
|
|
221
|
+
logger('warn', `settings 服务注入失败:${error?.message || error}`);
|
|
222
|
+
}
|
|
223
|
+
const sessions = new WeakMap();
|
|
224
|
+
|
|
225
|
+
try {
|
|
226
|
+
const dirs = ensureDirs();
|
|
227
|
+
if (!dirs.ok) state.lastError = `状态目录不可写:${dirs.error}`;
|
|
228
|
+
saveResolvedConfig({
|
|
229
|
+
version: VERSION,
|
|
230
|
+
enabled: cfg.enabled,
|
|
231
|
+
depth: cfg.depth,
|
|
232
|
+
maxEntries: cfg.maxEntries,
|
|
233
|
+
retentionDays: cfg.retentionDays,
|
|
234
|
+
roots: roots.map((root) => ({ id: root.id, path: root.path })),
|
|
235
|
+
stateDir: stateDir(),
|
|
236
|
+
});
|
|
237
|
+
const pruned = pruneTurns(cfg.retentionDays);
|
|
238
|
+
if (pruned > 0) logger('info', `清理了 ${pruned} 个过期存档`);
|
|
239
|
+
} catch (error) {
|
|
240
|
+
state.lastError = error?.message || String(error);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
if (!cfg.enabled) {
|
|
244
|
+
// 不 return:开关要能在运行中打开。每轮开始/结束各自判一次 enabled。
|
|
245
|
+
logger('info', 'enabled=false,本轮不做快照(可在设置里随时打开)');
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
if (roots.length === 0) {
|
|
249
|
+
logger('warn', '没有解析出任何观测根;检查配置里的 roots / extraRoots');
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** 会话当时的工作目录:DSH 的 Session header 里有,用它当隐式观测根最省心。 */
|
|
253
|
+
const cwdOf = (session) => {
|
|
254
|
+
try {
|
|
255
|
+
const cwd = session?.header?.cwd ?? session?.cwd ?? null;
|
|
256
|
+
if (typeof cwd !== 'string' || !cwd.trim()) return null;
|
|
257
|
+
return path.win32.normalize(cwd.trim());
|
|
258
|
+
} catch {
|
|
259
|
+
return null;
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
const rootsForTurn = (session) => {
|
|
264
|
+
const base = deps.roots || [];
|
|
265
|
+
if (cfg.followCwd === false) return base;
|
|
266
|
+
const cwd = cwdOf(session);
|
|
267
|
+
if (!cwd) return base;
|
|
268
|
+
const lower = cwd.toLowerCase();
|
|
269
|
+
// 已经在某个根之下(或就是某个根)就不重复加
|
|
270
|
+
if (base.some((root) => {
|
|
271
|
+
const rootLower = String(root.path || '').toLowerCase();
|
|
272
|
+
return lower === rootLower || lower.startsWith(`${rootLower}${'\\'}`);
|
|
273
|
+
})) return base;
|
|
274
|
+
try {
|
|
275
|
+
if (!fs.statSync(cwd).isDirectory()) return base;
|
|
276
|
+
} catch {
|
|
277
|
+
return base;
|
|
278
|
+
}
|
|
279
|
+
let depth = cfg.depth;
|
|
280
|
+
try {
|
|
281
|
+
// 顶层就有几十个子项的大目录(项目根、用户目录),再递归下去只会拖慢并制造噪音
|
|
282
|
+
if (fs.readdirSync(cwd).length > 60) depth = Math.min(depth, 1);
|
|
283
|
+
} catch {
|
|
284
|
+
/* 读不到就按默认深度 */
|
|
285
|
+
}
|
|
286
|
+
return [...base, { id: 'cwd', path: cwd, requested: cwd, exists: true, via: 'cwd', depth }];
|
|
287
|
+
};
|
|
288
|
+
|
|
289
|
+
const finalizeTurn = (session, turnNumber) => {
|
|
290
|
+
const entry = sessions.get(session);
|
|
291
|
+
if (!entry || !entry.pre) return;
|
|
292
|
+
refresh();
|
|
293
|
+
if (!cfg.enabled) {
|
|
294
|
+
sessions.set(session, { pre: null, at: entry.at, calls: [], turn: entry.turn });
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
const at = Date.now();
|
|
298
|
+
const post = snapshot(entry.roots || roots, cfg);
|
|
299
|
+
let delta = { created: [], deleted: [], modified: [], roots: [], skipped: [] };
|
|
300
|
+
try {
|
|
301
|
+
delta = diffSnapshotPair(entry.pre, post);
|
|
302
|
+
} catch (error) {
|
|
303
|
+
state.lastError = `diff 失败:${error?.message || error}`;
|
|
304
|
+
logger('warn', state.lastError);
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const all = toChangeList(delta);
|
|
309
|
+
const limited = all.slice(0, cfg.maxChangesPerReport);
|
|
310
|
+
const attributed = attributeChanges(limited, entry.calls || [], {
|
|
311
|
+
slackMs: cfg.intervalSlackMs,
|
|
312
|
+
turnEndAt: at,
|
|
313
|
+
});
|
|
314
|
+
const confidence = summarizeConfidence(attributed);
|
|
315
|
+
const intervals = analyzeIntervals(entry.calls || [], {
|
|
316
|
+
slackMs: cfg.intervalSlackMs,
|
|
317
|
+
turnEndAt: at,
|
|
318
|
+
});
|
|
319
|
+
const scanMs = post.reduce((sum, snap) => sum + (Number.isFinite(snap.ms) ? snap.ms : 0), 0);
|
|
320
|
+
const scanned = post.reduce((sum, snap) => sum + (snap.count || 0), 0);
|
|
321
|
+
const changed = all.filter((c) => c.kind === 'created' || c.kind === 'deleted' || c.kind === 'modified').length;
|
|
322
|
+
const health = {
|
|
323
|
+
scanMs: Math.round(scanMs),
|
|
324
|
+
ambiguousResults: entry.ambiguousResults || 0,
|
|
325
|
+
roots: post.length,
|
|
326
|
+
scanned,
|
|
327
|
+
changed,
|
|
328
|
+
listed: limited.length,
|
|
329
|
+
truncated: all.length > limited.length,
|
|
330
|
+
intervals,
|
|
331
|
+
};
|
|
332
|
+
const counts = {
|
|
333
|
+
created: all.filter((c) => c.kind === 'created').length,
|
|
334
|
+
deleted: all.filter((c) => c.kind === 'deleted').length,
|
|
335
|
+
modified: all.filter((c) => c.kind === 'modified').length,
|
|
336
|
+
moved: all.filter((c) => c.kind === 'moved').length,
|
|
337
|
+
total: all.length,
|
|
338
|
+
confidence,
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
const mapped = (entry.calls || []).map((call) => {
|
|
342
|
+
let evidence = null;
|
|
343
|
+
try {
|
|
344
|
+
evidence = extractEvidence(call);
|
|
345
|
+
} catch {
|
|
346
|
+
evidence = null;
|
|
347
|
+
}
|
|
348
|
+
return {
|
|
349
|
+
name: call.name || evidence?.name || 'tool',
|
|
350
|
+
verb: evidence?.verb || null,
|
|
351
|
+
mutating: evidence?.mutating === true,
|
|
352
|
+
source: evidence?.source || null,
|
|
353
|
+
excerpt: evidence?.excerpt || '',
|
|
354
|
+
at: call.at || null,
|
|
355
|
+
endAt: typeof call.endAt === 'number' ? call.endAt : null,
|
|
356
|
+
// 命令里出现过的绝对路径:即使不在观测根内也存下来,
|
|
357
|
+
// 这是“根外发生了什么”的唯一线索(不扫盘,零额外成本)。
|
|
358
|
+
paths: (evidence?.absPaths || [])
|
|
359
|
+
.map((item) => item.path)
|
|
360
|
+
.filter((p) => typeof p === 'string' && p.length > 0 && p.length <= 320)
|
|
361
|
+
.slice(0, 12),
|
|
362
|
+
};
|
|
363
|
+
});
|
|
364
|
+
// 写调用一条都不能扔:quiet 判定和“根外线索”全靠它。
|
|
365
|
+
// 只读调用留前 20 条足够看上下文,多留只是噪音。
|
|
366
|
+
const mutatingCalls = mapped.filter((call) => call.mutating);
|
|
367
|
+
const readCalls = mapped.filter((call) => !call.mutating).slice(0, 20);
|
|
368
|
+
const calls = [...mutatingCalls, ...readCalls];
|
|
369
|
+
const callsTruncated = mapped.length > calls.length;
|
|
370
|
+
|
|
371
|
+
const record = {
|
|
372
|
+
v: 2,
|
|
373
|
+
kind: all.length > 0 ? 'changes' : 'quiet',
|
|
374
|
+
at,
|
|
375
|
+
session: sessionKey(session),
|
|
376
|
+
turn: Number.isInteger(turnNumber) ? turnNumber : entry.turn ?? 0,
|
|
377
|
+
startedAt: entry.at,
|
|
378
|
+
durationMs: Math.max(0, at - (entry.at || at)),
|
|
379
|
+
version: VERSION,
|
|
380
|
+
roots: delta.roots,
|
|
381
|
+
skipped: delta.skipped,
|
|
382
|
+
counts,
|
|
383
|
+
health,
|
|
384
|
+
changes: attributed.map((change) => ({
|
|
385
|
+
kind: change.kind,
|
|
386
|
+
rootId: change.rootId,
|
|
387
|
+
root: change.root,
|
|
388
|
+
rel: change.rel,
|
|
389
|
+
abs: change.root && change.rel ? `${change.root}\\${change.rel}` : change.rel,
|
|
390
|
+
before: change.before ? { size: change.before.size, mtime: change.before.mtime, dir: change.before.dir } : null,
|
|
391
|
+
after: change.after ? { size: change.after.size, mtime: change.after.mtime, dir: change.after.dir } : null,
|
|
392
|
+
heuristic: change.heuristic === true,
|
|
393
|
+
movedFrom: change.movedFrom || null,
|
|
394
|
+
attribution: change.attribution || null,
|
|
395
|
+
})),
|
|
396
|
+
calls,
|
|
397
|
+
callsTruncated,
|
|
398
|
+
truncated: all.length > limited.length,
|
|
399
|
+
};
|
|
400
|
+
|
|
401
|
+
const incomplete = post.filter((snap) => snap.ok === false || snap.complete === false || snap.truncated === true);
|
|
402
|
+
if (incomplete.length === 0) {
|
|
403
|
+
try {
|
|
404
|
+
saveBaseline({ at, roots: post });
|
|
405
|
+
} catch {
|
|
406
|
+
/* 基线失败不影响主流程 */
|
|
407
|
+
}
|
|
408
|
+
} else {
|
|
409
|
+
// 名单不全就当基线,下一轮会把它当成“全都新建了”。宁可这条基线不更新。
|
|
410
|
+
logger('warn', `本轮有 ${incomplete.length} 个观测根不完整,未更新基线:${incomplete.map((s) => s.id).join(', ')}`);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
const quiet = all.length === 0;
|
|
414
|
+
const keepQuiet = quiet && cfg.recordQuietTurns !== false && mutatingCalls.length > 0;
|
|
415
|
+
if (!quiet || keepQuiet) {
|
|
416
|
+
const file = appendTurn(record);
|
|
417
|
+
if (file) state.appended += 1;
|
|
418
|
+
else state.lastError = '写入记录失败(状态目录不可写?)';
|
|
419
|
+
state.lastAt = at;
|
|
420
|
+
}
|
|
421
|
+
state.turns += 1;
|
|
422
|
+
sessions.set(session, { pre: post, at, calls: [], turn: entry.turn });
|
|
423
|
+
};
|
|
424
|
+
|
|
425
|
+
const onEvent = (first, second) => {
|
|
426
|
+
const event = toEvent(first, second);
|
|
427
|
+
if (!event) return;
|
|
428
|
+
const session = second && typeof second.type === 'string' ? first : first?.session ?? first;
|
|
429
|
+
const type = event.type;
|
|
430
|
+
try {
|
|
431
|
+
if (type === 'turn/start') {
|
|
432
|
+
const at = Date.now();
|
|
433
|
+
refresh();
|
|
434
|
+
const turnRoots = rootsForTurn(session);
|
|
435
|
+
const pre = cfg.enabled ? snapshot(turnRoots, cfg) : null;
|
|
436
|
+
sessions.set(session, { pre, at, calls: [], turn: event.data?.turn ?? 0, roots: turnRoots });
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
if (type === 'tool/call') {
|
|
440
|
+
const entry = sessions.get(session);
|
|
441
|
+
if (!entry) return;
|
|
442
|
+
const at = Number.isFinite(event.time) ? event.time : Date.now();
|
|
443
|
+
entry.calls.push({
|
|
444
|
+
callId: event.data?.callId ?? null,
|
|
445
|
+
name: event.data?.name ?? 'tool',
|
|
446
|
+
arguments: typeof event.data?.arguments === 'string' ? event.data.arguments : '',
|
|
447
|
+
at,
|
|
448
|
+
step: Number.isInteger(event.data?.step) ? event.data.step : null,
|
|
449
|
+
/** 调用结束时刻;等 tool/result 回来时补上。 */
|
|
450
|
+
endAt: null,
|
|
451
|
+
});
|
|
452
|
+
if (entry.calls.length > 200) entry.calls.splice(0, entry.calls.length - 200);
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
if (type === 'tool/result') {
|
|
456
|
+
// 只用来给对应的 tool/call 打上结束时刻,判定「这次调用持续到几点」。
|
|
457
|
+
// 配对优先级:callId(最硬)→ 同 step 只有一条候选 → 只剩一条未结束 → 退到最早的并记歧义。
|
|
458
|
+
const entry = sessions.get(session);
|
|
459
|
+
if (!entry || entry.calls.length === 0) return;
|
|
460
|
+
const at = Number.isFinite(event.time) ? event.time : Date.now();
|
|
461
|
+
const data = event.data || {};
|
|
462
|
+
const step = Number.isInteger(data.step) ? data.step : null;
|
|
463
|
+
const callId = typeof data.callId === 'string'
|
|
464
|
+
? data.callId
|
|
465
|
+
: typeof data.message?.toolCallId === 'string' ? data.message.toolCallId : null;
|
|
466
|
+
const pending = entry.calls.filter((call) => call.endAt === null);
|
|
467
|
+
if (pending.length === 0) return;
|
|
468
|
+
|
|
469
|
+
let target = callId ? pending.find((call) => call.callId === callId) : null;
|
|
470
|
+
if (!target) {
|
|
471
|
+
const sameStep = step === null ? [] : pending.filter((call) => call.step === step);
|
|
472
|
+
if (sameStep.length === 1) target = sameStep[0];
|
|
473
|
+
else if (pending.length === 1) target = pending[0];
|
|
474
|
+
else {
|
|
475
|
+
// 并行且乱序:无法唯一确定是哪个调用结束了。取最早的那条,但记下歧义,
|
|
476
|
+
// 让报告健康度把这件事说出来——不静默假装配对成功。
|
|
477
|
+
entry.ambiguousResults = (entry.ambiguousResults || 0) + 1;
|
|
478
|
+
target = sameStep[0] || pending[0];
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
target.endAt = Math.max(at, target.at ?? at);
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
if (type === 'turn/end') {
|
|
485
|
+
finalizeTurn(session, event.data?.turn);
|
|
486
|
+
}
|
|
487
|
+
} catch (error) {
|
|
488
|
+
state.lastError = `${type}: ${error?.message || error}`;
|
|
489
|
+
logger('warn', `事件处理失败 ${type}:${state.lastError}`);
|
|
490
|
+
}
|
|
491
|
+
};
|
|
492
|
+
|
|
493
|
+
try {
|
|
494
|
+
ctx.on('session/event', onEvent);
|
|
495
|
+
} catch (error) {
|
|
496
|
+
state.lastError = `订阅 session/event 失败:${error?.message || error}`;
|
|
497
|
+
logger('error', state.lastError);
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
try {
|
|
501
|
+
installCommands(ctx, deps);
|
|
502
|
+
} catch (error) {
|
|
503
|
+
logger('warn', `命令注册失败:${error?.message || error}`);
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// Plugins 页的「最近变更」面板:插件详情页没有会话,命令跑不起来,
|
|
507
|
+
// 所以由 Host 自己挂一条只读路由,客户端同源 fetch 即可。
|
|
508
|
+
try {
|
|
509
|
+
ctx.inject(['webServer'], (serverCtx) => {
|
|
510
|
+
try {
|
|
511
|
+
const server = serverCtx.get('webServer');
|
|
512
|
+
if (!server || typeof server.register !== 'function') return;
|
|
513
|
+
const dispose = server.register({
|
|
514
|
+
kind: 'exact',
|
|
515
|
+
path: PANEL_PATH,
|
|
516
|
+
resource: async () => {
|
|
517
|
+
refresh();
|
|
518
|
+
let records = [];
|
|
519
|
+
try {
|
|
520
|
+
records = readTurns({ limit: 8 });
|
|
521
|
+
} catch (error) {
|
|
522
|
+
state.lastError = `面板读取失败:${error?.message || error}`;
|
|
523
|
+
}
|
|
524
|
+
const today = records.filter((record) => {
|
|
525
|
+
const day = new Date(record?.at || 0);
|
|
526
|
+
const now = new Date();
|
|
527
|
+
return day.toDateString() === now.toDateString();
|
|
528
|
+
});
|
|
529
|
+
const latest = records[0] || null;
|
|
530
|
+
const payload = buildPanelPayload({
|
|
531
|
+
records: latest ? [{ ...latest, outside: outsideRootPaths(latest) }, ...records.slice(1)] : records,
|
|
532
|
+
roots,
|
|
533
|
+
config: cfg,
|
|
534
|
+
version: VERSION,
|
|
535
|
+
todayTurns: today.length,
|
|
536
|
+
todayChanges: today.reduce((sum, record) => sum + (record?.counts?.total || 0), 0),
|
|
537
|
+
});
|
|
538
|
+
return new Response(JSON.stringify(payload), { status: 200, headers: PANEL_HEADERS });
|
|
539
|
+
},
|
|
540
|
+
});
|
|
541
|
+
if (typeof dispose === 'function') {
|
|
542
|
+
ctx.effect(() => () => {
|
|
543
|
+
try {
|
|
544
|
+
dispose();
|
|
545
|
+
} catch { /* 卸载时尽力而为 */ }
|
|
546
|
+
});
|
|
547
|
+
}
|
|
548
|
+
} catch (error) {
|
|
549
|
+
logger('warn', `面板路由注册失败:${error?.message || error}`);
|
|
550
|
+
}
|
|
551
|
+
});
|
|
552
|
+
} catch (error) {
|
|
553
|
+
logger('warn', `webServer 服务注入失败:${error?.message || error}`);
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
if (ctx.tools && typeof ctx.tools.register === 'function') {
|
|
557
|
+
try {
|
|
558
|
+
ctx.tools.register({
|
|
559
|
+
name: 'aftermath_history',
|
|
560
|
+
description:
|
|
561
|
+
'读取 dsh-aftermath 在本机记录的文件变更历史:哪一轮删/改/移了哪些文件、能归因到哪条工具调用。' +
|
|
562
|
+
'当用户说「桌面的东西不见了」「图标全变白了」「某个目录被谁动了」时,用它按时间倒查。' +
|
|
563
|
+
'注意:用户消息里可能直接出现 `/aftermath report --since 10m` 这样的文本——新对话的第一条消息还没有会话,' +
|
|
564
|
+
'斜杠命令不会被当成命令执行,会作为普通消息送到你这里;这时不要尝试用 shell 去执行它,直接调用本工具按参数查询并转述结果。' +
|
|
565
|
+
'只读,不修改任何文件。',
|
|
566
|
+
parameters: {
|
|
567
|
+
type: 'object',
|
|
568
|
+
additionalProperties: false,
|
|
569
|
+
properties: {
|
|
570
|
+
since: { type: 'string', description: '时间范围,如 30m、2h、1d,缺省为最近若干轮' },
|
|
571
|
+
root: {
|
|
572
|
+
type: 'string',
|
|
573
|
+
enum: ['all', 'desktop', 'downloads', 'documents'],
|
|
574
|
+
description: '限定观测根,默认 all',
|
|
575
|
+
},
|
|
576
|
+
limit: { type: 'integer', description: '最多看几轮,默认 3,上限 20' },
|
|
577
|
+
},
|
|
578
|
+
},
|
|
579
|
+
output: {
|
|
580
|
+
schema: {
|
|
581
|
+
type: 'object',
|
|
582
|
+
additionalProperties: false,
|
|
583
|
+
properties: { text: { type: 'string' } },
|
|
584
|
+
},
|
|
585
|
+
render: (_args, value) => [{ type: 'text', text: String(value?.text ?? '') }],
|
|
586
|
+
},
|
|
587
|
+
async execute(args) {
|
|
588
|
+
try {
|
|
589
|
+
return { text: buildHistoryText(deps, args || {}) };
|
|
590
|
+
} catch (error) {
|
|
591
|
+
return { text: `读取 aftermath 记录失败:${error?.message || error}` };
|
|
592
|
+
}
|
|
593
|
+
},
|
|
594
|
+
});
|
|
595
|
+
} catch (error) {
|
|
596
|
+
logger('warn', `工具注册失败:${error?.message || error}`);
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
logger('info', `已启用,观测根 ${roots.map((root) => root.id).join(', ') || '(无)'},depth=${cfg.depth}`);
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
export { renderChatLine, loadBaseline, sameSnapshot };
|