@phyzess/kitto 0.2.0 → 0.3.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.
- package/CHANGELOG.md +32 -0
- package/README.md +36 -4
- package/bin/kitto.mjs +173 -2
- package/integration/dsh-archive-review.mjs +55 -0
- package/integration/dsh.mjs +3 -1
- package/integration/plugin.json +1 -1
- package/integration/scoped-dsh/native.mjs +33 -1
- package/integration/skills/kitto/SKILL.md +5 -4
- package/lib/codegraph.mjs +135 -0
- package/lib/codex-mcp.mjs +738 -0
- package/lib/dsh-profile.mjs +111 -0
- package/lib/environment-setup.mjs +19 -3
- package/lib/host-config.mjs +29 -4
- package/lib/hosts.mjs +288 -0
- package/lib/kitto.mjs +420 -55
- package/lib/mcp-credentials.mjs +289 -0
- package/lib/mcp-sync.mjs +500 -0
- package/lib/parity.mjs +64 -0
- package/lib/pi_config.py +218 -9
- package/lib/scope-dsh.mjs +10 -31
- package/lib/scope-setup.mjs +34 -12
- package/lib/scopes.mjs +45 -10
- package/lib/setup-prompts.mjs +68 -0
- package/lib/setup-wizard.mjs +61 -87
- package/lib/versions.mjs +8 -2
- package/lib/worktree-audit.mjs +189 -0
- package/lib/worktree-lifecycle.mjs +451 -0
- package/package.json +4 -3
- package/sync.sh +94 -25
package/lib/setup-wizard.mjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { execFile } from 'node:child_process';
|
|
2
2
|
import { homedir } from 'node:os';
|
|
3
3
|
import { resolve } from 'node:path';
|
|
4
|
-
import {
|
|
4
|
+
import { isDesktopProfile, normalizeDshProfile } from './dsh-profile.mjs';
|
|
5
|
+
import { setupPrompts } from './setup-prompts.mjs';
|
|
5
6
|
import { promisify } from 'node:util';
|
|
6
7
|
|
|
7
8
|
const agents = ['pi', 'codex', 'dsh'];
|
|
@@ -37,55 +38,17 @@ function expandHome(path) {
|
|
|
37
38
|
}
|
|
38
39
|
|
|
39
40
|
async function configure({ input, output, environment, execute, probeServicePnpm }) {
|
|
40
|
-
const
|
|
41
|
-
const rl = createInterface({ input, output, terminal });
|
|
42
|
-
const lines = rl[Symbol.asyncIterator]();
|
|
43
|
-
let interrupted = false;
|
|
44
|
-
rl.on('SIGINT', () => {
|
|
45
|
-
interrupted = true;
|
|
46
|
-
rl.close();
|
|
47
|
-
});
|
|
48
|
-
const print = line => output.write(line + '\n');
|
|
49
|
-
|
|
50
|
-
async function ask(prompt) {
|
|
51
|
-
if (interrupted) return undefined;
|
|
52
|
-
if (terminal) {
|
|
53
|
-
rl.setPrompt(prompt + ' ');
|
|
54
|
-
rl.prompt();
|
|
55
|
-
} else {
|
|
56
|
-
output.write(prompt + ' ');
|
|
57
|
-
}
|
|
58
|
-
const reply = await lines.next();
|
|
59
|
-
return interrupted || reply.done ? undefined : reply.value.trim();
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
async function choose(prompt, parse) {
|
|
63
|
-
while (true) {
|
|
64
|
-
const answer = await ask(prompt);
|
|
65
|
-
if (answer === undefined) return undefined;
|
|
66
|
-
const choice = parse(answer);
|
|
67
|
-
if (choice !== undefined) return choice;
|
|
68
|
-
print('输入无效,请重试。');
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
async function yesNo(prompt, defaultValue) {
|
|
73
|
-
return choose(prompt + (defaultValue ? ' [Y/n]' : ' [y/N]'), answer => {
|
|
74
|
-
if (!answer) return defaultValue;
|
|
75
|
-
if (/^(y|yes|是)$/i.test(answer)) return true;
|
|
76
|
-
if (/^(n|no|否)$/i.test(answer)) return false;
|
|
77
|
-
});
|
|
78
|
-
}
|
|
79
|
-
|
|
41
|
+
const { print, hosts, select, text, yesNo, close } = await setupPrompts(input, output);
|
|
80
42
|
try {
|
|
81
43
|
const { available, pnpmAvailable, serviceActive, canConfigureService } = environment;
|
|
82
44
|
const serviceAvailable = serviceActive && canConfigureService;
|
|
83
45
|
const defaults = agents.filter(agent => available.includes(agent) || (agent === 'dsh' && serviceAvailable));
|
|
84
46
|
print('Kitto 环境安装向导');
|
|
85
47
|
print('为选中的宿主配置当前账号的共享规则与 skills。按 Ctrl+C 可取消。');
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
48
|
+
const hostOptions = agents.map(value => ({
|
|
49
|
+
value, label: names[value],
|
|
50
|
+
hint: value === 'dsh' && serviceAvailable ? serviceUnit : available.includes(value) ? '已安装 CLI' : '未检测到 CLI',
|
|
51
|
+
}));
|
|
89
52
|
if (serviceActive) {
|
|
90
53
|
print('检测到正在运行的系统服务 dsh.service。' +
|
|
91
54
|
(canConfigureService ? '可以配置服务账号。' : '需要 root 权限才能配置服务账号。'));
|
|
@@ -94,17 +57,10 @@ async function configure({ input, output, environment, execute, probeServicePnpm
|
|
|
94
57
|
let selected;
|
|
95
58
|
let unit;
|
|
96
59
|
let installAgents;
|
|
60
|
+
let dshProfile = 'web';
|
|
61
|
+
let dshProfileAsked = false;
|
|
97
62
|
while (true) {
|
|
98
|
-
selected = await
|
|
99
|
-
`选择宿主,可用逗号分隔编号或名称${defaults.length ? ` [${defaults.join(',')}]` : ''},输入 0 取消。`,
|
|
100
|
-
answer => {
|
|
101
|
-
if (answer === '0') return [];
|
|
102
|
-
if (!answer && defaults.length) return defaults;
|
|
103
|
-
const items = answer.toLowerCase().split(/[,,\s]+/).filter(Boolean);
|
|
104
|
-
const chosen = items.map(item => /^[1-3]$/.test(item) ? agents[Number(item) - 1] : item);
|
|
105
|
-
if (chosen.length && chosen.every(item => agents.includes(item))) return [...new Set(chosen)];
|
|
106
|
-
},
|
|
107
|
-
);
|
|
63
|
+
selected = await hosts(hostOptions, defaults);
|
|
108
64
|
if (!selected?.length) return undefined;
|
|
109
65
|
|
|
110
66
|
unit = undefined;
|
|
@@ -114,7 +70,28 @@ async function configure({ input, output, environment, execute, probeServicePnpm
|
|
|
114
70
|
if (useService) unit = serviceUnit;
|
|
115
71
|
}
|
|
116
72
|
|
|
117
|
-
|
|
73
|
+
if (selected.includes('dsh') && !dshProfileAsked) {
|
|
74
|
+
dshProfile = await text('DSH 配置档名称(desktop 由 Desktop 应用管理,仅部署全局规则/skills)', {
|
|
75
|
+
initialValue: 'web',
|
|
76
|
+
validate: value => {
|
|
77
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(value)) return '请输入有效的 DSH 配置档名称';
|
|
78
|
+
if (unit && value.toLowerCase() === 'desktop') return '系统服务不能使用 desktop 配置档';
|
|
79
|
+
},
|
|
80
|
+
});
|
|
81
|
+
if (dshProfile === undefined) return undefined;
|
|
82
|
+
dshProfile = normalizeDshProfile(dshProfile);
|
|
83
|
+
dshProfileAsked = true;
|
|
84
|
+
if (isDesktopProfile(dshProfile)) {
|
|
85
|
+
print('DSH Desktop 由 App 管理:Kitto 只部署全局 AGENTS.md 和 skills;不安装 bundle、不写 profile patch、不需要 pnpm。');
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const desktopDsh = selected.includes('dsh') && isDesktopProfile(dshProfile);
|
|
90
|
+
const missing = selected.filter(agent => !available.includes(agent) &&
|
|
91
|
+
!(agent === 'dsh' && (unit || desktopDsh)));
|
|
92
|
+
if (desktopDsh && !available.includes('dsh')) {
|
|
93
|
+
print('DSH Desktop 不要求本机 dsh CLI:Kitto 不会用 npm 补装它。');
|
|
94
|
+
}
|
|
118
95
|
installAgents = false;
|
|
119
96
|
if (missing.length) {
|
|
120
97
|
installAgents = await yesNo(`补装 ${missing.map(agent => names[agent]).join('、')}?`, true);
|
|
@@ -124,22 +101,25 @@ async function configure({ input, output, environment, execute, probeServicePnpm
|
|
|
124
101
|
break;
|
|
125
102
|
}
|
|
126
103
|
|
|
127
|
-
print('配置来源');
|
|
128
104
|
print('完整配置包含仓库的 AGENTS.md、skills 和所选宿主的 Kitto 集成。选择 Pi 时还会同步 Pi 包、扩展和 MCP 设置。');
|
|
129
|
-
print(' 1. 使用默认 Kitto 配置,优先复用已有安装');
|
|
130
|
-
print(' 2. 指定配置仓库路径或 Git URL');
|
|
131
|
-
print(' 3. 仅配置共享规则与 skills');
|
|
132
105
|
let source;
|
|
133
106
|
let serviceInstallAgents;
|
|
134
107
|
let servicePnpmAvailable;
|
|
135
108
|
while (true) {
|
|
136
|
-
const sourceChoice = await
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
109
|
+
const sourceChoice = await select('选择配置来源', [
|
|
110
|
+
{ value: '1', label: '默认 Kitto 配置', hint: '优先复用已有安装' },
|
|
111
|
+
{ value: '2', label: '指定配置仓库路径或 Git URL' },
|
|
112
|
+
{ value: '3', label: '仅配置共享规则与 skills' },
|
|
113
|
+
{ value: '0', label: '取消' },
|
|
114
|
+
], '1');
|
|
140
115
|
if (sourceChoice === undefined || sourceChoice === '0') return;
|
|
141
116
|
|
|
142
|
-
|
|
117
|
+
if (sourceChoice === '3' && isDesktopProfile(dshProfile) && selected.includes('dsh')) {
|
|
118
|
+
print('DSH Desktop 需要配置来源才能部署全局规则与 skills,不能选择「仅配置共享规则与 skills」。请选择 1 或 2,或改用 web 配置档。');
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const needsPnpm = sourceChoice !== '3' && selected.includes('dsh') && !unit && !isDesktopProfile(dshProfile) && pnpmAvailable === false;
|
|
143
123
|
if (needsPnpm) {
|
|
144
124
|
const installPnpm = await yesNo('本机 DSH 的完整配置需要 pnpm。允许补装 pnpm?', true);
|
|
145
125
|
if (installPnpm === undefined) return;
|
|
@@ -150,7 +130,7 @@ async function configure({ input, output, environment, execute, probeServicePnpm
|
|
|
150
130
|
installAgents = true;
|
|
151
131
|
}
|
|
152
132
|
|
|
153
|
-
if (unit && sourceChoice !== '3') {
|
|
133
|
+
if (unit && sourceChoice !== '3' && !isDesktopProfile(dshProfile)) {
|
|
154
134
|
servicePnpmAvailable ??= await probeServicePnpm(unit);
|
|
155
135
|
if (servicePnpmAvailable === false) {
|
|
156
136
|
const installPnpm = await yesNo(`服务 ${unit} 的完整配置需要 pnpm。允许在服务账号中补装 pnpm?`, true);
|
|
@@ -164,7 +144,7 @@ async function configure({ input, output, environment, execute, probeServicePnpm
|
|
|
164
144
|
}
|
|
165
145
|
|
|
166
146
|
if (sourceChoice === '2') {
|
|
167
|
-
const path = await
|
|
147
|
+
const path = await text('配置仓库路径或 Git URL', { validate: value => value ? undefined : '请输入路径或 Git URL' });
|
|
168
148
|
if (path === undefined) return;
|
|
169
149
|
source = expandHome(path);
|
|
170
150
|
} else if (sourceChoice === '3') {
|
|
@@ -175,18 +155,9 @@ async function configure({ input, output, environment, execute, probeServicePnpm
|
|
|
175
155
|
|
|
176
156
|
const deps = source === false ? false : await yesNo('安装配置中声明的辅助工具和依赖?', false);
|
|
177
157
|
if (deps === undefined) return undefined;
|
|
178
|
-
const workspace = await
|
|
158
|
+
const workspace = await text('工作区父目录(可选)。例如未来项目会放在 ~/workspaces/workspace-1 下,就填 ~/workspaces。留空使用全局配置。');
|
|
179
159
|
if (workspace === undefined) return undefined;
|
|
180
160
|
|
|
181
|
-
let dshProfile = 'web';
|
|
182
|
-
if (selected.includes('dsh')) {
|
|
183
|
-
dshProfile = await choose('DSH 配置档名称 [web]。', answer => {
|
|
184
|
-
if (!answer) return 'web';
|
|
185
|
-
if (/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(answer) && answer !== 'desktop') return answer;
|
|
186
|
-
});
|
|
187
|
-
if (dshProfile === undefined) return undefined;
|
|
188
|
-
}
|
|
189
|
-
|
|
190
161
|
const plan = {
|
|
191
162
|
agents: selected, source, installAgents, deps, workspace: workspace ? expandHome(workspace) : undefined,
|
|
192
163
|
unit, dshProfile,
|
|
@@ -196,32 +167,35 @@ async function configure({ input, output, environment, execute, probeServicePnpm
|
|
|
196
167
|
print(` 宿主 ${selected.map(agent => names[agent]).join('、')}`);
|
|
197
168
|
print(` 配置来源 ${source === false ? '仅配置共享规则与 skills' : source ?? '默认 Kitto 配置'}`);
|
|
198
169
|
print(' 共享范围 全局' + (plan.workspace ? `,以及工作区 ${plan.workspace}` : ''));
|
|
199
|
-
if (selected.includes('dsh'))
|
|
170
|
+
if (selected.includes('dsh')) {
|
|
171
|
+
print(` DSH ${unit ?? '当前账号'},配置档 ${dshProfile}${isDesktopProfile(dshProfile) ? '(由 App 管理,仅全局规则/skills)' : ''}`);
|
|
172
|
+
}
|
|
200
173
|
print(` 补装缺少的宿主和必需工具 ${installAgents ? '是' : '否'}`);
|
|
174
|
+
if (selected.includes('dsh') && isDesktopProfile(dshProfile)) {
|
|
175
|
+
print(' DSH Desktop 不检查、也不补装本机 dsh CLI(由 App 管理)。');
|
|
176
|
+
}
|
|
201
177
|
if (serviceInstallAgents) print(` 为 ${unit} 的账号补装 pnpm 是`);
|
|
202
178
|
if (source !== false) print(` 安装配置声明的辅助依赖 ${deps ? '是' : '否'}`);
|
|
203
179
|
|
|
204
|
-
let action = await
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
});
|
|
180
|
+
let action = await select('下一步', [
|
|
181
|
+
{ value: '1', label: '预览' }, { value: '2', label: '安装' }, { value: '0', label: '取消' },
|
|
182
|
+
], '1');
|
|
208
183
|
if (action === '1') {
|
|
209
184
|
await execute({ ...plan, dryRun: true });
|
|
210
|
-
action = await
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
});
|
|
185
|
+
action = await select('预览完成', [
|
|
186
|
+
{ value: '0', label: '退出' }, { value: '2', label: '按此计划安装' },
|
|
187
|
+
], '0');
|
|
214
188
|
if (action !== '2') {
|
|
215
189
|
print('已退出,未执行安装。');
|
|
216
190
|
return true;
|
|
217
191
|
}
|
|
218
192
|
}
|
|
219
193
|
if (action !== '2') return;
|
|
220
|
-
|
|
194
|
+
close();
|
|
221
195
|
await execute({ ...plan, dryRun: false });
|
|
222
196
|
return true;
|
|
223
197
|
} finally {
|
|
224
|
-
|
|
198
|
+
close();
|
|
225
199
|
}
|
|
226
200
|
}
|
|
227
201
|
|
package/lib/versions.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto';
|
|
|
2
2
|
import { readFile, readdir } from 'node:fs/promises';
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
import { dependencyPlan, executable, npmSpec, npxPackage, optionalJson, piServers, query } from './dependencies.mjs';
|
|
5
|
+
import { isDesktopProfile } from './dsh-profile.mjs';
|
|
5
6
|
import { hostSkillRoots } from './host-config.mjs';
|
|
6
7
|
|
|
7
8
|
const version = output => output?.match(/\d+\.\d+\.\d+(?:-[\w.-]+)?/)?.[0] || null;
|
|
@@ -108,11 +109,16 @@ export async function versionReport(state, hosts, pnpmVersion, online, hashTree)
|
|
|
108
109
|
for (const name of state.agents) {
|
|
109
110
|
rows.push({ kind: 'npm', owner: name, name: hosts[name].package, installed: version(query(name, ['--version'])), tested: hosts[name].version });
|
|
110
111
|
}
|
|
111
|
-
if (state.agents.includes('dsh')) rows.push({ kind: 'npm', owner: 'dsh', name: 'pnpm', installed: version(query('pnpm', ['--version'])), tested: pnpmVersion });
|
|
112
|
+
if (state.agents.includes('dsh') && !isDesktopProfile(state.dshProfile)) rows.push({ kind: 'npm', owner: 'dsh', name: 'pnpm', installed: version(query('pnpm', ['--version'])), tested: pnpmVersion });
|
|
112
113
|
const revision = query('git', ['-C', state.source, 'rev-parse', 'HEAD']);
|
|
113
114
|
if (state.agents.includes('pi')) rows.push(...await piVersions(state, revision));
|
|
114
115
|
if (state.agents.includes('codex')) rows.push(...await codexVersions(state));
|
|
115
|
-
if (state.agents.includes('dsh'))
|
|
116
|
+
if (state.agents.includes('dsh')) {
|
|
117
|
+
if (isDesktopProfile(state.dshProfile)) {
|
|
118
|
+
rows.push({ kind: 'inventory', owner: 'dsh', profile: state.dshProfile,
|
|
119
|
+
note: 'DSH desktop profile is app-managed; Kitto does not manage its bundles, patch or pnpm.' });
|
|
120
|
+
} else rows.push(...await dshVersions(state));
|
|
121
|
+
}
|
|
116
122
|
for (const { name, source } of [{ name: 'shared', source: join(state.source, 'skills') }, ...hostSkillRoots(state)]) {
|
|
117
123
|
rows.push(...(await resources(source, revision, hashTree)).map(row => ({ ...row, owner: name })));
|
|
118
124
|
}
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { lstat, readFile, readdir, realpath } from 'node:fs/promises';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
|
+
|
|
5
|
+
const usage = 'kitto worktree audit [--workspace PATH] [--json]';
|
|
6
|
+
const text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
|
|
7
|
+
// Do not inherit repository selection, trace destinations or injected Git config.
|
|
8
|
+
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')));
|
|
9
|
+
Object.assign(env, { LC_ALL: 'C', GIT_ALLOW_PROTOCOL: '', GIT_NO_LAZY_FETCH: '1', GIT_TERMINAL_PROMPT: '0',
|
|
10
|
+
GIT_TRACE2: '0', GIT_TRACE2_PERF: '0', GIT_TRACE2_EVENT: '0' });
|
|
11
|
+
if (process.env.GIT_CONFIG_NOSYSTEM === '1') env.GIT_CONFIG_NOSYSTEM = '1';
|
|
12
|
+
|
|
13
|
+
export function git(cwd, ...args) {
|
|
14
|
+
return spawnSync('git', ['--no-optional-locks', '-c', 'core.fsmonitor=false',
|
|
15
|
+
'-c', 'core.hooksPath=/dev/null', '-c', 'gc.auto=0', '-C', cwd, ...args],
|
|
16
|
+
{ env, timeout: 30000, maxBuffer: 16 * 1024 * 1024 });
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function cleanExit(result, status = 0) {
|
|
20
|
+
// A probe can emit partial results and warn on stderr even with the expected exit code.
|
|
21
|
+
return !result.error && result.status === status && result.stderr?.length === 0;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function output(path, ...args) {
|
|
25
|
+
const result = git(path, ...args);
|
|
26
|
+
if (result.error) throw result.error;
|
|
27
|
+
if (!cleanExit(result)) throw new Error(`Cannot read Git ${args[0]} at ${JSON.stringify(path)}.`);
|
|
28
|
+
return text.decode(result.stdout).replace(/\n$/, ''); // Preserve whitespace in paths.
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function commonDir(path) {
|
|
32
|
+
return realpath(output(path, 'rev-parse', '--path-format=absolute', '--git-common-dir'));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function registrations(repo) {
|
|
36
|
+
return output(repo, 'worktree', 'list', '--porcelain', '-z').split('\0\0').filter(Boolean).map(record =>
|
|
37
|
+
Object.fromEntries(record.split('\0').map(line => {
|
|
38
|
+
const i = line.indexOf(' ');
|
|
39
|
+
return i < 0 ? [line, true] : [line.slice(0, i), line.slice(i + 1)];
|
|
40
|
+
})));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function diskBytes(path) {
|
|
44
|
+
// Both BSD and GNU du support -k, -s and -x. Ignore partial totals on error.
|
|
45
|
+
const result = spawnSync('du', ['-skx', path], { env, timeout: 60000 });
|
|
46
|
+
if (!cleanExit(result)) return null;
|
|
47
|
+
const match = /^(\d+)\t/.exec(result.stdout.toString());
|
|
48
|
+
const bytes = match ? Number(match[1]) * 1024 : NaN;
|
|
49
|
+
return Number.isSafeInteger(bytes) ? bytes : null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function changes(path) {
|
|
53
|
+
// A configured clean/process filter can run arbitrary programs during status.
|
|
54
|
+
// Don't invoke it, even indirectly through nested submodule status.
|
|
55
|
+
if (!cleanExit(git(path, 'config', '--get-regexp', '^filter\\..*\\.(clean|process)$'), 1)) return null;
|
|
56
|
+
const result = git(path, 'status', '--porcelain=v1', '-z', '--no-renames', '--ignored=matching',
|
|
57
|
+
'--untracked-files=normal', '--ignore-submodules=all');
|
|
58
|
+
if (!cleanExit(result)) return null;
|
|
59
|
+
const lines = result.stdout.toString('latin1').split('\0').filter(Boolean);
|
|
60
|
+
return { tracked: lines.some(line => !['!!', '??'].includes(line.slice(0, 2))),
|
|
61
|
+
untracked: lines.some(line => line.startsWith('??')), ignored: lines.some(line => line.startsWith('!!')) };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function checkoutGitDir(path, common, primary, bare) {
|
|
65
|
+
const gitDir = await realpath(output(path, 'rev-parse', '--absolute-git-dir'));
|
|
66
|
+
if (await commonDir(path) !== common || (!bare && output(path, 'rev-parse', '--show-toplevel') !== path)) {
|
|
67
|
+
throw new Error('Worktree checkout mismatch');
|
|
68
|
+
}
|
|
69
|
+
if (primary) {
|
|
70
|
+
if (gitDir !== common) throw new Error('Primary Git directory mismatch');
|
|
71
|
+
} else {
|
|
72
|
+
const marker = join(path, '.git');
|
|
73
|
+
if (dirname(gitDir) !== join(common, 'worktrees') ||
|
|
74
|
+
await realpath(output(path, 'rev-parse', '--resolve-git-dir', marker)) !== gitDir) {
|
|
75
|
+
throw new Error('Linked Git directory mismatch');
|
|
76
|
+
}
|
|
77
|
+
// A gitfile can select a different linked checkout in the same repository.
|
|
78
|
+
// Require its administrative directory to point back to this checkout's gitfile.
|
|
79
|
+
const reverse = join(gitDir, 'gitdir');
|
|
80
|
+
if (!(await lstat(reverse)).isFile()) throw new Error('Invalid worktree backlink');
|
|
81
|
+
const backlink = text.decode(await readFile(reverse)).replace(/\n$/, '');
|
|
82
|
+
if (!backlink || resolve(gitDir, backlink) !== marker) throw new Error('Worktree backlink mismatch');
|
|
83
|
+
}
|
|
84
|
+
return gitDir;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export async function inspect(repo, common, entry, primary, base, unique) {
|
|
88
|
+
const path = entry.worktree;
|
|
89
|
+
const row = { path, commonDir: common, gitDir: null, primary, bare: !!entry.bare,
|
|
90
|
+
branch: entry.branch ?? null, head: entry.HEAD ?? null, detached: !!entry.detached,
|
|
91
|
+
locked: !!entry.locked, prunable: !!entry.prunable, estimatedBytes: null,
|
|
92
|
+
changes: null, upstream: null, localBaseHead: base, mergedIntoLocalBase: null,
|
|
93
|
+
ownership: 'unmanaged', occupancy: 'unknown', blockers: ['unmanaged', 'occupancy-unknown'] };
|
|
94
|
+
for (const fact of ['primary', 'bare', 'detached', 'locked', 'prunable']) if (row[fact]) row.blockers.push(fact);
|
|
95
|
+
try {
|
|
96
|
+
if (!unique || await realpath(path) !== path) throw new Error('Worktree registration mismatch');
|
|
97
|
+
row.gitDir = await checkoutGitDir(path, common, primary, row.bare);
|
|
98
|
+
} catch {
|
|
99
|
+
row.blockers.push('identity-unknown');
|
|
100
|
+
return row;
|
|
101
|
+
}
|
|
102
|
+
row.estimatedBytes = diskBytes(path);
|
|
103
|
+
if (row.estimatedBytes === null) row.blockers.push('size-unknown');
|
|
104
|
+
if (row.bare) return row;
|
|
105
|
+
if (row.branch) {
|
|
106
|
+
try { row.upstream = output(repo, 'for-each-ref', '--format=%(upstream)', row.branch) || null; }
|
|
107
|
+
catch { row.blockers.push('upstream-unknown'); }
|
|
108
|
+
}
|
|
109
|
+
if (base && row.head) {
|
|
110
|
+
const result = git(repo, 'merge-base', '--is-ancestor', row.head, base);
|
|
111
|
+
if (cleanExit(result)) row.mergedIntoLocalBase = true;
|
|
112
|
+
else if (cleanExit(result, 1)) row.mergedIntoLocalBase = false;
|
|
113
|
+
}
|
|
114
|
+
if (row.mergedIntoLocalBase !== true) row.blockers.push(row.mergedIntoLocalBase === false ? 'not-in-local-base' : 'ancestry-unknown');
|
|
115
|
+
// Even --no-optional-locks does not stop Git freshening sharedindex.* mtimes.
|
|
116
|
+
// Without reading the index, conservatively skip probes if shared indexes exist.
|
|
117
|
+
const metadata = await readdir(row.gitDir).catch(() => null);
|
|
118
|
+
if (!metadata || metadata.some(name => name.startsWith('sharedindex.'))) {
|
|
119
|
+
row.blockers.push('index-probe-skipped', 'changes-unknown');
|
|
120
|
+
return row;
|
|
121
|
+
}
|
|
122
|
+
row.changes = changes(path);
|
|
123
|
+
if (!row.changes) row.blockers.push('changes-unknown');
|
|
124
|
+
else for (const [key, present] of Object.entries(row.changes)) if (present) row.blockers.push(key);
|
|
125
|
+
const files = git(path, 'ls-files', '-v', '--stage', '-z');
|
|
126
|
+
if (!cleanExit(files)) row.blockers.push('index-flags-unknown');
|
|
127
|
+
else {
|
|
128
|
+
const records = files.stdout.toString('latin1').split('\0');
|
|
129
|
+
if (records.some(record => /^[a-zS] /.test(record))) row.blockers.push('masked-index-entries');
|
|
130
|
+
if (records.some(record => /^. 160000 /.test(record))) row.blockers.push('submodules-unknown');
|
|
131
|
+
}
|
|
132
|
+
for (const marker of ['MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'BISECT_START', 'rebase-merge', 'rebase-apply', 'sequencer']) {
|
|
133
|
+
try { await lstat(join(row.gitDir, marker)); row.blockers.push(`git-operation:${marker}`); }
|
|
134
|
+
catch (error) { if (error.code !== 'ENOENT') row.blockers.push('git-operation-unknown'); }
|
|
135
|
+
}
|
|
136
|
+
return row;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async function candidates(workspace) {
|
|
140
|
+
if (!workspace) return [process.cwd()];
|
|
141
|
+
const root = await realpath(workspace);
|
|
142
|
+
const dirs = await readdir(root, { withFileTypes: true });
|
|
143
|
+
if (dirs.some(entry => entry.name === '.git')) return [root];
|
|
144
|
+
const repos = [];
|
|
145
|
+
for (const entry of dirs) {
|
|
146
|
+
if (!entry.isDirectory()) continue;
|
|
147
|
+
const dir = join(root, entry.name);
|
|
148
|
+
try { await lstat(join(dir, '.git')); repos.push(dir); }
|
|
149
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
150
|
+
}
|
|
151
|
+
return repos;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Inventory local Git registrations without creating state or inferring ownership. */
|
|
155
|
+
export async function auditWorktrees(workspace) {
|
|
156
|
+
const rows = [], seen = new Set();
|
|
157
|
+
for (const repo of await candidates(workspace)) {
|
|
158
|
+
const common = await commonDir(repo);
|
|
159
|
+
if (seen.has(common)) continue;
|
|
160
|
+
seen.add(common);
|
|
161
|
+
const entries = registrations(repo);
|
|
162
|
+
const base = entries[0]?.HEAD ?? null;
|
|
163
|
+
const counts = new Map();
|
|
164
|
+
for (const { worktree } of entries) counts.set(worktree, (counts.get(worktree) ?? 0) + 1);
|
|
165
|
+
for (const [index, entry] of entries.entries()) {
|
|
166
|
+
rows.push(await inspect(repo, common, entry, index === 0, base, counts.get(entry.worktree) === 1));
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return rows.sort((a, b) => (b.estimatedBytes ?? -1) - (a.estimatedBytes ?? -1) || a.path.localeCompare(b.path));
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export async function worktreeCommand([command, ...args]) {
|
|
173
|
+
if (!command || ['--help', '-h'].includes(command) || (command === 'audit' && args.length === 1 && ['--help', '-h'].includes(args[0]))) {
|
|
174
|
+
console.log(usage); return;
|
|
175
|
+
}
|
|
176
|
+
if (command !== 'audit') throw new Error(`Usage: ${usage}`);
|
|
177
|
+
let workspace, json = false;
|
|
178
|
+
for (let i = 0; i < args.length; i++) {
|
|
179
|
+
if (args[i] === '--json' && !json) json = true;
|
|
180
|
+
else if (args[i] === '--workspace' && !workspace && args[i + 1] && !args[i + 1].startsWith('-')) workspace = resolve(args[++i]);
|
|
181
|
+
else throw new Error(`Usage: ${usage}`);
|
|
182
|
+
}
|
|
183
|
+
const rows = await auditWorktrees(workspace);
|
|
184
|
+
if (json) console.log(JSON.stringify(rows, null, 2));
|
|
185
|
+
else {
|
|
186
|
+
console.log('Estimated bytes | Worktree | Branch / HEAD | Blockers (not a removal decision)');
|
|
187
|
+
for (const row of rows) console.log(`${row.estimatedBytes ?? 'unknown'} | ${JSON.stringify(row.path)} | ${JSON.stringify(row.branch ?? row.head)} | ${row.blockers.join(', ')}`);
|
|
188
|
+
}
|
|
189
|
+
}
|