Skip to content

An open-source, faster Devin alternative

TypeScript

computer: split host/main.ts and workspaces/index.ts (work 103, step 2) (#1031)

opencomputer-app[bot]0040e9bd7769
diff --git a/computer/src/host/cold-start.ts b/computer/src/host/cold-start.ts
index 1cc1fcc9..5a37c9ac 100644
--- a/computer/src/host/cold-start.ts
+++ b/computer/src/host/cold-start.ts
@@ -5,7 +5,7 @@
// Invariant: the fork is complete (every worktree added, .fork.json written)
// before `coldStart` resolves, and the host hands the runner its socket
// connection, and with it `credentials` and the first `deliver`, only after
-// that (host/main.ts `adopt`). The runner process itself may boot inside the
+// that (host/start-runner.ts `adopt`). The runner process itself may boot inside the
// still-empty fork directory: until it has credentials it only listens on its
// socket and never reads its cwd, so Claude Code never starts, nor sees the
// fork, before the worktrees exist. If the fork fails, a runner that already
diff --git a/computer/src/host/main.ts b/computer/src/host/main.ts
index 704fd4e7..ec83325e 100644
--- a/computer/src/host/main.ts
+++ b/computer/src/host/main.ts
@@ -35,44 +35,47 @@ import { AsyncLocalStorage } from 'node:async_hooks';
import type net from 'node:net';
import os from 'node:os';
import path from 'node:path';
-import { randomBytes } from 'node:crypto';
-import { existsSync, mkdirSync } from 'node:fs';
+import { mkdirSync } from 'node:fs';
import { HOST_DATA, HOST_RUN, HOST_TOKEN_SOCKET, PROTOCOL_VERSION, RUNNER_TOKEN_DIR } from '../protocol.js';
import { codexBin } from '../runner-env.js';
import { prereadCodex } from './codex-preread.js';
-import type { Delivery, GatewayToHost, HarnessName, HostCredentials, HostToGateway, ModelRoute, HostToRunner, Person,
- RunnerToHost, SessionReport, SessionSecret, SessionSpec, SpareReport, TraceContext } from '../protocol.js';
+import type {
+ Delivery,
+ GatewayToHost,
+ HostCredentials,
+ HostToGateway,
+ ModelRoute,
+ HostToRunner,
+ RunnerToHost,
+ SessionSecret,
+ SessionSpec,
+ TraceContext,
+} from '../protocol.js';
import {
applyGatewayDefinition,
checkoutRepos,
configureAsRunner,
fetchRepo,
- forkDir,
- forkInfo,
- mkdirAsRunner,
prepareInBackground,
observeWorkspaces,
oldestFetchAgeS,
startHousekeeping,
touchFork,
- workspacePrepared,
workspacesEnabled,
} from '../workspaces/index.js';
-import { lines, send, socketFor } from '../ipc.js';
+import { send, socketFor } from '../ipc.js';
import { log } from '../log.js';
-import { coldStart, forkFor } from './cold-start.js';
-import { closed, launchRunner, rediscover, retire } from './runner-sockets.js';
-import { adoption, type First } from './adoption.js';
+import { closed, rediscover, retire } from './runner-sockets.js';
+import { type Runner, runnerStarts } from './start-runner.js';
import { Pool } from './pool.js';
-import { claimSpare } from './claim.js';
import { tokenRelay } from './tokens.js';
import { hostPreviews } from './previews.js';
import { startHostTelemetry, workspaceTelemetry } from './telemetry.js';
import { diskReport, hostSampler } from './sample.js';
-import { type ColdStart, decidePath, type Forwarded, forwardTrace, loadForwarded, runnerGone, saveForwarded, traceFields } from './trace.js';
+import { decidePath, forwardTrace, loadForwarded, runnerGone, saveForwarded, traceFields } from './trace.js';
import type { Dimensions } from '../telemetry/envelope.js';
import { assignedIdentity, codeVersion, identityFile, loadIdentity, saveIdentity } from './identity.js';
-import { hostModelAccess, PROXY_DOWN } from './model-access.js';
+import { hostModelAccess } from './model-access.js';
import { unitExists } from './launch.js';
import { runnerUser } from './runner-user.js';
import { gatewayLink } from './gateway-link.js';
@@ -114,34 +117,11 @@ const subs = hostModelAccess({ controlSocket: env.SP_MODEL_PROXY || undefined, m
// ---------------------------------------------------------------- runners
-interface Runner {
- /** Its socket's name: an id (work 069), or its session key's for runners from before. */
- id: string;
- /** The session it serves; '' while it is a spare. */
- key: string;
- sock: net.Socket;
- spare?: SpareReport;
- /** The session's owner as last sent, so a `people` update reaches its commits. */
- owner?: Person;
- report?: SessionReport;
- /** Work 082: what it runs, from its launch's spec or its first report; absent = claude. */
- harness?: HarnessName;
- lastDelivery: number;
- connectedAt: number;
- exiting?: boolean;
- /** Told to exit for its session's new route (model-access.ts): a delivery waits for it to go and starts another. */
- switching?: boolean;
- /** Set by a launch, taken by the delivery that caused it: the path is not `warm`. */
- cold?: ColdStart;
- /** The last trace forwarded (also in `<key>.trace.json`), for `turn.abandoned`. */
- forwarded?: Forwarded;
- calls: Map<string, (r: { ok: boolean; error?: string }) => void>;
-}
const runners = new Map<string, Runner>();
const pool = new Pool<Runner>({
size: POOL_SIZE,
version: VERSION,
- launch: launchSpare,
+ launch: () => starts.launchSpare(),
failed: () => tm.emit('pool.spare_failed', {}),
evict: (r, reason) => {
tm.emit('pool.spare_evicted', { data: { reason } });
@@ -162,47 +142,20 @@ function switchRunner(key: string, r = runners.get(key)) {
/** Its session's epoch moved on (api-host `epoch`): end its turn now, then exit; killed after 10 s. */
const retireRunner = async (id: string, r = [...runners.values()].find((x) => x.id === id)) =>
r && ((r.exiting = true), retire(r.sock, socketFor(r.id), () => void call(r, { t: 'stop' }, 10_000).catch(() => {})));
-const newRunnerId = () => randomBytes(8).toString('hex');
-const launchOpts = { tm, mode: LAUNCH, env, root: ROOT };
/** spawn, secret and thread requests in flight to the gateway, by id: the runner that asked. */
const spawning = new Map<string, Runner>();
const starting = new Map<string, Promise<Runner>>();
/** Set on SIGTERM: runner sockets closing then are the host leaving, not the runners. */
let stopping = false;
-/** A workspace fork is complete once .fork.json is written (the last step of forkSession). */
-const forkComplete = (forkPath: string | undefined) => !workspacesEnabled() || !forkPath || !!forkInfo(forkPath);
-
-/** Take a connected runner on (adoption.ts): register it as its session's, or as a spare, follow its messages, send it `credentials`.
- * `key`: the session it was launched for; a verified runner names it in its first report, and one with no session is a spare.
- * `first`: the delivery's credentials, sent instead of the welcome ones, since the runner starts its harness with the first it gets. */
-function adopt(id: string, sock: net.Socket, o: { key?: string; verify?: boolean; first?: HostCredentials; harness?: HarnessName } = {}): Promise<Runner> {
- const r: Runner = { id, key: o.key ?? '', sock, lastDelivery: Date.now(), connectedAt: Date.now(), calls: new Map(), harness: o.harness };
- tokens.serveRunner(id, sock, () => r.key); // its own token socket names the session it serves now (work 080)
- return new Promise((resolve, reject) => {
- const take = (m?: First) => {
- if (m?.t === 'report') (r.key = m.report.key), (r.harness ??= m.report.harness);
- if (m?.t === 'spare') r.spare = m.spare;
- if (r.key) register(r, !!o.verify);
- else {
- pool.add(r);
- pool.changed(r);
- }
- sock.on('close', () => runnerClosed(r));
- const c = o.first ?? subs.forRunner(r.key, org.creds, r.harness);
- if (c) send(sock, { t: 'credentials', credentials: c } satisfies HostToRunner);
- resolve(r);
- };
- const stop = (why: string) => {
- log.warn(`runner ${id}: ${why}; stopping it`);
- exitRunner(sock);
- reject(new Error(why));
- };
- const a = adoption({ verify: !!o.verify, complete: forkComplete, take, stop, gone: () => reject(new Error('runner gone')) });
- lines(sock, (m: RunnerToHost) => a.message(m) && void onRunner(r, m));
- sock.once('close', () => a.closed());
- });
-}
+/** Starting and adopting runners (start-runner.ts); what it asks for is looked up when used, so `api` and `tokens` below are there by then. */
+const starts = runnerStarts({
+ tm, launch: { tm, mode: LAUNCH, env, root: ROOT }, version: VERSION, pool,
+ creds: () => org.creds, models: subs,
+ mint: (spec, id) => api.mint(spec, id), serveTokens: (id, sock, session) => tokens.serveRunner(id, sock, session),
+ fillPool: () => fillPool(), inFork: (f, fn) => forkContext.run(f, fn),
+ register, closed: runnerClosed, message: onRunner, exit: exitRunner, toGateway,
+});
/** The runner serves its session from now on; one already there for it (found twice after a restart) is told to go. */
function register(r: Runner, found = false) {
@@ -279,77 +232,12 @@ function ensureRunner(spec: SessionSpec, f: Fields, first?: HostCredentials): Pr
if (live) return Promise.resolve(live);
let p = starting.get(spec.key);
if (!p) {
- p = startRunner(spec, f, first).finally(() => starting.delete(spec.key));
+ p = starts.startRunner(spec, f, first).finally(() => starting.delete(spec.key));
starting.set(spec.key, p);
}
return p;
}
-async function startRunner(spec: SessionSpec, f: Fields, first?: HostCredentials): Promise<Runner> {
- if (!subs.up) throw new Error(PROXY_DOWN);
- let existing = spec.forkPath && existsSync(spec.forkPath) && forkComplete(spec.forkPath) ? spec.forkPath : undefined;
- // A new session in a prepared workspace may take a spare (work 069); a resumed one starts cold, to resume.
- // Claude takes one of its route's spare kind (C6); Codex (work 082) any.
- const codex = spec.harness === 'codex';
- if (pool.enabled && !spec.sdkSessionId && workspacesEnabled() && workspacePrepared(spec.owner) && subs.canSpare()) {
- const t0 = Date.now();
- const got = await claimSpare<Runner>({
- // Refill as soon as the spare is ours: the fork and the claim take seconds, in which another session may arrive.
- take: () => { const t = pool.take(subs.kind(spec.key, 'claude'), codex); fillPool(); return t; },
- fork: async () => existing ?? forkContext.run(f, () => forkFor(tm, spec, f)),
- claim: async (r, forkPath) => {
- // Bound to the session first (C6); Claude's credentials go before the claim, Codex's after (its claim drops the spare's).
- await subs.claim(r.id, spec.key, spec.harness ?? 'claude');
- const c = first ?? subs.forRunner(spec.key, org.creds, spec.harness ?? 'claude');
- if (c && !codex) send(r.sock, { t: 'credentials', credentials: c } satisfies HostToRunner);
- await call(r, { t: 'claim', session: { ...spec, forkPath }, api: await api.mint(spec, r.id) }, 5000);
- if (c && codex) send(r.sock, { t: 'credentials', credentials: c } satisfies HostToRunner);
- },
- discard: (r) => exitRunner(r.sock),
- release: (r) => r.sock.destroyed || pool.add(r),
- });
- if ('runner' in got) {
- const r = got.runner;
- r.key = spec.key;
- r.harness = spec.harness;
- r.lastDelivery = Date.now();
- register(r);
- if (r.report) toGateway({ t: 'session', report: r.report });
- r.cold = { resumed: false, prewarmed: true };
- tm.emit('runner.claimed', { ...f, duration_ms: Date.now() - t0 });
- log.info(`runner ${r.id} claimed for ${spec.key} in ${Date.now() - t0} ms`);
- return r;
- }
- tm.emit('pool.spare_missed', { ...f, data: { reason: got.missed } });
- existing ??= got.forkPath;
- }
- // A workspace fork's directory is known before forking: the runner boots in it while the worktrees are added.
- const dir = existing ?? (workspacesEnabled() ? forkDir(spec.owner, spec.key) : undefined);
- if (dir && !existing) await mkdirAsRunner(dir);
- const id = newRunnerId();
- const runnerApi = await api.mint(spec, id); // work 084: the session's journal, socket and token; undefined off the API
- const { ready: sock } = await coldStart({
- dir,
- fork: existing ? undefined : () => forkContext.run(f, () => forkFor(tm, spec, f)),
- start: (cwd) => launchRunner({ id, session: { ...spec, forkPath: cwd }, socket: socketFor(id), api: runnerApi && { ...runnerApi, token: '' }, version: VERSION }, { ...launchOpts, f }),
- abandon: exitRunner,
- });
- if (sock.destroyed) throw new Error('runner exited while its fork was made');
- const r = await adopt(id, sock, { key: spec.key, first, harness: spec.harness });
- if (runnerApi) send(sock, { t: 'api', api: runnerApi } satisfies HostToRunner); // the token stays out of argv and env
- r.cold = { resumed: !!spec.sdkSessionId };
- return r;
-}
-
-/** Start a spare for the pool, bound to `models.claude` first: a runner with no session, which parks a Claude Code once it has credentials. */
-async function launchSpare() {
- const id = newRunnerId();
- await subs.spare(id);
- await launchRunner({ id, socket: socketFor(id), version: VERSION }, launchOpts).then((sock) => adopt(id, sock))
- .catch((e) => (subs.closed('', id), Promise.reject(e)));
- tm.emit('pool.spare_started', { data: { launch_mode: LAUNCH } });
-}
-
setInterval(() => {
for (const r of runners.values()) {
if (api.subagentsRunning(r.report)) r.lastDelivery = Date.now(); // idle counts from the last subagent's end
@@ -547,7 +435,7 @@ const previews = hostPreviews({ ask: link.ask });
mkdirSync(HOST_RUN, { recursive: true });
const tokenServer = tokens.serve(path.join(HOST_RUN, HOST_TOKEN_SOCKET));
await api.boot(); // settles the journals no runner holds (work 084); none on a host that never had a v4 gateway
-api.rediscovered(await rediscover((id, sock) => adopt(id, sock, { verify: true }).then((r) => log.info('rediscovered runner', id, r.key || 'spare'))));
+api.rediscovered(await rediscover((id, sock) => starts.adopt(id, sock, { verify: true }).then((r) => log.info('rediscovered runner', id, r.key || 'spare'))));
log.info(`host ${identity.hostId} (${VERSION}) run=${HOST_RUN} launch=${LAUNCH} ${workspacesEnabled() ? 'workspaces' : 'laptop'} mode, ${runners.size} live runner(s), pool ${POOL_SIZE}`);
link.dial();
setInterval(fillPool, 30_000).unref();
diff --git a/computer/src/host/start-runner.ts b/computer/src/host/start-runner.ts
new file mode 100644
index 00000000..e188dfb7
--- /dev/null
+++ b/computer/src/host/start-runner.ts
@@ -0,0 +1,203 @@
+// Starting runners and taking them on (work 045, 069; split out of host/main.ts
+// for work 103): `adopt` makes a connected runner the host's (its session's, or
+// a spare), `startRunner` gets a session its runner (a claimed spare, else a
+// cold start in its fork), `launchSpare` starts one for the pool.
+// host/main.ts keeps the registry (`runners`), what a runner's messages mean,
+// and delivery; it passes those in as `StartDeps`.
+//
+// Invariants:
+// - A runner gets `credentials` only once adoption took it (adoption.ts):
+// never one whose fork is incomplete.
+// - A new session in a prepared workspace may take a spare; a resumed one
+// always starts cold, to resume.
+// - The API token of a cold-started runner goes over its socket, never in
+// argv or the environment.
+
+import type net from 'node:net';
+import { randomBytes } from 'node:crypto';
+import { existsSync } from 'node:fs';
+import type {
+ HarnessName,
+ HostCredentials,
+ HostToGateway,
+ HostToRunner,
+ Person,
+ RunnerToHost,
+ SessionReport,
+ SessionSpec,
+ SpareReport,
+} from '../protocol.js';
+import type { RunnerApi } from '../protocol-api.js';
+import { forkDir, forkInfo, mkdirAsRunner, workspacePrepared, workspacesEnabled } from '../workspaces/index.js';
+import { lines, send, socketFor } from '../ipc.js';
+import { log } from '../log.js';
+import type { Telemetry } from '../telemetry/emitter.js';
+import type { Dimensions } from '../telemetry/envelope.js';
+import { adoption, type First } from './adoption.js';
+import { claimSpare } from './claim.js';
+import { coldStart, forkFor } from './cold-start.js';
+import { type HostModelAccess, PROXY_DOWN } from './model-access.js';
+import type { Pool } from './pool.js';
+import { callRunner as call } from './runner-call.js';
+import { launchRunner } from './runner-sockets.js';
+import type { ColdStart, Forwarded } from './trace.js';
+
+export interface Runner {
+ /** Its socket's name: an id (work 069), or its session key's for runners from before. */
+ id: string;
+ /** The session it serves; '' while it is a spare. */
+ key: string;
+ sock: net.Socket;
+ spare?: SpareReport;
+ /** The session's owner as last sent, so a `people` update reaches its commits. */
+ owner?: Person;
+ report?: SessionReport;
+ /** Work 082: what it runs, from its launch's spec or its first report; absent = claude. */
+ harness?: HarnessName;
+ lastDelivery: number;
+ connectedAt: number;
+ exiting?: boolean;
+ /** Told to exit for its session's new route (model-access.ts): a delivery waits for it to go and starts another. */
+ switching?: boolean;
+ /** Set by a launch, taken by the delivery that caused it: the path is not `warm`. */
+ cold?: ColdStart;
+ /** The last trace forwarded (also in `<key>.trace.json`), for `turn.abandoned`. */
+ forwarded?: Forwarded;
+ calls: Map<string, (r: { ok: boolean; error?: string }) => void>;
+}
+
+/** What host/main.ts owns and a start needs. Everything is asked for when used, so main.ts may wire it before its parts exist. */
+export interface StartDeps {
+ tm: Telemetry;
+ /** How runners are launched (launch.ts): the mode, the host's environment and its release. */
+ launch: { tm: Telemetry; mode: string; env: NodeJS.ProcessEnv; root: string };
+ version: string;
+ pool: Pool<Runner>;
+ /** The organization's credentials as the gateway last sent them. */
+ creds(): HostCredentials | undefined;
+ /** The host's model access (model-access.ts, work 097): every runner and spare is bound at the model proxy through it. */
+ models: Pick<HostModelAccess, 'up' | 'canSpare' | 'kind' | 'spare' | 'claim' | 'closed' | 'forRunner'>;
+ /** Work 084: the session's journal, socket and token for this runner; undefined off the API. */
+ mint(spec: SessionSpec, runnerId: string): Promise<RunnerApi | undefined>;
+ /** The runner's own token socket, naming the session it serves now (tokens.ts). */
+ serveTokens(id: string, sock: net.Socket, session: () => string | undefined): void;
+ fillPool(): void;
+ /** Run a fork so its workspace events join the delivery's trace. */
+ inFork<T>(f: Dimensions, fn: () => Promise<T>): Promise<T>;
+ /** The runner serves its session from now on; `found`: it was running already when the host started. */
+ register(r: Runner, found?: boolean): void;
+ /** Its socket closed. */
+ closed(r: Runner): void;
+ /** A message from an adopted runner. */
+ message(r: Runner, m: RunnerToHost): unknown;
+ /** Tell a runner to go and close its socket. */
+ exit(sock: net.Socket): void;
+ toGateway(m: HostToGateway): void;
+}
+
+const newRunnerId = () => randomBytes(8).toString('hex');
+
+/** A workspace fork is complete once .fork.json is written (the last step of forkSession). */
+const forkComplete = (forkPath: string | undefined) => !workspacesEnabled() || !forkPath || !!forkInfo(forkPath);
+
+export function runnerStarts(d: StartDeps) {
+ const { tm } = d;
+
+ /** Take a connected runner on (adoption.ts): register it as its session's, or as a spare, follow its messages, send it `credentials`.
+ * `key`: the session it was launched for; a verified runner names it in its first report, and one with no session is a spare.
+ * `first`: the delivery's credentials, sent instead of the welcome ones, since the runner starts its harness with the first it gets. */
+ function adopt(id: string, sock: net.Socket, o: { key?: string; verify?: boolean; first?: HostCredentials; harness?: HarnessName } = {}): Promise<Runner> {
+ const r: Runner = { id, key: o.key ?? '', sock, lastDelivery: Date.now(), connectedAt: Date.now(), calls: new Map(), harness: o.harness };
+ d.serveTokens(id, sock, () => r.key); // its own token socket names the session it serves now (work 080)
+ return new Promise((resolve, reject) => {
+ const take = (m?: First) => {
+ if (m?.t === 'report') (r.key = m.report.key), (r.harness ??= m.report.harness);
+ if (m?.t === 'spare') r.spare = m.spare;
+ if (r.key) d.register(r, !!o.verify);
+ else {
+ d.pool.add(r);
+ d.pool.changed(r);
+ }
+ sock.on('close', () => d.closed(r));
+ const c = o.first ?? d.models.forRunner(r.key, d.creds(), r.harness);
+ if (c) send(sock, { t: 'credentials', credentials: c } satisfies HostToRunner);
+ resolve(r);
+ };
+ const stop = (why: string) => {
+ log.warn(`runner ${id}: ${why}; stopping it`);
+ d.exit(sock);
+ reject(new Error(why));
+ };
+ const a = adoption({ verify: !!o.verify, complete: forkComplete, take, stop, gone: () => reject(new Error('runner gone')) });
+ lines(sock, (m: RunnerToHost) => a.message(m) && void d.message(r, m));
+ sock.once('close', () => a.closed());
+ });
+ }
+
+ async function startRunner(spec: SessionSpec, f: Dimensions, first?: HostCredentials): Promise<Runner> {
+ if (!d.models.up) throw new Error(PROXY_DOWN);
+ let existing = spec.forkPath && existsSync(spec.forkPath) && forkComplete(spec.forkPath) ? spec.forkPath : undefined;
+ // A new session in a prepared workspace may take a spare (work 069); a resumed one starts cold, to resume.
+ // Claude takes one of its route's spare kind (C6); Codex (work 082) any.
+ const codex = spec.harness === 'codex';
+ if (d.pool.enabled && !spec.sdkSessionId && workspacesEnabled() && workspacePrepared(spec.owner) && d.models.canSpare()) {
+ const t0 = Date.now();
+ const got = await claimSpare<Runner>({
+ // Refill as soon as the spare is ours: the fork and the claim take seconds, in which another session may arrive.
+ take: () => { const t = d.pool.take(d.models.kind(spec.key, 'claude'), codex); d.fillPool(); return t; },
+ fork: async () => existing ?? d.inFork(f, () => forkFor(tm, spec, f)),
+ claim: async (r, forkPath) => {
+ // Bound to the session first (C6); Claude's credentials go before the claim, Codex's after (its claim drops the spare's).
+ await d.models.claim(r.id, spec.key, spec.harness ?? 'claude');
+ const c = first ?? d.models.forRunner(spec.key, d.creds(), spec.harness ?? 'claude');
+ if (c && !codex) send(r.sock, { t: 'credentials', credentials: c } satisfies HostToRunner);
+ await call(r, { t: 'claim', session: { ...spec, forkPath }, api: await d.mint(spec, r.id) }, 5000);
+ if (c && codex) send(r.sock, { t: 'credentials', credentials: c } satisfies HostToRunner);
+ },
+ discard: (r) => d.exit(r.sock),
+ release: (r) => r.sock.destroyed || d.pool.add(r),
+ });
+ if ('runner' in got) {
+ const r = got.runner;
+ r.key = spec.key;
+ r.harness = spec.harness;
+ r.lastDelivery = Date.now();
+ d.register(r);
+ if (r.report) d.toGateway({ t: 'session', report: r.report });
+ r.cold = { resumed: false, prewarmed: true };
+ tm.emit('runner.claimed', { ...f, duration_ms: Date.now() - t0 });
+ log.info(`runner ${r.id} claimed for ${spec.key} in ${Date.now() - t0} ms`);
+ return r;
+ }
+ tm.emit('pool.spare_missed', { ...f, data: { reason: got.missed } });
+ existing ??= got.forkPath;
+ }
+ // A workspace fork's directory is known before forking: the runner boots in it while the worktrees are added.
+ const dir = existing ?? (workspacesEnabled() ? forkDir(spec.owner, spec.key) : undefined);
+ if (dir && !existing) await mkdirAsRunner(dir);
+ const id = newRunnerId();
+ const runnerApi = await d.mint(spec, id); // work 084: the session's journal, socket and token; undefined off the API
+ const { ready: sock } = await coldStart({
+ dir,
+ fork: existing ? undefined : () => d.inFork(f, () => forkFor(tm, spec, f)),
+ start: (cwd) => launchRunner({ id, session: { ...spec, forkPath: cwd }, socket: socketFor(id), api: runnerApi && { ...runnerApi, token: '' }, version: d.version }, { ...d.launch, f }),
+ abandon: d.exit,
+ });
+ if (sock.destroyed) throw new Error('runner exited while its fork was made');
+ const r = await adopt(id, sock, { key: spec.key, first, harness: spec.harness });
+ if (runnerApi) send(sock, { t: 'api', api: runnerApi } satisfies HostToRunner); // the token stays out of argv and env
+ r.cold = { resumed: !!spec.sdkSessionId };
+ return r;
+ }
+
+ /** Start a spare for the pool, bound to `models.claude` first: a runner with no session, which parks a Claude Code once it has credentials. */
+ async function launchSpare() {
+ const id = newRunnerId();
+ await d.models.spare(id);
+ await launchRunner({ id, socket: socketFor(id), version: d.version }, d.launch).then((sock) => adopt(id, sock))
+ .catch((e) => (d.models.closed('', id), Promise.reject(e)));
+ tm.emit('pool.spare_started', { data: { launch_mode: d.launch.mode } });
+ }
+
+ return { adopt, startRunner, launchSpare };
+}
diff --git a/computer/src/runner/checkout.ts b/computer/src/runner/checkout.ts
index ae352613..64a9bc26 100644
--- a/computer/src/runner/checkout.ts
+++ b/computer/src/runner/checkout.ts
@@ -3,7 +3,7 @@
// before the session starts. The runner offers it as a tool of the in-process
// `calvin` MCP server (see session.ts); the request goes runner → host, which
// clones if needed and adds a worktree on the session's branch
-// (workspaces/index.ts checkoutRepos). The fork's AGENTS.md lists what exists.
+// (workspaces/fork.ts checkoutRepos). The fork's AGENTS.md lists what exists.
import { tool } from './tool.js';
import { z } from 'zod';
diff --git a/computer/src/workspaces/clones.ts b/computer/src/workspaces/clones.ts
new file mode 100644
index 00000000..dce01d35
--- /dev/null
+++ b/computer/src/workspaces/clones.ts
@@ -0,0 +1,178 @@
+// A person's clones on a host (work 045, item S4; split out of index.ts for
+// work 103): where things live under <SP_DATA>/people/<dir>, how git runs on
+// them, the locks, cloning, and preparing a person's workspace. fork.ts,
+// housekeep.ts and prune.ts build on this; index.ts has the overview.
+//
+// Invariants:
+// - Worktree operations on one clone are serialized (`serial`), and so are its
+// fetches, in a separate lane (`fetchLane`, fetch-schedule.ts).
+// - Git runs as the runners' user (as-runner.ts) and never prompts.
+// - No session waits on a clone (work 056): eager repositories are cloned in
+// the background, one preparation per person at a time.
+
+import { execFile } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import path from 'node:path';
+import { promisify } from 'node:util';
+import { log } from '../log.js';
+import { HOST_DATA, type Person } from '../protocol.js';
+import { type Definition, isLazy, loadDefinition, type RepoDef } from './definition.js';
+import { command, copyFile, mkdir, rename, rm, writeFile } from './as-runner.js';
+import { Freshness, keyedQueue } from './fetch-schedule.js';
+
+const exec = promisify(execFile);
+
+// ---------------------------------------------------------------- config
+
+/** Durations: `300` (seconds), `500ms`, `30s`, `5m`, `2h`. */
+function duration(value: string | undefined, fallback: string): number {
+ const m = (value || fallback).trim().match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)?$/);
+ if (!m) return duration(fallback, fallback);
+ return Number(m[1]) * { ms: 1, s: 1e3, m: 60e3, h: 3600e3, d: 86400e3 }[(m[2] ?? 's') as 'ms'];
+}
+export const fetchInterval = () => duration(process.env.SP_FETCH_INTERVAL, '5m');
+export const fetchTimeout = () => duration(process.env.SP_FETCH_TIMEOUT, '2m');
+export const forkFetchTimeout = () => duration(process.env.SP_FORK_FETCH_TIMEOUT, '5s');
+/** A fork skips its fetch of a clone fetched this recently and not pushed to since (fetch-schedule.ts). */
+export const forkFetchFresh = () => duration(process.env.SP_FORK_FETCH_FRESH, '60s');
+export const HOUSEKEEPING_FETCHES = 4;
+export const retention = () => duration(process.env.SP_FORK_RETENTION_DAYS ? `${process.env.SP_FORK_RETENTION_DAYS}d` : undefined, '14d');
+const CLONE_TIMEOUT = 30 * 60e3;
+
+// ---------------------------------------------------------------- layout
+
+/** A session key as a directory and branch name: `C0B:1791.82` → `C0B-1791-82`. */
+export function safeKey(key: string) {
+ return key.replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-|-$/g, '');
+}
+
+/** Root of a person's area on the host: <SP_DATA>/people/<dir>. */
+export function personRoot(person: Person): string {
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(person.dir)) throw new Error(`bad person dir: ${person.dir}`);
+ return path.join(HOST_DATA, 'people', person.dir);
+}
+export const workspaceDir = (person: Person) => path.join(personRoot(person), 'ws');
+export const forkDir = (person: Person, sessionKey: string) => path.join(personRoot(person), 'sessions', safeKey(sessionKey));
+
+// ---------------------------------------------------------------- git
+
+export async function git(cwd: string, args: string[], timeout = 0) {
+ const c = command('git', args, { GIT_TERMINAL_PROMPT: '0' });
+ return (await exec(c.cmd, c.args, { cwd, timeout, env: c.env, maxBuffer: 20 << 20 })).stdout.trim();
+}
+export const ok = (p: Promise<unknown>) => p.then(() => true, () => false);
+export function errText(e: any): string {
+ if (e?.killed) return 'timed out';
+ const lines = String(e?.stderr || e?.message || e).trim().split('\n').filter(Boolean);
+ return lines.find((l) => /^(fatal|error):/.test(l)) ?? lines.pop() ?? 'failed';
+}
+export const isClone = (dir: string) => existsSync(path.join(dir, '.git'));
+export const fetchErrorType = (e: unknown) => ((e as { killed?: boolean })?.killed ? 'timeout' : 'git_fetch');
+
+/** Timings the host agent reports as telemetry (work 054); calls never affect the work. */
+export interface WorkspaceObserver {
+ repoForked?(t: { repo: string; ms: number; fetchMs: number; worktreeMs: number; lockWaitMs: number; fetchSkipped: boolean; fetchError?: string }): void;
+ repoFetched?(t: { repo: string; ms: number; fastForwarded: boolean; trigger: FetchTrigger; fetchError?: string }): void;
+}
+/** Why housekeeping fetched a clone: its periodic pass, or a push to the branch it forks from. */
+export type FetchTrigger = 'periodic' | 'pushed';
+let observer: WorkspaceObserver = {};
+export const observeWorkspaces = (o: WorkspaceObserver) => void (observer = o);
+/** The observer now (fork.ts and housekeep.ts report through it). */
+export const observed = () => observer;
+export const observe = (f: () => void) => {
+ try {
+ f();
+ } catch {}
+};
+
+// One queue per clone: no concurrent clone, worktree add, prune or fast-forward on the same repository.
+export const serial = keyedQueue();
+// Fetches have their own lane per clone, so worktree operations never wait behind one.
+export const fetchLane = keyedQueue();
+export const freshness = new Freshness();
+
+const branches = new Map<string, string>();
+export async function defaultBranch(clone: string, repo: RepoDef) {
+ if (repo.branch) return repo.branch;
+ const cached = branches.get(clone);
+ if (cached) return cached;
+ const head = () => git(clone, ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD']);
+ const ref = await head().catch(async () => (await git(clone, ['remote', 'set-head', 'origin', '--auto'], fetchTimeout()), head()));
+ const b = ref.replace(/^origin\//, '');
+ branches.set(clone, b);
+ return b;
+}
+
+export const fetchedAt = new Map<string, string>();
+const PREPARED_FILE = '.workspace-prepared';
+
+export async function cloneRepo(clone: string, repo: RepoDef): Promise<boolean> {
+ return serial(clone, async () => {
+ if (isClone(clone)) return false;
+ const tmp = `${clone}.cloning`;
+ await rm(tmp);
+ await mkdir(path.dirname(clone), { recursive: true });
+ const t0 = Date.now();
+ // A lazy repository is cloned while a session waits: blobs come on demand (checkout fetches HEAD's).
+ const partial = isLazy(repo) ? ['--filter=blob:none'] : [];
+ await git(path.dirname(clone), ['clone', '--quiet', ...partial, ...(repo.branch ? ['-b', repo.branch] : []), repo.remote, tmp], CLONE_TIMEOUT);
+ await rename(tmp, clone);
+ fetchedAt.set(clone, new Date().toISOString());
+ freshness.fetchedFrom(clone, t0);
+ log.info(`workspaces: cloned ${repo.name} into ${clone} in ${Date.now() - t0} ms`);
+ for (const cmd of repo.setup ?? []) {
+ const c = command('sh', ['-c', cmd]);
+ await exec(c.cmd, c.args, { cwd: clone, env: c.env, timeout: CLONE_TIMEOUT, maxBuffer: 20 << 20 }).catch((e) => {
+ throw new Error(`setup \`${cmd}\`: ${errText(e)}`);
+ });
+ }
+ return true;
+ });
+}
+
+export async function copyRootFiles(def: Definition, dir: string) {
+ for (const [target, source] of Object.entries(def.rootFiles)) {
+ const dest = path.join(dir, target);
+ await mkdir(path.dirname(dest), { recursive: true });
+ await copyFile(source, dest).catch((e) => log.warn(`workspaces: root file ${target}: ${errText(e)}`));
+ }
+}
+
+// ---------------------------------------------------------------- workspace
+
+/** Ensure the person's workspace exists (clone its eager repositories if missing). Idempotent; nothing waits on it. */
+export async function ensureWorkspace(person: Person): Promise<void> {
+ const def = loadDefinition();
+ const ws = workspaceDir(person);
+ await mkdir(ws, { recursive: true });
+ await copyRootFiles(def, ws);
+ const failed: string[] = [];
+ await Promise.all(
+ def.repos
+ .filter((r) => !r.unpublished && !isLazy(r))
+ .map((r) =>
+ cloneRepo(path.join(ws, r.name), r).catch((e) => {
+ failed.push(`${r.name}: ${errText(e)}`);
+ }),
+ ),
+ );
+ // Housekeeping keeps retrying missing eager repositories in the background.
+ await writeFile(path.join(ws, PREPARED_FILE), new Date().toISOString() + '\n');
+ if (failed.length) throw new Error(`workspace ${person.dir}: ${failed.join('; ')}`);
+}
+
+// One background preparation per person at a time: forks in a row must not stack clones of the same failing repository.
+const preparing = new Map<string, Promise<void>>();
+/** ensureWorkspace without waiting: for forks, and for people the gateway just added. */
+export function prepareInBackground(person: Person) {
+ if (preparing.has(person.dir)) return;
+ const run = ensureWorkspace(person)
+ .catch((e) => log.warn(`workspaces: ${errText(e)}`))
+ .finally(() => preparing.delete(person.dir));
+ preparing.set(person.dir, run);
+}
+
+export function workspacePrepared(person: Person): boolean {
+ return existsSync(path.join(workspaceDir(person), PREPARED_FILE));
+}
diff --git a/computer/src/workspaces/codex-homes.ts b/computer/src/workspaces/codex-homes.ts
index 37238d67..5e3c0369 100644
--- a/computer/src/workspaces/codex-homes.ts
+++ b/computer/src/workspaces/codex-homes.ts
@@ -1,6 +1,6 @@
// A session's Codex home goes with its fork (work 082, #129 round 2). Codex
// writes its threads' rollouts under CODEX_HOME/sessions, which grow with
-// every turn; nothing else removes them. pruneFork (index.ts) calls this
+// every turn; nothing else removes them. pruneFork (prune.ts) calls this
// once it removed a fork, the point where Calvin decides a session is done.
//
// Invariants: it removes only the home named by the session's key
diff --git a/computer/src/workspaces/fetch-schedule.ts b/computer/src/workspaces/fetch-schedule.ts
index 929bc225..2bf3ca0e 100644
--- a/computer/src/workspaces/fetch-schedule.ts
+++ b/computer/src/workspaces/fetch-schedule.ts
@@ -7,7 +7,7 @@
// window ago. A push that lands while a fetch runs therefore never counts as
// fetched, and a clone never fetched by this process is never fresh.
// - Fetches of one clone run one at a time in their own lane, apart from the
-// clone's worktree lock (workspaces/index.ts `serial`): a fork's worktree add
+// clone's worktree lock (workspaces/clones.ts `serial`): a fork's worktree add
// never waits behind a housekeeping fetch, and a fork that needs a fetch
// joins the lane and re-checks freshness when its turn comes.
// - `limit(n)` bounds how many housekeeping fetches run at once on the host;
diff --git a/computer/src/workspaces/fork.ts b/computer/src/workspaces/fork.ts
new file mode 100644
index 00000000..5ab3d876
--- /dev/null
+++ b/computer/src/workspaces/fork.ts
@@ -0,0 +1,212 @@
+// A session's fork (work 045; split out of index.ts for work 103):
+// <root>/sessions/<key>/ with AGENTS.md, .fork.json and one git worktree per
+// repository on branch sp/<key>, from origin/<default>. Making one
+// (forkSession), adding repositories to it (checkoutRepos), reading and
+// touching its record.
+//
+// Invariants:
+// - .fork.json is written last: a fork without it is incomplete, and the host
+// gives no credentials to a runner in one (host/adoption.ts).
+// - A fork never waits on a clone it was not asked for, and its fetch is
+// bounded by SP_FORK_FETCH_TIMEOUT; past it the cached ref is used.
+// - A repository that cannot be forked is left out, not fatal to the session.
+
+import { existsSync, readFileSync } from 'node:fs';
+import { realpath } from 'node:fs/promises';
+import path from 'node:path';
+import { log } from '../log.js';
+import type { CheckoutResult, Person } from '../protocol.js';
+import { isLazy, loadDefinition, type RepoDef, repoSlug } from './definition.js';
+import { repoIndex } from './repo-index.js';
+import { appendFile, mkdir, rm, touch, writeFile } from './as-runner.js';
+import {
+ cloneRepo, copyRootFiles, defaultBranch, errText, fetchedAt, fetchErrorType, fetchLane, fetchTimeout, forkDir, forkFetchFresh, forkFetchTimeout,
+ freshness, git, isClone, observe, observed, ok, prepareInBackground, safeKey, serial, workspaceDir, workspacePrepared,
+} from './clones.js';
+import { FORK_FILE } from './idle.js';
+
+export interface ForkInfo {
+ key: string;
+ owner: string;
+ createdAt: string;
+ ms: number;
+ repos: Record<string, { branch: string; from: string; base: string; fetchError?: string }>;
+}
+
+/**
+ * Create the session's fork: <root>/sessions/<key>/ with a git worktree per
+ * repository on a fresh branch from origin/<default>, fetched just before
+ * unless the clone's refs are fresh (fetch-schedule.ts).
+ * Returns the fork path (the runner's cwd). Idempotent: an existing fork is returned as is.
+ */
+export async function forkSession(person: Person, sessionKey: string): Promise<string> {
+ const fork = forkDir(person, sessionKey);
+ if (existsSync(path.join(fork, FORK_FILE))) return fork;
+ const t0 = Date.now();
+ const def = loadDefinition();
+ const ws = workspaceDir(person);
+ // Nothing here waits on a clone (work 056): the fork gets the clones that
+ // exist. Eager repositories still missing (a first session, or ones the
+ // definition just gained) are cloned in the background; the session checks
+ // out any repository it needs with checkoutRepos, which waits for that one.
+ if (!workspacePrepared(person) || def.repos.some((r) => !r.unpublished && !isLazy(r) && !isClone(path.join(ws, r.name))))
+ prepareInBackground(person);
+ const repos = def.repos.filter((r) => isClone(path.join(ws, r.name)));
+ await mkdir(fork, { recursive: true });
+ await copyRootFiles(def, fork);
+ const branch = `sp/${safeKey(sessionKey)}`;
+ // A repository that cannot be forked (a partial clone whose remote is unreachable) is left out, not fatal to the session.
+ const forked = await Promise.all(
+ repos.map((r) =>
+ forkRepo(path.join(ws, r.name), r, path.join(fork, r.name), branch).then(
+ (f) => [r.name, f] as const,
+ (e) => (log.warn(`workspaces: ${r.name} left out of ${sessionKey}: ${errText(e)}`), undefined),
+ ),
+ ),
+ );
+ const info: ForkInfo = {
+ key: sessionKey,
+ owner: person.dir,
+ createdAt: new Date().toISOString(),
+ ms: Date.now() - t0,
+ repos: Object.fromEntries(forked.filter((f) => f !== undefined)),
+ };
+ const index = repoIndex(def.repos, new Set(Object.keys(info.repos)));
+ if (index) await appendFile(path.join(fork, 'AGENTS.md'), `\n${index}`);
+ await writeFile(path.join(fork, FORK_FILE), JSON.stringify(info, null, 2) + '\n');
+ const stale = Object.entries(info.repos).filter(([, r]) => r.fetchError);
+ log.info(`workspaces: forked ${Object.keys(info.repos).length} repos for ${sessionKey} (${person.dir}) in ${info.ms} ms`);
+ for (const [name, r] of stale) log.warn(`workspaces: ${name} forked from cached ${r.from} (${r.base.slice(0, 8)}); fetch failed: ${r.fetchError}`);
+ return fork;
+}
+
+async function forkRepo(clone: string, repo: RepoDef, dest: string, branch: string) {
+ const queued = Date.now();
+ const b = await defaultBranch(clone, repo);
+ const fetch = await forkFetch(clone, b);
+ const fetched = Date.now();
+ return serial(clone, async () => {
+ const locked = Date.now();
+ if (!existsSync(dest)) {
+ // A worktree whose directory the session deleted is still registered; forget it so it can be added again.
+ await git(clone, ['worktree', 'prune']);
+ const exists = await ok(git(clone, ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`]));
+ // --no-track: the session pushes its own branch (`git push -u origin HEAD`), not origin/<default>.
+ // On a partial clone this downloads the checkout's file contents, so it is bounded like a fetch.
+ await git(clone, ['worktree', 'add', '--quiet', ...(exists ? [dest, branch] : ['--no-track', '-b', branch, dest, `origin/${b}`])], fetchTimeout()).catch(
+ async (e) => {
+ await rm(dest);
+ await git(clone, ['worktree', 'prune']).catch(() => {});
+ throw e;
+ },
+ );
+ } else if (!(await isWorktreeOf(dest, clone))) {
+ throw new Error(`./${path.basename(dest)} exists but is not a worktree of this workspace's ${repo.name}; move it away and check out again`);
+ }
+ const base = await git(dest, ['rev-parse', 'HEAD']);
+ const end = Date.now();
+ observe(() => observed().repoForked?.({ repo: repo.name, ms: end - queued, fetchMs: fetched - queued, worktreeMs: end - locked,
+ lockWaitMs: locked - fetched, fetchSkipped: fetch.skipped, fetchError: fetch.kind }));
+ return { branch, from: `origin/${b}`, base, ...(fetch.error && { fetchError: fetch.error }) };
+ });
+}
+
+/**
+ * Make origin/<b> current for a fork: nothing if the clone is fresh, else a
+ * fetch of that branch alone (no prune: as fast as a fetch gets) in the
+ * clone's fetch lane. Waiting in the lane and the fetch together are bounded
+ * by SP_FORK_FETCH_TIMEOUT; past it the fork uses the cached ref.
+ */
+async function forkFetch(clone: string, b: string): Promise<{ skipped: boolean; error?: string; kind?: string }> {
+ if (freshness.fresh(clone, forkFetchFresh())) return { skipped: true };
+ const timeout = forkFetchTimeout();
+ const run = fetchLane(clone, async () => {
+ // A fetch that finished while this one waited (housekeeping's, another fork's) may be enough.
+ if (freshness.fresh(clone, forkFetchFresh())) return { skipped: true };
+ const started = Date.now();
+ await git(clone, ['fetch', '--quiet', '--no-tags', 'origin', b], timeout);
+ fetchedAt.set(clone, new Date().toISOString());
+ freshness.fetchedFrom(clone, started);
+ return { skipped: false };
+ });
+ let timer: NodeJS.Timeout | undefined;
+ const late = new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(Object.assign(new Error('timed out waiting for a fetch'), { killed: true })), timeout);
+ });
+ try {
+ return await Promise.race([run, late]);
+ } catch (e) {
+ return { skipped: false, error: errText(e), kind: fetchErrorType(e) };
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+async function isWorktreeOf(dir: string, clone: string) {
+ const common = await git(dir, ['rev-parse', '--git-common-dir']).catch(() => '');
+ if (!common) return false;
+ const real = (p: string) => realpath(p).catch(() => p);
+ return (await real(path.resolve(dir, common))) === (await real(path.join(clone, '.git')));
+}
+
+/**
+ * Check repositories out into an existing fork (the session's `checkout_repo`
+ * tool): clone each if missing (waiting for a background clone already
+ * running), then a worktree on the fork's branch. `wanted` holds definition
+ * names or `owner/name`. Each repository succeeds or fails on its own; the
+ * fork record gains the ones checked out.
+ */
+export async function checkoutRepos(forkPath: string, wanted: string[]): Promise<CheckoutResult[]> {
+ const info = forkInfo(forkPath);
+ if (!info) throw new Error(`not a session fork: ${forkPath}`);
+ const person = { dir: info.owner } as Person;
+ if (forkDir(person, info.key) !== path.resolve(forkPath)) throw new Error(`fork ${forkPath} is not where its record says`);
+ const def = loadDefinition();
+ const ws = workspaceDir(person);
+ const branch = `sp/${safeKey(info.key)}`;
+ const results = await Promise.all(
+ [...new Set(wanted.map((w) => w.trim()).filter(Boolean))].map(async (want): Promise<CheckoutResult> => {
+ const repo = findRepo(def.repos, want);
+ const fail = (error: string) => ({ name: repo?.name ?? want, dir: repo?.name ?? want, branch, from: '', base: '', error });
+ if (!repo) return fail(`no repository ${want} in this workspace; the list is in AGENTS.md`);
+ if (repo.unpublished) return fail(`${repo.name} is not published yet`);
+ const clone = path.join(ws, repo.name);
+ try {
+ const t0 = Date.now();
+ if (await cloneRepo(clone, repo)) log.info(`workspaces: ${repo.name} cloned on demand for ${info.key} in ${Date.now() - t0} ms`);
+ const r = await forkRepo(clone, repo, path.join(forkPath, repo.name), branch);
+ return { name: repo.name, dir: repo.name, ...r };
+ } catch (e) {
+ return fail(errText(e));
+ }
+ }),
+ );
+ const done = results.filter((r) => !r.error);
+ // Read-modify-write of the record, serialized: a session may check out in parallel tool calls.
+ if (done.length)
+ await serial(forkPath, async () => {
+ const fresh = forkInfo(forkPath) ?? info;
+ for (const { name, branch: b, from, base, fetchError } of done) fresh.repos[name] = { branch: b, from, base, ...(fetchError && { fetchError }) };
+ await writeFile(path.join(forkPath, FORK_FILE), JSON.stringify(fresh, null, 2) + '\n');
+ });
+ return results;
+}
+
+function findRepo(repos: RepoDef[], want: string): RepoDef | undefined {
+ const w = want.replace(/\.git$/, '').toLowerCase();
+ return repos.find((r) => r.name.toLowerCase() === w) ?? repos.find((r) => repoSlug(r.remote).toLowerCase() === w);
+}
+
+/** Read a fork's record (bases, fetch failures), if it is complete. */
+export function forkInfo(forkPath: string): ForkInfo | undefined {
+ try {
+ return JSON.parse(readFileSync(path.join(forkPath, FORK_FILE), 'utf8'));
+ } catch {
+ return undefined;
+ }
+}
+
+/** Mark a fork as used now; pruning counts retention from the latest use. The host calls this per delivery. */
+export async function touchFork(forkPath: string) {
+ await touch(path.join(forkPath, FORK_FILE)).catch(() => {});
+}
diff --git a/computer/src/workspaces/housekeep.ts b/computer/src/workspaces/housekeep.ts
new file mode 100644
index 00000000..4b1e3fbc
--- /dev/null
+++ b/computer/src/workspaces/housekeep.ts
@@ -0,0 +1,188 @@
+// Housekeeping of a person's workspace (work 045; split out of index.ts for
+// work 103): the periodic pass (clone what is missing, fetch and fast-forward
+// the rest, prune idle forks and their build directories), and the fetch after
+// a push to the branch forks start from.
+//
+// Invariants:
+// - At most HOUSEKEEPING_FETCHES housekeeping fetches run at once on the host,
+// each in its clone's fetch lane; the fast-forward runs under the worktree lock.
+// - One pass per person at a time.
+// - A clone's checkout is only ever fast-forwarded: never when it is on another
+// branch, has local changes or has diverged.
+
+import { readdir } from 'node:fs/promises';
+import path from 'node:path';
+import { log } from '../log.js';
+import type { Person, WorkspaceStatus } from '../protocol.js';
+import { isLazy, loadDefinition, type RepoDef, repoSlug, workspacesEnabled } from './definition.js';
+import { mkdir } from './as-runner.js';
+import {
+ cloneRepo, copyRootFiles, defaultBranch, errText, type FetchTrigger, fetchedAt, fetchErrorType, fetchInterval, fetchLane, fetchTimeout, freshness, git,
+ HOUSEKEEPING_FETCHES, isClone, observe, observed, ok, personRoot, serial, workspaceDir,
+} from './clones.js';
+import { limit } from './fetch-schedule.js';
+import { pruneIdleArtifacts } from './idle.js';
+import { pruneForks } from './prune.js';
+
+type RepoStatus = WorkspaceStatus['repos'][number];
+
+const housekeepingFetch = limit(HOUSEKEEPING_FETCHES);
+
+/** Fast-forward the checkout; a string says why not, `true` that it moved. */
+async function fastForward(clone: string, b: string): Promise<string | boolean | undefined> {
+ const current = await git(clone, ['symbolic-ref', '--quiet', '--short', 'HEAD']).catch(() => '');
+ if (current !== b) return `checkout is on ${current || 'a detached HEAD'}, not ${b}; not fast-forwarded`;
+ if (await git(clone, ['status', '--porcelain'])) return 'checkout has local changes; not fast-forwarded';
+ const [head, remote] = [await git(clone, ['rev-parse', 'HEAD']), await git(clone, ['rev-parse', `origin/${b}`])];
+ if (head === remote) return undefined;
+ if (!(await ok(git(clone, ['merge-base', '--is-ancestor', head, remote])))) return `${b} has diverged from origin/${b}; not fast-forwarded`;
+ await git(clone, ['merge', '--ff-only', '--quiet', `origin/${b}`], fetchTimeout()); // downloads contents on a partial clone
+ return true;
+}
+
+/**
+ * Clone if missing (eager only), else fetch --prune (in the clone's fetch
+ * lane, at most HOUSEKEEPING_FETCHES at once) and fast-forward the clone's
+ * default branch checkout (under the worktree lock).
+ */
+async function syncRepo(person: Person, repo: RepoDef, trigger: FetchTrigger): Promise<RepoStatus> {
+ if (repo.unpublished) return { name: repo.name, problem: 'unpublished; not cloned' };
+ const clone = path.join(workspaceDir(person), repo.name);
+ // Lazy and not checked out by any session yet: nothing to keep fetched. Once cloned, it is kept warm like the rest.
+ if (isLazy(repo) && !isClone(clone)) return { name: repo.name };
+ try {
+ await cloneRepo(clone, repo);
+ const b = await defaultBranch(clone, repo);
+ const problems: string[] = [];
+ let fetchError: string | undefined;
+ let ms = 0;
+ await housekeepingFetch(() =>
+ fetchLane(clone, async () => {
+ const started = Date.now();
+ await git(clone, ['fetch', '--quiet', '--prune', 'origin'], fetchTimeout()).then(
+ () => (fetchedAt.set(clone, new Date().toISOString()), freshness.fetchedFrom(clone, started)),
+ (e) => (problems.push(`fetch: ${errText(e)}`), (fetchError = fetchErrorType(e))),
+ );
+ ms = Date.now() - started;
+ }), trigger === 'pushed');
+ return await serial(clone, async () => {
+ const ff = await fastForward(clone, b).catch((e) => `fast-forward: ${errText(e)}`);
+ if (typeof ff === 'string') problems.push(ff);
+ observe(() => observed().repoFetched?.({ repo: repo.name, ms, fastForwarded: ff === true, trigger, fetchError }));
+ const head = await git(clone, ['rev-parse', '--short', `origin/${b}`]).catch(() => undefined);
+ return { name: repo.name, fetchedAt: fetchedAt.get(clone), head, ...(problems.length && { problem: problems.join('; ') }) };
+ });
+ } catch (e) {
+ return { name: repo.name, fetchedAt: fetchedAt.get(clone), problem: errText(e) };
+ }
+}
+
+/**
+ * One housekeeping pass for a person: root files, clone new repositories, fetch and
+ * fast-forward the rest, report repositories removed from the definition, prune idle forks
+ * and the build and dependency directories of forks idle a day, except forks in `active` (with a live runner).
+ */
+export async function housekeep(person: Person, active: Set<string> = new Set()): Promise<WorkspaceStatus> {
+ const def = loadDefinition();
+ const ws = workspaceDir(person);
+ await mkdir(ws, { recursive: true });
+ await copyRootFiles(def, ws);
+ const repos = await Promise.all(def.repos.map((r) => syncRepo(person, r, 'periodic')));
+ const defined = new Set(def.repos.map((r) => r.name));
+ for (const name of (await readdir(ws)).sort()) {
+ if (!defined.has(name) && isClone(path.join(ws, name))) repos.push({ name, problem: 'removed from the definition; clone kept' });
+ }
+ repos.push(...(await pruneForks(person)));
+ await pruneIdleArtifacts(path.join(personRoot(person), 'sessions'), active);
+ const status = { person: person.dir, repos };
+ lastStatus.set(person.dir, status);
+ return status;
+}
+
+/** Age of the least recently fetched clone this process fetched, in seconds. */
+export function oldestFetchAgeS(now = Date.now()): number | undefined {
+ const times = [...fetchedAt.values()].map(Date.parse);
+ return times.length ? Math.round((now - Math.min(...times)) / 1000) : undefined;
+}
+
+const lastStatus = new Map<string, WorkspaceStatus>();
+const running = new Map<string, Promise<void>>();
+let reporter: ((s: WorkspaceStatus) => void) | undefined;
+let activeForks: () => Set<string> = () => new Set();
+
+function cycle(person: Person) {
+ const busy = running.get(person.dir);
+ if (busy) return busy;
+ const run = housekeep(person, activeForks())
+ .then((s) => reporter?.(s))
+ .catch((e) => log.warn(`workspaces: housekeeping ${person.dir}: ${errText(e)}`))
+ .finally(() => running.delete(person.dir));
+ running.set(person.dir, run);
+ return run;
+}
+
+/**
+ * Start periodic housekeeping for these people; calls `report` with each workspace's
+ * status. `active` names the forks with a live runner, never pruned of build and dependency directories.
+ */
+export function startHousekeeping(
+ people: () => Person[],
+ report: (s: WorkspaceStatus) => void,
+ active: () => Set<string> = () => new Set(),
+): { now(): void; stop(): void } {
+ reporter = report;
+ activeForks = active;
+ const tick = () => {
+ if (workspacesEnabled()) for (const p of people()) void cycle(p);
+ };
+ tick();
+ const timer = setInterval(tick, fetchInterval());
+ return {
+ /** A pass right away (the definition changed); people already in a pass are left to it. */
+ now: tick,
+ stop() {
+ clearInterval(timer);
+ if (reporter === report) reporter = undefined;
+ },
+ };
+}
+
+/**
+ * A push to `ref` of one repository (by remote name, e.g. `acme/widgets`):
+ * every clone of it that forks from that branch stops being fresh now. Returns
+ * those clones by person. Pushes to other branches (sessions' own `sp/*`) touch nothing.
+ */
+export async function markPushed(repo: string, people: Person[], ref?: string): Promise<{ person: Person; repo: RepoDef }[]> {
+ const want = repo.replace(/\.git$/, '').toLowerCase();
+ const matches = loadDefinition().repos.filter((r) => !r.unpublished && (repoSlug(r.remote).toLowerCase() === want || r.name === repo));
+ const hit: { person: Person; repo: RepoDef }[] = [];
+ for (const person of people)
+ for (const r of matches) {
+ const clone = path.join(workspaceDir(person), r.name);
+ if (!isClone(clone)) continue;
+ // An unknown default branch counts as a match: fetching once too often is cheaper than a stale fork.
+ const b = ref && (await defaultBranch(clone, r).catch(() => undefined));
+ if (b && ref !== `refs/heads/${b}`) continue;
+ freshness.pushedNow(clone);
+ hit.push({ person, repo: r });
+ }
+ return hit;
+}
+
+/** Fetch one repository in every workspace that has it, after a push to `ref` (any branch if omitted). Returns the clones fetched. */
+export async function fetchRepo(repo: string, people: Person[], ref?: string): Promise<number> {
+ const hit = await markPushed(repo, people, ref);
+ await Promise.all(
+ people.map(async (p) => {
+ const present = hit.filter((h) => h.person === p).map((h) => h.repo);
+ if (!present.length) return;
+ const updated = await Promise.all(present.map((r) => syncRepo(p, r, 'pushed')));
+ const prev = lastStatus.get(p.dir);
+ if (!prev) return;
+ const status = { ...prev, repos: prev.repos.map((s) => updated.find((u) => u.name === s.name) ?? s) };
+ lastStatus.set(p.dir, status);
+ reporter?.(status);
+ }),
+ );
+ return hit.length;
+}
diff --git a/computer/src/workspaces/idle.ts b/computer/src/workspaces/idle.ts
index ea7d829a..e83aa1e7 100644
--- a/computer/src/workspaces/idle.ts
+++ b/computer/src/workspaces/idle.ts
@@ -1,7 +1,7 @@
// When a session fork was last used, and pruning the build and dependency
// directories of idle ones (work 071): a Node worktree's node_modules is about
// 1 GiB, the bulk of a fork on disk, and an install or build brings each back.
-// index.ts prunes whole forks.
+// prune.ts prunes whole forks.
import { execFile } from 'node:child_process';
import { existsSync } from 'node:fs';
@@ -28,7 +28,7 @@ const ARTIFACTS = new Set(['node_modules', '.next', '.nuxt', '.svelte-kit', '.tu
const isArtifact = (dir: string, name: string) =>
ARTIFACTS.has(name) || (name === 'target' && existsSync(path.join(dir, 'Cargo.toml')));
-// As the runner user, like index.ts: the host's own user fails git's ownership check on these repos.
+// As the runner user, like clones.ts: the host's own user fails git's ownership check on these repos.
const git = async (cwd: string, args: string[]) => {
const c = command('git', args, { GIT_TERMINAL_PROMPT: '0' });
return (await exec(c.cmd, c.args, { cwd, env: c.env })).stdout.trim();
diff --git a/computer/src/workspaces/index.ts b/computer/src/workspaces/index.ts
index b2885cf3..63763b6d 100644
--- a/computer/src/workspaces/index.ts
+++ b/computer/src/workspaces/index.ts
@@ -20,572 +20,17 @@
// remotes. Worktree operations on one clone are serialized, and so are its
// fetches, in a separate lane (fetch-schedule.ts); at most HOUSEKEEPING_FETCHES
// housekeeping fetches run at once on the host.
-
-import { execFile } from 'node:child_process';
-import { existsSync, readFileSync } from 'node:fs';
-import { readdir, realpath, stat } from 'node:fs/promises';
-import path from 'node:path';
-import { promisify } from 'node:util';
-import { log } from '../log.js';
-import { type CheckoutResult, HOST_DATA, type Person, type WorkspaceStatus } from '../protocol.js';
-import { type Definition, isLazy, loadDefinition, type RepoDef, repoSlug, workspacesEnabled } from './definition.js';
-import { repoIndex } from './repo-index.js';
-import { appendFile, command, copyFile, mkdir, rename, rm, touch, writeFile } from './as-runner.js';
-import { Freshness, keyedQueue, limit } from './fetch-schedule.js';
-import { FORK_FILE, lastUsed, pruneIdleArtifacts, worktrees } from './idle.js';
-import { removeCodexHome } from './codex-homes.js';
+//
+// Split by concept (work 103): clones.ts (layout, git, locks, cloning),
+// fork.ts (a session's fork), housekeep.ts (the periodic pass and fetches
+// after a push), prune.ts (idle forks). This file is what others import.
export * from './definition.js';
export { configureAsRunner, mkdir as mkdirAsRunner } from './as-runner.js';
-
-const exec = promisify(execFile);
-
-type RepoStatus = WorkspaceStatus['repos'][number];
-
-
-// ---------------------------------------------------------------- config
-
-/** Durations: `300` (seconds), `500ms`, `30s`, `5m`, `2h`. */
-function duration(value: string | undefined, fallback: string): number {
- const m = (value || fallback).trim().match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)?$/);
- if (!m) return duration(fallback, fallback);
- return Number(m[1]) * { ms: 1, s: 1e3, m: 60e3, h: 3600e3, d: 86400e3 }[(m[2] ?? 's') as 'ms'];
-}
-const fetchInterval = () => duration(process.env.SP_FETCH_INTERVAL, '5m');
-const fetchTimeout = () => duration(process.env.SP_FETCH_TIMEOUT, '2m');
-const forkFetchTimeout = () => duration(process.env.SP_FORK_FETCH_TIMEOUT, '5s');
-/** A fork skips its fetch of a clone fetched this recently and not pushed to since (fetch-schedule.ts). */
-const forkFetchFresh = () => duration(process.env.SP_FORK_FETCH_FRESH, '60s');
-const HOUSEKEEPING_FETCHES = 4;
-const retention = () => duration(process.env.SP_FORK_RETENTION_DAYS ? `${process.env.SP_FORK_RETENTION_DAYS}d` : undefined, '14d');
-const CLONE_TIMEOUT = 30 * 60e3;
-
-// ---------------------------------------------------------------- layout
-
-/** A session key as a directory and branch name: `C0B:1791.82` → `C0B-1791-82`. */
-export function safeKey(key: string) {
- return key.replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-|-$/g, '');
-}
-
-/** Root of a person's area on the host: <SP_DATA>/people/<dir>. */
-export function personRoot(person: Person): string {
- if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(person.dir)) throw new Error(`bad person dir: ${person.dir}`);
- return path.join(HOST_DATA, 'people', person.dir);
-}
-export const workspaceDir = (person: Person) => path.join(personRoot(person), 'ws');
-export const forkDir = (person: Person, sessionKey: string) => path.join(personRoot(person), 'sessions', safeKey(sessionKey));
-
-// ---------------------------------------------------------------- git
-
-async function git(cwd: string, args: string[], timeout = 0) {
- const c = command('git', args, { GIT_TERMINAL_PROMPT: '0' });
- return (await exec(c.cmd, c.args, { cwd, timeout, env: c.env, maxBuffer: 20 << 20 })).stdout.trim();
-}
-const ok = (p: Promise<unknown>) => p.then(() => true, () => false);
-function errText(e: any): string {
- if (e?.killed) return 'timed out';
- const lines = String(e?.stderr || e?.message || e).trim().split('\n').filter(Boolean);
- return lines.find((l) => /^(fatal|error):/.test(l)) ?? lines.pop() ?? 'failed';
-}
-const isClone = (dir: string) => existsSync(path.join(dir, '.git'));
-const fetchErrorType = (e: unknown) => ((e as { killed?: boolean })?.killed ? 'timeout' : 'git_fetch');
-
-/** Timings the host agent reports as telemetry (work 054); calls never affect the work. */
-export interface WorkspaceObserver {
- repoForked?(t: { repo: string; ms: number; fetchMs: number; worktreeMs: number; lockWaitMs: number; fetchSkipped: boolean; fetchError?: string }): void;
- repoFetched?(t: { repo: string; ms: number; fastForwarded: boolean; trigger: FetchTrigger; fetchError?: string }): void;
-}
-/** Why housekeeping fetched a clone: its periodic pass, or a push to the branch it forks from. */
-export type FetchTrigger = 'periodic' | 'pushed';
-let observer: WorkspaceObserver = {};
-export const observeWorkspaces = (o: WorkspaceObserver) => void (observer = o);
-const observe = (f: () => void) => {
- try {
- f();
- } catch {}
-};
-
-// One queue per clone: no concurrent clone, worktree add, prune or fast-forward on the same repository.
-const serial = keyedQueue();
-// Fetches have their own lane per clone, so worktree operations never wait behind one.
-const fetchLane = keyedQueue();
-const freshness = new Freshness();
-const housekeepingFetch = limit(HOUSEKEEPING_FETCHES);
-
-const branches = new Map<string, string>();
-async function defaultBranch(clone: string, repo: RepoDef) {
- if (repo.branch) return repo.branch;
- const cached = branches.get(clone);
- if (cached) return cached;
- const head = () => git(clone, ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD']);
- const ref = await head().catch(async () => (await git(clone, ['remote', 'set-head', 'origin', '--auto'], fetchTimeout()), head()));
- const b = ref.replace(/^origin\//, '');
- branches.set(clone, b);
- return b;
-}
-
-const fetchedAt = new Map<string, string>();
-const PREPARED_FILE = '.workspace-prepared';
-
-async function cloneRepo(clone: string, repo: RepoDef): Promise<boolean> {
- return serial(clone, async () => {
- if (isClone(clone)) return false;
- const tmp = `${clone}.cloning`;
- await rm(tmp);
- await mkdir(path.dirname(clone), { recursive: true });
- const t0 = Date.now();
- // A lazy repository is cloned while a session waits: blobs come on demand (checkout fetches HEAD's).
- const partial = isLazy(repo) ? ['--filter=blob:none'] : [];
- await git(path.dirname(clone), ['clone', '--quiet', ...partial, ...(repo.branch ? ['-b', repo.branch] : []), repo.remote, tmp], CLONE_TIMEOUT);
- await rename(tmp, clone);
- fetchedAt.set(clone, new Date().toISOString());
- freshness.fetchedFrom(clone, t0);
- log.info(`workspaces: cloned ${repo.name} into ${clone} in ${Date.now() - t0} ms`);
- for (const cmd of repo.setup ?? []) {
- const c = command('sh', ['-c', cmd]);
- await exec(c.cmd, c.args, { cwd: clone, env: c.env, timeout: CLONE_TIMEOUT, maxBuffer: 20 << 20 }).catch((e) => {
- throw new Error(`setup \`${cmd}\`: ${errText(e)}`);
- });
- }
- return true;
- });
-}
-
-async function copyRootFiles(def: Definition, dir: string) {
- for (const [target, source] of Object.entries(def.rootFiles)) {
- const dest = path.join(dir, target);
- await mkdir(path.dirname(dest), { recursive: true });
- await copyFile(source, dest).catch((e) => log.warn(`workspaces: root file ${target}: ${errText(e)}`));
- }
-}
-
-// ---------------------------------------------------------------- workspace
-
-/** Ensure the person's workspace exists (clone its eager repositories if missing). Idempotent; nothing waits on it. */
-export async function ensureWorkspace(person: Person): Promise<void> {
- const def = loadDefinition();
- const ws = workspaceDir(person);
- await mkdir(ws, { recursive: true });
- await copyRootFiles(def, ws);
- const failed: string[] = [];
- await Promise.all(
- def.repos
- .filter((r) => !r.unpublished && !isLazy(r))
- .map((r) =>
- cloneRepo(path.join(ws, r.name), r).catch((e) => {
- failed.push(`${r.name}: ${errText(e)}`);
- }),
- ),
- );
- // Housekeeping keeps retrying missing eager repositories in the background.
- await writeFile(path.join(ws, PREPARED_FILE), new Date().toISOString() + '\n');
- if (failed.length) throw new Error(`workspace ${person.dir}: ${failed.join('; ')}`);
-}
-
-// One background preparation per person at a time: forks in a row must not stack clones of the same failing repository.
-const preparing = new Map<string, Promise<void>>();
-/** ensureWorkspace without waiting: for forks, and for people the gateway just added. */
-export function prepareInBackground(person: Person) {
- if (preparing.has(person.dir)) return;
- const run = ensureWorkspace(person)
- .catch((e) => log.warn(`workspaces: ${errText(e)}`))
- .finally(() => preparing.delete(person.dir));
- preparing.set(person.dir, run);
-}
-
-export function workspacePrepared(person: Person): boolean {
- return existsSync(path.join(workspaceDir(person), PREPARED_FILE));
-}
-
-// ---------------------------------------------------------------- forks
-
-export interface ForkInfo {
- key: string;
- owner: string;
- createdAt: string;
- ms: number;
- repos: Record<string, { branch: string; from: string; base: string; fetchError?: string }>;
-}
-
-/**
- * Create the session's fork: <root>/sessions/<key>/ with a git worktree per
- * repository on a fresh branch from origin/<default>, fetched just before
- * unless the clone's refs are fresh (fetch-schedule.ts).
- * Returns the fork path (the runner's cwd). Idempotent: an existing fork is returned as is.
- */
-export async function forkSession(person: Person, sessionKey: string): Promise<string> {
- const fork = forkDir(person, sessionKey);
- if (existsSync(path.join(fork, FORK_FILE))) return fork;
- const t0 = Date.now();
- const def = loadDefinition();
- const ws = workspaceDir(person);
- // Nothing here waits on a clone (work 056): the fork gets the clones that
- // exist. Eager repositories still missing (a first session, or ones the
- // definition just gained) are cloned in the background; the session checks
- // out any repository it needs with checkoutRepos, which waits for that one.
- if (!workspacePrepared(person) || def.repos.some((r) => !r.unpublished && !isLazy(r) && !isClone(path.join(ws, r.name))))
- prepareInBackground(person);
- const repos = def.repos.filter((r) => isClone(path.join(ws, r.name)));
- await mkdir(fork, { recursive: true });
- await copyRootFiles(def, fork);
- const branch = `sp/${safeKey(sessionKey)}`;
- // A repository that cannot be forked (a partial clone whose remote is unreachable) is left out, not fatal to the session.
- const forked = await Promise.all(
- repos.map((r) =>
- forkRepo(path.join(ws, r.name), r, path.join(fork, r.name), branch).then(
- (f) => [r.name, f] as const,
- (e) => (log.warn(`workspaces: ${r.name} left out of ${sessionKey}: ${errText(e)}`), undefined),
- ),
- ),
- );
- const info: ForkInfo = {
- key: sessionKey,
- owner: person.dir,
- createdAt: new Date().toISOString(),
- ms: Date.now() - t0,
- repos: Object.fromEntries(forked.filter((f) => f !== undefined)),
- };
- const index = repoIndex(def.repos, new Set(Object.keys(info.repos)));
- if (index) await appendFile(path.join(fork, 'AGENTS.md'), `\n${index}`);
- await writeFile(path.join(fork, FORK_FILE), JSON.stringify(info, null, 2) + '\n');
- const stale = Object.entries(info.repos).filter(([, r]) => r.fetchError);
- log.info(`workspaces: forked ${Object.keys(info.repos).length} repos for ${sessionKey} (${person.dir}) in ${info.ms} ms`);
- for (const [name, r] of stale) log.warn(`workspaces: ${name} forked from cached ${r.from} (${r.base.slice(0, 8)}); fetch failed: ${r.fetchError}`);
- return fork;
-}
-
-async function forkRepo(clone: string, repo: RepoDef, dest: string, branch: string) {
- const queued = Date.now();
- const b = await defaultBranch(clone, repo);
- const fetch = await forkFetch(clone, b);
- const fetched = Date.now();
- return serial(clone, async () => {
- const locked = Date.now();
- if (!existsSync(dest)) {
- // A worktree whose directory the session deleted is still registered; forget it so it can be added again.
- await git(clone, ['worktree', 'prune']);
- const exists = await ok(git(clone, ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`]));
- // --no-track: the session pushes its own branch (`git push -u origin HEAD`), not origin/<default>.
- // On a partial clone this downloads the checkout's file contents, so it is bounded like a fetch.
- await git(clone, ['worktree', 'add', '--quiet', ...(exists ? [dest, branch] : ['--no-track', '-b', branch, dest, `origin/${b}`])], fetchTimeout()).catch(
- async (e) => {
- await rm(dest);
- await git(clone, ['worktree', 'prune']).catch(() => {});
- throw e;
- },
- );
- } else if (!(await isWorktreeOf(dest, clone))) {
- throw new Error(`./${path.basename(dest)} exists but is not a worktree of this workspace's ${repo.name}; move it away and check out again`);
- }
- const base = await git(dest, ['rev-parse', 'HEAD']);
- const end = Date.now();
- observe(() => observer.repoForked?.({ repo: repo.name, ms: end - queued, fetchMs: fetched - queued, worktreeMs: end - locked,
- lockWaitMs: locked - fetched, fetchSkipped: fetch.skipped, fetchError: fetch.kind }));
- return { branch, from: `origin/${b}`, base, ...(fetch.error && { fetchError: fetch.error }) };
- });
-}
-
-/**
- * Make origin/<b> current for a fork: nothing if the clone is fresh, else a
- * fetch of that branch alone (no prune: as fast as a fetch gets) in the
- * clone's fetch lane. Waiting in the lane and the fetch together are bounded
- * by SP_FORK_FETCH_TIMEOUT; past it the fork uses the cached ref.
- */
-async function forkFetch(clone: string, b: string): Promise<{ skipped: boolean; error?: string; kind?: string }> {
- if (freshness.fresh(clone, forkFetchFresh())) return { skipped: true };
- const timeout = forkFetchTimeout();
- const run = fetchLane(clone, async () => {
- // A fetch that finished while this one waited (housekeeping's, another fork's) may be enough.
- if (freshness.fresh(clone, forkFetchFresh())) return { skipped: true };
- const started = Date.now();
- await git(clone, ['fetch', '--quiet', '--no-tags', 'origin', b], timeout);
- fetchedAt.set(clone, new Date().toISOString());
- freshness.fetchedFrom(clone, started);
- return { skipped: false };
- });
- let timer: NodeJS.Timeout | undefined;
- const late = new Promise<never>((_, reject) => {
- timer = setTimeout(() => reject(Object.assign(new Error('timed out waiting for a fetch'), { killed: true })), timeout);
- });
- try {
- return await Promise.race([run, late]);
- } catch (e) {
- return { skipped: false, error: errText(e), kind: fetchErrorType(e) };
- } finally {
- clearTimeout(timer);
- }
-}
-
-async function isWorktreeOf(dir: string, clone: string) {
- const common = await git(dir, ['rev-parse', '--git-common-dir']).catch(() => '');
- if (!common) return false;
- const real = (p: string) => realpath(p).catch(() => p);
- return (await real(path.resolve(dir, common))) === (await real(path.join(clone, '.git')));
-}
-
-/**
- * Check repositories out into an existing fork (the session's `checkout_repo`
- * tool): clone each if missing (waiting for a background clone already
- * running), then a worktree on the fork's branch. `wanted` holds definition
- * names or `owner/name`. Each repository succeeds or fails on its own; the
- * fork record gains the ones checked out.
- */
-export async function checkoutRepos(forkPath: string, wanted: string[]): Promise<CheckoutResult[]> {
- const info = forkInfo(forkPath);
- if (!info) throw new Error(`not a session fork: ${forkPath}`);
- const person = { dir: info.owner } as Person;
- if (forkDir(person, info.key) !== path.resolve(forkPath)) throw new Error(`fork ${forkPath} is not where its record says`);
- const def = loadDefinition();
- const ws = workspaceDir(person);
- const branch = `sp/${safeKey(info.key)}`;
- const results = await Promise.all(
- [...new Set(wanted.map((w) => w.trim()).filter(Boolean))].map(async (want): Promise<CheckoutResult> => {
- const repo = findRepo(def.repos, want);
- const fail = (error: string) => ({ name: repo?.name ?? want, dir: repo?.name ?? want, branch, from: '', base: '', error });
- if (!repo) return fail(`no repository ${want} in this workspace; the list is in AGENTS.md`);
- if (repo.unpublished) return fail(`${repo.name} is not published yet`);
- const clone = path.join(ws, repo.name);
- try {
- const t0 = Date.now();
- if (await cloneRepo(clone, repo)) log.info(`workspaces: ${repo.name} cloned on demand for ${info.key} in ${Date.now() - t0} ms`);
- const r = await forkRepo(clone, repo, path.join(forkPath, repo.name), branch);
- return { name: repo.name, dir: repo.name, ...r };
- } catch (e) {
- return fail(errText(e));
- }
- }),
- );
- const done = results.filter((r) => !r.error);
- // Read-modify-write of the record, serialized: a session may check out in parallel tool calls.
- if (done.length)
- await serial(forkPath, async () => {
- const fresh = forkInfo(forkPath) ?? info;
- for (const { name, branch: b, from, base, fetchError } of done) fresh.repos[name] = { branch: b, from, base, ...(fetchError && { fetchError }) };
- await writeFile(path.join(forkPath, FORK_FILE), JSON.stringify(fresh, null, 2) + '\n');
- });
- return results;
-}
-
-function findRepo(repos: RepoDef[], want: string): RepoDef | undefined {
- const w = want.replace(/\.git$/, '').toLowerCase();
- return repos.find((r) => r.name.toLowerCase() === w) ?? repos.find((r) => repoSlug(r.remote).toLowerCase() === w);
-}
-
-/** Read a fork's record (bases, fetch failures), if it is complete. */
-export function forkInfo(forkPath: string): ForkInfo | undefined {
- try {
- return JSON.parse(readFileSync(path.join(forkPath, FORK_FILE), 'utf8'));
- } catch {
- return undefined;
- }
-}
-
-/** Mark a fork as used now; pruning counts retention from the latest use. The host calls this per delivery. */
-export async function touchFork(forkPath: string) {
- await touch(path.join(forkPath, FORK_FILE)).catch(() => {});
-}
-
-/** Remove a fork unless a worktree has uncommitted changes or commits on no remote. Returns why it was kept. */
-export async function pruneFork(forkPath: string): Promise<string | undefined> {
- const wts = await worktrees(forkPath);
- const reasons: string[] = [];
- for (const wt of wts) {
- const name = path.basename(wt);
- // --no-optional-locks: no index refresh, whose new mtime would make the fork look used (lastUsed).
- const dirty = await git(wt, ['--no-optional-locks', 'status', '--porcelain']).catch((e) => `unreadable: ${errText(e)}`);
- if (dirty) {
- reasons.push(`${name} has uncommitted changes`);
- continue;
- }
- const n = Number(await git(wt, ['rev-list', '--count', 'HEAD', '--not', '--remotes']).catch(() => '-1'));
- if (n) reasons.push(n > 0 ? `${name} has ${n} unpushed commit${n > 1 ? 's' : ''}` : `${name}: cannot count unpushed commits`);
- }
- if (reasons.length) return reasons.join(', ');
- const key = forkInfo(forkPath)?.key;
- for (const wt of wts) {
- const clone = path.dirname(path.resolve(wt, await git(wt, ['rev-parse', '--git-common-dir'])));
- const branch = await git(wt, ['symbolic-ref', '--quiet', '--short', 'HEAD']).catch(() => '');
- await serial(clone, async () => {
- // --force only for ignored files (build output): tracked and untracked changes were checked above.
- await git(clone, ['worktree', 'remove', '--force', wt]);
- if (branch.startsWith('sp/')) await git(clone, ['branch', '-D', branch]).catch(() => {});
- });
- }
- await rm(forkPath);
- if (key) await removeCodexHome(key); // its rollouts outlive nothing else of the session
- return undefined;
-}
-
-async function pruneForks(person: Person): Promise<RepoStatus[]> {
- const sessions = path.join(personRoot(person), 'sessions');
- const kept: RepoStatus[] = [];
- for (const name of await readdir(sessions).catch(() => [] as string[])) {
- const fork = path.join(sessions, name);
- if (Date.now() - (await lastUsed(fork)) < retention()) continue;
- const why = await pruneFork(fork).catch((e) => `prune failed: ${errText(e)}`);
- if (why) kept.push({ name: `sessions/${name}`, problem: `idle beyond retention, kept: ${why}` });
- else log.info(`workspaces: pruned fork ${fork}`);
- }
- return kept;
-}
-
-// ---------------------------------------------------------------- housekeeping
-
-/** Fast-forward the checkout; a string says why not, `true` that it moved. */
-async function fastForward(clone: string, b: string): Promise<string | boolean | undefined> {
- const current = await git(clone, ['symbolic-ref', '--quiet', '--short', 'HEAD']).catch(() => '');
- if (current !== b) return `checkout is on ${current || 'a detached HEAD'}, not ${b}; not fast-forwarded`;
- if (await git(clone, ['status', '--porcelain'])) return 'checkout has local changes; not fast-forwarded';
- const [head, remote] = [await git(clone, ['rev-parse', 'HEAD']), await git(clone, ['rev-parse', `origin/${b}`])];
- if (head === remote) return undefined;
- if (!(await ok(git(clone, ['merge-base', '--is-ancestor', head, remote])))) return `${b} has diverged from origin/${b}; not fast-forwarded`;
- await git(clone, ['merge', '--ff-only', '--quiet', `origin/${b}`], fetchTimeout()); // downloads contents on a partial clone
- return true;
-}
-
-/**
- * Clone if missing (eager only), else fetch --prune (in the clone's fetch
- * lane, at most HOUSEKEEPING_FETCHES at once) and fast-forward the clone's
- * default branch checkout (under the worktree lock).
- */
-async function syncRepo(person: Person, repo: RepoDef, trigger: FetchTrigger): Promise<RepoStatus> {
- if (repo.unpublished) return { name: repo.name, problem: 'unpublished; not cloned' };
- const clone = path.join(workspaceDir(person), repo.name);
- // Lazy and not checked out by any session yet: nothing to keep fetched. Once cloned, it is kept warm like the rest.
- if (isLazy(repo) && !isClone(clone)) return { name: repo.name };
- try {
- await cloneRepo(clone, repo);
- const b = await defaultBranch(clone, repo);
- const problems: string[] = [];
- let fetchError: string | undefined;
- let ms = 0;
- await housekeepingFetch(() =>
- fetchLane(clone, async () => {
- const started = Date.now();
- await git(clone, ['fetch', '--quiet', '--prune', 'origin'], fetchTimeout()).then(
- () => (fetchedAt.set(clone, new Date().toISOString()), freshness.fetchedFrom(clone, started)),
- (e) => (problems.push(`fetch: ${errText(e)}`), (fetchError = fetchErrorType(e))),
- );
- ms = Date.now() - started;
- }), trigger === 'pushed');
- return await serial(clone, async () => {
- const ff = await fastForward(clone, b).catch((e) => `fast-forward: ${errText(e)}`);
- if (typeof ff === 'string') problems.push(ff);
- observe(() => observer.repoFetched?.({ repo: repo.name, ms, fastForwarded: ff === true, trigger, fetchError }));
- const head = await git(clone, ['rev-parse', '--short', `origin/${b}`]).catch(() => undefined);
- return { name: repo.name, fetchedAt: fetchedAt.get(clone), head, ...(problems.length && { problem: problems.join('; ') }) };
- });
- } catch (e) {
- return { name: repo.name, fetchedAt: fetchedAt.get(clone), problem: errText(e) };
- }
-}
-
-/**
- * One housekeeping pass for a person: root files, clone new repositories, fetch and
- * fast-forward the rest, report repositories removed from the definition, prune idle forks
- * and the build and dependency directories of forks idle a day, except forks in `active` (with a live runner).
- */
-export async function housekeep(person: Person, active: Set<string> = new Set()): Promise<WorkspaceStatus> {
- const def = loadDefinition();
- const ws = workspaceDir(person);
- await mkdir(ws, { recursive: true });
- await copyRootFiles(def, ws);
- const repos = await Promise.all(def.repos.map((r) => syncRepo(person, r, 'periodic')));
- const defined = new Set(def.repos.map((r) => r.name));
- for (const name of (await readdir(ws)).sort()) {
- if (!defined.has(name) && isClone(path.join(ws, name))) repos.push({ name, problem: 'removed from the definition; clone kept' });
- }
- repos.push(...(await pruneForks(person)));
- await pruneIdleArtifacts(path.join(personRoot(person), 'sessions'), active);
- const status = { person: person.dir, repos };
- lastStatus.set(person.dir, status);
- return status;
-}
-
-/** Age of the least recently fetched clone this process fetched, in seconds. */
-export function oldestFetchAgeS(now = Date.now()): number | undefined {
- const times = [...fetchedAt.values()].map(Date.parse);
- return times.length ? Math.round((now - Math.min(...times)) / 1000) : undefined;
-}
-
-const lastStatus = new Map<string, WorkspaceStatus>();
-const running = new Map<string, Promise<void>>();
-let reporter: ((s: WorkspaceStatus) => void) | undefined;
-let activeForks: () => Set<string> = () => new Set();
-
-function cycle(person: Person) {
- const busy = running.get(person.dir);
- if (busy) return busy;
- const run = housekeep(person, activeForks())
- .then((s) => reporter?.(s))
- .catch((e) => log.warn(`workspaces: housekeeping ${person.dir}: ${errText(e)}`))
- .finally(() => running.delete(person.dir));
- running.set(person.dir, run);
- return run;
-}
-
-/**
- * Start periodic housekeeping for these people; calls `report` with each workspace's
- * status. `active` names the forks with a live runner, never pruned of build and dependency directories.
- */
-export function startHousekeeping(
- people: () => Person[],
- report: (s: WorkspaceStatus) => void,
- active: () => Set<string> = () => new Set(),
-): { now(): void; stop(): void } {
- reporter = report;
- activeForks = active;
- const tick = () => {
- if (workspacesEnabled()) for (const p of people()) void cycle(p);
- };
- tick();
- const timer = setInterval(tick, fetchInterval());
- return {
- /** A pass right away (the definition changed); people already in a pass are left to it. */
- now: tick,
- stop() {
- clearInterval(timer);
- if (reporter === report) reporter = undefined;
- },
- };
-}
-
-/**
- * A push to `ref` of one repository (by remote name, e.g. `acme/widgets`):
- * every clone of it that forks from that branch stops being fresh now. Returns
- * those clones by person. Pushes to other branches (sessions' own `sp/*`) touch nothing.
- */
-export async function markPushed(repo: string, people: Person[], ref?: string): Promise<{ person: Person; repo: RepoDef }[]> {
- const want = repo.replace(/\.git$/, '').toLowerCase();
- const matches = loadDefinition().repos.filter((r) => !r.unpublished && (repoSlug(r.remote).toLowerCase() === want || r.name === repo));
- const hit: { person: Person; repo: RepoDef }[] = [];
- for (const person of people)
- for (const r of matches) {
- const clone = path.join(workspaceDir(person), r.name);
- if (!isClone(clone)) continue;
- // An unknown default branch counts as a match: fetching once too often is cheaper than a stale fork.
- const b = ref && (await defaultBranch(clone, r).catch(() => undefined));
- if (b && ref !== `refs/heads/${b}`) continue;
- freshness.pushedNow(clone);
- hit.push({ person, repo: r });
- }
- return hit;
-}
-
-/** Fetch one repository in every workspace that has it, after a push to `ref` (any branch if omitted). Returns the clones fetched. */
-export async function fetchRepo(repo: string, people: Person[], ref?: string): Promise<number> {
- const hit = await markPushed(repo, people, ref);
- await Promise.all(
- people.map(async (p) => {
- const present = hit.filter((h) => h.person === p).map((h) => h.repo);
- if (!present.length) return;
- const updated = await Promise.all(present.map((r) => syncRepo(p, r, 'pushed')));
- const prev = lastStatus.get(p.dir);
- if (!prev) return;
- const status = { ...prev, repos: prev.repos.map((s) => updated.find((u) => u.name === s.name) ?? s) };
- lastStatus.set(p.dir, status);
- reporter?.(status);
- }),
- );
- return hit.length;
-}
+export {
+ ensureWorkspace, type FetchTrigger, forkDir, observeWorkspaces, personRoot, prepareInBackground, safeKey, workspaceDir, type WorkspaceObserver,
+ workspacePrepared,
+} from './clones.js';
+export { checkoutRepos, type ForkInfo, forkInfo, forkSession, touchFork } from './fork.js';
+export { fetchRepo, housekeep, markPushed, oldestFetchAgeS, startHousekeeping } from './housekeep.js';
+export { pruneFork } from './prune.js';
diff --git a/computer/src/workspaces/prune.ts b/computer/src/workspaces/prune.ts
new file mode 100644
index 00000000..3ec1cf92
--- /dev/null
+++ b/computer/src/workspaces/prune.ts
@@ -0,0 +1,62 @@
+// Removing idle forks (work 045; split out of index.ts for work 103): a fork
+// unused for SP_FORK_RETENTION_DAYS goes, with its worktrees and its branch.
+// idle.ts says when a fork was last used and prunes build directories.
+//
+// Invariant: a fork with uncommitted changes or commits on no remote is never
+// removed; the reason it was kept is reported.
+
+import { readdir } from 'node:fs/promises';
+import path from 'node:path';
+import { log } from '../log.js';
+import type { Person, WorkspaceStatus } from '../protocol.js';
+import { rm } from './as-runner.js';
+import { errText, git, personRoot, retention, serial } from './clones.js';
+import { removeCodexHome } from './codex-homes.js';
+import { forkInfo } from './fork.js';
+import { lastUsed, worktrees } from './idle.js';
+
+type RepoStatus = WorkspaceStatus['repos'][number];
+
+/** Remove a fork unless a worktree has uncommitted changes or commits on no remote. Returns why it was kept. */
+export async function pruneFork(forkPath: string): Promise<string | undefined> {
+ const wts = await worktrees(forkPath);
+ const reasons: string[] = [];
+ for (const wt of wts) {
+ const name = path.basename(wt);
+ // --no-optional-locks: no index refresh, whose new mtime would make the fork look used (lastUsed).
+ const dirty = await git(wt, ['--no-optional-locks', 'status', '--porcelain']).catch((e) => `unreadable: ${errText(e)}`);
+ if (dirty) {
+ reasons.push(`${name} has uncommitted changes`);
+ continue;
+ }
+ const n = Number(await git(wt, ['rev-list', '--count', 'HEAD', '--not', '--remotes']).catch(() => '-1'));
+ if (n) reasons.push(n > 0 ? `${name} has ${n} unpushed commit${n > 1 ? 's' : ''}` : `${name}: cannot count unpushed commits`);
+ }
+ if (reasons.length) return reasons.join(', ');
+ const key = forkInfo(forkPath)?.key;
+ for (const wt of wts) {
+ const clone = path.dirname(path.resolve(wt, await git(wt, ['rev-parse', '--git-common-dir'])));
+ const branch = await git(wt, ['symbolic-ref', '--quiet', '--short', 'HEAD']).catch(() => '');
+ await serial(clone, async () => {
+ // --force only for ignored files (build output): tracked and untracked changes were checked above.
+ await git(clone, ['worktree', 'remove', '--force', wt]);
+ if (branch.startsWith('sp/')) await git(clone, ['branch', '-D', branch]).catch(() => {});
+ });
+ }
+ await rm(forkPath);
+ if (key) await removeCodexHome(key); // its rollouts outlive nothing else of the session
+ return undefined;
+}
+
+export async function pruneForks(person: Person): Promise<RepoStatus[]> {
+ const sessions = path.join(personRoot(person), 'sessions');
+ const kept: RepoStatus[] = [];
+ for (const name of await readdir(sessions).catch(() => [] as string[])) {
+ const fork = path.join(sessions, name);
+ if (Date.now() - (await lastUsed(fork)) < retention()) continue;
+ const why = await pruneFork(fork).catch((e) => `prune failed: ${errText(e)}`);
+ if (why) kept.push({ name: `sessions/${name}`, problem: `idle beyond retention, kept: ${why}` });
+ else log.info(`workspaces: pruned fork ${fork}`);
+ }
+ return kept;
+}