Skill: athola/nm-conjure-delegation-core (version 1.0.2)

--- name: delegation-core description: Delegate tasks to external LLM services (Gemini, Qwen) with quota, logging, version: 1.9.5 triggers: - delegation - external-llm - gemini - qwen - task-management - quality-control metadata: {"openclaw": {"homepage": "https://github.com/athola/claude-night-market/tree/master/plugins/conjure", "emoji": "\ud83e\udd9e", "requires": {"config": ["night-market.leyline:quota-management", "night-market.leyline:usage-logging", "night-market.leyline:service-registry", "night-market.leyline:error-patterns", "night-market.leyline:authentication-patterns"]}}} source: claude-night-market source_plugin: conjure --- > **Night Market Skill** — ported from [claude-night-market/conjure](https://github.com/athola/claude-night-market/tree/master/plugins/conjure). For the full experience with agents, hooks, and commands, install the Claude Code plugin. ## Table of Contents - [Overview](#overview) - [When to Use](#when-to-use) - [Philosophy](#philosophy) - [Delegation Flow](#delegation-flow) - [Quick Decision Matrix](#quick-decision-matrix) - [Detailed Workflow Steps](#detailed-workflow-steps) - [1. Task Assessment (`delegation-core:task-assessed`)](#1-task-assessment-delegation-coretask-assessed) - [2. Suitability Evaluation (`delegation-core:delegation-suitability`)](#2-suitability-evaluation-delegation-coredelegation-suitability) - [3. Handoff Planning (`delegation-core:handoff-planned`)](#3-handoff-planning-delegation-corehandoff-planned) - [4. Execution & Integration (`delegation-core:results-integrated`)](#4-execution-integration-delegation-coreresults-integrated) - [Leyline Infrastructure](#leyline-infrastructure) - [Service-Specific Skills](#service-specific-skills) - [Module Reference](#module-reference) - [Exit Criteria](#exit-criteria) # Delegation Core Framework ## Overview A method for deciding when and how to delegate tasks to external LLM services. Core principle: **delegate execution, retain high-level reasoning**. ## When To Use - Before invoking external LLMs for task assistance. - When operations are token-heavy and exceed local context limits. - When batch processing benefits from different model characteristics. - When tasks require routing between models. ## When NOT To Use - Task requires reasoning by Claude ## Philosophy **Delegate execution, retain reasoning.** Claude handles architecture, strategy, design, and review. External LLMs perform data processing, pattern extraction, bulk operations, and summarization. ## Delegation Flow 1. **Task Assessment**: Classify task by complexity and context size. 2. **Suitability Evaluation**: Check prerequisites and service fit. 3. **Handoff Planning**: Formulate request and document plan. 4. **Execution & Integration**: Run delegation, validate, and integrate results. ## Quick Decision Matrix | Complexity | Context | Recommendation | |------------|---------|----------------| | High | Any | Keep local | | Low | Large | Delegate | | Low | Small | Either | **High Complexity**: Architecture, design decisions, trade-offs, creative problem solving. **Low Complexity**: Pattern counting, bulk extraction, boilerplate generation, summarization. ## Detailed Workflow Steps ### 1. Task Assessment (`delegation-core:task-assessed`) Classify the task: - See `modules/task-assessment.md` for classification criteria. - Use token estimates to determine thresholds. - Apply the decision matrix. **Exit Criteria**: Task classified with complexity level, context size, and delegation recommendation. ### 2. Suitability Evaluation (`delegation-core:delegation-suitability`) Verify prerequisites: - See `modules/handoff-patterns.md` for checklist. - Evaluate cost-benefit ratio using `modules/cost-estimation.md`. - Check for red flags (security, real-time iteration). **Exit Criteria**: Service authenticated, quotas verified, cost justified. ### 3. Handoff Planning (`delegation-core:handoff-planned`) Create a delegation plan: - See `modules/handoff-patterns.md` for request template. - Document service, command, input context, expected output. - Define validation method. **Exit Criteria**: Delegation plan documented. ### 4. Execution & Integration (`delegation-core:results-integrated`) Execute and validate results: - Run delegation and capture output. - Validate format and correctness. - Integrate only after validation passes. - Log usage. **Exit Criteria**: Results validated and integrated, usage logged. ## MCP Authentication ### OAuth Client Credentials (Claude Code 2.1.30+) For MCP servers that don't support Dynamic Client Registration (e.g., Slack), pre-configured OAuth client credentials can be provided: ```bash claude mcp add <server-name> --client-id <id> --client-secret <secret> ``` This enables delegation workflows through MCP servers that require pre-configured OAuth, expanding the range of external services available for task delegation. ### Claude.ai MCP Connectors (Claude Code 2.1.46+) As an alternative to manual OAuth setup, users can configure MCP servers directly in claude.ai at claude.ai/settings/connectors. These connectors are automatically available in Claude Code when logged in with a claude.ai account — no `claude mcp add` or credential management required. This provides a browser-based auth flow that may be simpler for services with complex OAuth requirements. ## Worktree Isolation for File-Modifying Delegations (Claude Code 2.1.49+) When delegating tasks that modify files to subagents, use `isolation: worktree` in the agent frontmatter to run each agent in a temporary git worktree. This prevents file conflicts when multiple delegated agents operate in parallel on overlapping paths. The worktree is auto-cleaned if no changes are made; preserved with commits if the agent produces changes. ```yaml # Agent frontmatter for isolated delegation isolation: worktree ``` ## Leyline Infrastructure Conjure uses leyline infrastructure: | Leyline Skill | Used For | |---------------|----------| | `quota-management` | Track service quotas and thresholds. | | `usage-logging` | Session-aware audit trails. | | `service-registry` | Unified service configuration. | | `error-patterns` | Consistent error handling. | | `authentication-patterns` | Auth verification. | See `modules/cost-estimation.md` for leyline integration examples. ## Service-Specific Skills For detailed service workflows: - `Skill(conjure:gemini-delegation)`: Gemini CLI specifics. - `Skill(conjure:qwen-delegation)`: Qwen MCP specifics. ## Execution Modes When delegating to multiple agents, choose the appropriate execution mode: | Mode | When to Use | How It Works | |------|-------------|--------------| | single-session | Sequential tasks, same-file edits | Claude works through tasks in order | | subagents | Parallel independent tasks | Agents work independently, report back | | agent-team | Parallel coordinated tasks | Agents can communicate with each other | See `references/execution-modes.md` for the selection decision matrix, mode compatibility notes, and anti-patterns to avoid. ## Module Reference - **task-assessment.md**: Complexity classification, decision matrix. - **cost-estimation.md**: Pricing, budgets, cost tracking. - **handoff-patterns.md**: Request templates, workflows. - **troubleshooting.md**: Common problems, service failures. ## Exit Criteria - [ ] Task assessed and classified. - [ ] Delegation decision justified. - [ ] Results validated before integration. - [ ] Lessons captured.

path: modules/cost-estimation.md
content: ---
name: cost-estimation
description: Token cost calculations, budget guidelines, and cost optimization strategies for external LLM delegation
parent_skill: conjure:delegation-core
category: delegation-framework
estimated_tokens: 250
dependencies:
  - leyline:quota-management
  - leyline:usage-logging
---

# Cost Estimation and Budget Guidelines

## Service Cost Comparisons

**Gemini 2.0 Models (per 1M tokens):**
- Input: $0.50, Output: $1.50 (Pro version)
- Input: $0.075, Output: $0.30 (Flash version)
- Context: Up to 1M tokens

**Qwen Models (per 1M tokens):**
- Input: $0.20-0.50, Output: $0.60-1.20 (varies by provider)
- Context: Up to 100K+ tokens
- Sandbox execution: Typically $0.001-0.01 per request

## Cost Decision Framework

**Calculate Cost-Benefit Ratio:**
```
Cost = (input_tokens * input_rate) + (output_tokens * output_rate)
Benefit = time_saved * hourly_rate + quality_improvement_value

Delegate if: Benefit > Cost * 3 (safety margin for quality risks)
```

## Practical Cost Examples

**Low-Cost Delegations (<$0.01):**
- Count function occurrences: 50 files × 30 tokens = $0.000015
- Extract import statements: 100 files × 50 tokens = $0.000025
- Generate 10 boilerplate files: ~2K output tokens = $0.003

**Medium-Cost Delegations ($0.01-0.10):**
- Summarize 50K lines of code: ~125K tokens = $0.06-0.19
- Analyze architecture of 100 files: ~80K tokens = $0.04-0.12
- Generate 20 API endpoints: ~3K output tokens = $0.005

**High-Cost Delegations ($0.10+):**
- Review entire codebase (500K+ tokens): $0.25-0.75
- Generate detailed documentation: $0.15-0.45
- Complex refactoring analysis: $0.20-0.60

## Cost Optimization Strategies

**Input Optimization:**
- Remove comments, tests, examples when not needed
- Use selective file patterns instead of entire directories
- Pre-filter with grep/awk for relevant content
- Compress multiple small queries into one request

**Model Selection:**
- Use Flash/cheaper models for simple extraction tasks
- Reserve Pro models for complex analysis only
- Consider batch processing for repetitive tasks

### Cheapest-Capable Model Selection

When dispatching subagents, select the cheapest model
that can handle the task. This is a recommendation,
not a mandate; override when judgment dictates.

| Task Type | Has Detailed Plan? | Recommended Model |
|-----------|-------------------|-------------------|
| Implementation | Yes | haiku |
| Implementation | No | sonnet |
| Planning/reasoning | Any | sonnet/opus |
| Security/safety review | Any | sonnet minimum, prefer opus |
| Code review | Any | sonnet minimum |

**Security/safety task types** (never downgrade):
- Security audit
- Secret scanning
- Permissions analysis
- Auth-critical review
- Dependency vulnerability scanning

If a code review surfaces security-relevant findings,
the reviewer should note "security-relevant" in its
output to prevent downstream model downgrade.

**Fallback**: When a downgrade rule triggers but the
task type is ambiguous, default to sonnet.

**Rationale**: Implementation tasks with detailed plans
are well-scoped and predictable; haiku handles these
effectively. Planning and security tasks require
reasoning depth that cheaper models may lack.

**Alternative Strategies:**
- Break large tasks into smaller, targeted analyses
- Use local processing for sensitive operations
- Cache results for repeated analysis requests

## Cost Monitoring

**Set Daily/Weekly Budgets:**
- Development: $1-5/day
- Batch processing: $10-50/month
- Enterprise: $100-500/month

**Tracking Methods:**
- Use built-in usage logging tools
- Monitor API dashboard for consumption
- Set up alerts for unexpected spikes

**Using Leyline for Cost Tracking:**

```python
from leyline.quota_tracker import QuotaTracker
from leyline.usage_logger import UsageLogger

# Initialize for your service
tracker = QuotaTracker(service="gemini")
logger = UsageLogger(service="gemini")

# Check quota before operation
level, warnings = tracker.get_quota_status()
if level == "critical":
    # Defer or use secondary logic
    pass

# Log after operation
logger.log_usage("analyze_files", tokens=5000, success=True, duration=2.5)
```


path: modules/handoff-patterns.md
content: ---
name: handoff-patterns
description: Request formulation templates and documentation patterns for delegating tasks to external LLMs
parent_skill: conjure:delegation-core
category: delegation-framework
estimated_tokens: 180
dependencies:
  - leyline:service-registry
  - leyline:authentication-patterns
---

# Handoff Patterns and Request Formulation

## Suitability Evaluation

**Check Prerequisites:**
- [ ] Authenticate and verify external service is reachable
- [ ] Confirm quota/rate limits have capacity for the task
- [ ] Verify task does not involve sensitive data requiring local processing
- [ ] Verify expected output format is well-defined

**Evaluate Service Fit:**
- Does the external model excel at this task type?
- Is the latency acceptable for the workflow?
- Can results be easily validated?

## Request Formulation

**Four-Step Process:**
1. Write a clear, self-contained prompt
2. Include all necessary context (files, constraints, examples)
3. Specify the exact output format expected
4. Define success criteria for validation

## Delegation Plan Template

```markdown
## Delegation Plan
- **Service**: [Gemini CLI / Qwen MCP / Other]
- **Command/Call**: [Exact invocation]
- **Input Context**: [Files, data provided]
- **Expected Output**: [Format, content type]
- **Validation Method**: [How to verify correctness]
- **Contingency**: [What to do if delegation fails]
```

## Execution and Integration

**Execute:**
1. Run the delegation with the planned command
2. Capture full output (save to file for audit trail)
3. Log usage metrics (tokens, duration, success/failure)

**Validate:**
- Does output match the expected format?
- Are results factually plausible?
- Do code suggestions compile/lint?
- Are there obvious errors or hallucinations?

**Integrate:**
- Apply results only after validation
- Document what was delegated and the outcome
- Note lessons learned for future delegations

## Collaborative Workflows

For complex tasks requiring both intelligence AND scale:

```
1. Claude: Define framework, criteria, evaluation rubric
2. External: Process data, extract patterns, generate candidates
3. Claude: Analyze results, make decisions, provide recommendations
```

**Example - Large Codebase Review:**
1. Claude: Define architectural principles to evaluate
2. Gemini: Catalog all modules, extract dependency graphs
3. Claude: Analyze patterns against principles, recommend changes

## Anti-Patterns vs Good Patterns

**Don't Delegate:**
- "Review this code and tell me if it's good" (intelligence task)
- "What's the best architecture for X?" (strategic decision)
- "Fix the bugs in this file" (requires understanding intent)

**Do Delegate:**
- "List all functions in these 50 files" (extraction)
- "Count occurrences of pattern X across codebase" (counting)
- "Generate boilerplate for these 20 endpoints" (templating)


path: modules/task-assessment.md
content: ---
name: task-assessment
description: Task classification framework for determining delegation suitability based on intelligence level and context requirements
parent_skill: conjure:delegation-core
category: delegation-framework
estimated_tokens: 200
dependencies:
  - leyline:quota-management
---

# Task Assessment for Delegation

## Intelligence Level Classification

**High Intelligence (Keep Local):**
- Architecture analysis
- Design decisions
- Trade-off evaluation
- Strategic recommendations
- Nuanced code review
- Creative problem solving

**Low Intelligence (Delegate):**
- Pattern counting
- Bulk extraction
- Boilerplate generation
- Large-file summarization
- Repetitive transformations

## Context Requirements

**Large Context (Favor Delegation):**
- Multi-file analysis
- Codebase-wide searches
- Log processing

**Small Context (Either):**
- Single-file operations
- Focused queries

## Decision Matrix

| Intelligence | Context | Recommendation |
|-------------|---------|----------------|
| High | Any | Keep local |
| Low | Large | Delegate |
| Low | Small | Either |

## Assessment Checklist

Record the following for each task:
- [ ] **Task Objective**: What needs to be accomplished?
- [ ] **Files Involved**: How many and what size?
- [ ] **Intelligence Level**: High or Low?
- [ ] **Context Size**: Large or Small?
- [ ] **Failure Impact**: What happens if delegation fails?

## Token Usage Estimates

**Low Intelligence Tasks (Good for Delegation):**
- Pattern counting across files: 10-50 tokens/file
- Bulk data extraction: 20-100 tokens/file
- Boilerplate generation: 100-500 tokens/template
- Large file summarization: 1-5% of file size tokens

**Context Size Estimations:**
- Single Python file (500 lines): ~2,000-3,000 tokens
- Small module (10 files): ~15,000-25,000 tokens
- Medium project (50 files): ~75,000-150,000 tokens
- Large codebase (200+ files): 300,000+ tokens

**Delegation Thresholds:**
- **Efficient to delegate**: >25,000 total tokens or >50 files
- **Consider delegation**: 10,000-25,000 tokens or 20-50 files
- **Keep local**: <10,000 tokens and <20 files

## Red Flags (Stay Local)

- Security-sensitive operations (auth, crypto, secrets)
- Tasks requiring real-time iteration
- Complex multi-step reasoning chains
- Subjective quality judgments


path: modules/troubleshooting.md
content: ---
name: troubleshooting
description: Common delegation problems and solutions for quality control, service failures, and integration issues
parent_skill: conjure:delegation-core
category: delegation-framework
estimated_tokens: 150
dependencies:
  - leyline:error-patterns
---

# Delegation Troubleshooting Guide

## Delegation Decision Issues

**Problem: Uncertain whether to delegate**
- **Solution**: Use the decision matrix. If high intelligence required, keep local.
- **Check**: Does this task require understanding intent, context, or making judgments?

**Problem: Delegated task produces poor results**
- **Common Causes**:
  - Task was actually high-intelligence (reclassify)
  - Instructions were ambiguous (make more specific)
  - Context was insufficient (add more examples)
  - Wrong tool for the job (try different service)

**Problem: External service fails unexpectedly**
- **Immediate**: Default to local processing
- **Investigation**: Check authentication, quotas, service status
- **Prevention**: Validate prerequisites before delegation

## Quality Control Issues

**Problem: Can't validate delegated results**
- **Solution**: Break task into smaller, verifiable chunks
- **Alternative**: Include self-validation in the delegation prompt
- **Prevention**: Always define success criteria before delegating

**Problem: Results integrate poorly**
- **Common Causes**:
  - Output format mismatch (specify exact format)
  - Style inconsistencies (provide style examples)
  - Missing context (include integration patterns)

## Service-Specific Issues

**Problem: Quota exhaustion**
- **Immediate**: Pause delegations, check quota status
- **Long-term**: Implement quota monitoring and throttling
- **See**: `Skill(leyline:quota-management)` for tracking patterns

**Problem: Authentication failures**
- **Check**: API keys, environment variables, service
  status
- **Verify**: Token expiration, permission scopes
- **See**: `Skill(leyline:authentication-patterns)` for
  setup

**Problem: SDK caller account metadata missing**
- **Context**: Early telemetry events may lack account
  info due to async initialization
- **Solution (2.1.51+)**: Set these env vars before
  launching Claude Code to provide account info
  synchronously:
  - `CLAUDE_CODE_ACCOUNT_UUID` - account identifier
  - `CLAUDE_CODE_USER_EMAIL` - user email address
  - `CLAUDE_CODE_ORGANIZATION_UUID` - organization ID
- **Benefit**: Eliminates race condition where early
  events lack metadata

**Problem: Rate limiting**
- **Solution**: Implement exponential backoff
- **Prevention**: Track request patterns, batch when possible
- **See**: `Skill(leyline:error-patterns)` for retry strategies

## Integration Failures

**Problem: Output doesn't match expected format**
- **Solution**: Validate schema before integration
- **Fix**: Update prompt with explicit format examples
- **Secondary Strategy**: Manual transformation or re-delegation

**Problem: Partial results returned**
- **Check**: Context window limits, timeout settings
- **Solution**: Break into smaller chunks
- **Alternative**: Use streaming if supported

**Problem: Results conflict with existing code**
- **Prevention**: Include existing patterns in delegation context
- **Solution**: Manual reconciliation with validation
- **Long-term**: Improve context specification


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: clean (LOW)