cueapril 0.0.0-stage → 1.2.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/README.md +173 -2
- package/agents.mjs +996 -0
- package/cli.mjs +4 -0
- package/client.mjs +360 -0
- package/commands.mjs +1273 -0
- package/doctor.mjs +186 -0
- package/http.mjs +263 -0
- package/init.mjs +635 -0
- package/io.mjs +379 -0
- package/key-store.mjs +287 -0
- package/login.mjs +601 -0
- package/package.json +39 -4
- package/skill/cueapril-qa/SKILL.md +90 -0
package/commands.mjs
ADDED
|
@@ -0,0 +1,1273 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
3
|
+
import {
|
|
4
|
+
CLI_VERSION,
|
|
5
|
+
DEFAULT_BASE_URL,
|
|
6
|
+
QualityApiError,
|
|
7
|
+
QualityClient,
|
|
8
|
+
QualityNetworkError,
|
|
9
|
+
RUN_COMMAND,
|
|
10
|
+
TRANSIENT_STATUSES,
|
|
11
|
+
agentToolName,
|
|
12
|
+
isTransientError,
|
|
13
|
+
normalizeBaseUrl,
|
|
14
|
+
retryDelayMs,
|
|
15
|
+
retrying,
|
|
16
|
+
} from './client.mjs';
|
|
17
|
+
import { CODEX_TOOL_TIMEOUT_SEC, agentConfigPath, codexHasServer } from './agents.mjs';
|
|
18
|
+
import { DOCTOR_USAGE, runDoctor } from './doctor.mjs';
|
|
19
|
+
import { INIT_USAGE, runInit } from './init.mjs';
|
|
20
|
+
import { defaultDeps, displayPath } from './io.mjs';
|
|
21
|
+
import { resolveApiKey } from './key-store.mjs';
|
|
22
|
+
import { LOGIN_USAGE, LOGOUT_USAGE, runLogin, runLogout } from './login.mjs';
|
|
23
|
+
|
|
24
|
+
/** Identical to CLI_EXIT_CODES in the API's agent contract; a test keeps the two equal. */
|
|
25
|
+
export const EXIT_CODES = Object.freeze({ passed: 0, failed: 1, incomplete: 2, cancelled: 2, blocked: 3, timeout: 4, error: 5 });
|
|
26
|
+
/** The server never holds a wait call longer than this (ASSESSMENT_WAIT_MAX_SECONDS). */
|
|
27
|
+
export const WAIT_MAX_SECONDS = 50;
|
|
28
|
+
/** Suggested pause between status calls while a run is active (ASSESSMENT_POLL_AFTER_SECONDS). */
|
|
29
|
+
export const POLL_AFTER_SECONDS = 30;
|
|
30
|
+
export const AGENT_KEY_PREFIX = 'cueapril_sk_';
|
|
31
|
+
export const ASSESSMENT_OUTCOMES = Object.freeze(['queued', 'running', 'passed', 'failed', 'incomplete', 'cancelled']);
|
|
32
|
+
export const DEFAULT_TIMEOUT_MINUTES = 90;
|
|
33
|
+
/** Gemini CLI stops a shell command after 300 seconds of silence, so waiting always speaks well within a minute. */
|
|
34
|
+
export const HEARTBEAT_MS = 45_000;
|
|
35
|
+
export const TOOLS = Object.freeze({
|
|
36
|
+
checkSetup: 'cueapril_check_setup',
|
|
37
|
+
start: 'cueapril_start_assessment',
|
|
38
|
+
get: 'cueapril_get_assessment',
|
|
39
|
+
wait: 'cueapril_wait_for_assessment',
|
|
40
|
+
results: 'cueapril_get_assessment_results',
|
|
41
|
+
cancel: 'cueapril_cancel_assessment',
|
|
42
|
+
list: 'cueapril_list_assessments',
|
|
43
|
+
projects: 'cueapril_list_projects',
|
|
44
|
+
});
|
|
45
|
+
const MAX_TIMEOUT_MINUTES = 24 * 60;
|
|
46
|
+
const HEARTBEAT_CHECK_MS = 5_000;
|
|
47
|
+
const READ_ATTEMPTS = 5;
|
|
48
|
+
const START_ATTEMPTS = 5;
|
|
49
|
+
const START_TIMEOUT_MS = 60_000;
|
|
50
|
+
const STDIN_LIMIT = 1_000_000;
|
|
51
|
+
const MAX_RESULT_PAGES = 200;
|
|
52
|
+
const AGENT_KEY_PATTERN = /^cueapril_sk_[0-9a-f]{20}_[A-Za-z0-9_-]{43}$/;
|
|
53
|
+
const ID_PATTERN = /^[A-Za-z0-9_.:-]{1,200}$/;
|
|
54
|
+
const IDEMPOTENCY_KEY_PATTERN = /^[\x21-\x7e]{8,200}$/;
|
|
55
|
+
const RESULT_SECTIONS = ['findings', 'fixes', 'coverage', 'evidence'];
|
|
56
|
+
const NEXT_COMMANDS = {
|
|
57
|
+
cueapril_wait_for_assessment: (id) => `cueapril wait ${id}`,
|
|
58
|
+
cueapril_get_assessment: (id) => `cueapril status ${id}`,
|
|
59
|
+
cueapril_get_assessment_results: (id) => `cueapril results ${id}`,
|
|
60
|
+
cueapril_check_setup: () => 'cueapril setup',
|
|
61
|
+
};
|
|
62
|
+
const ESCAPE_SEQUENCES = /\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|[@-Z\\-_])/g;
|
|
63
|
+
// Controls other than tab and newline, and format characters such as bidirectional overrides, which can hide or reorder terminal text.
|
|
64
|
+
const UNSAFE_CHARACTERS = /(?![\t\n])[\p{Cc}\p{Cf}]/gu;
|
|
65
|
+
|
|
66
|
+
class CliError extends Error {
|
|
67
|
+
constructor(message, { hint } = {}) {
|
|
68
|
+
super(message);
|
|
69
|
+
this.name = 'CliError';
|
|
70
|
+
if (hint) this.hint = hint;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
class UsageError extends CliError {
|
|
74
|
+
constructor(message) {
|
|
75
|
+
super(message);
|
|
76
|
+
this.name = 'UsageError';
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function isTerminalOutcome(outcome) {
|
|
81
|
+
return outcome !== 'queued' && outcome !== 'running';
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Commands that report an assessment exit 0 only when it passed; an outcome this CLI does not know is an error. */
|
|
85
|
+
export function exitCodeForOutcome(outcome) {
|
|
86
|
+
if (!isTerminalOutcome(outcome)) return EXIT_CODES.timeout;
|
|
87
|
+
return ['passed', 'failed', 'incomplete', 'cancelled'].includes(outcome) ? EXIT_CODES[outcome] : EXIT_CODES.error;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// ---------------------------------------------------------------- arguments
|
|
91
|
+
|
|
92
|
+
export function parseArgs(args, flags) {
|
|
93
|
+
const options = {};
|
|
94
|
+
const positionals = [];
|
|
95
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
96
|
+
const arg = args[index];
|
|
97
|
+
if (arg === '--') {
|
|
98
|
+
positionals.push(...args.slice(index + 1));
|
|
99
|
+
break;
|
|
100
|
+
}
|
|
101
|
+
if (!arg.startsWith('-') || arg === '-') {
|
|
102
|
+
positionals.push(arg);
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
if (!arg.startsWith('--')) throw new UsageError(`Unknown option ${clean(arg, 60)}`);
|
|
106
|
+
const equals = arg.indexOf('=');
|
|
107
|
+
const name = arg.slice(2, equals === -1 ? undefined : equals);
|
|
108
|
+
const kind = Object.hasOwn(flags, name) ? flags[name] : undefined;
|
|
109
|
+
if (!kind) throw new UsageError(`Unknown option --${clean(name, 60)}`);
|
|
110
|
+
if (Object.hasOwn(options, name)) throw new UsageError(`--${name} was given more than once`);
|
|
111
|
+
if (kind === 'flag') {
|
|
112
|
+
if (equals !== -1) throw new UsageError(`--${name} does not take a value`);
|
|
113
|
+
options[name] = true;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
let value;
|
|
117
|
+
if (equals !== -1) value = arg.slice(equals + 1);
|
|
118
|
+
else {
|
|
119
|
+
value = args[index + 1];
|
|
120
|
+
if (value === undefined || value.startsWith('--')) throw new UsageError(`--${name} needs a value`);
|
|
121
|
+
index += 1;
|
|
122
|
+
}
|
|
123
|
+
options[name] = value;
|
|
124
|
+
}
|
|
125
|
+
return { options, positionals };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function idValue(value, label) {
|
|
129
|
+
if (typeof value !== 'string' || !ID_PATTERN.test(value)) throw new UsageError(`${label} must be 1 to 200 letters, digits, dots, colons, dashes or underscores`);
|
|
130
|
+
return value;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function pullRequestNumber(value) {
|
|
134
|
+
const text = value.startsWith('#') ? value.slice(1) : value;
|
|
135
|
+
if (!/^[1-9]\d{0,9}$/.test(text) || Number(text) > 2147483647) throw new UsageError('--pr must be a pull request number, such as 42');
|
|
136
|
+
return Number(text);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function pullRequestTarget(value) {
|
|
140
|
+
if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) return { pull_request: pullRequestNumber(value) };
|
|
141
|
+
let url;
|
|
142
|
+
try {
|
|
143
|
+
url = new URL(value);
|
|
144
|
+
} catch {
|
|
145
|
+
throw new UsageError('--pr is not a valid URL');
|
|
146
|
+
}
|
|
147
|
+
const match = /^\/([^/]+)\/([^/]+)\/pull\/([1-9]\d{0,9})(?:\/.*)?$/.exec(url.pathname);
|
|
148
|
+
if (url.protocol !== 'https:' || url.username || url.password || !match)
|
|
149
|
+
throw new UsageError('--pr must be a pull request number or an https URL such as https://github.com/owner/repo/pull/42');
|
|
150
|
+
return { pull_request_url: `${url.origin}/${match[1]}/${match[2]}/pull/${match[3]}` };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** CueApril looks assessments up by the full head SHA only, as SHA-1 (40) or SHA-256 (64) hexadecimal. */
|
|
154
|
+
function commitSha(value) {
|
|
155
|
+
if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(value))
|
|
156
|
+
throw new UsageError('--commit must be a full commit SHA: 40 or 64 hexadecimal characters, as git rev-parse HEAD prints');
|
|
157
|
+
return value.toLowerCase();
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function boundedInteger(value, label, minimum, maximum) {
|
|
161
|
+
if (!/^\d+$/.test(value) || Number(value) < minimum || Number(value) > maximum) throw new UsageError(`${label} must be a whole number from ${minimum} to ${maximum}`);
|
|
162
|
+
return Number(value);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function waitLimitMs(value) {
|
|
166
|
+
if (value === undefined) return DEFAULT_TIMEOUT_MINUTES * 60_000;
|
|
167
|
+
const minutes = /^\d+(\.\d+)?$/.test(value) ? Number(value) : Number.NaN;
|
|
168
|
+
if (!(minutes > 0) || minutes > MAX_TIMEOUT_MINUTES) throw new UsageError(`--timeout must be a number of minutes above 0 and at most ${MAX_TIMEOUT_MINUTES}`);
|
|
169
|
+
return Math.round(minutes * 60_000);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function idempotencyKey(value) {
|
|
173
|
+
if (!IDEMPOTENCY_KEY_PATTERN.test(value)) throw new UsageError('--idempotency-key must be 8 to 200 visible ASCII characters');
|
|
174
|
+
return value;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function sections(value) {
|
|
178
|
+
const list = value.split(',').map((item) => item.trim()).filter(Boolean);
|
|
179
|
+
if (!list.length || list.some((item) => !RESULT_SECTIONS.includes(item)) || new Set(list).size !== list.length)
|
|
180
|
+
throw new UsageError(`--sections takes a comma-separated list of ${RESULT_SECTIONS.join(', ')}`);
|
|
181
|
+
return list;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function parseObject(raw) {
|
|
185
|
+
let value;
|
|
186
|
+
try {
|
|
187
|
+
value = JSON.parse(raw);
|
|
188
|
+
} catch {
|
|
189
|
+
throw new UsageError('Arguments must be valid JSON');
|
|
190
|
+
}
|
|
191
|
+
if (!value || Array.isArray(value) || typeof value !== 'object') throw new UsageError('Arguments must be a JSON object');
|
|
192
|
+
return value;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async function readStdin(ctx) {
|
|
196
|
+
let raw = '';
|
|
197
|
+
for await (const chunk of ctx.stdin) {
|
|
198
|
+
raw += chunk;
|
|
199
|
+
if (raw.length > STDIN_LIMIT) throw new CliError('Input exceeds limit');
|
|
200
|
+
}
|
|
201
|
+
return raw;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// ---------------------------------------------------------------- output helpers
|
|
205
|
+
|
|
206
|
+
function clean(value, max = 300) {
|
|
207
|
+
const text = (
|
|
208
|
+
typeof value === 'string' ? value : value === undefined || value === null ? '' : typeof value === 'object' ? JSON.stringify(value) : String(value)
|
|
209
|
+
)
|
|
210
|
+
.replace(ESCAPE_SEQUENCES, '')
|
|
211
|
+
.replace(UNSAFE_CHARACTERS, '');
|
|
212
|
+
return text.length > max ? `${text.slice(0, max - 3)}...` : text;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function oneLine(value, max = 300) {
|
|
216
|
+
return clean(value, max).replace(/\s*\n\s*/g, ' ').replace(/\t/g, ' ');
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function indented(value, indent, max = 600) {
|
|
220
|
+
const lines = clean(value, max).replace(/\t/g, ' ').split('\n');
|
|
221
|
+
return (lines.length > 8 ? [...lines.slice(0, 8), '...'] : lines).join(`\n${indent}`);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function count(value) {
|
|
225
|
+
return Number.isFinite(value) ? value : 0;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function list(value) {
|
|
229
|
+
return Array.isArray(value) ? value : [];
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export function formatDuration(ms) {
|
|
233
|
+
const total = Math.max(0, Math.round(ms / 1000));
|
|
234
|
+
const hours = Math.floor(total / 3600);
|
|
235
|
+
const minutes = Math.floor((total % 3600) / 60);
|
|
236
|
+
const seconds = total % 60;
|
|
237
|
+
if (hours) return `${hours}h ${minutes}m`;
|
|
238
|
+
if (minutes) return `${minutes}m ${seconds}s`;
|
|
239
|
+
return `${seconds}s`;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function formatBytes(bytes) {
|
|
243
|
+
if (!Number.isFinite(bytes)) return '';
|
|
244
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
245
|
+
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KiB`;
|
|
246
|
+
return `${(bytes / 1024 / 1024).toFixed(1)} MiB`;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function table(headings, rows) {
|
|
250
|
+
const widths = headings.map((heading, column) => Math.max(heading.length, ...rows.map((row) => row[column].length)));
|
|
251
|
+
const render = (cells) => cells.map((cell, column) => cell.padEnd(widths[column])).join(' ').trimEnd();
|
|
252
|
+
return `${[render(headings), ...rows.map(render)].join('\n')}\n`;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function redact(text, secret) {
|
|
256
|
+
return secret && secret.length >= 8 ? text.split(secret).join('[redacted]') : text;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const unicodeEscapes = (text) => Array.from({ length: text.length }, (_, index) => `\\u${text.charCodeAt(index).toString(16).padStart(4, '0')}`).join('');
|
|
260
|
+
/** JSON.stringify leaves C1 controls and format characters raw; escaping them keeps the JSON identical and the terminal safe. */
|
|
261
|
+
function jsonText(value, indent) {
|
|
262
|
+
return (JSON.stringify(value, null, indent) ?? 'null').replace(/(?!\n)[\p{Cc}\p{Cf}]/gu, unicodeEscapes);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function fixLocation(fix) {
|
|
266
|
+
const start = Number.isFinite(fix.start_line) ? fix.start_line : '?';
|
|
267
|
+
const end = Number.isFinite(fix.end_line) && fix.end_line !== fix.start_line ? `-${fix.end_line}` : '';
|
|
268
|
+
return `${oneLine(fix.path ?? 'unknown file', 300)}:${start}${end}`;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function nextCommand(status) {
|
|
272
|
+
const id = oneLine(status.assessment_id, 200);
|
|
273
|
+
const hinted = typeof status.next?.tool === 'string' ? NEXT_COMMANDS[status.next.tool] : undefined;
|
|
274
|
+
if (hinted) return hinted(id);
|
|
275
|
+
if (!isTerminalOutcome(status.outcome)) return `cueapril wait ${id}`;
|
|
276
|
+
return status.outcome === 'passed' && !count(status.suggested_fix_count) ? undefined : `cueapril results ${id}`;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function renderStatus(status, { fixes, timedOutAfterMs } = {}) {
|
|
280
|
+
const id = oneLine(status.assessment_id, 200);
|
|
281
|
+
const lines = [`CueApril assessment ${id}: ${oneLine(status.outcome, 40).toUpperCase()}`];
|
|
282
|
+
lines.push(
|
|
283
|
+
` Verdict: ${oneLine(status.verdict ?? 'unknown', 40)} Gate: ${oneLine(status.gate_decision ?? 'unknown', 40)} Lifecycle: ${oneLine(status.lifecycle ?? 'unknown', 40)}`,
|
|
284
|
+
);
|
|
285
|
+
const pr = status.pull_request;
|
|
286
|
+
if (pr && typeof pr === 'object' && pr.number !== undefined) lines.push(` Pull request: #${oneLine(pr.number, 20)}${pr.url ? ` ${oneLine(pr.url, 300)}` : ''}`);
|
|
287
|
+
if (status.head_sha) lines.push(` Commit: ${oneLine(status.head_sha, 64)}${status.base_sha ? ` (base ${oneLine(status.base_sha, 64)})` : ''}`);
|
|
288
|
+
if (status.reason) lines.push(` Reason: ${oneLine(status.reason, 500)}`);
|
|
289
|
+
const counts = status.counts;
|
|
290
|
+
if (counts && typeof counts === 'object')
|
|
291
|
+
lines.push(
|
|
292
|
+
` Tasks: ${count(counts.tasks)} total, ${count(counts.passed)} passed, ${count(counts.failed)} failed, ${count(counts.incomplete)} incomplete, ${count(counts.pending)} pending`,
|
|
293
|
+
);
|
|
294
|
+
const failures = list(status.failures).slice(0, 10);
|
|
295
|
+
if (failures.length) {
|
|
296
|
+
lines.push(' Failures:');
|
|
297
|
+
failures.forEach((failure, index) => {
|
|
298
|
+
lines.push(` ${index + 1}. ${failure?.method ? `[${oneLine(failure.method, 40)}] ` : ''}${oneLine(failure?.title ?? 'Untitled check', 200)}`);
|
|
299
|
+
if (failure?.expected !== undefined) lines.push(` expected: ${indented(failure.expected, ' ')}`);
|
|
300
|
+
if (failure?.observed !== undefined) lines.push(` observed: ${indented(failure.observed, ' ')}`);
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
const fixCount = count(status.suggested_fix_count);
|
|
304
|
+
if (fixCount) {
|
|
305
|
+
lines.push(` Suggested fixes: ${fixCount}`);
|
|
306
|
+
for (const fix of list(fixes)) lines.push(` ${fixLocation(fix)}`);
|
|
307
|
+
}
|
|
308
|
+
if (status.cost && typeof status.cost === 'object') {
|
|
309
|
+
const pence = (value) => (Number.isFinite(value) ? `${value}p` : 'unknown');
|
|
310
|
+
lines.push(` Cost: actual ${pence(status.cost.actual_pence)}, reserved ${pence(status.cost.reserved_pence)}`);
|
|
311
|
+
}
|
|
312
|
+
if (status.links?.ui) lines.push(` Details: ${oneLine(status.links.ui, 300)}`);
|
|
313
|
+
if (timedOutAfterMs !== undefined) {
|
|
314
|
+
lines.push(` Still ${oneLine(status.outcome, 40)} after ${formatDuration(timedOutAfterMs)}; this CLI stopped waiting, the assessment continues.`);
|
|
315
|
+
lines.push(` Resume: cueapril wait ${id}`);
|
|
316
|
+
} else {
|
|
317
|
+
const next = nextCommand(status);
|
|
318
|
+
if (next) lines.push(` Next: ${next}`);
|
|
319
|
+
}
|
|
320
|
+
return `${lines.join('\n')}\n`;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function renderBlocked(result) {
|
|
324
|
+
const pr = result.pull_request;
|
|
325
|
+
const target = pr && typeof pr === 'object' && pr.number !== undefined ? ` for pull request #${oneLine(pr.number, 20)}` : '';
|
|
326
|
+
const lines = [`CueApril did not start an assessment${target}: blocked.`];
|
|
327
|
+
list(result.blockers).forEach((blocker, index) => {
|
|
328
|
+
lines.push(` ${index + 1}. ${oneLine(blocker?.code ?? 'blocked', 80)}${blocker?.owner ? ` (${oneLine(blocker.owner, 20)})` : ''}: ${oneLine(blocker?.message ?? '', 500)}`);
|
|
329
|
+
if (blocker?.fix_url) lines.push(` Fix: ${oneLine(blocker.fix_url, 300)}`);
|
|
330
|
+
});
|
|
331
|
+
lines.push(` Next: cueapril setup${result.project_id ? ` --project ${oneLine(result.project_id, 200)}` : ''}`);
|
|
332
|
+
return `${lines.join('\n')}\n`;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function renderAccepted(result) {
|
|
336
|
+
const id = oneLine(result.assessment_id, 200);
|
|
337
|
+
const pr = result.pull_request ?? {};
|
|
338
|
+
const head = pr.head_sha ? ` (head ${oneLine(pr.head_sha, 64).slice(0, 12)})` : '';
|
|
339
|
+
const lines = [
|
|
340
|
+
`CueApril ${result.duplicate ? 'already has' : 'accepted'} assessment ${id} for pull request #${oneLine(pr.number ?? '?', 20)}${head}.`,
|
|
341
|
+
` Outcome: ${oneLine(result.outcome, 40)}`,
|
|
342
|
+
];
|
|
343
|
+
if (result.links?.ui) lines.push(` Details: ${oneLine(result.links.ui, 300)}`);
|
|
344
|
+
lines.push(isTerminalOutcome(result.outcome) ? ` Next: cueapril status ${id}` : ` Next: cueapril wait ${id}`);
|
|
345
|
+
return `${lines.join('\n')}\n`;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function renderResults(page) {
|
|
349
|
+
const status = page.assessment && typeof page.assessment === 'object' ? page.assessment : {};
|
|
350
|
+
const id = oneLine(status.assessment_id, 200);
|
|
351
|
+
const lines = [
|
|
352
|
+
`CueApril assessment ${id}: ${oneLine(status.outcome, 40).toUpperCase()} (verdict ${oneLine(status.verdict ?? 'unknown', 40)}, gate ${oneLine(status.gate_decision ?? 'unknown', 40)})`,
|
|
353
|
+
];
|
|
354
|
+
if (page.findings !== undefined) {
|
|
355
|
+
const findings = list(page.findings);
|
|
356
|
+
lines.push(`Findings (${findings.length}):`);
|
|
357
|
+
if (!findings.length) lines.push(' none');
|
|
358
|
+
findings.forEach((finding, index) => {
|
|
359
|
+
const labels = [finding?.method, finding?.status].filter(Boolean).map((label) => oneLine(label, 40));
|
|
360
|
+
lines.push(` ${index + 1}. ${oneLine(finding?.title ?? 'Untitled finding', 200)}${labels.length ? ` [${labels.join(', ')}]` : ''}${finding?.id ? ` (${oneLine(finding.id, 200)})` : ''}`);
|
|
361
|
+
if (finding?.expected !== undefined) lines.push(` expected: ${indented(finding.expected, ' ')}`);
|
|
362
|
+
if (finding?.observed !== undefined) lines.push(` observed: ${indented(finding.observed, ' ')}`);
|
|
363
|
+
if (finding?.file) lines.push(` at ${oneLine(finding.file, 300)}${Number.isFinite(finding.line) ? `:${finding.line}` : ''}`);
|
|
364
|
+
if (finding?.reproduction) lines.push(` reproduce: ${indented(finding.reproduction, ' ')}`);
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
if (page.suggested_fixes !== undefined) {
|
|
368
|
+
const fixes = list(page.suggested_fixes);
|
|
369
|
+
lines.push(`Suggested fixes (${fixes.length}):`);
|
|
370
|
+
if (!fixes.length) lines.push(' none');
|
|
371
|
+
for (const fix of fixes) {
|
|
372
|
+
const facts = [fix?.confidence ? `confidence ${oneLine(fix.confidence, 40)}` : '', fix?.verified ? 'verified' : 'not verified', fix?.finding_id ? `finding ${oneLine(fix.finding_id, 200)}` : '']
|
|
373
|
+
.filter(Boolean)
|
|
374
|
+
.join(', ');
|
|
375
|
+
lines.push(` ${fixLocation(fix ?? {})} (${facts})`);
|
|
376
|
+
for (const [mark, text] of [['-', fix?.original], ['+', fix?.replacement]]) {
|
|
377
|
+
if (typeof text !== 'string') continue;
|
|
378
|
+
const changed = clean(text, 4000).replace(/\n$/, '').split('\n');
|
|
379
|
+
for (const changedLine of changed.slice(0, 20)) lines.push(` ${mark} ${changedLine}`);
|
|
380
|
+
if (changed.length > 20) lines.push(` ${mark} ... ${changed.length - 20} more lines`);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
if (page.coverage !== undefined) {
|
|
385
|
+
const coverage = list(page.coverage);
|
|
386
|
+
lines.push(`Coverage (${coverage.length}):`);
|
|
387
|
+
if (!coverage.length) lines.push(' none');
|
|
388
|
+
for (const entry of coverage) lines.push(` ${oneLine(entry?.method ?? 'unknown', 60)}: ${oneLine(entry?.status ?? 'unknown', 40)}${entry?.reason ? ` - ${oneLine(entry.reason, 300)}` : ''}`);
|
|
389
|
+
}
|
|
390
|
+
if (page.evidence !== undefined) {
|
|
391
|
+
const evidence = list(page.evidence);
|
|
392
|
+
lines.push(`Evidence (${evidence.length}):`);
|
|
393
|
+
if (!evidence.length) lines.push(' none');
|
|
394
|
+
for (const item of evidence) {
|
|
395
|
+
const facts = [item?.kind ? oneLine(item.kind, 40) : '', formatBytes(item?.bytes)].filter(Boolean).join(', ');
|
|
396
|
+
lines.push(` ${oneLine(item?.name ?? item?.id ?? 'artifact', 200)}${facts ? ` (${facts})` : ''}${item?.url ? ` ${oneLine(item.url, 2000)}` : ''}${item?.expires_at ? ` expires ${oneLine(item.expires_at, 40)}` : ''}`);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
if (page.next_cursor) lines.push(`More results: cueapril results ${id} --all`);
|
|
400
|
+
return `${lines.join('\n')}\n`;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// ---------------------------------------------------------------- context and configuration
|
|
404
|
+
|
|
405
|
+
function context(io) {
|
|
406
|
+
const stdout = io.stdout ?? ((text) => process.stdout.write(text));
|
|
407
|
+
const stderr = io.stderr ?? ((text) => process.stderr.write(text));
|
|
408
|
+
// Every write passes through redaction, so a server that echoes the key cannot make the CLI print it.
|
|
409
|
+
const ctx = {
|
|
410
|
+
env: io.env ?? process.env,
|
|
411
|
+
out: (text) => stdout(redact(text, ctx.secret)),
|
|
412
|
+
err: (text) => stderr(redact(text, ctx.secret)),
|
|
413
|
+
stdin: io.stdin ?? process.stdin,
|
|
414
|
+
fetch: io.fetch,
|
|
415
|
+
now: io.now ?? (() => Date.now()),
|
|
416
|
+
sleep: io.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
|
|
417
|
+
setInterval: io.setInterval ?? ((callback, ms) => setInterval(callback, ms)),
|
|
418
|
+
clearInterval: io.clearInterval ?? ((timer) => clearInterval(timer)),
|
|
419
|
+
readFile: io.readFile ?? readFile,
|
|
420
|
+
writeFile: io.writeFile ?? writeFile,
|
|
421
|
+
resolveStoredKey: io.resolveStoredKey,
|
|
422
|
+
secret: undefined,
|
|
423
|
+
};
|
|
424
|
+
return ctx;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
function environmentValue(env, ...names) {
|
|
428
|
+
for (const name of names) {
|
|
429
|
+
const value = env[name];
|
|
430
|
+
if (typeof value === 'string' && value.trim()) return { name, value: value.trim() };
|
|
431
|
+
}
|
|
432
|
+
return undefined;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
function baseUrl(ctx) {
|
|
436
|
+
return environmentValue(ctx.env, 'CUEAPRIL_URL', 'TENHAW_URL')?.value ?? DEFAULT_BASE_URL;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/** A key stored by `cueapril login` or `init`, read relative to this context's own HOME. */
|
|
440
|
+
async function storedKey(ctx) {
|
|
441
|
+
if (ctx.resolveStoredKey) return ctx.resolveStoredKey(baseUrl(ctx));
|
|
442
|
+
const home = ctx.env.HOME || ctx.env.USERPROFILE;
|
|
443
|
+
if (!home && !ctx.env.XDG_CONFIG_HOME && !ctx.env.APPDATA) return null;
|
|
444
|
+
try {
|
|
445
|
+
const resolved = await resolveApiKey({ env: ctx.env, ...(home ? { homedir: () => home } : {}) }, { baseUrl: baseUrl(ctx) });
|
|
446
|
+
return resolved?.source === 'store' ? { name: `the key stored at ${resolved.path}`, value: resolved.key } : null;
|
|
447
|
+
} catch (error) {
|
|
448
|
+
throw new CliError(error instanceof Error ? error.message : 'The stored CueApril key could not be read');
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
async function agentClient(ctx) {
|
|
453
|
+
const key = environmentValue(ctx.env, 'CUEAPRIL_API_KEY', 'TENHAW_TOKEN') ?? (await storedKey(ctx));
|
|
454
|
+
if (!key) throw new CliError('No CueApril agent key. Run `cueapril login` (or `cueapril init`) to approve one in the browser, or set CUEAPRIL_API_KEY. An organisation admin can also create keys in CueApril settings under Agent access.');
|
|
455
|
+
if (key.value.startsWith(AGENT_KEY_PREFIX) && !AGENT_KEY_PATTERN.test(key.value))
|
|
456
|
+
throw new CliError(`${key.name} starts with ${AGENT_KEY_PREFIX} but is not a complete agent key; copy the whole key.`);
|
|
457
|
+
ctx.secret = key.value;
|
|
458
|
+
return new QualityClient({ baseUrl: baseUrl(ctx), token: key.value, fetch: ctx.fetch, authMode: 'oauth' });
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
function transientText(error) {
|
|
462
|
+
if (error instanceof QualityApiError) return error.status === 429 ? 'CueApril is rate limiting requests (429)' : `CueApril answered ${error.status}`;
|
|
463
|
+
return error instanceof QualityNetworkError && error.timedOut ? 'The request timed out' : 'The network request failed';
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
function readTool(ctx, client, name, args) {
|
|
467
|
+
return retrying(() => client.callTool(name, args), {
|
|
468
|
+
attempts: READ_ATTEMPTS,
|
|
469
|
+
sleep: ctx.sleep,
|
|
470
|
+
onRetry: (error, delay) => ctx.err(`cueapril: ${transientText(error)}; retrying in ${formatDuration(delay)}\n`),
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function assertAssessment(value) {
|
|
475
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || typeof value.assessment_id !== 'string' || typeof value.outcome !== 'string')
|
|
476
|
+
throw new CliError('The API returned an unexpected assessment response');
|
|
477
|
+
return value;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
function describeError(error) {
|
|
481
|
+
let message;
|
|
482
|
+
if (error instanceof QualityApiError) {
|
|
483
|
+
const detail = error.detail ? ` ${error.detail}` : '';
|
|
484
|
+
if (error.status === 401)
|
|
485
|
+
message = `CueApril did not accept the API key (401${detail}). Check CUEAPRIL_API_KEY: keys expire, and an organisation admin can revoke them.`;
|
|
486
|
+
else if (error.status === 403)
|
|
487
|
+
message = `This key is not allowed to do that (403${detail}). Starting needs the quality:run scope and cancelling needs quality:cancel; an organisation admin can issue a key that has them.`;
|
|
488
|
+
else if (error.status === 404) message = `Not found (404${detail}).`;
|
|
489
|
+
else if (error.status === 429) message = `CueApril is rate limiting this key (429${detail}). Try again shortly.`;
|
|
490
|
+
else if (TRANSIENT_STATUSES.includes(error.status)) message = `CueApril is temporarily unavailable (${error.status}${detail}). Try again shortly.`;
|
|
491
|
+
else message = error.message;
|
|
492
|
+
} else message = error instanceof Error ? error.message : String(error);
|
|
493
|
+
if (error?.hint) message += ` ${error.hint}`;
|
|
494
|
+
return oneLine(message, 800);
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
function fail(ctx, error, { json, command } = {}) {
|
|
498
|
+
let message = describeError(error);
|
|
499
|
+
if (!/[.!?]$/.test(message)) message += '.';
|
|
500
|
+
if (error instanceof UsageError) message += command ? ` Run "cueapril ${command} --help".` : ' Run "cueapril --help".';
|
|
501
|
+
if (error?.assessmentId) message += ` Assessment ${error.assessmentId} was accepted; resume with "cueapril wait ${error.assessmentId}".`;
|
|
502
|
+
ctx.err(`cueapril: ${message}\n`);
|
|
503
|
+
if (json) {
|
|
504
|
+
const detail = error instanceof QualityApiError ? { status: error.status, ...(error.detail ? { detail: error.detail } : {}) } : {};
|
|
505
|
+
ctx.out(`${jsonText({ error: { message, ...detail }, ...(error?.assessmentId ? { assessment_id: error.assessmentId } : {}), exit_code: EXIT_CODES.error })}\n`);
|
|
506
|
+
}
|
|
507
|
+
return EXIT_CODES.error;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
// ---------------------------------------------------------------- waiting
|
|
511
|
+
|
|
512
|
+
export function createProgress(ctx) {
|
|
513
|
+
let last = ctx.now();
|
|
514
|
+
let timer;
|
|
515
|
+
const line = (text) => {
|
|
516
|
+
ctx.err(`cueapril: ${text}\n`);
|
|
517
|
+
last = ctx.now();
|
|
518
|
+
};
|
|
519
|
+
return {
|
|
520
|
+
line,
|
|
521
|
+
start(describe) {
|
|
522
|
+
timer = ctx.setInterval(() => {
|
|
523
|
+
if (ctx.now() - last >= HEARTBEAT_MS) line(describe());
|
|
524
|
+
}, HEARTBEAT_CHECK_MS);
|
|
525
|
+
timer?.unref?.();
|
|
526
|
+
},
|
|
527
|
+
stop() {
|
|
528
|
+
if (timer !== undefined) ctx.clearInterval(timer);
|
|
529
|
+
timer = undefined;
|
|
530
|
+
},
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
function progressText(status, elapsedMs, remainingMs) {
|
|
535
|
+
const counts = status.counts && typeof status.counts === 'object' ? status.counts : undefined;
|
|
536
|
+
const done = counts ? count(counts.passed) + count(counts.failed) + count(counts.incomplete) : 0;
|
|
537
|
+
const tasks = counts && count(counts.tasks) ? `, ${done}/${count(counts.tasks)} tasks finished, ${count(counts.failed)} failed` : '';
|
|
538
|
+
return `assessment ${oneLine(status.assessment_id, 200)} ${oneLine(status.outcome, 40)} (${oneLine(status.lifecycle ?? 'unknown', 40)})${tasks}; ${formatDuration(elapsedMs)} elapsed, up to ${formatDuration(remainingMs)} left`;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
function isGatewayTimeout(error) {
|
|
542
|
+
return (error instanceof QualityApiError && [504, 522, 524].includes(error.status)) || (error instanceof QualityNetworkError && error.timedOut);
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/**
|
|
546
|
+
* Long-polls cueapril_wait_for_assessment until the outcome is terminal or the
|
|
547
|
+
* deadline passes. Transient failures are retried until the deadline; others end
|
|
548
|
+
* the wait. Returns the last status seen.
|
|
549
|
+
*/
|
|
550
|
+
async function waitForTerminal(ctx, client, assessmentId, { started, deadline, progress, onStatus }) {
|
|
551
|
+
let latest;
|
|
552
|
+
let lastError;
|
|
553
|
+
let failures = 0;
|
|
554
|
+
let cap = WAIT_MAX_SECONDS;
|
|
555
|
+
for (;;) {
|
|
556
|
+
const remaining = deadline - ctx.now();
|
|
557
|
+
// Always look once, even when starting used up the timeout, so the answer is a status rather than a guess.
|
|
558
|
+
if (remaining <= 0 && latest !== undefined) return { status: latest, timedOut: true, lastError };
|
|
559
|
+
const seconds = Math.max(1, Math.min(cap, Math.ceil(remaining / 1000)));
|
|
560
|
+
const asked = ctx.now();
|
|
561
|
+
let status;
|
|
562
|
+
try {
|
|
563
|
+
status = assertAssessment(
|
|
564
|
+
await client.callTool(TOOLS.wait, { assessment_id: assessmentId, timeout_seconds: seconds }, { timeoutMs: (seconds + 20) * 1000 }),
|
|
565
|
+
);
|
|
566
|
+
} catch (error) {
|
|
567
|
+
if (!isTransientError(error)) throw error;
|
|
568
|
+
failures += 1;
|
|
569
|
+
lastError = error;
|
|
570
|
+
// A gateway that cuts long requests short keeps cutting them: ask for shorter holds.
|
|
571
|
+
if (isGatewayTimeout(error)) cap = Math.max(5, Math.floor(cap / 2));
|
|
572
|
+
const delay = retryDelayMs(failures, error);
|
|
573
|
+
if (ctx.now() + delay >= deadline) return { status: latest, timedOut: true, lastError };
|
|
574
|
+
progress.line(`${transientText(error)} while waiting; retrying in ${formatDuration(delay)}`);
|
|
575
|
+
await ctx.sleep(delay);
|
|
576
|
+
continue;
|
|
577
|
+
}
|
|
578
|
+
failures = 0;
|
|
579
|
+
lastError = undefined;
|
|
580
|
+
latest = status;
|
|
581
|
+
onStatus?.(status);
|
|
582
|
+
if (isTerminalOutcome(status.outcome)) return { status, timedOut: false };
|
|
583
|
+
progress.line(progressText(status, ctx.now() - started, deadline - ctx.now()));
|
|
584
|
+
// The server answers early only for a finished run; pace a server or proxy that did not hold the call.
|
|
585
|
+
if (ctx.now() - asked < (seconds * 1000) / 2) {
|
|
586
|
+
const hint = Number(status.poll_after_seconds ?? status.next?.poll_after_seconds);
|
|
587
|
+
const pause = Math.min((hint > 0 ? Math.min(hint, 300) : POLL_AFTER_SECONDS) * 1000, Math.max(0, deadline - ctx.now()));
|
|
588
|
+
if (pause > 0) await ctx.sleep(pause);
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
async function reportStatus(ctx, client, status, { json, timedOutAfterMs }) {
|
|
594
|
+
const code = exitCodeForOutcome(status.outcome);
|
|
595
|
+
if (json) {
|
|
596
|
+
ctx.out(`${jsonText({ ...status, exit_code: code })}\n`);
|
|
597
|
+
return code;
|
|
598
|
+
}
|
|
599
|
+
let fixes;
|
|
600
|
+
if (isTerminalOutcome(status.outcome) && count(status.suggested_fix_count) > 0) {
|
|
601
|
+
try {
|
|
602
|
+
const page = await readTool(ctx, client, TOOLS.results, { assessment_id: status.assessment_id, sections: ['fixes'], limit: 10 });
|
|
603
|
+
fixes = list(page?.suggested_fixes);
|
|
604
|
+
} catch (error) {
|
|
605
|
+
ctx.err(`cueapril: could not read the suggested fixes: ${describeError(error)}\n`);
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
ctx.out(renderStatus(status, { fixes, timedOutAfterMs }));
|
|
609
|
+
return code;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
async function waitAndReport(ctx, client, assessmentId, { started, deadline, json }) {
|
|
613
|
+
const progress = createProgress(ctx);
|
|
614
|
+
let latest;
|
|
615
|
+
progress.start(
|
|
616
|
+
() => `still waiting for assessment ${assessmentId}${latest ? ` (${oneLine(latest.outcome, 40)}, ${oneLine(latest.lifecycle ?? 'unknown', 40)})` : ''}; ${formatDuration(ctx.now() - started)} elapsed`,
|
|
617
|
+
);
|
|
618
|
+
try {
|
|
619
|
+
const result = await waitForTerminal(ctx, client, assessmentId, { started, deadline, progress, onStatus: (status) => (latest = status) });
|
|
620
|
+
if (!result.timedOut) return await reportStatus(ctx, client, result.status, { json });
|
|
621
|
+
if (!result.status) throw result.lastError ?? new CliError('The timeout passed before CueApril answered.');
|
|
622
|
+
if (result.lastError) ctx.err(`cueapril: the last status request failed: ${describeError(result.lastError)}\n`);
|
|
623
|
+
return await reportStatus(ctx, client, result.status, { json, timedOutAfterMs: ctx.now() - started });
|
|
624
|
+
} finally {
|
|
625
|
+
progress.stop();
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
// ---------------------------------------------------------------- commands
|
|
630
|
+
|
|
631
|
+
async function assess(ctx, options) {
|
|
632
|
+
if (options.pr === undefined) throw new UsageError('--pr is required');
|
|
633
|
+
if (options.timeout !== undefined && !options.wait) throw new UsageError('--timeout applies only with --wait');
|
|
634
|
+
const body = pullRequestTarget(options.pr);
|
|
635
|
+
if (options.project !== undefined) body.project_id = idValue(options.project, '--project');
|
|
636
|
+
if (options['idempotency-key'] !== undefined) body.idempotency_key = idempotencyKey(options['idempotency-key']);
|
|
637
|
+
const limit = waitLimitMs(options.timeout);
|
|
638
|
+
const client = await agentClient(ctx);
|
|
639
|
+
const started = ctx.now();
|
|
640
|
+
let result;
|
|
641
|
+
try {
|
|
642
|
+
// Safe to resend: the same key, or the key the server derives from the pull request head.
|
|
643
|
+
result = await retrying(
|
|
644
|
+
() => client.callTool(TOOLS.start, body, { idempotencyKey: body.idempotency_key, timeoutMs: START_TIMEOUT_MS }),
|
|
645
|
+
{
|
|
646
|
+
attempts: START_ATTEMPTS,
|
|
647
|
+
sleep: ctx.sleep,
|
|
648
|
+
onRetry: (error, delay) => ctx.err(`cueapril: ${transientText(error)}; sending the same start request again in ${formatDuration(delay)}\n`),
|
|
649
|
+
},
|
|
650
|
+
);
|
|
651
|
+
} catch (error) {
|
|
652
|
+
if (!(error instanceof QualityApiError && error.body?.status === 'blocked')) throw error;
|
|
653
|
+
result = error.body;
|
|
654
|
+
}
|
|
655
|
+
if (result?.status === 'blocked') {
|
|
656
|
+
if (options.json) ctx.out(`${jsonText({ ...result, exit_code: EXIT_CODES.blocked })}\n`);
|
|
657
|
+
else ctx.out(renderBlocked(result));
|
|
658
|
+
return EXIT_CODES.blocked;
|
|
659
|
+
}
|
|
660
|
+
if (result?.status !== 'accepted' || typeof result.assessment_id !== 'string' || !ID_PATTERN.test(result.assessment_id) || typeof result.outcome !== 'string')
|
|
661
|
+
throw new CliError('The API returned an unexpected start response');
|
|
662
|
+
if (!options.wait) {
|
|
663
|
+
const code = exitCodeForOutcome(result.outcome);
|
|
664
|
+
if (options.json) ctx.out(`${jsonText({ ...result, exit_code: code })}\n`);
|
|
665
|
+
else ctx.out(renderAccepted(result));
|
|
666
|
+
return code;
|
|
667
|
+
}
|
|
668
|
+
const pr = result.pull_request ?? {};
|
|
669
|
+
ctx.err(
|
|
670
|
+
`cueapril: ${result.duplicate ? 'found existing' : 'accepted'} assessment ${result.assessment_id} for pull request #${oneLine(pr.number ?? '?', 20)}${pr.head_sha ? ` (head ${oneLine(pr.head_sha, 64).slice(0, 12)})` : ''}; waiting up to ${formatDuration(limit)}\n`,
|
|
671
|
+
);
|
|
672
|
+
try {
|
|
673
|
+
return await waitAndReport(ctx, client, result.assessment_id, { started, deadline: started + limit, json: options.json });
|
|
674
|
+
} catch (error) {
|
|
675
|
+
if (error && typeof error === 'object') error.assessmentId = result.assessment_id;
|
|
676
|
+
throw error;
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
async function status(ctx, options, positionals) {
|
|
681
|
+
const selectors = [positionals.length > 0, options.pr !== undefined, options.commit !== undefined].filter(Boolean).length;
|
|
682
|
+
if (selectors !== 1) throw new UsageError('Give exactly one of <assessment-id>, --pr <number> or --commit <full-sha>');
|
|
683
|
+
if (options.project !== undefined && positionals.length) throw new UsageError('--project applies only with --pr or --commit');
|
|
684
|
+
// The server needs project_id for a pull request or commit when the key covers several projects.
|
|
685
|
+
const project = options.project !== undefined ? { project_id: idValue(options.project, '--project') } : {};
|
|
686
|
+
let args;
|
|
687
|
+
if (positionals.length) args = { assessment_id: idValue(positionals[0], 'The assessment ID') };
|
|
688
|
+
else if (options.pr !== undefined) {
|
|
689
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(options.pr)) throw new UsageError('status --pr takes a pull request number; add --project when several projects share it');
|
|
690
|
+
args = { pull_request: pullRequestNumber(options.pr), ...project };
|
|
691
|
+
} else args = { commit_sha: commitSha(options.commit), ...project };
|
|
692
|
+
const client = await agentClient(ctx);
|
|
693
|
+
const result = assertAssessment(await readTool(ctx, client, TOOLS.get, args));
|
|
694
|
+
return reportStatus(ctx, client, result, { json: options.json });
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
async function wait(ctx, options, positionals) {
|
|
698
|
+
const id = idValue(positionals[0], 'The assessment ID');
|
|
699
|
+
const limit = waitLimitMs(options.timeout);
|
|
700
|
+
const client = await agentClient(ctx);
|
|
701
|
+
const started = ctx.now();
|
|
702
|
+
return waitAndReport(ctx, client, id, { started, deadline: started + limit, json: options.json });
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
function mergeById(target, items, key) {
|
|
706
|
+
const seen = new Set(target.map((item) => (item && typeof item === 'object' ? JSON.stringify(item[key] ?? item) : JSON.stringify(item))));
|
|
707
|
+
for (const item of items) {
|
|
708
|
+
const identity = item && typeof item === 'object' ? JSON.stringify(item[key] ?? item) : JSON.stringify(item);
|
|
709
|
+
if (!seen.has(identity)) {
|
|
710
|
+
seen.add(identity);
|
|
711
|
+
target.push(item);
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
function assertResults(page) {
|
|
717
|
+
if (!page || typeof page !== 'object' || Array.isArray(page)) throw new CliError('The API returned an unexpected results response');
|
|
718
|
+
assertAssessment(page.assessment);
|
|
719
|
+
return page;
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
async function results(ctx, options, positionals) {
|
|
723
|
+
const id = idValue(positionals[0], 'The assessment ID');
|
|
724
|
+
const limit = options.limit === undefined ? undefined : boundedInteger(options.limit, '--limit', 1, 50);
|
|
725
|
+
const base = { assessment_id: id, ...(options.sections !== undefined ? { sections: sections(options.sections) } : {}) };
|
|
726
|
+
const pageSize = options.all ? (limit ?? 50) : limit;
|
|
727
|
+
const client = await agentClient(ctx);
|
|
728
|
+
let page = assertResults(await readTool(ctx, client, TOOLS.results, { ...base, ...(pageSize ? { limit: pageSize } : {}) }));
|
|
729
|
+
if (options.all) {
|
|
730
|
+
const merged = { ...page };
|
|
731
|
+
for (const field of ['findings', 'suggested_fixes', 'coverage', 'evidence']) if (page[field] !== undefined) merged[field] = [...list(page[field])];
|
|
732
|
+
const cursors = new Set();
|
|
733
|
+
let pages = 1;
|
|
734
|
+
while (typeof page.next_cursor === 'string' && page.next_cursor) {
|
|
735
|
+
if (cursors.has(page.next_cursor) || pages >= MAX_RESULT_PAGES) throw new CliError('The API kept returning more result pages; stopped reading.');
|
|
736
|
+
cursors.add(page.next_cursor);
|
|
737
|
+
page = assertResults(await readTool(ctx, client, TOOLS.results, { ...base, limit: pageSize, cursor: page.next_cursor }));
|
|
738
|
+
pages += 1;
|
|
739
|
+
merged.assessment = page.assessment;
|
|
740
|
+
for (const [field, key] of [['findings', 'id'], ['suggested_fixes', 'id'], ['evidence', 'id'], ['coverage', 'method']])
|
|
741
|
+
if (page[field] !== undefined) mergeById((merged[field] ??= []), list(page[field]), key);
|
|
742
|
+
}
|
|
743
|
+
delete merged.next_cursor;
|
|
744
|
+
page = merged;
|
|
745
|
+
}
|
|
746
|
+
const code = exitCodeForOutcome(page.assessment.outcome);
|
|
747
|
+
if (options.json) ctx.out(`${jsonText({ ...page, exit_code: code })}\n`);
|
|
748
|
+
else ctx.out(renderResults(page));
|
|
749
|
+
return code;
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
async function cancel(ctx, options, positionals) {
|
|
753
|
+
const args = { assessment_id: idValue(positionals[0], 'The assessment ID') };
|
|
754
|
+
if (options.reason !== undefined) {
|
|
755
|
+
if (!options.reason.trim() || options.reason.length > 1000) throw new UsageError('--reason must be 1 to 1000 characters');
|
|
756
|
+
args.reason = options.reason;
|
|
757
|
+
}
|
|
758
|
+
if (options['idempotency-key'] !== undefined) args.idempotency_key = idempotencyKey(options['idempotency-key']);
|
|
759
|
+
const client = await agentClient(ctx);
|
|
760
|
+
let result;
|
|
761
|
+
try {
|
|
762
|
+
// A mutation: never resent automatically.
|
|
763
|
+
result = await client.callTool(TOOLS.cancel, args, { idempotencyKey: args.idempotency_key });
|
|
764
|
+
} catch (error) {
|
|
765
|
+
if (isTransientError(error) && error && typeof error === 'object')
|
|
766
|
+
error.hint = `The cancel request may or may not have reached CueApril. Check with "cueapril status ${args.assessment_id}" and run cancel again if needed.`;
|
|
767
|
+
throw error;
|
|
768
|
+
}
|
|
769
|
+
if (!result || typeof result !== 'object' || Array.isArray(result)) throw new CliError('The API returned an unexpected cancel response');
|
|
770
|
+
if (options.json) ctx.out(`${jsonText({ ...result, exit_code: 0 })}\n`);
|
|
771
|
+
else
|
|
772
|
+
ctx.out(
|
|
773
|
+
`Cancel requested for assessment ${oneLine(result.assessment_id ?? args.assessment_id, 200)}: outcome ${oneLine(result.outcome ?? 'unknown', 40)}, lifecycle ${oneLine(result.lifecycle ?? 'unknown', 40)}.\n Next: cueapril status ${args.assessment_id}\n`,
|
|
774
|
+
);
|
|
775
|
+
return 0;
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
async function setup(ctx, options) {
|
|
779
|
+
const args = options.project !== undefined ? { project_id: idValue(options.project, '--project') } : {};
|
|
780
|
+
const client = await agentClient(ctx);
|
|
781
|
+
const result = await readTool(ctx, client, TOOLS.checkSetup, args);
|
|
782
|
+
if (!result || typeof result !== 'object' || typeof result.ready !== 'boolean') throw new CliError('The API returned an unexpected setup response');
|
|
783
|
+
const code = result.ready ? 0 : EXIT_CODES.blocked;
|
|
784
|
+
if (options.json) {
|
|
785
|
+
ctx.out(`${jsonText({ ...result, exit_code: code })}\n`);
|
|
786
|
+
return code;
|
|
787
|
+
}
|
|
788
|
+
const project = [result.project_name ? oneLine(result.project_name, 200) : '', result.project_id ? `(${oneLine(result.project_id, 200)})` : ''].filter(Boolean).join(' ');
|
|
789
|
+
const lines = [`CueApril setup${project ? ` for ${project}` : ''}${result.repository ? `, repository ${oneLine(result.repository, 300)}` : ''}: ${result.ready ? 'ready' : 'not ready'}`];
|
|
790
|
+
for (const check of list(result.checks)) {
|
|
791
|
+
lines.push(
|
|
792
|
+
` ${check?.ok ? 'ok ' : 'FAIL'} ${oneLine(check?.code ?? 'check', 80)}${check?.owner && !check?.ok ? ` (${oneLine(check.owner, 20)})` : ''}: ${oneLine(check?.message ?? '', 500)}`,
|
|
793
|
+
);
|
|
794
|
+
if (check?.fix_url && !check?.ok) lines.push(` Fix: ${oneLine(check.fix_url, 300)}`);
|
|
795
|
+
}
|
|
796
|
+
if (result.next_step) lines.push(` Next: ${oneLine(result.next_step, 500)}`);
|
|
797
|
+
ctx.out(`${lines.join('\n')}\n`);
|
|
798
|
+
return code;
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
async function listAssessments(ctx, options) {
|
|
802
|
+
const args = {};
|
|
803
|
+
if (options.project !== undefined) args.project_id = idValue(options.project, '--project');
|
|
804
|
+
if (options.pr !== undefined) args.pull_request = pullRequestNumber(options.pr);
|
|
805
|
+
if (options.limit !== undefined) args.limit = boundedInteger(options.limit, '--limit', 1, 20);
|
|
806
|
+
const client = await agentClient(ctx);
|
|
807
|
+
const result = await readTool(ctx, client, TOOLS.list, args);
|
|
808
|
+
if (!result || !Array.isArray(result.assessments)) throw new CliError('The API returned an unexpected assessment list');
|
|
809
|
+
if (options.json) {
|
|
810
|
+
ctx.out(`${jsonText({ ...result, exit_code: 0 })}\n`);
|
|
811
|
+
return 0;
|
|
812
|
+
}
|
|
813
|
+
if (!result.assessments.length) {
|
|
814
|
+
ctx.out('No assessments found.\n');
|
|
815
|
+
return 0;
|
|
816
|
+
}
|
|
817
|
+
const rows = result.assessments.map((item) => {
|
|
818
|
+
const pr = item?.pull_request && typeof item.pull_request === 'object' ? item.pull_request.number : item?.pull_request;
|
|
819
|
+
return [
|
|
820
|
+
oneLine(item?.assessment_id ?? '', 200),
|
|
821
|
+
oneLine(item?.outcome ?? '', 20),
|
|
822
|
+
oneLine(item?.lifecycle ?? '', 30),
|
|
823
|
+
pr === undefined || pr === null ? '-' : `#${oneLine(pr, 20)}`,
|
|
824
|
+
oneLine(item?.head_sha ?? '', 64).slice(0, 12) || '-',
|
|
825
|
+
oneLine(item?.created_at ?? '', 40),
|
|
826
|
+
];
|
|
827
|
+
});
|
|
828
|
+
ctx.out(table(['ASSESSMENT', 'OUTCOME', 'LIFECYCLE', 'PR', 'COMMIT', 'CREATED'], rows));
|
|
829
|
+
return 0;
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
async function projects(ctx, options) {
|
|
833
|
+
const client = await agentClient(ctx);
|
|
834
|
+
const result = await readTool(ctx, client, TOOLS.projects, {});
|
|
835
|
+
const items = Array.isArray(result) ? result : Array.isArray(result?.items) ? result.items : Array.isArray(result?.projects) ? result.projects : undefined;
|
|
836
|
+
if (!items) throw new CliError('The API returned an unexpected project list');
|
|
837
|
+
if (options.json) {
|
|
838
|
+
ctx.out(`${jsonText({ projects: items, exit_code: 0 })}\n`);
|
|
839
|
+
return 0;
|
|
840
|
+
}
|
|
841
|
+
if (!items.length) {
|
|
842
|
+
ctx.out('No projects are visible to this key.\n');
|
|
843
|
+
return 0;
|
|
844
|
+
}
|
|
845
|
+
const rows = items.map((item) => [oneLine(item?.id ?? '', 200), oneLine(item?.name ?? '', 120), oneLine(item?.repository_url ?? item?.repository ?? '', 300) || '-']);
|
|
846
|
+
ctx.out(table(['PROJECT', 'NAME', 'REPOSITORY'], rows));
|
|
847
|
+
return 0;
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
const prettyJson = (value) => `${jsonText(value, 2)}\n`;
|
|
851
|
+
const tomlString = (value) => `"${value.replace(/[\\"]/g, (character) => `\\${character}`)}"`;
|
|
852
|
+
/** Each snippet reads the key from CUEAPRIL_API_KEY when the client starts; the key itself is never written out. */
|
|
853
|
+
export const MCP_CLIENTS = Object.freeze({
|
|
854
|
+
claude: {
|
|
855
|
+
label: 'Claude Code',
|
|
856
|
+
file: '.mcp.json in the repository root',
|
|
857
|
+
format: 'json',
|
|
858
|
+
snippet: (url) => prettyJson({ mcpServers: { cueapril: { type: 'http', url, headers: { Authorization: 'Bearer ${CUEAPRIL_API_KEY}' } } } }),
|
|
859
|
+
hint: (url) => `Or run: claude mcp add --scope project --transport http cueapril ${url} --header 'Authorization: Bearer \${CUEAPRIL_API_KEY}'`,
|
|
860
|
+
},
|
|
861
|
+
codex: {
|
|
862
|
+
label: 'Codex',
|
|
863
|
+
file: '~/.codex/config.toml',
|
|
864
|
+
format: 'toml',
|
|
865
|
+
// TOML refuses a table defined twice, so this is merged by hand, never appended to the file.
|
|
866
|
+
merge: true,
|
|
867
|
+
snippet: (url) =>
|
|
868
|
+
[
|
|
869
|
+
'# Merge into ~/.codex/config.toml by hand, or run: cueapril init --agents codex',
|
|
870
|
+
'# If the file already has [mcp_servers.cueapril], edit that table: a second copy stops Codex from starting.',
|
|
871
|
+
'[mcp_servers.cueapril]',
|
|
872
|
+
`url = ${tomlString(url)}`,
|
|
873
|
+
'bearer_token_env_var = "CUEAPRIL_API_KEY"',
|
|
874
|
+
`tool_timeout_sec = ${CODEX_TOOL_TIMEOUT_SEC}`,
|
|
875
|
+
'',
|
|
876
|
+
'[mcp_servers.cueapril.tools.cueapril_start_assessment]',
|
|
877
|
+
'approval_mode = "approve"',
|
|
878
|
+
'',
|
|
879
|
+
].join('\n'),
|
|
880
|
+
hint: () => '`cueapril init --agents codex` edits ~/.codex/config.toml in place and is safe to rerun. Never append this output to the file.',
|
|
881
|
+
},
|
|
882
|
+
gemini: {
|
|
883
|
+
label: 'Gemini CLI',
|
|
884
|
+
file: '~/.gemini/settings.json, or .gemini/settings.json in the repository',
|
|
885
|
+
format: 'json',
|
|
886
|
+
snippet: (url) => prettyJson({ mcpServers: { cueapril: { httpUrl: url, headers: { Authorization: 'Bearer ${CUEAPRIL_API_KEY}' } } } }),
|
|
887
|
+
},
|
|
888
|
+
cursor: {
|
|
889
|
+
label: 'Cursor',
|
|
890
|
+
file: '~/.cursor/mcp.json, or .cursor/mcp.json in the repository',
|
|
891
|
+
format: 'json',
|
|
892
|
+
snippet: (url) => prettyJson({ mcpServers: { cueapril: { url, headers: { Authorization: 'Bearer ${env:CUEAPRIL_API_KEY}' } } } }),
|
|
893
|
+
},
|
|
894
|
+
vscode: {
|
|
895
|
+
label: 'VS Code',
|
|
896
|
+
file: '.vscode/mcp.json',
|
|
897
|
+
format: 'json',
|
|
898
|
+
snippet: (url) => prettyJson({ servers: { cueapril: { type: 'http', url, headers: { Authorization: 'Bearer ${env:CUEAPRIL_API_KEY}' } } } }),
|
|
899
|
+
},
|
|
900
|
+
});
|
|
901
|
+
|
|
902
|
+
/** The Codex config.toml when it already defines a CueApril server (read from this context's HOME), else null. */
|
|
903
|
+
async function existingCodexServer(ctx) {
|
|
904
|
+
const home = ctx.env.HOME || ctx.env.USERPROFILE;
|
|
905
|
+
if (!home) return null;
|
|
906
|
+
const deps = defaultDeps({ env: ctx.env, homedir: () => home });
|
|
907
|
+
try {
|
|
908
|
+
const file = agentConfigPath('codex', deps);
|
|
909
|
+
return codexHasServer(await ctx.readFile(file, 'utf8')) ? displayPath(deps, file) : null;
|
|
910
|
+
} catch {
|
|
911
|
+
return null;
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
async function mcpConfig(ctx, options) {
|
|
916
|
+
if (options.client !== undefined && !Object.hasOwn(MCP_CLIENTS, options.client))
|
|
917
|
+
throw new UsageError(`--client must be one of ${Object.keys(MCP_CLIENTS).join(', ')}`);
|
|
918
|
+
const url = `${normalizeBaseUrl(baseUrl(ctx))}/mcp`;
|
|
919
|
+
const names = options.client === undefined ? Object.keys(MCP_CLIENTS) : [options.client];
|
|
920
|
+
const clients = names.map((name) => ({ client: name, label: MCP_CLIENTS[name].label, file: MCP_CLIENTS[name].file, format: MCP_CLIENTS[name].format, snippet: MCP_CLIENTS[name].snippet(url) }));
|
|
921
|
+
const configured = options.client === 'codex' ? await existingCodexServer(ctx) : null;
|
|
922
|
+
if (configured)
|
|
923
|
+
ctx.err(`cueapril: ${configured} already has an [mcp_servers.cueapril] table. Edit that table instead of adding this one, or run \`cueapril init --agents codex\`.\n`);
|
|
924
|
+
if (options.json) {
|
|
925
|
+
ctx.out(`${jsonText({ mcp_url: url, clients, exit_code: 0 })}\n`);
|
|
926
|
+
return 0;
|
|
927
|
+
}
|
|
928
|
+
if (options.client !== undefined) {
|
|
929
|
+
const chosen = MCP_CLIENTS[options.client];
|
|
930
|
+
ctx.out(clients[0].snippet);
|
|
931
|
+
ctx.err(`cueapril: ${chosen.merge ? 'merge this into' : 'add this to'} ${chosen.file}${chosen.merge ? ' by hand' : ''}. The client reads the key from CUEAPRIL_API_KEY when it starts; the key is never written into the file.\n`);
|
|
932
|
+
if (chosen.hint) ctx.err(`cueapril: ${chosen.hint(url)}\n`);
|
|
933
|
+
return 0;
|
|
934
|
+
}
|
|
935
|
+
const sectionsText = clients.map(({ client, label, file, snippet }) => {
|
|
936
|
+
const hint = MCP_CLIENTS[client].hint;
|
|
937
|
+
return `# ${label}: ${file}\n${snippet}${hint ? `# ${hint(url)}\n` : ''}`;
|
|
938
|
+
});
|
|
939
|
+
ctx.out(`${sectionsText.join('\n')}\n# Each client reads the key from CUEAPRIL_API_KEY when it starts. Print one with --client <name>.\n`);
|
|
940
|
+
return 0;
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
function toolName(value) {
|
|
944
|
+
try {
|
|
945
|
+
return agentToolName(value);
|
|
946
|
+
} catch (error) {
|
|
947
|
+
throw new UsageError(error.message);
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
async function tool(ctx, options, positionals) {
|
|
952
|
+
const name = toolName(positionals[0]);
|
|
953
|
+
if (['data', 'file', 'stdin'].filter((source) => options[source] !== undefined).length > 1) throw new UsageError('Use only one of --data, --file or --stdin');
|
|
954
|
+
const raw = options.file !== undefined ? await ctx.readFile(options.file, 'utf8') : options.data !== undefined ? options.data : options.stdin ? await readStdin(ctx) : '{}';
|
|
955
|
+
const args = parseObject(raw);
|
|
956
|
+
if (options['idempotency-key'] !== undefined) args.idempotency_key = idempotencyKey(options['idempotency-key']);
|
|
957
|
+
const client = await agentClient(ctx);
|
|
958
|
+
// The CLI cannot tell a read from a mutation here, so it never resends.
|
|
959
|
+
const result = await client.callTool(name, args, { idempotencyKey: typeof args.idempotency_key === 'string' ? args.idempotency_key : undefined });
|
|
960
|
+
if (options.json)
|
|
961
|
+
ctx.out(`${jsonText(result && typeof result === 'object' && !Array.isArray(result) ? { ...result, exit_code: 0 } : { result, exit_code: 0 })}\n`);
|
|
962
|
+
else ctx.out(`${jsonText(result, 2)}\n`);
|
|
963
|
+
return 0;
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
// ---------------------------------------------------------------- legacy dotted actions
|
|
967
|
+
|
|
968
|
+
async function legacy(ctx, argv) {
|
|
969
|
+
try {
|
|
970
|
+
const action = argv[0];
|
|
971
|
+
let raw = '{}';
|
|
972
|
+
const file = argv.indexOf('--file');
|
|
973
|
+
const data = argv.indexOf('--data');
|
|
974
|
+
if (file >= 0) raw = await ctx.readFile(argv[file + 1], 'utf8');
|
|
975
|
+
else if (data >= 0) raw = argv[data + 1];
|
|
976
|
+
else if (argv.includes('--stdin')) raw = await readStdin(ctx);
|
|
977
|
+
const args = JSON.parse(raw);
|
|
978
|
+
if (!args || Array.isArray(args) || typeof args !== 'object') throw new Error('Arguments must be an object');
|
|
979
|
+
const key = environmentValue(ctx.env, 'CUEAPRIL_API_KEY', 'TENHAW_TOKEN');
|
|
980
|
+
if (!key) throw new Error('Set CUEAPRIL_API_KEY (or TENHAW_TOKEN)');
|
|
981
|
+
ctx.secret = key.value;
|
|
982
|
+
const client = new QualityClient({ baseUrl: baseUrl(ctx), token: key.value, fetch: ctx.fetch, authMode: ctx.env.TENHAW_AUTH_MODE || 'oauth' });
|
|
983
|
+
const output = argv.indexOf('--output');
|
|
984
|
+
if (output >= 0 && action !== 'developer_review.export') throw new Error('--output is supported only for an approved developer_review.export');
|
|
985
|
+
const result = await client.call(action, args);
|
|
986
|
+
if (output >= 0) {
|
|
987
|
+
const filename = argv[output + 1];
|
|
988
|
+
if (typeof filename !== 'string' || !filename) throw new Error('An output filename is required');
|
|
989
|
+
if (typeof result.content !== 'string' || typeof result.sha256 !== 'string' || createHash('sha256').update(result.content).digest('hex') !== result.sha256)
|
|
990
|
+
throw new Error('Exported patch integrity could not be verified');
|
|
991
|
+
await ctx.writeFile(filename, result.content, { encoding: 'utf8', flag: 'wx' });
|
|
992
|
+
ctx.out(`${jsonText({ filename, sha256: result.sha256, head_sha: result.head_sha, path: result.path, ide: result.ide }, 2)}\n`);
|
|
993
|
+
} else ctx.out(`${jsonText(result, 2)}\n`);
|
|
994
|
+
return 0;
|
|
995
|
+
} catch (error) {
|
|
996
|
+
ctx.err(`${jsonText({ error: String(error?.message ?? error), ...(error instanceof QualityApiError ? { status: error.status } : {}) })}\n`);
|
|
997
|
+
return EXIT_CODES.error;
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
// ---------------------------------------------------------------- help
|
|
1002
|
+
|
|
1003
|
+
const NPX = RUN_COMMAND;
|
|
1004
|
+
const COMMANDS = {
|
|
1005
|
+
assess: {
|
|
1006
|
+
usage: 'assess --pr <number|url> [--project <id>] [--wait] [--timeout <minutes>] [--idempotency-key <key>] [--json]',
|
|
1007
|
+
summary:
|
|
1008
|
+
"Start an assessment of a pull request under the project's approved standing plan. With --wait, wait for the outcome (default 90 minutes) and exit with its code. Sending the same request again for the same pull request head never starts a second run.",
|
|
1009
|
+
flags: { pr: 'value', project: 'value', wait: 'flag', timeout: 'value', 'idempotency-key': 'value', json: 'flag' },
|
|
1010
|
+
positionals: [0, 0],
|
|
1011
|
+
run: assess,
|
|
1012
|
+
},
|
|
1013
|
+
status: {
|
|
1014
|
+
usage: 'status <assessment-id> | status --pr <number> [--project <id>] | status --commit <full-sha> [--project <id>] [--json]',
|
|
1015
|
+
summary:
|
|
1016
|
+
'Show one assessment: outcome, verdict, gate, task counts and the first failures. --commit takes the full 40- or 64-character SHA of the tested head (git rev-parse HEAD).',
|
|
1017
|
+
flags: { pr: 'value', project: 'value', commit: 'value', json: 'flag' },
|
|
1018
|
+
positionals: [0, 1],
|
|
1019
|
+
run: status,
|
|
1020
|
+
},
|
|
1021
|
+
wait: {
|
|
1022
|
+
usage: 'wait <assessment-id> [--timeout <minutes>] [--json]',
|
|
1023
|
+
summary: 'Wait until an assessment finishes (default 90 minutes), reporting progress on stderr at least once a minute.',
|
|
1024
|
+
flags: { timeout: 'value', json: 'flag' },
|
|
1025
|
+
positionals: [1, 1],
|
|
1026
|
+
argument: '<assessment-id>',
|
|
1027
|
+
run: wait,
|
|
1028
|
+
},
|
|
1029
|
+
results: {
|
|
1030
|
+
usage: 'results <assessment-id> [--limit <1-50>] [--all] [--sections findings,fixes,coverage,evidence] [--json]',
|
|
1031
|
+
summary: 'Findings with expected and observed values, suggested fixes, coverage by method and evidence links. --all reads every page.',
|
|
1032
|
+
flags: { limit: 'value', all: 'flag', sections: 'value', json: 'flag' },
|
|
1033
|
+
positionals: [1, 1],
|
|
1034
|
+
argument: '<assessment-id>',
|
|
1035
|
+
run: results,
|
|
1036
|
+
},
|
|
1037
|
+
cancel: {
|
|
1038
|
+
usage: 'cancel <assessment-id> [--reason <text>] [--idempotency-key <key>] [--json]',
|
|
1039
|
+
summary: 'Ask CueApril to stop an assessment. Never sent twice automatically.',
|
|
1040
|
+
flags: { reason: 'value', 'idempotency-key': 'value', json: 'flag' },
|
|
1041
|
+
positionals: [1, 1],
|
|
1042
|
+
argument: '<assessment-id>',
|
|
1043
|
+
run: cancel,
|
|
1044
|
+
},
|
|
1045
|
+
setup: {
|
|
1046
|
+
usage: 'setup [--project <id>] [--json]',
|
|
1047
|
+
summary: 'Check that a project is ready to assess pull requests, and what to fix if not.',
|
|
1048
|
+
flags: { project: 'value', json: 'flag' },
|
|
1049
|
+
positionals: [0, 0],
|
|
1050
|
+
run: setup,
|
|
1051
|
+
},
|
|
1052
|
+
list: {
|
|
1053
|
+
usage: 'list [--project <id>] [--pr <number>] [--limit <1-20>] [--json]',
|
|
1054
|
+
summary: 'Recent assessments.',
|
|
1055
|
+
flags: { project: 'value', pr: 'value', limit: 'value', json: 'flag' },
|
|
1056
|
+
positionals: [0, 0],
|
|
1057
|
+
run: listAssessments,
|
|
1058
|
+
},
|
|
1059
|
+
projects: {
|
|
1060
|
+
usage: 'projects [--json]',
|
|
1061
|
+
summary: 'Projects this key can see.',
|
|
1062
|
+
flags: { json: 'flag' },
|
|
1063
|
+
positionals: [0, 0],
|
|
1064
|
+
run: projects,
|
|
1065
|
+
},
|
|
1066
|
+
'mcp-config': {
|
|
1067
|
+
usage: 'mcp-config [--client claude|codex|gemini|cursor|vscode] [--json]',
|
|
1068
|
+
summary: 'Print MCP client configuration that reads the key from CUEAPRIL_API_KEY. Makes no network request.',
|
|
1069
|
+
flags: { client: 'value', json: 'flag' },
|
|
1070
|
+
positionals: [0, 0],
|
|
1071
|
+
run: mcpConfig,
|
|
1072
|
+
},
|
|
1073
|
+
tool: {
|
|
1074
|
+
usage: "tool <tool-name> [--data '<json>' | --file <path> | --stdin] [--idempotency-key <key>] [--json]",
|
|
1075
|
+
summary: 'Call any CueApril agent tool by name, for example cueapril_get_run or get_run. Never sent twice automatically.',
|
|
1076
|
+
flags: { data: 'value', file: 'value', stdin: 'flag', 'idempotency-key': 'value', json: 'flag' },
|
|
1077
|
+
positionals: [1, 1],
|
|
1078
|
+
argument: '<tool-name>',
|
|
1079
|
+
run: tool,
|
|
1080
|
+
},
|
|
1081
|
+
};
|
|
1082
|
+
|
|
1083
|
+
export function helpText() {
|
|
1084
|
+
const commands = Object.values(COMMANDS)
|
|
1085
|
+
.map(({ usage, summary }) => ` cueapril ${usage}\n ${summary}`)
|
|
1086
|
+
.join('\n');
|
|
1087
|
+
return `CueApril CLI ${CLI_VERSION}: assess pull requests with CueApril from a terminal, a coding agent or CI.
|
|
1088
|
+
|
|
1089
|
+
Usage: cueapril <command> [options]
|
|
1090
|
+
|
|
1091
|
+
Setup (a coding agent can run these itself; a person approves once in the browser):
|
|
1092
|
+
cueapril init [--agents auto|claude,codex,gemini,cursor] [--scope user|project]
|
|
1093
|
+
Get a key by browser approval if none is stored, check readiness, configure Claude Code,
|
|
1094
|
+
Codex, Gemini CLI and Cursor at user level, and install the cueapril-qa skill.
|
|
1095
|
+
--no-login --json returns auth_required with next_actions when a key is missing.
|
|
1096
|
+
--key-stdin verifies and stores an existing key from a pipe; --no-wait returns an approval link.
|
|
1097
|
+
cueapril login [--name <label>] [--no-browser] [--no-wait]
|
|
1098
|
+
Approve an agent key in the browser and store it for this user (never printed).
|
|
1099
|
+
Or use login --key-stdin to import a key from a secret manager's output.
|
|
1100
|
+
cueapril doctor [--project <id>]
|
|
1101
|
+
Check the API, the key, readiness, agent configuration and the skill.
|
|
1102
|
+
cueapril logout
|
|
1103
|
+
Revoke the stored key on CueApril and delete it here.
|
|
1104
|
+
|
|
1105
|
+
Commands:
|
|
1106
|
+
${commands}
|
|
1107
|
+
cueapril help [<command> | legacy]
|
|
1108
|
+
Help for one command, or for the older dotted actions (cueapril runs.get --data '{"id":"..."}').
|
|
1109
|
+
|
|
1110
|
+
Options:
|
|
1111
|
+
--json Print exactly one JSON object on stdout: the final tool result plus "exit_code".
|
|
1112
|
+
Progress and errors always go to stderr.
|
|
1113
|
+
--help Show help.
|
|
1114
|
+
--version Print the version.
|
|
1115
|
+
|
|
1116
|
+
Environment:
|
|
1117
|
+
CUEAPRIL_API_KEY Agent key (cueapril_sk_...). Falls back to TENHAW_TOKEN, then to the key
|
|
1118
|
+
stored by \`cueapril login\` or \`init\`. Never printed.
|
|
1119
|
+
CUEAPRIL_URL API origin. Default ${DEFAULT_BASE_URL}. Falls back to TENHAW_URL.
|
|
1120
|
+
HTTPS only, except http://localhost. Redirects are refused.
|
|
1121
|
+
|
|
1122
|
+
Exit codes:
|
|
1123
|
+
0 passed
|
|
1124
|
+
1 failed: a check failed or the gate blocked the pull request
|
|
1125
|
+
2 incomplete or cancelled: CueApril could not finish; not a product failure
|
|
1126
|
+
3 blocked: the start was refused, or setup is not ready
|
|
1127
|
+
4 still running: --timeout passed, or the command did not wait
|
|
1128
|
+
5 usage, authentication or API error
|
|
1129
|
+
assess, status, wait and results exit 0 only when the assessment passed. cancel, list,
|
|
1130
|
+
projects, mcp-config and tool exit 0 when the request succeeded.
|
|
1131
|
+
|
|
1132
|
+
Retries: reads are retried after network errors and 429, 502, 503, 504, 522 and 524.
|
|
1133
|
+
assess resends the identical request, with the same idempotency key or none (the server
|
|
1134
|
+
derives one from the pull request head), so a retry never starts a second run. cancel and
|
|
1135
|
+
tool are never resent.
|
|
1136
|
+
|
|
1137
|
+
Examples:
|
|
1138
|
+
# Coding agent: start, wait and branch on the exit code or the JSON
|
|
1139
|
+
export CUEAPRIL_API_KEY=cueapril_sk_...
|
|
1140
|
+
${NPX} assess --pr 42 --wait --json
|
|
1141
|
+
|
|
1142
|
+
# Later, from any session
|
|
1143
|
+
${NPX} status --pr 42
|
|
1144
|
+
${NPX} results <assessment-id> --all
|
|
1145
|
+
|
|
1146
|
+
# Agent shells that stop long commands: wait in slices; exit 4 means still running
|
|
1147
|
+
${NPX} wait <assessment-id> --timeout 4
|
|
1148
|
+
|
|
1149
|
+
# Connect an MCP client instead: init edits each agent's user settings in place, safely
|
|
1150
|
+
${NPX} init --agents codex
|
|
1151
|
+
# Or print a client's configuration and merge it by hand (never append it to the file)
|
|
1152
|
+
${NPX} mcp-config --client codex
|
|
1153
|
+
|
|
1154
|
+
# GitHub Actions step (pull_request event)
|
|
1155
|
+
- name: CueApril assessment
|
|
1156
|
+
timeout-minutes: 100
|
|
1157
|
+
env:
|
|
1158
|
+
CUEAPRIL_API_KEY: \${{ secrets.CUEAPRIL_API_KEY }}
|
|
1159
|
+
run: ${NPX} assess --pr \${{ github.event.pull_request.number }} --wait --timeout 90
|
|
1160
|
+
`;
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
function commandHelp(name) {
|
|
1164
|
+
const { usage, summary, flags } = COMMANDS[name];
|
|
1165
|
+
return `Usage: cueapril ${usage}\n\n${summary}\n\nOptions: ${Object.keys(flags)
|
|
1166
|
+
.map((flag) => `--${flag}`)
|
|
1167
|
+
.join(', ')}\nRun "cueapril --help" for the environment, exit codes and examples.\n`;
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
export const LEGACY_HELP = `Legacy dotted actions: cueapril <action> [--data JSON | --file path | --stdin]
|
|
1171
|
+
(the same actions also run as tenhaw-quality <action>).
|
|
1172
|
+
|
|
1173
|
+
Source review (native human authentication): developer_review.list/context/thread/comment/patch/approve/export. Mutations require an explicit stable idempotency_key. Use developer_review.export --data JSON --output reviewed.patch to save an independently approved patch after integrity verification; existing files are preserved.
|
|
1174
|
+
|
|
1175
|
+
Actions: rollout.get/inventory/checklist/connections/transition/deprecations (human org admin only), runs.telemetry, telemetry.sessions.start/pause/resume/finish (recorded human elapsed only), runner_pools.keys.get, runner_pools.keys.prepare/activate/retire/cancel (human org admin only), reuse.inspect/record/list, reuse.policies.list/create/revise/pause/resume (policy changes human), reruns.propose/draft/start, library.lineage/replacement (replacement human), first_assessments.readiness/start/report, samples.list/activate (activation native human), performance.campaign_quote, performance.browser_quote, performance.weighted_http_quote, quarantines.list / quarantines.create / quarantines.revise / quarantines.reassign / quarantines.pause / quarantines.resume / quarantines.close / performance.compare, clarifications.assess/assessments, locator_repairs.list/get/export, locator_repairs.create/approve/validate/revoke (native human), evaluations.list/get/export (finance read), evaluations.create/revise/approve/observe/close (human only),
|
|
1176
|
+
context.impacts, context.impacts.repair, sources.withdraw (human only), forecast.scenario, resources.list/resolve,
|
|
1177
|
+
setup.propose, setup.get, setup.apply, reports.catalog, reports.list, reports.get,
|
|
1178
|
+
reports.export, reports.assemble, reports.revise/sign/revoke (human only),
|
|
1179
|
+
waivers.list/get/request/approve/revoke/close (risk decisions human only), releases.components.get, releases.components.verify,
|
|
1180
|
+
releases.components.approve (human only), knowledge.overview, knowledge.search, knowledge.get, missions.readiness,
|
|
1181
|
+
missions.start, missions.report, projects.list, projects.get, library.list, library.get, library.create,
|
|
1182
|
+
standards.list, plans.get, plans.propose, plans.create, estimates.create, runs.create, runs.get,
|
|
1183
|
+
runs.events, runs.cancel, findings.list, findings.retest, findings.verify, findings.regression, evidence.get, coverage.get,
|
|
1184
|
+
costs.get, performance.quote, performance.purchase.
|
|
1185
|
+
|
|
1186
|
+
By default an action calls the cueapril_ agent tool of the same name through POST /api/v1/quality/agent-tools/<tool>,
|
|
1187
|
+
authenticated by CUEAPRIL_API_KEY (or TENHAW_TOKEN, which may hold an MCP-audience OAuth access token). Set
|
|
1188
|
+
TENHAW_AUTH_MODE=human to call the native REST routes with a signed-in person's session token instead. Mutations
|
|
1189
|
+
accept idempotency_key in JSON; use the same key when retrying an uncertain outcome. Errors print a JSON object on
|
|
1190
|
+
stderr and exit 5.
|
|
1191
|
+
Example: cueapril runs.get --data '{"id":"run-id"}'
|
|
1192
|
+
`;
|
|
1193
|
+
|
|
1194
|
+
// ---------------------------------------------------------------- entry point
|
|
1195
|
+
|
|
1196
|
+
/**
|
|
1197
|
+
* Runs one CLI invocation and resolves to its exit code. `io` replaces process
|
|
1198
|
+
* state in tests: env, fetch, stdout, stderr, stdin, now, sleep, setInterval,
|
|
1199
|
+
* clearInterval, readFile and writeFile.
|
|
1200
|
+
*/
|
|
1201
|
+
const SELF_INSTALL = {
|
|
1202
|
+
init: { run: (argv, deps) => runInit(argv, deps), usage: INIT_USAGE },
|
|
1203
|
+
login: { run: (argv, deps) => runLogin(argv, deps), usage: LOGIN_USAGE },
|
|
1204
|
+
logout: { run: (argv, deps) => runLogout(argv, deps), usage: LOGOUT_USAGE },
|
|
1205
|
+
doctor: { run: (argv, deps) => runDoctor(argv, deps), usage: DOCTOR_USAGE },
|
|
1206
|
+
};
|
|
1207
|
+
|
|
1208
|
+
/**
|
|
1209
|
+
* Setup commands parse their own flags; their output streams keep the CLI's
|
|
1210
|
+
* redaction. A caller that replaces stdout or stderr says whether it is a
|
|
1211
|
+
* terminal with an isTTY property on that function (absent means not a terminal).
|
|
1212
|
+
*/
|
|
1213
|
+
async function runSelfInstall(ctx, io, command, argv) {
|
|
1214
|
+
const deps = {
|
|
1215
|
+
...(io.selfInstallDeps ?? {}),
|
|
1216
|
+
env: ctx.env,
|
|
1217
|
+
...(ctx.fetch ? { fetch: ctx.fetch } : {}),
|
|
1218
|
+
stdout: { write: (text) => ctx.out(String(text)), isTTY: Boolean((io.stdout ?? process.stdout).isTTY) },
|
|
1219
|
+
stderr: { write: (text) => ctx.err(String(text)), isTTY: Boolean((io.stderr ?? process.stderr).isTTY) },
|
|
1220
|
+
};
|
|
1221
|
+
try {
|
|
1222
|
+
const result = await SELF_INSTALL[command].run(argv, deps);
|
|
1223
|
+
return Number.isInteger(result?.exitCode) ? result.exitCode : 5;
|
|
1224
|
+
} catch (error) {
|
|
1225
|
+
return fail(ctx, error, { json: argv.includes('--json'), command });
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
export async function main(argv, io = {}) {
|
|
1230
|
+
const ctx = context(io);
|
|
1231
|
+
const [command, ...rest] = argv;
|
|
1232
|
+
if (command === undefined || command === '--help' || command === '-h') {
|
|
1233
|
+
ctx.out(helpText());
|
|
1234
|
+
return 0;
|
|
1235
|
+
}
|
|
1236
|
+
if (command === '--version' || command === '-v' || command === 'version') {
|
|
1237
|
+
ctx.out(`${CLI_VERSION}\n`);
|
|
1238
|
+
return 0;
|
|
1239
|
+
}
|
|
1240
|
+
if (command === 'help') {
|
|
1241
|
+
const topic = rest[0];
|
|
1242
|
+
if (topic === undefined) ctx.out(helpText());
|
|
1243
|
+
else if (topic === 'legacy') ctx.out(LEGACY_HELP);
|
|
1244
|
+
else if (Object.hasOwn(SELF_INSTALL, topic)) ctx.out(`${SELF_INSTALL[topic].usage}\n`);
|
|
1245
|
+
else if (Object.hasOwn(COMMANDS, topic)) ctx.out(commandHelp(topic));
|
|
1246
|
+
else return fail(ctx, new UsageError(`No help for "${oneLine(topic, 60)}"`));
|
|
1247
|
+
return 0;
|
|
1248
|
+
}
|
|
1249
|
+
if (Object.hasOwn(SELF_INSTALL, command)) return runSelfInstall(ctx, io, command, rest);
|
|
1250
|
+
if (command.includes('.')) {
|
|
1251
|
+
if (rest.includes('--help')) {
|
|
1252
|
+
ctx.out(LEGACY_HELP);
|
|
1253
|
+
return 0;
|
|
1254
|
+
}
|
|
1255
|
+
return legacy(ctx, argv);
|
|
1256
|
+
}
|
|
1257
|
+
const json = rest.includes('--json');
|
|
1258
|
+
if (!Object.hasOwn(COMMANDS, command)) return fail(ctx, new UsageError(`Unknown command "${oneLine(command, 60)}"`), { json });
|
|
1259
|
+
if (rest.includes('--help') || rest.includes('-h')) {
|
|
1260
|
+
ctx.out(commandHelp(command));
|
|
1261
|
+
return 0;
|
|
1262
|
+
}
|
|
1263
|
+
const spec = COMMANDS[command];
|
|
1264
|
+
try {
|
|
1265
|
+
const { options, positionals } = parseArgs(rest, spec.flags);
|
|
1266
|
+
const [minimum, maximum] = spec.positionals;
|
|
1267
|
+
if (positionals.length < minimum) throw new UsageError(`${spec.argument} is required`);
|
|
1268
|
+
if (positionals.length > maximum) throw new UsageError(`Unexpected argument "${oneLine(positionals[maximum], 60)}"`);
|
|
1269
|
+
return await spec.run(ctx, options, positionals);
|
|
1270
|
+
} catch (error) {
|
|
1271
|
+
return fail(ctx, error, { json, command });
|
|
1272
|
+
}
|
|
1273
|
+
}
|