Skip to content

fix(cron): agents learn an automation run's outcome in the same tool call - #162481

Merged
obviyus merged 5 commits into
mainfrom
fix/automations-run-wait
Oct 1, 2026
Merged

obviyus merged 5 commits into
mainfrom
fix/automations-run-wait

Conversation

@obviyus

@obviyus obviyus commented Oct 1, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Fixes: when an agent runs an automation with automations run, the call returns as soon as the run is queued, so the model never learns whether the run worked. It then posts guesses, or schedules a separate "verify" job. That job runs with only its own scope, can't see the result, and reports a false "blocked".

User Impact

User impact: when an agent runs an automation, it gets the finished run (status, error, delivery status and summary) in the same tool result if the run ends within the call's timeoutMs (default 60 s, capped at 10 min). A longer run returns its runId and a note to check it later with runs jobId runId, not with a scheduled check. The CLI is unchanged.

Why This Change Was Made

cron.run became enqueue-only in #40204 (closing #40192). Back then a synchronous run held the RPC until the 60 s gateway timeout and returned a misleading timeout error while the job kept running. #81929 later added openclaw cron run --wait, polling cron.runs from the client, and deliberately kept cron.run from holding the request open. The agent tool never got a wait at all. A client-side poller would not work for the tool anyway: management-grant turns can run a job, but cron.runs is not one of their allowed methods.

This PR keeps that invariant (no unbounded request, no false failure) and gives the one owner of run completion a bounded, opt-in wait:

  • The cron service records each accepted manual run's settlement. waitForManualRun(runId, timeoutMs, signal) resolves when the run has written its history row. It is event-driven, with no polling.
  • cron.run accepts an optional waitTimeoutMs. When the run finishes in time, the ack also carries run, read through the existing cron.runs handler so the same visibility and authority rules apply. When the wait ends first, the ack is unchanged and the run continues.
  • When an agent turn runs a main-session job, or a session:<key> job in its own session, the call returns at once. The caller's turn holds the main lane and its own session lane: heartbeats skip while CommandLane.Main is busy, and a main-session run waits up to 2 min for that busy turn. Waiting there would only burn the budget.
  • The automations tool's run passes its timeoutMs as the wait. runs now forwards runId. The tool descriptions now steer models away from verify jobs. Against a shipped Gateway, which rejects the new param before enqueueing, the tool retries the plain call once, the same way it already does for compact on cron.list.
  • Accepted runs stay accepted, and outcomes go only to callers that may still read them. After the history read, the handler rechecks read authority (caller authority, agent runtime and any management grant), with no await between that check and the response. If the read or the recheck is refused, for example because a delegated grant lapsed or was revoked during a long wait, the caller gets the plain ack and nothing about the outcome. If the run finished but its history is not visible (for example a one-shot that deleted itself after succeeding), the ack carries finished: true. Management-only turns are pointed to the Automations page instead of runs.

The CLI keeps its client-side --wait polling in this PR. Moving it onto the Gateway wait is a separate, compatibility-reviewed follow-up.

Evidence

  • Real isolated Gateway, real Telegram plugin on the Crabline synthetic Bot API, and a deterministic Responses provider. An owner DM turn calls the automations tool (throwaway harness, not committed).
    • Before (origin/main build): every run returned only { ok, enqueued, runId, processInstanceId } in under 1 s, with no outcome. The report still reached the chat, so the model couldn't tell the run had succeeded.
    • After: the isolated job's run returned in 4.3 s with run { status: "ok", completionStatus: "succeeded", deliveryStatus: "delivered", summary: "FAST-REPORT-DELIVERED" }, and the report reached the chat. A slow job (8 s, called with timeoutMs: 2000) returned after 2.6 s with its runId and the runs jobId runId note. The run kept going and delivered, and a later runs call with that runId returned the single finished entry. A main-session job run from the owner's main-session DM returned in 0.6 s with the note instead of blocking the turn.
  • Gateway regression (src/gateway/server.cron.test.ts): waitTimeoutMs: 50 returns only the runId while the run is blocked. waitTimeoutMs: 10000 returns run { runId, status: "ok", completionStatus: "succeeded", summary }. On origin/main this fails because the closed schema rejects waitTimeoutMs.
  • Same-session skip (cron.validation.test.ts): from an agent turn, main and session:<own key> jobs return the plain ack without waiting. isolated jobs wait.
  • Authority chain (cron.validation.test.ts, through the real cron.run and cron.runs handlers with a stored run record): a caller that is still authorized gets run { runId, status: "ok" }. A caller revoked during the history read gets only the accepted ack. Before this change the revoked case turned into a request error.
  • Tool (cron-tool.test.ts): the wait is capped at 10 min, and the RPC timeout is the wait plus 60 s. An unfinished run gets the runs jobId runId note.
  • Tool contract (cron-tool.output-contract.test.ts): a shipped Gateway that rejects waitTimeoutMs still enqueues through a single retry, and the result stays valid against the output schema. The run output type only declares the outcome fields, so the generated code-mode declarations stay within their size allowance.
  • Measured local wall times on head cf942df0601 (one node scripts/run-vitest.mjs <file> per file; wrapper wall / Vitest duration): cron-tool.output-contract 5 tests, 24s / 7.0s; cron-tool 72 tests, 19s / 16.2s; server-cron-lazy 25 tests, 21s / 17.6s; cron.validation 261 tests, 24s / 21.4s; server.cron 17 tests, 46s / 43.8s. There are no CI seconds yet: CI skips the test jobs while the PR is a draft, and the only job that ran, "PR context and evidence", passed in 38s.
  • pnpm tsgo:core is clean. Targeted tests pass: server.cron, cron.validation, cron-tool, server-cron-lazy.

Bounded cost

  • The wait is bounded by timeoutMs (default 60 s, capped at 10 min in the tool) and ends early if the caller aborts. The cron.run RPC timeout is the wait plus a 60 s enqueue budget, so the response always arrives before the client gives up.
  • No new model calls or job runs. The waiter only watches a run that was already accepted. It does not retry, re-run or alert.
  • No nested waits. Automation-run sessions are limited to self status/list/get/runs/remove, so a job's run cannot call run. A job running itself gets already-running. Main-session and same-session runs, which can only start after the caller's turn, skip the wait.

@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@obviyus

obviyus commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper review

@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@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 Oct 1, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 1, 2026
@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 1, 2026, 6:55 AM ET / 10:55 UTC (Revision 9).

ClawSweeper review

What this changes

The automations tool gains a bounded wait for a manually triggered job’s outcome, exact-run history lookup, older-Gateway fallback, and matching protocol, documentation, tests, and prompt snapshots.

Merge readiness

✅ Ready for maintainer review

This PR remains useful: current main and the latest release still return an enqueue acknowledgement without the agent-facing completion capability. Earlier actionable findings are addressed, the stated tradeoffs have verified maintainer acceptance, and no blocking defect was found.

Priority: P2
Reviewed head: d07c382797cb80ae3d332eaf9ea11b54dc2f4e07

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful runtime evidence and a focused implementation support normal good PR quality with no remaining actionable finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Recorded isolated-Gateway observations exercise the production automations tool and cron owner: completion returns delivered success and summary, timeout preserves a continuing run and exact lookup, and main-session work acknowledges promptly. Handler coverage checks allowed and revoked outcome readers, with verified maintainer acceptance of that scoped proof. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Recorded isolated-Gateway observations exercise the production automations tool and cron owner: completion returns delivered success and summary, timeout preserves a continuing run and exact lookup, and main-session work acknowledges promptly. Handler coverage checks allowed and revoked outcome readers, with verified maintainer acceptance of that scoped proof. No stored-data contract changes.
Evidence reviewed 9 items Pinned production change: The introduced merge-base-to-head diff adds completion waiting through the existing cron service and history reader. Main-session and caller-session jobs bypass the wait, and refused outcome reads preserve the accepted acknowledgement.
Current-main and release necessity: Inspection of the fetched main handler shows cron.run still responds directly after enqueueing. The v2026.9.7 request schema lacks waitTimeoutMs. The merged CLI wait work at #81929 deliberately retained that enqueue-only Gateway behavior and does not replace this agent-tool change.
Upgrade compatibility: The tool retries without waitTimeoutMs only for the specific pre-enqueue INVALID_REQUEST rejection. The output-contract regression checks that single fallback and validates the resulting acknowledgement. Existing CLI defaults, saved jobs, and stored history formats are unchanged.
Findings None None.
Security None None.

How this fits together

Agents use the automations tool to trigger jobs through the Gateway’s cron service. The service executes accepted work and records its outcome; the Gateway returns authorized completion details or an acknowledgement for later follow-up.

flowchart TD
  A[Agent automation request] --> B[Gateway authorization]
  B --> C[Cron run queue]
  C --> D[Job execution and history]
  C --> E[Bounded completion wait]
  D --> E
  E --> F[Current read authority]
  F --> G[Outcome or accepted acknowledgement]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +160, Tests +177, Docs +2. Total +339 across 24 files.

View PR surface stats
Area Files Added Removed Net
Source 11 181 21 +160
Tests 11 202 25 +177
Docs 2 3 1 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 24 386 47 +339

Review metrics

Metric Value Why it matters
Completion contract 1 optional RPC parameter; agent wait defaults to 60 seconds, capped at 10 minutes The RPC remains non-blocking by default while the agent tool explicitly requests bounded completion.
Production versus test growth Production +181/-21 lines; tests, support, and fixtures +202/-25 lines Production growth implements service-owned settlement, authorized outcome reads, and compatibility fallback; test growth covers those distinct boundaries.

Technical review

Best possible solution:

Keep completion tracking with the cron execution owner, reuse authorized history reads, and preserve enqueue acknowledgements whenever waiting cannot yield an available outcome.

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

Not applicable as an established-behavior bug: enqueue-only responses were intentional. Current source and the recorded before/after Gateway observations establish the missing agent completion capability.

Is this the best way to solve the issue?

Yes. An event-driven wait at the cron owner avoids client polling and preserves accepted work, existing history visibility, and older-Gateway compatibility.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against d64730851269.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded automation improvement that reduces misleading agent follow-up without changing scheduled execution or CLI defaults.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Recorded isolated-Gateway observations exercise the production automations tool and cron owner: completion returns delivered success and summary, timeout preserves a continuing run and exact lookup, and main-session work acknowledges promptly. Handler coverage checks allowed and revoked outcome readers, with verified maintainer acceptance of that scoped proof. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded isolated-Gateway observations exercise the production automations tool and cron owner: completion returns delivered success and summary, timeout preserves a continuing run and exact lookup, and main-session work acknowledges promptly. Handler coverage checks allowed and revoked outcome readers, with verified maintainer acceptance of that scoped proof. No stored-data contract changes.

Evidence

What I checked:

  • Pinned production change: The introduced merge-base-to-head diff adds completion waiting through the existing cron service and history reader. Main-session and caller-session jobs bypass the wait, and refused outcome reads preserve the accepted acknowledgement. (src/gateway/server-methods/cron.ts:900, d07c382797cb)
  • Current-main and release necessity: Inspection of the fetched main handler shows cron.run still responds directly after enqueueing. The v2026.9.7 request schema lacks waitTimeoutMs. The merged CLI wait work at Add wait mode for manual cron runs #81929 deliberately retained that enqueue-only Gateway behavior and does not replace this agent-tool change. (src/gateway/server-methods/cron.ts, d64730851269)
  • Upgrade compatibility: The tool retries without waitTimeoutMs only for the specific pre-enqueue INVALID_REQUEST rejection. The output-contract regression checks that single fallback and validates the resulting acknowledgement. Existing CLI defaults, saved jobs, and stored history formats are unchanged. (src/agents/tools/cron-tool.ts:634, d07c382797cb)
  • Recorded real behavior: The captured PR body reports an isolated real Gateway and production automations tool using a deterministic provider and the real Telegram plugin against a synthetic Bot API. The fast run returned succeeded/delivered with its summary after 4.3 seconds; the timeout case returned its runId after 2.6 seconds, continued delivering, and later returned one exact history entry; the main-session case acknowledged in 0.6 seconds. These observations exercise the changed core completion path rather than claiming Telegram Test Server coverage.
  • Outcome authority and accepted tradeoffs: The handler rechecks caller and agent-runtime read authority plus the active management grant after reading history and immediately before returning the outcome. Allowed-versus-revoked handler coverage accompanies it. GitHub's collaborator permission endpoint verified obviyus has role_name maintain, validating the acceptance comments concerning bounded detached cancellation, management outcomes, and scoped authority proof: fix(cron): agents learn an automation run's outcome in the same tool call #162481 (comment) and fix(cron): agents learn an automation run's outcome in the same tool call #162481 (comment). (src/gateway/server-methods/cron.ts:931, d07c382797cb)
  • Re-review continuity: The preceding reviewed head has no retained findings or published rank-up moves. Its delta to the current head only adjusts the native-attempt regression to request a 1 ms wait while its cron lane is deliberately blocked; the admission, cancellation, and revocation assertions remain intact. Earlier compatibility, inaccessible-history, follow-up, pre-abort, and final-authority concerns were checked against current source. (src/cron/service/ops.native-attempt.test.ts:188, d07c382797cb)

Likely related people:

  • obviyus: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
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.

Workflow

  • 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.

History

Review history (8 earlier review cycles)
  • reviewed 2026-10-01T06:46:22.238Z sha d3030c7 :: blocked before merge. :: [P1] Preserve cron.run support against shipped Gateways | [P2] Preserve the accepted acknowledgement when outcome authority expires | [P2] Distinguish completed but inaccessible runs from pending work | [P2] Give management-only turns an available follow-up path | [P2] Handle signals already aborted before waiter registration
  • reviewed 2026-10-01T07:00:47.286Z sha 5c9cffb :: blocked before merge. :: [P2] Propagate caller cancellation to the completion wait
  • reviewed 2026-10-01T08:12:34.672Z sha 5c9cffb :: needs real behavior proof before merge. :: [P2] Revalidate history authority before sending the outcome
  • reviewed 2026-10-01T08:22:03.745Z sha cf942df :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-01T08:59:21.707Z sha cf942df :: needs changes before merge. :: none
  • reviewed 2026-10-01T09:30:08.506Z sha cf942df :: needs maintainer review before merge. :: none
  • reviewed 2026-10-01T10:22:20.648Z sha cf942df :: needs maintainer review before merge. :: none
  • reviewed 2026-10-01T10:41:02.940Z sha 5a3d4d3 :: needs maintainer review before merge. :: none

@obviyus

obviyus commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed review: shipped-Gateway fallback (single retry without waitTimeoutMs, mirrors the existing cron.list compact fallback), accepted ack survives a refused history read after a long wait, finished:true when the run ended but its history is hidden (self-deleting one-shot), management-only note points to the Automations page, pre-aborted signal returns at once, and the run output type declares only outcome fields so code-mode declarations stay within budget. @clawsweeper re-review

@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. and removed merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Oct 1, 2026
@obviyus

obviyus commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Owner note on caller cancellation: the turn is already released at the tool boundary. Every finalized agent tool is wrapped by wrapToolWithAbortSignal (src/agents/agent-tools.finalize.ts:53), and raceWithAbortSignal (src/agents/agent-tools.abort.ts:29) settles the tool call as soon as the run aborts, detaching the late result. So /stop does not wait for the run. What remains is the detached in-process cron.run request, which still holds a timer and a promise until the run settles or its bounded wait ends (at most 10 min). It makes no model calls and starts no runs, and the accepted run continues either way, which is the intended outcome. The in-process dispatcher deliberately withholds the signal from mutation-completion methods so a committed receipt is never turned into a cancellation. I'd keep that contract rather than thread a second wait-only signal through it. No change. @clawsweeper re-review

@obviyus

obviyus commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper Maintainer decision (Ayaan, repository maintainer): (1) Caller cancellation: accepted as is. The turn is released at the tool boundary (wrapToolWithAbortSignal / raceWithAbortSignal). What remains is a detached, bounded timer (at most 10 min) on a run that was already accepted. No wait-only signal will be threaded through the in-process mutation-completion path. (2) Management-grant turns receiving the outcome of a run they were allowed to start: accepted. It is read under the same cron.runs visibility rules, it is not a meaningful widening, and without it those turns would schedule verify jobs again. Please re-review.

@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper assist is taking a look at your question.

I queued a lightweight read-only assist pass. It will post a separate answer comment and will not edit the durable ClawSweeper review comment or trigger close, merge, repair, label, or branch changes.

Request: Maintainer decision (Ayaan, repository maintainer): (1) Caller cancellation: accepted as is. The turn is released at the tool boundary (wrapToolWithAbortSignal / raceWithAbortSignal). What remains is a detached, bounded timer (at most 10 min) on a run that was already accepted. No wait-only signal will be threaded through the in-process mutation-completion path. (2) Management-grant turns receiving the outcome of a run they were allowed to start: accepted. It is read under the same cron.runs vis...

@clawsweeper

clawsweeper Bot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper assist: The supplied decision accepts both tradeoffs: caller cancellation releases the turn while the bounded background wait continues, and management-grant callers may receive outcomes under existing visibility rules. A full correctness re-review is still needed; this assist response does not replace it.

Evidence:

  • The previous review covered current head 5c9cffbf67fd955052a01b161018ff52023ba5f7 and identified caller cancellation as its remaining finding.
  • The 07:35 UTC comment, posted by obviyus, attributes acceptance of both tradeoffs to maintainer Ayaan.
  • The PR body still says the wait “ends early if the caller aborts,” which needs clarification against the accepted detached-wait behavior.

Suggested next action: Record the accepted finding disposition and clarified cancellation behavior in the PR body, then request @clawsweeper review.


Source: #162481 (comment)
Assist reasoning: medium.

@obviyus

obviyus commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 1, 2026
@obviyus

obviyus commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper Maintainer decision (Ayaan, repository maintainer): the authority-chain proof gate is accepted without a dedicated revocation-mid-request harness. Read authority (caller authority, agent runtime, management grant) is rechecked synchronously right before the outcome is attached, with no await between the check and the response. The only remaining window is "revoked after the response was built", which every read API has. A harness that revokes mid-request would harden a hypothetical. The handler-level test covers allowed vs revoked callers through the real cron.run/cron.runs handlers. Please re-review.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 1, 2026
@obviyus

obviyus commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus
obviyus marked this pull request as ready for review October 1, 2026 10:17
@clawsweeper clawsweeper Bot removed 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 Oct 1, 2026
@obviyus
obviyus force-pushed the fix/automations-run-wait branch from 0536165 to 5a3d4d3 Compare October 1, 2026 10:35
@obviyus
obviyus merged commit 9f330ef into main Oct 1, 2026
129 checks passed
@obviyus
obviyus deleted the fix/automations-run-wait branch October 1, 2026 10:59
@obviyus

obviyus commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in 9f330ef.

  • Problem: automations run returned as soon as the run was queued. The model never learned the outcome, so it guessed or scheduled a "verify" job that couldn't see the result.
  • Fix: cron.run takes an optional waitTimeoutMs. The tool now waits up to the call's timeoutMs (default 60 s, capped at 10 min) and returns the finished run. Longer runs return a runId with a note to check runs jobId runId. Older Gateways that reject the param get the old enqueue call.
  • Proof: CI is green on d07c382 and the hosted review is ready. Before landing I regenerated the prompt snapshots for the new tool description. I also pinned timeoutMs: 1 in the native-attempt admission test, because its cron lane is deliberately blocked until after the reply, so waiting could never finish.

obviyus added a commit that referenced this pull request Oct 1, 2026
…r own conversation (#162683)

## What Problem This Solves

Fixes: when an agent runs an automation that targets its own conversation, `automations run` can hold the turn for the whole wait (60 s by default) and then return without an outcome. This happens when the job is a current-session job whose result is committed back to the calling conversation, or a named-session job written as an alias of the caller's session (for example `session:main`, or `session:agent:<id>:main` when `session.mainKey` is customized).

## User Impact

User impact: those runs return their acknowledgement immediately, as #162481 intended, so the turn ends promptly and the run, which can only start or commit after the turn, delivers as usual. Waits for isolated jobs and other sessions are unchanged.

## Why This Change Was Made

#162481 skipped the wait only for `main` jobs and for `session:<key>` targets whose raw suffix equalled the caller's session key. That check missed two real cases:

- A `current` job commits its result into `job.sessionKey`. The commit waits for that session's active work (`commitCurrentSessionCronCompletion`, from the serialized delivery contract in #126860), and that work is the calling turn.
- Named targets are run under `resolveCronAgentSessionKey`, which applies agent scoping and `mainKey` aliases (#29683 / #30654). The raw suffix `main` never equals the caller's `agent:<id>:main`.

The check now applies only to agent-turn payloads (command and script jobs run as processes and never queue behind a turn) and compares only the session the run actually depends on: the named execution target, or for `current` jobs with announce delivery the `job.sessionKey` they commit into (quiet `current` jobs run detached and never commit, so they keep waiting). Both go through the execution owner's `resolveCronAgentSessionKey` (agent scoping and `mainKey` aliases), so they compare equal to the caller's canonical session key. The raw-suffix comparison is deleted. Archival bindings such as the creator `sessionKey` that the automations tool stamps on named-session jobs are deliberately not considered, because those runs execute elsewhere and can finish while the caller waits. The `main` case and every other invariant from #162481 are unchanged.

## Evidence

- Live proof on the Telegram Test Server: owner DM, live OpenAI `gpt-5.5` behind a pass-through proxy (key never in the Gateway config), same scenario before (merge-base `ab1b93295ad`, which contains #162481) and after (`62ef249055c`). In each run the model creates three disabled jobs, then for each job calls `automations run` with `runMode: force` and replies `RUNn-DONE` once the tool returns. Times are from the user's send to the bot's reply, taken from the recorded Telegram timeline:

  | Job | Before: tool turn | Before: tool result | After: tool turn | After: tool result |
  |---|---|---|---|---|
  | `isolated` (control) | 13.8 s; report at 10.5 s | `run {status: ok, deliveryStatus: delivered, summary: ISOLATED-REPORT}` | 9.7 s; report at 7.7 s | same `run` |
  | `current` announce into the DM | 68.8 s (blocked for the full 60 s wait) | runId + note | 8.5 s | runId + note (immediate) |
  | `session:main` (alias of the DM's `agent:main:main`) | 73.8 s; NAMED-REPORT at 75.8 s | runId + note | 7.5 s; NAMED-REPORT at 10.0 s | runId + note (immediate) |

  Run history matches: before, the `session:main` run took 64.7 s because it queued behind the caller's turn; after, it took 4.3 s.
- Out of scope: in both runs the `current` job itself fails with `attempt disposed before transcript write`, so its report is never delivered (before after 62 s, after after 4.8 s). A manual run started from an agent turn inherits that turn's transcript-write lifecycle. The same error shows up as a mirror warning on the other jobs. It is pre-existing, identical on origin/main, and not touched by this PR; it is being handled separately.
- `cron.validation.test.ts` drives the real `cron.run` handler with the real binding resolver and runtime config. `session:main`, `session:agent:ops:main` with `mainKey: "work"`, and a `current` announce job bound to the caller return the plain ack without calling the wait. `isolated` jobs, quiet (`delivery: none`) `current` jobs, and a named job for another session that carries the creator's `sessionKey` (as the tool creates it), still wait. On origin/main the three own-session cases fail; the creator-`sessionKey` case catches the over-broad first version of this fix; the quiet-current case catches the second. A separate test runs a quiet `session:main` command job as a real Control UI management caller (the only callers that can see command jobs) and confirms it still waits; it fails on the previous head.
- `pnpm tsgo:core` clean. `cron.validation.test.ts`: 266 passed, 29 s wall / 25.9 s Vitest (before this PR: 264 tests, about 24 s wall / 21.4 s). `server.cron.test.ts`: 17 passed.

### Bounded cost

No new waits, runs, model calls or messages. The change only makes more own-session runs skip a wait that could not succeed anyway.

### Hermes

Hermes never blocks the caller on a manual run, so it has no equivalent of this check. Keeping the bounded wait and skipping it only when the run depends on the caller is the smallest change that keeps #162481's same-call outcome for everything else.

LOC (vs origin/main): production +21/-3 in one handler, tests +77/-9.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 2, 2026
…call (openclaw#162481)

## What Problem This Solves

Fixes: when an agent runs an automation with `automations run`, the call returns as soon as the run is queued, so the model never learns whether the run worked. It then posts guesses, or schedules a separate "verify" job. That job runs with only its own scope, can't see the result, and reports a false "blocked".

## User Impact

User impact: when an agent runs an automation, it gets the finished run (status, error, delivery status and summary) in the same tool result if the run ends within the call's `timeoutMs` (default 60 s, capped at 10 min). A longer run returns its `runId` and a note to check it later with `runs jobId runId`, not with a scheduled check. The CLI is unchanged.

## Why This Change Was Made

`cron.run` became enqueue-only in openclaw#40204 (closing openclaw#40192). Back then a synchronous run held the RPC until the 60 s gateway timeout and returned a misleading timeout error while the job kept running. openclaw#81929 later added `openclaw cron run --wait`, polling `cron.runs` from the client, and deliberately kept `cron.run` from holding the request open. The agent tool never got a wait at all. A client-side poller would not work for the tool anyway: management-grant turns can run a job, but `cron.runs` is not one of their allowed methods.

This PR keeps that invariant (no unbounded request, no false failure) and gives the one owner of run completion a bounded, opt-in wait:

- The cron service records each accepted manual run's settlement. `waitForManualRun(runId, timeoutMs, signal)` resolves when the run has written its history row. It is event-driven, with no polling.
- `cron.run` accepts an optional `waitTimeoutMs`. When the run finishes in time, the ack also carries `run`, read through the existing `cron.runs` handler so the same visibility and authority rules apply. When the wait ends first, the ack is unchanged and the run continues.
- When an agent turn runs a main-session job, or a `session:<key>` job in its own session, the call returns at once. The caller's turn holds the main lane and its own session lane: heartbeats skip while `CommandLane.Main` is busy, and a main-session run waits up to 2 min for that busy turn. Waiting there would only burn the budget.
- The `automations` tool's `run` passes its `timeoutMs` as the wait. `runs` now forwards `runId`. The tool descriptions now steer models away from verify jobs. Against a shipped Gateway, which rejects the new param before enqueueing, the tool retries the plain call once, the same way it already does for `compact` on `cron.list`.
- Accepted runs stay accepted, and outcomes go only to callers that may still read them. After the history read, the handler rechecks read authority (caller authority, agent runtime and any management grant), with no await between that check and the response. If the read or the recheck is refused, for example because a delegated grant lapsed or was revoked during a long wait, the caller gets the plain ack and nothing about the outcome. If the run finished but its history is not visible (for example a one-shot that deleted itself after succeeding), the ack carries `finished: true`. Management-only turns are pointed to the Automations page instead of `runs`.

The CLI keeps its client-side `--wait` polling in this PR. Moving it onto the Gateway wait is a separate, compatibility-reviewed follow-up.

## Evidence

- Real isolated Gateway, real Telegram plugin on the Crabline synthetic Bot API, and a deterministic Responses provider. An owner DM turn calls the `automations` tool (throwaway harness, not committed).
  - Before (origin/main build): every `run` returned only `{ ok, enqueued, runId, processInstanceId }` in under 1 s, with no outcome. The report still reached the chat, so the model couldn't tell the run had succeeded.
  - After: the isolated job's `run` returned in 4.3 s with `run { status: "ok", completionStatus: "succeeded", deliveryStatus: "delivered", summary: "FAST-REPORT-DELIVERED" }`, and the report reached the chat. A slow job (8 s, called with `timeoutMs: 2000`) returned after 2.6 s with its `runId` and the `runs jobId runId` note. The run kept going and delivered, and a later `runs` call with that `runId` returned the single finished entry. A main-session job run from the owner's main-session DM returned in 0.6 s with the note instead of blocking the turn.
- Gateway regression (`src/gateway/server.cron.test.ts`): `waitTimeoutMs: 50` returns only the `runId` while the run is blocked. `waitTimeoutMs: 10000` returns `run { runId, status: "ok", completionStatus: "succeeded", summary }`. On origin/main this fails because the closed schema rejects `waitTimeoutMs`.
- Same-session skip (`cron.validation.test.ts`): from an agent turn, `main` and `session:<own key>` jobs return the plain ack without waiting. `isolated` jobs wait.
- Authority chain (`cron.validation.test.ts`, through the real `cron.run` and `cron.runs` handlers with a stored run record): a caller that is still authorized gets `run { runId, status: "ok" }`. A caller revoked during the history read gets only the accepted ack. Before this change the revoked case turned into a request error.
- Tool (`cron-tool.test.ts`): the wait is capped at 10 min, and the RPC timeout is the wait plus 60 s. An unfinished run gets the `runs jobId runId` note.
- Tool contract (`cron-tool.output-contract.test.ts`): a shipped Gateway that rejects `waitTimeoutMs` still enqueues through a single retry, and the result stays valid against the output schema. The `run` output type only declares the outcome fields, so the generated code-mode declarations stay within their size allowance.
- Measured local wall times on head `cf942df0601` (one `node scripts/run-vitest.mjs <file>` per file; wrapper wall / Vitest duration): `cron-tool.output-contract` 5 tests, 24s / 7.0s; `cron-tool` 72 tests, 19s / 16.2s; `server-cron-lazy` 25 tests, 21s / 17.6s; `cron.validation` 261 tests, 24s / 21.4s; `server.cron` 17 tests, 46s / 43.8s. There are no CI seconds yet: CI skips the test jobs while the PR is a draft, and the only job that ran, "PR context and evidence", passed in 38s.
- `pnpm tsgo:core` is clean. Targeted tests pass: `server.cron`, `cron.validation`, `cron-tool`, `server-cron-lazy`.

### Bounded cost

- The wait is bounded by `timeoutMs` (default 60 s, capped at 10 min in the tool) and ends early if the caller aborts. The `cron.run` RPC timeout is the wait plus a 60 s enqueue budget, so the response always arrives before the client gives up.
- No new model calls or job runs. The waiter only watches a run that was already accepted. It does not retry, re-run or alert.
- No nested waits. Automation-run sessions are limited to self status/list/get/runs/remove, so a job's run cannot call `run`. A job running itself gets `already-running`. Main-session and same-session runs, which can only start after the caller's turn, skip the wait.

### Hermes

Hermes `cronjob(action="run")` sends the job to its async-delegation pool and returns a handle with "Do not wait or poll". The outcome comes back into the conversation as a new turn, and Hermes runs the job inline when no session can receive it. This PR borrows "the tool owns the follow-up, so the model doesn't poll". Feeding completions back into the conversation is not done here: OpenClaw already delivers run output to the job's target. It's a possible follow-up for long runs.

LOC (commit): production about +125/-12, tests about +96, docs +3.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 2, 2026
…r own conversation (openclaw#162683)

## What Problem This Solves

Fixes: when an agent runs an automation that targets its own conversation, `automations run` can hold the turn for the whole wait (60 s by default) and then return without an outcome. This happens when the job is a current-session job whose result is committed back to the calling conversation, or a named-session job written as an alias of the caller's session (for example `session:main`, or `session:agent:<id>:main` when `session.mainKey` is customized).

## User Impact

User impact: those runs return their acknowledgement immediately, as openclaw#162481 intended, so the turn ends promptly and the run, which can only start or commit after the turn, delivers as usual. Waits for isolated jobs and other sessions are unchanged.

## Why This Change Was Made

openclaw#162481 skipped the wait only for `main` jobs and for `session:<key>` targets whose raw suffix equalled the caller's session key. That check missed two real cases:

- A `current` job commits its result into `job.sessionKey`. The commit waits for that session's active work (`commitCurrentSessionCronCompletion`, from the serialized delivery contract in openclaw#126860), and that work is the calling turn.
- Named targets are run under `resolveCronAgentSessionKey`, which applies agent scoping and `mainKey` aliases (openclaw#29683 / openclaw#30654). The raw suffix `main` never equals the caller's `agent:<id>:main`.

The check now applies only to agent-turn payloads (command and script jobs run as processes and never queue behind a turn) and compares only the session the run actually depends on: the named execution target, or for `current` jobs with announce delivery the `job.sessionKey` they commit into (quiet `current` jobs run detached and never commit, so they keep waiting). Both go through the execution owner's `resolveCronAgentSessionKey` (agent scoping and `mainKey` aliases), so they compare equal to the caller's canonical session key. The raw-suffix comparison is deleted. Archival bindings such as the creator `sessionKey` that the automations tool stamps on named-session jobs are deliberately not considered, because those runs execute elsewhere and can finish while the caller waits. The `main` case and every other invariant from openclaw#162481 are unchanged.

## Evidence

- Live proof on the Telegram Test Server: owner DM, live OpenAI `gpt-5.5` behind a pass-through proxy (key never in the Gateway config), same scenario before (merge-base `db0e1a6e594`, which contains openclaw#162481) and after (`62ef249055c`). In each run the model creates three disabled jobs, then for each job calls `automations run` with `runMode: force` and replies `RUNn-DONE` once the tool returns. Times are from the user's send to the bot's reply, taken from the recorded Telegram timeline:

  | Job | Before: tool turn | Before: tool result | After: tool turn | After: tool result |
  |---|---|---|---|---|
  | `isolated` (control) | 13.8 s; report at 10.5 s | `run {status: ok, deliveryStatus: delivered, summary: ISOLATED-REPORT}` | 9.7 s; report at 7.7 s | same `run` |
  | `current` announce into the DM | 68.8 s (blocked for the full 60 s wait) | runId + note | 8.5 s | runId + note (immediate) |
  | `session:main` (alias of the DM's `agent:main:main`) | 73.8 s; NAMED-REPORT at 75.8 s | runId + note | 7.5 s; NAMED-REPORT at 10.0 s | runId + note (immediate) |

  Run history matches: before, the `session:main` run took 64.7 s because it queued behind the caller's turn; after, it took 4.3 s.
- Out of scope: in both runs the `current` job itself fails with `attempt disposed before transcript write`, so its report is never delivered (before after 62 s, after after 4.8 s). A manual run started from an agent turn inherits that turn's transcript-write lifecycle. The same error shows up as a mirror warning on the other jobs. It is pre-existing, identical on origin/main, and not touched by this PR; it is being handled separately.
- `cron.validation.test.ts` drives the real `cron.run` handler with the real binding resolver and runtime config. `session:main`, `session:agent:ops:main` with `mainKey: "work"`, and a `current` announce job bound to the caller return the plain ack without calling the wait. `isolated` jobs, quiet (`delivery: none`) `current` jobs, and a named job for another session that carries the creator's `sessionKey` (as the tool creates it), still wait. On origin/main the three own-session cases fail; the creator-`sessionKey` case catches the over-broad first version of this fix; the quiet-current case catches the second. A separate test runs a quiet `session:main` command job as a real Control UI management caller (the only callers that can see command jobs) and confirms it still waits; it fails on the previous head.
- `pnpm tsgo:core` clean. `cron.validation.test.ts`: 266 passed, 29 s wall / 25.9 s Vitest (before this PR: 264 tests, about 24 s wall / 21.4 s). `server.cron.test.ts`: 17 passed.

### Bounded cost

No new waits, runs, model calls or messages. The change only makes more own-session runs skip a wait that could not succeed anyway.

### Hermes

Hermes never blocks the caller on a manual run, so it has no equivalent of this check. Keeping the bounded wait and skipping it only when the run depends on the caller is the smallest change that keeps openclaw#162481's same-call outcome for everything else.

LOC (vs origin/main): production +21/-3 in one handler, tests +77/-9.

Co-authored-by: Ayaan Zaidi <[email protected]>
jalehman added a commit that referenced this pull request Oct 9, 2026
Main's #162481 made the automations run action wait up to timeoutMs
(default 60 s) for the run's outcome and added timeoutMs: 1 to this
test, whose cron lane stays blocked until after the reply. The merge in
e26c5f0 kept the branch's rewrite of the test and dropped that
argument, so every case waited for an outcome that cannot arrive and the
10 s native attempt timed out.
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: web-ui App: web-ui docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant