-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsovereignty
More file actions
executable file
·319 lines (247 loc) · 9.9 KB
/
sovereignty
File metadata and controls
executable file
·319 lines (247 loc) · 9.9 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
#!/usr/bin/env python3
"""
Sovereignty CLI - Command-Line Interface for All Operations
Complete command-line tooling for sovereignty management.
"""
import sys
import asyncio
import json
import argparse
import logging
from pathlib import Path
# Add src to path
sys.path.insert(0, str(Path(__file__).parent / "src"))
from metrics_collector import SystemMetricsCollector
from telemetry_sovereignty_v2 import TelemetrySovereignty
from spawn_tax_calculator import SpawnTaxCalculator
from roadmap_generator import SovereigntyRoadmap
from control_loop import SovereigntyControlLoop
from worker_pool import WorkerPool
class SovereigntyCLI:
"""Main CLI handler"""
def __init__(self):
self.metrics_collector = None
self.proof_engine = None
def analyze(self, args):
"""Run full sovereignty analysis"""
print("🔍 SOVEREIGNTY ANALYSIS")
print("=" * 80)
print()
# Collect metrics
print("📊 Collecting system metrics...")
collector = SystemMetricsCollector("data/metrics.db")
metrics = collector.collect_all_metrics()
# Evaluate
print("🧪 Evaluating proof obligations...")
engine = TelemetrySovereignty()
report = engine.evaluate_all(metrics)
print()
print(report)
# Save report
with open("data/sovereignty_report.txt", "w") as f:
f.write(report)
print()
print(f"📄 Report saved to: data/sovereignty_report.txt")
return 0
def measure_spawn_tax(self, args):
"""Measure process spawn overhead"""
print("⚡ SPAWN TAX MEASUREMENT")
print("=" * 80)
print()
calculator = SpawnTaxCalculator()
print("Running measurements (this takes ~10 seconds)...")
print()
measurement = calculator.measure_worker_spawn_tax()
print(measurement)
# Generate policy
policy = calculator.generate_spawn_policy(
target_tasks_per_second=args.target_tps,
avg_task_duration=args.task_duration
)
print()
print("SPAWN POLICY RECOMMENDATION")
print("=" * 80)
print(json.dumps(policy, indent=2))
# Save
with open("data/spawn_tax_measurement.json", "w") as f:
json.dump({
"measurement": {
"baseline_ms": measurement.baseline_latency_ms,
"worker_ms": measurement.worker_latency_ms,
"total_tax_ms": measurement.total_tax_ms,
"sustainable_rate": measurement.sustainable_rate_per_sec
},
"policy": policy
}, f, indent=2)
print()
print("📄 Results saved to: data/spawn_tax_measurement.json")
return 0
def generate_roadmap(self, args):
"""Generate 90-day improvement roadmap"""
print("🗺️ SOVEREIGNTY ROADMAP GENERATOR")
print("=" * 80)
print()
# First, run analysis to get gaps
collector = SystemMetricsCollector("data/metrics.db")
metrics = collector.collect_all_metrics()
engine = TelemetrySovereignty()
engine.evaluate_all(metrics)
# Generate roadmap
roadmap = SovereigntyRoadmap(
current_score=engine.total_score,
target_score=args.target_score
)
gaps = roadmap.analyze_gaps(engine.results)
plan = roadmap.generate_90_day_plan()
print(roadmap.generate_report())
# Export JSON
roadmap.export_json("data/sovereignty_roadmap.json")
print()
print("📄 Roadmap saved to: data/sovereignty_roadmap.json")
return 0
def monitor(self, args):
"""Start continuous monitoring"""
print("👁️ SOVEREIGNTY MONITOR")
print("=" * 80)
print()
print(f"Checking sovereignty every {args.interval}s")
print("Press Ctrl+C to stop")
print()
async def run_monitor():
control_loop = SovereigntyControlLoop(check_interval=args.interval)
await control_loop.start()
try:
while True:
await asyncio.sleep(1)
except KeyboardInterrupt:
print("\n\nStopping...")
await control_loop.stop()
# Show report
print()
print(control_loop.get_remediation_report())
asyncio.run(run_monitor())
return 0
def test_pool(self, args):
"""Test worker pool performance"""
print("🏊 WORKER POOL TEST")
print("=" * 80)
print()
async def run_test():
pool = WorkerPool(size=args.pool_size, recycle_after=args.recycle_after)
print(f"Initializing pool (size={args.pool_size})...")
await pool.initialize()
print()
print(f"Processing {args.task_count} tasks...")
print()
import time
start = time.time()
for i in range(args.task_count):
task = {
"type": "test",
"id": i,
"duration": args.task_duration
}
result = await pool.execute_task(task)
print(f"✅ Task {i+1}/{args.task_count}")
duration = time.time() - start
print()
print("=" * 80)
print("RESULTS")
print("=" * 80)
stats = pool.get_stats()
print(f"Total time: {duration:.2f}s")
print(f"Throughput: {args.task_count/duration:.2f} tasks/sec")
print(f"Total spawns: {stats['total_spawns']}")
print(f"Spawn rate: {stats['total_spawns']/duration:.2f} spawns/sec")
print()
await pool.shutdown()
asyncio.run(run_test())
return 0
def dashboard(self, args):
"""Start web dashboard (placeholder)"""
print("🌐 WEB DASHBOARD")
print("=" * 80)
print()
print(f"Starting dashboard on port {args.port}...")
print()
print("⚠️ Web dashboard not yet implemented")
print(" Use 'sovereignty monitor' for continuous monitoring")
print(" Use 'sovereignty analyze' for one-time analysis")
return 1
def main():
"""Main entry point"""
parser = argparse.ArgumentParser(
description="Telemetry Sovereignty 2.0 - Complete System Management",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Run full analysis
./sovereignty analyze
# Measure spawn tax
./sovereignty measure-spawn-tax
# Generate 90-day roadmap
./sovereignty roadmap --target-score 9.6
# Start continuous monitoring
./sovereignty monitor --interval 30
# Test worker pool
./sovereignty test-pool --pool-size 4 --task-count 20
"""
)
subparsers = parser.add_subparsers(dest='command', help='Command to run')
# Analyze command
analyze_parser = subparsers.add_parser('analyze', help='Run sovereignty analysis')
# Measure spawn tax
spawn_parser = subparsers.add_parser('measure-spawn-tax', help='Measure process spawn overhead')
spawn_parser.add_argument('--target-tps', type=float, default=1.0, help='Target tasks per second')
spawn_parser.add_argument('--task-duration', type=float, default=2.0, help='Average task duration (seconds)')
# Generate roadmap
roadmap_parser = subparsers.add_parser('roadmap', help='Generate improvement roadmap')
roadmap_parser.add_argument('--target-score', type=float, default=9.6, help='Target sovereignty score')
# Monitor
monitor_parser = subparsers.add_parser('monitor', help='Start continuous monitoring')
monitor_parser.add_argument('--interval', type=int, default=30, help='Check interval (seconds)')
# Test pool
pool_parser = subparsers.add_parser('test-pool', help='Test worker pool')
pool_parser.add_argument('--pool-size', type=int, default=4, help='Pool size')
pool_parser.add_argument('--task-count', type=int, default=20, help='Number of tasks')
pool_parser.add_argument('--task-duration', type=float, default=0.5, help='Task duration (seconds)')
pool_parser.add_argument('--recycle-after', type=int, default=100, help='Recycle workers after N tasks')
# Dashboard
dashboard_parser = subparsers.add_parser('dashboard', help='Start web dashboard')
dashboard_parser.add_argument('--port', type=int, default=8080, help='Port number')
args = parser.parse_args()
if not args.command:
parser.print_help()
return 1
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# Create data directory
Path("data").mkdir(exist_ok=True)
# Run command
cli = SovereigntyCLI()
command_func = {
'analyze': cli.analyze,
'measure-spawn-tax': cli.measure_spawn_tax,
'roadmap': cli.generate_roadmap,
'monitor': cli.monitor,
'test-pool': cli.test_pool,
'dashboard': cli.dashboard
}.get(args.command)
if command_func:
try:
return command_func(args)
except KeyboardInterrupt:
print("\n\nInterrupted by user")
return 130
except Exception as e:
print(f"\n❌ Error: {e}")
logging.exception("Command failed")
return 1
else:
print(f"Unknown command: {args.command}")
return 1
if __name__ == "__main__":
sys.exit(main())