-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
456 lines (364 loc) · 15.5 KB
/
cli.py
File metadata and controls
456 lines (364 loc) · 15.5 KB
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
#!/usr/bin/env python3
"""
Claude Skills CLI
Command-line interface for Engineering Management Claude Skills.
Provides easy access to skill execution, management, and monitoring.
Author: Engineering Management Tools Team
Created: 2024-12-09
Security Level: HIGH - Handles user authentication and skill execution
Usage:
python cli.py list # List available skills
python cli.py execute <skill_name> [params] # Execute a skill
python cli.py status # Show system status
python cli.py config # Configuration management
Security Notes:
- User authentication required for skill execution
- All commands are audited and logged
- Sensitive parameters are masked in logs
"""
import asyncio
import json
import sys
import uuid
from datetime import datetime
from typing import Dict, Any, List, Optional
import click
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, TextColumn
import logging
from core import (
SkillManager, Settings, get_settings,
ExecutionContext, SkillError, SkillCategory
)
# Initialize console for rich output
console = Console()
# Set up logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
@click.group()
@click.option('--debug', is_flag=True, help='Enable debug mode')
@click.option('--config-file', default='.env', help='Configuration file path')
def cli(debug: bool, config_file: str):
"""Claude Skills for Engineering Management - CLI Interface."""
if debug:
logging.getLogger().setLevel(logging.DEBUG)
console.print("[yellow]Debug mode enabled[/yellow]")
# Validate configuration
settings = get_settings()
integration_status = settings.validate_integrations()
if debug:
console.print(f"[dim]Configuration loaded from: {config_file}[/dim]")
console.print(f"[dim]Active integrations: {settings.get_active_integrations()}[/dim]")
@cli.command()
@click.option('--category', type=click.Choice([cat.value for cat in SkillCategory]), help='Filter by category')
@click.option('--format', 'output_format', type=click.Choice(['table', 'json']), default='table', help='Output format')
def list_skills(category: Optional[str], output_format: str):
"""List available Claude skills."""
manager = SkillManager()
skill_category = SkillCategory(category) if category else None
skills = manager.list_skills(skill_category)
if output_format == 'json':
console.print(json.dumps(skills, indent=2, default=str))
return
# Display as table
table = Table(title="Available Claude Skills")
table.add_column("Name", style="cyan")
table.add_column("Category", style="magenta")
table.add_column("Description", style="white")
table.add_column("Status", style="green")
table.add_column("Integrations", style="yellow")
for skill in skills:
status = "✅ Available" if skill["available"] else "❌ Missing deps"
integrations = ", ".join(skill["required_integrations"]) or "None"
table.add_row(
skill["name"],
skill["category"],
skill["description"][:50] + "..." if len(skill["description"]) > 50 else skill["description"],
status,
integrations
)
console.print(table)
console.print(f"\n[dim]Total skills: {len(skills)}[/dim]")
@cli.command()
@click.argument('skill_name')
@click.option('--user-id', default='cli_user', help='User identifier')
@click.option('--user-role', default='senior_manager', help='User role')
@click.option('--team-ids', multiple=True, help='Team IDs (can specify multiple)')
@click.option('--param', 'params', multiple=True, help='Skill parameters in key=value format')
@click.option('--dry-run', is_flag=True, help='Validate parameters without execution')
def execute(
skill_name: str,
user_id: str,
user_role: str,
team_ids: tuple,
params: tuple,
dry_run: bool
):
"""Execute a Claude skill with specified parameters."""
# Parse parameters
skill_params = {}
for param in params:
if '=' not in param:
console.print(f"[red]Invalid parameter format: {param}. Use key=value[/red]")
return
key, value = param.split('=', 1)
# Try to parse as JSON, fall back to string
try:
skill_params[key] = json.loads(value)
except json.JSONDecodeError:
skill_params[key] = value
# Add team IDs if specified
if team_ids:
skill_params['team_ids'] = list(team_ids)
# Create execution context
context = ExecutionContext(
user_id=user_id,
user_role=user_role,
team_ids=list(team_ids),
organization_id="cli_org",
permissions=_get_default_permissions(user_role),
request_id=str(uuid.uuid4())
)
if dry_run:
console.print(f"[yellow]Dry run mode - validating parameters for skill: {skill_name}[/yellow]")
console.print(f"Context: {context.dict()}")
console.print(f"Parameters: {skill_params}")
return
# Execute skill
asyncio.run(_execute_skill_async(skill_name, context, skill_params))
async def _execute_skill_async(skill_name: str, context: ExecutionContext, params: Dict[str, Any]):
"""Execute skill asynchronously with progress indication."""
manager = SkillManager()
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console
) as progress:
task = progress.add_task(f"Executing {skill_name}...", total=None)
try:
# Execute the skill
result = await manager.execute_skill(skill_name, context, **params)
progress.remove_task(task)
# Display results
_display_skill_result(result)
except SkillError as e:
progress.remove_task(task)
console.print(f"[red]Skill execution failed: {e.message}[/red]")
if e.error_code:
console.print(f"[red]Error code: {e.error_code}[/red]")
except Exception as e:
progress.remove_task(task)
console.print(f"[red]Unexpected error: {str(e)}[/red]")
def _display_skill_result(result):
"""Display skill execution results in a formatted way."""
# Success header
if result.success:
console.print(Panel(
f"✅ Skill '{result.skill_name}' executed successfully",
title="Execution Result",
border_style="green"
))
else:
console.print(Panel(
f"❌ Skill '{result.skill_name}' execution failed",
title="Execution Result",
border_style="red"
))
# Execution metadata
if result.execution_time_ms:
console.print(f"[dim]Execution time: {result.execution_time_ms}ms[/dim]")
console.print(f"[dim]Timestamp: {result.timestamp}[/dim]")
console.print(f"[dim]Security level: {result.security_level.value}[/dim]")
# Key insights
if result.insights:
console.print("\n[bold]Key Insights:[/bold]")
for i, insight in enumerate(result.insights, 1):
console.print(f" {i}. {insight}")
# Recommendations
if result.recommendations:
console.print("\n[bold]Recommendations:[/bold]")
for i, rec in enumerate(result.recommendations, 1):
if rec.startswith("URGENT") or rec.startswith("CRITICAL"):
console.print(f" [red]{i}. {rec}[/red]")
else:
console.print(f" {i}. {rec}")
# Summary data
if result.data:
console.print("\n[bold]Summary Data:[/bold]")
# Display key metrics from data
if "analysis_summary" in result.data:
summary = result.data["analysis_summary"]
console.print(f" • Files analyzed: {summary.get('files_analyzed', 'N/A')}")
if "overall_quality_score" in summary:
score = summary["overall_quality_score"]
color = "green" if score >= 80 else "yellow" if score >= 60 else "red"
console.print(f" • Quality score: [{color}]{score}/100[/{color}]")
if "team_summary" in result.data:
summary = result.data["team_summary"]
console.print(f" • Teams analyzed: {summary.get('teams_analyzed', 'N/A')}")
console.print(f" • Total commits: {summary.get('total_commits', 'N/A')}")
console.print(f" • Contributors: {summary.get('total_contributors', 'N/A')}")
# Offer to save detailed results
save_results = click.confirm("\nSave detailed results to file?", default=False)
if save_results:
filename = f"skill_results_{result.skill_name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
with open(filename, 'w') as f:
json.dump(result.dict(), f, indent=2, default=str)
console.print(f"[green]Results saved to {filename}[/green]")
@cli.command()
def status():
"""Show system status and integration health."""
settings = get_settings()
manager = SkillManager()
# System information
console.print(Panel(
f"Claude Skills v{settings.version}\n"
f"Environment: {'Debug' if settings.debug else 'Production'}",
title="System Information",
border_style="blue"
))
# Integration status
integration_status = settings.validate_integrations()
table = Table(title="Integration Status")
table.add_column("Integration", style="cyan")
table.add_column("Status", style="white")
table.add_column("Required By", style="yellow")
for integration, is_active in integration_status.items():
status_text = "✅ Active" if is_active else "❌ Inactive"
skills_requiring = manager.registry.get_skills_by_integration(integration)
table.add_row(
integration.title(),
status_text,
f"{len(skills_requiring)} skills" if skills_requiring else "None"
)
console.print(table)
# Execution statistics
stats = manager.get_execution_stats()
if stats["total_executions"] > 0:
console.print(f"\n[bold]Execution Statistics:[/bold]")
console.print(f" • Total executions: {stats['total_executions']}")
console.print(f" • Success rate: {stats['success_rate']:.1f}%")
console.print(f" • Average execution time: {stats['average_execution_time_ms']:.0f}ms")
console.print(f" • Currently active: {stats['active_executions']}")
@cli.command()
@click.argument('skill_name')
def info(skill_name: str):
"""Get detailed information about a specific skill."""
manager = SkillManager()
skill_info = manager.get_skill_info(skill_name)
if not skill_info:
console.print(f"[red]Skill '{skill_name}' not found[/red]")
return
# Basic information
console.print(Panel(
f"[bold]{skill_info['name']}[/bold]\n"
f"Category: {skill_info['category']}\n"
f"Security Level: {skill_info['security_level']}\n"
f"Description: {skill_info['description']}",
title="Skill Information",
border_style="cyan"
))
# Requirements
console.print(f"\n[bold]Requirements:[/bold]")
console.print(f" • Permissions: {', '.join(skill_info['required_permissions'])}")
console.print(f" • Integrations: {', '.join(skill_info['required_integrations'])}")
# Integration status
missing_integrations = skill_info.get('integration_status', [])
if missing_integrations:
console.print(f"[red] • Missing integrations: {', '.join(missing_integrations)}[/red]")
else:
console.print("[green] • All integrations configured[/green]")
# Parameter schema
if 'schema' in skill_info and 'parameters' in skill_info['schema']:
params_schema = skill_info['schema']['parameters']
if params_schema.get('properties'):
console.print(f"\n[bold]Parameters:[/bold]")
for param_name, param_info in params_schema['properties'].items():
required = param_name in params_schema.get('required', [])
req_indicator = "[red]*[/red]" if required else "[dim]optional[/dim]"
console.print(f" • {param_name} ({param_info.get('type', 'unknown')}) {req_indicator}")
console.print(f" {param_info.get('description', 'No description')}")
if 'default' in param_info:
console.print(f" [dim]Default: {param_info['default']}[/dim]")
@cli.command()
def config():
"""Show configuration status and help with setup."""
settings = get_settings()
console.print(Panel(
"Configuration Management",
title="Claude Skills Configuration",
border_style="blue"
))
# Show current configuration status
integration_status = settings.validate_integrations()
console.print("[bold]Integration Configuration:[/bold]")
for integration, is_active in integration_status.items():
if is_active:
console.print(f" ✅ {integration.title()}: Configured")
else:
console.print(f" ❌ {integration.title()}: Not configured")
# Provide setup hints
if integration == "git":
console.print(" [dim]Set up: Store GitHub token in keyring with key 'github_token'[/dim]")
elif integration == "jira":
console.print(" [dim]Set up: Configure JIRA_BASE_URL and store credentials in keyring[/dim]")
elif integration == "slack":
console.print(" [dim]Set up: Store Slack bot token in keyring with key 'slack_bot_token'[/dim]")
# Security recommendations
console.print(f"\n[bold]Security Configuration:[/bold]")
console.print(" • Credentials stored in OS keyring: ✅")
console.print(" • Data encryption enabled: ✅")
console.print(f" • Session timeout: {settings.security.session_timeout_hours} hours")
# Show example environment file
console.print(f"\n[bold]Example .env file:[/bold]")
console.print("""
[dim]# Database configuration
DB_DATABASE_URL=sqlite:///./data/skills.db
# Git integration
GIT_DEFAULT_ORG=your-organization
# Jira integration
JIRA_BASE_URL=https://your-company.atlassian.net
JIRA_DEFAULT_PROJECT=ENG
# Slack integration
SLACK_DEFAULT_CHANNEL=#engineering
# Security settings
SECURITY_SESSION_TIMEOUT_HOURS=4
SECURITY_DATA_RETENTION_MONTHS=18[/dim]
""")
def _get_default_permissions(user_role: str) -> List[str]:
"""Get default permissions based on user role."""
role_permissions = {
"senior_manager": [
"read_all_team_metrics",
"execute_cross_team_analysis",
"access_strategic_reports",
"read_codebase",
"execute_quality_analysis",
"view_technical_debt_metrics",
"view_individual_performance",
"access_git_repositories",
"view_team_performance"
],
"team_lead": [
"read_own_team_metrics",
"execute_team_analysis",
"access_tactical_reports",
"read_codebase",
"execute_quality_analysis",
"access_git_repositories",
"view_team_performance"
],
"individual_contributor": [
"read_own_metrics",
"execute_personal_analysis",
"read_codebase"
]
}
return role_permissions.get(user_role, role_permissions["individual_contributor"])
if __name__ == '__main__':
cli()