Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(autopilot): name each brain's autopilot job per brain on all four install targets (#5195)
garrytan45a12597300d
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.mdindex 0d8805f480..141a5c2a1e 100644--- a/docs/architecture/key-files/commands-1.md+++ b/docs/architecture/key-files/commands-1.md@@ -16,7 +16,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/auth.ts` — token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (`create --scopes read,write` narrows a token via the `scopes TEXT[]` column with mint-time validation — a typo'd scope refuses loudly, never silently denies or widens; `list` shows id + scopes columns with grandfathered rows rendered honestly; `revoke --id <uuid>` revokes exactly one row since names are not unique, and bulk revoke-by-name says when it hit several; `permissions set-takes-holders` MERGES into the permissions JSONB via `COALESCE(permissions,'{}'::jsonb) || $2::jsonb` — a whole-object replace would silently wipe the `source_id` federation grant), plus `gbrain auth register-client` and `gbrain auth revoke-client <client_id>` for OAuth 2.1 client lifecycle. `revoke-client` runs an atomic `DELETE...RETURNING` on `oauth_clients`; FK `ON DELETE CASCADE` on `oauth_tokens.client_id` and `oauth_codes.client_id` purges every active token + auth code in one transaction; `process.exit(1)` on no-such-client (idempotent). Legacy tokens stored as SHA-256 hashes in `access_tokens`; OAuth clients in `oauth_clients`; legacy tokens with no scopes grant grandfather to `read+write+admin` on the OAuth HTTP server (no migration); scoped tokens are honored at exactly their grant. Every SQL site routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` (and `executeRawJsonb` for the takes-holders `permissions` JSONB column) so `gbrain auth` works against PGLite; the takes-holders write goes through `executeRawJsonb(engine, sql, [name, hash], [{takes_holders:[...]}])` which round-trips with `jsonb_typeof = 'object'`. `register-client` accepts `--source <id>` (write authority, scalar), `--federated-read <S1,S2,...>` (read scope, array), and `--token-ttl <seconds>` (per-client access-token TTL persisted to `oauth_clients.token_ttl`, bounds `TOKEN_TTL_MIN_SECONDS`=60 to `TOKEN_TTL_MAX_SECONDS`=7,776,000/90d) and prints the resolved `Write source` + `Federated reads`; clients without a `source_id` backfill to `'default'` via migration v60. The registration core is the exported `registerScopedClient(sql, engine, name, parsed, opts)` — exit-free, print-free, injected-handle (engine-bound callers like `agent register` pass the dispatcher's engine; a second `withConfiguredSql` engine self-deadlocks PGLite's single-writer lock), returns a `RegisteredClient` data object and throws on failure; the thin CLI wrapper owns exit/print. Its printer `formatRegisterClientOutput` is a BYTE-PINNED contract (connect.ts's `defaultRegisterOAuthClient` regex-scrapes `Client ID:`/`Client Secret:` from it in production) — pinned by `test/auth-register-client-output-pin.test.ts`. `preflightOauthClientColumns(sql)` probes `information_schema.columns` for the optional columns (`token_ttl`, `surface`, `federated_read`, `source_id`, `deleted_at`) so statement shapes are decided BEFORE any transaction — Postgres/PGLite abort the whole tx on any statement error (25P02) and SqlQuery has no savepoint seam, so "catch 42703 and continue" inside a tx is impossible; skipped optional writes surface as `RegisteredClient.skipped` with an apply-migrations hint. `gbrain auth clients [--usage] [--days N] [--json]` lists clients with scopes, per-client surface, write source (`source_id`), and federated reads (`federated_read`) — one projection-widened SELECT with a degrade ladder for pre-migration brains (drops the newest columns first, never errors); `--usage` joins per-client op-call counts via `src/core/mcp-usage.ts`. The bare `gbrain auth create <name>` form (no `--takes-holders`) mints a token via the exported pure `parseAuthCreateArgs(rest)`. Pinned by `test/auth-create-args.test.ts` + `test/auth-register-client-args.test.ts`.- `src/commands/autopilot-pause.ts` — engine-free `gbrain autopilot pause [--reason <text>]` / `resume`: writes or removes the operator marker `autopilot-operator-paused` (`autopilotOperatorPauseMarkerPath` in `src/core/autopilot-paths.ts`, with `autopilotPaused()` and `autopilotPauseReason()`). The daemon loop and job workers honor it like the migration hold; `--install` (and so `gbrain upgrade`) clears only a leaked migration hold, and resume never clears a migration or restore hold. Test: `test/autopilot-operator-pause.test.ts`.-- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn with `--max-rss 2048` and soft `maxCrashes: 5`, preferring the current source/compiled CLI over PATH. The child worker performs private-queue recovery only after its driver/selected-child readiness and schema check; autopilot does not duplicate that recovery before spawn. A configuration-blocked child leaves the owning daemon alive and heartbeating but gates dispatch, worker restarts and engine work until explicit owner restart after repair. `--status --json` adds processing readiness, reason and runtime identities without replacing existing freshness/exit semantics; see [the owner-specific repair guide](../../guides/minions-fix.md). `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` lists `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`; a `provider_failure` result throws `formatDrainProviderFailure(result)` — batches/remaining plus the drain's sanitized `last_error` — so the dead-lettered job's `error_text` names the cause, e.g. a missing provider key); `src/core/config.ts` carries the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID; `src/core/autopilot-lock.ts` checks liveness and the process command before takeover. `looksLikeGbrainAutopilotCommand` recognizes quoted or unquoted `cli.ts` / `cli.js` / `cli.mjs` paths, including spaces and normalized Windows separators, so a live matching autopilot retains even an old lock. Synthetic command-line and lock-decision cases are pinned by `test/autopilot-lock.test.ts`; they are not native Windows process-probe validation. (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane: `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution). Once processing is configuration-blocked, `guardAutopilotEngine` refuses new engine calls (except disconnect), guards transaction callback engines, and rolls back a transaction whose callback finishes after the block; already committed work is not revoked. Pinned by `test/autopilot-transaction-fence.test.ts`.+- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn with `--max-rss 2048` and soft `maxCrashes: 5`, preferring the current source/compiled CLI over PATH. The child worker performs private-queue recovery only after its driver/selected-child readiness and schema check; autopilot does not duplicate that recovery before spawn. A configuration-blocked child leaves the owning daemon alive and heartbeating but gates dispatch, worker restarts and engine work until explicit owner restart after repair. `--status --json` adds processing readiness, reason and runtime identities without replacing existing freshness/exit semantics; see [the owner-specific repair guide](../../guides/minions-fix.md). `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` lists `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`; a `provider_failure` result throws `formatDrainProviderFailure(result)` — batches/remaining plus the drain's sanitized `last_error` — so the dead-lettered job's `error_text` names the cause, e.g. a missing provider key); `src/core/config.ts` carries the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID; `src/core/autopilot-lock.ts` checks liveness and the process command before takeover. `looksLikeGbrainAutopilotCommand` recognizes quoted or unquoted `cli.ts` / `cli.js` / `cli.mjs` paths, including spaces and normalized Windows separators, so a live matching autopilot retains even an old lock. Synthetic command-line and lock-decision cases are pinned by `test/autopilot-lock.test.ts`; they are not native Windows process-probe validation. (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane: `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution). Once processing is configuration-blocked, `guardAutopilotEngine` refuses new engine calls (except disconnect), guards transaction callback engines, and rolls back a transaction whose callback finishes after the block; already committed work is not revoked. Pinned by `test/autopilot-transaction-fence.test.ts`. #5195: install, status and uninstall act on one brain's job, named by `resolveAutopilotJob()` in `src/core/autopilot-paths.ts` (default brain: the shared names; any other brain: `<name>-<suffix>` from the random install id in `<brain>/.gbrain/autopilot-install-id`, with move/copy semantics); crontab lines carry `# gbrain-autopilot:<suffix>`; every log sink writes under the brain's home; a pre-#5195 shared job that runs this brain is replaced on install and reported by `--status` as `needs_reinstall: legacy_shared_job`; replacing or removing a job whose wrapper runs another live brain is refused (`autopilot_job_owned_by_other_brain`). Pinned by `test/autopilot-install-id.test.ts` and `test/e2e/autopilot-multi-brain.serial.test.ts`.Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers launchd/systemd/cron/container install and reload paths, the wrapper script with its env-file lane and exec guard, status and the self-upgrade channel. `runAutopilot` is a mode table (`AUTOPILOT_MODES`: --install, --uninstall, --status, --pause/--resume; first match wins) that otherwise lazily imports the daemon: `autopilot-daemon.ts` (`runAutopilotDaemon`: boot, lock, managed worker, shutdown and the tick loop over an explicit `AutopilotDaemonState`; steps `probeDatabaseOrReconnect`, `probeNoWorkerPeer`, `runInlineCycle`, `adaptiveInterval`), `autopilot-dispatch.ts` (`dispatchAutopilotTick`: freshness syncs, extract_atoms auto-drain, remediation plan, full-cycle fan-out or targeted submits) and `autopilot-probes.ts` (nightly quality and conversation-parser probes). No injectable single-tick function exists yet (TODOS: testable autopilot tick), so the wiring guards read these modules as source.- `src/commands/backup.ts` — trusted local `gbrain backup status|check`: status may reuse a recent warning; check forces a bounded remote readback sweep. Enabled missing/locked/degraded evidence does not return an all-clear. Quiet and disabled modes retain explicit zero-exit behavior. JSON separates configured repos from fresh verified recoverable repos and describes committed-file-only recovery. Remote MCP doctor never invokes this local Git path; see `docs/operations/backup-check.md` and `test/backup-cli.serial.test.ts`.diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.mdindex ac37ae5a4f..fa452c619e 100644--- a/docs/guides/live-sync.md+++ b/docs/guides/live-sync.md@@ -261,6 +261,38 @@ vars — incident-time escape hatches, not everyday knobs.reads only the filesystem — no database connection — so it keeps workingduring the exact outages it exists to diagnose.+## Several brains on one host++Each brain gets its own autopilot job. The default brain (`~/.gbrain`, that+is `GBRAIN_HOME` unset or set to your home directory) keeps the shared names:+launchd label `com.gbrain.autopilot`, systemd unit `gbrain-autopilot.service`,+start script `~/.gbrain/start-autopilot.sh`, and an unmarked crontab line.+Any other brain gets names with a suffix: `com.gbrain.autopilot.<suffix>`,+`gbrain-autopilot-<suffix>.service`, `<brain>/.gbrain/start-autopilot-<suffix>.sh`,+and a crontab line ending in `# gbrain-autopilot:<suffix>`. The suffix is the+first 8 hex characters of a random id that `--install` records in+`<brain>/.gbrain/autopilot-install-id`. Every brain logs to its own+`<brain>/.gbrain/autopilot.log`.++`gbrain autopilot --status [--json]` prints the brain's job name, suffix,+install-id path, wrapper path and log path (`job` in `--json`). `--status`+and `--uninstall` act only on that brain's job.++- **Moving a brain** keeps its id and job. `--status` reports+ `needs_reinstall: wrapper_missing` until you run+ `GBRAIN_HOME=<new parent> gbrain autopilot --install`, which repoints the+ same job.+- **Copying a brain** (`cp -r`) gives the copy a new id on its first+ `--install`, so the original brain keeps its job.+- **Upgrading from an older gbrain**: a non-default brain installed before+ per-brain names ran under the shared names. `--status` reports+ `needs_reinstall: legacy_shared_job`; `GBRAIN_HOME=<parent> gbrain autopilot --install`+ replaces that shared job with the brain's own job and says so.+- **`autopilot_job_owned_by_other_brain`**: installing the default brain+ refuses when the shared job still runs another brain. Run the printed+ `GBRAIN_HOME=<parent> gbrain autopilot --install` for that brain first, then+ install the default brain again.+---*Part of the [GBrain Skillpack](../GBRAIN_SKILLPACK.md).*diff --git a/docs/guides/minions-fix.md b/docs/guides/minions-fix.mdindex 658c62f57f..44e00697d5 100644--- a/docs/guides/minions-fix.md+++ b/docs/guides/minions-fix.md@@ -27,7 +27,10 @@ existing launch options throughout the repair.| Autopilot under user systemd | `gbrain autopilot --status --json`; `systemctl --user status gbrain-autopilot.service` | `systemctl --user stop gbrain-autopilot.service` | `systemctl --user start gbrain-autopilot.service` || Autopilot under launchd | `gbrain autopilot --status --json`; `launchctl print "gui/$(id -u)/com.gbrain.autopilot"` | `launchctl bootout "gui/$(id -u)/com.gbrain.autopilot"` | `launchctl bootstrap "gui/$(id -u)" "$HOME/Library/LaunchAgents/com.gbrain.autopilot.plist"` |-These are the default user-service names. If the installation uses a different+These are the default brain's user-service names. A brain under any other+`GBRAIN_HOME` uses its own suffixed names; `gbrain autopilot --status --json`+prints them under `job` ([several brains on one host](live-sync.md#several-brains-on-one-host)).+If the installation uses a differentservice definition, use its actual name and recorded launcher. For a foregroundautopilot or a container/cron owner, stop and restart that owner through itsexisting launcher; do not start a competing standalone supervisor. A timed-outdiff --git a/src/commands/autopilot.ts b/src/commands/autopilot.tsindex 2e33d2e717..388010b242 100644--- a/src/commands/autopilot.ts+++ b/src/commands/autopilot.ts@@ -55,7 +55,13 @@ import {autopilotPauseReason,autopilotDisableStrikesPath,autopilotLaunchdLabel,+ autopilotWrapperOwner,+ resolveAutopilotJob,+ DEFAULT_AUTOPILOT_LAUNCHD_LABEL,+ DEFAULT_AUTOPILOT_SYSTEMD_UNIT,+ type AutopilotJob,} from '../core/autopilot-paths.ts';+import { errorFor } from '../core/errors.ts';export { autopilotLockPath, autopilotDisabledMarkerPath, autopilotPausedMarkerPath, autopilotLaunchdLabel };export { relativeSourceLocalPathSkipWarning as relativeLocalPathSkipWarning };@@ -137,7 +143,7 @@ export function logError(phase: string, e: unknown) {const line = `[${ts}] [${phase}] ERROR: ${msg}`;console.error(line);try {- const logDir = join(process.env.HOME || '', '.gbrain');+ const logDir = gbrainHomePath();mkdirSync(logDir, { recursive: true });appendFileSync(join(logDir, 'autopilot.log'), line + '\n');} catch { /* best-effort */ }@@ -615,18 +621,86 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {// --- Install/Uninstall ----function plistPath(): string {- return join(process.env.HOME || '', 'Library', 'LaunchAgents', `${autopilotLaunchdLabel()}.plist`);+function plistPath(label: string): string {+ return join(process.env.HOME || '', 'Library', 'LaunchAgents', `${label}.plist`);}-function systemdUnitPath(): string {- return join(process.env.HOME || '', '.config', 'systemd', 'user', AUTOPILOT_SYSTEMD_UNIT);+function systemdUnitPath(unit: string = DEFAULT_AUTOPILOT_SYSTEMD_UNIT): string {+ return join(process.env.HOME || '', '.config', 'systemd', 'user', unit);}-function ephemeralStartScriptPath(): string {+/** The pre-#5195 shared start script, which every brain used to overwrite. */+function legacyStartScriptPath(): string {return join(process.env.HOME || '', '.gbrain', 'start-autopilot.sh');}+const shellQuote = (s: string) => `'${s.replace(/'/g, "'\\''")}'`;+const unshellQuote = (s: string) => s.replace(/'\\''/g, "'");++/** The wrapper a launchd plist runs (its first ProgramArguments entry). */+export function plistWrapperPath(plist: string): string | null {+ const m = /<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/.exec(plist);+ if (!m) return null;+ return m[1].replace(/"/g, '"').replace(/>/g, '>').replace(/</g, '<').replace(/&/g, '&');+}++/** The wrapper a systemd unit runs. */+export function unitWrapperPath(unit: string): string | null {+ return /^ExecStart=(.+)$/m.exec(unit)?.[1].trim() || null;+}++/** The autopilot wrapper a crontab line or start script names, if any. */+export function scriptWrapperPath(text: string): string | null {+ const quoted = /'((?:[^']|'\\'')*autopilot-run\.sh)'/.exec(text);+ if (quoted) return unshellQuote(quoted[1]);+ return /(\S*autopilot-run\.sh)/.exec(text)?.[1] ?? null;+}++/**+ * #5195: does this crontab line belong to this brain's job? A marked line+ * (`# gbrain-autopilot:<suffix>`) belongs to the brain with that suffix. An+ * unmarked line predates per-brain names: it belongs to the brain whose+ * wrapper it names, and to the default brain when it names none.+ */+export function cronLineBelongsToBrain(line: string, job: AutopilotJob): boolean {+ if (!crontabIndicatesAutopilotInstall(line)) return false;+ const marker = /#\s*gbrain-autopilot:([A-Za-z0-9]+)\s*$/.exec(line);+ if (marker) return job.suffix !== null && marker[1] === job.suffix;+ const wrapper = scriptWrapperPath(line);+ if (!wrapper) return job.kind === 'default';+ return autopilotWrapperOwner(wrapper, job.homeDir).owner === 'own';+}++/** `GBRAIN_HOME=<parent> gbrain autopilot <verb>` for the brain whose home is `brainHome`. */+function brainCommand(brainHome: string, verb: string): string {+ const parent = dirname(brainHome);+ const defaultHome = join(process.env.HOME || '', '.gbrain');+ return resolvePath(brainHome) === resolvePath(defaultHome)+ ? `gbrain autopilot ${verb}`+ : `GBRAIN_HOME=${shellQuote(parent)} gbrain autopilot ${verb}`;+}++/**+ * ENG-O11: before replacing a job, make sure its wrapper names this brain. A+ * job whose wrapper belongs to another live brain is that brain's supervision;+ * replacing it would silently stop it (the #5195 failure).+ */+function refuseForeignJob(jobName: string, wrapperPath: string | null, job: AutopilotJob): void {+ const owner = autopilotWrapperOwner(wrapperPath, job.homeDir);+ if (owner.owner !== 'other') return;+ throw errorFor({+ class: 'AutopilotJobOwnedByOtherBrain',+ code: 'autopilot_job_owned_by_other_brain',+ message: `The autopilot job ${jobName} runs the brain at ${owner.home}, not this brain at ${job.homeDir}.`,+ hint: `Give that brain its own job first: ${brainCommand(owner.home, '--install')}; then re-run: ${brainCommand(job.homeDir, '--install')}`,+ docs_url: 'docs/guides/live-sync.md#several-brains-on-one-host',+ });+}++function readIfExists(path: string): string | null {+ try { return readFileSync(path, 'utf-8'); } catch { return null; }+}+export type InstallTarget = 'macos' | 'linux-systemd' | 'ephemeral-container' | 'linux-cron';/**@@ -679,7 +753,7 @@ function detectOpenClaw(): { detected: boolean; bootstrapCandidates: string[] }/** systemd unit name. The launchd label lives in `autopilotLaunchdLabel()`* (core/autopilot-paths.ts) so installer, uninstaller, status, and the* wrapper's self-disable can never name different jobs. */-export const AUTOPILOT_SYSTEMD_UNIT = 'gbrain-autopilot.service';+export const AUTOPILOT_SYSTEMD_UNIT = DEFAULT_AUTOPILOT_SYSTEMD_UNIT;/**@@ -707,14 +781,14 @@ export const AUTOPILOT_SYSTEMD_UNIT = 'gbrain-autopilot.service';* Exported pure so tests can assert the emitted shape per target without* installing a daemon.*/-export function generateSelfDisableGuard(repoPath: string, target: InstallTarget): string {+export function generateSelfDisableGuard(repoPath: string, target: InstallTarget, job: AutopilotJob = resolveAutopilotJob()): string {const q = (s: string) => s.replace(/'/g, "'\\''");const marker = autopilotDisabledMarkerPath();const disableCmd =target === 'macos'- ? ` launchctl bootout "gui/$(id -u)/${autopilotLaunchdLabel()}" 2>/dev/null || true\n`+ ? ` launchctl bootout "gui/$(id -u)/${job.launchdLabel}" 2>/dev/null || true\n`: target === 'linux-systemd'- ? ` systemctl --user disable --now ${AUTOPILOT_SYSTEMD_UNIT} 2>/dev/null || true\n`+ ? ` systemctl --user disable --now ${job.systemdUnit} 2>/dev/null || true\n`: '';const strikes = autopilotDisableStrikesPath();return `# Self-disable if the captured checkout is gone (rename / relocation / deletion).@@ -772,7 +846,7 @@ const GBRAIN_ENV_TEMPLATE = `# gbrain daemon environment — sourced by autopilo# daemon's home from this file's own location.`;-export function writeWrapperScript(repoPath: string, target: InstallTarget): string {+export function writeWrapperScript(repoPath: string, target: InstallTarget, job: AutopilotJob = resolveAutopilotJob()): string {// gbrainHomePath, not raw $HOME: the daemon writes its lock/markers through// it and the status command reads through it, so a GBRAIN_HOME install must// keep its wrapper (and the start-script detection that looks for it) in@@ -855,7 +929,7 @@ export function writeWrapperScript(repoPath: string, target: InstallTarget): str# or which init file the OS loaded.export PATH=${runtimePathPrefix}"$HOME/.bun/bin:$PATH"${process.env.GBRAIN_HOME ? `# Baked at install: the supervisor does not pass the installer's env, and\n# without this the daemon would read/write a different home than the\n# install that configured it.\nexport GBRAIN_HOME='${(process.env.GBRAIN_HOME).replace(/'/g, "'\\''")}'\n` : ''}-${generateSelfDisableGuard(repoPath, target)}# #3696: daemon cwd = the repo, so any legacy RELATIVE sources.local_path /+${generateSelfDisableGuard(repoPath, target, job)}# #3696: daemon cwd = the repo, so any legacy RELATIVE sources.local_path /# sync.repo_path row resolves against it instead of a phantom path under the# supervisor's cwd. Done HERE — after the guard has proven the repo exists —# and NOT via launchd's plist WorkingDirectory: launchd chdir()s before exec,@@ -917,7 +991,20 @@ async function installDaemon(engine: BrainEngine, args: string[]) {const injectBootstrap = args.includes('--inject-bootstrap');const noInject = args.includes('--no-inject');- const wrapperPath = writeWrapperScript(repoPath, target);+ // #5195: every name this brain's job uses (minting the install id on a+ // non-default brain's first install), and a refusal before anything is+ // written when the job under that name runs another live brain.+ const job = resolveAutopilotJob({ mint: true });+ try {+ if (target === 'macos') refuseForeignJob(job.launchdLabel, plistWrapperPath(readIfExists(plistPath(job.launchdLabel)) ?? ''), job);+ if (target === 'linux-systemd') refuseForeignJob(job.systemdUnit, unitWrapperPath(readIfExists(systemdUnitPath(job.systemdUnit)) ?? ''), job);+ if (target === 'ephemeral-container') refuseForeignJob(job.startScriptPath, scriptWrapperPath(readIfExists(job.startScriptPath) ?? ''), job);+ } catch (e) {+ console.error(e instanceof Error ? e.message : String(e));+ process.exit(1);+ }++ const wrapperPath = writeWrapperScript(repoPath, target, job);// #2608: tell the operator about the deterministic key channel — launchd/// systemd don't inherit the login shell env, and rc-file interactive guards// routinely swallow exports, so "it works in my terminal" keys often never@@ -936,16 +1023,16 @@ async function installDaemon(engine: BrainEngine, args: string[]) {switch (target) {case 'macos':- installLaunchd(wrapperPath, home, repoPath);+ installLaunchd(wrapperPath, home, repoPath, job);break;case 'linux-systemd':- installSystemd(wrapperPath, repoPath);+ installSystemd(wrapperPath, repoPath, job);break;case 'ephemeral-container':- installEphemeralContainer(wrapperPath, home, repoPath, { injectBootstrap, noInject });+ installEphemeralContainer(wrapperPath, home, repoPath, { injectBootstrap, noInject }, job);break;case 'linux-cron':- installCrontab(wrapperPath, home);+ installCrontab(wrapperPath, home, job);break;default: {console.error(`Unknown --target "${forcedTarget}". Allowed: macos, linux-systemd, ephemeral-container, linux-cron.`);@@ -988,12 +1075,14 @@ export function pgliteDaemonGuardMessage(engineKind: string, force: boolean): st// proven it exists (writeWrapperScript), which is what makes legacy// RELATIVE sources.local_path / sync.repo_path rows resolve against the// repo instead of a phantom path.-export function generateLaunchdPlist(wrapperPath: string, home: string): string {+export function generateLaunchdPlist(wrapperPath: string, home: string, job?: AutopilotJob): string {+ const logPath = job?.logPath ?? `${home}/.gbrain/autopilot.log`;+ const errPath = job?.errPath ?? `${home}/.gbrain/autopilot.err`;return `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict>- <key>Label</key><string>${escapeXml(autopilotLaunchdLabel())}</string>+ <key>Label</key><string>${escapeXml(job?.launchdLabel ?? autopilotLaunchdLabel())}</string><key>ProgramArguments</key><array><string>${escapeXml(wrapperPath)}</string></array>@@ -1010,36 +1099,37 @@ export function generateLaunchdPlist(wrapperPath: string, home: string): stringfloor; launchd would have applied a default of 10s if unset.--><key>ThrottleInterval</key><integer>60</integer>- <key>StandardOutPath</key><string>${escapeXml(home)}/.gbrain/autopilot.log</string>- <key>StandardErrorPath</key><string>${escapeXml(home)}/.gbrain/autopilot.err</string>+ <key>StandardOutPath</key><string>${escapeXml(logPath)}</string>+ <key>StandardErrorPath</key><string>${escapeXml(errPath)}</string></dict></plist>`;}-function installLaunchd(wrapperPath: string, home: string, repoPath: string) {- const plist = generateLaunchdPlist(wrapperPath, home);+function installLaunchd(wrapperPath: string, home: string, repoPath: string, job: AutopilotJob) {+ const plist = generateLaunchdPlist(wrapperPath, home, job);try {const agentsDir = join(home, 'Library', 'LaunchAgents');mkdirSync(agentsDir, { recursive: true });- writeFileSync(plistPath(), plist, { mode: 0o644 });+ replaceLegacySharedJob(job, 'macos');+ writeFileSync(plistPath(job.launchdLabel), plist, { mode: 0o644 });// launchd rejects group/world-writable agent plists: bootstrap/load fails// with the opaque "Bootstrap failed: 5: Input/output error" and the login// scan skips the file silently. writeFileSync's mode only applies on// create — a reinstall over an existing plist keeps the old bits (a 0666// plist written under an umask-0 parent stays 0666 forever) — so// normalize unconditionally.- chmodSync(plistPath(), 0o644);+ chmodSync(plistPath(job.launchdLabel), 0o644);// Unload-before-load (same pattern as uninstall): bare `launchctl load`// on an already-loaded agent errors and aborted every reinstall — and a// running daemon must be relaunched anyway to pick up a regenerated// wrapper / env file (#2608: the boot warning tells users to re-run// --install to reload; this line is what makes that true on macOS).- execSync(`launchctl unload "${plistPath()}" 2>/dev/null || true`, { stdio: 'pipe' });- execSync(`launchctl load "${plistPath()}"`, { stdio: 'pipe' });- console.log(`Installed launchd service: ${autopilotLaunchdLabel()}`);+ execSync(`launchctl unload "${plistPath(job.launchdLabel)}" 2>/dev/null || true`, { stdio: 'pipe' });+ execSync(`launchctl load "${plistPath(job.launchdLabel)}"`, { stdio: 'pipe' });+ console.log(`Installed launchd service: ${job.launchdLabel}`);console.log(` Repo: ${repoPath}`);- console.log(` Log: ~/.gbrain/autopilot.log`);+ console.log(` Log: ${job.logPath}`);console.log(' Uninstall: gbrain autopilot --uninstall');} catch (e: unknown) {const msg = e instanceof Error ? e.message : String(e);@@ -1065,7 +1155,9 @@ function installLaunchd(wrapperPath: string, home: string, repoPath: string) {* Exported so the v0.42 migration can recognize the prior generated shape and* rewrite existing `on-failure` units in place.*/-export function generateSystemdUnit(wrapperPath: string): string {+export function generateSystemdUnit(wrapperPath: string, job?: AutopilotJob): string {+ const logPath = job && job.kind !== 'default' ? job.logPath : '%h/.gbrain/autopilot.log';+ const errPath = job && job.kind !== 'default' ? job.errPath : '%h/.gbrain/autopilot.err';return `[Unit]Description=GBrain AutopilotAfter=network-online.target@@ -1077,8 +1169,8 @@ Type=simpleExecStart=${wrapperPath}Restart=alwaysRestartSec=30-StandardOutput=append:%h/.gbrain/autopilot.log-StandardError=append:%h/.gbrain/autopilot.err+StandardOutput=append:${logPath}+StandardError=append:${errPath}[Install]WantedBy=default.target@@ -1141,27 +1233,28 @@ export function migrateSystemdUnitToRestartAlways(): { rewritten: boolean; reaso}}-function installSystemd(wrapperPath: string, repoPath: string) {- const unit = generateSystemdUnit(wrapperPath);+function installSystemd(wrapperPath: string, repoPath: string, job: AutopilotJob) {+ const unit = generateSystemdUnit(wrapperPath, job);try {- const unitPath = systemdUnitPath();+ const unitPath = systemdUnitPath(job.systemdUnit);mkdirSync(join(process.env.HOME || '', '.config', 'systemd', 'user'), { recursive: true });+ replaceLegacySharedJob(job, 'linux-systemd');writeFileSync(unitPath, unit, { mode: 0o644 });// Same umask-0 hardening as the launchd path (systemd warns on// world-writable units); mode only applies on create, so normalize.chmodSync(unitPath, 0o644);execSync('systemctl --user daemon-reload', { stdio: 'pipe', timeout: 10_000 });- execSync(`systemctl --user enable --now ${AUTOPILOT_SYSTEMD_UNIT}`, { stdio: 'pipe', timeout: 15_000 });+ execSync(`systemctl --user enable --now ${job.systemdUnit}`, { stdio: 'pipe', timeout: 15_000 });// enable --now does NOT restart an already-active unit, so a reinstall// over a running daemon would keep the old process (and its stale env)// alive indefinitely (#2608: the boot warning tells users to re-run// --install to reload; this line is what makes that true on systemd).// try-restart only bounces a running unit — a fresh install just started// above is restarted at worst, never left stopped.- execSync(`systemctl --user try-restart ${AUTOPILOT_SYSTEMD_UNIT}`, { stdio: 'pipe', timeout: 15_000 });- console.log(`Installed systemd user service: ${AUTOPILOT_SYSTEMD_UNIT}`);+ execSync(`systemctl --user try-restart ${job.systemdUnit}`, { stdio: 'pipe', timeout: 15_000 });+ console.log(`Installed systemd user service: ${job.systemdUnit}`);console.log(` Repo: ${repoPath}`);- console.log(' Log: ~/.gbrain/autopilot.log');+ console.log(` Log: ${job.logPath}`);console.log(' Uninstall: gbrain autopilot --uninstall');} catch (e: unknown) {console.error(`Failed to install systemd unit: ${e instanceof Error ? e.message : e}`);@@ -1175,18 +1268,20 @@ function installEphemeralContainer(home: string,repoPath: string,opts: { injectBootstrap: boolean; noInject: boolean },+ job: AutopilotJob,) {// Write a start script the agent's bootstrap can source on every container start.- const safeWrapperPath = wrapperPath.replace(/'/g, "'\\''");+ const pidPath = join(job.homeDir, 'autopilot.pid');const script = `#!/bin/bash# Auto-generated by gbrain autopilot --install (ephemeral-container target)# Ephemeral filesystems lose crontab on every deploy; source this from# your agent's bootstrap instead.-nohup '${safeWrapperPath}' > ~/.gbrain/autopilot.log 2>&1 &-echo \$! > ~/.gbrain/autopilot.pid+nohup ${shellQuote(wrapperPath)} > ${shellQuote(job.logPath)} 2>&1 &+echo \$! > ${shellQuote(pidPath)}`;- const scriptPath = ephemeralStartScriptPath();- mkdirSync(join(home, '.gbrain'), { recursive: true });+ const scriptPath = job.startScriptPath;+ mkdirSync(job.homeDir, { recursive: true });+ replaceLegacySharedJob(job, 'ephemeral-container');writeFileSync(scriptPath, script, { mode: 0o755 });console.log('Ephemeral container detected (Render / Railway / Fly / Docker).');@@ -1196,7 +1291,7 @@ echo \$! > ~/.gbrain/autopilot.pid// from it — that process keeps its old environment until the container// restarts. Never auto-kill; say how (#2608, same honesty as the cron path).console.log(' An already-running autopilot keeps its old environment until the container');- console.log(' restarts (or: kill $(cat ~/.gbrain/autopilot.pid), then re-run the start script).');+ console.log(` restarts (or: kill $(cat ${shellQuote(pidPath)}), then re-run the start script).`);console.log('');console.log('Crontab is unreliable here (wiped on deploy). Add ONE LINE to your');console.log('agent bootstrap to launch autopilot on every start:');@@ -1225,8 +1320,8 @@ echo \$! > ~/.gbrain/autopilot.pidfor (const candidate of bootstrapCandidates) {try {const existing = readFileSync(candidate, 'utf-8');- const marker = '# gbrain:autopilot v0.11.0';- if (existing.includes(marker)) {+ const marker = BOOTSTRAP_MARKER;+ if (existing.includes(`${marker}\nbash ${scriptPath}`)) {console.log(` [skip] ${candidate} already has the gbrain marker`);continue;}@@ -1245,13 +1340,23 @@ echo \$! > ~/.gbrain/autopilot.pidconsole.log(' Uninstall: gbrain autopilot --uninstall');}-function installCrontab(wrapperPath: string, home: string) {+function installCrontab(wrapperPath: string, home: string, job: AutopilotJob) {// Linux/WSL without systemd — crontab runs the wrapper every 5 minutes.- const safeWrapperPath = wrapperPath.replace(/'/g, "'\\''");- const cronLine = `*/5 * * * * '${safeWrapperPath}' >> '${home.replace(/'/g, "'\\''")}/.gbrain/autopilot.log' 2>&1`;+ // #5195: a non-default brain's line carries its marker; the default brain's+ // line is unchanged.+ const cronLine = `*/5 * * * * ${shellQuote(wrapperPath)} >> ${shellQuote(job.logPath)} 2>&1${job.cronMarker ? ` ${job.cronMarker}` : ''}`;try {- const existing = execSync('crontab -l 2>/dev/null || true', { encoding: 'utf-8' });- if (existing.includes('gbrain autopilot') || existing.includes('autopilot-run.sh')) {+ let existing = execSync('crontab -l 2>/dev/null || true', { encoding: 'utf-8' });+ // A line of this brain is stale when it predates the brain's marker (a+ // pre-#5195 shared line) or runs a wrapper that is not this brain's+ // current one (the brain moved): either is replaced, never duplicated.+ const ownLines = existing.split('\n').filter(l => cronLineBelongsToBrain(l, job));+ const staleLines = ownLines.filter(l =>+ (job.cronMarker !== null && !l.includes(job.cronMarker)) || (scriptWrapperPath(l) !== null && scriptWrapperPath(l) !== wrapperPath));+ if (staleLines.length > 0) {+ existing = existing.split('\n').filter(l => !staleLines.includes(l)).join('\n');+ console.log(`Replacing ${staleLines.length} crontab line(s) that ran this brain from an older install with its current line.`);+ } else if (ownLines.length > 0) {console.log('Crontab entry already exists. Remove with: gbrain autopilot --uninstall');// The wrapper (and env template) were regenerated above, but cron// cannot reload a loop that is already running — it keeps its old@@ -1263,7 +1368,8 @@ function installCrontab(wrapperPath: string, home: string) {return;}// Use a temp file instead of echo pipe to avoid shell escaping issues (#1)- const tmpFile = join(home, '.gbrain', 'crontab.tmp');+ const tmpFile = join(job.homeDir, 'crontab.tmp');+ mkdirSync(job.homeDir, { recursive: true });writeFileSync(tmpFile, existing.trimEnd() + '\n' + cronLine + '\n');execSync(`crontab '${tmpFile.replace(/'/g, "'\\''")}'`, { stdio: 'pipe' });try { unlinkSync(tmpFile); } catch { /* best-effort */ }@@ -1293,11 +1399,92 @@ export function runAutopilotStatus(args: string[]): void {showStatus(args.includes('--json'), Number.isFinite(rawInterval) && rawInterval > 0 ? rawInterval : 300);}+const BOOTSTRAP_MARKER = '# gbrain:autopilot v0.11.0';++/**+ * Remove the bootstrap lines that launch `scriptPath` (the marker line and the+ * `bash <script>` line after it) from every OpenClaw bootstrap candidate.+ * Another brain's injected lines name its own script and are left alone.+ */+function stripBootstrapLines(scriptPath: string): number {+ let removed = 0;+ try {+ const { bootstrapCandidates } = detectOpenClaw();+ for (const candidate of bootstrapCandidates) {+ try {+ const content = readFileSync(candidate, 'utf-8');+ if (!content.includes(`${BOOTSTRAP_MARKER}\nbash ${scriptPath}`)) continue;+ const lines = content.split('\n');+ const cleaned: string[] = [];+ for (let i = 0; i < lines.length; i++) {+ if (lines[i].includes(BOOTSTRAP_MARKER) && lines[i + 1] === `bash ${scriptPath}`) {+ // Skip this marker line AND the next line (the bash start-script call).+ i++;+ continue;+ }+ cleaned.push(lines[i]);+ }+ // Backup before edit+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');+ writeFileSync(`${candidate}.bak.${stamp}`, content);+ writeFileSync(candidate, cleaned.join('\n'));+ console.log(`Removed bootstrap marker from: ${candidate}`);+ removed++;+ } catch (e) {+ console.error(` [warn] bootstrap ${candidate}: ${e instanceof Error ? e.message : e}`);+ }+ }+ } catch { /* OpenClaw detection best-effort */ }+ return removed;+}++/**+ * #5195: a non-default brain installed by an older gbrain ran under the shared+ * job name. Installing it again on the same target removes that shared job —+ * only when its wrapper names this brain — before the brain's own job is+ * written, and says so. Crontab lines are handled by installCrontab.+ */+function replaceLegacySharedJob(job: AutopilotJob, target: InstallTarget): void {+ if (job.kind === 'default') return;+ const own = (wrapper: string | null) => autopilotWrapperOwner(wrapper, job.homeDir).owner === 'own';+ if (target === 'macos') {+ const legacyLabel = autopilotLaunchdLabel(null);+ const path = plistPath(legacyLabel);+ if (legacyLabel === job.launchdLabel || !own(plistWrapperPath(readIfExists(path) ?? ''))) return;+ execSync(`launchctl unload "${path}" 2>/dev/null || true`, { stdio: 'pipe' });+ unlinkSync(path);+ console.log(`Replaced the shared launchd job ${legacyLabel}, which ran this brain, with ${job.launchdLabel}.`);+ } else if (target === 'linux-systemd') {+ const path = systemdUnitPath(DEFAULT_AUTOPILOT_SYSTEMD_UNIT);+ if (!own(unitWrapperPath(readIfExists(path) ?? ''))) return;+ execSync(`systemctl --user disable --now ${DEFAULT_AUTOPILOT_SYSTEMD_UNIT} 2>/dev/null || true`, { stdio: 'pipe', timeout: 10_000 });+ unlinkSync(path);+ console.log(`Replaced the shared systemd unit ${DEFAULT_AUTOPILOT_SYSTEMD_UNIT}, which ran this brain, with ${job.systemdUnit}.`);+ } else if (target === 'ephemeral-container') {+ const path = legacyStartScriptPath();+ if (path === job.startScriptPath || !own(scriptWrapperPath(readIfExists(path) ?? ''))) return;+ unlinkSync(path);+ stripBootstrapLines(path);+ console.log(`Replaced the shared start script ${path}, which ran this brain, with ${job.startScriptPath}.`);+ console.log(` Update any bootstrap line that runs \`bash ${path}\` to run \`bash ${job.startScriptPath}\`.`);+ }+}+export function uninstallDaemon() {- const home = process.env.HOME || '';- // Same resolution as writeWrapperScript — a GBRAIN_HOME install must- // uninstall the wrapper it actually wrote, not a sibling under raw $HOME.- const wrapperPath = join(gbrainHomePath(), 'autopilot-run.sh');+ // #5195: only this brain's job is removed — its own named job (checked to+ // run this brain's wrapper before removal), plus, for a non-default brain,+ // a pre-#5195 shared-name job whose wrapper names this brain. A shared job+ // that runs another live brain is left alone and named.+ const job = resolveAutopilotJob();+ const wrapperPath = job.wrapperPath;+ const ownsDefinition = (name: string, wrapper: string | null): boolean => {+ const owner = autopilotWrapperOwner(wrapper, job.homeDir);+ if (owner.owner !== 'other') return true;+ console.log(`Left ${name} in place: it runs the brain at ${owner.home}. To remove it: ${brainCommand(owner.home, '--uninstall')}`);+ return false;+ };+ const legacyOnly = (wrapper: string | null) => autopilotWrapperOwner(wrapper, job.homeDir).owner === 'own';+ const assigned = job.kind !== 'unassigned';// Always try all four targets — the user might have run `--install` under// one target earlier and moved hosts (e.g. macOS laptop → Linux server).@@ -1306,11 +1493,18 @@ export function uninstallDaemon() {let removed = 0;// macOS launchd- if (existsSync(plistPath())) {+ const labels: Array<{ label: string; legacy: boolean }> = [];+ if (assigned) labels.push({ label: job.launchdLabel, legacy: false });+ if (job.kind !== 'default' && autopilotLaunchdLabel(null) !== job.launchdLabel) labels.push({ label: autopilotLaunchdLabel(null), legacy: true });+ for (const { label, legacy } of labels) {+ const path = plistPath(label);+ if (!existsSync(path)) continue;+ const wrapper = plistWrapperPath(readIfExists(path) ?? '');+ if (legacy ? !legacyOnly(wrapper) : !ownsDefinition(label, wrapper)) continue;try {- execSync(`launchctl unload "${plistPath()}" 2>/dev/null || true`, { stdio: 'pipe' });- unlinkSync(plistPath());- console.log(`Removed launchd service: ${autopilotLaunchdLabel()}`);+ execSync(`launchctl unload "${path}" 2>/dev/null || true`, { stdio: 'pipe' });+ unlinkSync(path);+ console.log(`Removed launchd service: ${label}`);removed++;} catch (e) {console.error(` [warn] launchd: ${e instanceof Error ? e.message : e}`);@@ -1318,12 +1512,19 @@ export function uninstallDaemon() {}// Linux systemd user unit- if (existsSync(systemdUnitPath())) {+ const units: Array<{ unit: string; legacy: boolean }> = [];+ if (assigned) units.push({ unit: job.systemdUnit, legacy: false });+ if (job.kind !== 'default') units.push({ unit: DEFAULT_AUTOPILOT_SYSTEMD_UNIT, legacy: true });+ for (const { unit, legacy } of units) {+ const path = systemdUnitPath(unit);+ if (!existsSync(path)) continue;+ const wrapper = unitWrapperPath(readIfExists(path) ?? '');+ if (legacy ? !legacyOnly(wrapper) : !ownsDefinition(unit, wrapper)) continue;try {- execSync(`systemctl --user disable --now ${AUTOPILOT_SYSTEMD_UNIT} 2>/dev/null || true`, { stdio: 'pipe', timeout: 10_000 });- unlinkSync(systemdUnitPath());+ execSync(`systemctl --user disable --now ${unit} 2>/dev/null || true`, { stdio: 'pipe', timeout: 10_000 });+ unlinkSync(path);try { execSync('systemctl --user daemon-reload', { stdio: 'pipe', timeout: 5_000 }); } catch { /* best-effort */ }- console.log('Removed systemd user service: gbrain-autopilot.service');+ console.log(`Removed systemd user service: ${unit}`);removed++;} catch (e) {console.error(` [warn] systemd: ${e instanceof Error ? e.message : e}`);@@ -1331,55 +1532,34 @@ export function uninstallDaemon() {}// Ephemeral container start script + bootstrap marker injection- if (existsSync(ephemeralStartScriptPath())) {+ const scripts: Array<{ path: string; legacy: boolean }> = [];+ if (assigned) scripts.push({ path: job.startScriptPath, legacy: false });+ if (job.kind !== 'default') scripts.push({ path: legacyStartScriptPath(), legacy: true });+ for (const { path, legacy } of scripts) {+ if (!existsSync(path)) continue;+ const wrapper = scriptWrapperPath(readIfExists(path) ?? '');+ if (legacy ? !legacyOnly(wrapper) : !ownsDefinition(path, wrapper)) continue;try {- unlinkSync(ephemeralStartScriptPath());- console.log('Removed ephemeral start script: ~/.gbrain/start-autopilot.sh');+ unlinkSync(path);+ console.log(`Removed ephemeral start script: ${path}`);removed++;} catch (e) {console.error(` [warn] start script: ${e instanceof Error ? e.message : e}`);}+ // Remove marker-lines from any OpenClaw bootstrap we previously injected.+ removed += stripBootstrapLines(path);}- // Remove marker-line from any OpenClaw bootstrap we previously injected.- try {- const { bootstrapCandidates } = detectOpenClaw();- for (const candidate of bootstrapCandidates) {- try {- const content = readFileSync(candidate, 'utf-8');- if (!content.includes('# gbrain:autopilot v0.11.0')) continue;- const lines = content.split('\n');- const cleaned: string[] = [];- for (let i = 0; i < lines.length; i++) {- if (lines[i].includes('# gbrain:autopilot v0.11.0')) {- // Skip this marker line AND the next line (the bash start-script call).- i++;- continue;- }- cleaned.push(lines[i]);- }- // Backup before edit- const stamp = new Date().toISOString().replace(/[:.]/g, '-');- writeFileSync(`${candidate}.bak.${stamp}`, content);- writeFileSync(candidate, cleaned.join('\n'));- console.log(`Removed bootstrap marker from: ${candidate}`);- removed++;- } catch (e) {- console.error(` [warn] bootstrap ${candidate}: ${e instanceof Error ? e.message : e}`);- }- }- } catch { /* OpenClaw detection best-effort */ }// Linux crontab (don't gate on platform — the user may have run `--install// --target linux-cron` on a different machine that now has the crontab).try {const existing = execSync('crontab -l 2>/dev/null || true', { encoding: 'utf-8' });- if (existing.includes('gbrain autopilot') || existing.includes('autopilot-run.sh')) {- const filtered = existing.split('\n').filter(l =>- !l.includes('gbrain autopilot') && !l.includes('autopilot-run.sh'),- ).join('\n');- const tmpFile = join(home, '.gbrain', 'crontab.tmp');- mkdirSync(join(home, '.gbrain'), { recursive: true });- writeFileSync(tmpFile, filtered);+ const lines = existing.split('\n');+ const filtered = lines.filter(l => !cronLineBelongsToBrain(l, job));+ if (filtered.length !== lines.length) {+ const tmpFile = join(job.homeDir, 'crontab.tmp');+ mkdirSync(job.homeDir, { recursive: true });+ writeFileSync(tmpFile, filtered.join('\n'));execSync(`crontab '${tmpFile.replace(/'/g, "'\\''")}' 2>/dev/null || true`, { stdio: 'pipe' });try { unlinkSync(tmpFile); } catch { /* best-effort */ }console.log('Removed crontab entry for gbrain autopilot');@@ -1397,7 +1577,7 @@ export function uninstallDaemon() {}if (removed === 0) {- console.log('No autopilot install found on this host. Nothing to uninstall.');+ console.log('No autopilot install found for this brain. Nothing to uninstall.');}// A deliberate uninstall ends the disabled/paused story: without this, a@@ -1506,25 +1686,65 @@ export function classifyAutopilotStatus(input: {};}+interface InstalledJob {+ target: InstallTarget;+ /** launchd label, systemd unit, start-script path, or the crontab marker. */+ name: string;+ wrapperPath: string | null;+ /** A pre-#5195 shared-name job that runs this non-default brain. */+ legacy: boolean;+}+/**- * Which supervisor, if any, currently holds an autopilot install.+ * Which supervisor, if any, currently holds THIS brain's autopilot job (#5195).** Checks every target `installDaemon` can produce. The prior version grepped* crontab ONLY on non-darwin, so systemd-user and ephemeral-container installs* read as "not installed" — cosmetic while status always exited 0, but a hard- * false failure once the exit code became load-bearing.+ * false failure once the exit code became load-bearing. A shared job whose+ * wrapper runs another live brain is reported separately, never as this+ * brain's install.*/-function detectInstalledTarget(): InstallTarget | null {- if (process.platform === 'darwin' && existsSync(plistPath())) return 'macos';- if (existsSync(systemdUnitPath())) return 'linux-systemd';- if (existsSync(join(gbrainHomePath(), 'start-autopilot.sh'))) return 'ephemeral-container';- try {- const crontab = execSync('crontab -l 2>/dev/null || true', { encoding: 'utf-8' });- if (crontabIndicatesAutopilotInstall(crontab)) {- return 'linux-cron';+function detectInstalledJob(job: AutopilotJob): { installed: InstalledJob | null; foreign: { name: string; home: string } | null } {+ let foreign: { name: string; home: string } | null = null;+ const assigned = job.kind !== 'unassigned';+ const consider = (target: InstallTarget, name: string, text: string | null, wrapperOf: (t: string) => string | null, legacy: boolean): InstalledJob | null => {+ if (text === null) return null;+ const wrapperPath = wrapperOf(text);+ const owner = autopilotWrapperOwner(wrapperPath, job.homeDir);+ if (legacy) return owner.owner === 'own' ? { target, name, wrapperPath, legacy } : null;+ if (owner.owner === 'other') {+ foreign ??= { name, home: owner.home };+ return null;+ }+ return { target, name, wrapperPath, legacy };+ };+ const candidates: Array<() => InstalledJob | null> = [];+ if (process.platform === 'darwin') {+ if (assigned) candidates.push(() => consider('macos', job.launchdLabel, readIfExists(plistPath(job.launchdLabel)), plistWrapperPath, false));+ if (job.kind !== 'default' && autopilotLaunchdLabel(null) !== job.launchdLabel) {+ candidates.push(() => consider('macos', autopilotLaunchdLabel(null), readIfExists(plistPath(autopilotLaunchdLabel(null))), plistWrapperPath, true));}- } catch { /* no crontab */ }- return null;+ }+ if (assigned) candidates.push(() => consider('linux-systemd', job.systemdUnit, readIfExists(systemdUnitPath(job.systemdUnit)), unitWrapperPath, false));+ if (job.kind !== 'default') candidates.push(() => consider('linux-systemd', DEFAULT_AUTOPILOT_SYSTEMD_UNIT, readIfExists(systemdUnitPath(DEFAULT_AUTOPILOT_SYSTEMD_UNIT)), unitWrapperPath, true));+ if (assigned) candidates.push(() => consider('ephemeral-container', job.startScriptPath, readIfExists(job.startScriptPath), scriptWrapperPath, false));+ if (job.kind !== 'default') candidates.push(() => consider('ephemeral-container', legacyStartScriptPath(), readIfExists(legacyStartScriptPath()), scriptWrapperPath, true));+ candidates.push(() => {+ try {+ const crontab = execSync('crontab -l 2>/dev/null || true', { encoding: 'utf-8' });+ if (!crontabIndicatesAutopilotInstall(crontab)) return null;+ const line = crontab.split('\n').find(l => cronLineBelongsToBrain(l, job));+ if (!line) return null;+ const legacy = job.cronMarker !== null && !line.includes(job.cronMarker);+ return { target: 'linux-cron', name: job.cronMarker ?? 'crontab entry', wrapperPath: scriptWrapperPath(line), legacy };+ } catch { return null; /* no crontab */ }+ });+ for (const candidate of candidates) {+ const installed = candidate();+ if (installed) return { installed, foreign };+ }+ return { installed: null, foreign };}/**@@ -1547,16 +1767,15 @@ function showStatus(json: boolean, intervalSeconds: number) {// gbrainHomePath, not raw HOME: the daemon writes its lock through// gbrainHomePath() (#1226), so a GBRAIN_HOME install had status reading one// directory while the daemon wrote another — a permanent false "stale".- const home = gbrainHomePath();+ // #5195: every log sink writes under the brain's own home, so the log is+ // read only there (a raw-$HOME fallback would show another brain's log).+ const job = resolveAutopilotJob();let lastLine = '';- for (const logPath of [join(home, 'autopilot.log'), join(process.env.HOME || '', '.gbrain', 'autopilot.log')]) {- try {- const content = readFileSync(logPath, 'utf-8');- const lines = content.trim().split('\n');- lastLine = lines[lines.length - 1] || '';- break;- } catch { /* try the next home; supervisor log redirects bake raw $HOME */ }- }+ try {+ const content = readFileSync(job.logPath, 'utf-8');+ const lines = content.trim().split('\n');+ lastLine = lines[lines.length - 1] || '';+ } catch { /* no log yet */ }let disabledReason: string | null = null;try {@@ -1571,7 +1790,28 @@ function showStatus(json: boolean, intervalSeconds: number) {heartbeatAgeSeconds = Math.max(0, Math.floor((Date.now() - mtimeMs) / 1000));} catch { /* never ran, or already cleaned up */ }- const installTarget = detectInstalledTarget();+ const { installed, foreign } = detectInstalledJob(job);+ const installTarget = installed?.target ?? null;+ const wrapperMissing = installed?.wrapperPath ? !existsSync(installed.wrapperPath) : false;+ const needsReinstall = installed?.legacy+ ? 'legacy_shared_job'+ : wrapperMissing ? 'wrapper_missing' : null;+ const jobReport = {+ kind: job.kind,+ suffix: job.suffix,+ launchd_label: job.kind === 'unassigned' ? null : job.launchdLabel,+ systemd_unit: job.kind === 'unassigned' ? null : job.systemdUnit,+ start_script: job.kind === 'unassigned' ? null : job.startScriptPath,+ cron_marker: job.cronMarker,+ install_id_path: job.installIdPath,+ wrapper_path: job.wrapperPath,+ log_path: job.logPath,+ installed_definition: installed+ ? { target: installed.target, name: installed.name, wrapper_path: installed.wrapperPath, wrapper_exists: !wrapperMissing, legacy_shared_name: installed.legacy }+ : null,+ needs_reinstall: needsReinstall,+ shared_job_of_other_brain: foreign,+ };const report = classifyAutopilotStatus({installed: installTarget !== null,installTarget,@@ -1584,7 +1824,7 @@ function showStatus(json: boolean, intervalSeconds: number) {const processing = readAutopilotProcessingStatus();if (json) {- console.log(JSON.stringify({ ...report, ...processing }));+ console.log(JSON.stringify({ ...report, ...processing, job: jobReport }));} else {switch (report.state) {case 'not_installed':@@ -1622,6 +1862,17 @@ function showStatus(json: boolean, intervalSeconds: number) {console.log(`Stage: ${processing.processing_stage}${processing.retry_at ? `; next retry ${processing.retry_at}` : ''}`);if (processing.processing_state === 'configuration_blocked') console.log('Repair the worker and selected child installation, then explicitly restart autopilot.');}+ const jobName = installed?.name ?? (job.kind === 'unassigned' ? null : `${job.launchdLabel} (launchd) / ${job.systemdUnit} (systemd)`);+ if (jobName) console.log(`Job: ${jobName}${job.suffix ? ` (suffix ${job.suffix})` : ''}`);+ if (job.installIdPath) console.log(`Install id: ${job.installIdPath}`);+ console.log(`Wrapper: ${installed?.wrapperPath ?? job.wrapperPath}`);+ console.log(`Log: ${job.logPath}`);+ if (needsReinstall === 'legacy_shared_job') {+ console.log(` This brain runs under the shared job ${installed!.name} from an older gbrain. Give it its own job: ${brainCommand(job.homeDir, '--install')}`);+ } else if (needsReinstall === 'wrapper_missing') {+ console.log(` The job runs ${installed!.wrapperPath}, which no longer exists (the brain moved?). Reinstall: ${brainCommand(job.homeDir, '--install')}`);+ }+ if (foreign) console.log(` ${foreign.name} runs the brain at ${foreign.home}, not this one.`);if (lastLine) console.log(`Last log: ${lastLine}`);}diff --git a/src/core/autopilot-paths.ts b/src/core/autopilot-paths.tsindex 035d90c635..7c327b5177 100644--- a/src/core/autopilot-paths.ts+++ b/src/core/autopilot-paths.ts@@ -20,9 +20,11 @@* because that is where the daemon itself writes; a `GBRAIN_HOME` install* otherwise has readers looking in a different directory than the writer.*/-import { existsSync, readFileSync } from 'fs';-import { join } from 'path';-import { gbrainPath } from './config.ts';+import { existsSync, linkSync, mkdirSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from 'fs';+import { homedir } from 'os';+import { dirname, join, resolve } from 'path';+import { randomBytes } from 'crypto';+import { configDir, gbrainPath } from './config.ts';/*** The daemon's lock file. Its mtime IS the liveness heartbeat — the tick loop@@ -42,29 +44,211 @@ export function autopilotDisabledMarkerPath(): string {return join(gbrainPath(), 'autopilot-disabled');}+/** The pre-#5195 shared job names, still used by the default brain. */+export const DEFAULT_AUTOPILOT_LAUNCHD_LABEL = 'com.gbrain.autopilot';+export const DEFAULT_AUTOPILOT_SYSTEMD_UNIT = 'gbrain-autopilot.service';+/**- * The launchd job label / plist basename (systemd keeps its own unit name).+ * The launchd job label / plist basename. `suffix` names a non-default brain's+ * own job (#5195); the default brain keeps the shared label.** The env override is a TEST SEAM, not a user knob: it exists so the real-launchd* lifecycle e2e can load a genuinely unique job on a dev Mac without colliding* with — or tearing down — the machine's actual autopilot install. It is read at- * CALL time, so every invocation touching the same install (install, status,- * uninstall, the generated wrapper's self-disable) must run with the same value;- * a mismatched pair reports a false not-installed or misses the plist.+ * CALL time and wins over the per-brain suffix, so every invocation touching the+ * same install (install, status, uninstall, the generated wrapper's self-disable)+ * must run with the same value; a mismatched pair reports a false not-installed+ * or misses the plist.** The grammar check is load-bearing: the label reaches a plist FILENAME and a* double-quoted shell line inside the generated wrapper. `escapeXml` protects* only the XML site, so slashes, quotes, whitespace, `$`, backticks, and* dot-dot must be rejected here.*/-export function autopilotLaunchdLabel(): string {- const label = process.env.GBRAIN_AUTOPILOT_LABEL ?? 'com.gbrain.autopilot';+export function autopilotLaunchdLabel(suffix: string | null = null): string {+ const label = process.env.GBRAIN_AUTOPILOT_LABEL+ ?? (suffix ? `${DEFAULT_AUTOPILOT_LAUNCHD_LABEL}.${suffix}` : DEFAULT_AUTOPILOT_LAUNCHD_LABEL);if (!/^[A-Za-z0-9._-]+$/.test(label) || label.includes('..')) {throw new Error(`invalid GBRAIN_AUTOPILOT_LABEL: ${JSON.stringify(label)}`);}return label;}+/** realpath, or `resolve` for a directory that does not exist yet (ENG-O11). */+export function canonicalDir(path: string): string {+ try { return realpathSync(path); } catch { return resolve(path); }+}++/**+ * #5195: the default brain is the one at `~/.gbrain` (GBRAIN_HOME unset, or+ * pointing at the user's home). It keeps the shared job names so existing+ * installs need no migration; every other brain gets its own job.+ */+export function isDefaultBrainHome(): boolean {+ return canonicalDir(configDir()) === canonicalDir(join(homedir(), '.gbrain'));+}++/** Where a non-default brain records the random id its job names derive from. */+export function autopilotInstallIdPath(): string {+ return gbrainPath('autopilot-install-id');+}++interface InstallIdRecord { id: string; realpath: string; created_at: string }++function readInstallIdRecord(): InstallIdRecord | null {+ try {+ const rec = JSON.parse(readFileSync(autopilotInstallIdPath(), 'utf-8')) as Partial<InstallIdRecord>;+ if (typeof rec.id !== 'string' || !/^[0-9a-f]{8,64}$/.test(rec.id)) return null;+ if (typeof rec.realpath !== 'string' || !rec.realpath) return null;+ return { id: rec.id, realpath: rec.realpath, created_at: typeof rec.created_at === 'string' ? rec.created_at : '' };+ } catch {+ return null;+ }+}++/**+ * Read-only view of this brain's install id (T4, ENG-O11). The record names the+ * directory it was written for, because a copied brain carries the file along:+ * - same — recorded for this directory;+ * - moved — the recorded directory no longer exists, so this brain is it,+ * moved or renamed (the id, and the job, carry over);+ * - copied — the recorded directory still exists elsewhere, so this is a+ * copy that has not installed its own job yet;+ * - none — never installed.+ */+export function resolveAutopilotInstallId():+ | { relation: 'same' | 'moved'; id: string; recordedPath: string }+ | { relation: 'copied' | 'none'; id: null; recordedPath: string | null } {+ const rec = readInstallIdRecord();+ if (!rec) return { relation: 'none', id: null, recordedPath: null };+ if (rec.realpath === canonicalDir(configDir())) return { relation: 'same', id: rec.id, recordedPath: rec.realpath };+ if (!existsSync(rec.realpath)) return { relation: 'moved', id: rec.id, recordedPath: rec.realpath };+ return { relation: 'copied', id: null, recordedPath: rec.realpath };+}++function writeRecordExclusive(path: string, rec: InstallIdRecord): boolean {+ const tmp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;+ writeFileSync(tmp, JSON.stringify(rec) + '\n', { mode: 0o644 });+ try {+ linkSync(tmp, path);+ return true;+ } catch (e) {+ if ((e as NodeJS.ErrnoException).code === 'EEXIST') return false;+ try {+ writeFileSync(path, JSON.stringify(rec) + '\n', { flag: 'wx', mode: 0o644 });+ return true;+ } catch (e2) {+ if ((e2 as NodeJS.ErrnoException).code === 'EEXIST') return false;+ throw e2;+ }+ } finally {+ try { unlinkSync(tmp); } catch { /* already gone */ }+ }+}++function replaceRecord(path: string, rec: InstallIdRecord): void {+ const tmp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;+ writeFileSync(tmp, JSON.stringify(rec) + '\n', { mode: 0o644 });+ renameSync(tmp, path);+}++/**+ * The install id for this brain, minting or re-homing it as ENG-O11 describes.+ * The first record is created exclusively, so concurrent first installs agree on+ * one id; a move keeps the id and records the new directory; a copy mints its+ * own id so the original brain's job is never taken over.+ */+export function ensureAutopilotInstallId(): string {+ mkdirSync(configDir(), { recursive: true });+ const path = autopilotInstallIdPath();+ const here = canonicalDir(configDir());+ for (let attempt = 0; attempt < 5; attempt++) {+ const current = resolveAutopilotInstallId();+ if (current.relation === 'same') return current.id;+ if (current.relation === 'moved') {+ replaceRecord(path, { id: current.id, realpath: here, created_at: readInstallIdRecord()?.created_at || new Date().toISOString() });+ } else {+ const fresh = { id: randomBytes(16).toString('hex'), realpath: here, created_at: new Date().toISOString() };+ if (current.relation === 'none') {+ if (writeRecordExclusive(path, fresh)) return fresh.id;+ continue;+ }+ replaceRecord(path, fresh);+ }+ const settled = readInstallIdRecord();+ if (settled && settled.realpath === here) return settled.id;+ }+ throw new Error(`could not settle the autopilot install id at ${path}`);+}++/**+ * Every name one brain's autopilot job uses (#5195). The default brain keeps the+ * shared pre-#5195 names; any other brain gets `<name>-<suffix>` names, where the+ * suffix is the first 8 hex characters of its install id. `unassigned` is a+ * non-default brain that has no id yet (never installed, or an uninstalled+ * copy): it owns no named job, and its names are the shared ones only so the+ * pure generators have something to print.+ */+export interface AutopilotJob {+ kind: 'default' | 'suffixed' | 'unassigned';+ suffix: string | null;+ launchdLabel: string;+ systemdUnit: string;+ /** Ephemeral-container start script, under the brain's own home. */+ startScriptPath: string;+ /** Trailing crontab comment that marks this brain's line; null for the default brain. */+ cronMarker: string | null;+ wrapperPath: string;+ logPath: string;+ errPath: string;+ installIdPath: string | null;+ /** configDir() at resolution time. */+ homeDir: string;+}++export function resolveAutopilotJob(opts: { mint?: boolean } = {}): AutopilotJob {+ const homeDir = configDir();+ let kind: AutopilotJob['kind'] = 'default';+ let suffix: string | null = null;+ if (!isDefaultBrainHome()) {+ const id = opts.mint ? ensureAutopilotInstallId() : resolveAutopilotInstallId().id;+ suffix = id ? id.slice(0, 8) : null;+ kind = suffix ? 'suffixed' : 'unassigned';+ }+ return {+ kind,+ suffix,+ launchdLabel: autopilotLaunchdLabel(suffix),+ systemdUnit: suffix ? `gbrain-autopilot-${suffix}.service` : DEFAULT_AUTOPILOT_SYSTEMD_UNIT,+ startScriptPath: join(homeDir, suffix ? `start-autopilot-${suffix}.sh` : 'start-autopilot.sh'),+ cronMarker: suffix ? `# gbrain-autopilot:${suffix}` : null,+ wrapperPath: join(homeDir, 'autopilot-run.sh'),+ logPath: join(homeDir, 'autopilot.log'),+ errPath: join(homeDir, 'autopilot.err'),+ installIdPath: kind === 'default' ? null : autopilotInstallIdPath(),+ homeDir,+ };+}++/**+ * Who a job definition belongs to, judged by the wrapper path it runs (the+ * wrapper always lives at `<brain home>/autopilot-run.sh`):+ * - own — this brain's wrapper;+ * - dangling — a wrapper that no longer exists (a moved or deleted brain);+ * - other — a live wrapper of another brain (`home` is that brain's dir);+ * - unknown — the definition names no wrapper.+ */+export function autopilotWrapperOwner(+ wrapperPath: string | null,+ homeDir: string = configDir(),+): { owner: 'own' | 'dangling' | 'unknown' } | { owner: 'other'; home: string } {+ if (!wrapperPath) return { owner: 'unknown' };+ const dir = dirname(wrapperPath);+ if (canonicalDir(dir) === canonicalDir(homeDir)) return { owner: 'own' };+ if (!existsSync(wrapperPath)) return { owner: 'dangling' };+ return { owner: 'other', home: dir };+}+/*** Cooperative pause. While present the tick loop keeps heartbeating but does no* work. `gbrain migrate` uses it to quiesce the daemon for thediff --git a/test/autopilot-install-id.test.ts b/test/autopilot-install-id.test.tsnew file mode 100644index 0000000000..419582786c--- /dev/null+++ b/test/autopilot-install-id.test.ts@@ -0,0 +1,257 @@+/**+ * #5195 (T4, ENG-O11): every brain gets its own autopilot job name.+ *+ * The default brain (`~/.gbrain`) keeps the shared pre-#5195 names; any other+ * brain derives `<name>-<suffix>` names from a random install id recorded in+ * `<brain>/autopilot-install-id` as `{ id, realpath, created_at }`. These pin+ * the id's copy/move semantics, the concurrent first install, the default-brain+ * rule, the test-seam override, and crontab-line ownership. The install-target+ * behavior (all four targets, two brains, legacy replacement) is pinned end to+ * end in test/e2e/autopilot-multi-brain.serial.test.ts.+ */++import { describe, test, expect } from 'bun:test';+import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'fs';+import { spawn, spawnSync } from 'child_process';+import { join, resolve } from 'path';+import { tmpdir } from 'os';++import {+ type AutopilotJob,+ autopilotInstallIdPath,+ autopilotLaunchdLabel,+ autopilotWrapperOwner,+ ensureAutopilotInstallId,+ isDefaultBrainHome,+ resolveAutopilotInstallId,+ resolveAutopilotJob,+} from '../src/core/autopilot-paths.ts';+import { cronLineBelongsToBrain, generateSelfDisableGuard } from '../src/commands/autopilot.ts';+import { withEnv } from './helpers/with-env.ts';++const REPO = resolve(import.meta.dir, '..');++/**+ * Bun's os.homedir() is fixed at process start, so the default-brain rule+ * (which compares against homedir()/.gbrain, as configDir() does) is checked+ * in a child process started with the HOME under test.+ */+function jobIn(env: Record<string, string | undefined>, mint = false): AutopilotJob & { isDefault: boolean } {+ const script = `import { resolveAutopilotJob, isDefaultBrainHome } from ${JSON.stringify(join(REPO, 'src/core/autopilot-paths.ts'))};\n` ++ `process.stdout.write(JSON.stringify({ ...resolveAutopilotJob({ mint: ${mint} }), isDefault: isDefaultBrainHome() }));\n`;+ const childEnv: Record<string, string> = {};+ for (const [k, v] of Object.entries({ ...process.env, ...env })) if (v !== undefined) childEnv[k] = v;+ const r = spawnSync(process.execPath, ['-e', script], { env: childEnv, encoding: 'utf-8' });+ if (r.status !== 0) throw new Error(`child failed: ${r.stderr}`);+ return JSON.parse(r.stdout);+}++async function withHosts(fn: (root: string) => Promise<void> | void): Promise<void> {+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-5195-')));+ mkdirSync(join(root, 'home'), { recursive: true });+ try {+ await withEnv({ HOME: join(root, 'home'), GBRAIN_AUTOPILOT_LABEL: undefined }, () => fn(root));+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+}++describe('#5195 default brain keeps the shared names', () => {+ test('GBRAIN_HOME unset, or pointing at $HOME, is the default brain', async () => {+ await withHosts(async (root) => {+ const home = join(root, 'home');+ for (const gbrainHome of [undefined, home]) {+ const job = jobIn({ HOME: home, GBRAIN_HOME: gbrainHome }, true);+ expect(job.isDefault).toBe(true);+ expect(job.kind).toBe('default');+ expect(job.launchdLabel).toBe('com.gbrain.autopilot');+ expect(job.systemdUnit).toBe('gbrain-autopilot.service');+ expect(job.startScriptPath).toBe(join(home, '.gbrain', 'start-autopilot.sh'));+ expect(job.cronMarker).toBeNull();+ expect(job.logPath).toBe(join(home, '.gbrain', 'autopilot.log'));+ expect(job.installIdPath).toBeNull();+ expect(existsSync(join(home, '.gbrain', 'autopilot-install-id'))).toBe(false);+ }+ });+ });++ test('a symlinked GBRAIN_HOME that resolves to ~/.gbrain is still the default brain', async () => {+ await withHosts(async (root) => {+ mkdirSync(join(root, 'home', '.gbrain'), { recursive: true });+ const { symlinkSync } = await import('fs');+ symlinkSync(join(root, 'home'), join(root, 'alias'));+ expect(jobIn({ HOME: join(root, 'home'), GBRAIN_HOME: join(root, 'alias') }).isDefault).toBe(true);+ expect(jobIn({ HOME: join(root, 'home'), GBRAIN_HOME: join(root, 'other') }).isDefault).toBe(false);+ });+ });+});++describe('#5195 non-default brains get their own names from the install id', () => {+ test('two brains on one host get distinct suffixed names, all four targets', async () => {+ await withHosts(async (root) => {+ const a = await withEnv({ GBRAIN_HOME: join(root, 'brain-a') }, () => resolveAutopilotJob({ mint: true }));+ const b = await withEnv({ GBRAIN_HOME: join(root, 'brain-b') }, () => resolveAutopilotJob({ mint: true }));+ for (const job of [a, b]) {+ expect(job.kind).toBe('suffixed');+ expect(job.suffix).toMatch(/^[0-9a-f]{8}$/);+ expect(job.launchdLabel).toBe(`com.gbrain.autopilot.${job.suffix}`);+ expect(job.systemdUnit).toBe(`gbrain-autopilot-${job.suffix}.service`);+ expect(job.startScriptPath).toBe(join(job.homeDir, `start-autopilot-${job.suffix}.sh`));+ expect(job.cronMarker).toBe(`# gbrain-autopilot:${job.suffix}`);+ expect(job.logPath).toBe(join(job.homeDir, 'autopilot.log'));+ }+ expect(a.suffix).not.toBe(b.suffix);+ expect(a.launchdLabel).not.toBe(b.launchdLabel);+ expect(a.systemdUnit).not.toBe(b.systemdUnit);+ });+ });++ test('the record holds { id, realpath, created_at } and a reinstall reuses it', async () => {+ await withHosts(async (root) => {+ await withEnv({ GBRAIN_HOME: join(root, 'brain-a') }, () => {+ const id = ensureAutopilotInstallId();+ const rec = JSON.parse(readFileSync(autopilotInstallIdPath(), 'utf-8'));+ expect(rec.id).toBe(id);+ expect(rec.realpath).toBe(join(root, 'brain-a', '.gbrain'));+ expect(Number.isNaN(Date.parse(rec.created_at))).toBe(false);+ expect(ensureAutopilotInstallId()).toBe(id);+ });+ });+ });++ test('read-only resolution never mints: an uninstalled brain owns no named job', async () => {+ await withHosts(async (root) => {+ await withEnv({ GBRAIN_HOME: join(root, 'never-installed') }, () => {+ const job = resolveAutopilotJob();+ expect(job.kind).toBe('unassigned');+ expect(job.suffix).toBeNull();+ // A configDir() that does not exist yet resolves with `resolve`.+ expect(resolveAutopilotInstallId().relation).toBe('none');+ expect(existsSync(join(root, 'never-installed'))).toBe(false);+ });+ });+ });++ test('cp -r of a brain mints a new id on install (the original still exists)', async () => {+ await withHosts(async (root) => {+ const original = await withEnv({ GBRAIN_HOME: join(root, 'brain-a') }, () => ensureAutopilotInstallId());+ cpSync(join(root, 'brain-a'), join(root, 'brain-copy'), { recursive: true });+ await withEnv({ GBRAIN_HOME: join(root, 'brain-copy') }, () => {+ expect(resolveAutopilotInstallId().relation).toBe('copied');+ expect(resolveAutopilotJob().kind).toBe('unassigned');+ const copy = ensureAutopilotInstallId();+ expect(copy).not.toBe(original);+ expect(JSON.parse(readFileSync(autopilotInstallIdPath(), 'utf-8')).realpath).toBe(join(root, 'brain-copy', '.gbrain'));+ });+ await withEnv({ GBRAIN_HOME: join(root, 'brain-a') }, () => {+ expect(ensureAutopilotInstallId()).toBe(original);+ });+ });+ });++ test('mv of a brain keeps its id and job, and records the new path', async () => {+ await withHosts(async (root) => {+ const before = await withEnv({ GBRAIN_HOME: join(root, 'brain-a') }, () => resolveAutopilotJob({ mint: true }));+ renameSync(join(root, 'brain-a'), join(root, 'brain-moved'));+ await withEnv({ GBRAIN_HOME: join(root, 'brain-moved') }, () => {+ expect(resolveAutopilotInstallId().relation).toBe('moved');+ expect(resolveAutopilotJob().suffix).toBe(before.suffix);+ const after = resolveAutopilotJob({ mint: true });+ expect(after.suffix).toBe(before.suffix);+ expect(after.launchdLabel).toBe(before.launchdLabel);+ expect(JSON.parse(readFileSync(autopilotInstallIdPath(), 'utf-8')).realpath).toBe(join(root, 'brain-moved', '.gbrain'));+ expect(resolveAutopilotInstallId().relation).toBe('same');+ });+ });+ });++ test('concurrent first installs agree on one id', async () => {+ await withHosts(async (root) => {+ const gbrainHome = join(root, 'brain-race');+ const script = `import { ensureAutopilotInstallId } from ${JSON.stringify(join(REPO, 'src/core/autopilot-paths.ts'))};\nprocess.stdout.write(ensureAutopilotInstallId());\n`;+ const scriptPath = join(root, 'race.ts');+ writeFileSync(scriptPath, script);+ const runs = Array.from({ length: 6 }, () => new Promise<string>((done, fail) => {+ const child = spawn(process.execPath, [scriptPath], { env: { ...process.env, GBRAIN_HOME: gbrainHome, HOME: join(root, 'home') } });+ let out = '';+ let err = '';+ child.stdout.on('data', (d) => { out += d; });+ child.stderr.on('data', (d) => { err += d; });+ child.on('close', (code) => (code === 0 ? done(out.trim()) : fail(new Error(`exit ${code}: ${err}`))));+ }));+ const ids = await Promise.all(runs);+ expect(new Set(ids).size).toBe(1);+ expect(ids[0]).toMatch(/^[0-9a-f]{32}$/);+ const leftovers = (await import('fs')).readdirSync(join(gbrainHome, '.gbrain')).filter(f => f.endsWith('.tmp'));+ expect(leftovers).toEqual([]);+ });+ }, 60_000);++ test('the GBRAIN_AUTOPILOT_LABEL test seam still wins over the suffix', async () => {+ await withHosts(async (root) => {+ await withEnv({ GBRAIN_HOME: join(root, 'brain-a'), GBRAIN_AUTOPILOT_LABEL: 'com.gbrain.autopilot.test.seam' }, () => {+ const job = resolveAutopilotJob({ mint: true });+ expect(job.suffix).not.toBeNull();+ expect(job.launchdLabel).toBe('com.gbrain.autopilot.test.seam');+ expect(autopilotLaunchdLabel(job.suffix)).toBe('com.gbrain.autopilot.test.seam');+ });+ });+ });++ test("the wrapper's self-disable lines name this brain's own label and unit", async () => {+ await withHosts(async (root) => {+ await withEnv({ GBRAIN_HOME: join(root, 'brain-a') }, () => {+ const job = resolveAutopilotJob({ mint: true });+ expect(generateSelfDisableGuard('/data/brain', 'macos', job)).toContain(`gui/$(id -u)/com.gbrain.autopilot.${job.suffix}`);+ expect(generateSelfDisableGuard('/data/brain', 'linux-systemd', job)).toContain(`disable --now gbrain-autopilot-${job.suffix}.service`);+ });+ });+ });+});++describe('#5195 crontab line ownership', () => {+ test('marked lines belong to their suffix; unmarked lines to the brain whose wrapper they name, else the default brain', async () => {+ await withHosts(async (root) => {+ const home = join(root, 'home');+ const def = jobIn({ HOME: home, GBRAIN_HOME: undefined });+ expect(def.kind).toBe('default');+ const a = await withEnv({ GBRAIN_HOME: join(root, 'brain-a') }, () => resolveAutopilotJob({ mint: true }));+ const b = await withEnv({ GBRAIN_HOME: join(root, 'brain-b') }, () => resolveAutopilotJob({ mint: true }));+ const marked = `*/5 * * * * '${a.wrapperPath}' >> '${a.logPath}' 2>&1 ${a.cronMarker}`;+ const legacyA = `*/5 * * * * '${a.wrapperPath}' >> '${home}/.gbrain/autopilot.log' 2>&1`;+ const legacyDefault = `*/5 * * * * '${home}/.gbrain/autopilot-run.sh' >> '${home}/.gbrain/autopilot.log' 2>&1`;+ const direct = '*/5 * * * * gbrain autopilot --repo /data/brain';+ const monitor = '*/10 * * * * gbrain autopilot --status --json >> health.log';++ expect(cronLineBelongsToBrain(marked, a)).toBe(true);+ expect(cronLineBelongsToBrain(marked, b)).toBe(false);+ expect(cronLineBelongsToBrain(marked, def)).toBe(false);++ expect(cronLineBelongsToBrain(legacyA, a)).toBe(true);+ expect(cronLineBelongsToBrain(legacyA, b)).toBe(false);+ expect(cronLineBelongsToBrain(legacyA, def)).toBe(false);++ expect(cronLineBelongsToBrain(legacyDefault, def)).toBe(true);+ expect(cronLineBelongsToBrain(legacyDefault, a)).toBe(false);++ expect(cronLineBelongsToBrain(direct, def)).toBe(true);+ expect(cronLineBelongsToBrain(direct, a)).toBe(false);++ expect(cronLineBelongsToBrain(monitor, def)).toBe(false);+ expect(cronLineBelongsToBrain(`# ${legacyDefault}`, def)).toBe(false);+ });+ });++ test('wrapper ownership: own, dangling (moved brain), another live brain', async () => {+ await withHosts(async (root) => {+ mkdirSync(join(root, 'brain-b', '.gbrain'), { recursive: true });+ writeFileSync(join(root, 'brain-b', '.gbrain', 'autopilot-run.sh'), '#!/bin/sh\n');+ const home = join(root, 'brain-a', '.gbrain');+ expect(autopilotWrapperOwner(join(home, 'autopilot-run.sh'), home).owner).toBe('own');+ expect(autopilotWrapperOwner(join(root, 'gone', '.gbrain', 'autopilot-run.sh'), home).owner).toBe('dangling');+ expect(autopilotWrapperOwner(join(root, 'brain-b', '.gbrain', 'autopilot-run.sh'), home))+ .toEqual({ owner: 'other', home: join(root, 'brain-b', '.gbrain') });+ expect(autopilotWrapperOwner(null, home).owner).toBe('unknown');+ });+ });+});diff --git a/test/e2e/autopilot-multi-brain.serial.test.ts b/test/e2e/autopilot-multi-brain.serial.test.tsnew file mode 100644index 0000000000..34e592531f--- /dev/null+++ b/test/e2e/autopilot-multi-brain.serial.test.ts@@ -0,0 +1,310 @@+/**+ * #5195 — two brains on one host each get their own autopilot job, on every+ * install target, end to end.+ *+ * Before the fix every brain installed under one shared name+ * (`com.gbrain.autopilot`, `gbrain-autopilot.service`, `~/.gbrain/start-autopilot.sh`,+ * one unmarked crontab line), so a second brain's install replaced the first+ * brain's job, logs interleaved in `~/.gbrain/autopilot.log`, and either+ * brain's uninstall removed the shared job.+ *+ * Hermetic like test/e2e/autopilot-linux-lifecycle.serial.test.ts: `crontab`,+ * `systemctl` and `launchctl` are PATH shims in a tempdir (crontab round-trips+ * a state file; the others record argv), HOME is a temp root, and each brain+ * is a GBRAIN_HOME under it with a hand-seeded keyless PGLite config. The CLI+ * is SPAWNED (Bun's execSync snapshots env at startup, #2747). The macos+ * target is forced with `--target macos`, so its plist arm runs on Linux too.+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { spawnSync } from 'child_process';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join, resolve } from 'path';++const REPO_ROOT = resolve(import.meta.dir, '..', '..');+const CLI = join(REPO_ROOT, 'src', 'cli.ts');++let root: string;+let home: string;+let repoDir: string;+let shimDir: string;+let cronState: string;+let sysctlLog: string;+let launchctlLog: string;+let baseEnv: Record<string, string>;++const FOREIGN = "*/10 * * * * /usr/local/bin/backup.sh --label 'nightly backup' # keep me\n";++function shim(name: string, body: string): void {+ writeFileSync(join(shimDir, name), body);+ chmodSync(join(shimDir, name), 0o755);+}++function seedBrain(gbrainHome: string): void {+ const dir = join(gbrainHome, '.gbrain');+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'config.json'), JSON.stringify({+ engine: 'pglite',+ database_path: join(dir, 'brain.pglite'),+ embedding_disabled: true,+ }) + '\n');+}++function run(gbrainHome: string | null, args: string[]): { status: number | null; out: string } {+ const env = { ...baseEnv };+ if (gbrainHome) env.GBRAIN_HOME = gbrainHome;+ const r = spawnSync(process.execPath, ['run', CLI, 'autopilot', ...args], {+ cwd: REPO_ROOT, env, encoding: 'utf-8', timeout: 120_000, killSignal: 'SIGKILL',+ });+ return { status: r.status, out: (r.stdout ?? '') + (r.stderr ?? '') };+}++function install(gbrainHome: string | null, target: string): { status: number | null; out: string } {+ return run(gbrainHome, ['--install', '--force', '--target', target, '--repo', repoDir]);+}++function status(gbrainHome: string | null): Record<string, any> {+ const r = run(gbrainHome, ['--status', '--json']);+ const line = r.out.split('\n').map(l => l.trim()).filter(l => l.startsWith('{')).pop();+ if (!line) throw new Error(`no status JSON:\n${r.out}`);+ return JSON.parse(line);+}++function suffixOf(gbrainHome: string): string {+ return JSON.parse(readFileSync(join(gbrainHome, '.gbrain', 'autopilot-install-id'), 'utf-8')).id.slice(0, 8);+}++const lines = (p: string) => (existsSync(p) ? readFileSync(p, 'utf-8').split('\n').filter(Boolean) : []);+const unitDir = () => join(home, '.config', 'systemd', 'user');+const agentsDir = () => join(home, 'Library', 'LaunchAgents');++let brainA: string;+let brainB: string;+let brainC: string;++beforeAll(() => {+ root = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-5195-e2e-')));+ home = join(root, 'home');+ repoDir = join(root, 'repo');+ shimDir = join(root, 'shims');+ cronState = join(root, 'cron-state.txt');+ sysctlLog = join(root, 'systemctl.log');+ launchctlLog = join(root, 'launchctl.log');+ for (const d of [home, repoDir, shimDir]) mkdirSync(d, { recursive: true });+ shim('crontab', `#!/bin/sh+if [ "$1" = "-l" ]; then if [ -f '${cronState}' ]; then cat '${cronState}'; exit 0; else exit 1; fi; fi+cat "$1" > '${cronState}'+`);+ shim('systemctl', `#!/bin/sh\nprintf '%s\\n' "$*" >> '${sysctlLog}'\nexit 0\n`);+ shim('launchctl', `#!/bin/sh\nprintf '%s\\n' "$*" >> '${launchctlLog}'\nexit 0\n`);+ shim('gbrain', '#!/bin/sh\nexit 0\n');+ writeFileSync(cronState, FOREIGN);+ baseEnv = {};+ for (const [k, v] of Object.entries(process.env)) if (v !== undefined) baseEnv[k] = v;+ Object.assign(baseEnv, {+ HOME: home,+ XDG_CONFIG_HOME: join(home, '.config'),+ PATH: `${shimDir}:${process.env.PATH ?? ''}`,+ GBRAIN_SKIP_STARTUP_HOOKS: '1',+ });+ for (const k of ['GBRAIN_HOME', 'GBRAIN_AUTOPILOT_LABEL', 'DATABASE_URL', 'GBRAIN_DATABASE_URL', 'OPENCLAW_HOME',+ 'VOYAGE_API_KEY', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'GOOGLE_API_KEY', 'RENDER', 'RAILWAY_ENVIRONMENT', 'FLY_APP_NAME']) {+ delete baseEnv[k];+ }+ brainA = join(root, 'brain-a');+ brainB = join(root, 'brain-b');+ brainC = join(root, 'brain-c');+ for (const b of [brainA, brainB, brainC]) seedBrain(b);+ seedBrain(home);+});++afterAll(() => {+ rmSync(root, { recursive: true, force: true });+});++describe('#5195 two brains on one host keep separate autopilot jobs', () => {+ test('linux-cron: two marked lines, per-brain logs; uninstall removes only its own line', () => {+ expect(install(brainA, 'linux-cron').status).toBe(0);+ expect(install(brainB, 'linux-cron').status).toBe(0);+ const sa = suffixOf(brainA);+ const sb = suffixOf(brainB);+ expect(sa).not.toBe(sb);+ const table = readFileSync(cronState, 'utf-8');+ expect(table.startsWith(FOREIGN)).toBe(true);+ expect(table).toContain(`*/5 * * * * '${brainA}/.gbrain/autopilot-run.sh' >> '${brainA}/.gbrain/autopilot.log' 2>&1 # gbrain-autopilot:${sa}`);+ expect(table).toContain(`*/5 * * * * '${brainB}/.gbrain/autopilot-run.sh' >> '${brainB}/.gbrain/autopilot.log' 2>&1 # gbrain-autopilot:${sb}`);++ // A reinstall of A keeps one line for A (the existence check is per brain).+ const again = install(brainA, 'linux-cron');+ expect(again.out).toContain('Crontab entry already exists');+ expect(readFileSync(cronState, 'utf-8')).toBe(table);++ const sA = status(brainA);+ expect(sA.installed).toBe(true);+ expect(sA.install_target).toBe('linux-cron');+ expect(sA.job.suffix).toBe(sa);+ expect(sA.job.cron_marker).toBe(`# gbrain-autopilot:${sa}`);+ expect(sA.job.install_id_path).toBe(join(brainA, '.gbrain', 'autopilot-install-id'));+ expect(sA.job.log_path).toBe(join(brainA, '.gbrain', 'autopilot.log'));+ expect(sA.job.wrapper_path).toBe(join(brainA, '.gbrain', 'autopilot-run.sh'));++ expect(run(brainA, ['--uninstall']).status).toBe(0);+ const after = readFileSync(cronState, 'utf-8');+ expect(after).not.toContain(`gbrain-autopilot:${sa}`);+ expect(after).toContain(`gbrain-autopilot:${sb}`);+ expect(after.startsWith(FOREIGN)).toBe(true);+ expect(status(brainA).installed).toBe(false);+ expect(status(brainB).installed).toBe(true);+ expect(run(brainB, ['--uninstall']).status).toBe(0);+ expect(readFileSync(cronState, 'utf-8').trim()).toBe(FOREIGN.trim());+ }, 240_000);++ test('linux-systemd: two units, each logs under its own brain; uninstall disables only its unit', () => {+ rmSync(sysctlLog, { force: true });+ expect(install(brainA, 'linux-systemd').status).toBe(0);+ expect(install(brainB, 'linux-systemd').status).toBe(0);+ const ua = `gbrain-autopilot-${suffixOf(brainA)}.service`;+ const ub = `gbrain-autopilot-${suffixOf(brainB)}.service`;+ expect(readdirSync(unitDir()).sort()).toEqual([ua, ub].sort());+ const unitA = readFileSync(join(unitDir(), ua), 'utf-8');+ expect(unitA).toContain(`ExecStart=${brainA}/.gbrain/autopilot-run.sh`);+ expect(unitA).toContain(`StandardOutput=append:${brainA}/.gbrain/autopilot.log`);+ expect(lines(sysctlLog)).toContain(`--user enable --now ${ua}`);+ expect(lines(sysctlLog)).toContain(`--user enable --now ${ub}`);+ expect(readFileSync(join(brainA, '.gbrain', 'autopilot-run.sh'), 'utf-8')).toContain(`systemctl --user disable --now ${ua}`);++ const sB = status(brainB);+ expect(sB.install_target).toBe('linux-systemd');+ expect(sB.job.systemd_unit).toBe(ub);++ rmSync(sysctlLog, { force: true });+ expect(run(brainA, ['--uninstall']).status).toBe(0);+ expect(existsSync(join(unitDir(), ua))).toBe(false);+ expect(existsSync(join(unitDir(), ub))).toBe(true);+ expect(lines(sysctlLog)).toEqual([`--user disable --now ${ua}`, '--user daemon-reload']);+ expect(run(brainB, ['--uninstall']).status).toBe(0);+ }, 240_000);++ test('ephemeral-container: one start script per brain, inside that brain', () => {+ expect(install(brainA, 'ephemeral-container').status).toBe(0);+ expect(install(brainB, 'ephemeral-container').status).toBe(0);+ const scriptA = join(brainA, '.gbrain', `start-autopilot-${suffixOf(brainA)}.sh`);+ const scriptB = join(brainB, '.gbrain', `start-autopilot-${suffixOf(brainB)}.sh`);+ expect(readFileSync(scriptA, 'utf-8')).toContain(`nohup '${brainA}/.gbrain/autopilot-run.sh' > '${brainA}/.gbrain/autopilot.log' 2>&1 &`);+ expect(readFileSync(scriptB, 'utf-8')).toContain(`> '${brainB}/.gbrain/autopilot.log'`);+ expect(existsSync(join(home, '.gbrain', 'start-autopilot.sh'))).toBe(false);+ expect(status(brainA).install_target).toBe('ephemeral-container');+ expect(run(brainA, ['--uninstall']).status).toBe(0);+ expect(existsSync(scriptA)).toBe(false);+ expect(existsSync(scriptB)).toBe(true);+ expect(run(brainB, ['--uninstall']).status).toBe(0);+ }, 240_000);++ test('macos (launchd): one plist per brain label; uninstall unloads only its own', () => {+ rmSync(launchctlLog, { force: true });+ expect(install(brainA, 'macos').status).toBe(0);+ expect(install(brainB, 'macos').status).toBe(0);+ const la = `com.gbrain.autopilot.${suffixOf(brainA)}`;+ const lb = `com.gbrain.autopilot.${suffixOf(brainB)}`;+ expect(readdirSync(agentsDir()).sort()).toEqual([`${la}.plist`, `${lb}.plist`].sort());+ const plistA = readFileSync(join(agentsDir(), `${la}.plist`), 'utf-8');+ expect(plistA).toContain(`<key>Label</key><string>${la}</string>`);+ expect(plistA).toContain(`<key>StandardOutPath</key><string>${brainA}/.gbrain/autopilot.log</string>`);+ expect(lines(launchctlLog)).toContain(`load ${join(agentsDir(), `${lb}.plist`)}`);+ expect(readFileSync(join(brainA, '.gbrain', 'autopilot-run.sh'), 'utf-8')).toContain(`gui/$(id -u)/${la}`);++ expect(run(brainA, ['--uninstall']).status).toBe(0);+ expect(existsSync(join(agentsDir(), `${la}.plist`))).toBe(false);+ expect(existsSync(join(agentsDir(), `${lb}.plist`))).toBe(true);+ expect(run(brainB, ['--uninstall']).status).toBe(0);+ }, 240_000);+});++describe('#5195 legacy shared-name jobs and moved brains', () => {+ test('status flags a legacy shared unit that runs this brain; install replaces it and says so', () => {+ mkdirSync(unitDir(), { recursive: true });+ mkdirSync(join(brainC, '.gbrain'), { recursive: true });+ writeFileSync(join(brainC, '.gbrain', 'autopilot-run.sh'), '#!/bin/sh\n', { mode: 0o755 });+ writeFileSync(join(unitDir(), 'gbrain-autopilot.service'), `[Unit]\nDescription=GBrain Autopilot\n[Service]\nExecStart=${brainC}/.gbrain/autopilot-run.sh\n`);++ const before = status(brainC);+ expect(before.installed).toBe(true);+ expect(before.job.needs_reinstall).toBe('legacy_shared_job');+ expect(before.job.installed_definition.legacy_shared_name).toBe(true);+ // The default brain does not claim a shared job that runs another live brain.+ const defaultView = status(null);+ expect(defaultView.installed).toBe(false);+ expect(defaultView.job.shared_job_of_other_brain.home).toBe(join(brainC, '.gbrain'));+ // ...and its uninstall leaves that job alone, naming the right command.+ const defaultUninstall = run(null, ['--uninstall']);+ expect(defaultUninstall.out).toContain(`GBRAIN_HOME='${brainC}' gbrain autopilot --uninstall`);+ expect(existsSync(join(unitDir(), 'gbrain-autopilot.service'))).toBe(true);+ // ...and its install refuses rather than taking that brain's job over.+ const refused = install(null, 'linux-systemd');+ expect(refused.status).toBe(1);+ expect(refused.out).toContain('autopilot job gbrain-autopilot.service runs the brain at');+ expect(refused.out).toContain(`GBRAIN_HOME='${brainC}' gbrain autopilot --install`);++ const r = install(brainC, 'linux-systemd');+ expect(r.status).toBe(0);+ expect(r.out).toContain('Replaced the shared systemd unit gbrain-autopilot.service, which ran this brain');+ expect(existsSync(join(unitDir(), 'gbrain-autopilot.service'))).toBe(false);+ expect(existsSync(join(unitDir(), `gbrain-autopilot-${suffixOf(brainC)}.service`))).toBe(true);+ expect(status(brainC).job.needs_reinstall).toBeNull();+ expect(run(brainC, ['--uninstall']).status).toBe(0);+ }, 240_000);++ test('an unmarked legacy crontab line naming this brain is replaced by its marked line', () => {+ const legacy = `*/5 * * * * '${brainC}/.gbrain/autopilot-run.sh' >> '${home}/.gbrain/autopilot.log' 2>&1`;+ writeFileSync(cronState, FOREIGN + legacy + '\n');+ expect(status(brainC).job.needs_reinstall).toBe('legacy_shared_job');+ const r = install(brainC, 'linux-cron');+ expect(r.status).toBe(0);+ const table = readFileSync(cronState, 'utf-8');+ expect(table).not.toContain(legacy);+ expect(table).toContain(`# gbrain-autopilot:${suffixOf(brainC)}`);+ expect(table.split('\n').filter(l => l.includes('autopilot-run.sh'))).toHaveLength(1);+ expect(run(brainC, ['--uninstall']).status).toBe(0);+ expect(readFileSync(cronState, 'utf-8').trim()).toBe(FOREIGN.trim());+ }, 240_000);++ test('mv keeps one job: status flags the missing wrapper, reinstall repoints the same job', () => {+ expect(install(brainB, 'linux-cron').status).toBe(0);+ const sb = suffixOf(brainB);+ const moved = join(root, 'brain-b-moved');+ renameSync(brainB, moved);+ // The seeded config names its PGLite file by absolute path; repoint it, or+ // the install's engine connect would recreate the old directory (which+ // would then read as a copy, correctly, and mint a new id).+ seedBrain(moved);+ const s = status(moved);+ expect(s.installed).toBe(true);+ expect(s.job.suffix).toBe(sb);+ expect(s.job.needs_reinstall).toBe('wrapper_missing');+ expect(s.job.installed_definition.wrapper_exists).toBe(false);++ expect(install(moved, 'linux-cron').status).toBe(0);+ expect(suffixOf(moved)).toBe(sb);+ const table = readFileSync(cronState, 'utf-8');+ const own = table.split('\n').filter(l => l.includes(`gbrain-autopilot:${sb}`));+ expect(own).toHaveLength(1);+ expect(own[0]).toContain(`'${moved}/.gbrain/autopilot-run.sh'`);+ expect(status(moved).job.needs_reinstall).toBeNull();+ expect(run(moved, ['--uninstall']).status).toBe(0);+ }, 240_000);++ test('cp -r gives the copy its own job; the original keeps its own', () => {+ expect(install(brainA, 'linux-cron').status).toBe(0);+ const copy = join(root, 'brain-a-copy');+ spawnSync('cp', ['-r', brainA, copy]);+ expect(status(copy).installed).toBe(false);+ expect(install(copy, 'linux-cron').status).toBe(0);+ expect(suffixOf(copy)).not.toBe(suffixOf(brainA));+ const autopilotLines = readFileSync(cronState, 'utf-8').split('\n').filter(l => l.includes('autopilot-run.sh'));+ expect(autopilotLines).toHaveLength(2);+ expect(run(copy, ['--uninstall']).status).toBe(0);+ expect(status(brainA).installed).toBe(true);+ expect(run(brainA, ['--uninstall']).status).toBe(0);+ }, 240_000);+});