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
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** 命令名冲突不启动失败:复制 purge 的降级策略(同名占用则换 fallback 名)。 */
|
|
2
|
+
export function registerCommand(commands, definition, fallback, warn) {
|
|
3
|
+
const log = typeof warn === 'function' ? warn : () => {};
|
|
4
|
+
const duplicate = (error, target) => String(error?.message || error).startsWith(`command "${target}" is already registered`);
|
|
5
|
+
|
|
6
|
+
try {
|
|
7
|
+
commands.register(definition);
|
|
8
|
+
return { name: definition.name, registered: definition.name, state: 'registered' };
|
|
9
|
+
} catch (error) {
|
|
10
|
+
if (!duplicate(error, definition.name)) return { name: definition.name, registered: null, state: 'error', error };
|
|
11
|
+
log(`[aftermath] /${definition.name} 已被其它插件占用,改用 /${fallback}`);
|
|
12
|
+
}
|
|
13
|
+
try {
|
|
14
|
+
commands.register({ ...definition, name: fallback });
|
|
15
|
+
return { name: definition.name, registered: fallback, state: 'fallback' };
|
|
16
|
+
} catch (error) {
|
|
17
|
+
if (!duplicate(error, fallback)) return { name: definition.name, registered: null, state: 'error', error };
|
|
18
|
+
log(`[aftermath] /${fallback} 也被占用,命令未注册`);
|
|
19
|
+
return { name: definition.name, registered: null, state: 'conflict' };
|
|
20
|
+
}
|
|
21
|
+
}
|
package/lib/commands.js
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* /aftermath 命令。只读历史 + 主动扫描,不改任何文件、不执行任何命令。
|
|
3
|
+
*
|
|
4
|
+
* 所有处理都包在 try/catch 里:命令报错只该返回一句 error,不该把宿主搞挂。
|
|
5
|
+
*/
|
|
6
|
+
import { registerCommand } from './command-registration.js';
|
|
7
|
+
import { scanRoots } from './scan.js';
|
|
8
|
+
import { diffSnapshotPair, toChangeList } from './diff.js';
|
|
9
|
+
import { attributeChanges, summarizeConfidence } from './attribution.js';
|
|
10
|
+
import { detectSymptoms } from './symptoms.js';
|
|
11
|
+
import { renderHistory, renderTurnReport } from './report.js';
|
|
12
|
+
import { loadBaseline, readTurns, saveBaseline, writeReport, dayKey } from './store.js';
|
|
13
|
+
import { resolveRoots, stateDir } from './config.js';
|
|
14
|
+
import { SCHEMA_SOURCE } from './schema.js';
|
|
15
|
+
import { VERSION } from './version.js';
|
|
16
|
+
|
|
17
|
+
const MAX_TEXT = 14000;
|
|
18
|
+
|
|
19
|
+
const HELP = [
|
|
20
|
+
'/aftermath report [--last N | --since 2h] [--root desktop] [--save] 看变更明细与归因',
|
|
21
|
+
'/aftermath scan [--keep] 立刻扫描,对比上次观测到的基线',
|
|
22
|
+
'/aftermath roots 打印解析出的观测根\n/aftermath roots --suggest | --add <路径> | --remove <路径> 推荐目录 / 预览加或减之后的样子',
|
|
23
|
+
'/aftermath status 配置与存档状态',
|
|
24
|
+
'/aftermath doctor 自检:设置命名空间是否就绪',
|
|
25
|
+
'/aftermath help 这张表',
|
|
26
|
+
].join('\n');
|
|
27
|
+
|
|
28
|
+
function parseDuration(token) {
|
|
29
|
+
const match = /^(\d+)\s*(s|m|h|d)?$/i.exec(String(token || '').trim());
|
|
30
|
+
if (!match) return null;
|
|
31
|
+
const n = Number(match[1]);
|
|
32
|
+
const unit = (match[2] || 'm').toLowerCase();
|
|
33
|
+
const factor = unit === 's' ? 1000 : unit === 'm' ? 60000 : unit === 'h' ? 3600000 : 86400000;
|
|
34
|
+
return n * factor;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function parseArgs(rawInput) {
|
|
38
|
+
const tokens = String(rawInput || '').trim().split(/\s+/).filter(Boolean);
|
|
39
|
+
const sub = (tokens.shift() || 'report').toLowerCase();
|
|
40
|
+
const options = { last: null, sinceMs: null, root: null, save: false, keep: false, suggest: false, add: null, remove: null, unknown: [] };
|
|
41
|
+
for (let i = 0; i < tokens.length; i += 1) {
|
|
42
|
+
const token = tokens[i];
|
|
43
|
+
if (token === '--save') options.save = true;
|
|
44
|
+
else if (token === '--keep') options.keep = true;
|
|
45
|
+
else if (token === '--suggest') options.suggest = true;
|
|
46
|
+
else if (token === '--add') options.add = String(tokens[(i += 1)] || '');
|
|
47
|
+
else if (token === '--remove') options.remove = String(tokens[(i += 1)] || '');
|
|
48
|
+
else if (token === '--last') options.last = Number(tokens[(i += 1)]);
|
|
49
|
+
else if (token === '--root') options.root = String(tokens[(i += 1)] || '').toLowerCase();
|
|
50
|
+
else if (token === '--since') {
|
|
51
|
+
const value = tokens[(i += 1)] || '';
|
|
52
|
+
const ms = parseDuration(value);
|
|
53
|
+
options.sinceMs = ms !== null ? Date.now() - ms : Date.parse(value);
|
|
54
|
+
if (!Number.isFinite(options.sinceMs)) options.sinceMs = null;
|
|
55
|
+
} else options.unknown.push(token);
|
|
56
|
+
}
|
|
57
|
+
return { sub, options };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function clampText(text) {
|
|
61
|
+
if (text.length <= MAX_TEXT) return text;
|
|
62
|
+
return `${text.slice(0, MAX_TEXT)}\n\n…(输出过长已截断,完整内容用 --save 落盘,或看 ${stateDir()})`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function filterByRoot(record, rootId) {
|
|
66
|
+
if (!rootId || rootId === 'all') return record;
|
|
67
|
+
const changes = (record.changes || []).filter((change) => change.rootId === rootId);
|
|
68
|
+
const confidence = summarizeConfidence(changes);
|
|
69
|
+
return {
|
|
70
|
+
...record,
|
|
71
|
+
changes,
|
|
72
|
+
counts: { ...record.counts, total: changes.length, confidence },
|
|
73
|
+
skipped: (record.skipped || []).filter((item) => item.id === rootId),
|
|
74
|
+
roots: (record.roots || []).filter((root) => root.id === rootId),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function scanNow(deps, flags = {}) {
|
|
79
|
+
const { cfg, roots } = deps;
|
|
80
|
+
const now = Date.now();
|
|
81
|
+
const snaps = scanRoots(roots, cfg);
|
|
82
|
+
const baseline = loadBaseline();
|
|
83
|
+
|
|
84
|
+
if (!baseline || !Array.isArray(baseline.roots)) {
|
|
85
|
+
saveBaseline({ at: now, roots: snaps });
|
|
86
|
+
const total = snaps.reduce((sum, snap) => sum + (snap.count || 0), 0);
|
|
87
|
+
return {
|
|
88
|
+
text: `第一次扫描,已建立基线:${snaps.length} 个根、${total} 个条目。\n以后再来 /aftermath scan 就能看到这段时间内发生了什么。`,
|
|
89
|
+
record: null,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const delta = diffSnapshotPair(baseline.roots, snaps);
|
|
94
|
+
const changes = attributeChanges(toChangeList(delta), []);
|
|
95
|
+
const confidence = summarizeConfidence(changes);
|
|
96
|
+
const record = {
|
|
97
|
+
v: 1,
|
|
98
|
+
at: now,
|
|
99
|
+
session: 'manual-scan',
|
|
100
|
+
turn: 0,
|
|
101
|
+
sinceAt: baseline.at || null,
|
|
102
|
+
roots: delta.roots,
|
|
103
|
+
skipped: delta.skipped,
|
|
104
|
+
counts: {
|
|
105
|
+
created: changes.filter((c) => c.kind === 'created').length,
|
|
106
|
+
deleted: changes.filter((c) => c.kind === 'deleted').length,
|
|
107
|
+
modified: changes.filter((c) => c.kind === 'modified').length,
|
|
108
|
+
moved: changes.filter((c) => c.kind === 'moved').length,
|
|
109
|
+
total: changes.length,
|
|
110
|
+
confidence,
|
|
111
|
+
},
|
|
112
|
+
changes,
|
|
113
|
+
calls: [],
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
if (!flags.keep) saveBaseline({ at: now, roots: snaps });
|
|
117
|
+
const header = `扫描区间:${baseline.at ? new Date(baseline.at).toLocaleString() : '上次基线'} → 现在`;
|
|
118
|
+
return { text: clampText(`${header}\n\n${renderTurnReport(record, { maskHome: cfg.maskHome })}`), record };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** 取用配置前先刷新一次:设置卡片里的改动不重启插件也立刻生效。 */
|
|
122
|
+
function syncDeps(deps) {
|
|
123
|
+
try {
|
|
124
|
+
if (deps && typeof deps.refresh === 'function') deps.refresh();
|
|
125
|
+
} catch {
|
|
126
|
+
/* 刷新失败就用上一次的值,绝不中断命令 */
|
|
127
|
+
}
|
|
128
|
+
return deps;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** 探测家用常见目录,标出哪些已经在观测范围里。 */
|
|
132
|
+
function suggestRoots(deps) {
|
|
133
|
+
const cfg = deps.cfg || {};
|
|
134
|
+
const resolved = Array.isArray(deps.roots) ? deps.roots : [];
|
|
135
|
+
const lowerRoots = resolved.map((root) => String(root.path || '').toLowerCase());
|
|
136
|
+
const candidates = ['desktop', 'documents', 'downloads', 'pictures', 'music', 'videos'];
|
|
137
|
+
const lines = ['推荐的观测目录(按小白最常丢东西的顺序):', ''];
|
|
138
|
+
for (const id of candidates) {
|
|
139
|
+
const one = resolveRoots({ ...cfg, roots: [id], extraRoots: [] })[0];
|
|
140
|
+
if (!one) continue;
|
|
141
|
+
const covered = lowerRoots.some((root) => root === one.path.toLowerCase());
|
|
142
|
+
lines.push(`- ${covered ? '[已加]' : '[未加]'} ${id}: ${one.path}${one.exists ? '' : '(这个目录不存在)'}`);
|
|
143
|
+
}
|
|
144
|
+
lines.push('');
|
|
145
|
+
lines.push('要加/减少目录:打开 Plugins → dsh-aftermath → 卡片里的「要盯着哪些地方」,保存后立即生效。');
|
|
146
|
+
lines.push('也可以用 yml(profile 的 cordis.patch.yml):');
|
|
147
|
+
lines.push('');
|
|
148
|
+
lines.push('```yaml');
|
|
149
|
+
lines.push('- id: dsh-aftermath');
|
|
150
|
+
lines.push(' config:');
|
|
151
|
+
lines.push(` roots: [${resolved.map((root) => `'${root.path.replace(/\\/g, '/')}'`).join(', ') || "'desktop'"}]`);
|
|
152
|
+
lines.push('```');
|
|
153
|
+
return lines.join('\n');
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* 改观测根:插件不直接写宿主配置(写入要走 settings 服务,失败时会让用户以为改了),
|
|
159
|
+
* 这里只把「改完会变成什么样」和可以直接粘的 yml 给出来,改由用户确认。
|
|
160
|
+
*/
|
|
161
|
+
function rootsEdit(deps, options) {
|
|
162
|
+
const cfg = deps.cfg || {};
|
|
163
|
+
const current = Array.isArray(deps.roots) ? deps.roots : [];
|
|
164
|
+
const specs = current.map((root) => root.path);
|
|
165
|
+
const index = (value) => {
|
|
166
|
+
const want = String(value).toLowerCase().replace(/[\/]+$/, '');
|
|
167
|
+
return current.findIndex((root) => {
|
|
168
|
+
const pathText = String(root.path || '').toLowerCase().replace(/[\/]+$/, '');
|
|
169
|
+
const idText = String(root.id || '').toLowerCase();
|
|
170
|
+
return pathText === want || idText === want;
|
|
171
|
+
});
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
const lines = [];
|
|
175
|
+
if (options.add) {
|
|
176
|
+
if (index(options.add) >= 0) lines.push(`已经在这个目录里了:${options.add}`);
|
|
177
|
+
else {
|
|
178
|
+
specs.push(options.add);
|
|
179
|
+
lines.push(`准备加入:${options.add}`);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
if (options.remove) {
|
|
183
|
+
const at = index(options.remove);
|
|
184
|
+
if (at < 0) lines.push(`没找到要移除的目录:${options.remove}`);
|
|
185
|
+
else {
|
|
186
|
+
lines.push(`准备移除:${specs[at]}`);
|
|
187
|
+
specs.splice(at, 1);
|
|
188
|
+
}
|
|
189
|
+
if (specs.length === 0) lines.push('注意:至少要留一个观测目录,否则不会记录任何东西。');
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
lines.push('');
|
|
193
|
+
lines.push('改完之后的观测目录:');
|
|
194
|
+
for (const spec of specs) {
|
|
195
|
+
const resolved = resolveRoots({ ...cfg, roots: [spec], extraRoots: [] })[0];
|
|
196
|
+
lines.push(`- ${resolved ? resolved.path : spec}${resolved && resolved.exists === false ? '(不存在)' : ''}`);
|
|
197
|
+
}
|
|
198
|
+
lines.push('');
|
|
199
|
+
lines.push('插件不替你写宿主配置,请二选一:');
|
|
200
|
+
lines.push('1. Plugins → dsh-aftermath → 卡片「要盯着哪些地方?」,把上面的行粘贴进去,点保存(立即生效);');
|
|
201
|
+
lines.push('2. 或写进 profile 的 cordis.patch.yml:');
|
|
202
|
+
lines.push('');
|
|
203
|
+
lines.push('```yaml');
|
|
204
|
+
lines.push('- id: dsh-aftermath');
|
|
205
|
+
lines.push(' config:');
|
|
206
|
+
lines.push(' roots:');
|
|
207
|
+
for (const spec of specs) lines.push(` - '${String(spec).split('\\').join('/')}'`);
|
|
208
|
+
lines.push('```');
|
|
209
|
+
return lines.join('\n');
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function rootsText(deps) {
|
|
213
|
+
const { cfg, roots } = deps;
|
|
214
|
+
const lines = [`观测根(depth=${cfg.depth},上限 ${cfg.maxEntries} 条目):`, ''];
|
|
215
|
+
for (const root of roots) {
|
|
216
|
+
const snap = { count: 0, ok: true, error: null };
|
|
217
|
+
try {
|
|
218
|
+
const scanned = scanRoots([root], { ...cfg, depth: 0 });
|
|
219
|
+
snap.count = scanned[0]?.count || 0;
|
|
220
|
+
snap.ok = scanned[0]?.ok !== false;
|
|
221
|
+
snap.error = scanned[0]?.error || null;
|
|
222
|
+
} catch {
|
|
223
|
+
snap.ok = false;
|
|
224
|
+
}
|
|
225
|
+
lines.push(`- ${root.id}: ${root.path} ${snap.ok ? `顶层 ${snap.count} 条` : `读不到(${snap.error})`}`);
|
|
226
|
+
}
|
|
227
|
+
lines.push('');
|
|
228
|
+
lines.push(`状态目录:${stateDir()}`);
|
|
229
|
+
lines.push('如果路径不对:打开 Plugins 页的「文件变更记录」卡片改观测目录,保存后立即生效。');
|
|
230
|
+
return lines.join('\n');
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export function doctorText(deps) {
|
|
234
|
+
const report = typeof deps.probeSettings === 'function' ? deps.probeSettings() : null;
|
|
235
|
+
if (!report) {
|
|
236
|
+
return [`dsh-aftermath v${VERSION}`, '拿不到自检结果:宿主设置服务不可用,或插件版本过旧。'].join('\n');
|
|
237
|
+
}
|
|
238
|
+
const lines = [
|
|
239
|
+
`dsh-aftermath v${VERSION} · ${report.at}`,
|
|
240
|
+
`Config 导出:${report.configExported ? '是' : '否'}`,
|
|
241
|
+
`schema 来源:${report.schemaSource || '未加载到 @deepseek-ai/schemastery'}`,
|
|
242
|
+
`设置命名空间:${report.ourNamespace ? '已就绪,卡片可编辑全部字段' : '缺失,卡片只能改总开关'}`,
|
|
243
|
+
];
|
|
244
|
+
if (report.namespaces) {
|
|
245
|
+
const list = report.namespaces.map((row) => row.ns).join(', ');
|
|
246
|
+
lines.push(`宿主可见命名空间(${report.namespaces.length}):${list || '无'}`);
|
|
247
|
+
const ours = report.namespaces.find((row) => row.ns === report.plugin);
|
|
248
|
+
if (ours) lines.push(`本插件可见字段(${ours.fields?.length ?? 0}):${ours.fields?.join(', ') || '无'}`);
|
|
249
|
+
}
|
|
250
|
+
if (report.error) lines.push(`问题:${report.error}`);
|
|
251
|
+
lines.push(`自检快照:${stateDir()}/settings-probe.json`);
|
|
252
|
+
return lines.join('\n');
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function statusText(deps) {
|
|
256
|
+
const { cfg, roots } = deps;
|
|
257
|
+
const state = deps.state || {};
|
|
258
|
+
const today = readTurns({ sinceMs: Date.parse(`${dayKey()}T00:00:00`), limit: 500 });
|
|
259
|
+
const lines = [
|
|
260
|
+
`dsh-aftermath v${VERSION} ${cfg.enabled ? '已启用' : '已停用(enabled=false)'}`,
|
|
261
|
+
`观测根:${roots.map((r) => r.id).join(', ') || '无'}`,
|
|
262
|
+
`快照:depth=${cfg.depth},上限 ${cfg.maxEntries},排除 ${cfg.exclude.length} 条规则`,
|
|
263
|
+
...(cfg.depth >= 4
|
|
264
|
+
? [`性能提示:depth=${cfg.depth} 会让每轮快照明显变慢,观测根是大目录时尤其明显;够用就降到 2`]
|
|
265
|
+
: []),
|
|
266
|
+
`归因:调用区间容差 ${cfg.intervalSlackMs} ms`,
|
|
267
|
+
`零变更回合:${cfg.recordQuietTurns === false ? '不记录' : '有写操作就记一条轻记录(只留命令摘要)'}`,
|
|
268
|
+
`保留:${cfg.retentionDays} 天`,
|
|
269
|
+
`状态目录:${stateDir()}`,
|
|
270
|
+
`设置表单:${SCHEMA_SOURCE ? `已就绪(schema 取自 ${SCHEMA_SOURCE})` : '不可用:没解析到 @deepseek-ai/schemastery,卡片只能改总开关,其余靠配置文件的 yml'}`,
|
|
271
|
+
`今天已记录:${today.length} 轮${state.lastAt ? `,最近一轮 ${new Date(state.lastAt).toLocaleString()}` : ''}`,
|
|
272
|
+
];
|
|
273
|
+
const changed = today.reduce((sum, record) => sum + (record?.counts?.total || 0), 0);
|
|
274
|
+
lines.push(`今天变更总数:${changed}`);
|
|
275
|
+
if (state.lastError) lines.push(`最近一次错误:${state.lastError}`);
|
|
276
|
+
return lines.join('\n');
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
async function reportText(deps, options) {
|
|
280
|
+
let records = [];
|
|
281
|
+
if (options.sinceMs) records = readTurns({ sinceMs: options.sinceMs, limit: 50 });
|
|
282
|
+
else records = readTurns({ limit: Number.isInteger(options.last) && options.last > 0 ? options.last : 1 });
|
|
283
|
+
|
|
284
|
+
if (records.length === 0) {
|
|
285
|
+
return '这段时间没有记录到文件变更。\n可能原因:观测根里确实没动过东西,或插件刚装还没跑过完整的一轮。';
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const filtered = records.map((record) => filterByRoot(record, options.root));
|
|
289
|
+
|
|
290
|
+
let text;
|
|
291
|
+
if (filtered.length === 1) {
|
|
292
|
+
text = renderTurnReport(filtered[0], { maskHome: deps.cfg.maskHome });
|
|
293
|
+
} else {
|
|
294
|
+
text = renderHistory(filtered);
|
|
295
|
+
const last = filtered[0];
|
|
296
|
+
if (last && (last.counts?.total || 0) > 0) {
|
|
297
|
+
text += `\n\n---\n\n## 最近一轮明细\n\n${renderTurnReport(last, { maskHome: deps.cfg.maskHome })}`;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
if (options.save) {
|
|
302
|
+
const name = `${dayKey()}-${Date.now().toString(36)}`;
|
|
303
|
+
const file = writeReport(name, text);
|
|
304
|
+
if (file) text += `\n\n已保存:${file}`;
|
|
305
|
+
}
|
|
306
|
+
return clampText(text);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
export function installCommands(ctx, deps) {
|
|
310
|
+
ctx.inject(['commands'], (host) => {
|
|
311
|
+
const commands = host.get('commands');
|
|
312
|
+
if (!commands || typeof commands.register !== 'function') return;
|
|
313
|
+
registerCommand(
|
|
314
|
+
commands,
|
|
315
|
+
{
|
|
316
|
+
name: 'aftermath',
|
|
317
|
+
description: '查「AI 这一轮到底动了哪些文件」:逐条变更 + 归因到具体命令 + 症状对照。只读。',
|
|
318
|
+
input: { hint: 'report [--last N|--since 2h] | scan | roots | status | help' },
|
|
319
|
+
handler: async (invocation) => {
|
|
320
|
+
try {
|
|
321
|
+
syncDeps(deps);
|
|
322
|
+
const { sub, options } = parseArgs(invocation?.rawInput);
|
|
323
|
+
if (sub === 'help' || sub === '-h' || sub === '?') return { kind: 'success', text: HELP };
|
|
324
|
+
if (sub === 'roots') {
|
|
325
|
+
const args = options.args || options;
|
|
326
|
+
if (options.suggest === true || args.suggest === true) {
|
|
327
|
+
return { kind: 'success', text: suggestRoots(deps) };
|
|
328
|
+
}
|
|
329
|
+
if (options.add || options.remove) {
|
|
330
|
+
return { kind: 'success', text: rootsEdit(deps, options) };
|
|
331
|
+
}
|
|
332
|
+
return { kind: 'success', text: rootsText(deps) };
|
|
333
|
+
}
|
|
334
|
+
if (sub === 'status') return { kind: 'success', text: statusText(deps) };
|
|
335
|
+
if (sub === 'doctor') return { kind: 'success', text: doctorText(deps) };
|
|
336
|
+
if (sub === 'scan') {
|
|
337
|
+
const result = scanNow(deps, { keep: options.keep === true });
|
|
338
|
+
return { kind: 'success', text: result.text };
|
|
339
|
+
}
|
|
340
|
+
if (sub === 'report') return { kind: 'success', text: await reportText(deps, options) };
|
|
341
|
+
return { kind: 'error', text: `不认识子命令 ${sub}\n\n${HELP}` };
|
|
342
|
+
} catch (error) {
|
|
343
|
+
return { kind: 'error', text: `aftermath 执行失败:${error?.message || error}` };
|
|
344
|
+
}
|
|
345
|
+
},
|
|
346
|
+
},
|
|
347
|
+
'aftermath-view',
|
|
348
|
+
(message) => {
|
|
349
|
+
try {
|
|
350
|
+
ctx.logger?.('aftermath')?.warn?.(message);
|
|
351
|
+
} catch {
|
|
352
|
+
/* 记日志失败无所谓 */
|
|
353
|
+
}
|
|
354
|
+
},
|
|
355
|
+
);
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** 供 aftermatch_history 工具复用:把历史渲染成一段文本。 */
|
|
360
|
+
export function buildHistoryText(deps, args) {
|
|
361
|
+
syncDeps(deps);
|
|
362
|
+
const options = { last: null, sinceMs: null, root: null, save: false };
|
|
363
|
+
const since = typeof args?.since === 'string' ? parseDuration(args.since) : null;
|
|
364
|
+
if (since !== null) options.sinceMs = Date.now() - since;
|
|
365
|
+
if (typeof args?.root === 'string' && args.root !== 'all') options.root = args.root.toLowerCase();
|
|
366
|
+
const limit = Number.isInteger(args?.limit) && args.limit > 0 ? Math.min(args.limit, 20) : 3;
|
|
367
|
+
options.last = limit;
|
|
368
|
+
const records = readTurns({ sinceMs: options.sinceMs || 0, limit });
|
|
369
|
+
if (records.length === 0) return '没有可用的 aftermath 记录。';
|
|
370
|
+
const filtered = records.map((record) => filterByRoot(record, options.root));
|
|
371
|
+
// 不能只留"有变更"的轮次:quiet 记录(根内没变、但执行过写操作)
|
|
372
|
+
// 正是回答"它是不是动了别的地方"的唯一线索。
|
|
373
|
+
const parts = [renderHistory(filtered)];
|
|
374
|
+
parts.push('---');
|
|
375
|
+
parts.push(renderTurnReport(filtered[0], { maskHome: deps.cfg.maskHome }));
|
|
376
|
+
const symptoms = detectSymptoms(filtered[0].changes || [], { roots: filtered[0].roots || [] });
|
|
377
|
+
if (symptoms.length === 0) parts.push('\n(这份记录里没有匹配到已知症状)');
|
|
378
|
+
return clampText(parts.join('\n\n'));
|
|
379
|
+
}
|
package/lib/config.js
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 配置与根目录解析。
|
|
3
|
+
*
|
|
4
|
+
* 硬约束(本机实测):宿主进程里调用 `reg.exe` 不可靠(任何参数都报「无效语法」),
|
|
5
|
+
* 因此这里不读注册表、不启子进程,只用 USERPROFILE + 别名探测 + 显式配置三级回退。
|
|
6
|
+
*/
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import os from 'node:os';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
|
|
11
|
+
export const DEFAULTS = {
|
|
12
|
+
enabled: true,
|
|
13
|
+
/** 根标识或绝对路径;内置标识见 ROOT_ALIASES。默认覆盖小白最容易丢文件的三处 */
|
|
14
|
+
roots: ['desktop', 'downloads', 'documents'],
|
|
15
|
+
/** 每个根向下递归的层数;0 = 只看根目录本身 */
|
|
16
|
+
depth: 2,
|
|
17
|
+
/** 单根条目上限,超限截断并标记 */
|
|
18
|
+
maxEntries: 20000,
|
|
19
|
+
/** 一次报告最多列出的变更条数 */
|
|
20
|
+
maxChangesPerReport: 200,
|
|
21
|
+
/** NDJSON 保留天数 */
|
|
22
|
+
retentionDays: 7,
|
|
23
|
+
/** 名称排除模式:精确名 / `前缀*` / `*后缀`,大小写不敏感 */
|
|
24
|
+
exclude: [
|
|
25
|
+
'node_modules',
|
|
26
|
+
'.git',
|
|
27
|
+
'.vs',
|
|
28
|
+
'.svn',
|
|
29
|
+
'~$*',
|
|
30
|
+
'Thumbs.db',
|
|
31
|
+
'desktop.ini',
|
|
32
|
+
'.DS_Store',
|
|
33
|
+
'$RECYCLE.BIN',
|
|
34
|
+
'System Volume Information',
|
|
35
|
+
// 工程目录:文件多、删了也能重新生成,没必要每轮扫一遍(README 的默认排除表逐条说明)
|
|
36
|
+
'dist',
|
|
37
|
+
'build',
|
|
38
|
+
'.next',
|
|
39
|
+
'.turbo',
|
|
40
|
+
'coverage',
|
|
41
|
+
'__pycache__',
|
|
42
|
+
'.venv',
|
|
43
|
+
'venv',
|
|
44
|
+
'.mypy_cache',
|
|
45
|
+
'.pytest_cache',
|
|
46
|
+
'target',
|
|
47
|
+
],
|
|
48
|
+
/** 额外绝对路径根(与 roots 合并) */
|
|
49
|
+
extraRoots: [],
|
|
50
|
+
/** 是否在报告里把绝对路径打码成 ~ */
|
|
51
|
+
maskHome: true,
|
|
52
|
+
/**
|
|
53
|
+
* 零变更但执行过写操作的回合,也落一条轻记录(只有命令摘要,没有变更表)。
|
|
54
|
+
* 关掉后这类回合完全不落盘——那既是省空间,也是彻底放弃“这轮动过别处”的线索。
|
|
55
|
+
*/
|
|
56
|
+
recordQuietTurns: true,
|
|
57
|
+
/**
|
|
58
|
+
* 调用区间归因的容差(毫秒)。
|
|
59
|
+
* 文件 mtime 与调用起止时间来自两个时钟(fs 与宿主事件),必然有几个 tick 的偏差,
|
|
60
|
+
* 因此命中判定留一点余量;调大到 0 会让边界情况退回「时间窗内」。
|
|
61
|
+
*/
|
|
62
|
+
intervalSlackMs: 1500,
|
|
63
|
+
/** 把会话当时的工作目录自动算进观测根(大目录只扫顶层) */
|
|
64
|
+
followCwd: true,
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const ROOT_ALIASES = {
|
|
68
|
+
desktop: ['Desktop', 'OneDrive/Desktop', '桌面', 'OneDrive/桌面'],
|
|
69
|
+
downloads: ['Downloads', '下载'],
|
|
70
|
+
documents: ['Documents', '文档'],
|
|
71
|
+
pictures: ['Pictures', '图片'],
|
|
72
|
+
music: ['Music', '音乐'],
|
|
73
|
+
videos: ['Videos', '视频'],
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
export function homeDir() {
|
|
77
|
+
const env = process.env.USERPROFILE || process.env.HOME;
|
|
78
|
+
if (typeof env === 'string' && env.trim()) return env.trim();
|
|
79
|
+
try {
|
|
80
|
+
return os.homedir();
|
|
81
|
+
} catch {
|
|
82
|
+
return 'C:\\Users\\Public';
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function expandHome(input) {
|
|
87
|
+
if (typeof input !== 'string') return '';
|
|
88
|
+
let s = input.trim();
|
|
89
|
+
if (!s) return '';
|
|
90
|
+
s = s.replace(/^%USERPROFILE%/i, homeDir());
|
|
91
|
+
s = s.replace(/^%HOMEDRIVE%%HOMEPATH%/i, homeDir());
|
|
92
|
+
if (s === '~' || s.startsWith('~/') || s.startsWith('~\\')) {
|
|
93
|
+
s = path.join(homeDir(), s.slice(1));
|
|
94
|
+
}
|
|
95
|
+
return s;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function isDir(p) {
|
|
99
|
+
try {
|
|
100
|
+
return fs.statSync(p, { throwIfNoEntry: false })?.isDirectory() === true;
|
|
101
|
+
} catch {
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function splitSpec(value) {
|
|
107
|
+
if (typeof value !== 'string') return null;
|
|
108
|
+
const trimmed = value.trim();
|
|
109
|
+
if (!trimmed) return null;
|
|
110
|
+
const eq = trimmed.indexOf('=');
|
|
111
|
+
if (eq > 0) {
|
|
112
|
+
const id = trimmed.slice(0, eq).trim();
|
|
113
|
+
const target = trimmed.slice(eq + 1).trim();
|
|
114
|
+
if (id && target) return { id, target };
|
|
115
|
+
}
|
|
116
|
+
return { id: trimmed, target: trimmed };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** 把一条 roots 条目解析成绝对目录;别名优先,解析不到就报 exists=false。 */
|
|
120
|
+
function resolveOne(spec) {
|
|
121
|
+
const raw = expandHome(spec);
|
|
122
|
+
if (!raw) return null;
|
|
123
|
+
// 绝对路径优先
|
|
124
|
+
if (path.isAbsolute(raw)) {
|
|
125
|
+
const abs = path.win32.normalize(raw);
|
|
126
|
+
return { id: basenameOf(abs), path: abs, requested: spec, exists: isDir(abs), via: 'path' };
|
|
127
|
+
}
|
|
128
|
+
const key = raw.toLowerCase();
|
|
129
|
+
const aliases = ROOT_ALIASES[key];
|
|
130
|
+
if (aliases) {
|
|
131
|
+
for (const alias of aliases) {
|
|
132
|
+
const abs = path.win32.normalize(path.join(homeDir(), alias));
|
|
133
|
+
if (isDir(abs)) {
|
|
134
|
+
return { id: key, path: abs, requested: spec, exists: true, via: `alias:${alias}` };
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
const first = path.win32.normalize(path.join(homeDir(), aliases[0]));
|
|
138
|
+
return { id: key, path: first, requested: spec, exists: false, via: `alias:${aliases[0]}` };
|
|
139
|
+
}
|
|
140
|
+
// 相对名:当作 home 下的子目录
|
|
141
|
+
const abs = path.win32.normalize(path.join(homeDir(), raw));
|
|
142
|
+
return { id: key, path: abs, requested: spec, exists: isDir(abs), via: 'home' };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function basenameOf(abs) {
|
|
146
|
+
const parts = abs.split(/[\\/]+/).filter(Boolean);
|
|
147
|
+
return (parts[parts.length - 1] || abs).toLowerCase();
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export function resolveRoots(config) {
|
|
151
|
+
const specs = [];
|
|
152
|
+
for (const r of config.roots || []) specs.push(r);
|
|
153
|
+
for (const r of config.extraRoots || []) specs.push(r);
|
|
154
|
+
const seen = new Set();
|
|
155
|
+
const out = [];
|
|
156
|
+
for (const spec of specs) {
|
|
157
|
+
const parsed = splitSpec(spec);
|
|
158
|
+
if (!parsed) continue;
|
|
159
|
+
const resolved = resolveOne(parsed.target);
|
|
160
|
+
if (!resolved) continue;
|
|
161
|
+
if (parsed.id && !/^[a-zA-Z]:/.test(parsed.id) && parsed.id !== resolved.id) {
|
|
162
|
+
// `id=path` 形态,保留用户给的 id
|
|
163
|
+
resolved.id = parsed.target === parsed.id ? resolved.id : parsed.id;
|
|
164
|
+
}
|
|
165
|
+
const key = resolved.path.toLowerCase();
|
|
166
|
+
if (seen.has(key)) continue;
|
|
167
|
+
seen.add(key);
|
|
168
|
+
out.push(resolved);
|
|
169
|
+
}
|
|
170
|
+
return dropNested(dedupeIds(out));
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* 同一个目录(或父子目录)都当根,会让同一个文件在报告里出现两次、
|
|
175
|
+
* 也白扫一遍。父目录已经在列时丢掉子目录——父目录能覆盖它。
|
|
176
|
+
*/
|
|
177
|
+
function dropNested(list) {
|
|
178
|
+
const lowered = list.map((root) => root.path.toLowerCase().replace(/[\/]+$/, ''));
|
|
179
|
+
return list.filter((root, index) => {
|
|
180
|
+
const child = lowered[index];
|
|
181
|
+
return !lowered.some((parent, other) => other !== index
|
|
182
|
+
&& parent !== child
|
|
183
|
+
&& child.startsWith(`${parent}${'\\'}`));
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** id 是报告分组和 --root 过滤的键,必须唯一;重名时按出现顺序加后缀。 */
|
|
188
|
+
function dedupeIds(list) {
|
|
189
|
+
const used = new Map();
|
|
190
|
+
const out = [];
|
|
191
|
+
for (const root of list) {
|
|
192
|
+
const base = root.id || 'root';
|
|
193
|
+
const count = used.get(base) || 0;
|
|
194
|
+
used.set(base, count + 1);
|
|
195
|
+
out.push(count === 0 ? root : { ...root, id: `${base}${count + 1}` });
|
|
196
|
+
}
|
|
197
|
+
return out;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export function normalizeConfig(input) {
|
|
201
|
+
const cfg = { ...DEFAULTS };
|
|
202
|
+
if (input && typeof input === 'object') {
|
|
203
|
+
for (const key of Object.keys(DEFAULTS)) {
|
|
204
|
+
if (input[key] !== undefined && input[key] !== null) cfg[key] = input[key];
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
const clampInt = (v, min, max, fallback) => {
|
|
208
|
+
const n = Number(v);
|
|
209
|
+
if (!Number.isFinite(n)) return fallback;
|
|
210
|
+
return Math.min(max, Math.max(min, Math.trunc(n)));
|
|
211
|
+
};
|
|
212
|
+
cfg.depth = clampInt(cfg.depth, 0, 6, DEFAULTS.depth);
|
|
213
|
+
cfg.maxEntries = clampInt(cfg.maxEntries, 100, 200000, DEFAULTS.maxEntries);
|
|
214
|
+
cfg.maxChangesPerReport = clampInt(cfg.maxChangesPerReport, 10, 5000, DEFAULTS.maxChangesPerReport);
|
|
215
|
+
cfg.retentionDays = clampInt(cfg.retentionDays, 1, 90, DEFAULTS.retentionDays);
|
|
216
|
+
cfg.intervalSlackMs = clampInt(cfg.intervalSlackMs, 0, 60000, DEFAULTS.intervalSlackMs);
|
|
217
|
+
cfg.enabled = cfg.enabled !== false;
|
|
218
|
+
cfg.maskHome = cfg.maskHome !== false;
|
|
219
|
+
cfg.followCwd = cfg.followCwd !== false;
|
|
220
|
+
cfg.recordQuietTurns = cfg.recordQuietTurns !== false;
|
|
221
|
+
if (!Array.isArray(cfg.roots)) cfg.roots = [...DEFAULTS.roots];
|
|
222
|
+
if (!Array.isArray(cfg.extraRoots)) cfg.extraRoots = [];
|
|
223
|
+
if (!Array.isArray(cfg.exclude)) cfg.exclude = [...DEFAULTS.exclude];
|
|
224
|
+
cfg.roots = cfg.roots.filter((x) => typeof x === 'string' && x.trim());
|
|
225
|
+
cfg.exclude = cfg.exclude.filter((x) => typeof x === 'string' && x.trim());
|
|
226
|
+
return cfg;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export function dshHome() {
|
|
230
|
+
const env = process.env.DSH_HOME;
|
|
231
|
+
if (typeof env === 'string' && env.trim()) return path.win32.normalize(env.trim());
|
|
232
|
+
return path.win32.normalize(path.join(homeDir(), '.dsh'));
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export function stateDir() {
|
|
236
|
+
return path.win32.normalize(path.join(dshHome(), 'state', 'aftermath'));
|
|
237
|
+
}
|