openvibers/openvibe-git Commits

Forge CI on the shared node: runs side by side, work in memory, installs kept per lockfile (#118)

OP OpenVibers committed 12 days ago · 3fa5b49247 · 21 files, +800 −65

* Forge CI on the shared node: runs side by side, work in memory, installs kept per lockfile

The owner, 2026-11-19: 'handle CI with our own system interconnected with git.openvibe.codes … modular, optimized,
efficient … using the shared node and making use of the RAM'. The runner ran one job at a time on the workstation for
four repositories, and every run reinstalled its dependencies from scratch.
- runner/index.js: concurrency workers (up to 8), each claiming as <host>/<n>; the start line says whether the work
  directories are in memory.
- runner/deps-cache.js: after an install succeeds, what it made (node_modules folders, files it wrote) is kept, keyed
  by the repository, lockfiles, install scripts, command, image, engine and Node; a later run with the same key has
  no install phase. Taken before the tests; least recently used out first. 'auto' commands from the lockfile.
- runner/sandbox.js: npm and pnpm download caches shared at /cache in the install phase only; Node's own fetch uses
  the proxy (NODE_USE_ENV_PROXY).
- runner/run.js: per-run kills (a superseded run is now actually stopped: currentKill was never set), timings in the
  description.
- deploy/ci/node-setup.sh and openvibe-git-ci-node.service: the ovci user, a tmpfs for the work, the caches, pnpm.
test/ci-deps-cache.test.js.

* /ci: every repository's runs on our own runner, in one place

What runs now and on which worker, the queue, the latest verdicts with where the time went, and the last day's
numbers (runs, passed, median time, installs from the cache). The JSON is /api/v1/ci/board; each repository's CI page
links it. test/ci.test.js checks the board and the page.

* Forge CI: a push with the same files as a passed run is answered by that run

A pull request merged onto an unmoved main, or a branch made from a tested commit, has exactly the files that already
passed; testing them again only queued real work behind it. Each run now records its tree (migration 0012, expand);
a push whose tree matches a passed run of the same repository is recorded as passed at once ('Same files as <sha>
(<branch>), which passed: …', runner 'forge (same files)') with its commit status. A run started by hand always runs.
test/ci.test.js covers both.

* Git's own tests pass in the forge's sandbox (no network, no nested sandbox)

The node runner's first run of this repository found two tests that needed what its test phase does not have:
- mirrors-quota resolved github.com for real (the mirror's URL check had no lookup to stub): createMirrors takes the
  app's lookup, and the test passes its stub.
- ci-runner started a bubblewrap sandbox inside the runner's own: it skips that end-to-end run when the test phase
  says OV_SANDBOX_OFFLINE=1.

Changes

ddiff --git a/deploy/ci/node-setup.sh b/deploy/ci/node-setup.sh
nnew file mode 100755
iindex 0000000..0c31dd1
---- /dev/null
++++ b/deploy/ci/node-setup.sh
@@@ -0,0 +1,75 @@
++#!/bin/bash
++# The forge CI runner on a shared node (2026-11-19: ov-node-01, 8 cores, 15 GB). Run as root; safe to run again.
++#
++# sudo deploy/ci/node-setup.sh <git ref> (then put the token and the configuration in place, below)
++#
++# - a system user `ovci` with its own systemd user manager (linger), which owns the runs' cgroup scopes;
++# - the work directories in memory: a tmpfs at /var/lib/ovci/work (8 GB at most, used only as runs fill it);
++# - the kept installs and the package managers' download caches on disk under /var/lib/ovci/cache (the page cache
++# keeps the busy ones in memory and gives it back when the node needs it);
++# - pnpm for the repositories that use it (bubblewrap runs the host's /usr, not an image);
++# - the runner itself: a root-owned checkout of OpenVibe.Git at /var/lib/ovci/runner (the runner can read it, not
++# change it), started by the user unit openvibe-git-ci.service.
++# The runner token (/var/lib/ovci/.config/openvibe/git-ci.token, 0600) and git-ci.json are copied in by hand; neither
++# is in this repository.
++set -euo pipefail
++REF=${1:-main}
++REPO=${OV_GIT_REPO:-https://github.com/OpenVibers/OpenVibe-Git.git}
++HOME_DIR=/var/lib/ovci
++PNPM_VERSION=${PNPM_VERSION:-10.6.5}
++
++id ovci >/dev/null 2>&1 || useradd --system --home-dir "$HOME_DIR" --create-home --shell /usr/sbin/nologin --comment 'OpenVibe forge CI runner' ovci
++OVCI_UID=$(id -u ovci)
++install -d -o ovci -g ovci -m 0700 "$HOME_DIR" "$HOME_DIR/cache" "$HOME_DIR/cache/deps" "$HOME_DIR/cache/shared" \
++ "$HOME_DIR/.config" "$HOME_DIR/.config/openvibe" "$HOME_DIR/.config/systemd" "$HOME_DIR/.config/systemd/user"
++install -d -o ovci -g ovci -m 0700 "$HOME_DIR/work"
++
++# The work directories in memory.
++cat > /etc/systemd/system/var-lib-ovci-work.mount <<EOF
++[Unit]
++Description=OpenVibe forge CI work directories, in memory
++Before=user@${OVCI_UID}.service
++
++[Mount]
++What=tmpfs
++Where=$HOME_DIR/work
++Type=tmpfs
++Options=size=8G,mode=0700,uid=${OVCI_UID},gid=$(id -g ovci),nosuid,nodev
++
++[Install]
++WantedBy=multi-user.target
++EOF
++systemctl daemon-reload
++systemctl enable --now var-lib-ovci-work.mount
++
++# pnpm into /usr (bubblewrap binds the host's /usr read-only).
++if ! command -v pnpm >/dev/null 2>&1 || [ "$(pnpm --version 2>/dev/null)" != "$PNPM_VERSION" ]; then
++ npm install -g --no-audit --no-fund "pnpm@$PNPM_VERSION" >/dev/null
++fi
++
++# The runner's code, owned by root.
++if [ -d "$HOME_DIR/runner/.git" ]; then
++ git -C "$HOME_DIR/runner" fetch --quiet origin "$REF"
++ git -C "$HOME_DIR/runner" checkout --quiet --force FETCH_HEAD
++else
++ rm -rf "$HOME_DIR/runner"
++ git clone --quiet "$REPO" "$HOME_DIR/runner"
++ git -C "$HOME_DIR/runner" fetch --quiet origin "$REF"
++ git -C "$HOME_DIR/runner" checkout --quiet --force FETCH_HEAD
++fi
++chown -R root:root "$HOME_DIR/runner"
++chmod -R go-w "$HOME_DIR/runner"
++install -o ovci -g ovci -m 0644 "$HOME_DIR/runner/deploy/systemd-user/openvibe-git-ci-node.service" "$HOME_DIR/.config/systemd/user/openvibe-git-ci.service"
++
++loginctl enable-linger ovci
++# Wait for the user manager, then (re)start the runner if its token and configuration are in place.
++for _ in 1 2 3 4 5 6 7 8 9 10; do [ -S "/run/user/$OVCI_UID/bus" ] && break; sleep 1; done
++as_ovci() { runuser -u ovci -- env XDG_RUNTIME_DIR="/run/user/$OVCI_UID" DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$OVCI_UID/bus" "$@"; }
++as_ovci systemctl --user daemon-reload
++if [ -s "$HOME_DIR/.config/openvibe/git-ci.token" ] && [ -s "$HOME_DIR/.config/openvibe/git-ci.json" ]; then
++ as_ovci systemctl --user enable openvibe-git-ci.service >/dev/null 2>&1
++ as_ovci systemctl --user restart openvibe-git-ci.service
++ echo "runner at $(git -C "$HOME_DIR/runner" rev-parse --short HEAD) (re)started"
++else
++ echo "put git-ci.token (0600) and git-ci.json in $HOME_DIR/.config/openvibe, then run this again"
++fi
ddiff --git a/deploy/systemd-user/openvibe-git-ci-node.service b/deploy/systemd-user/openvibe-git-ci-node.service
nnew file mode 100644
iindex 0000000..aca1dc6
---- /dev/null
++++ b/deploy/systemd-user/openvibe-git-ci-node.service
@@@ -0,0 +1,23 @@
++[Unit]
++Description=OpenVibe.Git forge CI runner (shared node; bubblewrap sandboxes, work in memory)
++Documentation=https://git.openvibe.codes/openvibers/openvibe-git/src/branch/main/docs/ci.md
++After=network-online.target
++Wants=network-online.target
++
++[Service]
++Type=simple
++WorkingDirectory=/var/lib/ovci/runner
++Environment=NODE_ENV=production
++Environment=PATH=/usr/local/bin:/usr/bin:/bin
++Environment=GIT_CI_CONFIG=/var/lib/ovci/.config/openvibe/git-ci.json
++ExecStart=/usr/bin/node /var/lib/ovci/runner/runner/index.js
++Restart=always
++RestartSec=10
++KillMode=control-group
++KillSignal=SIGTERM
++# SIGTERM kills the current runs' scopes; they report "the runner stopped" and the forge queues the next push.
++TimeoutStopSec=60
++LimitNOFILE=65536
++
++[Install]
++WantedBy=default.target
ddiff --git a/docs/ci.md b/docs/ci.md
iindex 703834b..ea4f8d7 100644
---- a/docs/ci.md
++++ b/docs/ci.md
@@@ -1,7 +1,7 @@
# Forge CI
--`git.openvibe.codes` runs the tests for a push to an OpenVibers repository on the workstation, in a sandbox, and
--reports the verdict on the commit. GitHub Actions stays exactly as it is: this is the first-party path that runs
++`git.openvibe.codes` runs the tests for a push to an OpenVibers repository on the shared node (since 2026-11-19;
++it was the workstation), in a sandbox, and reports the verdict on the commit. GitHub Actions stays exactly as it is: this is the first-party path that runs
beside it, not a replacement yet. Nothing in this document turns a GitHub workflow off.
## What runs, and when
@@@ -74,7 +74,7 @@ reason.
| network | install: loopback only, with the proxy on a Unix socket (the sandbox has no route anywhere else). test: no network namespace route at all |
| limits | `--cpus 4`, `--memory 6144m` (swap the same), `--pids-limit 2048`, 30 minutes wall clock (configurable 30 s–1 h). A run past it is killed and reported `timed_out`; a runner that disappears is reaped by the service a minute after its limit |
| capabilities | all dropped, `no-new-privileges`, a new session; bubblewrap also disables nested user namespaces |
--| concurrency | one run per repository (the forge's rule), and one at a time on this runner by default (`concurrency`) |
++| concurrency | one run per repository (the forge's rule); `concurrency` runs at once per runner (1 by default, 3 on the shared node, at most 8) |
**What is not contained, and why.** A container is not a virtual machine: a kernel or runtime escape is still a
host compromise, and the workstation is the busiest machine in the estate (it also runs the portal and agent jobs).
@@@ -109,6 +109,53 @@ the gate. If the machine is ever dedicated to CI, a disposable VM per run is the
Removing an entry stops new runs; it does not delete past runs or their statuses.
++## Running it on the shared node (2026-11-19)
++
++The owner: "handle CI with our own system interconnected with git.openvibe.codes … modular, optimized, efficient …
++using the shared node and making use of the RAM". The runner moved from the workstation (one run at a time, four
++repositories) to `ov-node-01` (8 cores, 15 GB):
++
++- **Every repository with tests.** All 68 official repositories with a `package.json` and a test script are
++ registered with `auto` commands: the checkout decides (`pnpm-lock.yaml` → `pnpm install --frozen-lockfile`, an npm
++ lockfile → `npm ci`, a `package.json` alone → `npm install`; then `npm test`). A repository with no test script
++ reports "Nothing to test here" instead of failing. A repository that needs more names its commands (Live skips
++ onnxruntime's CUDA download; Games runs typecheck and lint like its workflow).
++- **Three runs at once** (`concurrency`, up to 8). The forge keeps one live run per repository, so they are always
++ different repositories. Each worker claims as `<host>/<n>`.
++- **Work in memory.** The work directories are a tmpfs (`/var/lib/ovci/work`, 8 GB at most): an install's tens of
++ thousands of files never touch the disk, and a run's directory is gone when it ends.
++- **Installs kept per lockfile** (`runner/deps-cache.js`). After an install phase succeeds, what it made (every
++ `node_modules` outside another one, and any file it wrote outside them) is kept, keyed by the repository, its
++ lockfile(s), the root `package.json`'s install scripts and package manager, the install command, the image, the
++ engine and the runner's Node. A later run with the same key copies it back and has **no install phase**; most
++ pushes change code, not the lockfile. The copy is taken before any test runs, so no test can change what a later
++ run gets. The store is on disk (`depsCache`, 40 GB at most, least recently used first): the page cache keeps the
++ busy entries in memory and gives it back when the node needs it.
++- **Download caches shared.** npm's and pnpm's caches (`sharedCache`) are mounted at `/cache` in the install phase
++ only, so a pin bump (every lockfile changes) still downloads only what changed. npm and pnpm check each tarball
++ against the lockfile's integrity, so one run cannot hand another a different package. The test phase never sees it.
++- **Node's own fetch uses the proxy** (`NODE_USE_ENV_PROXY=1`, Node 22.21 and later): a postinstall that downloads a
++ prebuilt binary (mediasoup's worker) works through the same allowlist, which on the node also has `github.com`,
++ `objects.githubusercontent.com` and `release-assets.githubusercontent.com`.
++- **The verdict** is the forge's `forge/test` status; the node has no GitHub login, so it does not post to GitHub
++ (`"githubStatus": false`). The ship scripts read the forge's verdict directly.
++
++Each run's description says where the time went: `Forge runner passed in 2m 10s (install 3s from the cache, tests
++2m 4s)`.
++
++```sh
++# on the node, from a checkout of OpenVibe.Git (or scp the script): root, idempotent
++sudo deploy/ci/node-setup.sh <git ref>
++# then, once: the runner token (0600) and git-ci.json into /var/lib/ovci/.config/openvibe, and run it again
++sudo -u ovci XDG_RUNTIME_DIR=/run/user/$(id -u ovci) journalctl --user -u openvibe-git-ci -f
++```
++
++`node-setup.sh` makes the `ovci` system user (its own systemd user manager, so the runs' cgroup scopes have their
++memory and CPU caps), the tmpfs mount unit, the cache folders, pnpm in `/usr`, and a root-owned checkout of this
++repository at `/var/lib/ovci/runner` (the runner reads it and cannot change it), then installs
++`deploy/systemd-user/openvibe-git-ci-node.service` and restarts it. Updating the runner is the same command with the
++new ref.
++
## Running it on the workstation
```sh
ddiff --git a/migrations/0012_ci_run_tree.sql b/migrations/0012_ci_run_tree.sql
nnew file mode 100644
iindex 0000000..8b6950a
---- /dev/null
++++ b/migrations/0012_ci_run_tree.sql
@@@ -0,0 +1,7 @@
++-- phase: expand
++-- Forge CI: the tree each run tested (2026-11-19). A push whose files are exactly those of a run that already passed
++-- (a pull request merged onto an unmoved main, a branch made from a tested commit) is answered from that run instead of
++-- testing the same files again. Runs made before this have no tree and are simply never matched.
++ALTER TABLE git_ci_runs ADD COLUMN tree text;
++ALTER TABLE git_ci_runs ADD CONSTRAINT git_ci_runs_tree_hex CHECK (tree IS NULL OR tree ~ '^[0-9a-f]{40}([0-9a-f]{24})?$');
++CREATE INDEX git_ci_runs_repo_tree_passed ON git_ci_runs (repo_id, tree) WHERE state = 'success' AND tree IS NOT NULL;
ddiff --git a/runner/api.js b/runner/api.js
iindex 4017b48..897487c 100644
---- a/runner/api.js
++++ b/runner/api.js
@@@ -27,7 +27,7 @@ function createApi({ baseUrl, token, log = console }) {
return {
request,
register: (repos) => request('/api/v1/ci/repos', { method: 'POST', body: { repos } }),
-- claim: () => request('/api/v1/ci/runs/claim', { method: 'POST', body: { runner: os.hostname() || 'forge-runner' } }),
++ claim: (name) => request('/api/v1/ci/runs/claim', { method: 'POST', body: { runner: String(name || os.hostname() || 'forge-runner').slice(0, 100) } }),
heartbeat: (id) => request(`/api/v1/ci/runs/${encodeURIComponent(id)}/heartbeat`),
log: (id, chunk) => request(`/api/v1/ci/runs/${encodeURIComponent(id)}/log`, { method: 'POST', body: { chunk }, timeoutMs: 30_000 }),
finish: async (id, verdict) => {
ddiff --git a/runner/config.js b/runner/config.js
iindex 9239f93..548168b 100644
---- a/runner/config.js
++++ b/runner/config.js
@@@ -9,15 +9,18 @@
* "tokenFile": "~/.config/openvibe/git-ci.token",
* "workRoot": "~/.cache/openvibe-git-ci",
* "engine": "auto", // auto | podman | bwrap
-- * "concurrency": 1,
++ * "concurrency": 1, // runs at once (1-8); the shared node runs 3
++ * "depsCache": "~/.cache/openvibe-git-ci/deps", // installs kept between runs ("" turns it off)
++ * "depsCacheMb": 20480,
++ * "sharedCache": "~/.cache/openvibe-git-ci/shared", // npm and pnpm download caches, install phase only ("" off)
* "githubStatus": true, // also post the verdict to the GitHub pull request (via gh)
* "githubContext": "forge/test",
* "pollMs": 5000,
* "proxyAllow": ["registry.npmjs.org", "codeload.github.com", "git.openvibe.codes"],
* "repos": {
* "openvibers/openvibe.shared": {
-- * "install_command": "npm ci --no-audit --no-fund",
-- * "test_command": "npm test",
++ * "install_command": "auto", // auto (the default): pnpm, npm ci or npm install by lockfile
++ * "test_command": "auto", // auto: npm test, or nothing when there is no test script
* "timeout_seconds": 1800
* }
* }
@@@ -63,7 +66,12 @@ function loadConfig(env = process.env) {
podmanStorageConf: expand(raw.podmanStorageConf || path.join(HOME, '.config', 'openvibe', 'containers-storage.conf')),
engine: ['auto', 'podman', 'bwrap'].includes(raw.engine) ? raw.engine : 'auto',
image: String(raw.image || 'docker.io/library/node:22-bookworm'),
-- concurrency: int(raw.concurrency, 1, 1, 4),
++ concurrency: int(raw.concurrency, 1, 1, 8),
++ // Installs kept between runs (runner/deps-cache.js) and the package managers' download caches. Both live on
++ // disk: the page cache keeps the busy ones in memory and gives it back when something else needs it.
++ depsCache: raw.depsCache === '' ? '' : expand(raw.depsCache || path.join(HOME, '.cache', 'openvibe-git-ci', 'deps')),
++ depsCacheMb: int(raw.depsCacheMb, 20480, 256, 1_048_576),
++ sharedCache: raw.sharedCache === '' ? '' : expand(raw.sharedCache || path.join(HOME, '.cache', 'openvibe-git-ci', 'shared')),
// The verdict goes to GitHub through the workstation's gh login, so the pull request shows it beside
// GitHub Actions. Off only when the owner says so; the forge status is written either way.
githubStatus: raw.githubStatus !== false,
@@@ -78,8 +86,8 @@ function loadConfig(env = process.env) {
cfg.repos = Object.fromEntries(Object.entries(cfg.repos).map(([full, item]) => [
String(full).toLowerCase(),
{
-- install_command: String((item && item.install_command) || 'npm ci --no-audit --no-fund'),
-- test_command: String((item && item.test_command) || 'npm test'),
++ install_command: String((item && item.install_command) || 'auto'),
++ test_command: String((item && item.test_command) || 'auto'),
timeout_seconds: int(item && item.timeout_seconds, 1800, 30, 3600),
image: String((item && item.image) || cfg.image),
cpus: int(item && item.cpus, 4, 1, 8),
ddiff --git a/runner/deps-cache.js b/runner/deps-cache.js
nnew file mode 100644
iindex 0000000..b54aa67
---- /dev/null
++++ b/runner/deps-cache.js
@@@ -0,0 +1,205 @@
++'use strict';
++
++/**
++ * Installed dependencies kept between runs (2026-11-19, the owner: "our own modular, optimized, efficient … better
++ * system … making use of the RAM").
++ *
++ * Most pushes change code, not the lockfile, yet every run reinstalled the same dependencies from scratch (Live:
++ * 824 MB in 19,000 files). After an install phase succeeds, the runner keeps what it made, keyed by everything that
++ * decides it: the repository, its lockfile(s), the root package.json's install scripts, the install command, the image
++ * and engine, the runner's Node and platform. A later run with the same key copies it back and skips the install
++ * phase entirely; its tests still run in their own sandbox with no network.
++ *
++ * What is kept: every node_modules folder outside another one, plus any file outside them that the install created or
++ * changed (a `prepare` build's output). The copy is taken right after the install, before any test runs, so a test can
++ * never change what a later run gets. The store lives on disk, so the kernel's page cache keeps the busy entries in
++ * memory and gives the memory back under pressure; the least recently used entries go first once it passes its size.
++ */
++const fs = require('node:fs');
++const path = require('node:path');
++const crypto = require('node:crypto');
++const { spawn } = require('node:child_process');
++
++const LOCKFILES = ['package-lock.json', 'npm-shrinkwrap.json', 'pnpm-lock.yaml', 'yarn.lock'];
++const INSTALL_SCRIPTS = ['preinstall', 'install', 'postinstall', 'prepare', 'preprepare', 'postprepare'];
++// The runner's own folders in a run's work directory, never part of what the repository installs.
++const RUNNER_DIRS = new Set(['.git', '.ci', '.home', '.cache', '.pnpm']);
++const KEY_VERSION = 1;
++
++function readJson(file) {
++ try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
++}
++
++/** The cache key for a checkout, or null when it has no lockfile (an install without one is not reproducible). */
++function cacheKey({ dir, repo, install, image = '', engine = '', node = process.version }) {
++ const locks = LOCKFILES.filter((f) => fs.existsSync(path.join(dir, f)));
++ if (!locks.length) return null;
++ const pkg = readJson(path.join(dir, 'package.json')) || {};
++ const scripts = Object.fromEntries(INSTALL_SCRIPTS.filter((s) => pkg.scripts && pkg.scripts[s]).map((s) => [s, pkg.scripts[s]]));
++ const hash = crypto.createHash('sha256');
++ hash.update(JSON.stringify({
++ v: KEY_VERSION, repo: String(repo || '').toLowerCase(), install: String(install || ''), image: String(image || ''),
++ engine: String(engine || ''), node, platform: process.platform, arch: process.arch, scripts,
++ packageManager: pkg.packageManager || null, workspaces: pkg.workspaces || null,
++ }));
++ for (const f of locks) {
++ hash.update(`\0${f}\0`);
++ hash.update(fs.readFileSync(path.join(dir, f)));
++ }
++ return hash.digest('hex').slice(0, 40);
++}
++
++/**
++ * Every file outside node_modules (and outside the runner's folders), with its size and time, and every top-level
++ * node_modules folder. Cheap: a repository's own files, not its dependencies.
++ */
++function survey(dir) {
++ const files = new Map();
++ const modules = [];
++ const walk = (rel) => {
++ let entries;
++ try { entries = fs.readdirSync(path.join(dir, rel), { withFileTypes: true }); } catch { return; }
++ for (const e of entries) {
++ const child = rel ? `${rel}/${e.name}` : e.name;
++ if (!rel && RUNNER_DIRS.has(e.name)) continue;
++ if (e.name === 'node_modules' && e.isDirectory()) { modules.push(child); continue; }
++ if (e.isDirectory()) { walk(child); continue; }
++ try {
++ const st = fs.lstatSync(path.join(dir, child));
++ files.set(child, `${st.size}:${Math.round(st.mtimeMs)}`);
++ } catch { /* gone */ }
++ }
++ };
++ walk('');
++ return { files, modules };
++}
++
++/** What an install made: its node_modules folders and the files it created or changed outside them. */
++function installed(before, after) {
++ const changed = [];
++ for (const [rel, sig] of after.files) if (before.files.get(rel) !== sig) changed.push(rel);
++ return { modules: after.modules.slice().sort(), changed: changed.sort() };
++}
++
++function run(command, args, { cwd } = {}) {
++ return new Promise((resolve, reject) => {
++ const child = spawn(command, args, { cwd, stdio: ['ignore', 'ignore', 'pipe'] });
++ let err = '';
++ child.stderr.on('data', (d) => { err = (err + d).slice(-2000); });
++ child.on('error', reject);
++ child.on('close', (code) => (code === 0 ? resolve() : reject(new Error(`${command} exited ${code}: ${err.trim().slice(0, 300)}`))));
++ });
++}
++
++async function copyPaths(fromDir, rels, toDir) {
++ fs.mkdirSync(toDir, { recursive: true });
++ for (let i = 0; i < rels.length; i += 200) {
++ await run('cp', ['-a', '--reflink=auto', '--parents', '-t', toDir, '--', ...rels.slice(i, i + 200)], { cwd: fromDir });
++ }
++}
++
++function duBytes(dir) {
++ let total = 0;
++ const walk = (p) => {
++ let entries;
++ try { entries = fs.readdirSync(p, { withFileTypes: true }); } catch { return; }
++ for (const e of entries) {
++ const child = path.join(p, e.name);
++ if (e.isDirectory()) walk(child);
++ else { try { total += fs.lstatSync(child).size; } catch { /* gone */ } }
++ }
++ };
++ walk(dir);
++ return total;
++}
++
++function createDepsCache({ root, maxMb = 20480, log = () => {} }) {
++ if (!root) return null;
++ fs.mkdirSync(root, { recursive: true, mode: 0o700 });
++ const entry = (key) => path.join(root, key);
++ const maxBytes = Math.max(256, Number(maxMb) || 20480) * 1024 * 1024;
++
++ /** Copy a kept install into the run's checkout. Returns what it restored, or null on a miss. */
++ async function restore(key, dir) {
++ if (!key) return null;
++ const at = entry(key);
++ const manifest = readJson(path.join(at, 'manifest.json'));
++ if (!manifest || !fs.existsSync(path.join(at, 'files'))) return null;
++ const started = Date.now();
++ await run('cp', ['-a', '--reflink=auto', '--', `${path.join(at, 'files')}/.`, dir]);
++ const now = new Date();
++ try { fs.utimesSync(path.join(at, 'manifest.json'), now, now); } catch { /* evicted meanwhile */ }
++ return { ...manifest, ms: Date.now() - started };
++ }
++
++ /** Keep what an install made (taken before the tests run), then trim the store to its size. */
++ async function save(key, dir, made) {
++ if (!key || !made || (!made.modules.length && !made.changed.length)) return null;
++ if (fs.existsSync(path.join(entry(key), 'manifest.json'))) return null;
++ const started = Date.now();
++ const tmp = path.join(root, `.tmp-${key}-${process.pid}-${crypto.randomBytes(4).toString('hex')}`);
++ try {
++ await copyPaths(dir, [...made.modules, ...made.changed], path.join(tmp, 'files'));
++ const bytes = duBytes(path.join(tmp, 'files'));
++ const manifest = { key, bytes, modules: made.modules, changed: made.changed.length, saved_at: new Date().toISOString() };
++ fs.writeFileSync(path.join(tmp, 'manifest.json'), JSON.stringify(manifest));
++ try {
++ fs.renameSync(tmp, entry(key));
++ } catch {
++ // Another run with the same key kept it first.
++ fs.rmSync(tmp, { recursive: true, force: true });
++ return null;
++ }
++ trim();
++ return { ...manifest, ms: Date.now() - started };
++ } catch (err) {
++ fs.rmSync(tmp, { recursive: true, force: true });
++ log(`[git-ci-runner] the install was not kept: ${err.message}`);
++ return null;
++ }
++ }
++
++ /** Remove the least recently used entries until the store fits (and half-written ones a crash left behind). */
++ function trim() {
++ let names;
++ try { names = fs.readdirSync(root); } catch { return; }
++ const rows = [];
++ for (const name of names) {
++ const at = path.join(root, name);
++ if (name.startsWith('.tmp-')) {
++ try { if (Date.now() - fs.statSync(at).mtimeMs > 3600_000) fs.rmSync(at, { recursive: true, force: true }); } catch { /* gone */ }
++ continue;
++ }
++ const manifest = readJson(path.join(at, 'manifest.json'));
++ if (!manifest) { fs.rmSync(at, { recursive: true, force: true }); continue; }
++ let used = 0;
++ try { used = fs.statSync(path.join(at, 'manifest.json')).mtimeMs; } catch { /* gone */ }
++ rows.push({ at, bytes: Number(manifest.bytes) || 0, used });
++ }
++ rows.sort((a, b) => b.used - a.used);
++ let total = 0;
++ for (const row of rows) {
++ total += row.bytes;
++ if (total > maxBytes) fs.rmSync(row.at, { recursive: true, force: true });
++ }
++ }
++
++ return { root, restore, save, trim };
++}
++
++/**
++ * The commands for a repository registered with `auto` (the default for a new one): a pnpm lockfile installs with
++ * pnpm, an npm lockfile with `npm ci`, a package.json alone with `npm install`; the tests are `npm test`. A repository
++ * without a package.json, or without a test script, has nothing to run here.
++ */
++function autoCommands(dir) {
++ const pkg = readJson(path.join(dir, 'package.json'));
++ if (!pkg) return { none: 'no package.json' };
++ if (!pkg.scripts || !pkg.scripts.test) return { none: 'package.json has no test script' };
++ let install = 'npm install --no-audit --no-fund';
++ if (fs.existsSync(path.join(dir, 'pnpm-lock.yaml'))) install = 'pnpm install --frozen-lockfile';
++ else if (fs.existsSync(path.join(dir, 'package-lock.json')) || fs.existsSync(path.join(dir, 'npm-shrinkwrap.json'))) install = 'npm ci --no-audit --no-fund';
++ return { install, test: 'npm test' };
++}
++
++module.exports = { createDepsCache, cacheKey, survey, installed, autoCommands, LOCKFILES };
ddiff --git a/runner/index.js b/runner/index.js
iindex 77d8c6d..4950c83 100644
---- a/runner/index.js
++++ b/runner/index.js
@@@ -1,9 +1,10 @@
'use strict';
/**
-- * The forge CI runner (workstation). It polls OpenVibe.Git for the next queued run, executes it in the sandbox
-- * (runner/run.js) and reports the log and the verdict. One run at a time by default; the forge decides what is
-- * queued and supersedes, so the runner never chooses or trusts a repository itself.
++ * The forge CI runner. It polls OpenVibe.Git for the next queued run, executes it in the sandbox (runner/run.js) and
++ * reports the log and the verdict. `concurrency` workers claim runs side by side (the shared node runs 3; the forge
++ * keeps one live run per repository, so they are always different repositories); the forge decides what is queued and
++ * supersedes, so the runner never chooses or trusts a repository itself.
*
* node runner/index.js
* GIT_CI_CONFIG=... GIT_CI_RUNNER_TOKEN=... node runner/index.js
@@@ -15,6 +16,11 @@ const { createApi } = require('./api');
const { createRunner } = require('./run');
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
++// tmpfs: the work directories are in memory, so an install's tens of thousands of files never touch the disk.
++const TMPFS_MAGIC = 0x01021994;
++const inMemory = (dir) => {
++ try { return fs.statfsSync(dir).type === TMPFS_MAGIC; } catch { return false; }
++};
async function main(env = process.env) {
const cfg = loadConfig(env);
@@@ -24,7 +30,7 @@ async function main(env = process.env) {
const repos = registrations(cfg);
let stopping = false;
const onSignal = (signal) => {
-- process.stdout.write(`[git-ci-runner] ${signal}: stopping after the current run\n`);
++ process.stdout.write(`[git-ci-runner] ${signal}: stopping the current runs\n`);
stopping = true;
runner.stop();
};
@@@ -45,26 +51,33 @@ async function main(env = process.env) {
}
if (!stopping && !repos.length) process.stdout.write('[git-ci-runner] no repositories configured; only claiming nothing\n');
++ process.stdout.write(`[git-ci-runner] ${cfg.concurrency} worker${cfg.concurrency === 1 ? '' : 's'}; work directories ${inMemory(cfg.workRoot) ? 'in memory (tmpfs)' : 'on disk'}\n`);
let lastEmpty = 0;
-- while (!stopping) {
-- try {
-- const job = await api.claim();
-- if (!job) {
-- if (Date.now() - lastEmpty > 60_000) {
-- process.stdout.write(`[git-ci-runner] idle on ${os.hostname()} (${cfg.api})\n`);
-- lastEmpty = Date.now();
++ const worker = async (slot) => {
++ const name = cfg.concurrency > 1 ? `${os.hostname()}/${slot}` : os.hostname();
++ // Spread the first claims so the workers do not ask the forge in the same instant.
++ await wait((slot - 1) * Math.round(cfg.pollMs / cfg.concurrency));
++ while (!stopping) {
++ try {
++ const job = await api.claim(name);
++ if (!job) {
++ if (slot === 1 && Date.now() - lastEmpty > 60_000) {
++ process.stdout.write(`[git-ci-runner] idle on ${os.hostname()} (${cfg.api})\n`);
++ lastEmpty = Date.now();
++ }
++ await wait(cfg.pollMs);
++ continue;
}
-- await wait(cfg.pollMs);
-- continue;
++ lastEmpty = Date.now();
++ const out = await runner.runJob(job);
++ process.stdout.write(`[git-ci-runner] ${name} ${job.run.id} ${out.state} in ${Math.round(out.duration / 1000)}s\n`);
++ } catch (err) {
++ process.stdout.write(`[git-ci-runner] ${name} loop: ${err.message}\n`);
++ await wait(Math.max(cfg.pollMs, 5000));
}
-- lastEmpty = Date.now();
-- const out = await runner.runJob(job);
-- process.stdout.write(`[git-ci-runner] ${job.run.id} ${out.state} in ${Math.round(out.duration / 1000)}s\n`);
-- } catch (err) {
-- process.stdout.write(`[git-ci-runner] loop: ${err.message}\n`);
-- await wait(Math.max(cfg.pollMs, 5000));
}
-- }
++ };
++ await Promise.all(Array.from({ length: cfg.concurrency }, (_, i) => worker(i + 1)));
process.stdout.write('[git-ci-runner] stopped\n');
}
ddiff --git a/runner/run.js b/runner/run.js
iindex e534a9a..9fb3077 100644
---- a/runner/run.js
++++ b/runner/run.js
@@@ -13,6 +13,7 @@ const { createProxy } = require('./proxy');
const { runProcess } = require('./process');
const { podmanArgs, bwrapArgs, bwrapScope, installScript, podmanCleanup, scopeCleanup, detectEngine, RELAY } = require('./sandbox');
const { reportGithubStatus } = require('./github-status');
++const { createDepsCache, cacheKey, survey, installed, autoCommands } = require('./deps-cache');
@@@ -24,6 +25,7 @@ const git = (args, cwd, timeoutMs = 180_000) => new Promise((resolve, reject) =>
});
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
++const size = (bytes) => (bytes >= 1024 ** 3 ? `${(bytes / 1024 ** 3).toFixed(1)} GB` : `${Math.round(bytes / 1024 ** 2)} MB`);
const words = (ms) => {
const s = Math.max(0, Math.round(Number(ms) / 1000));
return s >= 60 ? `${Math.floor(s / 60)}m ${s % 60}s` : `${s}s`;
@@@ -77,7 +79,10 @@ function createRunner({ cfg, api, log = console, clock = Date.now }) {
if (image.error || image.status !== 0) say(`[git-ci-runner] image ${cfg.image} is not in ${cfg.podmanRoot}; run deploy/ci/install.sh`);
}
say(`[git-ci-runner] sandbox: ${engine.why}; ${Object.keys(cfg.repos).length} repositories configured`);
-- let activeKill = null;
++ const deps = cfg.depsCache ? createDepsCache({ root: cfg.depsCache, maxMb: cfg.depsCacheMb, log: say }) : null;
++ if (cfg.sharedCache) for (const sub of ['npm', 'pnpm-store']) fs.mkdirSync(path.join(cfg.sharedCache, sub), { recursive: true, mode: 0o700 });
++ // Every phase running now, across the runs this runner holds at once: stop() ends them all.
++ const activeKills = new Set();
let stopping = false;
async function runJob(job) {
@@@ -136,11 +141,11 @@ function createRunner({ cfg, api, log = console, clock = Date.now }) {
if (engine.kind === 'podman') {
return {
command: 'podman',
-- args: [...rootArgs, ...podmanArgs({ name, workspace: runDir, image: job.image, limits, proxySock, script: command })],
++ args: [...rootArgs, ...podmanArgs({ name, workspace: runDir, image: job.image, limits, proxySock, sharedCache: cfg.sharedCache || null, script: command })],
kill: () => podmanCleanup(name, rootArgs),
};
}
-- const wrapped = bwrapScope({ name, limits, args: bwrapArgs({ workspace: runDir, limits, proxySock, script: command }).args });
++ const wrapped = bwrapScope({ name, limits, args: bwrapArgs({ workspace: runDir, limits, proxySock, sharedCache: cfg.sharedCache || null, script: command }).args });
return { command: wrapped.command, args: wrapped.args, kill: () => scopeCleanup(wrapped.killUnit) };
};
@@@ -149,13 +154,16 @@ function createRunner({ cfg, api, log = console, clock = Date.now }) {
if (left < 5000) return { timedOut: true, code: null, skipped: true };
const box = sandbox(label, script, proxySock);
say(`[git-ci-runner] ${run.id} ${label}`);
-- activeKill = () => box.kill();
++ const kill = () => box.kill();
++ activeKills.add(kill);
++ currentKill = kill;
const res = await runProcess({
command: box.command, args: box.args, env: sandboxEnv, timeoutMs: left,
onData,
onKill: () => { box.kill(); },
});
-- activeKill = null;
++ activeKills.delete(kill);
++ currentKill = null;
await flush(true);
return res;
};
@@@ -167,20 +175,63 @@ function createRunner({ cfg, api, log = console, clock = Date.now }) {
say(`[git-ci-runner] ${run.id} ${job.repo.full_name} ${run.branch} ${run.sha.slice(0, 12)}`);
await cloneAt({ dir: runDir, cloneUrl: job.repo.clone_url, sha: run.sha, branch: run.branch, log: (line) => onData(`${line}\n`) });
-- proxy = createProxy({ allow: cfg.proxyAllow, log: { warn: (line) => onData(`${line}\n`) } });
-- const socket = path.join(runDir, '.ci', 'proxy.sock');
-- await proxy.listen(socket);
-- const install = await phase('install', installScript(job.command.install), socket);
-- if (superseded) { state = 'superseded'; } else if (install.timedOut) {
-- state = 'timed_out'; description = `Timed out installing dependencies after ${words(totalMs)}`;
-- } else if (install.code !== 0) {
-- state = 'failure'; exitCode = install.code; description = `Dependency install failed (exit ${install.code})`;
-- } else {
-- const test = await phase('test', installScript(job.command.test, { proxy: false }), null);
++ // `auto` (a repository registered without commands): the checkout says how it installs and tests.
++ const commands = { install: job.command.install, test: job.command.test };
++ if (commands.install === 'auto' || commands.test === 'auto') {
++ const auto = autoCommands(runDir);
++ if (auto.none) {
++ state = 'success';
++ description = `Nothing to test here (${auto.none})`;
++ onData(`${description}\n`);
++ } else {
++ if (commands.install === 'auto') commands.install = auto.install;
++ if (commands.test === 'auto') commands.test = auto.test;
++ onData(`install: ${commands.install}\ntest: ${commands.test}\n`);
++ }
++ }
++
++ let installMs = 0;
++ let fromCache = false;
++ if (!state) {
++ // The same lockfile as an earlier run: its install comes back from the runner's cache, no install phase.
++ const key = deps ? cacheKey({ dir: runDir, repo: job.repo.full_name, install: commands.install, image: job.image, engine: engine.kind }) : null;
++ let restored = null;
++ if (key) {
++ try { restored = await deps.restore(key, runDir); } catch (err) { onData(`the kept install could not be restored (${err.message}); installing\n`); }
++ }
++ if (restored) {
++ fromCache = true;
++ installMs = restored.ms;
++ onData(`dependencies: from the runner's cache (${size(restored.bytes)}, saved ${restored.saved_at}) in ${words(restored.ms) === '0s' ? `${restored.ms} ms` : words(restored.ms)}; no install phase\n`);
++ } else {
++ const before = key ? survey(runDir) : null;
++ proxy = createProxy({ allow: cfg.proxyAllow, log: { warn: (line) => onData(`${line}\n`) } });
++ const socket = path.join(runDir, '.ci', 'proxy.sock');
++ await proxy.listen(socket);
++ const t0 = clock();
++ const install = await phase('install', installScript(commands.install), socket);
++ installMs = clock() - t0;
++ await proxy.close().catch(() => {});
++ proxy = null;
++ if (superseded) { state = 'superseded'; } else if (install.timedOut) {
++ state = 'timed_out'; description = `Timed out installing dependencies after ${words(totalMs)}`;
++ } else if (install.code !== 0) {
++ state = 'failure'; exitCode = install.code; description = `Dependency install failed (exit ${install.code})`;
++ } else if (key) {
++ // Kept before any test runs, so no test can change what a later run gets.
++ const kept = await deps.save(key, runDir, installed(before, survey(runDir)));
++ if (kept) onData(`dependencies: kept for later runs with this lockfile (${size(kept.bytes)}, ${words(kept.ms)})\n`);
++ }
++ }
++ }
++ if (!state) {
++ const t1 = clock();
++ const test = await phase('test', installScript(commands.test, { proxy: false }), null);
++ const timing = `install ${words(installMs)}${fromCache ? ' from the cache' : ''}, tests ${words(clock() - t1)}`;
if (superseded) state = 'superseded';
else if (test.timedOut) { state = 'timed_out'; description = `Timed out after ${words(totalMs)}`; }
-- else if (test.code === 0) { state = 'success'; description = `Forge runner passed in ${words(clock() - started)}`; }
-- else { state = 'failure'; exitCode = test.code; description = `Forge runner failed (exit ${test.code}) in ${words(clock() - started)}`; }
++ else if (test.code === 0) { state = 'success'; description = `Forge runner passed in ${words(clock() - started)} (${timing})`; }
++ else { state = 'failure'; exitCode = test.code; description = `Forge runner failed (exit ${test.code}) in ${words(clock() - started)} (${timing})`; }
}
} catch (err) {
if (superseded) state = 'superseded';
@@@ -213,7 +264,7 @@ function createRunner({ cfg, api, log = console, clock = Date.now }) {
function stop() {
stopping = true;
-- if (activeKill) { try { activeKill(); } catch { /* gone */ } }
++ for (const kill of activeKills) { try { kill(); } catch { /* gone */ } }
}
return { engine, runJob, stop };
ddiff --git a/runner/sandbox.js b/runner/sandbox.js
iindex dbbf170..709e355 100644
---- a/runner/sandbox.js
++++ b/runner/sandbox.js
@@@ -57,6 +57,15 @@ function detectEngine(preferred = 'auto') {
// pin-drift reads GitHub's tags) can check what it still can offline instead of failing the run. GitHub Actions has the
// network and runs the whole check.
const phaseEnv = (proxySock) => (proxySock ? {} : { OV_SANDBOX_OFFLINE: '1' });
++// The install phase's package-manager caches, shared between runs (mounted at /cache, install phase only): a pin bump
++// changes every lockfile, and the tarballs it did not change come from here. npm and pnpm check every tarball against
++// the lockfile's integrity, so a run cannot hand another a different package.
++const SHARED_CACHE = '/cache';
++const cacheEnv = (sharedCache) => (sharedCache ? {
++ npm_config_cache: `${SHARED_CACHE}/npm`,
++ npm_config_store_dir: `${SHARED_CACHE}/pnpm-store`,
++ npm_config_prefer_offline: 'true',
++} : {});
const envList = (extra = {}) => ({
HOME: '/workspace/.home',
TMPDIR: '/tmp',
@@@ -87,6 +96,8 @@ trap 'kill "$relay" 2>/dev/null || true' EXIT
export http_proxy=http://127.0.0.1:3128 https_proxy=http://127.0.0.1:3128
export HTTP_PROXY="$http_proxy" HTTPS_PROXY="$https_proxy"
export npm_config_proxy="$http_proxy" npm_config_https_proxy="$https_proxy"
++# Node's own fetch (a postinstall that downloads a prebuilt binary) uses the proxy too (Node 22.21 and later).
++export NODE_USE_ENV_PROXY=1
` : ''}mkdir -p /workspace/.pnpm/bin
export PATH=/workspace/.pnpm/bin:$PATH
cd /workspace
@@@ -97,7 +108,7 @@ ${command}
/**
* The podman command line for one phase. proxySock is null for the test phase (no network at all).
*/
--function podmanArgs({ name, workspace, image, limits, proxySock = null, script }) {
++function podmanArgs({ name, workspace, image, limits, proxySock = null, sharedCache = null, script }) {
const args = [
'run', '--rm', '--name', name, '--pull=never', '--network=none',
'--cpus', String(limits.cpus), '--memory', `${limits.memory_mb}m`, '--memory-swap', `${limits.memory_mb}m`,
@@@ -107,8 +118,10 @@ function podmanArgs({ name, workspace, image, limits, proxySock = null, script }
'-v', `${workspace}:/workspace:rw`,
'--stop-timeout', '5',
];
-- for (const [key, value] of Object.entries(envList(phaseEnv(proxySock)))) args.push('-e', `${key}=${value}`);
++ const shared = proxySock ? sharedCache : null;
++ for (const [key, value] of Object.entries(envList({ ...phaseEnv(proxySock), ...cacheEnv(shared) }))) args.push('-e', `${key}=${value}`);
if (proxySock) args.push('-v', `${proxySock}:/run/ci-proxy.sock:rw`);
++ if (shared) args.push('-v', `${shared}:${SHARED_CACHE}:rw`);
args.push(image, '/bin/sh', '-c', script);
return args;
}
@@@ -137,7 +150,7 @@ function bwrapEtc(workspace) {
* The bubblewrap command line for one phase (no systemd scope here; the caller wraps it). Node is bound from
* the running runner's own installation, because a workstation's Node is rarely in /usr.
*/
--function bwrapArgs({ workspace, limits, proxySock = null, script }) {
++function bwrapArgs({ workspace, limits, proxySock = null, sharedCache = null, script }) {
const node = fs.realpathSync(process.execPath);
const prefix = path.dirname(path.dirname(node));
const nodeInside = path.join('/opt/node', path.relative(prefix, node));
@@@ -148,7 +161,8 @@ function bwrapArgs({ workspace, limits, proxySock = null, script }) {
'--disable-userns', '--die-with-parent', '--new-session', '--cap-drop', 'ALL', '--clearenv',
'--uid', String(UID), '--gid', String(GID), '--hostname', 'ci',
];
-- for (const [key, value] of Object.entries({ ...envList(phaseEnv(proxySock)), PATH: `${nodeBin}:/usr/local/bin:/usr/bin:/bin` })) {
++ const shared = proxySock ? sharedCache : null;
++ for (const [key, value] of Object.entries({ ...envList({ ...phaseEnv(proxySock), ...cacheEnv(shared) }), PATH: `${nodeBin}:/usr/local/bin:/usr/bin:/bin` })) {
args.push('--setenv', key, value);
}
args.push('--ro-bind', '/usr', '/usr');
@@@ -173,6 +187,7 @@ function bwrapArgs({ workspace, limits, proxySock = null, script }) {
args.push('--proc', '/proc', '--dev', '/dev', '--tmpfs', '/tmp', '--perms', '1777', '--tmpfs', '/run');
args.push('--bind', workspace, '/workspace');
if (proxySock) args.push('--bind', proxySock, '/run/ci-proxy.sock');
++ if (shared) args.push('--bind', shared, SHARED_CACHE);
args.push('--remount-ro', '/', '--chdir', '/workspace', '--', '/bin/sh', '-c', script);
return { args, nodeInside };
}
@@@ -202,5 +217,5 @@ function scopeCleanup(unit) {
}
module.exports = {
-- detectEngine, podmanArgs, bwrapArgs, bwrapScope, installScript, podmanCleanup, scopeCleanup, envList, UID, GID, RELAY,
++ detectEngine, podmanArgs, bwrapArgs, bwrapScope, installScript, podmanCleanup, scopeCleanup, envList, cacheEnv, UID, GID, RELAY, SHARED_CACHE,
};
ddiff --git a/server/app.js b/server/app.js
iindex bc5263c..e98e3fd 100644
---- a/server/app.js
++++ b/server/app.js
@@@ -61,7 +61,7 @@ function createApp(opts = {}) {
const repos = opts.repos || createRepos({ store: s, config, git, github, insights, log });
// GitHub, linked once (plan §AD.10 step 3): a person's token for push mirrors that have none of their own.
const githubLinks = opts.githubLinks || require('./github-links').createGithubLinks({ store: s, config, fetchImpl });
-- const mirrors = opts.mirrors || createMirrors({ store: s, repos, config, git, github, githubLinks, log });
++ const mirrors = opts.mirrors || createMirrors({ store: s, repos, config, git, github, githubLinks, log, lookup: opts.lookup });
const official = opts.official || createOfficialMirrors({ store: s, repos, config, github, log });
const sso = opts.sso || createSsoClient({
site: 'git', baseUrl: config.baseUrl, clientId: config.oauth.clientId, clientSecret: config.oauth.clientSecret,
ddiff --git a/server/ci.js b/server/ci.js
iindex 0957d3b..2600039 100644
---- a/server/ci.js
++++ b/server/ci.js
@@@ -132,15 +132,35 @@ function createCi({ config, store, checks, git, github, repos, log = console, cl
return { skipped: 'duplicate', run: rowToRun(live, { baseUrl: base(), owner: row.owner_username, name: row.name }) };
}
const id = store.newId('cir');
++ // The same files as a run that already passed (a pull request merged onto an unmoved main, a branch made from a
++ // tested commit): that verdict answers this push, and the runner tests something new instead. A manual run
++ // (force) always runs.
++ const tree = git && git.resolveTree ? await git.resolveTree(row.owner_username, row.name, clean).catch(() => null) : null;
++ const same = tree && !force
++ ? await store.maybe("SELECT * FROM git_ci_runs WHERE repo_id = ? AND tree = ? AND state = 'success' ORDER BY finished_at DESC LIMIT 1", [row.id, tree])
++ : null;
await store.execute(
"UPDATE git_ci_runs SET state = 'superseded', description = ?, finished_at = now(), updated_at = now() WHERE repo_id = ? AND state IN ('queued', 'running')",
[`Superseded by ${clean.slice(0, 12)}`, row.id],
);
++ if (same) {
++ const description = text(`Same files as ${same.sha.slice(0, 12)} (${same.branch}), which passed: ${same.description || 'passed'}`, 1000);
++ await store.execute(
++ `INSERT INTO git_ci_runs (id, repo_id, sha, branch, pusher, source, state, description, runner, started_at, finished_at, duration_ms, tree, exit_code)
++ VALUES (?, ?, ?, ?, ?, ?, 'success', ?, 'forge (same files)', now(), now(), 0, ?, 0)`,
++ [id, row.id, clean, ref, pusher ? text(pusher, 200) : null, text(source, 20), description, tree],
++ );
++ await checks.recordIfChanged(row.id, clean, {
++ context: settings.context || CONTEXT, state: 'success', description: text(`Same files as ${same.sha.slice(0, 12)}, which passed`, 140), target_url: runUrl(row, id),
++ }, 'svc:forge-runner').catch((err) => log.warn('[OpenVibe.Git] CI same-tree status:', err.message));
++ const done = await store.maybe('SELECT * FROM git_ci_runs WHERE id = ?', [id]);
++ return { run: rowToRun(done, { baseUrl: base(), owner: row.owner_username, name: row.name }), same_as: same.id };
++ }
try {
await store.execute(
-- `INSERT INTO git_ci_runs (id, repo_id, sha, branch, pusher, source, state, description)
-- VALUES (?, ?, ?, ?, ?, ?, 'queued', ?)`,
-- [id, row.id, clean, ref, pusher ? text(pusher, 200) : null, text(source, 20), 'Queued on the forge runner'],
++ `INSERT INTO git_ci_runs (id, repo_id, sha, branch, pusher, source, state, description, tree)
++ VALUES (?, ?, ?, ?, ?, ?, 'queued', ?, ?)`,
++ [id, row.id, clean, ref, pusher ? text(pusher, 200) : null, text(source, 20), 'Queued on the forge runner', tree],
);
} catch (err) {
if (/duplicate key|unique/i.test(String(err.message))) {
@@@ -342,6 +362,45 @@ function createCi({ config, store, checks, git, github, repos, log = console, cl
return rows.map((r) => rowToRun(r, { baseUrl: base(), owner: row.owner_username, name: row.name }));
}
++ /**
++ * Every public repository's runs in one place (/ci, 2026-11-19): what runs now and on which runner, the queue, the
++ * latest verdicts and the last day's numbers (runs, passed, median time, installs that came from the cache).
++ */
++ async function board({ limit = 60 } = {}) {
++ const n = Math.max(1, Math.min(200, Number(limit) || 60));
++ const cols = 'r.id, r.repo_id, r.sha, r.branch, r.pusher, r.source, r.state, r.description, r.exit_code, r.log_bytes, r.runner, r.started_at, r.finished_at, r.duration_ms, r.created_at, g.owner_username, g.name';
++ const live = await store.many(
++ `SELECT ${cols} FROM git_ci_runs r JOIN git_repos g ON g.id = r.repo_id
++ WHERE r.state IN ('queued', 'running') AND g.visibility = 'public' ORDER BY r.created_at ASC LIMIT 200`, [],
++ );
++ const recent = await store.many(
++ `SELECT ${cols} FROM git_ci_runs r JOIN git_repos g ON g.id = r.repo_id
++ WHERE r.state NOT IN ('queued', 'running') AND g.visibility = 'public' ORDER BY COALESCE(r.finished_at, r.created_at) DESC LIMIT ?`, [n],
++ );
++ const day = await store.many(
++ `SELECT r.state, r.duration_ms, r.description FROM git_ci_runs r JOIN git_repos g ON g.id = r.repo_id
++ WHERE r.created_at > now() - interval '1 day' AND g.visibility = 'public' AND r.state NOT IN ('queued', 'running', 'superseded')`, [],
++ );
++ const map = (row) => rowToRun(row, { baseUrl: base(), owner: row.owner_username, name: row.name });
++ const verdicts = day.filter((r) => ['success', 'failure', 'timed_out'].includes(r.state));
++ const passed = verdicts.filter((r) => r.state === 'success');
++ const times = passed.map((r) => Number(r.duration_ms)).filter((x) => Number.isFinite(x)).sort((a, b) => a - b);
++ const installed = day.filter((r) => /\(install /.test(r.description || ''));
++ return {
++ running: live.filter((r) => r.state === 'running').map(map),
++ queued: live.filter((r) => r.state === 'queued').map(map),
++ recent: recent.map(map),
++ day: {
++ runs: day.length,
++ verdicts: verdicts.length,
++ passed: passed.length,
++ median_ms: times.length ? times[Math.floor(times.length / 2)] : null,
++ from_cache: installed.filter((r) => /from the cache/.test(r.description || '')).length,
++ installs: installed.length,
++ },
++ };
++ }
++
async function runFor(row, id) {
const run = await store.maybe('SELECT * FROM git_ci_runs WHERE id = ? AND repo_id = ?', [text(id, 100), row.id]);
return rowToRun(run, { baseUrl: base(), owner: row.owner_username, name: row.name, log: true });
@@@ -361,7 +420,7 @@ function createCi({ config, store, checks, git, github, repos, log = console, cl
function stop() { if (timer) clearInterval(timer); timer = null; }
return {
-- onGithubPush, onForgePush, registerRepos, manual, enqueue, claim, heartbeat, appendLog, finish, reap,
++ onGithubPush, onForgePush, registerRepos, manual, enqueue, claim, heartbeat, appendLog, finish, reap, board,
runsFor, runFor, configFor, settingsFor, enabledFor, member, rowToRun, start, stop,
STATES, CONTEXT, SHA_RE, BRANCH_RE,
};
ddiff --git a/server/git/store.js b/server/git/store.js
iindex 13bf90b..7e897f4 100644
---- a/server/git/store.js
++++ b/server/git/store.js
@@@ -94,6 +94,16 @@ async function resolveCommit(owner, name, ref) {
} catch { return null; }
}
++/** The tree a commit points at, or null (the commit is not here yet, or the name is not a commit). */
++async function resolveTree(owner, name, sha) {
++ if (!/^[0-9a-f]{40}([0-9a-f]{24})?$/.test(String(sha || ''))) return null;
++ if (!(await repoExists(owner, name))) return null;
++ try {
++ const out = await runText(['rev-parse', '--verify', '--quiet', '--end-of-options', `${sha}^{tree}`], { cwd: repoDir(owner, name) });
++ return out.trim() || null;
++ } catch { return null; }
++}
++
async function defaultRef(owner, name, branch = 'main') {
return resolveCommit(owner, name, branch) ? branch : null;
}
@@@ -545,7 +555,7 @@ async function removeRepo(owner, name) {
}
module.exports = {
-- repoDir, ensureDataDirs, repoExists, repoBytes, initRepo, setRepoConfig, setRemote, resolveCommit, defaultRef,
++ repoDir, ensureDataDirs, repoExists, repoBytes, initRepo, setRepoConfig, setRemote, resolveCommit, resolveTree, defaultRef,
readTree, readBlob, rawBlob, blobBytes, history, commitDetail, branches, tags, contributors, commitsPerWeek, languages, commitFiles,
writeInitialCommit, cloneMirror, cloneLocal, fetchMirror, pushMirror, removeRepo, parseLsTree, catFiles,
remoteRefs, localRefs, mirrorChanged,
ddiff --git a/server/http/api.js b/server/http/api.js
iindex a72fe88..921f463 100644
---- a/server/http/api.js
++++ b/server/http/api.js
@@@ -282,6 +282,12 @@ function createApi(ctx) {
} catch (err) { return fail(req, res, err); }
}));
++ // Every public repository's runs: now, queued, latest, and the last day's numbers (the /ci page's data).
++ r.get('/ci/board', h(async (req, res) => {
++ res.set('Cache-Control', 'no-store');
++ return res.json(await ci.board({ limit: req.query.limit }));
++ }));
++
r.post('/ci/runs/claim', h(async (req, res) => {
if (!runnerOnly(req, res)) return undefined;
const job = await ci.claim((req.body && req.body.runner) || 'forge-runner');
ddiff --git a/server/http/pages.js b/server/http/pages.js
iindex 51d0cd0..cd27898 100644
---- a/server/http/pages.js
++++ b/server/http/pages.js
@@@ -174,6 +174,12 @@ function createPageRoutes(ctx) {
return page(req, res, render(out.result), { title: `${repo.name} · ${machine.name}`, index: false });
};
++ r.get('/ci', h(async (req, res) => {
++ const data = await ci.board({ limit: req.query.limit });
++ res.set('Cache-Control', 'no-store');
++ return page(req, res, ciViews.board({ ...data, runners: config.ci.boardRunners || 3 }), { title: 'CI', description: 'Every OpenVibers repository, tested on our own runner.', index: false });
++ }));
++
r.get('/machines', h(async (req, res) => {
const me = viewer(req);
if (!me) return res.redirect(303, loginTo('/machines'));
ddiff --git a/server/mirror.js b/server/mirror.js
iindex b2e5056..65d42d8 100644
---- a/server/mirror.js
++++ b/server/mirror.js
@@@ -13,7 +13,8 @@
*/
const { assertPublicUrl } = require('openvibe-shared/egress');
--function createMirrors({ store, repos, config, git, github, githubLinks = null, log = console }) {
++// lookup: a DNS lookup for the URL check (tests pass a stub, so they run with no network, as in the forge's sandbox).
++function createMirrors({ store, repos, config, git, github, githubLinks = null, log = console, lookup = null }) {
const running = new Map(); // repo id → promise
async function guardUrl(url) {
@@@ -21,7 +22,7 @@ function createMirrors({ store, repos, config, git, github, githubLinks = null,
try { u = new URL(url); } catch { throw new Error('not a URL'); }
if (u.protocol !== 'https:') throw new Error('a mirror URL is https');
if (!['github.com', 'www.github.com'].includes(u.hostname)) throw new Error('a mirror is on github.com');
-- await assertPublicUrl(u);
++ await assertPublicUrl(u, lookup ? { lookup } : {});
return u;
}
ddiff --git a/server/views/ci.js b/server/views/ci.js
iindex da7f938..9c021fc 100644
---- a/server/views/ci.js
++++ b/server/views/ci.js
@@@ -38,12 +38,48 @@ function list({ row, enabled, runs, context }) {
<span class="git-muted">${esc(run.pusher || '—')} · ${esc(duration(run.duration_ms))} · ${esc(when(run.created_at))}</span>
</li>`).join('');
return `<div class="git-list-page"><header class="git-page-head"><p class="git-crumb"><a href="${b}">${esc(row.owner_username)}/${esc(row.name)}</a></p><h1>CI</h1>
--<p>${enabled ? `The forge runner tests branch pushes by OpenVibers members and reports <code>${esc(context)}</code>.` : 'Forge CI is not enabled for this repository; GitHub Actions still runs.'}</p></header>
++<p>${enabled ? `The forge runner tests branch pushes by OpenVibers members and reports <code>${esc(context)}</code>. <a href="/ci">Every repository's runs</a>.` : 'Forge CI is not enabled for this repository; GitHub Actions still runs.'}</p></header>
${repoTabs(row, 'ci')}
${runs.length ? `<ul class="git-ci-list">${rows}</ul>` : kit.empty({ icon: 'gear', title: 'No forge runs yet', text: 'A run appears here when someone pushes a branch.' })}
<p class="git-muted git-small">The runner clones the branch, installs dependencies through an allowlisted proxy, then runs the tests with no network at all. Logs stay on the run they belong to.</p></div>`;
}
++const pct = (a, b) => (b ? `${Math.round((a / b) * 100)}%` : '—');
++const since = (value, now = Date.now()) => {
++ const t = new Date(value).getTime();
++ return Number.isFinite(t) ? duration(now - t) : '—';
++};
++
++function boardRow(r, extra = '') {
++ return `<li class="git-ci-row">
++ ${state(r.state)}
++ <a class="git-ci-main" href="/${esc(r.repo)}/ci/${esc(r.id)}"><b>${esc(String(r.repo).replace(/^openvibers\//, ''))}</b> ${esc(r.branch)}<code>${esc(String(r.sha).slice(0, 12))}</code></a>
++ <span class="git-muted">${extra}</span>
++</li>`;
++}
++
++/** /ci: every public repository's runs, on our own runners. */
++function board({ running, queued, recent, day, runners = 3 }) {
++ const now = Date.now();
++ const runningRows = running.map((r) => boardRow(r, `${esc(r.runner || '—')} · ${esc(since(r.started_at || r.created_at, now))} so far`)).join('');
++ const queuedRows = queued.map((r, i) => boardRow(r, `next ${i + 1} · waiting ${esc(since(r.created_at, now))}`)).join('');
++ const recentRows = recent.map((r) => boardRow(r, `${esc(r.description || '')} · ${esc(when(r.finished_at || r.created_at))}`)).join('');
++ return `<div class="git-list-page"><header class="git-page-head"><h1>CI</h1>
++<p>Every push to an OpenVibers repository is tested here, on our own runner: the shared node runs ${esc(runners)} at once, with
++the work in memory and installs kept per lockfile. The verdict is the commit's <code>forge/test</code> status.</p></header>
++<ul class="git-ci-facts">
++ <li><span>Runs, last day</span>${esc(day.runs)}</li>
++ <li><span>Passed</span>${esc(pct(day.passed, day.verdicts))}</li>
++ <li><span>Median time (passed)</span>${esc(duration(day.median_ms))}</li>
++ <li><span>Installs from the cache</span>${esc(pct(day.from_cache, day.installs))}</li>
++</ul>
++<h2>Now</h2>
++${running.length || queued.length ? `<ul class="git-ci-list">${runningRows}${queuedRows}</ul>` : '<p class="git-muted">Nothing running or waiting.</p>'}
++<h2>Latest</h2>
++${recent.length ? `<ul class="git-ci-list">${recentRows}</ul>` : kit.empty({ icon: 'gear', title: 'No runs yet', text: 'A run appears here when someone pushes a branch.' })}
++<p class="git-muted git-small">How it works: <a href="/openvibers/openvibe-git/src/branch/main/docs/ci.md">docs/ci.md</a>. The JSON is <code>/api/v1/ci/board</code>.</p></div>`;
++}
++
function run({ row, run: r }) {
const b = base(row);
const log = String(r.log || '');
@@@ -64,4 +100,4 @@ ${log ? `<pre class="git-cmd git-ci-log" aria-live="polite">${esc(log)}</pre>` :
${r.state === 'running' ? '<p class="git-muted git-small">This run is still writing its log; reload to see more.</p>' : ''}</section></div>`;
}
--module.exports = { list, run, when, duration, STATE };
++module.exports = { list, run, when, duration, STATE, board };
ddiff --git a/test/ci-deps-cache.test.js b/test/ci-deps-cache.test.js
nnew file mode 100644
iindex 0000000..3fcee36
---- /dev/null
++++ b/test/ci-deps-cache.test.js
@@@ -0,0 +1,150 @@
++'use strict';
++// The forge runner keeps installs between runs and runs several at once (2026-11-19: the owner asked for our own CI on
++// the shared node, "optimized, efficient … making use of the RAM").
++// - The cache key changes with anything that decides an install, and there is no key without a lockfile.
++// - What an install made (node_modules folders and the files it changed outside them) is kept and comes back whole.
++// - The store keeps to its size, least recently used first.
++// - `auto` picks the install command from the lockfile, and a repository with no test script has nothing to run.
++// - The download caches are mounted in the install phase only; Node's own fetch goes through the proxy.
++// - The configuration allows up to 8 workers, and repositories default to `auto`.
++const assert = require('assert');
++const fs = require('fs');
++const os = require('os');
++const path = require('path');
++const { createDepsCache, cacheKey, survey, installed, autoCommands } = require('../runner/deps-cache');
++const { bwrapArgs, podmanArgs, installScript } = require('../runner/sandbox');
++const { loadConfig, registrations } = require('../runner/config');
++
++const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ov-ci-deps-'));
++const write = (file, text) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, text); };
++
++(async () => {
++ try {
++ // ── The key ──
++ const a = path.join(tmp, 'a');
++ write(path.join(a, 'package.json'), JSON.stringify({ name: 'a', scripts: { test: 'node t.js' } }));
++ const base = { dir: a, repo: 'OpenVibers/A', install: 'npm ci', image: 'img', engine: 'bwrap' };
++ assert.strictEqual(cacheKey(base), null, 'no lockfile, no key');
++ write(path.join(a, 'package-lock.json'), '{"lockfileVersion":3,"packages":{}}');
++ const k1 = cacheKey(base);
++ assert.match(k1, /^[0-9a-f]{40}$/);
++ assert.strictEqual(cacheKey(base), k1, 'the same inputs give the same key');
++ assert.strictEqual(cacheKey({ ...base, repo: 'openvibers/a' }), k1, 'the repository name is case-insensitive');
++ assert.notStrictEqual(cacheKey({ ...base, install: 'npm ci --omit=dev' }), k1, 'the install command is in the key');
++ assert.notStrictEqual(cacheKey({ ...base, repo: 'openvibers/b' }), k1, 'each repository keeps its own');
++ assert.notStrictEqual(cacheKey({ ...base, node: 'v99.0.0' }), k1, 'Node is in the key');
++ write(path.join(a, 'package.json'), JSON.stringify({ name: 'a', scripts: { test: 'node other.js' } }));
++ assert.strictEqual(cacheKey(base), k1, 'a changed test script does not change the install');
++ write(path.join(a, 'package.json'), JSON.stringify({ name: 'a', scripts: { test: 'node t.js', postinstall: 'node build.js' } }));
++ const k2 = cacheKey(base);
++ assert.notStrictEqual(k2, k1, 'an install script is in the key');
++ write(path.join(a, 'package-lock.json'), '{"lockfileVersion":3,"packages":{"x":{}}}');
++ assert.notStrictEqual(cacheKey(base), k2, 'the lockfile is in the key');
++
++ // ── What an install made ──
++ write(path.join(a, 'src', 'index.js'), 'module.exports = 1;\n');
++ write(path.join(a, '.ci', 'etc', 'passwd'), 'runner file\n');
++ const before = survey(a);
++ write(path.join(a, 'node_modules', 'dep', 'index.js'), 'module.exports = "dep";\n');
++ write(path.join(a, 'node_modules', 'dep', 'node_modules', 'inner', 'x.js'), '1\n');
++ write(path.join(a, 'packages', 'p', 'node_modules', 'q', 'q.js'), 'q\n');
++ write(path.join(a, 'dist', 'built.js'), 'built by prepare\n');
++ write(path.join(a, '.home', '.npmrc'), 'runner home\n');
++ const made = installed(before, survey(a));
++ assert.deepStrictEqual(made.modules, ['node_modules', 'packages/p/node_modules'], 'top-level node_modules folders only');
++ assert.deepStrictEqual(made.changed, ['dist/built.js'], 'the files the install wrote, never the runner\'s own');
++
++ // ── Kept, and back in a fresh checkout ──
++ const store = path.join(tmp, 'store');
++ const cache = createDepsCache({ root: store, maxMb: 256 });
++ const key = cacheKey(base);
++ assert.strictEqual(await cache.restore(key, a), null, 'a miss before anything is kept');
++ const kept = await cache.save(key, a, made);
++ assert.ok(kept && kept.bytes > 0, 'kept with its size');
++ assert.strictEqual(await cache.save(key, a, made), null, 'kept once');
++ const b = path.join(tmp, 'b');
++ write(path.join(b, 'src', 'index.js'), 'module.exports = 1;\n');
++ const back = await cache.restore(key, b);
++ assert.ok(back, 'a hit');
++ assert.deepStrictEqual(back.modules, made.modules);
++ assert.strictEqual(fs.readFileSync(path.join(b, 'node_modules', 'dep', 'index.js'), 'utf8'), 'module.exports = "dep";\n');
++ assert.ok(fs.existsSync(path.join(b, 'node_modules', 'dep', 'node_modules', 'inner', 'x.js')), 'nested dependencies come back');
++ assert.ok(fs.existsSync(path.join(b, 'packages', 'p', 'node_modules', 'q', 'q.js')), 'a workspace\'s node_modules comes back');
++ assert.strictEqual(fs.readFileSync(path.join(b, 'dist', 'built.js'), 'utf8'), 'built by prepare\n', 'what prepare built comes back');
++ assert.ok(!fs.existsSync(path.join(b, '.home', '.npmrc')), 'the runner\'s own folders are not kept');
++ // A run that changes its copy does not change what is kept.
++ fs.writeFileSync(path.join(b, 'node_modules', 'dep', 'index.js'), 'tampered\n');
++ const c = path.join(tmp, 'c');
++ fs.mkdirSync(c);
++ await cache.restore(key, c);
++ assert.strictEqual(fs.readFileSync(path.join(c, 'node_modules', 'dep', 'index.js'), 'utf8'), 'module.exports = "dep";\n', 'a copy, not the kept files');
++
++ // ── The store keeps to its size, least recently used first ──
++ const small = createDepsCache({ root: path.join(tmp, 'small'), maxMb: 256 });
++ const big = path.join(tmp, 'big');
++ const blob = Buffer.alloc(100 * 1024 * 1024, 1);
++ write(path.join(big, 'package-lock.json'), '{}');
++ write(path.join(big, 'node_modules', 'blob', 'data.bin'), blob);
++ const bigMade = { modules: ['node_modules'], changed: [] };
++ const keys = ['1', '2', '3'].map((n) => cacheKey({ dir: big, repo: `r${n}`, install: 'npm ci' }));
++ await small.save(keys[0], big, bigMade);
++ await small.save(keys[1], big, bigMade);
++ // The first one was used since: the second is now the least recently used.
++ const later = new Date(Date.now() + 60_000);
++ fs.utimesSync(path.join(small.root, keys[0], 'manifest.json'), later, later);
++ await small.save(keys[2], big, bigMade);
++ const left = fs.readdirSync(small.root).filter((n) => !n.startsWith('.')).sort();
++ assert.deepStrictEqual(left, [keys[0], keys[2]].sort(), `256 MB holds two of three 100 MB entries, the least recently used went (${left})`);
++
++ // ── auto ──
++ const auto = (files) => {
++ const d = fs.mkdtempSync(path.join(tmp, 'auto-'));
++ for (const [name, text] of Object.entries(files)) write(path.join(d, name), text);
++ return autoCommands(d);
++ };
++ const pkg = JSON.stringify({ scripts: { test: 'node test/run.js' } });
++ assert.deepStrictEqual(auto({ 'package.json': pkg, 'package-lock.json': '{}' }), { install: 'npm ci --no-audit --no-fund', test: 'npm test' });
++ assert.deepStrictEqual(auto({ 'package.json': pkg, 'pnpm-lock.yaml': '' }), { install: 'pnpm install --frozen-lockfile', test: 'npm test' });
++ assert.deepStrictEqual(auto({ 'package.json': pkg }), { install: 'npm install --no-audit --no-fund', test: 'npm test' });
++ assert.match(auto({ 'package.json': '{}' }).none, /no test script/);
++ assert.match(auto({ 'go.mod': 'module x' }).none, /no package\.json/);
++
++ // ── The sandbox: download caches in the install phase only ──
++ const ws = path.join(tmp, 'ws');
++ fs.mkdirSync(ws);
++ const limits = { cpus: 2, memory_mb: 2048 };
++ const shared = path.join(tmp, 'shared');
++ const inst = bwrapArgs({ workspace: ws, limits, proxySock: path.join(ws, 'p.sock'), sharedCache: shared, script: 'true' }).args;
++ const at = inst.indexOf(shared);
++ assert.ok(at > 0 && inst[at - 1] === '--bind' && inst[at + 1] === '/cache', 'the install phase gets /cache');
++ assert.ok(inst.includes('npm_config_cache') && inst[inst.indexOf('npm_config_cache') + 1] === '/cache/npm');
++ const testArgs = bwrapArgs({ workspace: ws, limits, proxySock: null, sharedCache: shared, script: 'true' }).args;
++ assert.ok(!testArgs.includes(shared) && !testArgs.includes('/cache'), 'the test phase gets no shared cache');
++ assert.strictEqual(testArgs[testArgs.indexOf('npm_config_cache') + 1], '/workspace/.cache/npm');
++ const pod = podmanArgs({ name: 'n', workspace: ws, image: 'img', limits, proxySock: path.join(ws, 'p.sock'), sharedCache: shared, script: 'true' });
++ assert.ok(pod.includes(`${shared}:/cache:rw`) && pod.includes('npm_config_prefer_offline=true'));
++ const podTest = podmanArgs({ name: 'n', workspace: ws, image: 'img', limits, proxySock: null, sharedCache: shared, script: 'true' });
++ assert.ok(!podTest.some((x) => String(x).includes(':/cache')), 'podman\'s test phase gets no shared cache either');
++ assert.match(installScript('npm ci'), /NODE_USE_ENV_PROXY=1/, 'Node\'s own fetch uses the proxy');
++ assert.doesNotMatch(installScript('npm test', { proxy: false }), /NODE_USE_ENV_PROXY/);
++
++ // ── The configuration ──
++ const token = path.join(tmp, 'token');
++ fs.writeFileSync(token, 'x'.repeat(40), { mode: 0o600 });
++ const conf = path.join(tmp, 'ci.json');
++ fs.writeFileSync(conf, JSON.stringify({ tokenFile: token, concurrency: 8, repos: { 'OpenVibers/OpenVibe.Live': {} } }));
++ const cfg = loadConfig({ GIT_CI_CONFIG: conf });
++ assert.strictEqual(cfg.concurrency, 8);
++ assert.ok(cfg.depsCache && cfg.sharedCache, 'both caches are on by default');
++ assert.deepStrictEqual(registrations(cfg).map((r) => [r.full_name, r.install_command, r.test_command]), [['openvibers/openvibe.live', 'auto', 'auto']]);
++ fs.writeFileSync(conf, JSON.stringify({ tokenFile: token, concurrency: 50, depsCache: '', sharedCache: '' }));
++ const off = loadConfig({ GIT_CI_CONFIG: conf });
++ assert.strictEqual(off.concurrency, 8, 'at most 8 workers');
++ assert.strictEqual(off.depsCache, '');
++ assert.strictEqual(off.sharedCache, '');
++
++ console.log('ci-deps-cache: key, keep and restore, size limit, auto commands, install-only caches and workers passed');
++ } finally {
++ fs.rmSync(tmp, { recursive: true, force: true });
++ }
++})().catch((e) => { console.error(e); process.exit(1); });
ddiff --git a/test/ci-runner.test.js b/test/ci-runner.test.js
iindex 98e99fd..2ebb05c 100644
---- a/test/ci-runner.test.js
++++ b/test/ci-runner.test.js
@@@ -130,7 +130,10 @@ const { hashToken, parseHash, createCiAuth } = require('../server/ci-auth');
// GitHub's runners have neither, so the test says why it skipped instead of failing there.
let engine = null;
try { engine = detectEngine('auto'); } catch { engine = null; }
-- if (!engine) {
++ // Inside the forge's own sandbox (the test phase says OV_SANDBOX_OFFLINE=1) a sandbox cannot start another.
++ if (process.env.OV_SANDBOX_OFFLINE === '1') {
++ console.log('ci-runner: inside the forge sandbox; the nested end-to-end run is skipped');
++ } else if (!engine) {
console.log('ci-runner: no sandbox engine here; the end-to-end run is skipped');
} else {
const image = 'docker.io/library/node:22-bookworm';
ddiff --git a/test/ci.test.js b/test/ci.test.js
iindex d1aa926..d71d54c 100644
---- a/test/ci.test.js
++++ b/test/ci.test.js
@@@ -105,6 +105,25 @@ const ok = (body, status = 200) => ({ ok: status >= 200 && status < 300, status,
assert.equal(apiRun.json().log, 'installing…\n47 tests passed\n');
assert.equal((await t.get(`/api/v1/ci/runs/${job.run.id}/status`, { bearer: TOKEN, json: { state: 'failure' } })).status, 409, 'a finished run cannot be changed');
++ // The same files again (here: the same commit pushed as another branch, like a pull request merged onto an
++ // unmoved main): the passed run answers it, nothing is queued, the commit status is green at once.
++ const again = await t.ctx.ci.enqueue(await t.ctx.repos.getRow('openvibers', 'live'), { sha: live.head, branch: 'merged-main', pusher: 'openvibers' });
++ assert.equal(again.run.state, 'success', JSON.stringify(again));
++ assert.match(again.run.description, /^Same files as [0-9a-f]{12} \(/);
++ assert.equal(again.same_as, job.run.id);
++ assert.equal(again.run.runner, 'forge (same files)');
++
++ // The board: every public repository's runs in one place, the finished one among the latest.
++ const board = (await t.get('/api/v1/ci/board')).json();
++ assert.ok(board.recent.some((r) => r.id === job.run.id && r.state === 'success' && r.repo === 'openvibers/live'), 'the verdict is on the board');
++ assert.ok(Array.isArray(board.running) && Array.isArray(board.queued));
++ assert.ok(board.day.verdicts >= 1 && board.day.passed >= 1);
++ assert.ok(!('log' in board.recent[0]), 'no logs on the board');
++ const boardPage = await t.get('/ci');
++ assert.equal(boardPage.status, 200);
++ assert.match(boardPage.text, new RegExp(`/openvibers/live/ci/${job.run.id}`), 'the page links the run');
++ assert.match(boardPage.text, /Forge runner passed in 9s/);
++
// The collaborator's queued run is drained too, so the next queue is the supersede case alone.
const friendClaim = (await t.get('/api/v1/ci/runs/claim', { bearer: TOKEN, json: {} })).json();
assert.equal(friendClaim.run.id, friendRun.run.id);
@@@ -150,6 +169,7 @@ const ok = (body, status = 200) => ({ ok: status >= 200 && status < 300, status,
const manual = await t.get('/api/v1/repos/openvibers/live/ci/runs', { as: owner, json: {} });
assert.equal(manual.status, 201, manual.text);
assert.equal(manual.json().run.source, 'manual');
++ assert.equal(manual.json().run.state, 'queued', 'a run started by hand runs even when the same files passed');
assert.equal((await t.get('/api/v1/repos/openvibers/live/ci/runs', { as: t.asUser('mallory'), json: {} })).status, 403);
assert.ok(!t.logs().join('\n').includes(TOKEN), 'the runner token is never logged');
ddiff --git a/test/mirrors-quota.test.js b/test/mirrors-quota.test.js
iindex d688eeb..fd27e33 100644
---- a/test/mirrors-quota.test.js
++++ b/test/mirrors-quota.test.js
@@@ -164,7 +164,7 @@ const CONTRACTS = [
t.ctx.git.mirrorChanged = async () => { changed += 1; return false; };
t.ctx.git.fetchMirror = async () => { fetched += 1; return true; };
t.ctx.git.languages = async () => ({});
-- const mirrors = createMirrors({ store: t.store, repos: t.ctx.repos, config: t.config, git: t.ctx.git, github: t.ctx.github, log: { warn() {} } });
++ const mirrors = createMirrors({ store: t.store, repos: t.ctx.repos, config: t.config, git: t.ctx.git, github: t.ctx.github, log: { warn() {} }, lookup });
await mirrors.poll();
assert.equal(changed, 1);