DetVape commited on
Commit
490cce4
·
verified ·
1 Parent(s): b900b2d

Sync from GitHub via hub-sync

Browse files
Files changed (1) hide show
  1. agents/integration.py +343 -0
agents/integration.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Integration Glue — Wire Memory, Builder, and MCP into Detective Flows
3
+
4
+ This module coordinates the three new systems:
5
+ - Memory: Central brain (findings, lessons, skills, social events)
6
+ - Builder: Self-improvement agent (grounded in Memory, auto-appends outputs)
7
+ - MCP: External data sources (GitHub, Social, Tool Registry)
8
+
9
+ All flows query Memory at start, get grounded context, and append new findings at end.
10
+ """
11
+
12
+ import logging
13
+ from typing import Dict, Any, Optional
14
+
15
+ logger = logging.getLogger("VAPE.Integration")
16
+
17
+ # Optional imports (graceful degradation if not available)
18
+ try:
19
+ from skillforge.memory.retriever import (
20
+ search_memory, append_to_memory, get_memory_stats
21
+ )
22
+ MEMORY_AVAILABLE = True
23
+ except Exception as e:
24
+ logger.warning(f"Memory not available: {e}")
25
+ MEMORY_AVAILABLE = False
26
+ search_memory = None
27
+ append_to_memory = None
28
+
29
+ try:
30
+ from agents.builder import Builder
31
+ BUILDER_AVAILABLE = True
32
+ except Exception as e:
33
+ logger.warning(f"Builder not available: {e}")
34
+ BUILDER_AVAILABLE = False
35
+ Builder = None
36
+
37
+ try:
38
+ from skillforge.mcp import run_mcp_harvest
39
+ MCP_AVAILABLE = True
40
+ except Exception as e:
41
+ logger.warning(f"MCP not available: {e}")
42
+ MCP_AVAILABLE = False
43
+ run_mcp_harvest = None
44
+
45
+
46
+ # ============================================================================
47
+ # Flow: Detective Analysis with Memory Grounding
48
+ # ============================================================================
49
+
50
+ def analysis_with_memory_grounding(
51
+ task: str,
52
+ data: Dict[str, Any],
53
+ category: str = "finding"
54
+ ) -> Dict[str, Any]:
55
+ """
56
+ Run analysis grounded in past findings + auto-append new findings to Memory.
57
+
58
+ Args:
59
+ task: Analysis task description
60
+ data: Data to analyze (market data, slither results, etc.)
61
+ category: Memory category for append ("finding", "lesson", etc.)
62
+
63
+ Returns:
64
+ Analysis result dict
65
+ """
66
+ result = {
67
+ "task": task,
68
+ "grounded_in_memory": False,
69
+ "memory_context": [],
70
+ "analysis": None,
71
+ "appended_to_memory": False,
72
+ }
73
+
74
+ # Step 1: Ground in Memory
75
+ if MEMORY_AVAILABLE and search_memory:
76
+ try:
77
+ context = search_memory(
78
+ query=task,
79
+ max_results=5,
80
+ min_confidence=0.7
81
+ )
82
+ result["memory_context"] = context
83
+ result["grounded_in_memory"] = True
84
+
85
+ if context:
86
+ logger.info(f"Grounded '{task}' in {len(context)} Memory entries")
87
+ else:
88
+ logger.info(f"No prior Memory entries for '{task}' — starting fresh")
89
+ except Exception as e:
90
+ logger.warning(f"Memory grounding failed: {e}")
91
+
92
+ # Step 2: Run analysis (caller's responsibility; this just coordinates)
93
+ # The actual analysis happens in agents/run.py, which calls this function
94
+ result["analysis"] = data.get("analysis_result", {})
95
+
96
+ # Step 3: Append findings to Memory
97
+ if MEMORY_AVAILABLE and append_to_memory and result["analysis"]:
98
+ try:
99
+ entry = append_to_memory(
100
+ category=category,
101
+ title=f"{task} — Finding",
102
+ content=str(result["analysis"])[:2000],
103
+ source="agents/run.py",
104
+ tags=task.split(),
105
+ confidence=data.get("confidence", 0.8),
106
+ metadata={
107
+ "task": task,
108
+ "timestamp": data.get("timestamp"),
109
+ }
110
+ )
111
+ result["appended_to_memory"] = True
112
+ logger.info(f"Appended finding to Memory (ID: {entry.get('id')})")
113
+ except Exception as e:
114
+ logger.warning(f"Failed to append to Memory: {e}")
115
+
116
+ return result
117
+
118
+
119
+ # ============================================================================
120
+ # Flow: Builder Code Generation (Self-Improvement)
121
+ # ============================================================================
122
+
123
+ def builder_generate_and_append(
124
+ task: str,
125
+ context_query: Optional[str] = None,
126
+ tier: str = "deep"
127
+ ) -> Dict[str, Any]:
128
+ """
129
+ Generate code via Builder, grounded in Memory, auto-append to Memory.
130
+
131
+ Args:
132
+ task: Code generation task
133
+ context_query: Optional Memory search query for grounding
134
+ tier: LLM tier ("fast" or "deep")
135
+
136
+ Returns:
137
+ Result dict with generated code, metadata, memory append status
138
+ """
139
+ result = {
140
+ "task": task,
141
+ "generated": False,
142
+ "code": "",
143
+ "metadata": {},
144
+ "memory_appended": False,
145
+ "error": None,
146
+ }
147
+
148
+ if not BUILDER_AVAILABLE or not Builder:
149
+ result["error"] = "Builder not available"
150
+ return result
151
+
152
+ try:
153
+ builder = Builder()
154
+
155
+ # Use provided query or default to task
156
+ search_query = context_query or task
157
+
158
+ # Generate code (Builder internally grounds in Memory)
159
+ code, metadata = builder.generate_code(
160
+ task=task,
161
+ review=True,
162
+ tier=tier
163
+ )
164
+
165
+ if not code:
166
+ result["error"] = "Code generation failed"
167
+ return result
168
+
169
+ result["generated"] = True
170
+ result["code"] = code
171
+ result["metadata"] = metadata
172
+
173
+ # Auto-append to Memory (Builder handles this internally)
174
+ try:
175
+ if builder.auto_append_to_memory(code, metadata):
176
+ result["memory_appended"] = True
177
+ except Exception as e:
178
+ logger.warning(f"Builder Memory append failed: {e}")
179
+
180
+ logger.info(f"Builder generated code for '{task}'")
181
+
182
+ except Exception as e:
183
+ result["error"] = str(e)
184
+ logger.error(f"Builder generation failed: {e}")
185
+
186
+ return result
187
+
188
+
189
+ # ============================================================================
190
+ # Flow: MCP Data Harvest → Memory Append
191
+ # ============================================================================
192
+
193
+ def mcp_harvest_and_append() -> Dict[str, Any]:
194
+ """
195
+ Run MCP harvest cycle and append results to Memory.
196
+
197
+ Returns:
198
+ Harvest results (GitHub issues, social sentiment, tool updates)
199
+ """
200
+ result = {
201
+ "harvested": False,
202
+ "appended": False,
203
+ "data": {},
204
+ "error": None,
205
+ }
206
+
207
+ if not MCP_AVAILABLE or not run_mcp_harvest:
208
+ result["error"] = "MCP not available"
209
+ return result
210
+
211
+ try:
212
+ # Run MCP harvest
213
+ mcp_data = run_mcp_harvest()
214
+ result["harvested"] = True
215
+ result["data"] = mcp_data
216
+
217
+ # Append summary to Memory
218
+ if MEMORY_AVAILABLE and append_to_memory:
219
+ try:
220
+ append_to_memory(
221
+ category="finding",
222
+ title="MCP Harvest Summary",
223
+ content=str(mcp_data)[:2000],
224
+ source="skillforge/mcp.py",
225
+ tags=["mcp", "harvest", "external-data"],
226
+ confidence=0.75,
227
+ metadata=mcp_data
228
+ )
229
+ result["appended"] = True
230
+ logger.info("MCP harvest summary appended to Memory")
231
+ except Exception as e:
232
+ logger.warning(f"Failed to append MCP data to Memory: {e}")
233
+
234
+ logger.info(f"MCP harvest complete: {mcp_data}")
235
+
236
+ except Exception as e:
237
+ result["error"] = str(e)
238
+ logger.error(f"MCP harvest failed: {e}")
239
+
240
+ return result
241
+
242
+
243
+ # ============================================================================
244
+ # Flow: Full Cycle (Detective + Builder + MCP + Memory)
245
+ # ============================================================================
246
+
247
+ def run_full_cycle(
248
+ market_data: Dict[str, Any],
249
+ slither_output: str,
250
+ bounties: list
251
+ ) -> Dict[str, Any]:
252
+ """
253
+ Run the complete V.A.P.E. cycle with all three systems integrated.
254
+
255
+ Args:
256
+ market_data: Real market/chain data
257
+ slither_output: Static analysis results
258
+ bounties: List of active bounties
259
+
260
+ Returns:
261
+ Comprehensive result dict
262
+ """
263
+ cycle_result = {
264
+ "timestamp": None,
265
+ "detective_grounded": False,
266
+ "builder_generated": False,
267
+ "mcp_harvested": False,
268
+ "memory_stats": {},
269
+ "findings": [],
270
+ "generated_skills": [],
271
+ "external_data": {},
272
+ }
273
+
274
+ from datetime import datetime
275
+ cycle_result["timestamp"] = datetime.utcnow().isoformat()
276
+
277
+ # Step 1: Detective analysis grounded in Memory
278
+ logger.info("Step 1: Running detective analysis grounded in Memory...")
279
+ analysis_result = analysis_with_memory_grounding(
280
+ task="Analyze market anomalies and security threats",
281
+ data={
282
+ "analysis_result": {
283
+ "anomalies_detected": len([b for b in bounties if b.get("priority") == "high"]),
284
+ "threats": "sample_threat_data",
285
+ },
286
+ "confidence": 0.85,
287
+ "timestamp": cycle_result["timestamp"],
288
+ }
289
+ )
290
+ cycle_result["detective_grounded"] = analysis_result["grounded_in_memory"]
291
+ cycle_result["findings"] = analysis_result["memory_context"]
292
+
293
+ # Step 2: Builder generates improvements grounded in Memory
294
+ logger.info("Step 2: Builder generating code improvements...")
295
+ builder_result = builder_generate_and_append(
296
+ task="Create playbook for analyzing new Solidity smart contracts",
297
+ context_query="static analysis pattern",
298
+ tier="deep"
299
+ )
300
+ cycle_result["builder_generated"] = builder_result["generated"]
301
+ if builder_result["code"]:
302
+ cycle_result["generated_skills"].append({
303
+ "title": builder_result["metadata"].get("title"),
304
+ "code_lines": len(builder_result["code"].split("\n")),
305
+ "memory_appended": builder_result["memory_appended"],
306
+ })
307
+
308
+ # Step 3: MCP harvest external data
309
+ logger.info("Step 3: Harvesting external data via MCP...")
310
+ mcp_result = mcp_harvest_and_append()
311
+ cycle_result["mcp_harvested"] = mcp_result["harvested"]
312
+ cycle_result["external_data"] = mcp_result["data"]
313
+
314
+ # Step 4: Memory stats
315
+ if MEMORY_AVAILABLE and get_memory_stats:
316
+ try:
317
+ stats = get_memory_stats()
318
+ cycle_result["memory_stats"] = stats
319
+ logger.info(f"Memory now contains {stats['total_entries']} entries")
320
+ except Exception as e:
321
+ logger.warning(f"Failed to get Memory stats: {e}")
322
+
323
+ logger.info("Full cycle complete!")
324
+ return cycle_result
325
+
326
+
327
+ # ============================================================================
328
+ # Helpers
329
+ # ============================================================================
330
+
331
+ def get_system_status() -> Dict[str, Any]:
332
+ """Get status of all three systems."""
333
+ return {
334
+ "memory_available": MEMORY_AVAILABLE,
335
+ "builder_available": BUILDER_AVAILABLE,
336
+ "mcp_available": MCP_AVAILABLE,
337
+ "memory_stats": get_memory_stats() if MEMORY_AVAILABLE and get_memory_stats else None,
338
+ }
339
+
340
+
341
+ if __name__ == "__main__":
342
+ print("Integration module for Memory, Builder, and MCP")
343
+ print(f"Status: {get_system_status()}")