Coverage for little_loops / workflow_sequence_analyzer.py: 87%
364 statements
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-04 01:17 -0600
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-04 01:17 -0600
1"""ll-workflows: Identify multi-step workflow patterns from user message history.
3Identifies multi-step workflows and cross-session patterns using:
4- Entity-based clustering
5- Time-gap weighted boundaries
6- Semantic similarity scoring
7- Workflow template matching
9Usage as CLI:
10 ll-workflows analyze --input messages.jsonl --patterns step1.yaml
11 ll-workflows analyze -i messages.jsonl -p patterns.yaml -o output.yaml
13Usage as library:
14 from little_loops.workflow_sequence_analyzer import analyze_workflows
16 result = analyze_workflows(
17 messages_file=Path("user-messages.jsonl"),
18 patterns_file=Path("step1-patterns.yaml"),
19 output_file=Path("step2-workflows.yaml"),
20 )
21"""
23from __future__ import annotations
25import json
26import re
27from dataclasses import dataclass, field
28from datetime import datetime
29from pathlib import Path
30from typing import Any
32import yaml
34__all__ = [
35 "analyze_workflows",
36 "SessionLink",
37 "EntityCluster",
38 "WorkflowBoundary",
39 "Workflow",
40 "WorkflowAnalysis",
41 "extract_entities",
42 "calculate_boundary_weight",
43 "entity_overlap",
44 "get_verb_class",
45 "semantic_similarity",
46]
48# Module-level compiled regex patterns
49FILE_PATTERN = re.compile(r"[\w./-]+\.(?:md|py|json|yaml|yml|js|ts|tsx|jsx|sh|toml)", re.IGNORECASE)
50PHASE_PATTERN = re.compile(r"phase[- ]?\d+", re.IGNORECASE)
51MODULE_PATTERN = re.compile(r"module[- ]?\d+", re.IGNORECASE)
52COMMAND_PATTERN = re.compile(r"/[\w:-]+")
53ISSUE_PATTERN = re.compile(r"(?:BUG|FEAT|ENH)-\d+", re.IGNORECASE)
55# Verb class taxonomy for semantic similarity
56VERB_CLASSES: dict[str, set[str]] = {
57 "deletion": {"remove", "delete", "drop", "eliminate", "clear", "clean"},
58 "modification": {"update", "change", "modify", "edit", "fix", "adjust", "revise"},
59 "creation": {"create", "add", "generate", "write", "make", "build"},
60 "search": {"find", "search", "locate", "where", "what", "which", "list"},
61 "verification": {"check", "verify", "validate", "confirm", "review", "ensure"},
62 "execution": {"run", "execute", "launch", "start", "invoke", "call"},
63}
65# Workflow templates: category sequences that indicate common patterns
66WORKFLOW_TEMPLATES: dict[str, list[str]] = {
67 "explore → modify → verify": ["file_search", "code_modification", "testing"],
68 "create → refine → finalize": ["file_write", "code_modification", "git_operation"],
69 "review → fix → commit": ["code_review", "code_modification", "git_operation"],
70 "plan → implement → verify": ["planning", "code_modification", "testing"],
71 "debug → fix → test": ["debugging", "code_modification", "testing"],
72}
75# -----------------------------------------------------------------------------
76# Data Classes
77# -----------------------------------------------------------------------------
80@dataclass
81class SessionLink:
82 """Link between related sessions."""
84 link_id: str
85 sessions: list[dict[str, Any]] # session_id, position, link_evidence
86 unified_workflow: dict[str, Any] # name, total_messages, span_hours
87 confidence: float
89 def to_dict(self) -> dict[str, Any]:
90 """Convert to dictionary for YAML serialization."""
91 return {
92 "link_id": self.link_id,
93 "sessions": self.sessions,
94 "unified_workflow": self.unified_workflow,
95 "confidence": self.confidence,
96 }
99@dataclass
100class EntityCluster:
101 """Cluster of messages sharing entities."""
103 cluster_id: str
104 primary_entities: list[str]
105 all_entities: set[str] = field(default_factory=set)
106 messages: list[dict[str, Any]] = field(default_factory=list)
107 span: dict[str, Any] | None = None
108 inferred_workflow: str | None = None
109 cohesion_score: float = 0.0
111 def to_dict(self) -> dict[str, Any]:
112 """Convert to dictionary for YAML serialization."""
113 return {
114 "cluster_id": self.cluster_id,
115 "primary_entities": self.primary_entities,
116 "all_entities": sorted(self.all_entities),
117 "messages": self.messages,
118 "span": self.span,
119 "inferred_workflow": self.inferred_workflow,
120 "cohesion_score": round(self.cohesion_score, 2),
121 }
124@dataclass
125class WorkflowBoundary:
126 """Boundary between workflows based on time gaps and entity overlap."""
128 msg_a: str
129 msg_b: str
130 time_gap_seconds: int
131 time_gap_weight: float
132 entity_overlap: float
133 final_boundary_score: float
134 is_boundary: bool
136 def to_dict(self) -> dict[str, Any]:
137 """Convert to dictionary for YAML serialization."""
138 return {
139 "between": {"msg_a": self.msg_a, "msg_b": self.msg_b},
140 "time_gap_seconds": self.time_gap_seconds,
141 "time_gap_weight": round(self.time_gap_weight, 2),
142 "entity_overlap": round(self.entity_overlap, 2),
143 "final_boundary_score": round(self.final_boundary_score, 2),
144 "is_boundary": self.is_boundary,
145 }
148@dataclass
149class Workflow:
150 """Identified multi-step workflow."""
152 workflow_id: str
153 name: str
154 pattern: str
155 pattern_confidence: float
156 messages: list[dict[str, Any]]
157 session_span: list[str]
158 entity_cluster: str | None = None
159 semantic_cluster: str | None = None
160 duration_minutes: int = 0
161 handoff_points: list[dict[str, Any]] = field(default_factory=list)
163 def to_dict(self) -> dict[str, Any]:
164 """Convert to dictionary for YAML serialization."""
165 return {
166 "workflow_id": self.workflow_id,
167 "name": self.name,
168 "pattern": self.pattern,
169 "pattern_confidence": round(self.pattern_confidence, 2),
170 "messages": self.messages,
171 "session_span": self.session_span,
172 "entity_cluster": self.entity_cluster,
173 "semantic_cluster": self.semantic_cluster,
174 "duration_minutes": self.duration_minutes,
175 "handoff_points": self.handoff_points,
176 }
179@dataclass
180class WorkflowAnalysis:
181 """Complete workflow analysis output."""
183 metadata: dict[str, Any]
184 session_links: list[SessionLink] = field(default_factory=list)
185 entity_clusters: list[EntityCluster] = field(default_factory=list)
186 workflow_boundaries: list[WorkflowBoundary] = field(default_factory=list)
187 workflows: list[Workflow] = field(default_factory=list)
188 handoff_analysis: dict[str, Any] | None = None
190 def to_dict(self) -> dict[str, Any]:
191 """Convert to dictionary for YAML serialization."""
192 return {
193 "analysis_metadata": self.metadata,
194 "session_links": [s.to_dict() for s in self.session_links],
195 "entity_clusters": [c.to_dict() for c in self.entity_clusters],
196 "workflow_boundaries": [b.to_dict() for b in self.workflow_boundaries],
197 "workflows": [w.to_dict() for w in self.workflows],
198 "handoff_analysis": self.handoff_analysis,
199 }
202# -----------------------------------------------------------------------------
203# Core Analysis Functions
204# -----------------------------------------------------------------------------
207def extract_entities(content: str) -> set[str]:
208 """Extract file paths, commands, and concepts from message content.
210 Args:
211 content: Message text content
213 Returns:
214 Set of extracted entities (file paths, commands, issue IDs, etc.)
215 """
216 entities: set[str] = set()
218 # File paths
219 entities.update(FILE_PATTERN.findall(content))
221 # Phase/module references
222 entities.update(PHASE_PATTERN.findall(content.lower()))
223 entities.update(MODULE_PATTERN.findall(content.lower()))
225 # Slash commands
226 entities.update(COMMAND_PATTERN.findall(content))
228 # Issue IDs (normalize to uppercase)
229 entities.update(match.upper() for match in ISSUE_PATTERN.findall(content))
231 return entities
234def calculate_boundary_weight(gap_seconds: int) -> float:
235 """Calculate workflow boundary weight based on time gap.
237 Args:
238 gap_seconds: Time gap between messages in seconds
240 Returns:
241 Boundary weight from 0.0 to 0.95
242 """
243 if gap_seconds < 30:
244 return 0.0
245 elif gap_seconds < 120:
246 return 0.1
247 elif gap_seconds < 300:
248 return 0.3
249 elif gap_seconds < 900:
250 return 0.5
251 elif gap_seconds < 1800:
252 return 0.7
253 elif gap_seconds < 7200:
254 return 0.85
255 else:
256 return 0.95
259def entity_overlap(entities_a: set[str], entities_b: set[str]) -> float:
260 """Calculate Jaccard similarity between two entity sets.
262 Args:
263 entities_a: First set of entities
264 entities_b: Second set of entities
266 Returns:
267 Jaccard similarity coefficient (0.0 to 1.0)
268 """
269 if not entities_a or not entities_b:
270 return 0.0
271 intersection = len(entities_a & entities_b)
272 union = len(entities_a | entities_b)
273 return intersection / union if union > 0 else 0.0
276def get_verb_class(content: str) -> str | None:
277 """Extract verb class from message content.
279 Args:
280 content: Message text content
282 Returns:
283 Verb class name or None if no match
284 """
285 content_lower = content.lower()
286 words = set(re.findall(r"\b\w+\b", content_lower))
288 for verb_class, verbs in VERB_CLASSES.items():
289 if words & verbs:
290 return verb_class
291 return None
294def semantic_similarity(
295 content_a: str,
296 content_b: str,
297 entities_a: set[str],
298 entities_b: set[str],
299 category_a: str | None,
300 category_b: str | None,
301) -> float:
302 """Calculate semantic similarity between two messages.
304 Uses weighted combination of:
305 - Keyword overlap (0.3)
306 - Verb class match (0.3)
307 - Entity overlap (0.3)
308 - Category match (0.1)
310 Args:
311 content_a: First message content
312 content_b: Second message content
313 entities_a: Entities from first message
314 entities_b: Entities from second message
315 category_a: Category of first message
316 category_b: Category of second message
318 Returns:
319 Similarity score (0.0 to 1.0)
320 """
321 # Keyword overlap (simple word-level Jaccard)
322 words_a = set(re.findall(r"\b[a-z]{3,}\b", content_a.lower()))
323 words_b = set(re.findall(r"\b[a-z]{3,}\b", content_b.lower()))
324 keyword_sim = len(words_a & words_b) / len(words_a | words_b) if words_a | words_b else 0.0
326 # Verb class similarity
327 verb_a = get_verb_class(content_a)
328 verb_b = get_verb_class(content_b)
329 verb_sim = 1.0 if verb_a and verb_a == verb_b else 0.0
331 # Entity overlap
332 entity_sim = entity_overlap(entities_a, entities_b)
334 # Category match
335 category_sim = 1.0 if category_a and category_a == category_b else 0.0
337 # Weighted combination
338 return keyword_sim * 0.3 + verb_sim * 0.3 + entity_sim * 0.3 + category_sim * 0.1
341# -----------------------------------------------------------------------------
342# Internal Analysis Functions
343# -----------------------------------------------------------------------------
346def _load_messages(messages_file: Path) -> list[dict[str, Any]]:
347 """Load messages from JSONL file."""
348 messages = []
349 with open(messages_file, encoding="utf-8") as f:
350 for line in f:
351 line = line.strip()
352 if line:
353 messages.append(json.loads(line))
354 return messages
357def _load_patterns(patterns_file: Path) -> dict[str, Any]:
358 """Load patterns from Step 1 YAML output."""
359 with open(patterns_file, encoding="utf-8") as f:
360 return yaml.safe_load(f) or {}
363def _group_by_session(messages: list[dict[str, Any]]) -> dict[str, list[dict[str, Any]]]:
364 """Group messages by session_id."""
365 sessions: dict[str, list[dict[str, Any]]] = {}
366 for msg in messages:
367 session_id = msg.get("session_id", "unknown")
368 if session_id not in sessions:
369 sessions[session_id] = []
370 sessions[session_id].append(msg)
371 return sessions
374def _detect_handoff(content: str) -> bool:
375 """Check if message indicates a session handoff."""
376 handoff_markers = [
377 "/ll:handoff",
378 "continue in new session",
379 "pick up in next session",
380 "resuming from",
381 "continuation of",
382 ]
383 content_lower = content.lower()
384 return any(marker in content_lower for marker in handoff_markers)
387def _link_sessions(sessions: dict[str, list[dict[str, Any]]]) -> list[SessionLink]:
388 """Identify sessions that are part of the same workflow."""
389 links: list[SessionLink] = []
390 session_ids = list(sessions.keys())
391 link_counter = 0
393 for i, session_a_id in enumerate(session_ids):
394 session_a = sessions[session_a_id]
395 if not session_a:
396 continue
398 # Extract session metadata
399 last_msg_a = session_a[-1] if session_a else {}
400 entities_a: set[str] = set()
401 for msg in session_a:
402 entities_a.update(extract_entities(msg.get("content", "")))
403 branch_a = last_msg_a.get("git_branch")
405 for session_b_id in session_ids[i + 1 :]:
406 session_b = sessions[session_b_id]
407 if not session_b:
408 continue
410 first_msg_b = session_b[0] if session_b else {}
411 entities_b: set[str] = set()
412 for msg in session_b:
413 entities_b.update(extract_entities(msg.get("content", "")))
414 branch_b = first_msg_b.get("git_branch")
416 # Calculate link score
417 score = 0.0
418 evidence: list[str] = []
420 # Same git branch (HIGH weight)
421 if branch_a and branch_a == branch_b:
422 score += 0.4
423 evidence.append("shared_branch")
425 # Explicit handoff marker (HIGH weight)
426 if any(_detect_handoff(msg.get("content", "")) for msg in session_a):
427 score += 0.4
428 evidence.append("handoff_detected")
430 # Shared entities (MEDIUM weight)
431 overlap = entity_overlap(entities_a, entities_b)
432 if overlap > 0.5:
433 score += 0.2
434 evidence.append("entity_overlap")
435 elif overlap > 0.3:
436 score += 0.1
437 evidence.append("partial_entity_overlap")
439 if score > 0.3:
440 link_counter += 1
442 # Calculate span
443 timestamps: list[datetime] = []
444 for msg in session_a + session_b:
445 ts_str = msg.get("timestamp", "")
446 if ts_str:
447 try:
448 ts = datetime.fromisoformat(ts_str.replace("Z", "+00:00"))
449 timestamps.append(ts)
450 except ValueError:
451 pass
453 span_hours = 0.0
454 if len(timestamps) >= 2:
455 span_hours = (max(timestamps) - min(timestamps)).total_seconds() / 3600
457 links.append(
458 SessionLink(
459 link_id=f"link-{link_counter:03d}",
460 sessions=[
461 {
462 "session_id": session_a_id,
463 "position": 1,
464 "link_evidence": evidence[0] if evidence else "score",
465 },
466 {
467 "session_id": session_b_id,
468 "position": 2,
469 "link_evidence": evidence[-1] if evidence else "score",
470 },
471 ],
472 unified_workflow={
473 "name": f"Linked workflow {link_counter}",
474 "total_messages": len(session_a) + len(session_b),
475 "span_hours": round(span_hours, 1),
476 },
477 confidence=min(score, 1.0),
478 )
479 )
481 return links
484def _cluster_by_entities(
485 messages: list[dict[str, Any]], overlap_threshold: float = 0.3
486) -> list[EntityCluster]:
487 """Cluster messages with significant entity overlap."""
488 clusters: list[EntityCluster] = []
489 cluster_counter = 0
491 for msg in messages:
492 content = msg.get("content", "")
493 msg_entities = extract_entities(content)
495 if not msg_entities:
496 continue
498 # Find matching cluster
499 matched_cluster = None
500 best_overlap = overlap_threshold
502 for cluster in clusters:
503 overlap = entity_overlap(msg_entities, cluster.all_entities)
504 if overlap > best_overlap:
505 best_overlap = overlap
506 matched_cluster = cluster
508 if matched_cluster:
509 matched_cluster.all_entities.update(msg_entities)
510 matched_cluster.messages.append(
511 {
512 "uuid": msg.get("uuid", ""),
513 "content": content[:80] + "..." if len(content) > 80 else content,
514 "entities_matched": sorted(msg_entities & matched_cluster.all_entities),
515 }
516 )
517 # Update cohesion score (average overlap of messages)
518 matched_cluster.cohesion_score = (
519 matched_cluster.cohesion_score * (len(matched_cluster.messages) - 1) + best_overlap
520 ) / len(matched_cluster.messages)
521 else:
522 cluster_counter += 1
523 # Create new cluster
524 primary = sorted(msg_entities)[:3] # Top 3 entities
525 cluster = EntityCluster(
526 cluster_id=f"cluster-{cluster_counter:03d}",
527 primary_entities=primary,
528 all_entities=msg_entities.copy(),
529 messages=[
530 {
531 "uuid": msg.get("uuid", ""),
532 "content": content[:80] + "..." if len(content) > 80 else content,
533 "entities_matched": sorted(msg_entities),
534 }
535 ],
536 cohesion_score=1.0,
537 )
538 clusters.append(cluster)
540 # Filter out single-message clusters
541 return [c for c in clusters if len(c.messages) >= 2]
544def _compute_boundaries(
545 messages: list[dict[str, Any]], boundary_threshold: float = 0.6
546) -> list[WorkflowBoundary]:
547 """Compute workflow boundaries between consecutive messages."""
548 boundaries: list[WorkflowBoundary] = []
550 # Sort by timestamp
551 sorted_msgs = sorted(messages, key=lambda m: m.get("timestamp", ""))
553 for i in range(len(sorted_msgs) - 1):
554 msg_a = sorted_msgs[i]
555 msg_b = sorted_msgs[i + 1]
557 # Parse timestamps
558 ts_a_str = msg_a.get("timestamp", "")
559 ts_b_str = msg_b.get("timestamp", "")
561 try:
562 ts_a = datetime.fromisoformat(ts_a_str.replace("Z", "+00:00"))
563 ts_b = datetime.fromisoformat(ts_b_str.replace("Z", "+00:00"))
564 gap_seconds = int((ts_b - ts_a).total_seconds())
565 except (ValueError, AttributeError):
566 gap_seconds = 0
568 # Calculate time gap weight
569 time_weight = calculate_boundary_weight(gap_seconds)
571 # Calculate entity overlap
572 entities_a = extract_entities(msg_a.get("content", ""))
573 entities_b = extract_entities(msg_b.get("content", ""))
574 overlap = entity_overlap(entities_a, entities_b)
576 # Adjust for entity overlap (reduce boundary weight if same topic)
577 final_score = time_weight
578 if overlap > 0.5:
579 final_score = max(0.0, time_weight - 0.3)
580 elif overlap > 0.3:
581 final_score = max(0.0, time_weight - 0.15)
583 is_boundary = final_score >= boundary_threshold
585 boundaries.append(
586 WorkflowBoundary(
587 msg_a=msg_a.get("uuid", ""),
588 msg_b=msg_b.get("uuid", ""),
589 time_gap_seconds=gap_seconds,
590 time_gap_weight=time_weight,
591 entity_overlap=overlap,
592 final_boundary_score=final_score,
593 is_boundary=is_boundary,
594 )
595 )
597 return boundaries
600def _get_message_category(msg_uuid: str, patterns: dict[str, Any]) -> str | None:
601 """Look up message category from Step 1 patterns."""
602 for category_info in patterns.get("category_distribution", []):
603 for example in category_info.get("example_messages", []):
604 if example.get("uuid") == msg_uuid:
605 category = category_info.get("category")
606 return category if isinstance(category, str) else None
607 return None
610def _detect_workflows(
611 messages: list[dict[str, Any]],
612 boundaries: list[WorkflowBoundary],
613 patterns: dict[str, Any],
614) -> list[Workflow]:
615 """Detect multi-step workflows using template matching."""
616 workflows: list[Workflow] = []
617 workflow_counter = 0
619 # Sort messages by timestamp
620 sorted_msgs = sorted(messages, key=lambda m: m.get("timestamp", ""))
622 # Build boundary index (msg_b uuid -> is_boundary)
623 boundary_before: dict[str, bool] = {}
624 for b in boundaries:
625 boundary_before[b.msg_b] = b.is_boundary
627 # Segment messages by boundaries
628 segments: list[list[dict[str, Any]]] = []
629 current_segment: list[dict[str, Any]] = []
631 for msg in sorted_msgs:
632 uuid = msg.get("uuid", "")
633 if boundary_before.get(uuid, False) and current_segment:
634 segments.append(current_segment)
635 current_segment = []
636 current_segment.append(msg)
638 if current_segment:
639 segments.append(current_segment)
641 # Match each segment against workflow templates
642 for segment in segments:
643 if len(segment) < 2:
644 continue
646 # Get categories for segment messages (from patterns)
647 segment_categories: list[str] = []
648 for msg in segment:
649 cat = _get_message_category(msg.get("uuid", ""), patterns)
650 if cat:
651 segment_categories.append(cat)
653 if len(segment_categories) < 2:
654 continue
656 # Find best matching template
657 best_match: tuple[str, float] | None = None
659 for template_name, template_cats in WORKFLOW_TEMPLATES.items():
660 # Check if template categories appear in sequence (allowing gaps)
661 template_idx = 0
662 matches = 0
664 for cat in segment_categories:
665 if template_idx < len(template_cats) and cat == template_cats[template_idx]:
666 matches += 1
667 template_idx += 1
669 if matches >= 2: # At least 2 template steps matched
670 confidence = matches / len(template_cats)
671 if best_match is None or confidence > best_match[1]:
672 best_match = (template_name, confidence)
674 if best_match:
675 workflow_counter += 1
677 # Calculate duration
678 timestamps: list[datetime] = []
679 for msg in segment:
680 ts_str = msg.get("timestamp", "")
681 if ts_str:
682 try:
683 ts = datetime.fromisoformat(ts_str.replace("Z", "+00:00"))
684 timestamps.append(ts)
685 except ValueError:
686 pass
688 duration_minutes = 0
689 if len(timestamps) >= 2:
690 duration_minutes = int((max(timestamps) - min(timestamps)).total_seconds() / 60)
692 # Get sessions
693 session_ids = list({msg.get("session_id", "") for msg in segment})
695 workflows.append(
696 Workflow(
697 workflow_id=f"wf-{workflow_counter:03d}",
698 name=f"Detected: {best_match[0]}",
699 pattern=best_match[0],
700 pattern_confidence=best_match[1],
701 messages=[
702 {
703 "uuid": msg.get("uuid", ""),
704 "category": _get_message_category(msg.get("uuid", ""), patterns),
705 "step": i + 1,
706 }
707 for i, msg in enumerate(segment)
708 ],
709 session_span=session_ids,
710 duration_minutes=duration_minutes,
711 )
712 )
714 return workflows
717# -----------------------------------------------------------------------------
718# Main API
719# -----------------------------------------------------------------------------
722def analyze_workflows(
723 messages_file: Path,
724 patterns_file: Path,
725 output_file: Path | None = None,
726) -> WorkflowAnalysis:
727 """Main entry point: analyze workflows from messages and patterns.
729 Args:
730 messages_file: Path to JSONL file with extracted user messages
731 patterns_file: Path to YAML file from Step 1 (workflow-pattern-analyzer)
732 output_file: Output path for step2-workflows.yaml (optional)
734 Returns:
735 WorkflowAnalysis with all analysis results
736 """
737 # Load inputs
738 messages = _load_messages(messages_file)
739 patterns = _load_patterns(patterns_file)
741 # Build metadata
742 metadata = {
743 "source_file": messages_file.name,
744 "patterns_file": patterns_file.name,
745 "message_count": len(messages),
746 "analysis_timestamp": datetime.now().isoformat(),
747 "module": "workflow-sequence-analyzer",
748 "version": "1.0",
749 }
751 # Run analysis pipeline
752 sessions = _group_by_session(messages)
753 session_links = _link_sessions(sessions)
754 entity_clusters = _cluster_by_entities(messages)
755 boundaries = _compute_boundaries(messages)
756 workflows = _detect_workflows(messages, boundaries, patterns)
758 # Compute handoff analysis
759 handoff_count = sum(
760 1
761 for link in session_links
762 if any(s.get("link_evidence") == "handoff_detected" for s in link.sessions)
763 )
765 handoff_analysis: dict[str, Any] = {
766 "total_handoffs": handoff_count,
767 "handoff_patterns": [
768 {"pattern": "explicit_handoff", "count": handoff_count},
769 {"pattern": "session_timeout", "count": len(session_links) - handoff_count},
770 ],
771 "recommendations": [],
772 }
774 if len(session_links) > handoff_count:
775 handoff_analysis["recommendations"].append(
776 "Consider using /ll:handoff for cleaner session transitions"
777 )
779 # Build result
780 analysis = WorkflowAnalysis(
781 metadata=metadata,
782 session_links=session_links,
783 entity_clusters=entity_clusters,
784 workflow_boundaries=boundaries,
785 workflows=workflows,
786 handoff_analysis=handoff_analysis,
787 )
789 # Write output if path provided
790 if output_file:
791 output_file = Path(output_file)
792 output_file.parent.mkdir(parents=True, exist_ok=True)
793 with open(output_file, "w", encoding="utf-8") as f:
794 yaml.dump(analysis.to_dict(), f, default_flow_style=False, sort_keys=False)
796 return analysis
799# -----------------------------------------------------------------------------
800# CLI
801# -----------------------------------------------------------------------------
804def main() -> int:
805 """Entry point for ll-workflows command.
807 Analyze workflows from user messages and Step 1 patterns.
809 Returns:
810 Exit code (0 = success, 1 = failure)
811 """
812 import argparse
813 import sys
815 parser = argparse.ArgumentParser(
816 description="Identify multi-step workflow patterns from user message history",
817 formatter_class=argparse.RawDescriptionHelpFormatter,
818 epilog="""
819Examples:
820 %(prog)s analyze --input messages.jsonl --patterns step1.yaml
821 %(prog)s analyze -i messages.jsonl -p patterns.yaml -o output.yaml
822 %(prog)s analyze --input .claude/user-messages.jsonl \\
823 --patterns .claude/workflow-analysis/step1-patterns.yaml
824""",
825 )
827 subparsers = parser.add_subparsers(dest="command", help="Available commands")
829 # analyze subcommand
830 analyze_parser = subparsers.add_parser(
831 "analyze",
832 help="Analyze workflows from messages and patterns",
833 )
834 analyze_parser.add_argument(
835 "-i",
836 "--input",
837 type=Path,
838 required=True,
839 help="Input JSONL file with user messages",
840 )
841 analyze_parser.add_argument(
842 "-p",
843 "--patterns",
844 type=Path,
845 required=True,
846 help="Input YAML file from Step 1 (workflow-pattern-analyzer)",
847 )
848 analyze_parser.add_argument(
849 "-o",
850 "--output",
851 type=Path,
852 default=None,
853 help="Output YAML file (default: .claude/workflow-analysis/step2-workflows.yaml)",
854 )
855 analyze_parser.add_argument(
856 "-v",
857 "--verbose",
858 action="store_true",
859 help="Print verbose progress information",
860 )
862 args = parser.parse_args()
864 if args.command is None:
865 parser.print_help()
866 return 1
868 if args.command == "analyze":
869 # Validate input files
870 if not args.input.exists():
871 print(f"Error: Input file not found: {args.input}", file=sys.stderr)
872 return 1
874 if not args.patterns.exists():
875 print(f"Error: Patterns file not found: {args.patterns}", file=sys.stderr)
876 return 1
878 # Set default output path
879 output_path = args.output
880 if output_path is None:
881 output_path = Path(".claude/workflow-analysis/step2-workflows.yaml")
883 if args.verbose:
884 print(f"Input: {args.input}")
885 print(f"Patterns: {args.patterns}")
886 print(f"Output: {output_path}")
888 try:
889 analysis = analyze_workflows(
890 messages_file=args.input,
891 patterns_file=args.patterns,
892 output_file=output_path,
893 )
895 # Print summary
896 print(f"Analyzed {analysis.metadata['message_count']} messages")
897 print(f"Found {len(analysis.session_links)} session links")
898 print(f"Found {len(analysis.entity_clusters)} entity clusters")
899 print(f"Detected {len(analysis.workflows)} workflows")
900 print(f"Output written to: {output_path}")
902 return 0
904 except Exception as e:
905 print(f"Error: {e}", file=sys.stderr)
906 return 1
908 return 1
911if __name__ == "__main__":
912 raise SystemExit(main())