Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Fix five CLI and validation bugs from issue triage (#494)

Regan Bellc58bbaed0699
diff --git a/cli/package-lock.json b/cli/package-lock.json
index 8b469f6a2..471eabca4 100644
--- a/cli/package-lock.json
+++ b/cli/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@yc-software/qm",
- "version": "0.1.6",
+ "version": "0.1.7",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@yc-software/qm",
- "version": "0.1.6",
+ "version": "0.1.7",
"license": "MIT",
"bin": {
"qm": "dist/bin/qm.js"
diff --git a/cli/package.json b/cli/package.json
index 4fbc357d4..588271b14 100644
--- a/cli/package.json
+++ b/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@yc-software/qm",
- "version": "0.1.6",
+ "version": "0.1.7",
"license": "MIT",
"description": "Control-plane CLI for portable QM deployments on Docker, Fly, and AWS.",
"type": "module",
diff --git a/cli/src/config.ts b/cli/src/config.ts
index 2277e65cf..e5fc6ecf4 100644
--- a/cli/src/config.ts
+++ b/cli/src/config.ts
@@ -478,10 +478,42 @@ export function readConfigOrgId(path: string): string | undefined {
}
}
+const VALID_TOP_LEVEL_KEYS: ReadonlySet<string> = new Set([
+ "contract",
+ "orgId",
+ "publicUrl",
+ "apiUrl",
+ "target",
+ "model",
+ "modelProvider",
+ "basePort",
+ "services",
+ "plugins",
+ "skills",
+ "env",
+ "secretEnv",
+ "securityScreen",
+ "vms",
+ "imageOverrides",
+ "sandbox",
+ "appPrefix",
+ "region",
+ "flyOrg",
+ "imageFrom",
+ "deployAppPrefix",
+ "aws",
+]);
+
function validate(raw: unknown, path: string): QmConfig {
if (!isPlainObject(raw)) throw new CliError(`${path}: expected a JSON object`);
const o = raw;
+ for (const key of Object.keys(o)) {
+ if (!VALID_TOP_LEVEL_KEYS.has(key)) {
+ throw new CliError(`${path}: unknown top-level field ${JSON.stringify(key)}`);
+ }
+ }
+
const contract = o["contract"];
if (contract !== CONTRACT_VERSION) {
if (typeof contract === "number" && Number.isInteger(contract)) {
@@ -499,13 +531,18 @@ function validate(raw: unknown, path: string): QmConfig {
const publicUrl = o["publicUrl"];
if (typeof publicUrl !== "string" || !publicUrl.trim()) {
- throw new CliError(`${path}: "publicUrl" must be a non-empty http(s) URL`);
+ throw new CliError(`${path}: "publicUrl" must be a non-empty http(s) origin URL`);
}
try {
const parsed = new URL(publicUrl);
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error("protocol");
+ if (parsed.pathname !== "/" || parsed.search || parsed.hash || parsed.username || parsed.password)
+ throw new Error("origin");
+ if (parsed.hostname.endsWith(".")) throw new Error("trailing dot");
} catch {
- throw new CliError(`${path}: "publicUrl" must be a non-empty http(s) URL`);
+ throw new CliError(
+ `${path}: "publicUrl" must be a non-empty http(s) origin URL without credentials, a path, query, fragment, or trailing hostname dot`,
+ );
}
const apiUrl = o["apiUrl"];
@@ -796,13 +833,22 @@ function validateBrokerTrust(config: QmConfig, path: string, secrets?: ReadonlyM
}
}
+function isSlackIssuer(issuer: string): boolean {
+ try {
+ const host = new URL(issuer).hostname;
+ return host === "slack.com" || host.endsWith(".slack.com");
+ } catch {
+ return false;
+ }
+}
+
export function validatePortalTrust(config: QmConfig, path = "config", secrets?: ReadonlyMap<string, string>): void {
if (!config.services.includes("portal")) return;
if (config.services.includes("auth")) return validateBrokerTrust(config, path, secrets);
const env = config.env.portal ?? {};
const issuer = env.OIDC_ISSUER?.trim() || "https://slack.com";
const jwksUri = env.OIDC_JWKS_URI?.trim();
- if (issuer !== "https://slack.com" && isMissingOrPlaceholder(jwksUri)) {
+ if (!isSlackIssuer(issuer) && isMissingOrPlaceholder(jwksUri)) {
throw new CliError(`${path}: portal requires env.portal.OIDC_JWKS_URI when using a non-Slack OIDC issuer`);
}
if (jwksUri !== undefined) {
diff --git a/cli/src/slack-manifests.ts b/cli/src/slack-manifests.ts
index a7b65047c..8773570e1 100644
--- a/cli/src/slack-manifests.ts
+++ b/cli/src/slack-manifests.ts
@@ -32,10 +32,20 @@ export interface SlackManifests {
sso: string;
}
+function isSlackHost(value: string | undefined): boolean {
+ if (!value) return false;
+ try {
+ const host = new URL(value).hostname;
+ return host === "slack.com" || host.endsWith(".slack.com");
+ } catch {
+ return false;
+ }
+}
+
export function usesSlackOidc(config: QmConfig): boolean {
const portal = config.env.portal ?? {};
return ["OIDC_AUTH_ENDPOINT", "OIDC_TOKEN_ENDPOINT", "OIDC_USERINFO_ENDPOINT", "OIDC_ISSUER"].some((name) =>
- portal[name]?.includes("slack.com"),
+ isSlackHost(portal[name]),
);
}
diff --git a/cli/src/util.ts b/cli/src/util.ts
index c4da960fb..c3a738c3a 100644
--- a/cli/src/util.ts
+++ b/cli/src/util.ts
@@ -213,16 +213,37 @@ export function isInvalidSecret(name: string, value: string | undefined): boolea
);
}
+// One line of a dotenv file, following Node's --env-file semantics for the
+// `export ` prefix and quoted values ('', "", ``: the quotes are stripped and
+// \n expands to a newline inside double quotes). Two deliberate divergences
+// from Node, both pinned by tests: a `#` inside an unquoted value is part of
+// the value (tokens and URL fragments), and a quoted value ends on its own
+// line (writeEnvValue never emits multi-line values).
+function parseEnvLine(raw: string): [key: string, value: string] | undefined {
+ let line = raw.trim();
+ if (!line || line.startsWith("#")) return undefined;
+ if (line.startsWith("export ")) line = line.slice("export ".length).trimStart();
+ const eq = line.indexOf("=");
+ if (eq <= 0) return undefined;
+ const key = line.slice(0, eq).trim();
+ let value = line.slice(eq + 1).trim();
+ const quote = value[0];
+ if (quote === '"' || quote === "'" || quote === "`") {
+ const end = value.indexOf(quote, 1);
+ if (end > 0) {
+ value = value.slice(1, end);
+ if (quote === '"') value = value.replaceAll("\\n", "\n");
+ }
+ }
+ return [key, value];
+}
+
export function readEnvFile(path: string): Map<string, string> {
const out = new Map<string, string>();
if (!existsSync(path)) return out;
for (const raw of readFileSync(path, "utf8").split("\n")) {
- const line = raw.trim();
- if (!line || line.startsWith("#")) continue;
- const eq = line.indexOf("=");
- if (eq <= 0) continue;
- const key = line.slice(0, eq).trim();
- if (isEnvVarName(key)) out.set(key, line.slice(eq + 1));
+ const entry = parseEnvLine(raw);
+ if (entry && isEnvVarName(entry[0])) out.set(entry[0], entry[1]);
}
return out;
}
diff --git a/cli/test/config.test.ts b/cli/test/config.test.ts
index 7d62298de..8aed014ef 100644
--- a/cli/test/config.test.ts
+++ b/cli/test/config.test.ts
@@ -62,6 +62,12 @@ test("required fields: orgId, target, services (must include core), valid servic
const { config } = loadConfigAt(path);
assert.deepEqual(config.services, ["core", "web-ui", "admin", "portal"]);
});
+ withConfig({ unknownField: "bad" }, ({ path }) =>
+ assert.throws(() => loadConfigAt(path), /unknown top-level field "unknownField"/),
+ );
+ withConfig({ org_id: "acme" }, ({ path }) =>
+ assert.throws(() => loadConfigAt(path), /unknown top-level field "org_id"/),
+ );
});
test("apiUrl must be an http(s) origin URL; the trailing slash is stripped", () => {
@@ -84,6 +90,25 @@ test("apiUrl must be an http(s) origin URL; the trailing slash is stripped", ()
}
});
+test("publicUrl must be an http(s) origin URL on every target", () => {
+ withConfig({ publicUrl: "https://acme.example/" }, ({ path }) =>
+ assert.equal(loadConfigAt(path).config.publicUrl, "https://acme.example"),
+ );
+ for (const publicUrl of [
+ "",
+ "not a url",
+ "ftp://acme.example",
+ "https://acme.example/subpath",
+ "https://acme.example?x=1",
+ "https://user:[email protected]",
+ "https://acme.example.",
+ ]) {
+ withConfig({ publicUrl }, ({ path }) =>
+ assert.throws(() => loadConfigAt(path), /"publicUrl" must be a non-empty http\(s\) origin URL/),
+ );
+ }
+});
+
test("basePort must be a positive integer", () => {
withConfig({ basePort: 9000 }, ({ path }) => assert.equal(loadConfigAt(path).config.basePort, 9000));
withConfig({ basePort: -1 }, ({ path }) => assert.throws(() => loadConfigAt(path), /basePort/));
diff --git a/cli/test/slack-manifests.test.ts b/cli/test/slack-manifests.test.ts
new file mode 100644
index 000000000..58bc1ce4e
--- /dev/null
+++ b/cli/test/slack-manifests.test.ts
@@ -0,0 +1,24 @@
+import { test } from "node:test";
+import assert from "node:assert";
+import { usesSlackOidc } from "../src/slack-manifests.ts";
+import type { QmConfig } from "../src/config.ts";
+
+function configWithPortalEnv(env: Record<string, string>): QmConfig {
+ return { env: { portal: env } } as unknown as QmConfig;
+}
+
+test("usesSlackOidc matches by hostname, not substring", () => {
+ assert.equal(usesSlackOidc(configWithPortalEnv({ OIDC_ISSUER: "https://slack.com" })), true);
+ assert.equal(usesSlackOidc(configWithPortalEnv({ OIDC_ISSUER: "https://enterprise.slack.com" })), true);
+ assert.equal(
+ usesSlackOidc(configWithPortalEnv({ OIDC_AUTH_ENDPOINT: "https://slack.com/openid/connect/authorize" })),
+ true,
+ );
+ // substring lookalikes must not count as Slack
+ assert.equal(usesSlackOidc(configWithPortalEnv({ OIDC_ISSUER: "https://not-slack.com.example/idp" })), false);
+ assert.equal(usesSlackOidc(configWithPortalEnv({ OIDC_ISSUER: "https://evil-slack.com/auth" })), false);
+ assert.equal(usesSlackOidc(configWithPortalEnv({ OIDC_ISSUER: "https://slack.com.evil.example" })), false);
+ // malformed values fail closed
+ assert.equal(usesSlackOidc(configWithPortalEnv({ OIDC_ISSUER: "slack.com" })), false);
+ assert.equal(usesSlackOidc(configWithPortalEnv({})), false);
+});
diff --git a/cli/test/util.test.ts b/cli/test/util.test.ts
index f4a661efe..617b071fd 100644
--- a/cli/test/util.test.ts
+++ b/cli/test/util.test.ts
@@ -104,6 +104,39 @@ test("writeEnvValue rejects invalid keys and multi-line values", (t) => {
assert.throws(() => writeEnvValue(file, "GOOD_KEY", "a\nb"));
});
+test("readEnvFile matches Node --env-file for export prefixes and quoted values", (t) => {
+ const dir = mkdtempSync(join(tmpdir(), "qm-env-"));
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+ const file = join(dir, ".env");
+ writeFileSync(
+ file,
+ [
+ 'DQ="wrapped#value"',
+ "SQ='single'",
+ "BT=`tick`",
+ "export EXPORTED=yes",
+ 'ESCAPED="line1\\nline2"',
+ 'TRAILING="abc" rest is ignored',
+ 'UNCLOSED="keeps raw',
+ "SPACED= padded ",
+ "",
+ ].join("\n"),
+ );
+ assert.deepEqual(
+ [...readEnvFile(file)],
+ [
+ ["DQ", "wrapped#value"],
+ ["SQ", "single"],
+ ["BT", "tick"],
+ ["EXPORTED", "yes"],
+ ["ESCAPED", "line1\nline2"],
+ ["TRAILING", "abc"],
+ ["UNCLOSED", '"keeps raw'],
+ ["SPACED", "padded"],
+ ],
+ );
+});
+
async function withFakeStdin<T>(fn: (emit: (bytes: Buffer) => void) => Promise<T>): Promise<T> {
const { EventEmitter } = await import("node:events");
const fake = Object.assign(new EventEmitter(), {
diff --git a/plugins/portal/src/index.ts b/plugins/portal/src/index.ts
index 395064e37..f361018aa 100644
--- a/plugins/portal/src/index.ts
+++ b/plugins/portal/src/index.ts
@@ -118,6 +118,15 @@ const UPSTREAMS: Record<string, string> = {
};
const COOKIE_FOR: Record<string, string> = { "web-ui": "webuiuser", admin: "admin" };
+function isSlackIssuer(issuer: string): boolean {
+ try {
+ const host = new URL(issuer).hostname;
+ return host === "slack.com" || host.endsWith(".slack.com");
+ } catch {
+ return false;
+ }
+}
+
const OIDC: OidcConfig = {
authEndpoint: process.env.OIDC_AUTH_ENDPOINT ?? "https://slack.com/openid/connect/authorize",
tokenEndpoint: process.env.OIDC_TOKEN_ENDPOINT ?? "https://slack.com/api/openid.connect.token",
@@ -1260,7 +1269,7 @@ export function bootChecks(): void {
if (OIDC.expectedTeamId !== undefined && isMissingOrPlaceholder(OIDC.expectedTeamId)) {
problems.push("PORTAL_EXPECTED_TEAM_ID is optional, but may not be a placeholder when configured");
}
- if (OIDC.issuer !== "https://slack.com" && !OIDC_JWKS_CONFIGURED) {
+ if (!isSlackIssuer(OIDC.issuer) && !OIDC_JWKS_CONFIGURED) {
problems.push("OIDC_JWKS_URI is required for a non-Slack issuer");
}
if (SESSION_SECRET && CORE_SIGNING_SECRET && SESSION_SECRET === CORE_SIGNING_SECRET) {
diff --git a/scripts/dev/lib/pool.ts b/scripts/dev/lib/pool.ts
index d67e0e3bc..76db8be2f 100644
--- a/scripts/dev/lib/pool.ts
+++ b/scripts/dev/lib/pool.ts
@@ -50,15 +50,13 @@ export interface SlotTokens {
extra: Record<string, string>;
}
-const unquote = (value: string): string => value.replace(/^(['"])(.*)\1$/, "$2");
-
export function slotTokens(slot: string, store = poolStore()): SlotTokens {
const env = readEnvFile(join(store, `${slot}.env`));
return {
- botToken: unquote(env.SLACK_BOT_TOKEN ?? ""),
- appToken: unquote(env.SLACK_APP_TOKEN ?? ""),
- handle: unquote(env.HANDLE ?? ""),
- canaryChannel: unquote(env.CANARY_CHANNEL ?? ""),
+ botToken: env.SLACK_BOT_TOKEN ?? "",
+ appToken: env.SLACK_APP_TOKEN ?? "",
+ handle: env.HANDLE ?? "",
+ canaryChannel: env.CANARY_CHANNEL ?? "",
extra: env,
};
}
diff --git a/scripts/dev/lib/util.ts b/scripts/dev/lib/util.ts
index d8f33939d..d8a11f82e 100644
--- a/scripts/dev/lib/util.ts
+++ b/scripts/dev/lib/util.ts
@@ -29,6 +29,26 @@ export function fileMtimeEpoch(path: string): number {
}
}
+// Mirrors parseEnvLine in cli/src/util.ts — keep the two in agreement.
+function parseEnvLine(raw: string): [key: string, value: string] | undefined {
+ let line = raw.trim();
+ if (!line || line.startsWith("#")) return undefined;
+ if (line.startsWith("export ")) line = line.slice("export ".length).trimStart();
+ const eq = line.indexOf("=");
+ if (eq <= 0) return undefined;
+ const key = line.slice(0, eq).trim();
+ let value = line.slice(eq + 1).trim();
+ const quote = value[0];
+ if (quote === '"' || quote === "'" || quote === "`") {
+ const end = value.indexOf(quote, 1);
+ if (end > 0) {
+ value = value.slice(1, end);
+ if (quote === '"') value = value.replaceAll("\\n", "\n");
+ }
+ }
+ return [key, value];
+}
+
export function readEnvFile(path: string): Record<string, string> {
let raw: string;
try {
@@ -38,10 +58,8 @@ export function readEnvFile(path: string): Record<string, string> {
}
const out: Record<string, string> = {};
for (const line of raw.split("\n")) {
- const eq = line.indexOf("=");
- if (eq <= 0) continue;
- const key = line.slice(0, eq);
- if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) out[key] = line.slice(eq + 1);
+ const entry = parseEnvLine(line);
+ if (entry && /^[A-Za-z_][A-Za-z0-9_]*$/.test(entry[0])) out[entry[0]] = entry[1];
}
return out;
}
diff --git a/src/runs/postgres-run-store.ts b/src/runs/postgres-run-store.ts
index a3c4b1b6b..adb3280d5 100644
--- a/src/runs/postgres-run-store.ts
+++ b/src/runs/postgres-run-store.ts
@@ -6,6 +6,7 @@ import type { OrchestratorInput } from "../core/orchestrator.ts";
import { resolveTurnOrigin } from "../core/turn-origin.ts";
import type { EnqueueInput, EnqueueResult, ReapEvent, Run, RunDeliveryState, RunStore } from "./run-store.ts";
import { isTerminal } from "./run-store.ts";
+import { errMessage } from "../util/errors.ts";
import type { LedgerBegin, ToolLedger } from "./tool-ledger.ts";
export interface PostgresRuntime {
@@ -75,8 +76,35 @@ export function createPostgresRunStore(connectionString: string, opts?: { maxCla
PRIMARY KEY(run_id, attempt, call_index)
)`,
`ALTER TABLE tool_calls ADD COLUMN IF NOT EXISTS attempt INT NOT NULL DEFAULT 1`,
- `ALTER TABLE tool_calls DROP CONSTRAINT IF EXISTS tool_calls_pkey`,
- `ALTER TABLE tool_calls ADD PRIMARY KEY (run_id, attempt, call_index)`,
+ // One-time migration to the (run_id, attempt, call_index) key. The whole
+ // DO block is a single transaction, so a crash mid-migration can't leave
+ // the table without a primary key the way the old unconditional
+ // DROP CONSTRAINT + ADD PRIMARY KEY pair could (each ALTER autocommitted
+ // separately). It runs only while the PK is still the legacy shape, keeps
+ // the newest duplicate row if a keyless window let any in, and is a no-op
+ // on every later boot.
+ `DO $$
+ BEGIN
+ IF EXISTS (
+ SELECT 1 FROM pg_constraint c
+ WHERE c.conrelid = 'tool_calls'::regclass AND c.contype = 'p'
+ AND (SELECT array_agg(a.attname::text ORDER BY k.ord)
+ FROM unnest(c.conkey) WITH ORDINALITY AS k(attnum, ord)
+ JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k.attnum
+ ) <> ARRAY['run_id','attempt','call_index']
+ ) OR NOT EXISTS (
+ SELECT 1 FROM pg_constraint c
+ WHERE c.conrelid = 'tool_calls'::regclass AND c.contype = 'p'
+ ) THEN
+ DELETE FROM tool_calls t USING (
+ SELECT ctid, row_number() OVER (
+ PARTITION BY run_id, attempt, call_index ORDER BY created_at DESC, ctid DESC
+ ) AS rn FROM tool_calls
+ ) dup WHERE t.ctid = dup.ctid AND dup.rn > 1;
+ ALTER TABLE tool_calls DROP CONSTRAINT IF EXISTS tool_calls_pkey;
+ ALTER TABLE tool_calls ADD PRIMARY KEY (run_id, attempt, call_index);
+ END IF;
+ END $$`,
]);
async function getRun(id: string): Promise<Run | null> {
@@ -305,6 +333,7 @@ export function createPostgresRunStore(connectionString: string, opts?: { maxCla
if (done) return;
done = true;
clearInterval(poll);
+ clearTimeout(timer);
events.off(runId, onSettle);
resolve(r);
};
@@ -313,9 +342,13 @@ export function createPostgresRunStore(connectionString: string, opts?: { maxCla
}
events.once(runId, onSettle);
const poll = setInterval(() => {
- void getRun(runId).then((r) => {
- if (r && isTerminal(r.status)) finish(r);
- });
+ void getRun(runId)
+ .then((r) => {
+ if (r && isTerminal(r.status)) finish(r);
+ })
+ .catch((err: unknown) => {
+ console.error(`[postgres-run-store] waitFor poll for run ${runId} failed transiently:`, errMessage(err));
+ });
}, 250);
poll.unref?.();
const timer = setTimeout(() => {
diff --git a/test/dev-cli-lib.test.ts b/test/dev-cli-lib.test.ts
index d466b8eaa..3b0dd58b1 100644
--- a/test/dev-cli-lib.test.ts
+++ b/test/dev-cli-lib.test.ts
@@ -87,10 +87,10 @@ test("pool token parsing accepts quoted dotenv values", () => {
handle: "bot1",
canaryChannel: "C0TEST",
extra: {
- SLACK_BOT_TOKEN: '"xoxb-quoted"',
- SLACK_APP_TOKEN: "'xapp-quoted'",
- HANDLE: '"bot1"',
- CANARY_CHANNEL: "'C0TEST'",
+ SLACK_BOT_TOKEN: "xoxb-quoted",
+ SLACK_APP_TOKEN: "xapp-quoted",
+ HANDLE: "bot1",
+ CANARY_CHANNEL: "C0TEST",
},
});
assert.equal(slotValid("pool1", store), true);
diff --git a/test/postgres-store.test.ts b/test/postgres-store.test.ts
index e45a51ed1..1d7a5b674 100644
--- a/test/postgres-store.test.ts
+++ b/test/postgres-store.test.ts
@@ -923,6 +923,27 @@ test("pg run store: enqueue dedup, atomic one-per-session claim, fencing, ledger
}
});
+test("pg run store: waitFor survives a transient poll failure without an unhandled rejection", { skip }, async () => {
+ const { runs, close } = createPostgresRunStore(URL!);
+ let unhandled: unknown;
+ const onUnhandledRejection = (err: unknown): void => {
+ unhandled = err;
+ };
+ process.once("unhandledRejection", onUnhandledRejection);
+ try {
+ const r = (await runs.enqueue({ sessionId: "sWaitFor", request: turn("x") })).run;
+ const pending = runs.waitFor(r.id, 800);
+ // Kill the pool mid-poll: the next getRun() tick will reject, exercising the
+ // catch path instead of leaking an unhandled rejection out of setInterval.
+ await new Promise((res) => setTimeout(res, 50));
+ await close();
+ await assert.rejects(pending, /did not finish within 800ms/, "still settles via its own timeout, not a crash");
+ } finally {
+ process.removeListener("unhandledRejection", onUnhandledRejection);
+ }
+ assert.equal(unhandled, undefined, "a transient poll failure must not escape as an unhandled rejection");
+});
+
test(
"pg run store: releaseLease (deploy drain) hands the run back as a retry without spending budget; stale token is a no-op",
{ skip },
diff --git a/test/postgres-toolcalls-migration.test.ts b/test/postgres-toolcalls-migration.test.ts
new file mode 100644
index 000000000..9bf0f8ebb
--- /dev/null
+++ b/test/postgres-toolcalls-migration.test.ts
@@ -0,0 +1,90 @@
+import { test, before, after } from "node:test";
+import assert from "node:assert/strict";
+import { createPostgresRunStore } from "../src/runs/postgres-run-store.ts";
+
+const URL = process.env.DATABASE_URL;
+const skip = URL ? false : "set DATABASE_URL (a Postgres) to run the tool_calls migration tests";
+
+type Pg = {
+ query: (sql: string, params?: unknown[]) => Promise<{ rows: Record<string, unknown>[] }>;
+ end: () => Promise<void>;
+};
+async function pool(): Promise<Pg> {
+ const pg = (await import("pg")).default;
+ return new pg.Pool({ connectionString: URL }) as unknown as Pg;
+}
+
+async function pkColumns(p: Pg): Promise<{ oid: string; columns: string[] } | undefined> {
+ const { rows } = await p.query(`
+ SELECT c.oid::text AS oid,
+ (SELECT array_agg(a.attname::text ORDER BY k.ord)
+ FROM unnest(c.conkey) WITH ORDINALITY AS k(attnum, ord)
+ JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k.attnum) AS columns
+ FROM pg_constraint c
+ WHERE c.conrelid = 'tool_calls'::regclass AND c.contype = 'p'`);
+ const row = rows[0];
+ return row ? { oid: row.oid as string, columns: row.columns as string[] } : undefined;
+}
+
+async function bootAndClose(): Promise<void> {
+ const { runs, close } = createPostgresRunStore(URL!);
+ await runs.enqueue({ sessionId: "sMigrationPing", request: { text: "ping" } as never }).catch(() => undefined);
+ await close();
+}
+
+before(async () => {
+ if (!URL) return;
+ const p = await pool();
+ await p.query("DROP TABLE IF EXISTS runs, tool_calls CASCADE");
+ await p.end();
+});
+
+// leave a clean slate for suites sharing this database
+after(async () => {
+ if (!URL) return;
+ const p = await pool();
+ await p.query("DROP TABLE IF EXISTS runs, tool_calls CASCADE");
+ await p.end();
+});
+
+test("tool_calls: a keyless table with duplicates heals on boot, keeping the newest row", { skip }, async () => {
+ const p = await pool();
+ // the mid-crash state the old migration could leave: attempt column present, no PK, duplicates written
+ await p.query(`CREATE TABLE tool_calls(
+ run_id TEXT NOT NULL, attempt INT NOT NULL DEFAULT 1, call_index INT NOT NULL,
+ output TEXT NOT NULL, created_at BIGINT NOT NULL)`);
+ await p.query(`INSERT INTO tool_calls VALUES
+ ('r1', 1, 0, 'older', 100), ('r1', 1, 0, 'newer', 200), ('r1', 1, 1, 'only', 150)`);
+ await bootAndClose();
+ const pk = await pkColumns(p);
+ assert.deepEqual(pk?.columns, ["run_id", "attempt", "call_index"], "primary key restored");
+ const { rows } = await p.query("SELECT output FROM tool_calls WHERE run_id='r1' AND attempt=1 AND call_index=0");
+ assert.deepEqual(rows, [{ output: "newer" }], "newest duplicate survives");
+ await p.end();
+});
+
+test("tool_calls: a legacy two-column key migrates to (run_id, attempt, call_index)", { skip }, async () => {
+ const p = await pool();
+ await p.query("DROP TABLE IF EXISTS tool_calls");
+ await p.query(`CREATE TABLE tool_calls(
+ run_id TEXT NOT NULL, call_index INT NOT NULL, output TEXT NOT NULL, created_at BIGINT NOT NULL,
+ PRIMARY KEY(run_id, call_index))`);
+ await p.query("INSERT INTO tool_calls VALUES ('r2', 0, 'kept', 100)");
+ await bootAndClose();
+ const pk = await pkColumns(p);
+ assert.deepEqual(pk?.columns, ["run_id", "attempt", "call_index"]);
+ const { rows } = await p.query("SELECT output FROM tool_calls WHERE run_id='r2'");
+ assert.deepEqual(rows, [{ output: "kept" }], "existing row survives the migration");
+ await p.end();
+});
+
+test("tool_calls: a boot with the current key leaves the constraint untouched", { skip }, async () => {
+ const p = await pool();
+ const beforePk = await pkColumns(p);
+ assert.ok(beforePk, "previous test left the migrated key in place");
+ await bootAndClose();
+ const afterPk = await pkColumns(p);
+ assert.deepEqual(afterPk?.columns, ["run_id", "attempt", "call_index"]);
+ assert.equal(afterPk?.oid, beforePk?.oid, "constraint not dropped and recreated on a routine boot");
+ await p.end();
+});