-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo.py
More file actions
379 lines (314 loc) · 12.5 KB
/
demo.py
File metadata and controls
379 lines (314 loc) · 12.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
#!/usr/bin/env python3
"""
Ansib-eL Demo Script
====================
This script demonstrates the key features of the AI-Native Version Control System:
1. System initialization
2. Agent spawning with UUIDs
3. Tournament mode execution
4. Trust scoring
5. Lineage tracking
6. Human-in-the-loop approval
Run: python demo.py
"""
import sys
import tempfile
from pathlib import Path
from uuid import uuid4
# Add current directory to path for imports
sys.path.insert(0, str(Path(__file__).parent))
def print_header(title: str):
"""Print a formatted header."""
print("\n" + "="*70)
print(f" {title}")
print("="*70)
def print_section(title: str):
"""Print a section header."""
print(f"\n{'─'*70}")
print(f" {title}")
print("─"*70)
def demo_agent_system():
"""Demonstrate agent management system."""
print_header("DEMO 1: Agent Management System")
from agent_system import AgentManager, AgentStatus
with tempfile.TemporaryDirectory() as tmpdir:
# Initialize agent manager
manager = AgentManager(tmpdir)
print(f"✓ Agent manager initialized at: {tmpdir}")
# Spawn an agent
agent = manager.spawn_agent(
purpose="Implement user authentication",
model_version="gpt-5.2",
prompt="Create a secure login system with OAuth support",
task_id="task-001"
)
print(f"\n✓ Agent spawned:")
print(f" - Agent ID: {agent.agent_id}")
print(f" - Purpose: {agent.purpose}")
print(f" - Model: {agent.model_version}")
print(f" - Prompt Hash: {agent.prompt_hash[:16]}...")
print(f" - Status: {agent.status.name}")
print(f" - Workspace: {agent.workspace_branch}")
# List active agents
active = manager.list_active_agents()
print(f"\n✓ Active agents: {len(active)}")
# Update status
manager.update_agent_status(agent.agent_id, AgentStatus.WORKING)
print(f"✓ Agent status updated to: WORKING")
# Terminate agent
manager.terminate_agent(agent.agent_id)
print(f"✓ Agent terminated")
def demo_git_wrapper():
"""Demonstrate git wrapper functionality."""
print_header("DEMO 2: Git Wrapper with AI Metadata")
from git_wrapper import GitWrapper, AgentMetadata
with tempfile.TemporaryDirectory() as tmpdir:
# Initialize git wrapper
git = GitWrapper(tmpdir)
# Initialize repository
if git.init_repo():
print(f"✓ Repository initialized at: {tmpdir}")
else:
print("✗ Failed to initialize repository")
return
# Create a test file
test_file = Path(tmpdir) / "hello.txt"
test_file.write_text("Hello, Ansib-eL!")
# Create agent branch
branch_name = git.create_agent_branch(
agent_id="agent-001",
purpose="Add greeting file"
)
print(f"✓ Agent branch created: {branch_name}")
# Commit with metadata
metadata = AgentMetadata(
agent_id="agent-001",
model_version="gpt-5.2",
prompt_hash="sha256:abc123...",
timestamp="2024-01-15T10:30:00Z",
parent_task="task-001",
reasoning="Added greeting as per user request"
)
commit_hash = git.commit_with_metadata(
message="Add greeting file",
metadata=metadata,
files=[str(test_file)]
)
print(f"✓ Commit created: {commit_hash[:8]}")
# Retrieve metadata
retrieved = git.get_commit_metadata(commit_hash)
print(f"\n✓ Retrieved metadata:")
print(f" - Agent ID: {retrieved.agent_id}")
print(f" - Model: {retrieved.model_version}")
print(f" - Reasoning: {retrieved.reasoning}")
def demo_trust_lineage():
"""Demonstrate trust scoring and lineage tracking."""
print_header("DEMO 3: Trust Scoring & Lineage Tracking")
from trust_lineage import TrustLineageManager, DecisionType
from uuid import uuid4
with tempfile.TemporaryDirectory() as tmpdir:
# Initialize trust system
tl = TrustLineageManager(tmpdir)
print(f"✓ Trust system initialized")
# Create test agents
good_agent = uuid4()
bad_agent = uuid4()
print_section("Recording Decisions")
# Record good agent decisions (all accepted)
for i in range(5):
tl.record_decision(
agent_id=good_agent,
decision=DecisionType.ACCEPTED,
commit_hash=f"commit-good-{i}",
review_time_ms=5000
)
print(f"✓ Recorded 5 ACCEPTED decisions for good_agent")
# Record bad agent decisions (mixed)
for i in range(3):
tl.record_decision(
agent_id=bad_agent,
decision=DecisionType.ACCEPTED,
commit_hash=f"commit-bad-ok-{i}",
review_time_ms=10000
)
for i in range(4):
tl.record_decision(
agent_id=bad_agent,
decision=DecisionType.REJECTED,
commit_hash=f"commit-bad-fail-{i}",
review_time_ms=5000
)
print(f"✓ Recorded 3 ACCEPTED, 4 REJECTED for bad_agent")
print_section("Trust Scores")
# Get trust scores
good_score = tl.get_trust_score(good_agent)
bad_score = tl.get_trust_score(bad_agent)
print(f"Good Agent:")
print(f" - Trust Score: {good_score.score:.3f}")
print(f" - Confidence: {good_score.confidence:.3f}")
print(f" - Tier: {tl.get_trust_tier(good_agent).name}")
print(f" - Auto-approve 100 lines: {tl.should_auto_approve(good_agent, 100)}")
print(f"\nBad Agent:")
print(f" - Trust Score: {bad_score.score:.3f}")
print(f" - Confidence: {bad_score.confidence:.3f}")
print(f" - Tier: {tl.get_trust_tier(bad_agent).name}")
print(f" - Auto-approve 100 lines: {tl.should_auto_approve(bad_agent, 100)}")
print_section("Lineage Tracking")
# Record reasoning
tl.record_reasoning(
agent_id=good_agent,
task_id="task-001",
reasoning="""
Chose PostgreSQL over MySQL because:
1. Better JSON support for flexible schemas
2. Stronger consistency guarantees
3. Better geospatial extensions if needed later
"""
)
print(f"✓ Recorded reasoning for library choice")
# Query reasoning
lineage = tl.get_lineage("commit-good-0")
if lineage:
print(f"✓ Retrieved lineage for commit")
def demo_tournament():
"""Demonstrate tournament/parallel execution."""
print_header("DEMO 4: Tournament Mode (Parallel Execution)")
from tournament import (
TournamentOrchestrator, AgentConfig, Task,
SelectionMode, SolutionStatus
)
from agent_system import AgentManager
from git_wrapper import GitWrapper
with tempfile.TemporaryDirectory() as tmpdir:
# Initialize components
git = GitWrapper(tmpdir)
git.init_repo()
agents = AgentManager(tmpdir + "/agents")
# Create tournament orchestrator
tournament = TournamentOrchestrator(agents, git)
print(f"✓ Tournament orchestrator initialized")
# Create a task
task = Task(
task_id="task-001",
description="Implement a factorial function",
context_files=[],
requirements=[
"Handle edge cases (0, 1, negative)",
"Use recursion or iteration",
"Include docstring"
],
test_commands=["python -c \"assert factorial(5) == 120\""],
timeout_seconds=60
)
print(f"✓ Task created: {task.description}")
# Create agent configs for tournament
agent_configs = [
AgentConfig(
agent_id="agent-iterative",
agent_type="gpt-5.2",
model_config={"temperature": 0.7},
timeout_seconds=30
),
AgentConfig(
agent_id="agent-recursive",
agent_type="claude",
model_config={"temperature": 0.8},
timeout_seconds=30
),
AgentConfig(
agent_id="agent-mathlib",
agent_type="gpt-5.2",
model_config={"temperature": 0.5},
timeout_seconds=30
)
]
print(f"✓ Created {len(agent_configs)} agent configurations")
# Create tournament
tourney = tournament.create_tournament(
task=task,
agent_configs=agent_configs,
selection_mode=SelectionMode.HUMAN_CHOICE
)
print(f"✓ Tournament created: {tourney.tournament_id}")
print(f" - Agents: {len(tourney.agent_configs)}")
print(f" - Status: {tourney.status.value}")
print_section("Tournament Results")
# Note: In a real scenario, we'd run actual agents
# Here we just show the structure
print("Tournament structure ready for execution:")
print(f" - Tournament ID: {tourney.tournament_id}")
print(f" - Selection Mode: {tourney.selection_mode.name}")
print(f" - Max Concurrent: {tournament.max_concurrent_agents}")
# Show review presentation format
print("\n✓ Review presentation would include:")
print(" - Side-by-side diff comparison")
print(" - Agent metadata for each solution")
print(" - Evaluation scores")
print(" - Human selection interface")
def demo_orchestrator():
"""Demonstrate the main orchestrator."""
print_header("DEMO 5: Core Orchestrator Integration")
from ansib_el import AnsibElSystem
with tempfile.TemporaryDirectory() as tmpdir:
print(f"Repository: {tmpdir}")
# Initialize system
system = AnsibElSystem(tmpdir)
success = system.initialize()
if success:
print("✓ System initialized successfully")
else:
print("✗ Failed to initialize system")
return
# Show initial status
status = system.get_status()
print(f"\nInitial Status:")
print(f" - Repo initialized: {status.repo_initialized}")
print(f" - Active agents: {status.active_agents}")
print(f" - Pending approvals: {status.pending_approvals}")
print(f" - Total commits: {status.total_commits}")
print_section("Processing a Prompt")
# Note: In a real scenario with actual LLM agents
# this would spawn agents and execute tasks
print("Prompt: 'Add a login page'")
print("\nWorkflow:")
print(" 1. Orchestrator breaks down prompt into tasks")
print(" 2. Tasks delegated to agent pool")
print(" 3. Tournament mode: 3 agents work in parallel")
print(" 4. Solutions queued for human review")
print(" 5. Human approves/rejects")
print(" 6. Winner merged, trust scores updated")
print("\n✓ Orchestrator integration complete")
def main():
"""Run all demos."""
print("\n" + "█"*70)
print("█" + " "*68 + "█")
print("█" + " "*15 + "Ansib-eL: AI-Native Version Control" + " "*16 + "█")
print("█" + " "*68 + "█")
print("█"*70)
try:
demo_agent_system()
except Exception as e:
print(f"\n✗ Agent system demo failed: {e}")
try:
demo_git_wrapper()
except Exception as e:
print(f"\n✗ Git wrapper demo failed: {e}")
try:
demo_trust_lineage()
except Exception as e:
print(f"\n✗ Trust/lineage demo failed: {e}")
try:
demo_tournament()
except Exception as e:
print(f"\n✗ Tournament demo failed: {e}")
try:
demo_orchestrator()
except Exception as e:
print(f"\n✗ Orchestrator demo failed: {e}")
print("\n" + "█"*70)
print("█" + " "*68 + "█")
print("█" + " "*20 + "All demos completed!" + " "*23 + "█")
print("█" + " "*68 + "█")
print("█"*70 + "\n")
if __name__ == "__main__":
main()