#!/usr/bin/env python3 """ Agent Task Integration for BlackRoad OS Metrics Automatically creates agent-executable tasks based on metrics thresholds Author: Alexa Amundson Copyright: BlackRoad OS, Inc. """ import json from datetime import datetime import os def load_metrics(): """Load current KPIs and financial data""" kpis = {} financial = {} # Get script directory and parent script_dir = os.path.dirname(os.path.abspath(__file__)) parent_dir = os.path.dirname(script_dir) kpis_path = os.path.join(parent_dir, 'kpis.json') financial_path = os.path.join(parent_dir, 'financial', 'revenue_projections.json') try: with open(kpis_path, 'r') as f: kpis = json.load(f) except FileNotFoundError: print(f"āš ļø kpis.json not found at {kpis_path}") try: with open(financial_path, 'r') as f: financial = json.load(f) except FileNotFoundError: print(f"āš ļø revenue_projections.json not found at {financial_path}") return kpis, financial def generate_agent_task_yml(title, priority, instruction, files, done, constraints, agent="Codex"): """Generate YAML for agent task issue""" yml = f"""name: "šŸ¤– Agent Task" description: "Auto-generated from BlackRoad OS Metrics" title: "{title}" labels: ["agent-task", "automated", "metrics-generated"] body: - type: markdown attributes: value: | ## Agent-Executable Task This task was automatically generated by the BlackRoad OS Metrics system. **Generated:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} **Source:** Metrics threshold detection - type: dropdown id: priority attributes: label: Priority options: - "{priority}" validations: required: true - type: textarea id: instruction attributes: label: Instruction description: What should the agent do? value: | {instruction} validations: required: true - type: textarea id: files attributes: label: Files to touch description: Which files should be created or modified? value: | {files} - type: textarea id: done attributes: label: Definition of done description: How does the agent know it's complete? value: | {done} - type: textarea id: constraints attributes: label: Constraints / Don'ts value: | {constraints} - type: dropdown id: agent attributes: label: Assigned agent options: - "{agent}" """ return yml def analyze_metrics_and_create_tasks(kpis, financial): """Analyze metrics and create agent tasks for improvement opportunities""" tasks = [] # Check deployment success rate if 'data' in kpis and 'operations' in kpis['data']: deploy_success = kpis['data']['operations'].get('deployment_success_rate', 100) if deploy_success < 97: tasks.append({ "title": "[AGENT] Improve deployment success rate", "priority": "P1 - Today", "instruction": f"""Current deployment success rate is {deploy_success}%. Investigate recent failures and implement fixes. Steps: 1. Analyze deployment logs for common failure patterns 2. Identify root causes (config issues, dependency problems, etc.) 3. Implement automated fixes or better error handling 4. Add pre-deployment validation checks 5. Update deployment documentation""", "files": """- Review: .github/workflows/*.yml - Modify: deployment scripts in /scripts - Create: pre-deployment validation script - Update: deployment documentation""", "done": """- Deployment success rate increases above 97% - Root causes documented - Automated fixes implemented - Pre-deployment checks added""", "constraints": """- Don't modify core GitHub Actions - Don't skip security checks - Maintain backward compatibility""" }) # Check test coverage if 'data' in kpis and 'engineering' in kpis['data']: test_coverage = kpis['data']['engineering'].get('test_coverage_pct', 0) if test_coverage < 80: tasks.append({ "title": "[AGENT] Increase test coverage", "priority": "P2 - This week", "instruction": f"""Current test coverage is {test_coverage}%. Increase to minimum 80%. Steps: 1. Identify untested critical code paths 2. Write unit tests for core business logic 3. Add integration tests for API endpoints 4. Create E2E tests for critical user flows 5. Update CI to enforce minimum coverage""", "files": """- Create: tests/ directory structure - Add: test files for each module - Modify: package.json (test scripts) - Update: .github/workflows/test.yml""", "done": """- Test coverage reaches 80%+ - All critical paths tested - CI enforces coverage minimum - Coverage report generated on each run""", "constraints": """- Don't mock critical business logic - Write meaningful tests, not just coverage tests - Follow existing test patterns""" }) # Check documentation if 'data' in kpis and 'engineering' in kpis['data']: total_files = kpis['data']['engineering'].get('total_files', 1) docs = kpis['data']['engineering'].get('documentation_files', 0) doc_ratio = (docs / total_files * 100) if total_files > 0 else 0 if doc_ratio < 5: # Less than 5% documentation tasks.append({ "title": "[AGENT] Improve documentation coverage", "priority": "P2 - This week", "instruction": f"""Documentation ratio is {doc_ratio:.1f}%. Add comprehensive docs. Steps: 1. Create README.md for each major component 2. Add API documentation with examples 3. Write architecture overview 4. Create setup/deployment guides 5. Add inline code comments for complex logic""", "files": """- Create: README.md in each directory - Create: docs/API.md - Create: docs/ARCHITECTURE.md - Create: docs/SETUP.md - Add: JSDoc/docstrings in code""", "done": """- Each component has README - API fully documented with examples - Architecture documented - New developers can setup from docs alone""", "constraints": """- Don't duplicate existing docs - Keep docs concise and practical - Include code examples""" }) # Check revenue generation (from financial data) if 'data' in financial and 'projections' in financial['data']: current_cash = financial['data']['projections']['current_state'].get('cash_position', 0) if current_cash < 50000: # Less than $50K runway tasks.append({ "title": "[AGENT] Deploy monetization infrastructure", "priority": "P0 - Immediate", "instruction": f"""Current cash position: ${current_cash:,}. Deploy revenue streams immediately. Steps: 1. Deploy Stripe sponsor page to blackroad.io/sponsor 2. Add FUNDING.yml to all GitHub repositories 3. Create commercial licensing product pages 4. Set up GitHub Sponsors account 5. Launch consulting/support offerings 6. Create investor deck from financial data""", "files": """- Deploy: stripe/sponsor.html to Cloudflare Pages - Create: .github/FUNDING.yml (template for all repos) - Create: website/pricing.html - Modify: README.md files (add sponsor links) - Generate: investor-deck.pdf from investor_deck_data.json""", "done": """- Sponsor page live at blackroad.io/sponsor - FUNDING.yml in all repos - Pricing page published - GitHub Sponsors activated - Investor deck completed""", "constraints": """- Don't change pricing without approval - Keep brand consistent (see BRAND_GUIDELINES.md) - Follow COPYRIGHT.md for licensing terms""" }) # Check security vulnerabilities if 'data' in kpis and 'security' in kpis['data']: open_vulns = kpis['data']['security'].get('open_vulnerabilities', 0) if open_vulns > 0: tasks.append({ "title": f"[AGENT] Fix {open_vulns} security vulnerabilities", "priority": "P0 - Immediate", "instruction": f"""Found {open_vulns} open security vulnerabilities. Fix immediately. Steps: 1. Run npm audit / pip audit to list all vulnerabilities 2. Update dependencies to patched versions 3. For unfixable vulns, evaluate alternatives or workarounds 4. Add automated security scanning to CI 5. Document security update policy""", "files": """- Modify: package.json / requirements.txt - Run: npm audit fix / pip install --upgrade - Create: .github/workflows/security-scan.yml - Create: docs/SECURITY_POLICY.md""", "done": """- Zero high/critical vulnerabilities - All dependencies updated - Security scanning in CI - Security policy documented""", "constraints": """- Don't break existing functionality - Test after each dependency update - Document any breaking changes""" }) return tasks def save_agent_tasks(tasks): """Save generated agent tasks to files""" output_dir = 'agent_tasks' os.makedirs(output_dir, exist_ok=True) for i, task in enumerate(tasks): filename = f"{output_dir}/task_{i+1}_{task['title'].replace('[AGENT] ', '').replace(' ', '_')[:40]}.yml" yml_content = generate_agent_task_yml( task['title'], task['priority'], task['instruction'], task['files'], task['done'], task['constraints'] ) with open(filename, 'w') as f: f.write(yml_content) print(f"āœ… Created: {filename}") # Create summary summary = f"""# Auto-Generated Agent Tasks **Generated:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} **Source:** BlackRoad OS Metrics Analysis **Total Tasks:** {len(tasks)} --- ## Tasks Created """ for i, task in enumerate(tasks): summary += f"\n### {i+1}. {task['title']}\n" summary += f"**Priority:** {task['priority']}\n\n" summary += f"{task['instruction'][:200]}...\n\n" summary += "\n---\n\n" summary += "**Next Steps:**\n" summary += "1. Review each task in the `agent_tasks/` directory\n" summary += "2. Copy approved tasks to GitHub Issues\n" summary += "3. Label with `agent-task` for Codex to pick up\n" summary += "4. Monitor execution and metrics improvement\n\n" summary += "Ā© 2023-2025 BlackRoad OS, Inc. All Rights Reserved.\n" with open(f"{output_dir}/TASK_SUMMARY.md", 'w') as f: f.write(summary) print(f"āœ… Created: {output_dir}/TASK_SUMMARY.md") def main(): print("šŸ¤– Analyzing metrics and generating agent tasks...") kpis, financial = load_metrics() if not kpis and not financial: print("āŒ No metrics data found. Run update_kpis.py and revenue_tracker.py first.") return tasks = analyze_metrics_and_create_tasks(kpis, financial) if not tasks: print("āœ… No agent tasks needed - all metrics looking good!") return print(f"\nšŸ“‹ Generated {len(tasks)} agent tasks based on metrics analysis") save_agent_tasks(tasks) print(f"\nāœ… Agent tasks saved to scripts/agent_tasks/") print(f"\nTo deploy these tasks:") print(f" 1. Review tasks in scripts/agent_tasks/") print(f" 2. Copy to .github/ISSUE_TEMPLATE/ in target repos") print(f" 3. Create GitHub issues with agent-task label") if __name__ == "__main__": main()