Skip to content

fix(cron): deliver spawned child results when scheduled agents emit no text - #117308

Merged
steipete merged 2 commits into
mainfrom
codex/cron-spawn-only-child-delivery
Aug 1, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/cron-spawn-only-child-delivery

Conversation

@steipete

@steipete steipete commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where users running isolated scheduled agents that spawn a child without emitting parent text would never receive the child's completed answer, and a successful one-shot schedule could retire before the result was delivered.

Why This Change Was Made

Carry the runner's authoritative spawn-only fact through cron finalization, bypass heartbeat suppression only for truly empty parent turns, resolve active or completed descendant output before its session is retired, and preserve normal threaded, best-effort, media-only, heartbeat, cancellation, and delivery-error behavior.

User Impact

Scheduled delegated work reliably delivers the completed child response, including threaded destinations. Timed-out or empty handoffs remain visible as retryable failures instead of falsely succeeding.

Evidence

  • Baseline private production build passed all 16 phases.
  • Unfiltered QA catalog: 120 scenarios; 112 passed, zero failed, and eight unavailable optional-tool cases were correctly skipped.
  • Runtime stress soak: 100 turns passed.
  • Real Chromium GUI chat interaction passed.
  • Live authenticated OpenAI GPT-5.4 fast streaming integrity scenario passed.
  • Final changed-source regressions: 371 assertions passed across eight complete cron, heartbeat, lifecycle, and existing subagent guard test files.
  • Full remote pnpm check:changed gate passed all selected production/test type, formatting, lint, SDK/plugin, and safety lanes.
  • Fresh mandatory autoreview: no accepted or actionable findings.
  • Testbox proof: https://github.com/openclaw/openclaw/actions/runs/30689536283

AI-assisted; reviewed against current repository policy, owner boundaries, shipped behavior, and sibling delivery contracts.

Real scheduled-agent runtime proof

Testbox ran the production-built Gateway, deterministic mock provider, real qa-channel, and a naturally scheduled UTC one-shot job. The parent accepted one real sessions_spawn, emitted no visible assistant text, the child completed, exactly one actual channel reply was delivered, and the one-shot job retired.

child=qa-direct-fallback-worker accepted=true parentVisibleText=false delivery=delivered reply=QA-SUBAGENT-DIRECT-FALLBACK-OK outboundCount=1 retired=true
  • Scenario: cron-isolated-spawn-only-child-delivery; 1 passed, 0 failed, 0 skipped.
  • Production private-QA build: all 16 phases passed; 148 SDK entry points and 3,018 Control UI modules.
  • Four complete cron/agent owner and lifecycle suites: 276/276 tests passed.
  • Six-path pnpm check:changed: fail-safe all-lanes classification, full-project typecheck, core/plugins/scripts lint, formatting, SDK/API, plugin boundaries, dead-code, database-first, and runtime-cycle checks all passed.
  • Full-branch autoreview and TruffleHog: clean; review confidence 0.97.

Current main compatibility and review follow-through

  • Latest fetched maintainer-review main: a88f3ffc9609d6fc0b70e370160801dc66d8d14c; the independently verified remote-execution baseline was aa2a5c96f69a1be639c602649d4aa2e4de8da0a8.
  • Reviewed and published PR head: df3337573c0d6e35617c98528231c60748caf857.
  • Actual full-head three-way merge against latest maintainer-review main: c3aec13051b66e1bc865d8802156b9b0c7b6acc8; no conflicts.
  • Independent Testbox production-fix merge tree: 9c4a337e63ef50969fc235443cbfea203db57e07; all five reviewed scheduler owner/test blobs preserved, and the additional QA scenario path was absent on current main.
  • Both existing ClawSweeper rank-up moves are addressed: focused owner/lifecycle checks reran against verified current-main compatibility, and the complete redacted real runtime evidence is attached above.
  • No mechanical rebase was performed: repository policy treats base drift as advisory when the actual current-main three-way merge is clean.

@openclaw-barnacle openclaw-barnacle Bot added size: M maintainer Maintainer-authored PR labels Aug 1, 2026
@steipete
steipete marked this pull request as ready for review August 1, 2026 08:38
@clawsweeper clawsweeper Bot added 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. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Aug 1, 2026
@clawsweeper

clawsweeper Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 1, 2026, 6:56 AM ET / 10:56 UTC.

ClawSweeper review

What this changes

The PR makes isolated scheduled agents wait for and deliver an accepted child agent’s final response when the parent emits no visible text, and records an error if that handoff ends without output.

Merge readiness

⚠️ Ready for maintainer review - 4 items remain

Keep this PR open for explicit maintainer review. The patch carries an accepted child-spawn fact from isolated cron finalization into the existing descendant-result delivery path, preventing a textless parent turn from suppressing its child’s reply or retiring a one-shot run as successful; no discrete correctness defect was found in the reviewed diff.

Priority: P1
Reviewed head: df3337573c0d6e35617c98528231c60748caf857
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Strong focused repair with direct runtime proof and targeted lifecycle coverage; the remaining gate is protected maintainer acceptance of delivery/session semantics.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR body supplies a redacted Testbox runtime result for a naturally scheduled production-built Gateway, real QA channel delivery, exact child reply, no duplicate outbound message, and post-delivery one-shot retirement.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body supplies a redacted Testbox runtime result for a naturally scheduled production-built Gateway, real QA channel delivery, exact child reply, no duplicate outbound message, and post-delivery one-shot retirement.
Evidence reviewed 5 items Spawn-only fact is recorded at the owning finalization boundary: The branch derives spawnOnlyHandoff only for an accepted session spawn with no payload or synthesized parent text, excludes it from heartbeat suppression, and passes that fact to delivery dispatch.
Delivery resolves descendants before marking the handoff complete: For spawn-only handoffs, delivery checks completed descendants, waits when a descendant remains active, delivers the resolved child reply through the existing direct outbound path, and returns a visible error if no child output exists.
Regression coverage exercises delivery, empty completion, and abort precedence: Focused tests cover active and already-completed descendants, direct and threaded targets, best-effort delivery, empty child completion, and abort handling; the later PR commit adds a naturally scheduled QA-channel scenario that asserts one exact outbound reply before job retirement.
Findings None None.
Security None None.

How this fits together

An isolated cron run turns a scheduled prompt into an agent session and then delivers its result to the configured channel. This change affects the finalization boundary between the parent turn, descendant-session registry, outbound delivery, and one-shot session retirement.

flowchart LR
  A[Scheduled one-shot job] --> B[Isolated parent agent]
  B --> C{Parent emits visible text?}
  C -->|No, child accepted| D[Descendant result resolver]
  C -->|Yes| E[Normal cron delivery]
  D --> F[Outbound channel delivery]
  F --> G[Record result and retire one-shot job]
  D --> H[Visible retryable handoff error]
Loading

Decision needed

Question Recommendation
Should the repository accept this verified change to isolated cron delivery and one-shot retirement semantics after an exact current-main merge review? Accept the owner-boundary repair: Merge after the normal exact-head/current-main checks confirm the existing scheduled QA proof still delivers one child result exactly once before retirement.

Why: The PR is protected with the maintainer label and changes message delivery plus session completion behavior, so explicit owner acceptance is required even though the patch and real runtime evidence are strong.

Before merge

  • Resolve merge risk (P1) - The change intentionally changes the completion boundary for spawned scheduled work; before merge, the maintainer should confirm the exact current-main merge result still preserves one-and-only-one delivery and one-shot retirement behavior.
  • Resolve merge risk (P1) - This path joins delivery and session lifecycle state, so regressions could suppress, duplicate, or mis-associate a scheduled channel reply despite the focused proof.
  • Complete next step (P2) - The protected maintainer label and deliberate delivery/session-lifecycle semantic change require explicit owner acceptance rather than an automated repair lane.
Agent review details

Security

None.

PR surface

Source +36, Tests +314, Other +194. Total +544 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 3 43 7 +36
Tests 2 315 1 +314
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 194 0 +194
Total 6 552 8 +544

Review metrics

None.

Merge-risk options

Maintainer options:

  1. Confirm the exact merge behavior before landing (recommended)
    Run the existing scheduled QA proof on the exact current-main merge result and land if it still sends the resolved child reply once before one-shot retirement.
  2. Pause for a different lifecycle policy
    Pause this PR if maintainers want textless parent turns to retain the historical non-waiting completion rule instead of treating an accepted child spawn as incomplete work.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Re-run the existing isolated scheduled QA scenario against the exact current-main merge result; require one resolved child reply, no duplicate outbound message, and retirement only after delivery.

Technical review

Best possible solution:

Adopt the single owner-boundary flow: mark accepted textless child spawns at cron finalization, resolve descendant output through the existing delivery resolver, and keep an incomplete handoff visible rather than retiring it as success.

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

Yes, at source level: an accepted child spawn with no parent payload reaches the former text-delivery early return, while the branch’s scheduled QA scenario defines the real Gateway-to-channel reproduction and after-fix result. I did not execute the scenario locally because this review is read-only.

Is this the best way to solve the issue?

Yes. The patch carries the authoritative accepted-spawn fact through the existing cron finalizer and descendant delivery machinery rather than adding a parallel delivery path or channel-specific workaround.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 4e47c4cabf8f.

Labels

Label justifications:

  • P1: A successful scheduled delegated task can currently end without delivering the child’s answer, affecting a real agent-and-channel workflow.
  • merge-risk: 🚨 message-delivery: The patch changes when cron chooses and sends the final outbound message, including threaded and best-effort paths.
  • merge-risk: 🚨 session-state: The patch changes when a spawned isolated run is considered complete and therefore when a one-shot session may retire.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body supplies a redacted Testbox runtime result for a naturally scheduled production-built Gateway, real QA channel delivery, exact child reply, no duplicate outbound message, and post-delivery one-shot retirement.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body supplies a redacted Testbox runtime result for a naturally scheduled production-built Gateway, real QA channel delivery, exact child reply, no duplicate outbound message, and post-delivery one-shot retirement.

Evidence

What I checked:

  • Spawn-only fact is recorded at the owning finalization boundary: The branch derives spawnOnlyHandoff only for an accepted session spawn with no payload or synthesized parent text, excludes it from heartbeat suppression, and passes that fact to delivery dispatch. (src/cron/isolated-agent/run-finalize.ts:336, df3337573c0d)
  • Delivery resolves descendants before marking the handoff complete: For spawn-only handoffs, delivery checks completed descendants, waits when a descendant remains active, delivers the resolved child reply through the existing direct outbound path, and returns a visible error if no child output exists. (src/cron/isolated-agent/delivery-dispatch.ts:576, df3337573c0d)
  • Regression coverage exercises delivery, empty completion, and abort precedence: Focused tests cover active and already-completed descendants, direct and threaded targets, best-effort delivery, empty child completion, and abort handling; the later PR commit adds a naturally scheduled QA-channel scenario that asserts one exact outbound reply before job retirement. (src/cron/isolated-agent/delivery-dispatch.double-announce.test.ts:1138, df3337573c0d)
  • Current owner-boundary provenance: The current extracted isolated-cron delivery and finalization modules were introduced together by the recent owner-area commit, so the handoff repair belongs in this boundary rather than in a channel adapter or timer projection. (src/cron/isolated-agent/delivery-dispatch.ts:573, 97f8f25f0b9a)
  • Follow-up review adds runtime proof rather than changing reviewed production logic: Compared with the previous reviewed head, the latest commit adds only the isolated scheduled QA scenario; the production repair remains the already-reviewed source change. (qa/scenarios/scheduling/cron-isolated-spawn-only-child-delivery.yaml:1, df3337573c0d)

Likely related people:

  • joshavant: Commit 97f8f25f0b9a725f68ffeb0ce841f1e0f82f49a8 introduced the current isolated-cron delivery and finalization modules, and blame attributes the reviewed current-main ranges to that commit. (role: current owner-boundary introducer; confidence: high; commits: 97f8f25f0b9a; files: src/cron/isolated-agent/delivery-dispatch.ts, src/cron/isolated-agent/run-finalize.ts)

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 (2 earlier review cycles)
  • reviewed 2026-08-01T08:47:39.319Z sha cc23244 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-01T10:48:15.922Z sha df33375 :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor 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 Aug 1, 2026
@steipete
steipete merged commit e9e4023 into main Aug 1, 2026
212 of 224 checks passed
@steipete
steipete deleted the codex/cron-spawn-only-child-delivery branch August 1, 2026 11:16
@steipete

steipete commented Aug 1, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

obviyus added a commit that referenced this pull request Oct 1, 2026
## What Problem This Solves

Fixes: a scheduled agent run that could not do its task is recorded as `ok`, so run history, `--wait`, and the configured failure alerts treat it as a success.

In our setup, a monthly isolated job delivered nothing for two months and every receipt said `ok`. One month the turn knew it was blocked (no shell tool) and said so in plain text, but nothing structured recorded that.

## User Impact

- A run can now fail itself. A final reply whose first line is exactly `AUTOMATION_FAILED` records the run as `error`, with the lines that follow as the error text. The existing failure handling then applies: error backoff, plus failure alerts and owner-conversation repair for jobs that already have a failure route or `failureAlert` config.
- Announce jobs still deliver the agent's explanation, with the token removed.
- These stay ok: `NO_REPLY` runs, and replies that mention the token anywhere other than as the exact first line.
- **No change to notification contracts.** An unconfigured `delivery: none` job still sends nothing to chat (no alert, no repair request). It now records the error in run history and job status (`lastRunStatus`, `consecutiveErrors`).

**Not fixed here:**
- A delegated (spawn-only) `delivery: none` run still ends `ok` and drops its child's result. The parent never sees the child's reply, so it can't report that failure with the token. Since #135318, cron turns also can't `sessions_yield`. A separate PR fixes settlement at #117308's spawn-only path.
- Notifying owners of failing `delivery: none` jobs is a pending product decision and is not part of this PR.

## Why This Change Was Made

Provenance:
- #110949 added the unattended-run preamble. It tells the model "If something failed, state plainly what failed … the scheduler owns retries and failure alerts", but no structured fact carried that statement. The scheduler only fails runs on run-level errors, error payloads, or exec-denied tool errors (`failure-signal.ts`, `execution_denied`).
- #126164 and #131228 deliberately keep execution status separate from delivery outcome. This PR keeps that separation: the token is an execution outcome the agent reports. It is parsed in the existing cron outcome owner (`resolveCronPayloadOutcome`), next to `failureSignal`, and is never derived from delivery.

The token is a strict control line, like `NO_REPLY`. Only an exact first line counts, so ordinary prose is never classified. Hermes Agent uses the same mechanism for cron (`[CRON_FAILURE]` on the first line; `cron/scheduler_prompt.py`, `cron/scheduler.py`). The preamble sentence is reworded in place: similar length, still static for prompt caching.

## Bounded cost

New or changed paths that could lead to a model call or a job run:

- **The token parse.** No new turns, runs, or notifications. It only changes the recorded status of the run that produced the reply. It is parsed only in cron finalization for that run. The delivered explanation is outbound text, never inbound, so there is no self-trigger.
- **Error status → scheduler.**
  - One-shot jobs: an agent-reported failure carries `errorClassification: { kind: "permanent" }`, so it never enters the transient-retry path. This also means wording like "network timeout" in the explanation is never text-classified into a retry or an error reason. **Tested** in `run.meta-error-status.test.ts`.
  - Recurring jobs: the existing error backoff only delays the next run (natural schedule or later), and the existing auto-disable stops the job after 10 consecutive errors. Nothing runs sooner than scheduled.
- **Repair turns.** Unchanged. They still happen only for jobs with an existing chat failure route (#161007): at most one per failure incident, and the incident marker is persisted in job state. A repair turn can't start runs, because automation control is owner-only and the request carries no sender identity. It is an ordinary conversation turn, not a cron run, so its own failure can't open another repair.
- **The preamble text.** Static; it adds no turns.

## Evidence

Isolated Gateway, qa-lab mock-openai, new scenario `qa/scenarios/scheduling/cron-blocked-outcome.yaml`:

- **Before** (origin/main): a `delivery: none` job whose reply starts with `AUTOMATION_FAILED` → `status: "ok"`, `completionStatus: "succeeded"`, and the summary holds the blocker text.
- **After:** see the result comment below. The scenario checks:
  - An owned `delivery: none` job, run 3 times → each run is `error` with the reported reason; no repair request and no chat message.
  - An unowned announce job, run twice → `error`; the reason is delivered without the token, and the existing `failed 2 times` alert fires.
  - A mid-text quote, and `NO_REPLY` (with and without announce) → `ok`.

Focused tests (fail before, pass after): `src/cron/isolated-agent/run.meta-error-status.test.ts` covers token → `error` + permanent classification, and a mid-text quote → `ok` (two cases, about 1.7 s each in the shared harness). Also passing: `failure-alerts.{account-routing,persistence,recovery}`, `service.failure-repair`, and `run.message-tool-policy` (116 tests). `pnpm tsgo:core` and oxlint on the changed files are clean. `run.message-tool-policy.test.ts` no longer pins the full preamble wording; it keeps the ordering assertion.

LOC vs origin/main: production +36/−7, unit tests +24/−2, QA scenario and mock about +180, docs +1/−1.


## Upgrade compatibility

No migration is required. The diff touches no schema, store, codec or persisted type file. Run history keeps the existing `CronRunStatus` values (`ok | error | skipped`) and the existing error/permanent classification fields, so rows written before and after this change go through the same unchanged readers. The QA scenario's "repair" wording refers to the scheduler's automation repair request, not a data repair. Existing-state compatibility is verified by the unchanged `failure-alerts.persistence` and `service.failure-repair` suites passing on this head.
obviyus added a commit that referenced this pull request Oct 1, 2026
…ld's reply (#162460)

## What Problem This Solves

Fixes: a scheduled agent turn that only spawns a subagent and ends without text records its own prompt as the run summary, and announce jobs send that prompt to the chat instead of the subagent's reply.

## User Impact

Spawn-only scheduled jobs again deliver and record the child's final reply. In our setup the delivered text was the job prompt plus the scheduler preamble ("This is an unattended scheduled run…").

## Why This Change Was Made

When a spawn-only run still has a running child at delivery time, cron waits for the child and then reads the run session's latest assistant reply through `chat.history` (the synthesis grace read from #39089), falling back to the child's own reply when the parent wrote nothing new.

#150553 started projecting cron run prompts in `chat.history` as forwarded assistant rows (role `assistant`, input provenance `internal_system` / `sourceTool: "cron"`), the same presentation sessions_send messages already had. `readLatestAssistantReply` already skips the sessions_send projection by its `inter_session` provenance (#97259), but not the new cron one. So the grace read returned the prompt as if the parent had written it, and the child fallback never ran. The cron parent gets no completion wake turn in this shape (the scenario asserts exactly two parent provider requests), so the projected prompt was the only "reply" the read could find.

The reader now skips both projected input kinds. Model replies never carry `inter_session` or `internal_system` provenance, so no real reply is skipped. All `readLatestAssistantReply` callers get the fix, including the child-session reads in the same flow.

Hermes Agent sidesteps this class of bug: its cron takes the agent run's own final response and runs delegated work inline, so it never re-reads display history. OpenClaw spawns are asynchronous and settle after the parent turn, so the reader stays. It just has to ignore rows that are inputs.

## Evidence

- Real flow, isolated Gateway with qa-lab mock-openai, `qa/scenarios/scheduling/cron-isolated-spawn-only-child-delivery.yaml`:
  - before (origin/main reader): fails. The run summary and the delivered text are the cron prompt: `"Subagent direct fallback QA check: spawn one native subagent worker. … This is an unattended scheduled run. …"`.
  - after: passes. Both cases (empty parent, heartbeat parent) deliver `QA-SUBAGENT-DIRECT-FALLBACK-OK` exactly once, record it as the summary, and retire the one-shot job.
  - A temporary dump of the run session's `chat.history` at the grace read showed the culprit: the first row was `role: "assistant"` carrying the prompt with `provenance: { kind: "internal_system", sourceTool: "cron", jobId, runId }`. Removed after diagnosis.
- The scenario was failing on main for an unrelated fixture reason: with tool search on, the mock reached `sessions_yield` through `tool_call` although the job only allows `sessions_spawn` and `read`, so the parent was stopped as a blocked tool loop before delivery ran. The scenario now sets `tools.toolSearch: false`, which restores the path it was written for (#117308, #118743).
- `src/agents/run-wait.test.ts`: the projected cron run prompt case fails before, passes after (64 tests; the new case runs in about 10 ms). `subagent-followup`, `delivery-dispatch.double-announce` and `hosted-lifecycle-dispatch` tests pass (196 total).
- Telegram Test Server, real-user recorder (`telegram-e2e-userbot`, `--backend qa-mock --dm`, `tools.toolSearch: false`): one isolated announce cron job to the DM with the same empty-parent prompt and `--tools sessions_spawn,read`, run with `cron run --wait`.
  - before (origin/main build): run `ok`; the bot sent one DM message of 966 chars, starting `Subagent direct fallback QA check: spawn one native subagent worker. …` followed by the scheduler preamble (`This is an unattended scheduled run. …`).
  - after (this branch build): run `ok`; the bot sent one DM message, exactly `QA-SUBAGENT-DIRECT-FALLBACK-OK` (30 chars).
  - The recorder needed a `tools` field on its `cron` action to pass `--tools`; that harness tweak was local and is not part of this PR.
- Live model, Telegram Test Server: same recorder, one isolated announce cron job to the DM, a live OpenAI model behind the provider slot (`tools.toolSearch: false`). The live parent chose `sessions_spawn` itself and the child answered live. Only the parent's turn after the accepted spawn was steered to end empty, because that is the spawn-only shape under test (a parent that writes text or `NO_REPLY` never reaches this read).
  - before (origin/main `600117c262b` build): run `ok`; the child answered `Titan.` live, but the bot sent one DM message of 957 chars: the cron prompt (`LIVE-SPAWN-ONLY check: call sessions_spawn exactly once …`) plus the scheduler preamble.
  - after (this head `eda6043d497` build): run `ok`; the child answered live and the bot sent one DM message, exactly the child's answer: `Titan is the largest moon of Saturn.`

LOC vs origin/main: production +4/−1, tests +22/−7, QA scenario +4.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Oct 1, 2026
## What Problem This Solves

Fixes: when a `delivery: "none"` scheduled run's turn only hands work to a subagent, the run ends `ok` right away and the child's result is dropped.

In our setup, a monthly no-delivery job spawned a worker for its report. The worker reported that it was blocked (no shell tool), but the answer was never recorded and the run showed `ok`.

## User Impact

A `delivery.mode: "none"` run whose turn only spawned children now waits for them, but no longer than the run's existing deadline, and then:
- records the child's final reply as the run output (summary), without sending it anywhere;
- stays a quiet `ok` run when the child deliberately answers `NO_REPLY`;
- fails with the existing #117308 errors when the child times out or finishes without a reply, and keeps that run's transcript.

Announce jobs, webhook jobs, runs whose parent wrote its own reply, and `sessionTarget: "current"` jobs are unchanged.

## Why This Change Was Made

Provenance:
- #117308 added spawn-only settlement (wait for the children, adopt the child's reply, fail an empty or timed-out handoff), but only in the announce path.
- #135318 rejects `sessions_yield` in cron turns so the scheduler handles child output under the job's delivery policy, and nothing resumes a cron parent after its children finish. It deliberately left no-delivery jobs without a child wait.
- So nothing owned a no-delivery spawn-only run's child output: the subagent completion is marked `intentional_non_delivery` for a cron requester, and cron has already finalized `ok`.
- #162460 (merged) fixed the reader that this settlement depends on; before it, the run recorded the projected cron prompt instead of the child's reply.

**Decision:** the maintainer approved that no-delivery spawn-only runs settle by their children. This reverses #135318's no-wait choice for that one shape, gated on `deliveryPlan.mode === "none"`. Webhook jobs keep their policy, so a child's text never reaches a webhook endpoint through this path.

**Fix:** settle directly on the children's terminal results, at the follow-up owner (`subagent-followup.ts`).
- `waitForDescendantSubagentResult` reuses the existing descendant wait (`agent.wait` plus registry settlement, under the run deadline and abort signal). It stops as soon as the children settle, because the parent-synthesis grace exists only for parents that get resumed.
- It then reads the child's reply through the existing fallback reader. A child whose terminal reply is explicitly `silent` with an `ok` outcome settles as `NO_REPLY` rather than as "no output".
- `dispatchCronDelivery` records that result for none-mode spawn-only runs. A failed handoff no longer triggers delete-after-run cleanup, so the failed one-shot job keeps its transcript, as failed executions already do.

Hermes Agent's cron runs delegated work inline and takes the run's own final response. OpenClaw children settle after the parent turn, so the scheduler reads the children's results instead. It is the same idea: the run's output is the work's final answer, and nothing waits for a reply that will never come.

## Bounded cost

- **The wait:** the existing descendant wait, under the run's existing `timeoutMs` deadline and abort signal. It ends when the children settle; there is no extra 5 s synthesis poll. A timeout records an error; it does not retry.
- **No nested waits:** cron turns cannot `sessions_yield` (#135318). The wait observes the registry and the descendants' `agent.wait`; it starts no runs and wakes no parent.
- **Error status:** a failed handoff is an ordinary execution error. Explicit child silence is not an error. One-shot jobs retry only through the existing transient-retry classifier; recurring jobs only back off.
- **Model calls:** none added.

## Evidence

Live model, Telegram Test Server, real-user recorder (`telegram-e2e-userbot`, DM), with a live OpenAI model behind the provider slot and `tools.toolSearch: false`. The scenario creates an isolated `--no-deliver` cron job, then runs `cron run --wait` and `cron runs`. The live parent chose `sessions_spawn` itself and the child answered live. Only the parent's turn after the accepted spawn was steered to end empty, because that is the spawn-only shape.
- before (main `18154cae312`): the run was `ok` after 6.5 s with an empty summary. The child answered live (`Ganymede is the largest moon of Jupiter.`) but its reply was dropped.
- after (this head): the run was `ok` after 9.0 s, `deliveryStatus: not-requested`, and its summary was the child's live answer, `Ganymede is the largest moon of Jupiter.`
- In both runs the recorder captured zero bot messages in the DM.

Real flow, isolated Gateway with qa-lab mock-openai, temporary scenario (not committed): `delivery: none` jobs with `toolsAllow: [sessions_spawn, read]`, run through `cron.run`.
- previous head of this PR (announce-path reuse): visible child recorded after 8.6 s; a child answering `NO_REPLY` became `error: cron child-session handoff completed without a final assistant payload`.
- this head: visible child recorded after 3.7 s (no synthesis grace); `NO_REPLY` child gives `ok` with an empty summary. Zero outbound messages in both cases.

`delivery-dispatch.double-announce.test.ts` runs the real follow-up module (registry and Gateway mocked only at their edges), with coherent job/plan fixtures and the production 5 s grace under fake time:
- a child settling 3 s before the run deadline is recorded (on the previous head, the watchdog fired during the grace and the result was lost);
- an explicitly silent child gives a quiet `ok`;
- a webhook spawn-only job is unchanged;
- timeout and empty-child failures keep the transcript.

The first three fail on the previous head. `delivery-dispatch.double-announce`, `subagent-followup`, `run.session-lifecycle` and `run.meta-error-status` pass (164 tests).

No overlap with Pash/Sarah changes.

LOC vs main: production +81/−2, tests +153/−4, docs +1/−1.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Oct 1, 2026
…et auto-disabled (#162686)

Related: #162391

## What Problem This Solves

Fixes two follow-ups to #162391:
- A scheduled run that hands its work to a subagent can deliver the child's `AUTOMATION_FAILED` reply verbatim and still record the run as `ok`. This happens on announce jobs, and on `delivery: none` jobs since #162474 started recording the child's answer.
- A silent (`delivery: none`) job whose agent keeps reporting a blocked task gets auto-disabled after 10 runs, and that posts an auto-disable notice even though the job has nowhere to notify.

## User Impact

- When a delegated run's settled child answer starts with `AUTOMATION_FAILED`, the run is recorded as an error with the child's explanation. Announce and current-session delivery send only the explanation, never the token. `delivery: none` runs record it without sending anything, and keep the run transcript as other failed executions do.
- A `delivery: none` job with no failure-alert route still records agent-reported failures in run history, job status, and error backoff (escalating to hourly, like any failing job). Those failures never auto-disable the job or post the auto-disable notice, so the job stays silent.
- Unchanged:
  - Runtime errors on silent jobs still auto-disable at 10 as before.
  - Announce and webhook jobs, and jobs with a configured failure route, still auto-disable on agent-reported failures.
  - `NO_REPLY` behavior.

## Why This Change Was Made

- **Settled child answers.** #162391 classified the token in `resolveCronPayloadOutcome`, which runs on the parent's reply before #117308's descendant settlement. Two places in `dispatchCronDelivery` then adopt the settled child's reply as the run's answer: the announce settlement (#117308) and the no-delivery settlement (#162474). Neither classified it. Both now go through one adoption helper that calls the shared parser `readAutomationFailedReport`, so the run's effective terminal answer is classified after settlement. `buildDeliveryState` derives one execution-failed flag from that result and uses it for both the completion status and the transcript-cleanup decision, so a failed no-delivery run is no longer cleaned up as a quiet success. `run-finalize` consumes the result the same way it already handles `pendingPresentationWarningError`: error status, permanent classification, explanation as the summary.
- **Auto-disable.** Maintainer decision: an agent-reported blocked outcome on a job with no notification owner must not lead to auto-disable. The permanent error classification now carries `reportedByAgent`. `applyJobResult` in `timer-outcomes.ts` still counts every error in `consecutiveErrors`, so status and error backoff are unchanged. It skips only the auto-disable decision, and only when all of these hold: the failure was agent-reported, `resolveFailureAlert` finds no route, and the delivery mode is `none` (webhook jobs still auto-disable).
- Hermes handles the same protocol the same way (`[CRON_FAILURE]`): its cron hint asks the agent to report a delegated child's failure on the first line. No new tool is needed.

## Bounded cost

- No new turns, runs, waits, or notifications. Parsing happens once per settled answer inside the existing finalization.
- Agent-reported failures stay permanent, so the scheduler never retries them early.
- A silent blocked job keeps the normal error backoff (30 s, 1 min, 5 min, 15 min, then hourly), so it can never run more often than an identical job on origin/main. The only difference is that it keeps running at that backed-off cadence after the 10th failure instead of being disabled.

## Evidence

### Live model, Telegram Test Server (`telegram-e2e-userbot`, DM)

Setup: the repo runner unchanged (`run-mock-sut-user-e2e.mjs --backend mock --source-gateway --dm`, Convex lease). `E2E_MOCK_SERVER_PATH` points to a throwaway proxy that stands in for the mock provider and forwards every request unchanged to the real OpenAI API. The proxy reads the key from a private file, so the Gateway only ever holds the runner's dummy key. `E2E_ROOT_CONFIG_PATCH` selects `openai/gpt-6-astra` (`tools.toolSearch: false`). A scenario `command` step creates the jobs with `openclaw automations add` and runs them. No model output was steered: the live parent chose `sessions_spawn`, and the live child and the live silent job wrote their own `AUTOMATION_FAILED` reports because they had no shell tool. The only steer is timing in case (b): before each run, `cron.update` sets `nextRunAtMs` to now and moves `lastRunAtMs` back 2 h, so the error backoff (up to 1 h) counts as served. The Gateway's own scheduler then runs the job as a normal scheduled (not forced) run.

Before = origin/main `d8a110b1a15`, plus this PR's exact base `5c4e9aba929` for case (a). After = this head `8b77715ba4f`, with all three cases in one Gateway run.

**(a) Announce job, live parent delegates to one child, the child reports `AUTOMATION_FAILED`**
- before (`d8a110b1a15`): `cron run --wait` took 99.4 s. Run `ok`, `completionStatus: succeeded`, `deliveryStatus: delivered`. The DM received bot message 43601: `AUTOMATION_FAILED` / `The command could not run because no shell execution tool is available in this session.` The token is visible.
- before (`5c4e9aba929`, the PR base): 80.7 s. Same result: run `ok`, `delivered`, and bot message 43705 reads `AUTOMATION_FAILED` / `The command could not run because no shell execution tool is available in this session.`
- after: 63.5 s. Run `error`, `completionStatus: failed`, `deliveryStatus: delivered`. Error and summary are both the explanation. The DM received bot message 43712 with only `The command could not run because no shell execution tool is available in this session.` No token.
- Pre-existing flake, not in this diff: on both sides, the announce settlement sometimes ends with `cron child-session handoff completed without a final assistant payload` even though the live child answered. That happened on 1 of 3 origin/main-side attempts (a second `d8a110b1a15` run) and on 2 of 4 attempts on this branch (both on `bfe1f0f2169`). In those cases nothing reaches the chat. The PR's change only runs after a reply has been read, so it is not involved. The no-delivery path (case c) settled on every attempt.

**(c) Same delegated job with `delivery: none` (the #162474 path)**
- before: 55.2 s. Run `ok`, `succeeded`, `deliveryStatus: not-requested`, summary `AUTOMATION_FAILED ⏎ The command could not run because no shell execution tool is available in this session.` The token is recorded as an ok answer.
- after: 36.3 s. Run `error`, `failed`, `not-requested`. Error and summary are both `The command could not run because no shell execution tool is available in this session.` The job stays enabled. No chat message.

**(b) `delivery: none` job, no failure-alert route, the live model reports `AUTOMATION_FAILED` on every run (11 scheduled runs)**
- before: runs 1–10 were all `error` (`Could not run \`node scripts/ledger-sync.mjs\`: this session only provides a file-reading tool…`), with `consecutiveErrors` 1…10. After run 10 the job was `enabled: false` with `autoDisabled: {reason: "consecutive-failures", consecutiveErrors: 10}`, so run 11 never happened. The DM received bot message 43644 (heartbeat relay): `⚠️ Your "Nightly ledger sync" automation was automatically disabled after 10 consecutive failures. … openclaw automations enable <id>`. 10 runs took 504 s.
- after: all 11 runs were `error` with the same explanation, and `consecutiveErrors` went 1…11, which keeps feeding backoff. After run 11 the job was still `enabled: true` with no `autoDisabled`. History shows 11 `error` entries. Across the whole run, the DM received exactly one bot message: 43712 from case (a). Cases (c) and (b) sent none, including during a 120 s wait after the loop. 11 runs took 526 s.

Provider evidence (proxy log): before had 1 parent `sessions_spawn` turn, 1 child turn, 10 silent-job turns, and 1 relay turn carrying the auto-disable notice. After had 2 parent `sessions_spawn` turns, 2 child turns, 11 silent-job turns, no auto-disable relay turn, and only one routine heartbeat poll, which answered `NO_REPLY`.

Environment note: in `--source-gateway` mode on both refs, Telegram inbound polling could not start (the ingress worker's plugin capture has no `dist/plugin-sdk`). So the opening DM turn was not processed, and the jobs are owned by `agent:main:main`, the DM's owner session under the default `dmScope`. Outbound delivery and relays reached the DM normally. This is the same for before and after.

### Tests

Each new test fails on the code it fixes and passes on this head:
- `delivery-dispatch.double-announce.test.ts`, real `dispatchCronDelivery`:
  - Announce settlement: a settled child reply `AUTOMATION_FAILED ⏎ …` is delivered as the explanation only and recorded as `agentReportedFailure`.
  - No-delivery settlement: uses the real `waitForDescendantSubagentResult`, with the registry mocked only at its edge. The child's report is recorded as `agentReportedFailure` with the explanation as output and summary. Nothing is sent, and the `deleteAfterRun` transcript is not deleted. Classification fails without the shared adoption helper (checked on the rebased predecessor commit), and retention fails on `bfe1f0f2169`.
- `timer-outcomes.regression.test.ts`, real `applyJobResult`, 11 agent-reported failures from a clean streak:
  - `delivery: none`: still enabled, streak 11, no auto-disable notice, backoff delays 5 min, 15 min, 1 h, 1 h. This fails on `ee6d9e07fdf` (no streak, no backoff).
  - Webhook and announce jobs: auto-disabled at 10 with one notice, same backoff.

Measured on this head, run separately (vitest `Duration`):
- `delivery-dispatch.double-announce`: 84 tests, 22.1 s.
- `timer-outcomes.regression`: 20 tests, 15.5 s.
- `run.meta-error-status`: 14 tests, 20.0 s.

All pass. `pnpm tsgo:core` passes, and oxlint and oxfmt on the changed files are clean.

Docs: `delivery.md` documents the silent agent-failure exception to the 10-failure auto-disable. `payloads.md` notes that a delegated run's settled answer is classified the same way.

LOC vs origin/main: production +54/−25, tests +100/−1, docs +2/−2.

### Review

- Adversarial re-review round 1 (on `0530dc9f`): fixed the one real finding. Webhook jobs had been exempted too; the exemption now requires delivery mode `none`, with a webhook test case.
- Round 2 (on `ee6d9e07fdf`): NOT LAND, one finding. Skipping the increment also froze error backoff, so a silent blocked job could keep running every minute. Fixed per maintainer decision with no second counter: the streak always increments, and the exemption moved to the auto-disable decision.
- Round 3 (on `bfe1f0f2169`, rebased): LAND, no findings. The rebase onto origin/main also routes the #162474 no-delivery settlement through the same adoption helper.
- ClawSweeper on `bfe1f0f2169`: fixed both findings. (P2) A failed no-delivery child run deleted its transcript; it is now kept. (P3) The auto-disable exception is now documented. Also added per-file test timings.
- Round 4 (on `8b77715ba4f`): LAND, no findings.
- Accepted tradeoffs: the exemption is not re-derived during finalized-run startup recovery. A silent job whose streak is already 10 or more from reported failures auto-disables on its next runtime error.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Oct 1, 2026
…anup delete (#162962)

## What Problem This Solves

Fixes: a scheduled job whose agent hands the work to one subagent fails with "cron child-session handoff completed without a final assistant payload" when the agent spawns that subagent with `cleanup: "delete"`.

## User Impact

User impact: spawn-only cron jobs deliver the subagent's report, whatever `cleanup` value the model picks. Before this change, most `cleanup: "delete"` runs failed even though the subagent had finished its work.

## Why This Change Was Made

A cron run reads its subagent's result from the subagent registry row after the subagent settles (#117308; #162474 added the `delivery: none` path). The registry retires a `cleanup: "delete"` row as soon as the requester settle wake finishes. For a cron requester, that wake completes immediately because nothing wakes a cron run (#99396, #135318). The row was gone about 1 s after the child ended, and the cron run reads about 5 s later, so it found nothing.

The fix is in the subagent registry, which owns the row lifetime:
- A child whose requester is a cron run is not retired on settle for `cleanup: "delete"`. The child session is still deleted right after the announce, as before; only the registry row stays until the normal archive sweep (`archiveAfterMinutes`, default 60).
- That child's handoff delivery is recorded as terminal (`not_required` with disposition `intentional_non_delivery`) instead of `pending`. A pending handoff would block the archive sweep, so this keeps the row from leaking. Nothing ever delivered to a cron run requester here anyway.

Owner decision (retention): the maintainer accepted bounded retention for this case. A cron run's child row is not retired on settle; it stays until the normal archive sweep and is not held for the cron run's lifetime. A row whose result was already captured lasts at most `archiveAfterMinutes` (or the 5-minute run TTL when archiving is off). That is the archive deadline the registry already sets on `cleanup: "delete"` rows (`archiveAtMs`); this change only stops the earlier retirement on settle. No new storage, schema or field is added.

Invariants kept: non-cron `delete` rows still retire on settle (#99396). Killed children still retire on settle. Collector rows are unchanged. The cron settle-wake shortcut still runs. No new messages or warnings.

Alternatives rejected: making the settle wake wait for the cron run to end inverts ownership and holds gateway drain. Polling faster in cron is still a race. Treating cron children as swarm collectors (`collect`) would also change concurrency slots, structured output and kill handling.

Hermes comparison: Hermes joins delegated children synchronously when the session has no consumer for later results (cron included), so this race cannot happen there. OpenClaw's cron spawn-only handoff is asynchronous by design (#117308), so the fix keeps the result where the cron run reads it.

## Evidence

- Regression test (`subagent-registry.requester-wake.e2e.test.ts`) drives the real registry and the real cron reader (`readDescendantSubagentFallbackReply`). A `cleanup: "delete"` child of a cron run settles, its settle wake completes, and the cron read returns the child's answer. The sweeper then removes the row, and no announce or agent turn starts at any point. The test runs two cases:
  - Archiving enabled (`archiveAfterMinutes: 1`), no restart. The row is retired at the archive deadline.
  - Archiving disabled (`archiveAfterMinutes: 0`), with a registry restart between the settle and the read. The row is restored from SQLite, it is still readable, and it is retired after the 5-minute run TTL. Nothing is replayed.
  - Without the retirement change, the cron read returns `undefined` (the live failure).
  - Without the delivery change, the row is never swept (`expected { runId, … } to be undefined`).
  - With both changes, the test passes.
- CI on `cd5c3796304`: every type, lint, guard and node lane passes, including `check-test-types-core-1..5` and `check-prod-types`. The only red lane is `checks-ui-e2e-real-gateway (1/2)`, in `ui/src/e2e/model-catalog-partial-refresh.real-gateway.e2e.test.ts`. The same test fails on unrelated PRs in the same window (runs 36924844797, 36924235817, 36926791756, 36927139856, 36927939720). It passes locally on this head, and this PR touches no UI or model-catalog code.
- The full `subagent-registry.requester-wake.e2e.test.ts` file passes (27 tests). It took 60.9 s wall time, with Vitest reporting 58.4 s; each new case takes about 0.8 s.
- Neighboring suites pass: lifecycle, registry, persistence, sweeper lifecycle, cron subagent follow-up (unit and worker), and announce timeout (417 tests).
- Live, real `gpt-6-astra` (Telegram Test Server userbot harness with a pass-through proxy to the real OpenAI API). There were 10 spawn-only announce cron runs per side, and the parent was told to spawn with `cleanup: "delete"`. All 10 spawns per side used `cleanup: "delete"`.
  - Before, on origin/main `4f0541eb469`: 9 of 10 runs failed with "cron child-session handoff completed without a final assistant payload". Only 1 of 10 child reports reached the Telegram chat.
  - After, on this head (fix commit `d15345587a1`; later commits only change the test): 0 of 10 handoff failures, and all 10 child reports reached the Telegram chat.
  - The child has no shell tool in this harness, so its report is an `AUTOMATION_FAILED` message and the job status is `error` on purpose. The run shows the cron run receiving and delivering the child's own answer instead of the handoff error.

## Bounded cost

- Per cron run child with `cleanup: "delete"`: one registry row (already persisted) lives until the archive sweep instead of ~1 s after settle. That is bounded by `agents.defaults.subagents.archiveAfterMinutes` (default 60), or by the 5-minute run TTL when archiving is disabled.
- No new timers, waits, polling, model calls or messages. The child session is still deleted at announce time.

## LOC (vs origin/main)

Production +11 / -2, tests +67 (net).
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 2, 2026
## What Problem This Solves

Fixes: a scheduled agent run that could not do its task is recorded as `ok`, so run history, `--wait`, and the configured failure alerts treat it as a success.

In our setup, a monthly isolated job delivered nothing for two months and every receipt said `ok`. One month the turn knew it was blocked (no shell tool) and said so in plain text, but nothing structured recorded that.

## User Impact

- A run can now fail itself. A final reply whose first line is exactly `AUTOMATION_FAILED` records the run as `error`, with the lines that follow as the error text. The existing failure handling then applies: error backoff, plus failure alerts and owner-conversation repair for jobs that already have a failure route or `failureAlert` config.
- Announce jobs still deliver the agent's explanation, with the token removed.
- These stay ok: `NO_REPLY` runs, and replies that mention the token anywhere other than as the exact first line.
- **No change to notification contracts.** An unconfigured `delivery: none` job still sends nothing to chat (no alert, no repair request). It now records the error in run history and job status (`lastRunStatus`, `consecutiveErrors`).

**Not fixed here:**
- A delegated (spawn-only) `delivery: none` run still ends `ok` and drops its child's result. The parent never sees the child's reply, so it can't report that failure with the token. Since openclaw#135318, cron turns also can't `sessions_yield`. A separate PR fixes settlement at openclaw#117308's spawn-only path.
- Notifying owners of failing `delivery: none` jobs is a pending product decision and is not part of this PR.

## Why This Change Was Made

Provenance:
- openclaw#110949 added the unattended-run preamble. It tells the model "If something failed, state plainly what failed … the scheduler owns retries and failure alerts", but no structured fact carried that statement. The scheduler only fails runs on run-level errors, error payloads, or exec-denied tool errors (`failure-signal.ts`, `execution_denied`).
- openclaw#126164 and openclaw#131228 deliberately keep execution status separate from delivery outcome. This PR keeps that separation: the token is an execution outcome the agent reports. It is parsed in the existing cron outcome owner (`resolveCronPayloadOutcome`), next to `failureSignal`, and is never derived from delivery.

The token is a strict control line, like `NO_REPLY`. Only an exact first line counts, so ordinary prose is never classified. Hermes Agent uses the same mechanism for cron (`[CRON_FAILURE]` on the first line; `cron/scheduler_prompt.py`, `cron/scheduler.py`). The preamble sentence is reworded in place: similar length, still static for prompt caching.

## Bounded cost

New or changed paths that could lead to a model call or a job run:

- **The token parse.** No new turns, runs, or notifications. It only changes the recorded status of the run that produced the reply. It is parsed only in cron finalization for that run. The delivered explanation is outbound text, never inbound, so there is no self-trigger.
- **Error status → scheduler.**
  - One-shot jobs: an agent-reported failure carries `errorClassification: { kind: "permanent" }`, so it never enters the transient-retry path. This also means wording like "network timeout" in the explanation is never text-classified into a retry or an error reason. **Tested** in `run.meta-error-status.test.ts`.
  - Recurring jobs: the existing error backoff only delays the next run (natural schedule or later), and the existing auto-disable stops the job after 10 consecutive errors. Nothing runs sooner than scheduled.
- **Repair turns.** Unchanged. They still happen only for jobs with an existing chat failure route (openclaw#161007): at most one per failure incident, and the incident marker is persisted in job state. A repair turn can't start runs, because automation control is owner-only and the request carries no sender identity. It is an ordinary conversation turn, not a cron run, so its own failure can't open another repair.
- **The preamble text.** Static; it adds no turns.

## Evidence

Isolated Gateway, qa-lab mock-openai, new scenario `qa/scenarios/scheduling/cron-blocked-outcome.yaml`:

- **Before** (origin/main): a `delivery: none` job whose reply starts with `AUTOMATION_FAILED` → `status: "ok"`, `completionStatus: "succeeded"`, and the summary holds the blocker text.
- **After:** see the result comment below. The scenario checks:
  - An owned `delivery: none` job, run 3 times → each run is `error` with the reported reason; no repair request and no chat message.
  - An unowned announce job, run twice → `error`; the reason is delivered without the token, and the existing `failed 2 times` alert fires.
  - A mid-text quote, and `NO_REPLY` (with and without announce) → `ok`.

Focused tests (fail before, pass after): `src/cron/isolated-agent/run.meta-error-status.test.ts` covers token → `error` + permanent classification, and a mid-text quote → `ok` (two cases, about 1.7 s each in the shared harness). Also passing: `failure-alerts.{account-routing,persistence,recovery}`, `service.failure-repair`, and `run.message-tool-policy` (116 tests). `pnpm tsgo:core` and oxlint on the changed files are clean. `run.message-tool-policy.test.ts` no longer pins the full preamble wording; it keeps the ordering assertion.

LOC vs origin/main: production +36/−7, unit tests +24/−2, QA scenario and mock about +180, docs +1/−1.


## Upgrade compatibility

No migration is required. The diff touches no schema, store, codec or persisted type file. Run history keeps the existing `CronRunStatus` values (`ok | error | skipped`) and the existing error/permanent classification fields, so rows written before and after this change go through the same unchanged readers. The QA scenario's "repair" wording refers to the scheduler's automation repair request, not a data repair. Existing-state compatibility is verified by the unchanged `failure-alerts.persistence` and `service.failure-repair` suites passing on this head.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 2, 2026
…ld's reply (openclaw#162460)

## What Problem This Solves

Fixes: a scheduled agent turn that only spawns a subagent and ends without text records its own prompt as the run summary, and announce jobs send that prompt to the chat instead of the subagent's reply.

## User Impact

Spawn-only scheduled jobs again deliver and record the child's final reply. In our setup the delivered text was the job prompt plus the scheduler preamble ("This is an unattended scheduled run…").

## Why This Change Was Made

When a spawn-only run still has a running child at delivery time, cron waits for the child and then reads the run session's latest assistant reply through `chat.history` (the synthesis grace read from openclaw#39089), falling back to the child's own reply when the parent wrote nothing new.

openclaw#150553 started projecting cron run prompts in `chat.history` as forwarded assistant rows (role `assistant`, input provenance `internal_system` / `sourceTool: "cron"`), the same presentation sessions_send messages already had. `readLatestAssistantReply` already skips the sessions_send projection by its `inter_session` provenance (openclaw#97259), but not the new cron one. So the grace read returned the prompt as if the parent had written it, and the child fallback never ran. The cron parent gets no completion wake turn in this shape (the scenario asserts exactly two parent provider requests), so the projected prompt was the only "reply" the read could find.

The reader now skips both projected input kinds. Model replies never carry `inter_session` or `internal_system` provenance, so no real reply is skipped. All `readLatestAssistantReply` callers get the fix, including the child-session reads in the same flow.

Hermes Agent sidesteps this class of bug: its cron takes the agent run's own final response and runs delegated work inline, so it never re-reads display history. OpenClaw spawns are asynchronous and settle after the parent turn, so the reader stays. It just has to ignore rows that are inputs.

## Evidence

- Real flow, isolated Gateway with qa-lab mock-openai, `qa/scenarios/scheduling/cron-isolated-spawn-only-child-delivery.yaml`:
  - before (origin/main reader): fails. The run summary and the delivered text are the cron prompt: `"Subagent direct fallback QA check: spawn one native subagent worker. … This is an unattended scheduled run. …"`.
  - after: passes. Both cases (empty parent, heartbeat parent) deliver `QA-SUBAGENT-DIRECT-FALLBACK-OK` exactly once, record it as the summary, and retire the one-shot job.
  - A temporary dump of the run session's `chat.history` at the grace read showed the culprit: the first row was `role: "assistant"` carrying the prompt with `provenance: { kind: "internal_system", sourceTool: "cron", jobId, runId }`. Removed after diagnosis.
- The scenario was failing on main for an unrelated fixture reason: with tool search on, the mock reached `sessions_yield` through `tool_call` although the job only allows `sessions_spawn` and `read`, so the parent was stopped as a blocked tool loop before delivery ran. The scenario now sets `tools.toolSearch: false`, which restores the path it was written for (openclaw#117308, openclaw#118743).
- `src/agents/run-wait.test.ts`: the projected cron run prompt case fails before, passes after (64 tests; the new case runs in about 10 ms). `subagent-followup`, `delivery-dispatch.double-announce` and `hosted-lifecycle-dispatch` tests pass (196 total).
- Telegram Test Server, real-user recorder (`telegram-e2e-userbot`, `--backend qa-mock --dm`, `tools.toolSearch: false`): one isolated announce cron job to the DM with the same empty-parent prompt and `--tools sessions_spawn,read`, run with `cron run --wait`.
  - before (origin/main build): run `ok`; the bot sent one DM message of 966 chars, starting `Subagent direct fallback QA check: spawn one native subagent worker. …` followed by the scheduler preamble (`This is an unattended scheduled run. …`).
  - after (this branch build): run `ok`; the bot sent one DM message, exactly `QA-SUBAGENT-DIRECT-FALLBACK-OK` (30 chars).
  - The recorder needed a `tools` field on its `cron` action to pass `--tools`; that harness tweak was local and is not part of this PR.
- Live model, Telegram Test Server: same recorder, one isolated announce cron job to the DM, a live OpenAI model behind the provider slot (`tools.toolSearch: false`). The live parent chose `sessions_spawn` itself and the child answered live. Only the parent's turn after the accepted spawn was steered to end empty, because that is the spawn-only shape under test (a parent that writes text or `NO_REPLY` never reaches this read).
  - before (origin/main `e44e2640877` build): run `ok`; the child answered `Titan.` live, but the bot sent one DM message of 957 chars: the cron prompt (`LIVE-SPAWN-ONLY check: call sessions_spawn exactly once …`) plus the scheduler preamble.
  - after (this head `eda6043d497` build): run `ok`; the child answered live and the bot sent one DM message, exactly the child's answer: `Titan is the largest moon of Saturn.`

LOC vs origin/main: production +4/−1, tests +22/−7, QA scenario +4.

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

## What Problem This Solves

Fixes: when a `delivery: "none"` scheduled run's turn only hands work to a subagent, the run ends `ok` right away and the child's result is dropped.

In our setup, a monthly no-delivery job spawned a worker for its report. The worker reported that it was blocked (no shell tool), but the answer was never recorded and the run showed `ok`.

## User Impact

A `delivery.mode: "none"` run whose turn only spawned children now waits for them, but no longer than the run's existing deadline, and then:
- records the child's final reply as the run output (summary), without sending it anywhere;
- stays a quiet `ok` run when the child deliberately answers `NO_REPLY`;
- fails with the existing openclaw#117308 errors when the child times out or finishes without a reply, and keeps that run's transcript.

Announce jobs, webhook jobs, runs whose parent wrote its own reply, and `sessionTarget: "current"` jobs are unchanged.

## Why This Change Was Made

Provenance:
- openclaw#117308 added spawn-only settlement (wait for the children, adopt the child's reply, fail an empty or timed-out handoff), but only in the announce path.
- openclaw#135318 rejects `sessions_yield` in cron turns so the scheduler handles child output under the job's delivery policy, and nothing resumes a cron parent after its children finish. It deliberately left no-delivery jobs without a child wait.
- So nothing owned a no-delivery spawn-only run's child output: the subagent completion is marked `intentional_non_delivery` for a cron requester, and cron has already finalized `ok`.
- openclaw#162460 (merged) fixed the reader that this settlement depends on; before it, the run recorded the projected cron prompt instead of the child's reply.

**Decision:** the maintainer approved that no-delivery spawn-only runs settle by their children. This reverses openclaw#135318's no-wait choice for that one shape, gated on `deliveryPlan.mode === "none"`. Webhook jobs keep their policy, so a child's text never reaches a webhook endpoint through this path.

**Fix:** settle directly on the children's terminal results, at the follow-up owner (`subagent-followup.ts`).
- `waitForDescendantSubagentResult` reuses the existing descendant wait (`agent.wait` plus registry settlement, under the run deadline and abort signal). It stops as soon as the children settle, because the parent-synthesis grace exists only for parents that get resumed.
- It then reads the child's reply through the existing fallback reader. A child whose terminal reply is explicitly `silent` with an `ok` outcome settles as `NO_REPLY` rather than as "no output".
- `dispatchCronDelivery` records that result for none-mode spawn-only runs. A failed handoff no longer triggers delete-after-run cleanup, so the failed one-shot job keeps its transcript, as failed executions already do.

Hermes Agent's cron runs delegated work inline and takes the run's own final response. OpenClaw children settle after the parent turn, so the scheduler reads the children's results instead. It is the same idea: the run's output is the work's final answer, and nothing waits for a reply that will never come.

## Bounded cost

- **The wait:** the existing descendant wait, under the run's existing `timeoutMs` deadline and abort signal. It ends when the children settle; there is no extra 5 s synthesis poll. A timeout records an error; it does not retry.
- **No nested waits:** cron turns cannot `sessions_yield` (openclaw#135318). The wait observes the registry and the descendants' `agent.wait`; it starts no runs and wakes no parent.
- **Error status:** a failed handoff is an ordinary execution error. Explicit child silence is not an error. One-shot jobs retry only through the existing transient-retry classifier; recurring jobs only back off.
- **Model calls:** none added.

## Evidence

Live model, Telegram Test Server, real-user recorder (`telegram-e2e-userbot`, DM), with a live OpenAI model behind the provider slot and `tools.toolSearch: false`. The scenario creates an isolated `--no-deliver` cron job, then runs `cron run --wait` and `cron runs`. The live parent chose `sessions_spawn` itself and the child answered live. Only the parent's turn after the accepted spawn was steered to end empty, because that is the spawn-only shape.
- before (main `553e04cf3c3`): the run was `ok` after 6.5 s with an empty summary. The child answered live (`Ganymede is the largest moon of Jupiter.`) but its reply was dropped.
- after (this head): the run was `ok` after 9.0 s, `deliveryStatus: not-requested`, and its summary was the child's live answer, `Ganymede is the largest moon of Jupiter.`
- In both runs the recorder captured zero bot messages in the DM.

Real flow, isolated Gateway with qa-lab mock-openai, temporary scenario (not committed): `delivery: none` jobs with `toolsAllow: [sessions_spawn, read]`, run through `cron.run`.
- previous head of this PR (announce-path reuse): visible child recorded after 8.6 s; a child answering `NO_REPLY` became `error: cron child-session handoff completed without a final assistant payload`.
- this head: visible child recorded after 3.7 s (no synthesis grace); `NO_REPLY` child gives `ok` with an empty summary. Zero outbound messages in both cases.

`delivery-dispatch.double-announce.test.ts` runs the real follow-up module (registry and Gateway mocked only at their edges), with coherent job/plan fixtures and the production 5 s grace under fake time:
- a child settling 3 s before the run deadline is recorded (on the previous head, the watchdog fired during the grace and the result was lost);
- an explicitly silent child gives a quiet `ok`;
- a webhook spawn-only job is unchanged;
- timeout and empty-child failures keep the transcript.

The first three fail on the previous head. `delivery-dispatch.double-announce`, `subagent-followup`, `run.session-lifecycle` and `run.meta-error-status` pass (164 tests).

No overlap with Pash/Sarah changes.

LOC vs main: production +81/−2, tests +153/−4, docs +1/−1.

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

Related: openclaw#162391

## What Problem This Solves

Fixes two follow-ups to openclaw#162391:
- A scheduled run that hands its work to a subagent can deliver the child's `AUTOMATION_FAILED` reply verbatim and still record the run as `ok`. This happens on announce jobs, and on `delivery: none` jobs since openclaw#162474 started recording the child's answer.
- A silent (`delivery: none`) job whose agent keeps reporting a blocked task gets auto-disabled after 10 runs, and that posts an auto-disable notice even though the job has nowhere to notify.

## User Impact

- When a delegated run's settled child answer starts with `AUTOMATION_FAILED`, the run is recorded as an error with the child's explanation. Announce and current-session delivery send only the explanation, never the token. `delivery: none` runs record it without sending anything, and keep the run transcript as other failed executions do.
- A `delivery: none` job with no failure-alert route still records agent-reported failures in run history, job status, and error backoff (escalating to hourly, like any failing job). Those failures never auto-disable the job or post the auto-disable notice, so the job stays silent.
- Unchanged:
  - Runtime errors on silent jobs still auto-disable at 10 as before.
  - Announce and webhook jobs, and jobs with a configured failure route, still auto-disable on agent-reported failures.
  - `NO_REPLY` behavior.

## Why This Change Was Made

- **Settled child answers.** openclaw#162391 classified the token in `resolveCronPayloadOutcome`, which runs on the parent's reply before openclaw#117308's descendant settlement. Two places in `dispatchCronDelivery` then adopt the settled child's reply as the run's answer: the announce settlement (openclaw#117308) and the no-delivery settlement (openclaw#162474). Neither classified it. Both now go through one adoption helper that calls the shared parser `readAutomationFailedReport`, so the run's effective terminal answer is classified after settlement. `buildDeliveryState` derives one execution-failed flag from that result and uses it for both the completion status and the transcript-cleanup decision, so a failed no-delivery run is no longer cleaned up as a quiet success. `run-finalize` consumes the result the same way it already handles `pendingPresentationWarningError`: error status, permanent classification, explanation as the summary.
- **Auto-disable.** Maintainer decision: an agent-reported blocked outcome on a job with no notification owner must not lead to auto-disable. The permanent error classification now carries `reportedByAgent`. `applyJobResult` in `timer-outcomes.ts` still counts every error in `consecutiveErrors`, so status and error backoff are unchanged. It skips only the auto-disable decision, and only when all of these hold: the failure was agent-reported, `resolveFailureAlert` finds no route, and the delivery mode is `none` (webhook jobs still auto-disable).
- Hermes handles the same protocol the same way (`[CRON_FAILURE]`): its cron hint asks the agent to report a delegated child's failure on the first line. No new tool is needed.

## Bounded cost

- No new turns, runs, waits, or notifications. Parsing happens once per settled answer inside the existing finalization.
- Agent-reported failures stay permanent, so the scheduler never retries them early.
- A silent blocked job keeps the normal error backoff (30 s, 1 min, 5 min, 15 min, then hourly), so it can never run more often than an identical job on origin/main. The only difference is that it keeps running at that backed-off cadence after the 10th failure instead of being disabled.

## Evidence

### Live model, Telegram Test Server (`telegram-e2e-userbot`, DM)

Setup: the repo runner unchanged (`run-mock-sut-user-e2e.mjs --backend mock --source-gateway --dm`, Convex lease). `E2E_MOCK_SERVER_PATH` points to a throwaway proxy that stands in for the mock provider and forwards every request unchanged to the real OpenAI API. The proxy reads the key from a private file, so the Gateway only ever holds the runner's dummy key. `E2E_ROOT_CONFIG_PATCH` selects `openai/gpt-6-astra` (`tools.toolSearch: false`). A scenario `command` step creates the jobs with `openclaw automations add` and runs them. No model output was steered: the live parent chose `sessions_spawn`, and the live child and the live silent job wrote their own `AUTOMATION_FAILED` reports because they had no shell tool. The only steer is timing in case (b): before each run, `cron.update` sets `nextRunAtMs` to now and moves `lastRunAtMs` back 2 h, so the error backoff (up to 1 h) counts as served. The Gateway's own scheduler then runs the job as a normal scheduled (not forced) run.

Before = origin/main `88f22a318b4`, plus this PR's exact base `2ae97b30828` for case (a). After = this head `8b77715ba4f`, with all three cases in one Gateway run.

**(a) Announce job, live parent delegates to one child, the child reports `AUTOMATION_FAILED`**
- before (`88f22a318b4`): `cron run --wait` took 99.4 s. Run `ok`, `completionStatus: succeeded`, `deliveryStatus: delivered`. The DM received bot message 43601: `AUTOMATION_FAILED` / `The command could not run because no shell execution tool is available in this session.` The token is visible.
- before (`2ae97b30828`, the PR base): 80.7 s. Same result: run `ok`, `delivered`, and bot message 43705 reads `AUTOMATION_FAILED` / `The command could not run because no shell execution tool is available in this session.`
- after: 63.5 s. Run `error`, `completionStatus: failed`, `deliveryStatus: delivered`. Error and summary are both the explanation. The DM received bot message 43712 with only `The command could not run because no shell execution tool is available in this session.` No token.
- Pre-existing flake, not in this diff: on both sides, the announce settlement sometimes ends with `cron child-session handoff completed without a final assistant payload` even though the live child answered. That happened on 1 of 3 origin/main-side attempts (a second `88f22a318b4` run) and on 2 of 4 attempts on this branch (both on `bfe1f0f2169`). In those cases nothing reaches the chat. The PR's change only runs after a reply has been read, so it is not involved. The no-delivery path (case c) settled on every attempt.

**(c) Same delegated job with `delivery: none` (the openclaw#162474 path)**
- before: 55.2 s. Run `ok`, `succeeded`, `deliveryStatus: not-requested`, summary `AUTOMATION_FAILED ⏎ The command could not run because no shell execution tool is available in this session.` The token is recorded as an ok answer.
- after: 36.3 s. Run `error`, `failed`, `not-requested`. Error and summary are both `The command could not run because no shell execution tool is available in this session.` The job stays enabled. No chat message.

**(b) `delivery: none` job, no failure-alert route, the live model reports `AUTOMATION_FAILED` on every run (11 scheduled runs)**
- before: runs 1–10 were all `error` (`Could not run \`node scripts/ledger-sync.mjs\`: this session only provides a file-reading tool…`), with `consecutiveErrors` 1…10. After run 10 the job was `enabled: false` with `autoDisabled: {reason: "consecutive-failures", consecutiveErrors: 10}`, so run 11 never happened. The DM received bot message 43644 (heartbeat relay): `⚠️ Your "Nightly ledger sync" automation was automatically disabled after 10 consecutive failures. … openclaw automations enable <id>`. 10 runs took 504 s.
- after: all 11 runs were `error` with the same explanation, and `consecutiveErrors` went 1…11, which keeps feeding backoff. After run 11 the job was still `enabled: true` with no `autoDisabled`. History shows 11 `error` entries. Across the whole run, the DM received exactly one bot message: 43712 from case (a). Cases (c) and (b) sent none, including during a 120 s wait after the loop. 11 runs took 526 s.

Provider evidence (proxy log): before had 1 parent `sessions_spawn` turn, 1 child turn, 10 silent-job turns, and 1 relay turn carrying the auto-disable notice. After had 2 parent `sessions_spawn` turns, 2 child turns, 11 silent-job turns, no auto-disable relay turn, and only one routine heartbeat poll, which answered `NO_REPLY`.

Environment note: in `--source-gateway` mode on both refs, Telegram inbound polling could not start (the ingress worker's plugin capture has no `dist/plugin-sdk`). So the opening DM turn was not processed, and the jobs are owned by `agent:main:main`, the DM's owner session under the default `dmScope`. Outbound delivery and relays reached the DM normally. This is the same for before and after.

### Tests

Each new test fails on the code it fixes and passes on this head:
- `delivery-dispatch.double-announce.test.ts`, real `dispatchCronDelivery`:
  - Announce settlement: a settled child reply `AUTOMATION_FAILED ⏎ …` is delivered as the explanation only and recorded as `agentReportedFailure`.
  - No-delivery settlement: uses the real `waitForDescendantSubagentResult`, with the registry mocked only at its edge. The child's report is recorded as `agentReportedFailure` with the explanation as output and summary. Nothing is sent, and the `deleteAfterRun` transcript is not deleted. Classification fails without the shared adoption helper (checked on the rebased predecessor commit), and retention fails on `bfe1f0f2169`.
- `timer-outcomes.regression.test.ts`, real `applyJobResult`, 11 agent-reported failures from a clean streak:
  - `delivery: none`: still enabled, streak 11, no auto-disable notice, backoff delays 5 min, 15 min, 1 h, 1 h. This fails on `ee6d9e07fdf` (no streak, no backoff).
  - Webhook and announce jobs: auto-disabled at 10 with one notice, same backoff.

Measured on this head, run separately (vitest `Duration`):
- `delivery-dispatch.double-announce`: 84 tests, 22.1 s.
- `timer-outcomes.regression`: 20 tests, 15.5 s.
- `run.meta-error-status`: 14 tests, 20.0 s.

All pass. `pnpm tsgo:core` passes, and oxlint and oxfmt on the changed files are clean.

Docs: `delivery.md` documents the silent agent-failure exception to the 10-failure auto-disable. `payloads.md` notes that a delegated run's settled answer is classified the same way.

LOC vs origin/main: production +54/−25, tests +100/−1, docs +2/−2.

### Review

- Adversarial re-review round 1 (on `0530dc9f`): fixed the one real finding. Webhook jobs had been exempted too; the exemption now requires delivery mode `none`, with a webhook test case.
- Round 2 (on `ee6d9e07fdf`): NOT LAND, one finding. Skipping the increment also froze error backoff, so a silent blocked job could keep running every minute. Fixed per maintainer decision with no second counter: the streak always increments, and the exemption moved to the auto-disable decision.
- Round 3 (on `bfe1f0f2169`, rebased): LAND, no findings. The rebase onto origin/main also routes the openclaw#162474 no-delivery settlement through the same adoption helper.
- ClawSweeper on `bfe1f0f2169`: fixed both findings. (P2) A failed no-delivery child run deleted its transcript; it is now kept. (P3) The auto-disable exception is now documented. Also added per-file test timings.
- Round 4 (on `8b77715ba4f`): LAND, no findings.
- Accepted tradeoffs: the exemption is not re-derived during finalized-run startup recovery. A silent job whose streak is already 10 or more from reported failures auto-disables on its next runtime error.

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

## What Problem This Solves

Fixes: a scheduled job whose agent hands the work to one subagent fails with "cron child-session handoff completed without a final assistant payload" when the agent spawns that subagent with `cleanup: "delete"`.

## User Impact

User impact: spawn-only cron jobs deliver the subagent's report, whatever `cleanup` value the model picks. Before this change, most `cleanup: "delete"` runs failed even though the subagent had finished its work.

## Why This Change Was Made

A cron run reads its subagent's result from the subagent registry row after the subagent settles (openclaw#117308; openclaw#162474 added the `delivery: none` path). The registry retires a `cleanup: "delete"` row as soon as the requester settle wake finishes. For a cron requester, that wake completes immediately because nothing wakes a cron run (openclaw#99396, openclaw#135318). The row was gone about 1 s after the child ended, and the cron run reads about 5 s later, so it found nothing.

The fix is in the subagent registry, which owns the row lifetime:
- A child whose requester is a cron run is not retired on settle for `cleanup: "delete"`. The child session is still deleted right after the announce, as before; only the registry row stays until the normal archive sweep (`archiveAfterMinutes`, default 60).
- That child's handoff delivery is recorded as terminal (`not_required` with disposition `intentional_non_delivery`) instead of `pending`. A pending handoff would block the archive sweep, so this keeps the row from leaking. Nothing ever delivered to a cron run requester here anyway.

Owner decision (retention): the maintainer accepted bounded retention for this case. A cron run's child row is not retired on settle; it stays until the normal archive sweep and is not held for the cron run's lifetime. A row whose result was already captured lasts at most `archiveAfterMinutes` (or the 5-minute run TTL when archiving is off). That is the archive deadline the registry already sets on `cleanup: "delete"` rows (`archiveAtMs`); this change only stops the earlier retirement on settle. No new storage, schema or field is added.

Invariants kept: non-cron `delete` rows still retire on settle (openclaw#99396). Killed children still retire on settle. Collector rows are unchanged. The cron settle-wake shortcut still runs. No new messages or warnings.

Alternatives rejected: making the settle wake wait for the cron run to end inverts ownership and holds gateway drain. Polling faster in cron is still a race. Treating cron children as swarm collectors (`collect`) would also change concurrency slots, structured output and kill handling.

Hermes comparison: Hermes joins delegated children synchronously when the session has no consumer for later results (cron included), so this race cannot happen there. OpenClaw's cron spawn-only handoff is asynchronous by design (openclaw#117308), so the fix keeps the result where the cron run reads it.

## Evidence

- Regression test (`subagent-registry.requester-wake.e2e.test.ts`) drives the real registry and the real cron reader (`readDescendantSubagentFallbackReply`). A `cleanup: "delete"` child of a cron run settles, its settle wake completes, and the cron read returns the child's answer. The sweeper then removes the row, and no announce or agent turn starts at any point. The test runs two cases:
  - Archiving enabled (`archiveAfterMinutes: 1`), no restart. The row is retired at the archive deadline.
  - Archiving disabled (`archiveAfterMinutes: 0`), with a registry restart between the settle and the read. The row is restored from SQLite, it is still readable, and it is retired after the 5-minute run TTL. Nothing is replayed.
  - Without the retirement change, the cron read returns `undefined` (the live failure).
  - Without the delivery change, the row is never swept (`expected { runId, … } to be undefined`).
  - With both changes, the test passes.
- CI on `cd5c3796304`: every type, lint, guard and node lane passes, including `check-test-types-core-1..5` and `check-prod-types`. The only red lane is `checks-ui-e2e-real-gateway (1/2)`, in `ui/src/e2e/model-catalog-partial-refresh.real-gateway.e2e.test.ts`. The same test fails on unrelated PRs in the same window (runs 36924844797, 36924235817, 36926791756, 36927139856, 36927939720). It passes locally on this head, and this PR touches no UI or model-catalog code.
- The full `subagent-registry.requester-wake.e2e.test.ts` file passes (27 tests). It took 60.9 s wall time, with Vitest reporting 58.4 s; each new case takes about 0.8 s.
- Neighboring suites pass: lifecycle, registry, persistence, sweeper lifecycle, cron subagent follow-up (unit and worker), and announce timeout (417 tests).
- Live, real `gpt-6-astra` (Telegram Test Server userbot harness with a pass-through proxy to the real OpenAI API). There were 10 spawn-only announce cron runs per side, and the parent was told to spawn with `cleanup: "delete"`. All 10 spawns per side used `cleanup: "delete"`.
  - Before, on origin/main `559f2afe45e`: 9 of 10 runs failed with "cron child-session handoff completed without a final assistant payload". Only 1 of 10 child reports reached the Telegram chat.
  - After, on this head (fix commit `d15345587a1`; later commits only change the test): 0 of 10 handoff failures, and all 10 child reports reached the Telegram chat.
  - The child has no shell tool in this harness, so its report is an `AUTOMATION_FAILED` message and the job status is `error` on purpose. The run shows the cron run receiving and delivering the child's own answer instead of the handoff error.

## Bounded cost

- Per cron run child with `cleanup: "delete"`: one registry row (already persisted) lives until the archive sweep instead of ~1 s after settle. That is bounded by `agents.defaults.subagents.archiveAfterMinutes` (default 60), or by the 5-minute run TTL when archiving is disabled.
- No new timers, waits, polling, model calls or messages. The child session is still deleted at announce time.

## LOC (vs origin/main)

Production +11 / -2, tests +67 (net).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: qa-lab maintainer Maintainer-authored PR merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: L 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