|
| 1 | +"""TaskFlow audit infrastructure for tracking all actions. |
| 2 | +
|
| 3 | +Provides functions to: |
| 4 | +- Detect actor type (human vs agent) |
| 5 | +- Log actions with full context |
| 6 | +- Maintain audit trail for accountability |
| 7 | +""" |
| 8 | + |
| 9 | +from datetime import datetime |
| 10 | +from typing import Any, Literal |
| 11 | + |
| 12 | +from taskflow.models import AuditLog |
| 13 | +from taskflow.storage import Storage |
| 14 | + |
| 15 | + |
| 16 | +def get_actor_type(actor_id: str, storage: Storage) -> Literal["human", "agent"]: |
| 17 | + """Determine if an actor is human or agent. |
| 18 | +
|
| 19 | + Args: |
| 20 | + actor_id: Worker ID (e.g., @sarah, @claude-code) |
| 21 | + storage: Storage instance to look up worker |
| 22 | +
|
| 23 | + Returns: |
| 24 | + "human" or "agent" |
| 25 | + """ |
| 26 | + worker = storage.get_worker(actor_id) |
| 27 | + if worker is None: |
| 28 | + # Default to human if worker not found |
| 29 | + return "human" |
| 30 | + return worker.type |
| 31 | + |
| 32 | + |
| 33 | +def log_action( |
| 34 | + storage: Storage, |
| 35 | + action: str, |
| 36 | + actor_id: str, |
| 37 | + task_id: int | None = None, |
| 38 | + project_slug: str | None = None, |
| 39 | + context: dict[str, Any] | None = None, |
| 40 | +) -> AuditLog: |
| 41 | + """Log an action to the audit trail. |
| 42 | +
|
| 43 | + Creates an audit log entry and persists it to storage. |
| 44 | + Automatically determines actor type and generates unique ID. |
| 45 | +
|
| 46 | + Args: |
| 47 | + storage: Storage instance |
| 48 | + action: Action performed (e.g., "created", "started", "completed") |
| 49 | + actor_id: Worker ID who performed the action |
| 50 | + task_id: Optional task ID if action relates to a task |
| 51 | + project_slug: Optional project slug if action relates to a project |
| 52 | + context: Optional additional context (e.g., progress %, notes) |
| 53 | +
|
| 54 | + Returns: |
| 55 | + Created AuditLog entry |
| 56 | + """ |
| 57 | + # Determine actor type |
| 58 | + actor_type = get_actor_type(actor_id, storage) |
| 59 | + |
| 60 | + # Generate next ID |
| 61 | + existing_logs = storage.get_audit_logs() |
| 62 | + next_id = len(existing_logs) + 1 |
| 63 | + |
| 64 | + # Create audit log entry |
| 65 | + log = AuditLog( |
| 66 | + id=next_id, |
| 67 | + task_id=task_id, |
| 68 | + project_slug=project_slug, |
| 69 | + actor_id=actor_id, |
| 70 | + actor_type=actor_type, |
| 71 | + action=action, |
| 72 | + context=context or {}, |
| 73 | + timestamp=datetime.now(), |
| 74 | + ) |
| 75 | + |
| 76 | + # Persist to storage |
| 77 | + storage.add_audit_log(log) |
| 78 | + |
| 79 | + return log |
0 commit comments