Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

fix(service): the login service follows the install — detect drift, re-point, unload the old job

Salman Qureshi0f063ae9b0d2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 01ea41ba..dbabfb0d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,7 @@
## Unreleased — one runtime (ADR-024)
+- **The login service follows the install.** After a reinstall (npm → binary, stable → dev, a new Node under nvm) the old LaunchAgent / systemd unit kept resurrecting the *old* daemon on every login, so the new build could never own its port. Mercury now checks what the service launches on every launch and re-points it (unloading the old job first); `mercury doctor` shows **Login service: points at this install / STALE**, and the "port owned by another Mercury" message names the service when it is the cause.
- **The terminal no longer runs a second copy of Mercury.** Launching `mercury` with no daemon used to spawn the daemon *and* boot a full runtime in the terminal — Telegram, the scheduler and every bot ran twice, and the second copy ran on the thread that paints your keystrokes. That was the typing lag, and the Telegram "terminated by other getUpdates" (409) conflicts. Now the terminal spawns the daemon and attaches to it; a foreground runtime beside a live daemon (`mercury code`, recovery) is a terminal for the main agent only — no bots, no channels, no web port.
- **Attach waits for a booting daemon** (token not written yet, token rotated at bind) instead of failing on the first read.
- **Event-loop stall monitor**: `/api/health` reports `loopLag` (p99 / worst stall over the last 10 s) and stalls ≥250 ms are logged with a warning, so lag is a number, not a feeling.
diff --git a/DECISIONS.md b/DECISIONS.md
index b06a300a..e70c9778 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -214,4 +214,5 @@
- **Context**: `mercury` with no daemon ran `autoDaemonize(); await runAgent();` — it spawned the daemon and then booted a second, full runtime in the foreground process. Both constructed a `BotManager` on the same `queue.db`, both registered the Telegram channel (Telegram answers 409 "terminated by other getUpdates" to competing pollers — nine such conflicts in one day's daemon-error.log), and the foreground copy ran bot turns, tool executions and context compaction on the thread that renders the TUI. Once bots were made always-alive (liveness contract, §2.14), that second copy had enough work to make typing and menus visibly lag on every machine. A port conflict (a stale global install holding :6174) made the "heal" path take the same route on every launch.
- **Decision**: One process is the runtime. `bootDaemonThenAttach()` replaces spawn-then-boot at launch and in recovery: spawn the daemon, attach to it (`runAttach` now waits for the attach token and tolerates a token rotated during boot); only when no daemon can run here (Termux, unsupported platform) does the terminal become the runtime. A foreground runtime that finds a live daemon (`daemonOwnsRuntime`: `mercury code`, an attach that could not connect) wires the CLI channel only (`ChannelRegistry({ cliOnly })`), creates no `BotManager`, and does not bind the web port — it is a terminal for the main agent. The event loop is measured (`monitorEventLoopDelay`): `/api/health` reports `loopLag`, and stalls ≥250 ms are logged.
+- **Also**: the login service must launch *this* install. `serviceDrift()` compares the plist/unit's program with the running binary; `autoDaemonize` re-points a drifted service (macOS unloads the old label first — a loaded label ignores a rewritten plist and KeepAlive keeps the old daemon alive; Linux restarts the unit), `mercury doctor` reports it, and the attach "foreign port" message names it. On the reporting machine the LaunchAgent still launched the npm-global 1.3.0; that daemon owned :6174 for a day while every `mercury` launch healed around it.
- **Consequence**: Bots and channels run exactly once, in the daemon, on their own thread; the TUI process renders keystrokes and nothing else. The attach TUI is what most sessions see (the daemon auto-starts on login), so parity gaps in it — TUI-only bot threads (`/bots open`), the `/telegram` menu — are now visible and worth closing. Lag has a number: if `loopLag.maxMs` is high in the daemon, something in a bot turn is synchronous and should move off the thread.
diff --git a/src/cli/attach.ts b/src/cli/attach.ts
index 83cc4038..6c19476f 100644
--- a/src/cli/attach.ts
+++ b/src/cli/attach.ts
@@ -1,4 +1,5 @@
import { getForegroundRuntimeStatus, getDaemonStatus } from './daemon.js';
+import { serviceDrift } from './service.js';
import { getWebPort, readAttachToken } from '../web/auth.js';
/**
@@ -442,7 +443,12 @@ export async function runAttach(opts: AttachRunOptions = {}): Promise<AttachResu
if (message.startsWith('foreign:')) {
const [, pid, version] = message.split(':');
console.error(` Port ${new URL(target.baseUrl).port} is owned by another Mercury (PID ${pid}${version ? `, v${version}` : ''}) — the runtime you launched (PID ${target.pid}) has no web listener.`);
- console.error(` Stop the other one (kill ${pid}) or set web.port in mercury.yaml, then run \`mercury\` again. Restarting would not help.`);
+ const drift = serviceDrift();
+ if (drift) {
+ console.error(` Your login service starts that older install (${drift.installed}) on every login — run \`mercury service install\` to point it at this build, then \`mercury\` again.`);
+ } else {
+ console.error(` Stop the other one (kill ${pid}) or set web.port in mercury.yaml, then run \`mercury\` again. Restarting would not help.`);
+ }
if (opts.exitOnFailure) process.exitCode = 1;
return 'unavailable';
}
diff --git a/src/cli/service.test.ts b/src/cli/service.test.ts
index 14e1f4fa..0631ead8 100644
--- a/src/cli/service.test.ts
+++ b/src/cli/service.test.ts
@@ -349,3 +349,20 @@ describe('service install/uninstall/status on Termux (fake HOME, platform androi
expect(existsSync(termuxBootScriptPath(home))).toBe(false);
});
});
+
+describe('login service drift (what the installed service actually launches)', () => {
+ it('parses ProgramArguments back out of a LaunchAgent plist, entities included', async () => {
+ const { buildLaunchAgentPlist, parseLaunchAgentArgs } = await import('./service.js');
+ const args = ['/Users/x/.nvm/versions/node/v22.18.0/bin/node', '/Users/x/lib/node_modules/@cosmicstack/mercury-agent/dist/index.js', 'start', '--daemon'];
+ const plist = buildLaunchAgentPlist(args, { mercuryHome: '/Users/x/.mercury', userHome: '/Users/x', pathEnv: '/usr/bin:/bin' } as never);
+ expect(parseLaunchAgentArgs(plist)).toEqual(args);
+ expect(parseLaunchAgentArgs('<plist/>')).toEqual([]);
+ });
+
+ it('parses a systemd ExecStart= line with quoted words', async () => {
+ const { buildSystemdUnit, parseSystemdExecStart } = await import('./service.js');
+ const args = ['/home/x/.local/bin/mercury', 'start', '--daemon'];
+ expect(parseSystemdExecStart(buildSystemdUnit(args, { mercuryHome: '/home/x/.mercury', userHome: '/home/x', pathEnv: '/usr/bin' } as never))).toEqual(args);
+ expect(parseSystemdExecStart('ExecStart="/opt/My Apps/mercury" start --daemon')).toEqual(['/opt/My Apps/mercury', 'start', '--daemon']);
+ });
+});
diff --git a/src/cli/service.ts b/src/cli/service.ts
index f5698611..28d6ead1 100644
--- a/src/cli/service.ts
+++ b/src/cli/service.ts
@@ -1,4 +1,4 @@
-import { chmodSync, existsSync, mkdirSync, writeFileSync, unlinkSync, realpathSync } from 'node:fs';
+import { chmodSync, existsSync, mkdirSync, writeFileSync, unlinkSync, realpathSync, readFileSync } from 'node:fs';
import { dirname, join, posix, win32 } from 'node:path';
import { fileURLToPath } from 'node:url';
import { homedir } from 'node:os';
@@ -120,7 +120,7 @@ function getDistPath(): string {
* for standalone (bun --compile) binaries it is just `<mercury> start --daemon`
* because `process.argv[1]` is a bun-virtual path that must not be persisted.
*/
-function getServiceLaunchArgs(): string[] {
+export function getServiceLaunchArgs(): string[] {
if (isStandaloneBinary()) {
return [process.execPath, 'start', '--daemon'];
}
@@ -135,6 +135,76 @@ function getServiceLaunchArgs(): string[] {
* `'android'` on real devices) and other unsupported platforms print a hint
* and return false so the caller can still daemonize for this session.
*/
+/** ProgramArguments of a LaunchAgent plist, in order. */
+export function parseLaunchAgentArgs(plist: string): string[] {
+ const block = plist.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);
+ if (!block) return [];
+ return [...block[1].matchAll(/<string>([\s\S]*?)<\/string>/g)].map((m) => m[1]
+ .replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&amp;/g, '&'));
+}
+
+/** The words of a systemd ExecStart= line (double quotes, \" inside). */
+export function parseSystemdExecStart(unit: string): string[] {
+ const line = unit.split(/\r?\n/).find((l) => l.startsWith('ExecStart='));
+ if (!line) return [];
+ const rest = line.slice('ExecStart='.length).trim();
+ const words: string[] = [];
+ let i = 0;
+ while (i < rest.length) {
+ if (rest[i] === ' ') { i++; continue; }
+ let word = '';
+ if (rest[i] === '"') {
+ i++;
+ while (i < rest.length && rest[i] !== '"') { if (rest[i] === '\\' && rest[i + 1] === '"') { word += '"'; i += 2; } else { word += rest[i++]; } }
+ i++;
+ } else {
+ while (i < rest.length && rest[i] !== ' ') word += rest[i++];
+ }
+ words.push(word);
+ }
+ return words;
+}
+
+/** What the installed login service launches, or null when none / unknown platform. */
+export function installedServiceArgs(): string[] | null {
+ try {
+ if (isTermux()) return null;
+ if (process.platform === 'darwin') {
+ const p = join(homedir(), 'Library', 'LaunchAgents', 'com.cosmicstack.mercury.plist');
+ return existsSync(p) ? parseLaunchAgentArgs(readFileSync(p, 'utf-8')) : null;
+ }
+ if (process.platform === 'linux') {
+ const p = join(homedir(), '.config', 'systemd', 'user', 'mercury.service');
+ return existsSync(p) ? parseSystemdExecStart(readFileSync(p, 'utf-8')) : null;
+ }
+ } catch { /* unreadable — treat as unknown */ }
+ return null;
+}
+
+/** The program part of a launch argv (everything before `start --daemon`). */
+function programOf(args: string[]): string {
+ const end = args.indexOf('start');
+ return (end === -1 ? args : args.slice(0, end)).join(' ');
+}
+
+/**
+ * A login service that launches a DIFFERENT install than the one running
+ * now. After a reinstall (npm → binary, stable → dev, a new Node under nvm)
+ * the old plist/unit keeps resurrecting the old daemon on every login, and
+ * the new build can never bind its port. Null when none, current, or unknown.
+ */
+export function serviceDrift(): { installed: string; expected: string } | null {
+ const installed = installedServiceArgs();
+ if (!installed || installed.length === 0) return null;
+ const expected = getServiceLaunchArgs();
+ const a = programOf(installed);
+ const b = programOf(expected);
+ const same = (x: string, y: string) => { try { return realpathSync(x) === realpathSync(y); } catch { return x === y; } };
+ const wa = a.split(' '); const wb = b.split(' ');
+ if (wa.length === wb.length && wa.every((w, i) => same(w, wb[i]))) return null;
+ return { installed: a, expected: b };
+}
+
export function installService(): boolean {
const platform = process.platform;
@@ -738,6 +808,11 @@ function installMac(): void {
const logPath = join(opts.mercuryHome, 'daemon.log');
const plist = buildLaunchAgentPlist(getServiceLaunchArgs(), opts);
+ // A loaded label ignores a rewritten plist, and KeepAlive would keep the
+ // OLD install's daemon alive — unload first, then load the new file.
+ if (existsSync(plistPath)) {
+ try { execSync(`launchctl unload ${plistPath}`, { stdio: 'pipe' }); } catch { /* not loaded */ }
+ }
writeFileSync(plistPath, plist, 'utf-8');
try {
@@ -798,6 +873,11 @@ function showMacStatus(): void {
const output = execSync('launchctl list | grep com.cosmicstack.mercury', { encoding: 'utf-8' }).trim();
console.log(` ${chalk.green('Service installed and loaded')}`);
console.log(chalk.dim(` ${output}`));
+ const drift = serviceDrift();
+ if (drift) {
+ console.log(chalk.yellow(` ⚠ The service launches a different install: ${drift.installed}`));
+ console.log(chalk.yellow(` This build is: ${drift.expected} — run \`mercury service install\` to re-point it.`));
+ }
} catch {
console.log(` ${chalk.yellow('Service installed but not loaded')}`);
console.log(chalk.dim(` Plist: ${plistPath}`));
@@ -823,7 +903,8 @@ function installLinux(): void {
try {
execSync('systemctl --user daemon-reload', { stdio: 'inherit' });
execSync('systemctl --user enable mercury.service', { stdio: 'inherit' });
- execSync('systemctl --user start mercury.service', { stdio: 'inherit' });
+ // restart, not start: a running unit keeps the OLD ExecStart until restarted.
+ execSync('systemctl --user restart mercury.service', { stdio: 'inherit' });
} catch (err) {
console.log(chalk.yellow(' systemd commands failed. Try running manually:'));
console.log(chalk.dim(' systemctl --user daemon-reload'));
diff --git a/src/index.ts b/src/index.ts
index 18572979..a2523bf2 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -77,7 +77,7 @@ import { ask, InputClosedError } from './cli/ask.js';
import { startBackground, stopDaemon, showLogs, getDaemonStatus, registerRuntimeProcess, releaseRuntimeProcess, restartDaemon, tryAutoDaemonize, isStandaloneBinary, getForegroundRuntimeStatus, stopForegroundRuntime } from './cli/daemon.js';
import { runUninstall } from './cli/uninstall.js';
import { runAttach } from './cli/attach.js';
-import { installService, uninstallService, showServiceStatus, isServiceInstalled, pinDaemonPathOnWindows } from './cli/service.js';
+import { installService, uninstallService, showServiceStatus, isServiceInstalled, pinDaemonPathOnWindows, serviceDrift } from './cli/service.js';
import { detectInkPatch, describeInkPatch, inkPatchFixCommand } from './ui/ink-patch-check.js';
import { runWithWatchdog } from './cli/watchdog.js';
import { setGitHubToken } from './utils/github.js';
@@ -2274,7 +2274,15 @@ function autoDaemonize(): boolean {
// the wizard flow completes on phones too.
let serviceInstalled = false;
try {
- serviceInstalled = isServiceInstalled() || installService();
+ // A service left behind by a previous install (npm global, an older
+ // binary) resurrects THAT daemon on every login — the new build then
+ // never owns the port. Re-point it before starting anything.
+ const drift = serviceDrift();
+ if (drift) {
+ console.log(chalk.yellow(` Login service launches an older install: ${drift.installed}`));
+ console.log(chalk.yellow(` Re-pointing it to this build: ${drift.expected}`));
+ }
+ serviceInstalled = (isServiceInstalled() && !drift) || installService();
} catch {
console.log(chalk.dim(' Service install skipped (can run `mercury service install` later).'));
}
@@ -2319,6 +2327,10 @@ function runPlatformDoctor(): void {
console.log(` SSH session: ${sshSession ? chalk.yellow('yes') : chalk.green('no')}`);
console.log(` CI environment: ${ci ? chalk.yellow('yes') : chalk.green('no')}`);
console.log(` Daemon: ${daemon.running ? chalk.green(`running (PID: ${daemon.pid})`) : chalk.dim('not running')}`);
+ {
+ const drift = serviceDrift();
+ console.log(` Login service: ${!isServiceInstalled() ? chalk.dim('not installed') : drift ? chalk.red(`STALE — launches ${drift.installed} (run mercury service install)`) : chalk.green('points at this install')}`);
+ }
console.log(` Spotify inline art: ${canInlineArt ? chalk.green('supported (iTerm local)') : chalk.dim('disabled/fallback mode')}`);
const inkPatch = detectInkPatch();
console.log(` Ink TUI patch: ${inkPatch.patched ? chalk.green(describeInkPatch(inkPatch)) : chalk.red(describeInkPatch(inkPatch))}`);