Skip to content

Cron/Heartbeat: add preHook gate for pre-run script checks - #53789

Closed
scottgl9 wants to merge 2 commits into
openclaw:mainfrom
scottgl9:fix/pre-hook-gate-clean
Closed

scottgl9 wants to merge 2 commits into
openclaw:mainfrom
scottgl9:fix/pre-hook-gate-clean

Conversation

@scottgl9

Copy link
Copy Markdown
Contributor

Reopening #49415 with a clean rebase onto main (previous branch was closed by the bot due to unrelated commits picked up during merge).

Closes #49370


Summary

Operators running OpenClaw on resource-constrained hosts (Raspberry Pi, shared VMs, metered cloud instances) currently have no native way to gate cron or heartbeat agent runs on system preconditions — things like checking disk space, network reachability, API availability, or whether a dependent service is healthy. Everyone ends up rebuilding custom wrapper logic independently outside of OpenClaw, which is fragile and hard to maintain.

This PR adds an optional preHook config for cron jobs and heartbeats that runs a shell command before agent execution, using exit codes to decide whether to proceed, skip, or abort.

  • Exit 0 = proceed with agent execution
  • Exit 10 = skip (not counted as a failure, consecutiveErrors stays 0)
  • Any other code = error (counted as a failure, triggers backoff/alerts)

The timeout is capped at 300s to prevent blocking the executor thread.

Changes

  • New src/cron/pre-hook.ts: shared runPreHook() function using platform shell (cmd.exe /c on Windows, /bin/sh -c elsewhere), configurable timeout (default 30s, max 300s), stdout/stderr capture (64 KB cap), AbortSignal support
  • src/cron/types-shared.ts: add preHook to CronJobBase; CronJobPatch re-declares it as object | null to allow explicit clearing
  • src/config/types.agent-defaults.ts: add preHook to heartbeat config block
  • src/config/zod-schema.agent-runtime.ts: add preHook to HeartbeatSchema with z.string().trim().min(1) command validation
  • src/cron/service/timer.ts: preHook gate in executeJobCore() before abort signal check; passes AbortSignal through
  • src/cron/service/jobs.ts: persist preHook in createJob() and applyJobPatch()
  • src/infra/heartbeat-runner.ts: preHook gate in runHeartbeatOnce() with AbortSignal forwarding; falls back to default config preHook when override omits it
  • src/cron/normalize.ts: normalize preHook (trim command, clamp timeoutSeconds 1–300, null clears for patch, delete for create); rejects malformed patch objects (missing/non-string command returns error instead of silently clearing)
  • src/agents/tools/cron-tool.ts: add preHook to allowed keys for add/update actions
  • src/gateway/protocol/schema/cron.ts: add preHook to CronAddParamsSchema, CronJobPatchSchema (null allowed for patch), and CronJobSchema
  • docs/automation/cron-jobs.md, docs/gateway/heartbeat.md: documentation

Tests

  • src/cron/pre-hook.test.ts: exit 0/10/1/42, timeout, AbortSignal kill, maxBuffer handling, portable node -e commands
  • src/cron/normalize.test.ts: valid passthrough, empty/whitespace command, timeoutSeconds clamping, null for patch, malformed patch object rejection

Test plan

  • pnpm test -- src/cron/pre-hook.test.ts passes
  • pnpm test -- src/cron/normalize.test.ts passes
  • Manual: create cron job with preHook: { command: "exit 0" } → job runs normally
  • Manual: preHook: { command: "exit 10" } → job skipped, no error count increment
  • Manual: preHook: { command: "exit 1" } → job blocked, consecutiveErrors increments

@scottgl9
scottgl9 requested a review from a team as a code owner March 24, 2026 16:18
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: macos App: macos app: web-ui App: web-ui gateway Gateway runtime agents Agent runtime and tooling size: M labels Mar 24, 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: 5ebcbb7055

ℹ️ 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/cron/pre-hook.ts Resolved
Comment thread src/infra/heartbeat-runner.ts Resolved
@greptile-apps

greptile-apps Bot commented Mar 24, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds an optional preHook gate to cron jobs and heartbeats, letting operators run a shell command before each agent execution and use its exit code to proceed (0), skip silently (10), or signal an error (any other non-zero). The implementation is well-structured: runPreHook() correctly handles timeouts, AbortSignal forwarding, maxBuffer overflow, and the Windows vs Unix shell split; normalization covers all input shapes (valid object, empty/whitespace command, explicit null patch, malformed object); and the schema changes are consistent across TypeBox, Zod, and Swift gateway models.

Key issues found:

  • docs/gateway/configuration-reference.md line 1007 mis-documents the exit-code contract — it says "If the command exits non-zero, the heartbeat is skipped," which is only true for exit 10. Any other non-zero exit returns { status: "failed" } and can trigger backoff/alerts. Operators reading only this reference page could unknowingly misconfigure their pre-hooks.
  • AbortSignal test is missing from src/cron/pre-hook.test.ts despite being listed in the PR description's test plan.
  • Malformed preHook rejection test is missing from src/cron/normalize.test.ts — the null return path (triggered by a non-string command field) is called out in the PR description as important behavior but has no corresponding test.
  • Windows shell not mentioned in docs — cron-jobs.md and heartbeat.md say /bin/sh -c without noting that Windows uses cmd.exe /c, which could surprise operators writing Unix-style compound commands.

Confidence Score: 4/5

  • Safe to merge after fixing the configuration-reference.md exit-code description; remaining issues are minor test and doc gaps.
  • The core implementation (runPreHook, normalization, timer/heartbeat integration) is solid and handles edge cases well. The one P1 concern is a factual error in the configuration reference doc that could mislead operators into expecting exit-1 to silently skip a run rather than count as a failure. The P2 items (missing AbortSignal and malformed-preHook tests, Windows shell doc gap) are low-risk but worth addressing. No runtime correctness bugs were found in the code itself.
  • docs/gateway/configuration-reference.md (exit-code contract is incorrect); src/cron/pre-hook.test.ts and src/cron/normalize.test.ts (test gaps).

Comments Outside Diff (3)

  1. src/cron/normalize.test.ts, line 391-451 (link)

    P2 Missing test for malformed preHook rejection

    The PR description specifically calls out: "rejects malformed patch objects (missing/non-string command returns error instead of silently clearing)". The normalizeCronJobInput function returns null (signalling a validation error) when preHook is an object with a non-string command. However, there is no test case exercising this path.

    Consider adding:

    it("rejects preHook object with non-string command", () => {
      const normalized = normalizeCronJobPatch({
        preHook: { command: 42 },
      });
      expect(normalized).toBeNull();
    });

    Without this test, a refactor that accidentally coerces a non-string command to "" (clearing an existing hook silently) would go undetected.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: src/cron/normalize.test.ts
    Line: 391-451
    
    Comment:
    **Missing test for malformed `preHook` rejection**
    
    The PR description specifically calls out: *"rejects malformed patch objects (missing/non-string command returns error instead of silently clearing)"*. The `normalizeCronJobInput` function returns `null` (signalling a validation error) when `preHook` is an object with a non-string `command`. However, there is no test case exercising this path.
    
    Consider adding:
    
    ```ts
    it("rejects preHook object with non-string command", () => {
      const normalized = normalizeCronJobPatch({
        preHook: { command: 42 },
      });
      expect(normalized).toBeNull();
    });
    ```
    
    Without this test, a refactor that accidentally coerces a non-string command to `""` (clearing an existing hook silently) would go undetected.
    
    How can I resolve this? If you propose a fix, please make it concise.
  2. src/cron/pre-hook.test.ts, line 511 (link)

    P2 AbortSignal test missing despite being listed in PR description

    The PR description's test plan lists "AbortSignal kill" as a covered test case, but no such test exists in this file. The abort-signal path in runPreHook (lines 126–138 of pre-hook.ts) is exercised in production — e.g., when a cron job's outer timeout fires while the pre-hook is still running — but is currently untested.

    A minimal test could look like:

    it("returns error when abort signal fires", async () => {
      const controller = new AbortController();
      const resultPromise = runPreHook(
        { command: 'node -e "setTimeout(() => {}, 60000)"' },
        controller.signal,
      );
      controller.abort();
      const result = await resultPromise;
      expect(result.outcome).toBe("error");
      if (result.outcome === "error") {
        expect(result.message).toContain("aborted");
      }
    });
    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: src/cron/pre-hook.test.ts
    Line: 511
    
    Comment:
    **AbortSignal test missing despite being listed in PR description**
    
    The PR description's test plan lists "AbortSignal kill" as a covered test case, but no such test exists in this file. The abort-signal path in `runPreHook` (lines 126–138 of `pre-hook.ts`) is exercised in production — e.g., when a cron job's outer timeout fires while the pre-hook is still running — but is currently untested.
    
    A minimal test could look like:
    
    ```ts
    it("returns error when abort signal fires", async () => {
      const controller = new AbortController();
      const resultPromise = runPreHook(
        { command: 'node -e "setTimeout(() => {}, 60000)"' },
        controller.signal,
      );
      controller.abort();
      const result = await resultPromise;
      expect(result.outcome).toBe("error");
      if (result.outcome === "error") {
        expect(result.message).toContain("aborted");
      }
    });
    ```
    
    How can I resolve this? If you propose a fix, please make it concise.
  3. docs/automation/cron-jobs.md, line 231 (link)

    P2 Windows shell not mentioned

    Both docs/automation/cron-jobs.md and docs/gateway/heartbeat.md (line 303) describe the shell as /bin/sh -c, but the implementation uses cmd.exe /c on Windows. Windows operators who compose commands using Unix-style operators (&&, ||, |, curl -sf, etc.) may be surprised when their pre-hook behaves differently.

    Consider a one-line note:

    The same update is needed at docs/gateway/heartbeat.md:303.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: docs/automation/cron-jobs.md
    Line: 231
    
    Comment:
    **Windows shell not mentioned**
    
    Both `docs/automation/cron-jobs.md` and `docs/gateway/heartbeat.md` (line 303) describe the shell as `/bin/sh -c`, but the implementation uses `cmd.exe /c` on Windows. Windows operators who compose commands using Unix-style operators (`&&`, `||`, `|`, `curl -sf`, etc.) may be surprised when their pre-hook behaves differently.
    
    Consider a one-line note:
    
    
    
    The same update is needed at `docs/gateway/heartbeat.md:303`.
    
    How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: docs/gateway/configuration-reference.md
Line: 1007

Comment:
**Incorrect exit-code behavior documented**

This line says "If the command exits non-zero, the heartbeat is skipped," but that's only true for exit code `10`. Any other non-zero exit code causes a `{ status: "failed" }` result — not a silent skip — which can trigger backoff/alerts and increments error counters.

An operator reading only this reference could configure a pre-hook that returns exit `1` on a precondition failure, expecting it to quietly skip the heartbeat run, only to find it accumulates failures and triggers alerts instead.

```suggestion
- `preHook`: optional shell command to run before the heartbeat turn. Exit `0` proceeds, exit `10` skips silently (not counted as a failure), any other non-zero exit code is treated as a failure. Useful for lightweight pre-flight checks (e.g. "are there new emails?") without waking an LLM agent.
```

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: src/cron/normalize.test.ts
Line: 391-451

Comment:
**Missing test for malformed `preHook` rejection**

The PR description specifically calls out: *"rejects malformed patch objects (missing/non-string command returns error instead of silently clearing)"*. The `normalizeCronJobInput` function returns `null` (signalling a validation error) when `preHook` is an object with a non-string `command`. However, there is no test case exercising this path.

Consider adding:

```ts
it("rejects preHook object with non-string command", () => {
  const normalized = normalizeCronJobPatch({
    preHook: { command: 42 },
  });
  expect(normalized).toBeNull();
});
```

Without this test, a refactor that accidentally coerces a non-string command to `""` (clearing an existing hook silently) would go undetected.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: src/cron/pre-hook.test.ts
Line: 511

Comment:
**AbortSignal test missing despite being listed in PR description**

The PR description's test plan lists "AbortSignal kill" as a covered test case, but no such test exists in this file. The abort-signal path in `runPreHook` (lines 126–138 of `pre-hook.ts`) is exercised in production — e.g., when a cron job's outer timeout fires while the pre-hook is still running — but is currently untested.

A minimal test could look like:

```ts
it("returns error when abort signal fires", async () => {
  const controller = new AbortController();
  const resultPromise = runPreHook(
    { command: 'node -e "setTimeout(() => {}, 60000)"' },
    controller.signal,
  );
  controller.abort();
  const result = await resultPromise;
  expect(result.outcome).toBe("error");
  if (result.outcome === "error") {
    expect(result.message).toContain("aborted");
  }
});
```

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: docs/automation/cron-jobs.md
Line: 231

Comment:
**Windows shell not mentioned**

Both `docs/automation/cron-jobs.md` and `docs/gateway/heartbeat.md` (line 303) describe the shell as `/bin/sh -c`, but the implementation uses `cmd.exe /c` on Windows. Windows operators who compose commands using Unix-style operators (`&&`, `||`, `|`, `curl -sf`, etc.) may be surprised when their pre-hook behaves differently.

Consider a one-line note:

```suggestion
via the platform shell (`/bin/sh -c` on macOS/Linux, `cmd.exe /c` on Windows) before the agent turn starts. Use it to check resource
```

The same update is needed at `docs/gateway/heartbeat.md:303`.

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "fix(pre-hook): reject malformed patch pr..." | Re-trigger Greptile

Comment thread docs/gateway/configuration-reference.md Resolved
@scottgl9
scottgl9 force-pushed the fix/pre-hook-gate-clean branch from 5ebcbb7 to 5463c8f Compare March 26, 2026 21:59

@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: 5463c8fd88

ℹ️ 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/infra/heartbeat-runner.ts Resolved

@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: 6858cd2740

ℹ️ 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/infra/heartbeat-runner.ts Resolved
…nce delegate

The server-cron.ts production delegate was calling runHeartbeatOnce without
forwarding opts.abortSignal, so the cron job timeout signal never reached the
heartbeat pre-hook shell process. Side-effecting hooks could outlive a timed-
out cron job until their own preHook.timeoutSeconds expired.
@scottgl9
scottgl9 force-pushed the fix/pre-hook-gate-clean branch from 0d20dd8 to bd3ce00 Compare April 3, 2026 20:28
@openclaw-barnacle openclaw-barnacle Bot added size: XS and removed docs Improvements or additions to documentation app: macos App: macos app: web-ui App: web-ui agents Agent runtime and tooling size: M labels Apr 3, 2026
@vincentkoc vincentkoc added close:duplicate Closed as duplicate dedupe:child Duplicate issue/PR child in dedupe cluster labels Apr 5, 2026
@vincentkoc

Copy link
Copy Markdown
Member

closing this in favor of #54239. same preHook work, same author, and this branch currently has no diff to review. if you want this PR kept instead, say so and we can swap the canonical ref.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

close:duplicate Closed as duplicate dedupe:child Duplicate issue/PR child in dedupe cluster gateway Gateway runtime size: XS

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature: pre-run script hook/gate for heartbeat and cron agent triggers

2 participants