Skip to content

fix: keep automation runs alive and route monitoring waits - #1377

Merged
Astro-Han merged 6 commits into
devfrom
codex/automate-delete-run-routing
Jun 19, 2026
Merged

fix: keep automation runs alive and route monitoring waits#1377
Astro-Han merged 6 commits into
devfrom
codex/automate-delete-run-routing

Conversation

@Astro-Han

@Astro-Han Astro-Han commented Jun 18, 2026

Copy link
Copy Markdown
Owner

Summary

  • Decouple Automation deletion from active run cancellation: deleting an Automation now removes the definition and future scheduling while already-started runs continue.
  • Preserve automation run ledger rows after definition deletion by removing the definition cascade from automation_run.automation_id, and sync the delete OpenAPI/SDK contract.
  • Expand model-facing scheduling guidance so monitoring, polling, repeated checks, and minute-scale waits route to automate, while short current-turn sleeps stay capped at 60 seconds.

Why

A run could interrupt itself by deleting its own Automation definition, because Automation.remove() aborted the active controller and the run row was cascaded away with the definition. Separately, the automate routing contract did not make periodic monitoring obvious enough, so models could drift toward long sleep loops for tasks such as checking CI every few minutes.

Related Issue

No linked issue; this was requested directly by the maintainer after discussion.

Human Review Status

Approved by @Astro-Han (fresh-eye review gate passed with no P0/P1 findings)

Review Focus

  • The delete semantics: remove() no longer aborts active runs or returns a stopped run, and the HTTP/SDK contract no longer exposes a delete-time active-run 409.
  • The migration that rebuilds automation_run without the Automation definition foreign-key cascade while keeping the project cascade.
  • The prompt wording that separates short bounded waits from background monitoring/polling.

Risk Notes

  • Behavior/deletion: deleting an Automation now leaves already-started runs alive; cancelling a run remains a separate run-stop action.
  • Migration: automation_run.automation_id is intentionally no longer constrained to an existing definition so run history survives definition deletion; project_id still cascades with project deletion.
  • Generated content: the v2 SDK delete types were synchronized narrowly. Full SDK generation currently surfaces unrelated existing drift, so unrelated generated churn was not included.
  • UI/screenshots: no visible UI changed; only runtime behavior and model-facing prompt/tool descriptions changed.
  • Platform: no OS-specific execution path changed; the scheduler guidance still covers macOS/Windows/Linux scheduler names.

How To Verify

Focused automation/runtime/prompt tests: 173 passed across automation-runner, automation-routes, automate-manage, automate, registry, system prompt, and shell prompt tests.
Opencode typecheck: passed (`bun run typecheck` in packages/opencode).
SDK typecheck: passed (`bun run typecheck` in packages/sdk/js).
Migration check: passed (`bun run script/check-migrations.ts` in packages/opencode).
Diff whitespace check: passed (`git diff --check origin/dev...HEAD`).

Screenshots or Recordings

Not applicable; no visible UI changed.

Checklist

  • Type label — this PR carries exactly one of bug, enhancement, task, documentation. Type labels are author-added; the labeler bot does NOT assign them. Add the label in the GitHub UI, then tick this.
  • Routing labels — this PR carries at least one of app, ui, platform, harness, ci. The labeler bot assigns these on PR open based on changed paths. Confirm the bot's choice (or override if wrong), then tick this.
  • Priority label — this PR carries exactly one of P0, P1, P2, P3. The priority-triage bot suggests one on PR open. Confirm or override, then tick this.
  • Human Review Status above is set to Pending, Approved by @<reviewer>, or Not required: <reason> (default is Pending; "not required" is restricted to bot-authored low-risk PRs).
  • I linked the related issue, or stated in Summary why there is no issue.
  • I described the review focus and any meaningful risks.
  • I replaced the example block in How To Verify with the real verification steps and the key result for each.
  • I did not introduce unrelated refactors, dependencies, generated files, or file changes beyond the stated scope.
  • (conditional) I manually checked visible UI or copy changes when needed, with screenshots or recordings. Leave unticked only if no visible UI or copy changed.
  • (conditional) I considered macOS and Windows impact for platform, packaging, updater, signing, paths, shell, or permissions changes. Leave unticked only if no platform/packaging surface was touched.
  • (conditional) I called out docs, release notes, dependencies, permissions, credentials, deletion behavior, generated content, or local file changes when relevant. Leave unticked only if none of those surfaces was touched.
  • I reviewed the final diff for unrelated changes and suspicious dependency changes.
  • I am targeting dev, and my PR title and commit messages use Conventional Commits in English.

Summary by CodeRabbit

Release Notes

Improvements

  • Automation runs now continue executing even if their automation definition is deleted, ensuring critical background tasks complete without interruption.

Documentation

  • Enhanced automation tool guidance to clarify scheduling capabilities for monitoring, polling, and recurring tasks.

@Astro-Han Astro-Han added bug Something isn't working P2 Medium priority harness Model harness, prompts, tool descriptions, and session mechanics labels Jun 18, 2026
@coderabbitai

coderabbitai Bot commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Automation run history is decoupled from automation definition lifetime. A DB migration rebuilds automation_run without a FK to automation_definition, adds owner_directory, and ties project_id to project with ON DELETE CASCADE. The ActiveRunStillRunningError path is removed from the delete flow across the automation module, HTTP routes, and the automate-manage tool. Durable active-writer detection becomes scope-aware. Prompt and tool guidance adds explicit polling/monitoring use-cases and a 60-second in-turn sleep cap.

Changes

Automation run history survives definition delete

Layer / File(s) Summary
DB migration: rebuild automation_run without automation_definition FK
packages/opencode/migration/.../migration.sql, packages/opencode/src/automation/automation.sql.ts
Creates automation_run_next with owner_directory and project_id → project(id) ON DELETE CASCADE, copies all rows, drops and renames the table, adds two covering indexes, and removes the ORM foreign-key reference on automation_id.
Remove active-run stop/conflict logic from delete path
packages/opencode/src/automation/index.ts
Deletes ActiveRunStillRunningError, stopActiveRun, getLiveActiveRun, and the stoppedRun return value from remove(), deleteBySourceSession(), the Effect service interface, and the service-layer catch handler.
Scope-aware durable active-writer detection in executeRun
packages/opencode/src/automation/index.ts
hasDurableActiveWriter accepts a scope parameter and derives projectID/ownerDirectory from it; executeRun computes scope and passes it into reconcileInterruptedRuns and hasDurableActiveWriter.
HTTP route and tool layer: remove 409 and stoppedRun surface
packages/opencode/src/server/instance/automation.ts, packages/opencode/src/tool/automate-manage.ts
Removes the ActiveRunStillRunningError import, 409 response helper, and HTTP 409 branch from runRoute. Drops stoppedRun publish from deleteAutomation and from automate-manage delete metadata. Updates DELETE route OpenAPI description.
Prompt and tool description: polling/monitoring constraints
packages/opencode/src/tool/automate.ts, packages/opencode/src/tool/shell.txt, packages/opencode/src/session/prompt/pawwork.txt
PawWork system prompt adds monitoring/polling use-cases, a 60-second in-turn sleep cap, and a stronger OS-scheduler prohibition. automate description broadened to include background monitoring. Shell tool guidance adds 60-second sleep-loop limit and extended exclusion list.
Tests: assert run persists after definition delete
packages/opencode/test/server/automation-routes.test.ts, packages/opencode/test/server/automation-runner.test.ts, packages/opencode/test/tool/automate-manage.test.ts, packages/opencode/test/tool/automate.test.ts, packages/opencode/test/tool/registry.test.ts
Adds readRun/waitForRunByID DB-polling helpers. Updates all deletion tests to expect success and verify the active run row remains in the DB. Removes 409 OpenAPI assertions. Extends description contract tests for polling/monitoring phrasing.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant AutomationRoute as DELETE /automation/:id
    participant AutomationModule as Automation.remove()
    participant DB

    Client->>AutomationRoute: DELETE /automation/{automationID}
    AutomationRoute->>AutomationModule: remove(id)
    AutomationModule->>DB: delete automation_definition row
    DB-->>AutomationModule: ok
    AutomationModule-->>AutomationRoute: { tombstone }
    AutomationRoute-->>Client: 200 { tombstone }

    note over DB: automation_run rows<br/>remain untouched<br/>(no cascade delete)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

  • Astro-Han/pawwork#983: Modifies the same Automation.remove() and active-run stop logic in packages/opencode/src/automation/index.ts, directly overlapping with this PR's deletion flow changes.
  • Astro-Han/pawwork#984: Touches the same stopActiveRun/stopRunByID helpers in packages/opencode/src/automation/index.ts that this PR removes.
  • Astro-Han/pawwork#1278: Introduced the automate_manage delete lifecycle with ActiveRunStillRunningError handling and stoppedRun publish behavior that this PR removes.

Suggested labels

enhancement, P1

🐇 A run once started shall finish its race,
Even if its definition has left without trace.
No 409 to block, no cascade to erase,
The history survives in its own little space.
Migration complete — the records remain in place! 🗃️

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 5.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix: keep automation runs alive and route monitoring waits' accurately captures the main changes: decoupling automation deletion from run cancellation and updating scheduling guidance for monitoring/polling.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The PR description is comprehensive and complete, covering all required template sections including Summary, Why, Related Issue, Human Review Status, Review Focus, Risk Notes, How To Verify, and a fully ticked Checklist.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/automate-delete-run-routing

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested priority: P2 (includes non-doc, non-test paths outside the low-risk bucket).

P1/P0 are reserved for maintainer confirmation. Please relabel manually if this is a release blocker, security issue, data-loss risk, or updater/runtime failure.

@Astro-Han
Astro-Han merged commit 98d07fc into dev Jun 19, 2026
39 checks passed
@Astro-Han
Astro-Han deleted the codex/automate-delete-run-routing branch June 19, 2026 01:16
Astro-Han added a commit that referenced this pull request Jun 19, 2026
Related to #936.

Goal:
- Add local Effect HttpApi coverage for ordinary Automation JSON routes while preserving the existing Hono compatibility entry point.

Changes:
- Extract shared automation route actions so Hono and HttpApi handlers use the same lifecycle, validation, run ledger, pause/resume, run-now, and delete behavior.
- Add local HttpApi declarations and handlers for list, create, get, update, delete, runs, run, pause, and resume automation routes.
- Keep delete semantics from #1377: deleting an automation stops future scheduling but preserves already-started run history.
- Tighten automation HttpApi route contracts for automation IDs, run cursors, and run pagination limits so they match runtime validators.
- Update route inventory harness coverage for ordinary Automation routes.

Verification:
- bun install --frozen-lockfile
- Baseline focused tests before changes: bun test test/server/automation-routes.test.ts test/server/automation-runner.test.ts test/tool/automate-manage.test.ts test/server/route-inventory-harness.test.ts passed, 111 tests.
- Review-fix RED: the automation OpenAPI contract test failed before tightening automationID, limit, and cursor schemas.
- Focused tests after final changes: bun test test/server/automation-routes.test.ts test/server/automation-runner.test.ts test/tool/automate-manage.test.ts test/server/route-inventory-harness.test.ts passed, 119 tests.
- GOMAXPROCS=2 bun run typecheck
- git diff --check origin/dev...HEAD
- Final fresh-eye review: PASS under P0/P1 gate; no P0/P1/P2/P3 findings.
- PR CI passed, including unit-opencode and split Windows advisory shards.

Residual risk:
- Production server routing is intentionally not switched in this PR; Hono remains the compatibility entry point until the broader HttpApi cutover is ready.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working harness Model harness, prompts, tool descriptions, and session mechanics P2 Medium priority

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant