Repository navigation
feat(cron): run provenance, job kinds, agentTurn token budget, typed completion causes - #135889
TheArchitectit wants to merge 27 commits into
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Post-rebase re-verification (head Green: task-lanes 30/30 · gateway-client protocol 648/648 · gateway-server descriptors+context ✓ · ui-cron 308/308 · Flagged lanes, all diagnosed as not-from-this-stack (verbose re-runs, twice-deterministic):
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). |
|
Codex review: needs real behavior proof before merge. What this changesAdds 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.
Review scores
ProductKind: Feature · Worth it: Needs a maintainer decision · Fix scope: Partial 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 Decision needed
Before merge
Findings
Provenance
Tests
Agent review detailsHow this fits togetherCron 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]
Technical reviewBest 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:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 19d311e00246. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +925, Tests +1525, Docs +1. Total +2451 across 56 files. Added test files: 7. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (34 earlier review cycles; latest 8 shown)
Reviewed October 18, 2026, 6:59 AM ET / 10:59 UTC (Revision 35). |
90e3b93 to
19f6e4b
Compare
|
Post-review push + live Control-UI proof on the current head ( All four findings addressed (details in the PR body's Evidence section):
Proof environment: isolated dev gateway with its own @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
6213894 to
a5d2978
Compare
|
Rebased onto current @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
- 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.
…leaf import, oxlint cleanups
…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.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
…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]>
…state derivation from run labels
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]>
|
This pull request has been automatically marked as stale due to inactivity. |
|
Closing due to inactivity. |
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;
agentTurnjobs 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
agentTurnjobs accepttokenBudgetend-to-end: protocol → normalizer → create and same-kind update patch merge → live config patch → UI form/table round-trip.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):cron.updaterequest the UI sends ("payload":{"kind":"agentTurn","message":"…","tokenBudget":120000}), and after savecron geton 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).tokenBudgeton edit, but same-kindcron.updatemerges rebuilt the agentTurn payload without readingpatch.tokenBudget— create persisted the budget while every same-kind edit silently dropped it, and the explicit-null clear was never honored.a5d2978f1d1mirrors 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):
577db2e79f695a95088bf2062c9718e5f9f0bf4dbac57d77eb1b42c5b98180783fab0240077beea166202cc2260cd8d85956b1782aba48trigger=manual; on-exit watchers pass explicittriggerSource(review fix)12a429956d7a5d2978f1d1cron.updatemerges applytokenBudget(number sets, null clears) — found by live wire-level probing, see abovemain(2026-09-02, final headfd168c05633): two upstream movements were ported — (1) embedded-agent usage accounting moved intocreateEmbeddedModelState, so theonRunUsageTotalscheckpoint lives in itsrecordModelUsage(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 — ourtrigger/completionCausefields already live inCronRunLogEntrySchema, sosrc/cron/run-log-types.tsadopted the upstreamOmit-derivation verbatim.pnpm tsgo:coregreen; 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 (supersededrun-origin.tsformatter, test-only cause predicate/exports, production-dead UI helpers)./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.fd168c05633). pnpm-lock: clean. Author/trailer audit: Forge only, zero trailers. Private-path/secret-shape audit: clean (waivers logged; sole hit is thefile:///etc/passwdcanary in the URL-sanitization negative test).git diff --statnumbers are stale-proof: recompute withgit diff --shortstat origin/main...HEAD.Run-admission provenance note (CR-6): the premature
TimedCronRunOutcomeannotation removed in Slice-0 was introduced by that commit itself (pre-rebase97a31f34ac0); final form is unannotated literal +trigger: "scheduled" as const, squashed into577db2e79f6. Both merge sites fully type-checked;pnpm tsgo:coreexit 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):
Round-6 update (2026-09-04, rebased onto upstream
8e23a5324f5, head7daa73aa1e8):parseCronRunLogEntryObjectkeeps storedcompletionCauseverbatim (terminal causes are producer facts; legacy rows render as unknown) and the now-deadresolveLegacyGatewayRestartCausewas 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).scripts//qa-labfiles;tsc --noEmitreports 0 errors), all 5 core lint stripes +core:uipass, isolated-agent suite 852/852, cron history/detail 31/31.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 errorToken budget exhausted: the run reached its 200-token cappersists identically across the finished event, run history, andjob.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 explicitnullclears a stored value. Docs/wording-only follow-up on top of7daa73aa1e8; 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, head3f1386c6b59): the rebase ClawSweeper flagged is done. Two upstream movements needed porting: (1)src/cron/service/ops.test.tsimport 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 thethrowIfBudgetTrippedhelper + budget-trip.catchdetection from main. A rebase regression was caught before push: the merge revertedrunWithModelFallback'sabortSignalfrombudgetArmedAbortSignalback toparams.abortSignal, so a budget-exhausted first candidate no longer aborted the composite signal and fallback selection continued — the 3 budget-carry tests went red. RestoredabortSignal: budgetArmedAbortSignal; all 3 green again. Verification at3f1386c6b59: isolated-agent suite 857/857 (incl. the 3 budget-carry tests),tsc --noEmitcore 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; theabortSignalrestoration 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 incrementedcarriedTokenUsageTotal, 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 anonErrorhook on therunWithModelFallbackcall (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. NewcurrentCandidateUsagetracks 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 plainError, sorunCronIsolatedAgentTurn's catch could not distinguish it from a generic failure anddetectBudgetExhausted(timer-execution.ts:483) never sawusage.total_tokensto classifycompletionCause: "budget-exhausted". IntroducedCronTokenBudgetExhaustedError(token-budget-guard.ts) carryingbudget+usageTotal, thrown from both trip points (throwIfBudgetTrippedand the fallback.catch);run.tsspreadsusage: { 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 withonErrordisabled, green with it restored); (b) a boundary-carry test asserting the error result carriesusage.total_tokens: 220fordetectBudgetExhausted(verified red with thebudgetUsagespread 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):
Out of scope: failure-alert delivery-outcome write-back (follow-up PR), task lanes (PR-2).
Fixes #135876 (part 1 of 2).