Claude
Skills
Sign in
Back

when-managing-token-budget-use-token-budget-advisor

Included with Lifetime
$97 forever

Proactive token budget management tool for assessing usage, analyzing task complexity, generating chunking strategies, and creating execution plans that stay within budget limits

Productivitymeta-tooltoken-managementbudget-optimizationtask-planningchunking

What this skill does


# Token Budget Advisor

**Purpose:** Proactively manage token budgets by analyzing current usage, estimating task complexity, generating intelligent chunking strategies, prioritizing work, and creating step-by-step execution plans that stay within budget limits.

## When to Use This Skill

- Before starting large or complex tasks
- When approaching token budget limits
- During multi-phase project planning
- When tasks fail due to token exhaustion
- For optimizing resource allocation
- When coordinating multiple agents

## Analysis Dimensions

### 1. Budget Assessment
- Current token usage vs. limits
- Remaining budget calculation
- Historical usage patterns
- Projected usage for pending tasks
- Buffer allocation for safety

### 2. Task Complexity Analysis
- Token estimation by task type
- Agent requirements and costs
- Integration complexity
- Testing overhead
- Documentation needs

### 3. Chunking Strategy
- Logical task boundaries
- Dependency analysis
- Chunk size optimization
- Inter-chunk communication
- State management between chunks

### 4. Priority Optimization
- Critical path identification
- Value vs. cost analysis
- Risk assessment
- Quick wins identification
- Deferrable work detection

### 5. Execution Planning
- Step-by-step task sequence
- Budget tracking per step
- Checkpoint planning
- Rollback strategies
- Progress monitoring

## Execution Process

### Phase 1: Budget Assessment

```bash
# Initialize budget analysis
npx claude-flow@alpha hooks pre-task --description "Analyzing token budget"

# Retrieve current usage
npx claude-flow@alpha memory retrieve --key "token-usage/current"
```

**Budget Calculation:**
```javascript
function assessBudget(tokenLimit = 200000) {
  const usage = {
    limit: tokenLimit,
    used: getCurrentTokenUsage(),
    remaining: 0,
    buffer: 0,
    available: 0,
    status: "unknown"
  };

  usage.remaining = usage.limit - usage.used;
  usage.buffer = Math.floor(usage.limit * 0.15); // 15% safety buffer
  usage.available = usage.remaining - usage.buffer;

  // Calculate status
  const usagePercent = (usage.used / usage.limit) * 100;
  if (usagePercent > 90) {
    usage.status = "critical";
  } else if (usagePercent > 75) {
    usage.status = "warning";
  } else if (usagePercent > 50) {
    usage.status = "caution";
  } else {
    usage.status = "healthy";
  }

  return usage;
}

function getCurrentTokenUsage() {
  // Extract from context or tracking
  // This is a placeholder - actual implementation depends on system
  return 36000; // Example current usage
}
```

**Historical Pattern Analysis:**
```javascript
function analyzeUsagePatterns(historyData) {
  const patterns = {
    avgPerTask: 0,
    peakUsage: 0,
    typicalDuration: 0,
    commonOverages: []
  };

  if (historyData.length === 0) {
    // No history, use conservative estimates
    patterns.avgPerTask = 15000;
    patterns.peakUsage = 40000;
    patterns.typicalDuration = 30; // minutes
    return patterns;
  }

  // Calculate averages
  patterns.avgPerTask = historyData.reduce((sum, task) =>
    sum + task.tokens, 0) / historyData.length;

  patterns.peakUsage = Math.max(...historyData.map(t => t.tokens));

  patterns.typicalDuration = historyData.reduce((sum, task) =>
    sum + task.duration, 0) / historyData.length;

  // Identify common overage causes
  const overages = historyData.filter(t => t.exceeded_estimate);
  const causes = {};
  overages.forEach(o => {
    causes[o.reason] = (causes[o.reason] || 0) + 1;
  });
  patterns.commonOverages = Object.entries(causes)
    .sort((a, b) => b[1] - a[1])
    .slice(0, 5)
    .map(([reason, count]) => ({ reason, count }));

  return patterns;
}
```

### Phase 2: Task Complexity Analysis

**Complexity Estimator:**
```javascript
function estimateTaskComplexity(taskDescription) {
  const complexity = {
    baseTokens: 0,
    multipliers: {},
    totalEstimate: 0,
    confidence: "low",
    factors: []
  };

  // Base estimation by task type
  const taskType = inferTaskType(taskDescription);
  const baseEstimates = {
    "simple-edit": 2000,
    "feature-implementation": 15000,
    "refactoring": 8000,
    "architecture-design": 12000,
    "full-stack-development": 40000,
    "debugging": 5000,
    "testing": 6000,
    "documentation": 4000,
    "integration": 10000,
    "migration": 20000
  };

  complexity.baseTokens = baseEstimates[taskType] || 10000;
  complexity.factors.push({ type: "base", value: complexity.baseTokens, reason: `Task type: ${taskType}` });

  // Apply multipliers

  // Multiple agents
  const agentCount = estimateAgentCount(taskDescription);
  if (agentCount > 3) {
    complexity.multipliers.agents = 1.3;
    complexity.factors.push({ type: "multiplier", value: 1.3, reason: `${agentCount} agents required` });
  }

  // External integrations
  if (/\b(api|database|github|external|integration)\b/i.test(taskDescription)) {
    complexity.multipliers.integration = 1.4;
    complexity.factors.push({ type: "multiplier", value: 1.4, reason: "External integrations" });
  }

  // Testing requirements
  if (/\b(test|coverage|tdd|e2e)\b/i.test(taskDescription)) {
    complexity.multipliers.testing = 1.25;
    complexity.factors.push({ type: "multiplier", value: 1.25, reason: "Testing requirements" });
  }

  // Documentation
  if (/\b(document|readme|guide|tutorial)\b/i.test(taskDescription)) {
    complexity.multipliers.documentation = 1.15;
    complexity.factors.push({ type: "multiplier", value: 1.15, reason: "Documentation needed" });
  }

  // Complexity keywords
  if (/\b(complex|advanced|comprehensive|full|complete|entire)\b/i.test(taskDescription)) {
    complexity.multipliers.complexity = 1.5;
    complexity.factors.push({ type: "multiplier", value: 1.5, reason: "High complexity indicators" });
  }

  // Calculate total
  const totalMultiplier = Object.values(complexity.multipliers)
    .reduce((product, mult) => product * mult, 1);

  complexity.totalEstimate = Math.ceil(complexity.baseTokens * totalMultiplier);

  // Confidence assessment
  const factorCount = Object.keys(complexity.multipliers).length;
  if (factorCount >= 3) {
    complexity.confidence = "high";
  } else if (factorCount >= 1) {
    complexity.confidence = "medium";
  } else {
    complexity.confidence = "low";
  }

  return complexity;
}

function inferTaskType(description) {
  const patterns = {
    "simple-edit": /\b(fix typo|update|change|rename|small)\b/i,
    "feature-implementation": /\b(implement|add feature|create|build)\b/i,
    "refactoring": /\b(refactor|reorganize|restructure|cleanup)\b/i,
    "architecture-design": /\b(design|architect|plan|structure)\b/i,
    "full-stack-development": /\b(full.?stack|frontend.*backend|complete app)\b/i,
    "debugging": /\b(debug|fix bug|resolve error|troubleshoot)\b/i,
    "testing": /\b(test|tdd|coverage|qa)\b/i,
    "documentation": /\b(document|write.*guide|readme|tutorial)\b/i,
    "integration": /\b(integrat|connect|link|api.*call)\b/i,
    "migration": /\b(migrat|convert|port|upgrade)\b/i
  };

  for (const [type, pattern] of Object.entries(patterns)) {
    if (pattern.test(description)) {
      return type;
    }
  }

  return "feature-implementation"; // Default
}

function estimateAgentCount(description) {
  let count = 1; // At least one agent

  if (/\b(frontend|backend|database)\b/i.test(description)) count++;
  if (/\b(test|qa)\b/i.test(description)) count++;
  if (/\b(review|quality)\b/i.test(description)) count++;
  if (/\b(document)\b/i.test(description)) count++;
  if (/\b(deploy|devops|ci.?cd)\b/i.test(description)) count++;

  return count;
}
```

### Phase 3: Chunking Strategy

**Planner Agent Task:**
```bash
# Spawn planner agent for chunking strategy
# Agent instructions:
# 1. Analyze task dependencies
# 2. Identify logical boundaries
# 3. Optimize chunk sizes (within budget)
# 4. Define inter-chunk communication
# 5. Create state management plan
# 6. Store strategy in memory

npx claude-flow@alpha memory store --key "budget/chunki

Related in Productivity