Skip to content

feat(cron): run provenance, job kinds, agentTurn token budget, typed completion causes - #135889

Closed
TheArchitectit wants to merge 27 commits into
openclaw:mainfrom
TheArchitectit:feat/automation-single-pane
Closed

TheArchitectit wants to merge 27 commits into
openclaw:mainfrom
TheArchitectit:feat/automation-single-pane

Conversation

@TheArchitectit

@TheArchitectit TheArchitectit commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Run-log entries and the Control UI Automations page can't answer the questions an operator actually asks: where did this run come from, what kind of job is it, when does it next run, what did it cost, and why did it stop. Producers write freeform errors; the runs pane renders a generic failure label; agentTurn jobs can't cap their token spend; and trigger provenance is inferred downstream by string-matching instead of recorded at admission.

Why This Change Was Made

  • Every run-log entry gains a typed trigger origin (schedule / manual / system / ACP admission), populated uniformly across all 9 run-admission paths, typed at the protocol layer.
  • The Automations UI gains a job-kind column + detail badge and an upcoming/ETA panel — the page reads as a schedule, not a graveyard.
  • agentTurn jobs accept tokenBudget end-to-end: protocol → normalizer → create and same-kind update patch merge → live config patch → UI form/table round-trip.
  • Completion causes become a closed typed set (CronCompletionCause) with an exact legacy codec — restart/interrupt rows written by older versions decode identically, no silent reclassification. Producers emit typed causes; the runs pane renders cause-aware failure labels (7 buckets; producer cause wins over derived).

User Impact

Operators see provenance, cost caps, and truthful stop reasons on the surface they already use. Old run rows decode byte-identically (codec round-trip tested), so history is not reclassified. Clients that ignore the new fields are unaffected.

Evidence

Live Control-UI proof on the current head (2026-09-02, isolated dev gateway — own OPENCLAW_STATE_DIR, own port; the operator's running gateway was never touched):

  • Runs pane shows typed origin labels rendered from the new fields: "Scheduled — cron fire", "Manual run", "On-exit watcher" (screenshots 1–2), plus job-kind labels, the token-budget column, and the upcoming/ETA panel (screenshot 1).
  • Job editor shows the Token budget field with its help text under ADVANCED (screenshot 3).
  • TokenBudget round-trip proven at the wire level, not just visually: a Playwright session listening on the gateway WebSocket captured the cron.update request the UI sends ("payload":{"kind":"agentTurn","message":"…","tokenBudget":120000}), and after save cron get on the same state dir returns the payload with "tokenBudget": 120000; re-opening the editor shows 120000 in the field and the jobs table shows it in the TOKEN BUDGET column (screenshot 4).
  • That wire-level probe caught a real gateway bug, fixed in this PR: the UI was sending tokenBudget on edit, but same-kind cron.update merges rebuilt the agentTurn payload without reading patch.tokenBudget — create persisted the budget while every same-kind edit silently dropped it, and the explicit-null clear was never honored. a5d2978f1d1 mirrors the model/thinking override rules (number sets, null clears, omitted leaves untouched) with failing-first regression tests. This is exactly the class of drop the tokenBudget enforcement work would have hidden: the cap lever existed in the form but updates never stored it.

Redacted live proof (post-rebase re-verification recorded in the test battery, ~/openclaw-test-battery/evidence/): trigger origin visible on live run-log entries through the production gateway; typed completion causes flow producer → run record → cause-aware UI label against the live gateway.

Land-time suites (per commit, openspec §2.2):

Commit Slice What Land-time
577db2e79f6 0 populate trigger field on run log entries 113/113 (post-CR-6-rebase)
95a95088bf2 0 typed run trigger-source enum (protocol) 113/113
062c9718e5f 1 trigger origin on all 9 admission paths + Unknown (legacy) 142/142
9f0bf4dbac5 2 job-kind column, detail badge, upcoming/ETA panel 78/78
7d77eb1b42c 3a agentTurn tokenBudget protocol + normalizer 87/87
5b98180783f 3b tokenBudget UI form/table, Unlimited / N-a display 181/181 + UI build green
ab0240077be 4a typed completionCause contracts + exact legacy restart codec 85/85
ea166202cc2 4b-c2 producers emit typed causes + budget-cause gap fix 305/305 (8 files) + 301/301 (9 files)
260cd8d8595 4b-c3 cause-aware failure label in runs pane, 7 buckets 161/161 + UI build green
6b1782aba48 5 direct runs of event jobs stay trigger=manual; on-exit watchers pass explicit triggerSource (review fix) cron admission + active-jobs suites green
12a429956d7 5 render localized run origin + job-kind labels via locale catalog (review fix) UI cron suites green
a5d2978f1d1 6 fix: same-kind cron.update merges apply tokenBudget (number sets, null clears) — found by live wire-level probing, see above payload-merge 19/19 (3 failing-first), apply-patch + protocol conformance/schema 52/52
  • Rebase onto current main (2026-09-02, final head fd168c05633): two upstream movements were ported — (1) embedded-agent usage accounting moved into createEmbeddedModelState, so the onRunUsageTotals checkpoint lives in its recordModelUsage (threading verified across all 5 call sites); (2) refactor(cron): derive run history type from wire schema #136075 derived the run-log entry type from the gateway-protocol wire schema — our trigger/completionCause fields already live in CronRunLogEntrySchema, so src/cron/run-log-types.ts adopted the upstream Omit-derivation verbatim. pnpm tsgo:core green; payload-merge 19/19, protocol conformance + gateway-protocol validators 21/21. A follow-up CI-gate commit (fd168c05633) regenerates the Swift protocol models for the new schema fields and removes knip-flagged dead code (superseded run-origin.ts formatter, test-only cause predicate/exports, production-dead UI helpers).
  • Full CR-7 sweep at the pre-rebase tip: unit-src 486/490 (4 waivers logged, environmental/umask classes, baseline logs under /tmp/cr7-batch/), runtime-config 280/280, gateway-client 1148/1148, gateway-server/methods/plugin-sdk green, tsgo green, cron subsets 54/54/95, ui 857/857.
  • Tree: 54 files, +1840/−12 over merge-base (final head fd168c05633). pnpm-lock: clean. Author/trailer audit: Forge only, zero trailers. Private-path/secret-shape audit: clean (waivers logged; sole hit is the file:///etc/passwd canary in the URL-sanitization negative test).
  • git diff --stat numbers are stale-proof: recompute with git diff --shortstat origin/main...HEAD.

Run-admission provenance note (CR-6): the premature TimedCronRunOutcome annotation removed in Slice-0 was introduced by that commit itself (pre-rebase 97a31f34ac0); final form is unannotated literal + trigger: "scheduled" as const, squashed into 577db2e79f6. Both merge sites fully type-checked; pnpm tsgo:core exit 0.

Risk: legacy decode is exact, not approximate (round-trip codec tests). UI is additive — old clients ignore new fields. No schema migration.

Screenshots (isolated dev gateway, current head; hosted as fork release assets, no repo-branch artifacts):

Automations jobs table — job-kind, token-budget columns, upcoming panel

Run history — typed origin labels: Scheduled — cron fire, Manual run, On-exit watcher; cause-aware failure labels

Token budget field filled before save (ADVANCED disclosure)

Jobs table after save+reload — token budget 120000 persisted and rendered

Editor re-opened fresh — token budget 120000 round-trips

Round-6 update (2026-09-04, rebased onto upstream 8e23a5324f5, head 7daa73aa1e8):

  • Round-6 review fixes: (1) read-boundary no longer reclassifies legacy restart-interrupted rows — parseCronRunLogEntryObject keeps stored completionCause verbatim (terminal causes are producer facts; legacy rows render as unknown) and the now-dead resolveLegacyGatewayRestartCause was deleted with its tests; (2) a CLI/embedded candidate whose returned usage reaches the cap fails the run instead of returning a successful result past its budget (new regression test: CLI candidate reporting 250 usage against a 200 budget → terminal "Token budget exhausted" error).
  • Verification at the new head: tsgo core + UI clean (only pre-existing tsgo-vs-tsc noise in untouched scripts//qa-lab files; tsc --noEmit reports 0 errors), all 5 core lint stripes + core:ui pass, isolated-agent suite 852/852, cron history/detail 31/31.
  • Budget-trip real-behavior proof, re-run at the exact new head (7daa73aa1e8) — real CronService, real preflight, real token-budget guard + run-executor, real fallback coordinator; only the embedded model call speaks real HTTP (openai-completions SSE) to a localhost stub: exactly ONE chat completion reaches the server, the admission guard blocks candidate 2 after the trip, and the canonical terminal error Token budget exhausted: the run reached its 200-token cap persists identically across the finished event, run history, and job.state.lastError.

Round-7 update (2026-09-04, head c4d4c6b73f1): addressed the CR-7 tokenBudget contract finding. The budget guard fires after a candidate finishes, so one in-flight candidate can overshoot before the run is cancelled — observed-use semantics, not a hard cap. The UI help text (tokenBudgetHelp) and the Cron guide now describe this honestly: soft threshold, post-candidate cancellation with possible overshoot, cumulative count across the run's candidates (including fallback retries), CLI post-hoc observation vs. embedded candidate-boundary check, distinction from the session context budget, blank = unlimited, and explicit null clears a stored value. Docs/wording-only follow-up on top of 7daa73aa1e8; the token-budget runtime is unchanged, so the budget-trip proof below still holds at this head.

Round-8 update (2026-09-05, rebased onto current main, head 3f1386c6b59): the rebase ClawSweeper flagged is done. Two upstream movements needed porting: (1) src/cron/service/ops.test.ts import shape moved — kept this PR's two imports (saveCronJobsStoreWithTransactionHooks, cronStreamScheduleKey), still referenced 3×; (2) src/cron/isolated-agent/run-executor.ts — main restructured the context-engine lease while this PR restructured the budget binding, a deep semantic conflict; took this PR's budget binding and ported the throwIfBudgetTripped helper + budget-trip .catch detection from main. A rebase regression was caught before push: the merge reverted runWithModelFallback's abortSignal from budgetArmedAbortSignal back to params.abortSignal, so a budget-exhausted first candidate no longer aborted the composite signal and fallback selection continued — the 3 budget-carry tests went red. Restored abortSignal: budgetArmedAbortSignal; all 3 green again. Verification at 3f1386c6b59: isolated-agent suite 857/857 (incl. the 3 budget-carry tests), tsc --noEmit core exit 0. The token-budget runtime is byte-for-byte the post-round-7 behavior (the rebase only re-resolved the same files), so the budget-trip proof below still holds; the abortSignal restoration is what keeps the composite-signal abort path live at this head.

Round-9 update (2026-09-05, head bef7aac77fe): addressed the two P2 budget findings from the 02:57 UTC review. (1) Usage-on-throw retention — only settled results incremented carriedTokenUsageTotal, so a candidate that reported spend and then threw a fallback-eligible error left its tokens uncounted; the next candidate's tripwire started fresh and a 150+150 spend against a 200-token budget never tripped. Added an onError hook on the runWithModelFallback call (model-fallback-runner fires it after a candidate throws but before the next starts) that folds the in-flight candidate's observed total into the carried spend. New currentCandidateUsage tracks the candidate-local total; totalObservedTokenUsage() reconciles carried + in-flight for the trip message. (2) Typed budget cause through the run boundary — the budget trip was surfaced as a plain Error, so runCronIsolatedAgentTurn's catch could not distinguish it from a generic failure and detectBudgetExhausted (timer-execution.ts:483) never saw usage.total_tokens to classify completionCause: "budget-exhausted". Introduced CronTokenBudgetExhaustedError (token-budget-guard.ts) carrying budget + usageTotal, thrown from both trip points (throwIfBudgetTripped and the fallback .catch); run.ts spreads usage: { total_tokens: err.usageTotal } onto the error result when the typed trip crosses the run boundary. Failing-first coverage: (a) a throwing-candidate carry test — candidate A reports 150 then throws, candidate B reports 150 and the carry trips 300≥200 (verified red with onError disabled, green with it restored); (b) a boundary-carry test asserting the error result carries usage.total_tokens: 220 for detectBudgetExhausted (verified red with the budgetUsage spread disabled, green with it restored). Budget-carry suite 5/5; tsc --noEmit -p tsconfig.core.json (8GB heap) zero errors in touched files; oxfmt + oxlint clean.

Inline proof trace (budget-trip, redacted — inlined because the review sandbox cannot fetch release assets; full evidence at the release links above):

# captured at runtime head 7daa73aa1e8 (c4d4c6b73f1 is docs-only on top; runtime identical)
# real CronService, real preflight, real token-budget guard + run-executor + fallback coordinator;
# only the embedded model call speaks real HTTP (openai-completions SSE) to a localhost stub
preflight:  GET /v1/models -> 200 (model "available")
wire:       POST /v1/chat/completions  model=one  (stream, stream_options.include_usage)
            # no second completion: admission guard (model-fallback-attempt.ts: attempt>1 -> throwIfAborted)
SSE usage:  total_tokens=250 >= budget 200  ->  budgetAbortController.abort()
candidate1: fails (composite signal aborted post-trip, mirroring real runner abort)
candidate2: blocked before preparation by the admission guard
terminal:   finished CronEvent  status=error
            error="Token budget exhausted: the run reached its 200-token cap | stub candidate aborted by budget trip"
            run-history (limit 1): status=error  provider=stublocal  model=one  trigger=manual  (same error)
            job.state.lastError:  same error string

Out of scope: failure-alert delivery-outcome write-back (follow-up PR), task lanes (PR-2).

Fixes #135876 (part 1 of 2).

@clawsweeper

clawsweeper Bot commented Sep 2, 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.

@TheArchitectit

Copy link
Copy Markdown
Contributor Author

Post-rebase re-verification (head 4b70b920529, stack rebased 2026-09-02 onto 8fe71d40ff1; 4 file conflicts resolved: cron payload builders moved to cron-shared.ts, core-descriptors.ts, server-methods-list.test.ts, schema.tiers.ts):

Green: task-lanes 30/30 · gateway-client protocol 648/648 · gateway-server descriptors+context ✓ · ui-cron 308/308 · tsgo:core ✓ · tsgo:ui ✓ · gateway-methods 4236/4237 · runtime-config 4040/4046 · plugins 4529/4530.

Flagged lanes, all diagnosed as not-from-this-stack (verbose re-runs, twice-deterministic):

  • gateway-methods models.test.ts ×1 — ambient Anthropic auth on the dev box makes a fixture model report available; the test file itself changed upstream inside the rebased window (84e81339c2c). Environment-dependent.
  • runtime-config io.write-config.test.ts ×5 + validation.policy.test.ts ×1 — this stack touches none of those files; the write-config tests changed upstream during the window (717c78cc6cf). Upstream-drift/environment candidates.
  • plugins whatsapp external repair-hint ×1 — untouched by this stack; catalog/environment-dependent.
  • cron full shard — vitest worker crash (Worker exited unexpectedly, infra), no assertion failure; cron subsets green at land time (54/54/95).

Exact-head fork CI is the arbiter for the flagged lanes; will fold results in when CI reports.

Stack map: PR-1 #135889 (single-pane, 9 commits) → PR-2 #135890 (task-lanes, 9 commits). Draft until the live battery groups B/C/F5/G close (restart-gated on the operator's box).

@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. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 2, 2026
@clawsweeper

clawsweeper Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

Adds cron run origins, typed completion causes, an optional token threshold, and Automations UI scheduling information.

Example: An agent-turn automation has tokenBudget 200 and reports 250 tokens.

  • Before: Cron has no per-job token threshold.
  • After: The proposed guard aborts the run and reports token-budget exhaustion, with possible overshoot.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful contributor work and positive partial proof, with four unresolved findings and an unsettled product contract.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦪 silver shellfish (2/6) 4 actionable review findings remain.

Product

Kind: Feature · Worth it: Needs a maintainer decision · Fix scope: Partial
User problem: Operators lack explicit run-origin and stop-reason information and cannot configure a per-job token threshold.
Reason: The observability work has concrete value, but the new persisted execution policy needs owner direction and this PR covers only part of the linked umbrella request.

Merge readiness

⛔ Blocked before merge - 10 items remain

Keep open: this PR contains distinct, repairable work and remains paired with an open issue and companion PR, but four prior findings remain unresolved.

Priority: P2
Reviewed head: 744bf50e69aeeb1a1f5237387e19cbd5d53efafa
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should cron expose a persisted per-job observed-token threshold that turns an otherwise successful candidate into a failed run?
  • Recommendation: Separate the token policy: Review provenance and observability independently, deferring tokenBudget until its execution and persistence contract is accepted.
  • Why: This adds execution policy and configuration surface; contributor discussion explicitly leaves sponsorship outstanding, and no recorded maintainer approval settles it.

Before merge

  • Add real behavior proof - Inspected screenshots demonstrate the proposed Automations UI and saved 120000 budget, and the contributor’s inline HTTP/SSE trace positively exercises older cron execution owners. It predates the current candidate-dispatch and usage-retention changes, leaving their runtime result unproven. Add redacted execution logs for budget exhaustion and failed continuation, and the required baseline-before and after UI captures; remove IPs, keys, phone numbers, and non-public endpoints. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Remove the unused cron-side candidate classifier (P1) - The added classifyResult closure is never read: CLI finalization calls runOptions.classifyResult, and runEmbeddedAgentEntry owns the actual classification. With noUnusedLocals enabled in tsconfig.core.json, this declaration fails the production typecheck. Delete the unused closure, cache, and associated imports rather than introducing a second classification owner.
  • Preserve cumulative usage after a continuation exhausts the budget (P2) - If an acknowledgement completes with 150 tokens and its continuation spends another 150 against a 200-token threshold, settleUsage produces the earlier prompt’s 150-token usage object. The nullish fallback then discards CronTokenBudgetExhaustedError.usageTotal=300. History underreports spending and detectBudgetExhausted does not publish the typed cause because 150 is below 200. Preserve the typed cumulative total while retaining available usage breakdown fields.
  • Write the restart cause at the interruption producer (P2) - A Gateway restart during an active cron run reaches emitInterruptedCronRun, which still writes only the legacy error string. The new reader intentionally does not derive completionCause, and no production writer emits gateway-restart, so newly recovered runs never reach the advertised restart-specific UI label. Add completionCause at this producer and cover the persisted recovery event.
  • Keep cron list strings in their existing lazy catalog (P2) - This restores the automation-list strings to eager en.ts while en-cron.ts retains and registers the same subtree. Every startup now carries copy deliberately removed by fix(ui): open attached automations from session hovercards #147749, creating duplicate catalog ownership and violating ui/AGENTS.md’s lazy-registration contract. Restore the empty list anchor and keep these strings in en-cron.ts.
  • Complete next step - Resolve GitHub’s reported merge conflict with main.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.
  • Explain or restore the original intent of Automation-list lazy loading - b2fefda: Merged fix(ui): open attached automations from session hovercards #147749 moved list copy to lazy consumers to reduce startup payload.
  • Explain or restore the original intent of Shared candidate classification - f67e55a: Merged refactor: unify the embedded-agent fallback run-entry across all four pipelines #111608 centralized fallback classification and lifecycle to prevent caller copies from drifting.

Findings

  • [P1] Remove the unused cron-side candidate classifier — src/cron/isolated-agent/run-executor.ts:421-425
  • [P2] Preserve cumulative usage after a continuation exhausts the budget — src/cron/isolated-agent/run.ts:354-358
  • [P2] Write the restart cause at the interruption producer — src/cron/service/run-recovery-events.ts:15-17

Provenance

Tests

  • Low-value test src/cron/normalize-token-budget.test.ts: Remove the normalizer merge behavior group: its valid, invalid, null, and NaN cases repeat the earlier create/patch cases through the same normalizer without detecting a distinct failure.
  • Low-value test ui/src/pages/cron/upcoming-jobs.test.ts: Consolidate the event-inclusion and never-mixes cases into the initial separation test; they repeat its same on-exit/stream partition behavior.
  • Missing end-to-end proof: Supply current production-path budget-trip and continuation-failure evidence plus before/after UI captures; the retained tests do not demonstrate those scenarios failing before repair and passing afterward.
Agent review details

How this fits together

Cron admits scheduled and manual jobs, dispatches agent execution, and persists terminal facts that Gateway clients and the Automations UI display.

flowchart LR
  A[Schedule or operator] --> B[Cron admission]
  B --> C[Shared agent entry]
  C --> D[Provider execution]
  D --> E[Usage guard]
  E --> C
  C --> F[Run ledger]
  F --> G[Automations UI]
Loading

Technical review

Best possible solution:

Keep run facts with cron’s existing producers and shared execution owner, repair the incomplete paths, and settle the optional token-threshold policy before landing.

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

Source inspection establishes the unresolved branch defects, including a 150-token completed acknowledgement followed by a 150-token continuation against a 200-token threshold; no target code or tests were executed.

Is this the best way to solve the issue?

Recording facts at their producers fits the existing architecture, but the unused classifier and duplicated catalog should be removed and cumulative budget usage must survive continuation failure.

Full review comments:

  • [P1] Remove the unused cron-side candidate classifier — src/cron/isolated-agent/run-executor.ts:421-425
    The added classifyResult closure is never read: CLI finalization calls runOptions.classifyResult, and runEmbeddedAgentEntry owns the actual classification. With noUnusedLocals enabled in tsconfig.core.json, this declaration fails the production typecheck. Delete the unused closure, cache, and associated imports rather than introducing a second classification owner.
    Confidence: 0.99
  • [P2] Preserve cumulative usage after a continuation exhausts the budget — src/cron/isolated-agent/run.ts:354-358
    If an acknowledgement completes with 150 tokens and its continuation spends another 150 against a 200-token threshold, settleUsage produces the earlier prompt’s 150-token usage object. The nullish fallback then discards CronTokenBudgetExhaustedError.usageTotal=300. History underreports spending and detectBudgetExhausted does not publish the typed cause because 150 is below 200. Preserve the typed cumulative total while retaining available usage breakdown fields.
    Confidence: 0.99
  • [P2] Write the restart cause at the interruption producer — src/cron/service/run-recovery-events.ts:15-17
    A Gateway restart during an active cron run reaches emitInterruptedCronRun, which still writes only the legacy error string. The new reader intentionally does not derive completionCause, and no production writer emits gateway-restart, so newly recovered runs never reach the advertised restart-specific UI label. Add completionCause at this producer and cover the persisted recovery event.
    Confidence: 0.99
  • [P2] Keep cron list strings in their existing lazy catalog — ui/src/i18n/locales/en.ts:4989-4993
    This restores the automation-list strings to eager en.ts while en-cron.ts retains and registers the same subtree. Every startup now carries copy deliberately removed by fix(ui): open attached automations from session hovercards #147749, creating duplicate catalog ownership and violating ui/AGENTS.md’s lazy-registration contract. Restore the empty list anchor and keep these strings in en-cron.ts.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 55e1802 adds src/cron/isolated-agent/run.ts:186 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 55e1802b7144; files: src/cron/isolated-agent/run.ts)
  • Donnie Fiander: Raw commit 4321816 adds src/cron/isolated-agent/run-executor.ts:771 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 4321816e2a76; files: src/cron/isolated-agent/run-executor.ts)
  • RoboClaw: Raw commit b2fefda adds ui/src/i18n/locales/en-cron.ts:34 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: b2fefda199c6; files: ui/src/i18n/locales/en-cron.ts)

PR surface

Source +925, Tests +1525, Docs +1. Total +2451 across 56 files. Added test files: 7.

View PR surface stats
Area Files Added Removed Net
Source 36 944 19 +925
Tests 19 1527 2 +1525
Docs 1 1 0 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 56 2472 21 +2451

Review metrics

Metric Value Why it matters
New persisted policy field 1 optional field agentTurn.tokenBudget adds a positive-integer threshold with explicit-null clearing on updates.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #135876
Summary: The open umbrella issue coordinates this cron proposal and its separate task-lane companion.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

  • add proof: 📸 screenshot: Contributor real behavior proof includes screenshot evidence.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🦪 silver shellfish, so this older rating label is no longer current.
  • remove merge-risk: 🚨 compatibility: Current PR review selected no merge-risk labels.

Label justifications:

  • P2: This is a normal-priority automation observability and spending-control proposal without an established urgent upstream regression.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.
  • proof: 📸 screenshot: Contributor real behavior proof includes screenshot evidence.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (34 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-05T02:11:20.206Z sha 3f1386c6b59f3a607b282c169fde5ddd65a68bd9 :: blocked before merge. :: [P2] [P2] Preserve observed usage when a fallback candidate throws | [P2] [P2] Carry the typed budget outcome through the error result
  • reviewed 2026-09-05T02:57:58.860Z sha 3f1386c6b59f3a607b282c169fde5ddd65a68bd9 :: blocked before merge. :: [P2] Preserve observed usage when a fallback candidate throws | [P2] Carry the typed budget outcome through the error result
  • reviewed 2026-09-05T03:59:52.310Z sha bef7aac77fef57f9868680d571989fc3c67478a6 :: blocked before merge. :: [P2] Retain observed usage across live model-switch exits
  • reviewed 2026-09-05T22:01:48.771Z sha 62e236a71a42ca7f10d7b8d0737ca4103e6b80fb :: blocked before merge. :: [P1] Keep budget-counter access inside its owning closure | [P2] Retain usage before internally handled model switches
  • reviewed 2026-09-07T15:12:47.014Z sha 62e236a71a42ca7f10d7b8d0737ca4103e6b80fb :: blocked before merge. :: [P1] Keep budget-counter access inside its owning closure | [P2] Retain usage before internally handled model switches
  • reviewed 2026-09-22T22:00:25.118Z sha 62e236a71a42ca7f10d7b8d0737ca4103e6b80fb :: blocked before merge. :: [P1] Keep budget-counter access inside its owning closure | [P2] Retain usage before internally handled model switches
  • reviewed 2026-09-28T07:50:07.034Z sha 744bf50 :: needs real behavior proof before merge. :: [P1] Remove the unused cron-side candidate classifier
  • reviewed 2026-10-05T16:29:32.397Z sha 744bf50 :: needs real behavior proof before merge. :: [P1] Remove the unused cron-side candidate classifier | [P2] Preserve the cumulative budget total after a continuation fails | [P2] Write the restart cause at the interruption producer | [P1] Keep cron list strings in their existing lazy catalog

Reviewed October 18, 2026, 6:59 AM ET / 10:59 UTC (Revision 35).

@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Sep 2, 2026
@TheArchitectit
TheArchitectit force-pushed the feat/automation-single-pane branch from 90e3b93 to 19f6e4b Compare September 2, 2026 06:38
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Sep 2, 2026
@TheArchitectit TheArchitectit reopened this Sep 2, 2026
@TheArchitectit

Copy link
Copy Markdown
Contributor Author

Post-review push + live Control-UI proof on the current head (62138940cd8), 2026-09-02.

All four findings addressed (details in the PR body's Evidence section):

  1. Token budget enforced at the execution boundary — 19f6e4bcd0b (rebased; the onRunUsageTotals checkpoint was ported into createEmbeddedModelState.recordModelUsage after upstream moved usage accounting).
  2. Direct runs of event jobs stay trigger=manual — fda22c96503; on-exit watchers pass explicit triggerSource. Live runs pane shows both origins rendered (screenshot 2: "Scheduled — cron fire", "Manual run", "On-exit watcher").
  3. Run origin rendered in the runs pane — 6c32dc14d27 renders localized origin + job-kind labels via the locale catalog (screenshots 1–2).
  4. Token budget round-trip, now wire-level proven: a Playwright session listening on the gateway WebSocket captured the UI's cron.update request carrying "tokenBudget":120000; after save, cron get returns the stored budget and the editor + jobs table re-render it (screenshots 3–4). This probe caught a real gateway bug, fixed in 62138940cd8: same-kind cron.update merges rebuilt the agentTurn payload without reading patch.tokenBudget, silently dropping the budget on every edit (create worked, edit didn't; explicit-null clear never honored). Failing-first regression tests in src/cron/service/payload-merge.test.ts (19/19; apply-patch + protocol conformance/schema 52/52).

Proof environment: isolated dev gateway with its own OPENCLAW_STATE_DIR and port; the operator's gateway was not used.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Sep 2, 2026
@TheArchitectit
TheArchitectit force-pushed the feat/automation-single-pane branch from 6213894 to a5d2978 Compare September 2, 2026 08:25
@TheArchitectit

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (a481f53fa3a); head is now a5d2978f1d1. One upstream movement needed porting: #136075 derived the run-log entry type from the gateway-protocol wire schema. Our trigger/completionCause fields already live in CronRunLogEntrySchema (packages/gateway-protocol/src/schema/cron.ts), so src/cron/run-log-types.ts adopted the upstream Omit-derivation verbatim — no behavioral change. pnpm tsgo:core green; payload-merge 19/19, protocol conformance + gateway-protocol validators 21/21.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Sep 2, 2026
@TheArchitectit TheArchitectit reopened this Sep 2, 2026
@TheArchitectit
TheArchitectit marked this pull request as ready for review September 2, 2026 09:06
Forge and others added 10 commits September 18, 2026 19:29
- New lib: ui/src/lib/cron/completion-cause.ts
  - runFailureLabel(entry, nowMs): producer-authoritative cause
    (gateway-restart, owner-unavailable, budget-exhausted) wins;
    otherwise a derived bucket: active (24h) / previous (still recent)
    / historical. Pure: no i18n, just the key.
- view-runs.ts: threaded runFailureLabelText through renderRun so the
  header shows the classified failure next to status, keyed by the
  producer's completionCause from the read codec.
- en.ts: 7 new keys under cron.runs.failureLabel (active, autoDisabled,
  previous, historical, gatewayRestart, ownerUnavailable,
  budgetExhausted).
- index.test.ts: 2 pre-existing tsgo literals (job-budget-clear,
  job-budget-keep) gain the required name field.
- Unit test ui/src/lib/cron/completion-cause.test.ts covers the 7
  branches of the producer-causes-wins + derived-bucket logic.
…ss explicit triggerSource

Schedule kind on the admitted job cannot distinguish an operator Run now
from a watcher fire since both traverse the same run() seam. Event
producers now carry explicit provenance: exit watchers pass
triggerSource=on-exit, stream watchers stay authoritative via streamBatch,
and direct CLI/Control UI runs without either marker resolve to manual.

Replaces the land-time test that asserted schedule-kind-derived origin
for a watcher-less run with three origin cases: direct on-exit (manual),
watcher-marked on-exit (on-exit), direct stream (manual).
…atalog

The runs pane persisted entry.trigger but never rendered it, so the
advertised provenance was invisible to operators. Run entries now show a
localized origin fact for every recorded trigger source, mapping unknown
values to legacy-unknown and omitting the fact when no origin was
recorded.

Job-kind badges resolve through the locale catalog instead of embedded
English strings, so non-English sessions translate.

Also moves the orphaned cron.list.failureLabel subtree to cron.runs,
which is where the runs pane actually references it — the mismatch made
failure pills render raw catalog keys.
tokenBudget was recorded and post-hoc labeled but never constrained
execution: a run could exceed its configured cap and an unrelated
failure after crossing the threshold was mislabeled budget-exhausted.

The embedded runner now exposes a run-cumulative usage checkpoint
(onRunUsageTotals, invoked at each usage commit), and the cron
execution boundary arms a one-shot guard over it: when cumulative
usage reaches the job's cap the run's abort signal fires and the run
stops itself. Post-hoc attribution remains as the labeling fallback;
a genuine producer-set cause still wins. A capped run can overshoot
by at most one usage-commit interval.
cron.update with an unchanged payload.kind rebuilt the agentTurn payload
without reading patch.tokenBudget, so the Control UI editor and the cron
tool could set a token budget on create but every same-kind edit silently
dropped it (and the explicit-null clear was never honored). Mirror the
model/thinking override rules: number sets, null clears, omitted leaves
the stored value untouched.
…ad code, SAFETY comment

- Regenerate apps/shared GatewayModels.swift for the new protocol fields
  (trigger, completionCause, tokenBudget).
- Delete src/cron/run-origin.ts: superseded by the locale-catalog origin
  rendering; knip flagged it (and its test) as an unused file.
- completion-cause-constants.ts: drop the test-only CRON_COMPLETION_CAUSES
  const and isCronCompletionCause predicate; the canonical union already
  lives in src/cron/types.ts.
- ui cron helpers: remove production-dead exports (cronJobKindLabelKeys,
  hasUpcomingJobs) and their test blocks; annotate the remaining cast with
  the SAFETY invariant the assertion ratchet requires.
…acks

A budgeted run previously constructed its guard only in the embedded branch
after the CLI branch returned, and re-created it per fallback candidate: a
CLI-backed run was uncapped and each candidate could spend the full budget.
One logical-run guard is now constructed before candidate dispatch; candidate
totals accumulate across CLI and embedded candidates and continuation
attempts. CLI usage surfaces at candidate end, so CLI enforcement stops the
run at the candidate boundary.
…rigger-script origin

The composite budget abort signal now arms the outer fallback
coordinator's candidate admission guard, so a budget-exhausted first
candidate can no longer be prepared or executed again as a later
fallback candidate; a budget-only trip surfaces "Token budget
exhausted" as the terminal cause instead of a generic abort. Runs
whose trigger evaluation actually fired now record the trigger-script
origin at the producer (scheduled dispatcher and operator seam) rather
than advertising scheduled/manual provenance the run did not use.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Forge and others added 9 commits September 28, 2026 06:03
The Cron guide covered only wall-clock budgets; the per-job token budget
was undocumented, and the UI help text described it as a hard stop. The
budget guard fires after a candidate finishes, so one in-flight candidate
can overshoot before the run is cancelled — observed-use semantics, not
an enforced cap.

Reword the UI help text to state the semantics honestly: soft threshold,
post-candidate cancellation with possible overshoot, cumulative count
across the run's candidates (including fallback retries), separate from
the session context budget, blank = unlimited, and explicit null clears a
stored value. Add a matching "Per-run token budget" bullet to the Cron
guide covering the unlimited default, explicit clearing, cumulative
fallback behavior, the CLI-vs-embedded candidate-boundary difference
(CLI observes spend post-hoc and can overshoot further), and the
distinction from the session context budget.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Rebasing onto main restructured run-executor's fallback chain: the
runWithModelFallback call reverted to params.abortSignal and the
budget-trip terminal-cause path was lost. Restore budgetArmedAbortSignal
on the coordinator call so a budget-exhausted first candidate aborts the
composite signal and stops fallback selection, and surface the
budget-only trip as "Token budget exhausted" in the catch handler with
throwIfBudgetTripped after each settleCandidateUsage.

run.token-budget-carry: 3/3 green; isolated-agent suite 857/857.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…se through run boundary

A fallback candidate that reported token usage and then threw a
fallback-eligible error left its spend uncounted: only settled results
incremented carriedTokenUsageTotal, so the next candidate's tripwire
started fresh and a 150+150 spend against a 200-token budget never
tripped. Fold the in-flight candidate's observed total into the carried
spend via the runWithModelFallback onError hook, which fires after a
candidate throws but before the next one starts.

The budget trip was also surfaced as a plain Error, so the run boundary
could not distinguish it from a generic failure and detectBudgetExhausted
never saw usage.total_tokens to classify `budget-exhausted`. Introduce a
typed CronTokenBudgetExhaustedError carrying the budget and observed
usageTotal, throw it from both trip points (throwIfBudgetTripped and the
fallback .catch), and spread usage onto the error result in run.ts when
the typed trip crosses the run boundary.

Add failing-first coverage: a throwing-candidate carry test (candidate A
reports 150 then throws; candidate B's 150 trips 300>=200) and a
boundary-carry test asserting the error result carries usage.total_tokens
for detectBudgetExhausted.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
LiveSessionModelSwitchError triggers a retry in the outer while loop,
bypassing the model-fallback-runner's onError callback. Without this
retention, the switched-out candidate's spend is lost; the next
candidate starts at zero and can exceed the budget without tripping
the guard.

Adds failing-first test: a 200-token budget with 150+150 across a
model switch must trip the shared guard (previously it did not).

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…rebase

Upstream refactored the isolated-agent fallback path into
runEmbeddedAgentEntry and reworked the model-fallback contract, so the
token-budget work from this branch no longer compiled or enforced:

- classifyEmbeddedAgentRunResultForModelFallback now takes a params object
  ({provider, model, result}); the memoizing wrapper was rewritten and the
  classifier type re-imported from model-fallback-attempt.
- runWithModelFallback's onError is gone. The entry exposes onFallbackStep,
  which fires at the equivalent point, so a throwing candidate's observed
  usage is retained there instead.
- The model-switch retry loop lives outside the prompt-executor closure but
  must still fold the switched-out candidate's spend into the run total.
  Expose retainObservedUsage on the returned executor rather than reaching
  for closure state across a function boundary.

Both budget-trip throw sites now raise CronTokenBudgetExhaustedError with the
observed total, and the run boundary surfaces that total on the error result
when no prompt run completed. Without it detectBudgetExhausted could never
classify `budget-exhausted` and the failure surfaced as usage-less.

Tests updated to the new contract: the fallback mocks now dispatch through
runInitialModelFallbackAttempt and return the RunEntryCandidate shape the
entry expects, so candidates actually execute.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@openclaw-barnacle

Copy link
Copy Markdown

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

@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #clawtributors on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

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: 📸 screenshot Contributor real behavior proof includes screenshot evidence. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: XL stale Marked as stale due to inactivity status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Automations single-pane: run provenance, typed completion causes; task-lane observability seam

1 participant