Autonomous Goal Loop
Drop a goal in chat; the agent plans, works, and gets independently judged until it’s done — or a hard bound trips and a human decides.
What It Is
Section titled “What It Is”The goal loop (v1.37) turns one-shot Q&A into “give a goal → agent loops to completion → stuck escalates to a human”. From any connected channel (Telegram / Discord / Slack / LINE / …) you type:
/goal <goal description> || <acceptance criteria>/goal 產出 Q3 月報 || 含每月營收圖表 || outcome:files:report.docx/goal statusThis creates a goal_mode task on the Task Board, stamped with the source channel and chat so progress pushes back to the conversation that started it. Omit the || part and the goal description itself becomes the acceptance baseline; an optional third outcome:<spec> segment adds a machine-checkable output contract (JSON Schema subset or workdir file globs) that runs deterministically, at zero LLM cost, before the judge — structurally deficient output bounces straight back to revision without spending a judge call.
Acceptance criteria are frozen into an immutable baseline the moment the goal is created — every judge call (both the first-stage evaluator and the panel) reads that baseline, never a field an agent could edit later. An agent-identity tasks_update call is refused (with an audit entry) if it tries to change the acceptance criteria, the title or the description of a goal_mode task; only a dashboard operator can still edit the display copy, and doing so does not retroactively change what the frozen baseline judges against. Skip the || criteria and the confirmation reply also nudges you toward a sharper contract next time: a four-element prompt (goal / inputs / output format / constraints) plus a suggestion to write 3–5 outcome-style criteria.
The dispatch engine behind this is on by default since v1.59 (it idles at a periodic SQLite poll until a goal task exists; the acceptance judge only spends an LLM call when a goal actually reaches review). To opt out, set config.toml [dispatch] enabled = false — or flip the「派工引擎」switch in Settings → Automation, which hot-applies without a restart.
The Driver
Section titled “The Driver”GoalLoopDriver (goal_loop.rs) is the outer loop. Every 30 seconds (configurable tick_secs) it finds goal_mode tasks waiting to run and enqueues a work message into the existing message queue — the same wake-up rail a channel message uses — so the agent claims, works, and completes through unchanged plumbing. The closed loop:
driver enqueue ─▶ dispatcher ─▶ agent works ─▶ goal task → review ▲ │ └── reject → pending (+judge feedback) ◀── acceptance judge ──▶ pass → doneOn rejection the task returns to pending carrying the judge’s feedback; the very next tick re-dispatches it with that feedback in the work message — a Generator-Verifier retry loop. Every state transition pushes a short (1–3 line) progress note back to the source conversation, deduped per state.
The Acceptance Judge — Never Self-Report
Section titled “The Acceptance Judge — Never Self-Report”“Done” is only ever declared by the verifier, not the worker. When the agent reports completion, the task enters review. A cheap first-stage evaluator runs first — one tool-less LLM call returning a three-way JSON decision (continue / candidate_complete / blocked). continue skips the panel and re-dispatches immediately with the evaluator’s next_step as feedback (counts against the iteration cap); blocked goes straight to needs_human; only candidate_complete reaches the full panel below. Any evaluator failure (timeout, parse error, transport error) degrades straight to the panel — it never auto-accepts or auto-rejects on its own malfunction. Config: [dispatch] two_stage_judge (default true; false reverts to every review going straight to the panel).
Once a round reaches the panel, DispatchEngine runs a three-aspect MAV panel — correctness, completeness, safety — in one LLM call through the account rotator. All three must pass; a parse failure, a truncated/malformed panel reply, or a judge transport error parks the task as needs_human, never auto-accepts (fail-closed) — a truncated JSON fragment can no longer fall through to a legacy token scanner that might misread a stray pass substring as an accept. This is the defense against the classic loop trap where an agent narrates success and the system believes it.
The panel prompt also carries four standing discipline clauses, always on (no config gate): no ratcheting the bar higher round over round when the criteria haven’t changed; audit, don’t author — the judge may only check the worker’s submitted evidence and the tool-activity digest, never invent its own; no scope creep — a requirement absent from the acceptance criteria can’t be the reason for a rejection; and a self-reported “done” is not evidence on its own.
Each criterion also gets a status in a per-criterion acceptance ledger (C1, C2, …) that the worker reports every round and that the judge and the task detail page can read. How it is created, which modes exist ([goal_loop] criteria_ledger, default report) and what the judge does with it are in the acceptance ledger section of the goal loop guide.
Judge depth scales with goal difficulty (a local, zero-LLM heuristic): simple single-step goals get a two-aspect check (correctness + safety) and a lower iteration cap; hard goals get the full panel. The safety aspect is never dropped at any depth.
Round history and weekly report (v1.67.0)
Section titled “Round history and weekly report (v1.67.0)”Each dispatched round records the evaluator and judge decisions, dispatch sequence, Solo/Team mode and gate inputs, state and configuration snapshots, and any pause reason. Accepted rounds retain a bounded worker excerpt. Retrying a paused task adds a fresh open record; sealed decisions remain available, including after the pause is resolved. Token usage is attributed to the task and round.
duduclaw weekly-report --days 30 --format json includes goal statistics grouped by retry limit and Solo/Team mode. For each cutoff, it reports how many accepted tasks would be lost, how many rounds would be saved, and the fraction of accepted tasks completed by that round, with a 95% Wilson interval. Cancelled and still-running tasks are listed separately. Legacy configuration snapshots stay unknown; small samples are explicitly labelled as indistinguishable from luck. This descriptive table does not establish that changing the retry limit improves results.
duduclaw knobs survival --days 30 --format json is the dedicated read-only history report. It groups recorded retry limits, dispatch-time difficulty, Solo/Team mode, and verified manual retries. Missing or inconsistent historical snapshots remain unknown. A separate human-approved cohort uses authenticated outcome decisions; ordinary activity messages and permission to start a goal are not outcome approval. An approval without a bound iteration is counted separately, without inventing its round.
The command reads a private copy of the task ledger, verified against source hashes and file identity before and after capture. It does not migrate or update the task, cost, or audit databases. A nonempty WAL or journal makes the report unavailable; checkpoint it through the normal service before reporting. Missing, corrupt, changing, or oversized history produces an explicit error rather than an empty successful report. Output defaults to stdout; --output writes only the chosen report artifact and rejects aliases of database files and sidecars. The tables describe logical judged rounds, not total dispatches or an experiment proving a better retry policy; manual intervention and unknown settings retain that limitation.
The reader refuses oversized reports rather than returning a truncated subset: a 64 MiB source database, 5,000 tasks in the selected window, 2,000 iteration records, 64 KiB per text field, 8 MiB of retained text, logical rounds up to 1,000, and 2,000 table rows across both cohorts. Capture, SQL, and aggregation share a two-second deadline. File artifacts are published with directory-descriptor protection on Unix; other platforms explicitly reject --output and support stdout. The four reserved database/sidecar names cannot be used as output basenames.
Hard Guards — the Driver Owns the Bounds
Section titled “Hard Guards — the Driver Owns the Bounds”Termination is guaranteed by the driver, not by trusting the model:
| Guard | Default | On breach |
|---|---|---|
| Iteration cap (dispatches per task) | 5 (hard goals), 3 (simple) | needs_human |
| Wall clock from creation | 24 h | needs_human |
Goal cost cap (cost_cap_cents, fallback default_cost_cap_cents) |
No default cap (0) |
Measured task-tree spend at or above cap: needs_human / budget_exhausted; unreadable cost: defer dispatch; unmeasured usage: pause for a human decision |
| Concurrent goal tasks | 3 | queued, not dispatched |
| Stagnation detection | two consecutive rejections with the same gap fingerprint (path:line citations + backtick key tokens extracted and normalized from the feedback, not raw text equality — a reworded restatement of the same gap still matches; falls back to literal-text comparison only when no citation/token is extractable) |
early needs_human |
| Bail-pattern detection | nine zh+en anchored regexes over the agent’s last non-empty paragraph (e.g. self-signed VERDICT:, “check back later”, “ready for review”) |
telemetry + activity event + a hint folded into the next round’s judge/evaluator input — never rejects or blocks on its own |
| In-flight dedup | dispatched-but-unclaimed tasks are not re-enqueued until a stall timeout (600 s) | re-dispatch |
| Dispatch failure (the work message never reached a runtime — CLI missing, local engine down, credentials refused) | slot and edition lease released on the next tick; back-off 60 → 120 → 240 s; 3 consecutive failures | needs_human (infra), error text on the task timeline |
Cross-process circuit breaker (dispatch_guard) |
20 dispatches / 60 s sliding window | cooldown refusal |
| Delegation hop depth | 5 | dispatch refused |
Resume on gateway restart (resume_on_restart) |
pause (default) escalates every in-flight goal_mode task to needs_human (reason gateway_restart) at boot |
auto resumes in-flight tasks exactly as before a restart instead; toggle either in config.toml or the dashboard’s Settings → Automation tab (system.update_config, whitelisted to "auto"/"pause" only) |
No-progress report (progress_report_minutes) |
10 min of silence on an already-claimed task (Activity Feed signal, not the lease-renewer-refreshed updated_at) |
one “still running, no progress signal” notice to Activity Feed + source conversation, at most once per round — never re-dispatches, escalates, or cancels; 0 disables it |
Tool-call streak (tool_streak_pause, tool_streak_advisory) |
Pause at 8 identical consecutive calls within one round; 0 disables pause. Hints at 3 / 5 / 8 when advisory is on |
After the round: needs_human / no_progress, with tool and count; below the pause threshold, hint only |
Ephemeral spawn admission ([dispatch] admission) |
Over the concurrency cap (ephemeral_max_active, default 32) |
"queue" (default) durably FIFO-queues the request instead of rejecting it (bounded depth, per-ticket TTL, audited); "fail" reverts to the pre-H19 immediate rejection |
All under [goal_loop] / [dispatch_guard] / [dispatch] in config.toml, with built-in defaults when the sections are absent.
Goal cost cap and repeated-call pause
Section titled “Goal cost cap and repeated-call pause”Set cost_cap_cents to a positive integer in tasks_create with kind="goal". The dashboard assignment form is currently hidden. For example, 500 means US$5.00. Existing goals have no explicit cap. When no cap is stored, [goal_loop] default_cost_cap_cents applies (0, the default, means no cap).
Before every round, the driver reads measured spend across the goal’s recorded task tree through the shared responsibility cost source. At or above the ceiling it pauses as needs_human / budget_exhausted; the detail includes the cap and spend. An unreadable cost source skips dispatch for that round. A recorded usage row with zero token counts anywhere in the tree pauses the goal as needs_human / blocked_needs_decision, with a visible explanation that the runtime did not report usage; raising the ceiling alone does not resolve unknown spend. An ordinary capped goal has no reservation fallback: unknown usage is neither estimated nor counted as zero. This is a between-round guard, not a billing guarantee: a running round and concurrent child tasks may exceed the ceiling, and unreported costs are not measured spend. The goal ceiling and employee budget are configured separately.
/goals shows measured spend and the effective ceiling, or explicitly says spend is unavailable. Paused cards show the pause detail. If [goal_loop] default_cost_cap_cents is malformed or unreadable, all goals defer dispatch, including goals without an explicit cap; /goals displays the configuration issue until it is repaired. An authorized operator can enter a higher ceiling and choose Raise cap and retry: the cap is saved through tasks.update before the existing tasks.goal_decide retry action runs. A failed save never resumes the goal. MCP tasks_update accepts the same field; employees may only add or narrow a cap, while an operator can raise it. The dashboard also carries the cap into each goal created by a scheduled assignment.
[goal_loop] tool_streak_pause = 8 pauses a goal after a finished round contains at least eight consecutive calls to the same tool with the same masked arguments. The reason is no_progress, with the tool name and count in the detail. 0 disables this pause independently of tool_streak_advisory; below the pause threshold the existing 3 / 5 / 8 hints remain when advisory is enabled. No tool call is interrupted mid-round. Saving these settings in the dashboard’s Advanced config editor reloads the goal loop. If you edit config.toml directly, restart the gateway.
Per-goal run limit
Section titled “Per-goal run limit”Each CLI run (including Claude) and each OpenAI-compatible request is bounded by the employee’s Run limit (agent.toml [runtime] timeout_secs, from 30 s up to the global [runtime] max_timeout_secs). When unset, [runtime] default_timeout_secs applies if configured; otherwise every runtime uses 1800 s (since v1.84.0; runtimes other than Claude used 300 s before), capped by the global maximum. A complex goal can be given its own limit without changing the employee: timeout_secs (30 seconds up to min(max_timeout_secs, 3600); at most one hour) in tasks_create with kind="goal". Every round of that goal uses it; an employee with the task sandbox on uses it as the sandbox timeout too. Each run, including the sandbox, is capped by the current global [runtime] max_timeout_secs.
Only an Admin may set more than the employee’s own limit, the same rule as raising that limit on the employee’s edit page. A dashboard Operator, any MCP caller and a scheduled assignment whose creator is no longer an Admin get at most the employee’s own limit (a scheduled run is capped at each fire). The value is fixed when the goal is created; tasks_update refuses it. Handing the goal to another employee (any reassignment) clears it, so the new assignee runs under its own limit. The task detail page shows it as a badge.
needs_human Escalation
Section titled “needs_human Escalation”When a task parks as needs_human, it is stamped with a closed six-way pause_reason classification alongside the free-text judge_feedback — no_progress / budget_exhausted / blocked_needs_decision / infra / restart / unknown — assigned statically at the trigger site (never guessed from judge/evaluator prose). It renders as a chip on the /goals board and task detail, and as a “type” line in the channel approval message; unclassified or legacy rows read as unknown, the safe default. goal_notify.rs pushes an approval message with four inline actions — retry / mark done / abort / take over — to the source conversation (falling back to the agent’s [proactive] control channel). A message caps at 3 primary actions, so retry/mark-done stay primary and abort/take-over collapse into each platform’s secondary affordance: a second row on Telegram and Discord, a native overflow menu on Slack; LINE has no secondary-menu affordance at all, so those two are dropped from its quick reply and listed as plain text with a dashboard link instead. Other non-button channels get a text fallback, and the dashboard shows a needs_human board column.
Take over claims the task (claimed_by) without resolving it — the task stays needs_human, which is already outside the driver’s dispatch-candidate query, so automatic retries are already stopped without a status change. This is the button-driven layer of takeover (stop the loop + mark + collapse the card). Transferring the conversation — pausing inbound AI replies and every scheduled dispatch aimed at it — is the separate typing-triggered feature in 42-human-takeover.md; a conversation takeover also freezes this loop for any goal task that came from it.
Decisions are idempotent and fail-closed: retry/mark-done/abort only transition from needs_human, so a stale or double press is a no-op; take-over has no terminal state to compare against, so a repeat press (even by a different authorized decider) simply re-claims it.
Plan-First Mode (“想一想”, I-1c)
Section titled “Plan-First Mode (“想一想”, I-1c)”Use tasks.goal_create with plan_first: true (or the chat assignment command with || plan); the dashboard assignment form is hidden: instead of dispatching, the gateway synchronously calls the utility LLM to draft a short (3–8 bullet, plain-text) execution plan from the goal + acceptance criteria, and the task is born directly in needs_human — under the existing blocked_needs_decision pause reason, no new class added — so it never reaches the driver’s dispatch-candidate query until a human approves.
The plan lives in a dedicated plan_pending column, kept separate from judge_feedback on purpose: the “重試” (retry) action any needs_human task uses to resume overwrites judge_feedback with the human’s own approval note, which would otherwise erase the plan before it was ever read. Approving is that same existing retry action — no new button kind was added. Once approved, the very first dispatch round injects the plan as an <execution_plan> block into the work prompt, then clears plan_pending so later rounds don’t repeat it. The plan is guidance, not an exemption — the executed work still goes through the same two-stage/MAV acceptance judging as any other goal task.
If the planner call itself fails (timeout, transport error, empty reply), the task still parks needs_human fail-closed — but under the infra pause reason instead of blocked_needs_decision, with no plan_pending set, so approval can never silently start a task with no plan behind it.
Optional independent plan review
Section titled “Optional independent plan review”Set plan_review = "goldfish" in config.toml [goal_loop] to review a successfully generated plan before it is shown for human approval. The default is "off"; a missing or malformed setting also means off. Three fresh calls run concurrently in the current task, each with a 45-second timeout, adding at most 45 seconds: restate the goal and identify unclear parts, remove unnecessary work, and check the decisions, permissions and data needed to execute. Each reviewer receives only the XML-escaped goal, acceptance criteria and plan as data, without conversation, memory, SOUL or employee identity. Each reply asks for Traditional Chinese, at most five bullet points, and is kept to 400 characters.
These calls are system utility spending under goal-plan-review, use the existing system provider resolution without an employee directory, and are not charged to the employee budget. The versioned plan_review JSON is display-only: it never changes plan_pending or judge_feedback, never enters an execution or judging prompt, and never replaces human approval. Failed, empty or timed-out reviews show Not run, including when all three fail; the task still waits in needs_human. Both task detail and the Inbox show a collapsed Independent review (without conversation context) section. Channels show only the number of completed lenses and a dashboard pointer, never review text. This count is completed lenses, not individual findings.
Autonomy Levels
Section titled “Autonomy Levels”Each agent’s leash length is one dial: agent.toml [capabilities] autonomy_level. Missing or unparseable defaults to the conservative approver.
| Level | Behavior |
|---|---|
operator |
Loop never auto-drives; tasks sit until a human pushes them. |
collaborator / consultant |
First dispatch requires a human kickoff approval (ApprovalBroker, 1 h TTL, expiry = denial). Then autonomous to completion. |
approver |
Default. No kickoff gate; humans are only consulted at needs_human. |
observer |
Fully autonomous; needs_human notifies but does not wait. |
Internal Layout
Section titled “Internal Layout”The driver and its helpers live together under crates/duduclaw-gateway/src/goal_loop/:
| Module | What it holds |
|---|---|
goal_loop.rs |
GoalLoopDriver — the outer loop itself. |
goal_loop/signals.rs |
The four zero-LLM extractors that read a round’s output: gap fingerprint (H4), the (state, action) visit graph (A2), the in-round tool-call streak advisory (H10), and the premature-stop regex panel (H5). |
goal_loop/state.rs |
The structured <state> block (A1), the closed needs_human pause-reason classification (H11), and the budget-exhausted “best round” picker (WP-4F). |
goal_loop/plan.rs |
Goal decomposition and the plan-first (“想一想”) planner. |
Before 2026-09 these were eight separate crate-root modules (goal_state, goal_visit_graph, goal_gap_fingerprint, goal_budget_best_round, goal_bail_detect, goal_tool_streak, goal_plan, pause_reason). The 2026-09 feature audit (O8) merged them by role; every old crate::goal_* / crate::pause_reason path stays available as a re-export for one release, and no behavior, config key, or test changed.
ActionGuard: Three-Valued Irreversibility
Section titled “ActionGuard: Three-Valued Irreversibility”Layered on top, per tool call (approval.rs, after Magentic-UI’s ActionGuard):
irreversible_tools— always requires human approval.maybe_irreversible_tools— an LLM judge rules on this specific call; risky (or judge failure/timeout) escalates to a human, safe auto-proceeds. Fail-closed.- Unlisted — the existing allowed/denied/policy flow, no new friction.
The merge with the legacy approval_required_tools is take-the-stricter, so existing configs keep their exact semantics.
Full operator reference — config keys, dispatch policies, parallel sub-task DAGs, outcome schemas — lives in docs/guides/goal-loop.md.
Run step budgets
Section titled “Run step budgets”The step budget is configured separately: global [runtime] default_max_turns defaults to 50, and max_turns_limit defaults to 200 (integer 1–10000). An employee may set [runtime] max_turns from 1 up to that ceiling; leaving it unset uses the global default. Zero never means unlimited. Unexpected read, parse or type errors cap the resolved budget at 50 (10 for OpenAI-compatible tool loops), preserving lower valid limits, with warnings deduplicated per employee, configured value and applied cap; missing files or keys use defaults; values above the ceiling are clamped during execution and rejected on dashboard save. Raising an employee’s limit requires an administrator; owners may lower it, and clearing it requires an administrator if the inherited default raises the effective budget. Changing either global key also requires an administrator and is audited through the existing config commit path. The dashboard places these fields beside the time limits. More steps can consume more quota and extend runs. Claude chat, background work and terminal chat use this budget; protected mode remains fixed at 50 until native Linux protected mode supports it. OpenAI-compatible tool loops use an explicit employee max_turns, otherwise retain 10; exhaustion returns a distinct max-turns error. Headless Claude/Grok runs disable interactive question tools. Claude receives a system-prompt reminder to summarise progress and stop near its step budget. Proactive checks retain their separate max_turns, accepted from 1 to 64.
Web chat uses the target employee’s effective timeout, bounded by global max_timeout_secs, plus 30 seconds for delivery (1830 seconds for the default 1800-second employee). Goal task timeout_secs ranges from 30 seconds to min(max_timeout_secs, 3600); the goal limit stays at one hour even if the global maximum is higher.
Event-silence limits and continuation
Section titled “Event-silence limits and continuation”The global [runtime] default_idle_timeout_secs defaults to 900 seconds. An employee may override it with [runtime] idle_timeout_secs; absent means inherit, 0 disables, and other values must be 60..=max_timeout_secs. With an omitted global value, a lower global maximum also narrows the default. Read or parse failures use the built-in 900 seconds. Raising or disabling an employee limit, including clearing it to a larger or disabled global default, requires administrator authority; lowering does not. The dashboard places both fields next to the execution time limits, in the employee editor and global run limits.
Claude chat and background runs, Codex JSONL runs, and OpenAI-compatible SSE responses stop when no event arrives within that window. Any parsed event counts, including tool events; the periodic 90-second keep-alive notice does not. The last unfinished tool is named when known. Grok and non-streaming OpenAI-compatible requests/tool loops retain their total timeout because these paths do not expose a live event stream here.
A step limit (max_turns), total timeout (timeout_total), or event-silence timeout (timeout_no_progress) ends the current turn without marking an account unhealthy, changing accounts, or retrying another model/runtime. A timeout reports that no final answer was produced before the time limit, even when tools ran. For signed-in channel users, captured assistant text is delivered before the notice and saved as an assistant turn; reply “continue” to resume with that context. Claude step-limit notices include the applied step count. Public visitors receive only the visitor-safe generic message and reference number, with no partial text, counts, reason code, or operator hints.
Failure notices end with a stable lowercase reason code and the first eight characters of the turn reference. The audit record retains reason_code and the full reference_id; background results use the dispatch run reference. Goal-loop work limits pause with max_turns, timeout_total, or timeout_no_progress, without accumulating infrastructure dispatch failures.