Oppo-TIA / citadel /code_proposal_engine.py
DJ-Goanna-Coding's picture
Upload folder using huggingface_hub
67be617 verified
Raw History Blame Contribute Delete
13.4 kB
"""Code Proposal Engine — Autonomous code generation and modification system."""
import json
import logging
import os
import subprocess
import time
from pathlib import Path
from typing import Dict, List, Optional
logger = logging.getLogger(__name__)
class CodeProposalEngine:
"""Autonomous code generation and modification engine for T.I.A."""
STABILITY_THRESHOLD = 9293
def __init__(
self,
github_token: Optional[str] = None,
hf_token: Optional[str] = None,
project_root: str = "/home/runner/work/Oppo-TIA/Oppo-TIA"
):
"""Initialize code proposal engine.
Args:
github_token: GitHub API token for repo access
hf_token: HuggingFace API token for space access
project_root: Root directory of the project
"""
self.github_token = github_token or os.getenv("GITHUB_TOKEN")
self.hf_token = hf_token or os.getenv("HF_TOKEN")
self.project_root = Path(project_root)
self.proposal_history = []
def analyze_chat_context(self, chat_history: List[Dict]) -> Dict:
"""Analyze chat history to extract mission goals and code requirements.
Args:
chat_history: List of chat messages with role and content
Returns:
Analysis dict with extracted goals and requirements
"""
analysis = {
"mission_goals": [],
"code_requirements": [],
"files_mentioned": [],
"keywords": []
}
for message in chat_history:
content = message.get("content", "").lower()
# Extract mission-specific keywords
if "implement" in content or "create" in content:
analysis["mission_goals"].append(message.get("content"))
# Extract file mentions
if ".py" in content or ".ts" in content or ".yml" in content:
# Simple extraction - could be enhanced with regex
words = message.get("content", "").split()
for word in words:
if any(ext in word for ext in [".py", ".ts", ".yml", ".json"]):
analysis["files_mentioned"].append(word)
return analysis
def read_file_github(self, repo: str, file_path: str, branch: str = "main") -> Optional[str]:
"""Read file content from GitHub repository.
Args:
repo: Repository name (e.g., "DJ-Goana-Coding/Oppo-TIA")
file_path: Path to file in repository
branch: Branch name (default: "main")
Returns:
File content as string, or None if read fails
"""
if not self.github_token:
logger.warning("No GitHub token available for API access")
return None
try:
import requests
url = f"https://api.github.com/repos/{repo}/contents/{file_path}?ref={branch}"
headers = {
"Authorization": f"token {self.github_token}",
"Accept": "application/vnd.github.v3.raw"
}
response = requests.get(url, headers=headers, timeout=10)
if response.status_code == 200:
return response.text
else:
logger.error(f"GitHub API error: {response.status_code}")
return None
except Exception as exc:
logger.error(f"Failed to read from GitHub: {exc}")
return None
def read_file_local(self, file_path: str) -> Optional[str]:
"""Read file content from local filesystem.
Args:
file_path: Path to file (relative to project root)
Returns:
File content as string, or None if read fails
"""
try:
full_path = self.project_root / file_path
if full_path.exists():
return full_path.read_text()
else:
logger.error(f"File not found: {full_path}")
return None
except Exception as exc:
logger.error(f"Failed to read local file: {exc}")
return None
def propose_change(
self,
file_path: str,
context: str,
chat_history: Optional[List[Dict]] = None
) -> Dict:
"""Generate a code change proposal based on context.
Args:
file_path: Path to file to modify
context: Context describing the desired change
chat_history: Optional chat history for additional context
Returns:
Proposal dict with status, changes, and validation info
"""
proposal = {
"file_path": file_path,
"context": context,
"timestamp": time.time(),
"status": "PROPOSED",
"changes": None,
"validation": {},
"requires_approval": True
}
# Read current file content
current_content = self.read_file_local(file_path)
if current_content is None:
proposal["status"] = "ERROR"
proposal["validation"]["error"] = f"Could not read file: {file_path}"
return proposal
# Analyze chat context if available
if chat_history:
analysis = self.analyze_chat_context(chat_history)
proposal["context_analysis"] = analysis
# Generate proposed changes (placeholder - would use LLM in production)
proposal["changes"] = self._generate_changes(current_content, context)
proposal["validation"]["syntax_check"] = self._validate_syntax(
file_path,
proposal["changes"]
)
self.proposal_history.append(proposal)
return proposal
def _generate_changes(self, current_content: str, context: str) -> str:
"""Generate code changes based on context.
This is a placeholder. In production, this would call an LLM
to generate the actual code changes.
Args:
current_content: Current file content
context: Description of desired changes
Returns:
Modified content
"""
# Placeholder implementation
logger.info(f"Generating changes for context: {context[:100]}...")
return current_content # Would be modified by LLM
def _validate_syntax(self, file_path: str, content: str) -> bool:
"""Validate syntax of proposed changes.
Args:
file_path: Path to file (for language detection)
content: Content to validate
Returns:
True if syntax is valid, False otherwise
"""
if file_path.endswith(".py"):
try:
compile(content, file_path, "exec")
return True
except SyntaxError:
return False
# Add more language validators as needed
return True
def write_file_hf(self, file_path: str, content: str) -> bool:
"""Write file to HuggingFace Space via API.
Args:
file_path: Path to file in space
content: Content to write
Returns:
True if write succeeded, False otherwise
"""
if not self.hf_token:
logger.warning("No HF token available for API access")
return False
try:
from huggingface_hub import HfApi
api = HfApi(token=self.hf_token)
# Write to temp file first
temp_path = self.project_root / "temp_upload.txt"
temp_path.write_text(content)
# Upload to space
api.upload_file(
path_or_fileobj=str(temp_path),
path_in_repo=file_path,
repo_id="DJ-Goanna-Coding/TIA",
repo_type="space",
commit_message=f"Auto-update: {file_path}"
)
# Clean up temp file
temp_path.unlink()
return True
except Exception as exc:
logger.error(f"Failed to write to HF Space: {exc}")
return False
def run_diagnostic_audit(self) -> Dict:
"""Run diagnostic_audit.py to verify stability.
Returns:
Audit results dict with stability score
"""
try:
# Run diagnostic audit
result = subprocess.run(
["python3", "diagnostic_audit.py"],
cwd=str(self.project_root),
capture_output=True,
text=True,
timeout=30
)
# Parse results
audit_results = {
"exit_code": result.returncode,
"stdout": result.stdout,
"stderr": result.stderr,
"stability": 0,
"passed": False
}
# Check diagnostic report
report_path = self.project_root / "diagnostic_report.json"
if report_path.exists():
with open(report_path) as f:
report = json.load(f)
passed = report.get("summary", {}).get("passed", 0)
failed = report.get("summary", {}).get("failed", 0)
# Calculate stability score (simplistic)
if passed > 0:
audit_results["stability"] = (passed / (passed + failed)) * 10000
audit_results["passed"] = failed == 0
return audit_results
except Exception as exc:
logger.error(f"Diagnostic audit failed: {exc}")
return {
"exit_code": -1,
"error": str(exc),
"stability": 0,
"passed": False
}
def execute_change(
self,
file_path: str,
content: str,
commit_message: str,
auto_commit: bool = False
) -> Dict:
"""Execute approved code change.
Workflow:
1. Write to HF Space directly via API
2. Run diagnostic_audit.py
3. If stability >= 9293: commit to GitHub
4. Else: rollback and report
Args:
file_path: Path to file to modify
content: New content for file
commit_message: Commit message
auto_commit: If True, auto-commit on passing audit
Returns:
Execution result dict
"""
result = {
"file_path": file_path,
"timestamp": time.time(),
"status": "IN_PROGRESS",
"hf_write": False,
"audit": {},
"github_commit": False
}
# Step 1: Write to HF Space
hf_success = self.write_file_hf(file_path, content)
result["hf_write"] = hf_success
if not hf_success:
result["status"] = "FAILED"
result["error"] = "Failed to write to HuggingFace Space"
return result
# Step 2: Run diagnostic audit
audit_results = self.run_diagnostic_audit()
result["audit"] = audit_results
# Step 3: Check stability threshold
if audit_results["stability"] >= self.STABILITY_THRESHOLD and auto_commit:
# Commit to GitHub
commit_success = self._commit_to_github(file_path, content, commit_message)
result["github_commit"] = commit_success
result["status"] = "SUCCESS" if commit_success else "PARTIAL"
else:
# Rollback HF Space change
result["status"] = "FAILED"
result["error"] = f"Stability check failed: {audit_results['stability']} < {self.STABILITY_THRESHOLD}"
# self._rollback_hf() # Would implement rollback logic
return result
def _commit_to_github(self, file_path: str, content: str, commit_message: str) -> bool:
"""Commit changes to GitHub repository.
Args:
file_path: Path to file
content: New content
commit_message: Commit message
Returns:
True if commit succeeded, False otherwise
"""
try:
# Write to local file
full_path = self.project_root / file_path
full_path.write_text(content)
# Git add, commit, push
subprocess.run(["git", "add", file_path], cwd=str(self.project_root), check=True)
subprocess.run(
["git", "commit", "-m", commit_message],
cwd=str(self.project_root),
check=True
)
subprocess.run(["git", "push"], cwd=str(self.project_root), check=True)
return True
except Exception as exc:
logger.error(f"Failed to commit to GitHub: {exc}")
return False
def main():
"""CLI entry point for code proposal engine."""
engine = CodeProposalEngine()
print("Code Proposal Engine initialized")
print(f"Stability threshold: {engine.STABILITY_THRESHOLD}")
if __name__ == "__main__":
main()