Public: anyone can read this; the crew can change it.

Crew runs as cluster Jobs: crew.placement process | job #1908

Parked opened this
Closed without merging

scout/forge:scout/1426-crew-runs-as-cluster-jobs-crew-placement → main 4 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
11 files changed +621 −32
docs/APPS.md +17
@@ -375,6 +375,23 @@ run is recorded as uncontained ("egress not enforced on a cluster job"), and
375375 the pod carries the label `forge-check=true` so an operator's NetworkPolicy
376376 can select it and hold what `egress` declares.
377377
378 **Crew placement.** The `crew.placement` setting (Settings → Capacity,
379 `FORGE_CREW_PLACEMENT`) is `process` by default: the agent's Claude Code runs
380 on the forge's machine. `job` runs it as a Kubernetes Job through the same
381 client as checks: `FORGE_CREW_IMAGE` (git and Claude Code in it),
382 `FORGE_CREW_NODE_SELECTOR`, `FORGE_CREW_TOLERATIONS`; without a usable image
383 the run stays `process`. Nothing is mounted: the pod clones the repository
384 over the forge, takes the agent's branch from its fork, runs the agent with
385 the prompt on stdin and the run token in its environment, and pushes what it
386 made (work left uncommitted as one commit) to the fork's branch, which the
387 forge fetches back before landing. The pod's log is the transcript in the
388 run's log, line by line; the run records `placement` and `node`. A steer
389 cannot reach a Job. A Job that vanishes from the cluster interrupts the run,
390 which is queued again once, then fails. The pod carries the label
391 `forge-lane=agent` for an operator's NetworkPolicy; the forge does not
392 enforce egress on it. Work the agent pushed is not scrubbed of granted
393 secret values before it reaches the fork, as a process agent's pushes are not.
394
378395 Checks share `FORGE_CHECKS_CONCURRENCY` slots (default `1`), and when one
379396 frees, it goes to the most recently requested check waiting, not the one
380397 queued longest — a fresh push is never stuck behind pulls that queued hours
scripts/gate.ts +1
@@ -344,6 +344,7 @@ export const GATE: readonly string[] = [
344344 ];
345345
346346 export const EXCLUDED: readonly Exclusion[] = [
347 { file: "test/crew-job.test.ts", reason: "new; its vanished-Job run waits on a requeue, so it is admitted only after ten green runs", issue: 1426 },
347348 { file: "test/crew-sandbox-real.test.ts", reason: "landed unlisted and red locally; the builder admits it", issue: 1238 },
348349 { file: "test/api-errors.test.ts", reason: "not yet admitted", issue: 261 },
349350 { file: "test/apps-api.test.ts", reason: "not yet admitted", issue: 261 },
src/cluster/jobs.ts +60 −4
@@ -60,6 +60,12 @@ export type JobOptions = {
6060 maxLogBytes?: number;
6161 /** Aborted: the Job is deleted and the call throws. */
6262 signal?: AbortSignal;
63 /**
64 * Each log line, as the pod writes it (the log is followed once the pod is
65 * scheduled). Every line of `lines` reaches it exactly once, in order,
66 * whether followed live or read at the end.
67 */
68 onLine?: (line: string) => void;
6369 };
6470
6571 /** The service account the pod runs as; throws when there is none. */
@@ -170,8 +176,9 @@ export async function runJob(spec: JobSpec, opts: JobOptions = {}): Promise<JobR
170176 const ns = encodeURIComponent(cred.namespace);
171177 const name = encodeURIComponent(spec.name);
172178
173 const call = (method: string, path: string, payload?: string) =>
179 const call = (method: string, path: string, payload?: string, signal?: AbortSignal) =>
174180 doFetch(`${cred.server}${path}`, {
181 ...(signal ? { signal } : {}),
175182 method,
176183 headers: {
177184 authorization: `Bearer ${cred.token}`,
@@ -188,6 +195,9 @@ export async function runJob(spec: JobSpec, opts: JobOptions = {}): Promise<JobR
188195 };
189196
190197 const jobPath = `/apis/batch/v1/namespaces/${ns}/jobs/${name}`;
198 const stopFollowing = new AbortController();
199 let follower: Promise<void> | undefined;
200 let delivered = 0;
191201 let created = false;
192202 try {
193203 // Only a Job this call made is this call's to delete: a 4xx (409
@@ -218,9 +228,11 @@ export async function runJob(spec: JobSpec, opts: JobOptions = {}): Promise<JobR
218228 else if ((job.status?.failed ?? 0) > 0) done = "failed";
219229 else if (now() >= deadline) {
220230 const pod = await findPod().catch(() => undefined);
221 return { exitCode: null, lines: await logLines(pod?.metadata?.name), timedOut: true, ...nodeOf(pod) };
231 return { exitCode: null, lines: await finish(pod?.metadata?.name), timedOut: true, ...nodeOf(pod) };
232 } else {
233 if (opts.onLine && !follower) await startFollowing();
234 await sleep(pollMs);
222235 }
223 else await sleep(pollMs);
224236 }
225237 const pod = await findPod();
226238 // A failed Job with no pod, or a pod the kubelet evicted, never ran its
@@ -229,8 +241,9 @@ export async function runJob(spec: JobSpec, opts: JobOptions = {}): Promise<JobR
229241 throw new JobVanished(pod ? "the job's pod was evicted" : "the job's pod is gone");
230242 const code: unknown = pod?.status?.containerStatuses?.[0]?.state?.terminated?.exitCode;
231243 const exitCode = typeof code === "number" ? code : done === "succeeded" ? 0 : null;
232 return { exitCode, lines: await logLines(pod?.metadata?.name), timedOut: false, ...nodeOf(pod) };
244 return { exitCode, lines: await finish(pod?.metadata?.name), timedOut: false, ...nodeOf(pod) };
233245 } finally {
246 stopFollowing.abort();
234247 if (created) {
235248 try {
236249 await call("DELETE", `${jobPath}?propagationPolicy=Background`);
@@ -240,6 +253,49 @@ export async function runJob(spec: JobSpec, opts: JobOptions = {}): Promise<JobR
240253 }
241254 }
242255
256 // Following the log: lines go to `onLine` as they arrive; `delivered`
257 // counts them so the final read hands over only what was missed.
258
259 async function startFollowing(): Promise<void> {
260 const pod = await findPod().catch(() => undefined);
261 if (!pod?.spec?.nodeName || typeof pod.metadata?.name !== "string") return;
262 const path = `/api/v1/namespaces/${ns}/pods/${encodeURIComponent(pod.metadata.name)}/log?follow=true&limitBytes=${max}`;
263 follower = (async () => {
264 try {
265 const res = await call("GET", path, undefined, stopFollowing.signal);
266 if (!res.ok || !res.body) return;
267 const reader = res.body.getReader();
268 const decoder = new TextDecoder();
269 let carry = "";
270 let bytes = 0;
271 while (bytes < max) {
272 const { done, value } = await reader.read();
273 if (done) break;
274 bytes += value.length;
275 carry += decoder.decode(value, { stream: true });
276 for (let at = carry.indexOf("\n"); at !== -1; at = carry.indexOf("\n")) {
277 delivered++;
278 opts.onLine?.(carry.slice(0, at));
279 carry = carry.slice(at + 1);
280 }
281 }
282 await reader.cancel().catch(() => {});
283 } catch {
284 // the final read delivers what was missed
285 }
286 })();
287 }
288
289 /** Read the whole log, hand `onLine` the lines the follow missed, and return all. */
290 async function finish(podName?: string): Promise<string[]> {
291 if (follower) await Promise.race([follower, sleep(pollMs)]);
292 stopFollowing.abort();
293 const lines = await logLines(podName);
294 if (opts.onLine) for (const line of lines.slice(delivered)) opts.onLine(line);
295 delivered = lines.length;
296 return lines;
297 }
298
243299 async function findPod(): Promise<Pod | undefined> {
244300 const list = await json<PodList>("GET", `/api/v1/namespaces/${ns}/pods?labelSelector=${encodeURIComponent(`job-name=${spec.name}`)}`);
245301 return list.items?.[0];
src/core/capacity.ts +8
@@ -17,6 +17,7 @@ import { totalmem } from "node:os";
1717
1818 export type CapacityKey =
1919 | "crew.concurrency"
20 | "crew.placement"
2021 | "checks.concurrency"
2122 | "checks.shards"
2223 | "children.max"
@@ -45,6 +46,13 @@ export const CAPACITY: Record<CapacityKey, Definition> = {
4546 fallback: "2",
4647 help: "How many agent runs go at once. Lowering it lets running ones finish; the next one waits.",
4748 },
49 "crew.placement": {
50 label: "Where crew runs go",
51 env: "FORGE_CREW_PLACEMENT",
52 kind: { type: "choice", values: ["process", "job"] },
53 fallback: "process",
54 help: "process runs the agent on the forge's own machine; job runs it as a Kubernetes Job (FORGE_CREW_IMAGE, FORGE_CREW_NODE_SELECTOR, FORGE_CREW_TOLERATIONS), cloning over the forge. Without a usable image it stays process. Takes effect on the next run.",
55 },
4856 "checks.concurrency": {
4957 label: "Checks at once",
5058 env: "FORGE_CHECKS_CONCURRENCY",
src/crew/claude.ts +68 −22
@@ -56,8 +56,69 @@ export interface ClaudeInput {
5656 * on the result it already gave. Default `SETTLE_MS`.
5757 */
5858 readonly settleMs?: number | undefined;
59 /** Where the agent runs. Default: a child process of the forge. */
60 readonly launch?: ClaudeLauncher | undefined;
5961 }
6062
63 /**
64 * The agent as `runClaude` drives it: lines in on stdin, stream-json out on
65 * stdout, an exit. A child process is one (`spawnClaude`); a cluster Job
66 * is another (`job_launch.ts`).
67 */
68 export interface ClaudeProc {
69 readonly stdin: { write(text: string): unknown; flush(): unknown; end(): unknown };
70 readonly stdout: ReadableStream<Uint8Array> | null;
71 readonly stderr: ReadableStream<Uint8Array> | null;
72 readonly exited: Promise<number>;
73 readonly exitCode: number | null;
74 readonly signalCode: string | null;
75 /** Stop it and anything it started. */
76 stop(signal: "SIGTERM" | "SIGKILL"): void;
77 }
78
79 export type ClaudeLauncher = (
80 argv: string[],
81 cwd: string,
82 env: Record<string, string>,
83 ) => ClaudeProc;
84
85 /** Claude Code as a child of the forge, in its own session. */
86 export const spawnClaude: ClaudeLauncher = (argv, cwd, env) => {
87 const proc = Bun.spawn(argv, {
88 cwd,
89 env: childEnv(env),
90 stdin: "pipe",
91 stdout: "pipe",
92 stderr: "pipe",
93 // Its own session, so a cancel can reach whatever it spawned in turn
94 // (a tool call left running) and not just the agent itself: a signal
95 // to one pid never touches a grandchild holding stdout open.
96 detached: true,
97 });
98 return {
99 stdin: proc.stdin,
100 stdout: proc.stdout,
101 stderr: proc.stderr,
102 exited: proc.exited,
103 get exitCode() {
104 return proc.exitCode;
105 },
106 get signalCode() {
107 return proc.signalCode;
108 },
109 // Signals the whole process group (a negative pid), so anything the
110 // agent spawned in turn goes with it; falls back to the process alone
111 // if the group is already gone.
112 stop(sig) {
113 try {
114 process.kill(-proc.pid, sig);
115 } catch {
116 proc.kill(sig);
117 }
118 },
119 };
120 };
121
61122 /** The idle guard's default: five minutes of silence after a result. */
62123 export const IDLE_AFTER_RESULT_MS = 5 * 60_000;
63124 /** The grace a finished session has to exit on its own. */
@@ -172,21 +233,15 @@ export function claudeArgs(input: ClaudeInput): string[] {
172233
173234 /** Run Claude Code to completion. Never throws; every ending is an outcome. */
174235 export async function runClaude(input: ClaudeInput): Promise<ClaudeOutcome> {
175 const proc = Bun.spawn([input.binary, ...claudeArgs(input)], {
176 cwd: input.cwd,
177 env: childEnv({
236 const proc = (input.launch ?? spawnClaude)(
237 [input.binary, ...claudeArgs(input)],
238 input.cwd,
239 {
178240 CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1",
179241 DISABLE_TELEMETRY: "1",
180242 ...input.env,
181 }),
182 stdin: "pipe",
183 stdout: "pipe",
184 stderr: "pipe",
185 // Its own session, so a cancel can reach whatever it spawned in turn
186 // (a tool call left running) and not just the agent itself: a signal
187 // to one pid never touches a grandchild holding stdout open.
188 detached: true,
189 });
243 },
244 );
190245 // What the agent hears: the prompt first, then whatever a person says
191246 // while it works. Each is a user turn; the session ends when the forge
192247 // closes its stdin after a turn nobody followed.
@@ -357,16 +412,7 @@ export async function runClaude(input: ClaudeInput): Promise<ClaudeOutcome> {
357412 // `user` records are tool results: long and mostly file contents.
358413 };
359414
360 // Signals the whole process group (a negative pid), so anything the
361 // agent spawned in turn goes with it; falls back to the process alone
362 // if the group is already gone.
363 const signalGroup = (sig: "SIGTERM" | "SIGKILL"): void => {
364 try {
365 process.kill(-proc.pid, sig);
366 } catch {
367 proc.kill(sig);
368 }
369 };
415 const signalGroup = (sig: "SIGTERM" | "SIGKILL"): void => proc.stop(sig);
370416 let why: "timeout" | "cancelled" | undefined;
371417 const stopChild = (): void => {
372418 closeInput();
src/crew/job_launch.ts added +193
@@ -0,0 +1,193 @@
1 /**
2 * The agent as a cluster Job (`crew.placement: job`), shaped as the child
3 * process `runClaude` already drives. Nothing is mounted: the pod clones the
4 * base over the forge, takes the agent's branch from its fork, runs Claude
5 * Code with the prompt on stdin, and pushes what it made back to the fork's
6 * branch — work left uncommitted goes as one commit made in the forge's words, as
7 * landing would have made it, and `takeJobWork` brings the branch back.
8 * The pod's log is the transcript `runClaude` reads, line by line.
9 *
10 * A steer cannot reach a Job (its stdin is the prompt alone). The run token
11 * and git credential go in as environment, as they do for a process.
12 */
13 import { JobVanished, runJob, type JobOptions } from "../cluster/jobs.ts";
14 import type { ClaudeLauncher, ClaudeProc } from "./claude.ts";
15 import { runGit } from "../git/env.ts";
16 import { AGENT_LABELS, type CrewJobPlacement } from "./job_placement.ts";
17
18 /** What the forge knows once the Job has ended. */
19 export interface JobFate {
20 vanished: boolean;
21 node: string | undefined;
22 }
23
24 export interface JobLaunch {
25 readonly placement: CrewJobPlacement;
26 /** The Job's name: a DNS label, one per run attempt. */
27 readonly name: string;
28 readonly cloneUrl: string;
29 readonly forkUrl: string;
30 readonly branch: string;
31 readonly defaultBranch: string;
32 /** Whether the fork already has the branch. */
33 readonly forkHasBranch: boolean;
34 /** The words of a commit the Job makes of work left uncommitted. */
35 readonly commit: { readonly subject: string; readonly body: string };
36 /** The run's environment, minus anything that names this machine. */
37 readonly env: Record<string, string>;
38 readonly timeoutMs: number;
39 readonly options?: JobOptions | undefined;
40 readonly fate: JobFate;
41 }
42
43 /** Linux refuses one environment string over 128 KiB. */
44 const MAX_STDIN = 100_000;
45
46 const SCRIPT = `set -u
47 cd "$(mktemp -d)" || exit 70
48 git clone --quiet "$FORGE_CLONE_URL" work || exit 70
49 cd work || exit 70
50 git remote set-url --push origin "$FORGE_FORK_URL"
51 start="origin/$FORGE_DEFAULT_BRANCH"
52 if [ "$FORGE_FORK_HAS_BRANCH" = 1 ]; then
53 git fetch --quiet "$FORGE_FORK_URL" "+refs/heads/$FORGE_BRANCH:refs/remotes/origin/$FORGE_BRANCH" || exit 70
54 start="origin/$FORGE_BRANCH"
55 fi
56 git checkout --quiet -B "$FORGE_BRANCH" "$start" || exit 70
57 base=$(git rev-parse HEAD)
58 printf '%s\\n' "$FORGE_STDIN" | "$@"
59 code=$?
60 if [ -n "$(git status --porcelain)" ]; then
61 git add -A && git -c commit.gpgsign=false commit --quiet -m "$FORGE_COMMIT_SUBJECT" -m "$FORGE_COMMIT_BODY"
62 fi
63 if [ "$(git rev-parse HEAD)" != "$base" ]; then
64 git push --quiet "$FORGE_FORK_URL" "HEAD:refs/heads/$FORGE_BRANCH" || echo "! push to the fork failed"
65 fi
66 exit $code
67 `;
68
69 export function jobLauncher(cfg: JobLaunch, signal: AbortSignal): ClaudeLauncher {
70 return (argv): ClaudeProc => {
71 const encoder = new TextEncoder();
72 let out!: ReadableStreamDefaultController<Uint8Array>;
73 const stdout = new ReadableStream<Uint8Array>({ start: (c) => void (out = c) });
74 const stderr = new ReadableStream<Uint8Array>({ start: (c) => c.close() });
75 const stop = new AbortController();
76 const onAbort = (): void => stop.abort();
77 if (signal.aborted) onAbort();
78 else signal.addEventListener("abort", onAbort, { once: true });
79 let begun = false;
80 let pending = "";
81 let code: number | null = null;
82 let done!: (n: number) => void;
83 const exited = new Promise<number>((r) => (done = r));
84 // A reader that has gone away is not an error for the Job's sake.
85 const send = (line: string): void => {
86 try {
87 out.enqueue(encoder.encode(`${line}\n`));
88 } catch {
89 // cancelled
90 }
91 };
92 const end = (n: number, said?: string): void => {
93 if (said !== undefined) send(`! ${said}`);
94 code = n;
95 signal.removeEventListener("abort", onAbort);
96 try {
97 out.close();
98 } catch {
99 // cancelled
100 }
101 done(n);
102 };
103
104 const begin = (): void => {
105 begun = true;
106 const stdin = pending.replace(/\n+$/, "");
107 if (stdin.length > MAX_STDIN) return end(1, "the prompt is too large for a cluster job");
108 runJob(
109 {
110 name: cfg.name,
111 image: cfg.placement.image,
112 command: ["/bin/sh", "-c", SCRIPT, "sh", ...argv],
113 env: {
114 ...cfg.env,
115 FORGE_STDIN: stdin,
116 FORGE_CLONE_URL: cfg.cloneUrl,
117 FORGE_FORK_URL: cfg.forkUrl,
118 FORGE_BRANCH: cfg.branch,
119 FORGE_DEFAULT_BRANCH: cfg.defaultBranch,
120 FORGE_COMMIT_SUBJECT: cfg.commit.subject,
121 FORGE_COMMIT_BODY: cfg.commit.body,
122 FORGE_FORK_HAS_BRANCH: cfg.forkHasBranch ? "1" : "0",
123 },
124 nodeSelector: cfg.placement.nodeSelector,
125 tolerations: cfg.placement.tolerations,
126 labels: AGENT_LABELS,
127 },
128 {
129 ...cfg.options,
130 timeoutMs: cfg.timeoutMs,
131 signal: stop.signal,
132 onLine: send,
133 },
134 ).then(
135 (res) => {
136 cfg.fate.node = res.node;
137 end(res.timedOut ? 124 : (res.exitCode ?? 1));
138 },
139 (error) => {
140 if (error instanceof JobVanished) {
141 cfg.fate.vanished = true;
142 return end(1, `job vanished: ${error.message}`);
143 }
144 end(1, `job could not run: ${error instanceof Error ? error.message : String(error)}`);
145 },
146 );
147 };
148
149 return {
150 stdin: {
151 // The first message is the prompt; the Job starts when it is flushed.
152 write(text) {
153 if (begun) throw new Error("a cluster job takes no further input");
154 pending += text;
155 },
156 flush() {
157 if (!begun && pending !== "") begin();
158 },
159 end() {},
160 },
161 stdout,
162 stderr,
163 exited,
164 get exitCode() {
165 return code;
166 },
167 signalCode: null,
168 stop: () => stop.abort(),
169 };
170 };
171 }
172
173 /**
174 * After the Job: the branch it pushed to the fork, checked out here, so
175 * landing sees what the agent made. A Job that pushed nothing leaves the
176 * clone as it was.
177 */
178 export async function takeJobWork(input: {
179 dir: string;
180 forkUrl: string;
181 branch: string;
182 env: Record<string, string>;
183 log: (line: string) => void;
184 }): Promise<void> {
185 const ref = `refs/remotes/origin/${input.branch}`;
186 const fetched = await runGit(["fetch", "--quiet", input.forkUrl, `+refs/heads/${input.branch}:${ref}`], {
187 cwd: input.dir,
188 env: input.env,
189 timeoutMs: 2 * 60_000,
190 });
191 if (!fetched.ok) return input.log(`could not fetch the job's work: ${fetched.error.stderr.slice(0, 200)}`);
192 await runGit(["reset", "--quiet", "--hard", ref], { cwd: input.dir, env: input.env });
193 }
src/crew/job_placement.ts added +36
@@ -0,0 +1,36 @@
1 /**
2 * Where a crew run's agent runs: the forge's own machine (`process`, the
3 * default) or a Kubernetes Job. The choice is the `crew.placement` capacity
4 * setting, read on every run; where the Job may land is the forge's
5 * environment, validated here once per run:
6 * FORGE_CREW_IMAGE the Job's image: git and Claude Code in it
7 * FORGE_CREW_NODE_SELECTOR key=value,key=value
8 * FORGE_CREW_TOLERATIONS a JSON list of tolerations
9 * A job placement that cannot be built is not guessed at: the run stays on
10 * the forge.
11 */
12 import type { Database } from "bun:sqlite";
13 import type { Toleration } from "../cluster/jobs.ts";
14 import { parseSelector, parseTolerations } from "../checks/placement.ts";
15 import { capacityValue } from "../core/capacity.ts";
16
17 export type CrewJobPlacement = {
18 readonly image: string;
19 readonly nodeSelector: Record<string, string>;
20 readonly tolerations: Toleration[];
21 };
22
23 /** What a NetworkPolicy selects an agent's pod by. */
24 export const AGENT_LABELS = { "forge-lane": "agent" };
25
26 export function crewJobPlacement(
27 db: Database,
28 env: Record<string, string | undefined> = process.env,
29 ): CrewJobPlacement | undefined {
30 if (capacityValue(db, "crew.placement") !== "job") return undefined;
31 const image = env["FORGE_CREW_IMAGE"]?.trim() ?? "";
32 const nodeSelector = parseSelector(env["FORGE_CREW_NODE_SELECTOR"] ?? "");
33 const tolerations = parseTolerations(env["FORGE_CREW_TOLERATIONS"]?.trim() || "[]");
34 if (image === "" || /\s/.test(image) || !nodeSelector || !tolerations) return undefined;
35 return { image, nodeSelector, tolerations };
36 }
src/crew/runner.ts +68 −3
@@ -110,6 +110,9 @@ import {
110110 } from "../core/usage.ts";
111111 import { trackAgentRun, untrackAgentRun } from "./running.ts";
112112 import { sandboxPolicy } from "./sandbox.ts";
113 import { crewJobPlacement } from "./job_placement.ts";
114 import { jobLauncher, takeJobWork, type JobFate } from "./job_launch.ts";
115 import type { JobOptions } from "../cluster/jobs.ts";
113116 import { grantSecrets, parseDeclaration, type Grant } from "./grant.ts";
114117 import { historyHolds, scrubTree } from "./leak.ts";
115118 import { workdirFor } from "./workdir.ts";
@@ -142,6 +145,8 @@ export interface CrewOptions {
142145 readonly sandboxEnforced?: boolean | undefined;
143146 /** Why it cannot, when it cannot — said once in every run's log. */
144147 readonly sandboxNote?: string | undefined;
148 /** The kube client a `job` placement speaks through; tests stand one in. */
149 readonly job?: JobOptions | undefined;
145150 }
146151
147152 export { crewRoot, workdirFor } from "./workdir.ts";
@@ -988,11 +993,44 @@ async function work(
988993 // One deadline for the run, whatever it takes to get there: the token
989994 // dies ten minutes after it, so a second invocation gets what is left.
990995 const deadline = Date.now() + options.runTimeoutMs;
996 // `crew.placement: job` (`job_placement.ts`): the agent runs in a pod
997 // that clones over the forge, so nothing local reaches it.
998 const jobPlace = crewJobPlacement(app.db);
999 const fate: JobFate = { vanished: false, node: undefined };
1000 let invocations = 0;
1001 const jobEnv = (): Record<string, string> => {
1002 const out = { ...env };
1003 for (const name of ["TMPDIR", "CLAUDE_CODE_TMPDIR", "FORGE_TEST_SOCKET", "CLAUDE_CONFIG_DIR"])
1004 delete out[name];
1005 return out;
1006 };
9911007 const invoke = async (
9921008 prompt: string,
9931009 budgetUsd: number,
9941010 resume: string | undefined,
9951011 ): Promise<ClaudeOutcome> => {
1012 const launching =
1013 jobPlace === undefined
1014 ? undefined
1015 : {
1016 placement: jobPlace,
1017 name: `crew-${run.id.toLowerCase().replace(/[^a-z0-9]/g, "-")}-${run.attempt}${invocations++}`
1018 .slice(0, 53)
1019 .replace(/-+$/, ""),
1020 cloneUrl: `${options.forgeUrl}/${repo.ownerName}/${repo.name}.git`,
1021 forkUrl: `${options.forgeUrl}/${fork.value.ownerName}/${fork.value.name}.git`,
1022 branch,
1023 defaultBranch: repo.defaultBranch,
1024 forkHasBranch: (await resolveOid(forkBare, `refs/heads/${branch}`)) !== undefined,
1025 commit: {
1026 subject: issue.title.slice(0, 200),
1027 body: `Work by @${agent.user.username} on #${issue.number}, committed by the forge.`,
1028 },
1029 env: jobEnv(),
1030 timeoutMs: Math.max(deadline - Date.now(), 0) + 60_000,
1031 options: options.job,
1032 fate,
1033 };
9961034 const spent = redactResult(
9971035 await runClaude({
9981036 binary: options.binary,
@@ -1002,8 +1040,10 @@ async function work(
10021040 model: agent.model || undefined,
10031041 budgetUsd,
10041042 resume,
1005 env,
1006 sandbox: shellPolicy(),
1043 env: launching === undefined ? env : launching.env,
1044 // The pod is the sandbox; Claude Code's own cannot nest in it.
1045 sandbox: launching === undefined ? shellPolicy() : { ...shellPolicy(), enforced: false },
1046 ...(launching === undefined ? {} : { launch: jobLauncher(launching, signal) }),
10071047 timeoutMs: Math.max(deadline - Date.now(), 0),
10081048 log: write,
10091049 signal,
@@ -1026,6 +1066,14 @@ async function work(
10261066 meter.tokensIn += spent.tokensIn;
10271067 meter.tokensOut += spent.tokensOut;
10281068 meter.costUsd += spent.costUsd;
1069 if (launching !== undefined && !fate.vanished)
1070 await takeJobWork({
1071 dir,
1072 forkUrl: `${options.localUrl}/${fork.value.ownerName}/${fork.value.name}.git`,
1073 branch,
1074 env: { ...gitAuth, ...identity },
1075 log: write,
1076 });
10291077 return spent;
10301078 };
10311079 write(
@@ -1037,7 +1085,8 @@ async function work(
10371085 note: options.sandboxNote ?? "",
10381086 },
10391087 });
1040 if (!sandbox.enforced)
1088 if (jobPlace !== undefined) write("placement: job (the agent runs as a cluster job)");
1089 else if (!sandbox.enforced)
10411090 write(
10421091 `sandbox: off here${options.sandboxNote === undefined ? "" : ` — ${options.sandboxNote}`}; the shell runs unrestricted`,
10431092 );
@@ -1076,6 +1125,22 @@ async function work(
10761125 turns: result.turns + again.turns,
10771126 };
10781127 }
1128 if (jobPlace !== undefined)
1129 noteRunProgress(app.db, run.id, { placement: "job", node: fate.node });
1130 // The Job is gone from the cluster: the run was interrupted, not
1131 // judged. Queued again once; a second vanishing fails it.
1132 if (fate.vanished) {
1133 const said = "interrupted: the cluster job vanished before it ended";
1134 if (run.attempt === 0)
1135 return {
1136 state: "paused",
1137 summary: `${said}; queued again`,
1138 resumeAt: new Date().toISOString(),
1139 sessionId: result.sessionId,
1140 costUsd: meter.costUsd,
1141 };
1142 return { state: "failed", summary: said };
1143 }
10791144 noteRunProgress(app.db, run.id, {
10801145 sessionId: result.sessionId,
10811146 costUsd: result.costUsd,
src/http/mcp.ts +2 −2
@@ -1982,13 +1982,13 @@ const TOOLS: readonly Tool[] = [
19821982 {
19831983 name: "capacity",
19841984 description:
1985 "The forge's capacity and guards, live: crew runs at once (crew.concurrency), checks at once (checks.concurrency), test shards per check (checks.shards), whether a cell's undeclared egress is refused or reported (cells.egress), and whether new accounts may create repositories and forks (guard_new_accounts: on refuses accounts younger than 7 days, off is the default). Without `key`, each setting, its value and where it comes from, and the recent changes. With `key` and `value` (\"\" goes back to the boot default), the change it would make; with dryRun false, made, by a forge admin with an admin-scope token, never an agent. A change is honoured by the next run, check or cell, never by a restart. The same as Settings → Capacity and /api/v1/admin/capacity.",
1985 "The forge's capacity and guards, live: crew runs at once (crew.concurrency), where a crew run goes, process or job (crew.placement), checks at once (checks.concurrency), test shards per check (checks.shards), whether a cell's undeclared egress is refused or reported (cells.egress), and whether new accounts may create repositories and forks (guard_new_accounts: on refuses accounts younger than 7 days, off is the default). Without `key`, each setting, its value and where it comes from, and the recent changes. With `key` and `value` (\"\" goes back to the boot default), the change it would make; with dryRun false, made, by a forge admin with an admin-scope token, never an agent. A change is honoured by the next run, check or cell, never by a restart. The same as Settings → Capacity and /api/v1/admin/capacity.",
19861986 inputSchema: {
19871987 type: "object",
19881988 properties: {
19891989 key: {
19901990 type: "string",
1991 enum: ["crew.concurrency", "checks.concurrency", "checks.shards", "cells.egress", "guard_new_accounts"],
1991 enum: ["crew.concurrency", "crew.placement", "checks.concurrency", "checks.shards", "cells.egress", "guard_new_accounts"],
19921992 },
19931993 value: { type: "string", maxLength: 16 },
19941994 dryRun: { type: "boolean", description: "Plan only (the default). Send false to change it." },
test/crew-job.test.ts added +164
@@ -0,0 +1,164 @@
1 /**
2 * `crew.placement` (#1426): `job` runs the agent as a cluster Job through a
3 * stand-in kube client; the pod log is the transcript, a vanished Job is
4 * interrupted and queued again once, and `process` stays the default.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { assignIssue, openIssue } from "../src/actions/issues.ts";
8 import { JobVanished, runJob } from "../src/cluster/jobs.ts";
9 import { setCapacity } from "../src/core/capacity.ts";
10 import { crewJobPlacement } from "../src/crew/job_placement.ts";
11 import { readRunLog } from "../src/runs/log.ts";
12 import {
13 agentRunSettled,
14 startStandInCrew,
15 stopStandInCrew,
16 type StandInCrew,
17 } from "./helpers/crew-standin.ts";
18
19 const transcript = [
20 '{"type":"system","subtype":"init","session_id":"job-1","model":"fake"}',
21 '{"type":"assistant","message":{"content":[{"type":"text","text":"Working in the pod."}]}}',
22 '{"type":"result","subtype":"success","is_error":false,"result":"Nothing to change.","total_cost_usd":0.01,"num_turns":1,"session_id":"job-1","terminal_reason":"completed"}',
23 ].join("\n");
24
25 describe("crew placement", () => {
26 let standIn: StandInCrew;
27 let vanish = false;
28 const calls: { method: string; path: string; body?: string }[] = [];
29
30 // A stand-in kube API: the Job succeeds at once on node n3, its log the
31 // transcript; or, when `vanish` is set, the Job is gone when asked after.
32 const fetch = async (url: string, init: RequestInit) => {
33 const path = new URL(url).pathname;
34 calls.push({ method: String(init.method), path, ...(typeof init.body === "string" ? { body: init.body } : {}) });
35 if (init.method === "POST" || init.method === "DELETE") return Response.json({});
36 if (path.endsWith("/log")) return new Response(`${transcript}\n`);
37 if (path.endsWith("/pods"))
38 return Response.json({
39 items: [
40 {
41 metadata: { name: "p1" },
42 spec: { nodeName: "n3" },
43 status: { containerStatuses: [{ state: { terminated: { exitCode: 0 } } }] },
44 },
45 ],
46 });
47 if (vanish) return new Response("{}", { status: 404 });
48 return Response.json({ status: { succeeded: 1 } });
49 };
50
51 beforeAll(async () => {
52 process.env["FORGE_CREW_IMAGE"] = "registry.example/crew:1";
53 standIn = await startStandInCrew({
54 job: { fetch: fetch as never, credentials: { server: "https://k", token: "tok", namespace: "forge" }, pollMs: 1 },
55 });
56 }, 30_000);
57
58 afterAll(async () => {
59 delete process.env["FORGE_CREW_IMAGE"];
60 await stopStandInCrew(standIn);
61 });
62
63 const queue = async (title: string) => {
64 const { app, alice, bot, repo } = standIn;
65 const issue = openIssue(app, alice, repo, { title, body: "Please." });
66 if (!issue.ok) throw new Error(String(issue.error));
67 expect(assignIssue(app, alice, repo, issue.value, bot).ok).toBe(true);
68 return issue.value;
69 };
70
71 test("process is the default: no Job is made", async () => {
72 expect(crewJobPlacement(standIn.app.db)).toBeUndefined();
73 const issue = await queue("Water the ferns");
74 const run = await agentRunSettled(standIn.app, standIn.repo, (r) => r.issueId === issue.id);
75 expect(run.placement).not.toBe("job");
76 expect(calls).toEqual([]);
77 }, 30_000);
78
79 test("job without an image stays process", () => {
80 setCapacity(standIn.app.db, "crew.placement", "job", standIn.alice.id);
81 const kept = process.env["FORGE_CREW_IMAGE"];
82 delete process.env["FORGE_CREW_IMAGE"];
83 expect(crewJobPlacement(standIn.app.db)).toBeUndefined();
84 process.env["FORGE_CREW_IMAGE"] = kept;
85 expect(crewJobPlacement(standIn.app.db)?.image).toBe("registry.example/crew:1");
86 });
87
88 test("job runs the agent as a Job: labelled, token in, no mount, transcript from the pod log", async () => {
89 calls.length = 0;
90 const issue = await queue("Prune the vines");
91 const run = await agentRunSettled(standIn.app, standIn.repo, (r) => r.issueId === issue.id);
92 const made = calls.find((c) => c.method === "POST")!;
93 const spec = JSON.parse(made.body!);
94 const pod = spec.spec.template;
95 expect(pod.metadata.labels["forge-lane"]).toBe("agent");
96 expect(pod.spec.volumes).toBeUndefined();
97 expect(pod.spec.automountServiceAccountToken).toBe(false);
98 const container = pod.spec.containers[0];
99 expect(container.image).toBe("registry.example/crew:1");
100 const env = Object.fromEntries(container.env.map((e: { name: string; value: string }) => [e.name, e.value]));
101 expect(env["FORGE_TOKEN"]).toMatch(/\S/);
102 expect(env["FORGE_BRANCH"]).toBe(`bot/${issue.number}-prune-the-vines`);
103 expect(env["FORGE_STDIN"]).toContain("Prune the vines");
104 expect(env["TMPDIR"]).toBeUndefined();
105 expect(container.command.slice(0, 2)).toEqual(["/bin/sh", "-c"]);
106 expect(container.command).toContain("--restricted");
107 expect(calls.some((c) => c.method === "DELETE")).toBe(true);
108
109 expect(run.placement).toBe("job");
110 expect(run.node).toBe("n3");
111 const log = readRunLog(standIn.app.config.dataDir, run.id, 64 * 1024).lines.join("\n");
112 expect(log).toContain("Working in the pod.");
113 expect(log).toContain("claude: completed");
114 });
115
116 test("a vanished Job is interrupted and queued again once", async () => {
117 calls.length = 0;
118 vanish = true;
119 const issue = await queue("Mow the lawn");
120 const { app } = standIn;
121 const runs = () =>
122 app.db
123 .query<{ state: string; summary: string }, [string]>(
124 "SELECT state, summary FROM run WHERE issue_id = ?1 AND kind = 'agent' ORDER BY created_at",
125 )
126 .all(issue.id);
127 const deadline = Date.now() + 30_000;
128 while (Date.now() < deadline && !runs().some((r) => r.state === "failed")) await Bun.sleep(50);
129 vanish = false;
130 const seen = runs();
131 expect(seen.some((r) => r.state === "cancelled" && r.summary.includes("vanished") && r.summary.includes("queued again"))).toBe(true);
132 expect(seen.some((r) => r.state === "failed" && r.summary.includes("vanished"))).toBe(true);
133 expect(calls.filter((c) => c.method === "POST").length).toBe(2);
134 }, 40_000);
135 });
136
137 describe("runJob follows the log", () => {
138 const cred = { server: "https://k", token: "t", namespace: "n" };
139 const spec = { name: "j", image: "i", command: ["true"] };
140
141 test("every line reaches onLine once, in order, whether followed or read at the end", async () => {
142 const fetch = async (url: string, init: RequestInit) => {
143 const path = new URL(url).pathname;
144 if (init.method === "POST" || init.method === "DELETE") return Response.json({});
145 if (path.endsWith("/log")) return new Response("a\nb\nc\n");
146 if (path.endsWith("/pods")) return Response.json({ items: [{ metadata: { name: "p" }, spec: { nodeName: "n1" } }] });
147 return Response.json({ status: { succeeded: 1 } });
148 };
149 const seen: string[] = [];
150 const res = await runJob(spec, { fetch: fetch as never, credentials: cred, pollMs: 1, onLine: (l) => seen.push(l) });
151 expect(res.lines).toEqual(["a", "b", "c"]);
152 expect(seen).toEqual(["a", "b", "c"]);
153 });
154
155 test("a Job that is gone is reported as vanished, not as a failure to read", async () => {
156 const fetch = async (url: string, init: RequestInit) => {
157 const path = new URL(url).pathname;
158 if (init.method === "POST" || init.method === "DELETE") return Response.json({});
159 if (path.includes("/jobs/")) return new Response("{}", { status: 404 });
160 return Response.json({ items: [] });
161 };
162 await expect(runJob(spec, { fetch: fetch as never, credentials: cred, pollMs: 1 })).rejects.toBeInstanceOf(JobVanished);
163 });
164 });
test/helpers/crew-standin.ts +4 −1
@@ -42,7 +42,9 @@ export interface StandInCrew {
4242 }
4343
4444 /** A forge with checks and a crew whose Claude Code is the stand-in. */
45 export async function startStandInCrew(): Promise<StandInCrew> {
45 export async function startStandInCrew(
46 crewOptions: Partial<Parameters<typeof startCrew>[1]> = {},
47 ): Promise<StandInCrew> {
4648 const dataDir = await mkdtemp(join(tmpdir(), "forge-crew-"));
4749 const app = createApp({ dataDir, port: 0 });
4850 const servers = await serve(app);
@@ -112,6 +114,7 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Added CREW
112114 runTimeoutMs: 60_000,
113115 networkRetryScale: 0,
114116 reviewBudgetMs: 4_000,
117 ...crewOptions,
115118 });
116119 const a = await createUser(app.db, {
117120 trusted: true,

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs