-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclaude-code-builder-researcher.py
More file actions
9088 lines (7703 loc) · 359 KB
/
claude-code-builder-researcher.py
File metadata and controls
9088 lines (7703 loc) · 359 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Claude Code Builder v2.3.0 - Enhanced Production-Ready Autonomous Multi-Phase Project Builder
An intelligent project builder that orchestrates Claude Code SDK to autonomously build
complete projects through multiple execution phases, with enhanced memory management,
improved research capabilities, accurate cost tracking, and robust error handling.
Key Improvements in v2.3.0:
- Enhanced research implementation using Anthropic SDK knowledge base
- Accurate cost tracking from Claude Code execution results
- Improved error handling and recovery mechanisms
- Better memory management with context preservation
- Enhanced MCP server discovery and configuration
- Optimized phase execution with better context passing
- Improved streaming output parsing with real-time cost updates
- Advanced tool management with usage analytics
- Comprehensive validation and testing framework
This version implements:
- Claude Code SDK CLI integration (TypeScript/Python SDKs coming soon)
- MCP (Model Context Protocol) with enhanced server management
- Anthropic SDK for intelligent research and analysis
- Accurate cost tracking and usage analytics
- Robust error recovery and checkpoint system
Usage:
python claude_code_builder_v2.3.py <spec_file> [options]
Example:
python claude_code_builder_v2.3.py project-spec.md \
--output-dir ./my-project \
--api-key $ANTHROPIC_API_KEY \
--enable-research \
--discover-mcp \
--auto-confirm
Requirements:
- Python 3.8+
- Claude Code installed and accessible (npm install -g @anthropic-ai/claude-code)
- Anthropic SDK: pip install anthropic>=0.18.0
- Rich: pip install rich>=13.0.0
- Aiofiles: pip install aiofiles>=23.0.0
- MCP servers (optional): Various npm packages
Author: Claude (Version 2.3.0)
License: MIT
"""
import os
import sys
import json
import asyncio
import argparse
import logging
import time
import subprocess
import tempfile
import shutil
import re
import signal
import hashlib
import traceback
import uuid
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Any, Set, Union, AsyncIterator
from dataclasses import dataclass, field, asdict
from datetime import datetime, timedelta
from collections import defaultdict, Counter
from contextlib import contextmanager, asynccontextmanager
from enum import Enum, auto
# Anthropic SDK imports for AI interactions
try:
from anthropic import AsyncAnthropic, Anthropic
from anthropic.types import (
Message, MessageStreamEvent, ContentBlockDeltaEvent,
ContentBlockStartEvent, ContentBlockStopEvent,
MessageStartEvent, MessageStopEvent, MessageDeltaEvent,
ContentBlock, TextBlock, ToolUseBlock, ToolResultBlock,
Usage
)
ANTHROPIC_SDK_AVAILABLE = True
except ImportError:
ANTHROPIC_SDK_AVAILABLE = False
print("Warning: Anthropic SDK not installed. Install with: pip install anthropic")
print("This is required for research features and cost tracking.")
# Define placeholder types
Usage = Any
# Rich imports for beautiful console output
try:
from rich.console import Console, Group
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TimeRemainingColumn, TaskID
from rich.table import Table
from rich.panel import Panel
from rich.markdown import Markdown
from rich.prompt import Confirm, Prompt
from rich.live import Live
from rich.layout import Layout
from rich.syntax import Syntax
from rich import box
from rich.logging import RichHandler
from rich.tree import Tree
from rich.status import Status
from rich.text import Text
from rich.columns import Columns
except ImportError:
print("Error: Rich library not installed. Install with: pip install rich")
sys.exit(1)
# Async file operations
try:
import aiofiles
except ImportError:
print("Warning: aiofiles not installed. Install with: pip install aiofiles")
aiofiles = None
# Initialize Rich console for beautiful output
console = Console()
# Token costs per million tokens (as of 2025)
# Based on Anthropic's current pricing model
TOKEN_COSTS = {
# Claude 4 models (current generation)
"claude-opus-4-20250514": {"input": 15.00, "output": 75.00},
"claude-sonnet-4-20250514": {"input": 3.00, "output": 15.00},
# Claude 3.5 models (previous generation, still supported)
"claude-3-5-sonnet-20241022": {"input": 3.00, "output": 15.00},
"claude-3-5-haiku-20241022": {"input": 1.00, "output": 5.00},
"claude-3-opus-20240229": {"input": 15.00, "output": 75.00},
}
# Default models for different tasks
DEFAULT_ANALYZER_MODEL = "claude-opus-4-20250514" # Best for complex analysis
DEFAULT_EXECUTOR_MODEL = "claude-opus-4-20250514" # Best for code generation
DEFAULT_RESEARCH_MODEL = "claude-sonnet-4-20250514" # Good balance for research
# Retry configuration
MAX_RETRIES = 3
RETRY_DELAY = 2.0 # seconds
# Enhanced MCP Server Registry with v2.3 improvements
MCP_SERVER_REGISTRY = {
# Core MCP Servers - Essential for most projects
"memory": {
"package": "@modelcontextprotocol/server-memory",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-memory"],
"description": "Persistent memory storage across conversations",
"category": "core",
"priority": 10,
"tools": ["store", "recall", "search", "delete", "list", "update", "clear"],
"use_cases": ["context_preservation", "cross_session_memory", "decision_tracking", "state_management"],
"config_template": {
"storage_path": "${workspace}/.memory",
"max_entries": 10000,
"compression": True,
"auto_save": True
}
},
"sequential-thinking": {
"package": "@modelcontextprotocol/server-sequential-thinking",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-sequential-thinking"],
"description": "Structured problem decomposition and reasoning",
"category": "core",
"priority": 9,
"tools": ["plan", "decompose", "analyze", "synthesize", "reason", "evaluate"],
"use_cases": ["problem_solving", "task_planning", "decision_analysis", "architecture_design"]
},
"filesystem": {
"package": "@modelcontextprotocol/server-filesystem",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "${workspace}"],
"description": "Advanced file system operations",
"category": "core",
"priority": 8,
"tools": ["read_file", "write_file", "list_directory", "create_directory", "delete_file", "move_file", "copy_file"],
"use_cases": ["file_management", "code_operations", "project_structure", "asset_handling"]
},
# Development Tools
"git": {
"package": "@modelcontextprotocol/server-git",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-git"],
"description": "Git repository operations and version control",
"category": "development",
"priority": 7,
"tools": ["commit", "branch", "merge", "diff", "log", "status", "checkout", "push", "pull", "stash"],
"use_cases": ["version_control", "change_tracking", "collaboration", "release_management"]
},
"github": {
"package": "@modelcontextprotocol/server-github",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"description": "GitHub API integration for repository management",
"category": "development",
"priority": 6,
"tools": ["create_issue", "create_pr", "list_repos", "get_file", "create_repo", "update_issue"],
"use_cases": ["repository_management", "issue_tracking", "collaboration", "ci_cd"],
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
}
},
# Database Servers
"postgres": {
"package": "@modelcontextprotocol/server-postgres",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"description": "PostgreSQL database operations",
"category": "database",
"priority": 7,
"tools": ["query", "execute", "list_tables", "describe_table", "create_table", "alter_table"],
"use_cases": ["database_operations", "data_analysis", "schema_management", "data_migration"],
"env": {
"POSTGRES_URL": "${DATABASE_URL}"
}
},
"sqlite": {
"package": "@modelcontextprotocol/server-sqlite",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-sqlite", "${workspace}/database.db"],
"description": "SQLite database operations",
"category": "database",
"priority": 5,
"tools": ["query", "execute", "list_tables", "create_database", "backup"],
"use_cases": ["local_database", "prototyping", "testing", "embedded_apps"]
},
# External Services
"web": {
"package": "@modelcontextprotocol/server-web",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-web"],
"description": "Web browsing and scraping capabilities",
"category": "external",
"priority": 6,
"tools": ["fetch", "search", "scrape", "screenshot", "crawl"],
"use_cases": ["web_scraping", "api_testing", "documentation_lookup", "research"]
},
"slack": {
"package": "@modelcontextprotocol/server-slack",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-slack"],
"description": "Slack integration for messaging",
"category": "communication",
"priority": 4,
"tools": ["send_message", "list_channels", "search_messages", "create_channel"],
"use_cases": ["notifications", "team_communication", "alerts", "reporting"],
"env": {
"SLACK_TOKEN": "${SLACK_TOKEN}"
}
},
# New in v2.3: Additional useful servers
"context7": {
"package": "@modelcontextprotocol/server-context7",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-context7"],
"description": "Access latest documentation for libraries and frameworks",
"category": "documentation",
"priority": 8,
"tools": ["search_docs", "get_examples", "get_api_reference"],
"use_cases": ["documentation_lookup", "api_reference", "best_practices"]
}
}
class BuildStatus(Enum):
"""Enumeration for build phase status"""
PENDING = auto()
RUNNING = auto()
SUCCESS = auto()
FAILED = auto()
SKIPPED = auto()
CANCELLED = auto()
RETRYING = auto() # New in v2.3
@dataclass
class ToolCall:
"""
Represents a single tool call made during execution.
Enhanced in v2.3 with better metrics and categorization.
"""
id: str
name: str
parameters: Dict[str, Any]
start_time: datetime = field(default_factory=datetime.now)
end_time: Optional[datetime] = None
result: Optional[Any] = None
error: Optional[str] = None
category: Optional[str] = None # New in v2.3
phase_id: Optional[str] = None # New in v2.3
@property
def duration(self) -> float:
"""Calculate duration in seconds"""
if self.end_time:
return (self.end_time - self.start_time).total_seconds()
return (datetime.now() - self.start_time).total_seconds()
@property
def is_mcp_tool(self) -> bool:
"""Check if this is an MCP tool call"""
return self.name.startswith("mcp__")
@property
def mcp_server(self) -> Optional[str]:
"""Extract MCP server name if this is an MCP tool"""
if self.is_mcp_tool:
parts = self.name.split("__")
if len(parts) >= 2:
return parts[1]
return None
@property
def tool_type(self) -> str:
"""Categorize tool type"""
if self.is_mcp_tool:
return f"mcp_{self.mcp_server}"
elif any(cmd in self.name.lower() for cmd in ['bash', 'run', 'execute', 'command']):
return "command"
elif any(op in self.name.lower() for op in ['write', 'create', 'edit', 'read', 'delete']):
return "file_operation"
else:
return "other"
def to_rich(self) -> Panel:
"""Convert to rich panel for display"""
content = []
# Tool name and status
if self.error:
status = "[red]✗ Failed[/red]"
elif self.end_time:
status = f"[green]✓ Complete[/green] ({self.duration:.1f}s)"
else:
status = "[yellow]⚡ Running[/yellow]"
content.append(f"{status}")
# Tool type and category
content.append(f"[dim]Type:[/dim] {self.tool_type}")
if self.category:
content.append(f"[dim]Category:[/dim] {self.category}")
# MCP server info if applicable
if self.is_mcp_tool and self.mcp_server:
content.append(f"[dim]MCP Server:[/dim] {self.mcp_server}")
# Parameters (formatted better)
if self.parameters:
params_str = self._format_parameters()
content.append(f"\n[dim]Parameters:[/dim]\n{params_str}")
# Result preview
if self.result:
result_str = self._format_result()
content.append(f"\n[dim]Result:[/dim] {result_str}")
# Error
if self.error:
content.append(f"\n[red]Error:[/red] {self.error}")
return Panel(
"\n".join(content),
title=f"[bold cyan]{self.name}[/bold cyan]",
border_style="cyan" if not self.error else "red"
)
def _format_parameters(self) -> str:
"""Format parameters for display"""
if isinstance(self.parameters, dict):
# Special formatting for common parameters
if 'path' in self.parameters or 'file' in self.parameters:
path = self.parameters.get('path') or self.parameters.get('file', '')
return f" Path: {path}"
elif 'command' in self.parameters:
return f" Command: {self.parameters['command']}"
else:
params_str = json.dumps(self.parameters, indent=2)
if len(params_str) > 200:
params_str = params_str[:197] + "..."
return params_str
return str(self.parameters)[:200]
def _format_result(self) -> str:
"""Format result for display"""
result_str = str(self.result)
if len(result_str) > 100:
# Try to extract meaningful part
if isinstance(self.result, dict):
if 'status' in self.result:
return f"Status: {self.result['status']}"
elif 'success' in self.result:
return f"Success: {self.result['success']}"
return result_str[:97] + "..."
return result_str
@dataclass
class BuildStats:
"""
Comprehensive build statistics tracking.
Enhanced in v2.3 with better categorization and analytics.
"""
# File operations
files_created: int = 0
files_modified: int = 0
files_deleted: int = 0
directories_created: int = 0
# Testing metrics
tests_written: int = 0
tests_passed: int = 0
tests_failed: int = 0
test_coverage: float = 0.0 # New in v2.3
# Code metrics
lines_of_code: int = 0
functions_created: int = 0 # New in v2.3
classes_created: int = 0 # New in v2.3
# Execution metrics
commands_executed: int = 0
errors_encountered: int = 0
warnings_encountered: int = 0
retries_performed: int = 0 # New in v2.3
# Tool usage
mcp_calls: int = 0
web_searches: int = 0
tool_calls: Counter = field(default_factory=Counter)
tool_success_rate: Dict[str, float] = field(default_factory=dict) # New in v2.3
# File type tracking
file_types: Counter = field(default_factory=Counter)
# Performance metrics (new in v2.3)
phase_durations: Dict[str, float] = field(default_factory=dict)
tool_durations: Dict[str, List[float]] = field(default_factory=lambda: defaultdict(list))
# Active tool tracking
active_tool_calls: Dict[str, ToolCall] = field(default_factory=dict)
completed_tool_calls: List[ToolCall] = field(default_factory=list) # New in v2.3
def increment(self, stat: str, amount: int = 1):
"""Increment a statistic by amount"""
if hasattr(self, stat):
setattr(self, stat, getattr(self, stat) + amount)
def add_file(self, filepath: str, created: bool = True):
"""Track file creation/modification with enhanced metrics"""
if created:
self.files_created += 1
else:
self.files_modified += 1
# Track file type
ext = Path(filepath).suffix.lower() or 'no_extension'
self.file_types[ext] += 1
# Count lines and analyze code structure for code files
code_extensions = {'.py', '.js', '.ts', '.java', '.c', '.cpp', '.go', '.rs', '.rb', '.php', '.jsx', '.tsx'}
if ext in code_extensions and Path(filepath).exists():
try:
with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
lines = f.readlines()
self.lines_of_code += len(lines)
# Basic code analysis
for line in lines:
stripped = line.strip()
if ext in {'.py'}:
if stripped.startswith('def '):
self.functions_created += 1
elif stripped.startswith('class '):
self.classes_created += 1
elif ext in {'.js', '.ts', '.jsx', '.tsx'}:
if 'function ' in stripped or '=>' in stripped:
self.functions_created += 1
elif stripped.startswith('class '):
self.classes_created += 1
except Exception:
pass # Ignore errors in analysis
def start_tool_call(self, tool_id: str, name: str, parameters: Dict[str, Any],
phase_id: Optional[str] = None) -> ToolCall:
"""Start tracking a tool call with enhanced metadata"""
tool_call = ToolCall(
id=tool_id,
name=name,
parameters=parameters,
phase_id=phase_id
)
# Categorize tool
if tool_call.is_mcp_tool:
tool_call.category = "mcp"
elif "test" in name.lower():
tool_call.category = "testing"
elif any(cmd in name.lower() for cmd in ['bash', 'run', 'execute']):
tool_call.category = "command"
else:
tool_call.category = "file_operation"
self.active_tool_calls[tool_id] = tool_call
self.tool_calls[name] += 1
# Special tracking for tool types
if tool_call.is_mcp_tool:
self.mcp_calls += 1
elif "web" in name.lower() or "search" in name.lower():
self.web_searches += 1
return tool_call
def end_tool_call(self, tool_id: str, result: Any = None, error: str = None):
"""End tracking a tool call with enhanced analytics"""
if tool_id in self.active_tool_calls:
tool_call = self.active_tool_calls.pop(tool_id)
tool_call.end_time = datetime.now()
tool_call.result = result
tool_call.error = error
# Move to completed
self.completed_tool_calls.append(tool_call)
# Track duration
self.tool_durations[tool_call.name].append(tool_call.duration)
# Update success rate
if tool_call.name not in self.tool_success_rate:
self.tool_success_rate[tool_call.name] = 0.0
total_calls = self.tool_calls[tool_call.name]
if error:
self.errors_encountered += 1
# Update success rate
successful_calls = total_calls - sum(1 for tc in self.completed_tool_calls
if tc.name == tool_call.name and tc.error)
self.tool_success_rate[tool_call.name] = successful_calls / total_calls
else:
# Update success rate
successful_calls = sum(1 for tc in self.completed_tool_calls
if tc.name == tool_call.name and not tc.error)
self.tool_success_rate[tool_call.name] = successful_calls / total_calls
def get_summary(self) -> Dict[str, Any]:
"""Get a comprehensive summary of all statistics"""
# Calculate average tool durations
avg_tool_durations = {}
for tool, durations in self.tool_durations.items():
if durations:
avg_tool_durations[tool] = sum(durations) / len(durations)
return {
"files": {
"created": self.files_created,
"modified": self.files_modified,
"deleted": self.files_deleted,
"types": dict(self.file_types.most_common())
},
"code": {
"lines": self.lines_of_code,
"functions": self.functions_created,
"classes": self.classes_created,
"directories": self.directories_created
},
"testing": {
"written": self.tests_written,
"passed": self.tests_passed,
"failed": self.tests_failed,
"coverage": f"{self.test_coverage:.1f}%"
},
"execution": {
"commands": self.commands_executed,
"errors": self.errors_encountered,
"warnings": self.warnings_encountered,
"retries": self.retries_performed
},
"tools": {
"total_calls": sum(self.tool_calls.values()),
"mcp_calls": self.mcp_calls,
"web_searches": self.web_searches,
"by_tool": dict(self.tool_calls.most_common()),
"success_rates": {k: f"{v:.1%}" for k, v in self.tool_success_rate.items()},
"avg_durations": {k: f"{v:.1f}s" for k, v in avg_tool_durations.items()}
},
"performance": {
"phase_durations": {k: f"{v:.1f}s" for k, v in self.phase_durations.items()},
"total_tool_time": sum(sum(d) for d in self.tool_durations.values())
}
}
@dataclass
class CostTracker:
"""
Tracks API usage costs across all phases of execution.
Enhanced in v2.3 with accurate Claude Code cost tracking.
"""
total_input_tokens: int = 0
total_output_tokens: int = 0
total_cost: float = 0.0
claude_code_cost: float = 0.0 # New in v2.3
research_cost: float = 0.0 # New in v2.3
phase_costs: Dict[str, float] = field(default_factory=dict)
phase_tokens: Dict[str, Dict[str, int]] = field(default_factory=dict)
model_usage: Dict[str, Dict[str, int]] = field(default_factory=lambda: defaultdict(lambda: {"input": 0, "output": 0}))
claude_code_sessions: List[Dict[str, Any]] = field(default_factory=list) # New in v2.3
def add_tokens(self, input_tokens: int, output_tokens: int, model: str, phase: str = "general"):
"""Add tokens and calculate cost for a specific model and phase"""
self.total_input_tokens += input_tokens
self.total_output_tokens += output_tokens
# Track per-phase tokens
if phase not in self.phase_tokens:
self.phase_tokens[phase] = {"input": 0, "output": 0}
self.phase_tokens[phase]["input"] += input_tokens
self.phase_tokens[phase]["output"] += output_tokens
# Track per-model usage
self.model_usage[model]["input"] += input_tokens
self.model_usage[model]["output"] += output_tokens
# Calculate cost
if model in TOKEN_COSTS:
input_cost = (input_tokens / 1_000_000) * TOKEN_COSTS[model]["input"]
output_cost = (output_tokens / 1_000_000) * TOKEN_COSTS[model]["output"]
phase_cost = input_cost + output_cost
self.total_cost += phase_cost
if phase not in self.phase_costs:
self.phase_costs[phase] = 0.0
self.phase_costs[phase] += phase_cost
# Track research costs separately
if "research" in phase.lower():
self.research_cost += phase_cost
def add_usage(self, usage: 'Usage', model: str, phase: str = "general"):
"""Add tokens from Anthropic Usage object"""
if usage:
self.add_tokens(usage.input_tokens, usage.output_tokens, model, phase)
def add_claude_code_cost(self, cost: float, session_data: Dict[str, Any]):
"""Add Claude Code execution cost with session tracking"""
self.claude_code_cost += cost
self.total_cost += cost
# Store session data for analysis
session_info = {
"cost": cost,
"timestamp": datetime.now().isoformat(),
"session_id": session_data.get("session_id"),
"duration_ms": session_data.get("duration_ms"),
"num_turns": session_data.get("num_turns"),
"phase": session_data.get("phase", "unknown")
}
self.claude_code_sessions.append(session_info)
# Add to phase costs
phase = session_data.get("phase", "claude_code_execution")
if phase not in self.phase_costs:
self.phase_costs[phase] = 0.0
self.phase_costs[phase] += cost
def get_summary(self) -> Dict[str, Any]:
"""Get comprehensive cost summary with Claude Code breakdown"""
# Calculate average cost per Claude Code session
avg_claude_code_cost = 0.0
if self.claude_code_sessions:
avg_claude_code_cost = self.claude_code_cost / len(self.claude_code_sessions)
return {
"total_input_tokens": self.total_input_tokens,
"total_output_tokens": self.total_output_tokens,
"total_tokens": self.total_input_tokens + self.total_output_tokens,
"total_cost": round(self.total_cost, 2),
"claude_code_cost": round(self.claude_code_cost, 2),
"research_cost": round(self.research_cost, 2),
"analysis_cost": round(self.total_cost - self.claude_code_cost - self.research_cost, 2),
"phase_costs": {k: round(v, 2) for k, v in self.phase_costs.items()},
"phase_tokens": self.phase_tokens,
"model_usage": dict(self.model_usage),
"claude_code_sessions": len(self.claude_code_sessions),
"avg_claude_code_cost": round(avg_claude_code_cost, 4),
"average_cost_per_phase": round(self.total_cost / max(len(self.phase_costs), 1), 2)
}
def get_model_breakdown(self) -> List[Dict[str, Any]]:
"""Get cost breakdown by model"""
breakdown = []
for model, usage in self.model_usage.items():
if model in TOKEN_COSTS:
input_cost = (usage["input"] / 1_000_000) * TOKEN_COSTS[model]["input"]
output_cost = (usage["output"] / 1_000_000) * TOKEN_COSTS[model]["output"]
total_cost = input_cost + output_cost
breakdown.append({
"model": model,
"input_tokens": usage["input"],
"output_tokens": usage["output"],
"total_tokens": usage["input"] + usage["output"],
"cost": round(total_cost, 2)
})
# Add Claude Code as a separate entry
if self.claude_code_cost > 0:
breakdown.append({
"model": "claude-code-execution",
"sessions": len(self.claude_code_sessions),
"avg_turns": sum(s.get("num_turns", 0) for s in self.claude_code_sessions) / max(len(self.claude_code_sessions), 1),
"cost": round(self.claude_code_cost, 2)
})
return sorted(breakdown, key=lambda x: x["cost"], reverse=True)
@dataclass
class Phase:
"""
Represents a single build phase with enhanced metadata.
Enhanced in v2.3 with better context management and validation.
"""
id: str
name: str
description: str
tasks: List[str]
dependencies: List[str] = field(default_factory=list)
status: BuildStatus = BuildStatus.PENDING
completed: bool = False
success: bool = False
error: Optional[str] = None
start_time: Optional[datetime] = None
end_time: Optional[datetime] = None
output_summary: Optional[str] = None
files_created: List[str] = field(default_factory=list)
retry_count: int = 0
messages: List[str] = field(default_factory=list)
tool_calls: List[str] = field(default_factory=list) # Tool call IDs
context: Dict[str, Any] = field(default_factory=dict) # New in v2.3
validation_results: Dict[str, bool] = field(default_factory=dict) # New in v2.3
@property
def duration(self) -> Optional[timedelta]:
"""Calculate phase duration"""
if self.start_time and self.end_time:
return self.end_time - self.start_time
return None
@property
def duration_seconds(self) -> float:
"""Get duration in seconds"""
if self.duration:
return self.duration.total_seconds()
elif self.start_time:
return (datetime.now() - self.start_time).total_seconds()
return 0.0
def add_message(self, message: str, level: str = "info"):
"""Add a timestamped message to phase history with level"""
timestamp = datetime.now().strftime('%H:%M:%S')
self.messages.append(f"[{timestamp}] [{level.upper()}] {message}")
def add_context(self, key: str, value: Any):
"""Add context information for future phases"""
self.context[key] = value
def validate(self) -> bool:
"""Validate phase completion"""
validations = {
"has_files": len(self.files_created) > 0,
"no_errors": self.error is None,
"completed": self.completed,
"has_output": self.output_summary is not None
}
self.validation_results = validations
return all(validations.values())
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary for serialization"""
return {
"id": self.id,
"name": self.name,
"description": self.description,
"tasks": self.tasks,
"dependencies": self.dependencies,
"status": self.status.name,
"completed": self.completed,
"success": self.success,
"error": self.error,
"start_time": self.start_time.isoformat() if self.start_time else None,
"end_time": self.end_time.isoformat() if self.end_time else None,
"output_summary": self.output_summary,
"files_created": self.files_created,
"retry_count": self.retry_count,
"duration_seconds": self.duration_seconds,
"messages": self.messages,
"tool_calls": self.tool_calls,
"context": self.context,
"validation_results": self.validation_results
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> 'Phase':
"""Create Phase from dictionary"""
phase_data = data.copy()
# Convert status
if 'status' in phase_data:
phase_data['status'] = BuildStatus[phase_data['status']]
# Convert timestamps
if phase_data.get('start_time'):
phase_data['start_time'] = datetime.fromisoformat(phase_data['start_time'])
if phase_data.get('end_time'):
phase_data['end_time'] = datetime.fromisoformat(phase_data['end_time'])
# Remove computed fields
phase_data.pop('duration_seconds', None)
return cls(**phase_data)
@dataclass
class ProjectMemory:
"""
Persistent project memory with enhanced context management.
Enhanced in v2.3 with better state tracking and recovery.
"""
project_name: str
project_path: str
specification: str
specification_hash: str
phases: List[Phase]
completed_phases: List[str] = field(default_factory=list)
current_phase: Optional[str] = None
context: Dict[str, Any] = field(default_factory=dict)
created_files: List[str] = field(default_factory=list)
important_decisions: List[str] = field(default_factory=list)
checkpoints: List[Dict[str, Any]] = field(default_factory=list)
mcp_servers: Dict[str, Any] = field(default_factory=dict)
build_id: str = field(default_factory=lambda: str(uuid.uuid4()))
created_at: datetime = field(default_factory=datetime.now)
updated_at: datetime = field(default_factory=datetime.now)
phase_contexts: Dict[str, Dict[str, Any]] = field(default_factory=dict) # New in v2.3
error_log: List[Dict[str, Any]] = field(default_factory=list) # New in v2.3
def to_json(self) -> str:
"""Convert to JSON for storage"""
return json.dumps({
"project_name": self.project_name,
"project_path": self.project_path,
"specification": self.specification,
"specification_hash": self.specification_hash,
"phases": [p.to_dict() for p in self.phases],
"completed_phases": self.completed_phases,
"current_phase": self.current_phase,
"context": self.context,
"created_files": self.created_files,
"important_decisions": self.important_decisions,
"checkpoints": self.checkpoints,
"mcp_servers": self.mcp_servers,
"build_id": self.build_id,
"created_at": self.created_at.isoformat(),
"updated_at": self.updated_at.isoformat(),
"phase_contexts": self.phase_contexts,
"error_log": self.error_log
}, default=str, indent=2)
@classmethod
def from_json(cls, data: str) -> 'ProjectMemory':
"""Create from JSON data"""
obj = json.loads(data)
# Reconstruct phases
phases = [Phase.from_dict(p) for p in obj['phases']]
obj['phases'] = phases
# Convert timestamps
obj['created_at'] = datetime.fromisoformat(obj['created_at'])
obj['updated_at'] = datetime.fromisoformat(obj['updated_at'])
return cls(**obj)
def add_checkpoint(self, name: str, data: Any = None):
"""Add a checkpoint to the memory"""
checkpoint = {
"name": name,
"timestamp": datetime.now().isoformat(),
"phase": self.current_phase,
"completed_phases": self.completed_phases.copy(),
"data": data,
"build_stats_snapshot": data.get("build_stats") if data else None
}
self.checkpoints.append(checkpoint)
self.updated_at = datetime.now()
def store_phase_context(self, phase_id: str, context: Dict[str, Any]):
"""Store context from a completed phase"""
self.phase_contexts[phase_id] = {
"timestamp": datetime.now().isoformat(),
"context": context,
"files_created": self.get_phase_by_id(phase_id).files_created if self.get_phase_by_id(phase_id) else []
}
self.updated_at = datetime.now()
def log_error(self, error: str, phase_id: Optional[str] = None, context: Optional[Dict[str, Any]] = None):
"""Log an error with context"""
error_entry = {
"timestamp": datetime.now().isoformat(),
"error": error,
"phase_id": phase_id,
"context": context or {}
}
self.error_log.append(error_entry)
self.updated_at = datetime.now()
def get_phase_by_id(self, phase_id: str) -> Optional[Phase]:
"""Get phase by ID"""
return next((p for p in self.phases if p.id == phase_id), None)
def get_accumulated_context(self, up_to_phase: str) -> Dict[str, Any]:
"""Get accumulated context up to a specific phase"""
accumulated = self.context.copy()
# Add contexts from completed phases
for phase in self.phases:
if phase.id == up_to_phase:
break
if phase.id in self.phase_contexts:
accumulated.update(self.phase_contexts[phase.id].get("context", {}))
return accumulated
@dataclass
class MCPRecommendation:
"""
Enhanced MCP server recommendation with installation status.
"""
server_name: str
confidence: float # 0.0 to 1.0
reasons: List[str]
use_cases: List[str]
priority: int
install_command: str
config_suggestion: Dict[str, Any]
is_installed: bool = False # New in v2.3
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
@dataclass
class ResearchQuery:
"""
Enhanced research query with better context integration.
"""
id: str
query: str
context: Dict[str, Any]
focus_areas: List[str] # New in v2.3: specific areas to focus on
priority: int
estimated_time: int # seconds
dependencies: List[str] = field(default_factory=list)
status: str = "pending"
results: Optional[Dict[str, Any]] = None
confidence: float = 0.0 # New in v2.3
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
@dataclass
class CustomInstruction:
"""
Enhanced custom instruction with better filtering and validation.
"""
id: str
name: str
content: str
scope: str # global, project, phase, tool
context_filters: Dict[str, Any]
priority: int
active: bool = True
validation_rules: List[str] = field(default_factory=list) # New in v2.3
def matches_context(self, context: Dict[str, Any]) -> bool:
"""Check if instruction applies to given context with enhanced matching"""
for key, value in self.context_filters.items():
if key not in context:
return False
context_value = context[key]
# Handle list values (check if context value is in filter list)
if isinstance(value, list):
if isinstance(context_value, list):
# Check if any value matches