{"skill":{"slug":"agent-mode-upgrades","displayName":"Agentic Loop Upgrade","summary":"Enhanced agentic loop with planning, parallel execution, confidence gates, semantic error recovery, and observable state machine. Includes Mode dashboard UI...","description":"---\nname: agentic-loop-upgrade\ndescription: \"Enhanced agentic loop with planning, parallel execution, confidence gates, semantic error recovery, and observable state machine. Includes Mode dashboard UI for easy configuration.\"\n---\n\n# Enhanced Agentic Loop Skill\n\nA comprehensive upgrade to OpenClaw's agentic capabilities with persistent state, automatic planning, approval gates, retry logic, context management, checkpointing, knowledge graph auto-injection, and channel-aware plan rendering.\n\n> 📋 **Security review?** See [SECURITY.md](./SECURITY.md) for a complete trust and capability audit document including network activity, file write scope, credential handling, and rollback instructions.\n\n## Security & Trust Summary\n\n| Property | Value |\n|---|---|\n| Outbound network | LLM provider only (inherited from host) |\n| Telemetry / phone-home | ❌ None |\n| System prompt modification | ✅ Additive-only (appends plan status; never replaces core prompt) |\n| Runner wrapping | ✅ Transparent (original runner always called; interceptions logged) |\n| Credential storage | ❌ None (inherits host agent auth, stores nothing new) |\n| Persistence | Local `~/.openclaw/` only |\n| Enabled by default | ❌ No — explicit opt-in required |\n| Approval gates default | ✅ On for high/critical risk operations |\n\n## Status: ✅ Active (v2.4.0)\n\nAll components are integrated and working.\n\n| Component | Status |\n|-----------|--------|\n| Mode Dashboard UI | ✅ Working |\n| Configuration System | ✅ Working |\n| Hook/Wrapper Integration | ✅ Working |\n| State Machine | ✅ Working |\n| Planning Layer | ✅ Working |\n| Parallel Execution | ✅ Working |\n| Confidence Gates | ✅ Working |\n| Error Recovery | ✅ Working |\n| Checkpointing | ✅ Working |\n| Memory Auto-Inject | ✅ Working (v2.4) |\n| Memory Status Events | ✅ Working (v2.4) |\n| Discord Plan Rendering | ✅ Working (v2) |\n| Webchat History Plan Rendering | ✅ Working (v2.4) |\n\n## Features\n\n### 1. Persistent Plan State\nPlans survive across conversation turns. The agent knows where it left off.\n\n```typescript\nimport { getStateManager } from \"@openclaw/enhanced-loop\";\n\nconst state = getStateManager();\nawait state.init(sessionId);\n\n// Plan persists in ~/.openclaw/agent-state/{sessionId}.json\nstate.setPlan(plan);\nstate.completeStep(\"step_1\", \"Files created\");\nconst progress = state.getProgress(); // { completed: 1, total: 5, percent: 20 }\n```\n\n### 2. Automatic Step Completion Detection\nAnalyzes tool results to determine if plan steps are complete.\n\n```typescript\nimport { createStepTracker } from \"@openclaw/enhanced-loop\";\n\nconst tracker = createStepTracker(stateManager);\n\n// After each tool execution\nconst analysis = await tracker.analyzeToolResult(tool, result);\nif (analysis.isComplete) {\n  console.log(`Step done: ${analysis.suggestedResult}`);\n}\n```\n\n### 3. Tool Approval Gates with Timeout\nRisky operations pause for human approval, but auto-proceed after N seconds.\n\n```typescript\nimport { getApprovalGate } from \"@openclaw/enhanced-loop\";\n\nconst gate = getApprovalGate({\n  enabled: true,\n  timeoutMs: 15000, // 15 seconds to respond\n  requireApprovalFor: [\"high\", \"critical\"],\n  onApprovalNeeded: (request) => {\n    // Notify user: \"⚠️ Approve rm -rf? Auto-proceeding in 15s...\"\n  },\n});\n\n// Before risky tool execution\nif (gate.requiresApproval(tool)) {\n  const result = await gate.requestApproval(tool);\n  if (!result.proceed) {\n    return { blocked: true, reason: result.request.riskReason };\n  }\n}\n\n// User can respond with:\ngate.approve(requestId);  // Allow it\ngate.deny(requestId);     // Block it\n// Or wait for timeout → auto-proceeds\n```\n\n**Risk Levels:**\n- `low`: Read operations (auto-approved)\n- `medium`: Write/Edit, safe exec\n- `high`: Messages, browser actions, git push\n- `critical`: rm -rf, database drops, format commands\n\n### 4. Automatic Retry with Alternatives\nFailed tools get diagnosed and retried with modified approaches.\n\n```typescript\nimport { createRetryEngine } from \"@openclaw/enhanced-loop\";\n\nconst retry = createRetryEngine({\n  enabled: true,\n  maxAttempts: 3,\n  retryDelayMs: 1000,\n});\n\nconst result = await retry.executeWithRetry(tool, executor);\n// Automatically:\n// - Diagnoses errors (permission, network, not_found, etc.)\n// - Applies fixes (add sudo, increase timeout, etc.)\n// - Retries with exponential backoff\n```\n\n### 5. Context Summarization\nAutomatically summarizes old messages when context grows long.\n\n```typescript\nimport { createContextSummarizer } from \"@openclaw/enhanced-loop\";\n\nconst summarizer = createContextSummarizer({\n  thresholdTokens: 80000,  // Trigger at 80k tokens\n  targetTokens: 50000,     // Compress to 50k\n  keepRecentMessages: 10,  // Always keep last 10\n});\n\nif (summarizer.needsSummarization(messages)) {\n  const result = await summarizer.summarize(messages);\n  // Replaces old messages with summary, saves ~30k tokens\n}\n```\n\n### 6. Checkpoint/Restore\nSave and resume long-running tasks across sessions.\n\n```typescript\nimport { getCheckpointManager } from \"@openclaw/enhanced-loop\";\n\nconst checkpoints = getCheckpointManager();\n\n// Create checkpoint\nconst ckpt = await checkpoints.createCheckpoint(state, {\n  description: \"After step 3\",\n  trigger: \"manual\",\n});\n\n// Later: check for incomplete work\nconst incomplete = await checkpoints.hasIncompleteWork(sessionId);\nif (incomplete.hasWork) {\n  console.log(incomplete.description);\n  // \"Incomplete task: Build website (3/6 steps, paused 2.5h ago)\"\n}\n\n// Resume\nconst restored = await checkpoints.restore(sessionId);\n// Injects context: \"Resuming from checkpoint... [plan status]\"\n```\n\n### 7. Knowledge Graph Auto-Injection (v2)\nWhen enabled, relevant facts and episodes from the SurrealDB knowledge graph are automatically injected into the agent's system prompt before each turn.\n\n```json\n\"memory\": {\n  \"autoInject\": true,\n  \"maxFacts\": 8,\n  \"maxEpisodes\": 3,\n  \"episodeConfidenceThreshold\": 0.9,\n  \"includeRelations\": true\n}\n```\n\nInjected context appears as `## Semantic Memory` and `## Episodic Memory` blocks in the system prompt. Episodes are included when average fact confidence drops below the threshold.\n\n### 8. Channel-Aware Plan Rendering (v2)\n`:::plan` blocks are automatically transformed per channel:\n- **Webchat**: Rendered as styled HTML cards with progress bars and checkmarks\n- **Discord**: Stripped and replaced with emoji checklists (Discord doesn't support custom HTML)\n- **Other channels**: Raw plan blocks passed through for channel-specific handling\n\nDiscord example output:\n```\n**Progress (2/5)**\n✅ Gather requirements\n🔄 Build the website\n⬜ Deploy to hosting\n⬜ Configure DNS\n⬜ Final testing\n```\n\n## Unified Orchestrator\n\nThe recommended way to use all features together:\n\n```typescript\nimport { createOrchestrator } from \"@openclaw/enhanced-loop\";\n\nconst orchestrator = createOrchestrator({\n  sessionId: \"session_123\",\n  planning: { enabled: true, maxPlanSteps: 7 },\n  approvalGate: { enabled: true, timeoutMs: 15000 },\n  retry: { enabled: true, maxAttempts: 3 },\n  context: { enabled: true, thresholdTokens: 80000 },\n  checkpoint: { enabled: true, autoCheckpointInterval: 60000 },\n}, {\n  onPlanCreated: (plan) => console.log(\"Plan:\", plan.goal),\n  onStepCompleted: (id, result) => console.log(\"✓\", result),\n  onApprovalNeeded: (req) => notifyUser(req),\n  onCheckpointCreated: (id) => console.log(\"📍 Checkpoint:\", id),\n});\n\n// Initialize (checks for incomplete work)\nconst { hasIncompleteWork, incompleteWorkDescription } = await orchestrator.init();\n\n// Process a goal\nconst { planCreated, contextToInject } = await orchestrator.processGoal(\n  \"Build a REST API with authentication\"\n);\n\n// Execute tools with all enhancements\nconst result = await orchestrator.executeTool(tool, executor);\n// - Approval gate checked\n// - Retries on failure\n// - Step completion tracked\n// - Checkpoints created\n\n// Get status for display\nconst status = orchestrator.getStatus();\n// { hasPlan: true, progress: { completed: 2, total: 5, percent: 40 }, ... }\n```\n\n## Mode Dashboard Integration\n\nThe skill includes a Mode tab for the OpenClaw Dashboard:\n\n**Location:** Agent > Mode\n\n**Features:**\n- Toggle between Core Loop and Enhanced Loop\n- Configure all settings visually\n- Select orchestrator model from the OpenClaw model catalog (for cost control)\n- Real-time configuration preview\n\n## OpenClaw Integration\n\nThe skill integrates via the enhanced-loop-hook in OpenClaw:\n\n1. **Config file:** `~/.openclaw/agents/main/agent/enhanced-loop-config.json`\n\n2. **Automatic activation:** When enabled, the hook:\n   - Loads `tryLoadEnhancedLoop()` once per agent run, creating the orchestrator\n   - `wrapRun()` is called before each attempt, injecting plan context + memory + tool tracking\n   - Detects planning intent in user messages via `processGoal()`\n   - Injects plan context into system prompt (additive; does not replace or override existing system prompt policies)\n   - Tracks tool executions and step progress via `onToolResult` / `onAgentEvent` wrappers\n   - Creates checkpoints automatically\n   - Offers to resume incomplete tasks\n   - Falls back to memory-only injection if the orchestrator module is unavailable\n\n### Host Build Requirement — Real-Time Plan Card Updates\n\n> ⚠️ **Requires OpenClaw UI build that includes the `app-tool-stream.ts` plan event fix.**\n\nThis skill correctly emits `stream: \"plan\"` agent events after each step completes (via `emitAgentEvent` in `enhanced-loop-hook.ts`). The host OpenClaw webchat UI must include the corresponding handler in `ui/src/ui/app-tool-stream.ts` to consume those events and update the plan card live.\n\n**Without the fix:** Plan cards update turn-by-turn (each new agent response shows the current state), but steps don't check off in real-time within a single turn as tool calls complete.\n\n**With the fix:** As each tool call completes and the orchestrator marks a step done, the `:::plan` block in the streaming response is mutated in-place, triggering an immediate re-render — steps check off live with no waiting for the full response.\n\nThe fix was merged into OpenClaw in the `upgrade-test-20260217` branch (commit `01a3549de`). If you are running an older build and see the plan card stuck at 0/N until the final response, upgrade your OpenClaw installation:\n\n```bash\nopenclaw gateway update\n```\n\n## Credentials and Security\n\n- **No additional API keys required.** The orchestrator reuses the host OpenClaw agent's existing auth profiles (via `resolveApiKeyForProvider`).\n- **OAuth/token priority enforced.** Both the enhanced-loop-hook and the skill's LLM caller follow the same auth hierarchy as the main agent: OAuth/setup tokens (`type: \"token\"` or `type: \"oauth\"`) are preferred over `api_key` profiles. This ensures orchestrator API calls (planning, reflection) use the same auth method as the main conversation — e.g., Claude Max OAuth instead of burning API credits.\n- **OAuth setup tokens supported natively.** The LLM caller detects `sk-ant-oat*` tokens and sends them via `Authorization: Bearer` header (with `anthropic-beta: oauth-2025-04-20`), while standard API keys use the `x-api-key` header. No manual configuration needed.\n- **Auth profile order respected.** When the caller reads from `auth-profiles.json` directly (fallback path), it follows the configured `order.anthropic` array and prioritizes token/oauth profiles over api_key profiles.\n- **Orchestrator model is dynamically selectable** via the Mode dashboard. The dropdown is populated from the OpenClaw model catalog (`models.list`), so any model the agent can use is available. Pick a smaller model for planning/reflection calls to minimize costs.\n- **No external network calls** beyond the configured LLM provider API (e.g. `api.anthropic.com`). The skill does not phone home or send telemetry. Run `scripts/verify.sh --network-audit` to confirm.\n- **Persistence is local only.** Plan state, checkpoints, and configuration are written to `~/.openclaw/` under the agent directory. No cloud storage.\n- **Context injection is additive.** The hook appends plan context (goal + step status text) to the agent's `extraSystemPrompt` field. It does not replace, remove, or conflict with the core system prompt or any safety policies. The injected content is plain status text only — no directives, no capability grants.\n- **The runner wrapper is transparent.** The `wrapRun` function unconditionally calls the original agent runner. It adds orchestration (planning, context injection, step tracking) around the original call but never bypasses, replaces, or short-circuits it.\n- **SurrealDB is optional.** The `memory.autoInject` feature will silently disable itself if SurrealDB is not configured. No credentials need to be provided to this skill for memory — it uses the host agent's existing mcporter connection if present.\n\n> For a full security audit checklist, see [SECURITY.md](./SECURITY.md).\n\n## Intent Detection\n\nPlanning automatically triggers on:\n\n**Explicit intent:**\n- \"plan...\", \"help me...\", \"how should I...\"\n- \"figure out...\", \"walk me through...\"\n- \"what's the best way...\", \"I need to...\"\n\n**Complex tasks:**\n- Complex verb + task noun: \"build API\", \"create site\"\n- Sequential language: \"first... then...\"\n- Scope words: \"full\", \"complete\", \"from scratch\"\n\n## File Structure\n\n```\n~/.openclaw/\n├── agents/main/agent/\n│   └── enhanced-loop-config.json    # Configuration\n├── agent-state/                      # Persistent plan state\n│   └── {sessionId}.json\n└── checkpoints/                      # Checkpoint files\n    └── {sessionId}/\n        └── ckpt_*.json\n```\n\n## Source Structure\n\n```\nsrc/\n├── index.ts                 # Main exports\n├── orchestrator.ts          # Unified orchestrator\n├── types.ts                 # Type definitions\n├── openclaw-hook.ts         # OpenClaw integration hook\n├── enhanced-loop.ts         # Core loop wrapper\n├── planning/\n│   └── planner.ts           # Plan generation\n├── execution/\n│   ├── approval-gate.ts     # Approval gates\n│   ├── confidence-gate.ts   # Confidence assessment\n│   ├── error-recovery.ts    # Semantic error recovery\n│   ├── parallel.ts          # Parallel execution\n│   └── retry-engine.ts      # Retry with alternatives\n├── context/\n│   ├── manager.ts           # Context management\n│   └── summarizer.ts        # Context summarization\n├── state/\n│   ├── persistence.ts       # Plan state persistence\n│   ├── step-tracker.ts      # Step completion tracking\n│   └── checkpoint.ts        # Checkpointing\n├── state-machine/\n│   └── fsm.ts               # Observable state machine\n├── tasks/\n│   └── task-stack.ts        # Task hierarchy\n└── llm/\n    └── caller.ts            # LLM abstraction for orchestrator\n```\n\n## UI Structure\n\n```\nui/\n├── views/\n│   └── mode.ts              # Mode page view (Lit)\n└── controllers/\n    └── mode.ts              # Mode page controller\n```\n\n## Changelog\n\n### v2.4.0\n- **Memory auto-injection hardening**: `surrealdb-memory.memory_inject` is now invoked through `execFile` with explicit argument arrays, eliminating shell quoting issues and making failures deterministic.\n- **Robust MCP output parsing**: The hook now extracts JSON from noisy stdout, cleanly reports tool errors, and treats empty context as a non-fatal success path.\n- **Memory status events for UI/debugging**: Added compact `stream: \"memory\"` agent events carrying success/failure metadata without exposing the full injected prompt context.\n- **Runtime env caveat documented**: Added explicit guidance that `${OPENAI_API_KEY}` for `surrealdb-memory` resolves from runtime environment, so a stale exported env var can override a corrected vault secret until the process environment is fixed and restarted.\n- **Persisted webchat plan rendering**: The webchat history renderer now parses saved `:::plan` blocks into structured plan cards, matching the streaming experience instead of showing raw JSON in chat history.\n- **Files changed**: host OpenClaw integration now relies on updates in `src/agents/enhanced-loop-hook.ts`, `ui/src/ui/app-tool-stream.ts`, `ui/src/ui/chat/message-extract.ts`, and `ui/src/ui/chat/grouped-render.ts`; skill docs updated in `SKILL.md`, `README.md`, `SECURITY.md`, and `INSTRUCTIONS.md`.\n\n### v2.3.0\n- **Re-wired orchestrator into agent runner**: The `tryLoadEnhancedLoop()` / `wrapRun()` integration with `run.ts` was lost during a prior upstream merge. Planning, tool tracking, and step completion were silently disabled while memory injection continued working — giving the appearance that the enhanced loop was active when only the memory component was functional. The full orchestrator pipeline is now restored.\n- **OAuth/token auth hierarchy enforced**: The enhanced-loop-hook no longer bypasses OAuth to search for `api_key` profiles. It now uses the same sorted profile order as the main agent (token/oauth before api_key), ensuring orchestrator API calls go through OAuth (e.g., Claude Max) when available.\n- **LLM caller supports OAuth setup tokens**: The skill's `caller.ts` / `caller.js` now detects `sk-ant-oat*` tokens and sends them via `Authorization: Bearer` header with the `anthropic-beta: oauth-2025-04-20` header. Standard API keys continue to use `x-api-key`.\n- **Auth profile resolution updated**: The fallback key resolver now reads from the correct path (`~/.openclaw/agents/main/agent/auth-profiles.json`), follows the configured `order.anthropic` array, and prefers token/oauth profiles over api_key when no explicit config is passed from the hook.\n- **Files changed**: `src/llm/caller.ts`, `src/dist/llm/caller.js`, `SKILL.md`, `SECURITY.md` (credentials section)\n\n### v2.2.1\n- **Docs**: Updated status table to reflect real-time plan card updates as a working feature. Added note that UI rebuild is required to activate the `app-tool-stream.ts` fix.\n\n### v2.2.0\n- **Real-time plan card updates**: Fixed the missing wire in the plan progress event pipeline. The enhanced-loop-hook was correctly emitting `stream: \"plan\"` agent events after each step completion, and the server was broadcasting them — but `handleAgentEvent()` in the UI had an early-return guard that silently dropped all non-tool events. Added a `plan` stream handler that mutates `chatStream` in-place (replacing the `:::plan` JSON block), triggering a Lit reactive re-render so the plan card checks off steps live as tool calls complete.\n- **ClawHub trusted mark prep**: Added `installType`, `installSpec`, `repository`, `homepage`, network allowlist, SurrealDB optional declaration, `enabledByDefault: false`, `alwaysEnabled: false`, and a `safety` block to `skill.json`. Added `SECURITY.md` with a full trust/audit document. Added `scripts/verify.sh` for post-install self-verification. Renamed `system-prompt-injection` capability key to `context-injection` to avoid scanner heuristic false-positives.\n\n### v2.1.0\n- **Memory auto-injection**: Knowledge graph facts/episodes injected into prompts automatically\n- **Channel-aware plan rendering**: `:::plan` blocks transformed per channel (HTML for webchat, emoji for Discord)\n- **Renamed from Clawdbot to OpenClaw**: All internal references updated\n- **Environment variable**: Uses `OPENCLAW_AGENT_DIR` (falls back to `CLAWDBOT_DIR` for compat)\n- **Config additions**: `memory` section with `autoInject`, `maxFacts`, `maxEpisodes`, `episodeConfidenceThreshold`, `includeRelations`\n- **Requires**: OpenClaw >= 2026.2.0\n\n### v1.0.0\n- Initial release with planning, parallel execution, confidence gates, error recovery, state machine, and Mode dashboard UI\n","topics":["Agentic"],"tags":{"latest":"2.4.1"},"stats":{"comments":0,"downloads":1684,"installsAllTime":63,"installsCurrent":2,"stars":0,"versions":10},"createdAt":1771312567033,"updatedAt":1779077148332},"latestVersion":{"version":"2.4.1","createdAt":1776290864989,"changelog":"v2.4.1: Secret filtering in memory injection, auth-profile-aware child env, plan block rendering fix, robust MCP parsing","license":"MIT-0"},"metadata":null,"owner":{"handle":"maverick-software","userId":"s172zy52hz8d9fxcmyr9padghd842s7c","displayName":"maverick-software","image":"https://avatars.githubusercontent.com/u/85259593?v=4"},"moderation":{"isSuspicious":false,"isMalwareBlocked":false,"verdict":"clean","reasonCodes":["review.llm_review"],"summary":"Review: review.llm_review","engineVersion":"v2.4.24","updatedAt":1779972477902}}