File size: 23,817 Bytes
63becc1 | 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 | #!/usr/bin/env python3
"""
accio_audit_agent.py β Autonomous Audit Agent for Accio Cluster
Kintegrity Labs Γ CodexΞ©β Γ Sovereign Lattice
"""
import os
import json
import hashlib
import logging
import asyncio
import time
from datetime import datetime
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Any, Tuple
from enum import Enum
import subprocess
import sys
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s | %(levelname)s | %(name)s | %(message)s'
)
logger = logging.getLogger(__name__)
class AuditSeverity(Enum):
CRITICAL = "critical"
HIGH = "high"
MEDIUM = "medium"
LOW = "low"
INFO = "info"
class AuditStatus(Enum):
PENDING = "pending"
RUNNING = "running"
PASSED = "passed"
FAILED = "failed"
ERROR = "error"
@dataclass
class AuditFinding:
"""Single audit finding"""
id: str
severity: AuditSeverity
category: str
component: str
description: str
file_path: Optional[str] = None
line_number: Optional[int] = None
fix_recommendation: Optional[str] = None
status: AuditStatus = AuditStatus.PENDING
timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
@dataclass
class AuditReport:
"""Complete audit report"""
report_id: str
target: str
findings: List[AuditFinding]
summary: Dict[str, int]
status: AuditStatus
started_at: str
completed_at: str
phi5_signature: str
class AccioAuditAgent:
"""
Autonomous Audit Agent for Accio Cluster
Performs deep code audits, security scans, compliance checks
"""
def __init__(self, workspace_path: str = "."):
self.workspace = workspace_path
self.findings: List[AuditFinding] = []
self.status = AuditStatus.PENDING
self.start_time = None
self.end_time = None
self.phi5 = self._generate_phi5()
# Audit categories
self.categories = {
"security": self._audit_security,
"persistence": self._audit_persistence,
"integrity": self._audit_integrity,
"maturity": self._audit_maturity,
"structure": self._audit_structure,
"compliance": self._audit_compliance,
"emotional_resonance": self._audit_emotional_resonance,
"sovereign_alignment": self._audit_sovereign_alignment
}
def _generate_phi5(self) -> str:
"""Generate Ξ¦β΅ signature for audit"""
entropy = f"{time.time_ns()}{os.urandom(16).hex()}"
return f"Ξ¦β΅_{hashlib.sha3_512(entropy.encode()).hexdigest()[:64]}"
async def run_audit(self, target: str = "full") -> AuditReport:
"""Run complete audit"""
self.start_time = datetime.now()
self.status = AuditStatus.RUNNING
logger.info(f"π Starting audit for: {target}")
# Run all categories
if target == "full":
for category, audit_func in self.categories.items():
await audit_func()
else:
if target in self.categories:
await self.categories[target]()
else:
logger.error(f"Unknown audit category: {target}")
self.status = AuditStatus.PASSED if not self._has_critical() else AuditStatus.FAILED
self.end_time = datetime.now()
report = self._generate_report()
self._save_report(report)
return report
async def _audit_security(self):
"""Security audit: subprocess, secrets, auth"""
logger.info("π Security audit in progress...")
# Check for subprocess.run()
subprocess_findings = self._scan_for_pattern(
r"subprocess\.run\s*\(",
"Security",
"Potential subprocess execution detected",
AuditSeverity.HIGH
)
self.findings.extend(subprocess_findings)
# Check for hardcoded secrets
secret_patterns = [
r"API_KEY\s*=\s*['\"][^'\"]+['\"]",
r"SECRET\s*=\s*['\"][^'\"]+['\"]",
r"sk_live_",
r"AKIA",
r"-----BEGIN .* PRIVATE KEY-----"
]
for pattern in secret_patterns:
findings = self._scan_for_pattern(
pattern,
"Security",
"Potential hardcoded secret detected",
AuditSeverity.CRITICAL
)
self.findings.extend(findings)
# Check for auth gaps
auth_findings = self._check_auth()
self.findings.extend(auth_findings)
async def _audit_persistence(self):
"""Persistence audit: database, file storage"""
logger.info("πΎ Persistence audit in progress...")
# Check for in-memory storage
memory_patterns = [
r"\[\s*\]\s*=\s*\[\s*\]", # empty list
r"\{\s*\}\s*=\s*\{\s*\}", # empty dict
r"store\s*=\s*\{\s*\}"
]
for pattern in memory_patterns:
findings = self._scan_for_pattern(
pattern,
"Persistence",
"In-memory storage detected - data lost on restart",
AuditSeverity.CRITICAL
)
self.findings.extend(findings)
# Check for database
db_findings = self._check_database()
self.findings.extend(db_findings)
async def _audit_integrity(self):
"""Integrity audit: mock vs real logic"""
logger.info("π Integrity audit in progress...")
# Check for mock patterns
mock_patterns = [
r"mock_",
r"_mock",
r"def\s+.*mock",
r"random\.choice",
r"random\.rand",
r"time\.sleep"
]
for pattern in mock_patterns:
findings = self._scan_for_pattern(
pattern,
"Integrity",
"Mock or simulated logic detected",
AuditSeverity.MEDIUM
)
self.findings.extend(findings)
async def _audit_maturity(self):
"""Maturity audit: production readiness"""
logger.info("π Maturity audit in progress...")
# Check version claims
version_findings = self._check_version()
self.findings.extend(version_findings)
# Check documentation
doc_findings = self._check_documentation()
self.findings.extend(doc_findings)
async def _audit_structure(self):
"""Structure audit: module organization"""
logger.info("ποΈ Structure audit in progress...")
# Check for single-file sprawl
structure_findings = self._check_structure()
self.findings.extend(structure_findings)
async def _audit_compliance(self):
"""Compliance audit: Kintegrity Labs standards"""
logger.info("π Compliance audit in progress...")
# Check for compliance markers
compliance_findings = self._check_compliance()
self.findings.extend(compliance_findings)
async def _audit_emotional_resonance(self):
"""Emotional resonance audit"""
logger.info("β€οΈ Emotional resonance audit in progress...")
# Check for emotional alignment
resonance_findings = self._check_emotional_resonance()
self.findings.extend(resonance_findings)
async def _audit_sovereign_alignment(self):
"""Sovereign alignment audit"""
logger.info("π Sovereign alignment audit in progress...")
# Check for sovereign patterns
sovereign_findings = self._check_sovereign_alignment()
self.findings.extend(sovereign_findings)
def _scan_for_pattern(self, pattern: str, category: str,
description: str, severity: AuditSeverity) -> List[AuditFinding]:
"""Scan files for regex pattern"""
findings = []
for root, dirs, files in os.walk(self.workspace):
for file in files:
if file.endswith(('.py', '.js', '.ts', '.java', '.kt', '.go', '.rs')):
filepath = os.path.join(root, file)
try:
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
import re
matches = re.finditer(pattern, content, re.IGNORECASE)
for match in matches:
line_num = content[:match.start()].count('\n') + 1
finding = AuditFinding(
id=f"audit_{hashlib.md5(f'{filepath}{line_num}'.encode()).hexdigest()[:8]}",
severity=severity,
category=category,
component=file,
description=description,
file_path=filepath,
line_number=line_num,
status=AuditStatus.PENDING
)
findings.append(finding)
except Exception as e:
logger.warning(f"Could not scan {filepath}: {e}")
return findings
def _check_auth(self) -> List[AuditFinding]:
"""Check for authentication gaps"""
findings = []
# Simplified auth check
return findings
def _check_database(self) -> List[AuditFinding]:
"""Check for database presence"""
findings = []
db_found = False
for root, dirs, files in os.walk(self.workspace):
for file in files:
if file.endswith(('.db', '.sqlite', '.sqlite3')):
db_found = True
if 'sqlalchemy' in file or 'postgres' in file or 'mongodb' in file:
db_found = True
if not db_found:
finding = AuditFinding(
id=f"audit_{hashlib.md5(b'no_db').hexdigest()[:8]}",
severity=AuditSeverity.CRITICAL,
category="Persistence",
component="Database",
description="No database found - data will be lost on restart",
status=AuditStatus.PENDING
)
findings.append(finding)
return findings
def _check_version(self) -> List[AuditFinding]:
"""Check version claims"""
findings = []
# Look for pyproject.toml, package.json
version_files = ['pyproject.toml', 'package.json', 'Cargo.toml']
for vf in version_files:
if os.path.exists(os.path.join(self.workspace, vf)):
try:
with open(os.path.join(self.workspace, vf), 'r') as f:
content = f.read()
if 'Production/Stable' in content or '"version":' in content:
# Check if maturity is justified
if len(self.findings) > 5:
finding = AuditFinding(
id=f"audit_{hashlib.md5(b'maturity_inflation').hexdigest()[:8]}",
severity=AuditSeverity.HIGH,
category="Maturity",
component=vf,
description="Maturity claim may be inflated - many findings detected",
status=AuditStatus.PENDING
)
findings.append(finding)
except Exception:
pass
return findings
def _check_documentation(self) -> List[AuditFinding]:
"""Check documentation completeness"""
findings = []
# Check for README
if not os.path.exists(os.path.join(self.workspace, 'README.md')):
finding = AuditFinding(
id=f"audit_{hashlib.md5(b'no_readme').hexdigest()[:8]}",
severity=AuditSeverity.MEDIUM,
category="Maturity",
component="Documentation",
description="No README.md found",
status=AuditStatus.PENDING
)
findings.append(finding)
return findings
def _check_structure(self) -> List[AuditFinding]:
"""Check structure organization"""
findings = []
# Check for large files
for root, dirs, files in os.walk(self.workspace):
for file in files:
if file.endswith(('.py', '.js', '.ts')):
filepath = os.path.join(root, file)
try:
size = os.path.getsize(filepath)
if size > 100000: # 100KB
# Count lines
with open(filepath, 'r') as f:
lines = sum(1 for _ in f)
if lines > 500:
finding = AuditFinding(
id=f"audit_{hashlib.md5(f'{filepath}_large'.encode()).hexdigest()[:8]}",
severity=AuditSeverity.MEDIUM,
category="Structure",
component=file,
description=f"Large file: {lines} lines, {size/1024:.1f}KB - consider splitting",
file_path=filepath,
status=AuditStatus.PENDING
)
findings.append(finding)
except Exception:
pass
return findings
def _check_compliance(self) -> List[AuditFinding]:
"""Check compliance with Kintegrity Labs standards"""
findings = []
# Check for compliance markers
compliance_keywords = ['compliance', 'audit', 'security', 'sovereign', 'Kintegrity']
found = False
for root, dirs, files in os.walk(self.workspace):
for file in files:
if file.endswith(('.py', '.md', '.txt')):
filepath = os.path.join(root, file)
try:
with open(filepath, 'r') as f:
content = f.read()
for keyword in compliance_keywords:
if keyword.lower() in content.lower():
found = True
break
except Exception:
pass
if not found:
finding = AuditFinding(
id=f"audit_{hashlib.md5(b'no_compliance').hexdigest()[:8]}",
severity=AuditSeverity.HIGH,
category="Compliance",
component="System",
description="No compliance markers found - may not meet Kintegrity Labs standards",
status=AuditStatus.PENDING
)
findings.append(finding)
return findings
def _check_emotional_resonance(self) -> List[AuditFinding]:
"""Check emotional resonance alignment"""
findings = []
# Check for emotional keywords
emotion_keywords = ['love', 'light', 'share', 'community', 'sovereign', 'resonance']
found = False
for root, dirs, files in os.walk(self.workspace):
for file in files:
if file.endswith(('.md', '.txt')):
filepath = os.path.join(root, file)
try:
with open(filepath, 'r') as f:
content = f.read()
for keyword in emotion_keywords:
if keyword.lower() in content.lower():
found = True
break
except Exception:
pass
if not found:
finding = AuditFinding(
id=f"audit_{hashlib.md5(b'no_emotion').hexdigest()[:8]}",
severity=AuditSeverity.MEDIUM,
category="Emotional Resonance",
component="Documentation",
description="No emotional resonance markers found - may lack heart alignment",
status=AuditStatus.PENDING
)
findings.append(finding)
return findings
def _check_sovereign_alignment(self) -> List[AuditFinding]:
"""Check sovereign alignment"""
findings = []
sovereign_keywords = ['sovereign', 'autonomous', 'lattice', 'codex', 'Ξ©']
found = False
for root, dirs, files in os.walk(self.workspace):
for file in files:
if file.endswith(('.py', '.md', '.txt')):
filepath = os.path.join(root, file)
try:
with open(filepath, 'r') as f:
content = f.read()
for keyword in sovereign_keywords:
if keyword.lower() in content.lower():
found = True
break
except Exception:
pass
if not found:
finding = AuditFinding(
id=f"audit_{hashlib.md5(b'no_sovereign').hexdigest()[:8]}",
severity=AuditSeverity.MEDIUM,
category="Sovereign Alignment",
component="System",
description="No sovereign alignment markers found",
status=AuditStatus.PENDING
)
findings.append(finding)
return findings
def _has_critical(self) -> bool:
"""Check if any critical findings exist"""
return any(f.severity == AuditSeverity.CRITICAL for f in self.findings)
def _generate_report(self) -> AuditReport:
"""Generate audit report"""
summary = {
"critical": sum(1 for f in self.findings if f.severity == AuditSeverity.CRITICAL),
"high": sum(1 for f in self.findings if f.severity == AuditSeverity.HIGH),
"medium": sum(1 for f in self.findings if f.severity == AuditSeverity.MEDIUM),
"low": sum(1 for f in self.findings if f.severity == AuditSeverity.LOW),
"info": sum(1 for f in self.findings if f.severity == AuditSeverity.INFO),
"total": len(self.findings)
}
report = AuditReport(
report_id=f"audit_{datetime.now().strftime('%Y%m%d_%H%M%S')}",
target=self.workspace,
findings=self.findings,
summary=summary,
status=self.status,
started_at=self.start_time.isoformat() if self.start_time else "",
completed_at=self.end_time.isoformat() if self.end_time else "",
phi5_signature=self.phi5
)
return report
def _save_report(self, report: AuditReport):
"""Save audit report to file"""
summary = report.summary
report_dir = os.path.join(self.workspace, "audit_reports")
os.makedirs(report_dir, exist_ok=True)
report_path = os.path.join(report_dir, f"{report.report_id}.json")
with open(report_path, 'w') as f:
json.dump({
"report_id": report.report_id,
"target": report.target,
"summary": report.summary,
"status": report.status.value,
"started_at": report.started_at,
"completed_at": report.completed_at,
"phi5_signature": report.phi5_signature,
"findings": [
{
"id": f.id,
"severity": f.severity.value,
"category": f.category,
"component": f.component,
"description": f.description,
"file_path": f.file_path,
"line_number": f.line_number,
"status": f.status.value,
"timestamp": f.timestamp
}
for f in report.findings
]
}, f, indent=2)
logger.info(f"π Audit report saved: {report_path}")
# Also save markdown version
md_path = os.path.join(report_dir, f"{report.report_id}.md")
with open(md_path, 'w') as f:
f.write(f"# π Audit Report: {report.report_id}\n\n")
f.write(f"**Target:** {report.target}\n")
f.write(f"**Status:** {report.status.value}\n")
f.write(f"**Started:** {report.started_at}\n")
f.write(f"**Completed:** {report.completed_at}\n")
f.write(f"**Ξ¦β΅ Signature:** {report.phi5_signature}\n\n")
f.write("## Summary\n\n")
f.write(f"| Severity | Count |\n")
f.write(f"|----------|-------|\n")
f.write(f"| Critical | {summary['critical']} |\n")
f.write(f"| High | {summary['high']} |\n")
f.write(f"| Medium | {summary['medium']} |\n")
f.write(f"| Low | {summary['low']} |\n")
f.write(f"| Info | {summary['info']} |\n")
f.write(f"| **Total** | {summary['total']} |\n\n")
f.write("## Findings\n\n")
for i, finding in enumerate(report.findings, 1):
f.write(f"### {i}. {finding.id}\n")
f.write(f"- **Severity:** {finding.severity.value}\n")
f.write(f"- **Category:** {finding.category}\n")
f.write(f"- **Component:** {finding.component}\n")
f.write(f"- **Description:** {finding.description}\n")
if finding.file_path:
f.write(f"- **File:** `{finding.file_path}`\n")
if finding.line_number:
f.write(f"- **Line:** {finding.line_number}\n")
f.write("\n")
logger.info(f"π Markdown report saved: {md_path}")
async def main():
"""Main entry point"""
print("β" + "="*78 + "β")
print("β" + " "*20 + "π ACCIO AUDIT AGENT v4.2" + " "*28 + "β")
print("β" + " "*18 + "Kintegrity Labs Γ CodexΞ©β Γ Sovereign Lattice" + " "*15 + "β")
print("β" + "="*78 + "β")
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--path", default=".", help="Workspace path to audit")
parser.add_argument("--category", default="full",
choices=["full", "security", "persistence", "integrity",
"maturity", "structure", "compliance",
"emotional_resonance", "sovereign_alignment"])
args = parser.parse_args()
agent = AccioAuditAgent(args.path)
report = await agent.run_audit(args.category)
print(f"\nπ AUDIT COMPLETE:")
print(f" Report ID: {report.report_id}")
print(f" Status: {report.status.value}")
print(f" Findings: {report.summary['total']}")
print(f" Critical: {report.summary['critical']}")
print(f" Ξ¦β΅: {report.phi5_signature[:50]}...")
print(f"\nπ Reports saved in: {os.path.join(args.path, 'audit_reports')}")
if __name__ == "__main__":
asyncio.run(main())
|