Goals and restart recovery
Resuming a session does not mean retrying its tools: an old turn may end interrupted while its operations stay outcome_unknown, and a new turn checks actual state first. Behaviour: Goals in chat.
- Web, TUI, ACP, background Jobs and authorized subtasks share one chat execution layer.
- No second engine, no general scheduler, no exactly-once promise for external operations.
| Goal step | What happens |
|---|---|
| Save the objective | Original objective, completion conditions, permission scope, explicit budget |
| Work through chat | The agent keeps a Todo and uses existing tools and approvals |
| Check at turn end | Settle usage; continue, wait, pause or verify |
| Accept | Independent read-only turn confirms every condition; otherwise back to work |
No default round cap: round count is diagnostic. create_goal, get_goal and update_goal only read and write objectives.
In the chat, /goal <objective> leaves one message: the objective, with a Goal label (target icon, “Goal” in the accent ink, medium weight) opening its first line.
- The label comes from
starts_goalon that user row, never from the text; only the message that creates the Goal has it. - The label and the opening paragraph are one paragraph, so the objective starts on the label's line and wraps under it; later paragraphs, lists and code follow as in any message. An objective that opens with a list or code puts the label on its own line above it.
- The sender's bubble takes the label from
starts_goalonchat_ack, before the transcript row arrives. A/goalfrom a New chat draft runs in that draft./goal statusand the other subcommands that only answer leave no user message, only their reply line. - No reply line follows. Copy, edit and retry see the objective alone.
- A creation that fails answers in text. The Rich REPL draws no messages, so it prints “Goal saved; working in this conversation.”
Automatic recovery
- Load factsrun intent, controls, messages, checkpoints, effects, waits
- Confirm ownershipreconnect live executors, fence dead ones by generation
- Repair contextmerge real results, fill missing tool outputs
- Decideuser stops first, then approval, permission, budget, resources, unknowns
- Admit oncefair scheduling, quotas, stable continuation key
- Restore interfacecanonical snapshots, ordered events
Run intent and shutdown
| Topic | Rule |
|---|---|
Durable run_intent | Builds on existing admission, command and restart intent. Clients are acknowledged only after the request is saved. |
| What it records | work_id, original input and unconsumed messages, desired_state (run, paused, cancelled, done), latest control version, permission scope, objective revision, execution host, parent and child links, last committed progress, recovery policy |
| Default | Authorized work still in run resumes without reopening the session. Ordinary requests continue only until they finish. Background work keeps its authorization and concurrency quota; restart authorizes no new subtasks. |
| Window close, reload | Only disconnects. "Quit and stop all tasks" persists a stop intent. |
| App exit, upgrades, worker crashes, machine restarts | Not Pause. Graceful shutdown stops admission and saves controls and checkpoints; forced shutdown recovers from the last commit. |
| Unacknowledged client drafts | Not submitted requests |
execution.auto_resume_window_seconds | -1 by default (no expiry), 0 opts out; existing finite deadlines are not extended |
| Continuation checks | Rechecks directory, host, model and tool availability, credentials, permissions and budget. Missing resources show a precise waiting reason and never switch project, account or model or widen permissions. |
| Old paused records, unknown reasons | Stay paused with an explanation |
Stage rules
| Stage | Rule |
|---|---|
| Load | Also usage and projection cursors. Read or migration failure shows recovery failure and clears nothing. |
| Ownership | One host per work item; single-host recovery never becomes cross-host takeover |
| Repair | Resume from a complete safe checkpoint; otherwise a new turn with the same work_id, without re-appending user input |
| Decide | Runnable becomes queued; dependency waits become waiting; faults expose retryable reasons. All persisted in one control service. |
| Admit | Key from work_id, control version and predecessor commit. No duplication window between admission and consuming intent; cross-database steps converge through a retryable outbox. |
| Interface | Shows recovering, queued, working, waiting or failure; never a second control implementation |
- Coordination belongs to execution control. The server and JobRunner may call the same idempotent entry but decide nothing independently. UI orphan cleanup repairs only derived projections.
Goal.after_terminalsubmits continuation only for the current version. - A message in the client's send queue goes first: the client reports it and the continuation yields for up to 15 seconds, during which the user turn's admission supersedes it under the Goal lock.
- Temporary faults use durable retry times and bounded backoff, not idle model calls. Persistent faults keep pending-recovery records and show the error with Retry, Pause and End.
State after restart
| Before restart | After restart | Must hold |
|---|---|---|
| Accepted request, unscheduled | Requeue in input order, admit once | Deduplicate by client request id; late retries cannot override Stop |
| Interrupted model stream | Keep committed text and tool results, label incomplete output, request the rest | No fabricated whole response; a new attempt can cost more |
| Active Goal, working or between turns | Load objective, Todo, evidence, budget, run intent; continue work or acceptance | Idle active Goals are not skipped; 5/5 only triggers acceptance |
| User Pause, End or Stop | Stays paused or ended | Persisted when accepted; notifications cannot release it; "still stopping" is separate from intent |
| Pending approval or answer | Restore question, summary and scope; consume a committed answer once | Restart is not approval; changed implementation, arguments or permissions void old approval |
| Parent waiting for subtasks | Restore identities, outputs, inbox cursors, waits; parent continues on terminal state | Reconnect live children, never recreate finished ones; user pause reaches children in scope, not independent tasks |
| External process, terminal, remote job | Query by host, process-start identity or handle; keep observing if alive | PID alone is insufficient; uncertain stays unknown; no resubmission |
| Browser, MCP, temporary resource | Verify identity on reconnection; report invalidation; create new only if authorized | Forms, logins, JS memory and REPL variables are not guaranteed; a new tab cannot impersonate the old one |
| Compaction or message write in progress | Use last committed history and summary | Partial tool arguments never run; current permissions apply; unavailable dependencies shown |
| Result written, notification undelivered | Replay projections and inbox delivery, no rerun | Versions prevent UI rollback; no double charge in parent aggregation |
| Usage receipt absent or stream-only | Reconcile by provider attempt, deduplicate | Unobtainable usage stays unknown; downtime is not active time |
Recovery promises saved state, run intent and reconstructable execution, not process memory. Unpersisted fragments, a dead shell's memory and lost receipts are reported, never hidden.
Interrupted tools
| Before interruption | Fact after recovery | Next |
|---|---|---|
| Intent saved, dispatch unrecorded | not_started; holds only because every dispatch is recorded first | Call again under current permissions if still needed |
| Dispatch recorded, no result | outcome_unknown | Trusted read-only tools may reread; use the original idempotency key where deduplicated; reconcile other writes first |
| Result persisted | completed or error, actual value kept | Reuse; no rerun |
| External task alive | running_external with a verifiable handle | Reconnect, wait or cancel; no resubmission |
| Non-idempotent write, not queryable | outcome_unknown with operation details | Reads and investigation allowed; retry or abandon only after the user confirms the risk |
read_only, idempotent and state_probe come from trusted registration and the implementation identity saved at execution, never from model claims or a tool name. General shell, third-party MCP and custom tools default to unknown.
Choosing a recovery mode
| Situation | Mode |
|---|---|
| Owner alive | Reconnect only |
| Death confirmed, verifiable checkpoint | New attempt under the same execution |
| No reliable checkpoint | Take exclusive recovery ownership, fill missing outputs with a stable repair key, end the old turn interrupted, admit a new turn |
- Mutually exclusive, bound to one durable decision, control version and continuation key. Checkpoints must cover committed effects and satisfy permission, wait and safe-point contracts.
- Old executors are confirmed by lease and generation: no repairs when the lease is uncertain or storage unreadable; a dropped connection does not prove death; later writes from the old generation are rejected. Trackable live processes are reconnected, waited for or explicitly cancelled.
- Repairs are repeatable with no side effects. Real results take priority; no usage is fabricated. Late verifiable receipts append as reconciliation events that replace placeholders in later context.
- Only permission, budget, resource or unknown-operation issues need a person; restart alone is no reason for manual Resume. Old unknowns do not block investigation or independent work; related writes keep their restrictions, and recovery turns related to unknown writes start with trusted reads only.
- An old effect audit may stay unresolved while its turn ends
interrupted. Ordinary chat and Goals share this entry.
Request-history repair
| Rule | Holds |
|---|---|
| Pairing | Matches the nearest call by original call id, then converts provider ids. Real outputs win; duplicates use the last saved real record; missing results get deterministic unknown placeholders. |
| Order | Calls and results are adjacent in the request projection, user order intact, original history unchanged. Results without calls are not sent as tool items. |
| Interruption | Interrupted responses keep partial text and a marker, without reusing incomplete reasoning signatures. Ambiguous duplicate call ids in one response are an explicit error. |
| Permission | This conversion grants no permission and cannot replace recovery decisions. |
Permission scope for uncertain effects
| Topic | Rule |
|---|---|
| Scope | Conversation provenance scopes old executions and invoked Jobs, not every execution in an invoked session |
| Read-only investigation | Only the actual built-in read, grep, glob and list functions; names, acceptEdits and plugin declarations do not count |
| Everything else in scope | Needs one-time approval, which bypass, automatic classification and allow rules cannot waive. Approval binds to the new call and the unknown-effect set; a changed set needs fresh approval and erases nothing. Unreadable or corrupt recovery state fails closed. |
| New interactive owner turn in Auto or bypass | Evaluates uncertain effects only in its own execution subtree |
| Nested Runtime | Uses that boundary only when immutable admission proves an owner chat: stored actor is the interactive owner, the integrity-checked payload has the same source, and execution, session and principal match |
| Executor-thread submission | Carries the ContextVars so scope capture checks the same execution. Runtime stays non-interactive and cannot grant approval. |
| Mismatched evidence | Keeps the restriction. Old receipts are never resolved or replayed by this filter. Explicit ask or deny, source constraints, plan mode and exact Page binding still apply. |
State ownership
| Owner | Holds | Does not |
|---|---|---|
| Goal state service | goal_id, revision, objective, acceptance conditions, status, explicit budget, blocking reasons | Hold provider streams or call stacks |
| Plan store (Todo) | Stable item_id, goal_id, revision, status, evidence references | Shrink the objective by deleting items; prove progress by edits |
| Canonical execution | Input origin, permissions, objective attribution, owner generation, turn state, subtasks | Treat interrupted as Goal failure or stopped processes |
| Effect store | Call and implementation identity, input summary, start record, real or synthetic provenance, certainty | Let unknown pass as success or never-run; trust a tool name |
| Usage ledger | Request and attempt identity, attribution, model, tokens, price snapshot, amount, trust status | Infer Goal cost from session totals; present estimates as settled |
Existing stores; no second event platform. Cross-database updates use retryable notifications and unique operation keys, not assumed atomicity. Derived UI and statistics are rebuildable and never overwrite records.
| Goal status group | Values |
|---|---|
| Running | refining, active, running, evaluating |
| Waiting | paused, paused_recoverable, waiting_user, waiting_external |
| Stopped, resumable | blocked, stalled, budget_exhausted, capped, error, and all waiting values |
| Terminal | achieved, impossible, failed, cancelled, cleared |
Defined in programs/tools/planning/goal/state.py. failed is terminal yet resumable. Execution and acceptance live in phase or wait records. A revision or permission change voids old acceptance and continuation reservations; old usage keeps its attribution.
Acceptance
| Topic | Rule |
|---|---|
| At creation | Keep the objective, extract verifiable requirements, ask only if ambiguity changes scope. Each requirement has an evidence checkpoint. Simple tasks may skip Todo; Todo edits never remove requirements. |
Entering verifying | The worker submits a candidate, or required Todos finish unverified. Ordinary turns run no judge. Revision, required Todos, subtasks and related unknown effects are checked first. Completion text is not a fact. |
| Review | Independent read-only turn returns met, unmet or unknown with evidence per requirement. Deterministic requirements read test receipts, file versions and runtime state; semantic ones use model review. Tests keep normal approval and budget. Missing evidence returns to work. |
| Commit | Only the current goal_id, revision and verified result version. Evidence and control versions are rechecked. Controlled artifacts use versions or digests; external facts keep time and receipts. |
| After | Holds as of verification. No monitoring or reopening. Human waivers are explicit revisions with reasons. Acceptance can err. |
| No progress | Judged by results and evidence, not tool count. An automatic turn with no tool call warns the next prompt; a second in a row stops as stalled (IDLE_ROUND_LIMIT 2). |
blocked | Same real blocker recurs across at least three Goal turns with no independent work |
| Waiting | A live handle waits with no idle model turns. Durable waits store work_id, revision, handle, observed version and consumption key. Notifications admit once if intent is run, versions match and no execution is current. Reconciliation wakes at the earliest wait deadline and on run-table changes, then expires or recovers what is due. Pause, cancel or revision voids wakeups but keeps results. A query timeout does not mean the operation stopped. |
Usage and cost
| Topic | Rule |
|---|---|
| Attribution | goal_id, revision, turn_id and request_id fixed before dispatch. Chat after a pause has no old attribution. Subagent and acceptance requests inherit it; each receipt counts once. Retries are new attempts. |
| Streams | Cumulative usage moves a per-attempt watermark. Projections update only after durable writes. Temporary failures retry with the same key. Late receipts stay with the original Goal. |
| Display | Tokens and prices stored separately; price changes do not rewrite history. Estimates, known values and unknowns are separate: "Known $0.42; usage unknown for 1 additional request." |
| Active time | From durable start and stop records, excluding pauses and downtime. A lost executor keeps its last heartbeat and shows a lower bound with an unknown interval. Late usage restarts no timer. An unverifiable explicit time limit stops admission. |
| Budgets | Unlimited by default. With a hard cost budget, unknown prices or usage pause paid admission with a reason. Maximum amount reserved when calculable; otherwise no promise against overspend. Rechecked after ledger reload, before recovery and acceptance. |
| Background Jobs | Goal identity saved at the real caller's admission, restored at start. Cross-session calls keep caller provenance without a cross-session parent. Goal and Job share start and settlement transactions in usage.db; receipts save the Job reservation, so metering rebuilds after restart. Unknown tokens and costs reserve separately; partial data records lower bounds. Expired unstarted reservations cannot dispatch; started requests are not released. Hard budgets accept only audited limits, explicit prices and service tiers. |
| A turn that paused | A reply that paused for an answer or an approval and went on is one reply. Its row counts every provider request and token of the turn, before the pause and after. Cost and the Goal's total come from each request's ledger receipt, written when that request ended, so nothing is charged twice. |
Controls
| Transition | User sees | Execution |
|---|---|---|
| Running → restart → recovering or queued | No Resume click; obstacles show reason, action and Retry. Resume is for user-paused work. | One turn per work item; no blind resend |
| Steps 5/5 → verifying | "5/5 · Verifying", not "Complete" | "Goal completed" only after acceptance |
active → Pause | Automatic continuation stops; "still stopping" shown separately | Blocks admission, cancels current run, undoes nothing |
Unfinished → End → cancelled | "Goal ended", with leftover processes or unknowns | Needs no reconciliation; old runs trigger nothing |
| Pending operation → inspect, query, confirm | Exact call, input summary, time, available checks | Risky retries need the current user; models and page content cannot answer |
- Backend
can_resume,can_verify,can_endand reason codes set buttons; the frontend infers nothing from status. Read failure shows "State temporarily unavailable" with refresh. An empty Todo shows no placeholder. - User input outranks continuation through steer and queue. Keys bind
goal_id, revision and previous committed turn; durable state and generation block stale actions when pause, edit, cancel and admission race.
Goal lock
One lock per conversation orders every change to its Goal: admission, a provider request's budget check, usage refresh, a finished turn's accounting, controls. Two turns of one conversation can run at once (a Goal on one branch, a message on another), so writers meet often.
| Rule | Why |
|---|---|
| Wait in line | A writer queues behind the holder, up to 30 seconds, then gets GoalBusy. Trying once failed a reply whenever two writers met. |
| Nothing slow under the lock | The holder reads and writes Goal state only. The conversation's log is folded before waiting; a turn's tool-call scan and evidence file hashes are taken before the lock. On a 731 MB log a read under the lock took 6 s; the hold is now about 10 ms. |
| A running turn never fails on the lock | If the lock stays held, the turn's request check, elapsed-time steps and verifier reads run without it. Each Goal write is a compare-and-set on its version; one that meets a newer version reads again and is redone, a budget refusal and the conversion of old usage included. Nothing unseen is overwritten and the turn does not fail. |
| A usage refresh never holds a stream | Every usage event of the conversation asks for a refresh, on its provider stream's thread. One refresh per conversation waits in line and covers the ones asked for meanwhile; it reads the ledger after it holds the lock, and gives up after 2 seconds. |
| A Goal's turn is checked against its own branch | Admission refuses a Goal turn only while a foreground turn runs on the Goal's branch. A turn on another branch, selected or not, neither holds the Goal back nor is held by it. A turn continued after a worker restart is checked against its own branch the same way. |
| A finished turn's accounting is not dropped | It is retried at once, then off-thread for about two minutes. A lock that stayed held for a whole wait is not waited for again on the thread that still has the turn to close. The continuation is admitted only after that accounting released the lock. A stopped turn's cancelled reply and resource release never wait for it. |
| A Goal left on an ended turn recovers | Reading an active Goal whose turn is over and unaccounted settles it, in this worker or a later one. A failed turn becomes a resumable pause. |
Codex keeps the Goal in SQLite and starts a continuation only when the thread is idle; DeepSeek harness repairs after taking exclusive access. Taken from both: short exclusive sections over Goal state, and the next turn waits for the previous one's bookkeeping. The lock is an OS file lock, released when its process ends, so no stale owner needs guessing.
Codex keeps one goal per thread and continues it when that thread is idle. A branch is this product's thread, so only the Goal's own branch gates its turns.
A turn that failed
A failure the next turn would not meet again is continued without a click; one it would meet at once waits for a person.
| Case | What happens |
|---|---|
| Transient failure | A provider error, a lost connection, a timeout, a rate limit that asks for at most five minutes, the worker's own fault. The Goal goes on by itself after a wait, at most three failures in a row; a completed turn starts the count over. |
| Failure that repeats at once | A rejected key or missing permission, no credit or a spent quota, a model the plan or region does not serve, a refused address or request, a context that does not fit, a content refusal, a budget refusal, a retry-after over five minutes. The pause and its reason stay; Continue is the person's. |
| Never continued here | A turn the user stopped stays stopped. A turn a restart cut follows automatic recovery. A spent Goal budget waits for a higher limit. A Goal nobody typed (always-on, check-in, scheduled, handoff) is restarted by its Agent's wake, under that Agent's daily budget. |
| The wait | 5 seconds, then 30, then 2 minutes, or the provider's retry-after when that is longer. It is held in process memory: after a restart the next read of the Goal starts it again. The count of failures is saved with the Goal. |
| The next turn | The turn that would have followed a completed one: the failed turn's envelope and branch, the continuation prompt, a queued user message first. If the Goal was continued, edited or ended during the wait, nothing starts. |
| Failed verification turn | The same completion candidate is submitted again from the failed turn, so the next turn verifies instead of doing the work over. When it cannot be verified yet (work still running, an operation with an unknown result), that reason pauses the Goal. A repeated notice of the failed turn judges nothing. |
Codex continues an active goal whenever its thread is idle and stops once the control plane sets usage_limited or budget_limited. Claude Code keeps the Goal after a transient error and clears it on unrecoverable auth, balance, uncompactable overflow or model errors.
Taken from both: a transient failure costs no click, an account or limit failure stops. Added here: the growing wait and the cap of three, because a turn can fail before doing any work.
Goal in the transcript
- Only an explicitly activated Goal produces UI. Starting, running, pausing and verifying add no cards; the composer shows the current Goal only.
- At termination one compact, clickable status row stays at the ending anchor and opens the read-only historical details. Each row carries its own snapshot; a later Goal cannot replace it. Saved with Goal state under optimistic concurrency.
- Success: animated Lucide check and "Goal achieved in 9m 42s", from active elapsed time. Missing time is not zero; interrupted time keeps its lower-bound label. Other endings show their status. Nothing is inferred from assistant text or Todo counts.
- Canonically identified verifier messages are internal; no assessment text, evidence id or raw report enters chat.
Projection delivery
| Rule | Holds |
|---|---|
| Consumers | DAG, job, workflow and UI consumers get derived events from a durable outbox. |
| Order | Before each consumer, the dispatcher validates persisted owner, lease and claim attempt; acknowledgement and failure use the same attempt. |
| Owner | A reused owner id cannot settle a newer claim. Expired work stays recoverable. |
No exactly-once external effects, and a callback already running at lease expiry is not stopped: consumers stay idempotent and version-aware.
Where recovery lives
Under openprogram/ | Behaviour | Boundary |
|---|---|---|
runtime/execution/recovery/startup.py, control/recovery.py | Owner checks, canonical and wait-receipt recovery, projection redelivery | Unconfirmed effects can put an execution in reconciliation_required; operation reconciliation is separate from whether the session continues |
runtime/execution/recovery/restart.py | Pause intent, deduplicated commands, resource admission. Only a live turn of the same conversation holds continuation back. A later turn supersedes it, except a scheduled task's run, which is on its own branch: intent settles superseded, execution stays paused for explicit Continue. | No expiry does not authorize replaying unresolved effects |
programs/tools/planning/goal/chat.py, runtime/execution/projections/dag.py | Goals do not pause for downtime or projection repair. Completion notifications persist before execution finishes. | Old records without provenance keep explicit Resume |
runtime/jobs/runner/recovery.py, execution/control/waits.py | Job recovery, deferred inbox, durable answers, deduplicated continue | A saved Job is not a recovered child agent; some chat restart paths exclude spawn and merge |
runtime/execution/waits.py | Durable waits; live waits cancel when their producer disappears | Expired questions are kept and reconfirmed |
models/usage/context.py, event.py | Attribution and ledger | Attribution and keys fixed before requests; missing is not zero |
programs/applications/browser/pages.py, host/resources/terminal.py, Web session store | Resource identity, recovery state, projections | Reconnection, invalidation and new identity accepted per resource; frontend reconnect cannot cause execution |
A paused UI does not prove history was deleted; existing records do not prove continuation is possible.
What other harnesses taught
| Reference | Verified behaviour | Here |
|---|---|---|
| Codex repair, idle continuation | Missing outputs become aborted; Goals continue through thread-idle admission | Adopt chat continuation, pairing repair, state verification. aborted does not reverse effects. |
| Claude Code recovery, evaluation | No automatic rerun; a small model evaluates from conversation. Official contracts only. | Adopt no blind reruns and independent review, without evaluating every turn |
| OpenCode history, usage | Pending calls become interruption errors; usage recorded at step end | Adopt continuable history and per-request usage; Todo does not decide completion |
| OpenClaw repair | Matches results, synthesizes missing, handles duplicates | Adopt projection repair without overwriting records; heartbeat is not Goal |
| DeepSeek harness closure, continuation | Repairs after exclusive access; separates not-started from unknown; manual reactivation | Adopt layered state and idempotent repair; not its round cap or manual reactivation |
Reference source is pinned to inspected versions; their tests were not run. These are choices here, not claims of equal guarantees.
Codex's App Server docs and extension source load active Goals on resume and continue while idle. That does not establish recovery from arbitrary exits or tool-process deaths, so continuation here is its own contract.
Required acceptance
| Stage | Must demonstrate |
|---|---|
| Unified decisions: startup, restart, control recovery, JobRunner, DAG projections | Requests, active Goals and subtasks recover; user-paused work does not. No hidden window or projection-layer state rewrites; unique admission and current permissions preserved. |
Execution: runtime/conversation/production_driver, context, effects, waits, resources | Kill real child processes before dispatch, after start and after result persistence. Repair once, keep real results, continue chat. Late old-owner writes, live shells and unknown writes are not wrongly retried. |
Goal continuation: programs/tools/planning/goal, HTTP, WS, TUI, ACP | Resume replays no tools. Double clicks, repeated events and edit-pause races make no duplicates. Old revisions cannot complete new objectives. |
| Evidence | Reject unfinished items, missing evidence, failing tests, stale results and related unknowns; commit achieved once. Verification cannot raise permissions. |
Attribution: models/usage, Goal projections | Duplicate and out-of-order usage, concurrent subtasks, cumulative streams, retries, ledger faults, late receipts. Unknown is not zero; exceeded budgets stop paid requests. |
| Compatibility | Old Goals readable; unknown effects migrate without guessing; controls, restart and cost verified in the App |
Each stage starts with a public-entry failure reproduction. Source, automated tests, local App and remote release are distinct evidence.
Restart failure matrix
Work is created through public chat, Goal, Job, approval and control entries, with real termination on isolated storage. Never terminate the user's current work.
- Events
- Frontend reload, App exit, graceful and forced worker stop, long downtime, crash during recovery. Host restart through process-identity change; an actual OS reboot is unverified.
- Interruption points
- Around input acceptance, provider requests, tool dispatch, result commit, parent-child delivery, all Todos done, completion commit, usage persistence
- Concurrency
- Several sessions recover together: fair queueing, shared quotas, one owner, no duplicates. Pause, End, permission changes and new input win.
- Live and unknown
- Live children only reconnect; unknown writes only get investigation. Approvals consumed once. Late results keep identity.
- Faults
- Unavailable databases, broken migrations, missing credentials or directories, changed tool versions, lost projection events: explicit states and recoverable actions
Nested-scope acceptance
An old interrupted effect followed by a new owner activation through permission_decision and real nested Runtime gates: Auto and bypass, exact current and descendant uncertainty, mismatched provenance, rules, real subprocess Page access.
Goal implementations compared
A native Goal stores objective state and uses it after ordinary turns to decide whether to start another. Todo, Plan, Task and Cron alone are not Goals. General-framework baselines: OpenAI Agents SDK, LangGraph, AutoGen, CrewAI.
| Level | Input | Progress | Termination | Across turns | Example |
|---|---|---|---|---|---|
| Task input | User message | None required | Model stops | No | Ordinary turn |
| Progress ledger | Task and items | Todo, for prompting and UI | Not decided by it | No | OpenCode Todo |
| Graph termination | Graph state | Application | Edge or condition | Application | LangGraph, AutoGen |
| Persisted controller | Objective | Usage, status | Agent declares | When idle | Codex |
| Evaluator loop | Goal spec | Evidence | Independent evaluator | If incomplete | OpenProgram, Claude Code, Hermes |
| Native Goal | State | Work and judgment | Continuation and waiting |
|---|---|---|---|
| OpenProgram | Versioned snapshot, goal and run id, compare-and-set | Worker, then independent read-only judge | Controller and waits, restart recovery |
| Codex | SQLite ThreadGoal, typed status, usage | Worker self-reports with update_goal | Idle controller, pause, resume, limits |
| Claude Code | Session prompt, kept on resume | Stop-hook small model, no tools | Prevent stop or clear; defers for background tasks |
| Hermes Agent | GoalState and contract, gates, waits | Mechanical gates, then judge | Queue, wait barrier, event wakeup |
Comparison matrix
| System | Goal | Next turn | Completion | Budget | Waiting | Persistence |
|---|---|---|---|---|---|---|
| Codex | SQLite ThreadGoal with goal_id | Thread-idle lifecycle starts one | update_goal(complete|blocked), no judge | Optional tokens; tokens and time tracked | Controls pause, resume, usage limit; blocked needs a three-turn audit | Resume restores the controller |
| Claude Code | One condition per session | Prompt Stop hook supplies the reason | Small model: not met, met, impossible; no tools | None structured; outer turns and USD | Defers for background tasks; idle check-ins with backoff | Resume restores the condition, resets baselines |
| Hermes Agent | GoalState, contract, subgoals, gates, barrier | Queues a user-role continuation | Gates, then done, blocked, continue or wait | 20 turns; per-gate timeout and retry | PID, process session or duration; users first | SessionDB.state_meta; compression migration |
| OpenCode | User task and SQLite Todo | Same turn, by finish reason | Model stops calling tools | steps, unlimited by default | Question and permission in turn; no pause | Sessions, messages, todos; no controller |
| OpenClaw | Separate jobs, heartbeat scratch, commitments, background tasks | Scheduler, event or completion | Per-run result, exit code or stop | Per-run timeout and tools | Scheduled waits, event wakeup, delivery, backoff | Definitions, state and history survive gateway restarts |
Key property. Codex: most complete control plane. Claude Code: smallest surface, reuses hooks. Hermes: contracts, gates and waits. OpenCode: a progress ledger, not a Goal. OpenClaw: long-term scheduling.
When a task cannot finish
| System | Outcome | Hard stop | Can still loop | Gap |
|---|---|---|---|---|
| Codex | blocked; control plane may set paused, usage_limited, budget_limited, complete | Optional tokens; three-turn blocker audit | Yes, without a budget or declaration | Self-report only |
| Claude Code | impossible clears; no tool progress stops but keeps the Goal | 8 consecutive Stop preventions; 3 idle check-ins; outer turns, USD | Yes, if tools continue and verdict is not met | Evaluator cannot inspect files, tests or state |
| Hermes Agent | blocked or wait; turn limit | 20 turns; unchanged workspace skips failed gates; waits use no turns | Bounded; low-value repeats possible | No total token or cost budget confirmed |
| OpenCode | Turn ends when tools stop; Todo starts nothing | steps | Within one turn | No cross-turn contract |
| OpenClaw | Run succeeds, fails or times out | Timeout, tool budget, backoff | Only as Cron is configured | No objective evaluator |
Semantic evaluators alone guarantee no convergence. Reliable controllers need hard budgets, evidence-based stall detection, explicit blocked, impossible and waiting categories, and waits released only by events. A tool call proves action, not progress: compare new evidence, passed gates, unfinished items and external state. Waits consume no turns.
Codex
| Aspect | Behaviour |
|---|---|
| State | ThreadGoal: thread_id, goal_id, objective, status, token budget, tokens and time used, timestamps. Status is active or an outcome above. One unfinished Goal per thread. |
| Control | Model tools create, read, or set complete or blocked. User and system control pause, resume and limits. App server: thread/goal/set|get|clear and notifications. |
| Concurrency | Mutation and idle continuation share a semaphore; expected_goal_id stops an old turn updating a new Goal. Usage accumulates against a baseline at turn end. Resume re-registers only when active. |
| Limits | The worker runs the completion audit. Tracks elapsed time, but has no time budget or external-process wait state. |
Sources: thread_goal.rs, spec.rs, runtime.rs, continuation.md, app-server README
Claude Code
Source is not public; only official contracts are recorded.
| Aspect | Behaviour |
|---|---|
| Entry | /goal <condition>: one per session, a new value replaces and starts a turn; permission mode unchanged. Specializes a session-scoped prompt Stop hook. |
| Stop hook | A Stop hook may return decision:"block" and reason; a prompt hook returns ok, reason, impossible. stop_hook_active prevents recursion. |
| Evaluation | No evaluation while background shells or subagents run. Consecutive turns without tool progress stop looping but keep the Goal for the next prompt. |
| Errors and limits | Unrecoverable auth, balance, uncompactable overflow or model errors clear the Goal; transient ones keep it. Turn and time terms can go in the condition; print mode has --max-turns and --max-budget-usd. |
| Evidence | The evaluator relies on the worker placing evidence in the transcript. |
Sources: /goal, Stop hook, CLI, task tools
Hermes Agent
| Aspect | Behaviour |
|---|---|
| Entry and state | Entry /goal, /subgoal; persisted on each transition in state_meta[goal:session]. GoalState stores status, turn budget, judge-failure counters, subgoals, barrier, contract, gates. |
GoalContract | GoalContract: outcome, verification, constraints, boundaries, stop_when, injected into worker and judge. |
GoalGate | GoalGate runs shell checks before the judge; failures skip it and provide bounded output. Records attempts, exit code, output tail and workspace fingerprint. |
| Subgoals and sessions | A subgoal is an added condition; it does not restart the main Goal. CLI and gateway share GoalManager, without changing prompts or toolsets. Compression moves the Goal to the new session id. |
| Evidence base | The local snapshot lacks contracts, gates and barriers, so those rest on public upstream source. |
Sources: goals.py, guide, conversation_loop.py, todo_tool.py
OpenCode and OpenClaw
OpenCode
| Aspect | Behaviour |
|---|---|
| Loop | SessionPrompt.run exits on a non-tool-call finish with no unhandled calls. Each round resolves profile and tools and handles compaction and subtasks. The last step injects a max-steps hint. |
| Plan | Plan is an agent profile restricting edits, not Goal state. |
| Todo | Todo: content, status, priority, in SQLite by session, publishes todo.updated. todowrite replaces the list; disabled for subagents by default. Usable as a progress projection only. |
Sources: prompt.ts, todo.ts, agent.ts, todowrite, agents
OpenClaw
| Aspect | Behaviour |
|---|---|
| Automation jobs | id, name, enabled, schedule, session target, wake mode, typed payload, delivery, failure alert, run state. Payloads: system event, agent turn, command, script. Targets: main, current, isolated, named. Execution and delivery results are separate. |
| Heartbeat | a system monitor that reads scratch or HEARTBEAT.md and skips the model when nothing is due. Structured tasks: name, interval, prompt. |
| Commitments | inferred promises with due window, confidence, status, attempts, delivery scope. |
| Use here | Best as a reference for external waiting: a Goal controller could bind automation for a future time or event, then resume on it. |
Sources: types.ts, heartbeat-runner.ts, commitments, automation, heartbeat, tasks
Implementation status
| Part | Status |
|---|---|
| Implemented | Chat Goal continuation; no default round or recovery-expiry limit; history pairing; unknown-effect approval; deduplicated new turns; restricted Resume; incompatible-checkpoint handling; Job continuation with original authorization; independent acceptance; request attribution; late and partly unknown usage; hard-budget reservations; joint settlement; backend action conditions; explicit Verify; automatic continuation after a transient failed turn; crash-time lower bounds; projection claim validation; transcript row; nested-scope correction |
| Process evidence | Interruption matrices for chat and Goals; macOS live-background-process reconnection |
| Not established | Windows process survival, OS restart, cross-host takeover, general external-event scheduling. Skipped tests prove no capability. |
| Outside this design | Cross-host leases, a general workflow engine, an independent audit repository, bulk rewrite of historical costs or effects, exactly-once external operations, a judge on every turn |