Skip to content

feat(cron): add the scheduled-run execution context (no behavior change) - #178933

Merged
jalehman merged 8 commits into
mainfrom
automations/execution-context-foundation
Oct 22, 2026
Merged

jalehman merged 8 commits into
mainfrom
automations/execution-context-foundation

Conversation

@jalehman

@jalehman jalehman commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Related: #178812
Related: #178811

What Problem This Solves

Scheduled runs decide their tools, owner status and resources in dozens of separate places that disagree with each other. No single value describes what one occurrence of an automation may do.

User Impact

User impact: none yet. This adds the scheduled-run execution context and builds it for every isolated cron occurrence, but nothing reads it. Later PRs switch each consumer to it.

Why This Change Was Made

  • src/cron/execution-context.ts is a pure builder. It takes a stored job plus facts read at admission (the parent session row and a fresh requester check). From those it derives the occurrence's principal, placement, authority, tool policy, resource scopes and inference account.
    • A job linked to the exact conversation that created it (sourceConversation or a stored operator source) becomes a child of that conversation. When both exist, the operator source wins.
    • Jobs that store only a parent session key keep every legacy decision, and so do operator-created jobs.
    • A parent-linked job with no recorded requester gets no owner authority.
  • src/cron/execution-context-admission.ts mints the context for each prompt-executor attempt and binds it to the admitted run.
    • For parent-linked jobs it holds the parent's session generation. The context's assertCurrent fails once the parent is reset or removed, and the lease is released when the admission closes.
    • Minting errors become a fail result; they never fail the run.
    • If admission preparation throws, the prompt executor releases the lease immediately rather than waiting for a close that never happens.
  • src/cron/execution-context-projection.ts reproduces what the existing code decides for a stored job and labels each difference from the context: equal, gain-intended, gain-unexpected, loss, retarget or pause.
  • scripts/dev/cron-context-replay.mts is a development script and is not shipped.
    • It copies a Gateway's state and agent session databases into a private temp directory with SQLite's online backup, so the live databases are only read.
    • It replays every stored job against the copies, using the same parent precedence and agent resolution as runtime admission. It can also emit anonymized job shapes.
    • Anonymization keeps what decides a job's outcome: operator sources, channel requesters, whether the parent's session or lifecycle revision changed, and whether its worktree exists.
  • src/cron/execution-context.fixtures.test.ts pins the builder and projection results for the shapes the replay found. Other installs are covered by tests rather than runtime diagnostics.

Evidence

  • Focused tests (scripts/run-vitest.mjs): 4 files, 62 tests pass. They cover the builder, minting, the 27 stored-shape fixtures, and the replay's anonymization. The anonymization tests cover an operator-source parent, a channel requester, a changed lifecycle revision and a missing worktree.
  • Cron isolated-agent suites: all 60 files under src/cron/isolated-agent pass alongside the context tests, covering the prompt executor's admission path.
  • Static replay of a real Gateway's state copy: 88 non-main jobs were replayed.
    • Every field is equal except on the 5 jobs with an exact parent link. Those show only gain-intended (memory, automations) and retarget (board, event target).
    • No gain-unexpected, loss or pause.
  • pnpm check:changed: format, both typecheck lanes, and the SAFETY-comment, SQLite and mock-export ratchets pass. Two checks fail only on files this PR doesn't touch:
    • the max-lines ratchet (three ui/src files);
    • the core test-shard root budget (gateway-root, infra).
  • Lint: oxlint --type-aware on the changed files reports 0 warnings and 0 errors.
  • Autoreview (Codex, P0–P2): scoped-clean on the ClawSweeper fixes.
  • Not run: the live check for runtime-only fields (the final offered tool list per runtime). It needs a trace build on a real Gateway, and it only matters for the later owner-status phase.

@clawsweeper

clawsweeper Bot commented Oct 21, 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.

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts size: XL labels Oct 21, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 21, 2026
@clawsweeper

clawsweeper Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Adds an unused scheduled-run execution context, binds its lifetime to Cron admission, and provides development replay tooling.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The prior defects are resolved and the foundation is coherent, but proof remains tests and reported static replay, and the broader user outcome depends on later consumer slices.
Proof confidence 🦐 gold shrimp (3/6) The supplied maintainer-authored classification exempts this foundation from the ordinary contributor proof gate; reported static replay exercises context derivation, while source inspection confirms existing effect owners remain authoritative.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Feature · Worth it: Yes · Fix scope: Partial
User problem: Scheduled runs derive authority and resource identity separately across execution paths, contributing to inconsistent access to conversation resources.
Reason: The supplied maintainer-authored classification establishes direction, and the tracking issue and dependent PR identify a concrete staged use for this foundation; it correctly uses Related rather than claiming to close the broader request.

Merge readiness

✅ Ready for maintainer review

Keep this PR open as a useful foundation for scheduled-run consolidation; the prior findings are addressed, and no remaining concrete correctness blocker was found.

Priority: P2
Reviewed head: 1de54a2dd1a6d8af7d6cb547243a33dbc6a05037

Before merge

None.

Findings

None.

Tests

  • Low-value test src/cron/execution-context.fixtures.test.ts: Remove the standalone nonempty-fixture assertion: it checks static fixture inventory rather than a distinct execution-context failure.
  • Missing end-to-end proof: No shipped Gateway trace is supplied; the author reports static replay and test results, while the generation regression uses a mocked generation owner.
Agent review details

How this fits together

Cron supplies stored jobs and current parent/requester facts to a context builder; admission retains the result and releases its generation lease, while existing execution and effect owners continue making runtime decisions.

flowchart TD
  A[Scheduled job] --> B[Prompt executor]
  B --> C[Parent and requester facts]
  C --> D[Execution context builder]
  D --> E[Cron admission lifetime]
  E --> F[Release generation lease]
  B --> G[Existing runtime execution]
Loading

Technical review

Best possible solution:

Keep this as the bounded foundation and complete consumer cutovers through the linked admission and resource-owner PRs.

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

This is a staged feature foundation; source inspection confirms the new context is minted and retained without a production consumer, and no runtime reproduction was performed.

Is this the best way to solve the issue?

The builder reuses existing authority and generation owners, and the explicitly stacked admission cutover justifies retaining existing runtime decisions during this stage.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 3d2f7ca adds src/cron/run-admission.ts:70 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 3d2f7ca06b26; files: src/cron/run-admission.ts)
  • Josh Avant: Raw commit 187594c adds src/cron/run-admission.ts:50 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 187594c66309; files: src/cron/run-admission.ts)
  • Dallin Romney: Raw commit 5f604dd adds src/cron/isolated-agent/run-prompt-executor.ts:91 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 5f604ddd8095; files: src/cron/isolated-agent/run-prompt-executor.ts)

PR surface

Source +2689, Tests +804, Other +524. Total +4017 across 14 files. Added test files: 5.

View PR surface stats
Area Files Added Removed Net
Source 7 2720 31 +2689
Tests 5 804 0 +804
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 524 0 +524
Total 14 4048 31 +4017

Root-cause cluster

Relationship: partial_overlap
Canonical: #178812
Summary: This PR supplies the foundation for the tracked execution-context consolidation; occurrence-wide admission is a separate dependent slice.

Members:

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

Labels

Label changes:

  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Normal-priority foundation for scheduled-run consistency, with no immediate user-visible behavior change.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Exercise revisionless-parent admission and generation invalidation through the real generation owner.
  • Remove the standalone nonempty-fixture test.

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 (3 earlier review cycles)
  • reviewed 2026-10-21T02:36:53.987Z sha 0944c7d :: needs changes before merge. :: [P2] Use the runtime parent precedence in replay | [P2] Resolve the replay agent through the existing cron owner | [P2] Preserve requester and principal kinds in emitted fixtures | [P2] Preserve parent failure states when anonymizing rows
  • reviewed 2026-10-22T08:49:54.774Z sha 854c2aa223fa2950a5456fae9a222c70a6701e6c :: blocked before merge. :: [P2] Sanitize script payloads before exporting fixtures | [P2] Preserve the inputs that determine the effective tool cap
  • reviewed 2026-10-22T09:49:48.315Z sha 2fc1ec5 :: needs changes before merge. :: [P2] Retain the observed generation for revisionless parent links

Reviewed October 22, 2026, 6:16 AM ET / 10:16 UTC (Revision 4).

@jalehman

Copy link
Copy Markdown
Contributor Author

Addressed the review of 0944c7daf6f in b73bf86758d. The branch is also rebased onto current main, and the rebased PR diff is patch-identical.

  • Runtime parent precedence in replay: scheduledParentLinkOf in execution-context-admission.ts is now the one place that picks a job's parent link (operator source first, then the creating conversation). Both admission and the replay use it.
  • Replay agent resolution: the replay now resolves each job's agent with tryResolveCronJobEffectiveAgentId and the configured default (tryResolveAmbientOwnerAgentId). A job with no resolvable owner is reported as a fail row carrying the cron owner's error. It is no longer replayed as main.
  • Requester and principal kinds in fixtures: anonymization keeps a decodable operator source as a valid placeholder source (an undecodable one stays undecodable). It also keeps a channel requester's channel. Equal session keys stay equal.
  • Parent failure states in fixtures: the fixture parent row keeps three relationships to the stored link: same or replaced session, same or changed lifecycle revision (rev-1/rev-2), and whether the worktree exists.
  • Tests: test/scripts/cron-context-replay.test.ts covers each of these: an operator-source parent stays a parent, a channel requester is kept, a changed revision replays as pause, and a missing worktree replays as pause. Fixtures were regenerated from a real Gateway's state copy (27 shapes).
  • Low-value tests: removed the same-input self-comparison test and the repeated no-unexpected-gain traversal.
  • End-to-end proof: nothing consumes the context in this PR, so a live Gateway run can't show a behavior change yet. Consumer PRs carry that proof.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. 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. clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 22, 2026
buildScheduledExecutionContext derives one occurrence's principal, placement,
authority, tool policy, resource scopes and inference account from stored job
fields plus caller-read facts (parent row, requester check). No consumer reads
it yet; admission minting follows in openclaw-0d5.2.

Jobs with sourceConversation or operatorSource become children of that exact
parent and pause when it is removed, archived or reset, or its worktree is
gone. Key-only parent links stay on their legacy decisions. A parent-linked
job without a recorded requester gets no owner authority.

The admission-source rule moves unchanged into src/cron/admission-source.ts
so the timer and the builder share one owner.
Each prompt-executor attempt reads the parent session row (for jobs with an
exact parent link), rechecks the requester, builds the context and binds it to
the admitted run. A parent-linked context holds the parent's session generation
so assertCurrent fails once the parent is reset or removed; the lease is
released when the admission closes. Nothing reads the context yet, and minting
errors become a fail result instead of failing the run.

The prompt executor's scheduled tool policy setup moves into the same module so
the executor stays under its line cap.
execution-context-projection reproduces what the existing scheduled-run code
decides for a stored job and labels where the context differs (equal,
gain-intended, gain-unexpected, loss, retarget, pause). Doctor will reuse it.

scripts/dev/cron-context-replay.mts is a development script: it copies a
Gateway's state and agent session databases with SQLite's online backup into a
private temp directory, replays every stored job against the copies, prints the
labels and can emit anonymized job shapes. The fixture test pins the builder and
projection results for those shapes.
Read the parent row with the same precedence the builder uses (operator source
first, then the creating conversation). Expose the minted context through the
admission owner until a consumer reads it, use typed rank lookups, keep real
exports in test mocks, and register the replay script as a Knip script entry.
Replay now reads the parent row with the admission's parent precedence
(operator source first) and resolves each job's agent through the cron
owner resolver, reporting jobs with no resolvable owner instead of
replaying them as main. Fixture anonymization keeps operator sources,
channel requesters, lifecycle-revision changes and worktree existence,
so emitted fixtures replay to the same outcome as the recorded jobs.

Drops two tests that restated existing assertions and comments that
named future work.
The parent-generation lease taken while minting was released only by a closed admission or the missing-fence path. Any other preparation error left it held. The prompt executor now releases it whenever preparation throws, and admission keeps releasing it on close.
@jalehman
jalehman force-pushed the automations/execution-context-foundation branch from 854c2aa to c90ce34 Compare October 22, 2026 09:23
…puts

Script and system-event payloads were exported unchanged, so --emit-fixtures could write private script bodies into anonymized fixtures. Trigger and runtime-authority markers were dropped, letting resolveCronRunToolsAllow widen a restricted automatic cap in the fixture.
@jalehman

Copy link
Copy Markdown
Contributor Author

Addressed the review of 854c2aa223f in 2fc1ec5944c. The branch was also rebased onto current main first (patch-identical, c90ce347528), which cleared a stale-merge-ref UI type failure; CI was fully green there.

  • Sanitize script payloads: the anonymizer now rebuilds every payload kind. Script bodies become return null and system-event text becomes a placeholder; their toolsAllow lists and toolsAllowIsDefault are kept whole. Command argv was already replaced.
  • Preserve tool-cap inputs: fixtures now keep a condition trigger (with a placeholder script), runtimeAuthority (runtime id and namespace, empty payload) and runtimeAuthorityRecoveryRequired, so resolveCronRunToolsAllow returns the same cap for the fixture as for the stored job.
  • Exposure check: the committed execution-context.fixtures.json contains no script, system-event, trigger or runtime-authority jobs, so no private content was ever committed. Regenerating against the live store produces no such shapes either, so the committed fixtures are unchanged.
  • Tests: test/scripts/cron-context-replay.test.ts covers sanitized script and system-event bodies with long caps kept equal, and the restricted automatic cap for each of trigger, runtime authority and recovery-required. Both new cases fail without the fix.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 22, 2026
A parent link stored without a lifecycle revision leased generation null, which the generation owner rejects against the row's revision, so a valid parent-linked occurrence minted a fail result. Admission now leases the revision of the parent row the builder validated. Also replaces the anonymizer's switch with returns that satisfy consistent-return.
@jalehman

Copy link
Copy Markdown
Contributor Author

Addressed the review of 2fc1ec5944c in 1de54a2dd1a.

  • Revisionless parent links: admission now leases the lifecycle revision of the parent row the builder just validated when the stored link has none (parent.lifecycleRevision ?? observed row revision ?? null). The exact session-ID check and every later assertCurrent generation check are unchanged. execution-context-admission.test.ts covers a revisionless sourceConversation with a rev-1 row: the result is ready and the lease receives rev-1. The test fails without the fix.
  • Also fixes the check-lint failure on 2fc1ec5944c (consistent-return in the replay anonymizer). No behavior change.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 22, 2026
@jalehman
jalehman merged commit 240a90e into main Oct 22, 2026
133 checks passed
@jalehman

Copy link
Copy Markdown
Contributor Author

Merged via squash.

@jalehman
jalehman deleted the automations/execution-context-foundation branch October 22, 2026 10:30
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 23, 2026
…ge) (openclaw#178933)

* feat(cron): add pure scheduled execution context builder

buildScheduledExecutionContext derives one occurrence's principal, placement,
authority, tool policy, resource scopes and inference account from stored job
fields plus caller-read facts (parent row, requester check). No consumer reads
it yet; admission minting follows in openclaw-0d5.2.

Jobs with sourceConversation or operatorSource become children of that exact
parent and pause when it is removed, archived or reset, or its worktree is
gone. Key-only parent links stay on their legacy decisions. A parent-linked
job without a recorded requester gets no owner authority.

The admission-source rule moves unchanged into src/cron/admission-source.ts
so the timer and the builder share one owner.

* feat(cron): mint the scheduled execution context at run admission

Each prompt-executor attempt reads the parent session row (for jobs with an
exact parent link), rechecks the requester, builds the context and binds it to
the admitted run. A parent-linked context holds the parent's session generation
so assertCurrent fails once the parent is reset or removed; the lease is
released when the admission closes. Nothing reads the context yet, and minting
errors become a fail result instead of failing the run.

The prompt executor's scheduled tool policy setup moves into the same module so
the executor stays under its line cap.

* test(cron): add execution context replay and stored-shape fixtures

execution-context-projection reproduces what the existing scheduled-run code
decides for a stored job and labels where the context differs (equal,
gain-intended, gain-unexpected, loss, retarget, pause). Doctor will reuse it.

scripts/dev/cron-context-replay.mts is a development script: it copies a
Gateway's state and agent session databases with SQLite's online backup into a
private temp directory, replays every stored job against the copies, prints the
labels and can emit anonymized job shapes. The fixture test pins the builder and
projection results for those shapes.

* fix(cron): align the context's parent read with principal resolution

Read the parent row with the same precedence the builder uses (operator source
first, then the creating conversation). Expose the minted context through the
admission owner until a consumer reads it, use typed rank lookups, keep real
exports in test mocks, and register the replay script as a Knip script entry.

* fix(cron): keep replay fixtures faithful to runtime admission

Replay now reads the parent row with the admission's parent precedence
(operator source first) and resolves each job's agent through the cron
owner resolver, reporting jobs with no resolvable owner instead of
replaying them as main. Fixture anonymization keeps operator sources,
channel requesters, lifecycle-revision changes and worktree existence,
so emitted fixtures replay to the same outcome as the recorded jobs.

Drops two tests that restated existing assertions and comments that
named future work.

* fix(cron): release the minted context when admission preparation throws

The parent-generation lease taken while minting was released only by a closed admission or the missing-fence path. Any other preparation error left it held. The prompt executor now releases it whenever preparation throws, and admission keeps releasing it on close.

* fix(cron): sanitize every replay fixture payload and keep tool-cap inputs

Script and system-event payloads were exported unchanged, so --emit-fixtures could write private script bodies into anonymized fixtures. Trigger and runtime-authority markers were dropped, letting resolveCronRunToolsAllow widen a restricted automatic cap in the fixture.

* fix(cron): hold the observed parent generation for revisionless links

A parent link stored without a lifecycle revision leased generation null, which the generation owner rejects against the row's revision, so a valid parent-linked occurrence minted a fail result. Admission now leases the revision of the parent row the builder validated. Also replaces the anonymizer's switch with returns that satisfy consistent-return.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: XL 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