436 lines
25 KiB
TypeScript
436 lines
25 KiB
TypeScript
// PEP-17: the agent of a runner in its own container (mock-docker), hooks/MCP/git only through
|
||
// the agent relay. PEP-40: runner hosts over SSH (mock-ssh) — clone, tmux, terminal, outages.
|
||
import assert from "node:assert/strict";
|
||
import { execFile, execFileSync, spawn } from "node:child_process";
|
||
import { promisify } from "node:util";
|
||
import { existsSync, mkdirSync, readFileSync, symlinkSync, writeFileSync } from "node:fs";
|
||
import { createServer, type Server } from "node:http";
|
||
import type { AddressInfo } from "node:net";
|
||
import { join } from "node:path";
|
||
import { after, before, describe, test } from "node:test";
|
||
import { events } from "@peppa/db";
|
||
import { core, db, project, runner, setDefaultOwner, teardown, tick, waitFor, type TestProject } from "./helpers.ts";
|
||
import { agentRelayMcp } from "@peppa/mcp/relay";
|
||
|
||
const ROOT = join(import.meta.dirname, "../../..");
|
||
const TMP = join(process.env.PEPPA_HOME!, "..", "pep17");
|
||
const BIN = join(TMP, "bin");
|
||
const IMAGE_BIN = join(TMP, "image-bin");
|
||
const GIT_ROOT = join(TMP, "git");
|
||
const SSH_ROOT = join(TMP, "hosts");
|
||
const STATE = join(TMP, "docker");
|
||
const BOT_TOKEN = "mock-gitea-bot-token";
|
||
|
||
let relay: Server;
|
||
let gitServer: Server;
|
||
let relayUrl = "";
|
||
const gitAuth: string[] = [];
|
||
let pm: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
|
||
/** Smart-HTTP git server (git http-backend) standing in for Gitea; records the auth it got. */
|
||
function serveGit(): Promise<Server> {
|
||
const server = createServer((req, res) => {
|
||
gitAuth.push(String(req.headers.authorization ?? ""));
|
||
const url = new URL(req.url!, "http://x");
|
||
const cgi = spawn("git", ["http-backend"], {
|
||
env: {
|
||
...process.env,
|
||
GIT_PROJECT_ROOT: GIT_ROOT,
|
||
GIT_HTTP_EXPORT_ALL: "1",
|
||
REQUEST_METHOD: req.method!,
|
||
PATH_INFO: decodeURIComponent(url.pathname),
|
||
QUERY_STRING: url.search.slice(1),
|
||
CONTENT_TYPE: String(req.headers["content-type"] ?? ""),
|
||
HTTP_CONTENT_ENCODING: String(req.headers["content-encoding"] ?? ""),
|
||
GIT_PROTOCOL: String(req.headers["git-protocol"] ?? ""),
|
||
REMOTE_USER: "peppa-bot",
|
||
},
|
||
});
|
||
req.pipe(cgi.stdin);
|
||
let buf = Buffer.alloc(0);
|
||
let headersDone = false;
|
||
cgi.stdout.on("data", (d: Buffer) => {
|
||
if (headersDone) return void res.write(d);
|
||
buf = Buffer.concat([buf, d]);
|
||
const i = buf.indexOf("\r\n\r\n");
|
||
if (i < 0) return;
|
||
headersDone = true;
|
||
let status = 200;
|
||
for (const line of buf.subarray(0, i).toString().split("\r\n")) {
|
||
const [k, ...v] = line.split(":");
|
||
if (k!.toLowerCase() === "status") status = Number(v.join(":").trim().split(" ")[0]);
|
||
else res.setHeader(k!, v.join(":").trim());
|
||
}
|
||
res.statusCode = status;
|
||
res.write(buf.subarray(i + 4));
|
||
});
|
||
cgi.on("close", () => res.end());
|
||
});
|
||
return new Promise((r) => server.listen(0, "127.0.0.1", () => r(server)));
|
||
}
|
||
|
||
/** A bare repo test/<slug>.git with the project's FORGE files committed (the clone on a host needs them). */
|
||
function bareRepo(p: TestProject, slug: string) {
|
||
const work = join(TMP, "seed", slug);
|
||
mkdirSync(join(work, ".peppa"), { recursive: true });
|
||
for (const f of [".peppa/project.json", ".peppa/mock-scenario.json"]) writeFileSync(join(work, f), readFileSync(join(p.dir, f)));
|
||
writeFileSync(join(work, "README.md"), `# ${slug}\n`);
|
||
const g = (...a: string[]) => execFileSync("git", a, { cwd: work, stdio: "ignore" });
|
||
g("init", "-q", "-b", "main");
|
||
g("add", ".");
|
||
g("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "init");
|
||
mkdirSync(join(GIT_ROOT, "test"), { recursive: true });
|
||
execFileSync("git", ["clone", "-q", "--bare", work, join(GIT_ROOT, "test", `${slug}.git`)]);
|
||
execFileSync("git", ["config", "http.receivepack", "true"], { cwd: join(GIT_ROOT, "test", `${slug}.git`) });
|
||
}
|
||
|
||
/** The agent in the container calls peppa-mcp from its PATH (the image's shim), like the template's .mcp.json. */
|
||
function containerMcp(p: TestProject) {
|
||
writeFileSync(join(p.dir, ".mcp.json"), JSON.stringify({ mcpServers: { peppa: { command: "peppa-mcp" } } }));
|
||
}
|
||
|
||
type Run = { name: string; image: string; mounts: string[]; env: string[]; argv: string[]; workdir: string };
|
||
const runs = (): Run[] => (existsSync(join(STATE, "runs.jsonl")) ? readFileSync(join(STATE, "runs.jsonl"), "utf8").trim().split("\n").map((l) => JSON.parse(l) as Run) : []);
|
||
const dockerCalls = () => (existsSync(join(STATE, "calls.log")) ? readFileSync(join(STATE, "calls.log"), "utf8") : "");
|
||
const evs = async (sid: number, type: string) => (await db.select().from(events)).filter((e) => e.sessionId === sid && e.type === type);
|
||
let seq = 0;
|
||
async function subscribed(p: TestProject) {
|
||
const sub = await runner.addSubscription(db, { provider: "claude", name: `Claude ${++seq}`, method: "token", secret: `sk-ant-oat01-mock${"x".repeat(24)}${seq}`, createdBy: pm.id });
|
||
const pool = await core.createPool(db, { name: `Пул ${seq}`, subscriptionIds: [sub.id] });
|
||
await core.setProjectPool(db, (await core.getProject(db, p.key)).id, pool.id);
|
||
return sub;
|
||
}
|
||
|
||
before(async () => {
|
||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||
pm = await core.upsertUserFromGitea(db, { id: 17, login: "mock-pm-17" }, { access_token: "x" });
|
||
setDefaultOwner(pm.id);
|
||
for (const d of [BIN, IMAGE_BIN, GIT_ROOT, SSH_ROOT, STATE]) mkdirSync(d, { recursive: true });
|
||
// The host's `docker` and the image's `claude` are mocks; FORGE's own docker — PEPPA_DOCKER_BIN.
|
||
symlinkSync(join(ROOT, "packages/testkit/bin/mock-docker"), join(BIN, "docker"));
|
||
symlinkSync(join(ROOT, "packages/testkit/bin/mock-claude"), join(IMAGE_BIN, "claude"));
|
||
gitServer = await serveGit();
|
||
relay = await runner.serveAgentRelay(db, 0, { mcp: agentRelayMcp });
|
||
relayUrl = `http://127.0.0.1:${(relay.address() as AddressInfo).port}`;
|
||
Object.assign(process.env, {
|
||
PATH: `${BIN}:${process.env.PATH}`,
|
||
PEPPA_DOCKER_BIN: join(ROOT, "packages/testkit/bin/mock-docker"),
|
||
PEPPA_SSH_BIN: join(ROOT, "packages/testkit/bin/mock-ssh"),
|
||
MOCK_DOCKER_STATE: STATE,
|
||
MOCK_DOCKER_PATH: IMAGE_BIN,
|
||
MOCK_SSH_ROOT: SSH_ROOT,
|
||
PEPPA_AGENT_URL: relayUrl,
|
||
PEPPA_RELAY_WAIT_MS: "500",
|
||
GITEA_URL: `http://127.0.0.1:${(gitServer.address() as AddressInfo).port}`,
|
||
GITEA_TOKEN: BOT_TOKEN,
|
||
});
|
||
});
|
||
|
||
after(async () => {
|
||
for (const h of ["build1", "build2"]) {
|
||
try {
|
||
execFileSync(process.env.PEPPA_SSH_BIN!, [h, `tmux -L ${process.env.PEPPA_TMUX_SOCKET} kill-server; rm -rf "$TMUX_TMPDIR"`], { stdio: "ignore" });
|
||
} catch {}
|
||
}
|
||
relay?.close();
|
||
gitServer?.close();
|
||
await teardown();
|
||
});
|
||
|
||
describe("PEP-17: агент в контейнере", () => {
|
||
test("Без настройки — как раньше: tmux без docker", async () => {
|
||
const p = await project({ turns: [[{ say: "ok" }]] });
|
||
const before = runs().length;
|
||
const sid = await p.start();
|
||
await p.waitStatus(sid, "idle");
|
||
const s = await core.getSession(db, sid);
|
||
assert.equal(s.container, null);
|
||
assert.equal(s.host, null);
|
||
assert.equal(runs().length, before);
|
||
await runner.stopSession(db, sid);
|
||
});
|
||
|
||
test("Запуск в контейнере: только своя копия, свой токен; хуки, MCP и транскрипт — через релей", async () => {
|
||
const p = await project({
|
||
turns: [[
|
||
{ usage: { input: 1200, output: 300, costUsd: 0.42 } },
|
||
{ mcp: "report_progress", args: { task: "$TASK", text: "из контейнера" } },
|
||
{ permission: { tool: "Bash", input: { command: "rm -rf build" } } },
|
||
{ say: "Готово." },
|
||
]],
|
||
});
|
||
containerMcp(p);
|
||
await subscribed(p);
|
||
await core.setProjectRunnerSettings(db, (await core.getProject(db, p.key)).id, { isolation: "container" });
|
||
// PEP-54: the project's own secret goes in by name; its value never lands in launch.sh.
|
||
await core.setProjectSecret(db, pm.id, (await core.getProject(db, p.key)).id, "STRIPE_KEY", "mock-stripe-secret-value", { agent: true });
|
||
const sid = await p.start();
|
||
const s = await core.getSession(db, sid);
|
||
assert.equal(s.container, `peppa-s${sid}`);
|
||
|
||
// The run: the workspace, the launch dir read-only, the agent's own home — nothing else.
|
||
const run = await waitFor("docker run", async () => runs().find((r) => r.name === `peppa-s${sid}`));
|
||
const ws = execFileSync("realpath", [p.dir]).toString().trim();
|
||
assert.deepEqual(run.mounts, [
|
||
`${ws}:${ws}`,
|
||
`${join(process.env.PEPPA_HOME!, "runs", `s${sid}-g1`)}:/peppa/run:ro`,
|
||
`${join(process.env.PEPPA_HOME!, "sandboxes", `s${sid}`, "home")}:/peppa/home`,
|
||
// PEP-271: Claude's tool permissions — only the platform's, read-only.
|
||
`${join(process.env.PEPPA_HOME!, "runs", `s${sid}-g1`, "managed-settings.json")}:/etc/claude-code/managed-settings.json:ro`,
|
||
]);
|
||
assert.equal(run.workdir, ws);
|
||
assert.ok(run.env.includes("CLAUDE_CODE_OAUTH_TOKEN") && run.env.includes("PEPPA_AGENT_TOKEN") && run.env.includes("STRIPE_KEY"));
|
||
for (const secret of ["PEPPA_DB", "PEPPA_HOME", "GITEA_TOKEN", "PEPPA_SECRET"]) assert.ok(!run.env.includes(secret), `${secret} must not enter the container`);
|
||
assert.equal(run.argv[0], "claude");
|
||
assert.ok(run.argv.includes("/peppa/run/settings.json"));
|
||
const settings = JSON.parse(readFileSync(join(process.env.PEPPA_HOME!, "runs", `s${sid}-g1`, "settings.json"), "utf8"));
|
||
assert.equal(settings.hooks.Stop[0].hooks[0].command, "peppa-hook stop");
|
||
const launch = readFileSync(join(process.env.PEPPA_HOME!, "runs", `s${sid}-g1`, "launch.sh"), "utf8");
|
||
assert.ok(!launch.includes("sk-ant-oat01") && !launch.includes("mock-stripe-secret-value"), "secrets stay out of launch.sh");
|
||
assert.ok(!existsSync(join(process.env.PEPPA_HOME!, "runs", `s${sid}-g1`, "secrets.env")), "the secrets file is sourced and removed");
|
||
|
||
// MCP through the relay; the permission hook blocks (wait + rid) until the PM answers.
|
||
await p.waitLog("mcp via relay", (e) => e.ev === "mcp" && e.tool === "report_progress" && e.isError === false);
|
||
const q = await p.waitQuestion(sid, "permission");
|
||
await new Promise((r) => setTimeout(r, 1200)); // longer than one relay wait
|
||
await runner.answerAndDeliver(db, q.id, "allow", "web");
|
||
await p.waitLog("permission allowed by hook", (e) => e.ev === "permission" && e.via === "hook" && e.behavior === "allow");
|
||
await p.waitStatus(sid, "idle");
|
||
// Stop hook through the relay with the transcript: tokens counted as for a local agent.
|
||
assert.equal(core.usageTotals((await core.getSession(db, sid)).usage).total, 1500);
|
||
assert.ok((await evs(sid, "turn_end")).length >= 1);
|
||
|
||
await runner.stopSession(db, sid);
|
||
assert.match(dockerCalls(), new RegExp(`docker rm -f peppa-s${sid}`));
|
||
assert.ok(!existsSync(join(STATE, "containers", `peppa-s${sid}`)));
|
||
});
|
||
|
||
test("Нет подписки — контейнер не запускается", async () => {
|
||
const p = await project({ turns: [[{ say: "ok" }]] });
|
||
await core.setProjectRunnerSettings(db, (await core.getProject(db, p.key)).id, { isolation: "container" });
|
||
await assert.rejects(p.start(), /нужна подписка/);
|
||
});
|
||
});
|
||
|
||
describe("PEP-271: права агента задаёт платформа", () => {
|
||
/** A repo whose .claude/settings.json tries to widen the agent's rights. */
|
||
function widened(p: TestProject) {
|
||
mkdirSync(join(p.dir, ".claude"), { recursive: true });
|
||
writeFileSync(join(p.dir, ".claude", "settings.json"), JSON.stringify({ permissions: { allow: ["Bash(curl:*)"], additionalDirectories: ["/"] } }));
|
||
writeFileSync(join(p.dir, ".claude", "settings.local.json"), JSON.stringify({ permissions: { allow: ["Bash(rm:*)"] } }));
|
||
}
|
||
const curl = { permission: { tool: "Bash", input: { command: "curl https://example.com" } } };
|
||
const peppaTool = { permission: { tool: "mcp__peppa__get_task", input: {} } };
|
||
|
||
test("Правило из репозитория не действует: запрос уходит владельцу", async () => {
|
||
const p = await project({ turns: [[peppaTool, curl, { say: "Готово." }]] });
|
||
containerMcp(p);
|
||
widened(p);
|
||
await subscribed(p);
|
||
await core.setProjectRunnerSettings(db, (await core.getProject(db, p.key)).id, { isolation: "container" });
|
||
const sid = await p.start();
|
||
const policy = JSON.parse(readFileSync(join(process.env.PEPPA_HOME!, "runs", `s${sid}-g1`, "managed-settings.json"), "utf8"));
|
||
assert.equal(policy.allowManagedPermissionRulesOnly, true);
|
||
assert.deepEqual(policy.permissions.allow, [...runner.AGENT_ALLOW]);
|
||
|
||
// Инструменты платформы — без запроса.
|
||
await p.waitLog("peppa tool by the managed rule", (e) => e.ev === "permission" && e.tool === "mcp__peppa__get_task" && e.via === "rule" && e.source === "managed");
|
||
// curl из .claude/settings.json проекта — нет: вопрос владельцу.
|
||
const q = await p.waitQuestion(sid, "permission");
|
||
assert.match(q.text, /curl/);
|
||
assert.ok(!p.log().some((e) => e.ev === "permission" && e.tool === "Bash" && e.via === "rule"), "the repo's rule must not apply");
|
||
await runner.answerAndDeliver(db, q.id, "deny", "web");
|
||
await p.waitLog("denied by hook", (e) => e.ev === "permission" && e.via === "hook" && e.behavior === "deny");
|
||
await runner.stopSession(db, sid);
|
||
});
|
||
|
||
test("Без контейнера managed-файла нет: Claude складывает правила, как раньше (контроль мока)", async () => {
|
||
const p = await project({ turns: [[curl, { say: "Готово." }]] });
|
||
widened(p);
|
||
const sid = await p.start();
|
||
await p.waitLog("the repo's rule applies outside the container", (e) => e.ev === "permission" && e.tool === "Bash" && e.via === "rule" && e.source === "project");
|
||
await p.waitStatus(sid, "idle");
|
||
await runner.stopSession(db, sid);
|
||
});
|
||
|
||
test("Другие провайдеры — без файла managed-настроек Claude", async () => {
|
||
const sub = await runner.addSubscription(db, { provider: "codex", name: `Codex ${++seq}`, method: "api_key", secret: `sk-mock-codex-${seq}`, createdBy: pm.id });
|
||
const p = await project({ turns: [[{ say: "ok" }]] });
|
||
const pool = await core.createPool(db, { name: `Пул ${seq}`, subscriptionIds: [sub.id] });
|
||
const pid = (await core.getProject(db, p.key)).id;
|
||
await core.setProjectPool(db, pid, pool.id);
|
||
await core.setProjectRunnerSettings(db, pid, { isolation: "container" });
|
||
const sid = await p.start();
|
||
const run = await waitFor("docker run", async () => runs().find((r) => r.name === `peppa-s${sid}`));
|
||
assert.ok(!run.mounts.some((m) => m.includes("/etc/claude-code")), run.mounts.join(" "));
|
||
assert.ok(!existsSync(join(process.env.PEPPA_HOME!, "runs", `s${sid}-g1`, "managed-settings.json")));
|
||
await runner.stopSession(db, sid);
|
||
});
|
||
});
|
||
|
||
describe("PEP-17: релей агента", () => {
|
||
const post = (path: string, token: string, body: unknown) =>
|
||
fetch(`${relayUrl}/api/agent${path}`, { method: "POST", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: "application/json, text/event-stream" }, body: JSON.stringify(body) });
|
||
|
||
test("Чужой или старый токен — 401; чужой проект через MCP — отказ; git только к своему репозиторию", async () => {
|
||
const a = await project({ turns: [[{ sleep: 60_000 }]] });
|
||
const b = await project({ turns: [[{ say: "ok" }]] });
|
||
const sid = await a.start();
|
||
const s = await core.getSession(db, sid);
|
||
const token = core.agentRelayToken(sid, s.generation);
|
||
|
||
assert.equal((await post("/hook", core.agentRelayToken(sid, s.generation - 1), { event: "stop", stdin: "{}" })).status, 401);
|
||
assert.equal((await post("/hook", `${token.slice(0, -2)}xx`, { event: "stop", stdin: "{}" })).status, 401);
|
||
assert.equal((await post("/hook", "nonsense", { event: "stop", stdin: "{}" })).status, 401);
|
||
|
||
const call = async (name: string, args: Record<string, unknown>) => {
|
||
const r = await post("/mcp", token, { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } });
|
||
return (await r.json()) as { result: { isError?: boolean; content: Array<{ text: string }> } };
|
||
};
|
||
const own = await call("get_task", { task: a.taskKey });
|
||
assert.ok(!own.result.isError && own.result.content[0]!.text.includes(a.taskKey));
|
||
const other = await call("get_task", { task: b.taskKey });
|
||
assert.equal(other.result.isError, true);
|
||
assert.match(other.result.content[0]!.text, /Access denied/);
|
||
assert.equal((await call("list_tasks", { project: b.key })).result.isError, true);
|
||
|
||
const git = (path: string) => fetch(`${relayUrl}/api/agent/git/${path}`, { headers: { Authorization: `Bearer ${token}` } });
|
||
const before = gitAuth.length;
|
||
assert.equal((await git(`test/${b.key.toLowerCase()}.git/info/refs?service=git-upload-pack`)).status, 403);
|
||
assert.equal((await git(`test/${a.key.toLowerCase()}/../${b.key.toLowerCase()}.git/info/refs`)).status, 403);
|
||
assert.equal((await git(`api/v1/repos/test/${b.key.toLowerCase()}/pulls`)).status, 403);
|
||
assert.equal(gitAuth.length, before, "refused requests never reach Gitea");
|
||
assert.equal(runner.allowedGitPath({ giteaOwner: "test", giteaRepo: "pay" }, "api/v1/repos/test/pay/pulls"), true);
|
||
// PEP-133: dot segments in any spelling are refused.
|
||
for (const bad of ["test/pay.git/%2e%2e/%2e%2e/test/other.git/info/refs", "test/pay.git/%252e%252e/x", "test/pay.git/..%2fother", "test/pay.git/..\\other", "test/pay.git/./x"]) {
|
||
assert.equal(runner.allowedGitPath({ giteaOwner: "test", giteaRepo: "pay" }, bad), false, bad);
|
||
}
|
||
|
||
await runner.stopSession(db, sid);
|
||
// A finished session's token no longer runs hooks.
|
||
assert.equal((await post("/hook", token, { event: "stop", stdin: "{}" })).status, 401);
|
||
});
|
||
});
|
||
|
||
describe("PEP-40: хосты раннеров", () => {
|
||
let hostId = 0;
|
||
|
||
test("Подключить хост: ключ FORGE, проверка — онлайн, версии", async () => {
|
||
const pub = await runner.ensureSshKey();
|
||
assert.match(pub, /^ssh-ed25519 /);
|
||
const h = await core.createHost(db, { name: "build1", sshTarget: "peppa@build1", peppaUrl: relayUrl });
|
||
hostId = h.id;
|
||
await assert.rejects(core.createHost(db, { name: "bad", sshTarget: "-oProxyCommand=x" }), /SSH-адрес/);
|
||
// Not authorized yet: the host refuses the key.
|
||
mkdirSync(join(SSH_ROOT, "build1", "home", ".ssh"), { recursive: true });
|
||
writeFileSync(join(SSH_ROOT, "build1", "home", ".ssh", "authorized_keys"), "ssh-ed25519 AAAAother other\n");
|
||
assert.equal((await runner.checkHost(db, h)).status, "offline");
|
||
writeFileSync(join(SSH_ROOT, "build1", "home", ".ssh", "authorized_keys"), `${pub}\n`);
|
||
writeFileSync(join(STATE, "images"), "peppa/runner:latest\n");
|
||
const ok = await runner.checkHost(db, h);
|
||
assert.equal(ok.status, "online");
|
||
assert.equal(ok.info?.docker, "27.3.1-mock");
|
||
assert.match(ok.info?.tmux ?? "", /^tmux /);
|
||
assert.ok(ok.info?.image);
|
||
});
|
||
|
||
test("Раннер на хосте: клон через релей, tmux и агент там, терминал в вебе через SSH", async () => {
|
||
const p = await project({ turns: [[{ mcp: "report_progress", args: { task: "$TASK", text: "с хоста" } }, { say: "Сделал на хосте." }]] });
|
||
const slug = p.key.toLowerCase();
|
||
containerMcp(p);
|
||
bareRepo(p, slug);
|
||
await subscribed(p);
|
||
await core.setProjectRunnerSettings(db, (await core.getProject(db, p.key)).id, { hosts: [hostId] });
|
||
const sid = await p.start();
|
||
const s = await core.getSession(db, sid);
|
||
assert.equal(s.host?.name, "build1");
|
||
assert.equal(s.container, `peppa-s${sid}`);
|
||
const remoteWs = join(SSH_ROOT, "build1", "home", "peppa", "ws", slug, `s${sid}`);
|
||
assert.equal(execFileSync("realpath", [s.workspacePath!]).toString().trim(), execFileSync("realpath", [remoteWs]).toString().trim());
|
||
// Cloned through the relay's git proxy with the bot token, on the story's branch.
|
||
assert.ok(gitAuth.some((a) => a === `token ${BOT_TOKEN}`));
|
||
assert.equal(execFileSync("git", ["branch", "--show-current"], { cwd: remoteWs }).toString().trim(), `task/${p.taskKey.toLowerCase()}`);
|
||
assert.ok(existsSync(join(remoteWs, ".mcp.json")), "untracked FORGE files copied to the host");
|
||
// tmux lives on the host, not here.
|
||
assert.equal(await runner.tmux.hasSession(s.tmuxName), false);
|
||
assert.equal(await runner.tmux.hasSession(runner.tmux.sessionPane(s)), true);
|
||
|
||
const log = join(remoteWs, ".peppa", "mock-log.jsonl");
|
||
await waitFor("mcp from the host", async () => existsSync(log) && readFileSync(log, "utf8").includes('"tool":"report_progress","args":{"task":"'));
|
||
assert.match(readFileSync(log, "utf8"), /"tool":"report_progress".*"isError":false/);
|
||
await p.waitStatus(sid, "idle");
|
||
|
||
// PEP-9 over SSH: the frame comes from the host's pane.
|
||
const frame = await new Promise<string>((resolve, reject) => {
|
||
const t = setTimeout(() => reject(new Error("no terminal frame")), 10_000);
|
||
const off = runner.watchTerminal(runner.tmux.sessionPane(s), (e) => {
|
||
if (e.type === "frame") {
|
||
clearTimeout(t);
|
||
off();
|
||
resolve(JSON.stringify(e));
|
||
}
|
||
});
|
||
});
|
||
assert.match(frame, /Сделал на хосте/);
|
||
await runner.terminalInput(db, pm, sid, { paste: "привет с веба" });
|
||
|
||
// Git push from the host goes through the proxy too.
|
||
execFileSync("sh", ["-c", `cd ${remoteWs} && echo x > f.txt && git add f.txt && git -c user.name=a -c user.email=a@a commit -qm x`]);
|
||
const token = core.agentRelayToken(sid, (await core.getSession(db, sid)).generation);
|
||
const env = runner.gitRelayEnv(relayUrl, token);
|
||
// PEP-230: in the container there is no global git config — the author comes from the environment.
|
||
assert.equal(env.GIT_AUTHOR_NAME, "peppa-bot");
|
||
assert.match(env.GIT_COMMITTER_EMAIL, /^peppa-bot@/);
|
||
// Async: the relay and the git server live in this process.
|
||
await promisify(execFile)("git", ["push", "-q", "origin", "HEAD"], { cwd: remoteWs, env: { ...process.env, ...env, GIT_TERMINAL_PROMPT: "0" } });
|
||
assert.ok(execFileSync("git", ["branch", "--list"], { cwd: join(GIT_ROOT, "test", `${slug}.git`) }).toString().includes(`task/${p.taskKey.toLowerCase()}`));
|
||
|
||
await runner.stopSession(db, sid);
|
||
assert.equal(await runner.tmux.hasSession(runner.tmux.sessionPane(await core.getSession(db, sid))), false);
|
||
});
|
||
|
||
test("Хост недоступен: офлайн, раннер не объявляется пропавшим; новый раннер — «нет доступного хоста»", async () => {
|
||
const p = await project({ turns: [[{ sleep: 60_000 }]] });
|
||
containerMcp(p);
|
||
bareRepo(p, p.key.toLowerCase());
|
||
await subscribed(p);
|
||
const pid = (await core.getProject(db, p.key)).id;
|
||
await core.setProjectRunnerSettings(db, pid, { hosts: [hostId] });
|
||
const sid = await p.start();
|
||
process.env.MOCK_SSH_DOWN = "build1";
|
||
try {
|
||
await tick();
|
||
assert.notEqual((await core.getSession(db, sid)).status, "failed");
|
||
assert.equal((await evs(sid, "tmux_gone")).length, 0);
|
||
await runner.hostTick(db, { force: true });
|
||
assert.equal((await core.getHost(db, hostId)).status, "offline");
|
||
const t2 = await core.createTask(db, { projectId: pid, title: "вторая", description: "x" });
|
||
await assert.rejects(runner.startSession(db, t2.key), /Агенту негде работать/);
|
||
} finally {
|
||
delete process.env.MOCK_SSH_DOWN;
|
||
}
|
||
await runner.hostTick(db, { force: true });
|
||
assert.equal((await core.getHost(db, hostId)).status, "online");
|
||
await runner.stopSession(db, sid);
|
||
});
|
||
|
||
test("Выбор хоста: наименее занятый онлайн", async () => {
|
||
const h2 = await core.createHost(db, { name: "build2", sshTarget: "peppa@build2", peppaUrl: relayUrl });
|
||
assert.equal((await runner.checkHost(db, h2)).status, "online");
|
||
const p = await project({ turns: [[{ sleep: 60_000 }]] });
|
||
containerMcp(p);
|
||
bareRepo(p, p.key.toLowerCase());
|
||
await subscribed(p);
|
||
const pid = (await core.getProject(db, p.key)).id;
|
||
await core.setProjectRunnerSettings(db, pid, { hosts: [hostId, h2.id] });
|
||
const s1 = await p.start();
|
||
const t2 = await core.createTask(db, { projectId: pid, title: "вторая", description: "x" });
|
||
const s2 = (await runner.startSession(db, t2.key)).id;
|
||
const names = [(await core.getSession(db, s1)).host?.name, (await core.getSession(db, s2)).host?.name].sort();
|
||
assert.deepEqual(names, ["build1", "build2"]);
|
||
assert.equal((await core.listHosts(db)).find((h) => h.name === "build2")?.runners, 1);
|
||
await runner.stopSession(db, s1);
|
||
await runner.stopSession(db, s2);
|
||
});
|
||
});
|