-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcheck.ts
More file actions
231 lines (210 loc) · 8.34 KB
/
Copy pathcheck.ts
File metadata and controls
231 lines (210 loc) · 8.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
/**
* `agents check` — scriptable drift gate for CI.
*
* Runs the SAME drift/divergence diagnostic `agents doctor` computes (via the
* shared `computeDrift` in `../lib/drift.js`) and turns it into an exit code:
* non-zero when any installed version is stale or never-synced, zero when the
* whole install is fresh. `agents doctor` is the human report; `agents check`
* is the machine gate — same engine, different output.
*
* Orphans are surfaced informationally but never fail the check: they are a
* `prune` concern, not sync drift (mirrors the sync-status engine, where an
* orphan alone never flags needsSync).
*/
import type { Command } from 'commander';
import chalk from 'chalk';
import { AGENTS, ALL_AGENT_IDS } from '../lib/agents.js';
import { setHelpSections } from '../lib/help.js';
import { computeDrift, type SyncStatusRow } from '../lib/drift.js';
import { loadDevices } from '../lib/devices/registry.js';
import { fanOutDevices, planFleetTargets, remoteFleetTargets, type FanOutDeviceTarget } from '../lib/devices/fleet.js';
import { fleetDialTarget } from '../lib/devices/connect.js';
import { machineId } from '../lib/session/sync/config.js';
import { buildRemoteAgentsInvocation } from '../lib/hosts/remote-cmd.js';
import { sshExecAsync } from '../lib/ssh-exec.js';
const AGENT_NAMES: Record<string, string> = Object.fromEntries(
ALL_AGENT_IDS.map((id) => [id, AGENTS[id].name]),
);
interface CheckOptions {
json?: boolean;
quiet?: boolean;
cwd?: string;
devices?: boolean;
}
interface DeviceCheckResult {
device: string;
hasDrift: boolean;
stale: number;
neverSynced: number;
orphanVersions: number;
error?: string;
}
function label(row: SyncStatusRow): string {
return `${AGENT_NAMES[row.agent] || row.agent}@${row.version}`;
}
export function registerCheckCommand(program: Command): void {
const checkCmd = program
.command('check')
.description('CI drift gate: exit non-zero when any installed version is out of sync (stale or never-synced), zero when clean.')
.option('--json', 'Output machine-readable JSON')
.option('-q, --quiet', 'Suppress per-version lines; print only the one-line verdict')
.option('--cwd <path>', 'Resolution cwd for project layer detection (default: process.cwd())')
.option('--devices', 'Run the drift gate across every registered online device');
setHelpSections(checkCmd, {
examples: `
# Fail the build if anything drifted (exit 1), pass if clean (exit 0)
agents check
# Just the verdict line, nothing per-version
agents check --quiet
# Machine-readable, for scripting
agents check --json
# Gate every registered device
agents check --devices
# Gate in a CI step
agents check || { echo "resources drifted — run 'agents doctor --fix'"; exit 1; }
`,
});
checkCmd.action(async (opts: CheckOptions) => {
const cwd = opts.cwd ? opts.cwd : process.cwd();
if (opts.devices) {
await runDevicesCheck(opts, cwd);
return;
}
const drift = computeDrift(cwd);
if (opts.json) {
console.log(JSON.stringify({
hasDrift: drift.hasDrift,
stale: drift.staleCount,
neverSynced: drift.neverSyncedCount,
orphanVersions: drift.orphanVersionCount,
versions: drift.syncRows.map((r) => ({
agent: r.agent,
version: r.version,
status: r.status,
isDefault: r.isDefault,
divergence: r.divergence ?? [],
})),
}, null, 2));
process.exit(drift.hasDrift ? 1 : 0);
}
if (drift.syncRows.length === 0) {
// Nothing installed is a clean state, not a failure — CI on a fresh
// checkout with no versions should pass, not error.
console.log(chalk.gray('check: no installed versions — nothing to verify'));
process.exit(0);
}
if (!drift.hasDrift) {
const orphanNote = drift.orphanVersionCount > 0
? chalk.gray(` (${drift.orphanVersionCount} version(s) carry orphans — run \`agents prune cleanup\`)`)
: '';
console.log(`${chalk.green('ok')} ${drift.syncRows.length} version(s) in sync${orphanNote}`);
process.exit(0);
}
// Drift: one-line verdict always, per-version detail unless --quiet.
const parts: string[] = [];
if (drift.staleCount > 0) parts.push(`${drift.staleCount} stale`);
if (drift.neverSyncedCount > 0) parts.push(`${drift.neverSyncedCount} never-synced`);
console.error(`${chalk.red('drift')} ${parts.join(', ')} of ${drift.syncRows.length} version(s)`);
if (!opts.quiet) {
for (const row of drift.syncRows) {
if (row.status === 'fresh') continue;
const tag = row.status === 'stale' ? chalk.yellow('stale') : chalk.gray('cold ');
console.error(` ${tag} ${label(row)}`);
for (const line of row.divergence ?? []) {
console.error(chalk.gray(` ${line}`));
}
}
console.error(chalk.gray('\nReconcile with `agents doctor --fix` (or `agents doctor <agent>@<version> --fix`).'));
}
process.exit(1);
});
}
function checkPayload(device: string, drift: ReturnType<typeof computeDrift>): DeviceCheckResult {
return {
device,
hasDrift: drift.hasDrift,
stale: drift.staleCount,
neverSynced: drift.neverSyncedCount,
orphanVersions: drift.orphanVersionCount,
};
}
interface CheckFanOutTarget extends FanOutDeviceTarget {
platform?: string;
/** Registry Tailscale address to dial, not the bare name — see {@link fleetDialTarget}. */
dialTarget: string;
}
async function probeDeviceCheck(target: CheckFanOutTarget): Promise<DeviceCheckResult> {
const isWin = /^win/i.test((target.platform ?? '').trim());
const remoteCmd = buildRemoteAgentsInvocation(
['check', '--json'],
undefined,
isWin ? 'windows' : undefined,
isWin ? undefined : { PATH: '$HOME/.agents/.cache/shims:$HOME/.local/bin:$PATH' },
);
const res = await sshExecAsync(target.dialTarget, remoteCmd, { timeoutMs: 30000, multiplex: true });
if (res.code !== 0 && !res.stdout.trim()) {
throw new Error(res.timedOut ? 'timed out' : (res.stderr.trim() || `exit ${res.code ?? 'unknown'}`));
}
try {
const parsed = JSON.parse(res.stdout) as Omit<DeviceCheckResult, 'device'>;
return {
device: target.name,
hasDrift: Boolean(parsed.hasDrift),
stale: parsed.stale ?? 0,
neverSynced: parsed.neverSynced ?? 0,
orphanVersions: parsed.orphanVersions ?? 0,
};
} catch (err: any) {
throw new Error(`invalid JSON (${err?.message ?? 'parse error'})`);
}
}
async function runDevicesCheck(opts: CheckOptions, cwd: string): Promise<void> {
const registry = await loadDevices();
const self = machineId();
const planned = planFleetTargets(registry);
const local = checkPayload(self, computeDrift(cwd));
const remoteTargets: CheckFanOutTarget[] = remoteFleetTargets(planned, self)
.map((t) => ({
name: t.device.name,
platform: t.device.platform,
skip: t.skip,
dialTarget: fleetDialTarget(t.device),
}));
const remote = await fanOutDevices(remoteTargets, probeDeviceCheck);
const devices: DeviceCheckResult[] = [local];
for (const result of remote) {
if (result.status === 'ok' && result.value) {
devices.push(result.value);
} else {
devices.push({
device: result.name,
hasDrift: true,
stale: 0,
neverSynced: 0,
orphanVersions: 0,
error: result.error ?? String(result.reason ?? 'skipped'),
});
}
}
const hasDrift = devices.some((d) => d.hasDrift || d.error);
if (opts.json) {
console.log(JSON.stringify({ hasDrift, devices }, null, 2));
process.exit(hasDrift ? 1 : 0);
}
if (!hasDrift) {
console.log(chalk.green('ok') + chalk.gray(` ${devices.length} device(s) in sync`));
process.exit(0);
}
console.error(chalk.red('drift') + chalk.gray(` ${devices.filter((d) => d.hasDrift || d.error).length} of ${devices.length} device(s)`));
if (!opts.quiet) {
for (const d of devices) {
if (!d.hasDrift && !d.error) continue;
const detail = d.error
? d.error
: [`${d.stale} stale`, `${d.neverSynced} never-synced`].filter((p) => !p.startsWith('0 ')).join(', ');
console.error(` ${chalk.yellow(d.device.padEnd(18))} ${detail || 'drift'}`);
}
console.error(chalk.gray('\nReconcile each device with `agents doctor --fix` or `agents repo pull user`.'));
}
process.exit(1);
}