Coverage for little_loops / workflow_sequence_analyzer.py: 0%

422 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-03-14 23:20 -0500

1"""ll-workflows: Identify multi-step workflow patterns from user message history. 

2 

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 

8 

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 

12 

13Usage as library: 

14 from little_loops.workflow_sequence_analyzer import analyze_workflows 

15 

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""" 

22 

23from __future__ import annotations 

24 

25import json 

26import re 

27import sys 

28from dataclasses import dataclass, field 

29from datetime import datetime 

30from pathlib import Path 

31from typing import Any 

32 

33import yaml 

34 

35__all__ = [ 

36 "analyze_workflows", 

37 "SessionLink", 

38 "EntityCluster", 

39 "WorkflowBoundary", 

40 "Workflow", 

41 "WorkflowAnalysis", 

42 "extract_entities", 

43 "calculate_boundary_weight", 

44 "entity_overlap", 

45 "get_verb_class", 

46 "semantic_similarity", 

47] 

48 

49# Module-level compiled regex patterns 

50FILE_PATTERN = re.compile(r"[\w./-]+\.(?:md|py|json|yaml|yml|js|ts|tsx|jsx|sh|toml)", re.IGNORECASE) 

51PHASE_PATTERN = re.compile(r"phase[- ]?\d+", re.IGNORECASE) 

52MODULE_PATTERN = re.compile(r"module[- ]?\d+", re.IGNORECASE) 

53COMMAND_PATTERN = re.compile(r"/[\w:-]+") 

54ISSUE_PATTERN = re.compile(r"(?:BUG|FEAT|ENH)-\d+", re.IGNORECASE) 

55 

56# Verb class taxonomy for semantic similarity 

57VERB_CLASSES: dict[str, set[str]] = { 

58 "deletion": {"remove", "delete", "drop", "eliminate", "clear", "clean"}, 

59 "modification": {"update", "change", "modify", "edit", "fix", "adjust", "revise"}, 

60 "creation": {"create", "add", "generate", "write", "make", "build"}, 

61 "search": {"find", "search", "locate", "where", "what", "which", "list"}, 

62 "verification": {"check", "verify", "validate", "confirm", "review", "ensure"}, 

63 "execution": {"run", "execute", "launch", "start", "invoke", "call"}, 

64} 

65 

66# Workflow templates: category sequences that indicate common patterns 

67WORKFLOW_TEMPLATES: dict[str, list[str]] = { 

68 "explore → modify → verify": ["file_search", "code_modification", "testing"], 

69 "create → refine → finalize": ["file_write", "code_modification", "git_operation"], 

70 "review → fix → commit": ["code_review", "code_modification", "git_operation"], 

71 "plan → implement → verify": ["planning", "code_modification", "testing"], 

72 "debug → fix → test": ["debugging", "code_modification", "testing"], 

73} 

74 

75 

76# ----------------------------------------------------------------------------- 

77# Data Classes 

78# ----------------------------------------------------------------------------- 

79 

80 

81@dataclass 

82class SessionLink: 

83 """Link between related sessions.""" 

84 

85 link_id: str 

86 sessions: list[dict[str, Any]] # session_id, position, link_evidence 

87 unified_workflow: dict[str, Any] # name, total_messages, span_hours 

88 confidence: float 

89 

90 def to_dict(self) -> dict[str, Any]: 

91 """Convert to dictionary for YAML serialization.""" 

92 return { 

93 "link_id": self.link_id, 

94 "sessions": self.sessions, 

95 "unified_workflow": self.unified_workflow, 

96 "confidence": self.confidence, 

97 } 

98 

99 

100@dataclass 

101class EntityCluster: 

102 """Cluster of messages sharing entities.""" 

103 

104 cluster_id: str 

105 primary_entities: list[str] 

106 all_entities: set[str] = field(default_factory=set) 

107 messages: list[dict[str, Any]] = field(default_factory=list) 

108 span: dict[str, Any] | None = None 

109 inferred_workflow: str | None = None 

110 cohesion_score: float = 0.0 

111 

112 def to_dict(self) -> dict[str, Any]: 

113 """Convert to dictionary for YAML serialization.""" 

114 return { 

115 "cluster_id": self.cluster_id, 

116 "primary_entities": self.primary_entities, 

117 "all_entities": sorted(self.all_entities), 

118 "messages": self.messages, 

119 "span": self.span, 

120 "inferred_workflow": self.inferred_workflow, 

121 "cohesion_score": round(self.cohesion_score, 2), 

122 } 

123 

124 

125@dataclass 

126class WorkflowBoundary: 

127 """Boundary between workflows based on time gaps and entity overlap.""" 

128 

129 msg_a: str 

130 msg_b: str 

131 time_gap_seconds: int 

132 time_gap_weight: float 

133 entity_overlap: float 

134 final_boundary_score: float 

135 is_boundary: bool 

136 

137 def to_dict(self) -> dict[str, Any]: 

138 """Convert to dictionary for YAML serialization.""" 

139 return { 

140 "between": {"msg_a": self.msg_a, "msg_b": self.msg_b}, 

141 "time_gap_seconds": self.time_gap_seconds, 

142 "time_gap_weight": round(self.time_gap_weight, 2), 

143 "entity_overlap": round(self.entity_overlap, 2), 

144 "final_boundary_score": round(self.final_boundary_score, 2), 

145 "is_boundary": self.is_boundary, 

146 } 

147 

148 

149@dataclass 

150class Workflow: 

151 """Identified multi-step workflow.""" 

152 

153 workflow_id: str 

154 name: str 

155 pattern: str 

156 pattern_confidence: float 

157 messages: list[dict[str, Any]] 

158 session_span: list[str] 

159 entity_cluster: str | None = None 

160 semantic_cluster: str | None = None 

161 duration_minutes: int = 0 

162 handoff_points: list[dict[str, Any]] = field(default_factory=list) 

163 

164 def to_dict(self) -> dict[str, Any]: 

165 """Convert to dictionary for YAML serialization.""" 

166 return { 

167 "workflow_id": self.workflow_id, 

168 "name": self.name, 

169 "pattern": self.pattern, 

170 "pattern_confidence": round(self.pattern_confidence, 2), 

171 "messages": self.messages, 

172 "session_span": self.session_span, 

173 "entity_cluster": self.entity_cluster, 

174 "semantic_cluster": self.semantic_cluster, 

175 "duration_minutes": self.duration_minutes, 

176 "handoff_points": self.handoff_points, 

177 } 

178 

179 

180@dataclass 

181class WorkflowAnalysis: 

182 """Complete workflow analysis output.""" 

183 

184 metadata: dict[str, Any] 

185 session_links: list[SessionLink] = field(default_factory=list) 

186 entity_clusters: list[EntityCluster] = field(default_factory=list) 

187 workflow_boundaries: list[WorkflowBoundary] = field(default_factory=list) 

188 workflows: list[Workflow] = field(default_factory=list) 

189 handoff_analysis: dict[str, Any] | None = None 

190 

191 def to_dict(self) -> dict[str, Any]: 

192 """Convert to dictionary for YAML serialization.""" 

193 return { 

194 "analysis_metadata": self.metadata, 

195 "session_links": [s.to_dict() for s in self.session_links], 

196 "entity_clusters": [c.to_dict() for c in self.entity_clusters], 

197 "workflow_boundaries": [b.to_dict() for b in self.workflow_boundaries], 

198 "workflows": [w.to_dict() for w in self.workflows], 

199 "handoff_analysis": self.handoff_analysis, 

200 } 

201 

202 

203# ----------------------------------------------------------------------------- 

204# Core Analysis Functions 

205# ----------------------------------------------------------------------------- 

206 

207 

208def extract_entities(content: str) -> set[str]: 

209 """Extract file paths, commands, and concepts from message content. 

210 

211 Args: 

212 content: Message text content 

213 

214 Returns: 

215 Set of extracted entities (file paths, commands, issue IDs, etc.) 

216 """ 

217 entities: set[str] = set() 

218 

219 # File paths 

220 entities.update(FILE_PATTERN.findall(content)) 

221 

222 # Phase/module references 

223 entities.update(PHASE_PATTERN.findall(content.lower())) 

224 entities.update(MODULE_PATTERN.findall(content.lower())) 

225 

226 # Slash commands 

227 entities.update(COMMAND_PATTERN.findall(content)) 

228 

229 # Issue IDs (normalize to uppercase) 

230 entities.update(match.upper() for match in ISSUE_PATTERN.findall(content)) 

231 

232 return entities 

233 

234 

235def calculate_boundary_weight(gap_seconds: int) -> float: 

236 """Calculate workflow boundary weight based on time gap. 

237 

238 Args: 

239 gap_seconds: Time gap between messages in seconds 

240 

241 Returns: 

242 Boundary weight from 0.0 to 0.95 

243 """ 

244 if gap_seconds < 30: 

245 return 0.0 

246 elif gap_seconds < 120: 

247 return 0.1 

248 elif gap_seconds < 300: 

249 return 0.3 

250 elif gap_seconds < 900: 

251 return 0.5 

252 elif gap_seconds < 1800: 

253 return 0.7 

254 elif gap_seconds < 7200: 

255 return 0.85 

256 else: 

257 return 0.95 

258 

259 

260def entity_overlap(entities_a: set[str], entities_b: set[str]) -> float: 

261 """Calculate Jaccard similarity between two entity sets. 

262 

263 Args: 

264 entities_a: First set of entities 

265 entities_b: Second set of entities 

266 

267 Returns: 

268 Jaccard similarity coefficient (0.0 to 1.0) 

269 """ 

270 if not entities_a or not entities_b: 

271 return 0.0 

272 intersection = len(entities_a & entities_b) 

273 union = len(entities_a | entities_b) 

274 return intersection / union if union > 0 else 0.0 

275 

276 

277def get_verb_class(content: str) -> str | None: 

278 """Extract verb class from message content. 

279 

280 Args: 

281 content: Message text content 

282 

283 Returns: 

284 Verb class name or None if no match 

285 """ 

286 content_lower = content.lower() 

287 words = set(re.findall(r"\b\w+\b", content_lower)) 

288 

289 for verb_class, verbs in VERB_CLASSES.items(): 

290 if words & verbs: 

291 return verb_class 

292 return None 

293 

294 

295def semantic_similarity( 

296 content_a: str, 

297 content_b: str, 

298 entities_a: set[str], 

299 entities_b: set[str], 

300 category_a: str | None, 

301 category_b: str | None, 

302) -> float: 

303 """Calculate semantic similarity between two messages. 

304 

305 Uses weighted combination of: 

306 - Keyword overlap (0.3) 

307 - Verb class match (0.3) 

308 - Entity overlap (0.3) 

309 - Category match (0.1) 

310 

311 Args: 

312 content_a: First message content 

313 content_b: Second message content 

314 entities_a: Entities from first message 

315 entities_b: Entities from second message 

316 category_a: Category of first message 

317 category_b: Category of second message 

318 

319 Returns: 

320 Similarity score (0.0 to 1.0) 

321 """ 

322 # Keyword overlap (simple word-level Jaccard) 

323 words_a = set(re.findall(r"\b[a-z]{3,}\b", content_a.lower())) 

324 words_b = set(re.findall(r"\b[a-z]{3,}\b", content_b.lower())) 

325 keyword_sim = len(words_a & words_b) / len(words_a | words_b) if words_a | words_b else 0.0 

326 

327 # Verb class similarity 

328 verb_a = get_verb_class(content_a) 

329 verb_b = get_verb_class(content_b) 

330 verb_sim = 1.0 if verb_a and verb_a == verb_b else 0.0 

331 

332 # Entity overlap 

333 entity_sim = entity_overlap(entities_a, entities_b) 

334 

335 # Category match 

336 category_sim = 1.0 if category_a and category_a == category_b else 0.0 

337 

338 # Weighted combination 

339 return keyword_sim * 0.3 + verb_sim * 0.3 + entity_sim * 0.3 + category_sim * 0.1 

340 

341 

342# ----------------------------------------------------------------------------- 

343# Internal Analysis Functions 

344# ----------------------------------------------------------------------------- 

345 

346 

347def _load_messages(messages_file: Path) -> list[dict[str, Any]]: 

348 """Load messages from JSONL file.""" 

349 messages = [] 

350 skipped = 0 

351 with open(messages_file, encoding="utf-8") as f: 

352 for line_num, raw_line in enumerate(f, 1): 

353 line = raw_line.strip() 

354 if not line: 

355 continue 

356 try: 

357 messages.append(json.loads(line)) 

358 except json.JSONDecodeError as e: 

359 skipped += 1 

360 print(f"Warning: skipping malformed line {line_num}: {e}", file=sys.stderr) 

361 if skipped: 

362 print(f"Warning: skipped {skipped} malformed line(s) in {messages_file}", file=sys.stderr) 

363 return messages 

364 

365 

366def _load_patterns(patterns_file: Path) -> dict[str, Any]: 

367 """Load patterns from Step 1 YAML output.""" 

368 with open(patterns_file, encoding="utf-8") as f: 

369 return yaml.safe_load(f) or {} 

370 

371 

372def _group_by_session(messages: list[dict[str, Any]]) -> dict[str, list[dict[str, Any]]]: 

373 """Group messages by session_id.""" 

374 sessions: dict[str, list[dict[str, Any]]] = {} 

375 for msg in messages: 

376 session_id = msg.get("session_id", "unknown") 

377 if session_id not in sessions: 

378 sessions[session_id] = [] 

379 sessions[session_id].append(msg) 

380 return sessions 

381 

382 

383def _detect_handoff(content: str) -> bool: 

384 """Check if message indicates a session handoff.""" 

385 handoff_markers = [ 

386 "/ll:handoff", 

387 "continue in new session", 

388 "pick up in next session", 

389 "resuming from", 

390 "continuation of", 

391 ] 

392 content_lower = content.lower() 

393 return any(marker in content_lower for marker in handoff_markers) 

394 

395 

396def _parse_timestamps(messages: list[dict[str, Any]]) -> list[datetime]: 

397 """Parse valid ISO timestamps from a list of messages, stripping timezone info.""" 

398 timestamps = [] 

399 for msg in messages: 

400 ts_str = msg.get("timestamp", "") 

401 if ts_str: 

402 try: 

403 ts = datetime.fromisoformat(ts_str.replace("Z", "+00:00")) 

404 if ts.tzinfo is not None: 

405 ts = ts.replace(tzinfo=None) 

406 timestamps.append(ts) 

407 except (ValueError, AttributeError, TypeError): 

408 pass 

409 return timestamps 

410 

411 

412def _link_sessions(sessions: dict[str, list[dict[str, Any]]]) -> list[SessionLink]: 

413 """Identify sessions that are part of the same workflow.""" 

414 links: list[SessionLink] = [] 

415 session_ids = list(sessions.keys()) 

416 link_counter = 0 

417 

418 for i, session_a_id in enumerate(session_ids): 

419 session_a = sessions[session_a_id] 

420 if not session_a: 

421 continue 

422 

423 # Extract session metadata 

424 last_msg_a = session_a[-1] if session_a else {} 

425 entities_a: set[str] = set() 

426 for msg in session_a: 

427 entities_a.update(extract_entities(msg.get("content", ""))) 

428 branch_a = last_msg_a.get("git_branch") 

429 

430 for session_b_id in session_ids[i + 1 :]: 

431 session_b = sessions[session_b_id] 

432 if not session_b: 

433 continue 

434 

435 first_msg_b = session_b[0] if session_b else {} 

436 entities_b: set[str] = set() 

437 for msg in session_b: 

438 entities_b.update(extract_entities(msg.get("content", ""))) 

439 branch_b = first_msg_b.get("git_branch") 

440 

441 # Calculate link score 

442 score = 0.0 

443 evidence: list[str] = [] 

444 

445 # Same git branch (HIGH weight) 

446 if branch_a and branch_a == branch_b: 

447 score += 0.4 

448 evidence.append("shared_branch") 

449 

450 # Explicit handoff marker (HIGH weight) 

451 if any(_detect_handoff(msg.get("content", "")) for msg in session_a): 

452 score += 0.4 

453 evidence.append("handoff_detected") 

454 

455 # Shared entities (MEDIUM weight) 

456 overlap = entity_overlap(entities_a, entities_b) 

457 if overlap > 0.5: 

458 score += 0.2 

459 evidence.append("entity_overlap") 

460 elif overlap > 0.3: 

461 score += 0.1 

462 evidence.append("partial_entity_overlap") 

463 

464 if score > 0.3: 

465 link_counter += 1 

466 

467 # Calculate span 

468 timestamps = _parse_timestamps(session_a + session_b) 

469 

470 span_hours = 0.0 

471 if len(timestamps) >= 2: 

472 try: 

473 span_hours = (max(timestamps) - min(timestamps)).total_seconds() / 3600 

474 except TypeError: 

475 span_hours = 0.0 

476 

477 links.append( 

478 SessionLink( 

479 link_id=f"link-{link_counter:03d}", 

480 sessions=[ 

481 { 

482 "session_id": session_a_id, 

483 "position": 1, 

484 "link_evidence": evidence[0] if evidence else "score", 

485 }, 

486 { 

487 "session_id": session_b_id, 

488 "position": 2, 

489 "link_evidence": evidence[-1] if evidence else "score", 

490 }, 

491 ], 

492 unified_workflow={ 

493 "name": f"Linked workflow {link_counter}", 

494 "total_messages": len(session_a) + len(session_b), 

495 "span_hours": round(span_hours, 1), 

496 "evidence": evidence, 

497 }, 

498 confidence=min(score, 1.0), 

499 ) 

500 ) 

501 

502 return links 

503 

504 

505def _cluster_by_entities( 

506 messages: list[dict[str, Any]], overlap_threshold: float = 0.3 

507) -> list[EntityCluster]: 

508 """Cluster messages with significant entity overlap.""" 

509 clusters: list[EntityCluster] = [] 

510 cluster_counter = 0 

511 

512 for msg in messages: 

513 content = msg.get("content", "") 

514 msg_entities = extract_entities(content) 

515 

516 if not msg_entities: 

517 continue 

518 

519 # Find matching cluster 

520 matched_cluster = None 

521 best_overlap = overlap_threshold 

522 

523 for cluster in clusters: 

524 overlap = entity_overlap(msg_entities, cluster.all_entities) 

525 if overlap > best_overlap: 

526 best_overlap = overlap 

527 matched_cluster = cluster 

528 

529 if matched_cluster: 

530 entities_matched = sorted(msg_entities & matched_cluster.all_entities) 

531 matched_cluster.all_entities.update(msg_entities) 

532 matched_cluster.messages.append( 

533 { 

534 "uuid": msg.get("uuid", ""), 

535 "content": content[:80] + "..." if len(content) > 80 else content, 

536 "entities_matched": entities_matched, 

537 } 

538 ) 

539 # Update cohesion score (average overlap of messages) 

540 matched_cluster.cohesion_score = ( 

541 matched_cluster.cohesion_score * (len(matched_cluster.messages) - 1) + best_overlap 

542 ) / len(matched_cluster.messages) 

543 else: 

544 cluster_counter += 1 

545 # Create new cluster 

546 primary = sorted(msg_entities)[:3] # Top 3 entities 

547 cluster = EntityCluster( 

548 cluster_id=f"cluster-{cluster_counter:03d}", 

549 primary_entities=primary, 

550 all_entities=msg_entities.copy(), 

551 messages=[ 

552 { 

553 "uuid": msg.get("uuid", ""), 

554 "content": content[:80] + "..." if len(content) > 80 else content, 

555 "entities_matched": sorted(msg_entities), 

556 } 

557 ], 

558 cohesion_score=1.0, 

559 ) 

560 clusters.append(cluster) 

561 

562 # Filter out single-message clusters 

563 return [c for c in clusters if len(c.messages) >= 2] 

564 

565 

566def _compute_boundaries( 

567 messages: list[dict[str, Any]], boundary_threshold: float = 0.6 

568) -> list[WorkflowBoundary]: 

569 """Compute workflow boundaries between consecutive messages.""" 

570 boundaries: list[WorkflowBoundary] = [] 

571 

572 # Sort by timestamp 

573 sorted_msgs = sorted(messages, key=lambda m: m.get("timestamp", "")) 

574 

575 for i in range(len(sorted_msgs) - 1): 

576 msg_a = sorted_msgs[i] 

577 msg_b = sorted_msgs[i + 1] 

578 

579 # Parse timestamps 

580 pair_timestamps = _parse_timestamps([msg_a, msg_b]) 

581 if len(pair_timestamps) == 2: 

582 gap_seconds = int((pair_timestamps[1] - pair_timestamps[0]).total_seconds()) 

583 else: 

584 gap_seconds = 0 

585 

586 # Calculate time gap weight 

587 time_weight = calculate_boundary_weight(gap_seconds) 

588 

589 # Calculate entity overlap 

590 entities_a = extract_entities(msg_a.get("content", "")) 

591 entities_b = extract_entities(msg_b.get("content", "")) 

592 overlap = entity_overlap(entities_a, entities_b) 

593 

594 # Adjust for entity overlap (reduce boundary weight if same topic) 

595 final_score = time_weight 

596 if overlap > 0.5: 

597 final_score = max(0.0, time_weight - 0.3) 

598 elif overlap > 0.3: 

599 final_score = max(0.0, time_weight - 0.15) 

600 

601 is_boundary = final_score >= boundary_threshold 

602 

603 boundaries.append( 

604 WorkflowBoundary( 

605 msg_a=msg_a.get("uuid", ""), 

606 msg_b=msg_b.get("uuid", ""), 

607 time_gap_seconds=gap_seconds, 

608 time_gap_weight=time_weight, 

609 entity_overlap=overlap, 

610 final_boundary_score=final_score, 

611 is_boundary=is_boundary, 

612 ) 

613 ) 

614 

615 return boundaries 

616 

617 

618def _get_message_category(msg_uuid: str, patterns: dict[str, Any]) -> str | None: 

619 """Look up message category from Step 1 patterns.""" 

620 for category_info in patterns.get("category_distribution", []): 

621 for example in category_info.get("example_messages", []): 

622 if example.get("uuid") == msg_uuid: 

623 category = category_info.get("category") 

624 return category if isinstance(category, str) else None 

625 return None 

626 

627 

628def _detect_workflows( 

629 messages: list[dict[str, Any]], 

630 boundaries: list[WorkflowBoundary], 

631 patterns: dict[str, Any], 

632) -> list[Workflow]: 

633 """Detect multi-step workflows using template matching.""" 

634 workflows: list[Workflow] = [] 

635 workflow_counter = 0 

636 

637 # Sort messages by timestamp 

638 sorted_msgs = sorted(messages, key=lambda m: m.get("timestamp", "")) 

639 

640 # Build boundary index (msg_b uuid -> is_boundary) 

641 boundary_before: dict[str, bool] = {} 

642 for b in boundaries: 

643 boundary_before[b.msg_b] = b.is_boundary 

644 

645 # Segment messages by boundaries 

646 segments: list[list[dict[str, Any]]] = [] 

647 current_segment: list[dict[str, Any]] = [] 

648 

649 for msg in sorted_msgs: 

650 uuid = msg.get("uuid", "") 

651 if boundary_before.get(uuid, False) and current_segment: 

652 segments.append(current_segment) 

653 current_segment = [] 

654 current_segment.append(msg) 

655 

656 if current_segment: 

657 segments.append(current_segment) 

658 

659 # Match each segment against workflow templates 

660 for segment in segments: 

661 if len(segment) < 2: 

662 continue 

663 

664 # Get categories for segment messages (from patterns) 

665 segment_categories: list[str] = [] 

666 for msg in segment: 

667 cat = _get_message_category(msg.get("uuid", ""), patterns) 

668 if cat: 

669 segment_categories.append(cat) 

670 

671 if len(segment_categories) < 2: 

672 continue 

673 

674 # Find best matching template 

675 best_match: tuple[str, float] | None = None 

676 

677 for template_name, template_cats in WORKFLOW_TEMPLATES.items(): 

678 # Check if template categories appear in sequence (allowing gaps) 

679 template_idx = 0 

680 matches = 0 

681 

682 for cat in segment_categories: 

683 if template_idx < len(template_cats) and cat == template_cats[template_idx]: 

684 matches += 1 

685 template_idx += 1 

686 

687 if matches >= 2: # At least 2 template steps matched 

688 confidence = matches / len(template_cats) 

689 if best_match is None or confidence > best_match[1]: 

690 best_match = (template_name, confidence) 

691 

692 if best_match: 

693 workflow_counter += 1 

694 

695 # Calculate duration 

696 timestamps = _parse_timestamps(segment) 

697 

698 duration_minutes = 0 

699 if len(timestamps) >= 2: 

700 try: 

701 duration_minutes = int((max(timestamps) - min(timestamps)).total_seconds() / 60) 

702 except TypeError: 

703 duration_minutes = 0 

704 

705 # Get sessions 

706 session_ids = list({msg.get("session_id", "") for msg in segment}) 

707 

708 workflows.append( 

709 Workflow( 

710 workflow_id=f"wf-{workflow_counter:03d}", 

711 name=f"Detected: {best_match[0]}", 

712 pattern=best_match[0], 

713 pattern_confidence=best_match[1], 

714 messages=[ 

715 { 

716 "uuid": msg.get("uuid", ""), 

717 "category": _get_message_category(msg.get("uuid", ""), patterns), 

718 "step": i + 1, 

719 } 

720 for i, msg in enumerate(segment) 

721 ], 

722 session_span=session_ids, 

723 duration_minutes=duration_minutes, 

724 ) 

725 ) 

726 

727 return workflows 

728 

729 

730# ----------------------------------------------------------------------------- 

731# Main API 

732# ----------------------------------------------------------------------------- 

733 

734 

735def analyze_workflows( 

736 messages_file: Path, 

737 patterns_file: Path, 

738 output_file: Path | None = None, 

739 overlap_threshold: float = 0.3, 

740 boundary_threshold: float = 0.6, 

741 verbose: bool = False, 

742 output_format: str = "yaml", 

743) -> WorkflowAnalysis: 

744 """Main entry point: analyze workflows from messages and patterns. 

745 

746 Args: 

747 messages_file: Path to JSONL file with extracted user messages 

748 patterns_file: Path to YAML file from Step 1 (workflow-pattern-analyzer) 

749 output_file: Output path for step2-workflows.yaml (optional) 

750 overlap_threshold: Minimum entity overlap to cluster messages together (default: 0.3) 

751 boundary_threshold: Minimum boundary score to split workflow segments (default: 0.6) 

752 verbose: Emit per-stage progress to stderr (default: False) 

753 output_format: Output serialization format, "yaml" or "json" (default: "yaml") 

754 

755 Returns: 

756 WorkflowAnalysis with all analysis results 

757 """ 

758 # Load inputs 

759 messages = _load_messages(messages_file) 

760 patterns = _load_patterns(patterns_file) 

761 

762 # Build metadata 

763 metadata = { 

764 "source_file": messages_file.name, 

765 "patterns_file": patterns_file.name, 

766 "message_count": len(messages), 

767 "analysis_timestamp": datetime.now().isoformat(), 

768 "module": "workflow-sequence-analyzer", 

769 "version": "1.0", 

770 } 

771 

772 # Run analysis pipeline 

773 sessions = _group_by_session(messages) 

774 if verbose: 

775 print(f"[1/4] Linking sessions across {len(sessions)} session(s)...", file=sys.stderr) 

776 session_links = _link_sessions(sessions) 

777 if verbose: 

778 print(f" → {len(session_links)} link(s) found", file=sys.stderr) 

779 if verbose: 

780 print("[2/4] Clustering by entities...", file=sys.stderr) 

781 entity_clusters = _cluster_by_entities(messages, overlap_threshold=overlap_threshold) 

782 if verbose: 

783 print(f" → {len(entity_clusters)} cluster(s) found", file=sys.stderr) 

784 if verbose: 

785 print("[3/4] Computing workflow boundaries...", file=sys.stderr) 

786 boundaries = _compute_boundaries(messages, boundary_threshold=boundary_threshold) 

787 if verbose: 

788 print(f" → {len(boundaries)} boundary/boundaries found", file=sys.stderr) 

789 if verbose: 

790 print("[4/4] Detecting workflows...", file=sys.stderr) 

791 workflows = _detect_workflows(messages, boundaries, patterns) 

792 if verbose: 

793 print(f" → {len(workflows)} workflow(s) detected", file=sys.stderr) 

794 

795 # Cross-reference: link workflows to entity clusters and populate handoff_points 

796 uuid_to_cluster: dict[str, str] = {} 

797 for cluster in entity_clusters: 

798 for msg in cluster.messages: 

799 uuid = msg.get("uuid", "") 

800 if uuid: 

801 uuid_to_cluster[uuid] = cluster.cluster_id 

802 

803 uuid_to_content: dict[str, str] = { 

804 m.get("uuid", ""): m.get("content", "") for m in messages if m.get("uuid", "") 

805 } 

806 

807 for workflow in workflows: 

808 cluster_votes: dict[str, int] = {} 

809 for msg in workflow.messages: 

810 cluster_id = uuid_to_cluster.get(msg.get("uuid", "")) 

811 if cluster_id: 

812 cluster_votes[cluster_id] = cluster_votes.get(cluster_id, 0) + 1 

813 if cluster_votes: 

814 workflow.entity_cluster = max(cluster_votes, key=cluster_votes.__getitem__) 

815 

816 for msg in workflow.messages: 

817 uuid = msg.get("uuid", "") 

818 if uuid and _detect_handoff(uuid_to_content.get(uuid, "")): 

819 workflow.handoff_points.append({"uuid": uuid, "type": "explicit_handoff"}) 

820 

821 # Compute handoff analysis 

822 handoff_count = sum( 

823 1 

824 for link in session_links 

825 if "handoff_detected" in link.unified_workflow.get("evidence", []) 

826 ) 

827 

828 handoff_analysis: dict[str, Any] = { 

829 "total_handoffs": handoff_count, 

830 "handoff_patterns": [ 

831 {"pattern": "explicit_handoff", "count": handoff_count}, 

832 {"pattern": "session_timeout", "count": len(session_links) - handoff_count}, 

833 ], 

834 "recommendations": [], 

835 } 

836 

837 if len(session_links) > handoff_count: 

838 handoff_analysis["recommendations"].append( 

839 "Consider using /ll:handoff for cleaner session transitions" 

840 ) 

841 

842 # Build result 

843 analysis = WorkflowAnalysis( 

844 metadata=metadata, 

845 session_links=session_links, 

846 entity_clusters=entity_clusters, 

847 workflow_boundaries=boundaries, 

848 workflows=workflows, 

849 handoff_analysis=handoff_analysis, 

850 ) 

851 

852 # Write output if path provided 

853 if output_file: 

854 output_file = Path(output_file) 

855 output_file.parent.mkdir(parents=True, exist_ok=True) 

856 with open(output_file, "w", encoding="utf-8") as f: 

857 if output_format == "json": 

858 json.dump(analysis.to_dict(), f, indent=2, default=str) 

859 else: 

860 yaml.dump(analysis.to_dict(), f, default_flow_style=False, sort_keys=False) 

861 

862 return analysis 

863 

864 

865# ----------------------------------------------------------------------------- 

866# CLI 

867# ----------------------------------------------------------------------------- 

868 

869 

870def main() -> int: 

871 """Entry point for ll-workflows command. 

872 

873 Analyze workflows from user messages and Step 1 patterns. 

874 

875 Returns: 

876 Exit code (0 = success, 1 = failure) 

877 """ 

878 import argparse 

879 import sys 

880 

881 parser = argparse.ArgumentParser( 

882 description="Identify multi-step workflow patterns from user message history", 

883 formatter_class=argparse.RawDescriptionHelpFormatter, 

884 epilog=""" 

885Examples: 

886 %(prog)s analyze --input messages.jsonl --patterns step1.yaml 

887 %(prog)s analyze -i messages.jsonl -p patterns.yaml -o output.yaml 

888 %(prog)s analyze --input .claude/user-messages.jsonl \\ 

889 --patterns .claude/workflow-analysis/step1-patterns.yaml 

890""", 

891 ) 

892 

893 subparsers = parser.add_subparsers(dest="command", help="Available commands") 

894 

895 # analyze subcommand 

896 analyze_parser = subparsers.add_parser( 

897 "analyze", 

898 help="Analyze workflows from messages and patterns", 

899 ) 

900 analyze_parser.add_argument( 

901 "-i", 

902 "--input", 

903 type=Path, 

904 required=True, 

905 help="Input JSONL file with user messages", 

906 ) 

907 analyze_parser.add_argument( 

908 "-p", 

909 "--patterns", 

910 type=Path, 

911 required=True, 

912 help="Input YAML file from Step 1 (workflow-pattern-analyzer)", 

913 ) 

914 analyze_parser.add_argument( 

915 "-o", 

916 "--output", 

917 type=Path, 

918 default=None, 

919 help="Output file (default: .claude/workflow-analysis/step2-workflows.yaml or .json)", 

920 ) 

921 analyze_parser.add_argument( 

922 "-f", 

923 "--format", 

924 choices=["yaml", "json"], 

925 default="yaml", 

926 help="Output format (default: yaml)", 

927 ) 

928 analyze_parser.add_argument( 

929 "-v", 

930 "--verbose", 

931 action="store_true", 

932 help="Print verbose progress information", 

933 ) 

934 analyze_parser.add_argument( 

935 "--overlap-threshold", 

936 type=float, 

937 default=0.3, 

938 metavar="FLOAT", 

939 help="Minimum entity overlap to cluster messages together (default: 0.3)", 

940 ) 

941 analyze_parser.add_argument( 

942 "--boundary-threshold", 

943 type=float, 

944 default=0.6, 

945 metavar="FLOAT", 

946 help="Minimum boundary score to split workflow segments (default: 0.6)", 

947 ) 

948 

949 args = parser.parse_args() 

950 

951 if args.command is None: 

952 parser.print_help() 

953 return 1 

954 

955 if args.command == "analyze": 

956 # Validate input files 

957 if not args.input.exists(): 

958 print(f"Error: Input file not found: {args.input}", file=sys.stderr) 

959 return 1 

960 

961 if not args.patterns.exists(): 

962 print(f"Error: Patterns file not found: {args.patterns}", file=sys.stderr) 

963 return 1 

964 

965 # Validate threshold ranges 

966 if not (0.0 <= args.overlap_threshold <= 1.0): 

967 print( 

968 f"Error: --overlap-threshold must be in [0.0, 1.0], got {args.overlap_threshold}", 

969 file=sys.stderr, 

970 ) 

971 return 1 

972 

973 if not (0.0 <= args.boundary_threshold <= 1.0): 

974 print( 

975 f"Error: --boundary-threshold must be in [0.0, 1.0], got {args.boundary_threshold}", 

976 file=sys.stderr, 

977 ) 

978 return 1 

979 

980 # Set default output path 

981 output_path = args.output 

982 if output_path is None: 

983 if args.format == "json": 

984 output_path = Path(".claude/workflow-analysis/step2-workflows.json") 

985 else: 

986 output_path = Path(".claude/workflow-analysis/step2-workflows.yaml") 

987 

988 if args.verbose: 

989 print(f"Input: {args.input}") 

990 print(f"Patterns: {args.patterns}") 

991 print(f"Output: {output_path}") 

992 

993 try: 

994 analysis = analyze_workflows( 

995 messages_file=args.input, 

996 patterns_file=args.patterns, 

997 output_file=output_path, 

998 overlap_threshold=args.overlap_threshold, 

999 boundary_threshold=args.boundary_threshold, 

1000 verbose=args.verbose, 

1001 output_format=args.format, 

1002 ) 

1003 

1004 if args.verbose: 

1005 print(f"Analyzed {analysis.metadata['message_count']} messages") 

1006 print(f"Found {len(analysis.session_links)} session links") 

1007 print(f"Found {len(analysis.entity_clusters)} entity clusters") 

1008 print(f"Detected {len(analysis.workflows)} workflows") 

1009 print(f"Output written to: {output_path}") 

1010 

1011 return 0 

1012 

1013 except Exception as e: 

1014 print(f"Error: {e}", file=sys.stderr) 

1015 return 1 

1016 

1017 return 1 

1018 

1019 

1020if __name__ == "__main__": 

1021 raise SystemExit(main())