empathy-framework 4.6.3__py3-none-any.whl → 4.6.5__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 (65) hide show
  1. {empathy_framework-4.6.3.dist-info → empathy_framework-4.6.5.dist-info}/METADATA +53 -11
  2. {empathy_framework-4.6.3.dist-info → empathy_framework-4.6.5.dist-info}/RECORD +32 -57
  3. empathy_llm_toolkit/agent_factory/crews/health_check.py +7 -4
  4. empathy_llm_toolkit/agent_factory/decorators.py +3 -2
  5. empathy_llm_toolkit/agent_factory/memory_integration.py +6 -2
  6. empathy_llm_toolkit/contextual_patterns.py +5 -2
  7. empathy_llm_toolkit/git_pattern_extractor.py +8 -4
  8. empathy_llm_toolkit/providers.py +4 -3
  9. empathy_os/__init__.py +1 -1
  10. empathy_os/cli/__init__.py +306 -0
  11. empathy_os/cli/__main__.py +26 -0
  12. empathy_os/cli/commands/__init__.py +8 -0
  13. empathy_os/cli/commands/inspection.py +48 -0
  14. empathy_os/cli/commands/memory.py +56 -0
  15. empathy_os/cli/commands/provider.py +86 -0
  16. empathy_os/cli/commands/utilities.py +94 -0
  17. empathy_os/cli/core.py +32 -0
  18. empathy_os/cli.py +18 -6
  19. empathy_os/cli_unified.py +19 -3
  20. empathy_os/memory/short_term.py +12 -2
  21. empathy_os/project_index/scanner.py +151 -49
  22. empathy_os/socratic/visual_editor.py +9 -4
  23. empathy_os/workflows/bug_predict.py +70 -1
  24. empathy_os/workflows/pr_review.py +6 -0
  25. empathy_os/workflows/security_audit.py +13 -0
  26. empathy_os/workflows/tier_tracking.py +50 -2
  27. wizards/discharge_summary_wizard.py +4 -2
  28. wizards/incident_report_wizard.py +4 -2
  29. empathy_os/meta_workflows/agent_creator 2.py +0 -254
  30. empathy_os/meta_workflows/builtin_templates 2.py +0 -567
  31. empathy_os/meta_workflows/cli_meta_workflows 2.py +0 -1551
  32. empathy_os/meta_workflows/form_engine 2.py +0 -304
  33. empathy_os/meta_workflows/intent_detector 2.py +0 -298
  34. empathy_os/meta_workflows/pattern_learner 2.py +0 -754
  35. empathy_os/meta_workflows/session_context 2.py +0 -398
  36. empathy_os/meta_workflows/template_registry 2.py +0 -229
  37. empathy_os/meta_workflows/workflow 2.py +0 -980
  38. empathy_os/orchestration/pattern_learner 2.py +0 -699
  39. empathy_os/orchestration/real_tools 2.py +0 -938
  40. empathy_os/socratic/__init__ 2.py +0 -273
  41. empathy_os/socratic/ab_testing 2.py +0 -969
  42. empathy_os/socratic/blueprint 2.py +0 -532
  43. empathy_os/socratic/cli 2.py +0 -689
  44. empathy_os/socratic/collaboration 2.py +0 -1112
  45. empathy_os/socratic/domain_templates 2.py +0 -916
  46. empathy_os/socratic/embeddings 2.py +0 -734
  47. empathy_os/socratic/engine 2.py +0 -729
  48. empathy_os/socratic/explainer 2.py +0 -663
  49. empathy_os/socratic/feedback 2.py +0 -767
  50. empathy_os/socratic/forms 2.py +0 -624
  51. empathy_os/socratic/generator 2.py +0 -716
  52. empathy_os/socratic/llm_analyzer 2.py +0 -635
  53. empathy_os/socratic/mcp_server 2.py +0 -751
  54. empathy_os/socratic/session 2.py +0 -306
  55. empathy_os/socratic/storage 2.py +0 -635
  56. empathy_os/socratic/success 2.py +0 -719
  57. empathy_os/socratic/visual_editor 2.py +0 -812
  58. empathy_os/socratic/web_ui 2.py +0 -925
  59. empathy_os/workflows/batch_processing 2.py +0 -310
  60. empathy_os/workflows/release_prep_crew 2.py +0 -968
  61. empathy_os/workflows/test_coverage_boost_crew 2.py +0 -848
  62. {empathy_framework-4.6.3.dist-info → empathy_framework-4.6.5.dist-info}/WHEEL +0 -0
  63. {empathy_framework-4.6.3.dist-info → empathy_framework-4.6.5.dist-info}/entry_points.txt +0 -0
  64. {empathy_framework-4.6.3.dist-info → empathy_framework-4.6.5.dist-info}/licenses/LICENSE +0 -0
  65. {empathy_framework-4.6.3.dist-info → empathy_framework-4.6.5.dist-info}/top_level.txt +0 -0
@@ -1,1112 +0,0 @@
1
- """Collaboration Features for Socratic Workflow Builder
2
-
3
- Enables multiple users to collaboratively refine workflow requirements
4
- and review generated workflows.
5
-
6
- Features:
7
- - Collaborative sessions with multiple participants
8
- - Comment and discussion threads
9
- - Voting on requirements and decisions
10
- - Change tracking and history
11
- - Conflict resolution
12
- - Real-time synchronization support
13
-
14
- Copyright 2026 Smart-AI-Memory
15
- Licensed under Fair Source License 0.9
16
- """
17
-
18
- from __future__ import annotations
19
-
20
- import hashlib
21
- import json
22
- import time
23
- from collections.abc import Callable
24
- from dataclasses import dataclass, field
25
- from datetime import datetime
26
- from enum import Enum
27
- from pathlib import Path
28
- from typing import Any
29
-
30
- # =============================================================================
31
- # DATA STRUCTURES
32
- # =============================================================================
33
-
34
-
35
- class ParticipantRole(Enum):
36
- """Roles for session participants."""
37
-
38
- OWNER = "owner" # Full control
39
- EDITOR = "editor" # Can edit and vote
40
- REVIEWER = "reviewer" # Can comment and vote
41
- VIEWER = "viewer" # Read-only access
42
-
43
-
44
- class CommentStatus(Enum):
45
- """Status of a comment."""
46
-
47
- OPEN = "open"
48
- RESOLVED = "resolved"
49
- WONT_FIX = "wont_fix"
50
-
51
-
52
- class VoteType(Enum):
53
- """Types of votes."""
54
-
55
- APPROVE = "approve"
56
- REJECT = "reject"
57
- ABSTAIN = "abstain"
58
-
59
-
60
- class ChangeType(Enum):
61
- """Types of changes tracked."""
62
-
63
- GOAL_SET = "goal_set"
64
- ANSWER_SUBMITTED = "answer_submitted"
65
- REQUIREMENT_ADDED = "requirement_added"
66
- REQUIREMENT_REMOVED = "requirement_removed"
67
- AGENT_ADDED = "agent_added"
68
- AGENT_REMOVED = "agent_removed"
69
- WORKFLOW_MODIFIED = "workflow_modified"
70
- COMMENT_ADDED = "comment_added"
71
- VOTE_CAST = "vote_cast"
72
-
73
-
74
- @dataclass
75
- class Participant:
76
- """A participant in a collaborative session."""
77
-
78
- user_id: str
79
- name: str
80
- email: str | None = None
81
- role: ParticipantRole = ParticipantRole.VIEWER
82
- joined_at: datetime = field(default_factory=datetime.now)
83
- last_active: datetime = field(default_factory=datetime.now)
84
- is_online: bool = False
85
-
86
- def to_dict(self) -> dict[str, Any]:
87
- return {
88
- "user_id": self.user_id,
89
- "name": self.name,
90
- "email": self.email,
91
- "role": self.role.value,
92
- "joined_at": self.joined_at.isoformat(),
93
- "last_active": self.last_active.isoformat(),
94
- "is_online": self.is_online,
95
- }
96
-
97
- @classmethod
98
- def from_dict(cls, data: dict[str, Any]) -> Participant:
99
- return cls(
100
- user_id=data["user_id"],
101
- name=data["name"],
102
- email=data.get("email"),
103
- role=ParticipantRole(data.get("role", "viewer")),
104
- joined_at=datetime.fromisoformat(data["joined_at"]),
105
- last_active=datetime.fromisoformat(data["last_active"]),
106
- is_online=data.get("is_online", False),
107
- )
108
-
109
-
110
- @dataclass
111
- class Comment:
112
- """A comment on a session or specific element."""
113
-
114
- comment_id: str
115
- author_id: str
116
- content: str
117
- target_type: str # "session", "answer", "agent", "stage", etc.
118
- target_id: str # ID of the target element
119
- status: CommentStatus = CommentStatus.OPEN
120
- parent_id: str | None = None # For threaded comments
121
- created_at: datetime = field(default_factory=datetime.now)
122
- updated_at: datetime = field(default_factory=datetime.now)
123
- reactions: dict[str, list[str]] = field(default_factory=dict) # emoji -> user_ids
124
-
125
- def to_dict(self) -> dict[str, Any]:
126
- return {
127
- "comment_id": self.comment_id,
128
- "author_id": self.author_id,
129
- "content": self.content,
130
- "target_type": self.target_type,
131
- "target_id": self.target_id,
132
- "status": self.status.value,
133
- "parent_id": self.parent_id,
134
- "created_at": self.created_at.isoformat(),
135
- "updated_at": self.updated_at.isoformat(),
136
- "reactions": self.reactions,
137
- }
138
-
139
- @classmethod
140
- def from_dict(cls, data: dict[str, Any]) -> Comment:
141
- return cls(
142
- comment_id=data["comment_id"],
143
- author_id=data["author_id"],
144
- content=data["content"],
145
- target_type=data["target_type"],
146
- target_id=data["target_id"],
147
- status=CommentStatus(data.get("status", "open")),
148
- parent_id=data.get("parent_id"),
149
- created_at=datetime.fromisoformat(data["created_at"]),
150
- updated_at=datetime.fromisoformat(data["updated_at"]),
151
- reactions=data.get("reactions", {}),
152
- )
153
-
154
-
155
- @dataclass
156
- class Vote:
157
- """A vote on a decision or requirement."""
158
-
159
- vote_id: str
160
- voter_id: str
161
- target_type: str # "requirement", "agent", "workflow", etc.
162
- target_id: str
163
- vote_type: VoteType
164
- comment: str = ""
165
- created_at: datetime = field(default_factory=datetime.now)
166
-
167
- def to_dict(self) -> dict[str, Any]:
168
- return {
169
- "vote_id": self.vote_id,
170
- "voter_id": self.voter_id,
171
- "target_type": self.target_type,
172
- "target_id": self.target_id,
173
- "vote_type": self.vote_type.value,
174
- "comment": self.comment,
175
- "created_at": self.created_at.isoformat(),
176
- }
177
-
178
- @classmethod
179
- def from_dict(cls, data: dict[str, Any]) -> Vote:
180
- return cls(
181
- vote_id=data["vote_id"],
182
- voter_id=data["voter_id"],
183
- target_type=data["target_type"],
184
- target_id=data["target_id"],
185
- vote_type=VoteType(data["vote_type"]),
186
- comment=data.get("comment", ""),
187
- created_at=datetime.fromisoformat(data["created_at"]),
188
- )
189
-
190
-
191
- @dataclass
192
- class Change:
193
- """A tracked change in the session."""
194
-
195
- change_id: str
196
- change_type: ChangeType
197
- author_id: str
198
- description: str
199
- before_value: Any = None
200
- after_value: Any = None
201
- created_at: datetime = field(default_factory=datetime.now)
202
-
203
- def to_dict(self) -> dict[str, Any]:
204
- return {
205
- "change_id": self.change_id,
206
- "change_type": self.change_type.value,
207
- "author_id": self.author_id,
208
- "description": self.description,
209
- "before_value": self.before_value,
210
- "after_value": self.after_value,
211
- "created_at": self.created_at.isoformat(),
212
- }
213
-
214
- @classmethod
215
- def from_dict(cls, data: dict[str, Any]) -> Change:
216
- return cls(
217
- change_id=data["change_id"],
218
- change_type=ChangeType(data["change_type"]),
219
- author_id=data["author_id"],
220
- description=data["description"],
221
- before_value=data.get("before_value"),
222
- after_value=data.get("after_value"),
223
- created_at=datetime.fromisoformat(data["created_at"]),
224
- )
225
-
226
-
227
- @dataclass
228
- class VotingResult:
229
- """Result of a voting round."""
230
-
231
- target_id: str
232
- total_votes: int
233
- approvals: int
234
- rejections: int
235
- abstentions: int
236
- is_approved: bool
237
- quorum_reached: bool
238
-
239
- @property
240
- def approval_rate(self) -> float:
241
- """Calculate approval rate (excluding abstentions)."""
242
- active_votes = self.approvals + self.rejections
243
- if active_votes == 0:
244
- return 0.0
245
- return self.approvals / active_votes
246
-
247
-
248
- # =============================================================================
249
- # COLLABORATIVE SESSION
250
- # =============================================================================
251
-
252
-
253
- @dataclass
254
- class CollaborativeSession:
255
- """A session with collaboration features enabled."""
256
-
257
- session_id: str
258
- base_session_id: str # ID of the underlying SocraticSession
259
- name: str
260
- description: str = ""
261
- participants: list[Participant] = field(default_factory=list)
262
- comments: list[Comment] = field(default_factory=list)
263
- votes: list[Vote] = field(default_factory=list)
264
- changes: list[Change] = field(default_factory=list)
265
- created_at: datetime = field(default_factory=datetime.now)
266
- updated_at: datetime = field(default_factory=datetime.now)
267
- require_approval: bool = True
268
- approval_threshold: float = 0.5 # 50% approval required
269
- quorum: float = 0.5 # 50% participation required
270
-
271
- def to_dict(self) -> dict[str, Any]:
272
- return {
273
- "session_id": self.session_id,
274
- "base_session_id": self.base_session_id,
275
- "name": self.name,
276
- "description": self.description,
277
- "participants": [p.to_dict() for p in self.participants],
278
- "comments": [c.to_dict() for c in self.comments],
279
- "votes": [v.to_dict() for v in self.votes],
280
- "changes": [c.to_dict() for c in self.changes],
281
- "created_at": self.created_at.isoformat(),
282
- "updated_at": self.updated_at.isoformat(),
283
- "require_approval": self.require_approval,
284
- "approval_threshold": self.approval_threshold,
285
- "quorum": self.quorum,
286
- }
287
-
288
- @classmethod
289
- def from_dict(cls, data: dict[str, Any]) -> CollaborativeSession:
290
- return cls(
291
- session_id=data["session_id"],
292
- base_session_id=data["base_session_id"],
293
- name=data["name"],
294
- description=data.get("description", ""),
295
- participants=[Participant.from_dict(p) for p in data.get("participants", [])],
296
- comments=[Comment.from_dict(c) for c in data.get("comments", [])],
297
- votes=[Vote.from_dict(v) for v in data.get("votes", [])],
298
- changes=[Change.from_dict(c) for c in data.get("changes", [])],
299
- created_at=datetime.fromisoformat(data["created_at"]),
300
- updated_at=datetime.fromisoformat(data["updated_at"]),
301
- require_approval=data.get("require_approval", True),
302
- approval_threshold=data.get("approval_threshold", 0.5),
303
- quorum=data.get("quorum", 0.5),
304
- )
305
-
306
-
307
- # =============================================================================
308
- # COLLABORATION MANAGER
309
- # =============================================================================
310
-
311
-
312
- class CollaborationManager:
313
- """Manages collaborative workflow sessions."""
314
-
315
- def __init__(self, storage_path: Path | str | None = None):
316
- """Initialize the manager.
317
-
318
- Args:
319
- storage_path: Path to persist collaboration data
320
- """
321
- if storage_path is None:
322
- storage_path = Path.home() / ".empathy" / "socratic" / "collaboration"
323
- self.storage_path = Path(storage_path)
324
- self.storage_path.mkdir(parents=True, exist_ok=True)
325
-
326
- self._sessions: dict[str, CollaborativeSession] = {}
327
- self._change_listeners: list[Callable[[Change], None]] = []
328
-
329
- self._load_sessions()
330
-
331
- def create_session(
332
- self,
333
- base_session_id: str,
334
- name: str,
335
- owner_id: str,
336
- owner_name: str,
337
- description: str = "",
338
- ) -> CollaborativeSession:
339
- """Create a new collaborative session.
340
-
341
- Args:
342
- base_session_id: ID of the underlying SocraticSession
343
- name: Session name
344
- owner_id: ID of the session owner
345
- owner_name: Name of the session owner
346
- description: Optional description
347
-
348
- Returns:
349
- The created session
350
- """
351
- session_id = hashlib.sha256(
352
- f"{base_session_id}:{time.time()}".encode()
353
- ).hexdigest()[:12]
354
-
355
- owner = Participant(
356
- user_id=owner_id,
357
- name=owner_name,
358
- role=ParticipantRole.OWNER,
359
- is_online=True,
360
- )
361
-
362
- session = CollaborativeSession(
363
- session_id=session_id,
364
- base_session_id=base_session_id,
365
- name=name,
366
- description=description,
367
- participants=[owner],
368
- )
369
-
370
- self._sessions[session_id] = session
371
- self._save_session(session)
372
-
373
- return session
374
-
375
- def get_session(self, session_id: str) -> CollaborativeSession | None:
376
- """Get a collaborative session by ID."""
377
- return self._sessions.get(session_id)
378
-
379
- def add_participant(
380
- self,
381
- session_id: str,
382
- user_id: str,
383
- name: str,
384
- email: str | None = None,
385
- role: ParticipantRole = ParticipantRole.REVIEWER,
386
- ) -> Participant | None:
387
- """Add a participant to a session.
388
-
389
- Args:
390
- session_id: Session ID
391
- user_id: User ID
392
- name: User name
393
- email: Optional email
394
- role: Participant role
395
-
396
- Returns:
397
- The added participant or None
398
- """
399
- session = self._sessions.get(session_id)
400
- if not session:
401
- return None
402
-
403
- # Check if already a participant
404
- existing = next((p for p in session.participants if p.user_id == user_id), None)
405
- if existing:
406
- return existing
407
-
408
- participant = Participant(
409
- user_id=user_id,
410
- name=name,
411
- email=email,
412
- role=role,
413
- )
414
- session.participants.append(participant)
415
- session.updated_at = datetime.now()
416
-
417
- self._save_session(session)
418
- return participant
419
-
420
- def update_participant_role(
421
- self,
422
- session_id: str,
423
- user_id: str,
424
- new_role: ParticipantRole,
425
- by_user_id: str,
426
- ) -> bool:
427
- """Update a participant's role.
428
-
429
- Args:
430
- session_id: Session ID
431
- user_id: User ID to update
432
- new_role: New role
433
- by_user_id: ID of user making the change
434
-
435
- Returns:
436
- True if successful
437
- """
438
- session = self._sessions.get(session_id)
439
- if not session:
440
- return False
441
-
442
- # Check permissions
443
- requester = next((p for p in session.participants if p.user_id == by_user_id), None)
444
- if not requester or requester.role != ParticipantRole.OWNER:
445
- return False
446
-
447
- participant = next((p for p in session.participants if p.user_id == user_id), None)
448
- if not participant:
449
- return False
450
-
451
- participant.role = new_role
452
- session.updated_at = datetime.now()
453
-
454
- self._save_session(session)
455
- return True
456
-
457
- def add_comment(
458
- self,
459
- session_id: str,
460
- author_id: str,
461
- content: str,
462
- target_type: str,
463
- target_id: str,
464
- parent_id: str | None = None,
465
- ) -> Comment | None:
466
- """Add a comment to a session.
467
-
468
- Args:
469
- session_id: Session ID
470
- author_id: Comment author ID
471
- content: Comment content
472
- target_type: Type of target element
473
- target_id: ID of target element
474
- parent_id: Optional parent comment ID for threading
475
-
476
- Returns:
477
- The created comment or None
478
- """
479
- session = self._sessions.get(session_id)
480
- if not session:
481
- return None
482
-
483
- # Verify author is a participant
484
- author = next((p for p in session.participants if p.user_id == author_id), None)
485
- if not author:
486
- return None
487
-
488
- comment_id = hashlib.sha256(
489
- f"{session_id}:{author_id}:{time.time()}".encode()
490
- ).hexdigest()[:12]
491
-
492
- comment = Comment(
493
- comment_id=comment_id,
494
- author_id=author_id,
495
- content=content,
496
- target_type=target_type,
497
- target_id=target_id,
498
- parent_id=parent_id,
499
- )
500
- session.comments.append(comment)
501
- session.updated_at = datetime.now()
502
-
503
- # Track change
504
- self._track_change(
505
- session,
506
- ChangeType.COMMENT_ADDED,
507
- author_id,
508
- f"Comment added on {target_type}",
509
- after_value={"comment_id": comment_id, "target": target_id},
510
- )
511
-
512
- self._save_session(session)
513
- return comment
514
-
515
- def resolve_comment(
516
- self,
517
- session_id: str,
518
- comment_id: str,
519
- by_user_id: str,
520
- status: CommentStatus = CommentStatus.RESOLVED,
521
- ) -> bool:
522
- """Resolve a comment.
523
-
524
- Args:
525
- session_id: Session ID
526
- comment_id: Comment ID
527
- by_user_id: User resolving the comment
528
- status: New status
529
-
530
- Returns:
531
- True if successful
532
- """
533
- session = self._sessions.get(session_id)
534
- if not session:
535
- return False
536
-
537
- comment = next((c for c in session.comments if c.comment_id == comment_id), None)
538
- if not comment:
539
- return False
540
-
541
- comment.status = status
542
- comment.updated_at = datetime.now()
543
- session.updated_at = datetime.now()
544
-
545
- self._save_session(session)
546
- return True
547
-
548
- def add_reaction(
549
- self,
550
- session_id: str,
551
- comment_id: str,
552
- user_id: str,
553
- emoji: str,
554
- ) -> bool:
555
- """Add a reaction to a comment.
556
-
557
- Args:
558
- session_id: Session ID
559
- comment_id: Comment ID
560
- user_id: User adding reaction
561
- emoji: Emoji reaction
562
-
563
- Returns:
564
- True if successful
565
- """
566
- session = self._sessions.get(session_id)
567
- if not session:
568
- return False
569
-
570
- comment = next((c for c in session.comments if c.comment_id == comment_id), None)
571
- if not comment:
572
- return False
573
-
574
- if emoji not in comment.reactions:
575
- comment.reactions[emoji] = []
576
-
577
- if user_id not in comment.reactions[emoji]:
578
- comment.reactions[emoji].append(user_id)
579
- session.updated_at = datetime.now()
580
- self._save_session(session)
581
-
582
- return True
583
-
584
- def cast_vote(
585
- self,
586
- session_id: str,
587
- voter_id: str,
588
- target_type: str,
589
- target_id: str,
590
- vote_type: VoteType,
591
- comment: str = "",
592
- ) -> Vote | None:
593
- """Cast a vote on a target.
594
-
595
- Args:
596
- session_id: Session ID
597
- voter_id: Voter ID
598
- target_type: Type of target
599
- target_id: ID of target
600
- vote_type: Type of vote
601
- comment: Optional comment
602
-
603
- Returns:
604
- The cast vote or None
605
- """
606
- session = self._sessions.get(session_id)
607
- if not session:
608
- return None
609
-
610
- # Verify voter is a participant with voting rights
611
- voter = next((p for p in session.participants if p.user_id == voter_id), None)
612
- if not voter or voter.role == ParticipantRole.VIEWER:
613
- return None
614
-
615
- # Check if already voted
616
- existing = next(
617
- (v for v in session.votes
618
- if v.voter_id == voter_id and v.target_type == target_type and v.target_id == target_id),
619
- None
620
- )
621
- if existing:
622
- # Update existing vote
623
- existing.vote_type = vote_type
624
- existing.comment = comment
625
- existing.created_at = datetime.now()
626
- session.updated_at = datetime.now()
627
- self._save_session(session)
628
- return existing
629
-
630
- vote_id = hashlib.sha256(
631
- f"{session_id}:{voter_id}:{target_id}:{time.time()}".encode()
632
- ).hexdigest()[:12]
633
-
634
- vote = Vote(
635
- vote_id=vote_id,
636
- voter_id=voter_id,
637
- target_type=target_type,
638
- target_id=target_id,
639
- vote_type=vote_type,
640
- comment=comment,
641
- )
642
- session.votes.append(vote)
643
- session.updated_at = datetime.now()
644
-
645
- # Track change
646
- self._track_change(
647
- session,
648
- ChangeType.VOTE_CAST,
649
- voter_id,
650
- f"{vote_type.value} vote on {target_type}",
651
- after_value={"target": target_id, "vote": vote_type.value},
652
- )
653
-
654
- self._save_session(session)
655
- return vote
656
-
657
- def get_voting_result(
658
- self,
659
- session_id: str,
660
- target_type: str,
661
- target_id: str,
662
- ) -> VotingResult | None:
663
- """Get voting results for a target.
664
-
665
- Args:
666
- session_id: Session ID
667
- target_type: Type of target
668
- target_id: ID of target
669
-
670
- Returns:
671
- VotingResult or None
672
- """
673
- session = self._sessions.get(session_id)
674
- if not session:
675
- return None
676
-
677
- # Get votes for this target
678
- votes = [
679
- v for v in session.votes
680
- if v.target_type == target_type and v.target_id == target_id
681
- ]
682
-
683
- # Count by type
684
- approvals = sum(1 for v in votes if v.vote_type == VoteType.APPROVE)
685
- rejections = sum(1 for v in votes if v.vote_type == VoteType.REJECT)
686
- abstentions = sum(1 for v in votes if v.vote_type == VoteType.ABSTAIN)
687
-
688
- # Calculate quorum
689
- eligible_voters = [
690
- p for p in session.participants
691
- if p.role != ParticipantRole.VIEWER
692
- ]
693
- participation_rate = len(votes) / len(eligible_voters) if eligible_voters else 0
694
- quorum_reached = participation_rate >= session.quorum
695
-
696
- # Calculate approval
697
- active_votes = approvals + rejections
698
- approval_rate = approvals / active_votes if active_votes > 0 else 0
699
- is_approved = quorum_reached and approval_rate >= session.approval_threshold
700
-
701
- return VotingResult(
702
- target_id=target_id,
703
- total_votes=len(votes),
704
- approvals=approvals,
705
- rejections=rejections,
706
- abstentions=abstentions,
707
- is_approved=is_approved,
708
- quorum_reached=quorum_reached,
709
- )
710
-
711
- def get_comments_for_target(
712
- self,
713
- session_id: str,
714
- target_type: str,
715
- target_id: str,
716
- include_resolved: bool = True,
717
- ) -> list[Comment]:
718
- """Get comments for a target.
719
-
720
- Args:
721
- session_id: Session ID
722
- target_type: Type of target
723
- target_id: ID of target
724
- include_resolved: Include resolved comments
725
-
726
- Returns:
727
- List of comments
728
- """
729
- session = self._sessions.get(session_id)
730
- if not session:
731
- return []
732
-
733
- comments = [
734
- c for c in session.comments
735
- if c.target_type == target_type and c.target_id == target_id
736
- ]
737
-
738
- if not include_resolved:
739
- comments = [c for c in comments if c.status == CommentStatus.OPEN]
740
-
741
- return sorted(comments, key=lambda c: c.created_at)
742
-
743
- def get_change_history(
744
- self,
745
- session_id: str,
746
- limit: int = 50,
747
- ) -> list[Change]:
748
- """Get change history for a session.
749
-
750
- Args:
751
- session_id: Session ID
752
- limit: Maximum changes to return
753
-
754
- Returns:
755
- List of changes (most recent first)
756
- """
757
- session = self._sessions.get(session_id)
758
- if not session:
759
- return []
760
-
761
- return sorted(
762
- session.changes,
763
- key=lambda c: c.created_at,
764
- reverse=True,
765
- )[:limit]
766
-
767
- def track_change(
768
- self,
769
- session_id: str,
770
- change_type: ChangeType,
771
- author_id: str,
772
- description: str,
773
- before_value: Any = None,
774
- after_value: Any = None,
775
- ):
776
- """Track a change in the session.
777
-
778
- Args:
779
- session_id: Session ID
780
- change_type: Type of change
781
- author_id: Author of the change
782
- description: Description of the change
783
- before_value: Value before change
784
- after_value: Value after change
785
- """
786
- session = self._sessions.get(session_id)
787
- if session:
788
- self._track_change(
789
- session, change_type, author_id, description,
790
- before_value, after_value
791
- )
792
- self._save_session(session)
793
-
794
- def add_change_listener(self, listener: Callable[[Change], None]):
795
- """Add a listener for changes.
796
-
797
- Args:
798
- listener: Callback function
799
- """
800
- self._change_listeners.append(listener)
801
-
802
- def remove_change_listener(self, listener: Callable[[Change], None]):
803
- """Remove a change listener.
804
-
805
- Args:
806
- listener: Callback function to remove
807
- """
808
- if listener in self._change_listeners:
809
- self._change_listeners.remove(listener)
810
-
811
- def _track_change(
812
- self,
813
- session: CollaborativeSession,
814
- change_type: ChangeType,
815
- author_id: str,
816
- description: str,
817
- before_value: Any = None,
818
- after_value: Any = None,
819
- ):
820
- """Internal method to track a change."""
821
- change_id = hashlib.sha256(
822
- f"{session.session_id}:{time.time()}".encode()
823
- ).hexdigest()[:12]
824
-
825
- change = Change(
826
- change_id=change_id,
827
- change_type=change_type,
828
- author_id=author_id,
829
- description=description,
830
- before_value=before_value,
831
- after_value=after_value,
832
- )
833
- session.changes.append(change)
834
-
835
- # Notify listeners
836
- for listener in self._change_listeners:
837
- try:
838
- listener(change)
839
- except Exception:
840
- pass
841
-
842
- def _save_session(self, session: CollaborativeSession):
843
- """Save a session to storage."""
844
- path = self.storage_path / f"{session.session_id}.json"
845
- with path.open("w") as f:
846
- json.dump(session.to_dict(), f, indent=2)
847
-
848
- def _load_sessions(self):
849
- """Load all sessions from storage."""
850
- for path in self.storage_path.glob("*.json"):
851
- try:
852
- with path.open("r") as f:
853
- data = json.load(f)
854
- session = CollaborativeSession.from_dict(data)
855
- self._sessions[session.session_id] = session
856
- except Exception:
857
- pass
858
-
859
- def list_sessions(self) -> list[CollaborativeSession]:
860
- """List all collaborative sessions."""
861
- return sorted(
862
- self._sessions.values(),
863
- key=lambda s: s.updated_at,
864
- reverse=True,
865
- )
866
-
867
- def get_user_sessions(self, user_id: str) -> list[CollaborativeSession]:
868
- """Get sessions for a specific user.
869
-
870
- Args:
871
- user_id: User ID
872
-
873
- Returns:
874
- List of sessions the user participates in
875
- """
876
- return [
877
- s for s in self._sessions.values()
878
- if any(p.user_id == user_id for p in s.participants)
879
- ]
880
-
881
-
882
- # =============================================================================
883
- # REAL-TIME SYNC SUPPORT
884
- # =============================================================================
885
-
886
-
887
- @dataclass
888
- class SyncEvent:
889
- """An event for real-time synchronization."""
890
-
891
- event_id: str
892
- session_id: str
893
- event_type: str
894
- payload: dict[str, Any]
895
- author_id: str
896
- timestamp: datetime = field(default_factory=datetime.now)
897
-
898
- def to_dict(self) -> dict[str, Any]:
899
- return {
900
- "event_id": self.event_id,
901
- "session_id": self.session_id,
902
- "event_type": self.event_type,
903
- "payload": self.payload,
904
- "author_id": self.author_id,
905
- "timestamp": self.timestamp.isoformat(),
906
- }
907
-
908
-
909
- class SyncAdapter:
910
- """Adapter for real-time synchronization.
911
-
912
- Override this class to integrate with your preferred
913
- real-time infrastructure (WebSocket, SSE, etc.).
914
- """
915
-
916
- def __init__(self, session_id: str):
917
- """Initialize the adapter.
918
-
919
- Args:
920
- session_id: Session to sync
921
- """
922
- self.session_id = session_id
923
- self._event_handlers: list[Callable[[SyncEvent], None]] = []
924
-
925
- def emit(self, event: SyncEvent):
926
- """Emit an event to all connected clients.
927
-
928
- Override this to implement actual network transmission.
929
- """
930
- for handler in self._event_handlers:
931
- try:
932
- handler(event)
933
- except Exception:
934
- pass
935
-
936
- def on_event(self, handler: Callable[[SyncEvent], None]):
937
- """Register an event handler.
938
-
939
- Args:
940
- handler: Callback for incoming events
941
- """
942
- self._event_handlers.append(handler)
943
-
944
- def create_event(
945
- self,
946
- event_type: str,
947
- payload: dict[str, Any],
948
- author_id: str,
949
- ) -> SyncEvent:
950
- """Create a sync event.
951
-
952
- Args:
953
- event_type: Type of event
954
- payload: Event data
955
- author_id: Author of the event
956
-
957
- Returns:
958
- Created SyncEvent
959
- """
960
- event_id = hashlib.sha256(
961
- f"{self.session_id}:{event_type}:{time.time()}".encode()
962
- ).hexdigest()[:12]
963
-
964
- return SyncEvent(
965
- event_id=event_id,
966
- session_id=self.session_id,
967
- event_type=event_type,
968
- payload=payload,
969
- author_id=author_id,
970
- )
971
-
972
-
973
- # =============================================================================
974
- # INVITATION MANAGEMENT
975
- # =============================================================================
976
-
977
-
978
- @dataclass
979
- class Invitation:
980
- """An invitation to join a collaborative session."""
981
-
982
- invite_id: str
983
- session_id: str
984
- inviter_id: str
985
- invitee_email: str
986
- role: ParticipantRole
987
- message: str = ""
988
- created_at: datetime = field(default_factory=datetime.now)
989
- expires_at: datetime | None = None
990
- accepted: bool = False
991
-
992
-
993
- class InvitationManager:
994
- """Manages invitations to collaborative sessions."""
995
-
996
- def __init__(self, collaboration_manager: CollaborationManager):
997
- """Initialize the manager.
998
-
999
- Args:
1000
- collaboration_manager: The collaboration manager
1001
- """
1002
- self.collab = collaboration_manager
1003
- self._invitations: dict[str, Invitation] = {}
1004
-
1005
- def create_invitation(
1006
- self,
1007
- session_id: str,
1008
- inviter_id: str,
1009
- invitee_email: str,
1010
- role: ParticipantRole = ParticipantRole.REVIEWER,
1011
- message: str = "",
1012
- expires_hours: int = 72,
1013
- ) -> Invitation | None:
1014
- """Create an invitation.
1015
-
1016
- Args:
1017
- session_id: Session ID
1018
- inviter_id: ID of user sending invite
1019
- invitee_email: Email of invitee
1020
- role: Role to assign
1021
- message: Optional message
1022
- expires_hours: Hours until expiration
1023
-
1024
- Returns:
1025
- Created invitation or None
1026
- """
1027
- session = self.collab.get_session(session_id)
1028
- if not session:
1029
- return None
1030
-
1031
- # Verify inviter has permission
1032
- inviter = next((p for p in session.participants if p.user_id == inviter_id), None)
1033
- if not inviter or inviter.role not in [ParticipantRole.OWNER, ParticipantRole.EDITOR]:
1034
- return None
1035
-
1036
- invite_id = hashlib.sha256(
1037
- f"{session_id}:{invitee_email}:{time.time()}".encode()
1038
- ).hexdigest()[:16]
1039
-
1040
- from datetime import timedelta
1041
- expires = datetime.now() + timedelta(hours=expires_hours)
1042
-
1043
- invitation = Invitation(
1044
- invite_id=invite_id,
1045
- session_id=session_id,
1046
- inviter_id=inviter_id,
1047
- invitee_email=invitee_email,
1048
- role=role,
1049
- message=message,
1050
- expires_at=expires,
1051
- )
1052
-
1053
- self._invitations[invite_id] = invitation
1054
- return invitation
1055
-
1056
- def accept_invitation(
1057
- self,
1058
- invite_id: str,
1059
- user_id: str,
1060
- user_name: str,
1061
- ) -> Participant | None:
1062
- """Accept an invitation.
1063
-
1064
- Args:
1065
- invite_id: Invitation ID
1066
- user_id: ID of accepting user
1067
- user_name: Name of accepting user
1068
-
1069
- Returns:
1070
- Added participant or None
1071
- """
1072
- invitation = self._invitations.get(invite_id)
1073
- if not invitation:
1074
- return None
1075
-
1076
- # Check expiration
1077
- if invitation.expires_at and datetime.now() > invitation.expires_at:
1078
- return None
1079
-
1080
- if invitation.accepted:
1081
- return None
1082
-
1083
- # Add participant
1084
- participant = self.collab.add_participant(
1085
- invitation.session_id,
1086
- user_id,
1087
- user_name,
1088
- email=invitation.invitee_email,
1089
- role=invitation.role,
1090
- )
1091
-
1092
- if participant:
1093
- invitation.accepted = True
1094
-
1095
- return participant
1096
-
1097
- def get_pending_invitations(self, session_id: str) -> list[Invitation]:
1098
- """Get pending invitations for a session.
1099
-
1100
- Args:
1101
- session_id: Session ID
1102
-
1103
- Returns:
1104
- List of pending invitations
1105
- """
1106
- now = datetime.now()
1107
- return [
1108
- inv for inv in self._invitations.values()
1109
- if inv.session_id == session_id
1110
- and not inv.accepted
1111
- and (inv.expires_at is None or inv.expires_at > now)
1112
- ]