File size: 13,433 Bytes
67be617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()