OpenProgram Docs

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 stepWhat happens
Save the objectiveOriginal objective, completion conditions, permission scope, explicit budget
Work through chatThe agent keeps a Todo and uses existing tools and approvals
Check at turn endSettle usage; continue, wait, pause or verify
AcceptIndependent 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_goal on 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_goal on chat_ack, before the transcript row arrives. A /goal from a New chat draft runs in that draft. /goal status and 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 facts run intent, controls, messages, checkpoints, effects, waits Confirm ownership reconnect live executors, fence dead ones by generation Repair context merge real results, fill missing tool outputs Decide user stops first, then approval, permission, budget, resources, unknowns Admit once fair scheduling, quotas, stable continuation key Restore interface canonical snapshots, ordered events
  1. Load factsrun intent, controls, messages, checkpoints, effects, waits
  2. Confirm ownershipreconnect live executors, fence dead ones by generation
  3. Repair contextmerge real results, fill missing tool outputs
  4. Decideuser stops first, then approval, permission, budget, resources, unknowns
  5. Admit oncefair scheduling, quotas, stable continuation key
  6. Restore interfacecanonical snapshots, ordered events
Run intent and shutdown
TopicRule
Durable run_intentBuilds on existing admission, command and restart intent. Clients are acknowledged only after the request is saved.
What it recordswork_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
DefaultAuthorized 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, reloadOnly disconnects. "Quit and stop all tasks" persists a stop intent.
App exit, upgrades, worker crashes, machine restartsNot Pause. Graceful shutdown stops admission and saves controls and checkpoints; forced shutdown recovers from the last commit.
Unacknowledged client draftsNot submitted requests
execution.auto_resume_window_seconds-1 by default (no expiry), 0 opts out; existing finite deadlines are not extended
Continuation checksRechecks 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 reasonsStay paused with an explanation
Stage rules
StageRule
LoadAlso usage and projection cursors. Read or migration failure shows recovery failure and clears nothing.
OwnershipOne host per work item; single-host recovery never becomes cross-host takeover
RepairResume from a complete safe checkpoint; otherwise a new turn with the same work_id, without re-appending user input
DecideRunnable becomes queued; dependency waits become waiting; faults expose retryable reasons. All persisted in one control service.
AdmitKey from work_id, control version and predecessor commit. No duplication window between admission and consuming intent; cross-database steps converge through a retryable outbox.
InterfaceShows 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_terminal submits 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 restartAfter restartMust hold
Accepted request, unscheduledRequeue in input order, admit onceDeduplicate by client request id; late retries cannot override Stop
Interrupted model streamKeep committed text and tool results, label incomplete output, request the restNo fabricated whole response; a new attempt can cost more
Active Goal, working or between turnsLoad objective, Todo, evidence, budget, run intent; continue work or acceptanceIdle active Goals are not skipped; 5/5 only triggers acceptance
User Pause, End or StopStays paused or endedPersisted when accepted; notifications cannot release it; "still stopping" is separate from intent
Pending approval or answerRestore question, summary and scope; consume a committed answer onceRestart is not approval; changed implementation, arguments or permissions void old approval
Parent waiting for subtasksRestore identities, outputs, inbox cursors, waits; parent continues on terminal stateReconnect live children, never recreate finished ones; user pause reaches children in scope, not independent tasks
External process, terminal, remote jobQuery by host, process-start identity or handle; keep observing if alivePID alone is insufficient; uncertain stays unknown; no resubmission
Browser, MCP, temporary resourceVerify identity on reconnection; report invalidation; create new only if authorizedForms, logins, JS memory and REPL variables are not guaranteed; a new tab cannot impersonate the old one
Compaction or message write in progressUse last committed history and summaryPartial tool arguments never run; current permissions apply; unavailable dependencies shown
Result written, notification undeliveredReplay projections and inbox delivery, no rerunVersions prevent UI rollback; no double charge in parent aggregation
Usage receipt absent or stream-onlyReconcile by provider attempt, deduplicateUnobtainable 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 interruptionFact after recoveryNext
Intent saved, dispatch unrecordednot_started; holds only because every dispatch is recorded firstCall again under current permissions if still needed
Dispatch recorded, no resultoutcome_unknownTrusted read-only tools may reread; use the original idempotency key where deduplicated; reconcile other writes first
Result persistedcompleted or error, actual value keptReuse; no rerun
External task aliverunning_external with a verifiable handleReconnect, wait or cancel; no resubmission
Non-idempotent write, not queryableoutcome_unknown with operation detailsReads 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
SituationMode
Owner aliveReconnect only
Death confirmed, verifiable checkpointNew attempt under the same execution
No reliable checkpointTake 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
RuleHolds
PairingMatches 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.
OrderCalls and results are adjacent in the request projection, user order intact, original history unchanged. Results without calls are not sent as tool items.
InterruptionInterrupted responses keep partial text and a marker, without reusing incomplete reasoning signatures. Ambiguous duplicate call ids in one response are an explicit error.
PermissionThis conversion grants no permission and cannot replace recovery decisions.
Permission scope for uncertain effects
TopicRule
ScopeConversation provenance scopes old executions and invoked Jobs, not every execution in an invoked session
Read-only investigationOnly the actual built-in read, grep, glob and list functions; names, acceptEdits and plugin declarations do not count
Everything else in scopeNeeds 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 bypassEvaluates uncertain effects only in its own execution subtree
Nested RuntimeUses 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 submissionCarries the ContextVars so scope capture checks the same execution. Runtime stays non-interactive and cannot grant approval.
Mismatched evidenceKeeps 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

OwnerHoldsDoes not
Goal state servicegoal_id, revision, objective, acceptance conditions, status, explicit budget, blocking reasonsHold provider streams or call stacks
Plan store (Todo)Stable item_id, goal_id, revision, status, evidence referencesShrink the objective by deleting items; prove progress by edits
Canonical executionInput origin, permissions, objective attribution, owner generation, turn state, subtasksTreat interrupted as Goal failure or stopped processes
Effect storeCall and implementation identity, input summary, start record, real or synthetic provenance, certaintyLet unknown pass as success or never-run; trust a tool name
Usage ledgerRequest and attempt identity, attribution, model, tokens, price snapshot, amount, trust statusInfer 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 groupValues
Runningrefining, active, running, evaluating
Waitingpaused, paused_recoverable, waiting_user, waiting_external
Stopped, resumableblocked, stalled, budget_exhausted, capped, error, and all waiting values
Terminalachieved, 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

TopicRule
At creationKeep 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 verifyingThe 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.
ReviewIndependent 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.
CommitOnly 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.
AfterHolds as of verification. No monitoring or reopening. Human waivers are explicit revisions with reasons. Acceptance can err.
No progressJudged 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).
blockedSame real blocker recurs across at least three Goal turns with no independent work
WaitingA 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

TopicRule
Attributiongoal_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.
StreamsCumulative 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.
DisplayTokens 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 timeFrom 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.
BudgetsUnlimited 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 JobsGoal 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 pausedA 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

TransitionUser seesExecution
Running → restart → recovering or queuedNo 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 → PauseAutomatic continuation stops; "still stopping" shown separatelyBlocks admission, cancels current run, undoes nothing
Unfinished → End → cancelled"Goal ended", with leftover processes or unknownsNeeds no reconciliation; old runs trigger nothing
Pending operation → inspect, query, confirmExact call, input summary, time, available checksRisky retries need the current user; models and page content cannot answer
  • Backend can_resume, can_verify, can_end and 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.

RuleWhy
Wait in lineA 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 lockThe 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 lockIf 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 streamEvery 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 branchAdmission 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 droppedIt 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 recoversReading 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.

CaseWhat happens
Transient failureA 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 onceA 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 hereA 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 wait5 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 turnThe 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 turnThe 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

RuleHolds
ConsumersDAG, job, workflow and UI consumers get derived events from a durable outbox.
OrderBefore each consumer, the dispatcher validates persisted owner, lease and claim attempt; acknowledgement and failure use the same attempt.
OwnerA 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/BehaviourBoundary
runtime/execution/recovery/startup.py, control/recovery.pyOwner checks, canonical and wait-receipt recovery, projection redeliveryUnconfirmed effects can put an execution in reconciliation_required; operation reconciliation is separate from whether the session continues
runtime/execution/recovery/restart.pyPause 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.pyGoals 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.pyJob recovery, deferred inbox, durable answers, deduplicated continueA saved Job is not a recovered child agent; some chat restart paths exclude spawn and merge
runtime/execution/waits.pyDurable waits; live waits cancel when their producer disappearsExpired questions are kept and reconfirmed
models/usage/context.py, event.pyAttribution and ledgerAttribution and keys fixed before requests; missing is not zero
programs/applications/browser/pages.py, host/resources/terminal.py, Web session storeResource identity, recovery state, projectionsReconnection, 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

ReferenceVerified behaviourHere
Codex repair, idle continuationMissing outputs become aborted; Goals continue through thread-idle admissionAdopt chat continuation, pairing repair, state verification. aborted does not reverse effects.
Claude Code recovery, evaluationNo automatic rerun; a small model evaluates from conversation. Official contracts only.Adopt no blind reruns and independent review, without evaluating every turn
OpenCode history, usagePending calls become interruption errors; usage recorded at step endAdopt continuable history and per-request usage; Todo does not decide completion
OpenClaw repairMatches results, synthesizes missing, handles duplicatesAdopt projection repair without overwriting records; heartbeat is not Goal
DeepSeek harness closure, continuationRepairs after exclusive access; separates not-started from unknown; manual reactivationAdopt 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
StageMust demonstrate
Unified decisions: startup, restart, control recovery, JobRunner, DAG projectionsRequests, 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, resourcesKill 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, ACPResume replays no tools. Double clicks, repeated events and edit-pause races make no duplicates. Old revisions cannot complete new objectives.
EvidenceReject unfinished items, missing evidence, failing tests, stale results and related unknowns; commit achieved once. Verification cannot raise permissions.
Attribution: models/usage, Goal projectionsDuplicate and out-of-order usage, concurrent subtasks, cumulative streams, retries, ledger faults, late receipts. Unknown is not zero; exceeded budgets stop paid requests.
CompatibilityOld 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.

LevelInputProgressTerminationAcross turnsExample
Task inputUser messageNone requiredModel stopsNoOrdinary turn
Progress ledgerTask and itemsTodo, for prompting and UINot decided by itNoOpenCode Todo
Graph terminationGraph stateApplicationEdge or conditionApplicationLangGraph, AutoGen
Persisted controllerObjectiveUsage, statusAgent declaresWhen idleCodex
Evaluator loopGoal specEvidenceIndependent evaluatorIf incompleteOpenProgram, Claude Code, Hermes
Native GoalStateWork and judgmentContinuation and waiting
OpenProgramVersioned snapshot, goal and run id, compare-and-setWorker, then independent read-only judgeController and waits, restart recovery
CodexSQLite ThreadGoal, typed status, usageWorker self-reports with update_goalIdle controller, pause, resume, limits
Claude CodeSession prompt, kept on resumeStop-hook small model, no toolsPrevent stop or clear; defers for background tasks
Hermes AgentGoalState and contract, gates, waitsMechanical gates, then judgeQueue, wait barrier, event wakeup
Comparison matrix
SystemGoalNext turnCompletionBudgetWaitingPersistence
CodexSQLite ThreadGoal with goal_idThread-idle lifecycle starts oneupdate_goal(complete|blocked), no judgeOptional tokens; tokens and time trackedControls pause, resume, usage limit; blocked needs a three-turn auditResume restores the controller
Claude CodeOne condition per sessionPrompt Stop hook supplies the reasonSmall model: not met, met, impossible; no toolsNone structured; outer turns and USDDefers for background tasks; idle check-ins with backoffResume restores the condition, resets baselines
Hermes AgentGoalState, contract, subgoals, gates, barrierQueues a user-role continuationGates, then done, blocked, continue or wait20 turns; per-gate timeout and retryPID, process session or duration; users firstSessionDB.state_meta; compression migration
OpenCodeUser task and SQLite TodoSame turn, by finish reasonModel stops calling toolssteps, unlimited by defaultQuestion and permission in turn; no pauseSessions, messages, todos; no controller
OpenClawSeparate jobs, heartbeat scratch, commitments, background tasksScheduler, event or completionPer-run result, exit code or stopPer-run timeout and toolsScheduled waits, event wakeup, delivery, backoffDefinitions, 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

SystemOutcomeHard stopCan still loopGap
Codexblocked; control plane may set paused, usage_limited, budget_limited, completeOptional tokens; three-turn blocker auditYes, without a budget or declarationSelf-report only
Claude Codeimpossible clears; no tool progress stops but keeps the Goal8 consecutive Stop preventions; 3 idle check-ins; outer turns, USDYes, if tools continue and verdict is not metEvaluator cannot inspect files, tests or state
Hermes Agentblocked or wait; turn limit20 turns; unchanged workspace skips failed gates; waits use no turnsBounded; low-value repeats possibleNo total token or cost budget confirmed
OpenCodeTurn ends when tools stop; Todo starts nothingstepsWithin one turnNo cross-turn contract
OpenClawRun succeeds, fails or times outTimeout, tool budget, backoffOnly as Cron is configuredNo 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
AspectBehaviour
StateThreadGoal: 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.
ControlModel 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.
ConcurrencyMutation 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.
LimitsThe 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.

AspectBehaviour
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 hookA Stop hook may return decision:"block" and reason; a prompt hook returns ok, reason, impossible. stop_hook_active prevents recursion.
EvaluationNo evaluation while background shells or subagents run. Consecutive turns without tool progress stop looping but keep the Goal for the next prompt.
Errors and limitsUnrecoverable 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.
EvidenceThe evaluator relies on the worker placing evidence in the transcript.

Sources: /goal, Stop hook, CLI, task tools

Hermes Agent
AspectBehaviour
Entry and stateEntry /goal, /subgoal; persisted on each transition in state_meta[goal:session]. GoalState stores status, turn budget, judge-failure counters, subgoals, barrier, contract, gates.
GoalContractGoalContract: outcome, verification, constraints, boundaries, stop_when, injected into worker and judge.
GoalGateGoalGate runs shell checks before the judge; failures skip it and provide bounded output. Records attempts, exit code, output tail and workspace fingerprint.
Subgoals and sessionsA 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 baseThe 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

AspectBehaviour
LoopSessionPrompt.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.
PlanPlan is an agent profile restricting edits, not Goal state.
TodoTodo: 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

AspectBehaviour
Automation jobsid, 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.
Heartbeata system monitor that reads scratch or HEARTBEAT.md and skips the model when nothing is due. Structured tasks: name, interval, prompt.
Commitmentsinferred promises with due window, confidence, status, attempts, delivery scope.
Use hereBest 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

PartStatus
ImplementedChat 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 evidenceInterruption matrices for chat and Goals; macOS live-background-process reconnection
Not establishedWindows process survival, OS restart, cross-host takeover, general external-event scheduling. Skipped tests prove no capability.
Outside this designCross-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

Goals in chat

Last updated · 2026-11-25