opencode-completion-gate 1.1.0 → 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/dist/index.js CHANGED
@@ -1,7 +1,7 @@
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";
1
+ // src/process.ts
2
+ import { appendFileSync } from "fs";
3
+ import { join } from "path";
4
+ import { homedir } from "os";
5
5
  import { exec, execFile } from "child_process";
6
6
  var BASE_DIR = join(homedir(), ".config", "opencode");
7
7
  function logDiag(msg) {
@@ -21,6 +21,102 @@ function truncateTail(text, maxLines = 50) {
21
21
  return `[... ${lines.length - maxLines} earlier lines omitted]
22
22
  ${lines.slice(-maxLines).join("\n")}`;
23
23
  }
24
+ function outcomeFromErr(err) {
25
+ if (!err) return 0;
26
+ return typeof err.code === "number" ? err.code : null;
27
+ }
28
+ function runCommand(cmd, cwd, timeoutMs) {
29
+ return new Promise((resolve) => {
30
+ let childTimedOut = false;
31
+ const child = exec(
32
+ cmd,
33
+ { cwd, windowsHide: true, maxBuffer: 16 * 1024 * 1024 },
34
+ (err, stdout, stderr) => {
35
+ clearTimeout(timer);
36
+ resolve({
37
+ code: outcomeFromErr(err),
38
+ timedOut: Boolean(err && err.killed) || childTimedOut,
39
+ stdout: stdout?.toString() ?? "",
40
+ stderr: stderr?.toString() ?? ""
41
+ });
42
+ }
43
+ );
44
+ const timer = setTimeout(() => {
45
+ childTimedOut = true;
46
+ try {
47
+ child.kill();
48
+ } catch {
49
+ }
50
+ if (process.platform === "win32" && child.pid) {
51
+ exec(`taskkill /PID ${child.pid} /T /F`, { windowsHide: true }, () => {
52
+ });
53
+ }
54
+ }, timeoutMs);
55
+ });
56
+ }
57
+ function execFileOut(file, args, cwd, timeoutMs, spawnOpts) {
58
+ return new Promise((resolve) => {
59
+ execFile(
60
+ file,
61
+ args,
62
+ { cwd, windowsHide: true, timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024, ...spawnOpts },
63
+ (err, stdout, stderr) => {
64
+ resolve({
65
+ code: outcomeFromErr(err),
66
+ timedOut: Boolean(err && err.killed),
67
+ stdout: stdout?.toString() ?? "",
68
+ stderr: stderr?.toString() ?? ""
69
+ });
70
+ }
71
+ );
72
+ });
73
+ }
74
+ function quoteWin(s) {
75
+ return /[\s"^&|<>]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
76
+ }
77
+ function buildShellInvocation(args) {
78
+ if (process.platform !== "win32") return { file: args[0], args: args.slice(1) };
79
+ const cmdline = [args[0], ...args.slice(1)].map(quoteWin).join(" ");
80
+ return { file: process.env.ComSpec ?? "cmd.exe", args: ["/d", "/s", "/c", `"${cmdline}"`] };
81
+ }
82
+ var execShell = async (args, cwd, timeoutMs) => {
83
+ const inv = buildShellInvocation(args);
84
+ const r = await execFileOut(inv.file, inv.args, cwd, timeoutMs, {
85
+ windowsVerbatimArguments: true
86
+ });
87
+ if (r.timedOut) throw new Error(`${args[0]} timed out`);
88
+ if (r.code !== 0) {
89
+ const detail = truncateTail([r.stderr, r.stdout].filter((s) => s.trim()).join("\n"), 20);
90
+ throw new Error(`${args.join(" ")} failed (code ${r.code}):
91
+ ${detail}`);
92
+ }
93
+ return r.stdout;
94
+ };
95
+ function describeSdkError(err) {
96
+ if (err instanceof Error) return err.message;
97
+ if (typeof err === "string") return err;
98
+ if (err && typeof err === "object" && "message" in err) {
99
+ const message = err.message;
100
+ if (typeof message === "string") return message;
101
+ }
102
+ try {
103
+ return JSON.stringify(err);
104
+ } catch {
105
+ return String(err);
106
+ }
107
+ }
108
+
109
+ // src/config.ts
110
+ import { readFileSync, existsSync } from "fs";
111
+ import { join as join2, dirname } from "path";
112
+ var GateAborted = class extends Error {
113
+ };
114
+ function pass(name) {
115
+ return { name, passed: true, evidence: "" };
116
+ }
117
+ function fail(name, evidence) {
118
+ return { name, passed: false, evidence: evidence.trim() };
119
+ }
24
120
  function positiveInt(v, fallback) {
25
121
  return typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.floor(v) : fallback;
26
122
  }
@@ -73,9 +169,9 @@ function findGateConfigPath(startDir) {
73
169
  let dir = startDir;
74
170
  for (; ; ) {
75
171
  try {
76
- const candidate = join(dir, ".opencode", "completion-gate.json");
172
+ const candidate = join2(dir, ".opencode", "completion-gate.json");
77
173
  if (existsSync(candidate)) return candidate;
78
- if (existsSync(join(dir, ".git"))) return null;
174
+ if (existsSync(join2(dir, ".git"))) return null;
79
175
  const parent = dirname(dir);
80
176
  if (parent === dir) return null;
81
177
  dir = parent;
@@ -96,79 +192,6 @@ function loadGateConfig(startDir) {
96
192
  if (!config) return null;
97
193
  return { path, projectRoot: dirname(dirname(path)), config };
98
194
  }
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
195
  function parsePositiveIntToken(tok) {
173
196
  const n = Number(tok);
174
197
  return Number.isFinite(n) && n > 0 ? Math.floor(n) : null;
@@ -179,24 +202,20 @@ function parseOnlyCommand(remainder) {
179
202
  let leading = null;
180
203
  let trailing = null;
181
204
  let invalid = false;
182
- const leadingMatch = /^--(?:retries|max-retries)\s+(\S+)\s*/i.exec(body);
205
+ const leadingMatch = /^--(?:retries|max-retries)(?:\s+|=)(\S+)\s*/i.exec(body);
183
206
  if (leadingMatch) {
184
207
  const parsed = parsePositiveIntToken(leadingMatch[1]);
185
208
  if (parsed === null) invalid = true;
186
209
  else leading = parsed;
187
210
  body = body.slice(leadingMatch[0].length).trim();
188
- } else if (/^--(?:retries|max-retries)(\s|$)/i.test(body)) {
189
- invalid = true;
190
- }
191
- const trailingMatch = /\s+--(?:retries|max-retries)\s+(\S+)\s*$/i.exec(body);
211
+ } else if (/^--(?:retries|max-retries)(?:\s*=\s*)?$/i.test(body)) invalid = true;
212
+ const trailingMatch = /\s+--(?:retries|max-retries)(?:\s+|=)(\S+)\s*$/i.exec(body);
192
213
  if (trailingMatch) {
193
214
  const parsed = parsePositiveIntToken(trailingMatch[1]);
194
215
  if (parsed === null) invalid = true;
195
216
  else trailing = parsed;
196
217
  body = body.slice(0, trailingMatch.index).trim();
197
- } else if (/\s+--(?:retries|max-retries)\s*$/i.test(body)) {
198
- invalid = true;
199
- }
218
+ } else if (/\s+--(?:retries|max-retries)(?:\s*=\s*)?$/i.test(body)) invalid = true;
200
219
  const maxRetries = leading ?? trailing ?? void 0;
201
220
  return {
202
221
  command: body,
@@ -205,11 +224,15 @@ function parseOnlyCommand(remainder) {
205
224
  };
206
225
  }
207
226
  function effectiveMaxRetries(state, configMaxRetries) {
208
- if (state.gateMode === "command-only" && state.sessionMaxRetries !== null) {
227
+ if (state.gateMode === "command-only" && state.sessionMaxRetries !== null)
209
228
  return { value: state.sessionMaxRetries, source: "session" };
210
- }
211
229
  return { value: configMaxRetries, source: "config" };
212
230
  }
231
+
232
+ // src/ado-pr.ts
233
+ import { existsSync as existsSync2, mkdirSync, mkdtempSync } from "fs";
234
+ import { join as join3 } from "path";
235
+ import { tmpdir } from "os";
213
236
  function pickActivePrDetails(prListJson) {
214
237
  let parsed;
215
238
  try {
@@ -217,25 +240,25 @@ function pickActivePrDetails(prListJson) {
217
240
  } catch {
218
241
  return { ok: false, reason: "unparsable", detail: "az repos pr list returned invalid JSON" };
219
242
  }
220
- if (!Array.isArray(parsed)) {
243
+ if (!Array.isArray(parsed))
221
244
  return { ok: false, reason: "unparsable", detail: "expected an array of PRs" };
222
- }
223
- if (parsed.length === 0) {
245
+ if (parsed.length === 0)
224
246
  return { ok: false, reason: "none", detail: "no active PR found for this branch" };
225
- }
226
- const ids = parsed.map((p) => typeof p?.pullRequestId === "number" ? p.pullRequestId : p?.id).filter((n) => typeof n === "number");
227
- if (ids.length !== parsed.length) {
247
+ const ids = parsed.map((p) => {
248
+ if (!p || typeof p !== "object") return void 0;
249
+ const entry = p;
250
+ return typeof entry.pullRequestId === "number" ? entry.pullRequestId : entry.id;
251
+ }).filter((n) => typeof n === "number");
252
+ if (ids.length !== parsed.length)
228
253
  return { ok: false, reason: "unparsable", detail: "PR entries missing numeric pullRequestId" };
229
- }
230
- if (ids.length > 1) {
254
+ if (ids.length > 1)
231
255
  return {
232
256
  ok: false,
233
257
  reason: "multiple",
234
258
  detail: `multiple active PRs for this branch: ${ids.join(", ")}`
235
259
  };
236
- }
237
- const projectName = typeof parsed[0]?.repository?.project?.name === "string" && parsed[0].repository.project.name.trim() ? parsed[0].repository.project.name : void 0;
238
- return projectName ? { ok: true, prId: ids[0], projectName } : { ok: true, prId: ids[0] };
260
+ const projectName = parsed[0].repository?.project?.name;
261
+ return typeof projectName === "string" && projectName.trim() ? { ok: true, prId: ids[0], projectName } : { ok: true, prId: ids[0] };
239
262
  }
240
263
  function pickActivePr(prListJson) {
241
264
  const result = pickActivePrDetails(prListJson);
@@ -347,57 +370,36 @@ function requiredPoliciesGreen(policyListJson, opts = {}) {
347
370
  }
348
371
  return { green: true, retryable: false, detail: greenDetail };
349
372
  }
350
- function quoteWin(s) {
351
- return /[\s"^&|<>]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
352
- }
353
- function buildShellInvocation(args) {
354
- if (process.platform !== "win32") return { file: args[0], args: args.slice(1) };
355
- const cmdline = [args[0], ...args.slice(1)].map(quoteWin).join(" ");
356
- return { file: process.env.ComSpec ?? "cmd.exe", args: ["/d", "/s", "/c", `"${cmdline}"`] };
357
- }
358
- var execShell = async (args, cwd, timeoutMs) => {
359
- const inv = buildShellInvocation(args);
360
- const r = await execFileOut(inv.file, inv.args, cwd, timeoutMs, {
361
- windowsVerbatimArguments: true
362
- });
363
- if (r.timedOut) throw new Error(`${args[0]} timed out`);
364
- if (r.code !== 0) {
365
- const detail = truncateTail([r.stderr, r.stdout].filter((s) => s.trim()).join("\n"), 20);
366
- throw new Error(`${args.join(" ")} failed (code ${r.code}):
367
- ${detail}`);
368
- }
369
- return r.stdout;
370
- };
371
373
  var BUILD_LOG_TIMEOUT_MS = 12e4;
372
374
  var defaultBuildLogExtractor = async (archivePath, destination, cwd, timeoutMs) => {
373
375
  const r = await execFileOut("tar", ["-xf", archivePath, "-C", destination], cwd, timeoutMs);
374
376
  if (r.timedOut) throw new Error(`tar timed out extracting ${archivePath}`);
375
- if (r.code !== 0) {
376
- const detail = truncateTail([r.stderr, r.stdout].filter((s) => s.trim()).join("\n"), 20);
377
- throw new Error(`tar failed (code ${r.code}): ${brief(detail)}`);
378
- }
377
+ if (r.code !== 0)
378
+ throw new Error(
379
+ `tar failed (code ${r.code}): ${brief(truncateTail([r.stderr, r.stdout].filter((s) => s.trim()).join("\n"), 20))}`
380
+ );
379
381
  };
380
382
  async function downloadBuildLogs(projectName, buildId, cwd, options = {}) {
381
383
  const timeoutMs = options.timeoutMs ?? BUILD_LOG_TIMEOUT_MS;
382
384
  const shell = options.shell ?? execShell;
383
385
  const extract = options.extract ?? defaultBuildLogExtractor;
384
386
  if (options.isAborted?.()) throw new GateAborted();
385
- const root = options.tempRoot ?? join(tmpdir(), "opencode");
387
+ const root = options.tempRoot ?? join3(tmpdir(), "opencode");
386
388
  try {
387
389
  mkdirSync(root, { recursive: true });
388
390
  } catch {
389
391
  }
390
392
  let workDir;
391
393
  try {
392
- workDir = mkdtempSync(join(root, `completion-gate-logs-${buildId}-`));
394
+ workDir = mkdtempSync(join3(root, `completion-gate-logs-${buildId}-`));
393
395
  } catch (err) {
394
396
  return {
395
397
  buildId,
396
- error: `could not create artifact directory under ${root}: ${err?.message ?? String(err)}`
398
+ error: `could not create artifact directory under ${root}: ${describeSdkError(err)}`
397
399
  };
398
400
  }
399
- const archivePath = join(workDir, `build-${buildId}-logs.zip`);
400
- const destination = join(workDir, "extracted");
401
+ const archivePath = join3(workDir, `build-${buildId}-logs.zip`);
402
+ const destination = join3(workDir, "extracted");
401
403
  logDiag(`build-logs "${projectName}" #${buildId}: downloading to ${archivePath}`);
402
404
  try {
403
405
  await shell(
@@ -428,24 +430,20 @@ async function downloadBuildLogs(projectName, buildId, cwd, options = {}) {
428
430
  );
429
431
  } catch (err) {
430
432
  logDiag(
431
- `build-logs "${projectName}" #${buildId}: download failed \u2014 ${brief(String(err?.message ?? err))}`
433
+ `build-logs "${projectName}" #${buildId}: download failed \u2014 ${brief(describeSdkError(err))}`
432
434
  );
433
- return { buildId, error: `download failed: ${err?.message ?? String(err)}` };
435
+ return { buildId, error: `download failed: ${describeSdkError(err)}` };
434
436
  }
435
- if (!existsSync(archivePath)) {
436
- logDiag(`build-logs "${projectName}" #${buildId}: az exited zero but wrote no archive file`);
437
+ if (!existsSync2(archivePath))
437
438
  return { buildId, error: "az devops invoke succeeded but produced no archive file" };
438
- }
439
439
  const result = { buildId, archivePath };
440
440
  if (options.isAborted?.()) throw new GateAborted();
441
441
  try {
442
442
  mkdirSync(destination, { recursive: true });
443
443
  await extract(archivePath, destination, cwd, timeoutMs);
444
444
  result.extractedPath = destination;
445
- logDiag(`build-logs "${projectName}" #${buildId}: extracted to ${destination}`);
446
445
  } catch (err) {
447
- result.error = `extraction failed: ${err?.message ?? String(err)}`;
448
- logDiag(`build-logs "${projectName}" #${buildId}: extraction failed \u2014 ${brief(result.error)}`);
446
+ result.error = `extraction failed: ${describeSdkError(err)}`;
449
447
  }
450
448
  return result;
451
449
  }
@@ -456,21 +454,15 @@ async function runAdoPrAssertion(a, cwd, shell, opts = {}) {
456
454
  const intervalMs = Math.max(5, a.pollIntervalSeconds) * 1e3;
457
455
  const deadline = now() + Math.max(1, a.pollTimeoutMinutes) * 6e4;
458
456
  let branch;
459
- logDiag(`ado-pr "${a.name}": resolving current branch`);
460
457
  try {
461
458
  branch = (await shell(["git", "-C", cwd, "branch", "--show-current"], cwd, 1e4)).trim();
462
459
  } catch (err) {
463
- return fail(a.name, `could not resolve current branch: ${err?.message ?? String(err)}`);
460
+ return fail(a.name, `could not resolve current branch: ${describeSdkError(err)}`);
464
461
  }
465
462
  if (!branch) return fail(a.name, "not on a branch (detached HEAD?) \u2014 nothing to check a PR for");
466
- logDiag(
467
- `ado-pr "${a.name}": branch="${branch}", polling every ${intervalMs / 1e3}s up to ${a.pollTimeoutMinutes} min`
468
- );
469
- let round = 0;
470
463
  try {
471
464
  for (; ; ) {
472
465
  if (opts.isAborted?.()) throw new GateAborted();
473
- round += 1;
474
466
  const listJson = await shell(
475
467
  [
476
468
  "az",
@@ -489,16 +481,12 @@ async function runAdoPrAssertion(a, cwd, shell, opts = {}) {
489
481
  );
490
482
  const pr = pickActivePrDetails(listJson);
491
483
  if (!pr.ok) {
492
- if (pr.reason === "none" && a.skipIfNoPr) {
493
- logDiag(`ado-pr "${a.name}": no active PR \u2014 skipIfNoPr=true, passing`);
494
- return pass(a.name);
495
- }
484
+ if (pr.reason === "none" && a.skipIfNoPr) return pass(a.name);
496
485
  return fail(
497
486
  a.name,
498
487
  pr.reason === "none" ? `no active PR for branch "${branch}" \u2014 open one before finishing` : pr.detail
499
488
  );
500
489
  }
501
- logDiag(`ado-pr "${a.name}": round ${round} \u2014 active PR !${pr.prId}, checking policies`);
502
490
  const policyJson = await shell(
503
491
  ["az", "repos", "pr", "policy", "list", "--id", String(pr.prId), "--output", "json"],
504
492
  cwd,
@@ -507,18 +495,13 @@ async function runAdoPrAssertion(a, cwd, shell, opts = {}) {
507
495
  const g = requiredPoliciesGreen(policyJson, {
508
496
  ignoreHumanPolicies: a.ignoreHumanPolicies === true
509
497
  });
510
- if (g.green) {
511
- logDiag(`ado-pr "${a.name}": PR !${pr.prId} green (${g.detail})`);
512
- return pass(a.name);
513
- }
498
+ if (g.green) return pass(a.name);
514
499
  if (!g.retryable) {
515
- const baseEvidence = `PR !${pr.prId} has terminal policy failure \u2014 ${g.detail}`;
516
- const buildFailures = extractTerminalBuildFailures(policyJson, {
517
- ignoreHumanPolicies: a.ignoreHumanPolicies === true
518
- });
519
500
  const artifactEvidence = [];
520
501
  const seenBuildIds = /* @__PURE__ */ new Set();
521
- for (const build of buildFailures) {
502
+ for (const build of extractTerminalBuildFailures(policyJson, {
503
+ ignoreHumanPolicies: a.ignoreHumanPolicies === true
504
+ })) {
522
505
  if (build.buildId !== null) {
523
506
  if (seenBuildIds.has(build.buildId)) continue;
524
507
  seenBuildIds.add(build.buildId);
@@ -552,29 +535,29 @@ async function runAdoPrAssertion(a, cwd, shell, opts = {}) {
552
535
  artifactEvidence.push(`Build log artifact error: ${artifact.error}`);
553
536
  } catch (err) {
554
537
  if (err instanceof GateAborted) throw err;
555
- artifactEvidence.push(`Build log artifact error: ${err?.message ?? String(err)}`);
538
+ artifactEvidence.push(`Build log artifact error: ${describeSdkError(err)}`);
556
539
  }
557
540
  }
558
- logDiag(
559
- `ado-pr "${a.name}": PR !${pr.prId} has terminal policy failure \u2014 ${brief(g.detail)}; stopping polling`
541
+ return fail(
542
+ a.name,
543
+ [`PR !${pr.prId} has terminal policy failure \u2014 ${g.detail}`, ...artifactEvidence].filter(Boolean).join("\n")
560
544
  );
561
- return fail(a.name, [baseEvidence, ...artifactEvidence].filter(Boolean).join("\n"));
562
545
  }
563
- logDiag(`ado-pr "${a.name}": PR !${pr.prId} not green yet \u2014 ${brief(g.detail)}`);
564
- if (now() + intervalMs >= deadline) {
546
+ if (now() + intervalMs >= deadline)
565
547
  return fail(
566
548
  a.name,
567
549
  `PR !${pr.prId} did not reach green within ${a.pollTimeoutMinutes} min \u2014 ${g.detail}`
568
550
  );
569
- }
570
551
  if (opts.isAborted?.()) throw new GateAborted();
571
552
  await sleep(intervalMs);
572
553
  }
573
554
  } catch (err) {
574
555
  if (err instanceof GateAborted) throw err;
575
- return fail(a.name, err?.message ?? String(err));
556
+ return fail(a.name, describeSdkError(err));
576
557
  }
577
558
  }
559
+
560
+ // src/review.ts
578
561
  function parseVerdict(output) {
579
562
  const matches = [...output.matchAll(/VERDICT:\s*\b(PASS|FAIL)\b/gi)];
580
563
  const last = matches[matches.length - 1];
@@ -583,10 +566,10 @@ function parseVerdict(output) {
583
566
  function unwrapSdk(res) {
584
567
  if (res && typeof res === "object" && ("data" in res || "error" in res)) {
585
568
  const r = res;
586
- if (r.error != null) {
587
- const e = r.error;
588
- throw new Error(typeof e === "string" ? e : e?.message ?? JSON.stringify(e));
589
- }
569
+ if (r.error != null)
570
+ throw new Error(
571
+ typeof r.error === "string" ? r.error : r.error && typeof r.error === "object" && "message" in r.error ? String(r.error.message) : JSON.stringify(r.error)
572
+ );
590
573
  return r.data;
591
574
  }
592
575
  return res;
@@ -594,22 +577,14 @@ function unwrapSdk(res) {
594
577
  function reviewerText(res) {
595
578
  const parts = res?.parts;
596
579
  if (!Array.isArray(parts)) return "";
597
- return parts.filter((p) => p?.type === "text").map((p) => String(p.text ?? "")).join("\n");
598
- }
599
- function describeSdkError(err) {
600
- if (err instanceof Error) return err.message;
601
- if (typeof err === "string") return err;
602
- try {
603
- return JSON.stringify(err);
604
- } catch {
605
- return String(err);
606
- }
580
+ return parts.filter(
581
+ (p) => !!p && typeof p === "object" && p.type === "text"
582
+ ).map((p) => String(p.text ?? "")).join("\n");
607
583
  }
608
584
  async function runReviewAssertion(a, cwd, client, isAborted) {
609
585
  if (isAborted?.()) throw new GateAborted();
610
586
  if (!client?.session)
611
587
  return fail(a.name, "no opencode SDK client available to run the reviewer session");
612
- logDiag(`review "${a.name}": creating reviewer session in ${cwd}`);
613
588
  const prompt = [
614
589
  a.prompt ?? "Review the changes on this branch against the task requirements.",
615
590
  'Finish your reply with a final line containing exactly "VERDICT: PASS" or "VERDICT: FAIL" followed by a one-line justification.'
@@ -621,9 +596,6 @@ async function runReviewAssertion(a, cwd, client, isAborted) {
621
596
  const sessionId = created?.id;
622
597
  if (!sessionId)
623
598
  return fail(a.name, "could not create reviewer session (no session id in response)");
624
- logDiag(
625
- `review "${a.name}": reviewer session ${sessionId} \u2014 prompting agent "${a.agent}" (timeout=${a.timeoutSeconds}s)`
626
- );
627
599
  let timer;
628
600
  try {
629
601
  const raced = await Promise.race([
@@ -639,9 +611,6 @@ async function runReviewAssertion(a, cwd, client, isAborted) {
639
611
  })
640
612
  ]);
641
613
  if ("timedOut" in raced) {
642
- logDiag(
643
- `review "${a.name}": TIMED OUT after ${a.timeoutSeconds}s \u2014 aborting reviewer session`
644
- );
645
614
  try {
646
615
  await Promise.resolve(client.session.abort?.({ path: { id: sessionId } }));
647
616
  } catch {
@@ -651,9 +620,7 @@ async function runReviewAssertion(a, cwd, client, isAborted) {
651
620
  `review timed out after ${a.timeoutSeconds}s (reviewer session aborted)`
652
621
  );
653
622
  }
654
- if (!raced.ok) {
655
- return fail(a.name, `reviewer session failed: ${describeSdkError(raced.err)}`);
656
- }
623
+ if (!raced.ok) return fail(a.name, `reviewer session failed: ${describeSdkError(raced.err)}`);
657
624
  const text = reviewerText(unwrapSdk(raced.r));
658
625
  const verdict = parseVerdict(text);
659
626
  logDiag(`review "${a.name}": verdict=${verdict ?? "none"}`);
@@ -670,8 +637,25 @@ ${evidence}`);
670
637
  return fail(a.name, `reviewer session failed: ${describeSdkError(err)}`);
671
638
  }
672
639
  }
673
- var GateAborted = class extends Error {
674
- };
640
+
641
+ // src/gate.ts
642
+ async function runCommandAssertion(a, cwd, isAborted) {
643
+ if (isAborted?.()) throw new GateAborted();
644
+ logDiag(
645
+ `command "${a.name}": running ${JSON.stringify(a.run)} (cwd=${cwd}, timeout=${a.timeoutSeconds}s)`
646
+ );
647
+ const r = await runCommand(a.run, cwd, a.timeoutSeconds * 1e3);
648
+ logDiag(
649
+ r.timedOut ? `command "${a.name}": TIMED OUT after ${a.timeoutSeconds}s` : `command "${a.name}": exit code ${r.code}`
650
+ );
651
+ if (!r.timedOut && r.code === 0) return { name: a.name, passed: true, evidence: "" };
652
+ const why = r.timedOut ? `command timed out after ${a.timeoutSeconds}s` : `exit code ${r.code}`;
653
+ return fail(
654
+ a.name,
655
+ `${why}
656
+ ${truncateTail([r.stderr, r.stdout].filter((s) => s.trim()).join("\n---\n"))}`
657
+ );
658
+ }
675
659
  async function evaluateAssertions(assertions, projectRoot, client, isAborted, adoOpts) {
676
660
  const results = [];
677
661
  for (const a of assertions) {
@@ -691,7 +675,7 @@ async function evaluateAssertions(assertions, projectRoot, client, isAborted, ad
691
675
  logDiag(`assertion "${a.name}" aborted mid-run`);
692
676
  return null;
693
677
  }
694
- result = fail(a.name, `gate could not run this assertion: ${err?.message ?? String(err)}`);
678
+ result = fail(a.name, `gate could not run this assertion: ${describeSdkError(err)}`);
695
679
  }
696
680
  results.push(result);
697
681
  if (!result.passed) {