when-managing-token-budget-use-token-budget-advisor
Proactive token budget management tool for assessing usage, analyzing task complexity, generating chunking strategies, and creating execution plans that stay within budget limits
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/chunkiRelated in Productivity
gitea-workflow
IncludedOrchestrate agile development workflows for Gitea repositories using the tea CLI. Use when working with Gitea-hosted repos and asking to 'run the workflow', 'continue working', 'what's next', 'complete the task cycle', 'start my day', 'end the sprint', 'implement the next task', or wanting guided step-by-step development assistance. Keywords: workflow, orchestrate, agile, task cycle, sprint, daily, implement, review, PR, standup, retrospective, gitea, tea.
microsoft-graph-gateway
IncludedRoute Microsoft Graph work in this workspace. Use when users want to read or write Outlook mail, calendar events, contacts, OneDrive or SharePoint files, Teams, Planner, To Do, users, groups, directory data, or arbitrary Microsoft Graph endpoints from VS Code. Prefer WorkIQ for common read scenarios. Use Microsoft Graph for write actions and gap-read scenarios that need exact Graph properties, filters, permissions, or endpoints.
copilotkit
IncludedUse when building with CopilotKit — setup, development, integrations, debugging, upgrading, or contributing. Routes to the appropriate specialized skill based on the task.
wordly-wisdom
IncludedProvides calibrated decision analysis using Charlie Munger-style multiple mental models, inversion, incentive mapping, circle-of-competence checks, misjudgment audits, second-order effects, and forecast updates. Use when the user asks for an oracle take, a hard call, a decision memo, a premortem, an outside view, a red-team, a sanity-check, what am I missing, think this through, or wants a strategy, hire, investment, plan, product, partnership, or major life choice analysed. Avoid for simple factual lookups or time-sensitive legal, medical, or market questions without fresh evidence.
swain-session
IncludedSession management and project status dashboard. Owns the full session lifecycle (start/work/close/resume), focus lane, bookmarks, worktree detection, and tab naming. Also serves as the project status dashboard — shows active epics, progress, actionable next steps, blocked items, tasks, GitHub issues, and recommendations. Worktree creation is deferred to swain-do task dispatch (SPEC-195). Triggers on: 'session', 'status', 'what's next', 'dashboard', 'overview', 'where are we', 'what should I work on', 'show me priorities', 'bookmark', 'focus on', 'session info'.
gandi
IncludedComprehensive Gandi domain registrar integration for domain and DNS management. Register and manage domains, create/update/delete DNS records (A, AAAA, CNAME, MX, TXT, SRV, and more), configure email forwarding and aliases, check SSL certificate status, create DNS snapshots for safe rollback, bulk update zone files, and monitor domain expiration. Supports multi-domain management, zone file import/export, and automated DNS backups. Includes both read-only and destructive operations with safety controls.