[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M75NFC67B7VQV7F2KB4GGRXA":3,"skill-same:01M75NFC67B7VQV7F2KB4GGRXA":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":30,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M75NFC67B7VQV7F2KB4GGRXA","agentic-loop-upgrade",null,"Enhanced agentic loop with planning, parallel execution, confidence gates, semantic error recovery, and observable state machine. Includes Mode dashboard UI for easy configuration.","javimosch\u002Fopen-claw-skills","javimosch","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F12900508?v=4","01M6D3F2AS6PV75ET9PZ1QGP8J","Javier Leandro Arancibia","01M75B8NCTAJG9WH5YNZH7C3D8",0,"MIT","https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills\u002Fblob\u002Fmain\u002Fskills\u002Fmaverick-software\u002Fagent-mode-upgrades\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\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](.\u002FSECURITY.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 \u002F 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 `~\u002F.openclaw\u002F` only |\n| Enabled by default | ❌ No — explicit opt-in required |\n| Approval gates default | ✅ On for high\u002Fcritical risk operations |\n\n## Status: ✅ Active (v2.3.0)\n\nAll components are integrated and working.\n\n| Component | Status |\n|-----------|--------|\n| Mode Dashboard UI | ✅ Working |\n| Configuration System | ✅ Working |\n| Hook\u002FWrapper 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) |\n| Discord Plan Rendering | ✅ Working (v2) |\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\u002Fenhanced-loop\";\n\nconst state = getStateManager();\nawait state.init(sessionId);\n\n\u002F\u002F Plan persists in ~\u002F.openclaw\u002Fagent-state\u002F{sessionId}.json\nstate.setPlan(plan);\nstate.completeStep(\"step_1\", \"Files created\");\nconst progress = state.getProgress(); \u002F\u002F { 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\u002Fenhanced-loop\";\n\nconst tracker = createStepTracker(stateManager);\n\n\u002F\u002F 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\u002Fenhanced-loop\";\n\nconst gate = getApprovalGate({\n  enabled: true,\n  timeoutMs: 15000, \u002F\u002F 15 seconds to respond\n  requireApprovalFor: [\"high\", \"critical\"],\n  onApprovalNeeded: (request) => {\n    \u002F\u002F Notify user: \"⚠️ Approve rm -rf? Auto-proceeding in 15s...\"\n  },\n});\n\n\u002F\u002F 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\u002F\u002F User can respond with:\ngate.approve(requestId);  \u002F\u002F Allow it\ngate.deny(requestId);     \u002F\u002F Block it\n\u002F\u002F Or wait for timeout → auto-proceeds\n```\n\n**Risk Levels:**\n- `low`: Read operations (auto-approved)\n- `medium`: Write\u002FEdit, 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\u002Fenhanced-loop\";\n\nconst retry = createRetryEngine({\n  enabled: true,\n  maxAttempts: 3,\n  retryDelayMs: 1000,\n});\n\nconst result = await retry.executeWithRetry(tool, executor);\n\u002F\u002F Automatically:\n\u002F\u002F - Diagnoses errors (permission, network, not_found, etc.)\n\u002F\u002F - Applies fixes (add sudo, increase timeout, etc.)\n\u002F\u002F - 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\u002Fenhanced-loop\";\n\nconst summarizer = createContextSummarizer({\n  thresholdTokens: 80000,  \u002F\u002F Trigger at 80k tokens\n  targetTokens: 50000,     \u002F\u002F Compress to 50k\n  keepRecentMessages: 10,  \u002F\u002F Always keep last 10\n});\n\nif (summarizer.needsSummarization(messages)) {\n  const result = await summarizer.summarize(messages);\n  \u002F\u002F Replaces old messages with summary, saves ~30k tokens\n}\n```\n\n### 6. Checkpoint\u002FRestore\nSave and resume long-running tasks across sessions.\n\n```typescript\nimport { getCheckpointManager } from \"@openclaw\u002Fenhanced-loop\";\n\nconst checkpoints = getCheckpointManager();\n\n\u002F\u002F Create checkpoint\nconst ckpt = await checkpoints.createCheckpoint(state, {\n  description: \"After step 3\",\n  trigger: \"manual\",\n});\n\n\u002F\u002F Later: check for incomplete work\nconst incomplete = await checkpoints.hasIncompleteWork(sessionId);\nif (incomplete.hasWork) {\n  console.log(incomplete.description);\n  \u002F\u002F \"Incomplete task: Build website (3\u002F6 steps, paused 2.5h ago)\"\n}\n\n\u002F\u002F Resume\nconst restored = await checkpoints.restore(sessionId);\n\u002F\u002F 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\u002F5)**\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\u002Fenhanced-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\u002F\u002F Initialize (checks for incomplete work)\nconst { hasIncompleteWork, incompleteWorkDescription } = await orchestrator.init();\n\n\u002F\u002F Process a goal\nconst { planCreated, contextToInject } = await orchestrator.processGoal(\n  \"Build a REST API with authentication\"\n);\n\n\u002F\u002F Execute tools with all enhancements\nconst result = await orchestrator.executeTool(tool, executor);\n\u002F\u002F - Approval gate checked\n\u002F\u002F - Retries on failure\n\u002F\u002F - Step completion tracked\n\u002F\u002F - Checkpoints created\n\n\u002F\u002F Get status for display\nconst status = orchestrator.getStatus();\n\u002F\u002F { 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:** `~\u002F.openclaw\u002Fagents\u002Fmain\u002Fagent\u002Fenhanced-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` \u002F `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\u002Fsrc\u002Fui\u002Fapp-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\u002FN 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\u002Ftoken priority enforced.** Both the enhanced-loop-hook and the skill's LLM caller follow the same auth hierarchy as the main agent: OAuth\u002Fsetup 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\u002Foauth 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\u002Freflection 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\u002Fverify.sh --network-audit` to confirm.\n- **Persistence is local only.** Plan state, checkpoints, and configuration are written to `~\u002F.openclaw\u002F` 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](.\u002FSECURITY.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~\u002F.openclaw\u002F\n├── agents\u002Fmain\u002Fagent\u002F\n│   └── enhanced-loop-config.json    # Configuration\n├── agent-state\u002F                      # Persistent plan state\n│   └── {sessionId}.json\n└── checkpoints\u002F                      # Checkpoint files\n    └── {sessionId}\u002F\n        └── ckpt_*.json\n```\n\n## Source Structure\n\n```\nsrc\u002F\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\u002F\n│   └── planner.ts           # Plan generation\n├── execution\u002F\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\u002F\n│   ├── manager.ts           # Context management\n│   └── summarizer.ts        # Context summarization\n├── state\u002F\n│   ├── persistence.ts       # Plan state persistence\n│   ├── step-tracker.ts      # Step completion tracking\n│   └── checkpoint.ts        # Checkpointing\n├── state-machine\u002F\n│   └── fsm.ts               # Observable state machine\n├── tasks\u002F\n│   └── task-stack.ts        # Task hierarchy\n└── llm\u002F\n    └── caller.ts            # LLM abstraction for orchestrator\n```\n\n## UI Structure\n\n```\nui\u002F\n├── views\u002F\n│   └── mode.ts              # Mode page view (Lit)\n└── controllers\u002F\n    └── mode.ts              # Mode page controller\n```\n\n## Changelog\n\n### v2.3.0\n- **Re-wired orchestrator into agent runner**: The `tryLoadEnhancedLoop()` \u002F `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\u002Ftoken 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\u002Foauth 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` \u002F `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 (`~\u002F.openclaw\u002Fagents\u002Fmain\u002Fagent\u002Fauth-profiles.json`), follows the configured `order.anthropic` array, and prefers token\u002Foauth profiles over api_key when no explicit config is passed from the hook.\n- **Files changed**: `src\u002Fllm\u002Fcaller.ts`, `src\u002Fdist\u002Fllm\u002Fcaller.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\u002Faudit document. Added `scripts\u002Fverify.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\u002Fepisodes 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","# 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](.\u002FSECURITY.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 \u002F 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 `~\u002F.openclaw\u002F` only |\n| Enabled by default | ❌ No — explicit opt-in required |\n| Approval gates default | ✅ On for high\u002Fcritical risk operations |\n\n## Status: ✅ Active (v2.3.0)\n\nAll components are integrated and working.\n\n| Component | Status |\n|-----------|--------|\n| Mode Dashboard UI | ✅ Working |\n| Configuration System | ✅ Working |\n| Hook\u002FWrapper 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) |\n| Discord Plan Rendering | ✅ Working (v2) |\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\u002Fenhanced-loop\";\n\nconst state = getStateManager();\nawait state.init(sessionId);\n\n\u002F\u002F Plan persists in ~\u002F.openclaw\u002Fagent-state\u002F{sessionId}.json\nstate.setPlan(plan);\nstate.completeStep(\"step_1\", \"Files created\");\nconst progress = state.getProgress(); \u002F\u002F { 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\u002Fenhanced-loop\";\n\nconst tracker = createStepTracker(stateManager);\n\n\u002F\u002F 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\u002Fenhanced-loop\";\n\nconst gate = getApprovalGate({\n  enabled: true,\n  timeoutMs: 15000, \u002F\u002F 15 seconds to respond\n  requireApprovalFor: [\"high\", \"critical\"],\n  onApprovalNeeded: (request) => {\n    \u002F\u002F Notify user: \"⚠️ Approve rm -rf? Auto-proceeding in 15s...\"\n  },\n});\n\n\u002F\u002F 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\u002F\u002F User can respond with:\ngate.approve(requestId);  \u002F\u002F Allow it\ngate.deny(requestId);     \u002F\u002F Block it\n\u002F\u002F Or wait for timeout → auto-proceeds\n```\n\n**Risk Levels:**\n- `low`: Read operations (auto-approved)\n- `medium`: Write\u002FEdit, 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\u002Fenhanced-loop\";\n\nconst retry = createRetryEngine({\n  enabled: true,\n  maxAttempts: 3,\n  retryDelayMs: 1000,\n});\n\nconst result = await retry.executeWithRetry(tool, executor);\n\u002F\u002F Automatically:\n\u002F\u002F - Diagnoses errors (permission, network, not_found, etc.)\n\u002F\u002F - Applies fixes (add sudo, increase timeout, etc.)\n\u002F\u002F - 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\u002Fenhanced-loop\";\n\nconst summarizer = createContextSummarizer({\n  thresholdTokens: 80000,  \u002F\u002F Trigger at 80k tokens\n  targetTokens: 50000,     \u002F\u002F Compress to 50k\n  keepRecentMessages: 10,  \u002F\u002F Always keep last 10\n});\n\nif (summarizer.needsSummarization(messages)) {\n  const result = await summarizer.summarize(messages);\n  \u002F\u002F Replaces old messages with summary, saves ~30k tokens\n}\n```\n\n### 6. Checkpoint\u002FRestore\nSave and resume long-running tasks across sessions.\n\n```typescript\nimport { getCheckpointManager } from \"@openclaw\u002Fenhanced-loop\";\n\nconst checkpoints = getCheckpointManager();\n\n\u002F\u002F Create checkpoint\nconst ckpt = await checkpoints.createCheckpoint(state, {\n  description: \"After step 3\",\n  trigger: \"manual\",\n});\n\n\u002F\u002F Later: check for incomplete work\nconst incomplete = await checkpoints.hasIncompleteWork(sessionId);\nif (incomplete.hasWork) {\n  console.log(incomplete.description);\n  \u002F\u002F \"Incomplete task: Build website (3\u002F6 steps, paused 2.5h ago)\"\n}\n\n\u002F\u002F Resume\nconst restored = await checkpoints.restore(sessionId);\n\u002F\u002F 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\u002F5)**\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\u002Fenhanced-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\u002F\u002F Initialize (checks for incomplete work)\nconst { hasIncompleteWork, incompleteWorkDescription } = await orchestrator.init();\n\n\u002F\u002F Process a goal\nconst { planCreated, contextToInject } = await orchestrator.processGoal(\n  \"Build a REST API with authentication\"\n);\n\n\u002F\u002F Execute tools with all enhancements\nconst result = await orchestrator.executeTool(tool, executor);\n\u002F\u002F - Approval gate checked\n\u002F\u002F - Retries on failure\n\u002F\u002F - Step completion tracked\n\u002F\u002F - Checkpoints created\n\n\u002F\u002F Get status for display\nconst status = orchestrator.getStatus();\n\u002F\u002F { 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:** `~\u002F.openclaw\u002Fagents\u002Fmain\u002Fagent\u002Fenhanced-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` \u002F `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\u002Fsrc\u002Fui\u002Fapp-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\u002FN 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\u002Ftoken priority enforced.** Both the enhanced-loop-hook and the skill's LLM caller follow the same auth hierarchy as the main agent: OAuth\u002Fsetup 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\u002Foauth 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\u002Freflection 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\u002Fverify.sh --network-audit` to confirm.\n- **Persistence is local only.** Plan state, checkpoints, and configuration are written to `~\u002F.openclaw\u002F` 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](.\u002FSECURITY.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~\u002F.openclaw\u002F\n├── agents\u002Fmain\u002Fagent\u002F\n│   └── enhanced-loop-config.json    # Configuration\n├── agent-state\u002F                      # Persistent plan state\n│   └── {sessionId}.json\n└── checkpoints\u002F                      # Checkpoint files\n    └── {sessionId}\u002F\n        └── ckpt_*.json\n```\n\n## Source Structure\n\n```\nsrc\u002F\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\u002F\n│   └── planner.ts           # Plan generation\n├── execution\u002F\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\u002F\n│   ├── manager.ts           # Context management\n│   └── summarizer.ts        # Context summarization\n├── state\u002F\n│   ├── persistence.ts       # Plan state persistence\n│   ├── step-tracker.ts      # Step completion tracking\n│   └── checkpoint.ts        # Checkpointing\n├── state-machine\u002F\n│   └── fsm.ts               # Observable state machine\n├── tasks\u002F\n│   └── task-stack.ts        # Task hierarchy\n└── llm\u002F\n    └── caller.ts            # LLM abstraction for orchestrator\n```\n\n## UI Structure\n\n```\nui\u002F\n├── views\u002F\n│   └── mode.ts              # Mode page view (Lit)\n└── controllers\u002F\n    └── mode.ts              # Mode page controller\n```\n\n## Changelog\n\n### v2.3.0\n- **Re-wired orchestrator into agent runner**: The `tryLoadEnhancedLoop()` \u002F `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\u002Ftoken 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\u002Foauth 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` \u002F `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 (`~\u002F.openclaw\u002Fagents\u002Fmain\u002Fagent\u002Fauth-profiles.json`), follows the configured `order.anthropic` array, and prefers token\u002Foauth profiles over api_key when no explicit config is passed from the hook.\n- **Files changed**: `src\u002Fllm\u002Fcaller.ts`, `src\u002Fdist\u002Fllm\u002Fcaller.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\u002Faudit document. Added `scripts\u002Fverify.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\u002Fepisodes 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",{"name":5,"description":7},"main","f9d3fe7cf9ac8f1ea63a0d96e98e1f510a3814db","skills\u002Fmaverick-software\u002Fagent-mode-upgrades",1,"https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills","https:\u002F\u002Fgithub.com\u002Fjavimosch","intrane.fr","Building robust, open-source infrastructure for the commons. AI-leveraged, self-hosted, built to last.","2026-06-07 03:34:58",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add javimosch\u002Fopen-claw-skills --skill agentic-loop-upgrade",{"tool":39,"command":40},"bunx","bunx skills add javimosch\u002Fopen-claw-skills --skill agentic-loop-upgrade",{"tool":42,"command":43},"pnpm","pnpm dlx skills add javimosch\u002Fopen-claw-skills --skill agentic-loop-upgrade","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills\u002Fblob\u002Fmain\u002Fskills\u002Fmaverick-software\u002Fagent-mode-upgrades\u002FSKILL.md",true,[],[48,56,63,70,77,84],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":55},"01M778GGXG2VQ0YF31W2MKGMQZ","crowd-prompting","A marketplace where AI agents improve prompts, system instructions, tool descriptions, and other text-based content with domain expertise from real-world operations — and earn tokens for valuable contributions.","https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzzadrian\u002Fcrowd-prompting\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":55},"01M778G7BH8SBJ9FJ6C3G7CB1K","ceaser","Interact with the Ceaser privacy protocol on Base L2 using the ceaser-mcp MCP tools. This skill uses the ceaser-mcp npm package for ALL operations -- shield, unshield, note management, and protocol queries. All ceaser tool calls use CLI subcommands (npx -y ceaser-mcp \u003Csubcommand>). Ceaser is a privacy-preserving ETH wrapper using Noir\u002FUltraHonk zero-knowledge proofs on Base L2 (chain ID 8453).","https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzyra-v21\u002Fceaser\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":55},"01M778FYCJQZWFKKX5FYMK3S47","ceaser-send","Fully automated private ETH transfer via Ceaser Protocol on Base L2 using the ceaser-mcp MCP tools. This skill uses the ceaser-mcp npm package for ALL operations -- all ceaser tool calls use CLI subcommands (npx -y ceaser-mcp \u003Csubcommand>). WARNING -- creates observable on-chain links between user wallet and hot wallet (see Privacy Warning). Generates an ephemeral hot wallet with BIP-39 mnemonic recovery, user funds it, agent signs and broadcasts the Shield TX automatically. Exactly one manual step required (funding the hot wallet with ETH). Uses Noir\u002FUltraHonk zero-knowledge proofs.","https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzyra-v21\u002Fceaser-send\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":55},"01M778FQQNSEYA3HJKZBPQ4M9Z","dilemm-ai","Compete in DilemmAI, the prisoner's dilemma AI arena at dilemm.ai. Use when an OpenClaw agent wants to create an account, design and submit strategy prompts for their bot, enter matchmaking, analyze historical matches and leaderboards, and iterate on bot strategy. Requires headless browser automation (no API available yet).","https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzyori\u002Fdilemm-ai\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":55},"01M778FGVZX7QA2TF9BFMM37FY","moldium","Post and manage content on the Moldium blog platform. Triggered by \"post to Moldium\", \"write a blog post\", \"publish an article\", etc.","https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzyom45\u002Fmoldium\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":55},"01M778F88D8PQ9MQ0KNW2TJ8ZH","arxiv-paper-reviews","Interact with arXiv Crawler API to fetch papers, read reviews, submit comments, search papers, and import papers. Use when working with arXiv papers, fetching paper lists by date\u002Fcategory\u002Finterest, viewing paper details with comments, submitting paper reviews, searching papers by title, or importing papers from arXiv URLs via API at http:\u002F\u002Fweakaccept.top:8000\u002F.","https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzxrys\u002Farxiv-paper-reviews\u002FSKILL.md",[],[]]