Skip to content

feat(cron): add preHook gate for pre-run script checks - #62195

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

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

Conversation

@scottgl9

@scottgl9 scottgl9 commented Apr 6, 2026

Copy link
Copy Markdown
Contributor

Summary

Adds an optional preHook configuration for cron jobs and heartbeat triggers that runs a shell command before agent execution. This gates agent runs on system preconditions (disk space, network, API availability) — eliminating wasteful runs on resource-constrained hosts.

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

Config example (cron)

{
  schedule: "cron 0 8 * * 1-5",
  preHook: {
    command: "ping -c1 -W2 api.openai.com > /dev/null 2>&1",
    timeoutSeconds: 10,
  },
}

Config example (heartbeat)

{
  agents: {
    defaults: {
      heartbeat: {
        every: "30m",
        preHook: {
          command: "/usr/local/bin/check-should-run.sh",
          timeoutSeconds: 30,
        },
      },
    },
  },
}

Changes

  • New: src/cron/pre-hook.ts — core preHook runner with cross-platform shell support, timeout, maxBuffer handling, AbortSignal forwarding
  • New: src/cron/pre-hook.test.ts — 9 tests covering all exit paths
  • Types: preHook field on CronJobBase (flows to CronJob/Create/Patch), heartbeat config, zod schema
  • Cron integration: preHook gate in executeJobCore() before session-target dispatch; AbortSignal propagated from timer through server-cron bridge to heartbeat runner
  • Heartbeat integration: preHook gate after preflight + session lane check, before agent turn; emits heartbeat events on skip/error
  • Normalization: validates command string, clamps timeoutSeconds 1-300, rejects bare strings/primitives
  • Protocol schemas: CronPreHookSchema added to CronJob, CronAdd, CronJobPatch (nullable in patch)
  • Tool schemas: preHook in CRON_RECOVERABLE_OBJECT_KEYS and both add/update tool schemas
  • Docs: pre-run hooks sections in cron-jobs.md, heartbeat.md, configuration-reference.md

Review feedback addressed (from prior PRs #17529, #49415, #53789, #54239)

# Issue Fix
1 maxBuffer unknown exit treated as skip Now always "error"
2 preHook ran before preflight Placed after preflight + session lane check
3 stdout/stderr missing from logs Included in both cron and heartbeat log context
4 AbortSignal not propagated Threaded through state.ts → server-cron.ts → heartbeat-runner.ts
5 No abort check before spawn Checked in pre-hook.ts before execFile
6 Missing heartbeat event on skip/error emitHeartbeatEvent on both paths
7 Docs exit-code mismatch Corrected in all 3 doc files
8 Bare string preHook accepted Rejected in normalize.ts
9 Typed tool schemas missing preHook Added to both add and update schemas

Closes #62185

Test plan

  • pnpm test src/cron/pre-hook.test.ts — 9/9 passing
  • pnpm test src/cron/normalize.test.ts — 60/60 passing (10 new preHook tests)
  • pnpm check — no new errors (12 pre-existing on main)
  • pnpm test — full suite
  • Manual: cron job with preHook: { command: "exit 0" } → job runs
  • Manual: preHook: { command: "exit 10" } → job skipped, no error count
  • Manual: preHook: { command: "exit 1" } → job blocked, errors increment

@scottgl9
scottgl9 requested a review from a team as a code owner April 6, 2026 23:47
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime agents Agent runtime and tooling size: M labels Apr 6, 2026
@scottgl9
scottgl9 force-pushed the scottgl9/pre-hook-gate-v3 branch from be89f6c to 517fc08 Compare April 6, 2026 23:50
@greptile-apps

greptile-apps Bot commented Apr 6, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

Adds an optional preHook shell-command gate to cron jobs and heartbeat triggers: exit 0 proceeds, exit 10 skips (no error counted), any other exit or timeout is an error with backoff. The implementation is well-structured — protocol schemas, normalization, tool schemas, AbortSignal propagation, and heartbeat events are all updated consistently, and the nine feedback items from prior review rounds are addressed.

Confidence Score: 5/5

Safe to merge; remaining findings are P2 style and convention issues only.

No P0 or P1 issues found. The two remaining findings — missing *.runtime.ts lazy-load boundary and no preHook clearing sentinel in the update tool schema — are P2 quality-of-life concerns that do not affect correctness or runtime behavior. Prior review concerns (#1–9 per the PR description) are resolved in this iteration.

src/cron/service/timer.ts and src/infra/heartbeat-runner.ts for the dynamic import boundary; src/agents/tools/cron-tool.ts for the missing preHook clearing path in the update action.

Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/cron/service/timer.ts
Line: 1155-1156

Comment:
**Missing `*.runtime.ts` lazy-load boundary**

`pre-hook.js` is dynamically imported inline here and again in `src/infra/heartbeat-runner.ts:620`, but the repo convention (CLAUDE.md dynamic-import guardrail) requires a dedicated `*.runtime.ts` re-export boundary for lazy-loaded modules executing real work. Every other lazy-load in `src/cron/isolated-agent/` and `src/infra/` follows this pattern (e.g. `run.runtime.ts`, `heartbeat-runner.runtime.ts`). Without the boundary, tests cannot mock the seam to avoid actually spawning shell processes.

```suggestion
    const { runPreHook } = await import("../pre-hook.runtime.js");
```

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/agents/tools/cron-tool.ts
Line: 252-265

Comment:
**No mechanism to clear `preHook` via the update tool**

The protocol schema (`CronJobPatchSchema` in `cron.ts`) accepts `null` to remove a preHook, but the update tool action only declares `Type.Optional(Type.Object(...))` — there is no sentinel value and the description doesn't mention clearing. By contrast, `failureAlert` uses `Type.Unsafe<Record<string, unknown> | false>` with an explicit description to clear via `false`. An agent that adds a preHook through the tool has no documented path to remove it. Consider mirroring that pattern and documenting the clear sentinel in the description.

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

Reviews (1): Last reviewed commit: "feat(cron): add preHook gate for pre-run..." | Re-trigger Greptile

Comment thread src/cron/service/timer.ts Resolved
Comment thread src/agents/tools/cron-tool.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: be89f6c662

ℹ️ 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
@scottgl9
scottgl9 force-pushed the scottgl9/pre-hook-gate-v3 branch from 517fc08 to ab19c97 Compare April 8, 2026 19:04

@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: ab19c9758e

ℹ️ 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/agents/tools/cron-tool.ts Resolved
@scottgl9
scottgl9 force-pushed the scottgl9/pre-hook-gate-v3 branch from ab19c97 to d6fd61b Compare April 9, 2026 16:46

@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: d6fd61b610

ℹ️ 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: 66e84a01fd

ℹ️ 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/service/timer.ts Resolved
@scottgl9
scottgl9 force-pushed the scottgl9/pre-hook-gate-v3 branch from 66e84a0 to dae1753 Compare April 9, 2026 20:36

@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: dae1753818

ℹ️ 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/service/timer.ts Resolved
Comment thread src/infra/heartbeat-runner.ts Resolved
@scottgl9
scottgl9 force-pushed the scottgl9/pre-hook-gate-v3 branch 3 times, most recently from b75b011 to d3ab8a5 Compare April 10, 2026 13:38

@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: d3ab8a5905

ℹ️ 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/service/timer.ts Resolved
@openclaw-barnacle openclaw-barnacle Bot added the app: macos App: macos label Apr 10, 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: 48357cd291

ℹ️ 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/service/timer.ts Resolved
@scottgl9
scottgl9 force-pushed the scottgl9/pre-hook-gate-v3 branch from cec1e73 to 86c3736 Compare April 12, 2026 20:04

@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: 86c3736e89

ℹ️ 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/service/timer.ts Resolved
@scottgl9
scottgl9 force-pushed the scottgl9/pre-hook-gate-v3 branch from 44b9da9 to 59cc02b Compare April 15, 2026 01:04

@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: 59cc02b92f

ℹ️ 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/normalize.ts Resolved
@clawsweeper

clawsweeper Bot commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I swept through the related work, and this is now duplicate or superseded.

Close: the preHook idea is useful but this stale, conflicting PR is no longer the right landing vehicle; the remaining cron-hook API and security decision is tracked by the canonical open issue.

Canonical path: Keep the remaining design on #9465 and land a fresh, security-reviewed implementation only after maintainers choose the permanent cron-hook API and execution boundary.

So I’m closing this here and keeping the remaining discussion on #9465.

Review details

Best possible solution:

Keep the remaining design on #9465 and land a fresh, security-reviewed implementation only after maintainers choose the permanent cron-hook API and execution boundary.

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

Not applicable as a bug reproduction; this is a new feature request. The PR review blockers are source-reproducible from PR head: preHook.file accepts any non-empty string, direct execFile is used, and no real runtime proof is present.

Is this the best way to solve the issue?

No. A deterministic pre-run gate is plausible, but this branch is not the best solution now because it is conflicting, updates an obsolete protocol path, and leaves process-execution security and cleanup semantics unresolved.

Security review:

Security review needs attention: The PR introduces a security-sensitive local process execution surface with an unenforced path contract and weaker timeout cleanup than current cron command execution.

  • [high] Relative executable path remains accepted — src/cron/normalize.ts:507
    preHook.file is documented as absolute, but PR-head normalization accepts any trimmed non-empty string; Node can resolve bare executable names through PATH before execFile runs them.
    Confidence: 0.91
  • [medium] Timed-out hooks can leave child processes behind — src/cron/pre-hook.ts:66
    The hook runner uses direct execFile timeout/abort behavior instead of the existing process-tree cleanup used by cron command jobs, so scripts that spawn children may continue consuming resources after the hook is considered failed.
    Confidence: 0.84

AGENTS.md: found and applied where relevant.

What I checked:

Likely related people:

  • steipete: Peter Steinberger is the dominant recent contributor across cron, heartbeat, gateway protocol, and process-exec history sampled for this surface, and prior canonical issue review routed the product/security decision through these paths. (role: recent area contributor; confidence: high; commits: 60b61288c40b, 934927fd13ed, f03d7c5a4c40; files: src/cron/service/timer.ts, src/infra/heartbeat-runner.ts, packages/gateway-protocol/src/schema/cron.ts)
  • vincentkoc: Vincent Koc has recent current-main cron, protocol, and heartbeat-adjacent commits, including the latest cron timer touch that this stale branch must rebase across. (role: recent adjacent contributor; confidence: high; commits: efbefceb0e2e, 8c802aa68351, 74e7b8d47b18; files: src/cron/service/timer.ts, src/infra/heartbeat-runner.ts, packages/gateway-protocol/src/schema/cron.ts)
  • mbelinky: Mariano's recent cron commits changed unresolved next-run and backoff behavior in the same scheduler path that a pre-run gate must preserve. (role: recent cron behavior contributor; confidence: medium; commits: 190a4b48697b, c60282421524, d4e59a3666d8; files: src/cron/service/timer.ts)

Codex review notes: model internal, reasoning high; reviewed against 8682d0701b27.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels May 19, 2026
@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. label May 19, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels May 19, 2026
@clawsweeper

clawsweeper Bot commented May 20, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg

🎁 Pass real behavior proof to wake the egg and unlock a hatchable treat.

Where did the egg go?
  • The egg game starts only after the PR passes the real-behavior proof check.
  • Before that, no creature or rarity is rolled. The treat waits for real proof.
  • This is still just collectible flavor: proof affects review readiness, not creature quality.

@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jun 5, 2026
@clawsweeper clawsweeper Bot added rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 5, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Jun 6, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. and removed rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Jun 14, 2026
@clawsweeper

clawsweeper Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper applied the proposed close for this PR.

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

Labels

agents Agent runtime and tooling app: macos App: macos app: web-ui App: web-ui docs Improvements or additions to documentation gateway Gateway runtime 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. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: L status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: dirty-candidate Candidate: broad unrelated surfaces; may need splitting or cleanup. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: preHook gate for cron and heartbeat pre-run script checks

2 participants