-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbriefing.py
More file actions
3035 lines (2612 loc) · 120 KB
/
briefing.py
File metadata and controls
3035 lines (2612 loc) · 120 KB
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Briefing Generator - Daily briefing system for cross-project status
Synthesizes:
- Portfolio pulse (active projects, commits, blockers)
- Priority actions (top recommendations)
- Patterns noticed (activity trends)
- Waiting on (decisions needed)
"""
import inspect
import json
import os
import sys
from dataclasses import dataclass
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Dict, List, Optional
# Import existing tools
sys.path.insert(0, str(Path(__file__).parent.parent / "scripts"))
try:
from ai_intelligence import ProjectActivity, ProjectScanner
except ImportError:
ProjectScanner = None
ProjectActivity = None
try:
from goal_parser import Goal, GoalParser
except ImportError:
GoalParser = None
Goal = None
try:
from recommendation_engine import Recommendation, RecommendationEngine
except ImportError:
RecommendationEngine = None
Recommendation = None
try:
from intelligence.process_monitor import ProcessMonitor
except ImportError:
ProcessMonitor = None
try:
from integration.git_tracker import GitTracker, get_git_briefing
except ImportError:
GitTracker = None
get_git_briefing = None
try:
from learning import LearningSystem
except ImportError:
LearningSystem = None
try:
from portfolio_memory import PortfolioMemory
except ImportError:
PortfolioMemory = None
try:
from intelligence.session_manager import SessionManager
except ImportError:
SessionManager = None
try:
from batch.usage_optimizer import UsageOptimizer
except ImportError:
UsageOptimizer = None
try:
from metrics_tracker import MetricsTracker
except ImportError:
MetricsTracker = None
try:
from intelligence.bandwidth.contracts import ContractMetricsStore
except ImportError:
ContractMetricsStore = None
try:
from intelligence.bandwidth.queue_slo import check_queue_slo
except ImportError:
check_queue_slo = None
DEFAULT_BRIEFING_STYLE = {
"separator_width": 64,
"show_ascii_graphics": True,
"show_infographics": True,
"show_sparklines": True,
"progress_bar": {
"width": 10,
"filled_char": "#",
"empty_char": ".",
"left_bracket": "[",
"right_bracket": "]",
},
"sparkline_chars": "▁▂▃▄▅▆▇█",
}
def _load_briefing_style() -> Dict[str, Any]:
"""Load persistent briefing style contract from disk."""
style_path = Path(__file__).parent / "config" / "briefing_style.json"
style = dict(DEFAULT_BRIEFING_STYLE)
try:
if style_path.exists():
raw = json.loads(style_path.read_text(encoding="utf-8"))
if isinstance(raw, dict):
style.update({k: v for k, v in raw.items() if k in style})
if isinstance(raw.get("progress_bar"), dict):
pb = dict(style["progress_bar"])
pb.update(raw["progress_bar"])
style["progress_bar"] = pb
except Exception:
# Keep defaults if style file is malformed.
pass
return style
def _build_progress_bar(percent: int, style: Dict[str, Any]) -> str:
"""Build an ASCII progress bar using style config."""
pb = style.get("progress_bar", {})
width = max(1, int(pb.get("width", 10)))
filled_char = str(pb.get("filled_char", "#"))[:1]
empty_char = str(pb.get("empty_char", "."))[:1]
left = str(pb.get("left_bracket", "["))[:1]
right = str(pb.get("right_bracket", "]"))[:1]
pct = max(0, min(100, int(percent)))
filled = min(width, int(round((pct / 100) * width)))
return f"{left}{filled_char * filled}{empty_char * (width - filled)}{right}"
def _sparkline(values: List[float], charset: str) -> str:
"""Render mini trend chart from numeric values."""
if not values:
return ""
chars = charset or "▁▂▃▄▅▆▇█"
lo = min(values)
hi = max(values)
if hi <= lo:
return chars[0] * len(values)
span = hi - lo
out = []
last_idx = len(chars) - 1
for v in values:
idx = int(((v - lo) / span) * last_idx)
out.append(chars[max(0, min(last_idx, idx))])
return "".join(out)
def _compute_signal_quality(modified: int, untracked: int) -> str:
"""Compute signal quality from working-tree noise."""
dirty_total = int(modified) + int(untracked)
if dirty_total >= 75:
return "LOW"
if dirty_total >= 30:
return "MED"
return "HIGH"
def get_briefing_signal_quality(briefing: "BriefingData") -> Dict[str, int | str]:
"""Return signal quality and dirty-tree counts from briefing git summary."""
modified = 0
untracked = 0
if briefing.git_status and briefing.git_status.get("summary"):
gs = briefing.git_status["summary"]
modified = int(gs.get("uncommitted_changes", gs.get("working_tree", {}).get("modified", 0)))
untracked = int(gs.get("untracked_files", gs.get("working_tree", {}).get("untracked", 0)))
quality = _compute_signal_quality(modified, untracked)
return {
"quality": quality,
"modified": modified,
"untracked": untracked,
"dirty_total": modified + untracked,
}
def get_briefing_style_path() -> Path:
"""Get path to persistent briefing style config."""
return Path(__file__).parent / "config" / "briefing_style.json"
def get_briefing_style() -> Dict[str, Any]:
"""Get effective briefing style (defaults merged with file)."""
return _load_briefing_style()
def validate_briefing_style(style: Optional[Dict[str, Any]] = None) -> List[str]:
"""Validate briefing style and return list of errors (empty if valid)."""
data = style or _load_briefing_style()
errors: List[str] = []
if not isinstance(data.get("separator_width"), int) or data.get("separator_width", 0) < 20:
errors.append("separator_width must be an integer >= 20")
for key in ["show_ascii_graphics", "show_infographics", "show_sparklines"]:
if not isinstance(data.get(key), bool):
errors.append(f"{key} must be true/false")
pb = data.get("progress_bar")
if not isinstance(pb, dict):
errors.append("progress_bar must be an object")
else:
if not isinstance(pb.get("width"), int) or pb.get("width", 0) < 1:
errors.append("progress_bar.width must be an integer >= 1")
for char_key in ["filled_char", "empty_char", "left_bracket", "right_bracket"]:
val = pb.get(char_key)
if not isinstance(val, str) or len(val) != 1:
errors.append(f"progress_bar.{char_key} must be a single character")
sparkline_chars = data.get("sparkline_chars")
if not isinstance(sparkline_chars, str) or len(sparkline_chars) < 2:
errors.append("sparkline_chars must be a string with at least 2 characters")
return errors
@dataclass
class BriefingData:
"""Structured briefing data."""
# Portfolio pulse
active_projects: List[str]
recent_commits_24h: int
total_commits_7d: int
blockers: List[Dict[str, str]]
# Priority actions
priority_actions: List[Dict[str, Any]]
# Patterns noticed
patterns: List[str]
# Waiting on
waiting_on: List[str]
# Metadata
generated_at: datetime
# Optional fields
resource_status: Optional[Dict[str, Any]] = None
batch_queue_status: Optional[Dict[str, Any]] = None
git_status: Optional[Dict[str, Any]] = None
work_progress: Optional[Dict[str, Any]] = None # Work absorber status
project_snapshot: Optional[List[Dict[str, Any]]] = None # Top active projects with metrics
period: str = "24h"
# Enhanced intelligence fields
intelligence_metrics: Optional[Dict[str, Any]] = None # Learning system metrics
strategic_alignment: Optional[Dict[str, Any]] = None # Goal velocity, drift
temporal_context: Optional[Dict[str, Any]] = None # Day patterns, session continuity
cross_project_insights: Optional[Dict[str, Any]] = None # Related work, patterns
predictive_insights: Optional[Dict[str, Any]] = None # Predicted focus, optimal sequence
# Resource & Orchestration Intelligence (High-Value)
resource_intelligence: Optional[Dict[str, Any]] = None # AIO consumption, pacing
orchestration_advisory: Optional[Dict[str, Any]] = (
None # Agent recommendations, batch vs interactive
)
velocity_metrics: Optional[Dict[str, Any]] = None # ROI, time savings
# Overnight batch insights (surfaced from completed AI analysis tasks)
batch_insights: Optional[Dict[str, Any]] = None
bandwidth_contract_metrics: Optional[Dict[str, Any]] = None
queue_slo: Optional[Dict[str, Any]] = None
class BriefingGenerator:
"""Generate daily briefings from cross-project data."""
def __init__(self, root_dir: Optional[Path] = None):
if root_dir is None:
root_dir = Path(os.environ.get("CORTEX_ROOT_DIR", str(Path.cwd())))
self.root_dir = root_dir
# Initialize core tools
self.project_scanner = ProjectScanner(str(root_dir)) if ProjectScanner else None
self.goal_parser = GoalParser() if GoalParser else None
self.recommendation_engine = RecommendationEngine() if RecommendationEngine else None
# Initialize enhanced intelligence tools
self.learning_system = LearningSystem() if LearningSystem else None
self.portfolio_memory = PortfolioMemory() if PortfolioMemory else None
self.session_manager = SessionManager(root_dir) if SessionManager else None
# Initialize resource & orchestration tools
self.usage_optimizer = UsageOptimizer() if UsageOptimizer else None
self.metrics_tracker = MetricsTracker() if MetricsTracker else None
self.contract_metrics_store = ContractMetricsStore() if ContractMetricsStore else None
def generate_daily_briefing(self) -> BriefingData:
"""
Generate daily briefing with portfolio status and recommendations.
Returns:
BriefingData with all briefing sections
"""
# 1. Get project activity
project_activity = []
if self.project_scanner:
try:
repos = self.project_scanner.find_git_repos()
project_activity = [self.project_scanner.analyze_project(repo) for repo in repos]
except Exception as e:
print(f"Warning: Could not scan projects: {e}", file=sys.stderr)
# 2. Get goals
goals = []
if self.goal_parser:
try:
goals = self.goal_parser.parse()
except Exception as e:
print(f"Warning: Could not parse goals: {e}", file=sys.stderr)
# 3. Get recommendations
recommendations = []
if self.recommendation_engine:
try:
generate_fn = self.recommendation_engine.generate_recommendations
params = set(inspect.signature(generate_fn).parameters)
if "project_activity" in params:
recommendations = generate_fn(
project_activity=project_activity if project_activity else None,
limit=5,
)
elif "goals" in params or "context" in params:
recommendations = generate_fn(
goals=goals if goals else None,
context=(
{"project_activity": project_activity} if project_activity else None
),
limit=5,
)
elif "tasks" in params:
recommendations = generate_fn(limit=5)
else:
recommendations = generate_fn()
except Exception as e:
print(f"Warning: Could not generate recommendations: {e}", file=sys.stderr)
# 4. Get Git/GitHub status
git_status = None
if GitTracker:
try:
tracker = GitTracker(str(self.root_dir))
git_status = {
"summary": tracker.get_summary(),
"recommendations": tracker.get_recommendations(),
"formatted": tracker.format_for_briefing(),
}
except Exception as e:
print(f"Warning: Could not get Git status: {e}", file=sys.stderr)
# 5. Get resource status
resource_status = None
batch_queue_status = None
if ProcessMonitor:
try:
monitor = ProcessMonitor()
resource_status = monitor.get_status()
# Get batch queue statistics and task details
from intelligence.process_monitor import TaskState
batch_queue_status = monitor.batch_queue.get_queue_stats()
# Add detailed task lists
batch_queue_status["running_tasks"] = monitor.batch_queue.get_running_tasks()
batch_queue_status["scheduled_tasks"] = monitor.batch_queue.get_scheduled_tasks()[
:5
] # Next 5
batch_queue_status["pending_tasks"] = monitor.batch_queue.get_pending_tasks()[
:5
] # First 5
batch_queue_status["recent_completed"] = monitor.batch_queue.get_task_history(
limit=3, state=TaskState.COMPLETED
)
batch_queue_status["recent_failed"] = monitor.batch_queue.get_task_history(
limit=3, state=TaskState.FAILED
)
# Add V2a sprint batch status
try:
sys.path.insert(0, str(Path(__file__).parent / "batch"))
from v2a_sprint_orchestrator import V2aSprintOrchestrator
orchestrator = V2aSprintOrchestrator()
batch_queue_status["v2a_sprint"] = orchestrator.get_overall_status()
except Exception:
# V2a orchestrator not available or no V2a tasks
pass
except Exception as e:
# Sandbox-limited environments can block sysctl introspection.
# Suppress this expected warning to keep briefing output clean.
if "Operation not permitted" not in str(e):
print(f"Warning: Could not get resource status: {e}", file=sys.stderr)
# 5b. Get overnight batch insights from completed tasks
batch_insights = self._get_batch_insights()
# 6. Get work absorber status
work_progress = None
try:
from work_absorber import WorkAbsorber
absorber = WorkAbsorber()
# Get recent work summary
recent_items = absorber.get_recent_work(days=1)
all_items = absorber.get_recent_work(days=7)
drift_summary = absorber.get_drift_summary()
# Build work progress summary
work_progress = {
"items_24h": len(recent_items),
"items_7d": len(all_items),
"correlated_24h": sum(1 for i in recent_items if i.plan_step_id),
"orphaned_24h": sum(1 for i in recent_items if not i.plan_step_id),
"drifts_total": drift_summary.get("total", 0),
"drifts_by_type": dict(drift_summary.get("by_type", {})),
"recent_work": [
{"title": i.title, "project": i.project, "scope": i.scope}
for i in recent_items[:5]
],
}
except ImportError:
pass # Work absorber not available
except Exception as e:
print(f"Warning: Could not get work progress: {e}", file=sys.stderr)
# 7. Get enhanced intelligence (new sections)
intelligence_metrics = self._get_intelligence_metrics()
strategic_alignment = self._get_strategic_alignment(goals, project_activity)
temporal_context = self._get_temporal_context()
cross_project_insights = self._get_cross_project_insights(project_activity)
predictive_insights = self._get_predictive_insights(
project_activity, goals, temporal_context
)
# 8. Get resource & orchestration intelligence (HIGH-VALUE)
resource_intelligence = self._get_resource_intelligence()
orchestration_advisory = self._get_orchestration_advisory(
resource_intelligence, batch_queue_status, project_activity
)
velocity_metrics = self._get_velocity_metrics()
bandwidth_contract_metrics = self._get_bandwidth_contract_metrics()
queue_slo = self._get_queue_slo_metrics()
# 9. Build briefing sections
briefing = BriefingData(
active_projects=self._get_active_projects(project_activity),
recent_commits_24h=self._count_recent_commits(project_activity, hours=24),
total_commits_7d=self._count_recent_commits(project_activity, days=7),
blockers=self._get_blockers(project_activity, goals),
priority_actions=self._get_priority_actions(recommendations, goals),
patterns=self._detect_patterns(project_activity),
waiting_on=self._get_waiting_on(goals, project_activity),
resource_status=resource_status,
batch_queue_status=batch_queue_status,
git_status=git_status,
work_progress=work_progress,
project_snapshot=self._build_project_snapshot(project_activity),
generated_at=datetime.now(), # noqa: DTZ005
# Enhanced intelligence fields
intelligence_metrics=intelligence_metrics,
strategic_alignment=strategic_alignment,
temporal_context=temporal_context,
cross_project_insights=cross_project_insights,
predictive_insights=predictive_insights,
# Resource & Orchestration Intelligence
resource_intelligence=resource_intelligence,
orchestration_advisory=orchestration_advisory,
velocity_metrics=velocity_metrics,
# Overnight batch insights
batch_insights=batch_insights,
bandwidth_contract_metrics=bandwidth_contract_metrics,
queue_slo=queue_slo,
)
return briefing
def _get_active_projects(self, projects: List[ProjectActivity]) -> List[str]:
"""Get list of active project names."""
if not projects:
return []
# Active = has commits in last 7 days; dedupe by name and keep strongest signal.
by_name: Dict[str, ProjectActivity] = {}
for p in projects:
if p.commits_7d <= 0:
continue
existing = by_name.get(p.name)
if existing is None or p.commits_7d > existing.commits_7d:
by_name[p.name] = p
active = list(by_name.keys())
active.sort(key=lambda name: by_name[name].commits_7d, reverse=True)
return active
def _build_project_snapshot(self, projects: List[ProjectActivity]) -> List[Dict[str, Any]]:
"""Build top-project snapshot table rows for briefing display."""
if not projects:
return []
by_name: Dict[str, ProjectActivity] = {}
for p in projects:
existing = by_name.get(p.name)
if existing is None or p.commits_7d > existing.commits_7d:
by_name[p.name] = p
top = sorted(by_name.values(), key=lambda p: p.commits_7d, reverse=True)[:6]
max_commits = max((p.commits_7d for p in top), default=0)
rows: List[Dict[str, Any]] = []
for p in top:
# Relative trend buckets produce more informative variation.
if max_commits > 0 and p.commits_7d >= max_commits * 0.60:
trend = "hot"
elif max_commits > 0 and p.commits_7d >= max_commits * 0.25:
trend = "active"
elif p.commits_7d > 0:
trend = "steady"
else:
trend = "idle"
rows.append(
{
"project": p.name,
"commits_7d": p.commits_7d,
"uncommitted": p.uncommitted_changes,
"status": p.status,
"trend": trend,
}
)
return rows
def _count_recent_commits(
self,
projects: List[ProjectActivity],
hours: Optional[int] = None,
days: Optional[int] = None,
) -> int:
"""Count commits in recent time period."""
if not projects:
return 0
total = 0
now = datetime.now() # noqa: DTZ005
for project in projects:
if not project.last_commit_date:
continue
# Check if commit is within time window
if hours:
cutoff = now - timedelta(hours=hours)
if project.last_commit_date >= cutoff:
# Count all commits in 7d as proxy for 24h
# (we don't have 24h granularity in ProjectActivity)
total += max(1, project.commits_7d // 7)
elif days:
total += project.commits_7d if days <= 7 else project.commits_30d
return total
def _get_blockers(
self, projects: List[ProjectActivity], goals: List[Goal]
) -> List[Dict[str, str]]:
"""Get all current blockers from projects and goals."""
blockers = []
# Project blockers
if projects:
for project in projects:
if project.blockers and project.status in ["active", "recent"]:
for blocker in project.blockers:
blockers.append(
{
"project": project.name,
"blocker": blocker,
"source": "project",
}
)
# Goal blockers
if goals:
for goal in goals:
if goal.status == "blocked" and goal.project:
blocker_text = f"{goal.title}"
if goal.blockers:
blocker_text = goal.blockers[0]
blockers.append(
{
"project": goal.project,
"blocker": blocker_text,
"source": "goal",
}
)
return blockers
def _get_priority_actions(
self, recommendations: List[Recommendation], goals: List[Goal]
) -> List[Dict[str, Any]]:
"""Get top 5 priority actions from recommendations and goals with detailed info."""
actions = []
seen_titles = set() # Track titles to avoid duplicates
def normalize_title(title: str) -> str:
"""Normalize title for deduplication."""
import re
# Remove project prefix (e.g., "cortex: " or "vortex-backend: ")
normalized = re.sub(r"^[^:]+:\s*", "", title.lower())
# Remove parenthetical content (e.g., "(feat/branch-name)")
normalized = re.sub(r"\([^)]*\)", "", normalized)
# Remove punctuation
normalized = re.sub(r"[^\w\s]", "", normalized)
# Normalize common variations
normalized = normalized.replace("complete", "finish")
normalized = normalized.replace("pr 2", "pr2")
# Remove extra whitespace
normalized = " ".join(normalized.split())
return normalized.strip()
# Add recommendations first
if recommendations:
for rec in recommendations[:3]:
title = rec.action_title if hasattr(rec, "action_title") else rec.title
norm_title = normalize_title(title)
if norm_title in seen_titles:
continue
seen_titles.add(norm_title)
# Handle priority as int, enum, or string
priority = rec.priority
if isinstance(priority, int):
priority_str = "HIGH" if priority > 70 else "MEDIUM" if priority > 40 else "LOW"
elif hasattr(priority, "value"):
priority_str = priority.value.upper()
else:
priority_str = str(priority).upper()
related_projects = getattr(rec, "related_projects", None) or []
rationale = getattr(rec, "rationale", None) or getattr(rec, "description", "")
action = {
"title": title,
"priority": priority_str,
"project": related_projects[0] if related_projects else "General",
"rationale": rationale,
"source": "recommendation",
"steps": getattr(rec, "steps", []) or [],
"estimated_effort": getattr(rec, "estimated_effort", None),
"estimated_impact": getattr(rec, "estimated_impact", None),
"confidence": getattr(rec, "confidence", None),
}
actions.append(action)
# Fill remaining with high-priority goals (avoiding duplicates)
if goals:
priority_goals = [
g for g in goals if g.priority == "A" and g.status in ["pending", "in_progress"]
]
for goal in priority_goals:
if len(actions) >= 5:
break
norm_title = normalize_title(goal.title)
if norm_title in seen_titles:
continue
seen_titles.add(norm_title)
action = {
"title": goal.title,
"priority": "HIGH",
"project": goal.project or "General",
"rationale": goal.description[:150] if goal.description else "",
"source": "goal",
"steps": goal.actions[:3] if goal.actions else [],
"success_criteria": goal.success_criteria,
"estimated_effort": getattr(goal, "estimated_effort", None),
"completion_percentage": getattr(goal, "completion_percentage", 0),
}
actions.append(action)
return actions[:5]
def _detect_patterns(self, projects: List[ProjectActivity]) -> List[str]:
"""Detect activity patterns and trends."""
patterns = []
if not projects:
return patterns
# 1. Most productive project (dedupe by name to avoid double counting)
by_name: Dict[str, ProjectActivity] = {}
for p in projects:
if p.commits_7d <= 0:
continue
existing = by_name.get(p.name)
if existing is None or p.commits_7d > existing.commits_7d:
by_name[p.name] = p
active_projects = list(by_name.values())
if active_projects:
most_active = max(active_projects, key=lambda p: p.commits_7d)
patterns.append(
f"{most_active.name} momentum: {most_active.commits_7d} commits this week"
)
# 2. Multi-project activity
if len(active_projects) >= 3:
patterns.append(
f"Multi-project sprint: {len(active_projects)} projects active this week"
)
# 3. Dormant projects awakening
recently_awakened = [
p for p in projects if p.commits_7d > 0 and p.commits_30d <= p.commits_7d + 1
]
if recently_awakened:
patterns.append(f"Renewed focus on {recently_awakened[0].name}")
# 4. Consistency patterns (commits every day vs burst)
steady_projects = [p for p in active_projects if p.commits_7d >= 5 and p.commits_7d <= 10]
if steady_projects:
patterns.append(f"Steady progress on {steady_projects[0].name} (daily commits)")
# 5. Burst activity
burst_projects = [p for p in active_projects if p.commits_7d >= 15]
if burst_projects:
patterns.append(
f"Sprint on {burst_projects[0].name} ({burst_projects[0].commits_7d} commits)"
)
return patterns[:3] # Top 3 patterns
def _get_waiting_on(self, goals: List[Goal], projects: List[ProjectActivity]) -> List[str]:
"""Get list of things waiting on user decisions."""
waiting = []
# 1. Blocked goals
if goals:
blocked_goals = [g for g in goals if g.status == "blocked"]
for goal in blocked_goals:
if goal.blockers:
waiting.append(f"{goal.project or 'Project'}: {goal.blockers[0]}")
else:
waiting.append(f"{goal.project or 'Project'}: {goal.title}")
# 2. Missing .env files (API keys needed)
if projects:
for project in projects:
if "Missing .env file" in project.blockers:
waiting.append(f"{project.name}: Environment configuration needed")
# 3. Uncommitted changes (decisions to commit or not)
if projects:
uncommitted = [p for p in projects if p.uncommitted_changes > 5]
for project in uncommitted[:2]: # Top 2
waiting.append(
f"{project.name}: {project.uncommitted_changes} uncommitted changes to review"
)
return waiting[:4] # Top 4 items
def _get_intelligence_metrics(self) -> Optional[Dict[str, Any]]:
"""Get learning system metrics for briefing intelligence."""
if not self.learning_system:
return None
try:
metrics = self.learning_system.get_learning_metrics()
patterns = self.learning_system.get_outcome_patterns()
# Find best and worst performing recommendation types
best_type = None
worst_type = None
if patterns:
sorted_patterns = sorted(
[(k, v) for k, v in patterns.items() if v.get("followed", 0) >= 3],
key=lambda x: x[1].get("success_rate", 0),
reverse=True,
)
if sorted_patterns:
best_type = {
"type": sorted_patterns[0][0],
"success_rate": sorted_patterns[0][1].get("success_rate", 0),
"count": sorted_patterns[0][1].get("followed", 0),
}
if len(sorted_patterns) > 1:
worst_type = {
"type": sorted_patterns[-1][0],
"success_rate": sorted_patterns[-1][1].get("success_rate", 0),
"count": sorted_patterns[-1][1].get("followed", 0),
}
return {
"recommendation_accuracy": metrics.recommendation_accuracy,
"total_outcomes": metrics.total_outcomes,
"followed_count": metrics.followed_count,
"success_rate": metrics.success_rate,
"confidence_calibration": metrics.confidence_calibration,
"best_performing_type": best_type,
"worst_performing_type": worst_type,
"has_sufficient_data": metrics.total_outcomes >= 10,
}
except Exception as e:
print(f"Warning: Could not get intelligence metrics: {e}", file=sys.stderr)
return None
def _get_strategic_alignment(
self, goals: List[Goal], project_activity: List[ProjectActivity]
) -> Optional[Dict[str, Any]]:
"""Analyze strategic alignment: goal velocity, drift detection."""
if not goals:
return None
try:
# Calculate goal completion velocity
completed_goals = [g for g in goals if g.status == "completed"]
in_progress_goals = [g for g in goals if g.status == "in_progress"]
pending_goals = [g for g in goals if g.status == "pending"]
blocked_goals = [g for g in goals if g.status == "blocked"]
total_goals = len(goals)
completion_rate = len(completed_goals) / total_goals if total_goals > 0 else 0
# Analyze priority distribution
high_priority = [g for g in goals if g.priority == "A"]
high_priority_completed = [g for g in high_priority if g.status == "completed"]
high_priority_blocked = [g for g in high_priority if g.status == "blocked"]
# Detect strategic drift: high priority goals blocked or stalled
drift_indicators = []
if len(high_priority_blocked) > 0:
drift_indicators.append(f"{len(high_priority_blocked)} high-priority goals blocked")
if len(high_priority) > 0 and len(high_priority_completed) / len(high_priority) < 0.3:
drift_indicators.append("Low completion rate on high-priority goals")
# Project focus alignment: are commits happening on priority projects?
priority_projects = set(g.project for g in high_priority if g.project)
active_project_names = (
set(p.name for p in project_activity if p.commits_7d > 0)
if project_activity
else set()
)
aligned_projects = priority_projects & active_project_names
unaligned_active = active_project_names - priority_projects
if unaligned_active and priority_projects:
drift_indicators.append(
f"Activity on non-priority projects: {', '.join(list(unaligned_active)[:2])}"
)
# Goal velocity insight
velocity_status = "healthy"
if len(blocked_goals) > len(in_progress_goals):
velocity_status = "blocked"
elif len(pending_goals) > len(completed_goals) + len(in_progress_goals):
velocity_status = "backlog_growing"
return {
"total_goals": total_goals,
"completed": len(completed_goals),
"in_progress": len(in_progress_goals),
"pending": len(pending_goals),
"blocked": len(blocked_goals),
"completion_rate": completion_rate,
"high_priority_total": len(high_priority),
"high_priority_completed": len(high_priority_completed),
"velocity_status": velocity_status,
"drift_indicators": drift_indicators,
"aligned_projects": list(aligned_projects),
"has_strategic_drift": len(drift_indicators) > 0,
}
except Exception as e:
print(f"Warning: Could not analyze strategic alignment: {e}", file=sys.stderr)
return None
def _get_temporal_context(self) -> Optional[Dict[str, Any]]:
"""Get temporal context: day patterns, session continuity."""
try:
now = datetime.now() # noqa: DTZ005
day_of_week = now.strftime("%A")
hour = now.hour
# Day-based patterns and suggestions
day_patterns = {
"Monday": {
"pattern": "week_start",
"suggestion": "Good day for planning and high-priority tasks",
"energy": "fresh_start",
},
"Tuesday": {
"pattern": "deep_work",
"suggestion": "Peak productivity day - tackle complex problems",
"energy": "high",
},
"Wednesday": {
"pattern": "mid_week",
"suggestion": "Continue momentum on in-progress work",
"energy": "sustained",
},
"Thursday": {
"pattern": "delivery_prep",
"suggestion": "Focus on completing tasks before week end",
"energy": "focused",
},
"Friday": {
"pattern": "week_close",
"suggestion": "Wrap up, commit changes, plan next week",
"energy": "winding_down",
},
"Saturday": {
"pattern": "weekend_optional",
"suggestion": "Optional: exploration, learning, or rest",
"energy": "relaxed",
},
"Sunday": {
"pattern": "week_prep",
"suggestion": "Optional: review upcoming week priorities",
"energy": "preparatory",
},
}
# Time of day context
time_context = "morning" if hour < 12 else "afternoon" if hour < 17 else "evening"
time_suggestions = {
"morning": "Best for deep work and complex tasks",
"afternoon": "Good for meetings, reviews, and lighter tasks",
"evening": "Consider wrapping up and documenting progress",
}
# Get session continuity from session manager
session_context = None
last_focus = None
if self.session_manager:
try:
ctx = self.session_manager.load_session_context(max_age_hours=24)
if ctx:
session_context = {
"project": ctx.project,
"current_focus": ctx.current_focus,
"recent_work": (ctx.recent_work[:3] if ctx.recent_work else []),
"active_goals": (ctx.active_goals[:3] if ctx.active_goals else []),
}
last_focus = ctx.current_focus
except Exception:
pass
return {
"day_of_week": day_of_week,
"time_of_day": time_context,
"hour": hour,
"day_pattern": day_patterns.get(day_of_week, {}),
"time_suggestion": time_suggestions.get(time_context, ""),
"session_continuity": session_context,
"last_focus": last_focus,
"is_weekend": day_of_week in ["Saturday", "Sunday"],
}
except Exception as e:
print(f"Warning: Could not get temporal context: {e}", file=sys.stderr)
return None
def _get_cross_project_insights(
self, project_activity: List[ProjectActivity]
) -> Optional[Dict[str, Any]]:
"""Get cross-project intelligence: related work, shared patterns."""
if not self.portfolio_memory:
return None
try:
# Get portfolio-wide patterns
cross_patterns = self.portfolio_memory.get_cross_project_patterns()
# Find patterns used in multiple active projects
active_project_names = (
set(p.name for p in project_activity if p.commits_7d > 0)
if project_activity
else set()
)
shared_patterns = []
for pattern in cross_patterns[:10]:
pattern_projects = set(u["project"] for u in pattern.get("used_in", []))
overlap = pattern_projects & active_project_names
if len(overlap) > 1:
shared_patterns.append(
{
"pattern": pattern["pattern"],
"shared_by": list(overlap),