This document provides ready-to-use code examples for integrating VersionGuard with other Team Brain tools.
- SynapseLink Integration
- TokenTracker Integration
- DevSnapshot Integration
- TaskFlow Integration
- ConversationAuditor Integration
- AgentHealth Integration
- ErrorRecovery Integration
- Build Pipeline Integration
- Pre-Commit Hook
- Monitoring Dashboard
"""
VersionGuard + SynapseLink: Alert team when incompatibilities detected.
"""
from pathlib import Path
from versionguard import VersionGuard, CompatibilityStatus, Severity
# Import SynapseLink (adjust path as needed)
import sys
sys.path.append("C:\\Users\\logan\\OneDrive\\Documents\\AutoProjects\\SynapseLink")
from synapselink import quick_send
def check_and_alert(project_path: str) -> bool:
"""
Run version check and alert team if critical issues found.
Returns True if compatible, False if incompatible.
"""
guard = VersionGuard(Path(project_path))
guard.scan_project()
guard.check_compatibility()
report = guard.generate_report()
if report.status == CompatibilityStatus.INCOMPATIBLE:
# Build alert message
issues_text = "\n".join(
f"- [{i.severity.value.upper()}] {i.package}: {i.message}"
for i in guard.issues
)
recommendations_text = "\n".join(
f"- {rec}" for rec in report.recommendations
)
message_body = f"""Project: {project_path}
Status: INCOMPATIBLE
ISSUES:
{issues_text}
RECOMMENDATIONS:
{recommendations_text}
Please resolve before proceeding with development."""
# Send alert
quick_send(
recipients="FORGE,IRIS,BOLT",
subject="[VERSIONGUARD] Critical Incompatibility Detected",
body=message_body,
priority="HIGH"
)
return False
return True
# Usage
if not check_and_alert("./bch-mobile"):
print("Alert sent - waiting for resolution")
else:
print("All clear - proceeding")"""
VersionGuard + TokenTracker: Track version check operations.
"""
from pathlib import Path
from versionguard import VersionGuard
import time
# Import TokenTracker
import sys
sys.path.append("C:\\Users\\logan\\OneDrive\\Documents\\AutoProjects\\TokenTracker")
from tokentracker import TokenTracker
def tracked_version_check(project_path: str) -> dict:
"""
Run version check with operation tracking.
"""
tracker = TokenTracker()
# Start tracking
start_time = time.time()
# Run check
guard = VersionGuard(Path(project_path))
guard.scan_project()
guard.check_compatibility()
report = guard.generate_report()
# Calculate duration
duration = time.time() - start_time
# Log operation
tracker.log_operation(
operation="version_check",
tool="VersionGuard",
details={
"project": project_path,
"frontend_deps": len(guard.frontend_deps),
"backend_deps": len(guard.backend_deps),
"issues_found": len(guard.issues),
"status": report.status.value,
"duration_seconds": round(duration, 2)
}
)
return report.to_dict()
# Usage
result = tracked_version_check("./my-project")
print(f"Check complete: {result['status']}")"""
VersionGuard + DevSnapshot: Include compatibility data in development snapshots.
"""
from pathlib import Path
from versionguard import VersionGuard
import json
# Import DevSnapshot
import sys
sys.path.append("C:\\Users\\logan\\OneDrive\\Documents\\AutoProjects\\DevSnapshot")
from devsnapshot import DevSnapshot
def create_enhanced_snapshot(project_path: str, snapshot_name: str) -> str:
"""
Create development snapshot with version compatibility data.
"""
# Create base snapshot
snapshot = DevSnapshot(project_path)
# Run version check
guard = VersionGuard(Path(project_path))
guard.scan_project()
guard.check_compatibility()
report = guard.generate_report()
# Add version data to snapshot metadata
snapshot.add_metadata({
"version_compatibility": {
"status": report.status.value,
"frontend_deps": len(guard.frontend_deps),
"backend_deps": len(guard.backend_deps),
"issues": [i.to_dict() for i in guard.issues],
"recommendations": report.recommendations
}
})
# Save snapshot
snapshot_path = snapshot.save(snapshot_name)
return snapshot_path
# Usage
path = create_enhanced_snapshot("./my-project", "pre-feature-snapshot")
print(f"Snapshot saved: {path}")"""
VersionGuard + TaskFlow: Validate environment before task execution.
"""
from pathlib import Path
from versionguard import VersionGuard, CompatibilityStatus
# Import TaskFlow
import sys
sys.path.append("C:\\Users\\logan\\OneDrive\\Documents\\AutoProjects\\TaskFlow")
from taskflow import Task, TaskStatus
def version_check_gate(task: Task) -> bool:
"""
TaskFlow pre-execution gate for version compatibility.
Returns True if task can proceed, False if blocked.
"""
project_path = task.get_metadata("project_path")
if not project_path:
# No project path - allow task
return True
guard = VersionGuard(Path(project_path))
guard.scan_project()
guard.check_compatibility()
report = guard.generate_report()
if report.status == CompatibilityStatus.INCOMPATIBLE:
# Block task
task.add_note(f"[BLOCKED] Version incompatibility: {report.summary}")
task.set_status(TaskStatus.BLOCKED)
task.set_metadata("blocker", "version_incompatibility")
task.set_metadata("version_report", report.to_dict())
return False
# Add version check note
task.add_note(f"[VERSIONGUARD] {report.summary}")
return True
# Usage in TaskFlow pipeline
def execute_task(task: Task):
# Run version gate first
if not version_check_gate(task):
print(f"Task {task.id} blocked by version check")
return
# Proceed with task execution
print(f"Executing task {task.id}...")"""
VersionGuard + ConversationAuditor: Verify version-related claims.
"""
from pathlib import Path
from versionguard import VersionGuard, SemanticVersion
import re
# Import ConversationAuditor
import sys
sys.path.append("C:\\Users\\logan\\OneDrive\\Documents\\AutoProjects\\ConversationAuditor")
from conversationauditor import Auditor, Claim
def verify_version_claim(claim: Claim, project_path: str) -> dict:
"""
Verify claims about package versions against actual project.
Example claim: "We're using React 18" or "Socket.IO is v4"
"""
guard = VersionGuard(Path(project_path))
guard.scan_project()
# Build lookup
all_deps = {d.name.lower(): d for d in guard.frontend_deps + guard.backend_deps}
# Parse claim for package name and version
# Pattern: "using <package> <version>" or "<package> is v<version>"
patterns = [
r"using\s+(\w+[-\w]*)\s+v?(\d+(?:\.\d+)*)",
r"(\w+[-\w]*)\s+is\s+v?(\d+(?:\.\d+)*)",
r"(\w+[-\w]*)\s+v(\d+(?:\.\d+)*)"
]
for pattern in patterns:
match = re.search(pattern, claim.text, re.IGNORECASE)
if match:
claimed_package = match.group(1).lower()
claimed_version = match.group(2)
if claimed_package in all_deps:
actual_dep = all_deps[claimed_package]
actual_version = actual_dep.version
if actual_version:
claimed_sv = SemanticVersion.parse(claimed_version)
if claimed_sv and actual_version.major == claimed_sv.major:
return {
"verified": True,
"claim": claim.text,
"actual": str(actual_version),
"match": "major_version_match"
}
else:
return {
"verified": False,
"claim": claim.text,
"claimed": claimed_version,
"actual": str(actual_version),
"discrepancy": "version_mismatch"
}
return {
"verified": None,
"claim": claim.text,
"note": "Could not parse version claim"
}
# Usage
claim = Claim(text="We're using React 18 with TypeScript 5")
result = verify_version_claim(claim, "./my-project")
print(f"Verification: {result}")"""
VersionGuard + AgentHealth: Monitor version check health metrics.
"""
from pathlib import Path
from versionguard import VersionGuard
import time
# Import AgentHealth
import sys
sys.path.append("C:\\Users\\logan\\OneDrive\\Documents\\AutoProjects\\AgentHealth")
from agenthealth import HealthMonitor
class VersionGuardHealth:
"""Health monitoring for VersionGuard operations."""
def __init__(self):
self.monitor = HealthMonitor(component="VersionGuard")
self.total_checks = 0
self.failed_checks = 0
self.avg_duration = 0
def check_with_monitoring(self, project_path: str) -> dict:
"""Run version check with health monitoring."""
start = time.time()
try:
guard = VersionGuard(Path(project_path))
guard.scan_project()
guard.check_compatibility()
report = guard.generate_report()
duration = time.time() - start
self.total_checks += 1
self.avg_duration = (self.avg_duration + duration) / 2
# Report health metrics
self.monitor.report_metric("check_duration_ms", duration * 1000)
self.monitor.report_metric("deps_scanned",
len(guard.frontend_deps) + len(guard.backend_deps))
self.monitor.report_metric("issues_found", len(guard.issues))
return report.to_dict()
except Exception as e:
self.failed_checks += 1
self.monitor.report_error("check_failed", str(e))
raise
def get_health_summary(self) -> dict:
"""Get health summary."""
return {
"total_checks": self.total_checks,
"failed_checks": self.failed_checks,
"success_rate": (self.total_checks - self.failed_checks) / max(1, self.total_checks),
"avg_duration_ms": self.avg_duration * 1000
}
# Usage
health = VersionGuardHealth()
result = health.check_with_monitoring("./my-project")
print(f"Health: {health.get_health_summary()}")"""
VersionGuard + ErrorRecovery: Graceful error handling for version checks.
"""
from pathlib import Path
from versionguard import VersionGuard, CompatibilityStatus
# Import ErrorRecovery
import sys
sys.path.append("C:\\Users\\logan\\OneDrive\\Documents\\AutoProjects\\ErrorRecovery")
from errorrecovery import ErrorRecovery, RecoveryStrategy
def safe_version_check(project_path: str) -> dict:
"""
Run version check with error recovery.
"""
recovery = ErrorRecovery()
@recovery.with_retry(max_attempts=3, backoff=1.0)
def perform_check():
guard = VersionGuard(Path(project_path))
guard.scan_project()
guard.check_compatibility()
return guard.generate_report()
try:
report = perform_check()
return {
"success": True,
"status": report.status.value,
"report": report.to_dict()
}
except FileNotFoundError:
# Recovery: Create minimal report
return {
"success": False,
"error": "project_not_found",
"recovery": "skipped_check",
"status": CompatibilityStatus.UNKNOWN.value
}
except Exception as e:
# Log and return safe default
recovery.log_error("version_check", str(e))
return {
"success": False,
"error": str(e),
"recovery": "default_status",
"status": CompatibilityStatus.UNKNOWN.value
}
# Usage
result = safe_version_check("./possibly-missing-project")
if result["success"]:
print(f"Check passed: {result['status']}")
else:
print(f"Check failed: {result['error']}, using: {result['recovery']}")# .github/workflows/version-check.yml
name: Version Compatibility Check
on:
push:
paths:
- 'package.json'
- 'requirements.txt'
- 'pyproject.toml'
pull_request:
paths:
- 'package.json'
- 'requirements.txt'
- 'pyproject.toml'
jobs:
version-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.10'
- name: Clone VersionGuard
run: |
git clone https://github.com/DonkRonk17/VersionGuard.git .versionguard
- name: Run Compatibility Check
id: version_check
run: |
python .versionguard/versionguard.py scan . --json -o version-report.json
if grep -q '"status": "incompatible"' version-report.json; then
echo "status=incompatible" >> $GITHUB_OUTPUT
echo "::error::Version incompatibilities detected!"
python .versionguard/versionguard.py scan .
exit 1
elif grep -q '"status": "warning"' version-report.json; then
echo "status=warning" >> $GITHUB_OUTPUT
echo "::warning::Potential version issues detected"
else
echo "status=compatible" >> $GITHUB_OUTPUT
fi
- name: Upload Report
uses: actions/upload-artifact@v3
with:
name: version-compatibility-report
path: version-report.json
if: always()
- name: Comment on PR
if: github.event_name == 'pull_request'
uses: actions/github-script@v6
with:
script: |
const fs = require('fs');
const report = JSON.parse(fs.readFileSync('version-report.json', 'utf8'));
let body = '## VersionGuard Report\n\n';
body += `**Status:** ${report.status.toUpperCase()}\n\n`;
body += `**Summary:** ${report.summary}\n\n`;
if (report.issues.length > 0) {
body += '### Issues Found\n\n';
for (const issue of report.issues) {
body += `- **${issue.package}**: ${issue.message}\n`;
}
}
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: body
});#!/usr/bin/env python3
"""
Git pre-commit hook for VersionGuard.
Save as .git/hooks/pre-commit and make executable.
"""
import sys
from pathlib import Path
# Add VersionGuard to path
VERSIONGUARD_PATH = Path("C:/Users/logan/OneDrive/Documents/AutoProjects/VersionGuard")
sys.path.insert(0, str(VERSIONGUARD_PATH))
from versionguard import VersionGuard, CompatibilityStatus
def main():
"""Run pre-commit version check."""
print("Running VersionGuard pre-commit check...")
# Check if dependency files are being committed
import subprocess
result = subprocess.run(
["git", "diff", "--cached", "--name-only"],
capture_output=True,
text=True
)
changed_files = result.stdout.strip().split("\n")
dep_files = ["package.json", "requirements.txt", "pyproject.toml"]
if not any(f.endswith(df) for f in changed_files for df in dep_files):
print("No dependency files changed - skipping check")
return 0
# Run version check
guard = VersionGuard(Path("."))
guard.scan_project()
guard.check_compatibility()
report = guard.generate_report()
if report.status == CompatibilityStatus.INCOMPATIBLE:
print("\n" + "=" * 60)
print("COMMIT BLOCKED: Version Incompatibilities Detected!")
print("=" * 60)
print(guard.format_report())
print("\nResolve issues before committing.")
return 1
if report.status == CompatibilityStatus.WARNING:
print(f"\nWarning: {len(guard.issues)} potential issues found")
print("Proceeding with commit...")
print("VersionGuard check passed!")
return 0
if __name__ == "__main__":
sys.exit(main())"""
VersionGuard Monitoring Dashboard - Track multiple projects.
"""
from pathlib import Path
from versionguard import VersionGuard, CompatibilityStatus
from datetime import datetime
import json
class VersionGuardDashboard:
"""Dashboard for monitoring version compatibility across projects."""
def __init__(self, projects_file: str = "projects.json"):
self.projects_file = Path(projects_file)
self.results = []
def add_project(self, path: str, name: str = None):
"""Add a project to monitor."""
projects = self._load_projects()
projects.append({
"path": path,
"name": name or Path(path).name
})
self._save_projects(projects)
def scan_all(self) -> list:
"""Scan all registered projects."""
projects = self._load_projects()
self.results = []
for project in projects:
try:
guard = VersionGuard(Path(project["path"]))
guard.scan_project()
guard.check_compatibility()
report = guard.generate_report()
self.results.append({
"name": project["name"],
"path": project["path"],
"status": report.status.value,
"frontend_deps": len(guard.frontend_deps),
"backend_deps": len(guard.backend_deps),
"issues": len(guard.issues),
"critical": sum(1 for i in guard.issues if i.severity.value == "critical"),
"timestamp": datetime.now().isoformat()
})
except Exception as e:
self.results.append({
"name": project["name"],
"path": project["path"],
"status": "error",
"error": str(e),
"timestamp": datetime.now().isoformat()
})
return self.results
def print_dashboard(self):
"""Print formatted dashboard."""
print("=" * 80)
print("VERSIONGUARD MONITORING DASHBOARD")
print(f"Scanned: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print("=" * 80)
print(f"{'Project':<25} {'Status':<15} {'FE Deps':<10} {'BE Deps':<10} {'Issues':<10}")
print("-" * 80)
for result in self.results:
status = result["status"].upper()
if result.get("critical", 0) > 0:
status += f" ({result['critical']} CRIT)"
print(f"{result['name']:<25} {status:<15} "
f"{result.get('frontend_deps', 'N/A'):<10} "
f"{result.get('backend_deps', 'N/A'):<10} "
f"{result.get('issues', 'N/A'):<10}")
print("=" * 80)
# Summary
compatible = sum(1 for r in self.results if r["status"] == "compatible")
warning = sum(1 for r in self.results if r["status"] == "warning")
incompatible = sum(1 for r in self.results if r["status"] == "incompatible")
print(f"\nSUMMARY: {compatible} Compatible | {warning} Warnings | {incompatible} Incompatible")
def _load_projects(self) -> list:
if self.projects_file.exists():
return json.loads(self.projects_file.read_text())
return []
def _save_projects(self, projects: list):
self.projects_file.write_text(json.dumps(projects, indent=2))
# Usage
dashboard = VersionGuardDashboard()
dashboard.add_project("./project-alpha", "Project Alpha")
dashboard.add_project("./project-beta", "Project Beta")
dashboard.scan_all()
dashboard.print_dashboard()These integration examples demonstrate how VersionGuard works with:
| Integration | Purpose |
|---|---|
| SynapseLink | Team alerts |
| TokenTracker | Operation tracking |
| DevSnapshot | Snapshot metadata |
| TaskFlow | Pre-task gates |
| ConversationAuditor | Claim verification |
| AgentHealth | Health monitoring |
| ErrorRecovery | Graceful failures |
| GitHub Actions | CI/CD pipeline |
| Pre-Commit | Git hooks |
| Dashboard | Multi-project monitoring |
VersionGuard - Pre-validate. Don't waste time.