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:
@@ -130,10 +130,7 @@ bun run setup -- --step service
|
||||
이 명령은:
|
||||
- **ejclaw** 서비스를 설치하고 시작합니다
|
||||
|
||||
플랫폼별:
|
||||
- Linux (systemd): `~/.config/systemd/user/ejclaw.service`
|
||||
- macOS: `~/Library/LaunchAgents/com.ejclaw.plist`
|
||||
- WSL (no systemd): `start-ejclaw.sh`
|
||||
Linux systemd만 지원합니다: `~/.config/systemd/user/ejclaw.service`
|
||||
|
||||
수동으로 서비스 관리:
|
||||
|
||||
|
||||
1
.github/CODEOWNERS
vendored
1
.github/CODEOWNERS
vendored
@@ -1,7 +1,6 @@
|
||||
# Core code - maintainer only
|
||||
/src/ @gavrielc @gabi-simons
|
||||
/groups/ @gavrielc @gabi-simons
|
||||
/launchd/ @gavrielc @gabi-simons
|
||||
/package.json @gavrielc @gabi-simons
|
||||
/bun.lock @gavrielc @gabi-simons
|
||||
|
||||
|
||||
@@ -14,6 +14,8 @@
|
||||
- 웹 대시보드(`src/web-dashboard-*`, `apps/dashboard`), Android 앱(`apps/android`), Glasses UI와 이를 위해서만 있던 설정 저장소(`settings-store`, `settings-store-moa`, `room-skill-settings`, `runtime-inventory`, `codex-live-status`, `settings-effort`), `WEB_DASHBOARD_*` 설정, `dashboard:*`/`android:*` 스크립트, react·vite·playwright 의존성. 잘못된 계정(`~/.codex`)을 갱신하던 Codex 계정 새로고침 루프도 함께 제거. 호스트 증거 도구의 `dashboard_dist`/`android_debug_apk` 항목 제거. Discord 상태 대시보드는 그대로 유지
|
||||
- Mixture of Agents(MoA) arbiter 프롬프트 보강, Kimi 사용량 조회/대시보드 행, `MOA_*` 설정, 코드에서 읽지 않던 `FALLBACK_*` provider 설정 예시
|
||||
- 런타임에 연결되지 않았던 auto-paired-mode(`src/auto-paired-mode.ts`)와 그것만 쓰던 Claude/Codex 사용량 소진 판정 함수
|
||||
- 쓰이지 않던 export·고아 모듈(`src/dashboard.ts`, `src/dashboard-status-content.ts`, `src/restart-context-cli.ts`)과 `DELTA_HANDOFF_*` 설정
|
||||
- macOS launchd·nohup(WSL) 설치 경로와 `launchd/`, 쓰이지 않던 `repo-tokens/` GitHub Action. 서비스 설치는 Linux systemd만 지원
|
||||
|
||||
### Fixed
|
||||
|
||||
|
||||
@@ -114,7 +114,7 @@ Discord ──► SQLite (WAL) ──► GroupQueue ──┬──► Owner (ho
|
||||
|
||||
### 요구사항
|
||||
|
||||
- Linux(Ubuntu 22.04+) 또는 macOS
|
||||
- Linux(Ubuntu 22.04+, systemd)
|
||||
- [Bun](https://bun.sh/) 1.3+
|
||||
- Claude Code CLI
|
||||
- Codex CLI
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
<?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>com.ejclaw</string>
|
||||
<key>ProgramArguments</key>
|
||||
<array>
|
||||
<string>{{NODE_PATH}}</string>
|
||||
<string>{{PROJECT_ROOT}}/dist/index.js</string>
|
||||
</array>
|
||||
<key>WorkingDirectory</key>
|
||||
<string>{{PROJECT_ROOT}}</string>
|
||||
<key>RunAtLoad</key>
|
||||
<true/>
|
||||
<key>KeepAlive</key>
|
||||
<true/>
|
||||
<key>EnvironmentVariables</key>
|
||||
<dict>
|
||||
<key>PATH</key>
|
||||
<string>{{HOME}}/.local/bin:/usr/local/bin:/usr/bin:/bin</string>
|
||||
<key>HOME</key>
|
||||
<string>{{HOME}}</string>
|
||||
<key>ASSISTANT_NAME</key>
|
||||
<string>Andy</string>
|
||||
</dict>
|
||||
<key>StandardOutPath</key>
|
||||
<string>{{PROJECT_ROOT}}/logs/ejclaw.log</string>
|
||||
<key>StandardErrorPath</key>
|
||||
<string>{{PROJECT_ROOT}}/logs/ejclaw.error.log</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,113 +0,0 @@
|
||||
# Repo Tokens
|
||||
|
||||
A GitHub Action that calculates the size of your codebase in terms of tokens and updates a badge in your README.
|
||||
|
||||
<p>
|
||||
<img src="examples/green.svg" alt="tokens 12.4k">
|
||||
<img src="examples/yellow-green.svg" alt="tokens 74.8k">
|
||||
<img src="examples/yellow.svg" alt="tokens 120k">
|
||||
<img src="examples/red.svg" alt="tokens 158k">
|
||||
</p>
|
||||
|
||||
## Usage
|
||||
|
||||
```yaml
|
||||
- uses: phj1081/EJClaw/repo-tokens@v1
|
||||
with:
|
||||
include: 'src/**/*.ts'
|
||||
exclude: 'src/**/*.test.ts'
|
||||
```
|
||||
|
||||
This counts tokens using [tiktoken](https://github.com/openai/tiktoken) and writes the result between HTML comment markers in your README:
|
||||
|
||||
The badge color reflects what percentage of an LLMs context window the codebase fills (context window size is configurable, defaults to 200k which is the size of Claude Opus). Green for under 30%, yellow-green for 30%-50%, yellow for 50%-70%, red for 70%+.
|
||||
|
||||
## Why
|
||||
|
||||
Small codebases were always a good thing. With coding agents, there's now a huge advantage to having a codebase small enough that an agent can hold the full thing in context.
|
||||
|
||||
This badge gives some indication of how easy it will be to work with an agent on the codebase, and will hopefully be a visual reminder to avoid bloat.
|
||||
|
||||
## Examples
|
||||
|
||||
Repos using repo-tokens:
|
||||
|
||||
| Repo | Badge |
|
||||
|------|-------|
|
||||
| [EJClaw](https://github.com/phj1081/EJClaw) |  |
|
||||
|
||||
### Full workflow example
|
||||
|
||||
```yaml
|
||||
name: Update token count
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ['src/**']
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
update-tokens:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
|
||||
- uses: phj1081/EJClaw/repo-tokens@v1
|
||||
id: tokens
|
||||
with:
|
||||
include: 'src/**/*.ts'
|
||||
exclude: 'src/**/*.test.ts'
|
||||
badge-path: '.github/badges/tokens.svg'
|
||||
|
||||
- name: Commit if changed
|
||||
run: |
|
||||
git add README.md .github/badges/tokens.svg
|
||||
git diff --cached --quiet && exit 0
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git commit -m "docs: update token count to ${{ steps.tokens.outputs.badge }}"
|
||||
git push
|
||||
```
|
||||
|
||||
### README setup
|
||||
|
||||
Add markers where you want the token count text to appear:
|
||||
|
||||
```html
|
||||
<!-- token-count --><!-- /token-count -->
|
||||
```
|
||||
|
||||
The action replaces everything between the markers with the token count.
|
||||
|
||||
## Inputs
|
||||
|
||||
| Input | Default | Description |
|
||||
|-------|---------|-------------|
|
||||
| `include` | *required* | Glob patterns for files to count (space-separated) |
|
||||
| `exclude` | `''` | Glob patterns to exclude (space-separated) |
|
||||
| `context-window` | `200000` | Context window size for percentage calculation |
|
||||
| `readme` | `README.md` | Path to README file |
|
||||
| `encoding` | `cl100k_base` | Tiktoken encoding name |
|
||||
| `marker` | `token-count` | HTML comment marker name |
|
||||
| `badge-path` | `''` | Path to write SVG badge (empty = no SVG) |
|
||||
|
||||
## Outputs
|
||||
|
||||
| Output | Description |
|
||||
|--------|-------------|
|
||||
| `tokens` | Total token count (e.g., `34940`) |
|
||||
| `percentage` | Percentage of context window (e.g., `17`) |
|
||||
| `badge` | The formatted text that was inserted (e.g., `34.9k tokens · 17% of context window`) |
|
||||
|
||||
## How it works
|
||||
|
||||
Composite GitHub Action. Installs tiktoken, runs ~60 lines of inline Python. Takes about 10 seconds.
|
||||
|
||||
The action counts tokens and updates the README but does not commit. Your workflow decides the git strategy.
|
||||
@@ -1,186 +0,0 @@
|
||||
name: Repo Tokens
|
||||
description: Count codebase tokens with tiktoken and update a README badge
|
||||
|
||||
inputs:
|
||||
include:
|
||||
description: 'Glob patterns for files to count (space-separated)'
|
||||
required: true
|
||||
exclude:
|
||||
description: 'Glob patterns to exclude (space-separated)'
|
||||
required: false
|
||||
default: ''
|
||||
context-window:
|
||||
description: 'Context window size for percentage calculation'
|
||||
required: false
|
||||
default: '200000'
|
||||
readme:
|
||||
description: 'Path to README file'
|
||||
required: false
|
||||
default: 'README.md'
|
||||
encoding:
|
||||
description: 'Tiktoken encoding name'
|
||||
required: false
|
||||
default: 'cl100k_base'
|
||||
marker:
|
||||
description: 'HTML comment marker name'
|
||||
required: false
|
||||
default: 'token-count'
|
||||
badge-path:
|
||||
description: 'Path to write SVG badge (empty = no SVG)'
|
||||
required: false
|
||||
default: ''
|
||||
|
||||
outputs:
|
||||
tokens:
|
||||
description: 'Total token count'
|
||||
value: ${{ steps.count.outputs.tokens }}
|
||||
percentage:
|
||||
description: 'Percentage of context window'
|
||||
value: ${{ steps.count.outputs.percentage }}
|
||||
badge:
|
||||
description: 'Badge text that was inserted'
|
||||
value: ${{ steps.count.outputs.badge }}
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Install tiktoken
|
||||
shell: bash
|
||||
run: pip install tiktoken
|
||||
|
||||
- name: Count tokens and update README
|
||||
id: count
|
||||
shell: python
|
||||
env:
|
||||
INPUT_INCLUDE: ${{ inputs.include }}
|
||||
INPUT_EXCLUDE: ${{ inputs.exclude }}
|
||||
INPUT_CONTEXT_WINDOW: ${{ inputs.context-window }}
|
||||
INPUT_README: ${{ inputs.readme }}
|
||||
INPUT_ENCODING: ${{ inputs.encoding }}
|
||||
INPUT_MARKER: ${{ inputs.marker }}
|
||||
INPUT_BADGE_PATH: ${{ inputs.badge-path }}
|
||||
run: |
|
||||
import glob, os, re, tiktoken
|
||||
|
||||
include_patterns = os.environ["INPUT_INCLUDE"].split()
|
||||
exclude_patterns = os.environ["INPUT_EXCLUDE"].split()
|
||||
context_window = int(os.environ["INPUT_CONTEXT_WINDOW"])
|
||||
readme_path = os.environ["INPUT_README"]
|
||||
encoding_name = os.environ["INPUT_ENCODING"]
|
||||
marker = os.environ["INPUT_MARKER"]
|
||||
badge_path = os.environ.get("INPUT_BADGE_PATH", "").strip()
|
||||
|
||||
# Expand globs
|
||||
included = set()
|
||||
for pattern in include_patterns:
|
||||
included.update(glob.glob(pattern, recursive=True))
|
||||
|
||||
excluded = set()
|
||||
for pattern in exclude_patterns:
|
||||
excluded.update(glob.glob(pattern, recursive=True))
|
||||
|
||||
files = sorted(included - excluded)
|
||||
files = [f for f in files if os.path.isfile(f)]
|
||||
|
||||
# Count tokens
|
||||
enc = tiktoken.get_encoding(encoding_name)
|
||||
total = 0
|
||||
for path in files:
|
||||
try:
|
||||
with open(path, "r", encoding="utf-8", errors="ignore") as f:
|
||||
total += len(enc.encode(f.read()))
|
||||
except Exception as e:
|
||||
print(f"Skipping {path}: {e}")
|
||||
|
||||
# Format
|
||||
if total >= 100000:
|
||||
display = f"{round(total / 1000)}k"
|
||||
elif total >= 1000:
|
||||
display = f"{total / 1000:.1f}k"
|
||||
else:
|
||||
display = str(total)
|
||||
|
||||
pct = round(total / context_window * 100)
|
||||
badge = f"{display} tokens \u00b7 {pct}% of context window"
|
||||
|
||||
print(f"Files: {len(files)}, Tokens: {total}, Badge: {badge}")
|
||||
|
||||
# Update README (text between markers)
|
||||
marker_re = re.compile(
|
||||
rf"(<!--\s*{re.escape(marker)}\s*-->).*?(<!--\s*/{re.escape(marker)}\s*-->)",
|
||||
re.DOTALL,
|
||||
)
|
||||
|
||||
with open(readme_path, "r", encoding="utf-8") as f:
|
||||
content = f.read()
|
||||
|
||||
repo_tokens_url = "https://github.com/phj1081/EJClaw/tree/main/repo-tokens"
|
||||
linked_badge = f'<a href="{repo_tokens_url}">{badge}</a>'
|
||||
new_content = marker_re.sub(rf"\1{linked_badge}\2", content)
|
||||
|
||||
if new_content != content:
|
||||
with open(readme_path, "w", encoding="utf-8") as f:
|
||||
f.write(new_content)
|
||||
print("README updated")
|
||||
else:
|
||||
print("No change to README")
|
||||
|
||||
# Generate SVG badge
|
||||
if badge_path:
|
||||
label_text = "tokens"
|
||||
value_text = display
|
||||
full_desc = f"{display} tokens, {pct}% of context window"
|
||||
|
||||
cw = 7.0
|
||||
label_w = round(len(label_text) * cw) + 10
|
||||
value_w = round(len(value_text) * cw) + 10
|
||||
total_w = label_w + value_w
|
||||
|
||||
if pct < 30:
|
||||
color = "#4c1"
|
||||
elif pct < 50:
|
||||
color = "#97ca00"
|
||||
elif pct < 70:
|
||||
color = "#dfb317"
|
||||
else:
|
||||
color = "#e05d44"
|
||||
|
||||
lx = label_w // 2
|
||||
vx = label_w + value_w // 2
|
||||
|
||||
repo_tokens_url = "https://github.com/phj1081/EJClaw/tree/main/repo-tokens"
|
||||
|
||||
svg = f'''<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="{total_w}" height="20" role="img" aria-label="{full_desc}">
|
||||
<title>{full_desc}</title>
|
||||
<linearGradient id="s" x2="0" y2="100%">
|
||||
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
|
||||
<stop offset="1" stop-opacity=".1"/>
|
||||
</linearGradient>
|
||||
<clipPath id="r">
|
||||
<rect width="{total_w}" height="20" rx="3" fill="#fff"/>
|
||||
</clipPath>
|
||||
<a xlink:href="{repo_tokens_url}">
|
||||
<g clip-path="url(#r)">
|
||||
<rect width="{label_w}" height="20" fill="#555"/>
|
||||
<rect x="{label_w}" width="{value_w}" height="20" fill="{color}"/>
|
||||
<rect width="{total_w}" height="20" fill="url(#s)"/>
|
||||
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
|
||||
<text aria-hidden="true" x="{lx}" y="15" fill="#010101" fill-opacity=".3">{label_text}</text>
|
||||
<text x="{lx}" y="14">{label_text}</text>
|
||||
<text aria-hidden="true" x="{vx}" y="15" fill="#010101" fill-opacity=".3">{value_text}</text>
|
||||
<text x="{vx}" y="14">{value_text}</text>
|
||||
</g>
|
||||
</g>
|
||||
</a>
|
||||
</svg>'''
|
||||
|
||||
os.makedirs(os.path.dirname(badge_path) or ".", exist_ok=True)
|
||||
with open(badge_path, "w", encoding="utf-8") as f:
|
||||
f.write(svg)
|
||||
print(f"Badge SVG written to {badge_path}")
|
||||
|
||||
# Set outputs
|
||||
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
|
||||
f.write(f"tokens={total}\n")
|
||||
f.write(f"percentage={pct}\n")
|
||||
f.write(f"badge={badge}\n")
|
||||
@@ -1,23 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="97" height="20" role="img" aria-label="38.8k tokens, 19% of context window">
|
||||
<title>38.8k tokens, 19% of context window</title>
|
||||
<linearGradient id="s" x2="0" y2="100%">
|
||||
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
|
||||
<stop offset="1" stop-opacity=".1"/>
|
||||
</linearGradient>
|
||||
<clipPath id="r">
|
||||
<rect width="97" height="20" rx="3" fill="#fff"/>
|
||||
</clipPath>
|
||||
<a xlink:href="https://github.com/phj1081/EJClaw/tree/main/repo-tokens">
|
||||
<g clip-path="url(#r)">
|
||||
<rect width="52" height="20" fill="#555"/>
|
||||
<rect x="52" width="45" height="20" fill="#4c1"/>
|
||||
<rect width="97" height="20" fill="url(#s)"/>
|
||||
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
|
||||
<text aria-hidden="true" x="26" y="15" fill="#010101" fill-opacity=".3">tokens</text>
|
||||
<text x="26" y="14">tokens</text>
|
||||
<text aria-hidden="true" x="74" y="15" fill="#010101" fill-opacity=".3">38.8k</text>
|
||||
<text x="74" y="14">38.8k</text>
|
||||
</g>
|
||||
</g>
|
||||
</a>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1.1 KiB |
@@ -1,14 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="97" height="20" role="img" aria-label="12.4k tokens">
|
||||
<title>12.4k tokens</title>
|
||||
<linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient>
|
||||
<clipPath id="r"><rect width="97" height="20" rx="3"/></clipPath>
|
||||
<g clip-path="url(#r)">
|
||||
<rect width="52" height="20" fill="#555"/>
|
||||
<rect x="52" width="45" height="20" fill="#4c1"/>
|
||||
<rect width="97" height="20" fill="url(#s)"/>
|
||||
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
|
||||
<text x="26" y="15" fill="#010101" fill-opacity=".3">tokens</text><text x="26" y="14">tokens</text>
|
||||
<text x="74" y="15" fill="#010101" fill-opacity=".3">12.4k</text><text x="74" y="14">12.4k</text>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 867 B |
@@ -1,14 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="90" height="20" role="img" aria-label="158k tokens">
|
||||
<title>158k tokens</title>
|
||||
<linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient>
|
||||
<clipPath id="r"><rect width="90" height="20" rx="3"/></clipPath>
|
||||
<g clip-path="url(#r)">
|
||||
<rect width="52" height="20" fill="#555"/>
|
||||
<rect x="52" width="38" height="20" fill="#e05d44"/>
|
||||
<rect width="90" height="20" fill="url(#s)"/>
|
||||
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
|
||||
<text x="26" y="15" fill="#010101" fill-opacity=".3">tokens</text><text x="26" y="14">tokens</text>
|
||||
<text x="71" y="15" fill="#010101" fill-opacity=".3">158k</text><text x="71" y="14">158k</text>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 866 B |
@@ -1,14 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="97" height="20" role="img" aria-label="74.8k tokens">
|
||||
<title>74.8k tokens</title>
|
||||
<linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient>
|
||||
<clipPath id="r"><rect width="97" height="20" rx="3"/></clipPath>
|
||||
<g clip-path="url(#r)">
|
||||
<rect width="52" height="20" fill="#555"/>
|
||||
<rect x="52" width="45" height="20" fill="#97ca00"/>
|
||||
<rect width="97" height="20" fill="url(#s)"/>
|
||||
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
|
||||
<text x="26" y="15" fill="#010101" fill-opacity=".3">tokens</text><text x="26" y="14">tokens</text>
|
||||
<text x="74" y="15" fill="#010101" fill-opacity=".3">74.8k</text><text x="74" y="14">74.8k</text>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 870 B |
@@ -1,14 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="90" height="20" role="img" aria-label="120k tokens">
|
||||
<title>120k tokens</title>
|
||||
<linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient>
|
||||
<clipPath id="r"><rect width="90" height="20" rx="3"/></clipPath>
|
||||
<g clip-path="url(#r)">
|
||||
<rect width="52" height="20" fill="#555"/>
|
||||
<rect x="52" width="38" height="20" fill="#dfb317"/>
|
||||
<rect width="90" height="20" fill="url(#s)"/>
|
||||
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
|
||||
<text x="26" y="15" fill="#010101" fill-opacity=".3">tokens</text><text x="26" y="14">tokens</text>
|
||||
<text x="71" y="15" fill="#010101" fill-opacity=".3">120k</text><text x="71" y="14">120k</text>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 866 B |
@@ -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');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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';
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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[] = [];
|
||||
|
||||
|
||||
@@ -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', {
|
||||
|
||||
@@ -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' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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),
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -117,7 +117,6 @@ describe('verify state helpers', () => {
|
||||
kind: 'primary',
|
||||
name: 'ejclaw',
|
||||
description: 'EJClaw',
|
||||
launchdLabel: 'com.ejclaw',
|
||||
logName: 'ejclaw',
|
||||
},
|
||||
];
|
||||
|
||||
@@ -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');
|
||||
|
||||
Reference in New Issue
Block a user