camawowo commited on
Commit
bf225a8
Β·
1 Parent(s): 3d954b1

lauch agents

Browse files
README.md DELETED
@@ -1,10 +0,0 @@
1
- ---
2
- title: README
3
- emoji: πŸ“Š
4
- colorFrom: indigo
5
- colorTo: indigo
6
- sdk: gradio
7
- pinned: false
8
- ---
9
-
10
- Edit this `README.md` markdown file to author your organization card.
 
 
 
 
 
 
 
 
 
 
 
app.py DELETED
@@ -1,354 +0,0 @@
1
- import gradio as gr
2
- import networkx as nx
3
- import plotly.graph_objects as go
4
- from huggingface_hub import InferenceClient
5
- from concurrent.futures import ThreadPoolExecutor, as_completed
6
- from sentence_transformers import SentenceTransformer
7
- import numpy as np
8
- import sqlite3
9
- import json
10
- import os
11
- import time
12
- import re
13
- import subprocess
14
- import tempfile
15
- import shutil
16
- from datetime import datetime
17
- from typing import Dict, List, Optional, Any
18
- import requests
19
- import haralyzer # pip install haralyzer
20
- from urllib.parse import urlparse
21
- import threading
22
- import queue
23
-
24
- # ==========================================
25
- # CONFIG
26
- # ==========================================
27
- HF_TOKEN = os.getenv("HF_TOKEN")
28
- client = InferenceClient(provider="hf-inference", api_key=HF_TOKEN)
29
- MODEL_NAME = "Qwen/Qwen2.5-7B-Instruct"
30
- embedder = SentenceTransformer("all-MiniLM-L6-v2")
31
-
32
- # Use a simple in-memory vector store (replace with Chroma for scaling)
33
- from sklearn.metrics.pairwise import cosine_similarity
34
- MEMORY_EMBEDDINGS = [] # list of (vector, content, target, timestamp)
35
-
36
- # ==========================================
37
- # TOOL EXECUTOR – runs actual security tools
38
- # ==========================================
39
- AVAILABLE_TOOLS = {
40
- "nuclei": "nuclei -u {url} -json -silent",
41
- "subfinder": "subfinder -d {domain} -silent",
42
- "ffuf_dir": "ffuf -u {url}/FUZZ -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -fc 403,404",
43
- "whatweb": "whatweb {url}",
44
- "curl": "curl -s -o /dev/null -w '%{{http_code}}' {url}",
45
- }
46
-
47
- def execute_tool(tool_name: str, **kwargs) -> str:
48
- """Run a security tool and return its output."""
49
- if tool_name not in AVAILABLE_TOOLS:
50
- return f"Unknown tool: {tool_name}"
51
- cmd_template = AVAILABLE_TOOLS[tool_name]
52
- try:
53
- cmd = cmd_template.format(**kwargs)
54
- except KeyError as e:
55
- return f"Missing parameter {e}"
56
- try:
57
- result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=120)
58
- return result.stdout + "\n" + result.stderr
59
- except subprocess.TimeoutExpired:
60
- return "Tool timed out."
61
- except Exception as e:
62
- return str(e)
63
-
64
- # ==========================================
65
- # HAR PARSER – converts HAR into attack surface
66
- # ==========================================
67
- def parse_har(har_file_path: str) -> Dict[str, Any]:
68
- """Extract endpoints, params, cookies, auth headers from HAR."""
69
- with open(har_file_path, 'r', encoding='utf-8') as f:
70
- har_data = json.load(f)
71
- har = haralyzer.HarParser(har_data)
72
- endpoints = set()
73
- params = set()
74
- auth_headers = set()
75
- for page in har.pages:
76
- for entry in page.entries:
77
- url = entry['request']['url']
78
- endpoints.add(urlparse(url).path)
79
- # Extract query params
80
- query = urlparse(url).query
81
- if query:
82
- for p in query.split('&'):
83
- params.add(p.split('=')[0])
84
- # Check headers
85
- headers = {h['name'].lower(): h['value'] for h in entry['request']['headers']}
86
- if 'authorization' in headers:
87
- auth_headers.add(headers['authorization'][:50])
88
- if 'cookie' in headers:
89
- auth_headers.add(f"cookie={headers['cookie'][:30]}...")
90
- return {
91
- "endpoints": list(endpoints),
92
- "parameters": list(params),
93
- "auth_tokens": list(auth_headers),
94
- "total_requests": len(har.pages[0].entries) if har.pages else 0
95
- }
96
-
97
- # ==========================================
98
- # ADVANCED AGENT POOL (bug bounty roles)
99
- # ==========================================
100
- agent_pool = [
101
- {"name": "Recon", "objective": "Map subdomains, open ports, technologies. Use subfinder, whatweb, nuclei.", "tools": ["subfinder", "whatweb", "nuclei"], "temp": 0.6},
102
- {"name": "Injection Hunter", "objective": "Test for XSS, SQLi, SSTI, command injection. Provide cURL PoC.", "tools": ["curl", "nuclei"], "temp": 0.7},
103
- {"name": "Auth & IDOR", "objective": "Check IDOR, privilege escalation, JWT flaws. Use stolen tokens from HAR.", "tools": ["curl"], "temp": 0.65},
104
- {"name": "Business Logic", "objective": "Abuse workflows, coupon/pricing logic, race windows.", "tools": ["curl"], "temp": 0.8},
105
- {"name": "Config & Exposure", "objective": "Find .git, .env, debug endpoints, CORS misconfig.", "tools": ["ffuf_dir", "nuclei"], "temp": 0.75},
106
- ]
107
-
108
- # ==========================================
109
- # MEMORY (vector based)
110
- # ==========================================
111
- def save_to_memory(target: str, content: str):
112
- vec = embedder.encode([content])[0].tolist()
113
- MEMORY_EMBEDDINGS.append((vec, content, target, datetime.utcnow().isoformat()))
114
- # Also keep SQLite for persistence if desired
115
- cursor.execute("INSERT INTO findings (timestamp, target, content, embedding) VALUES (?, ?, ?, ?)",
116
- (datetime.utcnow().isoformat(), target, content, json.dumps(vec)))
117
- conn.commit()
118
-
119
- def retrieve_similar(query: str, top_k=3) -> List[str]:
120
- if not MEMORY_EMBEDDINGS:
121
- return []
122
- qvec = embedder.encode([query])[0]
123
- scores = []
124
- for vec, content, target, ts in MEMORY_EMBEDDINGS:
125
- sim = cosine_similarity([qvec], [vec])[0][0]
126
- scores.append((sim, content))
127
- scores.sort(reverse=True)
128
- return [content for _, content in scores[:top_k]]
129
-
130
- # ==========================================
131
- # REACT AGENT LOOP – tool-using agent
132
- # ==========================================
133
- def react_agent_run(agent_desc: dict, context: dict, max_steps=4) -> str:
134
- """
135
- context contains:
136
- target, endpoints, parameters, har_summary, memory_context
137
- """
138
- system_prompt = f"""You are an elite bug bounty hunter: {agent_desc['name']}.
139
- Your job: {agent_desc['objective']}
140
- You can call tools: {', '.join(agent_desc['tools'])}.
141
- To call a tool, output exactly: TOOL: <tool_name> ARGS: key=value,key2=value2
142
- When you have a finding, output: FINDING: <detailed description with cURL PoC>
143
- Never output both TOOL and FINDING in the same response.
144
- Be concise, evidence-based. Don't hallucinate URLs."""
145
-
146
- messages = [{"role": "system", "content": system_prompt}]
147
- user_context = f"""
148
- Target: {context.get('target', 'unknown')}
149
- Endpoints: {context.get('endpoints', [])}
150
- Parameters: {context.get('parameters', [])}
151
- Auth snippets: {context.get('auth_tokens', [])}
152
- Memory of past similar: {context.get('memory', '')}
153
- Your first step: choose a tool to gather info or test."""
154
- messages.append({"role": "user", "content": user_context})
155
-
156
- findings = []
157
- for step in range(max_steps):
158
- response = client.chat.completions.create(
159
- model=MODEL_NAME,
160
- messages=messages,
161
- temperature=agent_desc['temp'],
162
- max_tokens=800
163
- )
164
- content = response.choices[0].message.content
165
- messages.append({"role": "assistant", "content": content})
166
-
167
- if content.startswith("TOOL:"):
168
- # Parse tool call
169
- try:
170
- tool_line = content.split("\n")[0]
171
- tool_name = tool_line.split("TOOL:")[1].split("ARGS:")[0].strip()
172
- args_str = tool_line.split("ARGS:")[1].strip()
173
- args = dict(arg.split("=") for arg in args_str.split(","))
174
- # Execute tool
175
- tool_output = execute_tool(tool_name, **args)
176
- # Feed result back
177
- messages.append({"role": "tool", "content": tool_output[:2000]})
178
- # Continue loop
179
- except Exception as e:
180
- messages.append({"role": "tool", "content": f"Error parsing tool: {e}"})
181
- elif content.startswith("FINDING:"):
182
- findings.append(content.replace("FINDING:", "").strip())
183
- # Continue to allow more findings
184
- else:
185
- # If not a clear action, ask to continue
186
- messages.append({"role": "user", "content": "Continue or output FINDING."})
187
-
188
- if findings:
189
- return "\n\n---\n".join(findings)
190
- return "Agent did not produce a finding within steps."
191
-
192
- # ==========================================
193
- # MAIN ANALYSIS PIPELINE
194
- # ==========================================
195
- def full_analysis(
196
- target: str,
197
- har_file: Optional[str],
198
- additional_urls: str,
199
- use_tools: bool,
200
- use_memory: bool,
201
- num_agents: int
202
- ):
203
- start_time = time.time()
204
- logs = [] # live logs
205
- def log(msg):
206
- logs.append(msg)
207
-
208
- # Step 1: Parse HAR if provided
209
- har_summary = {}
210
- if har_file is not None:
211
- try:
212
- har_summary = parse_har(har_file.name)
213
- log(f"Parsed HAR: {har_summary['total_requests']} requests, {len(har_summary['endpoints'])} endpoints")
214
- except Exception as e:
215
- log(f"HAR parse error: {e}")
216
- har_summary = {}
217
- else:
218
- # Manually typed URLs
219
- if additional_urls:
220
- endpoint_list = [u.strip() for u in additional_urls.split("\n") if u.strip()]
221
- har_summary = {"endpoints": endpoint_list, "parameters": [], "auth_tokens": []}
222
-
223
- # Step 2: Active recon (if tools enabled)
224
- if use_tools and target:
225
- domain = urlparse(target).netloc or target
226
- log(f"Running subfinder on {domain}")
227
- sub_output = execute_tool("subfinder", domain=domain)
228
- log(sub_output[:200])
229
- # Append discovered subdomains as endpoints
230
- for line in sub_output.split("\n"):
231
- if line.strip() and not line.startswith("[") :
232
- har_summary.setdefault("endpoints", []).append(f"http://{line.strip()}")
233
-
234
- # Step 3: Memory retrieval
235
- memory_context = ""
236
- if use_memory:
237
- similar = retrieve_similar(target + " ".join(har_summary.get("endpoints", [])))
238
- memory_context = "\n".join(similar)
239
- log(f"Retrieved {len(similar)} memory items")
240
-
241
- # Step 4: Select agents
242
- selected_agents = np.random.choice(agent_pool, min(num_agents, len(agent_pool)), replace=False)
243
-
244
- # Build common context
245
- context = {
246
- "target": target,
247
- "endpoints": har_summary.get("endpoints", []),
248
- "parameters": har_summary.get("parameters", []),
249
- "auth_tokens": har_summary.get("auth_tokens", []),
250
- "memory": memory_context
251
- }
252
-
253
- # Step 5: Run agents in parallel (each may use tools)
254
- agent_results = {}
255
- with ThreadPoolExecutor(max_workers=num_agents) as executor:
256
- futures = {}
257
- for agent in selected_agents:
258
- futures[executor.submit(react_agent_run, agent, context)] = agent['name']
259
- for future in as_completed(futures):
260
- name = futures[future]
261
- try:
262
- agent_results[name] = future.result()
263
- log(f"Agent {name} finished")
264
- except Exception as e:
265
- agent_results[name] = f"Error: {e}"
266
- log(f"Agent {name} failed: {e}")
267
-
268
- # Step 6: Synthesis (master agent)
269
- synthesis_prompt = f"""
270
- You are the master exploit synthesizer. Combine the following agent findings into a comprehensive report.
271
- Include:
272
- - Critical vulnerabilities (with CVSS-like severity)
273
- - Step-by-step reproduction cURLs
274
- - Chained exploits
275
- - Recommended payloads
276
-
277
- AGENT FINDINGS:
278
- {json.dumps(agent_results, indent=2)}
279
- """
280
- final_report = client.chat.completions.create(
281
- model=MODEL_NAME,
282
- messages=[{"role": "user", "content": synthesis_prompt}],
283
- temperature=0.5,
284
- max_tokens=2000
285
- ).choices[0].message.content
286
-
287
- # Save to memory
288
- if use_memory:
289
- save_to_memory(target, final_report)
290
- log("Saved to memory")
291
-
292
- # Build graph (simple, from endpoints)
293
- G = nx.DiGraph()
294
- for ep in har_summary.get("endpoints", [])[:30]: # limit
295
- G.add_node(ep)
296
- # Add edges from target to each endpoint
297
- for ep in har_summary.get("endpoints", [])[:30]:
298
- G.add_edge(target, ep)
299
- fig = graph_to_plotly(G)
300
-
301
- duration = round(time.time() - start_time, 2)
302
- log_text = "\n".join(logs)
303
- return f"Analysis done in {duration}s\n\nLive Log:\n{log_text}", fig, final_report
304
-
305
- # ==========================================
306
- # UI (Gradio)
307
- # ==========================================
308
- def graph_to_plotly(G):
309
- pos = nx.spring_layout(G, seed=42)
310
- edge_x, edge_y = [], []
311
- for edge in G.edges():
312
- x0, y0 = pos[edge[0]]
313
- x1, y1 = pos[edge[1]]
314
- edge_x += [x0, x1, None]
315
- edge_y += [y0, y1, None]
316
- edge_trace = go.Scatter(x=edge_x, y=edge_y, mode='lines')
317
- node_x, node_y, text = [], [], []
318
- for node in G.nodes():
319
- x, y = pos[node]
320
- node_x.append(x)
321
- node_y.append(y)
322
- text.append(node)
323
- node_trace = go.Scatter(x=node_x, y=node_y, mode='markers+text', text=list(G.nodes()),
324
- marker=dict(size=18))
325
- fig = go.Figure(data=[edge_trace, node_trace])
326
- fig.update_layout(title="Attack Surface Graph", height=600)
327
- return fig
328
-
329
- with gr.Blocks(title="Bug Bounty Offensive Engine") as demo:
330
- gr.Markdown("# πŸ›‘οΈ Offensive Bug Bounty Engine")
331
-
332
- with gr.Row():
333
- with gr.Column():
334
- target = gr.Textbox(label="Target Domain/URL (e.g., example.com)")
335
- har_file = gr.File(label="Upload HAR file (optional)", file_types=[".har"])
336
- additional_urls = gr.Textbox(label="Additional URLs (one per line)", lines=4,
337
- placeholder="https://example.com/api/user\nhttps://example.com/admin")
338
- use_tools = gr.Checkbox(label="Enable active scanning tools", value=True)
339
- use_memory = gr.Checkbox(label="Use past findings memory", value=True)
340
- num_agents = gr.Slider(1, 5, value=3, step=1, label="Number of agents")
341
- btn = gr.Button("Run Analysis", variant="primary")
342
-
343
- with gr.Column():
344
- status = gr.Markdown("Ready")
345
- graph = gr.Plot()
346
- report = gr.Textbox(label="Final Report", lines=30, max_lines=50)
347
-
348
- btn.click(
349
- full_analysis,
350
- inputs=[target, har_file, additional_urls, use_tools, use_memory, num_agents],
351
- outputs=[status, graph, report]
352
- )
353
-
354
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
rapis-x/hf_space/README.md ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: RAPIS X
3
+ emoji: ⬑
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ sdk_version: 4.44.0
8
+ app_file: app.py
9
+ pinned: true
10
+ license: mit
11
+ short_description: Adversarial Cognition Platform for Security Analysis & Bug Bounty
12
+ ---
13
+
14
+ # ⬑ RAPIS X β€” Recon & Attack Path Intelligence System
15
+
16
+ Adversarial cognition platform for systemic security analysis.
17
+
18
+ ```
19
+ System = Identity + Trust + State + Flow + Time + Relationships
20
+ Vulnerability = Collapse(SecurityAssumption)
21
+ Attack = propagate(Failure(Assumption))
22
+ ```
23
+
24
+ ## Setup
25
+ Add `ANTHROPIC_API_KEY` in **Settings β†’ Secrets**.
26
+
27
+ ## Capabilities
28
+ - πŸ” AI Reconnaissance with inversion thinking
29
+ - πŸ”„ Deep inversion analysis (5 cognitive layers)
30
+ - πŸ•ΈοΈ Trust graph modeling
31
+ - 🚨 Attack path traversal
32
+ - πŸ’‘ Exploit hypotheses (no payloads)
33
+ - 🧠 6-dimensional cognitive analysis
34
+ - πŸ’Ύ Persistent memory store
35
+ - πŸ‹οΈ Training data generation for security AI fine-tuning
rapis-x/hf_space/app.py ADDED
@@ -0,0 +1,606 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ RAPIS X β€” HuggingFace Spaces Entry Point
3
+ Gradio UI for adversarial security cognition + training data generation.
4
+
5
+ System = Identity + Trust + State + Flow + Time + Relationships
6
+ Vulnerability = Collapse(SecurityAssumption)
7
+ Attack = propagate(Failure(Assumption))
8
+ """
9
+ import os, sys, json, io, uuid
10
+ sys.path.insert(0, os.path.dirname(__file__))
11
+
12
+ import gradio as gr
13
+ import pandas as pd
14
+ from datetime import datetime
15
+
16
+ from engines.claude_api import get_key, call_claude
17
+ from engines.inversion_engine import InversionEngine
18
+ from engines.reading_engine import ReadingEngine
19
+ from engines.pipeline import FullPipeline
20
+ from memory.memory_engine import MemoryEngine
21
+ from training.training_engine import TrainingEngine, TrainingExample
22
+
23
+ # ── Global instances ───────────────────────────────────────────────────────────
24
+ MEM = MemoryEngine()
25
+ READ = ReadingEngine()
26
+ INV = InversionEngine()
27
+ TRAIN = TrainingEngine()
28
+ PIPE = FullPipeline()
29
+
30
+ # Cache last analysis for training generation
31
+ _last_analysis: dict = {}
32
+ _last_inversion: dict = {}
33
+
34
+ # ─────────────────────────────────────────────────────────────────────────────
35
+ # TAB 1 β€” FULL ANALYSIS PIPELINE
36
+ # ─────────────────────────────────────────────────────────────────────────────
37
+
38
+ def run_full_analysis(target: str, context: str, depth: int, save_to_memory: bool, progress=gr.Progress()):
39
+ if not target.strip():
40
+ yield ("❌ Enter a target first.", "", "", "", "", "")
41
+ return
42
+
43
+ try:
44
+ get_key()
45
+ except RuntimeError as e:
46
+ yield (f"❌ {e}", "", "", "", "", "")
47
+ return
48
+
49
+ log_lines = []
50
+ recon_md = graph_md = paths_md = hypo_md = cogn_md = ""
51
+ final_analysis = {}
52
+
53
+ progress(0, desc="Starting pipeline…")
54
+
55
+ for stage, message, pct, data in PIPE.run_stream(target, context, depth):
56
+ log_lines.append(f"[{pct:3d}%] {message}")
57
+ log = "\n".join(log_lines)
58
+ progress(pct / 100, desc=message)
59
+
60
+ if stage == "recon" and data.get("assets"):
61
+ recon_md = _fmt_recon(data)
62
+
63
+ elif stage == "inversion" and data.get("assumptions"):
64
+ _last_inversion.update(data)
65
+
66
+ elif stage == "graph" and data.get("nodes"):
67
+ graph_md = _fmt_graph(data)
68
+
69
+ elif stage == "attack_paths" and data.get("paths"):
70
+ paths_md = _fmt_paths(data["paths"])
71
+
72
+ elif stage == "hypotheses" and data.get("hypotheses"):
73
+ hypo_md = _fmt_hypotheses(data["hypotheses"])
74
+
75
+ elif stage == "cognition" and data.get("identity_analysis"):
76
+ cogn_md = _fmt_cognition(data)
77
+
78
+ elif stage == "complete":
79
+ final_analysis.update(data)
80
+ _last_analysis.update(data)
81
+ log_lines.append(f"\n🎯 COMPLETE β€” Overall Risk: {data.get('overall_risk','?')}")
82
+ log = "\n".join(log_lines)
83
+
84
+ if save_to_memory:
85
+ MEM.store_analysis(target, data)
86
+ MEM.store_inversion(target, _last_inversion)
87
+ log_lines.append("πŸ’Ύ Saved to memory.")
88
+ log = "\n".join(log_lines)
89
+
90
+ yield (log, recon_md, graph_md, paths_md, hypo_md, cogn_md)
91
+
92
+
93
+ def _fmt_recon(r: dict) -> str:
94
+ md = f"## πŸ” Reconnaissance Report\n**Surface:** {r.get('attack_surface_summary','')}\n\n"
95
+ if r.get("assets"):
96
+ md += "### Assets\n| Name | Type | Exposed | Risk Notes |\n|---|---|---|---|\n"
97
+ for a in r["assets"]:
98
+ md += f"| {a.get('name','')} | {a.get('asset_type','')} | {'πŸ”΄ YES' if a.get('exposed') else 'βœ… NO'} | {a.get('risk_notes','')} |\n"
99
+ if r.get("trust_boundaries"):
100
+ md += "\n### Trust Boundaries\n"
101
+ for b in r["trust_boundaries"]:
102
+ md += f"**[{b.get('risk','?')}]** `{b.get('name','')}` β€” ⚠ {b.get('weakness','')}\n\n"
103
+ if r.get("initial_hypotheses"):
104
+ md += "### Initial Hypotheses\n"
105
+ for h in r["initial_hypotheses"]:
106
+ md += f"- {h}\n"
107
+ if r.get("high_risk_components"):
108
+ md += f"\n### High-Risk Components\n" + "".join(f"- πŸ”΄ {c}\n" for c in r["high_risk_components"])
109
+ return md
110
+
111
+ def _fmt_graph(g: dict) -> str:
112
+ md = f"## πŸ•ΈοΈ System Trust Graph\n*{g.get('graph_summary','')}*\n\n"
113
+ if g.get("nodes"):
114
+ md += "### Nodes\n| ID | Label | Type | Risk | Exposed |\n|---|---|---|---|---|\n"
115
+ for n in sorted(g["nodes"], key=lambda x: -x.get("risk_score",0)):
116
+ risk = n.get("risk_score",0)
117
+ clr = "πŸ”΄" if risk>=8 else "🟠" if risk>=6 else "🟑" if risk>=4 else "🟒"
118
+ md += f"| `{n.get('id','')}` | **{n.get('label','')}** | {n.get('node_type','')} | {clr} {risk:.1f} | {'Yes' if n.get('exposed') else 'No'} |\n"
119
+ if g.get("edges"):
120
+ md += "\n### Trust Edges\n| Source β†’ Target | Type | Trust |\n|---|---|---|\n"
121
+ TRUST_ICONS = {"strong":"🟒","weak":"🟠","implicit":"🟑","none":"πŸ”΄"}
122
+ for e in g["edges"]:
123
+ icon = TRUST_ICONS.get(e.get("trust_strength","implicit"),"βšͺ")
124
+ md += f"| `{e.get('source','')}` β†’ `{e.get('target','')}` | {e.get('edge_type','')} | {icon} {e.get('trust_strength','')} |\n"
125
+ return md
126
+
127
+ def _fmt_paths(paths: list) -> str:
128
+ if not paths:
129
+ return "No attack paths identified."
130
+ md = f"## 🚨 Attack Path Analysis ({len(paths)} paths)\n\n"
131
+ for p in paths:
132
+ risk_icons = {"CRITICAL":"πŸ”΄","HIGH":"🟠","MEDIUM":"🟑","LOW":"🟒"}
133
+ icon = risk_icons.get(p.get("risk",""),"βšͺ")
134
+ md += f"### {icon} [{p.get('risk','?')}] {p.get('category','')}\n"
135
+ if p.get("path_nodes"):
136
+ md += f"**Path:** `{'` β†’ `'.join(p['path_nodes'])}`\n\n"
137
+ md += f"**Reasoning:** {p.get('reasoning','')}\n\n"
138
+ if p.get("assumption_chain"):
139
+ md += "**Assumption Chain:**\n"
140
+ for i, a in enumerate(p["assumption_chain"], 1):
141
+ md += f"{i}. {a}\n"
142
+ if p.get("inversion_analysis"):
143
+ md += f"\n> β†Ί **Inversion:** {p['inversion_analysis']}\n"
144
+ md += f"\n*Confidence: {int(p.get('confidence',0)*100)}%*\n\n---\n\n"
145
+ return md
146
+
147
+ def _fmt_hypotheses(hypos: list) -> str:
148
+ if not hypos:
149
+ return "No hypotheses generated."
150
+ md = f"## πŸ’‘ Exploit Hypotheses ({len(hypos)})\n\n> ⚠️ Structural reasoning only β€” no payloads, no instructions.\n\n"
151
+ for h in hypos:
152
+ risk_icons = {"CRITICAL":"πŸ”΄","HIGH":"🟠","MEDIUM":"🟑","LOW":"🟒"}
153
+ icon = risk_icons.get(h.get("risk",""),"βšͺ")
154
+ md += f"### {icon} [{h.get('risk','?')}] {h.get('title','')}\n"
155
+ if h.get("affected_components"):
156
+ md += f"**Affects:** {', '.join(f'`{c}`' for c in h['affected_components'])}\n\n"
157
+ md += f"**Violated Assumption:** {h.get('assumption_violated','')}\n\n"
158
+ md += f"**Reasoning:** {h.get('systemic_reasoning','')}\n\n"
159
+ md += f"**Propagation:** {h.get('propagation_chain','')}\n\n"
160
+ if h.get("inversion_insight"):
161
+ md += f"> β†Ί **Inversion Insight:** {h['inversion_insight']}\n\n"
162
+ if h.get("recommendations"):
163
+ md += "**Defences:**\n" + "".join(f"- βœ… {r}\n" for r in h["recommendations"]) + "\n"
164
+ md += f"*Confidence: {int(h.get('confidence',0)*100)}%*\n\n---\n\n"
165
+ return md
166
+
167
+ def _fmt_cognition(c: dict) -> str:
168
+ md = "## 🧠 Six-Dimensional Cognitive Analysis\n\n"
169
+ dim_icons = {"identity":"πŸ‘€","trust":"🀝","state":"πŸ—„οΈ","time":"⏱️","flow":"🌊","relationship":"πŸ”—"}
170
+ for dim in ["identity","trust","state","time","flow","relationship"]:
171
+ key = f"{dim}_analysis"
172
+ data = c.get(key, {})
173
+ if data:
174
+ icon = dim_icons.get(dim, "⬑")
175
+ md += f"### {icon} {dim.upper()} ANALYSIS\n"
176
+ for k, v in data.items():
177
+ md += f"**{k.replace('_',' ').title()}:** {v}\n\n"
178
+ if c.get("inversion_insights"):
179
+ md += "### β†Ί Inversion Insights\n"
180
+ for ins in c["inversion_insights"]:
181
+ md += f"> {ins}\n\n"
182
+ if c.get("adversarial_questions"):
183
+ md += "### ❓ Adversarial Questions\n"
184
+ for q in c["adversarial_questions"]:
185
+ md += f"- {q}\n"
186
+ if c.get("systemic_risk_summary"):
187
+ md += f"\n### πŸ“Š Risk Summary\n{c['systemic_risk_summary']}\n"
188
+ return md
189
+
190
+
191
+ # ─────────────────────────────────────────────────────────────────────────────
192
+ # TAB 2 β€” INVERSION THINKING
193
+ # ─────────────────────────────────────────────────────────────────────────────
194
+
195
+ def run_inversion(target: str, assumption: str, depth: int, save: bool):
196
+ if not target.strip():
197
+ yield "❌ Enter a target system description."
198
+ return
199
+ try:
200
+ get_key()
201
+ except RuntimeError as e:
202
+ yield f"❌ {e}"
203
+ return
204
+
205
+ yield "## πŸ”„ Inversion Thinking Engine Active...\n\n"
206
+
207
+ if assumption.strip():
208
+ # Quick inversion on specific assumption
209
+ for chunk in INV.quick_inversion(assumption, target):
210
+ yield chunk
211
+ else:
212
+ # Full inversion on target
213
+ for chunk in INV.stream_inversion(target, depth=depth):
214
+ yield chunk
215
+
216
+ if save:
217
+ result = INV.full_inversion(target, depth=depth)
218
+ MEM.store_inversion(target, result.to_dict())
219
+ yield "\n\nπŸ’Ύ *Saved to Memory Bank.*"
220
+
221
+
222
+ # ─────────────────────────────────────────────────────────────────────────────
223
+ # TAB 3 β€” READING ENGINE
224
+ # ─────────────────────────────────────────────────────────────────────────────
225
+
226
+ def run_reading(content: str, deep_mode: bool, save: bool):
227
+ if not content.strip():
228
+ yield "❌ Paste content, a URL, code, or architecture description."
229
+ return
230
+ try:
231
+ get_key()
232
+ except RuntimeError as e:
233
+ yield f"❌ {e}"
234
+ return
235
+
236
+ if deep_mode:
237
+ for chunk in READ.deep_read_stream(content):
238
+ yield chunk
239
+ else:
240
+ yield "## πŸ“– Reading Engine Processing...\n\n"
241
+ result = READ.read(content)
242
+ md = f"**Source Type:** `{result.source_type}`\n\n"
243
+ if result.extracted_components:
244
+ md += f"**Components:** {', '.join(f'`{c}`' for c in result.extracted_components)}\n\n"
245
+ if result.trust_flows:
246
+ md += "**Trust Flows:**\n" + "".join(f"- {f}\n" for f in result.trust_flows) + "\n"
247
+ if result.technology_stack:
248
+ md += f"**Tech Stack:** {', '.join(f'`{t}`' for t in result.technology_stack)}\n\n"
249
+ if result.auth_mechanisms:
250
+ md += f"**Auth:** {', '.join(result.auth_mechanisms)}\n\n"
251
+ if result.attack_surface_notes:
252
+ md += "**Attack Surface Notes:**\n" + "".join(f"- ⚠️ {n}\n" for n in result.attack_surface_notes) + "\n"
253
+ if result.structured_summary:
254
+ md += f"**Summary:**\n{result.structured_summary}\n\n"
255
+ if result.cognitive_context:
256
+ md += f"**Cognitive Context:**\n> {result.cognitive_context}\n"
257
+ if save:
258
+ MEM.store_reading(content[:80], result.to_dict())
259
+ md += "\nπŸ’Ύ *Saved to Memory Bank.*"
260
+ yield md
261
+
262
+
263
+ # ─────────────────────────────────────────────────────────────────────────────
264
+ # TAB 4 β€” MEMORY BANK
265
+ # ─────────────────────────────────────────────────────────────────────────────
266
+
267
+ def view_memory(filter_type: str, search_query: str) -> tuple:
268
+ records = MEM.search(search_query) if search_query.strip() else MEM.get_all(
269
+ filter_type if filter_type != "all" else None
270
+ )
271
+ records = sorted(records, key=lambda r: r.created_at, reverse=True)
272
+
273
+ if not records:
274
+ return "No memory records found.", _memory_stats_md()
275
+
276
+ rows = []
277
+ for r in records[:50]:
278
+ rows.append({
279
+ "ID": r.id[:8],
280
+ "Type": r.memory_type,
281
+ "Target": r.target[:40],
282
+ "Risk": r.risk_level,
283
+ "Tags": ", ".join(r.tags[:3]),
284
+ "Date": r.created_at[:10],
285
+ })
286
+ df = pd.DataFrame(rows)
287
+ return df, _memory_stats_md()
288
+
289
+ def _memory_stats_md() -> str:
290
+ s = MEM.stats()
291
+ md = f"## πŸ’Ύ Memory Stats\n**Total Records:** {s['total']}\n\n"
292
+ md += "**By Type:**\n" + "".join(f"- `{k}`: {v}\n" for k, v in s['by_type'].items())
293
+ md += "\n**By Risk:**\n" + "".join(f"- `{k}`: {v}\n" for k, v in s['by_risk'].items() if v > 0)
294
+ md += f"\n**Training Ready:** {s['training_ready']} examples\n"
295
+ if s['targets']:
296
+ md += f"\n**Targets:** {', '.join(f'`{t[:30]}`' for t in s['targets'][:5])}"
297
+ return md
298
+
299
+ def delete_all_memory():
300
+ MEM.clear()
301
+ return "βœ… Memory cleared.", _memory_stats_md()
302
+
303
+ def export_memory_jsonl():
304
+ jsonl = MEM.export_training_jsonl()
305
+ if not jsonl:
306
+ return None
307
+ path = f"/tmp/rapis_x_export_{uuid.uuid4().hex[:6]}.jsonl"
308
+ with open(path, "w") as f:
309
+ f.write(jsonl)
310
+ return path
311
+
312
+
313
+ # ─────────────────────────────────────────────────────────────────────────────
314
+ # TAB 5 β€” TRAINING DATA GENERATION
315
+ # ─────────────────────────────────────────────────────────────────────────────
316
+
317
+ def generate_training(topic: str, count: int, ex_type: str, fmt: str, from_last_analysis: bool):
318
+ if not topic.strip() and not from_last_analysis:
319
+ yield "❌ Enter a topic or run a full analysis first."
320
+ return
321
+ try:
322
+ get_key()
323
+ except RuntimeError as e:
324
+ yield f"❌ {e}"
325
+ return
326
+
327
+ if from_last_analysis and _last_analysis:
328
+ yield f"## πŸ‹οΈ Generating training data from last analysis...\n\n"
329
+ examples = TRAIN.generate_from_analysis(_last_analysis, _last_analysis.get("target","unknown"))
330
+ yield f"βœ… Generated {len(examples)} examples from last analysis.\n\n"
331
+ else:
332
+ examples = []
333
+ for chunk in TRAIN.stream_generate(topic, count, ex_type):
334
+ yield chunk
335
+ examples = TRAIN.generate_batch(topic, count, ex_type)
336
+
337
+ # Save to memory
338
+ for ex in examples:
339
+ MEM.store("training", topic, ex.instruction[:60], ex.to_dict(),
340
+ tags=["training", ex.example_type], risk_level="INFO")
341
+
342
+ yield f"\n\n## πŸ“Š Generated {len(examples)} Training Examples\n\n"
343
+ for i, ex in enumerate(examples[:3], 1):
344
+ yield f"### Example {i}: {ex.example_type}\n"
345
+ yield f"**Instruction:** {ex.instruction}\n\n"
346
+ if ex.input:
347
+ yield f"**Input:** {ex.input[:200]}\n\n"
348
+ yield f"**Output (preview):** {ex.output[:300]}...\n\n---\n\n"
349
+
350
+ if fmt:
351
+ jsonl = TRAIN.export_jsonl(examples, fmt.lower())
352
+ yield f"\n\n```\n{jsonl[:2000]}\n```\n"
353
+ yield f"\n*{len(examples)} examples in `{fmt}` format. Export from Memory Bank.*"
354
+
355
+
356
+ def export_training_file(fmt: str) -> str | None:
357
+ records = MEM.get_all("training")
358
+ if not records:
359
+ return None
360
+ examples = [TrainingExample(**r.content) for r in records
361
+ if all(k in r.content for k in ["instruction","output","example_type"])]
362
+ if not examples:
363
+ return None
364
+ jsonl = TRAIN.export_jsonl(examples, fmt.lower())
365
+ path = f"/tmp/rapis_x_training_{fmt}_{uuid.uuid4().hex[:6]}.jsonl"
366
+ with open(path, "w") as f:
367
+ f.write(jsonl)
368
+ return path
369
+
370
+
371
+ # ─────────────────────────────────────────────────────────────────────────────
372
+ # GRADIO UI
373
+ # ─────────────────────────────────────────────────────────────────────────────
374
+
375
+ THEME = gr.themes.Base(
376
+ primary_hue="blue",
377
+ secondary_hue="slate",
378
+ neutral_hue="slate",
379
+ font=["IBM Plex Mono", "ui-monospace", "monospace"],
380
+ ).set(
381
+ body_background_fill="#060d1a",
382
+ body_background_fill_dark="#060d1a",
383
+ block_background_fill="#0d1424",
384
+ block_background_fill_dark="#0d1424",
385
+ block_border_color="#1e3a5f",
386
+ block_border_color_dark="#1e3a5f",
387
+ block_label_text_color="#60a5fa",
388
+ block_label_text_color_dark="#60a5fa",
389
+ input_background_fill="#0a1628",
390
+ input_background_fill_dark="#0a1628",
391
+ button_primary_background_fill="#1e3a5f",
392
+ button_primary_background_fill_dark="#1e3a5f",
393
+ button_primary_text_color="#93c5fd",
394
+ button_primary_border_color="#3b82f6",
395
+ )
396
+
397
+ CSS = """
398
+ body, .gradio-container { background: #060d1a !important; font-family: 'IBM Plex Mono', monospace !important; }
399
+ .panel-header { color: #60a5fa !important; letter-spacing: 2px; text-transform: uppercase; font-size: 11px; }
400
+ .risk-critical { color: #ef4444 !important; font-weight: bold; }
401
+ .risk-high { color: #f97316 !important; font-weight: bold; }
402
+ .risk-medium { color: #eab308 !important; font-weight: bold; }
403
+ .risk-low { color: #22c55e !important; font-weight: bold; }
404
+ .tab-nav button { font-family: monospace !important; font-size: 11px !important; letter-spacing: 1px; }
405
+ footer { display: none !important; }
406
+ """
407
+
408
+ HEADER_MD = """
409
+ <div style="text-align:center;padding:20px 0 10px;font-family:'IBM Plex Mono',monospace">
410
+ <div style="font-size:26px;font-weight:700;color:#60a5fa;letter-spacing:4px">⬑ RAPIS X</div>
411
+ <div style="font-size:10px;color:#3b82f6;letter-spacing:3px;margin-top:4px">RECON & ATTACK PATH INTELLIGENCE SYSTEM</div>
412
+ <div style="font-size:9px;color:#374151;margin-top:8px">
413
+ System = Identity + Trust + State + Flow + Time + Relationships &nbsp;|&nbsp;
414
+ Vulnerability = Collapse(SecurityAssumption) &nbsp;|&nbsp;
415
+ Attack = propagate(Failure(Assumption))
416
+ </div>
417
+ </div>
418
+ """
419
+
420
+ with gr.Blocks(theme=THEME, css=CSS, title="RAPIS X") as demo:
421
+ gr.HTML(HEADER_MD)
422
+
423
+ with gr.Tabs():
424
+
425
+ # ── TAB 1: FULL ANALYSIS ─────────────────────────────────────────────
426
+ with gr.Tab("⬑ Full Analysis"):
427
+ gr.Markdown("### 🎯 Full Adversarial Cognition Pipeline\n*Recon β†’ Inversion β†’ Graph β†’ Attack Paths β†’ Hypotheses β†’ Cognition*")
428
+ with gr.Row():
429
+ with gr.Column(scale=3):
430
+ t1_target = gr.Textbox(label="Target System", placeholder="E.g.: E-commerce platform with API Gateway, Redis cache, async payments, JWT auth...", lines=2)
431
+ t1_context = gr.Textbox(label="Additional Context (optional)", placeholder="Architecture notes, tech stack details, known components...", lines=2)
432
+ with gr.Column(scale=1):
433
+ t1_depth = gr.Slider(1, 5, value=3, step=1, label="Analysis Depth (1=Quick, 5=Elite)")
434
+ t1_save = gr.Checkbox(value=True, label="Save to Memory Bank")
435
+ t1_btn = gr.Button("β–Ά RUN FULL ANALYSIS", variant="primary")
436
+
437
+ t1_log = gr.Textbox(label="πŸ“‘ Live Pipeline Feed", lines=12, max_lines=20, interactive=False, show_copy_button=True)
438
+
439
+ with gr.Tabs():
440
+ with gr.Tab("πŸ” Recon"):
441
+ t1_recon = gr.Markdown()
442
+ with gr.Tab("πŸ•ΈοΈ Graph"):
443
+ t1_graph = gr.Markdown()
444
+ with gr.Tab("🚨 Attack Paths"):
445
+ t1_paths = gr.Markdown()
446
+ with gr.Tab("πŸ’‘ Hypotheses"):
447
+ t1_hypo = gr.Markdown()
448
+ with gr.Tab("🧠 Cognition"):
449
+ t1_cogn = gr.Markdown()
450
+
451
+ t1_btn.click(
452
+ fn=run_full_analysis,
453
+ inputs=[t1_target, t1_context, t1_depth, t1_save],
454
+ outputs=[t1_log, t1_recon, t1_graph, t1_paths, t1_hypo, t1_cogn],
455
+ )
456
+
457
+ # ── TAB 2: INVERSION THINKING ────────────────────────────────────────
458
+ with gr.Tab("πŸ”„ Inversion Thinking"):
459
+ gr.Markdown("""### β†Ί Deep Inversion Thinking Engine
460
+ *Never ask: "Where is the vulnerability?" β€” Always ask: "What assumptions currently prevent compromise?"*
461
+ """)
462
+ with gr.Row():
463
+ with gr.Column(scale=2):
464
+ t2_target = gr.Textbox(label="Target / System Description", placeholder="Describe the system or paste architecture details...", lines=3)
465
+ t2_assumption = gr.Textbox(label="Specific Assumption to Invert (optional)", placeholder="E.g.: 'The system assumes Redis always reflects current permission state' β€” leave blank for full inversion", lines=2)
466
+ with gr.Column(scale=1):
467
+ t2_depth = gr.Slider(1, 5, value=3, step=1, label="Inversion Depth")
468
+ t2_save = gr.Checkbox(value=True, label="Save to Memory")
469
+ t2_btn = gr.Button("β†Ί RUN INVERSION", variant="primary")
470
+
471
+ t2_out = gr.Markdown(label="Inversion Analysis")
472
+ t2_btn.click(fn=run_inversion, inputs=[t2_target, t2_assumption, t2_depth, t2_save], outputs=t2_out)
473
+
474
+ gr.Markdown("---\n#### 5-Layer Inversion Model\n| Layer | Question |\n|---|---|\n| L1 Surface | What does the system currently assume is true? |\n| L2 Dependency | What hidden structure supports each assumption? |\n| L3 Collapse | What causes each assumption to fail? |\n| L4 Emergence | What attack paths emerge from each collapse? |\n| L5 Recursion | What new assumptions does the attacker now rely on? |")
475
+
476
+ # ── TAB 3: READING ENGINE ────────────────────────────────────────────
477
+ with gr.Tab("πŸ“– Reading Engine"):
478
+ gr.Markdown("### πŸ“– Adversarial Reading Engine\n*Read any input as a security researcher. Extracts trust flows, attack surface, and cognitive context.*")
479
+ with gr.Row():
480
+ with gr.Column(scale=3):
481
+ t3_content = gr.Textbox(label="Content to Read", placeholder="Paste: URL / architecture doc / code / API spec / plain text description...", lines=8)
482
+ with gr.Column(scale=1):
483
+ t3_deep = gr.Checkbox(value=False, label="Deep Mode (adversarial stream)")
484
+ t3_save = gr.Checkbox(value=True, label="Save to Memory")
485
+ t3_btn = gr.Button("πŸ“– READ & ANALYSE", variant="primary")
486
+ gr.Markdown("**Accepts:**\n- Plain text\n- URLs (auto-fetch)\n- Code snippets\n- API specs\n- Architecture docs")
487
+
488
+ t3_out = gr.Markdown(label="Reading Intelligence")
489
+ t3_btn.click(fn=run_reading, inputs=[t3_content, t3_deep, t3_save], outputs=t3_out)
490
+
491
+ # ── TAB 4: MEMORY BANK ───────────────────────────────────────────────
492
+ with gr.Tab("πŸ’Ύ Memory Bank"):
493
+ gr.Markdown("### πŸ’Ύ Persistent Memory Store\n*All analyses, findings, inversions, and training data.*")
494
+ with gr.Row():
495
+ m_filter = gr.Dropdown(["all","analysis","inversion","reading","finding","training"],
496
+ value="all", label="Filter by Type")
497
+ m_search = gr.Textbox(label="Search", placeholder="Search targets, tags, content...")
498
+ m_refresh = gr.Button("πŸ”„ Refresh", variant="secondary")
499
+
500
+ m_table = gr.Dataframe(label="Memory Records", interactive=False)
501
+ m_stats = gr.Markdown()
502
+ m_export_btn = gr.Button("πŸ“€ Export as Training JSONL", variant="secondary")
503
+ m_export_file = gr.File(label="Download Export")
504
+ m_clear_btn = gr.Button("πŸ—‘οΈ Clear All Memory", variant="stop")
505
+
506
+ m_refresh.click(fn=view_memory, inputs=[m_filter, m_search], outputs=[m_table, m_stats])
507
+ m_export_btn.click(fn=export_memory_jsonl, outputs=m_export_file)
508
+ m_clear_btn.click(fn=delete_all_memory, outputs=[m_stats, m_stats])
509
+ demo.load(fn=view_memory, inputs=[m_filter, m_search], outputs=[m_table, m_stats])
510
+
511
+ # ── TAB 5: TRAINING DATA ─────────────────────────────────────────────
512
+ with gr.Tab("πŸ‹οΈ Training Data"):
513
+ gr.Markdown("""### πŸ‹οΈ Security AI Training Data Generator
514
+ *Generate instruction-tuning datasets for fine-tuning security-focused language models.*
515
+ *All examples teach cognitive reasoning, inversion thinking, and structural analysis β€” never exploitation.*
516
+ """)
517
+ with gr.Row():
518
+ with gr.Column(scale=2):
519
+ t5_topic = gr.Textbox(label="Topic / Domain", placeholder="E.g.: API authentication bypass patterns, race conditions in payment systems, SSRF in cloud environments...")
520
+ t5_from_last = gr.Checkbox(value=False, label="Generate from Last Analysis (uses cached pipeline result)")
521
+ with gr.Column(scale=1):
522
+ t5_count = gr.Slider(3, 20, value=5, step=1, label="Number of Examples")
523
+ t5_type = gr.Dropdown(["mixed","inversion","bug_bounty","attack_path","simplification","cognitive"],
524
+ value="mixed", label="Example Type")
525
+ t5_fmt = gr.Dropdown(["Alpaca","ChatML","Raw"], value="Alpaca", label="Export Format")
526
+ t5_btn = gr.Button("πŸ‹οΈ GENERATE TRAINING DATA", variant="primary")
527
+
528
+ t5_out = gr.Markdown(label="Generated Examples")
529
+ t5_export = gr.Button("πŸ’Ύ Export Training JSONL", variant="secondary")
530
+ t5_file = gr.File(label="Download Training Data")
531
+
532
+ t5_btn.click(fn=generate_training,
533
+ inputs=[t5_topic, t5_count, t5_type, t5_fmt, t5_from_last],
534
+ outputs=t5_out)
535
+ t5_export.click(fn=lambda fmt: export_training_file(fmt.lower()),
536
+ inputs=[t5_fmt], outputs=t5_file)
537
+
538
+ gr.Markdown("""---
539
+ #### Training Data Categories
540
+ | Type | Teaches |
541
+ |---|---|
542
+ | `inversion` | Assumption mapping β†’ collapse chain β†’ emergent attack surface |
543
+ | `bug_bounty` | Target reading β†’ cognitive triage β†’ hypothesis generation |
544
+ | `attack_path` | Graph traversal β†’ trust analysis β†’ risk ranking |
545
+ | `simplification` | Technical complexity β†’ plain English explanation |
546
+ | `cognitive` | 6-dimensional analysis (Identity/Trust/State/Time/Flow/Relationships) |
547
+ | `mixed` | All of the above β€” balanced dataset |
548
+ """)
549
+
550
+ # ── TAB 6: ABOUT ─────────────────────────────────────────────────────
551
+ with gr.Tab("ℹ️ About"):
552
+ gr.Markdown("""
553
+ ## ⬑ RAPIS X β€” Recon & Attack Path Intelligence System
554
+
555
+ ### What It Is
556
+ RAPIS X is an **adversarial cognitive security platform** β€” not a scanner.
557
+ It models how complex systems fail under trust collapse, state divergence, timing inconsistencies, and emergent relationships.
558
+
559
+ ### Core Cognitive Model
560
+ ```
561
+ System = Identity + Trust + State + Flow + Time + Relationships
562
+ Vulnerability = Collapse(SecurityAssumption)
563
+ Attack = propagate(Failure(Assumption))
564
+ ```
565
+
566
+ ### Inversion Thinking Principle
567
+ Instead of *"Where is the vulnerability?"* ask:
568
+ > *"What assumptions currently prevent compromise β€” and what if each one fails?"*
569
+
570
+ ### Six Cognitive Dimensions
571
+ | Dimension | Core Question |
572
+ |---|---|
573
+ | **Identity** | How is identity established? Can it become stale? Can authz diverge? |
574
+ | **Trust** | What trusts what? Can trust propagate? What if upstream validation fails? |
575
+ | **State** | Can services disagree about reality? What if cache is stale? |
576
+ | **Time** | What guarantees depend on timing? Can race conditions create temporary privilege? |
577
+ | **Flow** | Where does data originate? Can it reach unintended destinations? |
578
+ | **Relationships** | What hidden trust chains exist? What propagates recursively? |
579
+
580
+ ### Training Data
581
+ All generated training data teaches **cognitive security reasoning**:
582
+ - Structural vulnerability analysis
583
+ - Assumption collapse chains
584
+ - Inversion thinking examples
585
+ - Complexity β†’ simplicity reduction
586
+ - **Never**: payloads, exploit code, attack instructions
587
+
588
+ ### Ethical Constraints
589
+ - ❌ Never generates: payloads, exploit code, malware, attack instructions
590
+ - βœ… Only generates: structural analysis, cognitive reasoning, defensive insights
591
+
592
+ ### Setup
593
+ 1. Go to **Settings β†’ Secrets** in your HF Space
594
+ 2. Add `ANTHROPIC_API_KEY` = `sk-ant-...`
595
+ 3. Start analysing
596
+
597
+ Built with Claude Sonnet 4 Β· Gradio Β· HuggingFace Spaces
598
+ """)
599
+
600
+ if __name__ == "__main__":
601
+ demo.queue(max_size=5).launch(
602
+ server_name="0.0.0.0",
603
+ server_port=7860,
604
+ show_error=True,
605
+ share=False,
606
+ )
rapis-x/hf_space/engines/__init__.py ADDED
File without changes
rapis-x/hf_space/engines/claude_api.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ RAPIS X β€” Core Claude API Engine
3
+ Direct urllib calls β€” zero SDK dependency for HF Spaces compatibility.
4
+ """
5
+ from __future__ import annotations
6
+ import json, re, os, urllib.request, urllib.error
7
+ from typing import Generator
8
+
9
+
10
+ MODEL = "claude-sonnet-4-20250514"
11
+
12
+
13
+ def get_key() -> str:
14
+ k = os.environ.get("ANTHROPIC_API_KEY", "")
15
+ if not k:
16
+ raise RuntimeError("ANTHROPIC_API_KEY not set. Add it in HF Space Settings β†’ Secrets.")
17
+ return k
18
+
19
+
20
+ def call_claude(system: str, user: str, max_tokens: int = 4000) -> str:
21
+ """Single blocking call to Claude API."""
22
+ payload = json.dumps({
23
+ "model": MODEL,
24
+ "max_tokens": max_tokens,
25
+ "system": system,
26
+ "messages": [{"role": "user", "content": user}]
27
+ }).encode()
28
+ req = urllib.request.Request(
29
+ "https://api.anthropic.com/v1/messages",
30
+ data=payload,
31
+ headers={
32
+ "content-type": "application/json",
33
+ "anthropic-version": "2023-06-01",
34
+ "x-api-key": get_key(),
35
+ },
36
+ method="POST"
37
+ )
38
+ try:
39
+ with urllib.request.urlopen(req, timeout=120) as r:
40
+ body = json.loads(r.read())
41
+ return body["content"][0]["text"]
42
+ except urllib.error.HTTPError as e:
43
+ msg = e.read().decode()[:300]
44
+ raise RuntimeError(f"Claude API error {e.code}: {msg}")
45
+
46
+
47
+ def stream_claude(system: str, user: str, max_tokens: int = 4000) -> Generator[str, None, None]:
48
+ """Streaming call β€” yields text chunks."""
49
+ payload = json.dumps({
50
+ "model": MODEL,
51
+ "max_tokens": max_tokens,
52
+ "system": system,
53
+ "stream": True,
54
+ "messages": [{"role": "user", "content": user}]
55
+ }).encode()
56
+ req = urllib.request.Request(
57
+ "https://api.anthropic.com/v1/messages",
58
+ data=payload,
59
+ headers={
60
+ "content-type": "application/json",
61
+ "anthropic-version": "2023-06-01",
62
+ "x-api-key": get_key(),
63
+ },
64
+ method="POST"
65
+ )
66
+ with urllib.request.urlopen(req, timeout=180) as r:
67
+ for raw_line in r:
68
+ line = raw_line.decode().strip()
69
+ if not line.startswith("data:"):
70
+ continue
71
+ data_str = line[5:].strip()
72
+ if data_str == "[DONE]":
73
+ break
74
+ try:
75
+ evt = json.loads(data_str)
76
+ if evt.get("type") == "content_block_delta":
77
+ delta = evt.get("delta", {})
78
+ if delta.get("type") == "text_delta":
79
+ yield delta.get("text", "")
80
+ except Exception:
81
+ continue
82
+
83
+
84
+ def parse_json(raw: str) -> dict:
85
+ """Robustly extract JSON from model response."""
86
+ # Direct parse
87
+ try:
88
+ return json.loads(raw)
89
+ except Exception:
90
+ pass
91
+ # Markdown code block
92
+ m = re.search(r"```(?:json)?\s*([\s\S]+?)\s*```", raw)
93
+ if m:
94
+ try:
95
+ return json.loads(m.group(1))
96
+ except Exception:
97
+ pass
98
+ # First { ... } block
99
+ m2 = re.search(r"\{[\s\S]+\}", raw)
100
+ if m2:
101
+ try:
102
+ return json.loads(m2.group(0))
103
+ except Exception:
104
+ pass
105
+ return {}
rapis-x/hf_space/engines/inversion_engine.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ RAPIS X β€” Deep Inversion Thinking Engine
3
+ ═══════════════════════════════════════════════════════════════════
4
+ The core adversarial cognition model.
5
+
6
+ Inversion Principle:
7
+ Never ask: "Where is the vulnerability?"
8
+ Always ask: "What assumptions currently prevent compromise?"
9
+ Then: "What if each assumption fails β€” recursively?"
10
+
11
+ Cognitive Layers:
12
+ L1 β€” Surface Assumptions (what the system believes is true)
13
+ L2 β€” Dependency Chain (what supports those beliefs)
14
+ L3 β€” Collapse Cascade (how failure propagates)
15
+ L4 β€” Emergent Attack Paths (what becomes possible after collapse)
16
+ L5 β€” Recursive Depth (what new assumptions the attacker now relies on)
17
+ ═══════════════════════════════════════════════════════════════════
18
+ """
19
+ from __future__ import annotations
20
+ import json, uuid
21
+ from dataclasses import dataclass, field, asdict
22
+ from typing import Generator
23
+ from engines.claude_api import call_claude, stream_claude, parse_json
24
+
25
+
26
+ # ── Data Structures ────────────────────────────────────────────────────────────
27
+
28
+ @dataclass
29
+ class Assumption:
30
+ id: str
31
+ layer: int # 1-5
32
+ statement: str # "The system assumes X"
33
+ domain: str # identity|trust|state|time|flow|relationship
34
+ strength: str # strong|weak|implicit|unknown
35
+ dependencies: list = field(default_factory=list) # assumption IDs this depends on
36
+ collapse_trigger: str = "" # what causes this to fail
37
+ collapse_effect: str = "" # what happens when it fails
38
+ attack_surface: str = "" # what becomes attackable
39
+ confidence: float = 0.7
40
+
41
+ @dataclass
42
+ class InversionResult:
43
+ id: str = field(default_factory=lambda: str(uuid.uuid4()))
44
+ target: str = ""
45
+ assumptions: list = field(default_factory=list) # list[Assumption]
46
+ collapse_chains: list = field(default_factory=list) # ordered failure sequences
47
+ emergent_paths: list = field(default_factory=list) # what attacks emerge
48
+ recursive_insights: list = field(default_factory=list) # L5 recursive depth
49
+ complexity_summary: str = "" # complex β†’ simple explanation
50
+ simple_summary: str = "" # one-paragraph human-readable
51
+ risk_score: float = 0.0
52
+ cognitive_map: dict = field(default_factory=dict)
53
+
54
+ def to_dict(self):
55
+ return {
56
+ **asdict(self),
57
+ "assumptions": [asdict(a) for a in self.assumptions]
58
+ }
59
+
60
+
61
+ # ── Prompts ────────────────────────────────────────────────────────────────────
62
+
63
+ INVERSION_SYSTEM = """You are RAPIS X Deep Inversion Thinking Engine β€” the most advanced adversarial cognition model for security analysis.
64
+
65
+ ═══ INVERSION THINKING MODEL ═══
66
+
67
+ Core Axioms:
68
+ System = Identity + Trust + State + Flow + Time + Relationships
69
+ Vulnerability = Collapse(SecurityAssumption)
70
+ Attack = propagate(Failure(Assumption))
71
+
72
+ The Five Cognitive Layers:
73
+ L1 SURFACE β€” What does the system assume is currently true?
74
+ L2 DEPENDENCY β€” What hidden dependencies support each assumption?
75
+ L3 COLLAPSE β€” How does each assumption fail? What triggers it?
76
+ L4 EMERGENCE β€” What attack paths emerge from each collapse?
77
+ L5 RECURSION β€” What new assumptions does the attacker now rely on? Apply inversion again.
78
+
79
+ Six Assumption Domains:
80
+ IDENTITY β€” Who is who? Can identity become stale? Can authz diverge?
81
+ TRUST β€” What trusts what? Can trust be inherited? What if upstream fails?
82
+ STATE β€” Can services disagree about reality? What if state is stale?
83
+ TIME β€” What depends on timing? Race conditions? Retry abuse?
84
+ FLOW β€” Where does data travel? Can it reach unintended destinations?
85
+ RELATIONSHIP β€” What hidden chains exist? What propagates recursively?
86
+
87
+ Complexity β†’ Simplicity Rule:
88
+ After deep analysis, always reduce to plain English.
89
+ A non-technical person must understand the risk from the simple_summary.
90
+
91
+ ETHICAL CONSTRAINT: NEVER generate payloads, exploit code, malware, or attack instructions.
92
+ ONLY generate: assumption maps, collapse reasoning, emergent path analysis, defensive insights.
93
+
94
+ Respond ONLY with valid JSON β€” no markdown fences, no preamble:
95
+ {
96
+ "assumptions": [
97
+ {
98
+ "id": "a1",
99
+ "layer": 1,
100
+ "statement": "The system assumes...",
101
+ "domain": "trust",
102
+ "strength": "implicit",
103
+ "dependencies": ["a2", "a3"],
104
+ "collapse_trigger": "What causes this assumption to fail",
105
+ "collapse_effect": "What happens in the system when it fails",
106
+ "attack_surface": "What becomes attackable as a result",
107
+ "confidence": 0.85
108
+ }
109
+ ],
110
+ "collapse_chains": [
111
+ {
112
+ "chain_id": "c1",
113
+ "title": "Short name for this collapse chain",
114
+ "sequence": ["a1 fails β†’ a3 becomes invalid β†’ a5 exposed"],
115
+ "risk": "CRITICAL|HIGH|MEDIUM|LOW",
116
+ "domain": "trust"
117
+ }
118
+ ],
119
+ "emergent_paths": [
120
+ {
121
+ "path_id": "p1",
122
+ "title": "Attack path name",
123
+ "trigger_assumption": "a1",
124
+ "sequence": ["Step 1 (structural)", "Step 2", "Step 3"],
125
+ "category": "Privilege Escalation|IDOR|SSRF|Race Condition|Stale Authorization|Token Confusion|State Divergence|Trust Boundary Abuse",
126
+ "risk": "CRITICAL",
127
+ "inversion_depth": 3
128
+ }
129
+ ],
130
+ "recursive_insights": [
131
+ "Layer 5 recursive observation: after assumption A fails, the attacker now relies on assumption B which itself is weak because..."
132
+ ],
133
+ "complexity_summary": "Technical 2-paragraph summary of the full cognitive analysis",
134
+ "simple_summary": "Plain English 2-sentence summary a non-technical person can understand",
135
+ "risk_score": 8.5,
136
+ "cognitive_map": {
137
+ "total_assumptions": 8,
138
+ "critical_collapses": 2,
139
+ "weakest_domain": "trust",
140
+ "deepest_chain_length": 4
141
+ }
142
+ }"""
143
+
144
+
145
+ QUICK_INVERSION_SYSTEM = """You are RAPIS X Inversion Thinking Engine.
146
+
147
+ Given a specific security assumption, apply recursive inversion analysis.
148
+
149
+ Ask recursively:
150
+ 1. What currently prevents this assumption from failing?
151
+ 2. What happens to the system if it does fail?
152
+ 3. What new attack surface emerges?
153
+ 4. What new assumptions does the attacker now depend on?
154
+ 5. Apply inversion to THOSE assumptions too.
155
+
156
+ ETHICAL CONSTRAINT: No payloads. No exploit code. Structural reasoning only.
157
+
158
+ Respond in clear, structured markdown with sections:
159
+ ## Assumption Analysis
160
+ ## Collapse Trigger
161
+ ## Failure Propagation
162
+ ## Emergent Attack Surface
163
+ ## Recursive Layer (what if the new state is also inverted?)
164
+ ## Simplicity Summary (plain English, 2 sentences)
165
+ ## Defensive Countermeasures"""
166
+
167
+
168
+ # ── Engine ─────────────────────────────────────────────────────────────────────
169
+
170
+ class InversionEngine:
171
+ """
172
+ Deep recursive inversion thinking engine.
173
+ Models system security by mapping ALL assumptions and their collapse cascades.
174
+ """
175
+
176
+ def full_inversion(self, target: str, context: str = "", depth: int = 3) -> InversionResult:
177
+ """Full 5-layer inversion analysis."""
178
+ prompt = self._build_full_prompt(target, context, depth)
179
+ raw = call_claude(INVERSION_SYSTEM, prompt, max_tokens=5000)
180
+ data = parse_json(raw)
181
+ return self._build_result(target, data)
182
+
183
+ def stream_inversion(self, target: str, context: str = "", depth: int = 3) -> Generator[str, None, None]:
184
+ """Streaming inversion β€” yields markdown text as it's generated."""
185
+ prompt = self._build_full_prompt(target, context, depth)
186
+ yield "## πŸ”„ Running Deep Inversion Analysis...\n\n"
187
+ full = ""
188
+ for chunk in stream_claude(INVERSION_SYSTEM, prompt, max_tokens=5000):
189
+ full += chunk
190
+ yield chunk
191
+
192
+ def quick_inversion(self, assumption: str, context: str = "") -> Generator[str, None, None]:
193
+ """Stream a quick inversion on a single assumption statement."""
194
+ prompt = f"""Apply deep recursive inversion thinking to this specific security assumption:
195
+
196
+ Assumption: "{assumption}"
197
+
198
+ Context: {context if context else 'General web application / API system'}
199
+
200
+ Go through all 5 cognitive layers. Reduce final insight to plain English."""
201
+ yield f"## πŸ”„ Inverting: *{assumption[:80]}*\n\n"
202
+ for chunk in stream_claude(QUICK_INVERSION_SYSTEM, prompt, max_tokens=3000):
203
+ yield chunk
204
+
205
+ def invert_finding(self, finding: str, system_context: str = "") -> str:
206
+ """Invert a specific security finding to deepen understanding."""
207
+ prompt = f"""Security Finding: {finding}
208
+
209
+ System Context: {system_context}
210
+
211
+ Apply inversion thinking: instead of analysing this finding directly,
212
+ ask what assumptions its existence violates, trace the full dependency chain,
213
+ and reason about what the system must have believed was true for this to be exploitable."""
214
+ return call_claude(QUICK_INVERSION_SYSTEM, prompt, max_tokens=2000)
215
+
216
+ def _build_full_prompt(self, target: str, context: str, depth: int) -> str:
217
+ depth_map = {
218
+ 1: "surface-level β€” identify obvious assumptions only",
219
+ 2: "standard β€” map all L1-L2 assumptions and their immediate collapse effects",
220
+ 3: "deep β€” full L1-L4 analysis with collapse chains and emergent paths",
221
+ 4: "expert β€” all 5 layers including recursive L5 insights",
222
+ 5: "elite β€” maximum recursion, map every assumption chain, every emergent surface, every recursive dependency"
223
+ }
224
+ return f"""Target System: {target}
225
+
226
+ Additional Context:
227
+ {context if context else "No additional context provided. Infer from target description."}
228
+
229
+ Analysis Depth: {depth}/5 β€” {depth_map.get(depth, depth_map[3])}
230
+
231
+ Apply the complete 5-layer inversion model. Map every security assumption.
232
+ For each assumption: identify what currently keeps it stable, what collapses it,
233
+ how failure propagates, and what new attack surface emerges.
234
+
235
+ At layer 5: apply inversion recursively to the attacker's new position.
236
+
237
+ Reduce the final output to a simple_summary any non-technical person can understand.
238
+ Also provide a complexity_summary for the security professional."""
239
+
240
+ def _build_result(self, target: str, data: dict) -> InversionResult:
241
+ assumptions = []
242
+ for a in data.get("assumptions", []):
243
+ try:
244
+ assumptions.append(Assumption(
245
+ id=a.get("id", str(uuid.uuid4())[:8]),
246
+ layer=int(a.get("layer", 1)),
247
+ statement=a.get("statement", ""),
248
+ domain=a.get("domain", "trust"),
249
+ strength=a.get("strength", "implicit"),
250
+ dependencies=a.get("dependencies", []),
251
+ collapse_trigger=a.get("collapse_trigger", ""),
252
+ collapse_effect=a.get("collapse_effect", ""),
253
+ attack_surface=a.get("attack_surface", ""),
254
+ confidence=float(a.get("confidence", 0.7)),
255
+ ))
256
+ except Exception:
257
+ pass
258
+
259
+ return InversionResult(
260
+ target=target,
261
+ assumptions=assumptions,
262
+ collapse_chains=data.get("collapse_chains", []),
263
+ emergent_paths=data.get("emergent_paths", []),
264
+ recursive_insights=data.get("recursive_insights", []),
265
+ complexity_summary=data.get("complexity_summary", ""),
266
+ simple_summary=data.get("simple_summary", ""),
267
+ risk_score=float(data.get("risk_score", 0.0)),
268
+ cognitive_map=data.get("cognitive_map", {}),
269
+ )
rapis-x/hf_space/engines/pipeline.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ RAPIS X β€” Full Analysis Pipeline
3
+ Orchestrates all engines into a unified adversarial cognition pipeline.
4
+ """
5
+ from __future__ import annotations
6
+ import sys, os
7
+ sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
8
+
9
+ import uuid, json
10
+ from dataclasses import dataclass, field, asdict
11
+ from typing import Generator
12
+ from engines.claude_api import call_claude, stream_claude, parse_json, get_key
13
+
14
+
15
+ # ── Inline engine prompts (self-contained for HF Spaces) ──────────────────────
16
+
17
+ RECON_SYSTEM = """You are RAPIS X Reconnaissance Intelligence Engine.
18
+
19
+ System = Identity + Trust + State + Flow + Time + Relationships
20
+ Vulnerability = Collapse(SecurityAssumption)
21
+ Attack = propagate(Failure(Assumption))
22
+
23
+ Apply inversion thinking: ask what assumptions currently prevent compromise, then reason about failure.
24
+
25
+ ETHICAL CONSTRAINT: No payloads, no exploit code. Structural analysis only.
26
+
27
+ Respond ONLY with valid JSON β€” no markdown, no preamble:
28
+ {
29
+ "assets": [{"name":"...","asset_type":"...","exposed":true,"technology":"...","risk_notes":"..."}],
30
+ "technology_fingerprint": {"frameworks":[],"auth_systems":[],"caching_layers":[],"databases":[],"cloud_providers":[],"third_party":[]},
31
+ "attack_surface_summary": "...",
32
+ "trust_boundaries": [{"name":"...","from_zone":"...","to_zone":"...","weakness":"...","risk":"HIGH"}],
33
+ "high_risk_components": [],
34
+ "initial_hypotheses": ["Possible X due to Y structural weakness."]
35
+ }"""
36
+
37
+ GRAPH_SYSTEM = """You are RAPIS X Graph Intelligence Engine. Build a trust graph.
38
+
39
+ Node types: User,API,Service,Database,Token,Session,Role,Cache,Worker,Queue,External,Admin,Gateway,Auth
40
+ Edge types: TRUSTS,CALLS,AUTHENTICATES,READS,WRITES,DEPENDS_ON,INHERITS,FORWARDS,ROUTES_TO
41
+ Trust: strong|weak|implicit|none Risk score: 0.0–10.0
42
+
43
+ Respond ONLY with valid JSON:
44
+ {
45
+ "nodes":[{"id":"n1","label":"...","node_type":"Gateway","risk_score":7.5,"exposed":true,"internal":false}],
46
+ "edges":[{"id":"e1","source":"n1","target":"n2","edge_type":"ROUTES_TO","trust_strength":"implicit","validated":false}],
47
+ "graph_summary":"..."
48
+ }"""
49
+
50
+ ATTACK_SYSTEM = """You are RAPIS X Attack Path Engine.
51
+
52
+ Traversal: Assumption Failure β†’ Trust Collapse β†’ State Divergence β†’ Privilege Expansion β†’ Attack Path
53
+
54
+ Detect: privilege escalation, IDOR, SSRF, broken auth, stale authz, race conditions, trust abuse.
55
+ Apply inversion on every trust edge.
56
+
57
+ ETHICAL CONSTRAINT: No payloads. No instructions. Structural path reasoning only.
58
+
59
+ Respond ONLY with valid JSON:
60
+ {"attack_paths":[{"id":"ap1","path_nodes":["n1","n2"],"path_steps":[{"node_id":"n1","node_label":"...","action":"...","assumption_exploited":"...","trust_collapsed":"..."}],"risk":"CRITICAL","category":"Trust Boundary Abuse","reasoning":"...","assumption_chain":[],"inversion_analysis":"...","confidence":0.85}]}"""
61
+
62
+ HYPOTHESIS_SYSTEM = """You are RAPIS X Hypothesis Engine.
63
+
64
+ ETHICAL RULE: NEVER generate payloads, exploit code, or instructions. ONLY structural reasoning.
65
+
66
+ Generate vulnerability hypotheses. For each: violated assumption, structural reasoning, propagation chain, inversion insight, recommendations.
67
+
68
+ Respond ONLY with valid JSON:
69
+ {"hypotheses":[{"id":"h1","title":"...","category":"IDOR","risk":"HIGH","affected_components":[],"assumption_violated":"...","systemic_reasoning":"...","propagation_chain":"...","inversion_insight":"...","recommendations":[],"confidence":0.75}]}"""
70
+
71
+ COGNITION_SYSTEM = """You are RAPIS X Cognition Engine.
72
+
73
+ Apply 6-dimensional analysis: IDENTITY, TRUST, STATE, TIME, FLOW, RELATIONSHIPS.
74
+ Ask adversarial questions recursively. Apply inversion thinking at every layer.
75
+
76
+ Respond ONLY with valid JSON:
77
+ {"identity_analysis":{},"trust_analysis":{},"state_analysis":{},"time_analysis":{},"flow_analysis":{},"relationship_analysis":{},"inversion_insights":[],"adversarial_questions":[],"systemic_risk_summary":"..."}"""
78
+
79
+
80
+ class FullPipeline:
81
+ """Orchestrates the complete RAPIS X analysis pipeline."""
82
+
83
+ def run_stream(self, target: str, context: str = "", depth: int = 3) -> Generator[tuple, None, None]:
84
+ """
85
+ Stream full pipeline. Yields (stage, message, progress, data) tuples.
86
+ """
87
+ key = get_key()
88
+
89
+ # ── Stage 1: Recon ───────────────────────────────────────────────────
90
+ yield ("recon", "πŸ” Initiating reconnaissance scan...", 5, {})
91
+ recon = self._run_recon(target, context, depth, key)
92
+ yield ("recon", f"βœ… Recon β€” {len(recon.get('assets',[]))} assets Β· {len(recon.get('trust_boundaries',[]))} boundaries", 28, recon)
93
+
94
+ # ── Stage 2: Inversion ───────────────────────────────────────────────
95
+ yield ("inversion", "πŸ”„ Applying inversion thinking model...", 30, {})
96
+ inversion = self._run_inversion(target, context, recon, depth, key)
97
+ yield ("inversion", f"βœ… Inversion β€” {len(inversion.get('assumptions',[]))} assumptions mapped", 48, inversion)
98
+
99
+ # ── Stage 3: Graph ───────────────────────────────────────────────────
100
+ yield ("graph", "πŸ•ΈοΈ Building trust graph...", 50, {})
101
+ graph = self._run_graph(target, recon, key)
102
+ yield ("graph", f"βœ… Graph β€” {len(graph.get('nodes',[]))} nodes Β· {len(graph.get('edges',[]))} edges", 62, graph)
103
+
104
+ # ── Stage 4: Attack Paths ────────────────────────────────────────────
105
+ yield ("attack_paths", "🚨 Traversing attack paths...", 64, {})
106
+ paths = self._run_paths(target, graph, recon, inversion, key)
107
+ crit = sum(1 for p in paths if p.get("risk") == "CRITICAL")
108
+ high = sum(1 for p in paths if p.get("risk") == "HIGH")
109
+ yield ("attack_paths", f"βœ… {len(paths)} paths β€” {crit} CRITICAL Β· {high} HIGH", 76, {"paths": paths})
110
+
111
+ # ── Stage 5: Hypotheses ──────────────────────────────────────────────
112
+ yield ("hypotheses", "πŸ’‘ Generating hypotheses...", 78, {})
113
+ hypos = self._run_hypotheses(target, graph, paths, recon, inversion, key)
114
+ yield ("hypotheses", f"βœ… {len(hypos)} hypotheses", 87, {"hypotheses": hypos})
115
+
116
+ # ── Stage 6: Cognition ───────────────────────────────────────────────
117
+ yield ("cognition", "🧠 Running cognitive analysis...", 89, {})
118
+ cogn = self._run_cognition(target, graph, recon, inversion, key)
119
+ yield ("cognition", f"βœ… {len(cogn.get('inversion_insights',[]))} inversion insights", 96, cogn)
120
+
121
+ # ── Final ────────────────────────────────────────────────────────────
122
+ risks = [p.get("risk","") for p in paths] + [h.get("risk","") for h in hypos]
123
+ overall = next((r for r in ["CRITICAL","HIGH","MEDIUM","LOW"] if r in risks), "INFO")
124
+ analysis = {
125
+ "session_id": str(uuid.uuid4()),
126
+ "target": target,
127
+ "overall_risk": overall,
128
+ "executive_summary": cogn.get("systemic_risk_summary",""),
129
+ "recon_report": recon,
130
+ "system_graph": graph,
131
+ "inversion_analysis": inversion,
132
+ "attack_paths": paths,
133
+ "hypotheses": hypos,
134
+ "cognition_analysis": cogn,
135
+ }
136
+ yield ("complete", "🎯 Analysis Complete", 100, analysis)
137
+
138
+ def _run_recon(self, target, context, depth, key):
139
+ depth_map = {1:"Quick",2:"Standard",3:"Deep",4:"Expert",5:"Elite adversarial cognition"}
140
+ prompt = f"Target: {target}\nContext: {context or 'None provided'}\nDepth {depth}/5 β€” {depth_map.get(depth,'Deep')}\n\nApply inversion thinking. Map all trust assumptions. Return complete Recon Intelligence Report."
141
+ os.environ["ANTHROPIC_API_KEY"] = os.environ.get("ANTHROPIC_API_KEY", key)
142
+ return parse_json(call_claude(RECON_SYSTEM, prompt, 3500))
143
+
144
+ def _run_inversion(self, target, context, recon, depth, key):
145
+ from engines.inversion_engine import InversionEngine, INVERSION_SYSTEM
146
+ context_str = context or ""
147
+ if recon:
148
+ context_str += f"\nAssets: {[a.get('name','') for a in recon.get('assets',[])]}"
149
+ context_str += f"\nTrust weaknesses: {[b.get('weakness','') for b in recon.get('trust_boundaries',[])]}"
150
+ return parse_json(call_claude(INVERSION_SYSTEM,
151
+ f"Target: {target}\nContext: {context_str}\nDepth: {depth}/5\n\nApply full 5-layer inversion model.",
152
+ 4500))
153
+
154
+ def _run_graph(self, target, recon, key):
155
+ prompt = f"Target: {target}\nAssets: {recon.get('assets',[])}\nTech: {recon.get('technology_fingerprint',{})}\nBoundaries: {recon.get('trust_boundaries',[])}\nBuild complete trust graph."
156
+ return parse_json(call_claude(GRAPH_SYSTEM, prompt, 3500))
157
+
158
+ def _run_paths(self, target, graph, recon, inversion, key):
159
+ nodes_str = "\n".join(f"[{n.get('id')}] {n.get('label')} ({n.get('node_type')}) risk={n.get('risk_score')} exposed={n.get('exposed')}"
160
+ for n in graph.get("nodes",[]))
161
+ edges_str = "\n".join(f"{e.get('source')} --[{e.get('edge_type')}:{e.get('trust_strength')}]--> {e.get('target')}"
162
+ for e in graph.get("edges",[]))
163
+ inv_str = "\n".join(inversion.get("recursive_insights",[])[:3])
164
+ prompt = f"Target: {target}\nGraph Summary: {graph.get('graph_summary','')}\nNodes:\n{nodes_str}\nEdges:\n{edges_str}\nInversion Insights:\n{inv_str}\n\nTraverse graph. Find all attack paths. Apply inversion on every trust edge."
165
+ data = parse_json(call_claude(ATTACK_SYSTEM, prompt, 4000))
166
+ return data.get("attack_paths", [])
167
+
168
+ def _run_hypotheses(self, target, graph, paths, recon, inversion, key):
169
+ high_risk = [n for n in graph.get("nodes",[]) if n.get("risk_score",0) >= 7]
170
+ weak_edges = [e for e in graph.get("edges",[]) if e.get("trust_strength") in ("weak","implicit","none")]
171
+ prompt = (f"Target: {target}\nHigh-Risk Nodes: {[n.get('label','') for n in high_risk]}\n"
172
+ f"Weak Edges: {[(e.get('source'),e.get('edge_type'),e.get('target')) for e in weak_edges]}\n"
173
+ f"Attack Paths: {len(paths)} identified\n"
174
+ f"Inversion Insights: {inversion.get('recursive_insights',[][:3])}\n"
175
+ f"Generate detailed hypotheses. No payloads.")
176
+ data = parse_json(call_claude(HYPOTHESIS_SYSTEM, prompt, 4000))
177
+ return data.get("hypotheses", [])
178
+
179
+ def _run_cognition(self, target, graph, recon, inversion, key):
180
+ prompt = (f"Target: {target}\nArchitecture: {graph.get('graph_summary','')}\n"
181
+ f"Trust Boundaries: {[(b.get('name',''),b.get('weakness','')) for b in recon.get('trust_boundaries',[])]}\n"
182
+ f"Auth Systems: {recon.get('technology_fingerprint',{}).get('auth_systems',[])}\n"
183
+ f"Inversion Assumptions: {[a.get('statement','') for a in inversion.get('assumptions',[])][:5]}\n"
184
+ "Apply full 6-dimensional cognitive analysis with recursive adversarial questioning.")
185
+ return parse_json(call_claude(COGNITION_SYSTEM, prompt, 4000))
rapis-x/hf_space/engines/reading_engine.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ RAPIS X β€” Reading Engine
3
+ ═══════════════════════════════════════════════════════════════
4
+ Ingests any target: raw text, URL, pasted docs, API specs, code snippets.
5
+ Extracts security-relevant architecture, trust flows, and components.
6
+ Feeds structured output into all other engines.
7
+ ═══════════════════════════════════════════════════════════════
8
+ """
9
+ from __future__ import annotations
10
+ import re, json, urllib.request, urllib.error
11
+ from dataclasses import dataclass, field, asdict
12
+ from typing import Generator
13
+ from engines.claude_api import call_claude, stream_claude, parse_json
14
+
15
+
16
+ # ── Data ──────────────────────────────────────────────────────────────────────
17
+
18
+ @dataclass
19
+ class ReadingResult:
20
+ source: str = ""
21
+ source_type: str = "text" # text|url|code|spec|architecture
22
+ raw_content: str = ""
23
+ extracted_components: list = field(default_factory=list)
24
+ trust_flows: list = field(default_factory=list)
25
+ technology_stack: list = field(default_factory=list)
26
+ endpoints: list = field(default_factory=list)
27
+ auth_mechanisms: list = field(default_factory=list)
28
+ data_flows: list = field(default_factory=list)
29
+ security_controls: list = field(default_factory=list)
30
+ attack_surface_notes: list = field(default_factory=list)
31
+ structured_summary: str = ""
32
+ cognitive_context: str = "" # formatted for inversion engine input
33
+
34
+ def to_dict(self):
35
+ return asdict(self)
36
+
37
+ def to_context_string(self) -> str:
38
+ """Format for feeding into other engines."""
39
+ parts = [f"Source: {self.source}\n"]
40
+ if self.extracted_components:
41
+ parts.append(f"Components: {', '.join(self.extracted_components)}")
42
+ if self.technology_stack:
43
+ parts.append(f"Tech Stack: {', '.join(self.technology_stack)}")
44
+ if self.trust_flows:
45
+ parts.append(f"Trust Flows: {'; '.join(self.trust_flows)}")
46
+ if self.auth_mechanisms:
47
+ parts.append(f"Auth: {', '.join(self.auth_mechanisms)}")
48
+ if self.endpoints:
49
+ parts.append(f"Endpoints: {', '.join(self.endpoints[:10])}")
50
+ if self.attack_surface_notes:
51
+ parts.append(f"Surface Notes: {'; '.join(self.attack_surface_notes)}")
52
+ return "\n".join(parts)
53
+
54
+
55
+ # ── Prompts ───────────────────────────────────────────────────────────────────
56
+
57
+ READING_SYSTEM = """You are RAPIS X Reading Intelligence Engine.
58
+
59
+ Your role: Read any input (architecture description, code snippet, API spec, URL content, documentation) and extract ALL security-relevant structural information.
60
+
61
+ Extract with security analyst precision:
62
+ - Every component and service
63
+ - Every trust relationship and data flow
64
+ - Authentication and authorisation mechanisms
65
+ - External dependencies and third-party integrations
66
+ - Exposed endpoints and API surfaces
67
+ - Implicit assumptions baked into the architecture
68
+ - Potential weak points in the trust model
69
+
70
+ Also identify what is NOT stated β€” missing security controls are as important as stated ones.
71
+
72
+ Respond ONLY with valid JSON β€” no markdown, no preamble:
73
+ {
74
+ "source_type": "text|url|code|spec|architecture",
75
+ "extracted_components": ["Component 1", "Component 2"],
76
+ "trust_flows": ["ServiceA β†’ ServiceB (implicit trust)", "User β†’ API (JWT)"],
77
+ "technology_stack": ["Python", "Redis", "JWT", "PostgreSQL"],
78
+ "endpoints": ["/api/users", "/admin", "/api/payments"],
79
+ "auth_mechanisms": ["JWT bearer tokens", "Session cookies"],
80
+ "data_flows": ["User input β†’ API β†’ Database", "Payment β†’ Queue β†’ Worker"],
81
+ "security_controls": ["Rate limiting on /api", "HTTPS enforced"],
82
+ "attack_surface_notes": [
83
+ "Admin endpoint exposed without documented auth",
84
+ "User-controlled input passed to internal HTTP client"
85
+ ],
86
+ "structured_summary": "2-paragraph technical summary of what was read",
87
+ "cognitive_context": "Formatted context string optimised for adversarial reasoning"
88
+ }"""
89
+
90
+ DEEP_READ_SYSTEM = """You are RAPIS X Deep Reading Engine.
91
+
92
+ Read the provided content as a security researcher preparing for a bug bounty or security audit.
93
+
94
+ Extract not just what is written β€” but what is implied:
95
+ - What assumptions does the author make about security?
96
+ - What trust relationships are implicit but never stated?
97
+ - What controls are mentioned by omission (not present)?
98
+ - What architectural patterns create inherent risk?
99
+
100
+ Think like an adversary reading this for the first time.
101
+ What stands out as the highest-value targets?
102
+
103
+ Format response as structured markdown with clear headers."""
104
+
105
+
106
+ # ── Engine ────────────────────────────────────────────────────────────────────
107
+
108
+ class ReadingEngine:
109
+ """
110
+ Reads and structurally parses any target input.
111
+ Converts raw complexity into clean, engine-ready intelligence.
112
+ """
113
+
114
+ def read(self, content: str, source: str = "user input") -> ReadingResult:
115
+ """Parse any text input into structured security intelligence."""
116
+ source_type = self._detect_type(content)
117
+ # If URL, try to fetch
118
+ raw = content
119
+ if source_type == "url":
120
+ raw = self._fetch_url(content)
121
+ if not raw:
122
+ raw = f"[Could not fetch URL: {content}]\nURL: {content}"
123
+
124
+ prompt = self._build_prompt(raw, source_type)
125
+ result_text = call_claude(READING_SYSTEM, prompt, max_tokens=4000)
126
+ data = parse_json(result_text)
127
+ return self._build_result(source, source_type, raw, data)
128
+
129
+ def deep_read_stream(self, content: str) -> Generator[str, None, None]:
130
+ """Stream a deep adversarial reading of any content."""
131
+ source_type = self._detect_type(content)
132
+ raw = content
133
+ if source_type == "url":
134
+ raw = self._fetch_url(content) or content
135
+
136
+ prompt = f"""Content Type: {source_type}
137
+
138
+ Content to analyse:
139
+ {raw[:8000]}
140
+
141
+ Read this as a security researcher. Extract every security-relevant detail.
142
+ Think adversarially β€” what would an attacker notice first?"""
143
+
144
+ yield f"## πŸ“– Deep Reading: {source_type.upper()}\n\n"
145
+ for chunk in stream_claude(DEEP_READ_SYSTEM, prompt, max_tokens=4000):
146
+ yield chunk
147
+
148
+ def _detect_type(self, content: str) -> str:
149
+ c = content.strip()
150
+ if re.match(r'^https?://', c):
151
+ return "url"
152
+ if any(kw in c.lower() for kw in ['def ', 'function ', 'class ', 'import ', 'const ', 'async ']):
153
+ return "code"
154
+ if any(kw in c.lower() for kw in ['openapi', 'swagger', 'paths:', '\"paths\"', 'endpoints']):
155
+ return "spec"
156
+ if any(kw in c.lower() for kw in ['architecture', 'microservice', 'load balancer', 'cluster', 'vpc']):
157
+ return "architecture"
158
+ return "text"
159
+
160
+ def _fetch_url(self, url: str) -> str | None:
161
+ """Fetch URL content for analysis."""
162
+ try:
163
+ req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0 (Security Researcher)"})
164
+ with urllib.request.urlopen(req, timeout=15) as r:
165
+ raw = r.read().decode("utf-8", errors="ignore")
166
+ # Basic HTML strip
167
+ raw = re.sub(r'<script[^>]*>[\s\S]*?</script>', '', raw, flags=re.IGNORECASE)
168
+ raw = re.sub(r'<style[^>]*>[\s\S]*?</style>', '', raw, flags=re.IGNORECASE)
169
+ raw = re.sub(r'<[^>]+>', ' ', raw)
170
+ raw = re.sub(r'\s+', ' ', raw).strip()
171
+ return raw[:8000]
172
+ except Exception:
173
+ return None
174
+
175
+ def _build_prompt(self, content: str, source_type: str) -> str:
176
+ return f"""Content Type: {source_type}
177
+
178
+ Content:
179
+ {content[:6000]}
180
+
181
+ Extract all security-relevant structure. Pay special attention to:
182
+ - Trust relationships between components
183
+ - Authentication and authorisation patterns
184
+ - User-controlled inputs that reach sensitive operations
185
+ - Missing or weak security controls
186
+ - Implicit assumptions about security"""
187
+
188
+ def _build_result(self, source: str, source_type: str, raw: str, data: dict) -> ReadingResult:
189
+ return ReadingResult(
190
+ source=source,
191
+ source_type=data.get("source_type", source_type),
192
+ raw_content=raw[:2000],
193
+ extracted_components=data.get("extracted_components", []),
194
+ trust_flows=data.get("trust_flows", []),
195
+ technology_stack=data.get("technology_stack", []),
196
+ endpoints=data.get("endpoints", []),
197
+ auth_mechanisms=data.get("auth_mechanisms", []),
198
+ data_flows=data.get("data_flows", []),
199
+ security_controls=data.get("security_controls", []),
200
+ attack_surface_notes=data.get("attack_surface_notes", []),
201
+ structured_summary=data.get("structured_summary", ""),
202
+ cognitive_context=data.get("cognitive_context", ""),
203
+ )
rapis-x/hf_space/memory/__init__.py ADDED
File without changes
rapis-x/hf_space/memory/memory_engine.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ RAPIS X β€” Memory Engine
3
+ ═══════════════════════════════════════════════════════════════
4
+ Persistent memory for all analyses, findings, and training data.
5
+ Stores to local JSON (HF Spaces persistent disk) and optionally
6
+ pushes to HuggingFace Dataset Hub for training.
7
+
8
+ Memory Types:
9
+ ANALYSIS β€” full pipeline results
10
+ FINDING β€” individual security findings
11
+ INVERSION β€” inversion thinking results
12
+ READING β€” reading engine results
13
+ TRAINING β€” generated training examples
14
+ ═══════════════════════════════════════════════════════════════
15
+ """
16
+ from __future__ import annotations
17
+ import json, os, uuid, hashlib
18
+ from datetime import datetime, timezone
19
+ from dataclasses import dataclass, field, asdict
20
+ from pathlib import Path
21
+ from typing import Literal
22
+
23
+
24
+ MEMORY_FILE = os.environ.get("MEMORY_PATH", "/tmp/rapis_x_memory.json")
25
+ MemoryType = Literal["analysis", "finding", "inversion", "reading", "training", "hypothesis"]
26
+
27
+
28
+ @dataclass
29
+ class MemoryRecord:
30
+ id: str = field(default_factory=lambda: str(uuid.uuid4()))
31
+ memory_type: str = "analysis"
32
+ target: str = ""
33
+ title: str = ""
34
+ content: dict = field(default_factory=dict)
35
+ tags: list = field(default_factory=list)
36
+ risk_level: str = "MEDIUM"
37
+ created_at: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
38
+ session_id: str = ""
39
+ source_hash: str = ""
40
+
41
+ def to_dict(self):
42
+ return asdict(self)
43
+
44
+
45
+ class MemoryEngine:
46
+ """
47
+ Persistent memory store for all RAPIS X analyses.
48
+ - Saves to local JSON file (survives HF Space restarts with persistent storage)
49
+ - Can export to HuggingFace Dataset format for training
50
+ - Supports search, filtering, and retrieval
51
+ """
52
+
53
+ def __init__(self, memory_path: str = MEMORY_FILE):
54
+ self.path = Path(memory_path)
55
+ self._records: list[MemoryRecord] = []
56
+ self._load()
57
+
58
+ # ── Storage ────────────────────────────────────────────────────────────────
59
+
60
+ def _load(self):
61
+ try:
62
+ if self.path.exists():
63
+ raw = json.loads(self.path.read_text())
64
+ self._records = [MemoryRecord(**r) for r in raw]
65
+ except Exception:
66
+ self._records = []
67
+
68
+ def _save(self):
69
+ try:
70
+ self.path.parent.mkdir(parents=True, exist_ok=True)
71
+ self.path.write_text(json.dumps([r.to_dict() for r in self._records], indent=2))
72
+ except Exception:
73
+ pass
74
+
75
+ # ── Write ──────────────────────────────────────────────────────────────────
76
+
77
+ def store(
78
+ self,
79
+ memory_type: MemoryType,
80
+ target: str,
81
+ title: str,
82
+ content: dict,
83
+ tags: list = None,
84
+ risk_level: str = "MEDIUM",
85
+ session_id: str = "",
86
+ ) -> MemoryRecord:
87
+ """Store any analysis result."""
88
+ src_hash = hashlib.md5(f"{target}{title}".encode()).hexdigest()[:8]
89
+ record = MemoryRecord(
90
+ memory_type=memory_type,
91
+ target=target,
92
+ title=title,
93
+ content=content,
94
+ tags=tags or [],
95
+ risk_level=risk_level,
96
+ session_id=session_id or str(uuid.uuid4())[:8],
97
+ source_hash=src_hash,
98
+ )
99
+ self._records.append(record)
100
+ self._save()
101
+ return record
102
+
103
+ def store_analysis(self, target: str, analysis: dict, session_id: str = "") -> MemoryRecord:
104
+ return self.store("analysis", target,
105
+ f"Full Analysis: {target[:60]}",
106
+ analysis,
107
+ tags=["full-pipeline"],
108
+ risk_level=analysis.get("overall_risk", "MEDIUM"),
109
+ session_id=session_id)
110
+
111
+ def store_inversion(self, target: str, result: dict, session_id: str = "") -> MemoryRecord:
112
+ return self.store("inversion", target,
113
+ f"Inversion: {target[:60]}",
114
+ result,
115
+ tags=["inversion-thinking"],
116
+ risk_level=self._score_to_risk(result.get("risk_score", 0)),
117
+ session_id=session_id)
118
+
119
+ def store_finding(self, target: str, finding: str, category: str,
120
+ risk: str, details: dict) -> MemoryRecord:
121
+ return self.store("finding", target,
122
+ finding[:80],
123
+ {"finding": finding, "category": category, "details": details},
124
+ tags=["finding", category.lower().replace(" ", "-")],
125
+ risk_level=risk)
126
+
127
+ def store_reading(self, source: str, reading: dict) -> MemoryRecord:
128
+ return self.store("reading", source,
129
+ f"Reading: {source[:60]}",
130
+ reading,
131
+ tags=["reading", reading.get("source_type", "text")])
132
+
133
+ # ── Read ───────────────────────────────────────────────────────────────────
134
+
135
+ def get_all(self, memory_type: str = None) -> list[MemoryRecord]:
136
+ if memory_type:
137
+ return [r for r in self._records if r.memory_type == memory_type]
138
+ return list(self._records)
139
+
140
+ def get_by_target(self, target: str) -> list[MemoryRecord]:
141
+ t = target.lower()
142
+ return [r for r in self._records if t in r.target.lower()]
143
+
144
+ def get_by_risk(self, risk: str) -> list[MemoryRecord]:
145
+ return [r for r in self._records if r.risk_level == risk]
146
+
147
+ def get_recent(self, n: int = 10) -> list[MemoryRecord]:
148
+ return sorted(self._records, key=lambda r: r.created_at, reverse=True)[:n]
149
+
150
+ def search(self, query: str) -> list[MemoryRecord]:
151
+ q = query.lower()
152
+ results = []
153
+ for r in self._records:
154
+ if (q in r.target.lower() or q in r.title.lower() or
155
+ q in json.dumps(r.content).lower() or
156
+ any(q in tag for tag in r.tags)):
157
+ results.append(r)
158
+ return results
159
+
160
+ def stats(self) -> dict:
161
+ total = len(self._records)
162
+ by_type = {}
163
+ by_risk = {"CRITICAL": 0, "HIGH": 0, "MEDIUM": 0, "LOW": 0, "INFO": 0}
164
+ for r in self._records:
165
+ by_type[r.memory_type] = by_type.get(r.memory_type, 0) + 1
166
+ if r.risk_level in by_risk:
167
+ by_risk[r.risk_level] += 1
168
+ return {
169
+ "total": total,
170
+ "by_type": by_type,
171
+ "by_risk": by_risk,
172
+ "targets": list(set(r.target for r in self._records)),
173
+ "training_ready": by_type.get("training", 0),
174
+ }
175
+
176
+ def clear(self, memory_type: str = None):
177
+ if memory_type:
178
+ self._records = [r for r in self._records if r.memory_type != memory_type]
179
+ else:
180
+ self._records = []
181
+ self._save()
182
+
183
+ def delete(self, record_id: str) -> bool:
184
+ before = len(self._records)
185
+ self._records = [r for r in self._records if r.id != record_id]
186
+ self._save()
187
+ return len(self._records) < before
188
+
189
+ # ── Training Export ────────────────────────────────────────────────────────
190
+
191
+ def export_training_jsonl(self) -> str:
192
+ """
193
+ Export memory as JSONL in instruction-tuning format.
194
+ Compatible with HuggingFace datasets and fine-tuning pipelines.
195
+ """
196
+ lines = []
197
+ for r in self._records:
198
+ if r.memory_type == "training":
199
+ lines.append(json.dumps(r.content))
200
+ continue
201
+ # Convert other types to training format
202
+ entry = self._record_to_training(r)
203
+ if entry:
204
+ lines.append(json.dumps(entry))
205
+ return "\n".join(lines)
206
+
207
+ def export_hf_dataset_dict(self) -> list[dict]:
208
+ """Export as list of dicts for HuggingFace Dataset creation."""
209
+ result = []
210
+ for r in self._records:
211
+ entry = self._record_to_training(r)
212
+ if entry:
213
+ result.append(entry)
214
+ return result
215
+
216
+ def _record_to_training(self, r: MemoryRecord) -> dict | None:
217
+ """Convert a memory record to instruction-tuning training format."""
218
+ try:
219
+ if r.memory_type == "analysis":
220
+ content = r.content
221
+ return {
222
+ "instruction": f"Perform a full adversarial security analysis of: {r.target}",
223
+ "input": "",
224
+ "output": self._format_analysis_output(content),
225
+ "metadata": {"type": "analysis", "risk": r.risk_level, "target": r.target}
226
+ }
227
+ elif r.memory_type == "inversion":
228
+ content = r.content
229
+ return {
230
+ "instruction": f"Apply inversion thinking to identify security assumption failures in: {r.target}",
231
+ "input": content.get("complexity_summary", ""),
232
+ "output": content.get("simple_summary", "") + "\n\n" + "\n".join(content.get("recursive_insights", [])),
233
+ "metadata": {"type": "inversion", "risk_score": content.get("risk_score", 0)}
234
+ }
235
+ elif r.memory_type == "finding":
236
+ content = r.content
237
+ return {
238
+ "instruction": f"Analyse this security finding using adversarial cognition: {content.get('finding','')}",
239
+ "input": f"Target: {r.target}\nCategory: {content.get('category','')}",
240
+ "output": json.dumps(content.get("details", {}), indent=2),
241
+ "metadata": {"type": "finding", "risk": r.risk_level, "category": content.get("category","")}
242
+ }
243
+ except Exception:
244
+ pass
245
+ return None
246
+
247
+ def _format_analysis_output(self, content: dict) -> str:
248
+ parts = []
249
+ if content.get("executive_summary"):
250
+ parts.append(f"## Summary\n{content['executive_summary']}")
251
+ if content.get("attack_paths"):
252
+ paths = content["attack_paths"]
253
+ parts.append(f"## Attack Paths ({len(paths)})")
254
+ for p in paths[:3]:
255
+ parts.append(f"- [{p.get('risk','?')}] {p.get('category','')}: {p.get('reasoning','')[:200]}")
256
+ if content.get("hypotheses"):
257
+ hypos = content["hypotheses"]
258
+ parts.append(f"## Hypotheses ({len(hypos)})")
259
+ for h in hypos[:3]:
260
+ parts.append(f"- [{h.get('risk','?')}] {h.get('title','')}: {h.get('assumption_violated','')[:200]}")
261
+ return "\n\n".join(parts)
262
+
263
+ def _score_to_risk(self, score: float) -> str:
264
+ if score >= 9: return "CRITICAL"
265
+ if score >= 7: return "HIGH"
266
+ if score >= 5: return "MEDIUM"
267
+ return "LOW"
rapis-x/hf_space/requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio==4.44.0
2
+ anthropic==0.34.2
3
+ datasets==2.20.0
4
+ huggingface-hub==0.24.6
5
+ pandas==2.2.2
6
+ numpy==1.26.4
7
+ python-dotenv==1.0.1
8
+ httpx==0.27.2
9
+ beautifulsoup4==4.12.3
10
+ requests==2.32.3
11
+ Pillow==10.4.0
12
+ plotly==5.23.0
rapis-x/hf_space/training/__init__.py ADDED
File without changes
rapis-x/hf_space/training/training_engine.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ RAPIS X β€” Training Data Engine
3
+ ═══════════════════════════════════════════════════════════════
4
+ Generates high-quality instruction-tuning datasets for training
5
+ security-focused language models.
6
+
7
+ Generates:
8
+ - Bug bounty cognitive analysis pairs
9
+ - Inversion thinking examples
10
+ - Attack path reasoning chains
11
+ - Hypothesis generation examples
12
+ - Complexity β†’ Simplicity reduction pairs
13
+ - Adversarial question-answer pairs
14
+
15
+ Output formats:
16
+ - JSONL (instruction/input/output)
17
+ - HuggingFace Dataset
18
+ - Alpaca format
19
+ - ChatML format
20
+ ═══════════════════════════════════════════════════════════════
21
+ """
22
+ from __future__ import annotations
23
+ import json, uuid
24
+ from dataclasses import dataclass, field, asdict
25
+ from typing import Generator
26
+ from engines.claude_api import call_claude, stream_claude, parse_json
27
+
28
+
29
+ @dataclass
30
+ class TrainingExample:
31
+ id: str = field(default_factory=lambda: str(uuid.uuid4())[:8])
32
+ example_type: str = "" # inversion|attack_path|hypothesis|bug_bounty|cognitive|simplification
33
+ difficulty: str = "medium" # easy|medium|hard|expert
34
+ domain: str = "" # web|api|cloud|mobile|network|crypto
35
+ instruction: str = ""
36
+ input: str = ""
37
+ output: str = ""
38
+ chain_of_thought: str = ""
39
+ metadata: dict = field(default_factory=dict)
40
+
41
+ def to_alpaca(self) -> dict:
42
+ return {"instruction": self.instruction, "input": self.input, "output": self.output}
43
+
44
+ def to_chatml(self) -> dict:
45
+ messages = [{"role": "system", "content": TRAINING_SYSTEM_PROMPT}]
46
+ if self.input:
47
+ messages.append({"role": "user", "content": f"{self.instruction}\n\n{self.input}"})
48
+ else:
49
+ messages.append({"role": "user", "content": self.instruction})
50
+ messages.append({"role": "assistant", "content": self.output})
51
+ return {"messages": messages}
52
+
53
+ def to_dict(self):
54
+ return asdict(self)
55
+
56
+
57
+ TRAINING_SYSTEM_PROMPT = """You are RAPIS X β€” an elite adversarial security cognition system specialised in bug bounty analysis, attack path reasoning, and systemic vulnerability identification.
58
+
59
+ Core model:
60
+ System = Identity + Trust + State + Flow + Time + Relationships
61
+ Vulnerability = Collapse(SecurityAssumption)
62
+ Attack = propagate(Failure(Assumption))
63
+
64
+ You reason from complexity to simplicity, always applying inversion thinking.
65
+ You NEVER generate payloads or exploit code β€” only structural reasoning and defensive insights."""
66
+
67
+
68
+ GENERATOR_SYSTEM = """You are a training data generator for RAPIS X security AI.
69
+
70
+ Generate high-quality instruction-tuning training examples for a security-focused language model.
71
+
72
+ Each example must:
73
+ 1. Demonstrate adversarial cognitive reasoning (not just vulnerability descriptions)
74
+ 2. Apply inversion thinking where appropriate
75
+ 3. Go from complexity to simplicity in the output
76
+ 4. Include chain-of-thought reasoning
77
+ 5. NEVER include exploit payloads, shellcode, or attack instructions
78
+ 6. Focus on structural understanding and defensive insights
79
+
80
+ Respond ONLY with valid JSON β€” no markdown, no preamble."""
81
+
82
+
83
+ class TrainingEngine:
84
+ """
85
+ Generates training datasets for fine-tuning security AI models.
86
+ All examples teach cognitive reasoning, not exploitation.
87
+ """
88
+
89
+ def generate_batch(
90
+ self,
91
+ topic: str,
92
+ count: int = 5,
93
+ example_type: str = "mixed",
94
+ difficulty: str = "medium",
95
+ ) -> list[TrainingExample]:
96
+ """Generate a batch of training examples on a topic."""
97
+ prompt = self._build_batch_prompt(topic, count, example_type, difficulty)
98
+ raw = call_claude(GENERATOR_SYSTEM, prompt, max_tokens=5000)
99
+ data = parse_json(raw)
100
+ return self._build_examples(data, example_type, difficulty)
101
+
102
+ def stream_generate(
103
+ self,
104
+ topic: str,
105
+ count: int = 5,
106
+ example_type: str = "mixed",
107
+ ) -> Generator[str, None, None]:
108
+ """Stream training data generation with live output."""
109
+ prompt = self._build_batch_prompt(topic, count, example_type, "medium")
110
+ yield f"## πŸ‹οΈ Generating {count} Training Examples\n**Topic:** {topic}\n**Type:** {example_type}\n\n"
111
+ full = ""
112
+ for chunk in stream_claude(GENERATOR_SYSTEM, prompt, max_tokens=5000):
113
+ full += chunk
114
+ yield chunk
115
+ yield "\n\n---\n*Generation complete. Check Training Bank tab to export.*"
116
+
117
+ def generate_from_analysis(self, analysis: dict, target: str) -> list[TrainingExample]:
118
+ """Convert a completed analysis into training examples."""
119
+ examples = []
120
+
121
+ # Example 1: Full analysis pair
122
+ if analysis.get("executive_summary"):
123
+ examples.append(TrainingExample(
124
+ example_type="cognitive_analysis",
125
+ difficulty="hard",
126
+ domain="general",
127
+ instruction=f"Perform adversarial cognitive security analysis of: {target}",
128
+ input="Apply all six dimensions: Identity, Trust, State, Time, Flow, Relationships.",
129
+ output=self._format_analysis_as_output(analysis),
130
+ metadata={"source": "live_analysis", "risk": analysis.get("overall_risk", "?")}
131
+ ))
132
+
133
+ # Example 2: Inversion per attack path
134
+ for path in (analysis.get("attack_paths") or [])[:3]:
135
+ examples.append(TrainingExample(
136
+ example_type="inversion",
137
+ difficulty="expert",
138
+ domain="trust",
139
+ instruction=f"Apply inversion thinking to this attack path scenario in: {target}",
140
+ input=f"Category: {path.get('category','')}\nPath: {' β†’ '.join(path.get('path_nodes',[]))}\n",
141
+ output=f"**Reasoning:** {path.get('reasoning','')}\n\n**Inversion:** {path.get('inversion_analysis','')}\n\n**Assumption Chain:**\n" + "\n".join(f"- {a}" for a in path.get("assumption_chain",[])),
142
+ chain_of_thought=path.get("inversion_analysis", ""),
143
+ metadata={"risk": path.get("risk","?"), "category": path.get("category","?")}
144
+ ))
145
+
146
+ # Example 3: Hypothesis β†’ recommendation
147
+ for hypo in (analysis.get("hypotheses") or [])[:3]:
148
+ examples.append(TrainingExample(
149
+ example_type="hypothesis",
150
+ difficulty="medium",
151
+ domain="general",
152
+ instruction=f"Given this security hypothesis, provide structural reasoning and defensive recommendations.",
153
+ input=f"Hypothesis: {hypo.get('title','')}\nViolated Assumption: {hypo.get('assumption_violated','')}\nSystem: {target}",
154
+ output=f"**Reasoning:** {hypo.get('systemic_reasoning','')}\n\n**Propagation:** {hypo.get('propagation_chain','')}\n\n**Inversion Insight:** {hypo.get('inversion_insight','')}\n\n**Recommendations:**\n" + "\n".join(f"- {r}" for r in hypo.get("recommendations",[])),
155
+ metadata={"risk": hypo.get("risk","?"), "category": hypo.get("category","?")}
156
+ ))
157
+
158
+ # Example 4: Complexity β†’ Simplicity
159
+ if analysis.get("executive_summary") and analysis.get("cognition_analysis"):
160
+ cogn = analysis.get("cognition_analysis", {})
161
+ simple = cogn.get("systemic_risk_summary", "")
162
+ if simple:
163
+ examples.append(TrainingExample(
164
+ example_type="simplification",
165
+ difficulty="easy",
166
+ domain="communication",
167
+ instruction="Explain this complex security analysis in simple terms a non-technical person can understand.",
168
+ input=analysis.get("executive_summary", ""),
169
+ output=simple,
170
+ metadata={"source": "cognition_engine"}
171
+ ))
172
+
173
+ return examples
174
+
175
+ def export_jsonl(self, examples: list[TrainingExample], fmt: str = "alpaca") -> str:
176
+ """Export examples as JSONL string."""
177
+ lines = []
178
+ for ex in examples:
179
+ if fmt == "alpaca":
180
+ lines.append(json.dumps(ex.to_alpaca()))
181
+ elif fmt == "chatml":
182
+ lines.append(json.dumps(ex.to_chatml()))
183
+ else:
184
+ lines.append(json.dumps(ex.to_dict()))
185
+ return "\n".join(lines)
186
+
187
+ def _build_batch_prompt(self, topic: str, count: int, ex_type: str, difficulty: str) -> str:
188
+ type_instructions = {
189
+ "inversion": "inversion thinking examples (assumption β†’ collapse β†’ emergence)",
190
+ "bug_bounty": "bug bounty cognitive analysis examples (target reading β†’ attack surface β†’ hypotheses)",
191
+ "attack_path": "attack path reasoning examples (graph traversal β†’ assumption chain β†’ risk assessment)",
192
+ "simplification": "complexity-to-simplicity examples (technical analysis β†’ plain English)",
193
+ "cognitive": "6-dimensional cognitive analysis examples (Identity/Trust/State/Time/Flow/Relationships)",
194
+ "mixed": "mixed types covering all RAPIS X cognitive capabilities",
195
+ }
196
+ return f"""Generate {count} training examples for a security AI model.
197
+
198
+ Topic: {topic}
199
+ Example Type: {type_instructions.get(ex_type, type_instructions['mixed'])}
200
+ Difficulty: {difficulty}
201
+
202
+ Each example must demonstrate COGNITIVE SECURITY REASONING β€” not vulnerability scanning.
203
+ Teach the model to THINK like an adversary while reasoning DEFENSIVELY.
204
+
205
+ CRITICAL: No exploit payloads. No attack instructions. Only structural reasoning.
206
+
207
+ Respond with JSON:
208
+ {{
209
+ "examples": [
210
+ {{
211
+ "example_type": "{ex_type}",
212
+ "difficulty": "{difficulty}",
213
+ "domain": "web|api|cloud|mobile|network|auth",
214
+ "instruction": "Clear task instruction for the model",
215
+ "input": "Context or additional input (can be empty)",
216
+ "output": "Full, high-quality model response demonstrating cognitive security reasoning",
217
+ "chain_of_thought": "Internal reasoning steps the model should follow",
218
+ "metadata": {{"topic": "{topic}", "has_inversion": true/false}}
219
+ }}
220
+ ]
221
+ }}"""
222
+
223
+ def _build_examples(self, data: dict, ex_type: str, difficulty: str) -> list[TrainingExample]:
224
+ result = []
225
+ for ex in data.get("examples", []):
226
+ try:
227
+ result.append(TrainingExample(
228
+ example_type=ex.get("example_type", ex_type),
229
+ difficulty=ex.get("difficulty", difficulty),
230
+ domain=ex.get("domain", "general"),
231
+ instruction=ex.get("instruction", ""),
232
+ input=ex.get("input", ""),
233
+ output=ex.get("output", ""),
234
+ chain_of_thought=ex.get("chain_of_thought", ""),
235
+ metadata=ex.get("metadata", {}),
236
+ ))
237
+ except Exception:
238
+ pass
239
+ return result
240
+
241
+ def _format_analysis_as_output(self, analysis: dict) -> str:
242
+ parts = [f"## Risk Level: {analysis.get('overall_risk','?')}"]
243
+ parts.append(f"\n{analysis.get('executive_summary','')}")
244
+ paths = analysis.get("attack_paths", [])
245
+ if paths:
246
+ parts.append(f"\n## Attack Paths ({len(paths)})")
247
+ for p in paths[:3]:
248
+ parts.append(f"### [{p.get('risk','?')}] {p.get('category','')}")
249
+ parts.append(p.get("reasoning", ""))
250
+ if p.get("inversion_analysis"):
251
+ parts.append(f"*Inversion: {p['inversion_analysis']}*")
252
+ hypos = analysis.get("hypotheses", [])
253
+ if hypos:
254
+ parts.append(f"\n## Hypotheses ({len(hypos)})")
255
+ for h in hypos[:3]:
256
+ parts.append(f"### [{h.get('risk','?')}] {h.get('title','')}")
257
+ parts.append(f"Violated: {h.get('assumption_violated','')}")
258
+ parts.append(h.get("systemic_reasoning", ""))
259
+ return "\n\n".join(parts)
requirements.txt DELETED
@@ -1,15 +0,0 @@
1
- gradio==6.14.0
2
- uvicorn>=0.14.0
3
- websockets>=10.4
4
- spaces
5
- networkx
6
- plotly
7
- huggingface_hub
8
- sentence-transformers
9
- torch
10
- numpy
11
- faiss-cpu
12
- scikit-learn
13
- neo4j
14
- graphdatascience
15
- pandas