{"id":"4df34ec7-5b30-40b0-a9a0-0ad10012878a","entityType":"agent","slug":"clawhub-stephenlthorn-claude-handoff","name":"Claude Handoff","canonicalUrl":"https://www.xpersona.co/agent/clawhub-stephenlthorn-claude-handoff","canonicalPath":"/agent/clawhub-stephenlthorn-claude-handoff","generatedAt":"2026-10-12T21:01:54.032Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"editorial-content","verified":true,"confidence":"high","updatedAt":"2026-10-11T22:40:20.519Z","emptyReason":null},"description":"Writes a structured handoff package when local agent determines cloud Claude Code is needed. This is the ONLY path from local pipeline to cloud — the agent n... Skill: Claude Handoff Owner: stephenlthorn Summary: Writes a structured handoff package when local agent determines cloud Claude Code is needed. This is the ONLY path from local pipeline to cloud — the agent n... Tags: latest:1.0.0 Version history: v1.0.0 | 2026-04-21T13:46:35.122Z | auto claude-handoff 1.0.0 - Initial release of the Claude Handoff skill. - Generates a structured handoff package when local agent dete","descriptionLabel":"Technical summary","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. 983 downloads reported by the source. Last updated 10/11/2026.","installCommand":"clawhub skill install s1781macwsy8b25gaqa558qrx5858x3k:claude-handoff","sourceUrl":"https://clawhub.ai/stephenlthorn/claude-handoff","homepage":"https://clawhub.ai/stephenlthorn/skills/claude-handoff","primaryLinks":[{"label":"View on ClawHub","url":"https://clawhub.ai/stephenlthorn/claude-handoff","kind":"source"},{"label":"Homepage","url":"https://clawhub.ai/stephenlthorn/skills/claude-handoff","kind":"homepage"}],"safetyScore":84,"overallRank":62,"popularityScore":60,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"Writes a structured handoff package when local agent determines cloud Claude Code is needed. This is the ONLY path from local pipeline to cloud — the agent n..."},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-10-11T22:40:20.519Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[],"verifiedCount":0,"selfDeclaredCount":1,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile"}},"adoption":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-11T22:40:20.519Z","emptyReason":null},"stars":null,"forks":null,"downloads":983,"likes":null,"task":null,"library":null,"packageName":null,"latestVersion":"1.0.0","tractionLabel":"983 downloads"},"release":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-11T22:40:20.448Z","emptyReason":null},"lastUpdatedAt":"2026-10-11T22:40:20.519Z","lastCrawledAt":"2026-10-11T22:40:20.448Z","lastIndexedAt":null,"nextCrawlAt":"2026-10-12T22:40:20.448Z","lastVerifiedAt":null,"highlights":[{"version":"1.0.0","createdAt":"2026-04-21T13:46:35.122Z","changelog":"claude-handoff 1.0.0 - Initial release of the Claude Handoff skill. - Generates a structured handoff package when local agent determines cloud Claude Code is needed. - Supports user review and manual approval before any Claude Code invocation; never auto-invokes Claude. - Triggers on hard gates (e.g. iOS .swift files), escalation score, build failure, low reflection confidence, or explicit user request. - Summarizes context, rationale, proposed plan, local attempts, and provides ready-to-run Claude commands. - Helps users control Claude Max quota usage with clear cost estimates.","fileCount":4,"zipByteSize":12326}]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install s1781macwsy8b25gaqa558qrx5858x3k:claude-handoff","setupComplexity":"low","setupSteps":["Setup complexity is LOW. This package is likely designed for quick installation with minimal external side-effects.","Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-stephenlthorn-claude-handoff/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-stephenlthorn-claude-handoff/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-stephenlthorn-claude-handoff/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-stephenlthorn-claude-handoff/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-stephenlthorn-claude-handoff/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-stephenlthorn-claude-handoff/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-12T21:01:54.031Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-stephenlthorn-claude-handoff/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-stephenlthorn-claude-handoff/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-stephenlthorn-claude-handoff/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-stephenlthorn-claude-handoff/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"high","updatedAt":"2026-10-11T22:40:20.519Z","emptyReason":null},"readme":"Skill: Claude Handoff\n\nOwner: stephenlthorn\n\nSummary: Writes a structured handoff package when local agent determines cloud Claude Code is needed. This is the ONLY path from local pipeline to cloud — the agent n...\n\nTags: latest:1.0.0\n\nVersion history:\n\nv1.0.0 | 2026-04-21T13:46:35.122Z | auto\n\nclaude-handoff 1.0.0\n\n- Initial release of the Claude Handoff skill.\n- Generates a structured handoff package when local agent determines cloud Claude Code is needed.\n- Supports user review and manual approval before any Claude Code invocation; never auto-invokes Claude.\n- Triggers on hard gates (e.g. iOS .swift files), escalation score, build failure, low reflection confidence, or explicit user request.\n- Summarizes context, rationale, proposed plan, local attempts, and provides ready-to-run Claude commands.\n- Helps users control Claude Max quota usage with clear cost estimates.\n\nArchive index:\n\nArchive v1.0.0: 4 files, 12326 bytes\n\nFiles: claude_handoff.py (12088b), skill-card.md (2680b), SKILL.md (16104b), _meta.json (133b)\n\nFile v1.0.0:SKILL.md\n\n---\nname: claude-handoff\nversion: 1.0.0\ndescription: |\n  Writes a structured handoff package when local agent determines cloud\n  Claude Code is needed. This is the ONLY path from local pipeline to cloud —\n  the agent never auto-invokes Claude. The user reviews the handoff, decides\n  whether to run Claude Code, and retains full control over Max quota spend.\ntriggers:\n  - hard gate hit (iOS .swift file in scope)\n  - soft gate exceeded (escalation score >= 8)\n  - build feedback exhausted (3 failed iterations)\n  - reflection confidence LOW after max passes\n  - explicit user request: \"hand this to Claude\"\ntools:\n  - file-system\n  - shell\n  - notify\ninputs:\n  - task: original user request\n  - reason: why we're escalating (\"hard_gate\" | \"build_failed\" | \"reflection_low_confidence\" | \"user_request\")\n  - context_gathered: RAG chunks, file reads, investigation done so far\n  - proposed_approach: plan from decompose-plan (if any)\n  - build_errors: remaining compiler errors (if build_failed)\n  - critique_history: findings from reflection passes (if any)\n  - files_in_scope: list of affected file paths\noutputs:\n  - handoff_path: path to written handoff.md\n  - command: ready-to-paste claude command\n  - summary: one-sentence description for user\nmetadata:\n  openclaw:\n    category: coding\n    tags:\n      - coding\n      - handoff\n      - escalation\n      - claude-code\n    requires_openclaw: \">=2026.3.31\"\n    binaries:\n      - python3\n---\n\n# Claude Code Handoff\n\n## The principle: never auto-invoke Claude\n\nClaude Max quota is finite. Auto-invoking on every hard task burns it\nunnecessarily and removes user control. This skill ALWAYS produces a file\nand notifies the user — it never calls the Claude API directly.\n\nThe user reviews the handoff, decides if they want to spend quota on it,\nthen runs Claude Code themselves. This is the contract.\n\n## Handoff package format\n\nWritten to `{project_root}/.openclaw-skills/handoffs/{timestamp}-{slug}.md`\n\n```markdown\n---\ntimestamp: 2026-04-21T14:32:18Z\ntask_slug: add-swiftdata-cloudkit-migration\nreason: iOS domain (hard gate)\norchestrator_version: 1.0.0\nlocal_model: m27-jangtq-crack\n---\n\n# Handoff: Add SwiftData + CloudKit migration for iOS 26\n\n## Original request\n[verbatim user request]\n\n## Why this is being handed off\n**Reason**: iOS domain hard gate\n\nLocal M2.7 JANGTQ-CRACK's Swift training data is stale on SwiftData + CloudKit\nmigrations for iOS 26. This is a case where Claude Sonnet 4.6's more recent\ntraining plus 1M context beats retrieved RAG snippets.\n\n## Context gathered locally\n\n### Files read\n- `App/AppDelegate.swift` (112 lines)\n- `Models/User.swift` (48 lines)\n- `Models/UserDataSource.swift` (204 lines)\n- `Views/ContentView.swift` (89 lines)\n\n### Codebase patterns identified\n- Project uses SwiftData with `@Model` macro\n- Existing SwiftData stack in `Models/UserDataSource.swift:42`\n- No CloudKit integration yet\n- Deployment target: iOS 18, need to upgrade to iOS 26 first\n\n### Relevant Apple documentation retrieved\n1. [SwiftData CloudKit integration guide (iOS 26)](ref-link)\n2. [iOS 26 migration patterns for SwiftData](ref-link)\n3. [CloudKit schema synchronization](ref-link)\n\n### Related Stack Overflow patterns\n[if any]\n\n## Proposed approach (from local planning)\n\nSub-problems identified:\n1. **Update deployment target to iOS 26** (AppDelegate, Info.plist)\n2. **Add CloudKit entitlement** (project settings)\n3. **Migrate UserDataSource to use CloudKit-backed ModelContainer**\n   - Depends on sub-problem 1\n4. **Add migration plan for existing local data**\n   - Depends on sub-problem 3\n5. **Update Views to handle CloudKit sync state**\n   - Depends on sub-problem 3\n\nAPIs involved:\n- `ModelConfiguration(cloudKitDatabase:)` — iOS 26+\n- `CKContainer.applicationDefault()` — iOS 8+\n- `SchemaMigrationPlan` — iOS 26+\n\nRisks:\n- HIGH: Existing local user data could be lost if migration not handled\n- MEDIUM: CloudKit development vs production environment confusion\n- LOW: iOS version compatibility for existing users on < 26\n\n## What local attempted and failed\n\n[if build_failed]\nGenerated code that attempted the migration. Compile errors:\n- Error 1: `cannot find 'cloudKitDatabase' in scope at ModelConfiguration.swift:12`\n  (Fixed in iteration 2 — was missing import)\n- Error 2: `'SchemaMigrationPlan' is only available in iOS 26.0 or newer`\n  (Unable to fix — need guidance on availability strategy)\n\n## Suggested Claude Code prompt\n\nCopy-paste this into Claude Code:\n\n```\nRead /Users/stephen/projects/myapp/.openclaw-skills/handoffs/2026-04-21T14:32:18Z-add-swiftdata-cloudkit-migration.md\n\nThen implement the 5 sub-problems in order. You have write access to the\nproject. Run `swift build` after each sub-problem to verify.\n\nWhen done, produce a summary of what changed and any remaining concerns.\n```\n\nOr run from terminal:\n```bash\ncd /Users/stephen/projects/myapp\nclaude \"Read .openclaw-skills/handoffs/2026-04-21T14:32:18Z-add-swiftdata-cloudkit-migration.md and implement the plan\"\n```\n\n## Estimated Claude quota cost\nBased on context size: ~12K input tokens + ~8K output = ~20K tokens.\nSonnet 4.6: ~20K × $3/$15 per MTok = ~$0.15 in direct API equivalent.\nVia Max plan: draws modestly from your daily quota.\n\n---\n*Generated by coding-orchestrator v1.0.0*\n```\n\n## Execution\n\n```python\nimport asyncio\nimport json\nimport re\nfrom pathlib import Path\nfrom datetime import datetime, timezone\n\n\nHANDOFF_TEMPLATE = \"\"\"---\ntimestamp: {timestamp}\ntask_slug: {slug}\nreason: {reason_detail}\norchestrator_version: 1.0.0\nlocal_model: m27-jangtq-crack\n---\n\n# Handoff: {task_title}\n\n## Original request\n{task}\n\n## Why this is being handed off\n**Reason**: {reason_detail}\n\n{reason_explanation}\n\n## Context gathered locally\n\n### Files read\n{files_read_section}\n\n### Codebase patterns identified\n{patterns_section}\n\n### Relevant documentation retrieved\n{docs_section}\n\n## Proposed approach (from local planning)\n{plan_section}\n\n## What local attempted and failed\n{attempt_section}\n\n## Suggested Claude Code prompt\n\nCopy-paste this into Claude Code:\n\n```\nRead {handoff_path}\n\nThen implement the plan above. You have write access to the project.\n{execution_guidance}\n\nWhen done, produce a summary of what changed and any remaining concerns.\n```\n\nOr run from terminal:\n```bash\ncd {project_root}\nclaude \"Read {handoff_path_relative} and implement the plan\"\n```\n\n## Estimated Claude quota cost\nBased on context size: ~{input_tokens}K input + ~{output_tokens}K output = ~{total_tokens}K tokens.\n\n---\n*Generated by coding-orchestrator v1.0.0*\n\"\"\"\n\n\nREASON_EXPLANATIONS = {\n    \"hard_gate\": \"\"\"Local M2.7 JANGTQ-CRACK's Swift training data is 2+ years stale.\niOS/Swift work consistently benefits from Sonnet 4.6's more recent training\nand deeper Apple framework knowledge.\"\"\",\n\n    \"build_failed\": \"\"\"Local model generated code that failed to compile after 3\niterations. The remaining errors suggest the model is missing context that\nisn't in our RAG — likely an API interaction or constraint not present in\ntraining or retrieved docs.\"\"\",\n\n    \"reflection_low_confidence\": \"\"\"After reflection passes, local model's confidence\nin its own output is LOW. This usually means the model recognizes the code\nmight work but isn't sure — a strong signal to get a second opinion.\"\"\",\n\n    \"user_request\": \"\"\"User explicitly requested Claude Code handoff.\"\"\",\n\n    \"context_overflow\": \"\"\"Task requires more context than M2.7's practical window can\naccommodate. Sonnet 4.6's 1M context is the right tool.\"\"\",\n\n    \"soft_gate\": \"\"\"Escalation score exceeded threshold based on task complexity,\nfile count, and uncertainty signals.\"\"\",\n}\n\n\nasync def claude_handoff(\n    task: str,\n    reason: str,\n    context_gathered: dict = None,\n    proposed_approach: dict = None,\n    build_errors: list = None,\n    critique_history: list = None,\n    files_in_scope: list = None,\n    project_root: str = None,\n):\n    timestamp = datetime.now(timezone.utc).isoformat()\n    slug = _slugify(task)[:50]\n    project_root = Path(project_root or \".\")\n\n    # Build each section\n    sections = {\n        \"timestamp\": timestamp,\n        \"slug\": slug,\n        \"reason_detail\": _reason_to_human(reason),\n        \"reason_explanation\": REASON_EXPLANATIONS.get(reason, \"\"),\n        \"task\": task,\n        \"task_title\": _summarize_task(task),\n        \"files_read_section\": _format_files(context_gathered),\n        \"patterns_section\": _format_patterns(context_gathered),\n        \"docs_section\": _format_docs(context_gathered),\n        \"plan_section\": _format_plan(proposed_approach),\n        \"attempt_section\": _format_attempt(build_errors, critique_history),\n        \"input_tokens\": _estimate_input_tokens(context_gathered, proposed_approach) // 1000,\n        \"output_tokens\": 8,\n        \"total_tokens\": 20,\n        \"execution_guidance\": _execution_guidance(proposed_approach, files_in_scope),\n    }\n\n    # Write handoff file\n    handoff_dir = project_root / \".openclaw-skills\" / \"handoffs\"\n    handoff_dir.mkdir(parents=True, exist_ok=True)\n    handoff_path = handoff_dir / f\"{timestamp.replace(':', '-')}-{slug}.md\"\n\n    sections[\"handoff_path\"] = str(handoff_path.absolute())\n    sections[\"handoff_path_relative\"] = str(handoff_path.relative_to(project_root))\n    sections[\"project_root\"] = str(project_root.absolute())\n\n    content = HANDOFF_TEMPLATE.format(**sections)\n    handoff_path.write_text(content)\n\n    # Build the paste-ready command\n    command = (\n        f'cd {project_root.absolute()} && '\n        f'claude \"Read {sections[\"handoff_path_relative\"]} and implement the plan\"'\n    )\n\n    # Summary for user notification\n    summary = f\"Handoff ready: {_summarize_task(task)} → Claude Code\"\n\n    # Notify user via OpenClaw messaging channels\n    await notify_user(\n        title=\"🤖 Claude Code handoff ready\",\n        body=f\"{summary}\\n\\nPath: {sections['handoff_path_relative']}\\n\\n\"\n             f\"Run: {command}\",\n        level=\"info\"\n    )\n\n    return {\n        \"handoff_path\": str(handoff_path.absolute()),\n        \"command\": command,\n        \"summary\": summary\n    }\n\n\ndef _slugify(text):\n    \"\"\"Convert task text to filesystem-safe slug.\"\"\"\n    slug = re.sub(r'[^\\w\\s-]', '', text.lower())\n    slug = re.sub(r'[\\s_-]+', '-', slug)\n    return slug.strip('-')\n\n\ndef _reason_to_human(reason):\n    mapping = {\n        \"hard_gate\": \"iOS domain (hard gate)\",\n        \"build_failed\": \"Build errors unfixable locally\",\n        \"reflection_low_confidence\": \"Low reflection confidence\",\n        \"user_request\": \"User requested handoff\",\n        \"context_overflow\": \"Task exceeds local context\",\n        \"soft_gate\": \"Complexity threshold exceeded\",\n    }\n    return mapping.get(reason, reason)\n\n\ndef _summarize_task(task):\n    \"\"\"Extract first sentence or 80 chars for title.\"\"\"\n    first_sentence = task.split('.')[0].strip()\n    if len(first_sentence) > 80:\n        return first_sentence[:77] + \"...\"\n    return first_sentence\n\n\ndef _format_files(ctx):\n    if not ctx or \"files_read\" not in ctx:\n        return \"(none)\"\n    lines = []\n    for f in ctx[\"files_read\"]:\n        if isinstance(f, dict):\n            lines.append(f\"- `{f['path']}` ({f.get('lines', '?')} lines)\")\n        else:\n            lines.append(f\"- `{f}`\")\n    return \"\\n\".join(lines)\n\n\ndef _format_patterns(ctx):\n    if not ctx or \"patterns\" not in ctx:\n        return \"(none identified)\"\n    return \"\\n\".join(f\"- {p}\" for p in ctx[\"patterns\"])\n\n\ndef _format_docs(ctx):\n    if not ctx or \"retrieved_docs\" not in ctx:\n        return \"(none retrieved)\"\n    return \"\\n\".join(\n        f\"{i+1}. {d.get('title', d['url'])}\"\n        for i, d in enumerate(ctx[\"retrieved_docs\"])\n    )\n\n\ndef _format_plan(plan):\n    if not plan:\n        return \"(no plan developed — task escalated before planning)\"\n\n    output = [\"Sub-problems identified:\"]\n    for i, sp in enumerate(plan.get(\"sub_problems\", []), 1):\n        output.append(f\"{i}. **{sp['title']}**\")\n        output.append(f\"   {sp.get('description', '')}\")\n        if sp.get(\"depends_on\"):\n            output.append(f\"   Depends on: {', '.join(sp['depends_on'])}\")\n        output.append(\"\")\n\n    if plan.get(\"apis\"):\n        output.append(\"\\nAPIs involved:\")\n        for api in plan[\"apis\"]:\n            output.append(f\"- `{api['name']}` — {api.get('version_requirement', 'any')}\")\n\n    if plan.get(\"risks\"):\n        output.append(\"\\nRisks:\")\n        for r in plan[\"risks\"]:\n            output.append(f\"- {r.get('severity', 'MEDIUM').upper()}: {r['risk']}\")\n            if r.get(\"mitigation\"):\n                output.append(f\"  Mitigation: {r['mitigation']}\")\n\n    return \"\\n\".join(output)\n\n\ndef _format_attempt(build_errors, critique_history):\n    if not build_errors and not critique_history:\n        return \"(no prior attempts — escalated before code generation)\"\n\n    output = []\n    if build_errors:\n        output.append(\"Build errors remaining after fix attempts:\")\n        for err in build_errors[:10]:  # cap at 10\n            output.append(f\"- `{err['file']}:{err['line']}`: {err['message']}\")\n        if len(build_errors) > 10:\n            output.append(f\"- ... and {len(build_errors) - 10} more\")\n\n    if critique_history:\n        output.append(\"\\nReflection pass findings:\")\n        for pass_result in critique_history:\n            output.append(f\"\\n**Pass {pass_result['pass']}**:\")\n            output.append(pass_result['critique'][:500])\n\n    return \"\\n\".join(output)\n\n\ndef _execution_guidance(plan, files):\n    if not plan:\n        return \"Investigate the codebase, form a plan, then implement.\"\n\n    order = plan.get(\"order\", [])\n    if order:\n        return f\"Implement the {len(order)} sub-problems in the listed order. \"\\\n               f\"Run tests after each sub-problem.\"\n    return \"Implement the proposed approach.\"\n\n\ndef _estimate_input_tokens(ctx, plan):\n    \"\"\"Rough token estimate for quota budgeting.\"\"\"\n    total = 1000  # base overhead\n    if ctx:\n        for f in ctx.get(\"files_read\", []):\n            total += f.get(\"lines\", 100) * 8  # ~8 tokens per line\n        for d in ctx.get(\"retrieved_docs\", []):\n            total += 500\n    if plan:\n        total += 1000\n    return total\n\n\nasync def notify_user(title, body, level=\"info\"):\n    \"\"\"Send notification via OpenClaw's messaging channels.\"\"\"\n    # OpenClaw notifies via WhatsApp, Telegram, Discord based on user config\n    await openclaw.notify(title=title, body=body, level=level)\n    # Also write to a dashboard file for status checking\n    status_file = Path(\".openclaw-skills/last_notification.json\")\n    status_file.write_text(json.dumps({\n        \"title\": title, \"body\": body, \"timestamp\": datetime.now().isoformat()\n    }))\n```\n\n## Integration with other skills\n\n- Invoked by `coding-orchestrator` at multiple points (hard gate, after\n  failed build, after failed reflection)\n- Reads context from `task.scratchpad` populated by earlier steps\n- Writes to project's `.openclaw-skills/handoffs/` directory\n- Adds entry to global handoff log at `~/.openclaw-skills/handoff-log.sqlite`\n\n## Handoff log for analytics\n\nEvery handoff gets logged to SQLite:\n\n```sql\nCREATE TABLE handoff_log (\n    id INTEGER PRIMARY KEY,\n    timestamp TEXT NOT NULL,\n    task_slug TEXT NOT NULL,\n    reason TEXT NOT NULL,\n    project_root TEXT,\n    estimated_tokens INTEGER,\n    user_ran_claude BOOLEAN,  -- updated when user runs claude\n    claude_succeeded BOOLEAN,  -- updated manually or via claude output log\n    notes TEXT\n);\n```\n\nQuery this log periodically to understand your escalation patterns:\n- Which reasons are most common? (if \"build_failed\" dominates, improve\n  your iOS system prompt or RAG)\n- How often do handoffs actually get run? (if low, your escalation threshold\n  is too aggressive)\n- How often does Claude Code succeed? (if it fails too, the task genuinely\n  needs architectural input from you)\n\n## What handoff does NOT do\n\n- Does not execute Claude Code\n- Does not read your Claude Max quota\n- Does not cache or share handoffs between users\n- Does not modify source code (only writes to `.openclaw-skills/handoffs/`)\n\nThese are all explicit user actions. The skill's job is to prepare the best\npossible brief and then step aside.\n\nFile v1.0.0:_meta.json\n\n{\n  \"ownerId\": \"kn7c2bd0k76aqthvnncn5ck475859yfw\",\n  \"slug\": \"claude-handoff\",\n  \"version\": \"1.0.0\",\n  \"publishedAt\": 1776779195122\n}\n\nFile v1.0.0:skill-card.md\n\n## Description:\n\nWrites a structured handoff package when a local agent determines cloud Claude Code is needed, while leaving Claude Code execution under user control.\n\nThis skill is ready for commercial/non-commercial use.\n\n## Publisher:\n\n[stephenlthorn](https://clawhub.ai/user/stephenlthorn)\n\n### License/Terms of Use:\n\nMIT-0\n\n## Use Case:\n\nDevelopers and coding agents use this skill to prepare a structured Claude Code handoff when local work reaches an escalation gate, build-failure limit, low-confidence review, context limit, or explicit user request. It captures task context, local findings, a proposed plan, and a ready-to-run command so the user can review the handoff before spending Claude Max quota.\n\n### Deployment Geography for Use:\n\nGlobal\n\n## Known Risks and Mitigations:\n\nRisk: Generated handoff files can contain task details, project context, file paths, build errors, and other sensitive development information.\n\nMitigation: Review the generated Markdown handoff for secrets, proprietary details, and unnecessary context before sending it to Claude Code.\n\nRisk: Notification behavior can transmit handoff metadata when OPENCLAW_NOTIFY_ENDPOINT is configured.\n\nMitigation: Unset OPENCLAW_NOTIFY_ENDPOINT or restrict it to a trusted endpoint before using the skill in sensitive projects.\n\nRisk: The ready-to-paste shell command includes the project path and should be treated carefully for projects with unusual or untrusted path names.\n\nMitigation: Inspect and edit the command before running it, especially when the project path was created from external input.\n\nRisk: The skill writes local status and handoff-log files that may preserve metadata after the handoff is complete.\n\nMitigation: Review retention expectations for .openclaw-skills files and remove local handoff or log artifacts when they are no longer needed.\n\n## Reference(s):\n\n- [ClawHub skill page](https://clawhub.ai/stephenlthorn/skills/claude-handoff)\n\n## Skill Output:\n\n**Output Type(s):** [text, markdown, shell commands, configuration, guidance]\n\n**Output Format:** [Markdown handoff file with a ready-to-paste shell command and short text summary]\n\n**Output Parameters:** [1D]\n\n**Other Properties Related to Output:** [Writes a local handoff file under .openclaw-skills/handoffs and may write local notification and handoff-log files.]\n\n## Skill Version(s):\n\n1.0.0 (source: frontmatter and server release evidence)\n\n## Ethical Considerations:\n\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment.","readmeExcerpt":"Skill: Claude Handoff Owner: stephenlthorn Summary: Writes a structured handoff package when local agent determines cloud Claude Code is needed. This is the ONLY path from local pipeline to cloud — the agent n... Tags: latest:1.0.0 Version history: v1.0.0 | 2026-04-21T13:46:35.122Z | auto claude-handoff 1.0.0 - Initial release of the Claude Handoff skill. - Generates a structured handoff package when local agent dete","codeSnippets":[],"executableExamples":[{"language":"markdown","snippet":"---\ntimestamp: 2026-04-21T14:32:18Z\ntask_slug: add-swiftdata-cloudkit-migration\nreason: iOS domain (hard gate)\norchestrator_version: 1.0.0\nlocal_model: m27-jangtq-crack\n---\n\n# Handoff: Add SwiftData + CloudKit migration for iOS 26\n\n## Original request\n[verbatim user request]\n\n## Why this is being handed off\n**Reason**: iOS domain hard gate\n\nLocal M2.7 JANGTQ-CRACK's Swift training data is stale on SwiftData + CloudKit\nmigrations for iOS 26. This is a case where Claude Sonnet 4.6's more recent\ntraining plus 1M context beats retrieved RAG snippets.\n\n## Context gathered locally\n\n### Files read\n- `App/AppDelegate.swift` (112 lines)\n- `Models/User.swift` (48 lines)\n- `Models/UserDataSource.swift` (204 lines)\n- `Views/ContentView.swift` (89 lines)\n\n### Codebase patterns identified\n- Project uses SwiftData with `@Model` macro\n- Existing SwiftData stack in `Models/UserDataSource.swift:42`\n- No CloudKit integration yet\n- Deployment target: iOS 18, need to upgrade to iOS 26 first\n\n### Relevant Apple documentation retrieved\n1. [SwiftData CloudKit integration guide (iOS 26)](ref-link)\n2. [iOS 26 migration patterns for SwiftData](ref-link)\n3. [CloudKit schema synchronization](ref-link)\n\n### Related Stack Overflow patterns\n[if any]\n\n## Proposed approach (from local planning)\n\nSub-problems identified:\n1. **Update deployment target to iOS 26** (AppDelegate, Info.plist)\n2. **Add CloudKit entitlement** (project settings)\n3. **Migrate UserDataSource to use CloudKit-backed ModelContainer**\n   - Depends on sub-problem 1\n4. **Add migration plan for existing local data**\n   - Depends on sub-problem 3\n5. **Update Views to handle CloudKit sync state**\n   - Depends on sub-problem 3\n\nAPIs involved:\n- `ModelConfiguration(cloudKitDatabase:)` — iOS 26+\n- `CKContainer.applicationDefault()` — iOS 8+\n- `SchemaMigrationPlan` — iOS 26+\n\nRisks:\n- HIGH: Existing local user data could be lost if migration not handled\n- MEDIUM: CloudKit development vs production environment confusion\n- LOW: iOS version c"},{"language":"text","snippet":"Or run from terminal:"},{"language":"text","snippet":"## Estimated Claude quota cost\nBased on context size: ~12K input tokens + ~8K output = ~20K tokens.\nSonnet 4.6: ~20K × $3/$15 per MTok = ~$0.15 in direct API equivalent.\nVia Max plan: draws modestly from your daily quota.\n\n---\n*Generated by coding-orchestrator v1.0.0*"},{"language":"python","snippet":"import asyncio\nimport json\nimport re\nfrom pathlib import Path\nfrom datetime import datetime, timezone\n\n\nHANDOFF_TEMPLATE = \"\"\"---\ntimestamp: {timestamp}\ntask_slug: {slug}\nreason: {reason_detail}\norchestrator_version: 1.0.0\nlocal_model: m27-jangtq-crack\n---\n\n# Handoff: {task_title}\n\n## Original request\n{task}\n\n## Why this is being handed off\n**Reason**: {reason_detail}\n\n{reason_explanation}\n\n## Context gathered locally\n\n### Files read\n{files_read_section}\n\n### Codebase patterns identified\n{patterns_section}\n\n### Relevant documentation retrieved\n{docs_section}\n\n## Proposed approach (from local planning)\n{plan_section}\n\n## What local attempted and failed\n{attempt_section}\n\n## Suggested Claude Code prompt\n\nCopy-paste this into Claude Code:"},{"language":"text","snippet":"Or run from terminal:"},{"language":"text","snippet":"## Estimated Claude quota cost\nBased on context size: ~{input_tokens}K input + ~{output_tokens}K output = ~{total_tokens}K tokens.\n\n---\n*Generated by coding-orchestrator v1.0.0*\n\"\"\"\n\n\nREASON_EXPLANATIONS = {\n    \"hard_gate\": \"\"\"Local M2.7 JANGTQ-CRACK's Swift training data is 2+ years stale.\niOS/Swift work consistently benefits from Sonnet 4.6's more recent training\nand deeper Apple framework knowledge.\"\"\",\n\n    \"build_failed\": \"\"\"Local model generated code that failed to compile after 3\niterations. The remaining errors suggest the model is missing context that\nisn't in our RAG — likely an API interaction or constraint not present in\ntraining or retrieved docs.\"\"\",\n\n    \"reflection_low_confidence\": \"\"\"After reflection passes, local model's confidence\nin its own output is LOW. This usually means the model recognizes the code\nmight work but isn't sure — a strong signal to get a second opinion.\"\"\",\n\n    \"user_request\": \"\"\"User explicitly requested Claude Code handoff.\"\"\",\n\n    \"context_overflow\": \"\"\"Task requires more context than M2.7's practical window can\naccommodate. Sonnet 4.6's 1M context is the right tool.\"\"\",\n\n    \"soft_gate\": \"\"\"Escalation score exceeded threshold based on task complexity,\nfile count, and uncertainty signals.\"\"\",\n}\n\n\nasync def claude_handoff(\n    task: str,\n    reason: str,\n    context_gathered: dict = None,\n    proposed_approach: dict = None,\n    build_errors: list = None,\n    critique_history: list = None,\n    files_in_scope: list = None,\n    project_root: str = None,\n):\n    timestamp = datetime.now(timezone.utc).isoformat()\n    slug = _slugify(task)[:50]\n    project_root = Path(project_root or \".\")\n\n    # Build each section\n    sections = {\n        \"timestamp\": timestamp,\n        \"slug\": slug,\n        \"reason_detail\": _reason_to_human(reason),\n        \"reason_explanation\": REASON_EXPLANATIONS.get(reason, \"\"),\n        \"task\": task,\n        \"task_title\": _summarize_task(task),\n        \"files_read_section\": _format_files(context_gathered),\n   "}],"parameters":null,"dependencies":[],"permissions":[],"extractedFiles":[{"path":"SKILL.md","content":"---\nname: claude-handoff\nversion: 1.0.0\ndescription: |\n  Writes a structured handoff package when local agent determines cloud\n  Claude Code is needed. This is the ONLY path from local pipeline to cloud —\n  the agent never auto-invokes Claude. The user reviews the handoff, decides\n  whether to run Claude Code, and retains full control over Max quota spend.\ntriggers:\n  - hard gate hit (iOS .swift file in scope)\n  - soft gate exceeded (escalation score >= 8)\n  - build feedback exhausted (3 failed iterations)\n  - reflection confidence LOW after max passes\n  - explicit user request: \"hand this to Claude\"\ntools:\n  - file-system\n  - shell\n  - notify\ninputs:\n  - task: original user request\n  - reason: why we're escalating (\"hard_gate\" | \"build_failed\" | \"reflection_low_confidence\" | \"user_request\")\n  - context_gathered: RAG chunks, file reads, investigation done so far\n  - proposed_approach: plan from decompose-plan (if any)\n  - build_errors: remaining compiler errors (if build_failed)\n  - critique_history: findings from reflection passes (if any)\n  - files_in_scope: list of affected file paths\noutputs:\n  - handoff_path: path to written handoff.md\n  - command: ready-to-paste claude command\n  - summary: one-sentence description for user\nmetadata:\n  openclaw:\n    category: coding\n    tags:\n      - coding\n      - handoff\n      - escalation\n      - claude-code\n    requires_openclaw: \">=2026.3.31\"\n    binaries:\n      - python3\n---\n\n# Claude Code Handoff\n\n## The principle: never auto-invoke Claude\n\nClaude Max quota is finite. Auto-invoking on every hard task burns it\nunnecessarily and removes user control. This skill ALWAYS produces a file\nand notifies the user — it never calls the Claude API directly.\n\nThe user reviews the handoff, decides if they want to spend quota on it,\nthen runs Claude Code themselves. This is the contract.\n\n## Handoff package format\n\nWritten to `{project_root}/.openclaw-skills/handoffs/{timestamp}-{slug}.md`\n\n```markdown\n---\ntimestamp: 2026-04-21T14:32:18Z\ntask_slug: add-swiftdata-cloudkit-migration\nreason: iOS domain (hard gate)\norchestrator_version: 1.0.0\nlocal_model: m27-jangtq-crack\n---\n\n# Handoff: Add SwiftData + CloudKit migration for iOS 26\n\n## Original request\n[verbatim user request]\n\n## Why this is being handed off\n**Reason**: iOS domain hard gate\n\nLocal M2.7 JANGTQ-CRACK's Swift training data is stale on SwiftData + CloudKit\nmigrations for iOS 26. This is a case where Claude Sonnet 4.6's more recent\ntraining plus 1M context beats retrieved RAG snippets.\n\n## Context gathered locally\n\n### Files read\n- `App/AppDelegate.swift` (112 lines)\n- `Models/User.swift` (48 lines)\n- `Models/UserDataSource.swift` (204 lines)\n- `Views/ContentView.swift` (89 lines)\n\n### Codebase patterns identified\n- Project uses SwiftData with `@Model` macro\n- Existing SwiftData stack in `Models/UserDataSource.swift:42`\n- No CloudKit integration yet\n- Deployment target: iOS 18, need to upgrade to iOS 26 first\n\n### Relevant Apple documentation retrieved\n1. [S"},{"path":"_meta.json","content":"{\n  \"ownerId\": \"kn7c2bd0k76aqthvnncn5ck475859yfw\",\n  \"slug\": \"claude-handoff\",\n  \"version\": \"1.0.0\",\n  \"publishedAt\": 1776779195122\n}"},{"path":"skill-card.md","content":"## Description:\n\nWrites a structured handoff package when a local agent determines cloud Claude Code is needed, while leaving Claude Code execution under user control.\n\nThis skill is ready for commercial/non-commercial use.\n\n## Publisher:\n\n[stephenlthorn](https://clawhub.ai/user/stephenlthorn)\n\n### License/Terms of Use:\n\nMIT-0\n\n## Use Case:\n\nDevelopers and coding agents use this skill to prepare a structured Claude Code handoff when local work reaches an escalation gate, build-failure limit, low-confidence review, context limit, or explicit user request. It captures task context, local findings, a proposed plan, and a ready-to-run command so the user can review the handoff before spending Claude Max quota.\n\n### Deployment Geography for Use:\n\nGlobal\n\n## Known Risks and Mitigations:\n\nRisk: Generated handoff files can contain task details, project context, file paths, build errors, and other sensitive development information.\n\nMitigation: Review the generated Markdown handoff for secrets, proprietary details, and unnecessary context before sending it to Claude Code.\n\nRisk: Notification behavior can transmit handoff metadata when OPENCLAW_NOTIFY_ENDPOINT is configured.\n\nMitigation: Unset OPENCLAW_NOTIFY_ENDPOINT or restrict it to a trusted endpoint before using the skill in sensitive projects.\n\nRisk: The ready-to-paste shell command includes the project path and should be treated carefully for projects with unusual or untrusted path names.\n\nMitigation: Inspect and edit the command before running it, especially when the project path was created from external input.\n\nRisk: The skill writes local status and handoff-log files that may preserve metadata after the handoff is complete.\n\nMitigation: Review retention expectations for .openclaw-skills files and remove local handoff or log artifacts when they are no longer needed.\n\n## Reference(s):\n\n- [ClawHub skill page](https://clawhub.ai/stephenlthorn/skills/claude-handoff)\n\n## Skill Output:\n\n**Output Type(s):** [text, markdown, shell commands, configuration, guidance]\n\n**Output Format:** [Markdown handoff file with a ready-to-paste shell command and short text summary]\n\n**Output Parameters:** [1D]\n\n**Other Properties Related to Output:** [Writes a local handoff file under .openclaw-skills/handoffs and may write local notification and handoff-log files.]\n\n## Skill Version(s):\n\n1.0.0 (source: frontmatter and server release evidence)\n\n## Ethical Considerations:\n\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment."}],"languages":[],"docsSourceLabel":"CLAWHUB","editorialOverview":"Writes a structured handoff package when local agent determines cloud Claude Code is needed. This is the ONLY path from local pipeline to cloud — the agent n... Skill: Claude Handoff Owner: stephenlthorn Summary: Writes a structured handoff package when local agent determines cloud Claude Code is needed. This is the ONLY path from local pipeline to cloud — the agent n... Tags: latest:1.0.0 Version history: v1.0.0 | 2026-04-21T13:46:35.122Z | auto claude-handoff 1.0.0 - Initial release of the Claude Handoff skill. - Generates a structured handoff package when local agent dete","editorialQuality":{"score":100,"threshold":65,"status":"ready","wordCount":1239,"uniquenessScore":48,"reasons":[]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-10-11T22:40:20.519Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-10-11T22:40:20.519Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-12T21:01:54.032Z","emptyReason":null},"items":[{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-10-09T19:11:12.944Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}