Skip to content

feat(cli): manage Linux Runtime Host services - #3205

Merged
M4n5ter merged 3 commits into
mainfrom
feat/runtime-host-linux-service
Aug 19, 2026
Merged

feat(cli): manage Linux Runtime Host services#3205
M4n5ter merged 3 commits into
mainfrom
feat/runtime-host-linux-service

Conversation

@M4n5ter

@M4n5ter M4n5ter commented Aug 18, 2026

Copy link
Copy Markdown
Member

Summary

English

Add a managed Runtime Host service lifecycle to the CLI so a Linux Host can remain available after its SSH session ends.

The lifecycle contract, persisted configuration, normalized status, and clean-uninstall behavior are platform-neutral. Linux supplies a systemd user backend; a future macOS LaunchAgent backend can reuse the same CLI and lifecycle semantics. Installation pins the exact Node.js and Maka CLI paths, binds the WebSocket listener to loopback, and preserves the existing port and project roots on reinstall. Uninstall removes the managed unit and configuration while retaining the State Root and user data.

Refs #2522

中文

为 CLI 增加 managed Runtime Host service lifecycle,使 Linux Host 能在 SSH 会话结束后继续运行。

Lifecycle contract、持久配置、归一化状态和 clean uninstall 均保持平台无关;Linux 仅提供 systemd user backend,未来 macOS LaunchAgent backend 可以复用相同的 CLI 与 lifecycle 语义。安装会固定精确的 Node.js 与 Maka CLI 路径、只监听 loopback,并在重复安装时保留已有端口和 Project roots。卸载会移除托管 unit 与配置,同时保留 State Root 和用户数据。

Refs #2522

Verification

English
  • npm --workspace maka-agent test — 269 tests passed
  • npm run build — passed
  • npm run typecheck — all workspaces passed after a clean dependency install and build
  • npm run lint and npm run format:check — passed
  • CLI release pack and offline smoke validation — passed
  • Packaged CLI installed, restarted, inspected, and cleanly uninstalled a real systemd user service; the service survived the setup SSH session and uninstall retained the State Root
中文
  • npm --workspace maka-agent test — 269 项测试通过
  • npm run build — 通过
  • npm run typecheck — 干净安装依赖并构建后,所有 workspace 通过
  • npm run lintnpm run format:check — 通过
  • CLI release pack 与离线 smoke validation — 通过
  • 使用发布形态 CLI 在真实 systemd user 环境完成安装、重启、状态查询和干净卸载;service 不依赖 setup SSH 会话存活,卸载后 State Root 保留

AI use

Select exactly one:

  • No generative tool made a substantive contribution
  • Generative tooling made a substantive contribution

Tool(s) and scope: Codex assisted with implementation, tests, documentation, and validation under maintainer direction. The commit includes the required Generated-by: Codex trailer.

Checklist

  • Tests cover the change and fail without it
  • Lint, format, typecheck and the affected suites pass locally

Does this PR entail a change in behavior?

  • Yes — described under Summary above
  • No

@coderabbitai

coderabbitai Bot commented Aug 18, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Problem solved

This PR adds managed Runtime Host service lifecycle support to the CLI.

Users can install, inspect, start, stop, restart, and uninstall a Runtime Host service. Linux uses a systemd user service, so the Runtime Host can continue after an SSH session ends.

The service:

  • Pins the Node.js and Maka CLI executable paths.
  • Binds the WebSocket listener to loopback.
  • Preserves ports and project roots during reinstall.
  • Persists normalized configuration and status.
  • Removes the managed unit and configuration during uninstall.
  • Retains the State Root and user data during uninstall.

The PR also adds English and Chinese documentation and updates installation and uninstall guidance.

Source of truth and solution scope

The PR extends the existing CLI command path and Runtime Host configuration model. It does not create a parallel CLI.

The platform-neutral service manager owns lifecycle rules, validation, persistence, locking, readiness checks, rollback, and uninstall behavior. The Linux systemd backend owns systemd-specific operations. This separation provides one lifecycle authority and isolates platform-specific behavior.

The solution is the smallest coherent design supported by the current evidence. The manager, backend, CLI entry point, validation, persistence, and tests are necessary for the stated lifecycle contract and clean-uninstall behavior. The XDG configuration fallback supports reliable configuration resolution for the managed service.

Simplification opportunities

No clear deletion or simplification is supported by the current evidence.

The tests cover parsing, lifecycle actions, reinstall behavior, configuration repair, argument escaping, prerequisite errors, rollback, operation serialization, and State Root retention. Removing these tests would weaken regression coverage.

Dependency injection and backend overrides provide test seams without changing the production path. They should remain unless equivalent existing seams are identified.

Validation and concrete risks

Reported validation covered:

  • Tests.
  • Build and type checking.
  • Linting and formatting.
  • Release packaging.
  • Offline smoke tests.
  • Real systemd user-service installation.
  • Service restart and inspection.
  • Clean uninstallation.

The final status of required checks is unverified from direct repository evidence.

Concrete risks include:

  • Incorrect systemd argument escaping could change service startup behavior.
  • Disabled user lingering could prevent persistence after logout.
  • Path resolution or executable validation could reject valid packaged installations.
  • Reinstall logic could overwrite ports or project roots.
  • Uninstall logic could remove user data if State Root boundaries regress.
  • Configuration repair could alter invalid persisted state.
  • New CLI commands and exported types expand the public contract.
  • Release packaging must include the management modules and exact launch paths.
  • Systemd command execution and service replacement affect operational and security behavior.

Complexity delta

The PR adds:

  • One platform-neutral lifecycle authority.
  • One Linux systemd backend.
  • Explicit service states and backend status.
  • Persisted managed-service configuration.
  • Install, status, start, stop, restart, and uninstall branches.
  • Validation, configuration repair, locking, readiness polling, and rollback paths.
  • Service-management CLI options and exported types.
  • Systemd fixtures and lifecycle tests.
  • XDG configuration-home resolution.

The PR removes no existing authority or lifecycle path. It avoids duplicating lifecycle rules inside the systemd backend, but it adds configuration, public API surface, operational branches, and test-maintenance burden.

Total maintenance complexity increases. The increase is justified by the platform-neutral lifecycle contract, clean-uninstall requirements, rollback behavior, and backend separation. The current evidence does not show a reduction in overall complexity.

Review-relevant risks

The diff changes user-visible CLI behavior, documentation, service persistence, uninstall behavior, configuration resolution, and the exported TypeScript API. Material changes in these areas require independent human review under repository policy.

The diff adds Linux systemd service installation, process execution, executable-path pinning, loopback binding, and service replacement. These changes affect security and operational behavior. Material changes in these areas require independent human review under repository policy.

The diff affects release packaging and installation paths. Material changes in releases require independent human review under repository policy.

The person performing the merge reviews the final diff. A maintainer makes the final determination.

Walkthrough

The CLI now supports persistent Linux systemd user services for the Runtime Host. It validates and stores service configuration, manages lifecycle actions, verifies readiness, supports rollback, reports structured errors, and documents installation and removal behavior.

Changes

Managed Runtime Host service

Layer / File(s) Summary
Service configuration and lifecycle manager
packages/cli/src/runtime-host-service-manager.ts
Adds typed configuration, validation, durable persistence, loopback port allocation, readiness polling, status reporting, lifecycle orchestration, locking, and rollback.
systemd user-service backend
packages/cli/src/runtime-host-systemd-service.ts
Adds systemd user-service installation, status handling, lifecycle commands, lingering checks, unit rendering, launch validation, safe argument quoting, restoration, and uninstall cleanup.
CLI command and output integration
packages/cli/src/runtime-host-cli.ts, packages/cli/src/runtime-host-service-management-command.ts, packages/cli/src/cli-core.ts
Adds the runtime-host service command, validates service options, dispatches management actions, selects the Linux backend, and supports human-readable and JSON output.
Lifecycle validation and operational documentation
packages/cli/src/__tests__/runtime-host-service-manager.test.ts, docs/runtime-host-remote-access.md, docs/runtime-host-remote-access.zh-CN.md, packages/cli/README.md, packages/cli/README.zh-CN.md
Tests parsing, lifecycle operations, persistence, rollback, cleanup, escaping, errors, and locking. Documents installation, replacement, status checks, uninstall steps, and retained data.
Linux configuration path resolution
packages/storage/src/workspace-root.ts, packages/storage/src/__tests__/workspace-root.test.ts
Resolves absolute XDG_CONFIG_HOME values and falls back to <homeDir>/.config for unset, empty, or relative values.

Estimated code review effort: 4 (Complex) | ~45 minutes

Merge Risk: 🟡 Moderate · up to fc93a

The CLI’s managed-service status path can report an installed service as not installed when systemd metadata is incomplete, and executable paths containing spaces are not fully protected by tests, which could allow service startup failures to escape. Merge should wait for these bounded correctness risks to be fixed or explicitly accepted.

Sequence Diagram(s)

sequenceDiagram
  participant RuntimeHostCLI
  participant ServiceManagementCLI
  participant ServiceManager
  participant SystemdUserService
  participant Filesystem

  RuntimeHostCLI->>ServiceManagementCLI: Parse service action and options
  ServiceManagementCLI->>ServiceManager: Manage service configuration
  ServiceManager->>SystemdUserService: Validate and execute lifecycle action
  SystemdUserService->>Filesystem: Write or remove unit file
  SystemdUserService-->>ServiceManager: Return backend status
  ServiceManager->>Filesystem: Persist or remove managed configuration
  ServiceManager-->>ServiceManagementCLI: Return structured result
  ServiceManagementCLI-->>RuntimeHostCLI: Print human-readable or JSON output
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: adding Linux Runtime Host service management to the CLI.
Description check ✅ Passed The description includes the required summary, verification, AI use, checklist, behavior change, and issue reference details.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Ai Use Disclosure ✅ Passed The description selects substantive generative use and names Codex and its scope; all three PR commits contain standalone Generated-by: Codex trailers.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/runtime-host-linux-service

Comment @coderabbitai help to get the list of available commands.

@M4n5ter
M4n5ter marked this pull request as ready for review August 18, 2026 13:09
@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Add managed Linux Runtime Host service lifecycle

✨ Enhancement 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Add install, status, start, stop, restart, and uninstall commands for managed Runtime Hosts.
• Persist loopback configuration and pinned launch paths across safe, idempotent reinstalls.
• Add systemd user integration, lifecycle tests, and bilingual operational guidance.
Diagram

sequenceDiagram
  actor User
  participant CLI as Maka CLI
  participant Manager as Lifecycle Manager
  participant Config as Service Config
  participant Backend as systemd Backend
  participant Systemd as systemd User
  User->>CLI: service action
  CLI->>Manager: validated request
  Manager->>Config: read or persist config
  Manager->>Backend: lifecycle operation
  Backend->>Systemd: systemctl or loginctl
  Systemd-->>Backend: unit status
  Backend-->>Manager: normalized status
  Manager-->>CLI: lifecycle result
  CLI-->>User: human or JSON output
Loading
High-Level Assessment

The platform-neutral lifecycle manager with a dedicated systemd user backend is the strongest approach. It isolates Linux-specific behavior while preserving reusable configuration and status contracts for a future LaunchAgent backend; direct systemd handling in the command layer would increase coupling, while a system-wide service would require elevated permissions and complicate per-user data ownership.

Files changed (10) +1288 / -4

Enhancement (5) +971 / -2
cli-core.tsRoute managed service commands through the CLI +30/-1

Route managed service commands through the CLI

• Extends CLI help with managed Runtime Host actions and install options. Dispatches parsed requests to the service management adapter with resolved Node, CLI, data-root, and package metadata.

packages/cli/src/cli-core.ts

runtime-host-cli.tsParse the managed service command surface +95/-1

Parse the managed service command surface

• Adds parsing for install, status, start, stop, restart, and uninstall actions. Restricts configuration flags to installation and validates project roots, ports, and WebSocket paths.

packages/cli/src/runtime-host-cli.ts

runtime-host-service-management-command.tsAdapt service lifecycle results for CLI output +86/-0

Adapt service lifecycle results for CLI output

• Connects lifecycle requests to the platform backend and emits human-readable or versioned JSON results. Selects systemd on Linux and returns structured errors for unsupported platforms and failed prerequisites.

packages/cli/src/runtime-host-service-management-command.ts

runtime-host-service-manager.tsImplement platform-neutral service lifecycle management +396/-0

Implement platform-neutral service lifecycle management

• Defines the backend contract, persisted configuration schema, normalized status model, and lifecycle orchestration. Adds atomic configuration writes, validation, loopback port allocation, reinstall preservation, and verified uninstall while retaining the State Root.

packages/cli/src/runtime-host-service-manager.ts

runtime-host-systemd-service.tsImplement the systemd user service backend +364/-0

Implement the systemd user service backend

• Renders and manages a hardened systemd user unit using pinned Node and CLI paths. Verifies systemd availability and user lingering, normalizes unit status, safely quotes arguments, validates launch files, and removes all managed unit state during uninstall.

packages/cli/src/runtime-host-systemd-service.ts

Tests (1) +276 / -0
runtime-host-service-manager.test.tsTest managed service lifecycle and systemd safety +276/-0

Test managed service lifecycle and systemd safety

• Covers command parsing, install and reinstall preservation, normalized status, idempotent uninstall, retained state roots, corrupt-config repair, systemd argument escaping, and stable JSON errors. Uses a fake systemd backend to verify lifecycle calls without controlling real services.

packages/cli/src/tests/runtime-host-service-manager.test.ts

Documentation (4) +41 / -2
runtime-host-remote-access.mdDocument persistent Linux Runtime Host setup +16/-0

Document persistent Linux Runtime Host setup

• Adds commands for installing and inspecting a managed Runtime Host on Linux. Explains pinned launch paths, reinstall preservation, lingering requirements, and data-retaining uninstall behavior.

docs/runtime-host-remote-access.md

runtime-host-remote-access.zh-CN.mdDocument persistent Linux setup in Chinese +15/-0

Document persistent Linux setup in Chinese

• Adds the Chinese guidance for managed Runtime Host installation, status inspection, reinstall semantics, lingering prerequisites, and clean uninstall.

docs/runtime-host-remote-access.zh-CN.md

README.mdAdd managed service uninstall guidance +5/-1

Add managed service uninstall guidance

• Updates package removal instructions to uninstall the Linux systemd user service first. Clarifies that service and package removal retain user profile data.

packages/cli/README.md

README.zh-CN.mdAdd Chinese managed service uninstall guidance +5/-1

Add Chinese managed service uninstall guidance

• Documents the required managed-service cleanup before removing the global CLI package. Confirms that model connections, credentials, sessions, and artifacts remain intact.

packages/cli/README.zh-CN.md

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4


ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 9ea4f8f8-7283-4513-8372-416623e18876

📥 Commits

Reviewing files that changed from the base of the PR and between eeb3ce3 and 8f9ea9f.

📒 Files selected for processing (10)
  • docs/runtime-host-remote-access.md
  • docs/runtime-host-remote-access.zh-CN.md
  • packages/cli/README.md
  • packages/cli/README.zh-CN.md
  • packages/cli/src/__tests__/runtime-host-service-manager.test.ts
  • packages/cli/src/cli-core.ts
  • packages/cli/src/runtime-host-cli.ts
  • packages/cli/src/runtime-host-service-management-command.ts
  • packages/cli/src/runtime-host-service-manager.ts
  • packages/cli/src/runtime-host-systemd-service.ts

Included review availability: Your plan includes up to 3 reviews per rolling hour; 2 remain after this review.

Comment thread packages/cli/src/runtime-host-service-manager.ts
Comment thread packages/cli/src/runtime-host-systemd-service.ts
Comment thread packages/cli/src/runtime-host-systemd-service.ts Outdated
Comment thread packages/cli/src/runtime-host-systemd-service.ts
@qodo-code-review

qodo-code-review Bot commented Aug 18, 2026

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Systemd failures become not-installed ✓ Resolved 🐞 Bug ≡ Correctness
Description
readSystemdStatus() treats every nonzero systemctl show result without a parsed LoadState as
not-found. A disconnected user bus, permission failure, or other manager error therefore makes
status succeed with not_installed instead of reporting service_manager_operation_failed.
Code

packages/cli/src/runtime-host-systemd-service.ts[R177-180]

+  const properties = parseProperties(result.stdout);
+  const loadState = properties.get('LoadState') ?? (result.exitCode === 0 ? 'loaded' : 'not-found');
+  if (result.exitCode !== 0 && loadState !== 'not-found') {
+    throw managerError('Reading Runtime Host service status failed', result);
Relevance

●●● Strong

This is a concrete error-classification bug: failed manager queries are incorrectly converted into
not-installed status.

PR-#3169

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The fallback maps a nonzero exit to not-found, and the next condition only throws when the value
is not not-found; consequently an empty failed response cannot reach the error path. The backend
exposes this directly through status without running the install preflight that otherwise detects
an unavailable user manager.

packages/cli/src/runtime-host-systemd-service.ts[168-188]
packages/cli/src/runtime-host-systemd-service.ts[54-58]
packages/cli/src/runtime-host-systemd-service.ts[74-74]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description

Distinguish an explicitly reported `LoadState=not-found` from an arbitrary failed or empty `systemctl show` response. Unexpected nonzero results must become a normalized service-manager error rather than a successful not-installed status.

## Issue Context

The current fallback synthesizes `not-found` from any nonzero exit code, making the following error check unreachable for output that lacks `LoadState`. Reuse `managerError()` for nonzero responses unless systemd explicitly identifies the unit as absent, and add coverage for an unavailable user bus or equivalent empty failed response.

## Fix Focus Areas

- packages/cli/src/runtime-host-systemd-service.ts[168-188]
- packages/cli/src/__tests__/runtime-host-service-manager.test.ts[197-256]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Failed reinstall desynchronizes configuration ✓ Resolved 🐞 Bug ☼ Reliability
Description
The install path commits the new JSON configuration before systemd validates, reloads, enables, or
restarts the new unit. If any backend step fails, status reports the new root, port, and launch
paths even though the old process or unit may still be active, violating the reinstall and
normalized-status contract.
Code

packages/cli/src/runtime-host-service-manager.ts[R128-131]

+    const previous = await readServiceConfigForRepair(configPath);
+    const config = await prepareServiceConfig(input, previous, deps);
+    await writeRuntimeHostServiceFile(configPath, `${JSON.stringify(config, null, 2)}\n`, 0o600);
+    await backend.install(config);
Relevance

●●● Strong

Accepted history favors findings exposing state/config desynchronization and failure-path
inconsistencies in lifecycle code.

PR-#1587
PR-#3169

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The manager writes the new configuration before calling the backend. The backend subsequently has
multiple failure points—launch validation, unit replacement, daemon reload, enable, and
restart—while status independently combines the already-written config with systemd's state.

packages/cli/src/runtime-host-service-manager.ts[126-132]
packages/cli/src/runtime-host-systemd-service.ts[59-72]
packages/cli/src/runtime-host-service-manager.ts[251-260]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description

Make install and reinstall failure-atomic. A backend failure must not leave `runtime-host-service.json`, the on-disk unit, and the active service describing different configurations.

## Issue Context

The manager currently persists the proposed configuration before invoking the backend. Preserve the previous managed state and restore it when installation fails; simply moving the config write after `backend.install()` is insufficient because a later config-write failure would create the inverse mismatch, with a new service and stale configuration.

## Fix Focus Areas

- packages/cli/src/runtime-host-service-manager.ts[126-132]
- packages/cli/src/runtime-host-systemd-service.ts[59-72]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Install reports before readiness 🐞 Bug ≡ Correctness
Description
Because the unit uses Type=simple, systemctl restart can succeed and status can be active before
Runtime Host initialization or WebSocket binding completes. For example, installing with an occupied
port can print “installed and running” even though the listener subsequently fails and systemd
enters a restart loop.
Code

packages/cli/src/runtime-host-systemd-service.ts[146]

+    'Type=simple',
Relevance

●● Moderate

Readiness semantics are architectural and subjective; history supports reliability concerns but
lacks a matching service-readiness precedent.

PR-#3169

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The unit declares Type=simple, while install only waits for systemctl restart and then reads
process-level status. Runtime Host emits its ready event only after
startExecutionRuntimeHostService() finishes, but that event is not connected to the managed
installation result, which formats any immediately active service as installed and running.

packages/cli/src/runtime-host-systemd-service.ts[59-77]
packages/cli/src/runtime-host-systemd-service.ts[140-157]
packages/cli/src/runtime-host-service-command.ts[50-68]
packages/cli/src/runtime-host-service-management-command.ts[61-64]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description

Do not return a successful install/start result until the Runtime Host has completed initialization and bound its configured listener, or until startup definitively fails.

## Issue Context

Systemd process activity is not application readiness for a `Type=simple` unit. Reuse the Runtime Host's existing readiness concept if it can be connected to the backend; otherwise add the smallest bounded readiness check and timeout. New readiness state is necessary because neither `systemctl restart` nor the current status fields prove that the endpoint is accepting connections.

## Fix Focus Areas

- packages/cli/src/runtime-host-systemd-service.ts[59-77]
- packages/cli/src/runtime-host-systemd-service.ts[140-157]
- packages/cli/src/runtime-host-service-management-command.ts[61-64]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

4. Concurrent operations corrupt managed state ✓ Resolved 🐞 Bug ☼ Reliability
Description
Lifecycle operations have no serialization across config writes and multi-step systemd mutations.
Two installs with different options can finish with one invocation's JSON config and the other
invocation's active unit, while an overlapping uninstall can remove state created by an install.
Code

packages/cli/src/runtime-host-service-manager.ts[R124-127]

+  const configPath = resolveRuntimeHostManagedServiceConfigPath(input.clientDataRoot);
+
+  if (input.action === 'install') {
+    await backend.preflightInstall();
Relevance

●● Moderate

Concurrency and transactional ordering are plausible reliability gaps, but no close same-context
precedent establishes team acceptance.

PR-#1587
PR-#3169

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Install performs config read, preparation, config replacement, unit replacement, reload, enable, and
restart as independent asynchronous steps without a lock. Uninstall similarly mutates systemd before
deleting the config, allowing deterministic interleavings that leave the two managed files or active
process inconsistent.

packages/cli/src/runtime-host-service-manager.ts[115-162]
packages/cli/src/runtime-host-systemd-service.ts[59-108]
packages/cli/src/runtime-host-service-manager.ts[168-194]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description

Serialize install, uninstall, and other mutating lifecycle commands so their configuration and systemd operations cannot interleave.

## Issue Context

Atomic individual file replacement does not protect the larger read/write/systemd sequence. Existing systemd command serialization is insufficient because the JSON configuration is a separate authority; use a bounded per-service lock and define stale-lock handling. This introduces lock state and contention handling, which are necessary because no existing repository seam spans both authorities.

## Fix Focus Areas

- packages/cli/src/runtime-host-service-manager.ts[115-162]
- packages/cli/src/runtime-host-systemd-service.ts[59-108]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Context sources
Review mode: ⚖️ Balanced: Downgraded extended -> standard: change is below the extended eligibility bar (hunks 15/18, lines 1292/200; both must reach the floor). Router rationale: This introduces substantial new lifecycle, persisted configuration, CLI parsing, systemd integration, security-sensitive path/quoting behavior, and uninstall/state invariants across multiple independent code paths where redundant review could catch subtle defects.

Grey Divider

Tip of the day
💡 Did you know, you can show, collapse, or hide each part of a finding: code, evidence, and all

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread packages/cli/src/runtime-host-service-manager.ts Outdated
Comment thread packages/cli/src/runtime-host-systemd-service.ts
Comment thread packages/cli/src/runtime-host-systemd-service.ts

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The platform-neutral lifecycle and Linux backend are separated cleanly, and the loopback binding, exact executable paths, linger preflight, restrictive umask, and retained State Root are good boundaries. Existing reviews already cover the failure-atomic reinstall, systemd error classification, and readiness gaps, so I am not duplicating those threads.

The first-principles simplification is still one transactional launch authority: validate every path/argument first, stage config and unit together, activate, prove Runtime Host readiness, then commit—or restore the previous pair. That removes mixed states instead of adding more status heuristics. The two inline findings below are additional input-corruption/validation gaps on the latest head.

Review performed with three Codex reviewer agents and DeepSeek V4 Flash as advisory tools; I verified the novel findings against the latest head and live green CI.

中文评论

平台无关 lifecycle 与 Linux backend 的分层清晰;loopback binding、精确 executable path、linger preflight、限制性 umask 和保留 State Root 都是正确边界。已有 review 已覆盖 reinstall 非原子、systemd 错误分类和 readiness,我不重复这些线程。

更符合第一性原理的简化仍是单一、事务性的 launch authority:先验证所有 path/argument,再一起 stage config 与 unit,激活并证明 Runtime Host ready,最后 commit;任何失败恢复上一对配置。这样可直接消除 mixed state,而不是增加更多 status heuristic。以下两个行内问题是最新 head 上额外的输入破坏/验证缺口。

本次审查使用了三位 Codex reviewer agents 与 DeepSeek V4 Flash 作为辅助工具;我已依据最新 head 和实时绿色 CI 复核新增问题。

Comment thread packages/cli/src/runtime-host-systemd-service.ts
Comment thread packages/cli/src/runtime-host-service-manager.ts Outdated
@M4n5ter
M4n5ter force-pushed the feat/runtime-host-linux-service branch from 8f9ea9f to 1408c1c Compare August 18, 2026 14:07

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
packages/cli/src/__tests__/runtime-host-service-manager.test.ts (1)

101-111: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Optional: Remove the exact systemctl command snapshot.

This assertion couples the lifecycle test to internal systemctl call order and query flags. Keep assertions for required lifecycle effects, such as the unit file, enabled state, and active state.

As per path instructions, flag tests that assert implementation details.

Proposed simplification
-    assert.deepEqual(systemd.calls.slice(0, 4), [
-      ['show-environment'],
-      [
-        'show',
-        'maka-runtime-host.service',
-        '--property=LoadState,ActiveState,SubState,UnitFileState,MainPID,ExecMainStatus',
-        '--no-pager',
-      ],
-      ['daemon-reload'],
-      ['enable', 'maka-runtime-host.service'],
-    ]);

Source: Path instructions

packages/cli/src/runtime-host-systemd-service.ts (1)

294-301: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Delete the unreachable ?? 'loaded' fallback (optional).

Line 297 throws when reportedLoadState is undefined. Line 301 can therefore never apply the 'loaded' default. The leftover fallback suggests a second source of truth for loadState that no longer exists.

♻️ Proposed simplification
   const properties = parseProperties(result.stdout);
-  const reportedLoadState = properties.get('LoadState');
+  const loadState = properties.get('LoadState');
   if (
-    (result.exitCode !== 0 && reportedLoadState !== 'not-found') ||
-    reportedLoadState === undefined
+    loadState === undefined ||
+    (result.exitCode !== 0 && loadState !== 'not-found')
   ) {
     throw managerError('Reading Runtime Host service status failed', result);
   }
-  const loadState = reportedLoadState ?? 'loaded';
   return {

Source: Path instructions


ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: eb8215c0-0e2d-4df4-af22-d6d1a20a3685

📥 Commits

Reviewing files that changed from the base of the PR and between 8f9ea9f and 1408c1c.

📒 Files selected for processing (10)
  • docs/runtime-host-remote-access.md
  • docs/runtime-host-remote-access.zh-CN.md
  • packages/cli/README.md
  • packages/cli/README.zh-CN.md
  • packages/cli/src/__tests__/runtime-host-service-manager.test.ts
  • packages/cli/src/cli-core.ts
  • packages/cli/src/runtime-host-service-manager.ts
  • packages/cli/src/runtime-host-systemd-service.ts
  • packages/storage/src/__tests__/workspace-root.test.ts
  • packages/storage/src/workspace-root.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • packages/cli/src/cli-core.ts
  • packages/cli/README.zh-CN.md
  • docs/runtime-host-remote-access.md
  • packages/cli/README.md
  • docs/runtime-host-remote-access.zh-CN.md

Included review availability: Your plan includes up to 3 reviews per rolling hour; 1 remains after this review.

Comment thread packages/cli/src/runtime-host-service-manager.ts Outdated
@M4n5ter
M4n5ter requested a review from Astro-Han August 18, 2026 14:13

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The latest head resolves the earlier failure-atomic install, readiness/PID ownership, project-root canonicalization, and systemd error-reporting findings. One remaining authority collision prevents approval: the persisted config is profile/data-root scoped, but the systemd unit identity is global to the Unix user.

The first-principles fix is to give the managed service the same identity as its configuration authority. Either derive a stable unit name from the Maka profile/data-root identity, or explicitly reject service management from non-release/non-default profiles. One profile must never control another profile's process.

Reviewed with Codex using two independent review passes and DeepSeek V4 Flash as an external adversarial pass; I verified the identity paths against this exact head and current main.

中文

最新 head 已修复之前的原子安装、readiness/PID 归属、project root 规范化和 systemd 错误投影问题。仍有一个权威冲突:配置按 profile/data root 隔离,但 systemd unit 对同一 Unix 用户是全局的。

最小修复是让 service identity 与配置 authority 一致:unit 名包含稳定的 profile/data-root identity,或明确禁止非发布/非默认 profile 使用 service management。一个 profile 不能控制另一个 profile 的进程。

本次由 Codex 两轮独立审查,并使用 DeepSeek V4 Flash 做外部对抗审查;我核对了当前 head 与最新 main

Comment thread packages/cli/src/runtime-host-systemd-service.ts Outdated
Add a platform-neutral service lifecycle with a systemd user backend so a remote Host can persist beyond SSH sessions. Installation pins exact Node and CLI paths and clean uninstall retains the State Root while removing managed service state.

Generated-by: Codex
Wait for application readiness before committing replacements, and restore the prior systemd deployment and configuration when any step fails.

Serialize lifecycle operations and reject invalid roots, transient launch paths, and unavailable service-manager state.

Generated-by: Codex
Derive each platform service identity from its Client Data Root so release and development profiles cannot control one another.

Move lifecycle locking to the configuration authority and keep an unconfigured status query free of filesystem side effects.

Generated-by: Codex
@M4n5ter
M4n5ter force-pushed the feat/runtime-host-linux-service branch from 1408c1c to fc93a21 Compare August 18, 2026 15:03

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/cli/src/runtime-host-systemd-service.ts (1)

169-169: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the unnecessary network ordering (optional).

The managed WebSocket host is fixed to 127.0.0.1. The shown unit has no network dependency. Delete After=network.target to keep the unit at the smallest required behavior.

As per path instructions, choose deletion before adding behavior when it satisfies the invariant.

Source: Path instructions


ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: a74fc7c0-1525-423d-baf4-b34e8fb22a5f

📥 Commits

Reviewing files that changed from the base of the PR and between 1408c1c and fc93a21.

📒 Files selected for processing (4)
  • packages/cli/src/__tests__/runtime-host-service-manager.test.ts
  • packages/cli/src/runtime-host-service-management-command.ts
  • packages/cli/src/runtime-host-service-manager.ts
  • packages/cli/src/runtime-host-systemd-service.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/cli/src/runtime-host-service-manager.ts
  • packages/cli/src/runtime-host-service-management-command.ts

Included review availability: Your plan includes up to 3 reviews per rolling hour; 1 remains after this review.

Comment thread packages/cli/src/__tests__/runtime-host-service-manager.test.ts

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current head resolves the earlier service-identity collision and the previous lifecycle blockers. The managed unit is now scoped to the Client Data Root identity; install/reinstall is failure-atomic; readiness proves Runtime Host ownership; project roots are canonicalized and validated; and systemd failures remain failures rather than being projected as not_installed. The implementation now has one coherent configuration/service authority without adding a parallel lifecycle path.

I found no reproducible P0–P3 issue on this head. All current required checks are green.

AI-assisted review disclosure: Codex performed the final review using two independent reviewer passes and OpenCode Go DeepSeek V4 Flash (high effort) as an adversarial advisory pass. I verified the identity, rollback, readiness, and validation paths against exact head fc93a2167 and live CI.

中文评论

当前 head 已解决此前的 service identity 冲突和 lifecycle 阻塞项。managed unit 现在与 Client Data Root 身份一致;install/reinstall 具备失败原子性;readiness 会验证 Runtime Host 归属;project root 会做规范化和目录校验;systemd 失败也不会再被投影成 not_installed。整体保持了单一、连贯的配置与服务权威,没有引入并行 lifecycle。

当前 head 未发现可复现的 P0–P3 问题,所有必需检查均已通过。

AI 辅助审查说明:Codex 使用两轮独立 reviewer 审查,并以 OpenCode Go DeepSeek V4 Flash(high effort)进行对抗性辅助审查;我已针对精确 head fc93a2167 与实时 CI 复核 identity、rollback、readiness 和 validation 路径。

@M4n5ter
M4n5ter merged commit 8ea593a into main Aug 19, 2026
18 checks passed
@M4n5ter
M4n5ter deleted the feat/runtime-host-linux-service branch August 19, 2026 01:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants