Files
Profa 2253d05618 feat: flatten project structure — archive v2, promote v3 to root
Remove the nested v3/ subdirectory by moving all active source code,
tests, configs, and assets directly to the project root. Archive v2/
(dead code, 847MB) to v2-archive.tar.gz.

Key changes:
- Move v3/src/ → src/, v3/tests/ → tests/, v3/packages/ → packages/
- Move v3/tsconfig.json, v3/vitest.config.ts to root
- Merge v3/package.json into root package.json (ESM, scripts, deps, exports)
- Merge v3/scripts/ into scripts/, v3/implementation/ into docs/implementation/
- Update all CI workflows to remove "cd v3 &&" and v3/ path prefixes
- Fix all init installer path resolution (3-level-up → 2-level-up)
- Fix hooks to use "node ./dist/cli/bundle.js" instead of bare "aqe"
- Update settings.json ADR/DDD directories to docs/implementation/
- Fix helper scripts (statusline, adr-compliance, ddd-tracker, guidance-hooks)
- Update 58 agent definitions: aqe/v3/ → aqe/ memory namespaces
- Update 15 guidance shards: v3/src/ → src/ path references
- Fix sync interfaces: remove v3/ and v2/ path references
- Fix test path calculations (process.cwd() + '..' no longer needed)
- Fix flaky perf test threshold (500ms → 1000ms for CI environments)
- Fix complexity-analyzer test to match ADR-051 keyword-based eligibility

Build passes, 17,901 tests pass, CLI and MCP bundles verified.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 11:35:41 +00:00

6.4 KiB

SPEC-042-C: MCP Tools and CLI

Field Value
Specification ID SPEC-042-C
Parent ADR ADR-042
Version 1.0
Status Implemented
Last Updated 2026-01-14
Author Claude Code

Overview

Defines the MCP tool token_usage for analyzing token consumption patterns and the CLI commands for token usage reporting and optimization recommendations.


Specification Details

Section 1: MCP Tool Definition

// v3/src/mcp/tools/analysis/token-usage.ts

export const tokenUsageTool = {
  name: 'token_usage',
  description: 'Analyze token consumption patterns and identify optimization opportunities',
  inputSchema: {
    type: 'object',
    properties: {
      operation: {
        type: 'string',
        enum: ['session', 'agent', 'domain', 'task'],
        description: 'Scope of analysis'
      },
      timeframe: {
        type: 'string',
        enum: ['1h', '24h', '7d', '30d'],
        description: 'Time period to analyze'
      },
      agentId: {
        type: 'string',
        description: 'Specific agent to analyze (optional)'
      },
      domain: {
        type: 'string',
        description: 'Specific domain to analyze (optional)'
      }
    },
    required: ['operation']
  },

  async execute(args: TokenUsageArgs): Promise<TokenUsageResult> {
    const collector = TokenMetricsCollector.getInstance();

    switch (args.operation) {
      case 'session':
        return collector.getSessionSummary(args.timeframe);
      case 'agent':
        return collector.getAgentMetrics(args.agentId, args.timeframe);
      case 'domain':
        return collector.getDomainMetrics(args.domain, args.timeframe);
      case 'task':
        return collector.getTaskMetrics(args.timeframe);
    }
  }
};

Section 2: Example MCP Output

{
  "summary": {
    "totalTokens": 45230,
    "totalCost": "$0.68",
    "tokensSaved": 12450,
    "savingsPercentage": 27.5
  },
  "breakdown": {
    "byAgent": {
      "qe-test-generator": { "tokens": 15200, "cost": "$0.23" },
      "qe-coverage-analyzer": { "tokens": 8900, "cost": "$0.13" }
    },
    "byDomain": {
      "test-generation": { "tokens": 18500 },
      "coverage-analysis": { "tokens": 12000 }
    }
  },
  "optimization": {
    "patternsReused": 34,
    "cacheHits": 89,
    "earlyExits": 12,
    "recommendations": [
      "High reuse potential for test-generation patterns (>0.85 similarity)",
      "Consider batching coverage-analysis requests"
    ]
  }
}

Section 3: CLI Commands

# Check token usage for current session
aqe token-usage --period 24h

# Get breakdown by agent
aqe token-usage --by-agent

# Get breakdown by domain
aqe token-usage --by-domain

# Export detailed report
aqe token-usage --period 7d --export tokens.csv

# Show optimization recommendations
aqe token-usage --recommendations

Architecture Diagram

+---------------------------------------------------------------------+
|                     V3 QE Token Tracking System                      |
+---------------------------------------------------------------------+
|                                                                      |
|  +----------------------------------------------------------------+  |
|  |                    Token Metrics Collector                      |  |
|  |  - Per-task token tracking (input/output/total)                |  |
|  |  - Per-agent aggregation                                       |  |
|  |  - Per-domain breakdown                                        |  |
|  |  - Session-level summaries                                     |  |
|  +----------------------------------------------------------------+  |
|                              |                                       |
|         +--------------------+--------------------+                  |
|         v                    v                    v                  |
|  +--------------+    +--------------+    +--------------+            |
|  |   Pattern    |    |    Cache     |    |  Early Exit  |            |
|  |    Reuse     |    |   Manager    |    |  Optimizer   |            |
|  |              |    |              |    |              |            |
|  | - HNSW search|    | - File cache |    | - High conf  |            |
|  | - >0.85 sim  |    | - Query cache|    |   patterns   |            |
|  | - Skip regen |    | - 5min TTL   |    | - Skip LLM   |            |
|  +--------------+    +--------------+    +--------------+            |
|         |                    |                    |                  |
|         +--------------------+--------------------+                  |
|                              v                                       |
|  +----------------------------------------------------------------+  |
|  |                      Token Reduction Layer                      |  |
|  |  - Pattern-based shortcuts (avoid re-computation)              |  |
|  |  - Batch similar operations (fewer API calls)                  |  |
|  |  - Context compression (focused prompts)                       |  |
|  |  - Response caching (avoid duplicate requests)                 |  |
|  +----------------------------------------------------------------+  |
|                                                                      |
+---------------------------------------------------------------------+

Validation Rules

Rule ID Description Severity
SPEC-042-C-001 operation parameter is required Error
SPEC-042-C-002 timeframe must be valid enum value Error
SPEC-042-C-003 agentId required when operation is 'agent' Warning

Spec ID Title Relationship
SPEC-042-A Token Tracking Schema Data structures returned
SPEC-042-B Reduction Strategies Optimization metrics

Changelog

Version Date Author Changes
1.0 2026-01-14 Claude Code Initial specification

References