Skip to content

fix(sleep): restore agent auto-hibernation for non-Pi agents - #16430

Merged
brennanb2025 merged 3 commits into
mainfrom
brennanb2025/agent-sleep-live-anchor-fix
Aug 26, 2026
Merged

brennanb2025 merged 3 commits into
mainfrom
brennanb2025/agent-sleep-live-anchor-fix

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​559 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​557
Prod 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​456 $\color{#cf222e}{\Huge{\mathbf{−}}}$​206 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​250

Problem

Agent auto-sleep never fired for claude, codex, gemini, opencode, grok — or any resumable TUI agent except pi/omp/prime-agent. Reported as "not triggering as often as it should"; it was actually total for those agents.

Root cause. #10238 (b97e8c4e27) broadened the origin: 'live' resume anchor so every resumable agent keeps its --resume handle when a turn ends — fixing bare-shell restore after macOS logout (#9454). The planner rejects any pane that already carries a sleeping record, and its exemption was left Pi-only from #8991. Because the planner's eligibility conditions (done + resumable + provider session + resume argv) are exactly the conditions that write the anchor, that rejection covered every otherwise-eligible non-Pi pane.

Runtime-confirmed: driving the real store through a Claude working → done writes the anchor, and the planner then returns [] for a 31-minute-idle pane in a background worktree. Same for codex/gemini/opencode/grok. The identical pane without the record plans correctly.

Changes

  • Split the conflated predicate. isLiveResumeAnchorForCompletedAgent answers "is this record just this pane's own live anchor?" — no vendor gate. The Pi-gated wrapper keeps today's exact semantics at the manual-sleep (agent-status.ts:743) and quit-capture (:3205) call sites. isAutomaticHibernationAllowed carries the automaticResumeBlockedBy fence separately.
  • Fence automatic hibernation. A fenced orchestration worker must not be auto-relaunched, and sleepingRecordFromEntry does not copy the flag — so hibernating one would erase the fence. Checked in the planner, and again inside shutdownCompletedAgentPaneForHibernation against freshest state, re-evaluated after the synchronous capture callback (which can itself set it).
  • Anchor the idle clock on stateStartedAt. Same-state repaints (OSC 9999, reconnect snapshot replays) advance updatedAt, restarting the 30-minute countdown and invalidating the two-tick confirmation. stateStartedAt is the field that exists to survive within-state pings.
  • Floor it on PTY-binding age and boundary resolution. dropHibernatedAgentStatusPane never notifies main and main's lastStatusByPaneKey is persisted, so a woken or restarted pane replays an ancient anchor and would be instantly overdue. A wake spawns a fresh PTY and the map starts empty at launch, so binding age restores the grace updatedAt gave by accident. The boundary stamp is written synchronously where sessionBoundary clears — sampling it on the 60s tick would miss a boundary written and cleared between samples.
  • Signature drops updatedAt, gaining agent kind and full resume identity (provider key/id/transcript path) — the change detection updatedAt was providing incidentally.

Planner split into planner / pane-eligibility / snapshot to stay under the file-length limit.

Expected behavior change

This is the first time auto-sleep actually works since 2026-07-23, so the first run after updating will sleep a backlog of overdue panes. The binding floor delays that by one idle window after launch, and teardowns now drain one at a time (see below), so the backlog clears over minutes rather than all at once. Sleeping is the intended end state and is reversible via --resume. This is deliberate and signed off.

Sequential teardown drain (second commit)

runAgentHibernationTick launched every confirmed shutdown unawaited. Each shutdown re-runs a full runtime-liveness sweep (one terminal.list per runtime-owned worktree, 10s timeout) and then a terminal.stopExact (15s timeout) — so a backlog of ~100 overdue panes meant ~100 concurrent sweeps plus ~100 concurrent stops plus interleaved persistence writes. On an SSH runtime that is hundreds of near-simultaneous RPCs at the relay.

The fanout predates this branch; auto-hibernation simply could not fire for non-Pi agents, so it never ran at scale. Restoring eligibility is what exposes it.

Awaiting each teardown also makes tickInFlight real — it was cleared in the finally as soon as the promises were launched, so it never covered the drains it was meant to guard. Each candidate still re-validates against a fresh plan at its own turn, so a slow drain cannot act on stale confirmation, and per-candidate failures are already caught so one stuck teardown cannot abort the rest.

Head-of-line blocking is the tradeoff: a slow pane delays the rest. Bounded by RPC timeouts (~25s worst case per pane) on a background reclaimer that ticks every 60s. A small worker pool is the natural upgrade if first-run drain latency ever matters; it is not needed for correctness.

Testing

  • agent-hibernation-planner.test.ts — parametrized over every non-Pi RESUMABLE_TUI_AGENTS entry; fence rejection with an unfenced control; repaint/idle-anchor; signature stability and identity invalidation with updatedAt held constant; both floors.
  • agent-hibernation-live-anchor-e2e.test.ts — drives the real store working → done, asserts the live anchor is written, then feeds real store state to the planner. This pins the seam fix(agent-status): resume finished agents after macOS logout instead of a bare shell (#9454) #10238 broke.
  • agent-hibernation-pane-age.test.ts — binding carry/reset, layout-gap retention, age expiry, tab-removal pruning.
  • 17 of these fail on the pre-fix code and pass after (verified by reverting the behavior in place).
  • Full sweep across hibernation, agent-status, sleep/wake, resume, pty-connection and settings: 2068 passed. Typecheck and lint clean.

…tting the idle clock

Auto-hibernation could never fire for claude, codex, gemini, opencode, grok, or
any other resumable TUI agent — only pi/omp/prime-agent.

#10238 broadened the `origin: 'live'` resume anchor so every resumable agent
keeps its `--resume` handle when a turn ends. The planner rejects any pane that
already has a sleeping record, and its exemption was still Pi-only. Since the
planner's eligibility conditions are the same conditions that write the anchor,
that rejection covered every otherwise-eligible non-Pi pane.

- Split the conflated predicate. `isLiveResumeAnchorForCompletedAgent` answers
  "is this record just this pane's own live anchor?" with no vendor gate; the
  Pi-gated wrapper keeps today's exact semantics for the manual-sleep and quit
  capture call sites; `isAutomaticHibernationAllowed` carries the
  `automaticResumeBlockedBy` fence on its own.
- Fence automatic hibernation. A fenced worker must not be auto-relaunched, and
  the capture does not copy the flag — so hibernating one would erase it. Checked
  in the planner and again inside the shutdown action against freshest state,
  re-evaluated after the synchronous capture callback that could itself fence it.
- Anchor the idle clock on `stateStartedAt`, not `updatedAt`. Same-state
  repaints (OSC 9999, reconnect replays) advance `updatedAt`, restarting the
  30-minute countdown and invalidating the two-tick confirmation.
- Floor that anchor on PTY-binding age and a boundary-resolution stamp, so a
  wake or app restart still gets a full idle window instead of sleeping the
  whole backlog on the ancient timing main replays. The boundary stamp is
  written synchronously where the flag clears; sampling it per tick would miss
  a boundary written and cleared between two samples.
- Signature drops `updatedAt` and gains agent kind plus full resume identity,
  which is the change detection `updatedAt` was providing by accident.

Splits the planner into planner / pane-eligibility / snapshot to stay under the
file length limit.
@coderabbitai

coderabbitai Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: fc8b1d5e-c94f-4625-8fe8-fa89290f9662

📥 Commits

Reviewing files that changed from the base of the PR and between 392db93 and 3e31418.

📒 Files selected for processing (4)
  • src/renderer/src/lib/agent-hibernation-coordinator.test.ts
  • src/renderer/src/lib/agent-hibernation-coordinator.ts
  • src/renderer/src/lib/agent-hibernation-pane-age.test.ts
  • src/renderer/src/lib/agent-hibernation-pane-age.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.


📝 Walkthrough

Walkthrough

The change modularizes agent hibernation pane eligibility and planner snapshot types. It tracks PTY binding age and completion-boundary timestamps to enforce lifecycle timing. It adds live-resume anchor guards and automatic-resume fences during shutdown. Planner signatures now use stable agent state and resume identity fields instead of repaint timestamps. The coordinator now revalidates and shuts down candidates sequentially. Tests cover eligibility, timing floors, live anchors, fences, PTY rebinding, transient layout gaps, boundary resolution, runtime scoping, and teardown ordering.

Merge Risk: ⚪ Minimal · up to 3e314

The change is merge-ready after normal checks and review; no actionable merge-blocking risk remains.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description gives a detailed problem statement, root cause, implementation summary, expected behavior, and test results. However, it omits required template content, including a linked issue, visu… Add the missing required sections. Include a valid issue reference under Linked Issue, attach before-and-after visual proof or write N/A with a reason, complete the Testing checklist with platforms tested, complete AI Disclosure as applicab…
Docstring Coverage ⚠️ Warning Docstring coverage is 15.63% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 32 functions across 12 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the primary change: restoring automatic hibernation for non-Pi agents.
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.
Full details: Description check

Explanation

The description gives a detailed problem statement, root cause, implementation summary, expected behavior, and test results. However, it omits required template content, including a linked issue, visual proof or an explicit N/A explanation, the testing checklist and platform coverage, AI disclosure, review sections, notes, and the final checklist.

Resolution

Add the missing required sections. Include a valid issue reference under Linked Issue, attach before-and-after visual proof or write N/A with a reason, complete the Testing checklist with platforms tested, complete AI Disclosure as applicable, address Review, Agent skill upstream boundary, Notes, and Checklist items.

✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

`runAgentHibernationTick` launched every confirmed shutdown unawaited, so a backlog
fanned all of them out at once. Each shutdown re-runs a full runtime-liveness sweep
(one `terminal.list` per runtime-owned worktree, 10s timeout) and then a
`terminal.stopExact` (15s timeout) — so ~100 overdue panes meant ~100 concurrent
sweeps plus ~100 concurrent stops plus interleaved persistence writes. On an SSH
runtime that is hundreds of near-simultaneous RPCs at the relay.

The fanout predates this branch, but auto-hibernation could not fire for non-Pi
agents, so it never ran at scale. Restoring eligibility is what exposes it.

Awaiting each teardown also makes `tickInFlight` real: it was cleared in the
`finally` as soon as the promises were launched, so it never covered the drains it
was meant to guard. Each candidate still re-validates against a fresh plan at its
own turn, so a slow drain cannot act on stale confirmation, and per-candidate
failures are already caught so one stuck teardown cannot abort the rest.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status (final branch 3e314183f3cb0a4be61eddee1cef98c736556bc7)

Verdict: land after CI completes; no further code changes recommended.

  • Same-model fresh review was CLEAN. No additional functional, race, SSH/remote, folder-workspace, wire-compatibility, cross-platform, or performance issue was found.
  • Two meaningful in-scope P2 issues were fixed and pushed:
    • final pane teardown revalidation now lists only the candidate pane's owning runtime worktree (2W + C, instead of 2W + C×W);
    • boundary-resolution stamps are retired with expired PTY bindings, preventing closed split-pane map retention.
  • Verification passed locally: 76 focused lifecycle tests, project typecheck, oxlint, formatting, and git diff --check; the earlier focused review run also covered 150 tests and pre-commit hooks.
  • Opening and closing readiness reviews found no P0/P1 or release blocker, and the final readiness pass was requested against this exact head.
  • SSH validation used a throwaway Linux Docker SSH target and real demo-project; the documented bundle fallback was needed because GitHub auth failed inside the container. The Orca runtime became unavailable before app registration and the changed behavior could be driven end-to-end, so SSH/Electron visual proof remains an explicit gap—not a claimed pass.
  • An Orca-orchestrated Grok Electron/screenshot worker was started on the exact current worktree, but the Orca runtime closed before it returned worker_done; no screenshots were attached. No source changes resulted.
  • Current GitHub checks are still running; one Node 24 shard is currently marked failed, but its logs are unavailable while the run is in progress. Please inspect/re-run that shard before merge.

The user-owned untracked PLAN-agent-sleep-fix.md was preserved and is not part of the PR.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Attachments

Electron validation screenshots for PR #16430

01-before-empty-workspace.png 02-before-agent-sleep-off.png
01-before-empty-workspace.png 02-before-agent-sleep-off.png

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Update: CI failure is confirmed unrelated to this PR: Node 24 shard 2/16 fails only (p95 231.9ms vs 220ms budget); 15 other Node 24 shards passed and all other required checks are green. The required gate is red solely because that test aggregate failed. Please rerun/investigate that flaky performance-budget shard before merge.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Correction: CI failure is confirmed unrelated to this PR. Node 24 shard 2/16 fails only at src/renderer/src/lib/palette-match/palette-match-performance.test.ts:128 (p95 231.9ms vs 220ms budget). The other 15 Node 24 shards passed and all other required checks are green. The required verify gate is red solely because that test aggregate failed. Please rerun/investigate that performance-budget shard before merge.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Validation clarification: the attached Electron screenshots do not prove that real Claude/Codex agents sleep.

The orchestrated worker launched the exact PR worktree and validated the Agent sleep setting UI, but its isolated profile contained only a live shell: sleepingAgentSessionsByPaneKey count 0 and agentStatusByPaneKey count 0. No completed background Claude/Codex (or other non-Pi) session existed, so no real auto-hibernation, PTY teardown, sequential drain, or resume path was observed on screen.

The worker report records this explicitly. The lifecycle behavior is covered by focused tests; live non-Pi agent sleep remains an Electron validation gap.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Real-agent Electron validation completed on PR #16430 (isolated profile, exact PR worktree, Playwright CDP via $electron; no computer-use).

Passed

  • Real Orca-launched Claude Code and Codex sessions authenticated and completed a harmless exact PONG prompt.
  • With Agent sleep set to 1 minute, both background sessions auto-slept after the required coordinator ticks, despite origin: live anchors. Their provider/session identity and launch config were retained; target PTYs stopped.
  • Activating both sleeping rows resumed the original provider sessions; Claude rebound to a new PTY and Codex resumed with its saved session id.
  • Active-worktree/foreground exclusions, working-agent exclusion, split-pane sibling preservation, repeated Claude sleep/resume, and mismatched-pane fail-closed rollback passed.
  • CI is fully green after rerunning the flaky Node 24 shard; final readiness review found no proven P0/P1/P2 product defects.

Evidence
Full QA report

both slept
Claude resumed
Codex resumed
Codex working exclusion
Claude second sleep

Explicit gaps

  • A separate unsent post-done TUI draft was not injected as an idle-reset test.
  • A live terminal.stopExact RPC failure was not induced without mocking runtime behavior.
  • Codex was not put through a second sleep/resume cycle because it was intentionally left working for the exclusion test.

No product source changes were made during this review.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Correction to the evidence link above: artifacts/pr-16430-real-agent-qa/REPORT.md is the retained local QA artifact from the isolated run (the screenshots are attached directly in the comment). The report records the full transcript/store evidence and the explicit unexercised gaps; no artifact files were added to the PR diff.

@brennanb2025
brennanb2025 merged commit 630b717 into main Aug 26, 2026
93 of 95 checks passed
dallascrilley pushed a commit to dallascrilley/orca that referenced this pull request Aug 27, 2026
…i#16430)

* fix(sleep): let non-Pi agents hibernate again, and stop repaints resetting the idle clock

Auto-hibernation could never fire for claude, codex, gemini, opencode, grok, or
any other resumable TUI agent — only pi/omp/prime-agent.

stablyai#10238 broadened the `origin: 'live'` resume anchor so every resumable agent
keeps its `--resume` handle when a turn ends. The planner rejects any pane that
already has a sleeping record, and its exemption was still Pi-only. Since the
planner's eligibility conditions are the same conditions that write the anchor,
that rejection covered every otherwise-eligible non-Pi pane.

- Split the conflated predicate. `isLiveResumeAnchorForCompletedAgent` answers
  "is this record just this pane's own live anchor?" with no vendor gate; the
  Pi-gated wrapper keeps today's exact semantics for the manual-sleep and quit
  capture call sites; `isAutomaticHibernationAllowed` carries the
  `automaticResumeBlockedBy` fence on its own.
- Fence automatic hibernation. A fenced worker must not be auto-relaunched, and
  the capture does not copy the flag — so hibernating one would erase it. Checked
  in the planner and again inside the shutdown action against freshest state,
  re-evaluated after the synchronous capture callback that could itself fence it.
- Anchor the idle clock on `stateStartedAt`, not `updatedAt`. Same-state
  repaints (OSC 9999, reconnect replays) advance `updatedAt`, restarting the
  30-minute countdown and invalidating the two-tick confirmation.
- Floor that anchor on PTY-binding age and a boundary-resolution stamp, so a
  wake or app restart still gets a full idle window instead of sleeping the
  whole backlog on the ancient timing main replays. The boundary stamp is
  written synchronously where the flag clears; sampling it per tick would miss
  a boundary written and cleared between two samples.
- Signature drops `updatedAt` and gains agent kind plus full resume identity,
  which is the change detection `updatedAt` was providing by accident.

Splits the planner into planner / pane-eligibility / snapshot to stay under the
file length limit.

* fix(sleep): drain pane teardowns sequentially

`runAgentHibernationTick` launched every confirmed shutdown unawaited, so a backlog
fanned all of them out at once. Each shutdown re-runs a full runtime-liveness sweep
(one `terminal.list` per runtime-owned worktree, 10s timeout) and then a
`terminal.stopExact` (15s timeout) — so ~100 overdue panes meant ~100 concurrent
sweeps plus ~100 concurrent stops plus interleaved persistence writes. On an SSH
runtime that is hundreds of near-simultaneous RPCs at the relay.

The fanout predates this branch, but auto-hibernation could not fire for non-Pi
agents, so it never ran at scale. Restoring eligibility is what exposes it.

Awaiting each teardown also makes `tickInFlight` real: it was cleared in the
`finally` as soon as the promises were launched, so it never covered the drains it
was meant to guard. Each candidate still re-validates against a fresh plan at its
own turn, so a slow drain cannot act on stale confirmation, and per-candidate
failures are already caught so one stuck teardown cannot abort the rest.

* perf(sleep): scope hibernation rechecks to pane owner
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 28, 2026
…i#16430)

* fix(sleep): let non-Pi agents hibernate again, and stop repaints resetting the idle clock

Auto-hibernation could never fire for claude, codex, gemini, opencode, grok, or
any other resumable TUI agent — only pi/omp/prime-agent.

stablyai#10238 broadened the `origin: 'live'` resume anchor so every resumable agent
keeps its `--resume` handle when a turn ends. The planner rejects any pane that
already has a sleeping record, and its exemption was still Pi-only. Since the
planner's eligibility conditions are the same conditions that write the anchor,
that rejection covered every otherwise-eligible non-Pi pane.

- Split the conflated predicate. `isLiveResumeAnchorForCompletedAgent` answers
  "is this record just this pane's own live anchor?" with no vendor gate; the
  Pi-gated wrapper keeps today's exact semantics for the manual-sleep and quit
  capture call sites; `isAutomaticHibernationAllowed` carries the
  `automaticResumeBlockedBy` fence on its own.
- Fence automatic hibernation. A fenced worker must not be auto-relaunched, and
  the capture does not copy the flag — so hibernating one would erase it. Checked
  in the planner and again inside the shutdown action against freshest state,
  re-evaluated after the synchronous capture callback that could itself fence it.
- Anchor the idle clock on `stateStartedAt`, not `updatedAt`. Same-state
  repaints (OSC 9999, reconnect replays) advance `updatedAt`, restarting the
  30-minute countdown and invalidating the two-tick confirmation.
- Floor that anchor on PTY-binding age and a boundary-resolution stamp, so a
  wake or app restart still gets a full idle window instead of sleeping the
  whole backlog on the ancient timing main replays. The boundary stamp is
  written synchronously where the flag clears; sampling it per tick would miss
  a boundary written and cleared between two samples.
- Signature drops `updatedAt` and gains agent kind plus full resume identity,
  which is the change detection `updatedAt` was providing by accident.

Splits the planner into planner / pane-eligibility / snapshot to stay under the
file length limit.

* fix(sleep): drain pane teardowns sequentially

`runAgentHibernationTick` launched every confirmed shutdown unawaited, so a backlog
fanned all of them out at once. Each shutdown re-runs a full runtime-liveness sweep
(one `terminal.list` per runtime-owned worktree, 10s timeout) and then a
`terminal.stopExact` (15s timeout) — so ~100 overdue panes meant ~100 concurrent
sweeps plus ~100 concurrent stops plus interleaved persistence writes. On an SSH
runtime that is hundreds of near-simultaneous RPCs at the relay.

The fanout predates this branch, but auto-hibernation could not fire for non-Pi
agents, so it never ran at scale. Restoring eligibility is what exposes it.

Awaiting each teardown also makes `tickInFlight` real: it was cleared in the
`finally` as soon as the promises were launched, so it never covered the drains it
was meant to guard. Each candidate still re-validates against a fresh plan at its
own turn, so a slow drain cannot act on stale confirmation, and per-candidate
failures are already caught so one stuck teardown cannot abort the rest.

* perf(sleep): scope hibernation rechecks to pane owner

(cherry picked from commit 630b717)
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…i#16430)

* fix(sleep): let non-Pi agents hibernate again, and stop repaints resetting the idle clock

Auto-hibernation could never fire for claude, codex, gemini, opencode, grok, or
any other resumable TUI agent — only pi/omp/prime-agent.

stablyai#10238 broadened the `origin: 'live'` resume anchor so every resumable agent
keeps its `--resume` handle when a turn ends. The planner rejects any pane that
already has a sleeping record, and its exemption was still Pi-only. Since the
planner's eligibility conditions are the same conditions that write the anchor,
that rejection covered every otherwise-eligible non-Pi pane.

- Split the conflated predicate. `isLiveResumeAnchorForCompletedAgent` answers
  "is this record just this pane's own live anchor?" with no vendor gate; the
  Pi-gated wrapper keeps today's exact semantics for the manual-sleep and quit
  capture call sites; `isAutomaticHibernationAllowed` carries the
  `automaticResumeBlockedBy` fence on its own.
- Fence automatic hibernation. A fenced worker must not be auto-relaunched, and
  the capture does not copy the flag — so hibernating one would erase it. Checked
  in the planner and again inside the shutdown action against freshest state,
  re-evaluated after the synchronous capture callback that could itself fence it.
- Anchor the idle clock on `stateStartedAt`, not `updatedAt`. Same-state
  repaints (OSC 9999, reconnect replays) advance `updatedAt`, restarting the
  30-minute countdown and invalidating the two-tick confirmation.
- Floor that anchor on PTY-binding age and a boundary-resolution stamp, so a
  wake or app restart still gets a full idle window instead of sleeping the
  whole backlog on the ancient timing main replays. The boundary stamp is
  written synchronously where the flag clears; sampling it per tick would miss
  a boundary written and cleared between two samples.
- Signature drops `updatedAt` and gains agent kind plus full resume identity,
  which is the change detection `updatedAt` was providing by accident.

Splits the planner into planner / pane-eligibility / snapshot to stay under the
file length limit.

* fix(sleep): drain pane teardowns sequentially

`runAgentHibernationTick` launched every confirmed shutdown unawaited, so a backlog
fanned all of them out at once. Each shutdown re-runs a full runtime-liveness sweep
(one `terminal.list` per runtime-owned worktree, 10s timeout) and then a
`terminal.stopExact` (15s timeout) — so ~100 overdue panes meant ~100 concurrent
sweeps plus ~100 concurrent stops plus interleaved persistence writes. On an SSH
runtime that is hundreds of near-simultaneous RPCs at the relay.

The fanout predates this branch, but auto-hibernation could not fire for non-Pi
agents, so it never ran at scale. Restoring eligibility is what exposes it.

Awaiting each teardown also makes `tickInFlight` real: it was cleared in the
`finally` as soon as the promises were launched, so it never covered the drains it
was meant to guard. Each candidate still re-validates against a fresh plan at its
own turn, so a slow drain cannot act on stale confirmation, and per-candidate
failures are already caught so one stuck teardown cannot abort the rest.

* perf(sleep): scope hibernation rechecks to pane owner
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant