1- """Persona evaluation target — runs scenarios against a live study session."""
1+ """Persona evaluation target — runs scenarios via Claude Code print mode.
2+
3+ Uses ``claude -p`` (headless print mode) instead of tmux sessions.
4+ This avoids all TUI complexity: no pane capture, no trust dialogs,
5+ no timing issues. The persona is loaded via --append-system-prompt-file
6+ and the response comes back as structured JSON on stdout.
7+ """
28
39from __future__ import annotations
410
511import hashlib
12+ import json
613import logging
7- import os
814import shutil
9- import time
10- from datetime import UTC , datetime , timedelta
15+ import subprocess
1116from pathlib import Path
1217from typing import TYPE_CHECKING
1318
14- from studyctl .eval .capture import capture_response
15- from studyctl .session_state import (
16- PARKING_FILE ,
17- SESSION_DIR ,
18- TOPICS_FILE ,
19- _ensure_session_dir ,
20- is_session_active ,
21- read_session_state ,
22- write_session_state ,
23- )
24-
2519if TYPE_CHECKING :
2620 from studyctl .eval .models import Scenario
2721
2822logger = logging .getLogger (__name__ )
2923
24+ # Timeout for claude -p subprocess (seconds). Opus can take 60s+ to respond.
25+ CLAUDE_TIMEOUT = 120
26+
3027
3128class PersonaTarget :
32- """Eval target that starts a headless study session per scenario .
29+ """Eval target using Claude Code's print mode (``claude -p``) .
3330
34- Uses the same internal functions as ``POST /api/session/start`` —
35- creates the tmux session detached without trying to attach (which
36- would block when run non-interactively) .
31+ Each scenario is evaluated as a single-turn prompt with the full
32+ persona loaded as a system prompt. Setup prompts are prepended to
33+ provide conversational context .
3734 """
3835
3936 name = "persona"
4037
4138 def __init__ (self , agent : str = "claude" ) -> None :
4239 self .agent = agent
43- self ._session_name : str = ""
44- self ._tmux_main_pane : str = ""
4540 self .persona_hash : str = ""
41+ self ._persona_file : Path | None = None
4642
4743 def setup (self , scenario : Scenario ) -> None :
48- """Start a fresh headless study session for this scenario."""
44+ """Build the persona file for this scenario."""
4945 from studyctl .agent_launcher import (
5046 AGENTS ,
5147 build_canonical_persona ,
5248 detect_agents ,
5349 )
54- from studyctl .history import start_study_session
55- from studyctl .history .sessions import update_persona_hash
56- from studyctl .output import energy_to_label
57- from studyctl .session .orchestrator import (
58- build_wrapped_agent_cmd ,
59- create_tmux_environment ,
60- setup_session_dir ,
61- )
62- from studyctl .tmux import is_tmux_available , kill_session , session_exists
63-
64- if not is_tmux_available ():
65- logger .error ("tmux not available — cannot start eval session" )
66- return
67-
68- if is_session_active ():
69- logger .warning ("Session already active — cleaning up before eval" )
70- self ._force_teardown ()
7150
7251 # Resolve agent
7352 agent_name = self .agent
@@ -83,161 +62,110 @@ def setup(self, scenario: Scenario) -> None:
8362 logger .error ("Agent binary not found: %s" , adapter .binary )
8463 return
8564
86- # Create DB record
87- energy_label = energy_to_label (scenario .energy )
88- study_id = start_study_session (scenario .topic , energy_label )
89- if not study_id :
90- logger .error ("Failed to create session record" )
91- return
92-
93- # Write session state
94- _ensure_session_dir ()
95- now = datetime .now (UTC ).isoformat ()
96- write_session_state (
97- {
98- "study_session_id" : study_id ,
99- "topic" : scenario .topic ,
100- "energy" : scenario .energy ,
101- "energy_label" : energy_label ,
102- "mode" : "focus" ,
103- "timer_mode" : "energy" ,
104- "started_at" : now ,
105- "start_time" : now ,
106- "paused_at" : None ,
107- "total_paused_seconds" : 0 ,
108- }
109- )
110- TOPICS_FILE .touch (mode = 0o600 , exist_ok = True )
111- PARKING_FILE .touch (mode = 0o600 , exist_ok = True )
112-
113- # Session directory + tmux
114- slug = scenario .topic .lower ().replace (" " , "-" )[:20 ]
115- short_id = study_id [:8 ]
116- session_name = f"study-{ slug } -{ short_id } "
117- session_dir = SESSION_DIR / "sessions" / session_name
118-
119- if session_exists (session_name ):
120- kill_session (session_name )
121-
122- setup_session_dir (session_dir , scenario .topic )
123-
124- # Build persona
65+ # Build persona — same canonical persona used in live sessions
12566 canonical = build_canonical_persona ("focus" , scenario .topic , scenario .energy )
12667 self .persona_hash = hashlib .sha256 (canonical .encode ()).hexdigest ()[:16 ]
127- update_persona_hash (study_id , self .persona_hash )
128-
129- persona_file = adapter .setup (canonical , session_dir )
130- if adapter .mcp_setup :
131- adapter .mcp_setup (session_dir )
132-
133- # Build agent command
134- test_agent_cmd = os .environ .get ("STUDYCTL_TEST_AGENT_CMD" )
135- if test_agent_cmd :
136- agent_cmd = test_agent_cmd .format (persona_file = persona_file )
137- else :
138- claude_project_key = str (session_dir ).replace ("/" , "-" ).lstrip ("-" )
139- claude_project_dir = Path .home () / ".claude" / "projects" / claude_project_key
140- is_resuming = claude_project_dir .exists ()
141- agent_cmd = adapter .launch_cmd (persona_file , is_resuming )
142-
143- wrapped_cmd = build_wrapped_agent_cmd (session_dir , agent_cmd )
144-
145- result = create_tmux_environment (
146- session_name = session_name ,
147- session_dir = session_dir ,
148- wrapped_agent_cmd = wrapped_cmd ,
149- session_state_dir = SESSION_DIR ,
150- )
151-
152- # Persist tmux metadata
153- write_session_state (
154- {
155- "tmux_session" : session_name ,
156- "tmux_main_pane" : result ["tmux_main_pane" ],
157- "tmux_sidebar_pane" : result ["tmux_sidebar_pane" ],
158- "persona_file" : str (persona_file ),
159- "session_dir" : str (session_dir ),
160- "agent" : agent_name ,
161- "persona_hash" : self .persona_hash ,
162- }
163- )
16468
165- self ._session_name = session_name
166- self ._tmux_main_pane = result ["tmux_main_pane" ]
167-
168- # Wait for agent to be ready (poll for child process in tmux pane)
169- for _ in range (30 ):
170- if is_session_active ():
171- break
172- time .sleep (1 )
173-
174- # Accept Claude Code's trust dialog if present — send Enter to select
175- # "Yes, I trust this folder" (option 1, already highlighted).
176- # This is needed because Claude Code may not respect hasTrustDialogAccepted
177- # in settings.json for dynamically-created session directories.
178- from studyctl .eval .capture import capture_pane_plain , send_keys
179-
180- time .sleep (5 ) # Give Claude time to render the trust prompt
181- pane_content = capture_pane_plain (self ._tmux_main_pane )
182- if "trust" in pane_content .lower () and "Yes, I trust" in pane_content :
183- logger .info ("Trust dialog detected — accepting automatically" )
184- send_keys (self ._tmux_main_pane , "" ) # Enter accepts default option 1
185- time .sleep (15 ) # Wait for Claude to fully initialize after trust
186-
187- # Inject elapsed time for the scenario
188- fake_start = datetime .now (UTC ) - timedelta (minutes = scenario .elapsed_minutes )
189- write_session_state (
190- {
191- "started_at" : fake_start .isoformat (),
192- "start_time" : fake_start .isoformat (),
193- }
69+ # Write persona to a temp file for --append-system-prompt-file
70+ persona_dir = Path .home () / ".config" / "studyctl" / "eval-personas"
71+ persona_dir .mkdir (parents = True , exist_ok = True )
72+ persona_file = persona_dir / f"eval-{ scenario .id } .md"
73+ persona_file .write_text (canonical )
74+ self ._persona_file = persona_file
75+
76+ logger .info (
77+ "Persona ready for %s (hash=%s, file=%s)" ,
78+ scenario .id ,
79+ self .persona_hash ,
80+ persona_file ,
19481 )
19582
196- logger .info ("Session %s started for scenario %s" , session_name , scenario .id )
197-
19883 def run (self , scenario : Scenario ) -> str :
199- """Send setup prompts + test prompt, capture response.
84+ """Send the scenario prompt via claude -p, return the response.
20085
201- Uses the explicit tmux pane ID (``%N``) rather than the session name
202- to ensure we capture the agent pane, not the sidebar .
86+ If the scenario has setup_prompts, they are prepended as
87+ conversational context in a single multi-turn prompt .
20388 """
204- if not self ._tmux_main_pane :
205- logger .warning ("No main pane ID — returning empty response" )
89+ if not self ._persona_file :
90+ logger .warning ("No persona file — returning empty response" )
20691 return ""
20792
208- target = self ._tmux_main_pane
209- logger .info ("Capturing from pane %s (session %s)" , target , self ._session_name )
93+ # Build the full prompt with setup context
94+ prompt = self ._build_prompt (scenario )
95+
96+ cmd = [
97+ "claude" ,
98+ "-p" ,
99+ prompt ,
100+ "--append-system-prompt-file" ,
101+ str (self ._persona_file ),
102+ "--output-format" ,
103+ "json" ,
104+ ]
105+
106+ logger .info (
107+ "Running claude -p for %s (prompt=%d chars)" ,
108+ scenario .id ,
109+ len (prompt ),
110+ )
210111
211- # Send setup prompts — Claude Code (especially Opus) can take 30-60s
212- # to think + respond. Use generous timeouts.
213- for prompt in scenario .setup_prompts :
214- capture_response (target , prompt , timeout = 120 , stable_seconds = 5 )
112+ try :
113+ result = subprocess .run (
114+ cmd ,
115+ capture_output = True ,
116+ text = True ,
117+ timeout = CLAUDE_TIMEOUT ,
118+ check = False ,
119+ )
120+ except subprocess .TimeoutExpired :
121+ logger .warning ("claude -p timed out after %ds for %s" , CLAUDE_TIMEOUT , scenario .id )
122+ return ""
215123
216- # Send test prompt and capture — main response may take even longer
217- response = capture_response (target , scenario .prompt , timeout = 180 , stable_seconds = 8 )
218- logger .info ("Captured %d chars for %s" , len (response ), scenario .id )
219- return response
124+ if result .returncode != 0 :
125+ logger .warning (
126+ "claude -p failed for %s: rc=%d stderr=%s" ,
127+ scenario .id ,
128+ result .returncode ,
129+ result .stderr [:200 ],
130+ )
131+ return ""
132+
133+ # Parse JSON response
134+ try :
135+ data = json .loads (result .stdout )
136+ response = data .get ("result" , "" )
137+ except (json .JSONDecodeError , KeyError ):
138+ # Fall back to raw stdout if not valid JSON
139+ response = result .stdout
140+
141+ logger .info ("Got %d chars response for %s" , len (response ), scenario .id )
142+ return response .strip ()
220143
221144 def teardown (self ) -> None :
222- """End the session and clean up."""
223- self ._force_teardown ()
224-
225- def _force_teardown (self ) -> None :
226- """Force-kill any active session."""
227- from studyctl .session .cleanup import end_session_common
228-
229- state = read_session_state ()
230- if state .get ("study_session_id" ):
231- try :
232- end_session_common (state )
233- except Exception :
234- logger .exception ("end_session_common failed" )
235-
236- # Belt and suspenders: kill tmux session directly
237- if self ._session_name :
238- from studyctl .tmux import kill_session , session_exists
239-
240- if session_exists (self ._session_name ):
241- kill_session (self ._session_name )
242- self ._session_name = ""
243- self ._tmux_main_pane = ""
145+ """Clean up persona file."""
146+ if self ._persona_file and self ._persona_file .exists ():
147+ self ._persona_file .unlink (missing_ok = True )
148+ self ._persona_file = None
149+
150+ def _build_prompt (self , scenario : Scenario ) -> str :
151+ """Build the full prompt including setup context.
152+
153+ Setup prompts are included as conversational history so the
154+ model has context (e.g. "we've been discussing decorators").
155+ """
156+ parts : list [str ] = []
157+
158+ if scenario .setup_prompts :
159+ parts .append ("Context from earlier in the study session:" )
160+ for sp in scenario .setup_prompts :
161+ parts .append (f"Student: { sp } " )
162+ parts .append ("" )
163+ parts .append (
164+ f"The session has been running for { scenario .elapsed_minutes } minutes. "
165+ f"Student energy is { scenario .energy } /10."
166+ )
167+ parts .append ("" )
168+ parts .append ("Now the student says:" )
169+
170+ parts .append (scenario .prompt .strip ())
171+ return "\n " .join (parts )
0 commit comments