Repository navigation
feat(goal-driver): completion contracts, wait barriers, and an optional completion judge - #103586
100yenadmin wants to merge 61 commits into
Conversation
Mirrors ExecApprovalManager: synchronous register, async promise parks the asking tool, resolve/expire/list, emitter hooks for gateway broadcast+delivery. No default timeout (a human may be asleep); explicit expiresAtMs honored.
Structured question (1-3 items, 2-4 options, Recommended-first, auto 'Other'), hard input validation rejecting unknown fields, registers with the global QuestionManager and parks on its promise until any surface answers. Registered unconditionally in the core tool directory (human-in-the-loop, read-only).
…s (U3)
- QuestionResolveParams/QuestionListParams protocol schemas + validators
- question.list (visibility-filtered) and question.resolve gateway handlers
- question.pending/resolved/expired events; manager emitter bound to the
persistent gateway broadcast at startup so the tool's lifecycle reaches
Control UI and channels from outside any request context
- wire-contract integration test asserting the exact {id,answers:{[id]:{text}}}
param shape crosses the client<->gateway seam; drifted param names FAIL
- rename __resetGlobalQuestionManagerForTest -> resetGlobalQuestionManagerForTest (no-underscore-dangle); drop unused protocol re-exports; unknown->GatewayClient double-cast + remove redundant String() in the wire-contract test.
…estions (U5) Kills the hang-trap: /answer <n|text> resolves the session's pending ask_user_question via the process-global QuestionManager, reusing the shared harness answer parser (numbered select, free-text Other, multi-part 'header: answer' lines). Authorized-sender gated; looks up live registrations (no stale session read). Adds the remote-agent scoping caveat comment at the tool registration site (coordinator-approved).
…sweep (U2) Completes U2: a core-owned SessionEntry.pendingQuestion slot (goal-slot precedent, one-line reserved-slot addition) written when ask_user_question registers and cleared when it resolves/expires. On gateway startup a sweep emits question.expired for orphaned breadcrumbs (whose in-memory record died with the previous process) so no Control UI card or channel prompt silently hangs after a restart. Best-effort store writes; back-compat safe (additive optional field). Tests: record/clear, id-guarded clear, pure collect, restart sweep emits+clears, no-op for sessions that never asked.
Telegram: buildQuestionInlineKeyboard -> inline keyboard; each option is a native-command callback running /answer <n> (existing tgcmd: routing), plus a free-text Other button. Slack: buildQuestionAnswerBlocks builds a portable InteractiveReply (callback-value buttons, since Slack gates command-type buttons to exec-approval commands) rendered via the existing buildSlackInteractiveBlocks. Both route clicks to the shared /answer handler. Single-question prompts only; multi-part uses the numbered /answer text fallback. Tests assert exact payload shapes on both channels. Note: the question.pending -> deliver-to-channel forwarder wiring (subscribe + send the rendered buttons to the turn-source chat) remains follow-up; /answer already answers on these channels as text today.
- app/question-card.ts: parse question.pending/list/resolved payloads + queue store - components/question-card.ts: Lit card modelled on exec-approval — numbered options with a Recommended badge on the first, per-question groups, free-text Other input, submit -> question.resolve - overlays.ts: subscribe question.pending/resolved/expired, refresh via question.list on connect, submitQuestionAnswers over the gateway - app-host.ts: mount <openclaw-question-card> beside the exec-approval prompt - i18n: question.* keys in en.ts, propagated to all locales (ui:i18n:sync) Gates: ui:i18n:check, ui:build, ui vitest (store 5 + overlays 3 + exec 25), full pnpm lint — all green.
…(U6) - harness/question-bridge.ts: registerAgentHarnessQuestion adapter registers harness questions with the global QuestionManager and returns a wait promise (harness-shaped answers) + cancel() to dismiss the pending question. - plugin-sdk/agent-harness-runtime: export the adapter + manager accessor/reset. - codex user-input-bridge: on requestUserInput, ALSO register with the manager so it renders as a Control UI card / channel buttons; whichever resolves first — a structured question.resolve OR the legacy next-free-text reply — wins, and resolvePending cancels (expires) the other. Abort also dismisses the question. - race test: structured-wins, free-text-wins (expires the card), abort-dismisses.
…ttons (U5c) - infra/question-forwarder.ts: on question.pending, resolve the record's turn-source target and push a ReplyPayload (question text + option buttons) via the durable outbound path (sendDurableMessageBatch) — reusing the exec-approval delivery route, not a new one. Per-channel button contract matching the standalone renderers: Telegram command-action (/answer <n> native-command callback), Slack callback-action (Slack gates command buttons to approvals). Deduped by record id (pushed once; not re-pushed on reconnect/replay), cleared on resolve/expiry. - question.ts bindQuestionManagerEmitter composes the forwarder sink alongside the broadcast emitter; server.impl wires it at startup. - Codex questions register without turnSourceChannel, so the forwarder no-ops for them (no double delivery) — the codex bridge delivers its own prompt. Tests: telegram push payload, slack push payload, no-turn-source no-op, dedupe. Gates: core+core-test tsgo 0, full pnpm lint 0, touched suites green.
…ls (U1) Core-owned plan-state slot on the session entry (goal-slot precedent): inactive|planning|pending_approval, with a plan-state module mirroring goals.ts. enter_plan_mode flips to planning; exit_plan_mode persists the plan doc under ~/.openclaw/agents/<id>/plans/, requests approval through PR-A's QuestionManager (2-option approve/keep-planning + auto-Other feedback), and returns approved/revise. No parallel approval path. Migration/roundtrip + lifecycle tests included.
…all choke point (U2) Core policy inside runBeforeToolCallHook (skill-workshop core-policy precedent): when the session plan-state is planning|pending_approval, veto every tool not on the read-only allowlist (read/ls/grep/find/search/fetch/update_plan/ask_user_question/enter|exit_plan_mode /read-only session introspection; exec/bash only for read-only command prefixes). Default-deny for unknown/plugin/MCP tools; mutation/read suffix patterns for MCP; dangerous-flag + shell- operator rejection ported from the Smarter-Claw 156-case parity gate. Subagent spawn is blocked (a child runs outside the gate). Deny messages point at exit_plan_mode. Choke-point verified: every in-session dispatch path (built-in incl. exec, plugin/MCP-backed, catalog, code-mode, client tools) funnels through runBeforeToolCallHook with sessionKey+config; the only ctx-less path (ACPX MCP bridge exposing tools externally) is not in-session dispatch. Includes the NON-NEGOTIABLE adversarial bypass suite (exec/MCP/plugin/subagent-spawn all vetoed through the real hook) + gate matrix.
update_plan is now the live plan-mode checklist for every model; tools.experimental.planTool becomes a kill-switch (false removes it, true force-enables). Explicit allowlist still wins; explicit deny of update_plan opts out. update_plan tool description carries plan-mode checklist semantics (keep exactly one step in_progress, then exit_plan_mode). Gating tests rewritten to the default-on contract.
…n summary (U5) /plan show|status (state + summary), /plan accept|approve and /plan reject|revise <feedback> resolve the pending PR-A approval question via the process-global QuestionManager (turn-source routing preserved; the parked exit_plan_mode tool makes the state transition, avoiding the dup-approval bug class), /plan enter and /plan exit aliases. streaming.ts case plan now renders a structured multi-step summary (count + first steps) through the edit-in-place progress-line correlation key. Plan-state module exported from the sessions barrel.
…shot (U4 backend seam) The plan slot rides the same session event payload as goal (state chip + summary), so the Control-UI plan panel reads plan-mode state and the pending-approval flag without a new gateway method — approve/reject reuse the existing question.pending/question.resolve events (no new approval path) and the live checklist reuses the existing stream:plan broadcast. GatewaySessionRow carries plan; the builder emits an explicit null when inactive so clients drop the chip on merge. NOTE: the Lit panel view itself is intentionally deferred — see manifest (no panel precedent in this base + PR-A's question-card UI lands in the parallel lane; building it here would collide).
The compile-time _AssertAllSessionEntryKeysAreReserved guard requires every SessionEntry key to be in the plugin-collision reserved list; add 'plan' next to 'goal' (same precedent).
…tend) Self-contained plan-panel render component: plan-mode state chip (Planning / Awaiting approval), live plan checklist with per-step status icons + accessible labels, progress summary, presented plan summary, and — only when awaiting approval — Approve / Keep-planning controls. The controls send /plan accept|reject through the existing composer command sender, which resolves the PR-A approval question (no new approval path). Reads plan state from the session snapshot (U4 backend seam). Full i18n: new plan.* keys in en.ts propagated to all 20 locales (English fallback pending localization). Panel CSS matches the goal-chip design tokens; render test covers chip/checklist/ approval-controls/empty states. The live stream:plan checklist data-source threading is the one remaining seam (panel already renders a checklist when fed; mounted with session-derived state today).
Exercises the REAL exit_plan_mode <-> QuestionManager <-> /plan accept|reject seam (no mocks): the tool parks on the PR-A question, the channel command resolves it through the same process-global manager, and the tool returns approved (state cleared) / revise (back to planning with feedback). Completes U6 alongside the state-machine, gate-matrix, adversarial-bypass, panel-render, and store-migration suites.
…ignment, dangle) Brace the setTimeout poll executors, collapse the plan-status read to a single expression, and drop the unused __planModeGateContract introspection export.
…seam 5) handleAgentEvent captures each update_plan tool result (the stream:plan / tool agent-event path) into a per-session plan-checklist store; the chat composer reads it when mounting the panel, so the checklist updates in real time with per-step status transitions as the agent plans. Re-render + coalescing reuse the existing throttled scheduleToolStreamSync (no new throttle); cleared on run reset. Pure extraction + types live in a dependency-free lib/plan-checklist.ts so the node-tested tool-stream module never pulls in i18n/lit. Tests: extraction unit + a live stream:plan sequence asserting the panel re-renders step transitions.
… (U1) Adopt the spike GoalContinuationDriver (4-gate debounced scheduler, no self-re-arm after fire) and bind it to real gateway primitives in a testable createGoalDriverService factory. Ships behind tools.experimental.goalDriver (default off) with schema + labels + help. - Durable no-progress counter: first writers of SessionGoal.continuationTurns (recordSessionGoalContinuation / resetSessionGoalContinuations via patchSessionEntry) so the ceiling survives a gateway restart. - Fold the driver continuation marker into isFormattedGoalContinuationPrompt so both /goal and driver turns are classified uniformly (ceiling reset). - FIRE = enqueueSystemEventEntry + immediate targeted heartbeat together (enqueue alone strands the event, per spike). Spike suites: 11/11 pass. tsgo:core clean.
- extractGoalBudgetFlag parses inline --budget N|=N off the objective for /goal set|start|create (codex parity). - Add /goal stop as the host-facing verb for ending goal pursuit (clears the goal, disarming the driver on its next wake). - Host-only pause/resume already enforced: update_goal tool restricts the model to complete|blocked (MODEL_UPDATABLE_SESSION_GOAL_STATUSES); no fix. commands-goal suite: 14/14 pass.
…ility tests (U1/U3/U5) Wire the driver into the live gateway (behind tools.experimental.goalDriver): - startGoalDriverWiring: rearm persisted active goals on startup; arm the idle debounce on the clearTrackedActiveRun turn-completed seam; classify each turn as a driver continuation (via the driver's own 'fired' events) vs a real inbound turn (ceiling reset). - Register + broadcast 'goal.updated' on driver-initiated status changes (auto-pause); teardown via server-close goal-driver-stop step. Tests (U5): - goals.test: durable continuation-counter record/reset survives reload. - goal-driver-wiring.test: flag gate; fire onto system-event queue + heartbeat wake together; auto-pause ceiling -> durable goal.updated; SAFETY: a driver-continued turn does NOT bypass the exec-approval gate. Suites: goal-driver 11/11, wiring 4/4, commands-goal 14/14, goals 18/18. tsgo core + core-test clean.
…utations (U3)
Backend: single-source goal.updated broadcast via a goals.ts change-emitter
(setGoalUpdatedEmitter/emitGoalUpdated), bound to the gateway in
bindGoalUpdatedBroadcast — every mutation path (/goal commands, model tools,
driver auto-pause) now emits goal.updated {sessionKey,status,objective,
tokensUsed,tokenBudget,source}. Drops the driver wiring's separate broadcast
(dedupe). /goal edit gains --budget N (updateSessionGoalObjective sets budget).
Control UI: openclaw-goal-chip Lit component (persistent 'Pursuing goal' chip
+ objective/status/usage) and edit dialog (objective textarea + budget +
pause/resume/stop/save). overlays.ts subscribes to goal.updated and routes chip
actions through the existing /goal host verbs via chat.send. i18n en keys +
sync-generated fallbacks for all 20 locales (ui:i18n:check clean). Mounted in
app-host next to the question card.
Tests: goal-chip store 12 + goalActionCommand, component render 6 (15 UI total),
commands-goal 14, goal-driver 11, wiring 4. ui:build green; tsgo core + test:ui
clean; oxlint clean on touched files.
|
Codex review: needs real behavior proof before merge. Reviewed September 5, 2026, 5:39 AM ET / 09:39 UTC. ClawSweeper reviewWhat this changesAdds automatic goal continuation with completion criteria, timed or session-based waits, and an optional model judge, alongside inherited question, planning, channel, and chat UI changes. Merge readiness⛔ Blocked before merge - 30 items remain Keep open: current main does not cover the central request, and the proposed replacement is incomplete. The pinned branch has blocking scheduler, approval, and authorization defects. Priority: P2 Review scores
Verification
How this fits togetherThe goal driver watches idle sessions and uses stored goals, active runs, queued work, and an optional model judgment to decide whether to start another agent turn. The inherited question and planning services collect human answers that can release the agent from read-only planning. flowchart TD
A[Stored session goal] --> B[Idle scheduler]
C[Active runs and queued work] --> B
B --> D[Wait and budget checks]
D --> E[Optional completion judge]
E --> F[Complete or park goal]
E --> G[Queue continuation and wake agent]
G --> H[Agent turn and human approval gates]
H --> B
Decision needed
Why: The prerequisite closed unmerged, current main now owns overlapping question and goal UI capabilities, and the proposal adds autonomous completion policy, configuration, and SDK contracts. Before merge
Findings
Agent review detailsSecurityNeeds attention: The inherited plan-approval boundary admits stale or command-disallowed answers and permits mutating commands through its read-only prefix check. PR surfacePR surface statistics unavailable: the file list is incomplete. Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Build on current goal and question owners, with identity-checked durable transitions, reliable wait wakeups, and an explicitly approved opt-in judge. Do we have a high-confidence way to reproduce the issue? Yes for the patch defects: the pinned source provides deterministic wait, lifecycle, stale-answer, and authorization failure paths. No runtime reproduction or test execution was performed. Is this the best way to solve the issue? No, the full stack is not the best current integration shape: existing main question and goal APIs provide safer ownership boundaries, while the retained driver still needs lifecycle and durable-transition repairs. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against ee16d5436f9b. LabelsLabel changes:
Label justifications:
EvidenceSecurity concerns:
What I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (10 earlier review cycles; latest 8 shown)
|
|
@100yenadmin thanks for the PR. ClawSweeper is still waiting on real behavior proof before this can move forward. Useful proof can be a screenshot, short video, terminal output, copied live output, linked artifact, or redacted logs that show the changed behavior after the fix. Please redact private tokens, phone numbers, private endpoints, customer data, and anything else sensitive. Once proof is added to the PR body or a comment, ClawSweeper or a maintainer can re-check it. |
|
This PR concerns goal-driver completion contracts, wait barriers, and an optional completion judge. PR #158884 adds a conditional background-exec warning and implements none of those goal-driver mechanisms, so it does not supersede or resolve this PR; leave it open. |
|
This pull request has been automatically marked as stale due to inactivity. |
|
Thanks for the PR. We're closing older pull requests that have gone stale against current This 13.6k-line stacked PR has had no commits since July 10, still needs real behavior proof, and has many blocking review items. Please open a smaller, focused PR against current main if you'd like to pursue goal-driver completion contracts. If this change is still needed, please open a fresh PR against current |
feat(goal-driver): completion contracts, wait barriers, and an optional completion judge
What
Three opt-in upgrades to the experimental goal driver that make long goal runs converge
instead of firing continuations until the no-progress ceiling trips.
1. Completion contracts (
82879720c8)SessionGoalgains an optional structured contract —outcome / verification / constraints[] / boundaries[] / stopWhen— settable at goal-create time or later via the newset_goal_contracttool. The driver folds the contract block into every continuation prompt, so each nudge restates
what "done" means and which constraints bound the work, instead of re-sending a bare objective.
byte-for-byte unchanged.
completeQueuedChatTurn(2-arg)call indriver.integration-probe.test.tsthat lefttsgo:testred on the base branch.2. Wait barriers — gate g5 (
21792a1a3f)Goals can now park instead of burning continuation turns on async waits.
SessionGoalgains anoptional barrier (
waitingUntilepoch orwaitingOnSessionKey), surfaced via the newset_goal_waittool (secondsbackoff |session_keywatch). New driver gate g5:consume a no-progress turn from the ceiling.
resumes normal gating. Barriers auto-drop on any goal status change.
This is the "waiting on CI / waiting on a subagent" primitive: the goal stays alive without the
driver nudging a session that has nothing to do yet.
3. Optional LLM completion judge (
67c5600a13)Config-gated via
tools.experimental.goalDriver.judge.enabled(default: off). After a goal turncompletes and gates g1–g5 pass — and before a continuation fires — a bounded judge call classifies
the run:
done→ mark the goal complete (no continuation),wait→ park behind the g5barrier,
continue→ fire exactly as before.(
prepareSimpleCompletionModelForAgent+completeWithPreparedSimpleCompletionModel) — the sameseam
conversation-label-generatoruses.judge.modelRefoverrides the model if desired.thrown judge all resolve to a normal continuation — a broken judge can never wedge progress; the
no-progress ceiling remains the backstop.
(queue-nonempty → re-arm; goal deactivated mid-judge → safe no-op), so a user message landing
during judge deliberation behaves exactly like the sync path.
What Problem This Solves
Today the goal driver fires continuations blindly until the no-progress ceiling trips: a goal whose
work is actually finished keeps getting nudged, a goal waiting on CI or a subagent burns its
continuation budget on "still waiting" turns, and each nudge re-sends a bare objective with no
definition of done. With contracts + barriers + judge enabled, a goal run converges instead: every
continuation restates the verification surface (contract) → async waits park instead of spinning
(barrier) → the driver notices verifiable completion instead of nudging a finished session until the
ceiling trips (judge). Each piece is independently useful and independently off by default.
Behavior when you change nothing
None. No contract → identical prompts. No barrier → g5 passes trivially. No judge config → the
driver fires continuations exactly as on main. All config additions are
.strict()zod objects withhelp + labels wired.
Example
Evidence
node scripts/test-projects.mjs src/agents/goal-driver/) plus 27 insrc/config/sessions/goals.test.ts, including newsuites: contract prompt folding, g5 barrier gating (fire/park/clear/auto-drop), judge branching
(done/continue/wait), judge fail-open (undefined/throw), mid-judge race regressions
(queue-flip / run-flip / goal-deactivated), and the atomic
requireActiveStatusstore guard.The race regressions were proven fail-without/pass-with: the pre-fix judge path fired/mutated
unconditionally after the await.
pnpm tsgo:prodandpnpm tsgo:testclean (test-side was red on the base branch before commit 1;commit 1 fixes the broken
completeQueuedChatTurncall indriver.integration-probe.test.ts).