refactor: drop macOS launchd and nohup service install paths

The service only runs under Linux systemd. Remove setupLaunchd,
setupNohupFallback, buildLaunchdPlist, the launchd/nohup service checks
in setup/verify-services.ts, ServiceDef.launchdLabel, launchd/ and the
unused repo-tokens/ GitHub action. Without systemd, `setup --step
service` now fails with systemd_unavailable instead of writing a nohup
wrapper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Codex
2026-10-01 19:06:09 +09:00
parent a9fe9dac54
commit e999ce9a33
23 changed files with 49 additions and 882 deletions

View File

@@ -76,16 +76,12 @@ describe('hasSystemd', () => {
describe('getServiceManager', () => {
it('returns a valid service manager', () => {
const result = getServiceManager();
expect(['launchd', 'systemd', 'none']).toContain(result);
expect(['systemd', 'none']).toContain(result);
});
it('matches the detected platform', () => {
const platform = getPlatform();
const result = getServiceManager();
if (platform === 'macos') {
expect(result).toBe('launchd');
} else {
expect(['systemd', 'none']).toContain(result);
it('only reports systemd on Linux', () => {
if (getPlatform() !== 'linux') {
expect(getServiceManager()).toBe('none');
}
});
});

View File

@@ -6,7 +6,7 @@ import fs from 'fs';
import os from 'os';
export type Platform = 'macos' | 'linux' | 'unknown';
export type ServiceManager = 'launchd' | 'systemd' | 'none';
export type ServiceManager = 'systemd' | 'none';
export type LinuxReadonlySandboxAppArmorSetupResult =
| 'not-linux'
| 'not-needed'
@@ -56,12 +56,7 @@ export function hasSystemd(): boolean {
}
export function getServiceManager(): ServiceManager {
const platform = getPlatform();
if (platform === 'macos') return 'launchd';
if (platform === 'linux') {
if (hasSystemd()) return 'systemd';
return 'none';
}
if (getPlatform() === 'linux' && hasSystemd()) return 'systemd';
return 'none';
}

View File

@@ -3,24 +3,21 @@ export type ServiceKind = 'primary';
export interface ServiceDef {
/** Stable topology kind used by setup/verify logic */
kind: ServiceKind;
/** systemd unit name / nohup script name */
/** systemd unit name */
name: string;
/** launchd label */
launchdLabel: string;
/** Human-readable description for systemd/launchd */
/** Human-readable description for systemd */
description: string;
/** Log file prefix (e.g. "ejclaw" → logs/ejclaw.log) */
logName: string;
/** Absolute path to EnvironmentFile (systemd) — loaded before Environment= */
environmentFile?: string;
/** Extra Environment= lines for systemd / env dict entries for launchd */
/** Extra Environment= lines for systemd */
extraEnv?: Record<string, string>;
}
interface ServiceTemplate {
kind: ServiceKind;
name: string;
launchdLabel: string;
description: string;
logName: string;
}
@@ -29,7 +26,6 @@ const CURRENT_SERVICE_TEMPLATES: ServiceTemplate[] = [
{
kind: 'primary',
name: 'ejclaw',
launchdLabel: 'com.ejclaw',
description: 'EJClaw Personal Assistant (Claude Code)',
logName: 'ejclaw',
},
@@ -47,7 +43,6 @@ function materializeServiceDef(template: ServiceTemplate): ServiceDef {
return {
kind: template.kind,
name: template.name,
launchdLabel: template.launchdLabel,
description: template.description,
logName: template.logName,
environmentFile,

View File

@@ -7,63 +7,11 @@ import { getServiceManager, isRoot } from './platform.js';
import { STACK_RESTART_UNIT_NAME } from './restart-stack.js';
import type { ServiceDef } from './service-defs.js';
import {
buildLaunchdPlist,
buildStackRestartSystemdUnit,
buildSystemdUnit,
} from './service-renderers.js';
import { emitStatus } from './status.js';
export function setupLaunchd(
def: ServiceDef,
projectRoot: string,
nodePath: string,
homeDir: string,
): void {
const plistPath = path.join(
homeDir,
'Library',
'LaunchAgents',
`${def.launchdLabel}.plist`,
);
fs.mkdirSync(path.dirname(plistPath), { recursive: true });
const plist = buildLaunchdPlist(def, projectRoot, nodePath, homeDir);
fs.writeFileSync(plistPath, plist);
logger.info({ plistPath, service: def.name }, 'Wrote launchd plist');
try {
execSync(`launchctl load ${JSON.stringify(plistPath)}`, {
stdio: 'ignore',
});
logger.info({ service: def.name }, 'launchctl load succeeded');
} catch {
logger.warn(
{ service: def.name },
'launchctl load failed (may already be loaded)',
);
}
let serviceLoaded = false;
try {
const output = execSync('launchctl list', { encoding: 'utf-8' });
serviceLoaded = output.includes(def.launchdLabel);
} catch {
// launchctl list failed
}
emitStatus('SETUP_SERVICE', {
SERVICE_NAME: def.name,
SERVICE_TYPE: 'launchd',
NODE_PATH: nodePath,
PROJECT_PATH: projectRoot,
PLIST_PATH: plistPath,
SERVICE_LOADED: serviceLoaded,
STATUS: 'success',
LOG: 'logs/setup.log',
});
}
export function setupLinux(
serviceDefs: ServiceDef[],
projectRoot: string,
@@ -75,12 +23,23 @@ export function setupLinux(
if (serviceManager === 'systemd') {
setupSystemdAll(serviceDefs, projectRoot, nodePath, homeDir);
} else {
for (const def of serviceDefs) {
setupNohupFallback(def, projectRoot, nodePath, homeDir);
}
failWithoutSystemd(projectRoot, nodePath);
}
}
function failWithoutSystemd(projectRoot: string, nodePath: string): never {
logger.error('systemd is required to install the EJClaw service');
emitStatus('SETUP_SERVICE', {
SERVICE_TYPE: 'none',
NODE_PATH: nodePath,
PROJECT_PATH: projectRoot,
STATUS: 'failed',
ERROR: 'systemd_unavailable',
LOG: 'logs/setup.log',
});
process.exit(1);
}
/**
* Kill any orphaned ejclaw node processes left from previous runs or debugging.
* Prevents connection conflicts when two instances connect to the same channel simultaneously.
@@ -109,13 +68,8 @@ function setupSystemdAll(
try {
execSync('systemctl --user daemon-reload', { stdio: 'pipe' });
} catch {
logger.warn(
'systemd user session not available — falling back to nohup wrapper',
);
for (const def of serviceDefs) {
setupNohupFallback(def, projectRoot, nodePath, homeDir);
}
return;
logger.warn('systemd user session not available');
failWithoutSystemd(projectRoot, nodePath);
}
}
@@ -228,79 +182,3 @@ function setupSystemdStackRestartUnit(
'Wrote stack restart systemd unit',
);
}
function setupNohupFallback(
def: ServiceDef,
projectRoot: string,
nodePath: string,
_homeDir: string,
): void {
logger.warn(
{ service: def.name },
'No systemd detected — generating nohup wrapper script',
);
const wrapperPath = path.join(projectRoot, `start-${def.name}.sh`);
const pidFile = path.join(projectRoot, `${def.name}.pid`);
const exportLines: string[] = [];
if (def.environmentFile) {
exportLines.push(`# Load environment file`);
exportLines.push(`set -a`);
exportLines.push(`source ${JSON.stringify(def.environmentFile)}`);
exportLines.push(`set +a`);
exportLines.push('');
}
if (def.extraEnv) {
for (const [k, v] of Object.entries(def.extraEnv)) {
exportLines.push(`export ${k}=${JSON.stringify(v)}`);
}
exportLines.push('');
}
const lines = [
'#!/bin/bash',
`# start-${def.name}.sh — Start ${def.description} without systemd`,
`# To stop: kill \\$(cat ${pidFile})`,
'',
'set -euo pipefail',
'',
`cd ${JSON.stringify(projectRoot)}`,
'',
...exportLines,
'# Stop existing instance if running',
`if [ -f ${JSON.stringify(pidFile)} ]; then`,
` OLD_PID=$(cat ${JSON.stringify(pidFile)} 2>/dev/null || echo "")`,
' if [ -n "$OLD_PID" ] && kill -0 "$OLD_PID" 2>/dev/null; then',
` echo "Stopping existing ${def.name} (PID $OLD_PID)..."`,
' kill "$OLD_PID" 2>/dev/null || true',
' sleep 2',
' fi',
'fi',
'',
`echo "Starting ${def.description}..."`,
`nohup ${JSON.stringify(nodePath)} ${JSON.stringify(projectRoot + '/dist/index.js')} \\`,
` >> ${JSON.stringify(projectRoot + '/logs/' + def.logName + '.log')} \\`,
` 2>> ${JSON.stringify(projectRoot + '/logs/' + def.logName + '.error.log')} &`,
'',
`echo $! > ${JSON.stringify(pidFile)}`,
`echo "${def.name} started (PID $!)"`,
`echo "Logs: tail -f ${projectRoot}/logs/${def.logName}.log"`,
];
const wrapper = lines.join('\n') + '\n';
fs.writeFileSync(wrapperPath, wrapper, { mode: 0o755 });
logger.info({ wrapperPath, service: def.name }, 'Wrote nohup wrapper script');
emitStatus('SETUP_SERVICE', {
SERVICE_NAME: def.name,
SERVICE_TYPE: 'nohup',
NODE_PATH: nodePath,
PROJECT_PATH: projectRoot,
WRAPPER_PATH: wrapperPath,
SERVICE_LOADED: false,
FALLBACK: 'wsl_no_systemd',
STATUS: 'success',
LOG: 'logs/setup.log',
});
}

View File

@@ -7,26 +7,6 @@ export function buildRuntimePathEnv(nodePath: string, homeDir: string): string {
return `${path.dirname(nodePath)}:/usr/local/bin:/usr/bin:/bin:${homeDir}/.local/bin:${homeDir}/.npm-global/bin`;
}
function buildLaunchdEnvironmentEntries(
nodePath: string,
homeDir: string,
extraEnv?: Record<string, string>,
): string[] {
const envEntries = [
` <key>PATH</key>`,
` <string>${buildRuntimePathEnv(nodePath, homeDir)}</string>`,
` <key>HOME</key>`,
` <string>${homeDir}</string>`,
];
if (extraEnv) {
for (const [k, v] of Object.entries(extraEnv)) {
envEntries.push(` <key>${k}</key>`);
envEntries.push(` <string>${v}</string>`);
}
}
return envEntries;
}
function buildSystemdEnvironmentLines(
nodePath: string,
homeDir: string,
@@ -44,47 +24,6 @@ function buildSystemdEnvironmentLines(
return envLines;
}
export function buildLaunchdPlist(
def: ServiceDef,
projectRoot: string,
nodePath: string,
homeDir: string,
): string {
const envEntries = buildLaunchdEnvironmentEntries(
nodePath,
homeDir,
def.extraEnv,
);
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>${def.launchdLabel}</string>
<key>ProgramArguments</key>
<array>
<string>${nodePath}</string>
<string>${projectRoot}/dist/index.js</string>
</array>
<key>WorkingDirectory</key>
<string>${projectRoot}</string>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>EnvironmentVariables</key>
<dict>
${envEntries.join('\n')}
</dict>
<key>StandardOutPath</key>
<string>${projectRoot}/logs/${def.logName}.log</string>
<key>StandardErrorPath</key>
<string>${projectRoot}/logs/${def.logName}.error.log</string>
</dict>
</plist>`;
}
export function buildSystemdUnit(
def: ServiceDef,
projectRoot: string,

View File

@@ -4,7 +4,6 @@ import path from 'path';
import { afterEach, describe, expect, it } from 'vitest';
import {
buildLaunchdPlist,
buildRuntimePathEnv,
buildStackRestartSystemdUnit,
buildSystemdUnit,
@@ -14,61 +13,17 @@ import { getServiceDefs, type ServiceDef } from './service-defs.js';
/**
* Tests for service configuration generation.
*
* These tests verify the generated content of plist/systemd/nohup configs
* These tests verify the generated content of systemd configs
* without actually loading services.
*/
const baseServiceDef: ServiceDef = {
kind: 'primary',
description: 'EJClaw Personal Assistant',
launchdLabel: 'com.ejclaw',
logName: 'ejclaw',
name: 'ejclaw',
};
describe('plist generation', () => {
it('contains the correct label', () => {
const plist = buildLaunchdPlist(
baseServiceDef,
'/home/user/ejclaw',
'/usr/local/bin/node',
'/home/user',
);
expect(plist).toContain('<string>com.ejclaw</string>');
});
it('uses the correct node path', () => {
const plist = buildLaunchdPlist(
baseServiceDef,
'/home/user/ejclaw',
'/opt/node/bin/node',
'/home/user',
);
expect(plist).toContain('<string>/opt/node/bin/node</string>');
});
it('points to dist/index.js', () => {
const plist = buildLaunchdPlist(
baseServiceDef,
'/home/user/ejclaw',
'/usr/local/bin/node',
'/home/user',
);
expect(plist).toContain('/home/user/ejclaw/dist/index.js');
});
it('sets log paths', () => {
const plist = buildLaunchdPlist(
baseServiceDef,
'/home/user/ejclaw',
'/usr/local/bin/node',
'/home/user',
);
expect(plist).toContain('ejclaw.log');
expect(plist).toContain('ejclaw.error.log');
});
});
describe('systemd unit generation', () => {
it('shares the runtime PATH builder across service formats', () => {
expect(buildRuntimePathEnv('/usr/bin/bun', '/home/user')).toBe(
@@ -156,26 +111,6 @@ describe('systemd unit generation', () => {
});
});
describe('WSL nohup fallback', () => {
it('generates a valid wrapper script', () => {
const projectRoot = '/home/user/ejclaw';
const nodePath = '/usr/bin/node';
const pidFile = path.join(projectRoot, 'ejclaw.pid');
// Simulate what service.ts generates
const wrapper = `#!/bin/bash
set -euo pipefail
cd ${JSON.stringify(projectRoot)}
nohup ${JSON.stringify(nodePath)} ${JSON.stringify(projectRoot)}/dist/index.js >> ${JSON.stringify(projectRoot)}/logs/ejclaw.log 2>> ${JSON.stringify(projectRoot)}/logs/ejclaw.error.log &
echo $! > ${JSON.stringify(pidFile)}`;
expect(wrapper).toContain('#!/bin/bash');
expect(wrapper).toContain('nohup');
expect(wrapper).toContain(nodePath);
expect(wrapper).toContain('ejclaw.pid');
});
});
describe('service definitions', () => {
const tempRoots: string[] = [];

View File

@@ -17,7 +17,7 @@ import {
getNodePath,
} from './platform.js';
import { getServiceDefs } from './service-defs.js';
import { setupLaunchd, setupLinux } from './service-installers.js';
import { setupLinux } from './service-installers.js';
import { emitStatus } from './status.js';
/* ------------------------------------------------------------------ */
@@ -73,11 +73,7 @@ export async function run(_args: string[]): Promise<void> {
const serviceDefs = getServiceDefs(projectRoot);
if (platform === 'macos') {
for (const def of serviceDefs) {
setupLaunchd(def, projectRoot, nodePath, homeDir);
}
} else if (platform === 'linux') {
if (platform === 'linux') {
setupLinux(serviceDefs, projectRoot, nodePath, homeDir);
} else {
emitStatus('SETUP_SERVICE', {

View File

@@ -1,6 +1,3 @@
import fs from 'fs';
import os from 'os';
import path from 'path';
import { afterEach, describe, expect, it, vi } from 'vitest';
const { execSyncMock, isRootMock } = vi.hoisted(() => ({
@@ -17,10 +14,6 @@ vi.mock('./platform.js', () => ({
}));
import {
checkLaunchdService,
checkLaunchdServiceArtifact,
checkNohupService,
checkNohupServiceArtifact,
checkSystemdService,
checkSystemdServiceInScope,
getServiceChecks,
@@ -35,18 +28,6 @@ describe('verify service checks', () => {
vi.restoreAllMocks();
});
it('treats launchd entries with a PID as running', () => {
execSyncMock.mockReturnValue('123\t0\tcom.ejclaw\n');
expect(checkLaunchdService('com.ejclaw')).toBe('running');
});
it('treats launchd entries without a PID as stopped', () => {
execSyncMock.mockReturnValue('-\t0\tcom.ejclaw\n');
expect(checkLaunchdService('com.ejclaw')).toBe('stopped');
});
it('checks systemd user services with the user prefix', () => {
isRootMock.mockReturnValue(false);
execSyncMock.mockReturnValue(undefined);
@@ -82,25 +63,6 @@ describe('verify service checks', () => {
);
});
it('treats an unloaded launchd plist as stopped when artifact detection is enabled', () => {
const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), 'ejclaw-launchd-'));
const plistPath = path.join(
tempHome,
'Library',
'LaunchAgents',
'com.ejclaw-codex.plist',
);
fs.mkdirSync(path.dirname(plistPath), { recursive: true });
fs.writeFileSync(plistPath, '<plist />');
execSyncMock.mockReturnValue('');
expect(checkLaunchdServiceArtifact('com.ejclaw-codex', plistPath)).toBe(
'stopped',
);
fs.rmSync(tempHome, { recursive: true, force: true });
});
it('treats known but inactive systemd services as stopped', () => {
execSyncMock
.mockImplementationOnce(() => {
@@ -111,55 +73,34 @@ describe('verify service checks', () => {
expect(checkSystemdService('ejclaw')).toBe('stopped');
});
it('treats a live nohup PID as running', () => {
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'ejclaw-verify-'));
const pidFile = path.join(tempRoot, 'ejclaw.pid');
fs.writeFileSync(pidFile, '12345\n');
const killSpy = vi
.spyOn(process, 'kill')
.mockImplementation((_pid: number, _signal?: string | number) => true);
expect(checkNohupService(tempRoot, 'ejclaw')).toBe('running');
killSpy.mockRestore();
fs.rmSync(tempRoot, { recursive: true, force: true });
});
it('treats a legacy nohup wrapper without a live pid as stopped when artifact detection is enabled', () => {
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'ejclaw-verify-'));
fs.writeFileSync(
path.join(tempRoot, 'start-ejclaw-codex.sh'),
'#!/bin/bash\n',
);
expect(checkNohupServiceArtifact(tempRoot, 'ejclaw-codex')).toBe('stopped');
fs.rmSync(tempRoot, { recursive: true, force: true });
});
it('builds per-service status checks from service definitions', () => {
const defs: ServiceDef[] = [
{
kind: 'primary',
name: 'ejclaw',
description: 'EJClaw',
launchdLabel: 'com.ejclaw',
logName: 'ejclaw',
},
{
kind: 'primary',
name: 'ejclaw-secondary',
description: 'Secondary',
launchdLabel: 'com.ejclaw.secondary',
logName: 'ejclaw-secondary',
},
];
execSyncMock.mockReturnValue('123\t0\tcom.ejclaw\n');
execSyncMock.mockImplementation((cmd: string) => {
if (cmd === 'systemctl --user is-active ejclaw') return undefined;
if (cmd === 'systemctl --user list-unit-files') return '';
throw new Error('inactive');
});
expect(getServiceChecks(defs, '/tmp/ejclaw', 'launchd')).toEqual([
expect(getServiceChecks(defs, 'systemd')).toEqual([
{ name: 'ejclaw', status: 'running' },
{ name: 'ejclaw-secondary', status: 'not_found' },
]);
expect(getServiceChecks(defs, 'none')).toEqual([
{ name: 'ejclaw', status: 'not_found' },
{ name: 'ejclaw-secondary', status: 'not_found' },
]);
});
});

View File

@@ -1,6 +1,4 @@
import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';
import { isRoot } from './platform.js';
import type { ServiceDef } from './service-defs.js';
@@ -16,46 +14,8 @@ export interface ServiceCheck {
status: ServiceStatus;
}
export interface ServiceCheckOptions {
detectArtifacts?: boolean;
homeDir?: string;
}
export type SystemdScope = 'system' | 'user';
export function checkLaunchdService(label: string): ServiceStatus {
try {
const output = execSync('launchctl list', { encoding: 'utf-8' });
if (output.includes(label)) {
const line = output
.split('\n')
.find((candidate) => candidate.includes(label));
if (line) {
const pidField = line.trim().split(/\s+/)[0];
return pidField !== '-' && pidField ? 'running' : 'stopped';
}
}
} catch {
// launchctl not available
}
return 'not_found';
}
function getLaunchdPlistPath(homeDir: string, launchdLabel: string): string {
return path.join(homeDir, 'Library', 'LaunchAgents', `${launchdLabel}.plist`);
}
export function checkLaunchdServiceArtifact(
label: string,
plistPath: string,
): ServiceStatus {
const status = checkLaunchdService(label);
if (status !== 'not_found') {
return status;
}
return fs.existsSync(plistPath) ? 'stopped' : 'not_found';
}
export function checkSystemdServiceInScope(
name: string,
scope: SystemdScope,
@@ -83,77 +43,22 @@ export function checkSystemdService(name: string): ServiceStatus {
return checkSystemdServiceInScope(name, isRoot() ? 'system' : 'user');
}
export function checkNohupService(
projectRoot: string,
export function checkService(
serviceManager: 'systemd' | 'none',
serviceName: string,
): ServiceStatus {
const pidFile = path.join(projectRoot, `${serviceName}.pid`);
if (fs.existsSync(pidFile)) {
try {
const raw = fs.readFileSync(pidFile, 'utf-8').trim();
const pid = Number(raw);
if (raw && Number.isInteger(pid) && pid > 0) {
process.kill(pid, 0);
return 'running';
}
} catch {
return 'stopped';
}
if (serviceManager === 'systemd') {
return checkSystemdService(serviceName);
}
return 'not_found';
}
export function checkNohupServiceArtifact(
projectRoot: string,
serviceName: string,
): ServiceStatus {
const status = checkNohupService(projectRoot, serviceName);
if (status !== 'not_found') {
return status;
}
const wrapperPath = path.join(projectRoot, `start-${serviceName}.sh`);
return fs.existsSync(wrapperPath) ? 'stopped' : 'not_found';
}
export function checkService(
projectRoot: string,
serviceManager: 'launchd' | 'systemd' | 'none',
serviceName: string,
launchdLabel: string,
options: ServiceCheckOptions = {},
): ServiceStatus {
if (serviceManager === 'launchd') {
if (options.detectArtifacts && options.homeDir) {
return checkLaunchdServiceArtifact(
launchdLabel,
getLaunchdPlistPath(options.homeDir, launchdLabel),
);
}
return checkLaunchdService(launchdLabel);
}
if (serviceManager === 'systemd') {
return checkSystemdService(serviceName);
}
if (options.detectArtifacts) {
return checkNohupServiceArtifact(projectRoot, serviceName);
}
return checkNohupService(projectRoot, serviceName);
}
export function getServiceChecks(
serviceDefs: ServiceDef[],
projectRoot: string,
serviceManager: 'launchd' | 'systemd' | 'none',
options: ServiceCheckOptions = {},
serviceManager: 'systemd' | 'none',
): ServiceCheck[] {
return serviceDefs.map((def) => ({
name: def.name,
status: checkService(
projectRoot,
serviceManager,
def.name,
def.launchdLabel,
options,
),
status: checkService(serviceManager, def.name),
}));
}

View File

@@ -117,7 +117,6 @@ describe('verify state helpers', () => {
kind: 'primary',
name: 'ejclaw',
description: 'EJClaw',
launchdLabel: 'com.ejclaw',
logName: 'ejclaw',
},
];

View File

@@ -35,7 +35,7 @@ export async function run(_args: string[]): Promise<void> {
// 1. Check service statuses
const serviceDefs = getServiceDefs(projectRoot);
const services = getServiceChecks(serviceDefs, projectRoot, mgr);
const services = getServiceChecks(serviceDefs, mgr);
for (const svc of services) {
logger.info({ service: svc.name, status: svc.status }, 'Service status');