@miraland-labs/conduit-bridge 0.11.4 → 0.11.7

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.
@@ -6,6 +6,8 @@
6
6
  import { execFile } from "node:child_process";
7
7
  import { promisify } from "node:util";
8
8
  const execFileAsync = promisify(execFile);
9
+ /** Mirror execution.ts FORGE_TRANSPORT_PATTERN — keep local to avoid import cycles. */
10
+ const FORGE_TRANSPORT_PATTERN = /unable to access '?https?:\/\/|error in the http2 framing layer|could not resolve host|connection (?:reset|timed out|refused)|\bcurl\b.*\b(?:52|55|56|92)\b|remote end hung up unexpectedly|\brpc failed\b|tls handshake|network is unreachable|operation timed out/i;
9
11
  export function needsPullRequest(report, spec, grants) {
10
12
  return Boolean(grants.includes("pr_create")
11
13
  && (spec.change_scope?.length ?? 0) > 0
@@ -28,6 +30,23 @@ export function commitsMatch(reported, actual) {
28
30
  return false;
29
31
  return left === right || left.startsWith(right) || right.startsWith(left);
30
32
  }
33
+ /**
34
+ * Agents often put the PR URL only on evidence.uri and omit pull_request_url.
35
+ * Adopt it so finalize does not re-push and die on a forge blip after the PR already exists.
36
+ */
37
+ export function adoptPullRequestUrlFromEvidence(report) {
38
+ if (report.pull_request_url && isAbsoluteHttpsUrl(report.pull_request_url))
39
+ return report;
40
+ for (const item of report.evidence) {
41
+ const uri = item.uri?.trim();
42
+ if (!uri || !isAbsoluteHttpsUrl(uri))
43
+ continue;
44
+ if (/\/(?:pull|merge_requests)\/\d+/i.test(uri)) {
45
+ return { ...report, pull_request_url: uri };
46
+ }
47
+ }
48
+ return report;
49
+ }
31
50
  async function workspaceHeadCommit(workspace) {
32
51
  const { stdout } = await execFileAsync("git", ["-C", workspace, "rev-parse", "HEAD"], {
33
52
  timeout: 30_000,
@@ -38,13 +57,72 @@ async function workspaceHeadCommit(workspace) {
38
57
  throw new Error("Could not determine workspace HEAD commit");
39
58
  return head;
40
59
  }
60
+ function execErrorMessage(error) {
61
+ if (!(error instanceof Error))
62
+ return String(error);
63
+ const err = error;
64
+ const parts = [err.message, err.stderr, err.stdout].filter((part) => Boolean(part && String(part).trim()));
65
+ return parts.join("\n");
66
+ }
67
+ async function sleep(ms) {
68
+ await new Promise((resolve) => setTimeout(resolve, ms));
69
+ }
70
+ /** Push with short forge-transport retries; succeed if remote already has HEAD. */
71
+ export async function pushOriginHead(workspace, options = {}) {
72
+ const attempts = options.attempts ?? 3;
73
+ const execGit = options.execGit ?? (async (args) => {
74
+ const { stdout, stderr } = await execFileAsync("git", ["-C", workspace, ...args], {
75
+ timeout: 120_000,
76
+ maxBuffer: 2_000_000,
77
+ });
78
+ return { stdout: String(stdout), stderr: String(stderr) };
79
+ });
80
+ let lastMessage = "git push failed";
81
+ for (let attempt = 1; attempt <= attempts; attempt++) {
82
+ try {
83
+ await execGit(["push", "-u", "origin", "HEAD"]);
84
+ return;
85
+ }
86
+ catch (error) {
87
+ lastMessage = execErrorMessage(error);
88
+ // Remote may already have the branch from the agent's own push.
89
+ try {
90
+ const head = (await execGit(["rev-parse", "HEAD"])).stdout.trim().toLowerCase();
91
+ const remote = (await execGit(["ls-remote", "origin", "HEAD"])).stdout.trim().split(/\s+/)[0]?.toLowerCase() ?? "";
92
+ // Also check the current branch tip on origin.
93
+ const branch = (await execGit(["branch", "--show-current"])).stdout.trim();
94
+ const remoteBranch = branch
95
+ ? (await execGit(["ls-remote", "origin", `refs/heads/${branch}`])).stdout.trim().split(/\s+/)[0]?.toLowerCase() ?? ""
96
+ : "";
97
+ if (head && (commitsMatch(head, remote) || commitsMatch(head, remoteBranch))) {
98
+ return;
99
+ }
100
+ }
101
+ catch {
102
+ // fall through to retry / throw
103
+ }
104
+ if (attempt < attempts && FORGE_TRANSPORT_PATTERN.test(lastMessage)) {
105
+ await sleep(750 * attempt);
106
+ continue;
107
+ }
108
+ if (attempt < attempts && /Command failed:\s*git\b.*\bpush\b/i.test(lastMessage) && !lastMessage.includes("rejected")) {
109
+ // Empty stderr push failures are often transient HTTP/2; retry once more.
110
+ await sleep(750 * attempt);
111
+ continue;
112
+ }
113
+ throw new Error(lastMessage);
114
+ }
115
+ }
116
+ throw new Error(lastMessage);
117
+ }
41
118
  /**
42
119
  * Bind reported head_commit to the checkout HEAD, then open a PR when still needed.
43
120
  * Agent-supplied PR URLs skip creation but still require HEAD identity.
44
121
  */
45
122
  export async function ensureDeliveryPullRequest(input) {
46
123
  const readHead = input.readHeadCommit ?? workspaceHeadCommit;
47
- let report = input.report;
124
+ const push = input.pushOriginHead ?? pushOriginHead;
125
+ let report = adoptPullRequestUrlFromEvidence(input.report);
48
126
  if (report.head_commit && (input.spec.change_scope?.length ?? 0) > 0) {
49
127
  const head = await readHead(input.workspace);
50
128
  if (!commitsMatch(report.head_commit, head)) {
@@ -54,10 +132,7 @@ export async function ensureDeliveryPullRequest(input) {
54
132
  }
55
133
  if (!needsPullRequest(report, input.spec, input.grants))
56
134
  return report;
57
- await execFileAsync("git", ["-C", input.workspace, "push", "-u", "origin", "HEAD"], {
58
- timeout: 120_000,
59
- maxBuffer: 2_000_000,
60
- });
135
+ await push(input.workspace);
61
136
  const headAfterPush = await readHead(input.workspace);
62
137
  if (!report.head_commit || !commitsMatch(report.head_commit, headAfterPush)) {
63
138
  throw new Error(`Workspace HEAD changed during push (${report.head_commit} → ${headAfterPush})`);
@@ -0,0 +1,113 @@
1
+ /**
2
+ * When the contract requires test evidence and the agent forgot to paste command output,
3
+ * Bridge runs one bounded verification command and attaches the verbatim result — same
4
+ * mechanical-land pattern as ensureDeliveryPullRequest.
5
+ */
6
+ import { execFile } from "node:child_process";
7
+ import { promisify } from "node:util";
8
+ import { isBoundedVerificationCommand } from "./execution-class.js";
9
+ const execFileAsync = promisify(execFile);
10
+ const TEST_EVIDENCE_DETAILS_MIN = 32;
11
+ export function needsTestEvidence(report, spec, grants) {
12
+ if (!grants.includes("test_run"))
13
+ return false;
14
+ if (!(spec.required_evidence ?? []).includes("test"))
15
+ return false;
16
+ const existing = report.evidence.filter((item) => item.kind === "test");
17
+ if (existing.length === 0)
18
+ return true;
19
+ return existing.every((item) => item.details.join("\n").trim().length < TEST_EVIDENCE_DETAILS_MIN);
20
+ }
21
+ export function pickVerificationCommand(commands) {
22
+ for (const command of commands) {
23
+ const trimmed = command.trim();
24
+ if (trimmed && isBoundedVerificationCommand(trimmed))
25
+ return trimmed;
26
+ }
27
+ return null;
28
+ }
29
+ function argvForBoundedCommand(command) {
30
+ return command.trim().split(/\s+/);
31
+ }
32
+ async function defaultRunCommand(command, workspace) {
33
+ const argv = argvForBoundedCommand(command);
34
+ const bin = argv[0];
35
+ if (!bin)
36
+ throw new Error("Verification command is empty");
37
+ try {
38
+ const { stdout, stderr } = await execFileAsync(bin, argv.slice(1), {
39
+ cwd: workspace,
40
+ timeout: 120_000,
41
+ maxBuffer: 2_000_000,
42
+ env: process.env,
43
+ });
44
+ return { stdout: String(stdout), stderr: String(stderr), code: 0 };
45
+ }
46
+ catch (error) {
47
+ const err = error;
48
+ return {
49
+ stdout: String(err.stdout ?? ""),
50
+ stderr: String(err.stderr ?? err.message ?? "verification failed"),
51
+ code: typeof err.code === "number" ? err.code : 1,
52
+ };
53
+ }
54
+ }
55
+ function criteriaForTestEvidence(report, spec) {
56
+ const fromSpec = (spec.acceptance ?? []).filter(Boolean);
57
+ if (fromSpec.length > 0)
58
+ return fromSpec;
59
+ return report.acceptance_results.map((item) => item.criterion);
60
+ }
61
+ /**
62
+ * If test evidence is required and missing/thin, run one bounded verification command
63
+ * in the attempt workspace and attach verbatim stdout/stderr.
64
+ */
65
+ export async function ensureTestEvidence(input) {
66
+ if (!needsTestEvidence(input.report, input.spec, input.grants))
67
+ return input.report;
68
+ const command = pickVerificationCommand(input.verificationCommands);
69
+ if (!command) {
70
+ throw new Error("Agent report is missing required evidence: test (no bounded verification command available for Bridge to run)");
71
+ }
72
+ const run = input.runCommand ?? defaultRunCommand;
73
+ const result = await run(command, input.workspace);
74
+ // Silent success is valid for bounded targets like `make test` (`@test -f …` prints nothing).
75
+ // Still record an explicit no-output line so control-plane verbatim-detail checks pass.
76
+ const stdoutLines = result.stdout.trim() ? result.stdout.trim().split("\n") : [];
77
+ const stderrLines = result.stderr.trim() ? result.stderr.trim().split("\n") : [];
78
+ const details = [
79
+ `$ ${command}`,
80
+ ...stdoutLines,
81
+ ...stderrLines,
82
+ ...(stdoutLines.length === 0 && stderrLines.length === 0
83
+ ? ["(no stdout/stderr — command exited with the status below)"]
84
+ : []),
85
+ `exit ${result.code}`,
86
+ ].map((line) => line.slice(0, 4_000)).slice(0, 100);
87
+ if (result.code !== 0) {
88
+ throw new Error(`Verification failed (${command}): ${details.join("\n").slice(0, 2_000)}`);
89
+ }
90
+ if (details.join("\n").trim().length < TEST_EVIDENCE_DETAILS_MIN) {
91
+ throw new Error(`Verification produced insufficient output for test evidence (${command})`);
92
+ }
93
+ const withoutThinTest = input.report.evidence.filter((item) => {
94
+ if (item.kind !== "test")
95
+ return true;
96
+ return item.details.join("\n").trim().length >= TEST_EVIDENCE_DETAILS_MIN;
97
+ });
98
+ return {
99
+ ...input.report,
100
+ verification: input.report.verification.includes(command)
101
+ ? input.report.verification
102
+ : [...input.report.verification, `${command} — exit ${result.code}`],
103
+ evidence: [
104
+ ...withoutThinTest,
105
+ {
106
+ kind: "test",
107
+ name: command,
108
+ details,
109
+ acceptance_criteria: criteriaForTestEvidence(input.report, input.spec),
110
+ },
111
+ ],
112
+ };
113
+ }
package/dist/execution.js CHANGED
@@ -8,6 +8,7 @@ import { pickDriverForClaim, resolveDriverFuel } from "./drivers.js";
8
8
  import { attemptWorktreePath, createAttemptWorktree, proveResumeWorktree, quarantineAttemptWorktree, removeAttemptWorktree, } from "./attempt-worktree.js";
9
9
  import { buildWorkspaceBrief, ensureCommitAvailable, normalizeRepositoryUrl, resolveAttemptStartCommit } from "./brief.js";
10
10
  import { ensureDeliveryPullRequest } from "./ensure-pull-request.js";
11
+ import { ensureTestEvidence } from "./ensure-test-evidence.js";
11
12
  /** Feedback text for changes_requested summaries (plain string or `{ feedback }`). */
12
13
  function changesRequestedFeedback(summary) {
13
14
  if (!summary)
@@ -544,6 +545,14 @@ async function runClaimedAssignment(client, config, driver, workspace, brief, ta
544
545
  grants,
545
546
  title: task.objective,
546
547
  });
548
+ // Mechanical test path: agent often forgets verbatim make test / npm test output.
549
+ report = await ensureTestEvidence({
550
+ workspace: attemptWorkspace,
551
+ report,
552
+ spec,
553
+ grants,
554
+ verificationCommands: liveBrief?.verification ?? [],
555
+ });
547
556
  validateDeliveryReport(report, spec, grants);
548
557
  }
549
558
  catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miraland-labs/conduit-bridge",
3
- "version": "0.11.4",
3
+ "version": "0.11.7",
4
4
  "description": "Conduit Bridge CLI — join, connect, disconnect, multi-driver lanes, and run Claude Code / Codex / Cursor / OpenCode / Pi / Kiro / Antigravity agents for a Conduit organization",
5
5
  "type": "module",
6
6
  "bin": {