# Background Job lifecycle

Every spawned sub-agent is a Job in `openprogram/runtime/jobs/`, with `job_id` equal to its `execution_id`. Control goes through [the execution control plane](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/execution/control.html); a Job adds admission, a worker pool and result delivery.

1. **`pending`** record saved
2. **`queued`** waits for a worker
3. **`running`** turn in progress
4. **`completed` · `cancelled` · `errored`** terminal; pending and queued can also end cancelled or errored

Terminal states absorb; illegal moves raise `ValueError`. Since canonical executions do not mirror their running transition, the projection may also go `pending → running` and `queued → completed`.

## Entry points

|  |  |
| --- | --- |
| `agent(prompt, description, agent?, start_from="fresh", run_in_background=False, isolation?)` | Model tool. Foreground returns the result block; background returns the execution id. `send_message` delivers to an existing agent as a Job. |
| `read_conversation(execution_id)` | Model tool. Returns the Job's status, and its reply once terminal, without waiting. `job_output(job_id, block, timeout)` stays registered for programs, hidden from the model. |
| `list_agents()` | Model tool. Lists this session's running or queued Jobs, newest first, at most 20, beside its branches. `list_jobs()` is hidden from the model. |
| `/task`, `/task --async`, `/spawn` | Typed in chat. Blocks, or writes a running placeholder and returns. |
| `spawn_job`, `list_jobs`, `get_job` (WS) | Create and read. Replies: `spawn_job_result`, `jobs_list`, `job`. No `session_id` on `list_jobs` means all sessions. |
| `execution.cancel` (WS) | Cancels; Job actions do not include a separate cancel |

Clients follow the `job_status` broadcast. The branch view shows Job status; there is no separate Tasks panel.

## Scenarios

| Case | While running | Result reaches caller | Stop and failure |
| --- | --- | --- | --- |
| One foreground call | Caller blocks; the attach card goes straight to its final state | Reply as the tool result | Stopping the session cancels the child and the parent turn; partial output returns |
| One background call | Caller continues; a running card shows | A notice turn in one result shape; `read_conversation` reads it earlier | Cancel from the UI or `close_agent`; a stop by the person is told to the caller |
| Several background calls | Pool runs up to its width; the rest stay `queued`, first in first out | Each returns separately; finishing together during a turn produces one notice | Each has its own status and error; the parent decides on partial results |
| Long job, cancelled | Slot held until the worker exits | Partial output | Escalates after 30 seconds |

## Worker pool

|  |  |
| --- | --- |
| Pool | `ThreadPoolExecutor`, same thread model as a chat run. `process_user_turn` opens its own event loop, so there is no nested-loop conflict. |
| Width | `OPENPROGRAM_JOB_WORKERS`, default 8 |
| Admission | Resource governance admits and limits a Job; see [Resource allocation](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/reliability/agent-resource-governance.html) |
| Per-session limit | None |

## Persistence and recovery

|  |  |
| --- | --- |
| Store | One `jobs.json` document per session, `{"jobs": {id: Job}, "version": 1}`; each write is one line of the session log |
| Locking | One lock per session: read, mutate, write |
| Worker lost | A non-terminal Job with no current attempt or accepted command becomes `errored`, `worker died before completion`. One with a canonical attempt follows [restart recovery](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/execution/control.html#restart-window). |
| Notices | Pending in `<caller-session-dir>/notices.json`, so a restart keeps them; a crash before queuing one is covered in [Hand-offs across a crash](#handoffs) |

## Hand-offs across a crash

A sub-agent request crosses three hand-offs between the parent and the run. Each writes what it is about to do before doing it, the step after it is idempotent, and the Worker's resource reconciliation (at start, on run-table changes and at least every 60 seconds) finishes whatever a dead process left half done. `openprogram/runtime/jobs/handoff.py` holds the shared pieces.

1. **Admitted** Job and its intent saved
2. **Handed over** inbox entry or attach card, then published
3. **Ran** canonical execution and its recovery
4. **Parent told** tool result or notice

| Window | Intent written first | Idempotent step | Next Worker |
| --- | --- | --- | --- |
| `send_message` to a busy target: admitted, not yet queued | The inbox entry rides on the Job as `deferred_inbox`, saved with admission | `inbox.enqueue` keeps one entry per `job_id` | Recreates a missing entry; a surviving one stays as it is |
| Inbox drain: published, entry not yet removed | The admission row says the Job left the deferred state | Delivering an already published Job returns its id | The drain removes the leftover entry; the Job runs once |
| Spawn admitted held, attach card or publish not yet done | `Job.submitter` names the submitting process; `attach_pointer_id` names the card | The card is written only when its node is missing | Once the submitter is gone, writes the card if missing and publishes the Job |
| Terminal written, notice not yet queued | The terminal write sets `notice_pending` to the writing process | `notices.queue` keeps one entry per Job | Replays a mark whose writer is gone, then clears it |
| Waited-on spawn whose waiter died | `Job.submitter` is the waiter | As above | The finished Job is told to the parent by notice, its reply inline, since its card stays out of context |

The parent turn that was cut off in the middle of the `agent` call reads that call as interrupted with an unknown outcome ([restart recovery](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/execution/control.html#restart-window)); the attach card and the later notice tell it what became of the request. A held Job whose submitter still runs, in this process or another, is left to it.

### Why this design

| Topic | Why |
| --- | --- |
| Intent before acting | Exo's `beginTurn` durably accepts the input before the executor acts, and Maka commits the dispatch (T1) before a tool runs and the outcome (T2) before the result is published. Both make the record the authority and the action a consequence. Here the Job record is that record: whatever the next step needs travels on it, so recovery reads one row instead of guessing. |
| Idempotent by Job id | Maka's graph claims preallocate the run identity and observe an existing run instead of starting it again; Codex publishes the spawn edge before the child exists. A replay keyed by the Job id can run at every reconciliation pass without a second inbox entry, card, run or notice, so recovery needs no extra state to know it already ran. |
| Liveness of the submitter | The held spawn and the waited result belong to whoever submitted them while that process lives; only its death hands them to recovery. Process identity is the pid plus its start token, as execution leases already record, so a reused pid is not mistaken for the old waiter. |
| A dead waiter's result | Claude Code and Codex lose a foreground sub-agent's result with the process; Maka re-delivers its supervisor wake until the root run completes. Telling the parent by the same notice a background agent uses costs nothing new and keeps the work from being lost or redone. |
| Run the request rather than cancel it | The request was admitted with its budget; dropping it would make the model guess, and its interrupted call already warns that the outcome is unknown. Running it once and reporting is the outcome the parent asked for. |

## Cancellation

1. `JobRunner.cancel_execution` persists one `execution.cancel` command, and cascades to child Jobs.
2. The owning worker consumes it and sets `cancel_event`, which `process_user_turn` bridges into the agent loop; the provider stream stops at its next chunk.
3. Live subprocesses and exec runtimes are signalled by exact execution id. Agent methods check at their pre-invocation hook.
4. After `_CANCEL_ESCALATION_SECS` (30 s) the owner's grace ends.

A tool's own atomic operation finishes first. A cancelled or errored Job cannot be resumed as the same work; retry is a new spawn.

## Session and attach card

- A Job runs in exactly one session, `parent_session_id`, and that never changes. A caller in another session is `caller_session_id`, with a linked mirror for visibility and ownership checks.
- Output lands as a branch of that session, or a new root with `context="clean"`.
- An attach node (`function="attach"`) is written after admission with status `running` and the `job_id`. The runner updates that same node at each terminal state. A cross-session card lives in the source session and names the target.
- A synchronous caller settles the same card when its wait ends. Each writer merges only its own fields into the card as it stands inside the conversation's write lock (`SessionStore.merge_node`), never a copy read earlier.
- That wait ends when this process's runner has finished the Job (status, card, notice), not when the status is first written, so the tool result and the card agree.
- Context rendering skips a running card. A finished one becomes one sub-agent report with its task, final reply and transcript address.

**Job fields**

|  |  |
| --- | --- |
| Identity | `id`, `parent_session_id`, `caller_session_id`, `parent_job_id`, `parent_msg_id`, `caller_msg_id`, `agent_id` |
| Work | `prompt`, `subject`, `description`, `label`, `context_mode` (`inherit`, `clean`), `wait`, `source`, `model_override`, `tools_override`, `thinking_effort` |
| Timing | `status`, `created_at`, `queued_at`, `started_at`, `completed_at`, `cancel_requested_at` |
| Outcome | `head_id`, `result_text`, `error`, `reason_code`, `attempt`, `attach_pointer_id`, `target_branch_head_id` |
| Collaboration | `chain_messages`, `chain_generations`, `caller_chain_generations`, `archive_when_done`, `deferred_inbox`, `relation`, `worktree_id` |
| Hand-off | `submitter`, `notice_pending` |
| Authority and budget | `speaker_*`, `principal_id`, `authority_tier`, `admission_id`, `budget_scope_id`, `effective_limits`, `project_id` |

Runtime objects such as cancel events stay in the runner's maps, never on the record. `JobRunner` takes an injected governor and driver factory, so its state machine can run without a real model.

## Invariants

- Every Job ends in exactly one terminal state.
- States only move forward.
- The attach card changes with the record.
- `parent_session_id` is immutable.
- Runner maps are held under a lock.

## Out of scope

| Area | Not provided |
| --- | --- |
| Scheduling | Cross-process or multi-host workers; priorities and preemption; automatic retry (the agent decides) |
| Job relations | Several target sessions on one Job; Job dependency graphs; a parent agent subscribing to a child's output mid-flight |

## Implementation status

|  |  |
| --- | --- |
| Implemented | Record and state machine, persistent store, worker admission and execution, query and wait, cancellation at `JobRunner`, WS spawn, list, get and status, completion notices, hand-offs across a crash with a test that kills the process at each window |
| Partial | Attach-card lifecycle across every recovery path; resource governance across token, cost, runtime and idle limits; the full spawn and concurrent-cancel test matrix |
| Not done | The `tool_call_id` of a card that recovery writes is unknown, so that card is not paired with the interrupted tool call |

[Activity and control](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/execution/control.html)
