File size: 19,511 Bytes
95cc8f6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 | """
Action Tracking System for TRuCAL
Tracks user actions, achievements, and progress through the experience.
"""
from typing import Dict, List, Optional, Any, Set, Tuple
from dataclasses import dataclass, field
from datetime import datetime, timedelta
import json
import os
from enum import Enum
import uuid
from .purpose_assessment import PurposeDimension
class ActionType(str, Enum):
"""Types of actions that can be tracked"""
REALM_ACTION = "realm_action"
PURPOSE_ACTION = "purpose_action"
ACHIEVEMENT = "achievement"
MILESTONE = "milestone"
DAILY = "daily"
WEEKLY = "weekly"
CHALLENGE = "challenge"
class ActionStatus(str, Enum):
"""Possible statuses for an action"""
PENDING = "pending"
IN_PROGRESS = "in_progress"
COMPLETED = "completed"
FAILED = "failed"
ABANDONED = "abandoned"
@dataclass
class ActionDefinition:
"""Definition of a trackable action"""
id: str
name: str
description: str
action_type: ActionType
purpose_dimensions: List[PurposeDimension]
xp_reward: int = 0
cooldown: Optional[timedelta] = None
prerequisites: List[str] = field(default_factory=list) # IDs of required actions
repeatable: bool = False
max_repeats: Optional[int] = None
hidden: bool = False
metadata: Dict[str, Any] = field(default_factory=dict)
@dataclass
class ActionInstance:
"""A specific instance of a user taking an action"""
id: str
action_id: str
user_id: str
status: ActionStatus = ActionStatus.PENDING
start_time: Optional[datetime] = None
end_time: Optional[datetime] = None
progress: float = 0.0 # 0.0 to 1.0
data: Dict[str, Any] = field(default_factory=dict) # Any additional data
created_at: datetime = field(default_factory=datetime.utcnow)
updated_at: datetime = field(default_factory=datetime.utcnow)
class ActionTracker:
"""Tracks user actions and achievements"""
def __init__(self, storage_path: Optional[str] = None):
self.actions: Dict[str, ActionDefinition] = {}
self.action_instances: Dict[str, Dict[str, List[ActionInstance]]] = {} # user_id -> action_id -> [instances]
self.completed_actions: Dict[str, Set[str]] = {} # user_id -> set of completed action IDs
self.storage_path = storage_path
# Load default actions and achievements
self._load_default_actions()
# Load existing data if storage path is provided
if storage_path and os.path.exists(storage_path):
self.load_data()
def _load_default_actions(self) -> None:
"""Load default action definitions"""
self.actions = {
# Daily actions
'daily_reflection': ActionDefinition(
id='daily_reflection',
name='Daily Reflection',
description='Spend a few moments reflecting on your day',
action_type=ActionType.DAILY,
purpose_dimensions=[PurposeDimension.GROWTH, PurposeDimension.SELF_EXPRESSION],
xp_reward=20,
cooldown=timedelta(hours=20), # Allow some flexibility in timing
repeatable=True
),
'daily_goal_setting': ActionDefinition(
id='daily_goal_setting',
name='Set Daily Intentions',
description='Set your intentions for the day',
action_type=ActionType.DAILY,
purpose_dimensions=[PurposeDimension.GROWTH, PurposeDimension.MASTERY],
xp_reward=15,
cooldown=timedelta(hours=20),
repeatable=True
),
# Purpose-aligned actions
'express_gratitude': ActionDefinition(
id='express_gratitude',
name='Express Gratitude',
description='Express gratitude for something or someone',
action_type=ActionType.PURPOSE_ACTION,
purpose_dimensions=[PurposeDimension.COMPASSION, PurposeDimension.HARMONY],
xp_reward=30
),
'help_others': ActionDefinition(
id='help_others',
name='Help Someone',
description='Offer help or support to someone in need',
action_type=ActionType.PURPOSE_ACTION,
purpose_dimensions=[PurposeDimension.COMPASSION, PurposeDimension.COMMUNITY],
xp_reward=50
),
'learn_new_skill': ActionDefinition(
id='learn_new_skill',
name='Learn Something New',
description='Spend time learning a new skill or concept',
action_type=ActionType.PURPOSE_ACTION,
purpose_dimensions=[PurposeDimension.GROWTH, PurposeDimension.MASTERY],
xp_reward=40
),
'stand_up_for_justice': ActionDefinition(
id='stand_up_for_justice',
name='Stand Up for Justice',
description='Take action to support a cause you believe in',
action_type=ActionType.PURPOSE_ACTION,
purpose_dimensions=[PurposeDimension.JUSTICE, PurposeDimension.COMMUNITY],
xp_reward=60
),
# Milestones
'first_action': ActionDefinition(
id='first_action',
name='First Step',
description='Complete your first action',
action_type=ActionType.MILESTONE,
purpose_dimensions=[],
xp_reward=100,
hidden=True
),
'purpose_aligned_week': ActionDefinition(
id='purpose_aligned_week',
name='Purposeful Week',
description='Complete purpose-aligned actions for 7 days in a row',
action_type=ActionType.MILESTONE,
purpose_dimensions=[],
xp_reward=200,
prerequisites=['first_action']
)
}
def load_data(self) -> None:
"""Load action tracking data from disk"""
if not self.storage_path or not os.path.exists(self.storage_path):
return
try:
with open(self.storage_path, 'r') as f:
data = json.load(f)
# Load action instances
self.action_instances = {
user_id: {
action_id: [
ActionInstance(
id=inst['id'],
action_id=inst['action_id'],
user_id=inst['user_id'],
status=ActionStatus(inst['status']),
start_time=datetime.fromisoformat(inst['start_time']) if inst.get('start_time') else None,
end_time=datetime.fromisoformat(inst['end_time']) if inst.get('end_time') else None,
progress=inst.get('progress', 0.0),
data=inst.get('data', {}),
created_at=datetime.fromisoformat(inst['created_at']),
updated_at=datetime.fromisoformat(inst['updated_at'])
)
for inst in instances
]
for action_id, instances in user_actions.items()
}
for user_id, user_actions in data.get('action_instances', {}).items()
}
# Load completed actions
self.completed_actions = {
user_id: set(actions)
for user_id, actions in data.get('completed_actions', {}).items()
}
except Exception as e:
print(f"Error loading action tracking data: {e}")
def save_data(self) -> None:
"""Save action tracking data to disk"""
if not self.storage_path:
return
try:
# Create directory if it doesn't exist
os.makedirs(os.path.dirname(os.path.abspath(self.storage_path)), exist_ok=True)
# Prepare data for serialization
data = {
'action_instances': {
user_id: {
action_id: [
{
'id': inst.id,
'action_id': inst.action_id,
'user_id': inst.user_id,
'status': inst.status.value,
'start_time': inst.start_time.isoformat() if inst.start_time else None,
'end_time': inst.end_time.isoformat() if inst.end_time else None,
'progress': inst.progress,
'data': inst.data,
'created_at': inst.created_at.isoformat(),
'updated_at': inst.updated_at.isoformat()
}
for inst in instances
]
for action_id, instances in user_actions.items()
}
for user_id, user_actions in self.action_instances.items()
},
'completed_actions': {
user_id: list(actions)
for user_id, actions in self.completed_actions.items()
}
}
with open(self.storage_path, 'w') as f:
json.dump(data, f, indent=2)
except Exception as e:
print(f"Error saving action tracking data: {e}")
def start_action(self, user_id: str, action_id: str, data: Optional[Dict[str, Any]] = None) -> Optional[ActionInstance]:
"""Start a new action instance"""
if action_id not in self.actions:
return None
action_def = self.actions[action_id]
now = datetime.utcnow()
# Check if action is on cooldown
if not self._can_perform_action(user_id, action_id):
return None
# Check prerequisites
if not self._check_prerequisites(user_id, action_def):
return None
# Create new action instance
instance = ActionInstance(
id=str(uuid.uuid4()),
action_id=action_id,
user_id=user_id,
status=ActionStatus.IN_PROGRESS,
start_time=now,
data=data or {},
updated_at=now
)
# Store the instance
if user_id not in self.action_instances:
self.action_instances[user_id] = {}
if action_id not in self.action_instances[user_id]:
self.action_instances[user_id][action_id] = []
self.action_instances[user_id][action_id].append(instance)
# Save data if storage path is configured
if self.storage_path:
self.save_data()
return instance
def complete_action(self, user_id: str, action_id: str, data: Optional[Dict[str, Any]] = None) -> Optional[Dict[str, Any]]:
"""Mark an action as completed"""
if user_id not in self.action_instances or action_id not in self.action_instances[user_id]:
return None
# Find the most recent in-progress instance
instances = self.action_instances[user_id][action_id]
instance = next((i for i in reversed(instances) if i.status == ActionStatus.IN_PROGRESS), None)
if not instance:
return None
# Update instance
now = datetime.utcnow()
instance.status = ActionStatus.COMPLETED
instance.end_time = now
instance.progress = 1.0
instance.updated_at = now
if data:
instance.data.update(data)
# Update completed actions
if user_id not in self.completed_actions:
self.completed_actions[user_id] = set()
self.completed_actions[user_id].add(action_id)
# Get action definition
action_def = self.actions.get(action_id)
xp_reward = action_def.xp_reward if action_def else 0
# Check for any achievements or unlocks
unlocks = self._check_achievements(user_id)
# Save data if storage path is configured
if self.storage_path:
self.save_data()
return {
'success': True,
'action_id': action_id,
'instance_id': instance.id,
'xp_earned': xp_reward,
'unlocks': unlocks
}
def _can_perform_action(self, user_id: str, action_id: str) -> bool:
"""Check if a user can perform an action (cooldown, etc.)"""
action_def = self.actions.get(action_id)
if not action_def:
return False
# Check cooldown
if action_def.cooldown and user_id in self.action_instances and action_id in self.action_instances[user_id]:
last_instance = next(
(i for i in reversed(self.action_instances[user_id][action_id])
if i.status == ActionStatus.COMPLETED),
None
)
if last_instance and last_instance.end_time:
time_since_last = datetime.utcnow() - last_instance.end_time
if time_since_last < action_def.cooldown:
return False
# Check max repeats
if not action_def.repeatable and action_id in self.completed_actions.get(user_id, set()):
return False
if action_def.max_repeats and action_id in self.action_instances.get(user_id, {}):
completed_count = sum(
1 for i in self.action_instances[user_id][action_id]
if i.status == ActionStatus.COMPLETED
)
if completed_count >= action_def.max_repeats:
return False
return True
def _check_prerequisites(self, user_id: str, action_def: ActionDefinition) -> bool:
"""Check if a user meets all prerequisites for an action"""
if not action_def.prerequisites:
return True
completed = self.completed_actions.get(user_id, set())
return all(prereq in completed for prereq in action_def.prerequisites)
def _check_achievements(self, user_id: str) -> List[Dict[str, Any]]:
"""Check for any achievements or unlocks based on completed actions"""
unlocks = []
# Check for first action achievement
if 'first_action' not in self.completed_actions.get(user_id, set()) and \
any(i.status == ActionStatus.COMPLETED for instances in self.action_instances.get(user_id, {}).values() for i in instances):
self.complete_action(user_id, 'first_action')
unlocks.append({
'type': 'achievement',
'id': 'first_action',
'name': 'First Step',
'description': 'You\'ve taken your first action!',
'xp_reward': self.actions['first_action'].xp_reward
})
# Check for purpose-aligned week achievement
if 'first_action' in self.completed_actions.get(user_id, set()) and \
'purpose_aligned_week' not in self.completed_actions.get(user_id, set()):
# Check for 7 days of purpose-aligned actions
# This is a simplified check - in a real implementation, you'd want to check
# for actions on 7 consecutive days
purpose_action_count = sum(
1 for action_id in self.completed_actions.get(user_id, set())
if action_id in self.actions and
any(dim in [PurposeDimension.GROWTH, PurposeDimension.COMMUNITY,
PurposeDimension.JUSTICE, PurposeDimension.COMPASSION]
for dim in self.actions[action_id].purpose_dimensions)
)
if purpose_action_count >= 7:
self.complete_action(user_id, 'purpose_aligned_week')
unlocks.append({
'type': 'achievement',
'id': 'purpose_aligned_week',
'name': 'Purposeful Week',
'description': 'You\'ve completed purpose-aligned actions for 7 days!',
'xp_reward': self.actions['purpose_aligned_week'].xp_reward
})
return unlocks
def get_user_progress(self, user_id: str) -> Dict[str, Any]:
"""Get a summary of a user's progress and achievements"""
completed = self.completed_actions.get(user_id, set())
total_actions = len([a for a in self.actions.values() if not a.hidden])
# Calculate XP total
xp_total = sum(
self.actions[action_id].xp_reward
for action_id in completed
if action_id in self.actions
)
# Get recent activity
recent_activity = []
if user_id in self.action_instances:
all_instances = [
instance
for action_instances in self.action_instances[user_id].values()
for instance in action_instances
if instance.status == ActionStatus.COMPLETED
]
recent_activity = sorted(
all_instances,
key=lambda x: x.end_time or x.updated_at,
reverse=True
)[:10] # Last 10 completed actions
# Get available actions (not completed or repeatable)
available_actions = [
action for action_id, action in self.actions.items()
if not action.hidden and
(action_id not in completed or action.repeatable) and
self._check_prerequisites(user_id, action) and
self._can_perform_action(user_id, action_id)
]
return {
'completed_actions': len(completed),
'total_actions': total_actions,
'xp_total': xp_total,
'level': (xp_total // 1000) + 1, # Simple leveling: 1000 XP per level
'recent_activity': [
{
'action_id': i.action_id,
'action_name': self.actions[i.action_id].name if i.action_id in self.actions else 'Unknown',
'completed_at': i.end_time.isoformat() if i.end_time else None,
'xp_earned': self.actions[i.action_id].xp_reward if i.action_id in self.actions else 0
}
for i in recent_activity
],
'available_actions': [
{
'id': a.id,
'name': a.name,
'description': a.description,
'xp_reward': a.xp_reward,
'purpose_dimensions': [d.value for d in a.purpose_dimensions]
}
for a in available_actions
]
}
|