Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.60.70.0 fix(ubicloud): owner-tagged VM names, opt-in own-only GC, teardown that waits for in-flight creates
garrytand83b4e5e75d6
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex b1ac806810..954b022210 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.60.69.0",+ "version": "0.60.70.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 5ba1079bcf..cdd97f999f 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.60.69.0",+ "version": "0.60.70.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/AGENTS.md b/AGENTS.mdindex bb079bfece..11411b7d7b 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -210,10 +210,12 @@ seconds (gitleaks plus the doc checks) and runs the full gate otherwise. Require(Docker Desktop / OrbStack / Colima) and `gitleaks` (`brew install gitleaks`).Fastest path, with a Ubicloud token (`UBICLOUD_API_KEY` or-`UBICLOUD_API_TOKEN`): `bun run ci:ubicloud` runs the same gate across ten+`UBICLOUD_API_TOKEN`): `bun run ci:ubicloud` runs the same gate across fourephemeral VMs in about five minutes, uncommitted edits included(`ci:ubicloud:diff` for the doc-only fast path). See "Ubicloud fan-out" in-[`docs/TESTING.md`](./docs/TESTING.md).+[`docs/TESTING.md`](./docs/TESTING.md). Set `UBI_OWNER` to your thread code. In a+multi-lane wave, lanes run `ci:ubicloud:diff` or targeted suites; only the+integrator runs the full gate.Manual path: `bun test` plus the E2E lifecycle described in `./CLAUDE.md` (spinup the test Postgres container, run `bun run test:e2e`, tear it down).diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex 816e31a7d5..40f779ecf7 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.60.69.0 -->+<!-- gbrain-runbook-stamp: 0.60.70.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ced2b20c69..804039bccf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,21 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.70.0] - 2026-10-05++**`ci:ubicloud` VMs carry their owner's name, an interrupted run destroys every VM it asked for, and no run destroys another owner's VMs.**++VMs are named `ubirun-<owner>-<epoch>-<suffix>`, where the owner is `UBI_OWNER` or a per-machine id. Before, nothing showed which thread a VM belonged to, and every `up` destroyed any `ubirun-*` VM older than 12 hours, whoever started it. That sweep is now off unless `UBI_GC_HOURS` is set, and even then it only destroys the caller's own VMs. `ubi-runner.sh gc HOURS` runs the same sweep by hand.++A run stopped with SIGTERM while VMs were still provisioning used to tear down before their create requests finished. Those VMs appeared afterwards and leaked (three `standard-16` VMs sat idle for 84 minutes). Now each name is recorded before its create is sent. An interrupted `up` finishes its create request and destroys its own VM. Teardown then polls every recorded name until it is confirmed gone. A mock-API test reproduces the old leak (two of three VMs left behind) and passes with the fix.++`ubi-runner.sh list --mine` lists your VMs, and `ubi-runner.sh usage` shows VMs and vCPUs per owner across the project.++## To take advantage of v0.60.70.0++- Run `UBI_OWNER=<your-thread-code> bun run ci:ubicloud`. You no longer need `UBI_GC_HOURS=0`.+- In a multi-lane wave, lanes run `ci:ubicloud:diff` or targeted suites, and only the integrator runs the full gate. One full gate takes 64 of the project's 256 vCPUs.+## [0.60.69.0] - 2026-10-05**Korean entity names stop linking from inside longer words: mention precision on Hangul goes from 7% to 86%, and 65 of 74 real name mentions still link.**diff --git a/VERSION b/VERSIONindex 19023702bd..34c2ddde40 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.60.69.0+0.60.70.0diff --git a/docs/TESTING.md b/docs/TESTING.mdindex e27e604136..2290b7edad 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -450,6 +450,15 @@ too; build the admin app on the host when updating its committed bundle.from one heaviest-first work queue; every VM is destroyed on exit. VM setup, scheduling, weights, quotaand flags are in [scripts/ubicloud/README.md](../scripts/ubicloud/README.md).+VMs are named `ubirun-<owner>-<epoch>-<suffix>`; set `UBI_OWNER` to your thread+code. Teardown destroys every VM the run asked for, including creates still in+flight, and stale-VM sweeps run only with `UBI_GC_HOURS` set and only on your+own VMs. `scripts/ubicloud/ubi-runner.sh usage` shows vCPUs by owner.++The project quota is 256 vCPUs, shared with PR CI, and one full gate takes 64.+In a multi-lane wave, lanes run `ci:ubicloud:diff` or targeted suites (`bun+test <files>`, `--lanes`); only the integrator runs the full gate.+### E2E backend matrix`scripts/e2e-backend-matrix.txt` lists the E2E files that must pass on directdiff --git a/llms-full.txt b/llms-full.txtindex 4c303208ff..cebc6f6ccb 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -1895,10 +1895,12 @@ seconds (gitleaks plus the doc checks) and runs the full gate otherwise. Require(Docker Desktop / OrbStack / Colima) and `gitleaks` (`brew install gitleaks`).Fastest path, with a Ubicloud token (`UBICLOUD_API_KEY` or-`UBICLOUD_API_TOKEN`): `bun run ci:ubicloud` runs the same gate across ten+`UBICLOUD_API_TOKEN`): `bun run ci:ubicloud` runs the same gate across fourephemeral VMs in about five minutes, uncommitted edits included(`ci:ubicloud:diff` for the doc-only fast path). See "Ubicloud fan-out" in-[`docs/TESTING.md`](./docs/TESTING.md).+[`docs/TESTING.md`](./docs/TESTING.md). Set `UBI_OWNER` to your thread code. In a+multi-lane wave, lanes run `ci:ubicloud:diff` or targeted suites; only the+integrator runs the full gate.Manual path: `bun test` plus the E2E lifecycle described in `./CLAUDE.md` (spinup the test Postgres container, run `bun run test:e2e`, tear it down).diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex eb9eeb1a09..3c618b5d81 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.60.69.0",+ "version": "0.60.70.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","kind": "context-engine",diff --git a/package.json b/package.jsonindex 5c77b8ef0d..452d079953 100644--- a/package.json+++ b/package.json@@ -219,7 +219,7 @@"bun": ">=1.4.0"},"license": "MIT",- "version": "0.60.69.0",+ "version": "0.60.70.0","overrides": {"@ai-sdk/provider-utils": "4.0.56","@hono/node-server": "^2.0.5",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex a0a5b42859..f195704633 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.60.69.0",+ "version": "0.60.70.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex 9491c53e87..82034c0970 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.60.69.0",+ "version": "0.60.70.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex fa5cff2d97..af8ad25b1f 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.69.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.70.0 --># gbrain-coding (generated persona variant — do not hand-edit)Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex 1100944314..677d01ae6f 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.60.69.0",+ "version": "0.60.70.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex f592f18427..50e27aad1d 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.60.69.0",+ "version": "0.60.70.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex fce4fbdf0c..85f3ca6890 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.69.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.70.0 --># gbrain-daily (generated persona variant — do not hand-edit)Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.diff --git a/plugin/README.md b/plugin/README.mdindex 66eba794be..ef4dcc135c 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.69.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.70.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/scripts/ci-ubicloud.ts b/scripts/ci-ubicloud.tsindex fa1a2c070e..73eaa78807 100755--- a/scripts/ci-ubicloud.ts+++ b/scripts/ci-ubicloud.ts@@ -30,11 +30,16 @@* from (scripts/ubicloud/schedule.ts); items run through the same wrappers* ci:local uses (scripts/ubicloud/ci-item.sh). Durations of every run are* merged into .context/ci-ubicloud/weights.json, which weights the next run.- * All VMs are destroyed on exit, including Ctrl-C.+ *+ * VMs are named ubirun-<owner>-<epoch>-ciNN<hex> (owner: UBI_OWNER or the+ * runner's per-machine id). Each name is appended to <run>/vms.txt before its+ * create request is sent. On exit, including SIGINT and SIGTERM, in-flight+ * `up` calls are allowed to finish (they destroy their own VM), then every+ * recorded name is destroyed and polled until it is confirmed gone.*/import { spawn, spawnSync } from "node:child_process";-import { createReadStream, createWriteStream, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { appendFileSync, createReadStream, createWriteStream, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join, resolve } from "node:path";import {@@ -133,13 +138,13 @@ function sh(cmd: string, args: string[]): string {}const lines = (text: string) => text.split(/\s+/).map((l) => l.trim()).filter(Boolean);-const children = new Set<ReturnType<typeof spawn>>();+const children = new Map<ReturnType<typeof spawn>, string>();/** Run the runner script; stdout goes to `out` (a path) or is returned. */function runner(args: string[], opts: { out?: string; input?: string; timeoutMs?: number } = {}): Promise<{ code: number; stdout: string }> {return new Promise((resolvePromise) => {const child = spawn("bash", [RUNNER, ...args], { cwd: ROOT, stdio: ["pipe", "pipe", "pipe"] });- children.add(child);+ children.set(child, args[0]!);let stdout = "";let stderr = "";const sink = opts.out ? createWriteStream(opts.out) : null;@@ -166,7 +171,7 @@ const quote = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`;interface Vm {name: string;state: "provisioning" | "setup" | "ready" | "failed" | "destroyed";- created: boolean;+ requested: boolean;infraErrors: number;setupMs?: number;busySlots: number;@@ -239,32 +244,44 @@ async function main() {?? "1.4.2";// ── Teardown on every exit path ──────────────────────────────────────────+ const owner = sh("bash", [RUNNER, "owner"]).trim();+ const ledger = join(runDir, "vms.txt");const vms: Vm[] = Array.from({ length: opts.vms }, (_, i) => ({- name: `ubirun-${Math.floor(Date.now() / 1000)}-ci${String(i + 1).padStart(2, "0")}${Math.random().toString(16).slice(2, 6)}`,+ name: `ubirun-${owner}-${Math.floor(Date.now() / 1000)}-ci${String(i + 1).padStart(2, "0")}${Math.random().toString(16).slice(2, 6)}`,state: "provisioning",- created: false,+ requested: false,infraErrors: 0,busySlots: 0,heavy: 0,}));- let tornDown = false;- const teardown = async () => {- if (tornDown) return;- tornDown = true;- for (const child of children) child.kill("SIGKILL");+ // Memoized: the signal handler and main's finally must await the same+ // teardown, or main exits while its `down` calls are still running.+ let tornDown: Promise<void> | null = null;+ const teardown = () => (tornDown ??= destroyAll());+ const destroyAll = async () => {+ // An `up` gets SIGTERM, records its create answer and destroys its own VM;+ // waiting for it means no create request is in flight when `down` runs.+ const ups = [...children].filter(([, sub]) => sub === "up").map(([child]) => child);+ for (const [child, sub] of children) child.kill(sub === "up" ? "SIGTERM" : "SIGKILL");+ await Promise.all(ups.map((child) => new Promise((done) => (child.exitCode !== null || child.signalCode !== null ? done(null) : child.once("exit", done)))));rmSync(tarball, { force: true });- const live = vms.filter((vm) => vm.state !== "destroyed");+ const live = vms.filter((vm) => vm.requested && vm.state !== "destroyed");if (opts.keep) {log(`--keep: leaving ${live.map((vm) => vm.name).join(" ")} running; destroy with: scripts/ubicloud/ubi-runner.sh down NAME`);return;}- log(`destroying ${live.length} VM(s)`);+ log(`destroying ${live.length} VM(s): ${live.map((vm) => vm.name).join(" ")}`);await Promise.all(live.map(async (vm) => {- // A VM whose create call may be in flight is looked up by name.- const r = await runner(["down", vm.name]);- if (r.code === 0 || !vm.created || /not found/.test(r.stdout)) vm.state = "destroyed";- else console.error(`ci-ubicloud: WARNING failed to destroy ${vm.name}; run: scripts/ubicloud/ubi-runner.sh down ${vm.name}`);+ for (let attempt = 1; attempt <= 3; attempt++) {+ if ((await runner(["down", vm.name, "-l", opts.location])).code === 0) {+ vm.state = "destroyed";+ return;+ }+ }+ console.error(`ci-ubicloud: WARNING could not confirm ${vm.name} is gone; run: scripts/ubicloud/ubi-runner.sh down ${vm.name} -l ${opts.location}`);}));+ const left = live.filter((vm) => vm.state !== "destroyed").length;+ log(left ? `teardown left ${left} VM(s) unconfirmed (names in ${ledger})` : `teardown confirmed ${live.length} VM(s) gone`);};let interrupted = false;for (const signal of ["SIGINT", "SIGTERM"] as const) {@@ -360,8 +377,11 @@ async function main() {const vmLifecycle = async (vm: Vm, index: number) => {const started = Date.now();const setupLog = join(runDir, "logs", `setup-${vm.name}.log`);+ if (tornDown) return;+ vm.requested = true;+ appendFileSync(ledger, `${vm.name} ${opts.location}\n`);const up = await runner(["up", "-n", vm.name, "-s", opts.size, "-l", opts.location], { out: setupLog });- vm.created = true;+ if (tornDown) return;if (up.code !== 0) {vm.state = "failed";log(`VM ${index + 1} failed to provision (see ${setupLog}): ${readFileSync(setupLog, "utf8").trim().split("\n").slice(-2).join(" | ")}`);diff --git a/scripts/ubicloud/README.md b/scripts/ubicloud/README.mdindex 02bedea055..6e62ee0eaa 100644--- a/scripts/ubicloud/README.md+++ b/scripts/ubicloud/README.md@@ -4,8 +4,36 @@instead of one Docker host. It packs the working tree once (tracked files,untracked files that are not ignored, and `.git`) and streams it to every VM, souncommitted edits are tested. `scripts/ubicloud/ubi-runner.sh` creates and-destroys the VMs; every VM is destroyed on exit, including Ctrl-C, and any-`ubirun-*` VM older than 12 hours is garbage-collected by the next run.+destroys the VMs.++## Ownership and teardown++Every VM is named `ubirun-<owner>-<epoch>-<suffix>`. The owner is `UBI_OWNER`+(lowercased, letters and digits only, at most 12 characters, starting with a+letter) or a random per-machine id kept in the runner's state directory. Set+`UBI_OWNER` to your thread code (`UBI_OWNER=gbra41 bun run ci:ubicloud`) so+everyone can see whose VMs hold the quota. Ubicloud names allow 63 characters+of `[a-z0-9-]`, so a full name stays under 40.++Each name is recorded before its create request is sent: the runner writes+the VM's state directory first, and `ci-ubicloud.ts` appends the name to+`.context/ci-ubicloud/<run>/vms.txt`. On every exit, including Ctrl-C and+SIGTERM, an `up` still talking to the API finishes the request and destroys its+own VM. Then every recorded name gets `down`, which destroys the VM and polls+until it is confirmed gone. A create whose answer never arrived is waited out+for `UBI_CREATE_GRACE` seconds (default 180) before the VM counts as never+created. `down` gives up after `UBI_DOWN_TIMEOUT` seconds (default 900) and+prints the command to rerun.++Nothing sweeps stale VMs unless you ask. With `UBI_GC_HOURS` set to a positive+number, each `up` first destroys the caller's own VMs older than that many+hours. An operator runs the same sweep with `ubi-runner.sh gc HOURS`. Neither+ever destroys another owner's VM, an untagged legacy `ubirun-<epoch>-*` VM, or a+VM the runner did not name. Use `down NAME` for those after checking who owns+them.++`ubi-runner.sh list --mine` lists your VMs. `ubi-runner.sh usage` prints VMs+and vCPUs per owner across the project, which shows who holds the shared quota.Each VM runs `scripts/ubicloud/setup-ci-vm.sh`: the pinned Bun from`docker-compose.ci.yml`, the runner container's test prerequisites plus Node,@@ -45,7 +73,10 @@ Defaults are four `standard-16` VMs (64 vCPUs) in `eu-central-h1` with 8 slotseach, one per two vCPUs (`--vms`, `--size`, `--slots`, `--location`). TheUbicloud project's vCPU quota (256) is shared with pull-request CI, so thedefault leaves room for about two concurrent PR runs; the former default of-ten VMs took 160 vCPUs and queued PR jobs for up to 28 minutes. A VM that the+ten VMs took 160 vCPUs and queued PR jobs for up to 28 minutes. In a+multi-lane wave, each lane runs `ci:ubicloud:diff` or its targeted suites, and+only the integrator runs the full gate; four lanes each running the full gate+take 256 vCPUs, the whole quota. A VM that thequota refuses fails to provision and the run continues on the VMs that didstart, so a busy project shrinks the fleet instead of failing. Pass `--vms 10`only when the quota is idle. Slow-lane items run `test/export-scale.slow.test.ts`diff --git a/scripts/ubicloud/ubi-runner.sh b/scripts/ubicloud/ubi-runner.shindex 1869a5c4de..6d1f2d3f02 100755--- a/scripts/ubicloud/ubi-runner.sh+++ b/scripts/ubicloud/ubi-runner.sh@@ -13,9 +13,21 @@# optional setup script and the command, copies requested artifacts back, and# destroys the VM on every exit path. Exits with the command's status.# Needs only bash, curl, python3, ssh, ssh-keygen, and tar locally, so it works-# from dev boxes, containers, and cloud sandboxes. VMs are named-# ubirun-<epoch>-<hex>; every `up` first destroys ubirun-* VMs older than-# UBI_GC_HOURS (default 12) so an interrupted client cannot leak one for long.+# from dev boxes, containers, and cloud sandboxes.+#+# Ownership: VMs are named ubirun-<owner>-<epoch>-<suffix>. <owner> is UBI_OWNER+# (lowercased, letters and digits only, at most 12 characters, starting with a+# letter) or a random per-machine id kept in $STATE_ROOT/owner-id. Ubicloud names+# allow 63 characters of [a-z0-9-], so a full name stays under 40.+#+# Teardown: `up` records each VM's state (location, create status) before it+# sends the create request, and `down` destroys and polls until the VM is+# confirmed gone or provably never existed, waiting out a create that may still+# be in flight. An interrupted `up` or `run` (EXIT, INT, TERM) runs that `down`.+#+# Stale-VM sweeps are off by default. With UBI_GC_HOURS set to a positive+# number, every `up` first destroys this owner's VMs older than that; `gc HOURS`+# runs the same sweep on demand. Neither ever touches another owner's VMs.set -euo pipefail# Keep heredoc bodies on temp files, not the pipe window (test/heredoc-pipe-deadlock.test.ts).BASH_COMPAT=50@@ -24,7 +36,11 @@ API="${UBICLOUD_API_URL:-https://api.ubicloud.com}"STATE_ROOT="${UBI_RUNNER_STATE:-${XDG_STATE_HOME:-$HOME/.local/state}/ubi-runner}"DEFAULT_SIZE="${UBI_SIZE:-standard-16}"DEFAULT_LOCATION="${UBI_LOCATION:-eu-central-h1}"-GC_HOURS="${UBI_GC_HOURS:-12}"+GC_HOURS="${UBI_GC_HOURS:-0}"+API_TIMEOUT="${UBI_API_TIMEOUT:-120}"+CREATE_GRACE="${UBI_CREATE_GRACE:-180}"+DOWN_TIMEOUT="${UBI_DOWN_TIMEOUT:-900}"+POLL="${UBI_POLL_SECONDS:-5}"PREFIX="ubirun"die() { echo "ubi-runner: $*" >&2; exit 1; }@@ -34,16 +50,48 @@ for bin in curl python3 ssh ssh-keygen tar; docommand -v "$bin" >/dev/null || die "$bin is required"doneUBICLOUD_API_KEY="${UBICLOUD_API_KEY:-${UBICLOUD_API_TOKEN:-}}"-[ -n "${UBICLOUD_API_KEY:-}" ] || die "UBICLOUD_API_KEY is not set (create a token under your Ubicloud project's Tokens page)"+[[ "$GC_HOURS" =~ ^[0-9]+$ ]] || die "UBI_GC_HOURS must be a whole number of hours (unset or 0 disables the sweep)"-cli() {- local out code- out=$(mktemp)+owner_id() {+ local raw=${UBI_OWNER:-} file="$STATE_ROOT/owner-id" tmp+ if [ -z "$raw" ]; then+ if [ ! -s "$file" ]; then+ mkdir -p "$STATE_ROOT"+ tmp="$file.$$"+ echo "m$(head -c4 /dev/urandom | od -An -tx1 | tr -d ' \n')" >"$tmp"+ mv -n "$tmp" "$file"+ rm -f "$tmp"+ fi+ raw=$(cat "$file")+ fi+ raw=$(printf %s "$raw" | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9')+ [ -n "$raw" ] || die "UBI_OWNER must contain letters or digits"+ [[ "$raw" =~ ^[a-z] ]] || raw="u$raw"+ echo "${raw:0:12}"+}+OWNER=$(owner_id)++# api OUT ARGS...: send one Ubicloud CLI command, write the body to OUT, and+# print the HTTP status (000 when no response arrived).+api() {+ local out=$1 code+ shiftcode=$(python3 -c 'import json,sys; print(json.dumps({"argv": sys.argv[1:]}))' "$@" \- | curl -sS -o "$out" -w '%{http_code}' -X POST \+ | curl -sS -o "$out" -w '%{http_code}' --max-time "$API_TIMEOUT" -X POST \-H "Authorization: Bearer $UBICLOUD_API_KEY" \-H 'Accept: text/plain' -H 'Content-Type: application/json' \- -H 'X-Ubi-Version: 1.0.0' --data @- "$API/cli") || { rm -f "$out"; die "request failed: ubi $*"; }+ -H 'X-Ubi-Version: 1.0.0' --data @- "$API/cli") || true+ echo "${code:-000}"+}++cli() {+ local out code+ out=$(mktemp)+ code=$(api "$out" "$@")+ if [ "$code" = 000 ]; then+ rm -f "$out"+ die "request failed: ubi $*"+ fiif [ "$code" != 200 ]; thencat "$out" >&2rm -f "$out"@@ -79,25 +127,75 @@ remote() {ssh $(ssh_opts) "ubi@$IP" "umask 022; $*"}+# vm_rows: "location name owner" for every VM in the project; owner is+# "-" for untagged ubirun-<epoch>-* names and "." for VMs this runner did not name.+vm_rows() {+ cli vm list -N -f location,name | while read -r loc name; do+ if [[ "$name" =~ ^${PREFIX}-([a-z][a-z0-9]{0,11})-[0-9]{10}- ]]; then+ echo "$loc $name ${BASH_REMATCH[1]}"+ elif [[ "$name" =~ ^${PREFIX}-[0-9]{10}- ]]; then+ echo "$loc $name -"+ else+ echo "$loc $name ."+ fi+ done+}+cmd_gc() {- local hours=${1:-$GC_HOURS} now loc name ts- [ "$hours" -gt 0 ] || return 0+ local hours=${1:-$GC_HOURS} now loc name owner+ if ! [[ "$hours" =~ ^[0-9]+$ ]] || [ "$hours" -eq 0 ]; then die "gc: give HOURS > 0 (or set UBI_GC_HOURS)"; finow=$(date +%s)- cli vm list -N -f location,name | while read -r loc name; do- [[ "$name" =~ ^${PREFIX}-([0-9]{10})- ]] || continue- ts=${BASH_REMATCH[1]}- if [ $(( (now - ts) / 3600 )) -ge "$hours" ]; then- log "destroying stale $loc/$name (older than ${hours}h)"- cli vm "$loc/$name" destroy -f >/dev/null || log "failed to destroy $loc/$name"- rm -rf "$(state_dir "$name")"+ vm_rows | while read -r loc name owner; do+ [ "$owner" = "$OWNER" ] || continue+ [[ "$name" =~ -([0-9]{10})- ]] || continue+ if [ $(( (now - BASH_REMATCH[1]) / 3600 )) -ge "$hours" ]; then+ log "destroying stale $loc/$name (owner $OWNER, older than ${hours}h)"+ cmd_down "$name" -l "$loc" || log "failed to destroy $loc/$name"fidone}+cmd_list() {+ case ${1:-} in+ "") cli vm list ;;+ --mine) vm_rows | awk -v o="$OWNER" '$3==o {print $1 " " $2}' ;;+ *) die "list: unknown option $1 (use --mine)" ;;+ esac+}++# usage: VMs and vCPUs per owner, from each VM's size (standard-16 = 16 vCPUs).+cmd_usage() {+ local tmp loc name owner i=0+ tmp=$(mktemp -d)+ while read -r loc name owner; do+ i=$(( i + 1 ))+ cli vm "$loc/$name" show 2>/dev/null | sed -n "s/^size: /$owner /p" >"$tmp/$i" &+ [ $(( i % 8 )) -ne 0 ] || wait+ done < <(vm_rows)+ wait+ cat "$tmp"/* 2>/dev/null | awk -v me="$OWNER" '+ { n = $2; sub(/^.*-/, "", n); o = $1 == "-" ? "(untagged)" : $1 == "." ? "(other)" : $1+ vms[o]++; cpu[o] += n; total += n; count++ }+ END {+ printf "%-14s %4s %6s\n", "OWNER", "VMS", "VCPUS"+ for (o in cpu) printf "%-14s %4d %6d%s\n", o, vms[o], cpu[o], o == me ? " (you)" : "" | "sort -k3,3nr"+ close("sort -k3,3nr")+ printf "%-14s %4d %6d\n", "total", count, total+ }'+ rm -rf "$tmp"+}+write_state() {- printf 'NAME=%q\nLOCATION=%q\nSIZE=%q\nIP=%q\n' "$1" "$2" "$3" "$4" >"$(state_dir "$1")/env"+ printf 'NAME=%q\nLOCATION=%q\nSIZE=%q\nIP=%q\nCREATED=%q\nCREATE_AT=%q\nCREATE_PID=%q\n' \+ "$1" "$2" "$3" "$4" "$5" "$6" "$$" >"$(state_dir "$1")/env"}+new_name() { echo "$PREFIX-$OWNER-$(date +%s)-$(head -c4 /dev/urandom | od -An -tx1 | tr -d ' \n')"; }++valid_name() { [[ "$1" =~ ^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$ ]]; }++UP_NAME=""+UP_READY=""cmd_up() {local size=$DEFAULT_SIZE location=$DEFAULT_LOCATION name="" storage="" image=ubuntu-noblewhile [ $# -gt 0 ]; do@@ -110,10 +208,13 @@ cmd_up() {*) die "up: unknown option $1" ;;esacdone- [ -n "$name" ] || name="$PREFIX-$(date +%s)-$(head -c4 /dev/urandom | od -An -tx1 | tr -d ' \n')"- cmd_gc "$GC_HOURS" || log "stale-VM cleanup failed; continuing"+ [ -n "$name" ] || name=$(new_name)+ valid_name "$name" || die "invalid VM name '$name' (Ubicloud allows 1-63 of a-z, 0-9 and '-', starting and ending with a letter or digit)"+ if [ "$GC_HOURS" -gt 0 ]; then+ cmd_gc "$GC_HOURS" || log "stale-VM cleanup failed; continuing"+ fi- local dir+ local dir create_atdir=$(state_dir "$name")mkdir -p "$dir"chmod 700 "$dir"@@ -122,9 +223,19 @@ cmd_up() {local args=(vm "$location/$name" create -s "$size" -b "$image")[ -z "$storage" ] || args+=(-S "$storage")args+=("$(cat "$dir/key.pub")")+ create_at=$(date +%s)+ write_state "$name" "$location" "$size" "" unknown "$create_at"+ UP_NAME=$namelog "creating $location/$name ($size)"- cli "${args[@]}" >/dev/null || { rm -rf "$dir"; die "create failed"; }- write_state "$name" "$location" "$size" ""+ # Hold INT/TERM until the create answer is recorded, so teardown knows+ # whether the VM exists instead of waiting out UBI_CREATE_GRACE.+ local interrupted="" created=yes+ trap 'interrupted=1' INT TERM+ cli "${args[@]}" >/dev/null || created=no+ write_state "$name" "$location" "$size" "" "$created" "$create_at"+ trap 'exit 130' INT TERM+ [ -z "$interrupted" ] || exit 130+ [ "$created" = yes ] || die "create failed"local deadline=$(( $(date +%s) + 600 )) show state ipwhile :; do@@ -132,39 +243,85 @@ cmd_up() {state=$(sed -n 's/^state: //p' <<<"$show")ip=$(sed -n 's/^ip4: //p' <<<"$show")[ "$state" = running ] && [ -n "$ip" ] && break- [ "$(date +%s)" -lt "$deadline" ] || { cmd_down "$name"; die "VM did not reach running in 10 minutes (last state: ${state:-unknown})"; }- sleep 5+ [ "$(date +%s)" -lt "$deadline" ] || die "VM did not reach running in 10 minutes (last state: ${state:-unknown})"+ sleep "$POLL"done- write_state "$name" "$location" "$size" "$ip"+ write_state "$name" "$location" "$size" "$ip" yes "$create_at"load "$name"deadline=$(( $(date +%s) + 300 ))# shellcheck disable=SC2046until ssh $(ssh_opts) "ubi@$IP" true 2>/dev/null; do- [ "$(date +%s)" -lt "$deadline" ] || { cmd_down "$name"; die "SSH did not come up on $IP"; }- sleep 5+ [ "$(date +%s)" -lt "$deadline" ] || die "SSH did not come up on $IP"+ sleep "$POLL"doneremote "$name" 'cloud-init status --wait >/dev/null 2>&1 || true'+ UP_READY=1log "ready: $name ($IP)"echo "$name"}+# down NAME [-l LOCATION]: destroy NAME and return 0 only once it is confirmed+# gone or never existed. While this machine's create request for NAME may+# still be in flight (its `up` process is alive, or the create was sent less+# than UBI_CREATE_GRACE seconds ago with no answer), "not found" is not final.cmd_down() {- local name=$1 dir loc+ local name=${1:-} loc="" dir+ [ -n "$name" ] || die "down: missing NAME"+ shift+ while [ $# -gt 0 ]; do+ case $1 in+ -l|--location) loc=$2; shift 2 ;;+ *) die "down: unknown option $1" ;;+ esac+ done+ valid_name "$name" || die "invalid VM name '$name'"dir=$(state_dir "$name")+ local CREATED=none CREATE_AT=0 CREATE_PID="" IP="" LOCATION="" KEY=""if [ -f "$dir/env" ]; thenload "$name"loc=$LOCATION- else- loc=$(cli vm list -N -f location,name | awk -v n="$name" '$2==n {print $1}')- [ -n "$loc" ] || die "VM '$name' not found"- fi- if [ -S "$dir/ctl" ]; then- # shellcheck disable=SC2046- ssh $(ssh_opts) -O exit "ubi@$IP" >/dev/null 2>&1 || true+ if [ -S "$dir/ctl" ] && [ -n "$IP" ]; then+ # shellcheck disable=SC2046+ ssh $(ssh_opts) -O exit "ubi@$IP" >/dev/null 2>&1 || true+ fifi- cli vm "$loc/$name" destroy -f >/dev/null && log "destroyed $loc/$name"- rm -rf "$dir"++ local deadline=$(( $(date +%s) + DOWN_TIMEOUT )) seen=0 asked=0 out code now+ out=$(mktemp)+ while :; do+ now=$(date +%s)+ if [ -z "$loc" ]; then+ loc=$(vm_rows 2>/dev/null | awk -v n="$name" '$2==n {print $1}') || loc=""+ code=404+ [ -z "$loc" ] || code=$(api "$out" vm "$loc/$name" show)+ else+ code=$(api "$out" vm "$loc/$name" show)+ fi+ if [ "$code" = 200 ]; then+ seen=1+ if [ $(( now - asked )) -ge 60 ]; then+ api "$out" vm "$loc/$name" destroy -f >/dev/null+ asked=$now+ log "destroy requested: $loc/$name"+ fi+ elif [ "$code" = 404 ]; then+ if [ "$seen" = 1 ] || [ "$CREATED" != unknown ] || { [ $(( now - CREATE_AT )) -ge "$CREATE_GRACE" ] \+ && { [ "$CREATE_PID" = "$$" ] || ! kill -0 "$CREATE_PID" 2>/dev/null; }; }; then+ rm -f "$out"+ rm -rf "$dir"+ if [ "$seen" = 1 ]; then log "destroyed ${loc:-?}/$name"; else log "gone: ${loc:-?}/$name (never existed or already destroyed)"; fi+ return 0+ fi+ log "waiting for an in-flight create of $name to resolve"+ fi+ if [ "$now" -ge "$deadline" ]; then+ rm -f "$out"+ log "WARNING: could not confirm ${loc:-?}/$name is gone after ${DOWN_TIMEOUT}s; rerun: $0 down $name"+ return 1+ fi+ sleep "$POLL"+ done}# pack SRC: write a gzipped checkout tarball to stdout (tracked + untracked@@ -230,13 +387,19 @@ cmd_run() {src=$(cd "$src" && pwd)[ -n "$dest" ] || dest="work/$(basename "$src")"- RUN_VM=$(cmd_up ${up_args[@]+"${up_args[@]}"})- local name=$RUN_VM+ local i name=""+ for (( i = 0; i < ${#up_args[@]}; i += 2 )); do+ case ${up_args[i]} in -n|--name) name=${up_args[i+1]} ;; esac+ done+ [ -n "$name" ] || { name=$(new_name); up_args+=(-n "$name"); }+ RUN_VM=$name+ # Armed before the create request: an interrupted `up` still destroys its VM.+ trap 'cmd_down "$RUN_VM" || log "WARNING: failed to destroy $RUN_VM; run: $0 down $RUN_VM"' EXIT+ trap 'exit 130' INT TERM+ cmd_up "${up_args[@]}" >/dev/nullif [ "$keep" = 1 ]; then+ trap - EXITlog "--keep: leaving $name running; destroy with: $0 down $name"- else- trap 'cmd_down "$RUN_VM" || log "WARNING: failed to destroy $RUN_VM; run: $0 down $RUN_VM"' EXIT- trap 'exit 130' INT TERMfilocal e@@ -280,20 +443,32 @@ usage: ubi-runner.sh <command> [args]unpack NAME DEST extract a tarball from stdin into DEST on the VMpull NAME REMOTE_GLOB LOCAL_DIRcopy matching remote entries into LOCAL_DIR- down NAME destroy the VM- list list all VMs in the project- gc [HOURS] destroy $PREFIX-* VMs older than HOURS (default $GC_HOURS)+ down NAME [-l LOC] destroy the VM; returns once it is confirmed gone or never existed+ list [--mine] list all VMs in the project, or only this owner's+ usage VMs and vCPUs per owner across the project+ owner print this caller's owner tag ($OWNER)+ gc HOURS destroy this owner's VMs older than HOURS (never other owners')cli ARGS... raw Ubicloud CLI passthrough (e.g. cli vm list)+VMs are named $PREFIX-<owner>-<epoch>-<suffix>; set UBI_OWNER (e.g. your thread+code) to tag them, otherwise a per-machine id is used.defaults: size=$DEFAULT_SIZE location=$DEFAULT_LOCATION (env UBI_SIZE, UBI_LOCATION)+env: UBI_GC_HOURS (unset/0: no sweep on up), UBI_CREATE_GRACE (${CREATE_GRACE}s),+ UBI_DOWN_TIMEOUT (${DOWN_TIMEOUT}s), UBI_API_TIMEOUT (${API_TIMEOUT}s)EOF}cmd=${1:-help}[ $# -eq 0 ] || shift+case $cmd in+ owner|pack|help|-h|--help) ;;+ *) [ -n "${UBICLOUD_API_KEY:-}" ] || die "UBICLOUD_API_KEY is not set (create a token under your Ubicloud project's Tokens page)" ;;+esaccase $cmd inrun) cmd_run "$@" ;;- up) cmd_up "$@" ;;+ up) trap '[ -z "$UP_NAME" ] || [ -n "$UP_READY" ] || cmd_down "$UP_NAME" || log "WARNING: failed to destroy $UP_NAME; run: $0 down $UP_NAME"' EXIT+ trap 'exit 130' INT TERM+ cmd_up "$@" ;;ssh) name=$1; shift; load "$name"# shellcheck disable=SC2046if [ $# -eq 0 ]; then exec ssh -t $(ssh_opts) "ubi@$IP"; else remote "$name" "bash -lc $(printf %q "$*")"; fi ;;@@ -302,7 +477,9 @@ case $cmd inunpack) cmd_unpack "$@" ;;pull) cmd_pull "$@" ;;down) cmd_down "$@" ;;- list) cli vm list ;;+ list) cmd_list "$@" ;;+ usage) cmd_usage ;;+ owner) echo "$OWNER" ;;gc) cmd_gc "$@" ;;cli) cli "$@" ;;help|-h|--help) usage ;;diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex f28859beed..fc55d828ad 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.60.69.0 -->+<!-- gbrain-template-stamp: 0.60.70.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/helpers/mock-ubicloud-api.ts b/test/helpers/mock-ubicloud-api.tsnew file mode 100644index 0000000000..5fbdd9c47e--- /dev/null+++ b/test/helpers/mock-ubicloud-api.ts@@ -0,0 +1,92 @@+// mock-ubicloud-api.ts — an in-process stand-in for Ubicloud's POST /cli+// endpoint, enough for scripts/ubicloud/ubi-runner.sh: `vm list`, `vm L/N+// create` (slow on purpose, and completed even when the client hangs up, like+// the real API), `vm L/N show` (404 once gone) and `vm L/N destroy -f`.+// VMs never reach `running`, so every `up` stays mid-provision until killed.++export interface MockVm {+ location: string;+ name: string;+ size: string;+ state: "creating" | "destroying";+}++export interface MockUbicloudOptions {+ /** Delay before a create lands, per VM name. Default 0. */+ createDelayMs?: (name: string) => number;+ /** Delay between `destroy` and the VM disappearing. Default 200. */+ destroyDelayMs?: number;+ /** Answer every create with a 400, like a quota refusal. */+ rejectCreates?: boolean;+ seed?: Array<{ location?: string; name: string; size?: string }>;+}++export interface MockUbicloud {+ url: string;+ vms: Map<string, MockVm>;+ /** "create-start N", "created N", "create-rejected N", "destroy N", "removed N", in order. */+ events: string[];+ stop(): void;+}++export function startMockUbicloud(opts: MockUbicloudOptions = {}): MockUbicloud {+ const vms = new Map<string, MockVm>();+ const events: string[] = [];+ for (const vm of opts.seed ?? []) {+ vms.set(vm.name, { location: vm.location ?? "eu-central-h1", name: vm.name, size: vm.size ?? "standard-16", state: "creating" });+ }+ const text = (body: string, status = 200) => new Response(body, { status, headers: { "content-type": "text/plain" } });+ const server = Bun.serve({+ port: 0,+ hostname: "127.0.0.1",+ async fetch(req) {+ const { argv } = (await req.json()) as { argv: string[] };+ if (argv[0] !== "vm") return text(`! unsupported: ${argv.join(" ")}`, 400);+ if (argv[1] === "list") {+ return text([...vms.values()].map((vm) => `${vm.location} ${vm.name}\n`).join(""));+ }+ const [location, name] = (argv[1] ?? "").split("/") as [string, string];+ const verb = argv[2];+ if (verb === "create") {+ events.push(`create-start ${name}`);+ await Bun.sleep(opts.createDelayMs?.(name) ?? 0);+ if (opts.rejectCreates) {+ events.push(`create-rejected ${name}`);+ return text("! Validation failed: quota exceeded", 400);+ }+ const size = argv[argv.indexOf("-s") + 1] ?? "standard-16";+ vms.set(name, { location, name, size, state: "creating" });+ events.push(`created ${name}`);+ return text(`VM created with id: vm-${name}`);+ }+ const vm = vms.get(name);+ if (verb === "show") {+ if (!vm) return text("! Unexpected response status: 404", 404);+ return text(`id: vm-${name}\nname: ${name}\nstate: ${vm.state}\nlocation: ${vm.location}\nsize: ${vm.size}\n`);+ }+ if (verb === "destroy") {+ if (vm && vm.state !== "destroying") {+ vm.state = "destroying";+ events.push(`destroy ${name}`);+ setTimeout(() => {+ vms.delete(name);+ events.push(`removed ${name}`);+ }, opts.destroyDelayMs ?? 200);+ }+ return text("Virtual machine, if it exists, is now scheduled for destruction");+ }+ return text(`! unsupported: ${argv.join(" ")}`, 400);+ },+ });+ return { url: `http://127.0.0.1:${server.port}`, vms, events, stop: () => server.stop(true) };+}++export async function waitForEvent(mock: MockUbicloud, pattern: RegExp, timeoutMs = 20_000): Promise<string> {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ const hit = mock.events.find((e) => pattern.test(e));+ if (hit) return hit;+ await Bun.sleep(25);+ }+ throw new Error(`no event matching ${pattern} within ${timeoutMs}ms; events: ${mock.events.join(", ")}`);+}diff --git a/test/scripts/ci-ubicloud-teardown.slow.test.ts b/test/scripts/ci-ubicloud-teardown.slow.test.tsnew file mode 100644index 0000000000..2d0a518ec9--- /dev/null+++ b/test/scripts/ci-ubicloud-teardown.slow.test.ts@@ -0,0 +1,63 @@+// ci-ubicloud-teardown.slow.test.ts — SIGTERM to scripts/ci-ubicloud.ts while+// its VMs are still provisioning (one created, two creates in flight) against+// a mock Ubicloud API. Every name is recorded before its create, and teardown+// returns only after each VM that came to exist is destroyed and gone. Slow+// because the orchestrator packs the whole checkout before provisioning.++import { afterEach, describe, expect, it } from "bun:test";+import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";+import { startMockUbicloud, waitForEvent, type MockUbicloud } from "../helpers/mock-ubicloud-api.ts";++const ROOT = resolve(import.meta.dir, "..", "..");+let dir = "";+let runDir = "";+let mock: MockUbicloud | null = null;++afterEach(() => {+ mock?.stop();+ rmSync(dir, { recursive: true, force: true });+ if (runDir) rmSync(runDir, { recursive: true, force: true });+});++describe("ci:ubicloud teardown", () => {+ it("SIGTERM mid-provision destroys every VM it asked for, including creates still in flight", async () => {+ dir = mkdtempSync(join(tmpdir(), "ci-ubicloud-teardown-"));+ const api = (mock = startMockUbicloud({ createDelayMs: (name) => (/-ci01/.test(name) ? 0 : 4000) }));+ const proc = Bun.spawn(["bun", "run", "scripts/ci-ubicloud.ts", "--vms", "3", "--lanes", "gitleaks"], {+ cwd: ROOT,+ env: {+ PATH: process.env.PATH ?? "/usr/bin:/bin",+ HOME: dir,+ UBICLOUD_API_KEY: "test-token",+ UBICLOUD_API_URL: api.url,+ UBI_RUNNER_STATE: join(dir, "state"),+ UBI_OWNER: "probe",+ UBI_POLL_SECONDS: "0.2",+ },+ stdout: "pipe",+ stderr: "pipe",+ });+ const stdout = new Response(proc.stdout).text();+ const stderr = new Response(proc.stderr).text();+ await waitForEvent(api, /^created \S+-ci01/, 120_000);+ await waitForEvent(api, /^create-start \S+-ci03/, 10_000);+ expect(api.events.some((e) => /^created \S+-ci0[23]/.test(e))).toBe(false);+ proc.kill("SIGTERM");+ expect(await proc.exited).toBe(130);+ const out = await stdout;+ runDir = /logs in (\S+)/.exec(out)?.[1] ?? "";++ const requested = readFileSync(join(runDir, "vms.txt"), "utf8").trim().split("\n").map((l) => l.split(" ")[0]!);+ expect(requested).toHaveLength(3);+ for (const name of requested) {+ expect(name).toMatch(/^ubirun-probe-\d{10}-ci0[123][0-9a-f]{4}$/);+ expect(api.events).toContain(`created ${name}`);+ expect(api.events).toContain(`removed ${name}`);+ }+ expect(api.vms.size).toBe(0);+ expect(out).toContain("teardown confirmed 3 VM(s) gone");+ expect(await stderr).not.toContain("WARNING");+ }, 180_000);+});diff --git a/test/scripts/ubi-runner.test.ts b/test/scripts/ubi-runner.test.tsnew file mode 100644index 0000000000..6e0cc937bc--- /dev/null+++ b/test/scripts/ubi-runner.test.ts@@ -0,0 +1,168 @@+// ubi-runner.test.ts — scripts/ubicloud/ubi-runner.sh against a mock Ubicloud+// API: owner-tagged VM names, the stale sweep (off unless UBI_GC_HOURS is set,+// and never another owner's VMs), list --mine / usage, and teardown that waits+// out in-flight creates when `up` gets SIGTERM or SIGKILL mid-provision.++import { afterEach, beforeEach, describe, expect, it } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";+import { startMockUbicloud, waitForEvent, type MockUbicloud, type MockUbicloudOptions } from "../helpers/mock-ubicloud-api.ts";++const RUNNER = resolve(import.meta.dir, "..", "..", "scripts/ubicloud/ubi-runner.sh");+const NOW = Math.floor(Date.now() / 1000);+const OLD = NOW - 5 * 3600;++let dir = "";+let mock: MockUbicloud | null = null;++beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), "ubi-runner-test-"));+});+afterEach(() => {+ mock?.stop();+ mock = null;+ rmSync(dir, { recursive: true, force: true });+});++function serve(opts: MockUbicloudOptions = {}): MockUbicloud {+ mock = startMockUbicloud(opts);+ return mock;+}++function env(extra: Record<string, string> = {}): Record<string, string> {+ return {+ PATH: process.env.PATH ?? "/usr/bin:/bin",+ HOME: dir,+ UBICLOUD_API_KEY: "test-token",+ UBICLOUD_API_URL: mock?.url ?? "http://127.0.0.1:9",+ UBI_RUNNER_STATE: join(dir, "state"),+ UBI_POLL_SECONDS: "0.2",+ ...extra,+ };+}++function spawnRunner(args: string[], extra: Record<string, string> = {}) {+ return Bun.spawn(["bash", RUNNER, ...args], { env: env(extra), stdout: "pipe", stderr: "pipe" });+}++async function run(args: string[], extra: Record<string, string> = {}) {+ const proc = spawnRunner(args, extra);+ const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);+ return { stdout, stderr, code };+}++describe("owner tag", () => {+ it("sanitizes UBI_OWNER to at most 12 lowercase letters and digits, starting with a letter", async () => {+ expect((await run(["owner"], { UBI_OWNER: "GBRA-41 lane!" })).stdout.trim()).toBe("gbra41lane");+ expect((await run(["owner"], { UBI_OWNER: "12345" })).stdout.trim()).toBe("u12345");+ expect((await run(["owner"], { UBI_OWNER: "abcdefghijklmnopq" })).stdout.trim()).toBe("abcdefghijkl");+ expect((await run(["owner"], { UBI_OWNER: "--" })).code).toBe(1);+ });++ it("defaults to a stable per-machine id", async () => {+ const first = (await run(["owner"])).stdout.trim();+ expect(first).toMatch(/^m[0-9a-f]{8}$/);+ expect((await run(["owner"])).stdout.trim()).toBe(first);+ });+});++describe("teardown waits for in-flight creates", () => {+ it("SIGTERM during the create request: the create finishes, then the VM is destroyed and confirmed gone", async () => {+ const api = serve({ createDelayMs: () => 1500 });+ const proc = spawnRunner(["up"], { UBI_OWNER: "t1" });+ const started = await waitForEvent(api, /^create-start /);+ const name = started.split(" ")[1]!;+ expect(name).toMatch(/^ubirun-t1-\d{10}-[0-9a-f]{8}$/);+ proc.kill("SIGTERM");+ expect(await proc.exited).toBe(130);+ expect(api.events).toEqual([`create-start ${name}`, `created ${name}`, `destroy ${name}`, `removed ${name}`]);+ expect(api.vms.size).toBe(0);+ });++ it("SIGTERM while the VM is still provisioning destroys it before exiting", async () => {+ const api = serve();+ const proc = spawnRunner(["up"], { UBI_OWNER: "t1" });+ const name = (await waitForEvent(api, /^created /)).split(" ")[1]!;+ proc.kill("SIGTERM");+ expect(await proc.exited).toBe(130);+ expect(api.events.slice(-2)).toEqual([`destroy ${name}`, `removed ${name}`]);+ expect(api.vms.size).toBe(0);+ });++ it("after SIGKILL mid-create, down waits for the create to land and destroys the VM", async () => {+ const api = serve({ createDelayMs: () => 1500 });+ const proc = spawnRunner(["up"], { UBI_OWNER: "t1" });+ const name = (await waitForEvent(api, /^create-start /)).split(" ")[1]!;+ proc.kill("SIGKILL");+ await proc.exited;+ expect(api.vms.size).toBe(0);+ const down = await run(["down", name], { UBI_CREATE_GRACE: "20" });+ expect(down.code).toBe(0);+ expect(api.events).toEqual([`create-start ${name}`, `created ${name}`, `destroy ${name}`, `removed ${name}`]);+ expect(api.vms.size).toBe(0);+ });++ it("a refused create needs no grace wait, and down of an unknown name reports it gone", async () => {+ const api = serve({ rejectCreates: true });+ const t0 = Date.now();+ const up = await run(["up"], { UBI_OWNER: "t1", UBI_CREATE_GRACE: "60" });+ expect(up.code).toBe(1);+ expect(up.stderr).toContain("create failed");+ expect(Date.now() - t0).toBeLessThan(15_000);+ const down = await run(["down", `ubirun-t1-${NOW}-deadbeef`, "-l", "eu-central-h1"]);+ expect(down.code).toBe(0);+ expect(down.stderr).toContain("never existed or already destroyed");+ expect(api.vms.size).toBe(0);+ });+});++describe("stale sweep and ownership", () => {+ const seed = [+ { name: `ubirun-t1-${OLD}-aaaaaaaa`, size: "standard-16" },+ { name: `ubirun-t1-${NOW}-bbbbbbbb`, size: "standard-8" },+ { name: `ubirun-other-${OLD}-cccccccc`, size: "standard-16" },+ { name: `ubirun-${OLD}-dddddddd`, size: "standard-4" },+ { name: "prod-db", size: "standard-2" },+ ];++ it("up never sweeps when UBI_GC_HOURS is unset", async () => {+ const api = serve({ seed });+ const proc = spawnRunner(["up"], { UBI_OWNER: "t1" });+ const name = (await waitForEvent(api, /^created /)).split(" ")[1]!;+ proc.kill("SIGTERM");+ await proc.exited;+ expect(api.events.filter((e) => e.startsWith("destroy "))).toEqual([`destroy ${name}`]);+ expect(api.vms.size).toBe(seed.length);+ });++ it("with UBI_GC_HOURS set, up sweeps only the caller's own stale VMs", async () => {+ const api = serve({ seed });+ const proc = spawnRunner(["up"], { UBI_OWNER: "t1", UBI_GC_HOURS: "1" });+ const name = (await waitForEvent(api, /^created /)).split(" ")[1]!;+ proc.kill("SIGTERM");+ await proc.exited;+ expect(api.events.filter((e) => e.startsWith("destroy "))).toEqual([`destroy ubirun-t1-${OLD}-aaaaaaaa`, `destroy ${name}`]);+ expect([...api.vms.keys()].sort()).toEqual(seed.slice(1).map((s) => s.name).sort());+ });++ it("gc HOURS destroys only the caller's VMs older than HOURS and requires HOURS", async () => {+ const api = serve({ seed });+ expect((await run(["gc"], { UBI_OWNER: "t1" })).code).toBe(1);+ const gc = await run(["gc", "1"], { UBI_OWNER: "t1" });+ expect(gc.code).toBe(0);+ expect(api.events).toEqual([`destroy ubirun-t1-${OLD}-aaaaaaaa`, `removed ubirun-t1-${OLD}-aaaaaaaa`]);+ });++ it("list --mine shows only the caller's VMs; usage sums vCPUs by owner", async () => {+ serve({ seed });+ const mine = await run(["list", "--mine"], { UBI_OWNER: "t1" });+ expect(mine.stdout.trim().split("\n").map((l) => l.split(/\s+/)[1])).toEqual([`ubirun-t1-${OLD}-aaaaaaaa`, `ubirun-t1-${NOW}-bbbbbbbb`]);+ const usage = (await run(["usage"], { UBI_OWNER: "t1" })).stdout;+ expect(usage).toMatch(/^t1\s+2\s+24\s+\(you\)$/m);+ expect(usage).toMatch(/^other\s+1\s+16$/m);+ expect(usage).toMatch(/^\(untagged\)\s+1\s+4$/m);+ expect(usage).toMatch(/^\(other\)\s+1\s+2$/m);+ expect(usage).toMatch(/^total\s+5\s+46$/m);+ });+});