Skip to content

An open-source, faster Devin alternative

TypeScript

computer: workspace git as scripts (work 103, S2) (#1035)

opencomputer-app[bot]f3a792a60d6e
diff --git a/computer/README.md b/computer/README.md
index 945fa472..63fe7602 100644
--- a/computer/README.md
+++ b/computer/README.md
@@ -582,7 +582,7 @@ src/
workspace.ts scratch workdirs and git diff (one-machine mode)
dev/ fakes and checks
scripts/ `npm run check` helpers: file-size ratchet, import boundaries
-bin/ git credential helper and gh shim for hosts
+bin/ git credential helper and gh shim for hosts; ws-*.sh, the git sequences of src/workspaces
definitions/ workspace definitions (computer.json + its root AGENTS.md)
deploy/ gateway image entrypoint, VM provisioning, runbook
```
diff --git a/computer/bin/ws-add.sh b/computer/bin/ws-add.sh
new file mode 100755
index 00000000..65c408b8
--- /dev/null
+++ b/computer/bin/ws-add.sh
@@ -0,0 +1,80 @@
+#!/bin/sh
+# ws-add.sh <clones> <workspace> <branch> <fetch 0/1> <repo[=base]>…
+#
+# Give the workspace a git worktree of each repository, <workspace>/<repo>, on
+# <branch> (forkRepo in src/workspaces/fork.ts): the branch if the clone has
+# it, else a new one from origin/<base>, not tracking it (the session pushes
+# its own branch). <base> is the branch forks start from; not given, origin/HEAD
+# (ws-lib.sh). With <fetch> 1, origin/<base> is fetched first; a fetch that
+# fails is reported and the worktree is made from what the clone has.
+#
+# A destination that is already this clone's worktree is left as it is; one
+# that is anything else is an error and is not touched. A worktree that could
+# not be made completely is removed.
+#
+# Prints `<repo> ok <branch> <base> <HEAD> <fetch error>` (the last field empty
+# unless a fetch failed), or `<repo> failed <message>`.
+set -eu
+. "$(dirname "$0")/ws-lib.sh"
+[ $# -ge 4 ] || { echo "usage: ws-add.sh <clones> <workspace> <branch> <fetch 0/1> <repo[=base]>…" >&2; exit 2; }
+clones=$1 workspace=$2 branch=$3 fetch=$4
+shift 4
+
+adding=
+ws_cleanup() {
+ [ -n "$adding" ] || return 0
+ rm -rf -- "$adding"
+ (cd "$clone" && git worktree prune) >/dev/null 2>&1 || :
+}
+
+# True when <dir> is a worktree of the clone: both name the same git directory.
+is_worktree_of() {
+ common=$(ws_q "$1" git rev-parse --git-common-dir) || return 1
+ [ -n "$common" ] || return 1
+ a=$(cd "$1" && cd "$common" && pwd -P) || return 1
+ b2=$(cd "$2/.git" && pwd -P) || return 1
+ [ "$a" = "$b2" ]
+}
+
+add() {
+ repo=${1%%=*}
+ base=
+ case $1 in *=*) base=${1#*=} ;; esac
+ clone=$clones/$repo
+ dest=$workspace/$repo
+ if [ -z "$base" ]; then
+ ws_base "$clone" || { ws_failed "$repo" "$(ws_why 'no default branch')"; return 0; }
+ base=$ws_b
+ fi
+ fetch_error=
+ if [ "$fetch" = 1 ]; then
+ ws_in "$clone" git fetch --quiet --no-tags origin "$base" >/dev/null ||
+ fetch_error=$(ws_why "Command failed: git fetch --quiet --no-tags origin $base")
+ fi
+ if [ ! -e "$dest" ]; then
+ # A worktree whose directory the session deleted is still registered; forget it so it can be added again.
+ ws_q "$clone" git worktree prune >/dev/null || { ws_failed "$repo" "$(ws_why 'Command failed: git worktree prune')"; return 0; }
+ adding=$dest
+ # On a partial clone this downloads the checkout's file contents.
+ if ws_q "$clone" git rev-parse --verify --quiet "refs/heads/$branch" >/dev/null; then
+ ws_in "$clone" git worktree add --quiet "$dest" "$branch" >/dev/null && added=1 || added=0
+ else
+ ws_in "$clone" git worktree add --quiet --no-track -b "$branch" "$dest" "origin/$base" >/dev/null && added=1 || added=0
+ fi
+ if [ "$added" = 0 ]; then
+ why=$(ws_why "Command failed: git worktree add --quiet $dest")
+ ws_cleanup
+ adding=
+ ws_failed "$repo" "$why"
+ return 0
+ fi
+ adding=
+ elif ! is_worktree_of "$dest" "$clone"; then
+ ws_failed "$repo" "./$(basename "$dest") exists but is not a worktree of this workspace's $repo; move it away and check out again"
+ return 0
+ fi
+ head=$(ws_q "$dest" git rev-parse HEAD) || { ws_failed "$repo" "$(ws_why 'Command failed: git rev-parse HEAD')"; return 0; }
+ ws_ok "$repo" "$branch" "$base" "$head" "$fetch_error"
+}
+
+for r in "$@"; do add "$r"; done
diff --git a/computer/bin/ws-clone.sh b/computer/bin/ws-clone.sh
new file mode 100755
index 00000000..35922798
--- /dev/null
+++ b/computer/bin/ws-clone.sh
@@ -0,0 +1,46 @@
+#!/bin/sh
+# ws-clone.sh <clones> <repo> <url> <filter> <branch> <setup>…
+#
+# Clone <url> as <clones>/<repo> (cloneRepo in src/workspaces/clones.ts): into
+# <repo>.cloning, renamed when complete, so a clone that exists is whole. Then
+# each <setup> command through `sh -c` in the clone, stopping at the first
+# that fails. <filter> (`blob:none` for a partial clone) and <branch> may be
+# empty. A clone already there is left as it is and its setup is not run again.
+#
+# Prints `<repo> ok cloned` or `<repo> ok present`; `<repo> failed <message>`
+# when the clone or a setup command failed (after a failed setup the clone stays).
+set -eu
+. "$(dirname "$0")/ws-lib.sh"
+[ $# -ge 5 ] || { echo "usage: ws-clone.sh <clones> <repo> <url> <filter> <branch> <setup>…" >&2; exit 2; }
+clones=$1 repo=$2 url=$3 filter=$4 branch=$5
+shift 5
+clone=$clones/$repo
+tmp=$clone.cloning
+
+if [ -e "$clone/.git" ]; then
+ ws_ok "$repo" present
+ exit 0
+fi
+ws_cleanup() { rm -rf -- "$tmp"; }
+rm -rf -- "$tmp"
+mkdir -p -- "$clones"
+if ! ws_in "$clones" git clone --quiet ${filter:+"--filter=$filter"} ${branch:+-b "$branch"} "$url" "$tmp" >/dev/null; then
+ ws_failed "$repo" "$(ws_why "Command failed: git clone --quiet $url $tmp")"
+ exit 0
+fi
+# -T: onto <clone>, never into it. An empty directory there is replaced; one
+# with something in it fails the rename, and <repo>.cloning stays until the next call.
+ws_cleanup() { :; }
+if ! mv -T -- "$tmp" "$clone" 2>"$ws_tmp/err"; then
+ ws_failed "$repo" "$(ws_why "Command failed: mv -T $tmp $clone")"
+ exit 0
+fi
+# Setup commands are the repository's own: they run without the script's GIT_TERMINAL_PROMPT.
+unset GIT_TERMINAL_PROMPT
+for cmd in "$@"; do
+ if ! ws_in "$clone" sh -c "$cmd" >/dev/null; then
+ ws_failed "$repo" "setup \`$cmd\`: $(ws_why "Command failed: sh -c $cmd")"
+ exit 0
+ fi
+done
+ws_ok "$repo" cloned
diff --git a/computer/bin/ws-fetch.sh b/computer/bin/ws-fetch.sh
new file mode 100755
index 00000000..70903ccb
--- /dev/null
+++ b/computer/bin/ws-fetch.sh
@@ -0,0 +1,19 @@
+#!/bin/sh
+# ws-fetch.sh <clones> <repo> <ref>…
+#
+# Fetch these refs of origin into <clones>/<repo>, and nothing else: no tags,
+# no prune, as fast as a fetch gets (forkFetch in src/workspaces/fork.ts, which
+# asks for the branch a fork starts from). With no <ref>, what the remote's
+# refspec names.
+#
+# Prints `<repo> ok` or `<repo> failed <message>`.
+set -eu
+. "$(dirname "$0")/ws-lib.sh"
+[ $# -ge 2 ] || { echo "usage: ws-fetch.sh <clones> <repo> <ref>…" >&2; exit 2; }
+clones=$1 repo=$2
+shift 2
+if ws_in "$clones/$repo" git fetch --quiet --no-tags origin "$@" >/dev/null; then
+ ws_ok "$repo"
+else
+ ws_failed "$repo" "$(ws_why "Command failed: git fetch --quiet --no-tags origin $*")"
+fi
diff --git a/computer/bin/ws-forget.sh b/computer/bin/ws-forget.sh
new file mode 100755
index 00000000..3ca6cadc
--- /dev/null
+++ b/computer/bin/ws-forget.sh
@@ -0,0 +1,23 @@
+#!/bin/sh
+# ws-forget.sh <clones> <branch> <repo>…
+#
+# Delete <branch> from each clone <clones>/<repo>, merged or not (pruneFork in
+# src/workspaces/prune.ts, once the branch's worktree is gone). A clone that
+# has no such branch is `ok`: there is nothing left to forget.
+#
+# Prints `<repo> ok` or `<repo> failed <message>`.
+set -eu
+. "$(dirname "$0")/ws-lib.sh"
+[ $# -ge 2 ] || { echo "usage: ws-forget.sh <clones> <branch> <repo>…" >&2; exit 2; }
+clones=$1 branch=$2
+shift 2
+for repo in "$@"; do
+ clone=$clones/$repo
+ if ! ws_q "$clone" git rev-parse --verify --quiet "refs/heads/$branch" >/dev/null && [ -d "$clone" ]; then
+ ws_ok "$repo"
+ elif ws_q "$clone" git branch -D "$branch" >/dev/null; then
+ ws_ok "$repo"
+ else
+ ws_failed "$repo" "$(ws_why "Command failed: git branch -D $branch")"
+ fi
+done
diff --git a/computer/bin/ws-inspect.sh b/computer/bin/ws-inspect.sh
new file mode 100755
index 00000000..df9092f3
--- /dev/null
+++ b/computer/bin/ws-inspect.sh
@@ -0,0 +1,57 @@
+#!/bin/sh
+# ws-inspect.sh [--only=state|ignored] <clones> <workspace> <worktree>…
+#
+# What the host asks of a workspace's worktrees before it removes anything
+# (pruneFork in src/workspaces/prune.ts, pruneArtifacts in idle.ts). Each
+# <worktree> is a path below <workspace>: a repository's name, or `.wt/<name>`
+# for one an agent added. Read-only: nothing here writes to a worktree, not
+# even its index (--no-optional-locks: a refreshed index would look like use).
+#
+# state: whether it has uncommitted changes (`dirty`, also when git cannot
+# say), the number of commits on no remote (-1: cannot count; not
+# counted, `-`, when dirty), its branch (empty when detached) and its
+# clone's git directory as git names it.
+# ignored: of the directories named on stdin, one `<n><TAB><path below the
+# n-th worktree>` per line, the ones git ignores (tracked files are
+# never ignored).
+#
+# Nothing a session named is printed: a directory's name may hold a tab, which
+# would read as another field. A worktree is answered by its position among
+# the arguments and a directory by its line on stdin, both from 1. A path with
+# a tab or a newline cannot be asked about; the caller leaves those out.
+#
+# Prints `<n> ok <dirty|clean> <unpushed> <branch> <git dir> <ignored line>…`;
+# with --only=ignored the four state fields are `-`, with --only=state stdin is not read.
+set -eu
+. "$(dirname "$0")/ws-lib.sh"
+only=
+case ${1:-} in --only=*) only=${1#--only=}; shift ;; esac
+[ $# -ge 2 ] || { echo "usage: ws-inspect.sh [--only=state|ignored] <clones> <workspace> <worktree>…" >&2; exit 2; }
+workspace=$2
+shift 2
+if [ "$only" = state ]; then : >"$ws_tmp/dirs"; else cat >"$ws_tmp/dirs"; fi
+
+n=0
+for repo in "$@"; do
+ n=$((n + 1))
+ wt=$workspace/$repo
+ state=- unpushed=- branch=- common=-
+ if [ "$only" != ignored ]; then
+ state=dirty
+ if changes=$(ws_q "$wt" git --no-optional-locks status --porcelain) && [ -z "$changes" ]; then
+ state=clean
+ unpushed=$(ws_q "$wt" git rev-list --count HEAD --not --remotes) || unpushed=-1
+ fi
+ branch=$(ws_q "$wt" git symbolic-ref --quiet --short HEAD) || branch=
+ common=$(ws_q "$wt" git rev-parse --git-common-dir) || common=
+ fi
+ set -- "$state" "$unpushed" "$branch" "$common"
+ line=0
+ while IFS=$ws_tab read -r of rel; do
+ line=$((line + 1))
+ [ "$of" = "$n" ] && [ -n "$rel" ] || continue
+ # check-ignore exits 0 only for an ignored path.
+ if ws_q "$wt" git check-ignore -q "$rel"; then set -- "$@" "$line"; fi
+ done <"$ws_tmp/dirs"
+ ws_ok "$n" "$@"
+done
diff --git a/computer/bin/ws-lib.sh b/computer/bin/ws-lib.sh
new file mode 100644
index 00000000..f1c5658f
--- /dev/null
+++ b/computer/bin/ws-lib.sh
@@ -0,0 +1,93 @@
+# Shared by the ws-*.sh scripts (work 103, seam S2): sourced, never run.
+#
+# The scripts hold the git sequences of src/workspaces; TypeScript keeps the
+# locks, the scheduling, the telemetry and the parsing (script-runner.ts).
+# Paths are arguments, so a script does not know where it runs.
+#
+# Contract of every script:
+# - one line per repository on stdout, tab-separated: the repository, `ok` or
+# `failed`, then what the script documents; a failed line's third field is a
+# one-line message. The exit status is non-zero only for a wrong call.
+# A field never holds a tab or a newline: a name that could (a directory a
+# session made) is answered by its position in the input (ws-inspect.sh).
+# - running it twice gives the same result.
+# - git never prompts, and a command that can take long (clone, fetch, a
+# checkout) ends with the script when the script is signalled.
+
+export GIT_TERMINAL_PROMPT=0
+ws_tab=$(printf '\t')
+ws_tmp=$(mktemp -d "${TMPDIR:-/tmp}/ws.XXXXXX")
+# Set while ws_in has a command in the background; ws_before is `$!` from before it started.
+ws_running=
+ws_before=
+# What a script leaves half done when it is stopped; scripts redefine it.
+ws_cleanup() { :; }
+trap 'rm -rf "$ws_tmp"' EXIT
+ws_stop() {
+ trap - TERM INT HUP
+ # `$!` and not a variable set after the `&`: a signal that arrives while the
+ # shell starts the command runs this before any next assignment. `$!` is the
+ # command's as soon as it exists; until then it is still ws_before.
+ if [ -n "$ws_running" ] && [ "${!:-}" != "$ws_before" ]; then
+ ws_pid=$!
+ # Again every second until it is gone: a command this young may still be
+ # the shell's own copy, which drops a signal on its way to becoming it.
+ (while kill "$ws_pid" 2>/dev/null; do sleep 1; done) </dev/null >/dev/null 2>&1 &
+ wait "$ws_pid" 2>/dev/null || :
+ fi
+ ws_cleanup || :
+ exit 143
+}
+trap ws_stop TERM INT HUP
+
+# ws_in <dir> <command…>: run it there and wait in a way a signal interrupts
+# (the shell does not run a trap while a foreground command runs). Its stderr
+# is kept for ws_why; returns its status.
+ws_in() {
+ ws_dir=$1
+ shift
+ ws_before=${!:-}
+ ws_running=1
+ (cd "$ws_dir" && exec "$@") 2>"$ws_tmp/err" </dev/null &
+ ws_rc=0
+ wait "$!" || ws_rc=$?
+ ws_running=
+ return "$ws_rc"
+}
+
+# ws_q <dir> <command…>: a quick command there, in the foreground, for $(…).
+ws_q() {
+ ws_dir=$1
+ shift
+ (cd "$ws_dir" && exec "$@") 2>"$ws_tmp/err" </dev/null
+}
+
+# ws_why <fallback>: why the last ws_in or ws_q failed, in one line: git's
+# first `fatal:` or `error:` line, else the last line it wrote (errText in clones.ts).
+ws_why() {
+ ws_m=$(grep -E '^(fatal|error):' "$ws_tmp/err" 2>/dev/null | head -n 1) || :
+ [ -n "$ws_m" ] || ws_m=$(grep -v '^$' "$ws_tmp/err" 2>/dev/null | tail -n 1) || :
+ [ -n "$ws_m" ] || ws_m=$1
+ printf '%s' "$ws_m" | tr '\t\r\n' ' '
+}
+
+# ws_ok <repo> <field…>, ws_failed <repo> <message>: the repository's line.
+ws_ok() {
+ ws_line=$1
+ shift
+ for ws_f in ok "$@"; do ws_line=$ws_line$ws_tab$ws_f; done
+ printf '%s\n' "$ws_line"
+}
+ws_failed() {
+ printf '%s\tfailed\t%s\n' "$1" "$(printf '%s' "$2" | tr '\t\r\n' ' ')"
+}
+
+# ws_base <clone>: sets ws_b to the branch the clone's forks start from:
+# origin/HEAD, asked of the remote once when the clone does not know it.
+ws_base() {
+ ws_b=$(ws_q "$1" git symbolic-ref --short refs/remotes/origin/HEAD) || {
+ ws_in "$1" git remote set-head origin --auto >/dev/null || return 1
+ ws_b=$(ws_q "$1" git symbolic-ref --short refs/remotes/origin/HEAD) || return 1
+ }
+ ws_b=${ws_b#origin/}
+}
diff --git a/computer/bin/ws-sync.sh b/computer/bin/ws-sync.sh
new file mode 100755
index 00000000..eeb40888
--- /dev/null
+++ b/computer/bin/ws-sync.sh
@@ -0,0 +1,79 @@
+#!/bin/sh
+# ws-sync.sh [--only=base|fetch|forward] <clones> <repo> [<base>]
+#
+# Keep the clone <clones>/<repo> current (syncRepo and fastForward in
+# src/workspaces/housekeep.ts, defaultBranch in clones.ts): fetch origin with
+# --prune, then fast-forward the clone's own checkout of <base>. <base> is the
+# branch forks start from; empty or absent, origin/HEAD (asked of the remote
+# when the clone does not know it).
+#
+# The checkout is only ever fast-forwarded: never when it is on another
+# branch, has local changes or has diverged. A fetch that fails does not stop
+# the fast-forward to what was fetched before.
+#
+# The host runs the steps apart, because each holds a different lock there:
+# --only=base prints `<repo> ok <base>`
+# --only=fetch prints `<repo> ok`
+# --only=forward prints `<repo> ok <moved|current|kept> <origin/base, short> <why kept>`
+# With no --only all run and the line is that of `forward`, its last field
+# also naming a failed fetch (`fetch: …; …`). `<repo> failed <message>` when a
+# step that was asked for alone failed, or the base is not known.
+set -eu
+. "$(dirname "$0")/ws-lib.sh"
+only=
+case ${1:-} in --only=*) only=${1#--only=}; shift ;; esac
+[ $# -ge 2 ] || { echo "usage: ws-sync.sh [--only=base|fetch|forward] <clones> <repo> [<base>]" >&2; exit 2; }
+clones=$1 repo=$2 b=${3:-}
+clone=$clones/$repo
+
+if [ -z "$b" ] && [ "$only" != fetch ]; then
+ ws_base "$clone" || { ws_failed "$repo" "$(ws_why 'no default branch')"; exit 0; }
+ b=$ws_b
+fi
+[ "$only" != base ] || { ws_ok "$repo" "$b"; exit 0; }
+
+problem=
+if [ "$only" != forward ]; then
+ if ! ws_in "$clone" git fetch --quiet --prune origin >/dev/null; then
+ why=$(ws_why 'Command failed: git fetch --quiet --prune origin')
+ [ "$only" != fetch ] || { ws_failed "$repo" "$why"; exit 0; }
+ problem="fetch: $why"
+ fi
+ [ "$only" != fetch ] || { ws_ok "$repo"; exit 0; }
+fi
+
+# Sets state (moved, current, kept) and, when kept, why.
+forward() {
+ why=
+ state=kept
+ cur=$(ws_q "$clone" git symbolic-ref --quiet --short HEAD) || cur=
+ if [ "$cur" != "$b" ]; then
+ why="checkout is on ${cur:-a detached HEAD}, not $b; not fast-forwarded"
+ return 0
+ fi
+ changes=$(ws_q "$clone" git status --porcelain) || { why="fast-forward: $(ws_why 'Command failed: git status --porcelain')"; return 0; }
+ if [ -n "$changes" ]; then
+ why='checkout has local changes; not fast-forwarded'
+ return 0
+ fi
+ head=$(ws_q "$clone" git rev-parse HEAD) || { why="fast-forward: $(ws_why 'Command failed: git rev-parse HEAD')"; return 0; }
+ remote=$(ws_q "$clone" git rev-parse "origin/$b") || { why="fast-forward: $(ws_why "Command failed: git rev-parse origin/$b")"; return 0; }
+ if [ "$head" = "$remote" ]; then
+ state=current
+ return 0
+ fi
+ if ! ws_q "$clone" git merge-base --is-ancestor "$head" "$remote"; then
+ why="$b has diverged from origin/$b; not fast-forwarded"
+ return 0
+ fi
+ # Downloads file contents on a partial clone, so it can take as long as a fetch.
+ ws_in "$clone" git merge --ff-only --quiet "origin/$b" >/dev/null || {
+ why="fast-forward: $(ws_why "Command failed: git merge --ff-only --quiet origin/$b")"
+ return 0
+ }
+ state=moved
+}
+forward
+short=$(ws_q "$clone" git rev-parse --short "origin/$b") || short=
+[ -z "$why" ] || problem=${problem:+$problem; }$why
+ws_ok "$repo" "$state" "$short" "$problem"
diff --git a/computer/src/workspaces/clones.ts b/computer/src/workspaces/clones.ts
index dce01d35..7bcb86b0 100644
--- a/computer/src/workspaces/clones.ts
+++ b/computer/src/workspaces/clones.ts
@@ -6,7 +6,8 @@
// 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.
+// - Git runs in the scripts bin/ws-*.sh (script-runner.ts), 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.
@@ -17,8 +18,9 @@ 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 { command, copyFile, mkdir, writeFile } from './as-runner.js';
import { Freshness, keyedQueue } from './fetch-schedule.js';
+import { hostScripts, row } from './script-runner.js';
const exec = promisify(execFile);
@@ -56,11 +58,13 @@ export const forkDir = (person: Person, sessionKey: string) => path.join(personR
// ---------------------------------------------------------------- git
+/** Git on the host itself: only what no script does (prune.ts removes a worktree with it). */
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);
+/** The scripts (script-runner.ts) for the clones directory this clone is in, and its name there. */
+export const scriptsFor = (clone: string) => ({ s: hostScripts(path.dirname(clone)), repo: path.basename(clone) });
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);
@@ -97,9 +101,8 @@ 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\//, '');
+ const { s, repo: name } = scriptsFor(clone);
+ const [b] = row(await s.run('ws-sync.sh', ['--only=base', s.clones, name], { timeoutMs: fetchTimeout() }), name);
branches.set(clone, b);
return b;
}
@@ -110,23 +113,22 @@ 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();
+ const setup = repo.setup ?? [];
+ const cloned = () => {
+ fetchedAt.set(clone, new Date().toISOString());
+ freshness.fetchedFrom(clone, t0);
+ log.info(`workspaces: cloned ${repo.name} into ${clone} in ${Date.now() - t0} ms`);
+ };
// 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)}`);
- });
- }
+ // The clone and each setup command may take CLONE_TIMEOUT.
+ const { s, repo: name } = scriptsFor(clone);
+ const args = [s.clones, name, repo.remote, isLazy(repo) ? 'blob:none' : '', repo.branch ?? '', ...setup];
+ await s.run('ws-clone.sh', args, { timeoutMs: CLONE_TIMEOUT * (1 + setup.length) }).then((out) => row(out, name)).catch((e) => {
+ if (isClone(clone)) cloned(); // a setup command failed: the clone is there, and is not made again
+ throw e;
+ });
+ cloned();
return true;
});
}
diff --git a/computer/src/workspaces/fork.ts b/computer/src/workspaces/fork.ts
index 5ab3d876..2e58a0cc 100644
--- a/computer/src/workspaces/fork.ts
+++ b/computer/src/workspaces/fork.ts
@@ -12,18 +12,18 @@
// - 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 { appendFile, mkdir, 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,
+ freshness, isClone, observe, observed, prepareInBackground, safeKey, scriptsFor, serial, workspaceDir, workspacePrepared,
} from './clones.js';
import { FORK_FILE } from './idle.js';
+import { row } from './script-runner.js';
export interface ForkInfo {
key: string;
@@ -87,23 +87,11 @@ async function forkRepo(clone: string, repo: RepoDef, dest: string, branch: stri
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']);
+ // ws-add.sh: the branch if the clone has it, else a new one from origin/<b>; a destination that is already this
+ // clone's worktree is left as it is. On a partial clone the checkout downloads file contents, so it is bounded like a fetch.
+ const { s, repo: name } = scriptsFor(clone);
+ const out = await s.run('ws-add.sh', [s.clones, s.workspace(path.dirname(dest)), branch, '0', `${name}=${b}`], { timeoutMs: fetchTimeout() });
+ const [, , base] = row(out, name);
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 }));
@@ -124,7 +112,8 @@ async function forkFetch(clone: string, b: string): Promise<{ skipped: boolean;
// 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);
+ const { s, repo } = scriptsFor(clone);
+ row(await s.run('ws-fetch.sh', [s.clones, repo, b], { timeoutMs: timeout }), repo);
fetchedAt.set(clone, new Date().toISOString());
freshness.fetchedFrom(clone, started);
return { skipped: false };
@@ -142,13 +131,6 @@ async function forkFetch(clone: string, b: string): Promise<{ skipped: boolean;
}
}
-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
diff --git a/computer/src/workspaces/housekeep.ts b/computer/src/workspaces/housekeep.ts
index 4b1e3fbc..51105923 100644
--- a/computer/src/workspaces/housekeep.ts
+++ b/computer/src/workspaces/housekeep.ts
@@ -17,27 +17,26 @@ 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,
+ cloneRepo, copyRootFiles, defaultBranch, errText, type FetchTrigger, fetchedAt, fetchErrorType, fetchInterval, fetchLane, fetchTimeout, freshness,
+ HOUSEKEEPING_FETCHES, isClone, observe, observed, personRoot, scriptsFor, serial, workspaceDir,
} from './clones.js';
import { limit } from './fetch-schedule.js';
import { pruneIdleArtifacts } from './idle.js';
import { pruneForks } from './prune.js';
+import { row } from './script-runner.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;
+/**
+ * Fast-forward the checkout (ws-sync.sh): `ff` is a string that says why not, `true` that it moved; `head` is origin/<b>, short.
+ * Bounded like a fetch: the merge downloads contents on a partial clone.
+ */
+async function fastForward(clone: string, b: string): Promise<{ ff: string | boolean | undefined; head?: string }> {
+ const { s, repo } = scriptsFor(clone);
+ const [state, head, why] = row(await s.run('ws-sync.sh', ['--only=forward', s.clones, repo, b], { timeoutMs: fetchTimeout() }), repo);
+ return { ff: state === 'moved' ? true : state === 'current' ? undefined : why, head: head || undefined };
}
/**
@@ -59,17 +58,17 @@ async function syncRepo(person: Person, repo: RepoDef, trigger: FetchTrigger): P
await housekeepingFetch(() =>
fetchLane(clone, async () => {
const started = Date.now();
- await git(clone, ['fetch', '--quiet', '--prune', 'origin'], fetchTimeout()).then(
+ const { s, repo: name } = scriptsFor(clone);
+ await s.run('ws-sync.sh', ['--only=fetch', s.clones, name], { timeoutMs: fetchTimeout() }).then((out) => row(out, name)).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)}`);
+ const { ff, head } = await fastForward(clone, b).catch((e) => ({ ff: `fast-forward: ${errText(e)}`, head: undefined }));
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) {
diff --git a/computer/src/workspaces/idle.test.ts b/computer/src/workspaces/idle.test.ts
new file mode 100644
index 00000000..cdbf6614
--- /dev/null
+++ b/computer/src/workspaces/idle.test.ts
@@ -0,0 +1,82 @@
+// pruneArtifacts and pruneFork against real git in a temp dir: names with a
+// tab or a newline, which the scripts' line protocol cannot carry.
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { beforeAll, describe, expect, it } from 'vitest';
+import { configureAsRunner } from './as-runner.js';
+import { pruneArtifacts } from './idle.js';
+import { pruneFork } from './prune.js';
+
+const tmp = mkdtempSync(path.join(tmpdir(), 'ws-idle-'));
+const gitconfig = path.join(tmp, 'gitconfig');
+writeFileSync(gitconfig, '[user]\n\tname = check\n\temail = check@localhost\n[init]\n\tdefaultBranch = main\n');
+const env = { PATH: process.env.PATH, HOME: tmp, GIT_CONFIG_GLOBAL: gitconfig, GIT_CONFIG_NOSYSTEM: '1' };
+const git = (cwd: string, ...args: string[]) => execFileSync('git', args, { cwd, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+
+let forks = 0;
+const newFork = () => {
+ const fork = path.join(tmp, 'sessions', `k${++forks}`);
+ mkdirSync(fork, { recursive: true });
+ return fork;
+};
+/** A repository at `dir` with one commit of a .gitignore, and these directories. */
+function repo(dir: string, gitignore: string, dirs: string[]) {
+ mkdirSync(dir, { recursive: true });
+ git(dir, 'init', '--quiet');
+ writeFileSync(path.join(dir, '.gitignore'), gitignore);
+ git(dir, 'add', '-A');
+ git(dir, 'commit', '--quiet', '-m', 'first');
+ for (const d of dirs) mkdirSync(path.join(dir, d), { recursive: true });
+}
+
+beforeAll(() => configureAsRunner(undefined, env));
+
+describe('pruneArtifacts', () => {
+ it('removes the ignored directories and keeps the others', async () => {
+ const fork = newFork();
+ repo(path.join(fork, 'alpha'), '/node_modules/\n/pkg/.venv/\n', ['node_modules', 'pkg/.venv', 'pkg/node_modules']);
+ repo(path.join(fork, '.wt', 'beta'), '.turbo/\n', ['.turbo', 'venv']);
+ const rel = (await pruneArtifacts(fork)).map((d) => path.relative(fork, d)).sort();
+ expect(rel).toEqual(['.wt/beta/.turbo', 'alpha/node_modules', 'alpha/pkg/.venv']);
+ expect(existsSync(path.join(fork, 'alpha', 'node_modules'))).toBe(false);
+ expect(existsSync(path.join(fork, 'alpha', 'pkg', 'node_modules'))).toBe(true);
+ expect(existsSync(path.join(fork, '.wt', 'beta', 'venv'))).toBe(true);
+ });
+
+ it('keeps an unignored directory whose path ends an ignored one with a tab in its name', async () => {
+ const fork = newFork();
+ const wt = path.join(fork, 'alpha');
+ // `x<TAB>vendor/` is ignored, `vendor/` is not.
+ repo(wt, 'x?vendor/\n/node_modules/\n', ['x\tvendor/node_modules', 'vendor/node_modules', 'line\nbreak/node_modules', 'node_modules']);
+ writeFileSync(path.join(wt, 'vendor', 'node_modules', 'kept.txt'), 'not ignored');
+ expect(await pruneArtifacts(fork)).toEqual([path.join(wt, 'node_modules')]);
+ expect(existsSync(path.join(wt, 'vendor', 'node_modules', 'kept.txt'))).toBe(true);
+ // A path the line protocol cannot carry is not asked about, and stays.
+ expect(existsSync(path.join(wt, 'x\tvendor', 'node_modules'))).toBe(true);
+ expect(existsSync(path.join(wt, 'line\nbreak', 'node_modules'))).toBe(true);
+ });
+
+ it('prunes a fork that has a worktree with a tab or a newline in its name', async () => {
+ const fork = newFork();
+ repo(path.join(fork, 'alpha'), 'node_modules/\n', ['node_modules']);
+ repo(path.join(fork, '.wt', 'a\tb'), 'node_modules/\n', ['node_modules', 'venv']);
+ repo(path.join(fork, '.wt', 'c\nd'), 'node_modules/\n', ['node_modules']);
+ const rel = (await pruneArtifacts(fork)).map((d) => path.relative(fork, d)).sort();
+ expect(rel).toEqual(['.wt/a\tb/node_modules', '.wt/c\nd/node_modules', 'alpha/node_modules']);
+ expect(existsSync(path.join(fork, '.wt', 'a\tb', 'venv'))).toBe(true);
+ });
+});
+
+describe('pruneFork', () => {
+ it('says why a fork is kept when a worktree has a tab in its name', async () => {
+ const fork = newFork();
+ repo(path.join(fork, 'alpha'), '', []);
+ repo(path.join(fork, 'a\tb'), '', []);
+ writeFileSync(path.join(fork, 'a\tb', 'new.txt'), 'uncommitted');
+ // alpha has a commit on no remote; the other is dirty.
+ expect(await pruneFork(fork)).toBe('a\tb has uncommitted changes, alpha has 1 unpushed commit');
+ expect(existsSync(path.join(fork, 'a\tb', 'new.txt'))).toBe(true);
+ });
+});
diff --git a/computer/src/workspaces/idle.ts b/computer/src/workspaces/idle.ts
index e83aa1e7..9b916eb9 100644
--- a/computer/src/workspaces/idle.ts
+++ b/computer/src/workspaces/idle.ts
@@ -10,6 +10,7 @@ import path from 'node:path';
import { promisify } from 'node:util';
import { log } from '../log.js';
import { command, rm } from './as-runner.js';
+import { hostScripts, row } from './script-runner.js';
const exec = promisify(execFile);
@@ -28,7 +29,11 @@ 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')));
+/** A person's clones directory, from one of their forks: <root>/sessions/<key> and <root>/ws (clones.ts). */
+export const clonesOf = (fork: string) => path.join(path.dirname(path.dirname(path.resolve(fork))), 'ws');
+
// As the runner user, like clones.ts: the host's own user fails git's ownership check on these repos.
+// Only lastUsed runs git here; what pruneArtifacts asks goes through ws-inspect.sh.
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();
@@ -76,12 +81,31 @@ async function findArtifacts(dir: string, depth = ARTIFACT_DEPTH): Promise<strin
* ones are kept. Returns the directories removed.
*/
export async function pruneArtifacts(forkPath: string): Promise<string[]> {
- const removed: string[] = [];
+ const wts: string[] = [];
+ /** The directories asked about, in the order of the lines on stdin. */
+ const asked: string[] = [];
+ let lines = '';
for (const wt of await allWorktrees(forkPath)) {
- for (const dir of await findArtifacts(wt)) {
- // check-ignore exits 0 only for an ignored path; tracked files are never ignored.
- const ignored = await git(wt, ['check-ignore', '-q', path.relative(wt, dir)]).then(() => true, () => false);
- if (!ignored) continue;
+ // A path with a tab or a newline does not fit a line of the script's input: not asked about, so kept.
+ const dirs = (await findArtifacts(wt)).filter((dir) => !/[\t\n]/.test(path.relative(wt, dir)));
+ if (!dirs.length) continue;
+ wts.push(wt);
+ for (const dir of dirs) {
+ asked.push(dir);
+ lines += `${wts.length}\t${path.relative(wt, dir)}\n`;
+ }
+ }
+ if (!asked.length) return [];
+ // ws-inspect.sh says which git ignores; tracked files are never ignored. It answers a worktree by its
+ // position and a directory by its line, both from 1: a name with a tab would not survive being printed.
+ const s = hostScripts(clonesOf(forkPath));
+ const names = wts.map((wt) => path.relative(forkPath, wt));
+ const out = await s.run('ws-inspect.sh', ['--only=ignored', s.clones, s.workspace(forkPath), ...names], { stdin: lines, timeoutMs: 0 });
+ const removed: string[] = [];
+ for (const n of wts.keys()) {
+ for (const line of row(out, String(n + 1)).slice(4)) {
+ const dir = asked[Number(line) - 1];
+ if (!dir) continue;
await rm(dir);
removed.push(dir);
}
diff --git a/computer/src/workspaces/index.ts b/computer/src/workspaces/index.ts
index 63763b6d..3bf3f44e 100644
--- a/computer/src/workspaces/index.ts
+++ b/computer/src/workspaces/index.ts
@@ -24,6 +24,7 @@
// 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.
+// The git sequences themselves are the scripts bin/ws-*.sh (script-runner.ts).
export * from './definition.js';
export { configureAsRunner, mkdir as mkdirAsRunner } from './as-runner.js';
diff --git a/computer/src/workspaces/prune.ts b/computer/src/workspaces/prune.ts
index 3ec1cf92..7f131d54 100644
--- a/computer/src/workspaces/prune.ts
+++ b/computer/src/workspaces/prune.ts
@@ -10,37 +10,44 @@ 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 { errText, git, personRoot, retention, scriptsFor, serial } from './clones.js';
import { removeCodexHome } from './codex-homes.js';
import { forkInfo } from './fork.js';
-import { lastUsed, worktrees } from './idle.js';
+import { clonesOf, lastUsed, worktrees } from './idle.js';
+import { hostScripts, row } from './script-runner.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);
+ // ws-inspect.sh reads without refreshing the index, whose new mtime would make the fork look used (lastUsed).
+ const s = hostScripts(clonesOf(forkPath));
+ const names = wts.map((wt) => path.basename(wt));
+ const out = names.length ? await s.run('ws-inspect.sh', ['--only=state', s.clones, s.workspace(forkPath), ...names], { timeoutMs: 0 }) : '';
+ // Answered by position, from 1: a worktree's name may hold a tab.
+ const state = new Map(names.map((name, n) => [name, row(out, String(n + 1))] as const));
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) {
+ for (const name of names) {
+ const [dirty, unpushed] = state.get(name)!;
+ if (dirty !== 'clean') {
reasons.push(`${name} has uncommitted changes`);
continue;
}
- const n = Number(await git(wt, ['rev-list', '--count', 'HEAD', '--not', '--remotes']).catch(() => '-1'));
+ const n = Number(unpushed);
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(() => '');
+ const [, , branch, common] = state.get(path.basename(wt))!;
+ if (!common) throw new Error(`${path.basename(wt)}: no git directory`);
+ const clone = path.dirname(path.resolve(wt, common));
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(() => {});
+ const c = scriptsFor(clone);
+ if (branch.startsWith('sp/')) await c.s.run('ws-forget.sh', [c.s.clones, branch, c.repo], { timeoutMs: 0 }).catch(() => {});
});
}
await rm(forkPath);
diff --git a/computer/src/workspaces/script-runner.test.ts b/computer/src/workspaces/script-runner.test.ts
new file mode 100644
index 00000000..3741fe71
--- /dev/null
+++ b/computer/src/workspaces/script-runner.test.ts
@@ -0,0 +1,220 @@
+// bin/ws-*.sh against real git in a temp dir: the line each prints, and that a second run gives the same.
+import { execFileSync, spawn } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { beforeAll, describe, expect, it } from 'vitest';
+import { configureAsRunner } from './as-runner.js';
+import { hostScripts, row, rows, ScriptError } from './script-runner.js';
+
+const tmp = mkdtempSync(path.join(tmpdir(), 'ws-scripts-'));
+const gitconfig = path.join(tmp, 'gitconfig');
+writeFileSync(gitconfig, '[user]\n\tname = check\n\temail = check@localhost\n[init]\n\tdefaultBranch = main\n');
+const env = { PATH: process.env.PATH, HOME: tmp, GIT_CONFIG_GLOBAL: gitconfig, GIT_CONFIG_NOSYSTEM: '1' };
+const git = (cwd: string, ...args: string[]) => execFileSync('git', args, { cwd, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+
+const remote = path.join(tmp, 'remotes', 'alpha.git');
+const clones = path.join(tmp, 'ws');
+const workspace = path.join(tmp, 'sessions', 'k1');
+const s = hostScripts(clones);
+const run = (script: string, args: string[], stdin?: string) => s.run(script, args, { stdin, timeoutMs: 20_000 });
+/** A commit on the remote's main, through a throwaway checkout. */
+function push(file: string, text: string) {
+ const co = mkdtempSync(path.join(tmp, 'co-'));
+ git(co, 'clone', '--quiet', remote, '.');
+ writeFileSync(path.join(co, file), text);
+ git(co, 'add', '-A');
+ git(co, 'commit', '--quiet', '-m', file);
+ git(co, 'push', '--quiet', 'origin', 'HEAD:main');
+ return git(co, 'rev-parse', 'HEAD');
+}
+
+beforeAll(() => {
+ configureAsRunner(undefined, env);
+ mkdirSync(remote, { recursive: true });
+ mkdirSync(workspace, { recursive: true });
+ git(remote, 'init', '--quiet', '--bare');
+ const seed = mkdtempSync(path.join(tmp, 'seed-'));
+ git(seed, 'init', '--quiet');
+ writeFileSync(path.join(seed, '.gitignore'), 'node_modules/\n');
+ git(seed, 'add', '-A');
+ git(seed, 'commit', '--quiet', '-m', 'first');
+ git(seed, 'push', '--quiet', remote, 'HEAD:main');
+});
+
+describe('script output', () => {
+ it('is read by repository, a failed line as an error with its message', () => {
+ const out = 'a\tok\tx\t\ty\nb\tfailed\tfatal: no\n';
+ expect(rows(out).get('a')).toEqual(['ok', 'x', '', 'y']);
+ expect(row(out, 'a')).toEqual(['x', '', 'y']);
+ expect(() => row(out, 'b')).toThrow('fatal: no');
+ expect(() => row(out, 'c')).toThrow('no result for c');
+ });
+});
+
+describe('workspace scripts', () => {
+ it('ws-clone.sh clones once, runs setup in the clone, and leaves a clone that exists alone', async () => {
+ const args = [clones, 'alpha', remote, '', '', 'touch .git/set-up'];
+ expect(await run('ws-clone.sh', args)).toBe('alpha\tok\tcloned\n');
+ expect(existsSync(path.join(clones, 'alpha', '.git', 'set-up'))).toBe(true);
+ expect(existsSync(path.join(clones, 'alpha.cloning'))).toBe(false);
+ expect(await run('ws-clone.sh', [clones, 'alpha', remote, '', '', 'touch .git/again'])).toBe('alpha\tok\tpresent\n');
+ expect(existsSync(path.join(clones, 'alpha', '.git', 'again'))).toBe(false);
+ });
+
+ it('ws-clone.sh says why a clone or a setup command failed, in one line', async () => {
+ const [status, why] = rows(await run('ws-clone.sh', [clones, 'nowhere', path.join(tmp, 'remotes', 'none.git'), 'blob:none', 'main'])).get('nowhere')!;
+ expect([status, why]).toEqual(['failed', expect.stringMatching(/^fatal: /)]);
+ expect(existsSync(path.join(clones, 'nowhere'))).toBe(false);
+ expect(await run('ws-clone.sh', [clones, 'beta', remote, '', 'main', 'echo broken >&2; exit 3', 'touch .not-reached'])).toBe(
+ 'beta\tfailed\tsetup `echo broken >&2; exit 3`: broken\n',
+ );
+ expect(existsSync(path.join(clones, 'beta', '.git'))).toBe(true); // the clone stays
+ expect(existsSync(path.join(clones, 'beta', '.not-reached'))).toBe(false);
+ });
+
+ it('ws-clone.sh renames over an empty directory and never moves the clone into one that is not', async () => {
+ // As rename(2) did before the script: an empty directory is replaced.
+ mkdirSync(path.join(clones, 'empty'));
+ expect(await run('ws-clone.sh', [clones, 'empty', remote, '', ''])).toBe('empty\tok\tcloned\n');
+ expect(existsSync(path.join(clones, 'empty', '.git'))).toBe(true);
+ // One with something in it fails the rename, with mv's message, and is left as it was.
+ mkdirSync(path.join(clones, 'full'));
+ writeFileSync(path.join(clones, 'full', 'mine.txt'), 'x');
+ const [status, why] = rows(await run('ws-clone.sh', [clones, 'full', remote, '', '', 'touch .not-reached'])).get('full')!;
+ expect([status, why]).toEqual(['failed', expect.stringMatching(/^mv: .*full/)]);
+ expect(execFileSync('ls', ['-A', path.join(clones, 'full')], { encoding: 'utf8' })).toBe('mine.txt\n');
+ });
+
+ it('ws-clone.sh runs setup commands without GIT_TERMINAL_PROMPT, as before the script', async () => {
+ const args = [clones, 'gamma', remote, '', '', 'echo "${GIT_TERMINAL_PROMPT-unset}" >.git/prompt'];
+ expect(await run('ws-clone.sh', args)).toBe('gamma\tok\tcloned\n');
+ expect(readFileSync(path.join(clones, 'gamma', '.git', 'prompt'), 'utf8')).toBe('unset\n');
+ });
+
+ it('ws-sync.sh names the base, fetches, and only ever fast-forwards the checkout', async () => {
+ expect(await run('ws-sync.sh', ['--only=base', clones, 'alpha'])).toBe('alpha\tok\tmain\n');
+ expect(await run('ws-sync.sh', ['--only=forward', clones, 'alpha', 'main'])).toMatch(/^alpha\tok\tcurrent\t[0-9a-f]{7,}\t\n$/);
+ const pushed = push('one.txt', '1');
+ expect(await run('ws-sync.sh', ['--only=fetch', clones, 'alpha'])).toBe('alpha\tok\n');
+ expect(git(path.join(clones, 'alpha'), 'rev-parse', 'origin/main')).toBe(pushed);
+ const moved = await run('ws-sync.sh', ['--only=forward', clones, 'alpha', 'main']);
+ expect(row(moved, 'alpha')).toEqual(['moved', git(path.join(clones, 'alpha'), 'rev-parse', '--short', 'origin/main'), '']);
+ expect(git(path.join(clones, 'alpha'), 'rev-parse', 'HEAD')).toBe(pushed);
+ // All steps at once, twice: the second run finds nothing to do.
+ push('two.txt', '2');
+ expect(row(await run('ws-sync.sh', [clones, 'alpha']), 'alpha')[0]).toBe('moved');
+ expect(row(await run('ws-sync.sh', [clones, 'alpha']), 'alpha')[0]).toBe('current');
+ // Local changes are never overwritten.
+ writeFileSync(path.join(clones, 'alpha', 'two.txt'), 'mine');
+ push('three.txt', '3');
+ expect(row(await run('ws-sync.sh', [clones, 'alpha']), 'alpha')).toEqual(['kept', expect.any(String), 'checkout has local changes; not fast-forwarded']);
+ git(path.join(clones, 'alpha'), 'checkout', '--quiet', '--', 'two.txt');
+ git(path.join(clones, 'alpha'), 'checkout', '--quiet', '-b', 'other');
+ expect(row(await run('ws-sync.sh', ['--only=forward', clones, 'alpha', 'main']), 'alpha')[2]).toBe('checkout is on other, not main; not fast-forwarded');
+ git(path.join(clones, 'alpha'), 'checkout', '--quiet', 'main');
+ expect(row(await run('ws-sync.sh', ['--only=forward', clones, 'alpha', 'main']), 'alpha')[0]).toBe('moved');
+ });
+
+ it('ws-fetch.sh fetches the refs it is given', async () => {
+ const pushed = push('four.txt', '4');
+ expect(await run('ws-fetch.sh', [clones, 'alpha', 'main'])).toBe('alpha\tok\n');
+ expect(git(path.join(clones, 'alpha'), 'rev-parse', 'origin/main')).toBe(pushed);
+ expect(await run('ws-fetch.sh', [clones, 'alpha', 'main'])).toBe('alpha\tok\n');
+ expect(rows(await run('ws-fetch.sh', [clones, 'alpha', 'no-such-branch'])).get('alpha')).toEqual(['failed', expect.stringMatching(/^fatal: .*no-such-branch/)]);
+ });
+
+ it('ws-add.sh makes a worktree on the branch from origin/<base>, once', async () => {
+ const base = git(path.join(clones, 'alpha'), 'rev-parse', 'origin/main');
+ const line = `alpha\tok\tsp/k1\tmain\t${base}\t\n`;
+ expect(await run('ws-add.sh', [clones, workspace, 'sp/k1', '0', 'alpha=main'])).toBe(line);
+ expect(git(path.join(workspace, 'alpha'), 'symbolic-ref', '--short', 'HEAD')).toBe('sp/k1');
+ expect(git(path.join(workspace, 'alpha'), 'for-each-ref', '--format=%(upstream)', 'refs/heads/sp/k1')).toBe(''); // not tracking origin/main
+ // Again, with a fetch and the base left to the script: the same line, the worktree untouched.
+ writeFileSync(path.join(workspace, 'alpha', 'work.txt'), 'kept');
+ expect(await run('ws-add.sh', [clones, workspace, 'sp/k1', '1', 'alpha'])).toBe(line);
+ expect(existsSync(path.join(workspace, 'alpha', 'work.txt'))).toBe(true);
+ // A worktree whose directory was deleted is added again, on the branch that exists.
+ execFileSync('rm', ['-rf', path.join(workspace, 'alpha')]);
+ expect(await run('ws-add.sh', [clones, workspace, 'sp/k1', '0', 'alpha=main'])).toBe(line);
+ });
+
+ it('ws-add.sh reports each repository on its own: not a worktree, no such clone, a failed fetch', async () => {
+ mkdirSync(path.join(workspace, 'beta'));
+ writeFileSync(path.join(workspace, 'beta', 'mine.txt'), 'x');
+ const out = rows(await run('ws-add.sh', [clones, workspace, 'sp/k1', '0', 'beta=main', 'gone=main', 'alpha=main']));
+ expect(out.get('beta')).toEqual(['failed', "./beta exists but is not a worktree of this workspace's beta; move it away and check out again"]);
+ expect(existsSync(path.join(workspace, 'beta', 'mine.txt'))).toBe(true);
+ expect(out.get('gone')?.[0]).toBe('failed');
+ expect(existsSync(path.join(workspace, 'gone'))).toBe(false);
+ expect(out.get('alpha')?.[0]).toBe('ok');
+ git(path.join(clones, 'beta'), 'remote', 'set-url', 'origin', path.join(tmp, 'remotes', 'none.git'));
+ const other = path.join(tmp, 'sessions', 'k2');
+ mkdirSync(other);
+ const [branch, from, head, fetchError] = row(await run('ws-add.sh', [clones, other, 'sp/k2', '1', 'beta=main']), 'beta');
+ expect([branch, from, head]).toEqual(['sp/k2', 'main', git(path.join(clones, 'beta'), 'rev-parse', 'origin/main')]);
+ expect(fetchError).toMatch(/^fatal: /);
+ });
+
+ it('ws-inspect.sh tells clean from dirty, counts unpushed commits and names the ignored directories, changing nothing', async () => {
+ const wt = path.join(workspace, 'alpha');
+ const common = git(wt, 'rev-parse', '--git-common-dir');
+ const state = () => run('ws-inspect.sh', ['--only=state', clones, workspace, 'alpha']);
+ expect(await state()).toBe(`1\tok\tclean\t0\tsp/k1\t${common}\n`);
+ expect(await state()).toBe(`1\tok\tclean\t0\tsp/k1\t${common}\n`);
+ writeFileSync(path.join(wt, 'new.txt'), 'n');
+ expect(await state()).toBe(`1\tok\tdirty\t-\tsp/k1\t${common}\n`);
+ git(wt, 'add', '-A');
+ git(wt, 'commit', '--quiet', '-m', 'local');
+ expect(await state()).toBe(`1\tok\tclean\t1\tsp/k1\t${common}\n`);
+ mkdirSync(path.join(wt, 'node_modules'));
+ mkdirSync(path.join(wt, 'pkg', 'node_modules'), { recursive: true });
+ mkdirSync(path.join(wt, 'venv'));
+ // Answered by position: the worktree's among the arguments, the directory's line on stdin.
+ const asked = '1\tnode_modules\n1\tvenv\n2\tnode_modules\n1\tpkg/node_modules\n';
+ expect(await run('ws-inspect.sh', ['--only=ignored', clones, workspace, 'alpha'], asked)).toBe('1\tok\t-\t-\t-\t-\t1\t4\n');
+ expect(await run('ws-inspect.sh', [clones, workspace, 'alpha', 'missing'], asked)).toBe(
+ `1\tok\tclean\t1\tsp/k1\t${common}\t1\t4\n2\tok\tdirty\t-\t\t\n`,
+ );
+ });
+
+ it('ws-forget.sh deletes the branch, and has nothing to do the second time', async () => {
+ const clone = path.join(clones, 'alpha');
+ git(clone, 'worktree', 'remove', '--force', path.join(workspace, 'alpha'));
+ expect(await run('ws-forget.sh', [clones, 'sp/k1', 'alpha'])).toBe('alpha\tok\n');
+ expect(git(clone, 'branch', '--list', 'sp/k1')).toBe('');
+ expect(await run('ws-forget.sh', [clones, 'sp/k1', 'alpha', 'gone'])).toMatch(/^alpha\tok\ngone\tfailed\t.+\n$/);
+ });
+
+ it('a script stopped at its timeout stops its command and rejects as killed', async () => {
+ const started = Date.now();
+ const e = await s.run('ws-clone.sh', [clones, 'slow', remote, '', '', 'sleep 5'], { timeoutMs: 1500 }).catch((e) => e);
+ expect(e).toBeInstanceOf(ScriptError);
+ expect(e.killed).toBe(true);
+ expect(Date.now() - started).toBeLessThan(10_000);
+ });
+
+ it('a script signalled while it starts a command leaves none running', async () => {
+ // The signal is sent as soon as the script says it is about to start one: it lands around the fork.
+ const script = path.join(tmp, 'starting.sh');
+ writeFileSync(script, '. "$1/ws-lib.sh"\necho ready\nwhile :; do ws_in / sleep 30; done\n');
+ const bin = path.resolve(import.meta.dirname, '..', '..', 'bin');
+ const started = Date.now();
+ for (let n = 0; n < 20; n++) {
+ const code = await new Promise((resolve) => {
+ const p = spawn('sh', [script, bin], { env, stdio: ['ignore', 'pipe', 'ignore'] });
+ p.stdout.once('data', () => p.kill('SIGTERM'));
+ p.on('close', resolve); // not before the sleep, which holds stdout, is gone too
+ });
+ expect(code).toBe(143);
+ }
+ expect(Date.now() - started).toBeLessThan(15_000);
+ }, 20_000);
+
+ it('a wrong call is a ScriptError with the exit code and stderr', async () => {
+ const e = await run('ws-fetch.sh', []).catch((e) => e);
+ expect(e).toBeInstanceOf(ScriptError);
+ expect([e.code, e.killed]).toEqual([2, false]);
+ expect(e.stderr).toMatch(/^usage: ws-fetch.sh/);
+ });
+});
diff --git a/computer/src/workspaces/script-runner.ts b/computer/src/workspaces/script-runner.ts
new file mode 100644
index 00000000..160ebb13
--- /dev/null
+++ b/computer/src/workspaces/script-runner.ts
@@ -0,0 +1,87 @@
+// Running the workspace scripts, bin/ws-*.sh (work 103, seam S2). The scripts
+// hold the git sequences; clones.ts, fork.ts, housekeep.ts, prune.ts and
+// idle.ts keep the locks, the scheduling, the telemetry and the parsing, and
+// reach git only through a ScriptRunner. `hostScripts` runs a script on the
+// host as the runners' user (as-runner.ts), with host paths.
+//
+// Invariants:
+// - A script prints one line per repository, tab-separated: the repository,
+// `ok` or `failed`, then its fields; a failed line's third field is a
+// one-line message (bin/ws-lib.sh). `row` turns a failed line into an Error
+// with that message.
+// - `run` rejects only when the script itself failed: a non-zero exit, or the
+// timeout, after which the script is stopped and `killed` is set (errText in
+// clones.ts then says "timed out").
+
+import { spawn } from 'node:child_process';
+import path from 'node:path';
+import { command } from './as-runner.js';
+
+const BIN = path.resolve(import.meta.dirname, '..', '..', 'bin');
+
+export class ScriptError extends Error {
+ constructor(
+ script: string,
+ readonly code: number | null,
+ readonly stderr: string,
+ /** Stopped at its timeout. */
+ readonly killed = false,
+ ) {
+ super(`${script}: ${killed ? 'timed out' : stderr.trim() || `exit ${code}`}`);
+ }
+}
+
+export interface ScriptRunner {
+ /** Run bin/<script> with these arguments; resolves with stdout, rejects with ScriptError { code, stderr } on a non-zero exit or the timeout (0: none). */
+ run(script: string, args: string[], o: { stdin?: string; timeoutMs: number }): Promise<string>;
+ /** How this runner names the clones directory and a workspace: host paths, or /clones and /workspace. */
+ clones: string;
+ workspace(hostForkPath: string): string;
+}
+
+/** The scripts on the host, for one clones directory (a person's `ws`). */
+export function hostScripts(clones: string): ScriptRunner {
+ return {
+ clones,
+ workspace: (hostForkPath) => hostForkPath,
+ run(script, args, o) {
+ const c = command('sh', [path.join(BIN, script), ...args], { GIT_TERMINAL_PROMPT: '0' });
+ return new Promise<string>((resolve, reject) => {
+ const p = spawn(c.cmd, c.args, { env: c.env, stdio: [o.stdin === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'] });
+ let out = '';
+ let err = '';
+ let killed = false;
+ const timer = o.timeoutMs > 0 ? setTimeout(() => ((killed = true), p.kill('SIGTERM')), o.timeoutMs) : undefined;
+ p.stdout!.setEncoding('utf8').on('data', (d) => (out += d));
+ p.stderr!.setEncoding('utf8').on('data', (d) => (err += d));
+ p.on('error', (e) => (clearTimeout(timer), reject(e)));
+ p.on('close', (code) => {
+ clearTimeout(timer);
+ killed || code !== 0 ? reject(new ScriptError(script, code, err, killed)) : resolve(out);
+ });
+ if (o.stdin !== undefined) {
+ p.stdin!.on('error', () => {}); // a script that ended early: its exit says so
+ p.stdin!.end(o.stdin);
+ }
+ });
+ },
+ };
+}
+
+/** A script's lines by repository: the fields after the repository, the first `ok` or `failed`. */
+export function rows(stdout: string): Map<string, string[]> {
+ const found = new Map<string, string[]>();
+ for (const line of stdout.split('\n')) {
+ if (!line) continue;
+ const [repo, ...fields] = line.split('\t');
+ found.set(repo, fields);
+ }
+ return found;
+}
+
+/** The fields of an `ok` line for this repository; throws the message of a `failed` one. */
+export function row(stdout: string, repo: string): string[] {
+ const [status, ...fields] = rows(stdout).get(repo) ?? [];
+ if (status === 'ok') return fields;
+ throw new Error(status === 'failed' ? fields[0] || 'failed' : `no result for ${repo}`);
+}