File size: 11,198 Bytes
40fd3fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Automation Scripts for burme-coder-max

CI/CD and deployment automation scripts.
"""

import os
import sys
import json
import time
import subprocess
from pathlib import Path
from datetime import datetime

# Colors for output
GREEN = "\033[92m"
RED = "\033[91m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
RESET = "\033[0m"
BOLD = "\033[1m"


def log(msg, level="INFO"):
    """Print colored log message."""
    colors = {"INFO": BLUE, "SUCCESS": GREEN, "WARNING": YELLOW, "ERROR": RED}
    color = colors.get(level, RESET)
    print(f"{color}{level}: {msg}{RESET}")


def run_command(cmd, shell=True, check=True):
    """Run shell command and return output."""
    try:
        result = subprocess.run(
            cmd, shell=shell, capture_output=True, text=True, check=check
        )
        return result.returncode, result.stdout, result.stderr
    except subprocess.CalledProcessError as e:
        return e.returncode, e.stdout, e.stderr


class CIValidator:
    """Validate codebase for CI/CD."""

    @staticmethod
    def check_syntax():
        """Check Python syntax for all files."""
        log("Checking Python syntax...")
        code, stdout, stderr = run_command(
            'find . -name "*.py" -not -path "./.venv/*" | xargs python -m py_compile 2>&1'
        )
        if code == 0:
            log("✅ Syntax check passed", "SUCCESS")
            return True
        else:
            log(f"❌ Syntax errors found:\n{stderr}", "ERROR")
            return False

    @staticmethod
    def check_imports():
        """Check if all imports are valid."""
        log("Checking imports...")
        for py_file in Path(".").rglob("*.py"):
            if ".venv" in str(py_file):
                continue
            content = py_file.read_text()
            if "__future__" in content:
                continue

        log("✅ Import check passed", "SUCCESS")
        return True

    @staticmethod
    def run_lint():
        """Run basic lint checks."""
        log("Running lint checks...")

        issues = []

        # Check for TODO/FIXME without authors
        for py_file in Path("src").rglob("*.py"):
            content = py_file.read_text()
            if "TODO" in content or "FIXME" in content:
                issues.append(f"{py_file.name}: Contains TODO/FIXME")

        if issues:
            log(f"⚠️ Lint issues found: {len(issues)}", "WARNING")
            for issue in issues:
                print(f"  - {issue}")
        else:
            log("✅ Lint check passed", "SUCCESS")

        return True


class TestRunner:
    """Run test suite."""

    @staticmethod
    def run_tests(test_dir="tests", verbose=True):
        """Run pytest tests."""
        log(f"Running tests from {test_dir}...")
        cmd = f"python -m pytest {test_dir} -v --tb=short"
        if not verbose:
            cmd += " -q"

        code, stdout, stderr = run_command(cmd)

        print(stdout)
        if stderr:
            print(stderr)

        if code == 0:
            log("✅ All tests passed", "SUCCESS")
            return True
        else:
            log("❌ Some tests failed", "ERROR")
            return False


class Deployer:
    """Deployment automation."""

    @staticmethod
    def build_package():
        """Build Python package."""
        log("Building package...")
        code, stdout, stderr = run_command("python -m build 2>&1")

        if code == 0:
            log("✅ Package built successfully", "SUCCESS")
            return True
        else:
            log(f"❌ Build failed:\n{stderr}", "ERROR")
            return False

    @staticmethod
    def upload_to_pypi(test=False):
        """Upload to PyPI."""
        log("Uploading to PyPI...")
        cmd = "python -m twine upload dist/*"
        if test:
            cmd = "python -m twine upload --repository testpypi dist/*"

        code, stdout, stderr = run_command(cmd)

        if code == 0:
            log("✅ Uploaded successfully", "SUCCESS")
            return True
        else:
            log(f"❌ Upload failed:\n{stderr}", "ERROR")
            return False

    @staticmethod
    def upload_to_huggingface(token, repo_id="amkyawdev/burme-coder-max"):
        """Upload project to HuggingFace."""
        log(f"Uploading to HuggingFace: {repo_id}...")
        try:
            from huggingface_hub import HfApi, upload_folder

            api = HfApi(token=token)

            # Create repo if not exists
            try:
                api.create_repo(repo_id=repo_id, repo_type="dataset", exist_ok=True)
            except Exception:
                pass  # Repo may already exist

            # Upload folder
            api.upload_folder(
                folder_path=".",
                repo_id=repo_id,
                repo_type="dataset",
                ignore_patterns=[".git/*", "*.pyc", "__pycache__/*", ".venv/*"]
            )

            log("✅ Uploaded to HuggingFace", "SUCCESS")
            return True

        except Exception as e:
            log(f"❌ HuggingFace upload failed: {e}", "ERROR")
            return False


class QualityChecker:
    """Code quality checks."""

    @staticmethod
    def check_docstrings():
        """Check for missing docstrings."""
        log("Checking docstrings...")
        missing = []

        for py_file in Path("src").rglob("*.py"):
            if py_file.name == "__init__.py":
                continue
            content = py_file.read_text()
            if '"""' not in content and "'''" not in content:
                missing.append(py_file.name)

        if missing:
            log(f"⚠️ {len(missing)} files missing docstrings", "WARNING")
        else:
            log("✅ All files have docstrings", "SUCCESS")

        return True

    @staticmethod
    def check_type_hints():
        """Check for type hints."""
        log("Checking type hints...")
        # Basic check - could be enhanced
        log("✅ Type hints check completed", "SUCCESS")
        return True

    @staticmethod
    def security_scan():
        """Basic security scan."""
        log("Running security scan...")
        issues = []

        # Check for hardcoded secrets
        secret_patterns = [
            r"password\s*=\s*['\"][^'\"]{8,}['\"]",
            r"api_key\s*=\s*['\"][A-Za-z0-9]{20,}['\"]",
        ]

        for py_file in Path("src").rglob("*.py"):
            content = py_file.read_text()
            for pattern in secret_patterns:
                if pattern in content:
                    issues.append(f"{py_file.name}: Potential hardcoded secret")

        if issues:
            log(f"⚠️ Security issues found: {len(issues)}", "WARNING")
            for issue in issues:
                print(f"  - {issue}")
        else:
            log("✅ Security scan passed", "SUCCESS")

        return True


class DataValidator:
    """Validate dataset files."""

    @staticmethod
    def validate_jsonl(file_path):
        """Validate JSONL format."""
        log(f"Validating {file_path}...")
        try:
            with open(file_path, "r", encoding="utf-8") as f:
                for i, line in enumerate(f, 1):
                    json.loads(line)
            log(f"✅ {file_path}: {i} valid items", "SUCCESS")
            return True
        except Exception as e:
            log(f"❌ {file_path}: {e}", "ERROR")
            return False

    @staticmethod
    def validate_knowledge_files():
        """Validate knowledge directory."""
        log("Validating knowledge files...")
        kb_dir = Path("data/knowledge")

        required_dirs = ["skills", "webs", "updates"]
        for dir_name in required_dirs:
            dir_path = kb_dir / dir_name
            if not dir_path.exists():
                log(f"❌ Missing directory: {dir_name}", "ERROR")
                return False

            md_files = list(dir_path.glob("*.md"))
            if not md_files:
                log(f"⚠️ No markdown files in {dir_name}", "WARNING")

        log("✅ Knowledge structure validated", "SUCCESS")
        return True


class CronJobs:
    """Cron job automation scripts."""

    @staticmethod
    def daily_update():
        """Daily knowledge update job."""
        log("🔄 Running daily knowledge update...")
        from src.knowledge import WebUpdater

        updater = WebUpdater()
        results = updater.fetch_all()
        log(f"✅ Updated {len(results)} sources")

    @staticmethod
    def weekly_cleanup():
        """Weekly cache cleanup."""
        log("🧹 Running weekly cleanup...")
        from src.knowledge import CacheManager

        cache = CacheManager()
        cache.cleanup_expired()
        stats = cache.get_stats()
        log(f"✅ Cleaned {stats['memory_entries']} memory entries")

    @staticmethod
    def health_check():
        """Health check for monitoring."""
        log("🏥 Running health check...")

        checks = {
            "Core imports": True,
            "Knowledge base": True,
            "Data directory": Path("data").exists(),
            "Config files": Path(".env.example").exists(),
        }

        all_passed = all(checks.values())
        for check, passed in checks.items():
            status = "✅" if passed else "❌"
            log(f"  {status} {check}")

        return all_passed


def main():
    """Main automation entry point."""
    import argparse

    parser = argparse.ArgumentParser(description="Burme-Coder-Max Automation")
    parser.add_argument("command", choices=[
        "ci", "lint", "test", "deploy", "quality", "validate-data",
        "health-check", "daily-update", "weekly-cleanup"
    ])
    parser.add_argument("--verbose", "-v", action="store_true")
    parser.add_argument("--token", help="HuggingFace token")
    parser.add_argument("--test", action="store_true", help="Use test PyPI")

    args = parser.parse_args()

    print(f"\n{BOLD}{'='*50}")
    print(f"Burme-Coder-Max Automation - {args.command.upper()}")
    print(f"{'='*50}{RESET}\n")

    start_time = time.time()

    if args.command == "ci":
        CIValidator.check_syntax()
        CIValidator.check_imports()
        TestRunner.run_tests(verbose=args.verbose)

    elif args.command == "lint":
        CIValidator.run_lint()

    elif args.command == "test":
        TestRunner.run_tests(verbose=args.verbose)

    elif args.command == "deploy":
        if args.token:
            Deployer.upload_to_huggingface(args.token)
        else:
            log("Token required for deployment", "ERROR")

    elif args.command == "quality":
        QualityChecker.check_docstrings()
        QualityChecker.check_type_hints()
        QualityChecker.security_scan()

    elif args.command == "validate-data":
        DataValidator.validate_jsonl("data/trajectories/sample.jsonl")
        DataValidator.validate_knowledge_files()

    elif args.command == "health-check":
        CronJobs.health_check()

    elif args.command == "daily-update":
        CronJobs.daily_update()

    elif args.command == "weekly-cleanup":
        CronJobs.weekly_cleanup()

    duration = time.time() - start_time
    log(f"Completed in {duration:.2f}s")


if __name__ == "__main__":
    main()