@essrj/vc-workflow 0.0.0-stage → 0.1.1
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/legacy-0.1.0.json +35 -0
- package/package.json +9 -4
- package/runtime/agents/advisor.md +10 -0
- package/runtime/agents/reviewer.md +10 -0
- package/runtime/agents/verifier.md +11 -0
- package/runtime/prompts/coding.md +40 -0
- package/runtime/prompts/doctor.md +58 -0
- package/runtime/prompts/hunt.md +33 -0
- package/runtime/prompts/plan.md +30 -0
- package/runtime/prompts/ready-routing.md +15 -0
- package/runtime/skills/grilling/SKILL.md +28 -0
- package/runtime/skills/review/SKILL.md +28 -0
- package/runtime/skills/review/references/review-method.md +83 -0
- package/runtime/skills/vc-transfer/SKILL.md +16 -0
- package/runtime/skills/vc-transfer/templates/INT.md +33 -0
- package/runtime/skills/vc-transfer/templates/PLAN.md +20 -0
- package/runtime/skills/vc-transfer/templates/SPEC.md +31 -0
- package/runtime/skills/vc-transfer/templates/TCSET.md +30 -0
- package/runtime/vc.exe +0 -0
- package/setup.mjs +841 -0
- package/upgrade.mjs +56 -0
- package/README.md +0 -3
package/setup.mjs
ADDED
|
@@ -0,0 +1,841 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
+
import fs from 'node:fs/promises';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import process from 'node:process';
|
|
8
|
+
import { emitKeypressEvents } from 'node:readline';
|
|
9
|
+
import { createInterface } from 'node:readline/promises';
|
|
10
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
11
|
+
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
12
|
+
import { commitUpdate, removeEmptyParents } from './upgrade.mjs';
|
|
13
|
+
|
|
14
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
15
|
+
const supported = ['claude-code', 'codex'];
|
|
16
|
+
const stages = {
|
|
17
|
+
hunt: '调查问题、核实根因并提出下一步建议',
|
|
18
|
+
plan: '澄清需求、拆解功能并制定实施计划',
|
|
19
|
+
coding: '按任务范围实施改动、验证并完成本地交付',
|
|
20
|
+
};
|
|
21
|
+
const payload = ['vc.exe', ...['ready-routing', ...Object.keys(stages)].map(x => `prompts/${x}.md`)];
|
|
22
|
+
const matcher = '.*'; // PLAN inspects ordinary host tools as well as VC calls.
|
|
23
|
+
const events = ['UserPromptSubmit', 'PreToolUse'];
|
|
24
|
+
// Only fixed labels and sanitized version numbers cross this boundary. The
|
|
25
|
+
// installer never waits for its diagnostic helper to write or exit.
|
|
26
|
+
function writeSetupLog({ version, events }) {
|
|
27
|
+
if (process.platform !== 'win32' || !path.isAbsolute(process.env.LOCALAPPDATA ?? '')) return;
|
|
28
|
+
try {
|
|
29
|
+
const child = spawn(path.join(here, 'runtime', 'vc.exe'), ['setup-log', JSON.stringify({ version, events })], {
|
|
30
|
+
detached: true, windowsHide: true, stdio: 'ignore',
|
|
31
|
+
});
|
|
32
|
+
child.on('error', () => {});
|
|
33
|
+
child.unref();
|
|
34
|
+
} catch {
|
|
35
|
+
// Diagnostics never change the installer result.
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function fail(message) { throw new Error(message); }
|
|
40
|
+
function samePath(a, b) { return typeof a === 'string' && path.normalize(a).toLowerCase() === path.normalize(b).toLowerCase(); }
|
|
41
|
+
function object(value, label) {
|
|
42
|
+
if (!value || Array.isArray(value) || typeof value !== 'object') fail(`${label} must be a JSON object`);
|
|
43
|
+
return value;
|
|
44
|
+
}
|
|
45
|
+
async function optional(file) {
|
|
46
|
+
try { return await fs.readFile(file); } catch (error) { if (error.code !== 'ENOENT') throw error; return null; }
|
|
47
|
+
}
|
|
48
|
+
function jsonEdit(file, before, data) {
|
|
49
|
+
const after = Buffer.from(`${JSON.stringify(data, null, 2)}\n`);
|
|
50
|
+
return { file, before, after };
|
|
51
|
+
}
|
|
52
|
+
async function jsonFile(file) {
|
|
53
|
+
const before = await optional(file);
|
|
54
|
+
return { file, before, data: object(before === null ? {} : JSON.parse(before.toString('utf8').replace(/^\uFEFF/, '')), file) };
|
|
55
|
+
}
|
|
56
|
+
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
|
|
57
|
+
const matches = (a, b) => a === null ? b === null : Boolean(b?.equals(a));
|
|
58
|
+
|
|
59
|
+
export async function apply({ file, before, after, retire, backup }) {
|
|
60
|
+
if (after === null && !retire) {
|
|
61
|
+
if (!matches(before, await optional(file))) fail(`File changed during setup: ${file}`);
|
|
62
|
+
await fs.unlink(file);
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
if (retire) {
|
|
66
|
+
if (!(await optional(file))?.equals(before)) fail(`Entry changed during setup: ${file}`);
|
|
67
|
+
// Keep a recoverable copy, with a name neither host discovers as an entry.
|
|
68
|
+
const saved = typeof backup === 'string' ? backup : `${file}.vc-backup-${randomUUID()}`;
|
|
69
|
+
await fs.rename(file, saved);
|
|
70
|
+
console.log(`Backed up replaced entry: ${saved}`);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
74
|
+
const temp = `${file}.vc-${randomUUID()}.tmp`;
|
|
75
|
+
let installed = false;
|
|
76
|
+
try {
|
|
77
|
+
await fs.writeFile(temp, after, { flag: 'wx' });
|
|
78
|
+
const current = await optional(file);
|
|
79
|
+
if (before === null ? current !== null : !current?.equals(before)) fail(`Configuration changed during setup: ${file}`);
|
|
80
|
+
if (before === null) await fs.link(temp, file); // Do not replace a concurrently created user file.
|
|
81
|
+
else await fs.rename(temp, file);
|
|
82
|
+
installed = true;
|
|
83
|
+
} finally {
|
|
84
|
+
try { await fs.rm(temp, { force: true }); }
|
|
85
|
+
catch (error) { error.targetInstalled = installed; throw error; }
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Use the existing host CLI to update TOML. Pass arguments as a JSON array in
|
|
90
|
+
// the child environment, not as PowerShell/cmd source and not via shell:true.
|
|
91
|
+
function hostCommand(host, args, cwd, codexHome) {
|
|
92
|
+
const script = `$ErrorActionPreference = 'Stop'; $command = Get-Command -Name '${host}.exe','${host}.cmd' -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1; if (!$command) { exit 127 }; $a = @(ConvertFrom-Json $env:VC_SETUP_HOST_ARGS); & $command.Source @a; exit $LASTEXITCODE`;
|
|
93
|
+
const child = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')], {
|
|
94
|
+
cwd, env: { ...process.env, ...(codexHome ? { CODEX_HOME: codexHome } : {}), VC_SETUP_HOST_ARGS: JSON.stringify(args) }, encoding: 'utf8', windowsHide: true, timeout: 20000,
|
|
95
|
+
});
|
|
96
|
+
if (child.error) throw child.error;
|
|
97
|
+
return { result: child.status, out: child.stdout.trim(), error: child.stderr.trim() };
|
|
98
|
+
}
|
|
99
|
+
function cliVersion(host, installDir, progress) {
|
|
100
|
+
const result = hostCommand(host === 'claude-code' ? 'claude' : 'codex', ['--version'], installDir);
|
|
101
|
+
if (result.result !== 0) {
|
|
102
|
+
progress.events.push({ event: 'host_version', outcome: 'failed', host, reason: 'cli_unavailable' });
|
|
103
|
+
fail(`${host} CLI not found or could not run. Install it separately, then repeat setup.`);
|
|
104
|
+
}
|
|
105
|
+
const version = result.out.match(/\b\d{1,6}\.\d{1,6}\.\d{1,6}\b/)?.[0];
|
|
106
|
+
const tested = host === 'claude-code' ? '2.1.332' : '0.172.0';
|
|
107
|
+
if (version !== tested) {
|
|
108
|
+
progress.events.push({ event: 'host_version', outcome: 'failed', host, hostVersion: version, reason: 'unsupported_version' });
|
|
109
|
+
fail(`${host} ${version ?? '(unknown version)'} is not verified with this installer; expected ${tested}.`);
|
|
110
|
+
}
|
|
111
|
+
progress.events.push({ event: 'host_version', outcome: 'ok', host, hostVersion: version });
|
|
112
|
+
}
|
|
113
|
+
function psQuote(s) { return `'${s.replaceAll("'", "''")}'`; }
|
|
114
|
+
export function hookGroup(host, exe, event) {
|
|
115
|
+
const args = ['native-hook', host, event];
|
|
116
|
+
const command = `& ${[exe, ...args].map(psQuote).join(' ')}`;
|
|
117
|
+
const handler = host === 'claude-code'
|
|
118
|
+
? { type: 'command', command: exe, args, timeout: 8, ...(event === 'PreToolUse' ? { onFailure: 'block' } : {}) }
|
|
119
|
+
: { type: 'command', command, commandWindows: command, timeout: 8 };
|
|
120
|
+
return { ...(event === 'PreToolUse' ? { matcher } : {}), hooks: [handler] };
|
|
121
|
+
}
|
|
122
|
+
const oldLocalExe = String.raw`$env:LOCALAPPDATA\vc\versions\0.1.0\vc.exe`;
|
|
123
|
+
function windowsText(value) { return value.replaceAll('/', '\\').toLowerCase(); }
|
|
124
|
+
function oldLocalPath() {
|
|
125
|
+
const local = process.env.LOCALAPPDATA;
|
|
126
|
+
return local && path.isAbsolute(local) ? path.join(local, 'vc', 'versions', '0.1.0', 'vc.exe') : null;
|
|
127
|
+
}
|
|
128
|
+
// Only the documented, double-quoted old executable may use LOCALAPPDATA.
|
|
129
|
+
// All other supported tokens are literal. Never evaluate hook text.
|
|
130
|
+
function codexInvocation(text) {
|
|
131
|
+
if (typeof text !== 'string') return null;
|
|
132
|
+
let rest = text.trim().replace(/^&[ \t]*/, '');
|
|
133
|
+
const args = [];
|
|
134
|
+
while (rest) {
|
|
135
|
+
const envExe = !args.length && /^"([^"\r\n]+)"(?=[ \t]|$)/.exec(rest);
|
|
136
|
+
if (envExe && windowsText(envExe[1]) === windowsText(oldLocalExe)) {
|
|
137
|
+
const file = oldLocalPath();
|
|
138
|
+
if (!file) return null;
|
|
139
|
+
args.push(file);
|
|
140
|
+
rest = rest.slice(envExe[0].length).replace(/^[ \t]+/, '');
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
// A literal named option is one argument, even when only its value is quoted.
|
|
144
|
+
const option = args.length && /^(--[\w-]+=)(?:'((?:[^']|'')*)'|"([^"$`\r\n]*)")(?=[ \t]|$)/.exec(rest);
|
|
145
|
+
if (option) {
|
|
146
|
+
args.push(option[1] + (option[2]?.replaceAll("''", "'") ?? option[3]));
|
|
147
|
+
rest = rest.slice(option[0].length).replace(/^[ \t]+/, '');
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
const match = /^(?:'((?:[^']|'')*)'|"([^"$`\r\n]*)"|([^\s;&|<>(){}$`#'"@,]+))(?=[ \t]|$)/.exec(rest);
|
|
151
|
+
if (!match) return null;
|
|
152
|
+
args.push(match[1]?.replaceAll("''", "'") ?? match[2] ?? match[3]);
|
|
153
|
+
rest = rest.slice(match[0].length).replace(/^[ \t]+/, '');
|
|
154
|
+
}
|
|
155
|
+
return args.length ? args : null;
|
|
156
|
+
}
|
|
157
|
+
function sameInvocation(a, b) {
|
|
158
|
+
const x = codexInvocation(a), y = codexInvocation(b);
|
|
159
|
+
return x && y && samePath(x[0], y[0]) && isDeepStrictEqual(x.slice(1), y.slice(1));
|
|
160
|
+
}
|
|
161
|
+
function stockGroup(actual, expected, host) {
|
|
162
|
+
if (!expected || !actual || host !== 'codex') return isDeepStrictEqual(actual, expected);
|
|
163
|
+
const h = actual.hooks?.[0], target = expected.hooks[0];
|
|
164
|
+
if (!h || actual.hooks.length !== 1) return false;
|
|
165
|
+
const canonical = { ...h };
|
|
166
|
+
for (const key of ['command', 'commandWindows']) if (sameInvocation(h[key], target[key])) canonical[key] = target[key];
|
|
167
|
+
return isDeepStrictEqual({ ...actual, hooks: [canonical] }, expected);
|
|
168
|
+
}
|
|
169
|
+
function usesOldHook(config, host, legacyExe) {
|
|
170
|
+
for (const groups of Object.values(config.hooks ?? {})) for (const group of Array.isArray(groups) ? groups : []) {
|
|
171
|
+
for (const hook of group.hooks ?? []) {
|
|
172
|
+
if (host === 'claude-code') { if (samePath(hook.command, legacyExe)) return true; continue; }
|
|
173
|
+
const text = hook.commandWindows ?? hook.command;
|
|
174
|
+
const args = codexInvocation(text);
|
|
175
|
+
if (args && samePath(args[0], legacyExe)) return true;
|
|
176
|
+
// Compound expressions cannot be classified reliably. Don't retire a
|
|
177
|
+
// runtime mentioned by one; ordinary literal third-party arguments are fine.
|
|
178
|
+
if (!args && typeof text === 'string') {
|
|
179
|
+
const raw = windowsText(text.replaceAll("''", "'"));
|
|
180
|
+
if (raw.includes(windowsText(legacyExe)) || (samePath(oldLocalPath(), legacyExe) && raw.includes(windowsText(oldLocalExe)))) return true;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
async function mergeHooks(data, host, exe, file, previous, changed, choose) {
|
|
187
|
+
data.hooks ??= {};
|
|
188
|
+
object(data.hooks, `${file}: hooks`);
|
|
189
|
+
let dirty = false, backup = false;
|
|
190
|
+
for (const event of events) {
|
|
191
|
+
const groups = data.hooks[event] ?? [];
|
|
192
|
+
if (!Array.isArray(groups)) fail(`${file}: hooks.${event} must be an array`);
|
|
193
|
+
const group = hookGroup(host, exe, event);
|
|
194
|
+
const expected = [group, previous?.[event]].filter(Boolean);
|
|
195
|
+
const indexes = groups.flatMap((x, i) => x?.hooks?.some?.(h => expected.some(g => {
|
|
196
|
+
const handler = g.hooks[0];
|
|
197
|
+
return host === 'claude-code'
|
|
198
|
+
? samePath(h.command, handler.command) && isDeepStrictEqual(h.args, handler.args)
|
|
199
|
+
: sameInvocation(h.commandWindows ?? h.command, handler.commandWindows ?? handler.command);
|
|
200
|
+
})) ? [i] : []);
|
|
201
|
+
if (indexes.length > 1) fail(`${file}: multiple VC hooks for ${event}; reconcile them before updating`);
|
|
202
|
+
const index = indexes[0];
|
|
203
|
+
const old = groups[index];
|
|
204
|
+
if (isDeepStrictEqual(old, group)) {
|
|
205
|
+
if (previous?.[event]) changed[event] = group;
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
// Never replace a group that also contains another tool's hooks.
|
|
209
|
+
if (old?.hooks.length > 1) fail(`${file}: mixed hook group for ${event}; reconcile it before updating`);
|
|
210
|
+
if (old && !stockGroup(old, previous?.[event], host) && !stockGroup(old, group, host)) {
|
|
211
|
+
if (!await choose(host, `VC hook ${event}`, [file], true)) fail(`Hook conflict at ${file}; no update applied.`);
|
|
212
|
+
backup = true;
|
|
213
|
+
}
|
|
214
|
+
if (old) groups[index] = group;
|
|
215
|
+
else groups.push(group);
|
|
216
|
+
data.hooks[event] = groups;
|
|
217
|
+
changed[event] = group;
|
|
218
|
+
dirty = true;
|
|
219
|
+
}
|
|
220
|
+
return { dirty, backup };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export async function runtimeEdits(target, source, previous = {}, choose = chooseOverwrite, names = payload) {
|
|
224
|
+
const files = await Promise.all(names.map(async name => [name, await fs.readFile(path.join(source, name))]));
|
|
225
|
+
const [name, binary] = files[0];
|
|
226
|
+
if (binary.subarray(0, 2).toString() !== 'MZ' || files.some(([, data]) => !data.length)) fail(`Invalid bundled runtime: ${name}`);
|
|
227
|
+
const edits = [];
|
|
228
|
+
const records = {};
|
|
229
|
+
for (const relative of new Set([...names, ...Object.keys(previous)])) {
|
|
230
|
+
const file = path.join(target, relative);
|
|
231
|
+
const before = await optional(file);
|
|
232
|
+
const after = files.find(([name]) => name === relative)?.[1] ?? null;
|
|
233
|
+
const old = previous[relative];
|
|
234
|
+
const owned = old && old.reference !== true && typeof old !== 'string';
|
|
235
|
+
if (after === null && (!owned || !before || hash(before) !== old.sha256)) continue;
|
|
236
|
+
if (after !== null) records[relative] = { sha256: hash(after), reference: Boolean(!owned && matches(before, after)) };
|
|
237
|
+
if (matches(before, after)) continue;
|
|
238
|
+
const backup = Boolean(before && (!owned || hash(before) !== old.sha256));
|
|
239
|
+
if (backup && !await choose('VC', relative, [file], true)) fail(`Required runtime file not accepted: ${file}`);
|
|
240
|
+
edits.push({ file, before, after, backup });
|
|
241
|
+
}
|
|
242
|
+
return { edits, records };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function setup(harnesses, progress) {
|
|
246
|
+
if (process.platform !== 'win32' || process.arch !== 'x64') fail('This release supports Windows x64 only.');
|
|
247
|
+
if (!process.env.LOCALAPPDATA || !path.isAbsolute(process.env.LOCALAPPDATA)) fail('LOCALAPPDATA is not an absolute path.');
|
|
248
|
+
const pkg = JSON.parse(await fs.readFile(path.join(here, 'package.json'), 'utf8'));
|
|
249
|
+
if (/^\d{1,6}\.\d{1,6}\.\d{1,6}$/.test(pkg.version)) progress.version = pkg.version;
|
|
250
|
+
for (const host of harnesses) progress.events.push({ event: 'host_selected', outcome: 'ok', host });
|
|
251
|
+
for (const [host, variable] of [['claude-code', 'CLAUDE_CONFIG_DIR'], ['codex', 'CODEX_HOME']]) {
|
|
252
|
+
if (harnesses.includes(host) && process.env[variable] && !path.isAbsolute(process.env[variable])) fail(`${variable} must be an absolute path.`);
|
|
253
|
+
}
|
|
254
|
+
const base = path.join(process.env.LOCALAPPDATA, 'vc');
|
|
255
|
+
const target = path.join(base, 'runtime');
|
|
256
|
+
const exe = path.join(target, 'vc.exe');
|
|
257
|
+
const home = homedir();
|
|
258
|
+
await fs.mkdir(base, { recursive: true });
|
|
259
|
+
const lockPath = path.join(base, 'setup.lock');
|
|
260
|
+
let lock;
|
|
261
|
+
progress.stage = 'setup_lock';
|
|
262
|
+
try { lock = await fs.open(lockPath, 'wx'); } catch (err) {
|
|
263
|
+
if (err.code === 'EEXIST') fail(`Another VC setup is running or left a lock: ${lockPath}`);
|
|
264
|
+
throw err;
|
|
265
|
+
}
|
|
266
|
+
try {
|
|
267
|
+
// Run the host config commands outside the caller's repository.
|
|
268
|
+
const cwd = await fs.mkdtemp(path.join(process.env.LOCALAPPDATA, 'vc-setup-'));
|
|
269
|
+
try {
|
|
270
|
+
return await configure({ harnesses, base, target, exe, home, cwd, version: pkg.version, progress });
|
|
271
|
+
} finally {
|
|
272
|
+
await fs.rm(cwd, { recursive: true, force: true });
|
|
273
|
+
}
|
|
274
|
+
} finally {
|
|
275
|
+
await lock.close();
|
|
276
|
+
await fs.unlink(lockPath);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
async function planStageEntries(host, hostDir, edits, source = path.join(here, 'runtime')) {
|
|
281
|
+
for (const [stage, description] of Object.entries(stages)) {
|
|
282
|
+
const name = `vc-${stage}`;
|
|
283
|
+
const body = await fs.readFile(path.join(source, 'prompts', `${stage}.md`));
|
|
284
|
+
const claude = host === 'claude-code';
|
|
285
|
+
const file = claude ? path.join(hostDir, 'commands', `${name}.md`) : path.join(hostDir, 'skills', name, 'SKILL.md');
|
|
286
|
+
const after = claude ? body : Buffer.concat([Buffer.from(`---\nname: ${name}\ndescription: ${description}\n---\n\n`), body]);
|
|
287
|
+
const before = await optional(file);
|
|
288
|
+
edits.push({ name, file, before, after, host, stage: 'stage_entry_install' });
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
async function planControls(host, hostDir, home, exe, edits) {
|
|
293
|
+
const claude = host === 'claude-code';
|
|
294
|
+
for (const [name, description] of Object.entries({
|
|
295
|
+
'vc-pause': 'Show how to manually disable VC for this user.',
|
|
296
|
+
'vc-resume': 'Show how to manually enable VC for this user.',
|
|
297
|
+
})) {
|
|
298
|
+
const file = claude ? path.join(hostDir, 'commands', `${name}.md`) : path.join(home, '.agents', 'skills', name, 'SKILL.md');
|
|
299
|
+
const command = `& ${psQuote(exe)} ${name.slice(3)}`;
|
|
300
|
+
const body = `请只向用户展示以下命令,由用户在宿主外的 PowerShell 中手动运行。不要执行命令、调用工具或声称开关已经改变。\n\n\`\`\`powershell\n${command}\n\`\`\`\n`;
|
|
301
|
+
const header = claude ? `---\ndescription: ${description}\n---\n\n` : `---\nname: ${name}\ndescription: ${description} Use only when explicitly invoked by the user.\n---\n\n`;
|
|
302
|
+
edits.push({ name, file, before: await optional(file), after: Buffer.from(header + body), host, stage: claude ? 'stage_entry_install' : 'skill_install' });
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
const initOnly = "if (process.argv[2] !== 'init') {\n console.error('Usage: archive.mjs init <slug> <INT|SPEC|TCSET|PLAN>...');\n process.exit(1);\n}\n";
|
|
307
|
+
const archiveScript = (exe, transfer = false) => Buffer.from(`import { spawnSync } from 'node:child_process';\n${transfer ? initOnly : ''}const result = spawnSync(${JSON.stringify(exe)}, ['archive', ...process.argv.slice(2)], { stdio: 'inherit' });\nif (result.error) console.error(result.error.message);\nprocess.exitCode = result.status ?? 1;\n`);
|
|
308
|
+
|
|
309
|
+
// Use the same physical root for old fingerprints and new members of a bundled Skill.
|
|
310
|
+
async function bundledSkillDirs(host, hostDir, home) {
|
|
311
|
+
const discovered = await discoverEntries(host, hostDir, home);
|
|
312
|
+
const dirs = new Map();
|
|
313
|
+
for (const name of ['archive', 'vc-transfer', 'grilling', 'review']) {
|
|
314
|
+
const standard = path.join(hostDir, 'skills', name);
|
|
315
|
+
const candidates = discovered.filter(e => e.name === name);
|
|
316
|
+
const other = candidates.length === 1 && path.basename(candidates[0].file) === 'SKILL.md';
|
|
317
|
+
dirs.set(name, other && !(await listDirectory(standard)).length ? path.dirname(candidates[0].file) : standard);
|
|
318
|
+
}
|
|
319
|
+
return dirs;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
async function planSkills(host, exe, edits, runtime, dirs) {
|
|
323
|
+
const source = path.join(runtime, 'skills');
|
|
324
|
+
for (const relative of ['vc-transfer/SKILL.md', ...['INT', 'SPEC', 'TCSET', 'PLAN'].map(kind => `vc-transfer/templates/${kind}.md`), 'vc-transfer/archive.mjs', 'grilling/SKILL.md', 'review/SKILL.md', 'review/references/review-method.md']) {
|
|
325
|
+
const after = relative === 'vc-transfer/archive.mjs'
|
|
326
|
+
? archiveScript(exe, true)
|
|
327
|
+
: await fs.readFile(path.join(source, relative));
|
|
328
|
+
const [name, ...parts] = relative.split('/');
|
|
329
|
+
const file = path.join(dirs.get(name), ...parts);
|
|
330
|
+
edits.push({ name, file, before: await optional(file), after, host, stage: 'skill_install', bundledSkill: true });
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
async function listDirectory(dir) {
|
|
335
|
+
try { return await fs.readdir(dir, { withFileTypes: true }); }
|
|
336
|
+
catch (err) { if (err.code === 'ENOENT') return []; throw err; }
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
async function discoverEntries(host, hostDir, home) {
|
|
340
|
+
const found = [];
|
|
341
|
+
if (host === 'claude-code') {
|
|
342
|
+
const dir = path.join(hostDir, 'commands');
|
|
343
|
+
for (const item of await listDirectory(dir)) {
|
|
344
|
+
if (!item.isDirectory() && /\.md$/i.test(item.name)) found.push({ name: item.name.slice(0, -3).toLowerCase(), file: path.join(dir, item.name) });
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
const roots = [path.join(hostDir, 'skills')];
|
|
348
|
+
if (host === 'codex') roots.push(path.join(home, '.agents', 'skills'));
|
|
349
|
+
for (const root of roots) {
|
|
350
|
+
for (const item of await listDirectory(root)) {
|
|
351
|
+
if (!item.isDirectory() && !item.isSymbolicLink()) continue;
|
|
352
|
+
const file = path.join(root, item.name, 'SKILL.md');
|
|
353
|
+
const body = await optional(file);
|
|
354
|
+
if (!body) continue;
|
|
355
|
+
const header = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(body.toString('utf8'))?.[1];
|
|
356
|
+
const alias = /^name:\s*["']?([\w-]+)["']?\s*$/m.exec(header ?? '')?.[1];
|
|
357
|
+
for (const name of new Set([item.name.toLowerCase(), alias?.toLowerCase()].filter(Boolean))) found.push({ name, file });
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
return found;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
async function chooseOverwrite(host, name, files, core = false) {
|
|
364
|
+
console.error(`[${host}] ${name} — conflicting entry files:\n${files.map(file => ` ${file}`).join('\n')}`);
|
|
365
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) return false;
|
|
366
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
367
|
+
try { return /^(?:o|overwrite)$/i.test((await rl.question(core ? 'Back up and replace, or cancel setup? [o/C] ' : 'Back up and replace, or keep your version? [o/K] ')).trim()); }
|
|
368
|
+
finally { rl.close(); }
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// Decide for a whole skill at once, before any files or registrations are changed.
|
|
372
|
+
export async function resolveEntries(host, hostDir, home, entries, choose = chooseOverwrite, managed, decisions = {}) {
|
|
373
|
+
const existing = await discoverEntries(host, hostDir, home);
|
|
374
|
+
const result = [];
|
|
375
|
+
const prior = managed ?? new Map();
|
|
376
|
+
for (const [file, record] of prior) {
|
|
377
|
+
if (entries.some(e => samePath(e.file, file))) continue;
|
|
378
|
+
entries = [...entries, { ...record, file, before: await optional(file), after: null }];
|
|
379
|
+
}
|
|
380
|
+
const groups = new Map();
|
|
381
|
+
for (const e of entries) {
|
|
382
|
+
const agent = samePath(path.dirname(e.file), path.join(hostDir, 'agents'));
|
|
383
|
+
const key = `${agent ? 'agent' : 'entry'}:${e.name}`;
|
|
384
|
+
if (!groups.has(key)) groups.set(key, []);
|
|
385
|
+
groups.get(key).push(e);
|
|
386
|
+
}
|
|
387
|
+
for (const [key, group] of groups) {
|
|
388
|
+
const { name } = group[0];
|
|
389
|
+
// Retire the former official entry only as a whole. Any local change keeps
|
|
390
|
+
// the old entry and its dependencies, without blocking the renamed Skill.
|
|
391
|
+
if (key === 'entry:archive' && group.every(e => e.after === null)) {
|
|
392
|
+
if (group.every(e => e.before && hash(e.before) === prior.get(e.file).sha256)) result.push(...group);
|
|
393
|
+
continue;
|
|
394
|
+
}
|
|
395
|
+
if (!group.some(e => e.core) && decisions.version && decisions.previous?.[key] === decisions.version) {
|
|
396
|
+
decisions.kept[key] = decisions.version;
|
|
397
|
+
continue;
|
|
398
|
+
}
|
|
399
|
+
// Reused members participate in whole-skill decisions, never in removal.
|
|
400
|
+
const changed = group.filter(e => !matches(e.before, e.after) && !(e.after === null && prior.get(e.file)?.reference));
|
|
401
|
+
const alternate = !key.startsWith('agent:') && group.some(e => e.after !== null) ? [...new Set(existing.filter(e => e.name === name && !group.some(g => samePath(g.file, e.file))).map(e => e.file))] : [];
|
|
402
|
+
const core = managed && group.some(e => e.core);
|
|
403
|
+
const bundledSkill = group.some(e => e.bundledSkill);
|
|
404
|
+
const freshLocal = bundledSkill && !group.some(e => prior.has(e.file)) && group.some(e => e.before !== null);
|
|
405
|
+
const officialBaseline = bundledSkill && group.filter(e => prior.has(e.file)).every(e => e.before && hash(e.before) === prior.get(e.file).sha256);
|
|
406
|
+
const recordOfficial = () => {
|
|
407
|
+
if (bundledSkill) for (const e of group) if (e.after !== null) decisions.official?.add(e.file);
|
|
408
|
+
};
|
|
409
|
+
const upstreamChanged = changed.some(e => !prior.has(e.file) || e.after === null || hash(e.after) !== prior.get(e.file).sha256);
|
|
410
|
+
// A missing shipped member of a reused legacy copy must be offered as a
|
|
411
|
+
// group choice even when the two releases shipped identical bytes.
|
|
412
|
+
const actualDir = decisions.legacySkillDirs?.get(name);
|
|
413
|
+
const missingLegacyMember = actualDir && !samePath(actualDir, path.join(hostDir, 'skills', name)) &&
|
|
414
|
+
changed.some(e => e.after && !e.before && prior.get(e.file)?.missing);
|
|
415
|
+
if (managed && !core && !upstreamChanged && !alternate.length && !missingLegacyMember) {
|
|
416
|
+
if (!changed.length && group.every(e => matches(e.before, e.after))) recordOfficial();
|
|
417
|
+
continue;
|
|
418
|
+
}
|
|
419
|
+
// Reuse a single identical skill in an alternative discovery root, including
|
|
420
|
+
// its resources. Do not create a duplicate at the canonical target.
|
|
421
|
+
const entry = group.find(e => path.basename(e.file) === 'SKILL.md');
|
|
422
|
+
if (!core && entry?.after && group.every(e => e.before === null && e.after) && alternate.length === 1 && path.basename(alternate[0]) === 'SKILL.md') {
|
|
423
|
+
const dir = path.dirname(alternate[0]);
|
|
424
|
+
const matches = await Promise.all(group.map(async e => (await optional(path.join(dir, path.relative(path.dirname(entry.file), e.file))))?.equals(e.after)));
|
|
425
|
+
if (matches.every(Boolean)) continue;
|
|
426
|
+
}
|
|
427
|
+
const conflicts = [...(managed ? group : changed).filter(e => {
|
|
428
|
+
if (matches(e.before, e.after)) return false;
|
|
429
|
+
const old = prior.get(e.file);
|
|
430
|
+
if (freshLocal) return true; // An existing Skill missing a packaged member is not the official group.
|
|
431
|
+
if (officialBaseline && old) return false;
|
|
432
|
+
if (old?.missing && !e.before) return true;
|
|
433
|
+
return old && !old.reference ? !e.before || hash(e.before) !== old.sha256 : e.before !== null;
|
|
434
|
+
}).map(e => e.file), ...alternate];
|
|
435
|
+
if (conflicts.length && !await choose(host, name, conflicts, core)) {
|
|
436
|
+
if (core) fail(`Required resource ${host}/${name} was not accepted; no update applied.`);
|
|
437
|
+
if (decisions.kept) decisions.kept[key] = decisions.version;
|
|
438
|
+
console.log(`Skipped [${host}] ${name}; existing entry retained.`);
|
|
439
|
+
continue;
|
|
440
|
+
}
|
|
441
|
+
recordOfficial();
|
|
442
|
+
result.push(...changed.map(e => conflicts.includes(e.file) && e.before ? { ...e, backup: true } : e));
|
|
443
|
+
for (const file of alternate) {
|
|
444
|
+
if (entries.some(e => samePath(e.file, file)) || result.some(e => e.retire && samePath(e.file, file))) fail(`Ambiguous entry name at ${file}; reconcile it before overwriting.`);
|
|
445
|
+
result.push({ file, before: await fs.readFile(file), retire: true, host, stage: group[0].stage });
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
return result;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
async function planAgents(host, hostDir, expected, runtime) {
|
|
452
|
+
const claude = host === 'claude-code';
|
|
453
|
+
const folder = path.join(hostDir, 'agents');
|
|
454
|
+
const extension = claude ? '.md' : '.toml';
|
|
455
|
+
const installed = await fs.readdir(folder).catch(error => { if (error.code === 'ENOENT') return []; throw error; });
|
|
456
|
+
for (const name of ['advisor', 'reviewer', 'verifier']) {
|
|
457
|
+
const text = await fs.readFile(path.join(runtime, 'agents', `${name}.md`), 'utf8');
|
|
458
|
+
const parsed = /^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]+)$/.exec(text);
|
|
459
|
+
const description = parsed?.[1].match(/^description: (.+)$/m)?.[1].trim();
|
|
460
|
+
const declared = parsed?.[1].match(/^name: (.+)$/m)?.[1].trim();
|
|
461
|
+
if (!description || declared?.toLowerCase() !== name || !parsed[2].trim()) fail(`Invalid bundled agent: ${name}`);
|
|
462
|
+
const body = parsed[2].trim();
|
|
463
|
+
for (const entry of installed) {
|
|
464
|
+
if (entry.toLowerCase() === `${name}${extension}` || !entry.endsWith(extension)) continue;
|
|
465
|
+
const other = await fs.readFile(path.join(folder, entry), 'utf8');
|
|
466
|
+
const header = claude ? /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(other)?.[1] ?? '' : other.split(/^\s*\[/m, 1)[0];
|
|
467
|
+
const match = (claude ? /^\s*name\s*:\s*["']?([\w-]+)/m : /^\s*name\s*=\s*["']([\w-]+)/m).exec(header);
|
|
468
|
+
if (match?.[1].toLowerCase() === name) fail(`Existing agent named ${name} at ${path.join(folder, entry)}; reconcile it before setup.`);
|
|
469
|
+
}
|
|
470
|
+
const after = claude
|
|
471
|
+
? `---\nname: ${name}\ndescription: ${JSON.stringify(description)}\ntools: Read, Grep, Glob\n---\n\n${body}\n`
|
|
472
|
+
: `name = ${JSON.stringify(name)}\ndescription = ${JSON.stringify(description)}\nsandbox_mode = "read-only"\ndeveloper_instructions = ${JSON.stringify(body)}\n`;
|
|
473
|
+
const file = path.join(folder, `${name}${extension}`);
|
|
474
|
+
const bytes = Buffer.from(after);
|
|
475
|
+
expected.push({ name, file, before: await optional(file), after: bytes, host, stage: 'agent_install' });
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
export async function planDoctor({ host, hostDir, target, exe, trustFile, hooksPath, args, entries, agents, runtime, version = path.basename(target) }) {
|
|
480
|
+
const claude = host === 'claude-code';
|
|
481
|
+
const name = 'vc-doctor';
|
|
482
|
+
const scope = createHash('sha256').update(JSON.stringify([hostDir, trustFile])).digest('hex').slice(0, 16);
|
|
483
|
+
const manifest = path.join(target, `doctor-${host}-${scope}.json`);
|
|
484
|
+
const binding = { version, installDir: target, host, manifest };
|
|
485
|
+
const file = claude ? path.join(hostDir, 'commands', `${name}.md`) : path.join(hostDir, 'skills', name, 'SKILL.md');
|
|
486
|
+
const header = claude ? '' : `name: ${name}\n`;
|
|
487
|
+
const body = await fs.readFile(path.join(runtime, 'prompts', 'doctor.md'), 'utf8');
|
|
488
|
+
const after = Buffer.from(`---\n${header}description: 只读检查本版本的 VC 安装和当前宿主配置,仅在用户显式调用时运行。\n---\n\n本入口的安装绑定:\n\n\`\`\`json\n${JSON.stringify(binding, null, 2)}\n\`\`\`\n\n${body}`);
|
|
489
|
+
const entry = { name, file, before: await optional(file), after, host, stage: claude ? 'stage_entry_install' : 'skill_install' };
|
|
490
|
+
const runtimeFiles = await Promise.all(payload.map(async relative => ({ file: path.join(target, relative), after: await fs.readFile(path.join(runtime, relative)) })));
|
|
491
|
+
const data = {
|
|
492
|
+
version, installDir: target, host, hostDir,
|
|
493
|
+
names: { entries: [...new Set([...entries.map(e => e.name), name])], agents: agents.map(e => e.name) },
|
|
494
|
+
files: [...runtimeFiles, ...entries, ...agents, entry].map(e => ({ path: e.file, sha256: createHash('sha256').update(e.after).digest('hex') })),
|
|
495
|
+
mcp: { file: trustFile, command: exe, args },
|
|
496
|
+
hooks: { file: hooksPath, groups: Object.fromEntries(events.map(event => [event, hookGroup(host, exe, event)])) },
|
|
497
|
+
};
|
|
498
|
+
return { entry, manifest, bytes: Buffer.from(`${JSON.stringify(data, null, 2)}\n`) };
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
function hostPaths(host, home) {
|
|
502
|
+
const claude = host === 'claude-code';
|
|
503
|
+
const override = process.env[claude ? 'CLAUDE_CONFIG_DIR' : 'CODEX_HOME'];
|
|
504
|
+
if (override && !path.isAbsolute(override)) fail(`Expected an absolute config directory for ${host}`);
|
|
505
|
+
const hostDir = override || path.join(home, claude ? '.claude' : '.codex');
|
|
506
|
+
return { hostDir, hooksPath: path.join(hostDir, claude ? 'settings.json' : 'hooks.json'),
|
|
507
|
+
trustFile: claude ? path.join(override || home, '.claude.json') : path.join(hostDir, 'config.toml') };
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
async function confirmUpdate(question) {
|
|
511
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) fail('Run setup in an interactive terminal to confirm this update.');
|
|
512
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
513
|
+
try { return /^(y|yes)$/i.test((await rl.question(`${question} [y/N] `)).trim()); }
|
|
514
|
+
finally { rl.close(); }
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
async function bundleFingerprint(dir) {
|
|
518
|
+
const files = [];
|
|
519
|
+
for (const item of (await fs.readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name, 'en'))) {
|
|
520
|
+
const file = path.join(dir, item.name);
|
|
521
|
+
files.push([item.name, item.isDirectory() ? await bundleFingerprint(file) : hash(await fs.readFile(file))]);
|
|
522
|
+
}
|
|
523
|
+
return hash(JSON.stringify(files));
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
const hookRecords = (host, exe) => Object.fromEntries(events.map(event => [event, hookGroup(host, exe, event)]));
|
|
527
|
+
const mcpArgs = (host, file) => ['mcp', '--stdio', '--harness', host, '--installed', file];
|
|
528
|
+
const mcpValue = (exe, args) => ({ type: 'stdio', command: exe, args });
|
|
529
|
+
|
|
530
|
+
function readCodex(cwd, dir, command) {
|
|
531
|
+
const get = command('codex', ['mcp', 'get', '--json', 'vc'], cwd, dir);
|
|
532
|
+
if (get.result === 0) return JSON.parse(get.out);
|
|
533
|
+
if (/No MCP server named 'vc' found\./.test(get.error)) return null;
|
|
534
|
+
fail(`Cannot inspect Codex MCP configuration: ${get.error}`);
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
async function inspectMcp(host, file, cwd, command) {
|
|
538
|
+
if (host === 'claude-code') {
|
|
539
|
+
const config = await jsonFile(file);
|
|
540
|
+
const servers = object(config.data.mcpServers ?? {}, `${file}: mcpServers`);
|
|
541
|
+
return { ...config, servers, value: servers.vc };
|
|
542
|
+
}
|
|
543
|
+
const before = await optional(file);
|
|
544
|
+
const dir = await fs.mkdtemp(path.join(cwd, 'codex-'));
|
|
545
|
+
if (before) await fs.writeFile(path.join(dir, 'config.toml'), before);
|
|
546
|
+
const server = before ? readCodex(cwd, dir, command) : null;
|
|
547
|
+
return { file, before, dir, server, value: server?.transport };
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
function isMcp(info, exe, args) {
|
|
551
|
+
return info.value?.type === 'stdio' && samePath(info.value.command, exe) && isDeepStrictEqual(info.value.args, args);
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
function isStockMcp(info, exe, args) {
|
|
555
|
+
if (!isMcp(info, exe, args)) return false;
|
|
556
|
+
if (!info.server) return isDeepStrictEqual(info.value, mcpValue(exe, args));
|
|
557
|
+
const { transport, ...server } = info.server;
|
|
558
|
+
return server.enabled === true && Object.entries(server).every(([k, v]) => ['name', 'enabled'].includes(k) || v == null) &&
|
|
559
|
+
Object.entries(transport).every(([k, v]) => ['type', 'command', 'args'].includes(k) || v == null || (Array.isArray(v) && !v.length));
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
async function mcpEdit(host, info, exe, args, cwd, command, backup = false) {
|
|
563
|
+
if (host === 'claude-code') return { ...jsonEdit(info.file, info.before, { ...info.data, mcpServers: { ...info.servers, vc: mcpValue(exe, args) } }), backup };
|
|
564
|
+
const added = command('codex', ['mcp', 'add', 'vc', '--', exe, ...args], cwd, info.dir);
|
|
565
|
+
if (added.result !== 0) fail(`Codex MCP registration failed: ${added.error}`);
|
|
566
|
+
const server = readCodex(cwd, info.dir, command);
|
|
567
|
+
if (!isStockMcp({ server, value: server?.transport }, exe, args)) fail('Codex generated an unexpected MCP registration');
|
|
568
|
+
return { file: info.file, before: info.before, after: await fs.readFile(path.join(info.dir, 'config.toml')), backup };
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
async function legacyFiles(host, hostDir, home, exe, baseline, dirs) {
|
|
572
|
+
const records = new Map();
|
|
573
|
+
const entries = [];
|
|
574
|
+
await planControls(host, hostDir, home, exe, entries);
|
|
575
|
+
entries.push({ file: path.join(dirs.get('archive'), 'archive.mjs'), name: 'archive', after: archiveScript(exe) });
|
|
576
|
+
for (const [relative, sha256] of Object.entries({ ...baseline.common, ...baseline[host] })) {
|
|
577
|
+
const [folder, name, ...members] = relative.split('/');
|
|
578
|
+
const file = folder === 'skills' && dirs.has(name) ? path.join(dirs.get(name), ...members) : path.join(hostDir, relative);
|
|
579
|
+
records.set(file, { name: folder === 'skills' ? name : path.parse(name).name, sha256 });
|
|
580
|
+
}
|
|
581
|
+
for (const e of entries) records.set(e.file, { name: e.name, sha256: hash(e.after) });
|
|
582
|
+
// Modified files remain unowned; keep their old official fingerprints only
|
|
583
|
+
// as a comparison baseline, not as permission to delete them later.
|
|
584
|
+
for (const [file, record] of records) {
|
|
585
|
+
const before = await optional(file);
|
|
586
|
+
record.reference = !before || hash(before) !== record.sha256;
|
|
587
|
+
if (!before) record.missing = true;
|
|
588
|
+
record.core = coreEntry(record.name, file);
|
|
589
|
+
}
|
|
590
|
+
return records;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
function coreEntry(name, file) {
|
|
594
|
+
if (name === 'vc-transfer') return false;
|
|
595
|
+
return name.startsWith('vc-') || (name === 'archive' && path.basename(file) === 'archive.mjs');
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
export async function configure({ harnesses, base, target, exe, home, cwd, version, progress,
|
|
599
|
+
runtime = path.join(here, 'runtime'), command = hostCommand, checkVersion = cliVersion,
|
|
600
|
+
confirm = confirmUpdate, choose = chooseOverwrite, write = apply, baseline: suppliedBaseline }) {
|
|
601
|
+
const manifestFile = path.join(base, 'install-manifest.json');
|
|
602
|
+
const manifest = await jsonFile(manifestFile);
|
|
603
|
+
const previous = manifest.before ? manifest.data : null;
|
|
604
|
+
if (previous && (previous.schema !== 1 || !previous.version || !previous.hosts || !previous.runtime)) fail(`Unsupported install manifest: ${manifestFile}`);
|
|
605
|
+
if (previous && version.localeCompare(previous.version, 'en', { numeric: true }) < 0) fail(`VC ${previous.version} is already installed; downgrades are not supported.`);
|
|
606
|
+
const legacyDir = path.join(base, 'versions', '0.1.0');
|
|
607
|
+
const legacyExe = path.join(legacyDir, 'vc.exe');
|
|
608
|
+
const legacyPresent = !previous && Boolean(await optional(legacyExe));
|
|
609
|
+
const baseline = legacyPresent ? suppliedBaseline ?? JSON.parse(await fs.readFile(path.join(here, 'legacy-0.1.0.json'), 'utf8')) : null;
|
|
610
|
+
const active = new Map();
|
|
611
|
+
for (const host of supported) {
|
|
612
|
+
const old = previous?.hosts[host];
|
|
613
|
+
if (!old && !legacyPresent && !harnesses.includes(host)) continue;
|
|
614
|
+
const paths = old ?? hostPaths(host, home);
|
|
615
|
+
if (old && harnesses.includes(host) && !samePath(old.hostDir, hostPaths(host, home).hostDir)) fail(`${host} is already managed at ${old.hostDir}; use that configuration root.`);
|
|
616
|
+
const config = await jsonFile(paths.hooksPath);
|
|
617
|
+
const info = await inspectMcp(host, paths.trustFile, cwd, command);
|
|
618
|
+
const args = mcpArgs(host, paths.trustFile);
|
|
619
|
+
const stockHooks = hookRecords(host, legacyExe);
|
|
620
|
+
// A customized registration can still be using the old runtime. Detect
|
|
621
|
+
// the binding first; exact matching is only for automatic replacement.
|
|
622
|
+
const legacy = legacyPresent && (samePath(info.value?.command, legacyExe) ||
|
|
623
|
+
usesOldHook(config.data, host, legacyExe));
|
|
624
|
+
if (old || legacy || harnesses.includes(host)) active.set(host, { ...paths, old, legacy, config, info, args, stockHooks, skillDirs: await bundledSkillDirs(host, paths.hostDir, home) });
|
|
625
|
+
}
|
|
626
|
+
const adoption = new Map();
|
|
627
|
+
const cleanup = [];
|
|
628
|
+
let keepLegacyRuntime = false;
|
|
629
|
+
if (legacyPresent) {
|
|
630
|
+
for (const [host, data] of active) if (data.legacy) adoption.set(host, await legacyFiles(host, data.hostDir, home, legacyExe, baseline, data.skillDirs));
|
|
631
|
+
if (!adoption.size) fail(`Found ${legacyDir}, but no old VC installation at the current host roots. Use the original CLAUDE_CONFIG_DIR or CODEX_HOME first.`);
|
|
632
|
+
for (const [relative, digest] of Object.entries(baseline.runtime)) {
|
|
633
|
+
const file = path.join(legacyDir, relative);
|
|
634
|
+
const before = await optional(file);
|
|
635
|
+
if (before && hash(before) !== digest) fail(`Old runtime differs from the published 0.1.0 at ${file}; resolve it before migrating.`);
|
|
636
|
+
if (before) cleanup.push({ file, before, after: null });
|
|
637
|
+
}
|
|
638
|
+
console.log('Legacy 0.1.0 resources matching the published baseline (not previously tracked).');
|
|
639
|
+
console.log('Check that the list includes all old VC hosts. If an old host used another configuration root, cancel and set its original config directory before continuing.');
|
|
640
|
+
for (const [host, records] of adoption) {
|
|
641
|
+
const { hooksPath, trustFile } = active.get(host);
|
|
642
|
+
console.log(` ${host}: ${hooksPath} (VC hooks), ${trustFile} (vc MCP)`);
|
|
643
|
+
for (const [file, record] of records) if (!record.reference) console.log(` ${file}`);
|
|
644
|
+
}
|
|
645
|
+
if (!await confirm('Allow VC to manage these legacy resources?')) return false;
|
|
646
|
+
}
|
|
647
|
+
const bundle = await bundleFingerprint(runtime);
|
|
648
|
+
if (previous?.version === version && previous.bundle !== bundle) fail(`Assets for ${version} differ from the installed release; increment the package version.`);
|
|
649
|
+
const nextRuntime = await runtimeEdits(target, runtime, previous?.runtime, choose);
|
|
650
|
+
const edits = [...nextRuntime.edits];
|
|
651
|
+
const hosts = {};
|
|
652
|
+
for (const [host, data] of active) {
|
|
653
|
+
progress.host = host;
|
|
654
|
+
progress.stage = 'host_version_check';
|
|
655
|
+
checkVersion(host, cwd, progress);
|
|
656
|
+
const { hostDir, hooksPath, trustFile, args, old, legacy, config, info, stockHooks } = data;
|
|
657
|
+
const entries = [], agents = [];
|
|
658
|
+
await planStageEntries(host, hostDir, entries, runtime);
|
|
659
|
+
await planSkills(host, exe, entries, runtime, data.skillDirs);
|
|
660
|
+
await planControls(host, hostDir, home, exe, entries);
|
|
661
|
+
await planAgents(host, hostDir, agents, runtime);
|
|
662
|
+
const doctor = await planDoctor({ host, hostDir, target, exe, trustFile, hooksPath, args, entries, agents, runtime, version });
|
|
663
|
+
const entriesAndAgents = [...entries, ...agents, doctor.entry];
|
|
664
|
+
const managed = adoption.get(host) ?? new Map((old?.files ?? []).map(({ file, ...record }) => [file, record]));
|
|
665
|
+
for (const e of entriesAndAgents) e.core = coreEntry(e.name, e.file);
|
|
666
|
+
const kept = {}, official = new Set();
|
|
667
|
+
const planned = await resolveEntries(host, hostDir, home, entriesAndAgents, choose, managed, {
|
|
668
|
+
version, previous: old?.kept, kept, official, legacySkillDirs: legacy ? data.skillDirs : undefined,
|
|
669
|
+
});
|
|
670
|
+
if (legacy) {
|
|
671
|
+
const oldLauncher = path.join(data.skillDirs.get('archive'), 'archive.mjs');
|
|
672
|
+
const contents = await optional(oldLauncher);
|
|
673
|
+
if (contents?.includes(Buffer.from(JSON.stringify(legacyExe))) && !planned.some(p => samePath(p.file, oldLauncher))) {
|
|
674
|
+
keepLegacyRuntime = true;
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
// Do not remove the legacy executable while a retained VC entry still calls it.
|
|
678
|
+
if (legacy) for (const e of entriesAndAgents) {
|
|
679
|
+
if (e.before && !planned.some(p => samePath(p.file, e.file)) &&
|
|
680
|
+
[legacyExe, JSON.stringify(legacyExe).slice(1, -1)].some(s => e.before.toString().toLowerCase().includes(s.toLowerCase()))) {
|
|
681
|
+
fail(`Retained entry still references the old runtime: ${e.file}`);
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
const files = new Map([...managed].filter(([file, record]) => {
|
|
685
|
+
// A retained legacy archive is no longer managed as part of this install.
|
|
686
|
+
if (record.name === 'archive' && !entriesAndAgents.some(e => e.name === 'archive')) return false;
|
|
687
|
+
const key = `${samePath(path.dirname(file), path.join(hostDir, 'agents')) ? 'agent' : 'entry'}:${record.name}`;
|
|
688
|
+
return kept[key] || !record.reference || entriesAndAgents.some(e => samePath(e.file, file));
|
|
689
|
+
}));
|
|
690
|
+
// A kept Skill keeps its bytes, not ownership. Remember the entire offered
|
|
691
|
+
// version (including locally missing members) for the next group comparison.
|
|
692
|
+
for (const e of entriesAndAgents) {
|
|
693
|
+
if (official.has(e.file)) {
|
|
694
|
+
files.set(e.file, { name: e.name, sha256: hash(e.after), core: e.core });
|
|
695
|
+
} else if (e.bundledSkill && kept[`entry:${e.name}`]) {
|
|
696
|
+
files.set(e.file, { name: e.name, sha256: hash(e.after), core: e.core, reference: true, ...(!e.before && { missing: true }) });
|
|
697
|
+
} else if (!files.has(e.file) && !planned.some(p => samePath(p.file, e.file))) {
|
|
698
|
+
files.set(e.file, { name: e.name, sha256: hash(e.after), core: e.core, reference: true });
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
for (const e of planned) {
|
|
702
|
+
if (e.retire || e.after === null) files.delete(e.file);
|
|
703
|
+
else files.set(e.file, { name: e.name, sha256: hash(e.after), core: e.core });
|
|
704
|
+
}
|
|
705
|
+
edits.push(...planned);
|
|
706
|
+
const doctorBefore = await optional(doctor.manifest);
|
|
707
|
+
const doctorOwned = old?.doctor?.reference === false;
|
|
708
|
+
const doctorRecord = { sha256: hash(doctor.bytes), reference: !doctorOwned && matches(doctorBefore, doctor.bytes) };
|
|
709
|
+
if (!matches(doctorBefore, doctor.bytes)) {
|
|
710
|
+
const backup = Boolean(doctorBefore && (!doctorOwned || hash(doctorBefore) !== old.doctor.sha256));
|
|
711
|
+
if (backup && !await choose(host, 'doctor manifest', [doctor.manifest], true)) fail(`Required doctor manifest not accepted: ${doctor.manifest}`);
|
|
712
|
+
edits.push({ file: doctor.manifest, before: doctorBefore, after: doctor.bytes, host, stage: 'stage_entry_install', backup });
|
|
713
|
+
}
|
|
714
|
+
const hooks = {};
|
|
715
|
+
const hookEdit = await mergeHooks(config.data, host, exe, hooksPath, legacy ? stockHooks : old?.hooks, hooks, choose);
|
|
716
|
+
if (legacy && usesOldHook(config.data, host, legacyExe)) fail(`Unresolved hook referencing the old runtime in ${hooksPath}; no update or cleanup applied.`);
|
|
717
|
+
if (hookEdit.dirty) edits.push({ ...jsonEdit(hooksPath, config.before, config.data), host, stage: 'hook_registration', backup: hookEdit.backup });
|
|
718
|
+
let mcp = old?.mcp ?? false;
|
|
719
|
+
if (!isStockMcp(info, exe, args)) {
|
|
720
|
+
const officialLegacy = legacy && isStockMcp(info, legacyExe, args);
|
|
721
|
+
const conflict = Boolean(info.value || info.server) && !officialLegacy;
|
|
722
|
+
if (conflict && !await choose(host, 'vc MCP', [trustFile], true)) fail(`MCP conflict at ${trustFile}; no update applied.`);
|
|
723
|
+
progress.stage = 'mcp_registration';
|
|
724
|
+
try { edits.push({ ...await mcpEdit(host, info, exe, args, cwd, command, conflict), host, stage: progress.stage }); }
|
|
725
|
+
catch (error) {
|
|
726
|
+
progress.events.push({ host, event: progress.stage, outcome: 'failed' });
|
|
727
|
+
throw error;
|
|
728
|
+
}
|
|
729
|
+
mcp = true;
|
|
730
|
+
}
|
|
731
|
+
hosts[host] = { hostDir, hooksPath, trustFile, hooks, mcp, kept, doctor: doctorRecord, files: [...files].map(([file, record]) => ({ file, ...record })) };
|
|
732
|
+
}
|
|
733
|
+
const next = jsonEdit(manifestFile, manifest.before, { schema: 1, version, bundle, runtime: nextRuntime.records, hosts });
|
|
734
|
+
if (!keepLegacyRuntime) edits.push(...cleanup);
|
|
735
|
+
else console.log(`Keeping ${legacyDir}: a retained archive Skill still uses it.`);
|
|
736
|
+
if (!matches(next.before, next.after)) edits.push(next);
|
|
737
|
+
const from = previous?.version ?? (legacyPresent ? '0.1.0' : null);
|
|
738
|
+
if (!edits.length) { console.log(`VC ${version} is already up to date.`); return true; }
|
|
739
|
+
if (legacyPresent || (from && from !== version)) {
|
|
740
|
+
console.log(`VC ${from} -> ${version}; hosts: ${[...active.keys()].join(', ')}`);
|
|
741
|
+
for (const e of edits) console.log(` ${e.after === null || e.retire ? 'Remove' : e.before ? 'Update' : 'Add'}${e.backup ? ' (back up first)' : ''}: ${e.file}`);
|
|
742
|
+
if (!await confirm('Apply this update to all listed hosts?')) return false;
|
|
743
|
+
}
|
|
744
|
+
progress.host = undefined;
|
|
745
|
+
progress.stage = 'runtime_copy';
|
|
746
|
+
const registration = stage => stage === 'hook_registration' || stage === 'mcp_registration';
|
|
747
|
+
try {
|
|
748
|
+
await commitUpdate(edits, write, undefined, edit => {
|
|
749
|
+
progress.host = edit.host;
|
|
750
|
+
progress.stage = edit.stage ?? 'runtime_copy';
|
|
751
|
+
});
|
|
752
|
+
} catch (error) {
|
|
753
|
+
if (registration(progress.stage)) progress.events.push({ host: progress.host, event: progress.stage, outcome: 'failed' });
|
|
754
|
+
throw error;
|
|
755
|
+
}
|
|
756
|
+
for (const { host, stage } of edits) if (registration(stage)) progress.events.push({ host, event: stage, outcome: 'ok' });
|
|
757
|
+
if (!keepLegacyRuntime) for (const { file } of cleanup) await removeEmptyParents(file, base);
|
|
758
|
+
console.log(`VC ${version}: ${[...active.keys()].join(', ')}. Runtime: ${target}`);
|
|
759
|
+
if (active.has('codex')) console.log('Codex: review VC hooks with /hooks.');
|
|
760
|
+
return true;
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
export async function main(argv, terminal = process) {
|
|
764
|
+
const usage = 'Usage: npx @essrj/vc-workflow [setup] [--harness claude-code,codex]';
|
|
765
|
+
if (argv[0] === '--help' || argv[0] === '-h') {
|
|
766
|
+
console.log(usage);
|
|
767
|
+
return;
|
|
768
|
+
}
|
|
769
|
+
const args = argv[0] === 'setup' ? argv.slice(1) : argv;
|
|
770
|
+
if (args.length && (args.length !== 2 || args[0] !== '--harness')) fail(usage);
|
|
771
|
+
let selected = args[1]?.split(',').map(x => x.trim());
|
|
772
|
+
if (!selected) {
|
|
773
|
+
const local = process.env.LOCALAPPDATA;
|
|
774
|
+
const base = terminal === process && path.isAbsolute(local ?? '') ? path.join(local, 'vc') : null;
|
|
775
|
+
const installed = base && (await optional(path.join(base, 'install-manifest.json')) ||
|
|
776
|
+
await optional(path.join(base, 'versions', '0.1.0', 'vc.exe')));
|
|
777
|
+
if (installed) selected = []; // Update existing hosts, without requiring a new selection.
|
|
778
|
+
else {
|
|
779
|
+
selected = await chooseHarnesses(terminal);
|
|
780
|
+
if (selected.length === 0) return;
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
if (selected.some(x => !supported.includes(x))) fail(`Select one or more of: ${supported.join(', ')}`);
|
|
784
|
+
const progress = { stage: 'preflight', events: [] };
|
|
785
|
+
try {
|
|
786
|
+
if (await setup([...new Set(selected)], progress)) progress.events.push({ event: 'setup_finish', outcome: 'ok' });
|
|
787
|
+
} catch (err) {
|
|
788
|
+
progress.events.push({ event: 'setup_finish', outcome: 'failed', host: progress.host, reason: progress.stage });
|
|
789
|
+
throw err;
|
|
790
|
+
} finally {
|
|
791
|
+
writeSetupLog(progress);
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
export function chooseHarnesses({ stdin, stdout }) {
|
|
796
|
+
if (!stdin.isTTY || !stdout.isTTY) fail('Use --harness claude-code,codex for noninteractive setup.');
|
|
797
|
+
const labels = ['Claude Code', 'Codex'];
|
|
798
|
+
const selected = new Set();
|
|
799
|
+
let cursor = 0;
|
|
800
|
+
let drawnRows = 0;
|
|
801
|
+
const draw = () => {
|
|
802
|
+
// Keep the redraw region ASCII so each character occupies one terminal column.
|
|
803
|
+
const lines = labels.map((label, i) => `${i === cursor ? '>' : ' '} [${selected.has(i) ? 'x' : ' '}] ${label}`);
|
|
804
|
+
lines.push(selected.size ? ` ${selected.size} selected - Enter to install` : ' Select at least one host to continue.');
|
|
805
|
+
const columns = stdout.columns || Infinity;
|
|
806
|
+
drawnRows = lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(line.length / columns)), 0);
|
|
807
|
+
stdout.write(lines.join('\n') + '\n');
|
|
808
|
+
};
|
|
809
|
+
stdout.write('VC Setup — Select hosts\n ↑/↓ Move · Space Toggle · Enter Install · Esc Cancel\n');
|
|
810
|
+
draw();
|
|
811
|
+
emitKeypressEvents(stdin);
|
|
812
|
+
const wasRaw = stdin.isRaw;
|
|
813
|
+
stdin.setRawMode(true);
|
|
814
|
+
stdin.resume();
|
|
815
|
+
return new Promise(resolve => {
|
|
816
|
+
const finish = (result) => {
|
|
817
|
+
stdin.off('keypress', onKey);
|
|
818
|
+
stdin.setRawMode(wasRaw);
|
|
819
|
+
stdin.pause();
|
|
820
|
+
resolve(result);
|
|
821
|
+
};
|
|
822
|
+
const onKey = (_, key) => {
|
|
823
|
+
if (!key) return;
|
|
824
|
+
if (key.name === 'escape' || (key.ctrl && key.name === 'c')) return finish([]);
|
|
825
|
+
if (key.name === 'return' && selected.size) return finish(supported.filter((_, i) => selected.has(i)));
|
|
826
|
+
if (key.name === 'up') cursor = (cursor + labels.length - 1) % labels.length;
|
|
827
|
+
else if (key.name === 'down') cursor = (cursor + 1) % labels.length;
|
|
828
|
+
else if (key.name === 'space') selected.has(cursor) ? selected.delete(cursor) : selected.add(cursor);
|
|
829
|
+
else return;
|
|
830
|
+
stdout.moveCursor(0, -drawnRows);
|
|
831
|
+
stdout.cursorTo(0);
|
|
832
|
+
stdout.clearScreenDown();
|
|
833
|
+
draw();
|
|
834
|
+
};
|
|
835
|
+
stdin.on('keypress', onKey);
|
|
836
|
+
});
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
840
|
+
main(process.argv.slice(2)).catch(error => { console.error(`vc setup: ${error.message}`); process.exitCode = 1; });
|
|
841
|
+
}
|