# Activity and control

Activity counts conversation branches. Sending another message on the same branch does not add a History item.

| Object | Meaning | Appears |
| --- | --- | --- |
| Conversation branch | One path through a conversation; a real fork creates another | One counted Activity row |
| Execution | One task run, such as producing a reply | In branch details; its id is the exact control target |
| Managed process | A command started by a tool | Under its execution, with its own output and stop control |

## How branches are counted

| Example | Count | Details |
| --- | --- | --- |
| Send a message, then say "continue" | 1 | Both executions in one branch |
| Create an alternative reply from an earlier point | 2 | One row each |
| A later execution on the same branch fails | 1 | Kept in details |
| Two branches share earlier messages | 2 | Shared executions may appear in both details and add no rows |

Branch details use a short heading and an execution count; the request appears only in its execution row. Membership comes from the conversation graph and message ids, and compaction keeps earlier associations. Missing records never produce a guessed branch.

## Which status appears

| Situation | Section | Meaning |
| --- | --- | --- |
| Approval, question, pause or unresolved tool result | Needs attention | A new message does not dismiss it |
| Execution, child task or owned process running | In progress | An Agent finishing its reply does not stop its background process |
| Ended, nothing active or actionable | History | Failures and outputs stay in details |
| Owner ended, only the model response record is missing, no active wait or non-cancel control | History | "Ended · response record incomplete". An old Cancel does not make it actionable; Cancel is offered only while a child is active. Does not claim success. |

Status comes from the branch's newest execution, plus real waits, active descendants and owned processes. Declined waits read Declined and open ones Waiting for your response; declining does not run the pending operation.

Activity shows no error while loading or reconnecting. A failed read keeps what was read and retries silently; runs never read leave their place empty ([reading](https://fzkuji.github.io/OpenProgram/docs/reference/design/ui/chat/activity-panel.html#reading-overview)).

## Two branches running at once

Each branch of a conversation has its own run slot. The selected branch keeps the conversation's slot; a message that names another recorded branch (`branch_id`) takes that branch's slot, so it runs while the selected branch runs.

| Part | Turn on the selected branch | Turn on another branch |
| --- | --- | --- |
| Slot | The conversation's, keyed by session | Its branch's, keyed by session and branch; refused while that branch has any unfinished execution, a scheduled run included |
| Writes | Move the head and the selected branch | Go under the branch's tip and move only that branch's record; the head, selection and live mirror stay |
| Model input | The selected branch | Its own branch's history and settings (Agent, model, permission) |
| Conversation state | Status, unread dot, model, token count, title, channel reply | None of these; they stay the selected branch's |
| Branch state | Each turn compacts its own chain when over budget (the summary lands on that chain and the head stays) and records its last request's occupancy on its own branch record (`last_prompt_tokens`); the conversation's figure is the selected branch's. A background check-in does neither: it reads a bounded tail. | Each turn compacts its own chain when over budget (the summary lands on that chain and the head stays) and records its last request's occupancy on its own branch record (`last_prompt_tokens`); the conversation's figure is the selected branch's. A background check-in does neither: it reads a bounded tail. |
| Run state | `running_task`, `run_active`, `run_task`: unchanged meaning | `branch_running_task` and its clear, with `branch_id`; every frame of the turn names its branch |
| Stop | An exact command on one execution; it frees only that turn's slot | An exact command on one execution; it frees only that turn's slot |
| Rewind point | One per prompt, on any branch. A file's state before a turn first edits it is recorded in that turn's own point, not in the newest one. | One per prompt, on any branch. A file's state before a turn first edits it is recorded in that turn's own point, not in the newest one. |

The branch a turn runs on is fixed at admission (`branch_id`); whether that branch is the selected one is read when asked, against `active_branch_id`.

Whether a turn may touch the conversation's state at all is frozen as `owns_conversation_effects`, false for a turn on another branch and for a background check-in, so a turn keeps its standing across a pause, a resume and a Worker restart. A request admitted before the flag existed derives it from `side_branch` and `background`.

### Switching branches

Switching is a view change. It takes no slot and is never refused because a turn, a compaction or another operation runs on the branch left or the branch entered.

| Part | What a switch does |
| --- | --- |
| Selection | Moves the head to the entered branch's tip (compare-and-set), then re-keys the slots: the operation of the branch left goes to that branch's own slot and is reported with `branch_running_task`; the entered branch's operation becomes the selected one and is reported with `running_task` (`switch_branch`) |
| Running turn | Keeps its branch. Its user message, history and reply stay on that branch, and its end moves only that branch's record: the writes of the head and the selected branch's fields carry `expected_branch_id` and are skipped once another branch is selected |
| Page and terminal UI | Draw and keep run state for the selected branch only. Every frame of a turn names its branch; a frame of another branch is not drawn. The checkout reply names the branch entered, and a load hands over that branch's running turn, so Stop reaches it after a reload |
| Branch record | Switching back finds the branch's record by its tip, or, for a record whose tip fell behind its line, the nearest record on that line (`record_on_line`). Old data needs no migration |
| Still refused | Deleting a tail that holds a running branch's tip, and a rewind on a running branch. A rewind that changes files stays conversation-wide |

What a switch, starting again and a rewind each create, and which work keeps its branch after a switch: [Branch collaboration](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/dag/branch-collaboration.html#three-operations).

### Settings a turn runs with

Admission also freezes each setting's value, where it came from and the Agent it belongs to, and the turn writes them on its user message as `turn_settings`. That record is the conversation's own answer to which model, effort and permission a turn used.

| Source | Meaning |
| --- | --- |
| `request` | The caller sent the value with the turn |
| `parent` | Taken from the live turn that started this one in the same conversation |
| `branch` | Taken from the turn's branch record |
| `agent` | Left empty; the Agent or its fallback decides when the turn runs |

Where each setting comes from when a branch leaves it unset, and which tool state belongs to a branch: [Branch settings](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/execution/branch-settings.html).

### One foreground operation per branch

A branch's run slot holds one foreground operation at a time. Every operation has an `op_id`, a kind and a version a Stop raises; a load, `running_task` and `branch_running_task` report the kind, so the run bar can say "Compacting context" with a Stop, also after a reload.

| Kind | What holds the slot | Stop |
| --- | --- | --- |
| `reply`, `retry`, `edit`, `function` | A turn, from reservation to its end; after its `result` a request [waits for the slot](https://fzkuji.github.io/OpenProgram/docs/reference/design/ui/turn-lifecycle/turn-occupancy.html#finishing) | On its execution, exact by version |
| `compact` | `/compact`; the summary request ends at a Stop and nothing is written | `operation.cancel` with its `op_id` |
| `rewind` | A rewind, its undo and redo | `operation.cancel` |
| `branch` | A branch delete, for a moment; not shown while it runs. A switch takes no slot | None |

Branches never block each other: an operation needs only its own branch to be free, and a second one there is refused (`run_active`) with the kind of what runs, which the client may queue. A delete of a tail holding the tip of a branch whose turn runs is refused naming that branch.

A request that finds its own key on the slot is a repeat, not a second operation:

A request repeated while the first holds the slot

| Request | Key | The repeat |
| --- | --- | --- |
| Rewind apply | `idempotency_key` | Waits for the first to end (up to a minute, the store's lock budget), then takes the slot; the store returns the first's recorded outcome ([storage consistency](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/session/storage-consistency.html)), so files and head change once and both callers get one result, `head_changed` included |
| Revert, reapply | `idempotency_key` with the turn |  |
| Head after a rewind | `idempotency_key` | The request that applies the rewind mirrors the new head in the server and re-measures the context before it frees the slot. A repeat mirrors it again only while the stored head is still the one the rewind left, so a conversation that has moved on is never pulled back |
| Chat send, function run | `client_request_id` | Answered `request_admitted` with the running turn's ids, without `retry_query`: one send admits one execution, and a `run_active` would have the client queue it as a new turn |
| Another key, or none | Any | Refused, `run_active`. The slot is checked before the store, so it has to know a repeat too |

What a branch delete removes

| Case | Result |
| --- | --- |
| Removed | From the tip up to the fork point (the first message whose predecessor has another conversation child), the tool calls under it, and the branch's record |
| Kept | The fork point and everything above it: other branches share them |
| Which branch | Any message on it names it; none names the selected branch, which is switched away from first |
| Refused | The conversation's only line (delete the conversation), or a message below which several branches continue |
| Why | Git's `branch -d` also removes only what no other branch reaches. Deleting only the named message left the branch listed and its record taking messages |

A turn that compacts its own context mid-run stays a `reply`; the page shows the step while `compaction_started` lasts.

Only a rewind that changes files is conversation-wide

| Case | Rule |
| --- | --- |
| Another branch runs, or a turn waits on an approval or a question | Refused with `code: branch_running` and `blocking`: that branch's name, its execution id and version or its `op_id` |
| Rewind dialog | Then offers "Stop it, then rewind": stops that run and applies the same rewind once the run has ended |
| While it runs | A durable record holds the conversation's files. No branch is admitted; a new execution (a scheduled run, a queued Job, a turn admitted by another process) waits for it at admission |

Each running operation is also recorded on disk (`state/store/session/operations.py`). After a restart the first reader marks the operations of a gone process cancelled with `reason_code: restart`; none is resumed.

Other operations hold only the branches they touch (`reserve_branches_operation`, taken in sorted order); a refusal names the busy branch

| Operation | Branches held |
| --- | --- |
| Deleting messages, turn-file history actions | Every branch whose line holds the node; a common ancestor touches every branch below it |
| Agent switch | Its own branch |
| Scheduled run | Reads its branch's durable record before it starts and skips the run while that branch is busy |
| Commands, skills, Agent invocations | The branch the message names. Only `/clear`, `/rename` and starting a Goal change the whole conversation and stay with the selected branch |

### Rewinding beside another branch

A rewind takes back only what its own branch's turns wrote after the chosen prompt. A scheduled run on its own branch counts as another branch.

| The other branch edited the same file | What the rewind does |
| --- | --- |
| Not at all | Restores the file to its state at the prompt |
| Before this branch's first edit | Restores the file to what the other branch left; its edit stays |
| After, or between, this branch's edits | Leaves the file alone. The plan is blocked with `changed_since_edit` before any write; Conversation only stays available. |
| After this branch's first edit, and a rewind on the other branch already took that edit back | The edit no longer counts; the file is restored as in the rows above |

A sub-agent's turn records in the point of the turn that spawned it. A turn the runtime started records in the nearest earlier prompt on its branch. Such a turn may first edit a file after a later prompt's turn did; a rewind past both returns the file to the state from before either. Rules for one file: [File management](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/operations/file-management.html#rewind).

Claude Code's rewind returns each tracked file to its checkpoint state, later Bash changes to it included. Codex has removed its undo; its `thread/rollback` drops turns from the context and leaves files as they are. Neither describes a check for a later edit by another session, so here such a file is left alone and named.

Claude Code and Codex branch by copying: a fork gets a new session or thread id and runs as its own conversation. Neither publishes a rule for two concurrent turns inside one session or thread; Claude Code bug reports describe concurrent resumes of one session writing interleaved branches without a lock.

## What each control does

| Control | Result | Boundary |
| --- | --- | --- |
| Pause | Stop at the next safe point | The current action may finish; no arbitrary line is frozen |
| Continue | Resume the same execution from saved progress | Only when saved state and capability permit |
| Step | Run one declared step, then pause | A tool action or declared boundary, not a source line |
| Steer | Add instructions for work not yet run | Completed work is unchanged |
| Cancel | End the execution and what it waits on: a synchronous sub-agent and the turns under it | Cannot undo completed external actions; a managed process has its own control. A background sub-agent and a branch made from a saved point keep running. A turn another live process owns (a scheduled run) gets the request through its execution's function log and stops itself. |
| Fork / Retry | Create an independent child from an allowed saved point | Original history stays. Agent chat children start paused and need Continue; others follow their scheduler. |

The UI offers only controls that execution supports. "Accepted" means saved; "applied" means it took effect. Command completion is idempotent when terminal reconciliation wins the race: after a compare-and-swap conflict the service accepts only an already applied command for the same execution and result version, keeps the stored receipt and propagates other conflicts.

## Stopping a turn

A Stop ends one branch's foreground operation and keeps what it already produced. Compared with Codex, Claude Code, OpenCode, Pi, KimiCode, Grok Build, Hermes Agent, ZCode and Cline; each topic names the one it follows.

| Topic | What happens | Follows |
| --- | --- | --- |
| Stopped reply | Model calls that finished stay in the history with their reasoning signatures. Text cut while streaming is kept as one last unsigned call; its unsigned reasoning is shown, not sent; a tool call whose arguments had not all arrived is dropped. The kept text is the deltas that went out as stream frames; a reply cut by a steer is cut back to them too. | OpenCode |
| Stopped reply's text | The text of its blocks ([a blank line between passages](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/execution/dispatcher-split.html#reply-text)), then the files it attached. The stored reply, the final `result` frame, `--print` and a channel all get that one value. | OpenCode |
| Every call gets a result | A running call: its output so far, then `Stopped by the user after 3.2s.` A call sent but not started: `Not run: the turn was stopped before this call started.` A Worker restart: `Interrupted after 3.2s because the service restarted.` No conversation id reaches the model. | Codex, with OpenCode's kept output |
| Note on the next message | The stop writes `interruption` (reason, phase, whether a call was cut) on the reply. The next message's turn block gets one sentence saying why the previous reply stopped, plus "A tool call that was stopped may have partly run." when one was cut. It is written once on the message's node, so every later request sends the same bytes. | Codex's wording, Grok Build's placement |
| Empty stopped reply | Nothing is written in the assistant's place. Anthropic and Gemini requests join two adjacent plain user messages into one. | Codex |
| Stop key in the terminal UI | Ctrl-C or Esc stops on the first press while a turn streams or a send waits for its ack; otherwise it stops the branch's `/compact` by its `op_id`. Later presses resend the same stop with the same command id and add no line. Idle, a double Ctrl-C still exits. | Claude Code; Codex for one key per task |
| Stop before the id | A chat, a function run and a retry carry `client_request_id`; a Stop before the ack names it. The page keeps `_optimisticStops` so the ack does not show the stopped turn running again. | Claude Code's `queryGuard`; Codex for returning the id |
| How the signal arrives | The stop sets the turn's plain Event and runs what is registered beside it (`run_control/wakeups.py`): the turn's loop is woken and the task reading the provider is cancelled at once. A 0.5 s check remains for a signal set without that call; the function log still carries a stop across processes. | Codex `or_cancel(&token)` |
| Background agents | A Stop leaves them running. Stopping one from its own row queues "Background agent … was stopped by the user." for the conversation that started it. | Claude Code |
| Queued messages | They are sent once the server has released the stopped turn. | Claude Code |
| Stop before any reply | The message stays, with its "Stopped before it started" line. Taking it back is a rewind. | Codex, Pi, OpenCode |
| Waits | A Stop replaces a pause, an open question and a pending reconciliation; they close. | Codex, Claude Code |
| `--print` on Windows | Ctrl-C and Ctrl-Break take the stop path; closing the console does too, with a 3.5 s grace inside the time Windows allows. | Claude Code's Node signal mapping |

### Why this design

| Topic | Why |
| --- | --- |
| Stopped reply | The model should see what the person saw: after a stop people say "continue" or "change that line", and dropping the cut text (Codex, Pi) makes the model start over. Finished calls are valid signed history. Anthropic refuses unsigned reasoning, so only the cut call's reasoning is left out. |
| Stopped reply's text | A provider adds a delta to its partial before the loop reads its event, so at a stop or a steer the partial can be ahead of the stream; keeping it would store, and after a steer send the model, text no client was sent. OpenCode builds the stored part from the delta events it handled, so stream and store agree. The cut text joins the turn's text where the loop ends; no later step holds a second value. |
| Call results | A call without a result makes the provider refuse the request. The elapsed time and the "not run" case let the model judge whether to run it again; a per-tool side-effect table (Hermes) costs upkeep the cut-call sentence already covers. |
| Note placement | Text in the assistant's place gets repeated by the model (Hermes found this), so the note rides on the user's turn block, by the same mechanism as the rewind note. Writing it at stop time keeps the cached prefix stable. |
| Stop key | Codex and Claude Code stop on the first press; a hint first reads as no response, and the second press then hit the exit flow. One line per stop is enough, but the resend stays because a first signal can be lost. |
| Signal | Every peer is event-driven; two polls cost a median of about 160 ms and a thread per turn. The Event stays plain because request options holding it are deep-copied. |
| Background agents | The person asked for them to keep running. Without the notice the model waits for a result that never comes. |
| Queued messages | Codex and Pi put the queue back in the input because theirs cannot be edited; here queued messages are visible and editable above the input, as in Claude Code. |
| Stop before any reply | A rewind is something the person does; taking the message back on a Stop would make one button do two things. |
| Windows | Windows has no SIGTERM; scripts send Ctrl-Break, and a closed console allows about 5 s before the process is killed with its execution left running. |

## What survives a restart

| Record | Meaning | Why |
| --- | --- | --- |
| Checkpoint | Next action after a model decision or tool result | Continue starts here; no frozen thread is restored |
| Effect receipt | Whether a model or tool request finished and what was confirmed | Confirmed work is not repeated; an uncertain external action is checked first |
| Attempt ownership | Which worker may update the execution | An old worker cannot overwrite a replacement |

| Case | Recovery |
| --- | --- |
| Running Agent execution, Worker gone | Startup claims it once and activates the original execution, revision, turn and assistant reply from durable input and its latest continuation |
| Interrupted model request | Regenerated from committed context; completed tools are skipped |
| No first model response yet | Restarts from admission input within the original deadline |
| External operation unresolved | Not repeated; stays reconciliation-required. A not-committed receipt is never fabricated. |
| Manually paused, cancelling, cancelled, completed | Not continued automatically |
| Interface closed or reconnected | Transcript preserved; worker-owned execution keeps running |

Worker interruption is not an assistant failure: no error reply and no restart or recovery messages. Real provider and tool failures appear as usual. No special save or graceful exit is required.

## Automatic continuation window

|  |  |
| --- | --- |
| `execution.auto_resume_window_seconds` | Default `-1`, no time limit (a null deadline). `0` disables automatic restart. A positive value is a duration. |
| Measured from | The orderly shutdown intent, or the abandoned attempt's last durable activity; not the next startup. Restarting again does not extend it; existing finite intents stay finite across upgrade. |
| Orderly stop | Disables dispatch and restart reconciliation in the exiting runner, then asks the turns this process owns for a cooperative pause; a scheduled turn runs in its own process and is left alone. A racing checkpoint version is retried at most three times within the same attempt and deadline. |
| Attempt already ended | Startup recovery takes the ending the turn's log recorded and rejects its pending commands. With no recorded ending it publishes no checkpoint: the run becomes `interrupted` and its pending pause is rejected. |
| Resumes automatically | Only a pause owned by restart recovery |
| Stays explicit | User pause, cancellation, unanswered approval, unresolved effects, stale checkpoints, incompatible runtime contracts, legacy paused records with no restart intent |
| Expiry | Keeps the checkpoint for manual continuation and never deletes conversation data |
| Self-update | Same duration, from the completed update's last persisted activity; deadline and expiry saved in the update directory. Resume, contract-repair planning and original-session follow-up honour it. A still-running update is not stopped. Maintenance still controls admission and verification. |

**Restart mechanics**

| Part | Rule |
| --- | --- |
| Checkpoint and receipt | Provider decisions and completed tool actions publish them atomically during ordinary execution. The original execution id, immutable inputs, permissions, budgets and continuation commands stay authoritative; queued Jobs use the resource queue. |
| Restart intents | Canonical execution events stored with the transition; fixed command identities make repeated startup idempotent. No second database, scheduler, process owner or permission path. |
| Resume ownership | Records the exact inherited checkpoint; a second interruption before a new effect keeps it |
| New Jobs | Own stable user and assistant message ids at admission. Pause completion releases resources by the attempt and lease identities the Job waiter retained. |
| Abandoned ownership | Startup classifies it before the runner applies this policy. Provider-only or never-activated chat admissions can continue from immutable input inside the original activity deadline. |

## Resuming the same turn

| Aspect | Rule |
| --- | --- |
| Bindings | Restores the same session, turn, reply, runtime and tool bindings; releases them on completion, suspension or error |
| Browser page capabilities | Stay bound to the original owner; another owner's token is never accepted. A rejection is an explicit tool error with its original reason. |
| Iteration limit exhausted | The run ends unsuccessful, keeping its text and operation history |
| Resolved wait | Considered only while its checkpoint is still the execution's current one, so an older answer cannot resume, fail or cancel a newer wait. Repeats are idempotent. |
| Declined wait | Its checkpoint keeps the displayed text, reasoning and tool calls; the terminal projection publishes a session reload after saving |
| Pending approval | Shows near its assistant message only when the authoritative execution update names that message in the same session. Reconnecting requests the canonical replay. Missing evidence never attaches another run's decision to a message. |

## Function versions

`execution.code_change_policy` selects `keep_original` (default) or `use_latest`; Continue can override per execution. Relevant function and dependency identity decide whether code changed. A policy change is a version-fenced command and never creates a new call.

|  |  |
| --- | --- |
| A durable function records | Source and dependency identity, input, completed steps and results, next safe position, serializable state, outstanding effects |
| Boundaries | Synchronous `step`, nested `workflow`, named `parallel`. Pure orchestration rebuilds local JSON state from committed results. |
| Storage | Existing execution events, blobs, checkpoints and effect ledger |
| `use_latest` | Keeps completed results with their provenance and validates the rest. State conversion and step correspondence must be explicit; ambiguous edits stay paused with specific differences. A compatible candidate becomes the retained version before new work. |
| Never degrades | A missing source, unavailable dependency, nonserializable state or unsupported boundary cannot fall back to fresh execution. An incompatible `use_latest` does not fall back to `keep_original`. Retry is a separate new execution. |
| Effects | Completed effects are reused. An in-flight step with no confirmed result stays unresolved unless its protocol proves safe. Repeated resume and a second crash cannot duplicate accepted effects. |
| Nesting | Nested calls keep parent identity, parallel branches keep separate progress |
| Agent-owned call | Shares the mechanism with manual calls. The result returns to the original tool-call position; a stored result is delivered without re-execution. A manual call updates its original result record. |
| Outside the contract | Native frames, asynchronous orchestration, live handles, and arbitrary Python functions. Helper-local imports and opaque non-standard-library dependencies are rejected before external steps. |

**Pause at a step boundary**

| Case | Handling |
| --- | --- |
| Pause accepted after a durable step checks its boundary, before effect registration or dispatch admission | Suspends the function through the pending Pause command |
| Admission-closed conflict | Converted only when that real command is pending; other collisions keep their errors |
| Planned intent that never dispatched | Records a not-started receipt before the pause |
| Dispatched operation | Never classified as not started |
| Cancellation | Takes precedence |
| Continue | Keeps the call cursor and reuses committed steps |
| Crash recovery | Uses the last durable boundary and fences the former owner |
| Function subprocess startup | Holds no history-wide write transaction; sequence backfill belongs only to the migration that adds the column |
| Standalone function progress frames | Address the existing code node; completion releases foreground occupancy before optional session naming |

## Who owns run state

Run state is folded from each session's log into in-memory tables; no database file exists. See [Session storage](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/session/storage.html). The process holding `worker.lock` owns the runs it starts. A function subprocess reads the tables and hands changes to its parent.

A scheduled task's turn, and a turn in a stand-alone ACP or MCP process, belongs to that process, which writes that turn's rows to its own log. A sub-agent a scheduled task starts is admitted and run by the Worker, the only process that can claim a queued Job.

## Attempts and fencing

| Case | Rule |
| --- | --- |
| Owner | An activated execution has one current attempt, owned by the `worker.lock` holder, with no heartbeat |
| Turn run in another process | Its owner lease records that process's id and start time |
| Process exits, lock released | A new Worker that takes the lock may close attempts the logs show as open, unless the recorded process is still running; it then reads how that turn ended once the process exits |
| Orderly stop, self-update checkpoint | Never touch a turn another process owns |
| Log recorded a turn's ending, a later line left it unfinished | Startup restores the recorded ending |
| A pause or a stop wins against the starter | Each step of starting a turn is a compare-and-swap (lease, activate) or a hand-off the driver may refuse. Whichever loses, one check reads the execution again and gives way to the control intent it finds. Anything else is the starter's failure. |
| What the starter finds when it loses | Paused with no checkpoint and no attempt: nothing is written, a later Continue starts the turn. Cancelling or cancelled with no attempt: the stop ends the queued turn itself. Cancelling under the starter's own attempt, which no driver heard: that attempt reports its own loss, the execution ends cancelled and the cancel is applied, with the attempt ended `cancelled_during_activation`. |
| Turn stopped before it started | Activation returns no result. Every caller reports the turn as stopped before it started: a sub-agent, a merge, a check-in, a channel reply, an MCP call and a function call. |
| Its reply | A chat turn opens its reply when it starts, so the stop writes it: empty and stopped, after the message. Live and after a reload the page shows a stopped reply, as for a stop just after the start. A turn that writes its message only when it starts leaves nothing to close. |
| No reply row otherwise | A function call's row, written just after admission, can still arrive; a turn that started and left none has lost it. The stop logs an error and the event effect tries again, five times, then logs that it gave up. |
| Every owner write (tool result, safe point, wait, steering delivery, finish) | Verifies inside its transaction that the attempt has not ended, its generation is current and the execution still names it. An owner that fails this check stops. |

An attempt that fails keeps its readable error on the attempt row, with credential-shaped values scrubbed and at most 4000 characters. It stays out of snapshots and event payloads; only Activity's per-run events read it. An attempt closed by owner loss has no such text, and older rows read as none.

## How the control plane reaches the engines

`openprogram.runtime.execution` imports no engine and no Program. What it must decode, it owns; to start or ask an engine, it calls a hook from `execution/hooks.py` that the engine registered at import.

| Hook | Registered by | Does |
| --- | --- | --- |
| `agent_activator` | conversation, required | Build the production driver that activates an attempt |
| `recovery_turn_starter` | conversation, required | Admit the turn that continues an interrupted chat |
| `permission_wait_reconciler` | conversation, required | Re-run permission approval waits at recovery |
| `session_goals` | conversation, required | Session Goal owner lock for restart reconciliation; recoverable pause of a Workflow Goal |
| `live_owner_signals` | conversation, optional | Stop or kill a subprocess and exec runtime |
| `terminal_settler` | conversation, optional | Settle the chat Goal: usage, idle count, next turn. A Goal that is busy or whose usage is not in yet defers the accounting to the turn's owner and the next read of the Goal, and never raises. A stopped turn's cancelled reply and resource release run whatever the settlement does. |
| `job_records` | jobs, required | Find, list and settle Job records during cancellation |
| `turn_request_fields` | jobs, required | Fields a stored Job input may carry |
| `job_runner` | jobs, optional | Live runner bound to an execution store |

A missing required hook raises `EngineNotRegistered` (`engine_not_registered`), naming the hook and package; the work is never skipped silently. A missing optional hook is itself the answer: no such engine in this process. Loading conversations also loads Jobs.

**What the control plane owns**

|  |  |
| --- | --- |
| `execution/agent_journal.py` | Versioned Agent state payload, written as lines of the session log |
| `execution/admission_input/job_input.py` | A Job's strict admission input envelope |
| `execution/run_control/` | Bound session and execution, cancellation tokens, live owners and grace period, exact cancel and child admission |
| `conversation/run_control` | The turn side: turn tokens, cancel events, active exec runtimes |
| `execution/recovery/resource_saga.py` | Takes its governor as an argument; the governor implements `ResourceGovernor` |

Goal hooks belong to conversations because a chat Goal runs as conversation turns; they import `openprogram.programs.tools.planning.goal` on first call, since that tool can load after startup recovery.

## Workflow questions

A question from a running Python Workflow

| Aspect | Rule |
| --- | --- |
| Where it waits | In its current process, bound to the exact execution, attempt and generation. Uses the canonical wait store and question UI; neither checkpoints the Workflow nor restarts its call stack |
| Answer | Returns to the original call. A browser refresh reloads the pending request |
| Who | Only the live current owner may create or answer one. Cancellation, execution end or loss of the process owner invalidates it. Worker restart does not replay the Workflow |
| Transport | The subprocess publishes through the existing queue bridge. Unexpected errors propagate rather than become an unanswered result. Agent tool questions with declared pre-wait checkpoints keep durable continuation |

## User decision panels and receipts

Questions, confirmations, forms and permission approvals are session-scoped panels above the composer. Terminal receipts stay in the conversation.

|  |  |
| --- | --- |
| Composer | Keeps its draft, attachments, function form, focus and send or queue behaviour. New requests never capture it or move focus. |
| Navigation | Back, Next and collapse keep drafts and send nothing |
| Skip | Declines the whole question request |
| Submit | Immediately shows the submitted answer and a sending state |
| Applied | Answered receipt |
| Delivery unknown | Retry keeps the same command identity and answer |
| Rejected or expired | Cannot imply approval |
| Several requests | Separate keyed cards, scoped to session and execution, including split views |

Cards reuse the shared question renderer, canonical question events and execution commands. Each card owns its answer fields, submission controls and delivery status. Receipts are not Workflow checkpoints; refresh reloads pending questions and does not add historical receipt persistence.

**Identifiers and safety rules**

|  |  |
| --- | --- |
| `session_id` | Conversation scope and authorization; never a control target |
| `run_id` | Groups related original, fork and retry executions |
| `execution_id` | Exact control target. Pause and Continue keep it; a fork or retry creates another. |
| `attempt_id` | One activation of a worker |
| `revision_id` | Immutable version of the program and its contract |
| `command_id` + `expected_version` | Prevent duplicate actions and reject stale commands. A cancel names its execution only: its version is recorded, never compared |

| Rule | Behaviour |
| --- | --- |
| Command service | All transports use one command service, which saves the command before the owner applies it. UI state does not authorize an operation. |
| Precedence | Cancellation takes precedence over pause, step, continue and steering. Only the current owner publishes progress or a final state. |
| A stop and its version | A stop names its execution, not a version. A turn's version moves twice in its first tenth of a second (leased, then running), so a Stop pressed right after sending often carries an old one. The store takes the stop at the current version in one transaction and only logs the one the sender saw (`cancel.version_moved`). |
| Other commands and their version | Pause, Continue, steering and answers still need the current version: they are decisions about a snapshot. |
| One stop, answered by state | Every surface takes the same stop, internal or public, and its answer depends only on the state. Running: the execution moves to cancelling and its owner is told. Already cancelling: the stop in force comes back and its owner is told again, since a first signal may have been lost. Nothing new is written. Ended: the final state comes back with `already_terminal`, which is not a refusal. |
| Same command id | The same command id stopping the same execution is the same stop, whatever reason it gives. |
| Queued Job | A queued Job ends at once, so its dispatch is fenced first, for that exact snapshot; should the snapshot move before the stop is written, the fence goes to recovery. |
| What stops with an execution | One finder answers what stops with an execution. An execution's parents are its canonical parent and, for a Job, the caller and parent Job its input names, in whichever conversation; the walk passes through executions that have ended. |
| Public and internal stops | A public stop (the page, Activity, the terminal, `--print`, ACP and MCP clients) takes what the turn waits on: a synchronous sub-agent and the turns under it, not a background sub-agent or a branch. The internal stop (a channel's `/stop`, Goals, time limits) takes every descendant. |
| Order | Children stop before their parent, deepest first, so a queued child is fenced before its parent's ending frees the pool slot it would take. A child admitted while the parent was being stopped is stopped after it. |
| Delivery to an owner | An owner is handed a stop once. A repeated stop answers `already_delivered` without calling an owner that took it, whose handle may already be released; an owner that did not get it, or took over since, gets it now. |
| Clients | Clients send a stop once. The page says "Stopped." when the execution's own frame reports it cancelled, not on the command's answer. A Stop on a turn the page knows by id but not by version goes out at once. |
| What the Worker announces | On connect the Worker sends `worker_capabilities`: `cancel_ignores_version` (a stop is never refused as stale) and `cancel_by_request` (a stop may name a send). The terminal UI and `--print` resend a stale-refused stop, and name a send, only by what the Worker on their socket announced; an older Worker or remote server keeps the old behaviour. |
| A stop before the id | A stop pressed before the client knows the turn's execution names the send: its `session_id` and `client_request_id`, which admission records with the execution, one execution per send in a session. One store transaction decides. If the send was admitted, its execution is stopped like any other. The page, the terminal UI and `--print` send it this way. A new terminal conversation gets its id when its first message is sent, as a page draft does. |
| A stop mark | A stop of a send not yet admitted is written to the conversation's run log as a mark, answered `marked`. The send's admission takes it, and the turn ends cancelled when it activates, before an owner is leased, with its reply written as stopped before it started. A mark outlives a Worker restart and lapses after ten minutes. |
| Model errors and tool outcomes | Known model errors and aborts get response records. Unknown tool outcomes stay unresolved; the History label does not clear them. |
| Forks | Forks validate the saved point, immutable revision and permission. Program, model or tool contract changes keep their independent review. |
| Jobs | For Jobs, `job_id` equals `execution_id`. Resource allocation stays separate from execution state. |
| Project location | The current stored project location is read before loading a session. Reads and controls are restricted to the authorized conversation. Reconnect uses saved versions and event positions and creates no duplicate task. |
| Managed processes | Managed processes keep identity, ownership and bounded output. Restart recovery checks the supervisor; a saved PID alone is not permission to send a signal. |

## Implementation status

| Area | Implementation | Acceptance |
| --- | --- | --- |
| Branch counts | One row per real branch | Linear conversation → History 1. Three tips → History 3. |
| Attention | Provider-only missing records are told apart from real waits and uncertain effects | A real approval stays visible; an ended model request alone asks nothing |
| Execution controls | Shared commands, checkpoints and revisions; capabilities differ by execution | Test only advertised controls. Forced-tool, spawn and merge paths keep restrictions. |
| Processes and recovery | Ownership, separate stop, output retention and refresh on the default macOS App | Windows and Linux are not established by these checks |
| Branch run slots | Server side: admission per branch, branch-owned writes, per-branch run state and stop | Two branches finish concurrently with their own heads; stopping one leaves the other running; a switch while a turn runs goes ahead, the turn finishes on its own branch and the selection stays |
| Foreground operations | One slot table keyed by conversation and branch (`server_runtime/run_slots.py`); `reserve_operation` for compact, rewind, retry, edit, branch and function; `operation.cancel`; durable records and the file-rewind hold | Operations on one branch run beside another branch's turn; a file rewind is refused naming the running branch; a hold in another process refuses operations here; a rewind or revert repeated with its key while the first runs gets the first's result, another key is still refused, and a repeated send gets `request_admitted` (`tests/component/webui/chat/test_keyed_operation_repeat.py`) |

Not yet for a turn on another branch

| Gap | State |
| --- | --- |
| The web pane | Shows and sends to the selected branch only |
| Steer and queued page messages | Reach the selected branch's turn |
| Continue after a pause or a Worker restart | The resumed turn's context is not yet proven to read its own branch |
| Edit and retry while the selected branch's own turn runs | They wait: the new branch would take the selected branch's slot |
| Scheduled runs | Their process does not take the server's branch slot; a message is refused while a run is open on that branch, not the other way round |

Not yet for branch settings and branch state

| Gap | State |
| --- | --- |
| Merge | Holds the selected branch's slot, not its source and target |
| The menus' first item "Agent default (current: …)", a badge beside the composer for runs on other branches | The data is sent (`inherited`, `wait_state`); the controls wait on an approved design |
| An entry that names no branch (a channel) | Continues on the selected branch; the branch written last is recorded (`last_branch_id`) and not yet used |
| Follow-the-Agent migration | Not yet run on real conversations |
| Run state read only from the execution store | The slot table is still the live record of reservations and executionless operations; the execution store is consulted for paused and scheduled turns |
| One branch record | Names, turn counts and archive state still live in `meta.branches`, keyed by tip, beside `branch_refs`. Moving them needs a record for every tip a client names by message id (spawned branches, tips recorded before branch records existed) and a migration of the readers that key by tip |
| Stopping a rewind from the terminal UI | Its stop key reaches turns and `/compact` |

Not yet for a stop

| Gap | State |
| --- | --- |
| Resending a stale-version stop | The terminal UI and `--print` resend a stale-refused stop only to a Worker that does not announce `cancel_ignores_version`. The branch is deleted once both local Workers announce it; the remote-server branch stays until the next release. |
| The Job runner's own stop | The Job runner's own stop (Activity's Job cancel, a Job's budget) still finds descendant Jobs by walking `parent_job_id` itself, because it keeps each Job's queue, inbox and resource bookkeeping; it does not yet take the shared finder. A function run with only a session-graph record stops the graph nodes it called through the graph's own caller links. |
| Signal latency | With the two polls a stop reached cancelled in a median of about 160 ms on the dev Worker. The direct wakeup is not yet measured there. |
| Effect of the stop note | Whether the model continues from the cut after "continue" is not yet measured on real requests; the wording follows the peers. |
| `--print` on Windows | The Ctrl-Break test is written for Windows CI and has not run there yet. |

- Not available: arbitrary thread-stack restoration, automatic undo, reconstruction of process records never saved.
- Runtime calls that ask questions inside an ordinary function need a declared interaction boundary.
- Waiting deadlines and Job budgets are not yet connected to resource management.

**Source and references**

- [Branch membership](https://github.com/Fzkuji/OpenProgram/blob/main/openprogram/runtime/execution/projections/activity_branches.py)
- [Branch membership tests](https://github.com/Fzkuji/OpenProgram/blob/main/tests/component/webui/execution/test_activity_branches.py)
- [Activity panel tests](https://github.com/Fzkuji/OpenProgram/blob/main/apps/web/tests/execution/activity/activity-panel.test.mjs)
- [Execution protocol and persistence](https://github.com/Fzkuji/OpenProgram/blob/main/openprogram/runtime/execution)

|  |  |
| --- | --- |
| [Debug Adapter Protocol](https://microsoft.github.io/debug-adapter-protocol/) | Separate observation from control; advertise supported controls |
| [Temporal Workflow Execution](https://github.com/temporalio/documentation/blob/main/docs/encyclopedia/workflow/workflow-execution/workflow-execution.mdx) | Persist execution state |
| [Temporal Workflow Pause](https://github.com/temporalio/documentation/blob/main/docs/encyclopedia/workflow/workflow-pause.mdx) | Pausing does not undo work already started |
| [LangGraph persistence](https://docs.langchain.com/oss/python/langgraph/persistence) | Save progress at checkpoints |
| [LangGraph interrupts](https://docs.langchain.com/oss/python/langgraph/interrupts) | Wait for input and resume at a defined boundary |
| [LangGraph time travel](https://docs.langchain.com/oss/python/langgraph/use-time-travel) | Keep original history when creating alternatives |
| [Kubernetes Pod lifecycle](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/) | Request termination, then confirm owner shutdown |
| [Claude Code checkpointing](https://code.claude.com/docs/en/checkpointing) | One checkpoint per prompt; another session's edits are captured only when they touch the same files |
| [Codex features](https://github.com/openai/codex/blob/main/codex-rs/features/src/lib.rs) | Undo is marked removed; rollback does not restore files |

[Background Jobs](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/execution/async-job-lifecycle.html) · [Resource allocation](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/reliability/agent-resource-governance.html) · [Error handling](https://fzkuji.github.io/OpenProgram/docs/reference/design/repository/error-handling.html)
