Skip to content

fix(agents): remove a deleted agent's cron jobs on the offline delete path - #127075

Merged
steipete merged 2 commits into
mainfrom
steipete/offline-delete-cron-cleanup
Aug 21, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/offline-delete-cron-cleanup

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Follow-up to #127037, which fixed the exec-approvals half of this gap and named this one explicitly.

agents delete tries the Gateway first and falls back to a local path when the Gateway is unavailable. The Gateway handler nests two transactional cleanups around the roster commit:

await context.cron.removeAgentJobsTransactional(agentId, async () =>
  await withAgentExecApprovalsRemoved(agentId, async () => { ...deleteAgentConfigEntry... }))

After #127037 the offline path performed the inner one. It still skipped cron:

$ openclaw agents delete cronprobe --force
Deleted agent: cronprobe                       <- no mention of cron

$ sqlite3 <state>/state/openclaw.sqlite "select job_id, name, agent_id, enabled from cron_jobs"
975cb750-... | cronprobe-job | cronprobe | 1

$ openclaw cron list
cronprobe-job    every 1h    Next: in 59m    idle

Being accurate about severity: this is not a silent failure. Firing the job records error: "cron job agent is unavailable: cronprobe", and cron list flips to error. The defect is that the job keeps its schedule forever, failing on every fire, and agents delete never mentions it. The sharper risk is id reuse — recreate an agent with that id and the orphaned job starts running against it.

Why This Change Was Made

The interesting part was working out whether the offline path may touch the cron store at all.

maybeDeleteAgentThroughGateway collapsed two different failure reasons into one null return: an unreachable Gateway, and a Gateway credentials failure. Those are not equivalent. Credential resolution fails before transport, so a live scheduler may still own the cron store; an unreachable Gateway means nothing else is holding it. Mutating the store directly is safe in the second case and wrong in the first.

It now returns a discriminated union, and only the unreachable branch removes jobs directly. The credentials branch commits the roster, emits a warning, and sets cronCleanupSkipped: true in --json:

Warning: cron cleanup was skipped for deleted agent "X" because the Gateway could not be
authenticated; scheduled jobs may remain.

Transaction ordering matches the Gateway: cron wraps approvals, which wraps the roster commit, with the deletion journal committing afterward.

A working non-Gateway removeAgentJobsTransactional already existed inside local-request-context.ts. Rather than write a second cron mutation path, it moves to src/cron/local-service.ts and both callers share it.

That extraction changes one thing deliberately: the default-owner resolver goes from tryResolveLegacyCompatibilityAgentId to tryResolveAmbientOwnerAgentId. The latter is a strict superset — it honors an explicitly configured agents.defaults.systemAgent.agentId and otherwise falls back to exactly the former, so no config without that key changes behavior. Live testing showed agentless memory-dreaming jobs need it to load correctly under explicit agent ownership, and "ambient system work" is what that resolver documents itself as being for.

User Impact

Deleting an agent with no Gateway running now removes its scheduled jobs, matching Gateway behavior. When credentials prevent the CLI from knowing whether a scheduler is live, deletion still completes but says what it skipped instead of reporting a clean delete.

docs/cli/agents.md documents both branches.

Production LOC: +89/-62, net +27. Tests +95/-1, docs +1/-1.

Evidence

Live before/after on isolated OPENCLAW_STATE_DIR and HOME with a pinned unused port, reading cron_jobs directly rather than trusting CLI output:

case before after
deleted agent's job cronprobe-job remains, enabled=1 removed
another agent's job (survivor-job) — untouched
built-in heartbeat-main, Memory Dreaming Promotion — untouched, survive Gateway restart
agent with no cron jobs — deletes cleanly, other jobs unchanged

Both proof Gateways were stopped afterward; ports 18995 and 18996 confirmed free.

Tests, re-run here after resolving the rebase onto post-#127037 main: agents.delete.test.ts 27 passed, local-request-context.test.ts 10 passed, exec-approvals-store.test.ts 24 passed, rc=0. The worker's fuller sweep additionally covered cron transactional ops (68), gateway agent mutations (204), lazy cron contract (44), CLI registration (33), gateway config patch (92), and tooling fixtures (205). A pre-fix regression test failed as intended with removed-job still present.

pnpm build passed (3m30s). node scripts/check-changed.mjs passed on Testbox tbx_01m0hgq27dncd1tfc2yzzmawcd (Actions run 32455263712), including oxlint, typecheck, import-cycle and database-first guards, 777 docs MDX files and 6,525 links. $autoreview: clean, no actionable findings.

Known gaps, stated rather than buried

  • The credentials branch is regression-test proven, not live-proven. The isolated Gateway auto-paired its local CLI, so that path could not be induced end to end.
  • src/gateway/server-cron.test.ts hangs on an untouched test, keeps script failure detail transient…. I ran that suite on clean main with no changes applied and it hung the same way for 15+ minutes before I stopped it, so it looks pre-existing rather than caused here — but I could not obtain a clean baseline pass to compare against, so I am flagging it rather than asserting it. CI is the authority.
  • Probing the credentials branch surfaced an unrelated /tmp vs /private/tmp Gateway trash-root refusal, left as a named follow-up rather than widening this change.

… path

Follow-up to #127037, which fixed the exec-approvals half of the same gap and
named this one explicitly.

`agents delete` tries the Gateway first and falls back to a local path. The
Gateway handler nests two transactional cleanups around the roster commit --
cron wrapping approvals wrapping the config write. After #127037 the offline
path did the inner one; it still skipped cron. So deleting an agent without a
Gateway left its scheduled jobs enabled:

    $ openclaw agents delete cronprobe --force
    Deleted agent: cronprobe            <- no mention of cron
    $ sqlite3 <state>/state/openclaw.sqlite "select job_id, name, agent_id, enabled from cron_jobs"
    975cb750-... | cronprobe-job | cronprobe | 1
    $ openclaw cron list
    cronprobe-job   every 1h   Next: in 59m   idle

To be accurate about severity: this is not silent. Each firing records
`error: "cron job agent is unavailable: cronprobe"` and `cron list` flips to
`error`. The defect is that the job keeps its schedule forever, and that
recreating an agent with the same id points it at the new agent.

The fallback had collapsed two different reasons into one `null` return, which
is what made the fix look unsafe at first: credential failures happen *before*
transport, so a live scheduler may still own the cron store, while an
unreachable Gateway means nothing else is holding it. `maybeDeleteAgentThroughGateway`
now returns a discriminated union, and only the unreachable branch mutates the
store directly. The credentials branch commits the roster, warns, and sets
`cronCleanupSkipped: true` in JSON.

The local `CronService` construction already existed inside
`local-request-context.ts`; it moves to `src/cron/local-service.ts` and both
callers share it rather than growing a second cron mutation path. That
extraction also switches the default-owner resolver from
`tryResolveLegacyCompatibilityAgentId` to `tryResolveAmbientOwnerAgentId`, which
is a superset -- it honors an explicitly configured
`agents.defaults.systemAgent.agentId` and otherwise falls back to exactly the
previous function. Live testing showed agentless memory-dreaming jobs need it to
load under explicit agent ownership.

Production +89/-62.
@clawsweeper

clawsweeper Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@steipete
steipete marked this pull request as ready for review August 21, 2026 06:59
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime commands Command implementations size: M maintainer Maintainer-authored PR labels Aug 21, 2026
…nder the cap

The 40-line cron regression test added in the previous commit pushed
`src/commands/agents.delete.test.ts` to 1018 code lines, over the 1000 cap, and
`check-lint-core-3` went red. Repo policy forbids a `max-lines` suppression.

Unlike the earlier `cron/view.test.ts` split there was no describe-level seam --
23 flat tests in a single describe -- so the split follows subject instead. The
seven workspace-lifecycle tests (trashing, sharing, overlap, symlink reachability,
workspace-state cleanup) move to `agents.delete.workspace.test.ts`.

`vi.mock` and `vi.hoisted` are per-file and cannot be imported, so the mock
preamble and the shared `beforeEach` are declared in both files; the helper block
above them is unchanged in each. Each file then imports only what it uses, which
is why the import lists differ.

Trimming to a hair under the cap by moving only the new test was possible and
rejected: it would have left the file at ~978 code lines, back at the cap within
a couple of changes. This leaves 749 and 603 physical lines.

No test content changed: 27 passed before, 27 after.
@steipete

Copy link
Copy Markdown
Contributor Author

check-lint-core-3 was mine, not pre-existing: the 40-line cron regression test pushed src/commands/agents.delete.test.ts to 1018 code lines, past the 1000 max-lines cap.

Fixed by splitting rather than suppressing, per repo policy. Unlike the earlier cron/view.test.ts split there was no describe-level seam — 23 flat tests in one describe — so this splits by subject: the seven workspace-lifecycle tests (trashing, sharing, path overlap, symlink reachability, workspace-state cleanup) move to agents.delete.workspace.test.ts. vi.mock/vi.hoisted are per-file and cannot be imported, so the mock preamble and shared beforeEach are declared in both, and each file imports only what it uses.

Moving just the new test would also have cleared the cap, at ~978 code lines — rejected for the same reason I gave when closing #127020: that is back at the cap within a couple of changes. The files now sit at 749 and 603 lines.

27 tests passed before the split and 27 after; oxlint over all of src/commands/ is clean.

@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. labels Aug 21, 2026
@clawsweeper

clawsweeper Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed August 21, 2026, 3:13 AM ET / 07:13 UTC.

ClawSweeper review

What this changes

This PR removes an offline-deleted agent’s cron jobs when the Gateway is unreachable, while warning and preserving cron state when Gateway credentials are unavailable.

Merge readiness

⚠️ Needs maintainer review before merge - 4 items remain

Keep this PR open: its new local cron helper ignores configured cron.store, so offline deletion can leave scheduled jobs for a deleted agent in existing custom-store setups.

Priority: P1
Reviewed head: dd20e9cc7f44df4a3e63935ae7596d992c3fab7a

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The default-path behavior has credible live proof, but a P1 custom-store defect blocks merge readiness.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The PR body supplies after-fix isolated CLI evidence that inspects persisted cron rows and shows the deleted agent’s job removed while survivor and system jobs remain.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR body supplies after-fix isolated CLI evidence that inspects persisted cron rows and shows the deleted agent’s job removed while survivor and system jobs remain.
Evidence reviewed 8 items Broken configured-store selection: The new shared local helper creates its CronService with the bare default-path resolver, so it does not use cfg.cron.store.
Existing canonical resolver: The cron store module provides a config-aware resolver that selects cfg.cron.store before falling back to the environment/default path.
New affected entry point: The offline-unreachable branch now invokes the shared local cron helper around roster cleanup, exposing this partition-selection bug to agents delete.
Findings 1 actionable finding [P1] Resolve the configured cron partition
Security None None.

Live Verification

Command: pnpm openclaw agents delete --help

Result: PASS (completed)

pnpm openclaw agents delete --help
runner@runnervm76f27:/tmp/clawsweeper-live-proof-127075-xXhuGg/target$ pnpm openclaw agents delete --help
$ node scripts/run-node.mjs agents delete --help
pnpm openclaw agents delete --help
[openclaw] Building TypeScript (dist is stale: missing_build_stamp - build stamp missing).
[openclaw] Building bundled plugin assets.
[canvas] build: node scripts/bundle-a2ui.mjs
[log] ‹DIR›/a2ui.bundle.js  chunk │ size: 399.96 kB
[log] ‹DIR›/a2ui-v0.9.bundle.js  chunk │ size: 615.66 kB
[log]
[success] rolldown v1.2.0 Finished in 98.71 ms
[diffs] build: node --import tsx ../../scripts/build-diffs-viewer-runtime.mts curated
[diffs-language-pack] build: node --import tsx ../../scripts/build-diffs-viewer-runtime.mts full
[discord] build: node --import tsx ../../scripts/build-discord-activity-sdk.mts
[tsdown-build] invocation 1/2 finished in 0.7s
node_modules/web-tree-sitter/web-tree-sitter.js (2343:30) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
      ╭─[ node_modules/web-tree-sitter/web-tree-sitter.js:2343:31 ]
      │
 2343 │           ASM_CONSTS[start] = eval(func);
      │                               ──┬─
      │                                 ╰─── Use of direct ˋevalˋ here.
      │
      │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
──────╯

node_modules/web-tree-sitter/web-tree-sitter.js (2366:32) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
      ╭─[ node_modules/web-tree-sitter/web-tree-sitter.js:2366:33 ]
      │
 2366 │           moduleExports[name] = eval(func);
      │                                 ──┬─
      │                                   ╰─── Use of direct ˋevalˋ here.
      │
      │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
──────╯

node_modules/playwright-core/lib/coreBundle.js (65821:28) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
       ╭─[ node_modules/playwright-core/lib/coreBundle.js:65821:29 ]
       │
 65821 │               const value = eval(ˋ(${expr})ˋ);
       │                             ──┬─
       │                               ╰─── Use of direct ˋevalˋ here.
       │
       │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
───────╯

node_modules/playwright-core/lib/coreBundle.js (65828:28) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
       ╭─[ node_modules/playwright-core/lib/coreBundle.js:65828:29 ]
       │
 65828 │               const value = eval(ˋ(${expr})ˋ);
       │                             ──┬─
       │                               ╰─── Use of direct ˋevalˋ here.
       │
       │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
───────╯

[tsdown-build] invocation 2/2 finished in 13.5s
[plugin-control-plane-loads] verified 35 built modules with native require and checked doctor closures
runtime-postbuild: 11 phases completed in 4138ms (slowest: built plugin control-plane loads 3411ms)
│
◇

OpenClaw 2026.8.1 (dd20e9c) — All your chats, one OpenClaw.

Usage: openclaw agents delete [options] ‹id›

Delete an agent and prune workspace/state

Options:
  --force     Skip confirmation (default: false)
  -h, --help  Display help for command
  --json      Output JSON summary (default: false)
runner@runnervm76f27:/tmp/clawsweeper-live-proof-127075-xXhuGg/target$ pnpm openclaw agents delete --help
$ node scripts/run-node.
… output truncated …

Assertions:

  • PASS expect_output: --force

How this fits together

agents delete delegates to the Gateway when possible and otherwise performs local lifecycle cleanup. Cron jobs are persistent work associated with agent IDs, so deletion must remove jobs from the same configured scheduler partition.

flowchart LR
  A[Operator runs agents delete] --> B[Gateway attempt]
  B --> C{Gateway result}
  C -->|Deleted| D[Gateway lifecycle cleanup]
  C -->|Unreachable| E[Local transactional cleanup]
  C -->|Credentials unavailable| F[Local delete with warning]
  E --> G[Cron jobs and approvals removed]
  D --> G
  F --> H[Scheduler state left untouched]
Loading

Before merge

  • Resolve the configured cron partition (P1) - CronService receives resolveCronJobsStorePath() without cfg.cron.store, although resolveCronJobsStorePathFromConfig owns that contract. A custom-store installation will therefore mutate the default partition and leave the deleted agent’s real jobs enabled. The current test uses the default-equivalent path, so it misses this case.
  • Resolve merge risk (P1) - Custom cron.store installations can retain jobs for a deleted agent because this PR selects the default cron partition.
  • Resolve merge risk (P1) - Production code is net +27 lines; the two-caller extraction is justified, but its shared store-selection contract must be corrected before merge.
  • Complete next step (P2) - The maintainer label requires explicit maintainer handling; fix the concrete P1 finding before merge.

Findings

  • [P1] Resolve the configured cron partition — src/cron/local-service.ts:16
Agent review details

Security

None.

PR surface

Source +27, Tests +323, Docs 0. Total +350 across 7 files.

View PR surface stats
Area Files Added Removed Net
Source 3 89 62 +27
Tests 3 698 375 +323
Docs 1 1 1 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 788 438 +350

Review metrics

Metric Value Why it matters
Production versus test delta production +89/-62 (net +27); tests +95/-1 after discounting a 603-line test move; docs 0 net The shared helper removes duplicated local Gateway setup, but its configuration-sensitive behavior needs correction.

Merge-risk options

Maintainer options:

  1. Respect configured cron storage (recommended)
    Use the config-derived cron store resolver and add a non-default-store regression test before merging.

Technical review

Best possible solution:

Keep the shared local helper, resolve its store path from runtime configuration, and prove both default and non-default cron partitions retain only surviving agents’ jobs.

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

Yes from source: configure a non-default cron.store, seed an agent job there, stop the Gateway, and delete that agent; the new helper resolves no config store argument.

Is this the best way to solve the issue?

No. The shared local cleanup is the right owner boundary, but it must use the config-derived cron store resolver.

Full review comments:

  • [P1] Resolve the configured cron partition — src/cron/local-service.ts:16
    CronService receives resolveCronJobsStorePath() without cfg.cron.store, although resolveCronJobsStorePathFromConfig owns that contract. A custom-store installation will therefore mutate the default partition and leave the deleted agent’s real jobs enabled. The current test uses the default-equivalent path, so it misses this case.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.99

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P1: A supported custom scheduler partition can retain enabled jobs that continue to target a deleted agent.
  • add merge-risk: 🚨 compatibility: Existing users with cron.store configured can experience incomplete deletion after this change.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body supplies after-fix isolated CLI evidence that inspects persisted cron rows and shows the deleted agent’s job removed while survivor and system jobs remain.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): The PR body supplies after-fix isolated CLI evidence that inspects persisted cron rows and shows the deleted agent’s job removed while survivor and system jobs remain.

Label justifications:

  • P1: A supported custom scheduler partition can retain enabled jobs that continue to target a deleted agent.
  • merge-risk: 🚨 compatibility: Existing users with cron.store configured can experience incomplete deletion after this change.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): The PR body supplies after-fix isolated CLI evidence that inspects persisted cron rows and shows the deleted agent’s job removed while survivor and system jobs remain.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body supplies after-fix isolated CLI evidence that inspects persisted cron rows and shows the deleted agent’s job removed while survivor and system jobs remain.

Evidence

What I checked:

Likely related people:

  • steipete: Authored the current patch and the merged adjacent offline agent-deletion lifecycle repair. (role: recent area contributor; confidence: high; commits: 0f642d2ac178, dd20e9cc7f44; files: src/commands/agents.commands.delete.ts, src/cron/local-service.ts, src/gateway/server-methods/agents.ts)

Rank-up moves

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

  • Resolve the cron store from runtime configuration and add a non-default-store regression test.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@steipete
steipete merged commit 58127fa into main Aug 21, 2026
414 of 416 checks passed
@steipete
steipete deleted the steipete/offline-delete-cron-cleanup branch August 21, 2026 07:31
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 22, 2026
… path (openclaw#127075)

* fix(agents): remove a deleted agent's cron jobs on the offline delete path

Follow-up to openclaw#127037, which fixed the exec-approvals half of the same gap and
named this one explicitly.

`agents delete` tries the Gateway first and falls back to a local path. The
Gateway handler nests two transactional cleanups around the roster commit --
cron wrapping approvals wrapping the config write. After openclaw#127037 the offline
path did the inner one; it still skipped cron. So deleting an agent without a
Gateway left its scheduled jobs enabled:

    $ openclaw agents delete cronprobe --force
    Deleted agent: cronprobe            <- no mention of cron
    $ sqlite3 <state>/state/openclaw.sqlite "select job_id, name, agent_id, enabled from cron_jobs"
    975cb750-... | cronprobe-job | cronprobe | 1
    $ openclaw cron list
    cronprobe-job   every 1h   Next: in 59m   idle

To be accurate about severity: this is not silent. Each firing records
`error: "cron job agent is unavailable: cronprobe"` and `cron list` flips to
`error`. The defect is that the job keeps its schedule forever, and that
recreating an agent with the same id points it at the new agent.

The fallback had collapsed two different reasons into one `null` return, which
is what made the fix look unsafe at first: credential failures happen *before*
transport, so a live scheduler may still own the cron store, while an
unreachable Gateway means nothing else is holding it. `maybeDeleteAgentThroughGateway`
now returns a discriminated union, and only the unreachable branch mutates the
store directly. The credentials branch commits the roster, warns, and sets
`cronCleanupSkipped: true` in JSON.

The local `CronService` construction already existed inside
`local-request-context.ts`; it moves to `src/cron/local-service.ts` and both
callers share it rather than growing a second cron mutation path. That
extraction also switches the default-owner resolver from
`tryResolveLegacyCompatibilityAgentId` to `tryResolveAmbientOwnerAgentId`, which
is a superset -- it honors an explicitly configured
`agents.defaults.systemAgent.agentId` and otherwise falls back to exactly the
previous function. Live testing showed agentless memory-dreaming jobs need it to
load under explicit agent ownership.

Production +89/-62.

* test(agents): split the delete suite so the new cron coverage stays under the cap

The 40-line cron regression test added in the previous commit pushed
`src/commands/agents.delete.test.ts` to 1018 code lines, over the 1000 cap, and
`check-lint-core-3` went red. Repo policy forbids a `max-lines` suppression.

Unlike the earlier `cron/view.test.ts` split there was no describe-level seam --
23 flat tests in a single describe -- so the split follows subject instead. The
seven workspace-lifecycle tests (trashing, sharing, overlap, symlink reachability,
workspace-state cleanup) move to `agents.delete.workspace.test.ts`.

`vi.mock` and `vi.hoisted` are per-file and cannot be imported, so the mock
preamble and the shared `beforeEach` are declared in both files; the helper block
above them is unchanged in each. Each file then imports only what it uses, which
is why the import lists differ.

Trimming to a hair under the cap by moving only the new test was possible and
rejected: it would have left the file at ~978 code lines, back at the cap within
a couple of changes. This leaves 749 and 603 physical lines.

No test content changed: 27 passed before, 27 after.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant