Skip to content
Back to skills

Rule Daemon Agent Turns

ASecurity

Agent turns and off-turn work — held turn_complete, background commands and delegates, command-end wakes, sub-agent recovery. A repository rule for apps/daemon/src/v1/agents/**/spawn-cli*, apps/daemon/src/v1/agents/**/chat.service*, apps/daemon/src/v1/agents/**/message-send*, apps/daemon/src/v1/agents/**/fold-turn-complete*, apps/daemon/src/v1/agents/**/compaction-rows*, apps/daemon/src/v1/agents/**/open-delegates*, apps/daemon/src/v1/agents/**/open-shells*, apps/daemon/src/v1/agents/**/backg...

  • 8 stars
  • 0 votes
  • 0 copies
  • 1 view
  • Added November 17, 2026
ai-agentsgoshellnodeapi

Works with

  • cursor
  • terminal
  • cli
  • api
  • mcp

Security analysis

A100/100

Scanned December 5, 2026

npx -y skills add geniro-io/geniro-app --skill rule-daemon-agent-turns --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Rule Daemon Agent Turns?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Rule Daemon Agent Turns
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/geniro-io-rule-daemon-agent-turns/badge)](https://www.skillsdirectory.com/skills/geniro-io-rule-daemon-agent-turns)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: rule-daemon-agent-turns
description: "Agent turns and off-turn work — held turn_complete, background commands and delegates, command-end wakes, sub-agent recovery. A repository rule for apps/daemon/src/v1/agents/**/spawn-cli*, apps/daemon/src/v1/agents/**/chat.service*, apps/daemon/src/v1/agents/**/message-send*, apps/daemon/src/v1/agents/**/fold-turn-complete*, apps/daemon/src/v1/agents/**/compaction-rows*, apps/daemon/src/v1/agents/**/open-delegates*, apps/daemon/src/v1/agents/**/open-shells*, apps/daemon/src/v1/agents/**/background-work*, apps/daemon/src/v1/agents/**/follow-up-background-work*, apps/daemon/src/v1/agents/**/*delegate*, apps/daemon/src/v1/agents/**/command-end-wake*, apps/daemon/src/v1/agents/**/subagent-recovery*, apps/daemon/src/v1/agents/**/chat-shells*, apps/daemon/src/v1/agents/**/shell-output*, apps/daemon/src/v1/agents/adapters/*.ts, apps/daemon/src/v1/agents/**/agent-session*, apps/daemon/src/v1/agents/**/turn-folder*; read it before editing a file there."
---
<!-- GENERATED by scripts/sync-agent-rules.mjs from .claude/rules/daemon-agent-turns.md. DO NOT EDIT: edit the source, then run `pnpm sync:agent-rules`. -->

# Agents: turns and off-turn work

In `utils/spawn-cli.ts` unless noted.

- **A turn never starts in a deleted folder** (user decision: a removed worktree is never re-created). Every CLI turn, chat (`ChatService.sendMessageOnce`) and team (`beginAgentTurn`, and the next pass's `prepareNextPass`) alike, takes its folder from `TurnFolderService.folderFor` (and so does "Continue in terminal", `HandoffService`): an existing folder as it is, a gone one replaced by `movedFolderOf` (`utils/turn-folder.ts`) — only the work's own source (user decision): the card's folder for a task worktree (`ProjectRootsService`), the repository root above it, the run's project folder, never the home folder, `/`, `/Volumes` or a folder holding or inside Geniro's data folder; with none of them the turn is refused `FOLDER_GONE`, moving nothing. The run is moved once (`RunDao.rehome`, compare-and-set on the old folder; concurrent turns share one move), its `startSha` dropped so the changes chip hides (user decision), re-checking first that the folder is not back, with one `info` notice (caption `folder moved`) naming both folders, one prompt line (paths JSON-quoted) owed to EACH conversation of the run before its next turn there (`oweMoveNote`, called beside every `startTurn`, chat and team; in memory) and a `runs_changed` of the row. A card's Run press puts a moved run back into the worktree it cut (`TurnFolderService.returnTo`, from `TaskRunsService`), restoring the press's `startSha` / `startDirty`, told the same way. A team pass's folder is a `let` read live by its monitor sinks and call capability. claude, codex and cursor-agent resume a session from another folder (measured through `-p --resume` / `exec resume`; codex's rollouts and cursor's ACP store are keyed by id, not folder), so a move keeps the conversation. A folder that exists but cannot be used still refuses `INVALID_CWD` / `FOLDER_NOT_READABLE`, and neither a failure before work whose folder is gone nor a refused start is a pool hand-on (`fallsThroughPool`'s `folderGone`).

- A `turn_complete` is HELD while a delegate it launched is out (`openWork`), in a turn of ours and in a stretch the CLI runs by itself (`deferredOffTurnTerminal`) alike, and both holds are announced as `turn_held` (off-turn only while no turn of ours is open). A report from a unit it waits on, or a main-thread detached command ending, ends the hold's announcement at once (`wakeOnReport`): claude starts working on a report immediately. Release the held result on the last report, at `idle`, or at the silence deadline. When the main thread speaks again (`RESUMES_A_HELD_TURN`) or a follow-up is delivered it ends nothing, but its segment is folded into whatever ending comes (`continuedSegment`, `offTurnContinued`) and counts on the live cost until then, never dropped: claude's cost is a step of its session ledger, so a dropped segment loses its money for good. A held off-turn result a turn of ours releases is stamped `insideTurn`, and what a stretch continued past with nothing held becomes that turn's earlier work. A session close takes a hold announced between turns down (`settleAfterSessionClosed`): its own release arrives after the session stopped being the run's. Only on a `session` stdin lifetime.
- For a CLI that announces session state, `idle` (claude `session_state_changed`) ends a held turn and writes off missed units. Do not reintroduce a grace timer after the last report.
- A follow-up written into a turn holds the turn until the CLI echoes it (`unconsumedFollowUps`, gated on `followUp.consumptionReported`). The held segment's usage is folded (`fold-turn-complete.ts`).
- Backgrounded commands never hold a turn; only `unit === 'agent'` does, and `'other'` counts as a shell.
- These holds (and cursor's `holdForDelegates`, below) are what each adapter's `backgroundWork.agentNote` promises the agent: change a hold, re-check its note. Never put a hold's bounds in the note.
- Every user-facing claude turn runs on a kept (`session`) process, an `auto` one without the permission dialogue included (`canHostSession`), so every one is held. Never send one back to a stdin-closed process: there claude holds back its own first result, waits on background commands too, and stops its agents after 10 idle minutes. A process spawned without the dialogue is never re-moded into another mode; the base respawns it (`spawnedOnDialogue`).
- A foreground unit (`is_backgrounded: false`) is never announced as background work until a `backgrounded` patch arrives. A delegate one still enters `openWork`; a command one holds nothing, and is recorded where it runs (Run processes → Left commands).
- `shell_open` / `shell_info` rows record detach and end. `announceShellWork` runs BEFORE `announceDelegateWork` and announces once per unit (`settledShells`). A settle for a shell this process never opened writes nothing: an earlier process closed it as it ended, and claude, resumed after a crash, reports its task `stopped` again.
- A command call the CLI never answered when its process died under the turn (not a Stop) is answered `CUT_OFF_COMMAND_RESULT` ahead of the turn's ending (`cutOffCommands`).
- A delegate's own detached command (`ownedByDelegate`) gets no shell row, but it is filed under its delegate through its launching call's `parentToolUseId` (either arrival order). While one runs, the delegate's `completed` settle is held, not announced: claude reports a delegate completed at each turn end and restarts it when the command reports. The held settle is announced when the delegate's last command ends; if claude then restarts the delegate, it reopens at once (deliberate: waiting for the restart could leave it working for good). If the process ends first, the held settle is announced as `stopped`, figures kept. If the delegate is started again while its settle is held, the held settle is dropped. A never-ending command keeps its delegate working. These commands count in `shellsRunning`, so the process is not reaped under them.
- A message into a running turn that would cancel background sub-agents (`AgentTurnHandle.subagentsAFollowUpCancels`, cursor's sub-agent sessions: `AcpTurnDriver`) is never delivered unasked. Absent `backgroundWork` the driver refuses it, the caller's `RUN_BUSY`; `ask` (a Send-now press) answers `FOLLOW_UP_CANCELS_SUBAGENTS` naming how many, writing nothing and telling the CLI nothing; `cancel` is the user's confirmation, and the driver interrupts as for any follow-up. The queue's own send carries `waitForAnswer`, refused `RUN_AWAITS_ANSWER` while a card stands that a new turn would retire (`awaitsCardAnswer`), so a queued message never expires a question the user has not answered.
- A follow-up written into a CLI's stdin (claude) and not yet echoed as taken (`TurnState.unconsumedFollowUps`, with its `deliveryId`) dies with the process: claude queues it and, after an interrupt, runs it as a turn of its own only while the process lives (probed on 2.1.295), and a chat's Stop closes the session. So `spawn-cli` reports it `follow_up_dropped` when the process ends under the turn, and in `finishTurn` once the group has been signalled (`groupKilled`) — claude prints its cancel result inside the SIGTERM's window. A turn asked to stop (`cancelRequested`) refuses every further follow-up (`sendUserMessage` → false, the RUN_BUSY the composer queues on; otherwise a message sent right after Stop is steered into the stopping turn and lost). A follow-up sent while the turn's own prompt is still held (`promptHeld`, claude's MCP-readiness gate) is accepted on the stdin-line path and written right behind the prompt (`TurnState.heldFollowUps`), never ahead of it; one the turn ends before writing is reported `follow_up_dropped` ahead of the terminal. A driver that writes follow-ups itself (`sendFollowUp`) still refuses while held.
- `restatesRunAsWorking` excludes `shell_open`, `shell_info`, `notice`, `follow_up_dropped`, a `tool_result` marked `endsBackgroundWork` (a background command's end, codex) and every `subagent_info` but an announced start (`backgroundOpen: true`) — a close, or a facts-only row such as claude's delegate price, which can land after its continuation settled; anything else from a settled run flips it back to `running`.
- `late_work_ended` (no row) says every call the CLI started or left open after its turn ended has ended or gone to the background, and ends that off-turn stretch the way a terminal event does (`endsOffTurnStretch`): the chat hands back the badge (`ChatService.settleLateWork`; a held delegate lease keeps it until expiry, a send that has claimed the run keeps it), a team member its own (`onOffTurnEvent`). Both read it ahead of their row gate, and the chat runs it only after the run's between-turn handlers already in flight (`offTurnInFlight`), since it would otherwise settle before the late result ahead of it restates the run, and drops it when a main-thread tool call arrives after it (`offTurnLateCalls`, counted on arrival): that is new late work, which ends with its own. Inside a turn the chat ignores it. Only the adapter knows its turn ended, so only it emits it.
- Work a callee's process does by itself while its call is still open with the turn over (`CallBrokerService.callOpenBetweenTurns`: held, or about to be) is a stretch of its own in that call: a `running` row with `offTurn` and the `callId`, the member's `node_state` left `running`. It ends on the CLI's own terminal row, else (`late_work_ended`, the process closing, a wake starting the call's next turn) on a `turn_complete` with no usage the executor writes, measured into `wall_turns`, never on a status row, which would end the call.
- **A CLI that reports a backgrounded command FINISHED** (cursor) is checked at a settle and when its turn goes quiet (`sweepDetachedShells`, gated by `shells.unreportedDetachReason`): only ANSWERED execute calls, each decided by the CLI's own record of it where it keeps one (`readCommandRecords`, `commandLiveness`), else by its text in the table under the CLI; fed back through `announceShellWork`; poll only while something is out. The same record tells a session where such a command runs (`recordedPidsRunning`), and a Stop falls back to those groups, while a recorded member anchors them, when the text is nowhere in the table (`ChatShellsService.recordedGroups`).
- **A CLI that sends nothing while it waits on a command it detached** (`shells.silentWaitReason`, cursor): `onTurnQuiet`, `COMMAND_WAIT_QUIET_MS` after the CLI last spoke, asks the driver whether the quiet is explained (`TurnDriver.onQuiet`: null while a reported call is open or being written, a Stop or interrupt is out, or background sub-agents run; else the open text block as its row, so a thinking row stops claiming). With a detached command alive the turn is announced `turn_held` with `unit: 'command'`, so the composer sends straight in and the queue drains; a message cancels only the wait, and the command runs on. It ends when the agent speaks (`RESUMES_A_HELD_TURN`), a message is delivered, or the last such command ends. While it stands over a command this turn started (`TurnState.ownCommands`), the silence deadline takes up to `COMMAND_WAIT_SILENCE_WINDOWS` windows (the CLI's own wait tool blocks for at most 119 minutes), and its end restarts a full one. Never read the agent's prose for this; a quiet turn with no command alive is left to the deadline. Known limit, since nothing on the wire tells the two apart: with a long-lived command out (a dev server), a model thinking past the window reads as waiting, and a queued message then cancels that thinking.
- **A CLI that tells its agent nothing about a command that ends after the turn** (`shells.lateEndWakeReason`, cursor: it hands a finished command to the model only at the end of a `session/prompt`, and sends nothing between prompts — measured on 2026.11.05-86047df): the sweep's settle carries how the command ended (`shell_info.ending`: the command, and from its terminal file's footer the exit code, the end time and the file's path, `CommandRecord` — only a record that ended after the call was made, `endedRecordOf`, so an earlier run of the same line is never taken for it), and a between-turn end of one in a chat or a member's own conversation goes to `CommandEndWakeService`, which gathers the ends within `COMMAND_END_WAKE_BATCH_MS` into ONE host wake (`note: null`) naming each command, its exit code and its output, and saying the same completion may reach the agent once more after it answers (the CLI still drains it at that prompt's end). Never queued behind a running turn and never sent once any turn of that conversation has started (a pending one is dropped, a published one `withdrawn()`): the CLI hands the completion over at that prompt's end itself. No wake for an end inside a turn or one that ended before that conversation's last turn did (`turnEnded`; the settle sweep can find it after the turn), a command the user stopped (`noteShellClosed`), a callee conversation (its call has settled), after the user's Stop, an archive or a delete (`forgetRun`), nor past `MAX_COMMAND_END_WAKES` in a row with no message from the user (`userSpoke`).
- Stopping a foreground command (`ChatShellsService.killForeground`): attribute first (only processes under this run's live CLI, never the CLI itself, and of those the ones its session recorded running that call's command when it did — `AgentSessionRegistry.recordedGroupsOf` — since two commands written alike cannot be told apart by text), then match. Signal the whole tree; write nothing. A detached command's Stop (`ChatShellsService.kill`) narrows its whole-table match to the recorded processes the same way while the session lives.
- A shell whose call codex has not answered is stopped from the process panel as a foreground command (`ChatShellsService.kill` → `stopForeground`): its written `/bin/zsh -lc '…'` is exec'd away. One found nowhere among the agent's processes is closed as already stopped once codex no longer reports it running (`recordedGroupsOf` answers null); while codex still does, the match missed a program that exec'd under another name, so Stop says it cannot tell which process it is and keeps the row.
- **A background DELEGATE's ending** for cursor is written by the daemon. The ACP session watches the delegate's own transcript, located by its brief, born after launch, unclaimed (`cursor-delegate-transcript.utils.ts`).
  - A turn ending closes nothing it can watch. Do not reintroduce a turn-settle closer. Unwatchable delegates become `untracked` ahead of the completed turn's `turn_complete`.
  - A turn with watched background delegates it launched holds, then wakes the agent with their reports (`holdForDelegates`, `MAX_DELEGATE_WAKES`). `DELEGATE_HOLD_IDLE_MS` must stay under spawn-cli's 30-min silence deadline. The hold is announced like spawn-cli's (`turn_held` with the count, then `open: 0` from `endHold`), so the composer sends straight in. While held, Stop is `withdrawHeldPrompt` and a message ends the hold.
  - A resumed delegate appends to its old transcript; the claim moves to the newest brief. The delegate it continues is closed `stopped` with recovery off (`recovery: null`).
  - A session close marks every delegate still out `untracked` with `trackingLost: 'process-ended'` (`processEndedCloseEvent`); the boot sweep, the team executor's `closeStrandedWork` and spawn-cli's exit flush do the same. Its work is over and only its outcome is unknown, so it is drawn as settled. A close that is the user's Stop says so (`SessionCloseCause` `'user-stop'`): the chat Stop passes it to `AgentSessionRegistry.close`, a team Stop or archive marks the run's kept processes first (`noteUserStop`). The session itself holds the cause (`AgentSession.noteCloseCause`, withdrawn by its next turn), so however the process then ends — a later close or its own kill after a refused interrupt — every writer above closes the delegates still out `stopped`. The open set is folded from durable `subagent_info` rows, ranked like the renderer's `subagentBlockStatus` (twin).
  - codex sub-agents (`subAgentActivity`) close on whichever ending arrives first; no turn-settle closer.
- An outcome-less ending reads `untracked` only for a delegate whose recovery ref still stands; without one (every row from before refs) it keeps its old reading: a close or a reply reads `completed` (`failed` on an error reply), and a turn that ended without a reply reads `cancelled`. A delegate the user's Stop cut off reads `cancelled` either way. The delegate's OWN turn ending decides (`turn_cancelled` is a Stop); the run's status is read only when no ending of its turn exists, since a chat settles after every turn and its status describes only the latest one.
- `SubagentRecoveryService` reconciles durable untracked children on a run's WebSocket join (open/reconnect), on new loss evidence, and — 5 s after boot, off the listen path — for runs that recorded a ref in the last 24 h. Each reconciliation has at most three attempts; duplicate joins share that budget and recovered terminal rows never restart it. A delegate settled by its rows, or still unknown when a round ran out, is retired at its row version: no later trigger reads it again until a newer `subagent_info` row of its own appears — or, for one given up while it may still run (not process-ended), until a 10-minute cooldown passes — and the run's tool rows are read only for delegates the declarations leave unresolved. Retired delegates are remembered for the newest 500 runs. `AgentAdapter.recoverSubagent` reads existing state through the CLI's read API or an adapter-local record reader; missing evidence and legacy rows without a reference stay unknown. Recovery preserves node/call ownership, never starts work, defers to live subordinate-command holds and rechecks racing live outcomes. Resumed child identities belong only to their newest launch.
- A bracketed delegate's off-turn steps are not the run working (`BackgroundWorkCounts.isDelegateOut`).
- A team run's stranded delegates and shells are closed by the EXECUTOR (`closeStrandedWork`), ahead of its terminal row. Every close carries its open row's member AND call id (`ownerFields`).
- `workflow_info` rows come only from roster-bearing `task_progress` lines; the anchor is emitted at `task_started` (the only line carrying the name).
- Every finished compaction is one row; with no summary the daemon writes `COMPACTED_WITHOUT_SUMMARY` (`compaction-rows.ts`). Delegate compactions are skipped.
- A turn never settles on a continuation's result (`turn_complete.continuation`), unless the continuation absorbed this turn's prompt (echo matched, `promptTaken`).
- Between-turn events (`handleBetweenTurnEvent`) are persisted exactly like in-turn ones, and a settled run goes back to `running`.
  - Exceptions: a CANCELLED run stays cancelled (rows still written); a run whose `running` this path did not write is left alone (`offTurnRuns`).
  - Main-thread `text_delta` / `thinking_progress` / `reasoning_delta` also flip it back (`restatusAfterOffTurnSignal`); `context_progress` never does.
  - An unbracketed delegate's rows take a lease (`DELEGATE_ROW_LEASE_MS`), not a latch.
  - A session close restores the badge (`settleAfterSessionClosed`), except during shutdown. A process dying on its own is a close too.
- The silence deadline does not run while a verdict is outstanding; `respondApproval` rearms on delivery.
- Only `cancelRequested` settles `cancelled`. Any other signal settles `failed`, naming the signal.

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.