Skip to content

An open-source, faster Devin alternative

TypeScript

computer: one-time systemd->podman migration and drain-then-flip (work 103) (#1084)

opencomputer-app[bot]c44f953d666d
diff --git a/computer/bin/legacy-migrate.mjs b/computer/bin/legacy-migrate.mjs
new file mode 100644
index 00000000..b11691f7
--- /dev/null
+++ b/computer/bin/legacy-migrate.mjs
@@ -0,0 +1,175 @@
+#!/usr/bin/env node
+// ONE-TIME systemd->podman migration (work 103). Delete together with the systemd launch path in step 11.
+//
+// Moves one thread made under the `systemd` launch into the shape a container
+// expects, from inside a helper container (src/host/legacy-migration/migrate.ts
+// runs it as uid 1500 under `--userns=keep-id:uid=1500`, so whatever it writes
+// is the session's). Mounts it is given:
+// /legacy/claude-projects ro the runners' user's ~/.claude/projects (absent when there is none)
+// /legacy/codex ro the runners' user's ~/.calvin/codex (absent when there is none)
+// /home/agent the thread's new home volume
+// /clones the person's clones (`<people>/<p>/ws`)
+// /wt the thread's worktree registries (`<people>/<p>/wt/<key>`)
+// /workspace the thread's fork (`<people>/<p>/sessions/<key>`), in place
+//
+// node legacy-migrate.mjs <fork on the host> <clones on the host> <harness> <sdkSessionId or -> <codex home name>
+//
+// Prints one JSON line: { repos, claude, codex, skipped }. Exits non-zero (the
+// host then sets the fork aside and starts the thread fresh) when the fork has
+// no `.fork.json` or the transcript it is to resume is not there.
+//
+// Invariants:
+// - The person's files change only in the worktree step, which is last and is
+// safe to repeat: an admin directory already moved is found in /wt.
+// - A transcript's absolute paths are rewritten: the fork -> /workspace, the
+// clones -> /clones. Nothing else in it changes, and the session id is kept.
+// - No git runs: the worktree's `.git` file and its admin directory's
+// `gitdir` are written directly; `commondir` is left as it is.
+
+import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+export const IN = {
+ claudeProjects: '/legacy/claude-projects',
+ codex: '/legacy/codex',
+ home: '/home/agent',
+ clones: '/clones',
+ wt: '/wt',
+ workspace: '/workspace',
+};
+
+/** Claude Code's project directory name for a cwd. */
+export function claudeSlug(cwd) {
+ return cwd.replace(/[^a-zA-Z0-9]/g, '-');
+}
+
+const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+
+/** `text` with the fork's host path made /workspace and the clones' made /clones; a longer name that only starts the same is left alone. */
+export function rewritePaths(text, forkHost, clonesHost) {
+ const fork = forkHost.replace(/\/+$/, '');
+ const clones = clonesHost.replace(/\/+$/, '');
+ return text
+ .replace(new RegExp(`${escape(fork)}(?![A-Za-z0-9._-])`, 'g'), '/workspace')
+ .replace(new RegExp(`${escape(clones)}/`, 'g'), '/clones/');
+}
+
+/** Copy `src` into `dst`, rewriting the text of .jsonl and .json files. */
+function copyRewritten(src, dst, rewrite) {
+ const st = statSync(src);
+ if (st.isDirectory()) {
+ mkdirSync(dst, { recursive: true, mode: 0o700 });
+ for (const name of readdirSync(src)) copyRewritten(path.join(src, name), path.join(dst, name), rewrite);
+ } else if (st.isFile()) {
+ if (/\.jsonl?$/.test(src)) writeFileSync(dst, rewrite(readFileSync(src, 'utf8')), { mode: st.mode & 0o777 });
+ else cpSync(src, dst, { preserveTimestamps: true });
+ }
+}
+
+/** The Claude project directory of `cwd` under `projects`, or undefined; Claude Code shortens a long name and adds a hash. */
+function projectDir(projects, cwd) {
+ const slug = claudeSlug(cwd);
+ if (existsSync(path.join(projects, slug))) return path.join(projects, slug);
+ if (slug.length <= 200 || !existsSync(projects)) return undefined;
+ const found = readdirSync(projects).find((n) => n.startsWith(`${slug.slice(0, 200)}-`));
+ return found && path.join(projects, found);
+}
+
+/** Rename, or copy and remove when the two are on different mounts. */
+function move(src, dst) {
+ try {
+ renameSync(src, dst);
+ } catch (e) {
+ if (e.code !== 'EXDEV') throw e;
+ cpSync(src, dst, { recursive: true, preserveTimestamps: true, verbatimSymlinks: true });
+ rmSync(src, { recursive: true, force: true });
+ }
+}
+
+/**
+ * One repository's worktree, re-pointed: its admin directory from the shared clone into the thread's registry under the
+ * name ws-add.sh gives it (the repository's), `gitdir` naming /workspace, and the worktree's `.git` naming /clones. Returns
+ * why it was left out, or undefined when it is done.
+ */
+function repoint(p, o, repo) {
+ const dotGit = path.join(p.workspace, repo, '.git');
+ if (!existsSync(dotGit)) return 'its worktree is not in the fork';
+ if (!statSync(dotGit).isFile()) return 'its .git is not a worktree pointer';
+ const target = path.join(p.wt, repo, repo);
+ const want = `gitdir: ${IN.clones}/${repo}/.git/worktrees/${repo}`;
+ const now = readFileSync(dotGit, 'utf8').trim();
+ if (now === want && existsSync(target)) return undefined; // done by an earlier run
+ const prefix = `gitdir: ${o.clonesHost.replace(/\/+$/, '')}/${repo}/.git/worktrees/`;
+ if (!now.startsWith(prefix)) return `its .git names ${now.slice(8)}`;
+ const name = now.slice(prefix.length);
+ if (!name || name.includes('/') || name === '.' || name === '..') return `its .git names ${now.slice(8)}`;
+ const admin = path.join(p.clones, repo, '.git', 'worktrees', name);
+ if (!existsSync(admin)) {
+ if (!existsSync(target)) return `no admin directory ${name} in the clone`;
+ } else {
+ const back = readFileSync(path.join(admin, 'gitdir'), 'utf8').trim();
+ if (back !== path.join(o.forkHost, repo, '.git')) return `the clone's ${name} belongs to ${back}`;
+ rmSync(target, { recursive: true, force: true }); // half of an earlier run
+ mkdirSync(path.dirname(target), { recursive: true });
+ move(admin, target);
+ }
+ writeFileSync(path.join(target, 'gitdir'), `${IN.workspace}/${repo}/.git\n`);
+ writeFileSync(dotGit, `${want}\n`);
+ return undefined;
+}
+
+/**
+ * The migration, on paths `p` (IN in a helper container; a fixture in tests). `o`: the fork's and the clones' paths on the
+ * host, the harness, the session id to resume (or none) and the name of the thread's CODEX_HOME.
+ */
+export function migrate(p, o) {
+ const fork = JSON.parse(readFileSync(path.join(p.workspace, '.fork.json'), 'utf8'));
+ const repos = fork.repos && typeof fork.repos === 'object' ? fork.repos : {};
+ const rewrite = (t) => rewritePaths(t, o.forkHost, o.clonesHost);
+
+ let claude = false;
+ const project = projectDir(p.claudeProjects, o.forkHost);
+ if (o.harness !== 'codex' && o.sdkSessionId && !(project && existsSync(path.join(project, `${o.sdkSessionId}.jsonl`))))
+ throw new Error(`no transcript ${o.sdkSessionId}.jsonl for ${o.forkHost}`);
+ if (project) {
+ copyRewritten(project, path.join(p.home, '.claude', 'projects', claudeSlug(IN.workspace)), rewrite);
+ claude = true;
+ }
+
+ let codex = false;
+ const codexSrc = path.join(p.codex, o.codexName);
+ if (existsSync(codexSrc)) {
+ mkdirSync(path.join(p.home, '.calvin', 'codex'), { recursive: true, mode: 0o700 });
+ cpSync(codexSrc, path.join(p.home, '.calvin', 'codex', o.codexName), { recursive: true, preserveTimestamps: true, verbatimSymlinks: true });
+ codex = true;
+ } else if (o.harness === 'codex' && o.sdkSessionId) throw new Error(`no Codex home ${o.codexName} for ${o.forkHost}`);
+
+ const kept = {};
+ const skipped = [];
+ for (const [repo, info] of Object.entries(repos)) {
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(repo) || repo === '.git') {
+ skipped.push({ repo, why: 'not a repository name' });
+ continue;
+ }
+ const why = repoint(p, o, repo);
+ if (why) skipped.push({ repo, why });
+ else kept[repo] = info;
+ }
+ return { repos: kept, claude, codex, skipped };
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ const [forkHost, clonesHost, harness, sdk, codexName] = process.argv.slice(2);
+ if (!forkHost || !clonesHost || !harness || !sdk || !codexName) {
+ console.error('usage: legacy-migrate.mjs <fork> <clones> <harness> <sdkSessionId|-> <codex name>');
+ process.exit(2);
+ }
+ try {
+ const out = migrate(IN, { forkHost, clonesHost, harness, sdkSessionId: sdk === '-' ? undefined : sdk, codexName });
+ process.stdout.write(`${JSON.stringify(out)}\n`);
+ } catch (e) {
+ console.error(`legacy-migrate: ${e?.message ?? e}`);
+ process.exit(1);
+ }
+}
diff --git a/computer/deploy/vm/provision.sh b/computer/deploy/vm/provision.sh
index f3659b97..53235c89 100755
--- a/computer/deploy/vm/provision.sh
+++ b/computer/deploy/vm/provision.sh
@@ -870,12 +870,57 @@ EOF
umask 022
fi
+# ---- ONE-TIME systemd->podman migration (work 103). Delete together with the systemd launch path in step 11.
+# When this run turns the host's SP_LAUNCH from systemd to podman, a plain
+# restart would leave the `systemd` runners running beside a `podman` host.
+# Instead the running host is drained (src/host/legacy-migration/drain.ts):
+# SIGUSR2, it tells every runner to exit after its turn, holds new deliveries
+# and exits when none is left (10 min at most); Restart= brings it back as a
+# `podman` host, which migrates each thread at its next delivery. Returns 1,
+# for a plain restart, when SP_LAUNCH does not change that way, when the
+# running release has no drain, or when the host did not come back in time.
+sp_launch_of_files() { # <env files...>: the last SP_LAUNCH= in them, unquoted
+ local f v=''
+ for f in "$@"; do
+ [[ -r $f ]] || continue
+ v=$(sed -n 's/^[[:space:]]*\(export[[:space:]]\+\)\?SP_LAUNCH=//p' "$f" | tail -n1 | sed "s/^[\"']//; s/[\"']\$//")
+ [[ -n $v ]] && printf '%s\n' "$v"
+ done | tail -n1
+}
+legacy_drain_restart() {
+ local pid old new files
+ pid=$(systemctl show -p MainPID --value slack-presence-host.service 2>/dev/null || echo 0)
+ [[ -n $pid && $pid != 0 && -r /proc/$pid/environ ]] || return 1
+ old=$(tr '\0' '\n' < "/proc/$pid/environ" | sed -n 's/^SP_LAUNCH=//p' | tail -n1)
+ # What the restarted unit will have: its Environment=, then its EnvironmentFile=s in order (they win).
+ new=$(systemctl show -p Environment --value slack-presence-host.service | tr ' ' '\n' | sed -n 's/^SP_LAUNCH=//p' | tail -n1)
+ mapfile -t files < <(systemctl show -p EnvironmentFiles --value slack-presence-host.service | tr ' ' '\n' | grep '^/' || true)
+ local fromfiles; fromfiles=$(sp_launch_of_files "${files[@]}")
+ new=${fromfiles:-$new}
+ [[ ${old:-systemd} == systemd && ${new:-systemd} == podman ]] || return 1
+ if [[ ! -f /proc/$pid/cwd/src/host/legacy-migration/drain.ts ]]; then
+ warn "SP_LAUNCH turns to podman but the running host has no drain: plain restart (deploy this release on systemd first)"
+ return 1
+ fi
+ log "SP_LAUNCH systemd -> podman: draining host $pid (runners finish their turns; at most ~10 min)"
+ systemctl kill -s SIGUSR2 --kill-whom=main slack-presence-host.service || return 1
+ local i now
+ for ((i = 0; i < 660; i += 5)); do
+ sleep 5
+ now=$(systemctl show -p MainPID --value slack-presence-host.service 2>/dev/null || echo 0)
+ if [[ -n $now && $now != 0 && $now != "$pid" ]]; then log "host drained and back as podman (pid $now)"; return 0; fi
+ done
+ warn "host $pid did not drain in time: restarting it"
+ return 1
+}
+# ---- end ONE-TIME systemd->podman migration
+
if [[ -f $HOST_ENV ]]; then
chmod 0600 "$HOST_ENV"; chown root:root "$HOST_ENV"
log "starting slack-presence-host"
systemctl enable slack-presence-host.service
# Restart picks up the new release; runners are unaffected (see KillMode).
- systemctl restart slack-presence-host.service
+ legacy_drain_restart || systemctl restart slack-presence-host.service # ONE-TIME systemd->podman migration (work 103): delete in step 11
# The relay follows the release too (its clients reconnect after 1012); a no-op unless the host is sp-host.
systemctl enable -q slack-presence-wire.service
systemctl restart slack-presence-wire.service || warn "slack-presence-wire did not start: journalctl -u slack-presence-wire"
diff --git a/computer/src/dev/fake-model.mjs b/computer/src/dev/fake-model.mjs
index 098f9c11..24d556cd 100644
--- a/computer/src/dev/fake-model.mjs
+++ b/computer/src/dev/fake-model.mjs
@@ -11,6 +11,8 @@
// of the offered tool whose name is `<tool>` or ends in `__<tool>`; the
// request that carries its result is answered `done`, and the result's text
// is kept. `GET /calls` returns what was kept: `[{ tool, input, result }]`.
+// `GET /turns` returns, for each turn's request, the text of its person's
+// messages, earlier ones too (sandbox-check-legacy.ts: a resumed transcript).
//
// Invariants: plain Node, no dependency, no file written: it runs from a
// release mounted read-only. It listens on 127.0.0.1 only.
@@ -28,6 +30,8 @@ if (!port || (key && !cert)) {
/** @type {{ tool: string, input: unknown, result?: string }[]} */
const calls = [];
+/** @type {string[]} */
+const turns = [];
const ASK = /call ([a-z_]+) (\{[^\n]*\})/;
const textOf = (content) =>
@@ -56,10 +60,12 @@ const handle = (req, res) => {
req.on('data', (c) => (body += c));
req.on('end', () => {
const json = (code, v) => (res.writeHead(code, { 'content-type': 'application/json' }), res.end(JSON.stringify(v)));
+ if (req.method === 'GET' && req.url === '/turns') return json(200, turns);
if (req.method === 'GET' && req.url === '/calls') return json(200, calls.map(({ tool, input, result }) => ({ tool, input, result })));
if (!req.url?.startsWith('/v1/messages')) return json(404, { type: 'error', error: { type: 'not_found_error', message: 'not found' } });
if (req.url.startsWith('/v1/messages/count_tokens')) return json(200, { input_tokens: 10 });
const j = body ? JSON.parse(body) : {};
+ if (j.stream) turns.push((j.messages ?? []).filter((m) => m.role === 'user').map((m) => textOf(m.content)).join('\n'));
const a = j.stream ? answer(j) : { text: 'ok' }; // only a turn streams; the side requests (a title) get a word
const content = a.call ? [{ type: 'tool_use', id: a.call.id, name: a.call.tool, input: a.call.input }] : [{ type: 'text', text: a.text }];
const stop_reason = a.call ? 'tool_use' : 'end_turn';
diff --git a/computer/src/dev/sandbox-check-legacy.ts b/computer/src/dev/sandbox-check-legacy.ts
new file mode 100644
index 00000000..1db3839e
--- /dev/null
+++ b/computer/src/dev/sandbox-check-legacy.ts
@@ -0,0 +1,252 @@
+// ONE-TIME systemd->podman migration (work 103). Delete together with the systemd launch path in step 11.
+//
+// End-to-end check of the flip, on a computer: a host agent with
+// SP_LAUNCH=systemd serves two threads of a workspace with one repository
+// (turns answered by src/dev/fake-model.mjs behind the release's
+// oc-modelproxy, sandbox-check-model.ts); one goes idle and its runner exits
+// (a cold thread), the other is live with an uncommitted file in its
+// worktree. SIGUSR2 drains the host (legacy-migration/drain.ts): a delivery
+// sent then gets no reply from it, its runner exits and so does the host. A
+// host with SP_LAUNCH=podman comes up, the fake gateway sends the held
+// delivery again (as the gateway does when a host's socket closes), then
+// delivers to the cold thread with the session id and fork path of its last
+// report. Each thread is migrated (legacy-migration/migrate.ts): a record
+// with its repository, its worktree working inside its container, its
+// uncommitted file, its transcript in its home, and the stand-in model sent
+// the earlier turns' text with the new turn: the session was resumed.
+//
+// It needs what deploy/vm/provision.sh sets up and github.com, so it runs on
+// a computer, as the host's user, from a release, with no host agent running:
+// cd /opt/slack-presence/current && set -a && . ./.sp-version.env && set +a && \
+// sudo -u sp-host env SP_RUNNER_USER=agent SP_IMAGE="$SP_IMAGE" SP_IMAGE_ABI="$SP_IMAGE_ABI" \
+// node --import tsx src/dev/sandbox-check-legacy.ts [--keep]
+//
+// Invariants:
+// - It refuses to run beside a host agent (sandbox-check.ts does the same).
+// - It removes what it made, pass or fail, unless `--keep`: containers, home
+// volumes, records, run directories, the person directory
+// `sandbox-check-legacy`, the threads' transcripts and Codex homes in the
+// runners' user's home, and the definition it saved.
+
+import { execFileSync, spawn, type ChildProcess } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import type net from 'node:net';
+import path from 'node:path';
+import { WebSocketServer, type WebSocket } from 'ws';
+import { codexHome } from '../codex-home.js';
+import { runnerUser } from '../host/runner-user.js';
+import { mounts } from '../host/sandbox/mounts.js';
+import { asRunner, type PodmanError } from '../host/sandbox/podman.js';
+import { containerName, unshareRmArgs, volumeName } from '../host/sandbox/podman-args.js';
+import { sandboxRecords } from '../host/sandbox/records.js';
+import { sandboxRunFor } from '../ipc.js';
+import type { GatewayToHost, HostToGateway, Person, SessionReport, SessionSpec } from '../protocol.js';
+import { gatewayDefinitionPath } from '../workspaces/definition.js';
+import { checkModel } from './sandbox-check-model.js';
+
+const ROOT = path.resolve(import.meta.dirname, '..', '..');
+const KEEP = process.argv.includes('--keep');
+const RUN = process.env.SP_RUN ?? '/run/slack-presence';
+const DATA = process.env.SP_DATA ?? '/data';
+const IDLE_MS = 20_000;
+const NOW = Date.now() / 1000;
+
+const t0 = Date.now();
+const say = (...a: unknown[]) => console.log(`+${((Date.now() - t0) / 1000).toFixed(1)}s`, ...a);
+let failed = 0;
+const check = (ok: boolean, what: string) => {
+ say(ok ? 'PASS' : 'FAIL', what);
+ if (!ok) failed++;
+};
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+async function until<T>(f: () => T | undefined | Promise<T | undefined>, ms = 30_000, every = 200): Promise<T | undefined> {
+ for (const end = Date.now() + ms; Date.now() < end; await sleep(every)) {
+ const v = await f();
+ if (v) return v;
+ }
+}
+const refuse = (why: string): never => {
+ console.error(`sandbox-check-legacy: ${why}`);
+ process.exit(2);
+};
+
+const user = runnerUser(process.env) ?? refuse("set SP_RUNNER_USER (the runners' user, `agent` on a computer)");
+if (!process.env.SP_IMAGE || !process.env.SP_IMAGE_ABI) refuse("set SP_IMAGE and SP_IMAGE_ABI (the release's .sp-version.env has them)");
+if (!existsSync(path.join(ROOT, 'dist/runner-boot.mjs'))) refuse(`${ROOT} has no dist/runner-boot.mjs: run it from a release`);
+try {
+ execFileSync('/usr/bin/systemctl', ['is-active', '--quiet', 'slack-presence-host.service']);
+ refuse('slack-presence-host is running here; this check would be a second host on its directories');
+} catch {
+ // not active: the directories are ours for the run
+}
+const model = await checkModel({ root: ROOT, run: RUN }).catch((e) => refuse(`no model proxy: ${e.message}`));
+const as = asRunner(user.sudo);
+const podman = (args: string[], timeoutMs = 30_000) => as.podman(args, { timeoutMs });
+const mnt = mounts({ as, root: ROOT, dataDir: DATA });
+const records = () => sandboxRecords(path.join(DATA, 'state', 'sandboxes'));
+const savedDefinition = existsSync(gatewayDefinitionPath()) ? readFileSync(gatewayDefinitionPath(), 'utf8') : undefined;
+
+// ---- fake gateway: it sends a delivery with no reply again to the next host, as the gateway does
+
+const PAT: Person = { slackUserId: 'U_OWNER', userId: 'usr_sandbox_check_legacy', dir: 'sandbox-check-legacy', gitName: 'Sandbox Check', gitEmail: '[email protected]' };
+const credentials = { slackBotToken: '', slackBotUserId: '' };
+const definition = { name: 'sandbox-check-legacy', about: 'legacy', repos: [{ name: 'hello', remote: 'https://github.com/octocat/Hello-World' }] };
+const events: HostToGateway[] = [];
+const pending = new Map<string, GatewayToHost>();
+let conn: WebSocket | undefined;
+const wss = new WebSocketServer({ port: 0, path: '/host', verifyClient: ({ req }: { req: { headers: Record<string, unknown> } }) => req.headers.authorization === 'Bearer check-token' });
+await new Promise((r) => wss.on('listening', r));
+const toHost = (m: GatewayToHost) => conn?.send(JSON.stringify(m));
+wss.on('connection', (c) => {
+ conn = c;
+ c.on('message', (d) => {
+ const m = JSON.parse(String(d)) as HostToGateway;
+ events.push(m);
+ if (m.t === 'hello') {
+ toHost({ t: 'welcome', protocol: 4, credentials, models: { claude: model.route }, people: [PAT], definition });
+ for (const p of pending.values()) toHost(p);
+ }
+ if (m.t === 'reply') pending.delete(m.id);
+ if (m.t === 'token') toHost({ t: 'token', id: m.id, result: { token: 'ghs_fake', expiresAt: new Date(Date.now() + 3600_000).toISOString() } });
+ });
+});
+
+function thread(n: number) {
+ const key = `C_LEGACY:${(NOW + n).toFixed(3)}`;
+ const spec: SessionSpec = { key, kind: 'thread', channel: 'C_LEGACY', threadTs: key.split(':')[1], owner: PAT, title: `legacy check ${n}`, mode: 'bypassPermissions' };
+ const t = {
+ key, spec,
+ fork: mnt.workspace({ person: PAT.dir, key }),
+ record: () => records().find(PAT.dir, key),
+ reports: () => events.flatMap((e) => (e.t === 'session' && e.report.key === key ? [e.report] : [])),
+ report: () => t.reports().pop(),
+ /** The last report with a session id: what the gateway keeps of the thread. */
+ known: (): SessionReport | undefined => t.reports().filter((r) => r.sdkSessionId).pop(),
+ /** Deliver `text` with the spec the gateway sends: for a thread it knows, its last report's session id and fork path. */
+ send(text: string) {
+ const id = randomUUID();
+ const known = t.known();
+ const session = known ? { ...spec, sdkSessionId: known.sdkSessionId, forkPath: known.forkPath } : spec;
+ const m: GatewayToHost = { t: 'deliver', id, session, msg: { userId: 'U_OWNER', text, ts: `3.${Date.now()}` }, credentials };
+ pending.set(id, m);
+ toHost(m);
+ return id;
+ },
+ reply: (id: string, ms = 120_000) => until(() => events.find((e): e is Extract<HostToGateway, { t: 'reply' }> => e.t === 'reply' && e.id === id), ms),
+ inside: (script: string) =>
+ podman(['exec', '--user', '1500:1500', containerName(t.record()?.id ?? ''), '/bin/sh', '-c', script], 60_000).then((s) => s.trim(), (e: PodmanError) => `error: ${(e.stderr || e.message).trim()}`),
+ };
+ return t;
+}
+type Thread = ReturnType<typeof thread>;
+const LIVE = thread(1);
+const COLD = thread(2);
+
+// ---- the hosts, and the cleanup
+
+let host: ChildProcess | undefined;
+function startHost(launch: 'systemd' | 'podman'): ChildProcess {
+ const { SP_DEFINITION, WORKDIR, SLACK_BOT_TOKEN, ...rest } = process.env;
+ const h = spawn(process.execPath, ['--import', 'tsx', 'src/host/main.ts'], {
+ cwd: ROOT,
+ env: { ...rest, SP_GATEWAY_URL: `ws://127.0.0.1:${(wss.address() as net.AddressInfo).port}/host`, SP_HOST_TOKEN: 'check-token', SP_HOST_ID: 'sandbox-check-legacy',
+ SP_RUN: RUN, SP_DATA: DATA, SP_IDLE_MS: String(IDLE_MS), SP_LAUNCH: launch, SP_POOL_SIZE: '0', SP_FAKE_SLACK: '1', SP_MODEL_PROXY: model.control, SP_MODEL_SOCKET: model.api },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ for (const s of [h.stdout!, h.stderr!]) s.on('data', (d) => process.stdout.write(String(d).replace(/^(?=.)/gm, ` ${launch}| `)));
+ return h;
+}
+const exited = (h: ChildProcess, ms: number) => until(() => h.exitCode !== null || h.signalCode !== null, ms, 250);
+
+async function cleanup() {
+ if (host && host.exitCode === null) {
+ host.kill('SIGTERM');
+ await exited(host, 20_000);
+ }
+ model.stop();
+ if (KEEP) return say('--keep: left the containers and their files');
+ const quiet = (p: Promise<unknown>) => p.catch((e) => say(`cleanup: ${e.message}`));
+ for (const t of [LIVE, COLD]) {
+ const id = t.record()?.id;
+ if (id) {
+ await quiet(podman(['rm', '--force', '--volumes', containerName(id)]));
+ await quiet(podman(['volume', 'rm', '--force', volumeName(id)]));
+ await podman(unshareRmArgs([sandboxRunFor(RUN, id)])).catch(() => {});
+ rmSync(sandboxRunFor(RUN, id), { recursive: true, force: true });
+ records().delete(id);
+ }
+ // The `systemd` runners' leftovers in their user's home: the transcript (named for the fork) and the Codex home.
+ const slug = t.fork.replace(/[^a-zA-Z0-9]/g, '-');
+ await quiet(as.run(['/bin/rm', '-rf', '--', path.join(user.env.HOME, '.claude', 'projects', slug), codexHome(path.join(user.env.HOME, '.calvin', 'codex'), t.key)], { timeoutMs: 30_000 }));
+ }
+ await quiet(podman(unshareRmArgs([path.join(DATA, 'people', PAT.dir)]), 60_000));
+ if (savedDefinition === undefined) rmSync(gatewayDefinitionPath(), { force: true });
+ else writeFileSync(gatewayDefinitionPath(), savedDefinition);
+}
+
+// ---- the check
+
+async function onSystemd() {
+ host = startHost('systemd');
+ const [l, c] = [LIVE.send('remember marker-live-1'), COLD.send('remember marker-cold-1')];
+ const [rl, rc] = await Promise.all([LIVE.reply(l), COLD.reply(c)]);
+ check(!!rl?.ok && !!rc?.ok, `systemd: both threads answered (${rl?.error ?? ''}${rc?.error ?? ''})`);
+ const reported = await until(() => (LIVE.known() && COLD.known() ? [LIVE.known()!, COLD.known()!] : undefined));
+ check(!!reported && reported.every((r) => r.forkPath && !r.forkPath.startsWith('/workspace')), `systemd: each thread reports a session id and its fork on the host: ${JSON.stringify(reported?.map((r) => r.forkPath))}`);
+ check(!records().find(PAT.dir, LIVE.key) && existsSync(path.join(LIVE.fork, 'hello', '.git')), `systemd: no record, the fork and its worktree in ${LIVE.fork}`);
+ await as.run(['/bin/sh', '-c', `echo uncommitted-live > ${path.join(LIVE.fork, 'hello', 'wip.txt')}`], { timeoutMs: 10_000 });
+ // The cold thread: its runner exits for idleness; the gateway keeps its last report.
+ const cold = await until(() => COLD.report()?.status === 'stopped', IDLE_MS + 30_000, 500);
+ check(!!cold, `systemd: ${COLD.key}'s runner left for idleness`);
+ // Keep the live one live, then drain.
+ const again = await LIVE.reply(LIVE.send('remember marker-live-2'));
+ check(!!again?.ok, 'systemd: a second turn on the live thread');
+}
+
+async function drain() {
+ const h = host!;
+ h.kill('SIGUSR2');
+ await sleep(500);
+ const held = LIVE.send('during the drain marker-live-3');
+ const out = await exited(h, 120_000);
+ check(!!out && h.exitCode === 0, `drain: the systemd host exited on its own (code ${h.exitCode} ${h.signalCode ?? ''})`);
+ check(pending.has(held), 'drain: the delivery sent during the drain got no reply from the systemd host');
+ return held;
+}
+
+async function onPodman(held: string, before: { live?: SessionReport; cold?: SessionReport }) {
+ host = startHost('podman');
+ const r1 = await LIVE.reply(held, 240_000);
+ check(!!r1?.ok, `podman: the held delivery, sent again, is answered on ${LIVE.key} (${r1?.error ?? ''})`);
+ const r2 = await COLD.reply(COLD.send('back after the flip marker-cold-2'), 240_000);
+ check(!!r2?.ok, `podman: the cold thread, delivered to with its last report's session id and fork, is answered (${r2?.error ?? ''})`);
+ const turns = await model.turns();
+ const last = (marker: string) => [...turns].reverse().find((t) => t.includes(marker)) ?? '';
+ check(last('marker-live-3').includes('marker-live-1') && last('marker-live-3').includes('marker-live-2'), 'podman: the live thread\'s turn carried its earlier turns: resumed');
+ check(last('marker-cold-2').includes('marker-cold-1'), "podman: the cold thread's turn carried its earlier turn: resumed");
+ for (const [t, was] of [[LIVE, before.live], [COLD, before.cold]] as [Thread, SessionReport | undefined][]) {
+ const rec = t.record();
+ check(!!rec?.repos?.hello, `podman: ${t.key} has a record with its repository: ${JSON.stringify(rec?.repos)}`);
+ const now = await until(() => t.reports().filter((r) => r.forkPath === '/workspace' && r.sdkSessionId).pop());
+ check(!!was?.sdkSessionId && now?.sdkSessionId === was.sdkSessionId, `podman: ${t.key} kept its session id ${was?.sdkSessionId}`);
+ const seen = await t.inside(`cat /workspace/hello/.git; git -C /workspace/hello status --porcelain; test -f "$HOME/.claude/projects/-workspace/${was?.sdkSessionId}.jsonl" && echo transcript`);
+ const wip = t === LIVE ? '?? wip.txt\n' : '';
+ check(seen === `gitdir: /clones/hello/.git/worktrees/hello\n${wip}transcript`, `podman: ${t.key}'s worktree works inside, its transcript is in its home: ${JSON.stringify(seen)}`);
+ }
+ check(!existsSync(path.join(DATA, 'people', PAT.dir, 'sessions.pre-sandbox')), 'podman: no fork was set aside');
+}
+
+try {
+ await onSystemd();
+ const before = { live: LIVE.known(), cold: COLD.known() };
+ const held = await drain();
+ await onPodman(held, before);
+} catch (e) {
+ check(false, `threw: ${(e as Error)?.stack ?? e}`);
+} finally {
+ await cleanup();
+ wss.close();
+}
+say(failed ? `${failed} check(s) failed` : 'all checks passed');
+process.exit(failed ? 1 : 0);
diff --git a/computer/src/dev/sandbox-check-model.ts b/computer/src/dev/sandbox-check-model.ts
index 7d0911a5..54ce554e 100644
--- a/computer/src/dev/sandbox-check-model.ts
+++ b/computer/src/dev/sandbox-check-model.ts
@@ -34,6 +34,8 @@ export interface CheckModel {
route: ModelRoute;
/** The tool calls the stand-in made, with the results it was given. */
calls(): Promise<ModelCall[]>;
+ /** Per turn the stand-in answered, the text of the person's messages it was sent, earlier turns' too. */
+ turns(): Promise<string[]>;
stop(): void;
}
@@ -83,11 +85,13 @@ export async function checkModel(o: { root: string; run: string }): Promise<Chec
}
chmodSync(api, 0o666);
const token = 'check-not-a-credential';
- const calls = () => new Promise<ModelCall[]>((resolve) => {
- https.get({ host: '127.0.0.1', port: MODEL_PORT, path: '/calls', ca: readFileSync(cert), timeout: 5000 }, (res) => {
+ const get = <T>(what: string) => new Promise<T[]>((resolve) => {
+ https.get({ host: '127.0.0.1', port: MODEL_PORT, path: what, ca: readFileSync(cert), timeout: 5000 }, (res) => {
let body = '';
res.setEncoding('utf8').on('data', (d) => (body += d)).on('end', () => resolve(JSON.parse(body || '[]')));
}).on('timeout', function (this: { destroy(): void }) { this.destroy(); }).on('error', () => resolve([]));
});
- return { control, api, route: { mode: 'profile', profile: PROFILE, vars: { token }, key: modelKey(PROFILE, { token }) }, calls, stop };
+ const calls = () => get<ModelCall>('/calls');
+ const turns = () => get<string>('/turns');
+ return { control, api, route: { mode: 'profile', profile: PROFILE, vars: { token }, key: modelKey(PROFILE, { token }) }, calls, turns, stop };
}
diff --git a/computer/src/host/legacy-migration/drain.test.ts b/computer/src/host/legacy-migration/drain.test.ts
new file mode 100644
index 00000000..9610fdc6
--- /dev/null
+++ b/computer/src/host/legacy-migration/drain.test.ts
@@ -0,0 +1,78 @@
+// ONE-TIME systemd->podman migration (work 103). Delete together with the systemd launch path in step 11.
+
+import type net from 'node:net';
+import { describe, expect, it } from 'vitest';
+import type { HostToRunner } from '../../protocol.js';
+import { legacyDrain } from './drain.js';
+
+function rig(ids: string[]) {
+ let t = 0;
+ const live = new Map(ids.map((id) => [id, { id, sock: { id } as unknown as net.Socket }]));
+ const sent: string[] = [];
+ let exits = 0;
+ let ticks = 0;
+ const drain = legacyDrain({
+ runners: () => live.values(),
+ send: (sock, m: HostToRunner) => void sent.push(`${(sock as unknown as { id: string }).id} ${JSON.stringify(m)}`),
+ exit: () => void exits++,
+ deadlineMs: 600_000, graceMs: 10_000, now: () => t,
+ setInterval: () => void ticks++,
+ });
+ return { drain, live, sent, exits: () => exits, ticks: () => ticks, at: (ms: number) => ((t = ms), drain.tick()) };
+}
+
+describe('legacy drain', () => {
+ it('tells every runner to exit after its turn, once, and exits when none is left', () => {
+ const r = rig(['a', 'spare']);
+ expect(r.drain.draining).toBe(false);
+ r.drain.start();
+ expect(r.drain.draining).toBe(true);
+ expect(r.sent).toEqual(['a {"t":"exit"}', 'spare {"t":"exit"}']);
+ r.live.delete('spare');
+ r.at(1000);
+ expect(r.sent).toHaveLength(2);
+ expect(r.exits()).toBe(0);
+ r.live.delete('a');
+ r.at(2000);
+ expect(r.exits()).toBe(1);
+ r.at(3000);
+ expect(r.exits()).toBe(1);
+ });
+
+ it('tells a runner that connects later too', () => {
+ const r = rig(['a']);
+ r.drain.start();
+ r.live.set('b', { id: 'b', sock: { id: 'b' } as unknown as net.Socket });
+ r.at(1000);
+ expect(r.sent).toEqual(['a {"t":"exit"}', 'b {"t":"exit"}']);
+ });
+
+ it('holds every delivery: the promise never settles', async () => {
+ const r = rig(['a']);
+ r.drain.start();
+ const settled = await Promise.race([r.drain.held().then(() => 'settled', () => 'settled'), new Promise((ok) => setTimeout(() => ok('held'), 20))]);
+ expect(settled).toBe('held');
+ });
+
+ it('at the deadline tells the rest to go now, and leaves after the grace whatever is left', () => {
+ const r = rig(['busy']);
+ r.drain.start();
+ r.at(599_999);
+ expect(r.sent).toEqual(['busy {"t":"exit"}']);
+ r.at(600_000);
+ expect(r.sent).toEqual(['busy {"t":"exit"}', 'busy {"t":"exit","ms":0}']);
+ r.at(605_000);
+ expect(r.sent).toHaveLength(2);
+ expect(r.exits()).toBe(0);
+ r.at(610_000);
+ expect(r.exits()).toBe(1);
+ });
+
+ it('a host with no runner exits at once; a second start is nothing', () => {
+ const r = rig([]);
+ r.drain.start();
+ r.drain.start();
+ expect(r.exits()).toBe(1);
+ expect(r.ticks()).toBe(0);
+ });
+});
diff --git a/computer/src/host/legacy-migration/drain.ts b/computer/src/host/legacy-migration/drain.ts
new file mode 100644
index 00000000..7511ef5f
--- /dev/null
+++ b/computer/src/host/legacy-migration/drain.ts
@@ -0,0 +1,89 @@
+// ONE-TIME systemd->podman migration (work 103). Delete together with the systemd launch path in step 11.
+//
+// Drain-then-flip, on a `systemd` host: told to (SIGUSR2, from provision.sh
+// when the release's SP_LAUNCH turns from systemd to podman), the host tells
+// every runner to exit after its turn, starts nothing new and exits once no
+// runner is left, or at the deadline. Its unit's `Restart=` brings it back
+// with the new SP_LAUNCH, as a `podman` host, and each thread's next delivery
+// migrates it there (migrate.ts).
+//
+// Invariants:
+// - Nothing is cut: a runner ends its turn and its subagents first (runner
+// main.ts `exit`). Only at the deadline is a runner still busy told to go
+// now, and the host leaves `graceMs` later whatever is left.
+// - No delivery reaches a runner once the drain began: `held()` never settles,
+// so the delivery is the gateway's again when the host's socket closes, and
+// it sends it to the next host.
+// - A runner that connects after the drain began (a start already under way)
+// is told to exit too, at the next tick.
+
+import type net from 'node:net';
+import { log } from '../../log.js';
+import type { HostToRunner } from '../../protocol.js';
+
+export const DRAIN_DEADLINE_MS = 10 * 60_000;
+const TICK_MS = 1000;
+const GRACE_MS = 10_000;
+
+export interface DrainDeps {
+ /** Every connected runner, the spares too. */
+ runners(): Iterable<{ id: string; sock: net.Socket }>;
+ send(sock: net.Socket, m: HostToRunner): void;
+ /** The host's own shutdown (main.ts): its unit restarts it. */
+ exit(): void;
+ deadlineMs?: number;
+ graceMs?: number;
+ tickMs?: number;
+ now?: () => number;
+ setInterval?: (fn: () => void, ms: number) => unknown;
+}
+
+export function legacyDrain(d: DrainDeps) {
+ const deadlineMs = d.deadlineMs ?? DRAIN_DEADLINE_MS;
+ const graceMs = d.graceMs ?? GRACE_MS;
+ const now = d.now ?? Date.now;
+ const every = d.setInterval ?? ((fn, ms) => setInterval(fn, ms));
+ const told = new WeakSet<net.Socket>();
+ let since: number | undefined;
+ let forced = false;
+ let done = false;
+
+ function tick() {
+ if (done || since === undefined) return;
+ const left = [...d.runners()];
+ if (left.length === 0) return finish('no runner left');
+ const late = now() - since >= deadlineMs;
+ for (const r of left) {
+ if (late && !forced) d.send(r.sock, { t: 'exit', ms: 0 } satisfies HostToRunner);
+ else if (!told.has(r.sock)) d.send(r.sock, { t: 'exit' } satisfies HostToRunner);
+ told.add(r.sock);
+ }
+ if (late && !forced) {
+ forced = true;
+ log.warn(`legacy drain: deadline, ${left.length} runner(s) told to exit now: ${left.map((r) => r.id).join(' ')}`);
+ }
+ if (now() - since >= deadlineMs + graceMs) finish(`${left.length} runner(s) still connected`);
+ }
+
+ function finish(why: string) {
+ done = true;
+ log.info(`legacy drain: exiting after ${Math.round((now() - (since ?? now())) / 1000)} s (${why})`);
+ d.exit();
+ }
+
+ return {
+ get draining() {
+ return since !== undefined;
+ },
+ /** What a delivery gets while draining: a promise that never settles (the gateway redelivers to the next host). */
+ held: <T>() => new Promise<T>(() => {}),
+ start() {
+ if (since !== undefined) return;
+ since = now();
+ log.info(`legacy drain: telling every runner to exit after its turn; leaving when none is left or in ${Math.round(deadlineMs / 1000)} s`);
+ tick();
+ if (!done) (every(tick, d.tickMs ?? TICK_MS) as { unref?: () => void })?.unref?.();
+ },
+ tick,
+ };
+}
diff --git a/computer/src/host/legacy-migration/migrate.test.ts b/computer/src/host/legacy-migration/migrate.test.ts
new file mode 100644
index 00000000..8dccb744
--- /dev/null
+++ b/computer/src/host/legacy-migration/migrate.test.ts
@@ -0,0 +1,193 @@
+// ONE-TIME systemd->podman migration (work 103). Delete together with the systemd launch path in step 11.
+
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { describe, expect, it } from 'vitest';
+import type { SessionSpec } from '../../protocol.js';
+import type { AsRunner } from '../sandbox/podman.js';
+import { sandboxRecords } from '../sandbox/records.js';
+import { legacyMigration, migrateArgv, parseResult } from './migrate.js';
+
+// biome-ignore lint/suspicious/noExplicitAny: a plain .mjs, imported for its exports
+const script: any = await import('../../../bin/legacy-migrate.mjs' as string);
+
+const SID = '0b7c6a52-1f3e-4d6a-9a43-2f6f4bfb0e11';
+const CODEX = 'a1b2c3d4e5f6a1b2c3d4e5f6';
+
+/** A `systemd` host's leftovers of one thread, in a temporary directory: the paths the script sees, and the host's. */
+function fixture() {
+ const root = mkdtempSync(path.join(tmpdir(), 'legacy-'));
+ const forkHost = path.join(root, 'people/pat/sessions/C1-1.1');
+ const clonesHost = path.join(root, 'people/pat/ws');
+ const p = {
+ claudeProjects: path.join(root, 'agent/.claude/projects'), codex: path.join(root, 'agent/.calvin/codex'),
+ home: path.join(root, 'volume'), clones: clonesHost, wt: path.join(root, 'people/pat/wt/C1-1.1'), workspace: forkHost,
+ };
+ for (const d of [p.home, p.wt]) mkdirSync(d, { recursive: true });
+ // The fork: two worktrees and an uncommitted file; .fork.json names a third that is not there.
+ const info = { branch: 'sp/C1-1-1', from: 'origin/main', base: 'abc' };
+ mkdirSync(forkHost, { recursive: true });
+ writeFileSync(path.join(forkHost, '.fork.json'), JSON.stringify({ repos: { hello: info, other: info, gone: info } }));
+ for (const [repo, name] of [['hello', 'C1-1.1'], ['other', 'C1-1.12']]) {
+ const admin = path.join(clonesHost, repo, '.git/worktrees', name);
+ mkdirSync(admin, { recursive: true });
+ writeFileSync(path.join(admin, 'gitdir'), `${forkHost}/${repo}/.git\n`);
+ writeFileSync(path.join(admin, 'commondir'), '../..\n');
+ writeFileSync(path.join(admin, 'HEAD'), 'ref: refs/heads/sp/C1-1-1\n');
+ mkdirSync(path.join(forkHost, repo), { recursive: true });
+ writeFileSync(path.join(forkHost, repo, '.git'), `gitdir: ${admin}\n`);
+ }
+ writeFileSync(path.join(forkHost, 'hello/wip.txt'), 'uncommitted\n');
+ // The transcript, a subagent's beside it, and a file that is not text.
+ const project = path.join(p.claudeProjects, script.claudeSlug(forkHost));
+ mkdirSync(path.join(project, SID, 'subagents'), { recursive: true });
+ const line = (o: object) => `${JSON.stringify(o)}\n`;
+ writeFileSync(path.join(project, `${SID}.jsonl`),
+ line({ sessionId: SID, cwd: forkHost, message: { content: 'marker-turn-1' } }) +
+ line({ sessionId: SID, tool: { file_path: `${forkHost}/hello/wip.txt`, cd: `${clonesHost}/hello/.git`, sibling: `${forkHost}2/x` } }));
+ writeFileSync(path.join(project, SID, 'subagents/agent-1.jsonl'), line({ sessionId: SID, cwd: `${forkHost}/hello` }));
+ writeFileSync(path.join(project, 'blob.bin'), forkHost);
+ // Another thread's transcript is not copied.
+ mkdirSync(path.join(p.claudeProjects, script.claudeSlug(`${forkHost}2`)), { recursive: true });
+ mkdirSync(path.join(p.codex, CODEX, 'sessions'), { recursive: true });
+ writeFileSync(path.join(p.codex, CODEX, 'sessions/rollout.jsonl'), `{"cwd":"${forkHost}"}\n`);
+ return { root, forkHost, clonesHost, p, o: { forkHost, clonesHost, harness: 'claude', sdkSessionId: SID, codexName: CODEX } };
+}
+
+describe('legacy-migrate.mjs', () => {
+ it('copies the transcript to -workspace with its paths rewritten and its session id kept', () => {
+ const f = fixture();
+ const out = script.migrate(f.p, f.o);
+ expect(out.claude).toBe(true);
+ const into = path.join(f.p.home, '.claude/projects/-workspace');
+ const lines = readFileSync(path.join(into, `${SID}.jsonl`), 'utf8').trim().split('\n').map((l) => JSON.parse(l));
+ expect(lines[0]).toEqual({ sessionId: SID, cwd: '/workspace', message: { content: 'marker-turn-1' } });
+ expect(lines[1].tool).toEqual({ file_path: '/workspace/hello/wip.txt', cd: '/clones/hello/.git', sibling: `${f.forkHost}2/x` });
+ expect(JSON.parse(readFileSync(path.join(into, SID, 'subagents/agent-1.jsonl'), 'utf8'))).toEqual({ sessionId: SID, cwd: '/workspace/hello' });
+ expect(readFileSync(path.join(into, 'blob.bin'), 'utf8')).toBe(f.forkHost); // not text: as it was
+ expect(readFileSync(path.join(f.p.claudeProjects, script.claudeSlug(f.forkHost), `${SID}.jsonl`), 'utf8')).toContain(f.forkHost); // the source is untouched
+ });
+
+ it('copies the Codex home as it is', () => {
+ const f = fixture();
+ expect(script.migrate(f.p, { ...f.o, harness: 'codex' }).codex).toBe(true);
+ expect(readFileSync(path.join(f.p.home, '.calvin/codex', CODEX, 'sessions/rollout.jsonl'), 'utf8')).toBe(`{"cwd":"${f.forkHost}"}\n`);
+ });
+
+ it('re-points each worktree at container paths, moves its admin directory into the registry, and leaves commondir', () => {
+ const f = fixture();
+ const out = script.migrate(f.p, f.o);
+ expect(Object.keys(out.repos)).toEqual(['hello', 'other']);
+ expect(out.skipped).toEqual([{ repo: 'gone', why: 'its worktree is not in the fork' }]);
+ for (const [repo, name] of [['hello', 'C1-1.1'], ['other', 'C1-1.12']]) {
+ expect(readFileSync(path.join(f.forkHost, repo, '.git'), 'utf8')).toBe(`gitdir: /clones/${repo}/.git/worktrees/${repo}\n`);
+ const admin = path.join(f.p.wt, repo, repo);
+ expect(readFileSync(path.join(admin, 'gitdir'), 'utf8')).toBe(`/workspace/${repo}/.git\n`);
+ expect(readFileSync(path.join(admin, 'commondir'), 'utf8')).toBe('../..\n');
+ expect(readFileSync(path.join(admin, 'HEAD'), 'utf8')).toBe('ref: refs/heads/sp/C1-1-1\n');
+ expect(existsSync(path.join(f.clonesHost, repo, '.git/worktrees', name))).toBe(false);
+ }
+ expect(readFileSync(path.join(f.forkHost, 'hello/wip.txt'), 'utf8')).toBe('uncommitted\n');
+ // Again: nothing left to do, the same answer.
+ expect(script.migrate(f.p, f.o).repos).toEqual(out.repos);
+ });
+
+ it("leaves out a worktree whose admin directory is another fork's", () => {
+ const f = fixture();
+ writeFileSync(path.join(f.clonesHost, 'other/.git/worktrees/C1-1.12/gitdir'), '/elsewhere/other/.git\n');
+ const out = script.migrate(f.p, f.o);
+ expect(Object.keys(out.repos)).toEqual(['hello']);
+ expect(out.skipped).toContainEqual({ repo: 'other', why: "the clone's C1-1.12 belongs to /elsewhere/other/.git" });
+ expect(readFileSync(path.join(f.forkHost, 'other/.git'), 'utf8')).toContain(f.clonesHost);
+ });
+
+ it('fails, changing nothing of the person\'s, when the transcript to resume or .fork.json is missing', () => {
+ const f = fixture();
+ expect(() => script.migrate(f.p, { ...f.o, sdkSessionId: 'nope' })).toThrow(/no transcript nope.jsonl/);
+ expect(readFileSync(path.join(f.forkHost, 'hello/.git'), 'utf8')).toContain(f.clonesHost);
+ const g = fixture();
+ writeFileSync(path.join(g.forkHost, '.fork.json'), '');
+ expect(() => script.migrate(g.p, g.o)).toThrow();
+ });
+
+ it('rewrites only whole path names', () => {
+ expect(script.rewritePaths('"/a/s/C1" "/a/s/C1/x" "/a/s/C1.2" "/a/ws/r" "/a/wsx"', '/a/s/C1', '/a/ws')).toBe('"/workspace" "/workspace/x" "/a/s/C1.2" "/clones/r" "/a/wsx"');
+ });
+});
+
+const owner = { dir: 'pat', gitName: 'Pat', gitEmail: '[email protected]' };
+const spec: SessionSpec = { key: 'C1:1.1', kind: 'thread', owner, title: 't', mode: 'default', sdkSessionId: SID, forkPath: '/data/people/pat/sessions/C1-1.1' };
+
+function host(o: { there?: boolean; helper?: () => Promise<string>; mv?: () => Promise<string> } = {}) {
+ const calls: string[] = [];
+ const records = sandboxRecords(mkdtempSync(path.join(tmpdir(), 'records-')));
+ const as: AsRunner = {
+ podman: async (args) => (calls.push(`podman ${args.slice(0, 3).join(' ')}`), ''),
+ run: async (argv) => {
+ calls.push(argv[0] === '/usr/bin/systemd-run' ? `helper record=${records.get('00112233445566aa') ? 'yes' : 'no'}` : argv.join(' '));
+ if (argv[0] === '/usr/bin/systemd-run') return o.helper ? o.helper() : `noise\n${JSON.stringify({ repos: { hello: { branch: 'b' } }, claude: true, codex: false, skipped: [] })}\n`;
+ if (argv[0] === '/bin/mv' && o.mv) return o.mv();
+ return '';
+ },
+ settled: async () => void calls.push('settled'),
+ } as AsRunner;
+ const migrate = legacyMigration({
+ as, records, root: '/opt/slack-presence/releases/abc', image: 'img', helperRun: '/run/sp/helper', runRoot: (id) => `/run/sp/sandbox/${id}` as never,
+ agentHome: '/data/home/agent', there: () => o.there ?? true, newId: () => '00112233445566aa',
+ mounts: { people: '/data/people', workspace: (r) => `/data/people/${r.person}/sessions/${r.key.replace(':', '-')}`, clones: (p) => `/data/people/${p}/ws` },
+ });
+ return { calls, records, migrate };
+}
+
+describe('legacyMigration', () => {
+ it('a thread with no fork is not touched', async () => {
+ const h = host({ there: false });
+ expect(await h.migrate(spec)).toBeUndefined();
+ expect(h.calls).toEqual([]);
+ });
+
+ it('makes the home volume first and writes the record last, with the repositories the script re-pointed', async () => {
+ const h = host();
+ const r = await h.migrate(spec);
+ expect(r).toMatchObject({ id: '00112233445566aa', person: 'pat', key: 'C1:1.1', repos: { hello: { branch: 'b' } } });
+ expect(h.records.find('pat', 'C1:1.1')).toEqual(r);
+ expect(h.calls[0]).toMatch(/^podman volume create/);
+ expect(h.calls).toContain('helper record=no');
+ expect(h.calls.indexOf('settled')).toBeLessThan(h.calls.indexOf('helper record=no'));
+ });
+
+ it('on a failure removes the volume, sets the fork aside and starts fresh, with no record', async () => {
+ const h = host({ helper: async () => Promise.reject(new Error('exit 1: legacy-migrate: no transcript')) });
+ expect(await h.migrate(spec)).toBeUndefined();
+ expect(h.records.find('pat', 'C1:1.1')).toBeUndefined();
+ expect(h.calls.slice(-3)).toEqual([
+ 'podman volume rm --force',
+ '/bin/mkdir -p -- /data/people/pat/sessions.pre-sandbox',
+ '/bin/mv --backup=numbered -T -- /data/people/pat/sessions/C1-1.1 /data/people/pat/sessions.pre-sandbox/C1-1.1',
+ ]);
+ });
+
+ it('fails the start when the fork cannot be set aside either', async () => {
+ const h = host({ helper: async () => 'not json', mv: async () => Promise.reject(new Error('mv: busy')) });
+ await expect(h.migrate(spec)).rejects.toThrow(/mv: busy/);
+ });
+
+ it("runs the script in a helper container with the legacy homes read-only, the new home, the registry and the fork", () => {
+ const argv = migrateArgv({
+ root: '/opt/r', image: 'img', helperRun: '/run/h', people: '/data/people', person: 'pat', id: 'ff', fork: '/data/people/pat/sessions/C1-1.1',
+ clones: '/data/people/pat/ws', wt: '/data/people/pat/wt/C1-1.1', claudeProjects: '/home/a/.claude/projects', harness: 'claude', sdkSessionId: SID, codexName: CODEX,
+ });
+ const s = argv.join(' ');
+ expect(s).toContain('--userns=keep-id:uid=1500,gid=1500');
+ expect(s).toContain('-v /home/a/.claude/projects:/legacy/claude-projects:ro');
+ expect(s).not.toContain('/legacy/codex');
+ expect(s).toContain('-v /data/people/pat/wt/C1-1.1:/wt -v /data/people/pat/sessions/C1-1.1:/workspace');
+ expect(argv.slice(-6)).toEqual(['/opt/r/bin/legacy-migrate.mjs', '/data/people/pat/sessions/C1-1.1', '/data/people/pat/ws', 'claude', SID, CODEX]);
+ });
+
+ it('takes the last line of the output as the result', () => {
+ expect(parseResult('x\n{"repos":{},"claude":false,"codex":false,"skipped":[]}\n').repos).toEqual({});
+ expect(() => parseResult('{"repos":null}')).toThrow();
+ });
+});
diff --git a/computer/src/host/legacy-migration/migrate.ts b/computer/src/host/legacy-migration/migrate.ts
new file mode 100644
index 00000000..a180ca8c
--- /dev/null
+++ b/computer/src/host/legacy-migration/migrate.ts
@@ -0,0 +1,142 @@
+// ONE-TIME systemd->podman migration (work 103). Delete together with the systemd launch path in step 11.
+//
+// A thread made under the `systemd` launch, reaching a `podman` host: it has
+// a fork in `<people>/<p>/sessions/<key>` and no sandbox record. Its first
+// start on the `podman` host (sandbox/start.ts, in the thread's turn) asks
+// `migrateLegacy` before it takes the thread for a new one. That gives it a
+// home volume holding its transcript, its worktrees re-pointed at container
+// paths, and a record, so the start resumes it under the session id the
+// gateway sent.
+//
+// Invariants:
+// - It runs only on a record miss, in the thread's turn (thread-lock.ts), and
+// only for a thread whose fork is there: a new thread is not touched.
+// - The home volume is made first, so that the start finds it and resumes
+// with `sdkSessionId` (start.ts keeps it only for a home that was there).
+// - The files move in one helper container (bin/legacy-migrate.mjs) as uid
+// 1500 under `--userns=keep-id:uid=1500`: the host itself reads and writes
+// nothing of the person's.
+// - The record is written last, with the repositories `.fork.json` named and
+// the script re-pointed. A thread with a record is never migrated again.
+// - Any failure leaves the thread as a new one: its volume removed, its fork
+// moved to `<people>/<p>/sessions.pre-sandbox/<key>` (an earlier one there
+// kept as `<key>.~N~`), and the start goes on with no record and no
+// transcript. When the fork cannot be moved either, the start fails.
+
+import { randomBytes } from 'node:crypto';
+import path from 'node:path';
+import { codexHome } from '../../codex-home.js';
+import type { RunRoot } from '../../ipc.js';
+import { log } from '../../log.js';
+import type { SessionSpec } from '../../protocol.js';
+import { safeKey } from '../../workspaces/clones.js';
+import type { Mounts } from '../sandbox/mounts.js';
+import { type AsRunner, PODMAN } from '../sandbox/podman.js';
+import { HELPER_SCOPE, helperArgs, homeArgs, volumeName } from '../sandbox/podman-args.js';
+import type { Records, SandboxRecord } from '../sandbox/records.js';
+
+/** The script's whole run, Podman's own bound; the host waits a little longer. */
+export const MIGRATE_SECONDS = 300;
+const STEP_MS = 60_000;
+
+export interface LegacyDeps {
+ as: AsRunner;
+ records: Records;
+ mounts: Pick<Mounts, 'people' | 'workspace' | 'clones'>;
+ /** The host's release (bin/legacy-migrate.mjs), the image, the helpers' run directory. */
+ root: string;
+ image: string;
+ helperRun: string;
+ runRoot(id: string): RunRoot;
+ /** The runners' user's HOME, where the `systemd` runners kept ~/.claude and ~/.calvin. */
+ agentHome: string;
+ /** True when the thread has a fork on this host (workspace.ts `there`). */
+ there(person: string, key: string): boolean;
+ newId?: () => string;
+}
+
+export interface LegacyResult {
+ repos: NonNullable<SandboxRecord['repos']>;
+ claude: boolean;
+ codex: boolean;
+ skipped: { repo: string; why: string }[];
+}
+
+/** The argv, for the runners' user, of the helper container that migrates one thread. */
+export function migrateArgv(o: {
+ root: string; image: string; helperRun: string; people: string; person: string; id: string; fork: string; clones: string; wt: string;
+ claudeProjects?: string; codex?: string; harness: string; sdkSessionId?: string; codexName: string;
+}): string[] {
+ const binds = [
+ ...(o.claudeProjects ? [{ src: o.claudeProjects, dst: '/legacy/claude-projects', ro: true }] : []),
+ ...(o.codex ? [{ src: o.codex, dst: '/legacy/codex', ro: true }] : []),
+ { src: volumeName(o.id), dst: '/home/agent' },
+ { src: o.wt, dst: '/wt' },
+ { src: o.fork, dst: '/workspace' },
+ ];
+ const script = path.join(o.root, 'bin', 'legacy-migrate.mjs');
+ return [
+ ...HELPER_SCOPE, PODMAN,
+ ...helperArgs({ person: o.person, people: o.people, run: o.helperRun, image: o.image, network: false, timeoutS: MIGRATE_SECONDS, binds,
+ sh: ['-c', 'exec node "$0" "$@"', script, o.fork, o.clones, o.harness, o.sdkSessionId || '-', o.codexName] }),
+ ];
+}
+
+/** The last line of the script's output, as its result; throws when it is not one. */
+export function parseResult(out: string): LegacyResult {
+ const line = out.trim().split('\n').pop() ?? '';
+ const r = JSON.parse(line) as LegacyResult;
+ if (!r || typeof r.repos !== 'object' || r.repos === null || !Array.isArray(r.skipped)) throw new Error(`legacy-migrate printed ${line.slice(0, 200)}`);
+ return r;
+}
+
+export function legacyMigration(d: LegacyDeps) {
+ const newId = d.newId ?? (() => randomBytes(8).toString('hex'));
+ const exists = (p: string) => d.as.run(['/usr/bin/test', '-d', p], { timeoutMs: STEP_MS }).then(() => true, () => false);
+
+ /** The fork out of the way, so that the thread starts fresh; rejects when it could not be moved. */
+ async function setAside(person: string, fork: string) {
+ const aside = path.join(d.mounts.people, person, 'sessions.pre-sandbox');
+ await d.as.run(['/bin/mkdir', '-p', '--', aside], { timeoutMs: STEP_MS });
+ await d.as.run(['/bin/mv', '--backup=numbered', '-T', '--', fork, path.join(aside, path.basename(fork))], { timeoutMs: STEP_MS });
+ }
+
+ /**
+ * The sandbox record of `spec`'s thread made from its `systemd` fork, or undefined: there is no fork (a new thread), or the
+ * migration failed and the fork was set aside (a new thread now). Call it in the thread's turn, on a record miss.
+ */
+ return async function migrateLegacy(spec: SessionSpec): Promise<SandboxRecord | undefined> {
+ const person = spec.owner.dir;
+ const { key } = spec;
+ if (!d.there(person, key)) return undefined;
+ const fork = d.mounts.workspace({ person, key });
+ const id = newId();
+ const t0 = Date.now();
+ try {
+ await d.as.podman(homeArgs(id, d.runRoot(id)), { timeoutMs: STEP_MS, repeatable: true });
+ const wt = path.join(d.mounts.people, person, 'wt', safeKey(key));
+ const clones = d.mounts.clones(person);
+ await d.as.run(['/bin/mkdir', '-p', '--', wt, clones], { timeoutMs: STEP_MS });
+ const claudeProjects = path.join(d.agentHome, '.claude', 'projects');
+ const codex = path.join(d.agentHome, '.calvin', 'codex');
+ const argv = migrateArgv({
+ root: d.root, image: d.image, helperRun: d.helperRun, people: d.mounts.people, person, id, fork, clones, wt,
+ claudeProjects: (await exists(claudeProjects)) ? claudeProjects : undefined, codex: (await exists(codex)) ? codex : undefined,
+ harness: spec.harness ?? 'claude', sdkSessionId: spec.sdkSessionId, codexName: path.basename(codexHome('/', key)),
+ });
+ await d.as.settled();
+ const r = parseResult(await d.as.run(argv, { timeoutMs: (MIGRATE_SECONDS + 10) * 1000 }));
+ const now = new Date().toISOString();
+ const record: SandboxRecord = { id, person, key, createdAt: now, usedAt: now, repos: r.repos };
+ d.records.write(record); // last: from here the thread is a sandboxed one
+ for (const s of r.skipped) log.warn(`legacy migration: ${s.repo} left out of ${key}: ${s.why}`);
+ log.info(`legacy migration: ${key} (${person}) is sandbox ${id} in ${Date.now() - t0} ms: ${Object.keys(r.repos).length} repos, transcript ${r.claude ? 'copied' : 'none'}, codex ${r.codex ? 'copied' : 'none'}`);
+ return record;
+ } catch (e) {
+ log.warn(`legacy migration: ${key} (${person}) not migrated, starting fresh with its fork set aside: ${(e as Error)?.message ?? e}`);
+ await d.as.podman(['volume', 'rm', '--force', volumeName(id)], { timeoutMs: STEP_MS, repeatable: true }).catch(() => {});
+ await setAside(person, fork);
+ return undefined;
+ }
+ };
+}
diff --git a/computer/src/host/main.ts b/computer/src/host/main.ts
index b879d7da..3c3521a4 100644
--- a/computer/src/host/main.ts
+++ b/computer/src/host/main.ts
@@ -91,6 +91,7 @@ import { callRunner as call } from './runner-call.js';
import { apiHost, type StartOptions } from './api-host.js';
import { wireFor } from './api-wire.js';
import { sandboxHost, sandboxWorkspace } from './sandbox/host.js';
+import { legacyDrain } from './legacy-migration/drain.js'; // ONE-TIME systemd->podman migration (work 103): delete in step 11
const env = process.env;
const IDENTITY_FILE = identityFile(HOST_DATA);
@@ -138,7 +139,10 @@ const pool = new Pool<Runner>({
});
/** Every connected runner: the sessions' and the spares. */
const allRunners = () => [...runners.values(), ...pool.spares];
-const fillPool = () => !stopping && pool.fill(subs.canSpare());
+// ONE-TIME systemd->podman migration (work 103): delete in step 11. SIGUSR2 (provision.sh): drain, exit, come back as `podman`.
+const drain = LAUNCH === 'systemd' ? legacyDrain({ runners: allRunners, send, exit: () => void shutdown() }) : undefined;
+if (drain) process.on('SIGUSR2', () => drain.start());
+const fillPool = () => !stopping && !drain?.draining && pool.fill(subs.canSpare());
function exitRunner(sock: net.Socket) {
send(sock, { t: 'exit' } satisfies HostToRunner);
sock.end();
@@ -251,6 +255,7 @@ async function onRunner(r: Runner, m: RunnerToHost) {
}
function ensureRunner(spec: SessionSpec, f: Fields, first?: HostCredentials): Promise<Runner> {
+ if (drain?.draining) return drain.held(); // ONE-TIME systemd->podman migration (work 103): delete in step 11
const live = runners.get(spec.key);
if (live) return Promise.resolve(live);
let p = starting.get(spec.key);
diff --git a/computer/src/host/sandbox/host.ts b/computer/src/host/sandbox/host.ts
index eedebadc..90a97295 100644
--- a/computer/src/host/sandbox/host.ts
+++ b/computer/src/host/sandbox/host.ts
@@ -38,6 +38,7 @@ import { runnerVars } from '../../runner-env.js';
import type { Telemetry } from '../../telemetry/emitter.js';
import { definitionFile, forkDir, loadDefinition, repoSlug, useForkKeeper, useScripts, workspacesEnabled } from '../../workspaces/index.js';
import { launch } from '../launch.js';
+import { legacyMigration } from '../legacy-migration/migrate.js'; // ONE-TIME systemd->podman migration (work 103): delete in step 11
import { dialSocket } from '../runner-sockets.js';
import { runnerUser } from '../runner-user.js';
import { sandboxArtifacts } from './artifacts.js';
@@ -136,7 +137,8 @@ export function sandboxHost(d: SandboxHostDeps) {
return {
stop: all.stop,
spares,
- starts: sandboxStarts({ tm: d.tm, records, locks, containers: all, runRoot, image, abi, version: d.version, mint: d.mint, workspace, workspaces: workspacesEnabled, dial }),
+ starts: sandboxStarts({ tm: d.tm, records, locks, containers: all, runRoot, image, abi, version: d.version, mint: d.mint, workspace, workspaces: workspacesEnabled, dial,
+ legacy: legacyMigration({ as, records, mounts: mnt, root: d.root, image, helperRun, runRoot, agentHome: user.env.HOME, there: workspace.there }) }), // ONE-TIME systemd->podman migration (work 103): delete in step 11
/** Host restart: the running containers taken back, by id (sweep.ts). */
reconcile: sweep.reconcile,
/** One sweep of what belongs to no thread; never rejects. */
diff --git a/computer/src/host/sandbox/spares.test.ts b/computer/src/host/sandbox/spares.test.ts
index 7e1a96de..97534be4 100644
--- a/computer/src/host/sandbox/spares.test.ts
+++ b/computer/src/host/sandbox/spares.test.ts
@@ -57,6 +57,7 @@ function rig(o: { settleMs?: number; deferMs?: number; fail?: Partial<Record<'cr
mint: async (s, id, run) => (await step(`mint ${id} ${run} sdk=${s.sdkSessionId ?? '-'} fork=${s.forkPath ?? '-'}`, 0), o.api ? ({ journal: '/data/journals/s1/journal.jsonl', token: 'tok' } as RunnerApi) : undefined),
workspace: {
repos: () => ['hello'],
+ there: (_person, key) => key === 'C9:legacy', // ONE-TIME systemd->podman migration (work 103): a `systemd` fork
dirs: async (r, names) => void log.push(`dirs ${r.key} ${names.join(',')}`),
binds: (r, names, journal) => [{ src: `ws:${r.key}`, dst: '/workspace' }, ...names.map((n) => ({ src: n, dst: `/clones/${n}` })), ...(journal ? [{ src: journal, dst: journal }] : [])],
mount: (id, pid, person, b) => step(`mount ${id} ${pid} ${person} ${b.map((x) => x.dst).join(' ')}`, undefined),
@@ -144,6 +145,7 @@ describe('a spare container', () => {
await expect(t.bind(id, { ...spec, key: 'C1:2.2' }, {})).rejects.toThrow(/not a spare/);
expect(t.known(spec)).toBe(true);
expect(t.known({ ...spec, key: 'C1:2.2' })).toBe(false);
+ expect(t.known({ ...spec, key: 'C9:legacy' })).toBe(true); // ONE-TIME systemd->podman migration (work 103): a fork with no record takes no spare
expect(t.records.all().map((r) => r.id)).toEqual([id]);
});
diff --git a/computer/src/host/sandbox/spares.ts b/computer/src/host/sandbox/spares.ts
index 7f8c300a..d5aa6970 100644
--- a/computer/src/host/sandbox/spares.ts
+++ b/computer/src/host/sandbox/spares.ts
@@ -95,7 +95,7 @@ export interface SpareDeps {
version: string;
/** The session's journal, socket (below `run`) and token for this runner; undefined off the API. */
mint(spec: SessionSpec, runnerId: string, run: RunRoot): Promise<RunnerApi | undefined>;
- workspace: Pick<SandboxWorkspace, 'repos' | 'dirs' | 'binds' | 'mount' | 'prepare'>;
+ workspace: Pick<SandboxWorkspace, 'repos' | 'there' | 'dirs' | 'binds' | 'mount' | 'prepare'>;
/** Connect to a runner's socket; undefined when nothing answers. */
dial?: (socket: string) => Promise<net.Socket | undefined>;
/** How long after a thread's start no spare is made while the pool has one; SETTLE_MS unless given. */
@@ -304,7 +304,8 @@ export function sandboxSpares(d: SpareDeps) {
/** `fn` in the thread's turn: a claim, from the look for its record to the spare claimed or discarded. */
turn: <T>(spec: SessionSpec, fn: () => Promise<T>): Promise<T> => d.locks.run(spec.owner.dir, spec.key, fn),
/** True when the thread has a record: it resumes, and never takes a spare. */
- known: (spec: SessionSpec) => !!d.records.find(spec.owner.dir, spec.key),
+ // ONE-TIME systemd->podman migration (work 103): a `systemd` fork with no record is migrated by its start, never given a spare. Delete `there` in step 11.
+ known: (spec: SessionSpec) => !!d.records.find(spec.owner.dir, spec.key) || d.workspace.there(spec.owner.dir, spec.key),
/** A spare's connection closed (it exited, was evicted, the host told it to go): Remove. Nothing for a container that is a thread's. */
gone: (id: string): Promise<void> => (mine.has(id) || leaving.has(id) ? drop(id) : Promise.resolve()),
/** A spare that was taken and not claimed: Remove; its record, if written, stays. */
diff --git a/computer/src/host/sandbox/start.test.ts b/computer/src/host/sandbox/start.test.ts
index 193130f2..65aede27 100644
--- a/computer/src/host/sandbox/start.test.ts
+++ b/computer/src/host/sandbox/start.test.ts
@@ -19,7 +19,8 @@ const spec: SessionSpec = { key: 'C1:1.1', kind: 'thread', owner, title: 't', mo
const sock = { destroyed: false } as net.Socket;
function rig(o: { have?: ContainerInfo[]; homes?: string[]; fail?: Partial<Record<'create' | 'up' | 'inventory' | 'mount' | 'prepare', Error>>; stale?: boolean;
- dial?: () => Promise<net.Socket | undefined>; definition?: boolean; clones?: string[]; api?: boolean; unread?: string; there?: boolean; stays?: boolean } = {}) {
+ dial?: () => Promise<net.Socket | undefined>; definition?: boolean; clones?: string[]; api?: boolean; unread?: string; there?: boolean; stays?: boolean;
+ legacy?: (records: ReturnType<typeof sandboxRecords>) => SandboxStartDeps['legacy'] } = {}) { // legacy: ONE-TIME systemd->podman migration (work 103)
const log: string[] = [];
const ups: RunnerSpec[] = [];
const sent: TelemetryEvent[] = [];
@@ -69,6 +70,7 @@ function rig(o: { have?: ContainerInfo[]; homes?: string[]; fail?: Partial<Recor
},
},
dial: o.dial ?? (async () => sock),
+ legacy: o.legacy?.(records), // ONE-TIME systemd->podman migration (work 103): delete in step 11
};
const events = async () => (await tm.flush(), sent);
return { ...sandboxStarts(d), log, ups, records, locks, events, tm };
@@ -97,6 +99,27 @@ describe('sandbox start', () => {
expect(t.tm.dropped).toEqual({}); // every key is in the catalog
});
+ // ONE-TIME systemd->podman migration (work 103): delete in step 11.
+ it('a `systemd` thread with no record is migrated in its turn and resumes under the session id the gateway sent', async () => {
+ const id = '00112233445566aa';
+ const asked: string[] = [];
+ const t = rig({ homes: [id], legacy: (records) => async (s) => {
+ asked.push(s.key);
+ const r = { id, person: 'pat', key: s.key, createdAt: '', usedAt: '', repos: { hello: { branch: 'sp/C1-1-1', from: 'origin/main', base: 'abc' } } };
+ records.write(r);
+ return r;
+ } });
+ const s = await t.start({ ...spec, sdkSessionId: 'sdk-old', forkPath: '/data/people/pat/sessions/C1-1-1' }, {});
+ expect(asked).toEqual(['C1:1.1']);
+ expect(s.record.id).toBe(id);
+ expect(s.resumed).toBe(true);
+ expect(t.log).toEqual(['dirs C1:1.1 hello', 'inventory', `mint ${id} /run/sp/sandbox/${id} sdk=sdk-old`, `recreate ${id}`, `up ${id} C1:1.1`, `mount ${id} 5 pat /workspace /clones/hello`]);
+ expect(t.ups[0].session).toMatchObject({ sdkSessionId: 'sdk-old', forkPath: '/workspace' });
+ // Its record found from now on: not asked again.
+ await t.start({ ...spec, sdkSessionId: 'sdk-old' }, {});
+ expect(asked).toEqual(['C1:1.1']);
+ });
+
it("a thread with a record resumes under the record's id, with its transcript, on its container", async () => {
const t = rig();
const first = await t.start(spec, {});
diff --git a/computer/src/host/sandbox/start.ts b/computer/src/host/sandbox/start.ts
index 56c30b63..c966a68c 100644
--- a/computer/src/host/sandbox/start.ts
+++ b/computer/src/host/sandbox/start.ts
@@ -85,6 +85,8 @@ export interface SandboxStartDeps {
workspaces(): boolean;
/** Connect to a runner's socket; undefined when nothing answers. */
dial?: (socket: string) => Promise<net.Socket | undefined>;
+ /** ONE-TIME systemd->podman migration (work 103, legacy-migration/): a record made from a `systemd` fork on a miss. Delete in step 11. */
+ legacy?: (spec: SessionSpec) => Promise<SandboxRecord | undefined>;
}
export interface Started {
@@ -126,10 +128,11 @@ export function sandboxStarts(d: SandboxStartDeps) {
async function startNow(spec: SessionSpec, f: Dimensions): Promise<Started> {
const now = new Date().toISOString();
- const found = d.records.find(spec.owner.dir, spec.key);
+ let found = d.records.find(spec.owner.dir, spec.key);
const unread = found ? [] : d.records.unread();
if (unread.length && d.workspace.there(spec.owner.dir, spec.key))
throw new Error(`this thread has files but no sandbox record, and the record ${unread.map((id) => `${id}.json`).join(', ')} did not load; nothing was started. Repair that file in the host's state/sandboxes, or remove it for a new sandbox`);
+ found ??= await d.legacy?.(spec); // ONE-TIME systemd->podman migration (work 103): delete in step 11
const { sdkSessionId, forkPath: _fork, ...fresh } = spec;
let record: SandboxRecord = found ? { ...found, usedAt: now } : { id: randomBytes(8).toString('hex'), person: spec.owner.dir, key: spec.key, createdAt: now, usedAt: now };
d.records.write(record);