Skip to content

feat(gateway): idempotent start, non-interactive stop guard, unified lifecycle audit - #110323

Merged
steipete merged 5 commits into
mainfrom
feat/gateway-lifecycle-guards
Jul 18, 2026
Merged

steipete merged 5 commits into
mainfrom
feat/gateway-lifecycle-guards

Conversation

@steipete

Copy link
Copy Markdown
Contributor

Summary

Agents (and scripts) have been fighting over operators' running gateways: gateway start on a loaded service silently restarted it, non-interactive gateway stop could bootout a production service or SIGTERM a dev gateway it never started, and gateway run --force killed whatever held the port. Most restarts also bypassed the gateway-restart.log audit trail.

Changes

  • gateway start is now idempotent: loaded + running -> "already running (pid N)", exit 0. No hidden restart.
  • gateway stop in a non-interactive shell requires --force; the refusal teaches the isolated-dev-gateway path (run --dev / --profile + free port). Interactive behavior unchanged. Applies to managed bootout and the unmanaged port-SIGTERM fallback. The system-agent approval flow supplies force (its approval gate is the consent).
  • gateway run --force in a non-interactive shell refuses to kill a verified existing gateway listener, with per-signal revalidation (no check-then-kill race); fuser fallback resolves and validates concrete PIDs (stdout only) before signaling.
  • Unified lifecycle audit: every start/stop/restart mutation (cli, safe-rpc, supervisor, handoff) appends a key=value line to gateway-restart.log, immediately after each successful mutation, best-effort.

Proof

  • Focused suites green across daemon + CLI shards (service, lifecycle, launchd/systemd/schtasks, ports/run guards): 400+ tests.
  • tsgo core + core:test green on Blacksmith Testbox.
  • Structured review (Codex gpt-5.6-sol): two hardening rounds (fuser TOCTOU, stderr PID parsing, partial-mutation audit ordering) fixed; final run clean.

Docs: docs/cli/gateway.md updated. Policy context: AGENTS.md "Tests" live-gateway rules (2ca4d92).

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime cli CLI command changes size: XL maintainer Maintainer-authored PR labels Jul 18, 2026
@steipete steipete self-assigned this Jul 18, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1a29054839

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +581 to +583
if (!isTerminalInteractive() && !opts.force) {
const { fail } = createDaemonActionContext({ action: "stop", json: Boolean(opts.json) });
fail(NON_INTERACTIVE_GATEWAY_STOP_MESSAGE);

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.

P1 Badge Add --force for scripted gateway stop paths

In non-interactive release automation this guard now exits before the service stop runs: scripts/lib/cross-os-release-checks/runtime.ts:109-117 still invokes gateway stop without --force, and runInstalledCli runs it through runCommandInvocation with stdio: ["ignore", "pipe", "pipe"] and check defaulting true (scripts/lib/cross-os-release-checks/process.ts:274-279, scripts/lib/cross-os-release-checks/installed.ts:371-377). That makes the managed lifecycle release check fail every time it reaches the stop phase instead of proceeding to the following gateway start; update those owned scripted stop calls to pass --force or otherwise exempt this trusted lane.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 14e7c7d654

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/daemon/service.ts
Comment on lines +217 to +220
if (state.loaded && state.running) {
return {
outcome: "already-running",
state,

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.

P1 Badge Check repair issues before reporting already running

When the service is loaded and currently running, this new early return bypasses the repairIssues check below, so openclaw gateway start will report success without repairing a stale service definition. This hits real upgrade/config-change cases such as OPENCLAW_SERVICE_VERSION drift, temporary/missing program paths, or a managed port that no longer matches the current config; the existing repair path only runs when readRuntime() is not running, so a healthy-but-stale gateway keeps running on the old command instead of being reinstalled/restarted.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 18, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f674cc69d8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

action: GatewayLifecycleAction;
}): ((mutation: GatewayLifecycleMutation) => void) | undefined {
return params.serviceNoun === "Gateway"
? createGatewayLifecycleMutationAudit({ action: params.action })

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.

P2 Badge Write lifecycle audits to the service state dir

When the installed service carries its own OPENCLAW_STATE_DIR or OPENCLAW_PROFILE, managed start/stop/restart run the platform adapter with the merged service environment, but this audit callback is created without that env and falls back to process.env. In that scenario the lifecycle mutation succeeds against the selected service while the new gateway-restart.log entry is written under the caller's default state dir, so status/debug hints that point at the service state dir won't contain the documented audit record.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Jul 18, 2026
@clawsweeper

clawsweeper Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 18, 2026, 1:58 AM ET / 05:58 UTC.

Summary
Adds idempotent Gateway start behavior, force guards for non-interactive stop and forced run, and lifecycle audit logging across Gateway service-control paths.

PR surface: Source +478, Tests +603, Docs +3. Total +1084 across 35 files.

Reproducibility: not applicable. as a conventional bug reproduction: this PR introduces a new lifecycle safety policy, and the supplied evidence is tests and typechecks rather than an observed before/after operator run.

Review metrics: 1 noteworthy metric.

  • Public lifecycle control surface: 1 CLI flag added; 3 lifecycle behaviors changed. The added stop override and changed start/stop/run defaults affect unattended operator workflows, not only internal implementation details.

Stored data model
Persistent data-model change detected: migration/backfill/repair: src/cli/daemon-cli/lifecycle-core.test.ts. Confirm migration or upgrade compatibility proof before merge.

Merge readiness
Overall: 🧂 unranked krab
Proof: 🧂 unranked krab
Patch quality: 🐚 platinum hermit
Result: blocked until real behavior proof from a real setup is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Post redacted live CLI proof for already-running start, rejected unforced stop, explicit forced stop, and guarded forced run.
  • Obtain an explicit maintainer decision on the compatibility policy for existing non-interactive stop callers.

Proof guidance:

  • [P1] Needs real behavior proof before merge: The PR reports tests and typechecks only; add redacted after-fix terminal output, logs, or a recording showing the real Gateway lifecycle outcomes before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Risk before merge

  • [P1] Existing non-interactive scripts or integrations that invoke gateway stop without --force will now fail instead of stopping the service; this requires an intentional compatibility decision and migration coverage.
  • [P1] The new guard can leave automation unable to recover a stuck managed Gateway unless supported callers are updated and the intended override path is proven in a real environment.
  • [P1] The PR has no after-fix real behavior evidence for the safety-critical CLI paths, so test and typecheck results alone do not demonstrate the operator-facing result.

Maintainer options:

  1. Confirm policy and prove supported automation (recommended)
    Before merge, explicitly approve the fail-closed non-interactive stop contract, cover supported callers with --force, and add redacted real CLI evidence for the guarded lifecycle paths.
  2. Retain legacy non-interactive stop semantics
    Revise the default if maintainers decide that existing unattended stop workflows must remain compatible without an added force flag.
  3. Pause until operator policy is settled
    Do not merge a destructive-operation default change until its upgrade and support implications have an explicit owner decision.

Next step before merge

  • [P1] The remaining blocker is an intentional public lifecycle-policy and compatibility decision, plus contributor-provided real behavior proof; it is not a safe automated repair task.

Maintainer decision needed

  • Question: Should non-interactive gateway stop become fail-closed by default, requiring existing automation to pass --force?
  • Rationale: This is an intentional public CLI behavior change that can stop established automation from performing Gateway recovery; tests cannot choose the acceptable compatibility and operator-safety tradeoff.
  • Likely owner: steipete — The assigned author owns the proposed lifecycle-policy direction and its current implementation.
  • Options:
    • Adopt the fail-closed default (recommended): Approve --force as the explicit non-interactive consent mechanism after supported automation callers and upgrade guidance are covered.
    • Preserve existing automation behavior: Keep non-interactive stop behavior compatible by making the stricter guard opt-in or otherwise limiting it to newly introduced automation paths.

Security
Cleared: The patch changes process-control behavior but the supplied diff adds ownership checks and explicit signaling safeguards rather than a concrete security or supply-chain regression.

Review details

Best possible solution:

Confirm the non-interactive safety policy, update every supported automation caller and migration note, then demonstrate idempotent start, refused unforced stop, deliberate forced stop, and guarded run --force in a redacted real CLI session.

Do we have a high-confidence way to reproduce the issue?

Not applicable as a conventional bug reproduction: this PR introduces a new lifecycle safety policy, and the supplied evidence is tests and typechecks rather than an observed before/after operator run.

Is this the best way to solve the issue?

Unclear. The implementation is a plausible safety design, but it is not the best solution until maintainers confirm that breaking existing non-interactive stop callers is preferable to preserving their current behavior.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 8178cf10385d.

Label changes

Label justifications:

  • P1: The PR changes Gateway lifecycle behavior used by real unattended automation and recovery workflows.
  • merge-risk: 🚨 compatibility: Non-interactive gateway stop now requires an explicit flag, which can break existing scripted callers.
  • merge-risk: 🚨 availability: A rejected stop or forced-run cleanup can prevent existing recovery automation from restoring Gateway service.
  • merge-risk: 🚨 automation: The diff intentionally changes CLI behavior relied on by scripts and release or service-management automation.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR reports tests and typechecks only; add redacted after-fix terminal output, logs, or a recording showing the real Gateway lifecycle outcomes before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed

PR surface:

Source +478, Tests +603, Docs +3. Total +1084 across 35 files.

View PR surface stats
Area Files Added Removed Net
Source 19 678 200 +478
Tests 15 630 27 +603
Docs 1 5 2 +3
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 35 1313 229 +1084

What I checked:

  • Idempotent managed start: The branch adds an already-running outcome when a loaded managed Gateway is running, preventing the prior start path from restarting it. (src/daemon/service.ts:214, fe2330fb8eed)
  • Non-interactive stop contract: The branch exposes gateway stop --force and documents that non-interactive callers must explicitly opt into stopping the service. (src/cli/daemon-cli/register-service-commands.ts:123, fe2330fb8eed)
  • Lifecycle audit path: The branch introduces best-effort, profile-aware lifecycle log records in the existing Gateway restart-log facility. (src/daemon/restart-logs.ts:72, fe2330fb8eed)
  • Prior review continuity: The current branch includes follow-up commits after the prior review cycle, including the stated lifecycle CI-gate repair commit; no still-definite line-level defect is established from the supplied current-head material. (fe2330fb8eed)
  • Proof gap: The PR body reports focused tests and typechecks, but it contains no inspected after-fix live CLI transcript, redacted runtime log, terminal capture, or recording for the changed start/stop/run behavior. (fe2330fb8eed)

Likely related people:

  • steipete: The PR timeline assigns the Gateway lifecycle work to this contributor, who also authored the current policy and follow-up commits. (role: assigned decision owner; confidence: medium; commits: 4ee7bfd1e0ec, fe2330fb8eed; files: src/cli/daemon-cli/lifecycle.ts, src/daemon/service.ts, src/cli/ports.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.
Review history (1 earlier review cycle)
  • reviewed 2026-07-18T03:35:45.832Z sha f674cc6 :: needs real behavior proof before merge. :: [P1] Preserve stale-service repair before reporting already running | [P1] Update owned scripted stop callers for the new force guard | [P2] Use the managed service environment for lifecycle audits

@steipete
steipete force-pushed the feat/gateway-lifecycle-guards branch from f674cc6 to fe2330f Compare July 18, 2026 05:55
@steipete
steipete merged commit 8992f92 into main Jul 18, 2026
114 checks passed
@steipete
steipete deleted the feat/gateway-lifecycle-guards branch July 18, 2026 06:01
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fe2330fb8e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

}
if (opts.force) {
const describeNonInteractiveGatewayOwner = () => {
const gatewayPids = findVerifiedGatewayListenerPidsOnPortSync(port);

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.

P1 Badge Verify fuser victims before non-interactive force-kill

When openclaw gateway run --force is non-interactive on a minimal Linux host where lsof is missing or denied, this check returns no gateway PIDs because findVerifiedGatewayListenerPidsOnPortSync uses the lsof-backed path that returns [] on ENOENT (src/infra/restart-stale-pids.ts:367-368). forceFreePortAndWait then falls back to fuser (src/cli/ports.ts:343-355) and the beforeSignal callback re-runs the same blind check, so an operator Gateway listener can still be SIGTERM/SIGKILLed despite the new refusal; verify the fuser PID passed to beforeSignal before allowing the signal.

Useful? React with 👍 / 👎.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 18, 2026
…lifecycle audit (openclaw#110323)

* feat: guard gateway lifecycle mutations

* fix: harden gateway lifecycle mutation guards

* fix: harden gateway lifecycle audit safety

* fix(cli): repair gateway lifecycle checks

* fix(cli): satisfy lifecycle CI gates
zooqueen pushed a commit to zooqueen/openclaw that referenced this pull request Sep 11, 2026
…lifecycle audit (openclaw#110323)

* feat: guard gateway lifecycle mutations

* fix: harden gateway lifecycle mutation guards

* fix: harden gateway lifecycle audit safety

* fix(cli): repair gateway lifecycle checks

* fix(cli): satisfy lifecycle CI gates
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant