# Remote Cluster Management for vg-coder-cli Tunnel

**Status**: Plan, ready for implementation by an AI agent or human developer.
**Repo**: `vg-coder-cli` (separate submodule, NOT `medgraph`).
**Target version**: `2.0.84` (current: `2.0.83`).
**Scope estimate**: 7–8 hours single implementer.

---

## 1. Problem statement

A tunnel deployment of `vg-coder-cli` is a remote machine running:

- 1 vg-coder-cli server (Node, port `6868`) — exposed via Cloudflare quick
  tunnel to the operator's local machine. Hosts REST APIs and a socket.io
  hub.
- 13 Chrome profiles each running the `VetGo Pro` extension (`vetgo-auto/
  chrome/`). Each profile's extension service worker holds a persistent
  socket.io connection to the server. Each profile's AI Studio tab is a
  "worker" used to run Best-of-N LLM tasks (Layer 1 monograph builds).

**Observed failure modes (2026-05-13 audit):**

1. **Socket disconnect without reconnect** — Service Worker eviction +
   Cloudflare tunnel timeout interact badly. socket.io's auto-reconnect
   only fires when the SW is awake; if the SW is evicted *during* a
   network blip, it may not fire any event to wake itself up. Result:
   `/api/launchers` reports `email: null` for that chromeId (the SW
   reconnects on next alarm tick but the email rebind handshake doesn't
   replay), or the launcher disappears entirely.

2. **No remote restart path** — to recover, the operator currently has to
   noVNC into the tunnel machine, manually right-click "Reload" on each
   broken extension, or `kill -9` Chrome and relaunch. No REST API
   exists for any of this.

3. **CLI upgrades require SSH** — bumping `vg-coder-cli` from `2.0.83`
   to `2.0.84` needs an SSH session: `npm install -g vg-coder-cli@latest
   && pm2 restart vg-coder`. There is no `/api/system/update-cli`
   endpoint.

4. **No visibility** — operator does not know whether 13 profiles are
   healthy, or only 2, without manually inspecting `/api/launchers`
   payload + reading `lastSeen` timestamps.

**This plan** delivers a small, focused set of HTTP endpoints + extension
event handlers so the operator can fully manage the tunnel from their
local machine: update CLI, restart Chrome, reload extensions, run
arbitrary diagnostic commands, all via REST.

---

## 2. Context the implementer needs

### 2.1 Repo layout (vg-coder-cli)

```
vg-coder-cli/
├── package.json                  # name=vg-coder-cli, version=2.0.83
├── bin/
│   ├── vg.js                     # CLI entry (Commander.js)
│   └── vg-coder.js               # alias
├── src/server/
│   ├── api-server.js             # Express app — 56 routes today
│   ├── task-queue.js             # socket.io hub, launcher registry
│   ├── task-store.js
│   ├── terminal-manager.js       # PTY for /api/execute
│   └── server-log.js             # ring buffer queryable via /api/server/logs
└── vetgo-auto/chrome/
    ├── manifest.json             # MV3, name=VetGo Pro, version=1.0.0
    ├── src/launcher.ts           # service worker, socket.io client
    ├── src/background.ts         # extension entry point
    └── dist/                     # compiled JS (loaded as unpacked extension)
```

### 2.2 Existing patterns to follow

**Server-side endpoint pattern** (`api-server.js`):

```javascript
this.app.post('/api/launcher/some-action', async (req, res) => {
    try {
        const body = req.body || {};
        const opts = launcherOpts(body) || (body.all ? { all: true } : {});
        const timeoutMs = Math.min(Math.max(parseInt(body.timeoutMs, 10) || 10_000, 1_000), 30_000);
        const result = await taskQueue.requestLauncher(
            'launcher:some_event', { ...body }, opts, timeoutMs
        );
        res.json(result);
    } catch (e) { res.status(launcherErr(e)).json({ error: e.message }); }
});
```

`launcherOpts(body, query)` resolves `chromeId` → `workerLabel` → `all`
in that precedence. `launcherErr(e)` maps Error→HTTP-status. Both are
already defined in `api-server.js`.

**Extension event handler pattern** (`launcher.ts`):

```typescript
socket.on('launcher:some_event', async (payload, ack) => {
    try {
        const result = await doSomething(payload);
        ack?.({ ok: true, ...result });
    } catch (e) {
        ack?.({ ok: false, error: (e as Error).message });
    }
});
```

The `ack` callback returns the response to the server's `requestLauncher`
call. Always call `ack` exactly once.

**Bash exec pattern** (already used by `/api/execute`):

```javascript
const { BashExecutor } = require('./bash-executor'); // exact path TBD
const executor = new BashExecutor(req.workingDir);
const result = await executor.execute('npm install -g ...');
// result = { success: boolean, stdout: string, stderr: string, exitCode: number }
```

Look at `/api/execute` (`api-server.js:152`) for the canonical example.

### 2.3 Constraints

- **No authentication** — operator-only deployment, intranet trust.
  Don't add auth boilerplate; matches existing `/api/execute` design.
- **bash 3.2 compatible** for any shell snippets (mac default; CI runs
  on Linux but operator's dev box is macOS).
- **Manifest V3** for Chrome extension — service workers, NOT background
  pages. `chrome.runtime.reload()` is allowed. `eval()` is not.
- **Don't break existing routes** — 56 routes are in production use.
  Add new routes; don't refactor.
- **Restart-safety**: any endpoint that restarts the server itself
  (CLI update) must `res.send(...)` BEFORE forking the restart command,
  or the operator sees a hung HTTP call.

### 2.4 Known data shapes

`/api/launchers` returns:
```json
{
  "launchers": [
    {
      "id": "QT32GatIBwuCDxXKAAAD",        // socket.id
      "chromeId": "af8c47b2-...",
      "email": "petland.com.vn@gmail.com", // null = zombie
      "lastSeen": 1778586734485,           // epoch ms
      "cooldownUntil": 0,
      "cooldownRemainingMinutes": 0
    }
  ]
}
```

`/api/workers` returns similar shape with `status` field (`idle|busy|rate_limited|offline`).

---

## 3. Deliverables (in priority order)

### Phase 1 — Core remote control (must-have, ~2h)

#### Endpoint A: `POST /api/launcher/:chromeId/reload`

- Body: `{}` (chromeId comes from URL path)
- Server emits `launcher:reload` socket event to the matching extension
- Extension handler calls `chrome.runtime.reload()`
- 5-second ack timeout
- Returns `{ ok: true, chromeId, reloaded_at }` on success
- Returns `404 { error: "launcher_not_connected" }` if the chromeId
  has no live socket (operator can fall back to Endpoint B)

**Extension code** (add to `launcher.ts` around line 269 where
`launcher:debug` lives):

```typescript
socket.on('launcher:reload', async (_payload, ack) => {
  ack?.({ ok: true, scheduled_at: Date.now() });
  // Defer so the ack actually goes out before SW dies
  setTimeout(() => chrome.runtime.reload(), 100);
});
```

#### Endpoint B: `POST /api/system/restart-chrome`

- Body: `{ profiles?: string[] }` — defaults to all known profiles
- Implementation: shells out via `BashExecutor`. The shell command
  comes from a config file `~/.vg-coder/restart-chrome.sh` (operator
  supplies — script knows their actual profile paths and Chrome flags).
- The script MUST write a registry file `~/.vg-coder/profile-registry.json`
  mapping `chromeId ↔ user-data-dir ↔ cdp_port ↔ pid`. The server reads
  this for Endpoints F/G and to know which profile-dir to clean.
- Returns `{ ok: true, killed_pids: [...], launched: [...], registry_path }`
- If the config script doesn't exist, returns `400` with a hint to
  create it (sample provided in docs).

##### Why a user-supplied script

Every machine's Chrome launch flags differ (profile paths, debugging
ports, display env). Generating it in Node would be brittle.

##### Why a registry file (instead of asking the extension)

**Critical context for the implementer**: Chrome's extension API does
NOT expose the `user-data-dir` path. There is no
`chrome.runtime.getProfilePath()` or equivalent — this is a sandbox
boundary, not an oversight. We tried:

- `chrome.runtime.getPackageDirectoryEntry()` → extension's own folder, not user-data-dir
- `chrome.identity.getProfileUserInfo()` → returns Google account email, not filesystem
- `chrome.management.getSelf()` → extension metadata only

Therefore the extension cannot tell the server "I'm running in profile
at /Users/foo/profiles/profile-3". The launch script — which knows
because it set `--user-data-dir` itself — must record the mapping at
launch time.

The chromeId UUID lives in `chrome.storage.local` per profile (see
`launcher.ts:getChromeId`). The script reads it back via CDP after
launch and pairs it with the profile path it just used.

##### Sample restart-chrome.sh

Ship as `examples/restart-chrome.sh`. The version below produces the
registry the server needs:

```bash
#!/bin/bash
# ~/.vg-coder/restart-chrome.sh — operator-edited template.
# REQUIRED: must write profile-registry.json so the server can map
#           chromeId → user-data-dir → CDP port for Endpoints F & G.

set -e
PROFILES_ROOT="${PROFILES_ROOT:-$HOME/chrome-profiles}"
REGISTRY="$HOME/.vg-coder/profile-registry.json"
N_PROFILES="${N_PROFILES:-13}"
BASE_PORT="${BASE_PORT:-9222}"
CHROME_BIN="${CHROME_BIN:-/Applications/Google Chrome.app/Contents/MacOS/Google Chrome}"

mkdir -p "$(dirname "$REGISTRY")"
echo "[]" > "$REGISTRY"

# Kill existing Chrome instances. -9 is intentional — Chrome's graceful
# shutdown can take 30+ seconds and we want a clean state.
pkill -9 -f 'Google Chrome' || true
sleep 2

for i in $(seq 1 "$N_PROFILES"); do
  profile_dir="$PROFILES_ROOT/profile-$i"
  port=$((BASE_PORT + i - 1))

  mkdir -p "$profile_dir"
  "$CHROME_BIN" \
    --user-data-dir="$profile_dir" \
    --remote-debugging-port="$port" \
    --no-first-run \
    --disable-features=ChromeWhatsNewUI \
    "https://aistudio.google.com" \
    >/dev/null 2>&1 &
  pid=$!

  # Wait for extension service worker to wake and register chromeId.
  # ~5s is conservative; tune down once you've observed your env.
  sleep 5

  # Pull chromeId out of the extension's storage.local via CDP.
  # `find_extension_target.sh` (sibling helper) locates the SW target;
  # inlined here for brevity.
  ws_url="$(curl -sf "http://127.0.0.1:$port/json" \
    | jq -r '[.[] | select(.type=="service_worker") | .webSocketDebuggerUrl][0]')"
  if [ -z "$ws_url" ] || [ "$ws_url" = "null" ]; then
    echo "  WARN profile-$i: no SW target on port $port (extension not loaded yet?)"
    chrome_id=""
  else
    # Evaluate chrome.storage.local.get(['id']) on the SW. Use websocat
    # or a small node helper — websocat shown:
    chrome_id="$(echo "{\"id\":1,\"method\":\"Runtime.evaluate\",\"params\":{\"expression\":\"new Promise(r=>chrome.storage.local.get(['id'],x=>r(x.id)))\",\"awaitPromise\":true,\"returnByValue\":true}}" \
      | websocat -n1 "$ws_url" \
      | jq -r '.result.result.value // empty')"
  fi

  # Append entry to registry. jq handles file-locking-free append by
  # rewriting whole file; fine for N=13.
  jq --arg p "$profile_dir" \
     --argjson port "$port" \
     --argjson pid "$pid" \
     --arg cid "$chrome_id" \
     '. += [{profile_dir: $p, cdp_port: $port, pid: $pid, chromeId: $cid}]' \
     "$REGISTRY" > "$REGISTRY.tmp" && mv "$REGISTRY.tmp" "$REGISTRY"

  echo "  profile-$i pid=$pid port=$port chromeId=${chrome_id:-MISSING}"
done

echo "Launched $N_PROFILES profiles. Registry: $REGISTRY"
```

##### Registry schema

`~/.vg-coder/profile-registry.json`:

```json
[
  {
    "profile_dir": "/Users/foo/chrome-profiles/profile-1",
    "cdp_port": 9222,
    "pid": 12345,
    "chromeId": "af8c47b2-f15b-4e75-b51f-c6b79e2a08f8"
  },
  ...
]
```

Server reads on demand (not cached — operator may regenerate via
re-running restart-chrome). If `chromeId` is empty in some entries,
those profiles failed to register their extension at launch — log a
warning and skip them in Endpoint F lookups.

#### Endpoint C: `POST /api/system/update-cli`

- Body: `{ version?: string }` — default `latest`
- Runs `npm install -g vg-coder-cli@<version>` via `BashExecutor`
- After successful install, schedules a process restart via
  `setTimeout(() => process.exit(0), 500)`. Assumes `pm2`/`systemd`
  /equivalent will respawn. Document this assumption.
- Returns `{ ok: true, old_version: "2.0.83", new_version: "2.0.84",
  restart_scheduled_at: <epoch> }` BEFORE exiting.

**Critical**: send response first, then exit. Code pattern:

```javascript
this.app.post('/api/system/update-cli', async (req, res) => {
    const version = (req.body || {}).version || 'latest';
    const oldVersion = require('../../package.json').version;
    const executor = new BashExecutor(process.cwd());
    const result = await executor.execute(`npm install -g vg-coder-cli@${version}`);
    if (!result.success) {
        return res.status(500).json({ error: 'install_failed', stderr: result.stderr });
    }
    res.json({
        ok: true,
        old_version: oldVersion,
        new_version: version,
        restart_scheduled_at: Date.now()
    });
    setTimeout(() => process.exit(0), 500);
});
```

### Phase 2 — Visibility (~1.5h)

#### Endpoint D: `GET /api/system/health`

Returns aggregate cluster state:

```json
{
  "server_version": "2.0.83",
  "server_uptime_s": 12345,
  "launchers": {
    "total": 13,
    "email_bound": 11,
    "zombie": 2,
    "stale_5min": 1
  },
  "workers": {
    "total": 11,
    "idle": 8,
    "busy": 2,
    "rate_limited": 1
  },
  "chrome_processes": 13,
  "system": {
    "cpu_pct": 12.4,
    "mem_pct": 47.2,
    "disk_free_gb": 89.1
  }
}
```

Chrome process count comes from `pgrep -c 'Google Chrome'` or
`ps -ef | grep -c '[C]hrome'`. System stats: `os.loadavg()`,
`os.freemem()`, `fs.statSync('/').size` etc — node built-ins.

#### Endpoint E: `POST /api/launcher/reload-stale`

Server-side automation:
1. Read `/api/launchers` internally
2. Filter `lastSeen > 5*60*1000ms ago`
3. For each stale launcher, fire Endpoint A (`launcher:reload`)
4. Return `{ reloaded: [chromeId, ...], skipped: [chromeId, ...] }`

This is the "fix the cluster" one-liner the operator runs every few
hours.

### Phase 3 — Last-resort recovery (~3h)

#### Endpoint F: `POST /api/cdp/:chromeId/exec`

When the extension itself is broken (rare but happens), the operator
needs a path that bypasses it. Chrome remote debugging port (CDP)
provides this.

- Body: `{ method: "Runtime.evaluate" | "Input.dispatchMouseEvent" | ..., params: {...} }`
- Server reads `~/.vg-coder/profile-registry.json` (written by
  Endpoint B's restart script) to look up the `cdp_port` for the
  given `chromeId`
- Connects to `http://127.0.0.1:<cdp_port>/json` to enumerate targets,
  picks the Page target whose URL matches AI Studio
- Sends the CDP message via WebSocket, returns the result
- Use the `chrome-remote-interface` npm package (mature, MIT, ~3KB)
- Returns `404 { error: "chromeId_not_in_registry" }` if no entry
  for that chromeId — the operator needs to re-run restart-chrome
  to regenerate the registry

The registry's existence is what makes this endpoint possible.
Without it, the server has no way to know which port a chromeId is
listening on, because Chrome extensions can't tell us their
profile path or debugging port — see Endpoint B's "Why a registry
file" rationale.

#### Endpoint G: `POST /api/system/exec-script`

Run a named script from `~/.vg-coder/scripts/<name>.sh`. Not arbitrary
bash (mitigates accidental footgun); operator pre-stages scripts they
want to be able to fire remotely.

- Body: `{ name: "diagnose-network" | "tail-chrome-logs" | ..., args?: string[] }`
- Refuses if script path escapes the scripts directory (basic path
  traversal guard, even though no auth)
- Returns stdout/stderr/exitCode

---

## 4. Implementation steps (recommended order)

1. **Branch + read context** (15 min)
   - `cd vg-coder-cli && git checkout -b feat/remote-cluster-mgmt`
   - Read: `src/server/api-server.js` (existing patterns),
     `src/server/task-queue.js` (`requestLauncher` impl),
     `vetgo-auto/chrome/src/launcher.ts` (existing `launcher:*` handlers)

2. **Phase 1A: extension reload handler** (30 min)
   - Add `socket.on('launcher:reload', ...)` to `launcher.ts`
   - Add `POST /api/launcher/:chromeId/reload` to `api-server.js`
   - Test by hitting endpoint, watching `/api/launcher/logs` for SW
     restart

3. **Phase 1B: restart-chrome endpoint** (45 min)
   - Add `POST /api/system/restart-chrome` to `api-server.js`
   - Write `examples/restart-chrome.sh` template
   - Document the `~/.vg-coder/restart-chrome.sh` convention in
     `INTEGRATION.md`

4. **Phase 1C: CLI update endpoint** (30 min)
   - Add `POST /api/system/update-cli` (see code in §3)
   - Document the pm2/systemd assumption
   - Sample `pm2 ecosystem.config.js` in `examples/`

5. **Build + bump version + commit + npm publish** (15 min)
   - `cd vetgo-auto/chrome && npm run build`
   - Bump `package.json` to `2.0.84`
   - `git commit -m "feat: remote cluster management endpoints"`
   - `npm publish` (or document publish step for human)

6. **Phase 2: health + reload-stale** (1.5h)
   - Add `GET /api/system/health` collecting fields per §3
   - Add `POST /api/launcher/reload-stale` calling Endpoint A in a loop

7. **Phase 3: CDP exec + script runner** (3h)
   - `npm install chrome-remote-interface --save`
   - Implement profile-ports.json registry write in restart-chrome flow
   - Add `POST /api/cdp/:chromeId/exec` reading port from registry
   - Add `POST /api/system/exec-script` with path-traversal guard

8. **INTEGRATION.md updates** (30 min)
   - New section "Remote cluster management"
   - Document each endpoint, body/response shape, when to use
   - Reference operator scripts in `examples/`

9. **End-to-end test on tunnel** (1h) — see §5

---

## 5. Tests that must pass

These are **acceptance tests**, not unit tests. Run them on a real
tunnel deployment (operator-supplied URL, e.g.
`https://example.trycloudflare.com`).

### Test 1 — extension reload by chromeId

```bash
TUNNEL="https://example.trycloudflare.com"
CID="$(curl -s $TUNNEL/api/launchers | jq -r '.launchers[0].chromeId')"

# Note current socket id
SOCKET_BEFORE="$(curl -s $TUNNEL/api/launchers | jq -r ".launchers[] | select(.chromeId==\"$CID\") | .id")"

# Reload
curl -X POST -s "$TUNNEL/api/launcher/$CID/reload"

# Wait for extension to come back
sleep 8

# New socket id should differ from old
SOCKET_AFTER="$(curl -s $TUNNEL/api/launchers | jq -r ".launchers[] | select(.chromeId==\"$CID\") | .id")"
test "$SOCKET_BEFORE" != "$SOCKET_AFTER" || { echo "FAIL: socket id didn't change"; exit 1; }

# Email should be re-bound (proves register handshake replayed)
EMAIL="$(curl -s $TUNNEL/api/launchers | jq -r ".launchers[] | select(.chromeId==\"$CID\") | .email")"
test "$EMAIL" != "null" || { echo "FAIL: email rebind didn't happen"; exit 1; }

echo "PASS test 1"
```

### Test 2 — restart-chrome ends and respawns

```bash
# Save baseline
CHROME_COUNT_BEFORE="$(curl -s $TUNNEL/api/system/health | jq '.chrome_processes')"
test "$CHROME_COUNT_BEFORE" -ge 1 || { echo "FAIL: no Chrome running before test"; exit 1; }

curl -X POST -s "$TUNNEL/api/system/restart-chrome" | jq '.ok' | grep -q true \
    || { echo "FAIL: restart-chrome didn't return ok=true"; exit 1; }

# Chrome should be killed then respawned. Allow generous time.
sleep 30
CHROME_COUNT_AFTER="$(curl -s $TUNNEL/api/system/health | jq '.chrome_processes')"
test "$CHROME_COUNT_AFTER" -ge 1 || { echo "FAIL: Chrome didn't come back"; exit 1; }

# Launchers should reconnect within 60s
sleep 30
LAUNCHER_COUNT="$(curl -s $TUNNEL/api/launchers | jq '.launchers | map(select(.email != null)) | length')"
test "$LAUNCHER_COUNT" -ge 1 || { echo "FAIL: no launchers reconnected"; exit 1; }

echo "PASS test 2"
```

### Test 3 — CLI update endpoint sends response before exit

```bash
RESPONSE="$(curl -X POST -s -m 5 "$TUNNEL/api/system/update-cli" \
  -H 'Content-Type: application/json' -d '{"version":"2.0.83"}')"
# Reinstalls same version — should succeed without changing anything

echo "$RESPONSE" | jq '.ok' | grep -q true \
    || { echo "FAIL: update-cli didn't return ok=true"; exit 1; }

# Curl shouldn't have timed out (response came before process.exit)
echo "$RESPONSE" | jq -e '.restart_scheduled_at != null' >/dev/null \
    || { echo "FAIL: missing restart_scheduled_at"; exit 1; }

# Server should respawn within ~10s if pm2 is configured
sleep 15
curl -s --max-time 5 "$TUNNEL/api/system/health" | jq '.server_version' \
    || { echo "FAIL: server didn't come back after update-cli"; exit 1; }

echo "PASS test 3"
```

### Test 4 — health endpoint returns all fields

```bash
HEALTH="$(curl -s "$TUNNEL/api/system/health")"
for field in server_version server_uptime_s launchers workers chrome_processes system; do
    echo "$HEALTH" | jq -e ".$field != null" >/dev/null \
        || { echo "FAIL: missing field $field"; exit 1; }
done
echo "$HEALTH" | jq -e '.launchers.total >= 0' >/dev/null \
    || { echo "FAIL: launchers.total not a number"; exit 1; }
echo "PASS test 4"
```

### Test 5 — reload-stale only touches stale launchers

```bash
# Snapshot launcher set
ALL="$(curl -s $TUNNEL/api/launchers | jq -r '.launchers[].chromeId' | sort)"

# Find a launcher that's fresh (lastSeen <30s ago)
FRESH="$(curl -s $TUNNEL/api/launchers | jq -r '
  .launchers[] | select(.lastSeen > (now*1000 - 30000)) | .chromeId' | head -1)"
test -n "$FRESH" || { echo "SKIP: no fresh launcher to verify; need a recently-active profile"; exit 0; }

# Fire reload-stale
RESPONSE="$(curl -X POST -s "$TUNNEL/api/launcher/reload-stale")"

# Fresh launcher should NOT be in the reloaded list
echo "$RESPONSE" | jq -e ".reloaded | index(\"$FRESH\") == null" >/dev/null \
    || { echo "FAIL: reload-stale reloaded a fresh launcher ($FRESH)"; exit 1; }

echo "PASS test 5"
```

### Test 6 — CDP exec returns valid response (Phase 3 only)

```bash
# Assumes restart-chrome wrote profile-ports.json
CID="$(curl -s $TUNNEL/api/launchers | jq -r '.launchers[0].chromeId')"

RESPONSE="$(curl -X POST -s "$TUNNEL/api/cdp/$CID/exec" \
  -H 'Content-Type: application/json' \
  -d '{"method":"Runtime.evaluate","params":{"expression":"1+1","returnByValue":true}}')"

echo "$RESPONSE" | jq -e '.result.value == 2' >/dev/null \
    || { echo "FAIL: CDP eval didn't return 2"; exit 1; }
echo "PASS test 6"
```

### Test 7 — extension reload survives 5 consecutive cycles

Regression guard against the SW-eviction race condition.

```bash
CID="$(curl -s $TUNNEL/api/launchers | jq -r '.launchers[0].chromeId')"
for i in 1 2 3 4 5; do
    curl -X POST -s "$TUNNEL/api/launcher/$CID/reload" >/dev/null
    sleep 10
    EMAIL="$(curl -s $TUNNEL/api/launchers | jq -r ".launchers[] | select(.chromeId==\"$CID\") | .email")"
    test "$EMAIL" != "null" || { echo "FAIL: cycle $i email lost"; exit 1; }
done
echo "PASS test 7 (5/5 reload cycles healthy)"
```

---

## 6. Out of scope (don't do)

- **Authentication / authorization** — operator explicitly opted out.
- **Refactoring existing 56 routes** — additive only.
- **Replacing socket.io with raw WS** — works fine, no need.
- **Per-profile resource quotas / scheduler** — different problem.
- **Encrypted config files** — operator runs internal-only, not needed.
- **Cross-platform Chrome launch** — operator supplies their own
  `restart-chrome.sh`; the server doesn't try to guess.
- **Web UI for cluster management** — REST API only this round.

---

## 7. Deliverables checklist for the implementer

Done when:

- [ ] Endpoints A–G implemented and returning correct shapes
- [ ] Extension handlers for `launcher:reload` added and built
  (`vetgo-auto/chrome/dist/launcher.js` updated)
- [ ] `package.json` version bumped to `2.0.84`
- [ ] `examples/restart-chrome.sh` template shipped
- [ ] `examples/pm2-ecosystem.config.js` ships
- [ ] `INTEGRATION.md` has a new top-level section "Remote cluster
      management" covering each endpoint with body/response examples
- [ ] All 7 acceptance tests pass against a real tunnel
- [ ] One commit per phase; commit messages reference the specific
      endpoint letter (e.g., "feat(server): endpoint A — launcher reload")
- [ ] Final commit message includes the regression context: explain
      why the SW-eviction failure mode necessitates this

---

## 8. Open questions for the operator (raise before implementing if unsure)

1. Does the tunnel server use `pm2`, `systemd`, `nohup`, or something
   else for process supervision? Determines what
   `POST /api/system/update-cli` should assume.
2. Is `npm` installed at a path that doesn't need `sudo` for `-g`
   installs? If sudo is needed, the BashExecutor approach won't work
   without privilege escalation.
3. Are there >1 tunnel deployments to consider? This plan assumes a
   single tunnel; if there's a fleet, the operator likely wants the
   driver-side (medgraph) to call these endpoints in a loop.
4. Does the operator want self-healing watchdog (server-side timer
   that auto-fires reload-stale every 5 min)? Not in this plan, but
   trivial to add given Endpoint E exists.
