peppa/packages/testkit/test/agent-versions.test.ts
peppa-bot 6e77fddb9d
All checks were successful
peppa/lint lint: success за 6с
peppa/typecheck typecheck: success за 49с
peppa/build build: success за 41с
peppa/test test: success за 1609с
peppa-ci / ci (pull_request) Successful in 29m48s
PEP-267: закреплённые версии Claude Code, Codex, OpenCode — без автообновления, дымовой тест и откат образа, сверка для суперадмина
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 17:01:06 +00:00

251 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-267: pinned agent CLI versions. Tests are named after the scenarios of
// openspec/changes/pep-267-pinned-agent-cli/specs/agent-cli-versions.
import assert from "node:assert/strict";
import { execFileSync, spawnSync } from "node:child_process";
import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { after, before, describe, test } from "node:test";
import { like } from "drizzle-orm";
import { telegramOutbox } from "@peppa/db";
import { stripAsIs } from "@peppa/shared/i18n";
import { core, db, runner, superadmin, teardown } from "./helpers.ts";
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
const TMP = mkdtempSync(join(tmpdir(), "peppa-agent-versions-"));
const PINNED = JSON.parse(readFileSync(join(ROOT, "infra/agent-versions.json"), "utf8")) as Record<string, string>;
const ARGS: Record<string, string> = { claude: "CLAUDE_CODE_VERSION", codex: "CODEX_VERSION", opencode: "OPENCODE_VERSION" };
const argsOf = (file: string) => Object.fromEntries([...readFileSync(join(ROOT, file), "utf8").matchAll(/^ARG (\w+)=(.*)$/gm)].map((m) => [m[1]!, m[2]!.trim()]));
/** A fake CLI: answers `--version` with the given text. */
function mockCli(name: string, out: string): string {
const f = join(TMP, `mock-${name}`);
writeFileSync(f, `#!/bin/sh\necho "${out}"\n`);
chmodSync(f, 0o755);
return f;
}
/**
* mock-docker for the image script: images are files `<state>/<repo>__<tag>` holding an id and the
* versions; `run --entrypoint <cli> <image> --version` prints the version from the image (MOCK_BROKEN=codex
* makes codex print another one).
*/
function mockDocker(state: string): string {
const f = join(TMP, "mock-docker");
writeFileSync(
f,
`#!/usr/bin/env bash
S="${state}"; mkdir -p "$S"
key() { echo "$S/$(echo "$1" | tr '/:' '__')"; }
case "$1" in
build)
shift; tag=""; c=""; x=""; o=""
while [ $# -gt 1 ]; do case "$1" in -t) tag=$2; shift 2;; --build-arg) case "$2" in CLAUDE_CODE_VERSION=*) c=\${2#*=};; CODEX_VERSION=*) x=\${2#*=};; OPENCODE_VERSION=*) o=\${2#*=};; esac; shift 2;; *) shift;; esac; done
printf 'id=%s\\nclaude=%s\\ncodex=%s\\nopencode=%s\\n' "$RANDOM$RANDOM" "$c" "$x" "$o" > "$(key "$tag")" ;;
tag) cp "$(key "$2")" "$(key "$3")" ;;
rmi) rm -f "$(key "$2")" ;;
image)
shift 2; img=\${@: -1}; [ -f "$(key "$img")" ] || exit 1
case "$*" in *Id*) grep '^id=' "$(key "$img")" | cut -d= -f2;; *Labels*) . "$(key "$img")"; printf '{"quest.telecom.peppa.cli.claude":"%s","quest.telecom.peppa.cli.codex":"%s","quest.telecom.peppa.cli.opencode":"%s"}\\n' "$claude" "$codex" "$opencode";; esac ;;
run)
shift; ep=""; while [ "$1" != "\${1#-}" ]; do case "$1" in --entrypoint) ep=$2; shift 2;; *) shift;; esac; done
img=$1; [ -f "$(key "$img")" ] || exit 1; . "$(key "$img")"
case "$ep" in
claude) echo "$claude (Claude Code)";;
codex) [ "$MOCK_BROKEN" = codex ] && echo "codex-cli 9.9.9" || echo "codex-cli $codex";;
opencode) echo "$opencode";;
sh) exit 0;;
esac ;;
esac
`,
);
chmodSync(f, 0o755);
return f;
}
/** A copy of the scripts and infra the image script edits (the real ones stay as they are). */
function copyRoot(): string {
const dir = mkdtempSync(join(TMP, "root-"));
mkdirSync(join(dir, "scripts"));
cpSync(join(ROOT, "scripts/runner-image.sh"), join(dir, "scripts/runner-image.sh"));
cpSync(join(ROOT, "infra"), join(dir, "infra"), { recursive: true, filter: (p) => !p.includes("whisper") });
return dir;
}
function image(root: string, docker: string, args: string[], env: Record<string, string> = {}) {
return spawnSync("bash", [join(root, "scripts/runner-image.sh"), ...args], {
encoding: "utf8",
env: { ...process.env, PEPPA_DOCKER_BIN: docker, PEPPA_RUNNER_IMAGE: "mock/runner:latest", PEPPA_AGENT_VERSIONS_FILE: "", ...env },
});
}
const tagOf = (state: string, tag: string) => {
const f = join(state, tag.replace(/[/:]/g, "_"));
return existsSync(f) ? readFileSync(f, "utf8") : null;
};
before(async () => {
await superadmin();
});
after(teardown);
describe("Версии CLI агентов закреплены", () => {
test("Dockerfile совпадает с файлом версий", () => {
assert.deepEqual(Object.keys(PINNED).sort(), ["claude", "codex", "opencode"]);
for (const file of ["infra/runner/Dockerfile", "infra/platform/Dockerfile"]) {
const args = argsOf(file);
for (const [cli, arg] of Object.entries(ARGS)) {
if (file.includes("platform") && cli === "opencode") continue; // the platform has no OpenCode
assert.equal(args[arg], PINNED[cli], `${file}: ARG ${arg}`);
}
}
assert.deepEqual(core.pinnedAgentVersions(join(ROOT, "infra/agent-versions.json")), PINNED);
});
test("Расхождение ловит тест: ни один ARG версии CLI не latest", () => {
for (const file of ["infra/runner/Dockerfile", "infra/platform/Dockerfile"]) {
const args = argsOf(file);
for (const arg of Object.values(ARGS)) if (arg in args) assert.notEqual(args[arg], "latest", `${file}: ARG ${arg}`);
}
});
test("разбор ответа --version", () => {
assert.equal(core.parseCliVersion("2.1.330 (Claude Code)"), "2.1.330");
assert.equal(core.parseCliVersion("codex-cli 0.171.0\n"), "0.171.0");
assert.equal(core.parseCliVersion("1.19.6"), "1.19.6");
assert.equal(core.parseCliVersion("command not found"), null);
});
});
describe("CLI не обновляются сами", () => {
const ctx = { sessionId: 26701, generation: 1, cwd: TMP, prompt: "go", rules: "rules" };
test("Запуск агента Codex", () => {
const cmd = runner.buildCommand("codex", ctx);
const i = cmd.indexOf("check_for_update_on_startup=false");
assert.ok(i > 0 && cmd[i - 1] === "-c", cmd.join(" "));
const env = runner.providerEnv("codex", ctx);
assert.equal(env.DISABLE_AUTOUPDATER, "1");
assert.equal(env.OPENCODE_DISABLE_AUTOUPDATE, "1");
});
test("Запуск агента OpenCode", () => {
runner.buildCommand("opencode", ctx);
const conf = JSON.parse(readFileSync(join(runner.runDir(ctx.sessionId, ctx.generation), "opencode.json"), "utf8"));
assert.equal(conf.autoupdate, false);
const env = runner.providerEnv("opencode", ctx);
assert.ok(env.OPENCODE_CONFIG?.endsWith("opencode.json"));
assert.equal(env.OPENCODE_DISABLE_AUTOUPDATE, "1");
});
test("образы: автообновление выключено в ENV", () => {
for (const file of ["infra/runner/Dockerfile", "infra/platform/Dockerfile"]) {
const text = readFileSync(join(ROOT, file), "utf8");
assert.match(text, /DISABLE_AUTOUPDATER=1/, file);
assert.match(text, /OPENCODE_DISABLE_AUTOUPDATE=1/, file);
}
});
});
describe("Новая версия — через дымовой тест, откат одной командой", () => {
test("успешная сборка: рабочий образ — новый, прежний — previous", () => {
const root = copyRoot();
const state = join(TMP, "docker-ok");
const docker = mockDocker(state);
const first = image(root, docker, []);
assert.equal(first.status, 0, first.stderr);
assert.match(first.stdout, /smoke: codex 0\.171\.0 ok/);
const v1 = tagOf(state, "mock/runner:latest");
assert.ok(v1?.includes(`codex=${PINNED.codex}`));
// the same versions again — a fresh build (new id); the old one becomes previous
const second = image(root, docker, []);
assert.equal(second.status, 0, second.stderr);
assert.equal(tagOf(state, "mock/runner:previous"), v1);
assert.notEqual(tagOf(state, "mock/runner:latest"), v1);
});
test("Дымовой тест не прошёл", () => {
const root = copyRoot();
const state = join(TMP, "docker-broken");
const docker = mockDocker(state);
assert.equal(image(root, docker, []).status, 0);
const working = tagOf(state, "mock/runner:latest");
const r = image(root, docker, [], { MOCK_BROKEN: "codex" });
assert.notEqual(r.status, 0);
assert.match(r.stderr, /codex wants 0\.171\.0, got: codex-cli 9\.9\.9/);
assert.match(r.stderr, /working image mock\/runner:latest is unchanged/);
assert.equal(tagOf(state, "mock/runner:latest"), working);
});
test("Откат", () => {
const root = copyRoot();
const state = join(TMP, "docker-rollback");
const docker = mockDocker(state);
assert.match(image(root, docker, ["--rollback"]).stderr, /nothing to roll back/);
image(root, docker, []);
const old = tagOf(state, "mock/runner:latest");
image(root, docker, []);
const fresh = tagOf(state, "mock/runner:latest");
const r = image(root, docker, ["--rollback"]);
assert.equal(r.status, 0, r.stderr);
assert.equal(tagOf(state, "mock/runner:latest"), old);
assert.equal(tagOf(state, "mock/runner:previous"), fresh);
});
test("--try: новая версия записывается только после дымового теста", () => {
const root = copyRoot();
const state = join(TMP, "docker-try");
const docker = mockDocker(state);
const bad = image(root, docker, ["--try", "codex", "0.172.0"], { MOCK_BROKEN: "codex" });
assert.notEqual(bad.status, 0);
assert.equal(JSON.parse(readFileSync(join(root, "infra/agent-versions.json"), "utf8")).codex, PINNED.codex);
const ok = image(root, docker, ["--try", "codex", "0.172.0"]);
assert.equal(ok.status, 0, ok.stderr);
assert.equal(JSON.parse(readFileSync(join(root, "infra/agent-versions.json"), "utf8")).codex, "0.172.0");
for (const f of ["infra/runner/Dockerfile", "infra/platform/Dockerfile"]) assert.match(readFileSync(join(root, f), "utf8"), /^ARG CODEX_VERSION=0\.172\.0$/m);
assert.equal(tagOf(state, "mock/runner:latest"), null, "the working image is not touched");
});
});
describe("Версии видны суперадмину", () => {
const alerts = async () => (await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, "agent-version:%"))).map((r) => stripAsIs(String(r.params.text)));
test("Версия совпадает", async () => {
process.env.PEPPA_CLAUDE_BIN = mockCli("claude", `${PINNED.claude} (Claude Code)`);
process.env.PEPPA_CODEX_BIN = mockCli("codex", `codex-cli ${PINNED.codex}`);
process.env.PEPPA_OPENCODE_BIN = join(TMP, "no-such-opencode");
process.env.PEPPA_DOCKER_BIN = join(TMP, "no-such-docker");
const snap = await runner.checkAgentVersions(db);
assert.deepEqual(snap.service, { claude: PINNED.claude, codex: PINNED.codex });
assert.equal(snap.runner, null);
assert.deepEqual(core.versionDrifts(snap), []);
assert.deepEqual(await alerts(), []);
const status = await core.platformStatus(db);
assert.match(status, new RegExp(`Claude Code: pinned ${PINNED.claude.replace(/\./g, "\\.")}, service ${PINNED.claude.replace(/\./g, "\\.")}`));
assert.doesNotMatch(status, /DRIFT/);
});
test("Версия поменялась сама", async () => {
process.env.PEPPA_CODEX_BIN = mockCli("codex", "codex-cli 0.172.0");
const state = join(TMP, "docker-inspect");
process.env.PEPPA_DOCKER_BIN = mockDocker(state);
execFileSync("bash", [join(ROOT, "scripts/runner-image.sh")], { env: { ...process.env, PEPPA_RUNNER_IMAGE: "peppa/runner:latest" }, stdio: "ignore" });
await runner.checkAgentVersions(db);
await runner.checkAgentVersions(db);
const sent = await alerts();
assert.equal(sent.length, 1, sent.join("\n"));
assert.match(sent[0]!, /Codex в сервисе FORGE: версия 0\.172\.0 вместо закреплённой 0\.171\.0/);
const status = await core.platformStatus(db);
assert.match(status, /Codex: pinned 0\.171\.0, service 0\.172\.0, runner image 0\.171\.0 — DRIFT in service/);
});
test("сверка раз в час", async () => {
process.env.PEPPA_AGENT_VERSIONS = "on";
const at = Date.parse((await core.getAgentVersions(db))!.at);
assert.equal(await runner.agentVersionsTick(db, { now: new Date(at + 30 * 60_000) }), null);
assert.ok(await runner.agentVersionsTick(db, { now: new Date(at + 61 * 60_000) }));
process.env.PEPPA_AGENT_VERSIONS = "off";
});
});