empathy-framework 4.1.1__py3-none-any.whl → 4.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. {empathy_framework-4.1.1.dist-info → empathy_framework-4.4.0.dist-info}/METADATA +77 -12
  2. {empathy_framework-4.1.1.dist-info → empathy_framework-4.4.0.dist-info}/RECORD +45 -14
  3. empathy_os/cli_unified.py +13 -0
  4. empathy_os/memory/long_term.py +5 -0
  5. empathy_os/memory/unified.py +149 -9
  6. empathy_os/meta_workflows/__init__.py +74 -0
  7. empathy_os/meta_workflows/agent_creator.py +254 -0
  8. empathy_os/meta_workflows/builtin_templates.py +567 -0
  9. empathy_os/meta_workflows/cli_meta_workflows.py +1551 -0
  10. empathy_os/meta_workflows/form_engine.py +304 -0
  11. empathy_os/meta_workflows/intent_detector.py +298 -0
  12. empathy_os/meta_workflows/models.py +567 -0
  13. empathy_os/meta_workflows/pattern_learner.py +754 -0
  14. empathy_os/meta_workflows/session_context.py +398 -0
  15. empathy_os/meta_workflows/template_registry.py +229 -0
  16. empathy_os/meta_workflows/workflow.py +980 -0
  17. empathy_os/orchestration/execution_strategies.py +888 -1
  18. empathy_os/orchestration/pattern_learner.py +699 -0
  19. empathy_os/socratic/__init__.py +273 -0
  20. empathy_os/socratic/ab_testing.py +969 -0
  21. empathy_os/socratic/blueprint.py +532 -0
  22. empathy_os/socratic/cli.py +689 -0
  23. empathy_os/socratic/collaboration.py +1112 -0
  24. empathy_os/socratic/domain_templates.py +916 -0
  25. empathy_os/socratic/embeddings.py +734 -0
  26. empathy_os/socratic/engine.py +729 -0
  27. empathy_os/socratic/explainer.py +663 -0
  28. empathy_os/socratic/feedback.py +767 -0
  29. empathy_os/socratic/forms.py +624 -0
  30. empathy_os/socratic/generator.py +716 -0
  31. empathy_os/socratic/llm_analyzer.py +635 -0
  32. empathy_os/socratic/mcp_server.py +751 -0
  33. empathy_os/socratic/session.py +306 -0
  34. empathy_os/socratic/storage.py +635 -0
  35. empathy_os/socratic/success.py +719 -0
  36. empathy_os/socratic/visual_editor.py +812 -0
  37. empathy_os/socratic/web_ui.py +925 -0
  38. empathy_os/workflows/manage_documentation.py +18 -2
  39. empathy_os/workflows/release_prep_crew.py +16 -1
  40. empathy_os/workflows/test_coverage_boost_crew.py +16 -1
  41. empathy_os/workflows/test_maintenance_crew.py +18 -1
  42. {empathy_framework-4.1.1.dist-info → empathy_framework-4.4.0.dist-info}/WHEEL +0 -0
  43. {empathy_framework-4.1.1.dist-info → empathy_framework-4.4.0.dist-info}/entry_points.txt +0 -0
  44. {empathy_framework-4.1.1.dist-info → empathy_framework-4.4.0.dist-info}/licenses/LICENSE +0 -0
  45. {empathy_framework-4.1.1.dist-info → empathy_framework-4.4.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,729 @@
1
+ """Socratic Workflow Builder - Main Engine
2
+
3
+ The core engine that orchestrates Socratic questioning for agent generation.
4
+
5
+ Flow:
6
+ 1. User provides initial goal (free text)
7
+ 2. Engine analyzes goal and generates clarifying questions
8
+ 3. User answers questions (forms)
9
+ 4. Engine determines if more clarification needed
10
+ 5. When ready, generates optimized workflow with agents
11
+ 6. Defines success criteria for measuring completion
12
+
13
+ Copyright 2026 Smart-AI-Memory
14
+ Licensed under Fair Source License 0.9
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import logging
20
+ import re
21
+ from dataclasses import dataclass
22
+ from typing import Any
23
+
24
+ from .forms import (
25
+ FieldOption,
26
+ FieldType,
27
+ FieldValidation,
28
+ Form,
29
+ FormField,
30
+ create_additional_context_field,
31
+ create_automation_level_field,
32
+ create_goal_text_field,
33
+ create_language_field,
34
+ create_quality_focus_field,
35
+ create_team_size_field,
36
+ )
37
+ from .generator import AgentGenerator, GeneratedWorkflow
38
+ from .session import GoalAnalysis, SessionState, SocraticSession
39
+ from .success import (
40
+ MetricType,
41
+ SuccessCriteria,
42
+ SuccessMetric,
43
+ code_review_criteria,
44
+ security_audit_criteria,
45
+ test_generation_criteria,
46
+ )
47
+
48
+ logger = logging.getLogger(__name__)
49
+
50
+
51
+ # =============================================================================
52
+ # DOMAIN DETECTION
53
+ # =============================================================================
54
+
55
+
56
+ @dataclass
57
+ class DomainPattern:
58
+ """Pattern for detecting user intent domain."""
59
+
60
+ domain: str
61
+ keywords: list[str]
62
+ phrases: list[str]
63
+ weight: float = 1.0
64
+
65
+
66
+ DOMAIN_PATTERNS = [
67
+ DomainPattern(
68
+ domain="code_review",
69
+ keywords=["review", "pr", "pull request", "merge", "diff", "changes"],
70
+ phrases=["code review", "review code", "check my code", "review my"],
71
+ weight=1.0,
72
+ ),
73
+ DomainPattern(
74
+ domain="security",
75
+ keywords=["security", "vulnerability", "secure", "exploit", "attack", "owasp"],
76
+ phrases=["security audit", "find vulnerabilities", "security check", "penetration"],
77
+ weight=1.2,
78
+ ),
79
+ DomainPattern(
80
+ domain="testing",
81
+ keywords=["test", "coverage", "unit test", "integration", "pytest", "jest"],
82
+ phrases=["write tests", "generate tests", "test coverage", "increase coverage"],
83
+ weight=1.0,
84
+ ),
85
+ DomainPattern(
86
+ domain="documentation",
87
+ keywords=["document", "docstring", "readme", "api docs", "comment"],
88
+ phrases=["write documentation", "generate docs", "add docstrings"],
89
+ weight=0.9,
90
+ ),
91
+ DomainPattern(
92
+ domain="performance",
93
+ keywords=["performance", "optimize", "speed", "slow", "memory", "efficient"],
94
+ phrases=["improve performance", "optimize code", "make faster", "reduce memory"],
95
+ weight=1.0,
96
+ ),
97
+ DomainPattern(
98
+ domain="refactoring",
99
+ keywords=["refactor", "clean", "restructure", "simplify", "modular"],
100
+ phrases=["refactor code", "clean up", "improve structure"],
101
+ weight=0.9,
102
+ ),
103
+ ]
104
+
105
+
106
+ def detect_domain(goal: str) -> tuple[str, float]:
107
+ """Detect the domain from goal text.
108
+
109
+ Returns:
110
+ Tuple of (domain, confidence)
111
+ """
112
+ goal_lower = goal.lower()
113
+ scores: dict[str, float] = {}
114
+
115
+ for pattern in DOMAIN_PATTERNS:
116
+ score = 0.0
117
+
118
+ # Check keywords
119
+ for keyword in pattern.keywords:
120
+ if keyword in goal_lower:
121
+ score += 1.0 * pattern.weight
122
+
123
+ # Check phrases (higher weight)
124
+ for phrase in pattern.phrases:
125
+ if phrase in goal_lower:
126
+ score += 2.0 * pattern.weight
127
+
128
+ if score > 0:
129
+ scores[pattern.domain] = score
130
+
131
+ if not scores:
132
+ return "general", 0.5
133
+
134
+ best_domain = max(scores, key=lambda k: scores[k])
135
+ max_score = scores[best_domain]
136
+
137
+ # Normalize confidence (cap at 1.0)
138
+ confidence = min(max_score / 5.0, 1.0)
139
+
140
+ return best_domain, confidence
141
+
142
+
143
+ def extract_keywords(goal: str) -> list[str]:
144
+ """Extract important keywords from goal."""
145
+ # Remove common words
146
+ stop_words = {
147
+ "i", "want", "to", "the", "a", "an", "my", "our", "for", "with",
148
+ "that", "this", "is", "are", "be", "will", "would", "could",
149
+ "should", "can", "help", "me", "us", "please", "need", "like",
150
+ }
151
+
152
+ # Extract words
153
+ words = re.findall(r"\b\w+\b", goal.lower())
154
+ keywords = [w for w in words if w not in stop_words and len(w) > 2]
155
+
156
+ # Return unique keywords preserving order
157
+ return list(dict.fromkeys(keywords))
158
+
159
+
160
+ def identify_ambiguities(goal: str, domain: str) -> list[str]:
161
+ """Identify ambiguities in the goal that need clarification."""
162
+ ambiguities = []
163
+
164
+ # Check for missing specifics
165
+ if not any(lang in goal.lower() for lang in ["python", "javascript", "typescript", "java", "go", "rust"]):
166
+ ambiguities.append("Programming language not specified")
167
+
168
+ # Check for vague scope
169
+ vague_terms = ["some", "various", "different", "several", "multiple"]
170
+ for term in vague_terms:
171
+ if term in goal.lower():
172
+ ambiguities.append(f"Vague scope indicator: '{term}'")
173
+ break
174
+
175
+ # Domain-specific ambiguities
176
+ if domain == "code_review":
177
+ if "security" not in goal.lower() and "style" not in goal.lower():
178
+ ambiguities.append("Review focus areas not specified")
179
+
180
+ if domain == "testing":
181
+ if "unit" not in goal.lower() and "integration" not in goal.lower():
182
+ ambiguities.append("Test type not specified")
183
+
184
+ return ambiguities
185
+
186
+
187
+ def identify_assumptions(goal: str, domain: str) -> list[str]:
188
+ """Identify assumptions we're making from the goal."""
189
+ assumptions = []
190
+
191
+ # Common assumptions
192
+ if domain == "code_review":
193
+ assumptions.append("Assuming code is version-controlled (git)")
194
+ assumptions.append("Assuming PR/diff-based review workflow")
195
+
196
+ if domain == "testing":
197
+ assumptions.append("Assuming existing test framework in project")
198
+
199
+ if domain == "security":
200
+ assumptions.append("Assuming standard web application security model")
201
+
202
+ return assumptions
203
+
204
+
205
+ # =============================================================================
206
+ # QUESTION GENERATION
207
+ # =============================================================================
208
+
209
+
210
+ def generate_initial_questions(
211
+ goal_analysis: GoalAnalysis,
212
+ session: SocraticSession,
213
+ ) -> Form:
214
+ """Generate the first round of questions based on goal analysis."""
215
+ fields: list[FormField] = []
216
+
217
+ # Always ask about languages if not detected
218
+ if "Programming language not specified" in goal_analysis.ambiguities:
219
+ fields.append(create_language_field(required=True))
220
+
221
+ # Ask about quality focus
222
+ fields.append(create_quality_focus_field(required=True))
223
+
224
+ # Domain-specific questions
225
+ if goal_analysis.domain == "code_review":
226
+ fields.append(FormField(
227
+ id="review_scope",
228
+ field_type=FieldType.SINGLE_SELECT,
229
+ label="What scope of review do you need?",
230
+ options=[
231
+ FieldOption("pr", "Pull Request/Diff", description="Review specific changes", recommended=True),
232
+ FieldOption("file", "Single File", description="Deep review of one file"),
233
+ FieldOption("directory", "Directory/Module", description="Review entire module"),
234
+ FieldOption("project", "Full Project", description="Comprehensive codebase review"),
235
+ ],
236
+ validation=FieldValidation(required=True),
237
+ category="scope",
238
+ ))
239
+
240
+ if goal_analysis.domain == "security":
241
+ fields.append(FormField(
242
+ id="security_focus",
243
+ field_type=FieldType.MULTI_SELECT,
244
+ label="What security aspects are most important?",
245
+ options=[
246
+ FieldOption("owasp", "OWASP Top 10", description="Common web vulnerabilities"),
247
+ FieldOption("injection", "Injection Attacks", description="SQL, command, XSS"),
248
+ FieldOption("auth", "Authentication/Authorization", description="Access control issues"),
249
+ FieldOption("crypto", "Cryptography", description="Encryption, hashing, secrets"),
250
+ FieldOption("deps", "Dependencies", description="Vulnerable dependencies"),
251
+ ],
252
+ validation=FieldValidation(required=True),
253
+ category="security",
254
+ ))
255
+
256
+ if goal_analysis.domain == "testing":
257
+ fields.append(FormField(
258
+ id="test_type",
259
+ field_type=FieldType.MULTI_SELECT,
260
+ label="What types of tests do you need?",
261
+ options=[
262
+ FieldOption("unit", "Unit Tests", description="Test individual functions", recommended=True),
263
+ FieldOption("integration", "Integration Tests", description="Test component interactions"),
264
+ FieldOption("e2e", "End-to-End Tests", description="Test full user flows"),
265
+ FieldOption("edge", "Edge Cases", description="Test boundary conditions"),
266
+ ],
267
+ validation=FieldValidation(required=True),
268
+ category="testing",
269
+ ))
270
+
271
+ # Automation level (always relevant)
272
+ fields.append(create_automation_level_field())
273
+
274
+ # Team context (helps calibration)
275
+ fields.append(create_team_size_field())
276
+
277
+ # Additional context (optional)
278
+ fields.append(create_additional_context_field())
279
+
280
+ return Form(
281
+ id=f"round_{session.current_round + 1}",
282
+ title="Help Us Understand Your Needs",
283
+ description=f"Based on your goal: \"{goal_analysis.raw_goal[:100]}...\"",
284
+ fields=fields,
285
+ round_number=session.current_round + 1,
286
+ progress=0.3,
287
+ )
288
+
289
+
290
+ def generate_followup_questions(
291
+ session: SocraticSession,
292
+ ) -> Form | None:
293
+ """Generate follow-up questions based on previous answers."""
294
+ # Check if we need more clarification
295
+ if session.requirements.completeness_score() >= 0.8:
296
+ return None # Ready to generate
297
+
298
+ if session.current_round >= session.max_rounds:
299
+ return None # Max rounds reached
300
+
301
+ fields: list[FormField] = []
302
+
303
+ # Check what's still missing
304
+ reqs = session.requirements
305
+
306
+ # If no must-haves, ask for priorities
307
+ if not reqs.must_have:
308
+ fields.append(FormField(
309
+ id="priorities",
310
+ field_type=FieldType.TEXT_AREA,
311
+ label="What are your top 3 priorities for this workflow?",
312
+ help_text="Be as specific as possible about what success looks like.",
313
+ validation=FieldValidation(required=True, min_length=20),
314
+ category="priorities",
315
+ ))
316
+
317
+ # If technical constraints missing
318
+ if not reqs.technical_constraints.get("languages"):
319
+ fields.append(create_language_field(required=True))
320
+
321
+ # Domain-specific follow-ups
322
+ if session.goal_analysis and session.goal_analysis.domain == "code_review":
323
+ if "review_depth" not in [r.get("id") for r in session.question_rounds[-1]["questions"]] if session.question_rounds else True:
324
+ fields.append(FormField(
325
+ id="review_depth",
326
+ field_type=FieldType.SINGLE_SELECT,
327
+ label="How thorough should the review be?",
328
+ options=[
329
+ FieldOption("quick", "Quick Scan", description="Fast, surface-level review"),
330
+ FieldOption("standard", "Standard", description="Balanced depth", recommended=True),
331
+ FieldOption("deep", "Deep Dive", description="Thorough, detailed analysis"),
332
+ ],
333
+ category="depth",
334
+ ))
335
+
336
+ if not fields:
337
+ return None
338
+
339
+ return Form(
340
+ id=f"round_{session.current_round + 1}",
341
+ title="A Few More Questions",
342
+ description="Help us fine-tune your workflow.",
343
+ fields=fields,
344
+ round_number=session.current_round + 1,
345
+ progress=0.3 + (session.current_round * 0.2),
346
+ )
347
+
348
+
349
+ # =============================================================================
350
+ # MAIN ENGINE
351
+ # =============================================================================
352
+
353
+
354
+ class SocraticWorkflowBuilder:
355
+ """Main engine for Socratic agent/workflow generation.
356
+
357
+ Example:
358
+ >>> builder = SocraticWorkflowBuilder()
359
+ >>>
360
+ >>> # Start with a goal
361
+ >>> session = builder.start_session("I want to automate security reviews")
362
+ >>>
363
+ >>> # Get questions
364
+ >>> form = builder.get_next_questions(session)
365
+ >>> print(form.title)
366
+ >>>
367
+ >>> # Submit answers
368
+ >>> session = builder.submit_answers(session, {
369
+ ... "languages": ["python"],
370
+ ... "quality_focus": ["security"],
371
+ ... "automation_level": "semi_auto"
372
+ ... })
373
+ >>>
374
+ >>> # Check if ready
375
+ >>> if builder.is_ready_to_generate(session):
376
+ ... workflow = builder.generate_workflow(session)
377
+ ... print(workflow.describe())
378
+ """
379
+
380
+ def __init__(self):
381
+ """Initialize the builder."""
382
+ self.generator = AgentGenerator()
383
+ self._sessions: dict[str, SocraticSession] = {}
384
+
385
+ def start_session(self, goal: str = "") -> SocraticSession:
386
+ """Start a new Socratic session.
387
+
388
+ Args:
389
+ goal: Optional initial goal (can be set later)
390
+
391
+ Returns:
392
+ New SocraticSession
393
+ """
394
+ session = SocraticSession()
395
+
396
+ if goal:
397
+ session = self.set_goal(session, goal)
398
+
399
+ self._sessions[session.session_id] = session
400
+ return session
401
+
402
+ def get_session(self, session_id: str) -> SocraticSession | None:
403
+ """Retrieve a session by ID."""
404
+ return self._sessions.get(session_id)
405
+
406
+ def set_goal(self, session: SocraticSession, goal: str) -> SocraticSession:
407
+ """Set or update the session goal.
408
+
409
+ Args:
410
+ session: The session to update
411
+ goal: The user's goal statement
412
+
413
+ Returns:
414
+ Updated session with goal analysis
415
+ """
416
+ session.goal = goal
417
+ session.state = SessionState.ANALYZING_GOAL
418
+ session.touch()
419
+
420
+ # Analyze the goal
421
+ domain, confidence = detect_domain(goal)
422
+ keywords = extract_keywords(goal)
423
+ ambiguities = identify_ambiguities(goal, domain)
424
+ assumptions = identify_assumptions(goal, domain)
425
+
426
+ session.goal_analysis = GoalAnalysis(
427
+ raw_goal=goal,
428
+ intent=self._extract_intent(goal, domain),
429
+ domain=domain,
430
+ confidence=confidence,
431
+ ambiguities=ambiguities,
432
+ assumptions=assumptions,
433
+ keywords=keywords,
434
+ )
435
+
436
+ # Transition to awaiting answers
437
+ session.state = SessionState.AWAITING_ANSWERS
438
+ return session
439
+
440
+ def _extract_intent(self, goal: str, domain: str) -> str:
441
+ """Extract the core intent from the goal."""
442
+ intent_patterns = {
443
+ "code_review": "Automated code review",
444
+ "security": "Security vulnerability analysis",
445
+ "testing": "Automated test generation",
446
+ "documentation": "Documentation generation",
447
+ "performance": "Performance optimization",
448
+ "refactoring": "Code refactoring",
449
+ "general": "Code analysis and improvement",
450
+ }
451
+ return intent_patterns.get(domain, "Code analysis")
452
+
453
+ def get_initial_form(self) -> Form:
454
+ """Get the initial goal capture form."""
455
+ return Form(
456
+ id="initial_goal",
457
+ title="What would you like to accomplish?",
458
+ description=(
459
+ "Describe your goal in your own words. Be as specific as you like - "
460
+ "we'll ask clarifying questions to understand exactly what you need."
461
+ ),
462
+ fields=[create_goal_text_field()],
463
+ round_number=0,
464
+ progress=0.1,
465
+ )
466
+
467
+ def get_next_questions(self, session: SocraticSession) -> Form | None:
468
+ """Get the next set of questions for a session.
469
+
470
+ Args:
471
+ session: The current session
472
+
473
+ Returns:
474
+ Form with questions, or None if ready to generate
475
+ """
476
+ if session.state == SessionState.AWAITING_GOAL:
477
+ return self.get_initial_form()
478
+
479
+ if session.state == SessionState.READY_TO_GENERATE:
480
+ return None
481
+
482
+ if session.state == SessionState.COMPLETED:
483
+ return None
484
+
485
+ if session.goal_analysis is None:
486
+ return self.get_initial_form()
487
+
488
+ # First round of questions
489
+ if session.current_round == 0:
490
+ return generate_initial_questions(session.goal_analysis, session)
491
+
492
+ # Follow-up questions
493
+ return generate_followup_questions(session)
494
+
495
+ def submit_answers(
496
+ self,
497
+ session: SocraticSession,
498
+ answers: dict[str, Any],
499
+ ) -> SocraticSession:
500
+ """Submit answers to the current questions.
501
+
502
+ Args:
503
+ session: The current session
504
+ answers: Dictionary mapping field IDs to values
505
+
506
+ Returns:
507
+ Updated session
508
+ """
509
+ session.state = SessionState.PROCESSING_ANSWERS
510
+ session.touch()
511
+
512
+ # Record this round
513
+ current_form = self.get_next_questions(session)
514
+ questions_data = []
515
+ if current_form:
516
+ questions_data = [
517
+ {"id": f.id, "label": f.label}
518
+ for f in current_form.fields
519
+ ]
520
+
521
+ session.add_question_round(questions_data, answers)
522
+
523
+ # Update requirements from answers
524
+ self._update_requirements(session, answers)
525
+
526
+ # Check if we can generate
527
+ if session.can_generate():
528
+ session.state = SessionState.READY_TO_GENERATE
529
+ else:
530
+ session.state = SessionState.AWAITING_ANSWERS
531
+
532
+ return session
533
+
534
+ def _update_requirements(
535
+ self,
536
+ session: SocraticSession,
537
+ answers: dict[str, Any],
538
+ ) -> None:
539
+ """Update session requirements from answers."""
540
+ reqs = session.requirements
541
+
542
+ # Languages
543
+ if "languages" in answers:
544
+ reqs.technical_constraints["languages"] = answers["languages"]
545
+
546
+ # Quality focus
547
+ if "quality_focus" in answers:
548
+ reqs.quality_attributes = dict.fromkeys(answers["quality_focus"], 1.0)
549
+ # Add to must-haves
550
+ for quality in answers["quality_focus"]:
551
+ req = f"Optimize for {quality}"
552
+ if req not in reqs.must_have:
553
+ reqs.must_have.append(req)
554
+
555
+ # Automation level
556
+ if "automation_level" in answers:
557
+ reqs.preferences["automation_level"] = answers["automation_level"]
558
+
559
+ # Team size
560
+ if "team_size" in answers:
561
+ reqs.preferences["team_size"] = answers["team_size"]
562
+
563
+ # Domain-specific
564
+ if "review_scope" in answers:
565
+ reqs.domain_specific["review_scope"] = answers["review_scope"]
566
+
567
+ if "security_focus" in answers:
568
+ reqs.domain_specific["security_focus"] = answers["security_focus"]
569
+
570
+ if "test_type" in answers:
571
+ reqs.domain_specific["test_type"] = answers["test_type"]
572
+
573
+ # Additional context
574
+ if "additional_context" in answers and answers["additional_context"]:
575
+ reqs.domain_specific["additional_context"] = answers["additional_context"]
576
+
577
+ # Priorities
578
+ if "priorities" in answers:
579
+ priorities = answers["priorities"]
580
+ if isinstance(priorities, str):
581
+ # Parse priorities from text
582
+ for line in priorities.split("\n"):
583
+ line = line.strip()
584
+ if line and line not in reqs.must_have:
585
+ reqs.must_have.append(line)
586
+
587
+ def is_ready_to_generate(self, session: SocraticSession) -> bool:
588
+ """Check if session is ready for workflow generation."""
589
+ return session.state == SessionState.READY_TO_GENERATE or session.can_generate()
590
+
591
+ def generate_workflow(
592
+ self,
593
+ session: SocraticSession,
594
+ ) -> GeneratedWorkflow:
595
+ """Generate workflow from the session.
596
+
597
+ Args:
598
+ session: Session with complete requirements
599
+
600
+ Returns:
601
+ Generated workflow ready for execution
602
+
603
+ Raises:
604
+ ValueError: If session not ready for generation
605
+ """
606
+ if not self.is_ready_to_generate(session):
607
+ raise ValueError("Session not ready for generation. Answer more questions.")
608
+
609
+ session.state = SessionState.GENERATING
610
+ session.touch()
611
+
612
+ # Build requirements dict for generator
613
+ reqs = session.requirements
614
+ requirements = {
615
+ "quality_focus": list(reqs.quality_attributes.keys()),
616
+ "languages": reqs.technical_constraints.get("languages", []),
617
+ "automation_level": reqs.preferences.get("automation_level", "semi_auto"),
618
+ "domain": session.goal_analysis.domain if session.goal_analysis else "general",
619
+ }
620
+
621
+ # Generate agents
622
+ agents = self.generator.generate_agents_for_requirements(requirements)
623
+
624
+ # Determine workflow name
625
+ domain = session.goal_analysis.domain if session.goal_analysis else "general"
626
+ name = self._generate_workflow_name(domain, requirements)
627
+
628
+ # Generate success criteria
629
+ success_criteria = self._generate_success_criteria(domain, requirements)
630
+
631
+ # Create blueprint
632
+ blueprint = self.generator.create_workflow_blueprint(
633
+ name=name,
634
+ description=session.goal or "Generated workflow",
635
+ agents=agents,
636
+ quality_focus=requirements["quality_focus"],
637
+ automation_level=requirements["automation_level"],
638
+ success_criteria=success_criteria,
639
+ )
640
+
641
+ blueprint.source_session_id = session.session_id
642
+ blueprint.supported_languages = requirements["languages"]
643
+
644
+ # Generate workflow
645
+ workflow = self.generator.generate_workflow(blueprint)
646
+
647
+ # Update session
648
+ session.blueprint = blueprint
649
+ session.workflow = workflow
650
+ session.state = SessionState.COMPLETED
651
+ session.touch()
652
+
653
+ return workflow
654
+
655
+ def _generate_workflow_name(
656
+ self,
657
+ domain: str,
658
+ requirements: dict[str, Any],
659
+ ) -> str:
660
+ """Generate a descriptive workflow name."""
661
+ domain_names = {
662
+ "code_review": "Code Review",
663
+ "security": "Security Audit",
664
+ "testing": "Test Generation",
665
+ "documentation": "Documentation",
666
+ "performance": "Performance Analysis",
667
+ "refactoring": "Refactoring",
668
+ "general": "Code Analysis",
669
+ }
670
+
671
+ base_name = domain_names.get(domain, "Custom Workflow")
672
+
673
+ # Add qualifier
674
+ qualities = requirements.get("quality_focus", [])
675
+ if qualities:
676
+ qualifier = qualities[0].title()
677
+ return f"{qualifier}-Focused {base_name}"
678
+
679
+ return f"Automated {base_name}"
680
+
681
+ def _generate_success_criteria(
682
+ self,
683
+ domain: str,
684
+ requirements: dict[str, Any],
685
+ ) -> SuccessCriteria:
686
+ """Generate appropriate success criteria for the workflow."""
687
+ # Use predefined criteria based on domain
688
+ if domain == "code_review":
689
+ return code_review_criteria()
690
+ elif domain == "security":
691
+ return security_audit_criteria()
692
+ elif domain == "testing":
693
+ return test_generation_criteria()
694
+ else:
695
+ # Generic criteria
696
+ return SuccessCriteria(
697
+ id=f"{domain}_success",
698
+ name=f"{domain.title()} Success Criteria",
699
+ metrics=[
700
+ SuccessMetric(
701
+ id="task_completed",
702
+ name="Task Completed",
703
+ metric_type=MetricType.BOOLEAN,
704
+ is_primary=True,
705
+ extraction_path="success",
706
+ ),
707
+ SuccessMetric(
708
+ id="findings_count",
709
+ name="Findings",
710
+ metric_type=MetricType.COUNT,
711
+ extraction_path="findings_count",
712
+ ),
713
+ ],
714
+ success_threshold=0.7,
715
+ )
716
+
717
+ def get_session_summary(self, session: SocraticSession) -> dict[str, Any]:
718
+ """Get a summary of the session state for display."""
719
+ return {
720
+ "session_id": session.session_id,
721
+ "state": session.state.value,
722
+ "goal": session.goal,
723
+ "domain": session.goal_analysis.domain if session.goal_analysis else None,
724
+ "confidence": session.goal_analysis.confidence if session.goal_analysis else 0,
725
+ "rounds_completed": session.current_round,
726
+ "requirements_completeness": session.requirements.completeness_score(),
727
+ "ready_to_generate": self.is_ready_to_generate(session),
728
+ "ambiguities_remaining": len(session.goal_analysis.ambiguities) if session.goal_analysis else 0,
729
+ }