sweepwise 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,71 @@
1
+ // Docker 构建缓存和没有容器在用的镜像。只有 Docker 在运行时才能判断。
2
+ import { run, which, home, exists, duBytes } from '../util.js';
3
+ import { tr } from '../i18n.js';
4
+ import { finding } from '../model.js';
5
+
6
+ export const id = 'docker';
7
+ export const label = () => 'Docker';
8
+
9
+ /** docker 的大小格式:"7.739GB (60%)" -> 字节 */
10
+ export function parseDockerSize(s) {
11
+ const m = String(s).match(/([\d.]+)\s*([kKMGT]?B)/);
12
+ if (!m) return 0;
13
+ const mult = { B: 1, kB: 1e3, KB: 1e3, MB: 1e6, GB: 1e9, TB: 1e12 }[m[2]] ?? 1;
14
+ return parseFloat(m[1]) * mult;
15
+ }
16
+
17
+ export async function detect(ctx) {
18
+ if (!(await which('docker'))) return [];
19
+ // 扫描时磁盘很忙,docker 响应会变慢,超时给宽一点
20
+ const r = await run('docker', ['system', 'df', '--format', '{{json .}}'], { timeout: 60_000 });
21
+ if (!r.ok) {
22
+ const raw = home('Library', 'Containers', 'com.docker.docker', 'Data', 'vms', '0', 'data', 'Docker.raw');
23
+ if (await exists(raw)) {
24
+ return [
25
+ finding({
26
+ category: id,
27
+ title: tr('Docker 磁盘镜像', 'Docker disk image'),
28
+ bytes: await duBytes(raw),
29
+ risk: 'review',
30
+ details: [tr('Docker 没有运行(或没响应),无法判断里面有多少能清理', "Docker isn't running (or didn't respond), so reclaimable space is unknown")],
31
+ paths: [raw],
32
+ action: { type: 'manual', hint: tr('启动 Docker Desktop 后重新运行 sweepwise', 'Start Docker Desktop and run sweepwise again') },
33
+ }),
34
+ ];
35
+ }
36
+ return [];
37
+ }
38
+ const rows = r.stdout.split('\n').filter(Boolean).map((l) => JSON.parse(l));
39
+ const out = [];
40
+ for (const row of rows) {
41
+ const bytes = parseDockerSize(row.Reclaimable);
42
+ if (bytes < ctx.cacheMin) continue;
43
+ if (row.Type === 'Build Cache') {
44
+ out.push(
45
+ finding({
46
+ category: id,
47
+ title: tr('Docker 构建缓存', 'Docker build cache'),
48
+ bytes,
49
+ risk: 'safe',
50
+ details: [tr(`共 ${row.TotalCount} 条,没有在用的`, `${row.TotalCount} entries, none in use`), tr('下次构建会慢一些', 'The next build will be slower')],
51
+ action: { type: 'command', argv: ['docker', 'builder', 'prune', '-af'] },
52
+ }),
53
+ );
54
+ } else if (row.Type === 'Images') {
55
+ out.push(
56
+ finding({
57
+ category: id,
58
+ title: tr('没有容器在用的 Docker 镜像', 'Docker images not used by any container'),
59
+ bytes,
60
+ risk: 'review',
61
+ details: [
62
+ tr(`共 ${row.TotalCount} 个镜像,${row.Active} 个在用`, `${row.TotalCount} images, ${row.Active} in use`),
63
+ tr('需要时重新 pull 或 build', 'Pull or build again when needed'),
64
+ ],
65
+ action: { type: 'command', argv: ['docker', 'image', 'prune', '-af'] },
66
+ }),
67
+ );
68
+ }
69
+ }
70
+ return out;
71
+ }
@@ -0,0 +1,93 @@
1
+ // 仓库里被 .gitignore 忽略、但体积很大的目录或文件(构建产物、临时实验输出、虚拟环境…)。
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { git, run, pMap, ago, isInside, formatBytes, tildify } from '../util.js';
5
+ import { tr, list } from '../i18n.js';
6
+ import { finding } from '../model.js';
7
+
8
+ export const id = 'ignored';
9
+ export const label = () => tr('被忽略的大目录', 'ignored dirs');
10
+
11
+ const BUILD = new Set([
12
+ 'dist', 'build', 'out', '.next', '.nuxt', '.output', 'target', '.turbo', '.cache', '.parcel-cache',
13
+ 'coverage', '.svelte-kit', 'DerivedData', '.gradle', '.expo', '.vercel', 'storybook-static',
14
+ '__pycache__', '.pytest_cache', '.mypy_cache', '.angular', '.docusaurus', '.vite', 'Pods',
15
+ ]);
16
+ const TEMP = new Set(['.tmp', 'tmp', 'temp', '.temp', 'logs', 'log']);
17
+ const VENV = new Set(['.venv', 'venv', 'env']);
18
+
19
+ export async function detect(ctx) {
20
+ const { repos, worktreePaths } = await ctx.repoIndex();
21
+ const wts = [...worktreePaths];
22
+ const out = [];
23
+ let i = 0;
24
+ for (const repo of repos) {
25
+ ctx.tick(id, ++i, repos.length);
26
+ const r = await git(repo.path, ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory', '-z'], {
27
+ timeout: 300_000,
28
+ });
29
+ if (!r.ok) continue;
30
+ const entries = r.stdout
31
+ .split('\0')
32
+ .filter(Boolean)
33
+ .filter((e) => !e.split('/').includes('node_modules')) // node_modules 有单独的检测器
34
+ .map((e) => path.join(repo.path, e.replace(/\/$/, '')))
35
+ // 含有 worktree 的目录不算(worktree 单独判断),worktree 内部也不算
36
+ .filter((full) => !wts.some((w) => w === full || isInside(w, full) || isInside(full, w)));
37
+
38
+ const sized = await pMap(entries, (full) => measure(full), 6);
39
+ for (const s of sized) {
40
+ if (!s || s.bytes < ctx.minSize) continue;
41
+ const base = path.basename(s.full);
42
+ let risk = 'review';
43
+ let why = tr('不在版本库里', 'Not tracked by git');
44
+ if (BUILD.has(base)) {
45
+ risk = 'safe';
46
+ why = tr('构建产物或缓存,可重新生成', 'Build output or cache — can be regenerated');
47
+ } else if (TEMP.has(base)) {
48
+ why = tr('临时/日志目录,不在版本库里', 'Temp/log directory, not tracked by git');
49
+ } else if (VENV.has(base)) {
50
+ why = tr('Python 虚拟环境,需要时重新创建', 'Python virtualenv — recreate when needed');
51
+ }
52
+ const details = [why, tr(`${ago(s.mtime)}有变动`, `Changed ${ago(s.mtime)}`)];
53
+ if (s.top.length) details.push(tr('最大的:', 'Largest: ') + list(s.top.map((t) => `${t.name} ${formatBytes(t.bytes)}`)));
54
+ out.push(
55
+ finding({
56
+ category: id,
57
+ title: tildify(s.full),
58
+ tag: s.isDir ? tr('目录', 'dir') : tr('文件', 'file'),
59
+ bytes: s.bytes,
60
+ risk,
61
+ details,
62
+ paths: [s.full],
63
+ action: { type: 'trash', paths: [s.full] },
64
+ }),
65
+ );
66
+ }
67
+ }
68
+ return out;
69
+ }
70
+
71
+ async function measure(full) {
72
+ const st = await fs.lstat(full).catch(() => null);
73
+ if (!st || st.isSymbolicLink()) return null;
74
+ if (!st.isDirectory()) return { full, bytes: st.blocks * 512, isDir: false, mtime: st.mtimeMs, top: [] };
75
+ // 一次 du 同时拿到总大小和一级子目录大小
76
+ const r = await run('du', ['-k', '-d', '1', full], { timeout: 600_000 });
77
+ const rows = r.stdout
78
+ .trim()
79
+ .split('\n')
80
+ .map((l) => {
81
+ const tab = l.indexOf('\t');
82
+ return { bytes: parseInt(l.slice(0, tab), 10) * 1024, p: l.slice(tab + 1) };
83
+ })
84
+ .filter((x) => Number.isFinite(x.bytes));
85
+ const total = rows.find((x) => x.p === full)?.bytes ?? 0;
86
+ const top = rows
87
+ .filter((x) => x.p !== full)
88
+ .sort((a, b) => b.bytes - a.bytes)
89
+ .slice(0, 3)
90
+ .filter((x) => x.bytes > total * 0.05)
91
+ .map((x) => ({ name: path.basename(x.p), bytes: x.bytes }));
92
+ return { full, bytes: total, isDir: true, mtime: st.mtimeMs, top };
93
+ }
@@ -0,0 +1,163 @@
1
+ // 应用已经卸载,但数据还留在 ~/Library 里(比如卸载微信后留下的 44G 聊天数据)。
2
+ // 判断依据:常见安装位置的应用 + Spotlight 都找不到这个 bundle id。
3
+ import path from 'node:path';
4
+ import { run, home, readdirSafe, duBytes, pMap, statSafe, ago } from '../util.js';
5
+ import { tr } from '../i18n.js';
6
+ import { finding } from '../model.js';
7
+
8
+ export const id = 'leftover';
9
+ export const label = () => tr('卸载残留', 'leftovers');
10
+
11
+ const BUNDLE_RE = /^[A-Za-z0-9-]+(\.[A-Za-z0-9_-]+){2,}$/;
12
+ const isApple = (b) => /^com\.apple\./i.test(b);
13
+ const stripPrefix = (s) => s.replace(/^[A-Z0-9]{10}\./, '').replace(/^group\./, '');
14
+ const vendorOf = (b) => b.split('.').slice(0, 2).join('.').toLowerCase();
15
+
16
+ const GENERIC = new Set(['com', 'net', 'org', 'cn', 'io', 'co', 'app', 'mac', 'macos', 'osx', 'desktop', 'client', 'helper', 'agent', 'group']);
17
+
18
+ /** 已安装应用里有没有「像是同一个产品」的(比如旧版钉钉 com.dingtalk.mac vs 新版 com.alibaba.DingTalkMac)。 */
19
+ export function similarInstalled(bid, installedIds) {
20
+ const tokens = bid
21
+ .toLowerCase()
22
+ .split('.')
23
+ .slice(1)
24
+ .filter((t) => t.length >= 4 && !GENERIC.has(t));
25
+ return installedIds.find((a) => tokens.some((t) => a.toLowerCase().includes(t))) ?? null;
26
+ }
27
+
28
+ export async function detect(ctx) {
29
+ const installedRaw = await installedBundleIds();
30
+ const installed = installedRaw.map((s) => s.toLowerCase());
31
+ const installedExact = (bid) => {
32
+ const b = bid.toLowerCase();
33
+ return installed.some((a) => a === b || b.startsWith(a + '.') || a.startsWith(b + '.'));
34
+ };
35
+ const vendorInstalled = (bid) => installed.some((a) => vendorOf(a) === vendorOf(bid));
36
+
37
+ const cands = [];
38
+ // 1) 每个应用自己的沙盒容器
39
+ const cdir = home('Library', 'Containers');
40
+ await pMap(
41
+ await readdirSafe(cdir),
42
+ async (n) => {
43
+ const p = path.join(cdir, n);
44
+ let bid = n;
45
+ if (!BUNDLE_RE.test(bid)) {
46
+ const r = await run('plutil', ['-extract', 'MCMMetadataIdentifier', 'raw', '-o', '-', path.join(p, '.com.apple.containermanagerd.metadata.plist')]);
47
+ if (r.ok) bid = r.stdout.trim();
48
+ }
49
+ bid = stripPrefix(bid);
50
+ if (!BUNDLE_RE.test(bid) || isApple(bid) || installedExact(bid)) return;
51
+ cands.push({ p, bid, where: 'Containers', risk: vendorInstalled(bid) ? 'careful' : 'review' });
52
+ },
53
+ 8,
54
+ );
55
+ // 2) 应用组共享容器(同一厂商还有应用在,就不动)
56
+ const gdir = home('Library', 'Group Containers');
57
+ for (const n of await readdirSafe(gdir)) {
58
+ const bid = stripPrefix(n);
59
+ if (!BUNDLE_RE.test(bid) || isApple(bid) || vendorInstalled(bid)) continue;
60
+ cands.push({ p: path.join(gdir, n), bid, where: 'Group Containers', risk: 'careful', vendorOnly: true });
61
+ }
62
+ // 3) 以 bundle id 命名的 Application Support / Caches 目录
63
+ for (const [sub, risk] of [['Application Support', 'review'], ['Caches', 'safe']]) {
64
+ const d = home('Library', sub);
65
+ for (const n of await readdirSafe(d)) {
66
+ if (!BUNDLE_RE.test(n) || isApple(n) || installedExact(n)) continue;
67
+ cands.push({ p: path.join(d, n), bid: n, where: sub, risk: vendorInstalled(n) ? 'careful' : risk });
68
+ }
69
+ }
70
+
71
+ let done = 0;
72
+ const sized = await pMap(
73
+ cands,
74
+ async (c) => {
75
+ ctx.tick(id, ++done, cands.length);
76
+ return { ...c, bytes: await duBytes(c.p) };
77
+ },
78
+ 6,
79
+ );
80
+
81
+ const out = [];
82
+ for (const c of sized) {
83
+ if (c.bytes < ctx.minSize) continue;
84
+ if (await spotlightHasApp(c.bid, c.vendorOnly)) continue;
85
+ const st = await statSafe(c.p);
86
+ let risk = c.risk;
87
+ const details = [
88
+ tr(`找不到 ${c.bid} 对应的应用,可能已卸载`, `No app found for ${c.bid} — probably uninstalled`),
89
+ c.where === 'Caches'
90
+ ? tr('只是缓存', 'Cache only')
91
+ : tr('可能有聊天记录、文档等数据', 'May contain chat history, documents or other data'),
92
+ ];
93
+ const similar = similarInstalled(c.bid, installedRaw);
94
+ if (similar && c.where !== 'Caches') {
95
+ risk = 'careful';
96
+ details.push(
97
+ tr(
98
+ `已安装的 ${similar} 可能是它的新版本,这里多半是旧版本留下的`,
99
+ `The installed ${similar} looks like a newer version — this is probably left over from an old one`,
100
+ ),
101
+ );
102
+ } else if (c.risk === 'careful') {
103
+ details.push(
104
+ c.where === 'Group Containers'
105
+ ? tr('多个应用共享的数据', 'Data shared by several apps')
106
+ : tr('同一厂商的其他应用还在,可能是它的组件', 'Another app from the same vendor is installed — this may belong to it'),
107
+ );
108
+ }
109
+ if (st) details.push(tr(`${ago(st.mtimeMs)}有变动`, `Changed ${ago(st.mtimeMs)}`));
110
+ out.push(
111
+ finding({
112
+ category: id,
113
+ title: c.bid,
114
+ tag: c.where,
115
+ bytes: c.bytes,
116
+ risk,
117
+ details,
118
+ paths: [c.p],
119
+ action: { type: 'trash', paths: [c.p] },
120
+ check: { kind: 'leftover', bid: c.bid, vendorOnly: !!c.vendorOnly },
121
+ }),
122
+ );
123
+ }
124
+ return out;
125
+ }
126
+
127
+ export async function spotlightHasApp(bid, vendorOnly = false) {
128
+ const queries = vendorOnly
129
+ ? [`kMDItemCFBundleIdentifier == "${vendorOf(bid)}.*"c`]
130
+ : [bid, bid.split('.').length > 3 ? bid.split('.').slice(0, -1).join('.') : null]
131
+ .filter(Boolean)
132
+ .map((b) => `kMDItemCFBundleIdentifier == "${b}"c`);
133
+ for (const q of queries) {
134
+ const r = await run('mdfind', [q], { timeout: 20_000 });
135
+ if (r.ok && r.stdout.trim()) return true;
136
+ }
137
+ return false;
138
+ }
139
+
140
+ async function installedBundleIds() {
141
+ const top = ['/Applications', home('Applications')];
142
+ const dirs = [...top, '/System/Applications', '/System/Applications/Utilities', '/System/Library/CoreServices'];
143
+ const apps = [];
144
+ for (const d of dirs) {
145
+ for (const n of await readdirSafe(d)) {
146
+ const p = path.join(d, n);
147
+ if (n.endsWith('.app')) apps.push(p);
148
+ else if (top.includes(d)) for (const m of await readdirSafe(p)) if (m.endsWith('.app')) apps.push(path.join(p, m));
149
+ }
150
+ }
151
+ const ids = await pMap(
152
+ apps,
153
+ async (a) => {
154
+ for (const plist of [path.join(a, 'Contents', 'Info.plist'), path.join(a, 'WrappedBundle', 'Info.plist')]) {
155
+ const r = await run('plutil', ['-extract', 'CFBundleIdentifier', 'raw', '-o', '-', plist]);
156
+ if (r.ok) return r.stdout.trim();
157
+ }
158
+ return null;
159
+ },
160
+ 16,
161
+ );
162
+ return ids.filter(Boolean);
163
+ }
@@ -0,0 +1,94 @@
1
+ // 长期没动的项目里的 node_modules:按仓库分组,用 git 活动和 lock 文件判断能不能删。
2
+ import path from 'node:path';
3
+ import { run, git, duMany, statSafe, pMap, ago, daysSince, isInside, tildify } from '../util.js';
4
+ import { tr } from '../i18n.js';
5
+ import { finding } from '../model.js';
6
+
7
+ export const id = 'node_modules';
8
+ export const label = () => 'node_modules';
9
+
10
+ const LOCKS = ['package-lock.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lockb', 'bun.lock', 'npm-shrinkwrap.json'];
11
+
12
+ export async function detect(ctx) {
13
+ const found = new Set();
14
+ for (const root of ctx.roots) {
15
+ const r = await run('find', [
16
+ root, '-maxdepth', '8',
17
+ '(', '-name', '.git', '-o', '-name', '.Trash', '-o', '-name', 'Library', ')', '-prune',
18
+ '-o', '-type', 'd', '-name', 'node_modules', '-prune', '-print',
19
+ ]);
20
+ for (const l of r.stdout.split('\n')) if (l) found.add(l);
21
+ }
22
+ const { worktreePaths } = await ctx.repoIndex();
23
+ const wts = [...worktreePaths];
24
+ const candidates = [...found].filter((p) => !wts.some((w) => isInside(p, w)));
25
+
26
+ // 按 git 仓库根目录分组(monorepo 里的多个 node_modules 合成一条)
27
+ const groups = new Map();
28
+ await pMap(
29
+ candidates,
30
+ async (nm) => {
31
+ const proj = path.dirname(nm);
32
+ const top = await git(proj, ['rev-parse', '--show-toplevel']);
33
+ const root = top.ok ? top.stdout.trim() : proj;
34
+ if (!groups.has(root)) groups.set(root, { root, isGit: top.ok, nms: [] });
35
+ groups.get(root).nms.push(nm);
36
+ },
37
+ 8,
38
+ );
39
+
40
+ const out = [];
41
+ let i = 0;
42
+ const all = [...groups.values()];
43
+ for (const g of all) {
44
+ ctx.tick(id, ++i, all.length);
45
+ const last = await lastActivity(g);
46
+ const days = daysSince(last);
47
+ if (days === null || days < ctx.staleDays) continue;
48
+ const bytes = await duMany(g.nms);
49
+ if (bytes < ctx.minSize) continue;
50
+ const hasLock = await anyLock(g);
51
+ out.push(
52
+ finding({
53
+ category: id,
54
+ title: tildify(g.root),
55
+ tag: g.nms.length > 1 ? tr(`${g.nms.length} 个`, `${g.nms.length} dirs`) : undefined,
56
+ bytes,
57
+ risk: hasLock ? 'safe' : 'review',
58
+ details: [
59
+ tr(`项目最后改动 ${ago(last)}`, `Project last changed ${ago(last)}`),
60
+ hasLock
61
+ ? tr('有 lock 文件,需要时重新 install 即可', 'Has a lockfile — just reinstall when needed')
62
+ : tr('没有 lock 文件,重装可能拿到不同版本', 'No lockfile — a reinstall may pull different versions'),
63
+ ],
64
+ paths: g.nms,
65
+ action: { type: 'trash', paths: g.nms },
66
+ }),
67
+ );
68
+ }
69
+ return out;
70
+ }
71
+
72
+ async function lastActivity(g) {
73
+ const times = [];
74
+ const push = (s) => s && times.push(s.mtimeMs);
75
+ push(await statSafe(g.root));
76
+ if (g.isGit) {
77
+ const ct = await git(g.root, ['log', '-1', '--format=%ct']);
78
+ if (ct.ok && ct.stdout.trim()) times.push(Number(ct.stdout.trim()) * 1000);
79
+ const gd = await git(g.root, ['rev-parse', '--absolute-git-dir']);
80
+ if (gd.ok) push(await statSafe(path.join(gd.stdout.trim(), 'index')));
81
+ }
82
+ for (const nm of g.nms) {
83
+ const proj = path.dirname(nm);
84
+ push(await statSafe(path.join(proj, 'package.json')));
85
+ for (const l of LOCKS) push(await statSafe(path.join(proj, l)));
86
+ }
87
+ return times.length ? Math.max(...times) : null;
88
+ }
89
+
90
+ async function anyLock(g) {
91
+ const dirs = new Set([g.root, ...g.nms.map((nm) => path.dirname(nm))]);
92
+ for (const d of dirs) for (const l of LOCKS) if (await statSafe(path.join(d, l))) return true;
93
+ return false;
94
+ }
@@ -0,0 +1,176 @@
1
+ // AI 编程工具(Claude Code / Cursor / Codex…)和手动创建的 git worktree。
2
+ // 关键判断:有没有未提交改动、是否已合并、是否推送、最近是否还在用。
3
+ import path from 'node:path';
4
+ import { git, duBytes, statSafe, pMap, ago, daysSince, exists } from '../util.js';
5
+ import { tr } from '../i18n.js';
6
+ import { finding, maxRisk } from '../model.js';
7
+ import { agentOf, readGitdirFile } from '../repos.js';
8
+
9
+ export const id = 'worktree';
10
+ export const label = () => 'worktree';
11
+
12
+ export async function detect(ctx) {
13
+ const { repos, agentDirs, worktreePaths } = await ctx.repoIndex();
14
+ const jobs = [];
15
+ for (const repo of repos) for (const wt of repo.linked) jobs.push({ repo, wt });
16
+
17
+ let done = 0;
18
+ const results = await pMap(
19
+ jobs,
20
+ async ({ repo, wt }) => {
21
+ const f = await analyze(repo, wt);
22
+ ctx.tick(id, ++done, jobs.length);
23
+ return f;
24
+ },
25
+ 4,
26
+ );
27
+
28
+ // 孤立的 worktree:目录还在,但主仓库已经不记得它了
29
+ for (const { dir, gitdir } of agentDirs) {
30
+ if (worktreePaths.has(dir)) continue;
31
+ if (gitdir && (await exists(gitdir))) continue;
32
+ const bytes = await duBytes(dir);
33
+ results.push(
34
+ finding({
35
+ category: id,
36
+ title: tr(`${path.basename(dir)}(孤立)`, `${path.basename(dir)} (orphaned)`),
37
+ tag: agentOf(dir) ?? 'git',
38
+ bytes,
39
+ risk: 'review',
40
+ details: [
41
+ tr('主仓库里已没有这个 worktree 的记录(仓库被删或已 prune)', 'The main repo no longer knows this worktree (repo deleted or pruned)'),
42
+ tr('里面没提交的内容会一起删除', 'Anything uncommitted inside goes with it'),
43
+ ],
44
+ paths: [dir],
45
+ action: { type: 'trash', paths: [dir] },
46
+ }),
47
+ );
48
+ }
49
+ return results.filter(Boolean);
50
+ }
51
+
52
+ async function analyze(repo, wt) {
53
+ if (wt.prunable || !(await exists(wt.path))) return null;
54
+ const gitdir = await readGitdirFile(wt.path);
55
+
56
+ // 最后活动时间:HEAD / reflog(提交、切换分支时更新)+ 提交时间 + 未提交文件的修改时间。
57
+ // 不用 index 的时间:任何工具跑一次 git status 都会刷新它,不代表有人在用。
58
+ const times = [];
59
+ for (const f of gitdir ? ['HEAD', 'logs/HEAD'] : []) {
60
+ const s = await statSafe(path.join(gitdir, f));
61
+ if (s) times.push(s.mtimeMs);
62
+ }
63
+ const ct = await git(wt.path, ['log', '-1', '--format=%ct', 'HEAD']);
64
+ if (ct.ok && ct.stdout.trim()) times.push(Number(ct.stdout.trim()) * 1000);
65
+
66
+ const st = await git(wt.path, ['status', '--porcelain']);
67
+ const changed = st.ok ? st.stdout.split('\n').filter(Boolean) : [];
68
+ const dirty = st.ok ? changed.length : null;
69
+ for (const line of changed.slice(0, 50)) {
70
+ const rel = line.slice(3).replace(/^.* -> /, '').replace(/^"(.*)"$/, '$1');
71
+ const s = await statSafe(path.join(wt.path, rel));
72
+ if (s) times.push(s.mtimeMs);
73
+ }
74
+ const lastActive = times.length ? Math.max(...times) : null;
75
+
76
+ const mergedInto = await findMergedInto(repo, wt);
77
+ const remote = await remoteState(repo, wt);
78
+ const bytes = await duBytes(wt.path);
79
+
80
+ let risk = 'safe';
81
+ const details = [];
82
+ if (dirty === null) {
83
+ risk = 'careful';
84
+ details.push(tr('读不到 git 状态', "Couldn't read git status"));
85
+ } else if (dirty > 0) {
86
+ risk = 'careful';
87
+ details.push(tr(`${dirty} 处未提交改动,删除后会丢失`, `${dirty} uncommitted change${dirty === 1 ? '' : 's'} — would be lost`));
88
+ } else {
89
+ details.push(tr('没有未提交改动', 'No uncommitted changes'));
90
+ }
91
+
92
+ if (mergedInto) {
93
+ details.push(tr(`已合并到 ${mergedInto}`, `Merged into ${mergedInto}`));
94
+ } else {
95
+ risk = maxRisk(risk, 'review');
96
+ const n = remote.ahead;
97
+ if (n > 0) details.push(tr(`未合并,${n} 个提交没推送(分支会保留)`, `Not merged; ${n} unpushed commit${n === 1 ? '' : 's'} (the branch is kept)`));
98
+ else if (remote.onRemote) details.push(tr('未合并,分支已推送', 'Not merged; branch is pushed'));
99
+ else details.push(tr('未合并,分支只在本地(删 worktree 不删分支)', 'Not merged; branch is local only (removing the worktree keeps the branch)'));
100
+ }
101
+
102
+ const days = daysSince(lastActive);
103
+ if (days !== null && days < 2) {
104
+ risk = maxRisk(risk, 'review');
105
+ details.push(tr(`${ago(lastActive)}还在用`, `Active ${ago(lastActive)} — may still be in use`));
106
+ } else {
107
+ details.push(tr(`最后活动 ${ago(lastActive)}`, `Last active ${ago(lastActive)}`));
108
+ }
109
+
110
+ let action;
111
+ if (wt.locked) {
112
+ risk = 'careful';
113
+ details.push(tr('已被 git worktree lock 锁定', 'Locked with git worktree lock'));
114
+ action = {
115
+ type: 'manual',
116
+ hint: tr(
117
+ `先确认没人在用,再运行 git -C ${repo.path} worktree unlock ${wt.path}`,
118
+ `Make sure nothing is using it, then run git -C ${repo.path} worktree unlock ${wt.path}`,
119
+ ),
120
+ };
121
+ } else {
122
+ const argv = ['git', '-C', repo.path, 'worktree', 'remove'];
123
+ if (dirty > 0) argv.push('--force');
124
+ argv.push(wt.path);
125
+ action = { type: 'command', argv };
126
+ }
127
+
128
+ return finding({
129
+ category: id,
130
+ title: `${path.basename(repo.path)} · ${wt.branch ?? `detached@${(wt.head || '').slice(0, 7)}`}`,
131
+ tag: agentOf(wt.path) ?? 'git',
132
+ bytes,
133
+ risk,
134
+ details,
135
+ paths: [wt.path],
136
+ action,
137
+ check: { kind: 'worktree', path: wt.path, dirty },
138
+ });
139
+ }
140
+
141
+ function integrationRefs(repo) {
142
+ return (repo._refs ??= (async () => {
143
+ const refs = [];
144
+ const add = (r) => r && !refs.includes(r) && refs.push(r);
145
+ const oh = await git(repo.path, ['symbolic-ref', '-q', '--short', 'refs/remotes/origin/HEAD']);
146
+ if (oh.ok) add(oh.stdout.trim());
147
+ for (const b of ['main', 'master', 'develop', 'dev']) {
148
+ if ((await git(repo.path, ['rev-parse', '--verify', '-q', `refs/heads/${b}`])).ok) add(b);
149
+ if ((await git(repo.path, ['rev-parse', '--verify', '-q', `refs/remotes/origin/${b}`])).ok) add(`origin/${b}`);
150
+ }
151
+ if (repo.main.branch) add(repo.main.branch);
152
+ return refs;
153
+ })());
154
+ }
155
+
156
+ async function findMergedInto(repo, wt) {
157
+ if (!wt.head) return null;
158
+ for (const ref of await integrationRefs(repo)) {
159
+ if (ref === wt.branch) continue;
160
+ const r = await git(repo.path, ['merge-base', '--is-ancestor', wt.head, ref]);
161
+ if (r.ok) return ref;
162
+ }
163
+ return null;
164
+ }
165
+
166
+ async function remoteState(repo, wt) {
167
+ if (wt.branch) {
168
+ const up = await git(repo.path, ['rev-parse', '--abbrev-ref', `${wt.branch}@{upstream}`]);
169
+ if (up.ok && up.stdout.trim()) {
170
+ const n = await git(repo.path, ['rev-list', '--count', `${up.stdout.trim()}..${wt.head}`]);
171
+ return { onRemote: true, ahead: Number(n.stdout.trim()) || 0 };
172
+ }
173
+ }
174
+ const r = await git(repo.path, ['for-each-ref', '--contains', wt.head, '--count=1', '--format=%(refname)', 'refs/remotes']);
175
+ return { onRemote: r.ok && r.stdout.trim().length > 0, ahead: 0 };
176
+ }