opencode-completion-gate 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/LICENSE +21 -0
- package/README.md +56 -0
- package/dist/core.d.ts +212 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +697 -0
- package/dist/plugin.d.ts +11 -0
- package/dist/plugin.js +1061 -0
- package/package.json +81 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,697 @@
|
|
|
1
|
+
// src/core.ts
|
|
2
|
+
import { readFileSync, appendFileSync, existsSync, mkdirSync, mkdtempSync } from "fs";
|
|
3
|
+
import { join, dirname } from "path";
|
|
4
|
+
import { homedir, tmpdir } from "os";
|
|
5
|
+
import { exec, execFile } from "child_process";
|
|
6
|
+
var BASE_DIR = join(homedir(), ".config", "opencode");
|
|
7
|
+
function logDiag(msg) {
|
|
8
|
+
try {
|
|
9
|
+
appendFileSync(join(BASE_DIR, "gate-diag.log"), `${(/* @__PURE__ */ new Date()).toISOString()} ${msg}
|
|
10
|
+
`);
|
|
11
|
+
} catch {
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
function brief(s) {
|
|
15
|
+
const line = s.replace(/\r\n/g, "\n").split("\n").find((l) => l.trim() !== "") ?? "";
|
|
16
|
+
return line.length > 160 ? `${line.slice(0, 157)}...` : line;
|
|
17
|
+
}
|
|
18
|
+
function truncateTail(text, maxLines = 50) {
|
|
19
|
+
const lines = text.replace(/\r\n/g, "\n").split("\n").filter((l) => l.trim() !== "");
|
|
20
|
+
if (lines.length <= maxLines) return lines.join("\n");
|
|
21
|
+
return `[... ${lines.length - maxLines} earlier lines omitted]
|
|
22
|
+
${lines.slice(-maxLines).join("\n")}`;
|
|
23
|
+
}
|
|
24
|
+
function positiveInt(v, fallback) {
|
|
25
|
+
return typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.floor(v) : fallback;
|
|
26
|
+
}
|
|
27
|
+
function validateGateConfig(raw) {
|
|
28
|
+
if (!raw || typeof raw !== "object") return null;
|
|
29
|
+
const obj = raw;
|
|
30
|
+
if (obj.enabled === false) return null;
|
|
31
|
+
if (!Array.isArray(obj.assertions)) return null;
|
|
32
|
+
const assertions = [];
|
|
33
|
+
for (const a of obj.assertions) {
|
|
34
|
+
if (!a || typeof a !== "object") return null;
|
|
35
|
+
const nameOf = (fb) => typeof a.name === "string" && a.name.trim() ? a.name : fb;
|
|
36
|
+
switch (a.type) {
|
|
37
|
+
case "command":
|
|
38
|
+
if (typeof a.run !== "string" || !a.run.trim()) return null;
|
|
39
|
+
assertions.push({
|
|
40
|
+
type: "command",
|
|
41
|
+
name: nameOf(a.run.split(/\s+/)[0]),
|
|
42
|
+
run: a.run,
|
|
43
|
+
timeoutSeconds: positiveInt(a.timeoutSeconds, 300)
|
|
44
|
+
});
|
|
45
|
+
break;
|
|
46
|
+
case "ado-pr":
|
|
47
|
+
assertions.push({
|
|
48
|
+
type: "ado-pr",
|
|
49
|
+
name: nameOf("ado-pr"),
|
|
50
|
+
pollTimeoutMinutes: positiveInt(a.pollTimeoutMinutes, 15),
|
|
51
|
+
pollIntervalSeconds: positiveInt(a.pollIntervalSeconds, 30),
|
|
52
|
+
skipIfNoPr: a.skipIfNoPr === true,
|
|
53
|
+
ignoreHumanPolicies: a.ignoreHumanPolicies === true
|
|
54
|
+
});
|
|
55
|
+
break;
|
|
56
|
+
case "opencode-review":
|
|
57
|
+
assertions.push({
|
|
58
|
+
type: "opencode-review",
|
|
59
|
+
name: nameOf("self-review"),
|
|
60
|
+
agent: typeof a.agent === "string" && a.agent.trim() ? a.agent : "reviewer",
|
|
61
|
+
prompt: typeof a.prompt === "string" && a.prompt.trim() ? a.prompt : void 0,
|
|
62
|
+
timeoutSeconds: positiveInt(a.timeoutSeconds, 900)
|
|
63
|
+
});
|
|
64
|
+
break;
|
|
65
|
+
default:
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
if (assertions.length === 0) return null;
|
|
70
|
+
return { enabled: true, maxRetries: positiveInt(obj.maxRetries, 3), assertions };
|
|
71
|
+
}
|
|
72
|
+
function findGateConfigPath(startDir) {
|
|
73
|
+
let dir = startDir;
|
|
74
|
+
for (; ; ) {
|
|
75
|
+
try {
|
|
76
|
+
const candidate = join(dir, ".opencode", "completion-gate.json");
|
|
77
|
+
if (existsSync(candidate)) return candidate;
|
|
78
|
+
if (existsSync(join(dir, ".git"))) return null;
|
|
79
|
+
const parent = dirname(dir);
|
|
80
|
+
if (parent === dir) return null;
|
|
81
|
+
dir = parent;
|
|
82
|
+
} catch {
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function loadGateConfig(startDir) {
|
|
88
|
+
const path = findGateConfigPath(startDir);
|
|
89
|
+
if (!path) return null;
|
|
90
|
+
let config = null;
|
|
91
|
+
try {
|
|
92
|
+
config = validateGateConfig(JSON.parse(readFileSync(path, "utf8")));
|
|
93
|
+
} catch {
|
|
94
|
+
config = null;
|
|
95
|
+
}
|
|
96
|
+
if (!config) return null;
|
|
97
|
+
return { path, projectRoot: dirname(dirname(path)), config };
|
|
98
|
+
}
|
|
99
|
+
function outcomeFromErr(err) {
|
|
100
|
+
if (!err) return 0;
|
|
101
|
+
return typeof err.code === "number" ? err.code : null;
|
|
102
|
+
}
|
|
103
|
+
function runCommand(cmd, cwd, timeoutMs) {
|
|
104
|
+
return new Promise((resolve) => {
|
|
105
|
+
let childTimedOut = false;
|
|
106
|
+
const child = exec(
|
|
107
|
+
cmd,
|
|
108
|
+
{ cwd, windowsHide: true, maxBuffer: 16 * 1024 * 1024 },
|
|
109
|
+
(err, stdout, stderr) => {
|
|
110
|
+
clearTimeout(timer);
|
|
111
|
+
resolve({
|
|
112
|
+
code: outcomeFromErr(err),
|
|
113
|
+
timedOut: Boolean(err && err.killed) || childTimedOut,
|
|
114
|
+
stdout: stdout?.toString() ?? "",
|
|
115
|
+
stderr: stderr?.toString() ?? ""
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
);
|
|
119
|
+
const timer = setTimeout(() => {
|
|
120
|
+
childTimedOut = true;
|
|
121
|
+
try {
|
|
122
|
+
child.kill();
|
|
123
|
+
} catch {
|
|
124
|
+
}
|
|
125
|
+
if (process.platform === "win32" && child.pid) {
|
|
126
|
+
exec(`taskkill /PID ${child.pid} /T /F`, { windowsHide: true }, () => {
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
}, timeoutMs);
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
function execFileOut(file, args, cwd, timeoutMs, spawnOpts) {
|
|
133
|
+
return new Promise((resolve) => {
|
|
134
|
+
execFile(
|
|
135
|
+
file,
|
|
136
|
+
args,
|
|
137
|
+
{ cwd, windowsHide: true, timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024, ...spawnOpts },
|
|
138
|
+
(err, stdout, stderr) => {
|
|
139
|
+
resolve({
|
|
140
|
+
code: outcomeFromErr(err),
|
|
141
|
+
timedOut: Boolean(err && err.killed),
|
|
142
|
+
stdout: stdout?.toString() ?? "",
|
|
143
|
+
stderr: stderr?.toString() ?? ""
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
);
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
function pass(name) {
|
|
150
|
+
return { name, passed: true, evidence: "" };
|
|
151
|
+
}
|
|
152
|
+
function fail(name, evidence) {
|
|
153
|
+
return { name, passed: false, evidence: evidence.trim() };
|
|
154
|
+
}
|
|
155
|
+
async function runCommandAssertion(a, cwd, isAborted) {
|
|
156
|
+
if (isAborted?.()) throw new GateAborted();
|
|
157
|
+
logDiag(
|
|
158
|
+
`command "${a.name}": running ${JSON.stringify(a.run)} (cwd=${cwd}, timeout=${a.timeoutSeconds}s)`
|
|
159
|
+
);
|
|
160
|
+
const r = await runCommand(a.run, cwd, a.timeoutSeconds * 1e3);
|
|
161
|
+
logDiag(
|
|
162
|
+
r.timedOut ? `command "${a.name}": TIMED OUT after ${a.timeoutSeconds}s` : `command "${a.name}": exit code ${r.code}`
|
|
163
|
+
);
|
|
164
|
+
if (!r.timedOut && r.code === 0) return pass(a.name);
|
|
165
|
+
const why = r.timedOut ? `command timed out after ${a.timeoutSeconds}s` : `exit code ${r.code}`;
|
|
166
|
+
return fail(
|
|
167
|
+
a.name,
|
|
168
|
+
`${why}
|
|
169
|
+
${truncateTail([r.stderr, r.stdout].filter((s) => s.trim()).join("\n---\n"))}`
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
function pickActivePrDetails(prListJson) {
|
|
173
|
+
let parsed;
|
|
174
|
+
try {
|
|
175
|
+
parsed = JSON.parse(prListJson);
|
|
176
|
+
} catch {
|
|
177
|
+
return { ok: false, reason: "unparsable", detail: "az repos pr list returned invalid JSON" };
|
|
178
|
+
}
|
|
179
|
+
if (!Array.isArray(parsed)) {
|
|
180
|
+
return { ok: false, reason: "unparsable", detail: "expected an array of PRs" };
|
|
181
|
+
}
|
|
182
|
+
if (parsed.length === 0) {
|
|
183
|
+
return { ok: false, reason: "none", detail: "no active PR found for this branch" };
|
|
184
|
+
}
|
|
185
|
+
const ids = parsed.map((p) => typeof p?.pullRequestId === "number" ? p.pullRequestId : p?.id).filter((n) => typeof n === "number");
|
|
186
|
+
if (ids.length !== parsed.length) {
|
|
187
|
+
return { ok: false, reason: "unparsable", detail: "PR entries missing numeric pullRequestId" };
|
|
188
|
+
}
|
|
189
|
+
if (ids.length > 1) {
|
|
190
|
+
return {
|
|
191
|
+
ok: false,
|
|
192
|
+
reason: "multiple",
|
|
193
|
+
detail: `multiple active PRs for this branch: ${ids.join(", ")}`
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
const projectName = typeof parsed[0]?.repository?.project?.name === "string" && parsed[0].repository.project.name.trim() ? parsed[0].repository.project.name : void 0;
|
|
197
|
+
return projectName ? { ok: true, prId: ids[0], projectName } : { ok: true, prId: ids[0] };
|
|
198
|
+
}
|
|
199
|
+
function pickActivePr(prListJson) {
|
|
200
|
+
const result = pickActivePrDetails(prListJson);
|
|
201
|
+
return result.ok ? { ok: true, prId: result.prId } : result;
|
|
202
|
+
}
|
|
203
|
+
var GREEN_POLICY_STATUSES = /* @__PURE__ */ new Set(["approved", "succeeded", "notapplicable"]);
|
|
204
|
+
var IN_PROGRESS_POLICY_STATUSES = /* @__PURE__ */ new Set(["queued", "running"]);
|
|
205
|
+
var HUMAN_POLICY_RE = /minimum number of reviewers|required reviewers|comment requirements/i;
|
|
206
|
+
function isHumanReviewPolicy(e) {
|
|
207
|
+
return HUMAN_POLICY_RE.test(String(e?.configuration?.type?.displayName ?? ""));
|
|
208
|
+
}
|
|
209
|
+
function parseBuildId(value) {
|
|
210
|
+
const id = typeof value === "number" ? value : typeof value === "string" && value.trim() ? Number(value) : NaN;
|
|
211
|
+
return Number.isFinite(id) && id > 0 ? id : null;
|
|
212
|
+
}
|
|
213
|
+
function extractTerminalBuildFailures(policyListJson, opts = {}) {
|
|
214
|
+
let evals;
|
|
215
|
+
try {
|
|
216
|
+
evals = JSON.parse(policyListJson);
|
|
217
|
+
} catch {
|
|
218
|
+
return [];
|
|
219
|
+
}
|
|
220
|
+
if (!Array.isArray(evals)) return [];
|
|
221
|
+
return evals.filter((e) => e?.configuration?.isBlocking === true || e?.configuration?.isRequired === true).filter((e) => String(e?.configuration?.type?.displayName ?? "").toLowerCase() === "build").filter((e) => !(opts.ignoreHumanPolicies && isHumanReviewPolicy(e))).filter((e) => {
|
|
222
|
+
const status = String(e?.status ?? "").toLowerCase();
|
|
223
|
+
return !GREEN_POLICY_STATUSES.has(status) && !IN_PROGRESS_POLICY_STATUSES.has(status);
|
|
224
|
+
}).map((e) => {
|
|
225
|
+
const context = e.context;
|
|
226
|
+
const preview = context?.buildOutputPreview;
|
|
227
|
+
const failure = {
|
|
228
|
+
buildId: parseBuildId(context?.buildId),
|
|
229
|
+
status: String(e?.status ?? ""),
|
|
230
|
+
previewErrors: Array.isArray(preview?.errors) ? preview.errors.map((error) => error?.message).filter(
|
|
231
|
+
(message) => typeof message === "string" && message.trim() !== ""
|
|
232
|
+
) : []
|
|
233
|
+
};
|
|
234
|
+
if (typeof context?.buildDefinitionName === "string")
|
|
235
|
+
failure.definitionName = context.buildDefinitionName;
|
|
236
|
+
if (typeof preview?.jobName === "string") failure.jobName = preview.jobName;
|
|
237
|
+
if (typeof preview?.taskName === "string") failure.taskName = preview.taskName;
|
|
238
|
+
return failure;
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
function formatBuildPreview(build) {
|
|
242
|
+
const lines = [
|
|
243
|
+
build.definitionName ? `Build definition: ${build.definitionName}` : "",
|
|
244
|
+
`Build policy status: ${build.status}`,
|
|
245
|
+
build.jobName ? `Job: ${build.jobName}` : "",
|
|
246
|
+
build.taskName ? `Task: ${build.taskName}` : ""
|
|
247
|
+
];
|
|
248
|
+
if (build.previewErrors.length > 0) {
|
|
249
|
+
lines.push("Preview errors:");
|
|
250
|
+
for (const line of truncateTail(build.previewErrors.join("\n"), 20).split("\n"))
|
|
251
|
+
lines.push(line);
|
|
252
|
+
}
|
|
253
|
+
return lines.filter((l) => l.trim() !== "").join("\n");
|
|
254
|
+
}
|
|
255
|
+
function requiredPoliciesGreen(policyListJson, opts = {}) {
|
|
256
|
+
let evals;
|
|
257
|
+
try {
|
|
258
|
+
evals = JSON.parse(policyListJson);
|
|
259
|
+
} catch {
|
|
260
|
+
return {
|
|
261
|
+
green: false,
|
|
262
|
+
retryable: false,
|
|
263
|
+
detail: "az repos pr policy list returned invalid JSON"
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
if (!Array.isArray(evals))
|
|
267
|
+
return { green: false, retryable: false, detail: "expected an array of policy evaluations" };
|
|
268
|
+
const allRequired = evals.filter(
|
|
269
|
+
(e) => e?.configuration?.isBlocking === true || e?.configuration?.isRequired === true
|
|
270
|
+
);
|
|
271
|
+
if (allRequired.length === 0)
|
|
272
|
+
return { green: false, retryable: false, detail: "no blocking policies found on this PR" };
|
|
273
|
+
const ignored = opts.ignoreHumanPolicies ? allRequired.filter(isHumanReviewPolicy) : [];
|
|
274
|
+
const required = opts.ignoreHumanPolicies ? allRequired.filter((e) => !isHumanReviewPolicy(e)) : allRequired;
|
|
275
|
+
if (required.length === 0) {
|
|
276
|
+
const names = ignored.map((e) => e.configuration?.type?.displayName ?? "policy").join(", ");
|
|
277
|
+
return {
|
|
278
|
+
green: true,
|
|
279
|
+
retryable: false,
|
|
280
|
+
detail: `only human-review policies on this PR (${names}) \u2014 ignored via ignoreHumanPolicies`
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
const bad = required.filter(
|
|
284
|
+
(e) => !GREEN_POLICY_STATUSES.has(String(e.status ?? "").toLowerCase())
|
|
285
|
+
);
|
|
286
|
+
if (bad.length > 0) {
|
|
287
|
+
const names = bad.map((e) => `${e.configuration?.type?.displayName ?? "policy"}: ${String(e.status ?? "?")}`).join("; ");
|
|
288
|
+
const skipped = ignored.length > 0 ? ` (${ignored.length} human policy(ies) ignored)` : "";
|
|
289
|
+
const hasTerminalAutomatedFailure = bad.some(
|
|
290
|
+
(e) => !isHumanReviewPolicy(e) && !IN_PROGRESS_POLICY_STATUSES.has(String(e.status ?? "").toLowerCase())
|
|
291
|
+
);
|
|
292
|
+
return {
|
|
293
|
+
green: false,
|
|
294
|
+
retryable: !hasTerminalAutomatedFailure,
|
|
295
|
+
detail: `PR policies not green \u2014 ${names}${skipped}`
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
const greenDetail = `${required.length} required policy(ies) green`;
|
|
299
|
+
if (ignored.length > 0) {
|
|
300
|
+
const names = ignored.map((e) => e.configuration?.type?.displayName ?? "policy").join(", ");
|
|
301
|
+
return {
|
|
302
|
+
green: true,
|
|
303
|
+
retryable: false,
|
|
304
|
+
detail: `${greenDetail}, ${ignored.length} human policy(ies) ignored (${names})`
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
return { green: true, retryable: false, detail: greenDetail };
|
|
308
|
+
}
|
|
309
|
+
function quoteWin(s) {
|
|
310
|
+
return /[\s"^&|<>]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
|
|
311
|
+
}
|
|
312
|
+
function buildShellInvocation(args) {
|
|
313
|
+
if (process.platform !== "win32") return { file: args[0], args: args.slice(1) };
|
|
314
|
+
const cmdline = [args[0], ...args.slice(1)].map(quoteWin).join(" ");
|
|
315
|
+
return { file: process.env.ComSpec ?? "cmd.exe", args: ["/d", "/s", "/c", `"${cmdline}"`] };
|
|
316
|
+
}
|
|
317
|
+
var execShell = async (args, cwd, timeoutMs) => {
|
|
318
|
+
const inv = buildShellInvocation(args);
|
|
319
|
+
const r = await execFileOut(inv.file, inv.args, cwd, timeoutMs, {
|
|
320
|
+
windowsVerbatimArguments: true
|
|
321
|
+
});
|
|
322
|
+
if (r.timedOut) throw new Error(`${args[0]} timed out`);
|
|
323
|
+
if (r.code !== 0) {
|
|
324
|
+
const detail = truncateTail([r.stderr, r.stdout].filter((s) => s.trim()).join("\n"), 20);
|
|
325
|
+
throw new Error(`${args.join(" ")} failed (code ${r.code}):
|
|
326
|
+
${detail}`);
|
|
327
|
+
}
|
|
328
|
+
return r.stdout;
|
|
329
|
+
};
|
|
330
|
+
var BUILD_LOG_TIMEOUT_MS = 12e4;
|
|
331
|
+
var defaultBuildLogExtractor = async (archivePath, destination, cwd, timeoutMs) => {
|
|
332
|
+
const r = await execFileOut("tar", ["-xf", archivePath, "-C", destination], cwd, timeoutMs);
|
|
333
|
+
if (r.timedOut) throw new Error(`tar timed out extracting ${archivePath}`);
|
|
334
|
+
if (r.code !== 0) {
|
|
335
|
+
const detail = truncateTail([r.stderr, r.stdout].filter((s) => s.trim()).join("\n"), 20);
|
|
336
|
+
throw new Error(`tar failed (code ${r.code}): ${brief(detail)}`);
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
async function downloadBuildLogs(projectName, buildId, cwd, options = {}) {
|
|
340
|
+
const timeoutMs = options.timeoutMs ?? BUILD_LOG_TIMEOUT_MS;
|
|
341
|
+
const shell = options.shell ?? execShell;
|
|
342
|
+
const extract = options.extract ?? defaultBuildLogExtractor;
|
|
343
|
+
if (options.isAborted?.()) throw new GateAborted();
|
|
344
|
+
const root = options.tempRoot ?? join(tmpdir(), "opencode");
|
|
345
|
+
try {
|
|
346
|
+
mkdirSync(root, { recursive: true });
|
|
347
|
+
} catch {
|
|
348
|
+
}
|
|
349
|
+
let workDir;
|
|
350
|
+
try {
|
|
351
|
+
workDir = mkdtempSync(join(root, `completion-gate-logs-${buildId}-`));
|
|
352
|
+
} catch (err) {
|
|
353
|
+
return {
|
|
354
|
+
buildId,
|
|
355
|
+
error: `could not create artifact directory under ${root}: ${err?.message ?? String(err)}`
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
const archivePath = join(workDir, `build-${buildId}-logs.zip`);
|
|
359
|
+
const destination = join(workDir, "extracted");
|
|
360
|
+
logDiag(`build-logs "${projectName}" #${buildId}: downloading to ${archivePath}`);
|
|
361
|
+
try {
|
|
362
|
+
await shell(
|
|
363
|
+
[
|
|
364
|
+
"az",
|
|
365
|
+
"devops",
|
|
366
|
+
"invoke",
|
|
367
|
+
"--detect",
|
|
368
|
+
"true",
|
|
369
|
+
"--area",
|
|
370
|
+
"build",
|
|
371
|
+
"--resource",
|
|
372
|
+
"logs",
|
|
373
|
+
"--route-parameters",
|
|
374
|
+
`project=${projectName}`,
|
|
375
|
+
`buildId=${buildId}`,
|
|
376
|
+
"--api-version",
|
|
377
|
+
"7.1",
|
|
378
|
+
"--http-method",
|
|
379
|
+
"GET",
|
|
380
|
+
"--accept-media-type",
|
|
381
|
+
"application/zip",
|
|
382
|
+
"--out-file",
|
|
383
|
+
archivePath
|
|
384
|
+
],
|
|
385
|
+
cwd,
|
|
386
|
+
timeoutMs
|
|
387
|
+
);
|
|
388
|
+
} catch (err) {
|
|
389
|
+
logDiag(
|
|
390
|
+
`build-logs "${projectName}" #${buildId}: download failed \u2014 ${brief(String(err?.message ?? err))}`
|
|
391
|
+
);
|
|
392
|
+
return { buildId, error: `download failed: ${err?.message ?? String(err)}` };
|
|
393
|
+
}
|
|
394
|
+
if (!existsSync(archivePath)) {
|
|
395
|
+
logDiag(`build-logs "${projectName}" #${buildId}: az exited zero but wrote no archive file`);
|
|
396
|
+
return { buildId, error: "az devops invoke succeeded but produced no archive file" };
|
|
397
|
+
}
|
|
398
|
+
const result = { buildId, archivePath };
|
|
399
|
+
if (options.isAborted?.()) throw new GateAborted();
|
|
400
|
+
try {
|
|
401
|
+
mkdirSync(destination, { recursive: true });
|
|
402
|
+
await extract(archivePath, destination, cwd, timeoutMs);
|
|
403
|
+
result.extractedPath = destination;
|
|
404
|
+
logDiag(`build-logs "${projectName}" #${buildId}: extracted to ${destination}`);
|
|
405
|
+
} catch (err) {
|
|
406
|
+
result.error = `extraction failed: ${err?.message ?? String(err)}`;
|
|
407
|
+
logDiag(`build-logs "${projectName}" #${buildId}: extraction failed \u2014 ${brief(result.error)}`);
|
|
408
|
+
}
|
|
409
|
+
return result;
|
|
410
|
+
}
|
|
411
|
+
var defaultBuildLogArtifact = (projectName, buildId, cwd, isAborted) => downloadBuildLogs(projectName, buildId, cwd, { isAborted });
|
|
412
|
+
async function runAdoPrAssertion(a, cwd, shell, opts = {}) {
|
|
413
|
+
const sleep = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
414
|
+
const now = opts.now ?? (() => Date.now());
|
|
415
|
+
const intervalMs = Math.max(5, a.pollIntervalSeconds) * 1e3;
|
|
416
|
+
const deadline = now() + Math.max(1, a.pollTimeoutMinutes) * 6e4;
|
|
417
|
+
let branch;
|
|
418
|
+
logDiag(`ado-pr "${a.name}": resolving current branch`);
|
|
419
|
+
try {
|
|
420
|
+
branch = (await shell(["git", "-C", cwd, "branch", "--show-current"], cwd, 1e4)).trim();
|
|
421
|
+
} catch (err) {
|
|
422
|
+
return fail(a.name, `could not resolve current branch: ${err?.message ?? String(err)}`);
|
|
423
|
+
}
|
|
424
|
+
if (!branch) return fail(a.name, "not on a branch (detached HEAD?) \u2014 nothing to check a PR for");
|
|
425
|
+
logDiag(
|
|
426
|
+
`ado-pr "${a.name}": branch="${branch}", polling every ${intervalMs / 1e3}s up to ${a.pollTimeoutMinutes} min`
|
|
427
|
+
);
|
|
428
|
+
let round = 0;
|
|
429
|
+
try {
|
|
430
|
+
for (; ; ) {
|
|
431
|
+
if (opts.isAborted?.()) throw new GateAborted();
|
|
432
|
+
round += 1;
|
|
433
|
+
const listJson = await shell(
|
|
434
|
+
[
|
|
435
|
+
"az",
|
|
436
|
+
"repos",
|
|
437
|
+
"pr",
|
|
438
|
+
"list",
|
|
439
|
+
"--source-branch",
|
|
440
|
+
branch,
|
|
441
|
+
"--status",
|
|
442
|
+
"active",
|
|
443
|
+
"--output",
|
|
444
|
+
"json"
|
|
445
|
+
],
|
|
446
|
+
cwd,
|
|
447
|
+
12e4
|
|
448
|
+
);
|
|
449
|
+
const pr = pickActivePrDetails(listJson);
|
|
450
|
+
if (!pr.ok) {
|
|
451
|
+
if (pr.reason === "none" && a.skipIfNoPr) {
|
|
452
|
+
logDiag(`ado-pr "${a.name}": no active PR \u2014 skipIfNoPr=true, passing`);
|
|
453
|
+
return pass(a.name);
|
|
454
|
+
}
|
|
455
|
+
return fail(
|
|
456
|
+
a.name,
|
|
457
|
+
pr.reason === "none" ? `no active PR for branch "${branch}" \u2014 open one before finishing` : pr.detail
|
|
458
|
+
);
|
|
459
|
+
}
|
|
460
|
+
logDiag(`ado-pr "${a.name}": round ${round} \u2014 active PR !${pr.prId}, checking policies`);
|
|
461
|
+
const policyJson = await shell(
|
|
462
|
+
["az", "repos", "pr", "policy", "list", "--id", String(pr.prId), "--output", "json"],
|
|
463
|
+
cwd,
|
|
464
|
+
12e4
|
|
465
|
+
);
|
|
466
|
+
const g = requiredPoliciesGreen(policyJson, {
|
|
467
|
+
ignoreHumanPolicies: a.ignoreHumanPolicies === true
|
|
468
|
+
});
|
|
469
|
+
if (g.green) {
|
|
470
|
+
logDiag(`ado-pr "${a.name}": PR !${pr.prId} green (${g.detail})`);
|
|
471
|
+
return pass(a.name);
|
|
472
|
+
}
|
|
473
|
+
if (!g.retryable) {
|
|
474
|
+
const baseEvidence = `PR !${pr.prId} has terminal policy failure \u2014 ${g.detail}`;
|
|
475
|
+
const buildFailures = extractTerminalBuildFailures(policyJson, {
|
|
476
|
+
ignoreHumanPolicies: a.ignoreHumanPolicies === true
|
|
477
|
+
});
|
|
478
|
+
const artifactEvidence = [];
|
|
479
|
+
const seenBuildIds = /* @__PURE__ */ new Set();
|
|
480
|
+
for (const build of buildFailures) {
|
|
481
|
+
if (build.buildId !== null) {
|
|
482
|
+
if (seenBuildIds.has(build.buildId)) continue;
|
|
483
|
+
seenBuildIds.add(build.buildId);
|
|
484
|
+
}
|
|
485
|
+
artifactEvidence.push(formatBuildPreview(build));
|
|
486
|
+
if (build.buildId === null) {
|
|
487
|
+
artifactEvidence.push(
|
|
488
|
+
"Build logs unavailable: terminal Build policy has no valid buildId."
|
|
489
|
+
);
|
|
490
|
+
continue;
|
|
491
|
+
}
|
|
492
|
+
if (!pr.projectName) {
|
|
493
|
+
artifactEvidence.push(
|
|
494
|
+
`Build logs unavailable for build ${build.buildId}: active PR payload has no repository project name.`
|
|
495
|
+
);
|
|
496
|
+
continue;
|
|
497
|
+
}
|
|
498
|
+
if (opts.isAborted?.()) throw new GateAborted();
|
|
499
|
+
try {
|
|
500
|
+
const artifact = await (opts.buildLogArtifact ?? defaultBuildLogArtifact)(
|
|
501
|
+
pr.projectName,
|
|
502
|
+
build.buildId,
|
|
503
|
+
cwd,
|
|
504
|
+
opts.isAborted
|
|
505
|
+
);
|
|
506
|
+
if (artifact.extractedPath)
|
|
507
|
+
artifactEvidence.push(`Build logs extracted directory: ${artifact.extractedPath}`);
|
|
508
|
+
if (artifact.archivePath)
|
|
509
|
+
artifactEvidence.push(`Build logs ZIP: ${artifact.archivePath}`);
|
|
510
|
+
if (artifact.error)
|
|
511
|
+
artifactEvidence.push(`Build log artifact error: ${artifact.error}`);
|
|
512
|
+
} catch (err) {
|
|
513
|
+
if (err instanceof GateAborted) throw err;
|
|
514
|
+
artifactEvidence.push(`Build log artifact error: ${err?.message ?? String(err)}`);
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
logDiag(
|
|
518
|
+
`ado-pr "${a.name}": PR !${pr.prId} has terminal policy failure \u2014 ${brief(g.detail)}; stopping polling`
|
|
519
|
+
);
|
|
520
|
+
return fail(a.name, [baseEvidence, ...artifactEvidence].filter(Boolean).join("\n"));
|
|
521
|
+
}
|
|
522
|
+
logDiag(`ado-pr "${a.name}": PR !${pr.prId} not green yet \u2014 ${brief(g.detail)}`);
|
|
523
|
+
if (now() + intervalMs >= deadline) {
|
|
524
|
+
return fail(
|
|
525
|
+
a.name,
|
|
526
|
+
`PR !${pr.prId} did not reach green within ${a.pollTimeoutMinutes} min \u2014 ${g.detail}`
|
|
527
|
+
);
|
|
528
|
+
}
|
|
529
|
+
if (opts.isAborted?.()) throw new GateAborted();
|
|
530
|
+
await sleep(intervalMs);
|
|
531
|
+
}
|
|
532
|
+
} catch (err) {
|
|
533
|
+
if (err instanceof GateAborted) throw err;
|
|
534
|
+
return fail(a.name, err?.message ?? String(err));
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
function parseVerdict(output) {
|
|
538
|
+
const matches = [...output.matchAll(/VERDICT:\s*\b(PASS|FAIL)\b/gi)];
|
|
539
|
+
const last = matches[matches.length - 1];
|
|
540
|
+
return last ? last[1].toUpperCase() : null;
|
|
541
|
+
}
|
|
542
|
+
function unwrapSdk(res) {
|
|
543
|
+
if (res && typeof res === "object" && ("data" in res || "error" in res)) {
|
|
544
|
+
const r = res;
|
|
545
|
+
if (r.error != null) {
|
|
546
|
+
const e = r.error;
|
|
547
|
+
throw new Error(typeof e === "string" ? e : e?.message ?? JSON.stringify(e));
|
|
548
|
+
}
|
|
549
|
+
return r.data;
|
|
550
|
+
}
|
|
551
|
+
return res;
|
|
552
|
+
}
|
|
553
|
+
function reviewerText(res) {
|
|
554
|
+
const parts = res?.parts;
|
|
555
|
+
if (!Array.isArray(parts)) return "";
|
|
556
|
+
return parts.filter((p) => p?.type === "text").map((p) => String(p.text ?? "")).join("\n");
|
|
557
|
+
}
|
|
558
|
+
function describeSdkError(err) {
|
|
559
|
+
if (err instanceof Error) return err.message;
|
|
560
|
+
if (typeof err === "string") return err;
|
|
561
|
+
try {
|
|
562
|
+
return JSON.stringify(err);
|
|
563
|
+
} catch {
|
|
564
|
+
return String(err);
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
async function runReviewAssertion(a, cwd, client, isAborted) {
|
|
568
|
+
if (isAborted?.()) throw new GateAborted();
|
|
569
|
+
if (!client?.session)
|
|
570
|
+
return fail(a.name, "no opencode SDK client available to run the reviewer session");
|
|
571
|
+
logDiag(`review "${a.name}": creating reviewer session in ${cwd}`);
|
|
572
|
+
const prompt = [
|
|
573
|
+
a.prompt ?? "Review the changes on this branch against the task requirements.",
|
|
574
|
+
'Finish your reply with a final line containing exactly "VERDICT: PASS" or "VERDICT: FAIL" followed by a one-line justification.'
|
|
575
|
+
].join("\n");
|
|
576
|
+
try {
|
|
577
|
+
const created = unwrapSdk(
|
|
578
|
+
await client.session.create({ query: { directory: cwd } })
|
|
579
|
+
);
|
|
580
|
+
const sessionId = created?.id;
|
|
581
|
+
if (!sessionId)
|
|
582
|
+
return fail(a.name, "could not create reviewer session (no session id in response)");
|
|
583
|
+
logDiag(
|
|
584
|
+
`review "${a.name}": reviewer session ${sessionId} \u2014 prompting agent "${a.agent}" (timeout=${a.timeoutSeconds}s)`
|
|
585
|
+
);
|
|
586
|
+
let timer;
|
|
587
|
+
try {
|
|
588
|
+
const raced = await Promise.race([
|
|
589
|
+
client.session.prompt({
|
|
590
|
+
path: { id: sessionId },
|
|
591
|
+
body: { agent: a.agent, parts: [{ type: "text", text: prompt }] }
|
|
592
|
+
}).then(
|
|
593
|
+
(r) => ({ ok: true, r }),
|
|
594
|
+
(err) => ({ ok: false, err })
|
|
595
|
+
),
|
|
596
|
+
new Promise((resolve) => {
|
|
597
|
+
timer = setTimeout(() => resolve({ timedOut: true }), a.timeoutSeconds * 1e3);
|
|
598
|
+
})
|
|
599
|
+
]);
|
|
600
|
+
if ("timedOut" in raced) {
|
|
601
|
+
logDiag(
|
|
602
|
+
`review "${a.name}": TIMED OUT after ${a.timeoutSeconds}s \u2014 aborting reviewer session`
|
|
603
|
+
);
|
|
604
|
+
try {
|
|
605
|
+
await Promise.resolve(client.session.abort?.({ path: { id: sessionId } }));
|
|
606
|
+
} catch {
|
|
607
|
+
}
|
|
608
|
+
return fail(
|
|
609
|
+
a.name,
|
|
610
|
+
`review timed out after ${a.timeoutSeconds}s (reviewer session aborted)`
|
|
611
|
+
);
|
|
612
|
+
}
|
|
613
|
+
if (!raced.ok) {
|
|
614
|
+
return fail(a.name, `reviewer session failed: ${describeSdkError(raced.err)}`);
|
|
615
|
+
}
|
|
616
|
+
const text = reviewerText(unwrapSdk(raced.r));
|
|
617
|
+
const verdict = parseVerdict(text);
|
|
618
|
+
logDiag(`review "${a.name}": verdict=${verdict ?? "none"}`);
|
|
619
|
+
const evidence = truncateTail(text);
|
|
620
|
+
if (verdict === "PASS") return pass(a.name);
|
|
621
|
+
if (verdict === "FAIL") return fail(a.name, `reviewer rejected:
|
|
622
|
+
${evidence}`);
|
|
623
|
+
return fail(a.name, `reviewer produced no VERDICT line:
|
|
624
|
+
${evidence}`);
|
|
625
|
+
} finally {
|
|
626
|
+
if (timer) clearTimeout(timer);
|
|
627
|
+
}
|
|
628
|
+
} catch (err) {
|
|
629
|
+
return fail(a.name, `reviewer session failed: ${describeSdkError(err)}`);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
var GateAborted = class extends Error {
|
|
633
|
+
};
|
|
634
|
+
async function evaluateAssertions(assertions, projectRoot, client, isAborted, adoOpts) {
|
|
635
|
+
const results = [];
|
|
636
|
+
for (const a of assertions) {
|
|
637
|
+
if (isAborted?.()) return null;
|
|
638
|
+
let result;
|
|
639
|
+
logDiag(`evaluating assertion "${a.name}" (${a.type})`);
|
|
640
|
+
try {
|
|
641
|
+
if (a.type === "command") {
|
|
642
|
+
result = await runCommandAssertion(a, projectRoot, isAborted);
|
|
643
|
+
} else if (a.type === "ado-pr") {
|
|
644
|
+
result = await runAdoPrAssertion(a, projectRoot, execShell, { ...adoOpts, isAborted });
|
|
645
|
+
} else {
|
|
646
|
+
result = await runReviewAssertion(a, projectRoot, client, isAborted);
|
|
647
|
+
}
|
|
648
|
+
} catch (err) {
|
|
649
|
+
if (err instanceof GateAborted) {
|
|
650
|
+
logDiag(`assertion "${a.name}" aborted mid-run`);
|
|
651
|
+
return null;
|
|
652
|
+
}
|
|
653
|
+
result = fail(a.name, `gate could not run this assertion: ${err?.message ?? String(err)}`);
|
|
654
|
+
}
|
|
655
|
+
results.push(result);
|
|
656
|
+
if (!result.passed) {
|
|
657
|
+
logDiag(
|
|
658
|
+
`assertion "${a.name}" FAILED \u2014 ${brief(result.evidence)} (stopping here, remaining assertions skipped)`
|
|
659
|
+
);
|
|
660
|
+
break;
|
|
661
|
+
}
|
|
662
|
+
logDiag(`assertion "${a.name}" passed`);
|
|
663
|
+
}
|
|
664
|
+
return results;
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
// src/index.ts
|
|
668
|
+
var VERSION = "1.0.0";
|
|
669
|
+
var pluginMeta = {
|
|
670
|
+
name: "opencode-completion-gate",
|
|
671
|
+
version: VERSION,
|
|
672
|
+
description: "Per-session quality gate that blocks declaring done until configured assertions pass"
|
|
673
|
+
};
|
|
674
|
+
export {
|
|
675
|
+
VERSION,
|
|
676
|
+
buildShellInvocation,
|
|
677
|
+
defaultBuildLogArtifact,
|
|
678
|
+
downloadBuildLogs,
|
|
679
|
+
evaluateAssertions,
|
|
680
|
+
execFileOut,
|
|
681
|
+
execShell,
|
|
682
|
+
extractTerminalBuildFailures,
|
|
683
|
+
findGateConfigPath,
|
|
684
|
+
isHumanReviewPolicy,
|
|
685
|
+
loadGateConfig,
|
|
686
|
+
parseVerdict,
|
|
687
|
+
pickActivePr,
|
|
688
|
+
pickActivePrDetails,
|
|
689
|
+
pluginMeta,
|
|
690
|
+
quoteWin,
|
|
691
|
+
requiredPoliciesGreen,
|
|
692
|
+
runAdoPrAssertion,
|
|
693
|
+
runCommand,
|
|
694
|
+
runCommandAssertion,
|
|
695
|
+
runReviewAssertion,
|
|
696
|
+
truncateTail
|
|
697
|
+
};
|