Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

fix bedrock provider loading in packaged cli installs (#2134)

kte8b7168cc997
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2fca23f717..17e520f3ac 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -50,8 +50,11 @@ jobs:
- name: Install system dependencies
run: |
- sudo apt-get update
- sudo apt-get install -y libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev fd-find ripgrep
+ # These dependencies come from Ubuntu, not the runner's third-party repositories.
+ test -f /etc/apt/sources.list.d/ubuntu.sources
+ apt_sources=(-o Dir::Etc::sourcelist=/etc/apt/sources.list.d/ubuntu.sources -o Dir::Etc::sourceparts=-)
+ sudo apt-get "${apt_sources[@]}" update
+ sudo apt-get "${apt_sources[@]}" install -y libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev fd-find ripgrep
sudo ln -s $(which fdfind) /usr/local/bin/fd
- name: Install dependencies
@@ -123,8 +126,11 @@ jobs:
- name: Install system dependencies
run: |
- sudo apt-get update
- sudo apt-get install -y libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev fd-find ripgrep
+ # These dependencies come from Ubuntu, not the runner's third-party repositories.
+ test -f /etc/apt/sources.list.d/ubuntu.sources
+ apt_sources=(-o Dir::Etc::sourcelist=/etc/apt/sources.list.d/ubuntu.sources -o Dir::Etc::sourceparts=-)
+ sudo apt-get "${apt_sources[@]}" update
+ sudo apt-get "${apt_sources[@]}" install -y libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev fd-find ripgrep
sudo ln -s $(which fdfind) /usr/local/bin/fd
- name: Install dependencies
diff --git a/.github/workflows/linear-ticket.yml b/.github/workflows/linear-ticket.yml
index 7fa32d98d9..0346efbf42 100644
--- a/.github/workflows/linear-ticket.yml
+++ b/.github/workflows/linear-ticket.yml
@@ -20,7 +20,7 @@ jobs:
script: |
const pr = context.payload.pull_request;
const text = `${pr.title}\n${pr.body ?? ""}\n${pr.head.ref}`;
- const ticket = /\b(?:eng|res)-\d+\b|linear\.app\/[\w-]+\/issue\/(?:eng|res)-\d+/i;
+ const ticket = /\b(?:eng|res)-\d+\b/i;
const optOut = /^\s*No-Ticket:\s*\S.*$/im;
if (ticket.test(text)) {
core.info("Linear ticket reference found.");
diff --git a/package.json b/package.json
index 26995da820..5f7efd314b 100644
--- a/package.json
+++ b/package.json
@@ -14,7 +14,8 @@
"build": "cd packages/tui && npm run build && cd ../ai && npm run build && cd ../agent && npm run build && cd ../coding-agent && npm run build",
"dev": "concurrently --names \"ai,agent,coding-agent,tui\" --prefix-colors \"cyan,yellow,red,magenta\" \"cd packages/ai && npm run dev\" \"cd packages/agent && npm run dev\" \"cd packages/coding-agent && npm run dev\" \"cd packages/tui && npm run dev\"",
"dev:tsc": "cd packages/ai && npm run dev:tsc",
- "check": "biome check --write --error-on-warnings . && tsgo --noEmit && npm run check:installer && npm run check:browser-smoke",
+ "check": "biome check --write --error-on-warnings . && tsgo --noEmit && npm run check:linear-ticket && npm run check:installer && npm run check:browser-smoke",
+ "check:linear-ticket": "node scripts/check-linear-ticket.mjs",
"check:installer": "node scripts/check-installer.mjs",
"check:browser-smoke": "node scripts/check-browser-smoke.mjs",
"profile:tui": "node scripts/profile-coding-agent-node.mjs --mode tui",
diff --git a/packages/ai/.changes/eng-6006-bedrock-cli-provider.md b/packages/ai/.changes/eng-6006-bedrock-cli-provider.md
new file mode 100644
index 0000000000..82656e03e7
--- /dev/null
+++ b/packages/ai/.changes/eng-6006-bedrock-cli-provider.md
@@ -0,0 +1 @@
+- Added log sink configuration to the Bedrock provider entry so bundled consumers can preserve structured diagnostics.
diff --git a/packages/ai/src/bedrock-provider.ts b/packages/ai/src/bedrock-provider.ts
index 0730541893..51051bdf74 100644
--- a/packages/ai/src/bedrock-provider.ts
+++ b/packages/ai/src/bedrock-provider.ts
@@ -1,5 +1,7 @@
import { streamBedrock, streamSimpleBedrock } from "./providers/amazon-bedrock.js";
+export { setLogSink } from "./log.js";
+
export const bedrockProviderModule = {
streamBedrock,
streamSimpleBedrock,
diff --git a/packages/coding-agent/.changes/eng-6006-bedrock-cli-provider.md b/packages/coding-agent/.changes/eng-6006-bedrock-cli-provider.md
new file mode 100644
index 0000000000..f310f3fc3e
--- /dev/null
+++ b/packages/coding-agent/.changes/eng-6006-bedrock-cli-provider.md
@@ -0,0 +1,2 @@
+- Fixed Amazon Bedrock requests failing to load the provider in packaged CLI installations.
+- Fixed Bedrock provider failures losing structured error severity and worker context in the shared CLI log.
diff --git a/packages/coding-agent/scripts/bundle.mjs b/packages/coding-agent/scripts/bundle.mjs
index c14d432123..d8bdbf75af 100644
--- a/packages/coding-agent/scripts/bundle.mjs
+++ b/packages/coding-agent/scripts/bundle.mjs
@@ -13,7 +13,7 @@
*/
import { chmodSync, readFileSync, rmSync } from "node:fs";
import { execFileSync } from "node:child_process";
-import { dirname, join } from "node:path";
+import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { build } from "esbuild";
@@ -31,16 +31,28 @@ try {
rmSync(outdir, { recursive: true, force: true });
-await build({
- entryPoints: [join(packageDir, "dist", "cli.js")],
+const result = await build({
+ entryPoints: {
+ cli: join(packageDir, "dist", "cli.js"),
+ // The Node-only lazy loader uses a variable import that esbuild cannot discover.
+ "amazon-bedrock": join(packageDir, "dist", "node", "amazon-bedrock.js"),
+ },
outdir,
bundle: true,
+ metafile: true,
splitting: true,
format: "esm",
platform: "node",
// Native or interop-sensitive packages stay external; they resolve from
// node_modules at runtime (and are loaded via createRequire/lazily anyway).
- external: ["koffi", "undici", "@silvia-odwyer/photon-node", "@mariozechner/clipboard"],
+ external: [
+ "koffi",
+ "undici",
+ "@silvia-odwyer/photon-node",
+ "@mariozechner/clipboard",
+ // Preserve Node's CommonJS interop for the AWS SDK's lazy transport imports.
+ "@earendil-works/pi-ai/bedrock-provider",
+ ],
define: { __PI_BUNDLED__: "true", __PI_BUILD_ID__: JSON.stringify(buildId) },
banner: {
js: "import { createRequire as __piBundleCreateRequire } from 'node:module'; const require = __piBundleCreateRequire(import.meta.url);",
@@ -48,5 +60,14 @@ await build({
logLevel: "warning",
});
+const bedrockOutput = Object.entries(result.metafile.outputs).find(
+ ([path]) => resolve(path) === join(outdir, "amazon-bedrock.js"),
+)?.[1];
+for (const name of ["streamBedrock", "streamSimpleBedrock"]) {
+ if (!bedrockOutput?.exports.includes(name)) {
+ throw new Error(`Bedrock bundle is missing the ${name} export`);
+ }
+}
+
chmodSync(join(outdir, "cli.js"), 0o755);
console.log("bundled dist/cli.js -> dist/bundle/");
diff --git a/packages/coding-agent/src/core/logging.ts b/packages/coding-agent/src/core/logging.ts
index 44ed72f13e..4c64994d00 100644
--- a/packages/coding-agent/src/core/logging.ts
+++ b/packages/coding-agent/src/core/logging.ts
@@ -10,6 +10,10 @@ export function setLogContext(fields: Record<string, unknown>): void {
Object.assign(context, fields);
}
+export function writeFileLogEntry(entry: LogEntry): void {
+ appendRotatingLog(getAgentLogPath(), stringifyLogEntry({ ...entry, ...context }), AGENT_LOG_MAX_BYTES);
+}
+
/**
* Route all structured logging (coding-agent and pi-ai) to the shared JSONL
* log at ~/.prime/agent/logs/agent.jsonl. One master file, filterable by the
@@ -17,7 +21,5 @@ export function setLogContext(fields: Record<string, unknown>): void {
*/
export function installFileLogSink(fields?: Record<string, unknown>): void {
context = { pid: process.pid, ...fields };
- setLogSink((entry: LogEntry) => {
- appendRotatingLog(getAgentLogPath(), stringifyLogEntry({ ...entry, ...context }), AGENT_LOG_MAX_BYTES);
- });
+ setLogSink(writeFileLogEntry);
}
diff --git a/packages/coding-agent/src/node/amazon-bedrock.ts b/packages/coding-agent/src/node/amazon-bedrock.ts
new file mode 100644
index 0000000000..af98f20fd7
--- /dev/null
+++ b/packages/coding-agent/src/node/amazon-bedrock.ts
@@ -0,0 +1,7 @@
+import { bedrockProviderModule, setLogSink } from "@earendil-works/pi-ai/bedrock-provider";
+import { writeFileLogEntry } from "../core/logging.js";
+
+// The external provider has its own logger instance; keep the CLI's sink and context.
+setLogSink(writeFileLogEntry);
+
+export const { streamBedrock, streamSimpleBedrock } = bedrockProviderModule;
diff --git a/packages/coding-agent/test/suite/regressions/6006-bundled-bedrock.test.ts b/packages/coding-agent/test/suite/regressions/6006-bundled-bedrock.test.ts
new file mode 100644
index 0000000000..4434dedfe5
--- /dev/null
+++ b/packages/coding-agent/test/suite/regressions/6006-bundled-bedrock.test.ts
@@ -0,0 +1,317 @@
+import { execFile, spawn } from "node:child_process";
+import { once } from "node:events";
+import { existsSync, readFileSync, writeFileSync } from "node:fs";
+import { createServer, type Server } from "node:http";
+import { join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { promisify } from "node:util";
+import { type AssistantMessage, fauxAssistantMessage, type LogEntry } from "@earendil-works/pi-ai";
+import { EventStreamCodec } from "@smithy/core/event-streams";
+import { afterEach, beforeAll, describe, expect, it } from "vitest";
+import type { AgentSessionEvent } from "../../../src/core/agent-session.js";
+import { getProcessStartId } from "../../../src/core/session-lease.js";
+import { DaemonClient } from "../../../src/modes/daemon/daemon-client.js";
+import { DAEMON_PROTOCOL_VERSION } from "../../../src/modes/daemon/daemon-protocol.js";
+import { isProcessAlive } from "../../../src/utils/child-process.js";
+import { killProcessTree } from "../../../src/utils/shell.js";
+import { createHarness, getAssistantTexts, type Harness } from "../harness.js";
+
+const run = promisify(execFile);
+const packageDir = fileURLToPath(new URL("../../../", import.meta.url));
+const installedCli = process.env.PRIME_AGENT_TEST_BUNDLED_CLI;
+const cliPath = installedCli ? resolve(installedCli) : join(packageDir, "dist/bundle/cli.js");
+const codec = new EventStreamCodec(
+ (bytes) => new TextDecoder().decode(bytes),
+ (text) => new TextEncoder().encode(text),
+);
+
+function encodeEvent(type: string, body: unknown): Uint8Array {
+ return codec.encode({
+ headers: {
+ ":message-type": { type: "string", value: "event" },
+ ":event-type": { type: "string", value: type },
+ ":content-type": { type: "string", value: "application/json" },
+ },
+ body: new TextEncoder().encode(JSON.stringify(body)),
+ });
+}
+
+describe("ENG-6006 bundled Bedrock provider", () => {
+ let harness: Harness | undefined;
+ let server: Server | undefined;
+ let socketPath: string | undefined;
+
+ beforeAll(async () => {
+ if (!installedCli) {
+ await run(process.execPath, ["scripts/bundle.mjs"], { cwd: packageDir, timeout: 30_000 });
+ }
+ });
+
+ async function cleanupFixture(exitTimeoutMs = 10_000): Promise<void> {
+ const fixture = { harness, server, socketPath };
+ harness = undefined;
+ server = undefined;
+ socketPath = undefined;
+ let client: DaemonClient | undefined;
+ let supervisor: { pid: number; startId: string } | undefined;
+ try {
+ if (fixture.socketPath && existsSync(fixture.socketPath)) {
+ client = new DaemonClient(fixture.socketPath);
+ await client.connect(1000);
+ const { supervisorPid } = await client.waitForHello();
+ if (!supervisorPid) throw new Error("Missing fixture supervisor PID");
+ const startId = getProcessStartId(supervisorPid);
+ if (!startId) throw new Error("Missing fixture supervisor process identity");
+ supervisor = { pid: supervisorPid, startId };
+ const response = await client.request({ type: "shutdown", force: true }, 5000);
+ if (!response.success) throw new Error(response.error);
+ client.close();
+ // The shutdown response precedes the daemon's final file writes.
+ await expect.poll(() => isProcessAlive(supervisorPid), { timeout: exitTimeoutMs }).toBe(false);
+ }
+ } finally {
+ client?.close();
+ try {
+ if (
+ supervisor &&
+ isProcessAlive(supervisor.pid) &&
+ getProcessStartId(supervisor.pid) === supervisor.startId
+ ) {
+ const { pid } = supervisor;
+ killProcessTree(pid);
+ await expect.poll(() => isProcessAlive(pid), { timeout: 2000 }).toBe(false);
+ }
+ } finally {
+ try {
+ if (fixture.server) {
+ fixture.server.closeAllConnections();
+ await new Promise<void>((done) => fixture.server!.close(() => done()));
+ }
+ } finally {
+ fixture.harness?.cleanup();
+ }
+ }
+ }
+ }
+
+ // Budget for the handshake, shutdown, exit waits, and the harness's bounded filesystem retries.
+ afterEach(() => cleanupFixture(), 90_000);
+
+ it.each(["does not exit", "rejects shutdown"])("cleans up when the fixture supervisor %s", async (failure) => {
+ harness = await createHarness();
+ const tempDir = harness.tempDir;
+ server = createServer();
+ const fixtureServer = server;
+ await new Promise<void>((done) => fixtureServer.listen(0, "127.0.0.1", done));
+ socketPath = join(tempDir, "unresponsive.sock");
+ const child = spawn(
+ process.execPath,
+ [
+ "--input-type=module",
+ "--eval",
+ [
+ 'import { createServer } from "node:net";',
+ 'import { createInterface } from "node:readline";',
+ "const [socketPath, failure, version] = process.argv.slice(1);",
+ "createServer((socket) => {",
+ ' const send = (message) => socket.write(JSON.stringify(message) + "\\n");',
+ ' send({ type: "daemon_hello", protocol: { version: Number(version) }, supervisorPid: process.pid });',
+ ' createInterface({ input: socket }).on("line", (line) => {',
+ " const request = JSON.parse(line);",
+ " const command = request.command ?? request;",
+ ' if (command.type === "shutdown") {',
+ ' send({ type: "response", id: request.id, command: "shutdown", success: failure !== "rejects shutdown", error: "fixture shutdown rejected" });',
+ " }",
+ " });",
+ '}).listen(socketPath, () => process.send("ready"));',
+ ].join("\n"),
+ socketPath,
+ failure,
+ String(DAEMON_PROTOCOL_VERSION),
+ ],
+ {
+ detached: true,
+ stdio: ["ignore", "ignore", "ignore", "ipc"],
+ env: { PATH: process.env.PATH, HOME: tempDir },
+ },
+ );
+ try {
+ await once(child, "message", { signal: AbortSignal.timeout(5000) });
+ await expect(cleanupFixture(50)).rejects.toThrow();
+ expect(isProcessAlive(child.pid!)).toBe(false);
+ expect(fixtureServer.listening).toBe(false);
+ expect(existsSync(tempDir)).toBe(false);
+ } finally {
+ child.kill("SIGKILL");
+ }
+ });
+
+ it("keeps Bedrock unloaded when the bundled CLI starts without a request", async () => {
+ harness = await createHarness();
+ const hookPath = join(harness.tempDir, "reject-bedrock.mjs");
+ writeFileSync(
+ hookPath,
+ `import { registerHooks } from "node:module";
+registerHooks({
+ resolve(specifier, context, nextResolve) {
+ if (specifier.includes("amazon-bedrock") || specifier === "@earendil-works/pi-ai/bedrock-provider" || specifier === "@aws-sdk/client-bedrock-runtime") {
+ throw new Error("Bedrock loaded before a request");
+ }
+ return nextResolve(specifier, context);
+ },
+});`,
+ );
+ const { stdout, stderr } = await run(process.execPath, ["--import", hookPath, cliPath, "--offline", "--help"], {
+ cwd: harness.tempDir,
+ timeout: 20_000,
+ env: { PATH: process.env.PATH, HOME: harness.tempDir, PRIME_AGENT_CODING_AGENT_DIR: harness.tempDir },
+ });
+ expect(stdout + stderr).toContain("Usage:");
+ });
+
+ it.each([
+ { outcome: "success", transport: "http1" },
+ { outcome: "denied", transport: "http1" },
+ { outcome: "success", transport: "proxy" },
+ { outcome: "denied", transport: "proxy" },
+ ])("handles a local $outcome response through the bundled CLI with $transport", async ({ outcome, transport }) => {
+ harness = await createHarness({ settings: { retry: { enabled: false } } });
+ harness.setResponses([fauxAssistantMessage("bedrock bundle response")]);
+ await harness.session.prompt("Reply OK");
+ const expectedText = getAssistantTexts(harness)[0]!;
+ const requests: Array<{ method: string | undefined; path: string | undefined; body: string }> = [];
+ server = createServer(async (request, response) => {
+ const chunks: Buffer[] = [];
+ for await (const chunk of request) chunks.push(Buffer.from(chunk));
+ requests.push({ method: request.method, path: request.url, body: Buffer.concat(chunks).toString("utf8") });
+ if (outcome === "denied") {
+ response.writeHead(403, {
+ "content-type": "application/json",
+ "x-amzn-errortype": "AccessDeniedException",
+ "x-amzn-requestid": "bedrock-fixture-request",
+ });
+ response.end(JSON.stringify({ message: "bedrock fixture denied" }));
+ return;
+ }
+ response.writeHead(200, { "content-type": "application/vnd.amazon.eventstream" });
+ response.write(encodeEvent("messageStart", { role: "assistant" }));
+ response.write(encodeEvent("contentBlockDelta", { contentBlockIndex: 0, delta: { text: expectedText } }));
+ response.write(encodeEvent("contentBlockStop", { contentBlockIndex: 0 }));
+ response.write(encodeEvent("messageStop", { stopReason: "end_turn" }));
+ response.end(encodeEvent("metadata", { usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 } }));
+ });
+ await new Promise<void>((done) => server!.listen(0, "127.0.0.1", done));
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("Missing fixture address");
+ writeFileSync(join(harness.tempDir, "settings.json"), JSON.stringify({ retry: { enabled: false } }));
+ writeFileSync(
+ join(harness.tempDir, "models.json"),
+ JSON.stringify({ providers: { "amazon-bedrock": { baseUrl: `http://127.0.0.1:${address.port}` } } }),
+ );
+ socketPath = join(harness.tempDir, "d.sock");
+ const pending = run(
+ process.execPath,
+ [
+ cliPath,
+ "--daemon-socket",
+ socketPath,
+ "--offline",
+ "--mode",
+ "json",
+ "--no-session",
+ "--no-tools",
+ "--no-extensions",
+ "--no-skills",
+ "--no-context-files",
+ "--provider",
+ "amazon-bedrock",
+ "--model",
+ "amazon.nova-2-lite-v1:0",
+ "--api-key",
+ "fixture-not-a-real-key",
+ "-p",
+ "Reply OK",
+ ],
+ {
+ cwd: harness.tempDir,
+ timeout: 20_000,
+ maxBuffer: 2 * 1024 * 1024,
+ env: {
+ PATH: process.env.PATH,
+ HOME: harness.tempDir,
+ PRIME_AGENT_CODING_AGENT_DIR: harness.tempDir,
+ PI_OFFLINE: "1",
+ DO_NOT_TRACK: "1",
+ AWS_EC2_METADATA_DISABLED: "true",
+ AWS_BEDROCK_SKIP_AUTH: "1",
+ AWS_BEDROCK_FORCE_HTTP1: "1",
+ ...(transport === "proxy" ? { HTTP_PROXY: "http://127.0.0.1:9", NO_PROXY: "127.0.0.1" } : {}),
+ AWS_SHARED_CREDENTIALS_FILE: join(harness.tempDir, "no-credentials"),
+ AWS_CONFIG_FILE: join(harness.tempDir, "no-config"),
+ },
+ },
+ );
+ pending.child.stdin?.end();
+ const { stdout, stderr } = await pending;
+ expect(stderr).toBe("");
+ expect(stdout).not.toContain("Cannot find module");
+ expect(requests).toHaveLength(1);
+ expect(requests[0]).toMatchObject({ method: "POST", path: "/model/amazon.nova-2-lite-v1%3A0/converse-stream" });
+ expect(JSON.parse(requests[0]!.body).messages.at(-1)).toEqual({
+ role: "user",
+ content: [{ text: "Reply OK" }],
+ });
+ const messages = stdout
+ .trim()
+ .split("\n")
+ .flatMap((line): AssistantMessage[] => {
+ const event = JSON.parse(line) as AgentSessionEvent;
+ return event.type === "message_end" && event.message.role === "assistant" ? [event.message] : [];
+ });
+ expect(messages).toHaveLength(1);
+ if (outcome === "success") {
+ expect(messages[0]).toMatchObject({ stopReason: "stop", content: [{ type: "text", text: expectedText }] });
+ } else {
+ expect(messages[0]).toMatchObject({
+ stopReason: "error",
+ errorMessage: expect.stringContaining("bedrock fixture denied"),
+ diagnostics: expect.arrayContaining([
+ expect.objectContaining({
+ type: "provider_stream_failure",
+ details: expect.objectContaining({
+ kind: "permission",
+ providerErrorType: "AccessDeniedException",
+ requestId: "bedrock-fixture-request",
+ }),
+ }),
+ ]),
+ });
+ const logs = readFileSync(join(harness.tempDir, "logs", "agent.jsonl"), "utf8")
+ .trim()
+ .split("\n")
+ .map((line) => JSON.parse(line) as LogEntry);
+ const failures = logs.filter((entry) => entry.component === "ai.provider");
+ expect(failures).toEqual([
+ expect.objectContaining({
+ level: "error",
+ msg: "provider stream failure",
+ provider: "amazon-bedrock",
+ model: "amazon.nova-2-lite-v1:0",
+ api: "bedrock-converse-stream",
+ kind: "permission",
+ providerErrorType: "AccessDeniedException",
+ requestId: "bedrock-fixture-request",
+ message: expect.stringContaining("bedrock fixture denied"),
+ pid: expect.any(Number),
+ mode: "daemon",
+ }),
+ ]);
+ expect(failures[0]!.pid).not.toBe(pending.child.pid);
+ expect(
+ logs.filter(
+ (entry) => entry.component === "coding-agent.daemon-supervisor" && entry.msg.includes("ai.provider"),
+ ),
+ ).toEqual([]);
+ }
+ });
+});
diff --git a/packages/coding-agent/test/suite/regressions/6014-literal-prompt-arguments.test.ts b/packages/coding-agent/test/suite/regressions/6014-literal-prompt-arguments.test.ts
index 07e564e5e8..68b652bf1f 100644
--- a/packages/coding-agent/test/suite/regressions/6014-literal-prompt-arguments.test.ts
+++ b/packages/coding-agent/test/suite/regressions/6014-literal-prompt-arguments.test.ts
@@ -77,7 +77,7 @@ describe("ENG-6014 literal prompt arguments", () => {
await harness.session.prompt(command);
expect(getUserTexts(harness)).toEqual([expected]);
- expect(providerTexts).toEqual([expected]);
+ expect(providerTexts.at(-1)).toBe(expected);
expect(harness.faux.state.callCount).toBe(1);
} finally {
harness.cleanup();
diff --git a/scripts/check-linear-ticket.mjs b/scripts/check-linear-ticket.mjs
new file mode 100644
index 0000000000..3bb8529301
--- /dev/null
+++ b/scripts/check-linear-ticket.mjs
@@ -0,0 +1,77 @@
+#!/usr/bin/env node
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { compileFunction } from "node:vm";
+
+const workflow = readFileSync(new URL("../.github/workflows/linear-ticket.yml", import.meta.url), "utf8");
+const script = workflow.split(" script: |\n")[1];
+assert.ok(script, "Missing inline Linear ticket validator");
+const validate = compileFunction(script.replace(/^ {12}/gm, ""), ["context", "core"]);
+
+function run(pr) {
+ const messages = [];
+ const failures = [];
+ validate(
+ { payload: { pull_request: pr } },
+ { info: (message) => messages.push(message), setFailed: (message) => failures.push(message) },
+ );
+ return { messages, failures };
+}
+
+const valid = [
+ "ENG-6006",
+ "res-1234",
+ "fix/eng-6006-bedrock-provider",
+ "https://linear.app/primeintellect/issue/ENG-6006/bedrock-requests-fail-because-the-published-cli-is-missing-its",
+ "[Research](https://linear.app/primeintellect/issue/RES-1234/research)",
+ "https://linear.app/team/issue/ENG-123",
+ "https://linear.app/team/issue/res-123?view=details#comment",
+];
+const invalid = [
+ "",
+ "Fix Bedrock provider loading",
+ "ENG-",
+ "ENG-123not-a-ticket",
+ "RES-123suffix",
+ "ENG-123_suffix",
+ "SOMETHING-ENG-",
+ "NOTENG-123",
+ "https://linear.app/team/issue/ENG-123not-a-ticket",
+ "https://linear.app/team/issue/RES-123suffix",
+ "https://linear.app/team/issue/ENG-123_suffix",
+ "https://linear.app/team/issue/ENG-no-number",
+ "https://linear.app/team/issue/OTHER-123",
+];
+let cases = 0;
+for (const field of ["title", "body", "branch"]) {
+ for (const [references, expected] of [[valid, true], [invalid, false]]) {
+ for (const reference of references) {
+ const pr = { title: "Fix provider loading", body: "Validation details", head: { ref: "fix/provider" } };
+ if (field === "branch") pr.head.ref = reference;
+ else pr[field] = reference;
+ const result = run(pr);
+ assert.equal(result.failures.length, expected ? 0 : 1, `${field}: ${JSON.stringify(reference)}`);
+ assert.deepEqual(result.messages, expected ? ["Linear ticket reference found."] : []);
+ cases++;
+ }
+ }
+}
+
+for (const body of [undefined, "No-Ticket:", "No-Ticket: ", "No-Ticket:\n"]) {
+ assert.equal(run({ title: "Fix provider", body, head: { ref: "fix/provider" } }).failures.length, 1);
+ cases++;
+}
+const optOut = run({ title: "Update tooling", body: "No-Ticket: internal maintenance", head: { ref: "chore/tooling" } });
+assert.deepEqual(optOut.failures, []);
+assert.deepEqual(optOut.messages, ["No-ticket opt-out present: No-Ticket: internal maintenance"]);
+cases++;
+
+if (process.argv[2]) {
+ const pr = JSON.parse(readFileSync(process.argv[2], "utf8"));
+ assert.deepEqual(run({ title: pr.title, body: pr.body, head: { ref: pr.headRefName } }), {
+ messages: ["Linear ticket reference found."],
+ failures: [],
+ });
+ cases++;
+}
+console.log(`Linear ticket check passed (${cases} cases).`);