Executor-Tyrant-Framework Claude Opus 4.6 (1M context) commited on
Commit
2dcd6e8
·
1 Parent(s): d715ed0

Add persona_client.py — TQB roleplay model integration (Phase 2)

Browse files

New persona_client.py: calls Hermes 3 70B via OpenRouter with TQB
personality files injected as system prompts. Graph context prepended
to task prompts so the substrate's learned knowledge flows through
each persona's evaluation lens.

Functions:
- call_persona(role, task, graph_context) — core call
- review_with_persona(role, content, review_type) — convenience wrapper
- load_personality(role) — loads character sheet + unit disciplines

Tested: Razor (security review), Wrench (unconventional solutions),
Razor with Graph context injection. All three showed differentiated
persona-consistent output.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Files changed (2) hide show
  1. Dockerfile +1 -0
  2. persona_client.py +235 -0
Dockerfile CHANGED
@@ -70,6 +70,7 @@ COPY worker_ng.py .
70
  COPY ng_embed.py .
71
  COPY work_block_schema.py .
72
  COPY spec_executor.py .
 
73
 
74
  # Copy tools directory
75
  COPY tools/ ./tools/
 
70
  COPY ng_embed.py .
71
  COPY work_block_schema.py .
72
  COPY spec_executor.py .
73
+ COPY persona_client.py .
74
 
75
  # Copy tools directory
76
  COPY tools/ ./tools/
persona_client.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ---- Changelog ----
2
+ # [2026-04-07] Josh + Claude — Persona client for TQB roleplay model integration
3
+ # What: Calls RP model with personality + Graph context + task prompt, returns structured response
4
+ # Why: Phase 2 of autonomous build organ — the model is the lens, the Graph is the brain
5
+ # How: OpenRouter via OpenAI SDK, personality file injection, Graph recall prepended, JSON output
6
+ # -------------------
7
+
8
+ """Persona Client — TQB roleplay model integration.
9
+
10
+ Calls the roleplay model with a personality file (the lens), Graph context
11
+ (the brain), and a task prompt. The persona drives the question. The Graph
12
+ provides the knowledge. The spec format constrains the output.
13
+ """
14
+
15
+ import json
16
+ import logging
17
+ import os
18
+ import time
19
+ from pathlib import Path
20
+ from typing import Optional
21
+
22
+ logger = logging.getLogger("persona_client")
23
+
24
+ # Personality files directory
25
+ PERSONALITY_DIR = Path(os.getenv(
26
+ "TQB_PERSONALITY_DIR",
27
+ os.path.expanduser("~/docs/queen-bitch/tqb-personalities")
28
+ ))
29
+
30
+ # Unit disciplines — injected into every persona
31
+ UNIT_DISCIPLINES_FILE = PERSONALITY_DIR / "UNIT_DISCIPLINES.md"
32
+
33
+
34
+ def _get_rp_client():
35
+ """Create OpenRouter client for the RP model."""
36
+ from openai import OpenAI
37
+ return OpenAI(
38
+ base_url="https://openrouter.ai/api/v1",
39
+ api_key=os.getenv("OPENROUTER_API_KEY"),
40
+ )
41
+
42
+
43
+ def _get_rp_model_id() -> str:
44
+ """Return the RP model ID from env."""
45
+ return os.getenv("CODEMINE_RP_MODEL_ID", "nousresearch/hermes-3-llama-3.1-70b")
46
+
47
+
48
+ def load_personality(role: str) -> str:
49
+ """Load a personality file by role name.
50
+
51
+ Returns the full markdown content for system prompt injection.
52
+ Includes unit disciplines.
53
+ """
54
+ personality_file = PERSONALITY_DIR / f"{role.lower()}.md"
55
+ if not personality_file.exists():
56
+ raise FileNotFoundError(f"No personality file for role '{role}' at {personality_file}")
57
+
58
+ personality = personality_file.read_text(encoding="utf-8")
59
+
60
+ # Load unit disciplines if available
61
+ disciplines = ""
62
+ if UNIT_DISCIPLINES_FILE.exists():
63
+ disciplines = UNIT_DISCIPLINES_FILE.read_text(encoding="utf-8")
64
+
65
+ return personality, disciplines
66
+
67
+
68
+ def _build_system_prompt(role: str, personality: str, disciplines: str) -> str:
69
+ """Build the full system prompt from personality + disciplines.
70
+
71
+ Extracts the system prompt injection block from the personality file
72
+ and prepends unit disciplines.
73
+ """
74
+ # Extract the system prompt injection block if present
75
+ injection_marker = "## System Prompt Injection"
76
+ if injection_marker in personality:
77
+ # Find the code block after the marker
78
+ marker_pos = personality.index(injection_marker)
79
+ rest = personality[marker_pos:]
80
+ # Find the content between ``` markers
81
+ start = rest.find("```\n")
82
+ end = rest.find("\n```", start + 4)
83
+ if start >= 0 and end >= 0:
84
+ injection = rest[start + 4:end].strip()
85
+ else:
86
+ injection = rest[len(injection_marker):].strip()
87
+ else:
88
+ # Use the whole personality as the system prompt
89
+ injection = personality
90
+
91
+ return injection
92
+
93
+
94
+ def _format_graph_context(recalls: list, max_chars: int = 4000) -> str:
95
+ """Format Graph recall results for injection into persona prompt."""
96
+ if not recalls:
97
+ return ""
98
+
99
+ lines = ["## Relevant Context from the Graph\n"]
100
+ total = 0
101
+ for r in recalls:
102
+ content = r.get("content", "")[:500]
103
+ similarity = r.get("similarity", 0)
104
+ entry = f"- (relevance: {similarity:.2f}) {content}\n"
105
+ if total + len(entry) > max_chars:
106
+ break
107
+ lines.append(entry)
108
+ total += len(entry)
109
+
110
+ return "\n".join(lines)
111
+
112
+
113
+ def call_persona(
114
+ role: str,
115
+ task: str,
116
+ graph_context: Optional[list] = None,
117
+ response_format: Optional[dict] = None,
118
+ max_tokens: int = 4096,
119
+ temperature: float = 0.7,
120
+ max_retries: int = 2,
121
+ ) -> dict:
122
+ """Call the RP model as a specific TQB persona.
123
+
124
+ Args:
125
+ role: Persona name (strategist, razor, reviewer, tracker, wrench, forge)
126
+ task: The task/prompt for this persona to evaluate
127
+ graph_context: List of Graph recall results to inject as context
128
+ response_format: Optional JSON schema for structured output
129
+ max_tokens: Max response tokens
130
+ temperature: Creativity level (higher = more creative, lower = more focused)
131
+ max_retries: Retry count on transient failures
132
+
133
+ Returns:
134
+ dict with keys: role, response (str), structured (dict|None), model, elapsed_seconds
135
+ """
136
+ personality, disciplines = load_personality(role)
137
+ system_prompt = _build_system_prompt(role, personality, disciplines)
138
+
139
+ # Build the user message with Graph context prepended
140
+ graph_section = _format_graph_context(graph_context or [])
141
+ user_content = f"{graph_section}\n\n{task}" if graph_section else task
142
+
143
+ client = _get_rp_client()
144
+ model_id = _get_rp_model_id()
145
+ last_error = None
146
+ start = time.time()
147
+
148
+ for attempt in range(max_retries + 1):
149
+ try:
150
+ kwargs = {
151
+ "model": model_id,
152
+ "max_tokens": max_tokens,
153
+ "temperature": temperature,
154
+ "messages": [
155
+ {"role": "system", "content": system_prompt},
156
+ {"role": "user", "content": user_content},
157
+ ],
158
+ }
159
+ if response_format:
160
+ kwargs["response_format"] = response_format
161
+
162
+ response = client.chat.completions.create(**kwargs)
163
+ raw_text = response.choices[0].message.content or ""
164
+
165
+ # Try to parse as JSON if structured output was requested
166
+ structured = None
167
+ if response_format:
168
+ try:
169
+ structured = json.loads(raw_text)
170
+ except json.JSONDecodeError:
171
+ # Try to extract JSON from markdown code blocks
172
+ if "```json" in raw_text:
173
+ start_idx = raw_text.index("```json") + 7
174
+ end_idx = raw_text.index("```", start_idx)
175
+ structured = json.loads(raw_text[start_idx:end_idx].strip())
176
+ elif "```" in raw_text:
177
+ start_idx = raw_text.index("```") + 3
178
+ end_idx = raw_text.index("```", start_idx)
179
+ structured = json.loads(raw_text[start_idx:end_idx].strip())
180
+
181
+ elapsed = round(time.time() - start, 2)
182
+ logger.info("Persona %s responded in %.1fs (%d tokens)", role, elapsed,
183
+ response.usage.completion_tokens if response.usage else 0)
184
+
185
+ return {
186
+ "role": role,
187
+ "response": raw_text,
188
+ "structured": structured,
189
+ "model": model_id,
190
+ "elapsed_seconds": elapsed,
191
+ }
192
+
193
+ except Exception as e:
194
+ last_error = e
195
+ logger.warning("Persona %s attempt %d/%d failed: %s",
196
+ role, attempt + 1, max_retries + 1, e)
197
+ if attempt < max_retries:
198
+ time.sleep(2 * (2 ** attempt))
199
+
200
+ return {
201
+ "role": role,
202
+ "response": f"Error: {last_error}",
203
+ "structured": None,
204
+ "model": model_id,
205
+ "elapsed_seconds": round(time.time() - start, 2),
206
+ }
207
+
208
+
209
+ def review_with_persona(
210
+ role: str,
211
+ content: str,
212
+ review_type: str = "general",
213
+ graph_context: Optional[list] = None,
214
+ ) -> dict:
215
+ """Convenience wrapper for code/spec review through a persona lens.
216
+
217
+ Args:
218
+ role: Which persona reviews (razor, reviewer, tracker, etc.)
219
+ content: The code, spec, or report to review
220
+ review_type: One of "security", "quality", "rootcause", "integration", "general"
221
+ graph_context: Graph recall results for context
222
+
223
+ Returns:
224
+ call_persona result
225
+ """
226
+ review_prompts = {
227
+ "security": "Review the following for security vulnerabilities, attack surface, credential exposure, and policy violations. Be thorough. Be paranoid.\n\n",
228
+ "quality": "Review the following for code quality, standards compliance, completeness, and maintainability. Read the diff, not just the description.\n\n",
229
+ "rootcause": "Analyze the following failure or bug report. Trace the root cause. Don't accept the symptom — find what caused it. What changed? Why did it break?\n\n",
230
+ "integration": "Review the following for integration issues — interface mismatches, contract violations, assumptions that don't hold when components connect. Does it actually work together?\n\n",
231
+ "general": "Review the following through your lens. What do you see? What concerns you? What would you check first?\n\n",
232
+ }
233
+
234
+ prompt = review_prompts.get(review_type, review_prompts["general"])
235
+ return call_persona(role, prompt + content, graph_context=graph_context)