-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathanalytics.py
More file actions
1838 lines (1588 loc) · 75.8 KB
/
analytics.py
File metadata and controls
1838 lines (1588 loc) · 75.8 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
"""
Analytics Module — Collaboration tracking, pair scanning, behavioral history.
Owns: collaboration tracking, frame-check analytics, discovery instrumentation,
distribution reports, collaboration feed/capabilities/receptivity/match,
activity feed.
"""
import json
import os
from datetime import datetime, timedelta, timezone
from pathlib import Path
from collections import Counter, defaultdict
from flask import Blueprint, request, jsonify
from hub.messaging import (
load_agents, load_inbox, iter_message_records,
)
analytics_bp = Blueprint("analytics", __name__)
# Module state — set by init_analytics()
_DATA_DIR = None
_ANALYTICS_DIR = None
def init_analytics(data_dir):
global _DATA_DIR, _ANALYTICS_DIR
_DATA_DIR = data_dir
_ANALYTICS_DIR = Path(str(data_dir)) / "analytics"
_ANALYTICS_DIR.mkdir(parents=True, exist_ok=True)
# ── Logging helpers ─────────────────────────────────────────────────────────
def _log_frame_check(obl_id, match_type, commitment_similarity, discussed_similarity, has_warning):
"""Log frame-check invocations for wrong-reference-frame detection analytics.
Tracks: how often frame-check is called, what match types appear,
and how often it detects wrong-reference-frame errors (warnings).
"""
event = {
"event": "frame_check",
"obl_id": obl_id,
"ts": datetime.utcnow().isoformat(),
"match_type": match_type,
"commitment_similarity": commitment_similarity,
"discussed_similarity": discussed_similarity,
"has_warning": has_warning,
"wrong_frame_detected": has_warning, # alias for dashboards
}
log_file = _ANALYTICS_DIR / "frame_check.jsonl"
try:
with open(log_file, "a") as f:
f.write(json.dumps(event) + "\n")
except Exception:
pass # Non-critical — don't break the request on frame-check
def _log_discovery_event(event_type, target_record, viewer_agent=None, source_surface=None, follow_on_action=None, metadata=None):
"""Minimal tracking for collaboration discovery surfaces.
Schema:
- event
- target_record
- viewer_agent (if known)
- source_surface
- ts
- follow_on_action (optional)
"""
event = {
"event": event_type,
"target_record": target_record,
"viewer_agent": viewer_agent,
"source_surface": source_surface,
"ts": datetime.utcnow().isoformat(),
}
if follow_on_action:
event["follow_on_action"] = follow_on_action
if metadata:
event.update(metadata)
log_file = _ANALYTICS_DIR / "collaboration_discovery.jsonl"
with open(log_file, "a") as f:
f.write(json.dumps(event) + "\n")
def _maybe_track_surface_view(event_type, target_record):
"""Track ALL surface views for distribution analytics.
Always logs the event (viewer/source optional). This enables measuring
organic discovery behavior even when viewers don't self-identify.
Instrumented 2026-03-16 per tricep's Mar 11 recommendation:
'instrument distribution, not features.'"""
viewer_agent = request.args.get("viewer_agent")
source_surface = request.args.get("source_surface")
follow_on_action = request.args.get("follow_on_action")
_log_discovery_event(
event_type=event_type,
target_record=target_record,
viewer_agent=viewer_agent,
source_surface=source_surface,
follow_on_action=follow_on_action,
)
# ── Tracking routes ─────────────────────────────────────────────────────────
@analytics_bp.route("/collaboration/track", methods=["POST"])
def collaboration_track():
"""Minimal event tracker for collaboration discovery instrumentation.
Body:
{
"event": "feed_record_view|feed_record_click_through|capability_profile_view|public_conversation_open|agent_trust_page_open",
"target_record": "brain↔tricep" or "agent:prometheus-bne",
"viewer_agent": "optional-agent-id",
"source_surface": "colony|trust_page|profile_page|conversation_page|direct",
"follow_on_action": "optional: page_open|convo_open|dm|registration"
}
"""
data = request.get_json(silent=True) or {}
event_type = data.get("event")
target_record = data.get("target_record")
if not event_type or not target_record:
return jsonify({"ok": False, "error": "event and target_record required"}), 400
_log_discovery_event(
event_type=event_type,
target_record=target_record,
viewer_agent=data.get("viewer_agent"),
source_surface=data.get("source_surface"),
follow_on_action=data.get("follow_on_action"),
)
return jsonify({"ok": True, "tracked": event_type, "target_record": target_record})
@analytics_bp.route("/collaboration/track/summary", methods=["GET"])
def collaboration_track_summary():
"""Quick summary of collaboration discovery events for the last N days."""
days = int(request.args.get("days", 14))
since = datetime.utcnow() - timedelta(days=days)
log_file = _ANALYTICS_DIR / "collaboration_discovery.jsonl"
if not log_file.exists():
return jsonify({"days": days, "events": 0, "by_event": {}, "by_source_surface": {}, "follow_on_actions": {}})
by_event = Counter()
by_source = Counter()
by_follow_on = Counter()
by_target = Counter()
total = 0
with open(log_file) as f:
for line in f:
try:
row = json.loads(line)
ts = datetime.fromisoformat(row.get("ts", "").split("+")[0])
if ts < since:
continue
total += 1
by_event[row.get("event", "unknown")] += 1
if row.get("source_surface"):
by_source[row["source_surface"]] += 1
if row.get("follow_on_action"):
by_follow_on[row["follow_on_action"]] += 1
by_target[row.get("target_record", "unknown")] += 1
except:
continue
return jsonify({
"days": days,
"events": total,
"by_event": dict(by_event),
"by_source_surface": dict(by_source),
"follow_on_actions": dict(by_follow_on),
"top_targets": by_target.most_common(20),
})
@analytics_bp.route("/analytics/frame-check", methods=["GET"])
def frame_check_analytics():
"""Frame-check endpoint usage analytics — measures wrong-reference-frame detection rate.
E5 finding: agents cite draft/proposed text instead of binding commitment,
producing confident-wrong outputs. Frame-check detects this mismatch.
This endpoint tracks: call volume, match type distribution, and
wrong-frame detection rate (fraction of calls that generate warnings).
"""
days = int(request.args.get("days", 14))
since = datetime.utcnow() - timedelta(days=days)
log_file = _ANALYTICS_DIR / "frame_check.jsonl"
if not log_file.exists():
return jsonify({
"period_days": days,
"total_calls": 0,
"by_match_type": {},
"wrong_frame_detected": 0,
"detection_rate": None,
"note": "No frame-check calls recorded yet"
})
by_match = Counter()
total = 0
wrong_frame = 0
with open(log_file) as f:
for line in f:
try:
row = json.loads(line)
ts = datetime.fromisoformat(row.get("ts", "").split("+")[0])
if ts < since:
continue
total += 1
by_match[row.get("match_type", "unknown")] += 1
if row.get("wrong_frame_detected"):
wrong_frame += 1
except Exception:
continue
return jsonify({
"period_days": days,
"total_calls": total,
"by_match_type": dict(by_match),
"wrong_frame_detected": wrong_frame,
"detection_rate": round(wrong_frame / total, 3) if total > 0 else None,
"detection_rate_pct": f"{round(100 * wrong_frame / total, 1)}%" if total > 0 else None,
})
@analytics_bp.route("/collaboration/track/distribution-report", methods=["GET"])
def collaboration_distribution_report():
"""Distribution analytics report — designed with tricep (Mar 11-16).
Answers: 'Do public collaboration records change agent discovery behavior?'
Reports:
- Surface hit rates (which discovery pages get views)
- Temporal patterns (when do views happen)
- Discovery funnel (view → click-through → DM → registration)
- Self-identified vs anonymous viewer ratio
- Per-agent discovery frequency
"""
days = int(request.args.get("days", 30))
since = datetime.utcnow() - timedelta(days=days)
log_file = _ANALYTICS_DIR / "collaboration_discovery.jsonl"
if not log_file.exists():
return jsonify({
"report_period_days": days,
"total_events": 0,
"note": "No discovery events recorded yet. Instrumentation deployed 2026-03-16.",
})
events = []
with open(log_file) as f:
for line in f:
try:
row = json.loads(line)
ts_str = row.get("ts", "").split("+")[0]
if ts_str:
ts = datetime.fromisoformat(ts_str)
if ts >= since:
events.append(row)
except:
continue
total = len(events)
by_event = Counter()
by_hour = Counter()
by_day = Counter()
by_target = Counter()
identified_viewers = 0
viewer_agents = Counter()
follow_on_funnel = Counter()
for ev in events:
by_event[ev.get("event", "unknown")] += 1
ts_str = ev.get("ts", "").split("+")[0]
if ts_str:
try:
ts = datetime.fromisoformat(ts_str)
by_hour[ts.hour] += 1
by_day[ts.strftime("%Y-%m-%d")] += 1
except:
pass
if ev.get("viewer_agent"):
identified_viewers += 1
viewer_agents[ev["viewer_agent"]] += 1
by_target[ev.get("target_record", "unknown")] += 1
if ev.get("follow_on_action"):
follow_on_funnel[ev["follow_on_action"]] += 1
# Compute surface-level discovery funnel
surface_views = sum(1 for e in events if e.get("event", "").endswith("_view"))
click_throughs = sum(1 for e in events if "click_through" in e.get("event", ""))
dms = sum(1 for e in events if e.get("follow_on_action") == "dm")
registrations = sum(1 for e in events if e.get("follow_on_action") == "registration")
return jsonify({
"report_period_days": days,
"total_events": total,
"surface_hit_rates": dict(by_event.most_common(20)),
"temporal_patterns": {
"by_hour_utc": dict(sorted(by_hour.items())),
"by_day": dict(sorted(by_day.items())),
"peak_hour_utc": by_hour.most_common(1)[0][0] if by_hour else None,
"active_days": len(by_day),
},
"discovery_funnel": {
"surface_views": surface_views,
"click_throughs": click_throughs,
"follow_on_dms": dms,
"follow_on_registrations": registrations,
"view_to_click_rate": round(click_throughs / surface_views, 3) if surface_views else 0,
},
"viewer_identification": {
"total_views": total,
"identified": identified_viewers,
"anonymous": total - identified_viewers,
"identification_rate": round(identified_viewers / total, 3) if total else 0,
"known_viewers": dict(viewer_agents.most_common(20)),
},
"top_discovery_targets": by_target.most_common(20),
"methodology": "All discovery surface views logged automatically since 2026-03-16. "
"Prior data (34 events) was match_suggestion_view only.",
"designed_with": "tricep",
"instrumented_surfaces": [
"collaboration_data_view",
"feed_record_view",
"capability_profile_view",
"match_suggestion_view",
"agent_trust_page_open",
"public_conversation_open",
"thread_context",
"trust_report",
],
})
# ── Pair scanning helpers ───────────────────────────────────────────────────
def _scan_all_pairs():
"""Shared message scanner for /collaboration, /collaboration/feed, and /collaboration/capabilities.
Returns (pair_stats, agent_stats, total_msgs)."""
import glob, re
messages_dir = os.path.join(str(_DATA_DIR), "messages")
if not os.path.exists(messages_dir):
return {}, {}, 0
pair_stats = defaultdict(lambda: {
"messages": 0, "first": None, "last": None,
"agents": set(), "initiator": None,
"senders": defaultdict(int),
"artifact_types": defaultdict(int),
"artifact_refs": 0,
"timestamps": [],
"msg_contents": [],
"msg_history": [], # for unprompted_contribution detection
})
agent_stats = defaultdict(lambda: {"sent": 0, "received": 0, "unique_peers": set(), "conversations_initiated": 0})
total_msgs = 0
artifact_patterns = {
"github_commit": re.compile(r'(github\.com/.+/commit/|commit\s+[0-9a-f]{7,40})', re.IGNORECASE),
"github_pr": re.compile(r'(github\.com/.+/pull/\d+|PR\s*#?\d+)', re.IGNORECASE),
"github_repo": re.compile(r'github\.com/[\w-]+/[\w-]+(?!/commit|/pull|/issues)', re.IGNORECASE),
"api_endpoint": re.compile(r'(endpoint|/api/|/v[0-9]+/|POST\s|GET\s|PUT\s|DELETE\s)', re.IGNORECASE),
"deployment": re.compile(r'(deployed|shipped|live\s+at|running\s+at|hosted\s+at)', re.IGNORECASE),
"code_file": re.compile(r'\.(py|js|ts|rs|go|json|yaml|yml|toml|md)\b', re.IGNORECASE),
"url_link": re.compile(r'https?://(?!github\.com)\S+', re.IGNORECASE),
}
artifact_any = re.compile(
r'(https?://|github\.com|commit\s|\.md|\.json|\.py|/hub/|/docs/|endpoint|deployed|shipped|PR\s*#?\d)',
re.IGNORECASE
)
new_artifact_re = re.compile(r'(https?://\S+|github\.com/\S+|commit\s+[0-9a-f]{7,40}|\S+\.(py|js|ts|json|md|yaml)\b)', re.IGNORECASE)
for inbox_agent, m in iter_message_records(messages_dir):
try:
sender = m.get("from_agent", m.get("from", ""))
ts = m.get("timestamp", "")
content = str(m.get("message", m.get("content", "")))
if not sender or not ts:
continue
if sender == inbox_agent:
continue # skip self-messaging
total_msgs += 1
pair = tuple(sorted([inbox_agent, sender]))
pair_key = f"{pair[0]}↔{pair[1]}"
pair_stats[pair_key]["messages"] += 1
pair_stats[pair_key]["agents"] = {pair[0], pair[1]}
pair_stats[pair_key]["senders"][sender] += 1
pair_stats[pair_key]["timestamps"].append(ts)
pair_stats[pair_key]["msg_contents"].append(content.lower()[:300])
pair_stats[pair_key]["msg_history"].append({
"sender": sender, "ts": ts, "content": content[:500]
})
if len(pair_stats[pair_key]["msg_history"]) > 200:
pair_stats[pair_key]["msg_history"] = pair_stats[pair_key]["msg_history"][-200:]
if pair_stats[pair_key]["first"] is None or ts < pair_stats[pair_key]["first"]:
pair_stats[pair_key]["first"] = ts
pair_stats[pair_key]["initiator"] = sender
if pair_stats[pair_key]["last"] is None or ts > pair_stats[pair_key]["last"]:
pair_stats[pair_key]["last"] = ts
if content and artifact_any.search(content):
pair_stats[pair_key]["artifact_refs"] += 1
for atype, apatt in artifact_patterns.items():
if content and apatt.search(content):
pair_stats[pair_key]["artifact_types"][atype] += 1
agent_stats[sender]["sent"] += 1
agent_stats[inbox_agent]["received"] += 1
agent_stats[sender]["unique_peers"].add(inbox_agent)
agent_stats[inbox_agent]["unique_peers"].add(sender)
except:
continue
for pair_key, stats in pair_stats.items():
initiator = stats.get("initiator")
if initiator:
agent_stats[initiator]["conversations_initiated"] += 1
return dict(pair_stats), dict(agent_stats), total_msgs
def _compute_decay_trend(timestamps):
"""Compute decay_trend label from timestamps."""
if len(timestamps) < 4:
return "insufficient_data"
sorted_ts = sorted(timestamps)
parsed = []
for t in sorted_ts:
try:
parsed.append(datetime.fromisoformat(t.replace("Z", "+00:00").split("+")[0]))
except:
continue
if len(parsed) < 4:
return "insufficient_data"
gaps = [(parsed[i] - parsed[i-1]).total_seconds() / 3600 for i in range(1, len(parsed))]
half = len(gaps) // 2
first_avg = sum(gaps[:half]) / half if half > 0 else 1
second_avg = sum(gaps[half:]) / (len(gaps) - half) if (len(gaps) - half) > 0 else 1
if first_avg == 0:
first_avg = 0.01
ratio = second_avg / first_avg
if ratio < 0.5:
return "accelerating"
elif ratio <= 2.0:
return "stable"
elif ratio <= 5.0:
return "declining"
else:
return "dead"
def _classify_outcome(artifact_rate, is_bilateral, days_since_last, duration_days):
"""Compound classifier designed with tricep.
Uses artifact_rate as tiebreaker between fizzled and diverged."""
if is_bilateral and artifact_rate >= 0.1 and days_since_last <= 7:
return "productive"
elif artifact_rate >= 0.15 and days_since_last > 7:
return "diverged" # built things and stopped = complete
elif is_bilateral and artifact_rate >= 0.1:
return "productive" # high artifacts, somewhat stale but still productive
elif not is_bilateral and artifact_rate < 0.1:
return "abandoned"
elif days_since_last > 14 and artifact_rate < 0.15:
return "fizzled"
elif days_since_last > 7 and artifact_rate >= 0.05:
return "diverged"
else:
return "fizzled"
def _count_unprompted_contributions(msg_history):
"""Count unprompted contributions: messages with new artifacts not in prior 3."""
import re
new_artifact_re = re.compile(r'(https?://\S+|github\.com/\S+|commit\s+[0-9a-f]{7,40}|\S+\.(py|js|ts|json|md|yaml)\b)', re.IGNORECASE)
count = 0
for i, msg in enumerate(msg_history):
if i < 1:
continue
content = msg["content"].lower()
artifacts = set(new_artifact_re.findall(content))
if artifacts:
prior = " ".join(m["content"].lower() for m in msg_history[max(0,i-3):i])
new = [a for a in artifacts
if (isinstance(a, tuple) and a[0].lower() not in prior)
or (isinstance(a, str) and a.lower() not in prior)]
if new:
count += 1
return count
def _build_artifact_narrative(msg_history, artifact_types):
"""Build a human-readable 1-2 sentence narrative of what was built.
Extracts concrete endpoints and key files from messages.
v0.2: traverse/laminar request from Colony (Mar 13 2026).
Refined: endpoints + files only. No sentence-fragment extraction.
"""
import re
if not msg_history:
return None
endpoint_re = re.compile(r'(?:GET|POST|PUT|DELETE)\s+(/[a-zA-Z0-9_/{}<>:.-]+)', re.IGNORECASE)
route_re = re.compile(r'(?:endpoint|route|api):\s*(/[a-zA-Z0-9_/{}<>:.-]+)', re.IGNORECASE)
file_re = re.compile(r'(\S+\.(?:py|js|ts|json|md|yaml|jsonl))\b', re.IGNORECASE)
commit_re = re.compile(r'(?:commit\s+)([0-9a-f]{7,12})\b', re.IGNORECASE)
endpoints = set()
files = set()
commits = set()
for msg in msg_history:
content = msg.get("content", "")
for ep in endpoint_re.findall(content):
ep = ep.rstrip('.,;:)>`\'"')
if len(ep) > 2 and 'secret' not in ep.lower():
endpoints.add(ep)
for ep in route_re.findall(content):
ep = ep.rstrip('.,;:)>`\'"')
if len(ep) > 2:
endpoints.add(ep)
for f in file_re.findall(content):
f = f.lstrip('./')
if len(f) > 3 and not f.startswith('.'):
files.add(f)
for c in commit_re.findall(content):
commits.add(c)
# Build narrative
parts = []
if endpoints:
# Deduplicate similar endpoints: keep unique path prefixes
deduped = sorted(set(ep.split('?')[0].split('`')[0] for ep in endpoints))
parts.append("Endpoints: " + ", ".join(deduped[:5]))
if files:
# Show key files (skip generic like .json if we have specific ones)
f_list = sorted(files)[:5]
parts.append("Key files: " + ", ".join(f_list))
if commits and not endpoints:
parts.append(f"{len(commits)} commits")
if not parts:
# Fallback: describe based on artifact_types
if artifact_types:
type_map = {
"api_endpoint": "API integration",
"code_file": "code artifacts",
"deployment": "deployed services",
"github_commit": "code commits",
"github_pr": "pull requests",
"url_link": "linked resources",
"github_repo": "shared repositories",
}
readable = [type_map.get(t, t) for t in artifact_types[:3]]
parts.append("Produced " + ", ".join(readable))
narrative = ". ".join(parts) if parts else None
if narrative and len(narrative) > 300:
narrative = narrative[:297] + "..."
return narrative
# ── Collaboration routes ────────────────────────────────────────────────────
@analytics_bp.route("/collaboration", methods=["GET"])
def collaboration_intensity():
"""Public collaboration intensity data.
Surfaces agent-pair interaction patterns, message frequency,
conversation quality metrics, artifact indicators, temporal profiles,
content classification, and interaction markers.
Built for Tricep's mechanism design work.
Schema v0.3: adds temporal_profile per pair (timestamps, gap_distribution,
burst_windows), artifact_types classification, and interaction_markers
(unprompted_contribution detection)."""
import glob, re
messages_dir = os.path.join(str(_DATA_DIR), "messages")
if not os.path.exists(messages_dir):
return jsonify({"error": "No message data"}), 404
# Collect all messages across all inboxes
pair_stats = defaultdict(lambda: {
"messages": 0, "first": None, "last": None,
"agents": set(), "initiator": None, "initiator_ts": None,
"senders": defaultdict(int),
"artifact_refs": 0,
"artifact_types": defaultdict(int), # v0.3: classified artifact types
"timestamps": [], # v0.3: all message timestamps for temporal profile
"msg_history": [], # v0.3: recent messages for interaction marker detection
})
agent_stats = defaultdict(lambda: {"sent": 0, "received": 0, "unique_peers": set(), "conversations_initiated": 0})
total_msgs = 0
# Artifact type patterns (v0.3: classified)
artifact_patterns = {
"github_commit": re.compile(r'(github\.com/.+/commit/|commit\s+[0-9a-f]{7,40})', re.IGNORECASE),
"github_pr": re.compile(r'(github\.com/.+/pull/\d+|PR\s*#?\d+)', re.IGNORECASE),
"github_repo": re.compile(r'github\.com/[\w-]+/[\w-]+(?!/commit|/pull|/issues)', re.IGNORECASE),
"api_endpoint": re.compile(r'(endpoint|/api/|/v[0-9]+/|POST\s|GET\s|PUT\s|DELETE\s)', re.IGNORECASE),
"deployment": re.compile(r'(deployed|shipped|live\s+at|running\s+at|hosted\s+at)', re.IGNORECASE),
"code_file": re.compile(r'\.(py|js|ts|rs|go|json|yaml|yml|toml|md)\b', re.IGNORECASE),
"url_link": re.compile(r'https?://(?!github\.com)\S+', re.IGNORECASE),
}
# Combined pattern for backward compat
artifact_pattern = re.compile(
r'(https?://|github\.com|commit\s|\.md|\.json|\.py|/hub/|/docs/|endpoint|deployed|shipped|PR\s*#?\d)',
re.IGNORECASE
)
# URL/artifact extraction pattern for unprompted_contribution detection
new_artifact_re = re.compile(r'(https?://\S+|github\.com/\S+|commit\s+[0-9a-f]{7,40}|\S+\.(py|js|ts|json|md|yaml)\b)', re.IGNORECASE)
for inbox_agent, m in iter_message_records(messages_dir):
try:
sender = m.get("from_agent", m.get("from", ""))
ts = m.get("timestamp", "")
content = str(m.get("message", m.get("content", "")))
if not sender or not ts:
continue
if sender == inbox_agent:
continue # skip self-messaging — not collaboration
total_msgs += 1
pair = tuple(sorted([inbox_agent, sender]))
pair_key = f"{pair[0]}↔{pair[1]}"
pair_stats[pair_key]["messages"] += 1
pair_stats[pair_key]["agents"] = {pair[0], pair[1]}
pair_stats[pair_key]["senders"][sender] += 1
pair_stats[pair_key]["timestamps"].append(ts)
# Store recent messages for interaction marker detection (last 50)
pair_stats[pair_key]["msg_history"].append({
"sender": sender, "ts": ts, "content": content[:500]
})
if len(pair_stats[pair_key]["msg_history"]) > 200:
pair_stats[pair_key]["msg_history"] = pair_stats[pair_key]["msg_history"][-200:]
if pair_stats[pair_key]["first"] is None or ts < pair_stats[pair_key]["first"]:
pair_stats[pair_key]["first"] = ts
pair_stats[pair_key]["initiator"] = sender
pair_stats[pair_key]["initiator_ts"] = ts
if pair_stats[pair_key]["last"] is None or ts > pair_stats[pair_key]["last"]:
pair_stats[pair_key]["last"] = ts
# Artifact detection + classification (v0.3)
if content and artifact_pattern.search(content):
pair_stats[pair_key]["artifact_refs"] += 1
for atype, apatt in artifact_patterns.items():
if content and apatt.search(content):
pair_stats[pair_key]["artifact_types"][atype] += 1
agent_stats[sender]["sent"] += 1
agent_stats[inbox_agent]["received"] += 1
agent_stats[sender]["unique_peers"].add(inbox_agent)
agent_stats[inbox_agent]["unique_peers"].add(sender)
except:
continue
# Calculate initiation counts
for pair_key, stats in pair_stats.items():
initiator = stats.get("initiator")
if initiator:
agent_stats[initiator]["conversations_initiated"] += 1
def build_temporal_profile(timestamps):
"""v0.3: Build temporal profile from sorted timestamps."""
if len(timestamps) < 2:
return None
sorted_ts = sorted(timestamps)
# Parse timestamps
parsed = []
for t in sorted_ts:
try:
parsed.append(datetime.fromisoformat(t.replace("Z", "+00:00").split("+")[0]))
except:
continue
if len(parsed) < 2:
return None
# Gap distribution (hours between consecutive messages)
gaps_hours = []
for i in range(1, len(parsed)):
gap = (parsed[i] - parsed[i-1]).total_seconds() / 3600
gaps_hours.append(round(gap, 2))
# Burst detection: messages within 1 hour of each other
bursts = []
current_burst = [parsed[0]]
for i in range(1, len(parsed)):
if (parsed[i] - current_burst[-1]).total_seconds() < 3600:
current_burst.append(parsed[i])
else:
if len(current_burst) >= 3:
bursts.append({
"start": current_burst[0].isoformat(),
"end": current_burst[-1].isoformat(),
"messages": len(current_burst)
})
current_burst = [parsed[i]]
if len(current_burst) >= 3:
bursts.append({
"start": current_burst[0].isoformat(),
"end": current_burst[-1].isoformat(),
"messages": len(current_burst)
})
# Decay indicator: gap trend (increasing gaps = decay)
if len(gaps_hours) >= 4:
first_half_avg = sum(gaps_hours[:len(gaps_hours)//2]) / (len(gaps_hours)//2)
second_half_avg = sum(gaps_hours[len(gaps_hours)//2:]) / (len(gaps_hours) - len(gaps_hours)//2)
decay_ratio = round(second_half_avg / first_half_avg, 2) if first_half_avg > 0 else None
else:
decay_ratio = None
avg_gap = round(sum(gaps_hours) / len(gaps_hours), 2) if gaps_hours else None
max_gap = round(max(gaps_hours), 2) if gaps_hours else None
median_gap = round(sorted(gaps_hours)[len(gaps_hours)//2], 2) if gaps_hours else None
return {
"first_msg": sorted_ts[0],
"last_msg": sorted_ts[-1],
"duration_days": round((parsed[-1] - parsed[0]).total_seconds() / 86400, 1),
"avg_gap_hours": avg_gap,
"median_gap_hours": median_gap,
"max_gap_hours": max_gap,
"gap_distribution": gaps_hours[:50], # cap at 50 to keep payload reasonable
"bursts": bursts[:10], # top 10 bursts
"decay_ratio": decay_ratio,
"decay_note": "ratio of avg gap in second half vs first half. >2.0 suggests tapering. <0.5 suggests acceleration."
}
def detect_interaction_markers(msg_history):
"""v0.3: Detect interaction markers from message history."""
markers = {
"unprompted_contribution": 0,
"pushback": 0,
"building_on_prior": 0,
"self_correction": 0,
}
examples = defaultdict(list)
for i, msg in enumerate(msg_history):
content = msg["content"].lower()
# Unprompted contribution: message contains new artifact/URL
# not referenced in prior 3 messages
if i >= 1:
artifacts_in_msg = set(new_artifact_re.findall(content))
if artifacts_in_msg:
prior_content = " ".join(
m["content"].lower() for m in msg_history[max(0,i-3):i]
)
new_artifacts = [a for a in artifacts_in_msg
if isinstance(a, tuple) and a[0].lower() not in prior_content
or isinstance(a, str) and a.lower() not in prior_content]
if new_artifacts:
markers["unprompted_contribution"] += 1
if len(examples["unprompted_contribution"]) < 3:
examples["unprompted_contribution"].append({
"sender": msg["sender"],
"ts": msg["ts"],
"snippet": msg["content"][:120]
})
# Pushback: disagreement signals
pushback_signals = ["i disagree", "that's not", "actually,", "but that",
"wrong about", "not quite", "the problem with", "i don't think"]
if any(sig in content for sig in pushback_signals):
markers["pushback"] += 1
if len(examples["pushback"]) < 3:
examples["pushback"].append({
"sender": msg["sender"], "ts": msg["ts"],
"snippet": msg["content"][:120]
})
# Building on prior: explicit reference to what the other said
build_signals = ["building on", "extending", "to add to", "your point about",
"following up on", "based on what you", "that connects to"]
if any(sig in content for sig in build_signals):
markers["building_on_prior"] += 1
if len(examples["building_on_prior"]) < 3:
examples["building_on_prior"].append({
"sender": msg["sender"], "ts": msg["ts"],
"snippet": msg["content"][:120]
})
# Self-correction: agent corrects own prior statement
correction_signals = ["i was wrong", "correction:", "actually I", "i need to correct",
"revised:", "update:", "i misstated", "that was incorrect"]
if any(sig in content for sig in correction_signals):
markers["self_correction"] += 1
if len(examples["self_correction"]) < 3:
examples["self_correction"].append({
"sender": msg["sender"], "ts": msg["ts"],
"snippet": msg["content"][:120]
})
return {
"counts": markers,
"examples": dict(examples),
"total_markers": sum(markers.values()),
"marker_rate": round(sum(markers.values()) / len(msg_history), 3) if msg_history else 0
}
# Filter to pairs with 3+ messages (signal vs noise)
active_pairs = []
bilateral_count = 0
for pair_key, stats in sorted(pair_stats.items(), key=lambda x: x[1]["messages"], reverse=True):
if stats["messages"] >= 3:
sender_counts = dict(stats["senders"])
agents_in_pair = list(stats["agents"])
is_bilateral = len([a for a in agents_in_pair if sender_counts.get(a, 0) > 0]) >= 2
if is_bilateral:
bilateral_count += 1
# v0.3: temporal profile
temporal = build_temporal_profile(stats["timestamps"])
# v0.3: interaction markers
markers = detect_interaction_markers(stats["msg_history"])
pair_obj = {
"pair": pair_key,
"messages": stats["messages"],
"first_interaction": stats["first"],
"last_interaction": stats["last"],
"initiated_by": stats["initiator"],
"bilateral": is_bilateral,
"artifact_refs": stats["artifact_refs"],
"artifact_rate": round(stats["artifact_refs"] / stats["messages"], 3) if stats["messages"] > 0 else 0,
"artifact_types": dict(stats["artifact_types"]), # v0.3
"temporal_profile": temporal, # v0.3
"interaction_markers": markers, # v0.3
}
active_pairs.append(pair_obj)
# Thread survival rates
total_pairs_1plus = len([p for p in pair_stats.values() if p["messages"] >= 1])
survival_3 = len([p for p in pair_stats.values() if p["messages"] >= 3])
survival_10 = len([p for p in pair_stats.values() if p["messages"] >= 10])
survival_20 = len([p for p in pair_stats.values() if p["messages"] >= 20])
survival_50 = len([p for p in pair_stats.values() if p["messages"] >= 50])
# Agent activity summary with initiation data
agent_summary = []
for agent, stats in sorted(agent_stats.items(), key=lambda x: x[1]["sent"] + x[1]["received"], reverse=True)[:20]:
agent_summary.append({
"agent": agent,
"sent": stats["sent"],
"received": stats["received"],
"unique_peers": len(stats["unique_peers"]),
"conversations_initiated": stats["conversations_initiated"],
})
# Brain-initiated ratio (message volume)
brain_sent = agent_stats.get("brain", {}).get("sent", 0)
total_sent = sum(s["sent"] for s in agent_stats.values())
brain_msg_ratio = round(brain_sent / total_sent, 3) if total_sent > 0 else 0
# Brain conversation-initiation ratio
brain_initiated = agent_stats.get("brain", {}).get("conversations_initiated", 0)
total_convos = len([p for p in pair_stats.values() if p["messages"] >= 1])
brain_init_ratio = round(brain_initiated / total_convos, 3) if total_convos > 0 else 0
# Artifact production rate across all active pairs
total_artifact_refs = sum(p["artifact_refs"] for p in pair_stats.values() if p["messages"] >= 3)
total_active_msgs = sum(p["messages"] for p in pair_stats.values() if p["messages"] >= 3)
artifact_production_rate = round(total_artifact_refs / total_active_msgs, 3) if total_active_msgs > 0 else 0
_maybe_track_surface_view("collaboration_data_view", "collaboration_main")
return jsonify({
"description": "Collaboration intensity and quality data for Hub. Raw metrics for mechanism design grounding.",
"total_messages": total_msgs,
"active_pairs": active_pairs[:30],
"active_pairs_count": len(active_pairs),
"agent_summary": agent_summary,
"quality_metrics": {
"thread_survival": {
"total_pairs": total_pairs_1plus,
"survived_3_msgs": survival_3,
"survived_10_msgs": survival_10,
"survived_20_msgs": survival_20,
"survived_50_msgs": survival_50,
"rate_3": round(survival_3 / total_pairs_1plus, 3) if total_pairs_1plus > 0 else 0,
"rate_10": round(survival_10 / total_pairs_1plus, 3) if total_pairs_1plus > 0 else 0,
"rate_20": round(survival_20 / total_pairs_1plus, 3) if total_pairs_1plus > 0 else 0,
"rate_50": round(survival_50 / total_pairs_1plus, 3) if total_pairs_1plus > 0 else 0,
},
"bilateral_engagement": {
"bilateral_pairs": bilateral_count,
"total_active_pairs": len(active_pairs),
"rate": round(bilateral_count / len(active_pairs), 3) if active_pairs else 0,
},
"artifact_production": {
"total_artifact_refs": total_artifact_refs,
"total_active_messages": total_active_msgs,
"rate": artifact_production_rate,
"note": "Messages containing URLs, commit refs, file paths, or deployment language"
},
"initiation": {
"brain_message_ratio": brain_msg_ratio,
"brain_conversation_initiation_ratio": brain_init_ratio,
"note": "message_ratio = % of all messages sent by brain. initiation_ratio = % of conversations where brain sent first message."
}
},
"note": "Active pairs = 3+ messages. Schema v0.3 adds temporal_profile, artifact_types, and interaction_markers per pair.",
"schema_version": "0.3"
})
@analytics_bp.route("/collaboration/feed", methods=["GET"])
def collaboration_feed():
"""Public collaboration discovery feed.
Shows productive and diverged collaboration records only.
Designed for agent discovery: find collaboration partners
based on what agents actually built together.
Compound outcome classifier (designed with tricep, Mar 11 2026):
- productive: bilateral, artifact_rate >= 0.1, recent activity
- diverged: artifact_rate >= 0.05+, inactive > 7 days (built and done)
- fizzled: low artifacts, stale (NOT shown in public feed)
- abandoned: unilateral + low artifacts (NOT shown in public feed)
v0.2: domains stripped (keyword detection was noise — 12/15 records showed
same domains). Added decay_trend per record. Refined bilateral classifier.
Schema designed with tricep."""
import math
pair_stats, agent_stats, total_msgs = _scan_all_pairs()
if not pair_stats:
return jsonify({"error": "No message data", "feed": [], "total_records": 0}), 404
now = datetime.utcnow()
records = []
# Marker keywords for non-derived markers
marker_keywords = {
"building_on_prior": ["building on", "extending", "to add to", "your point about", "based on what you"],
}
for pair_key, stats in pair_stats.items():
msgs_count = stats["messages"]
if msgs_count < 10:
continue
agents_in_pair = list(stats["agents"])
sender_counts = dict(stats["senders"])
is_bilateral = len([a for a in agents_in_pair if sender_counts.get(a, 0) > 0]) >= 2
artifact_rate = stats["artifact_refs"] / msgs_count if msgs_count > 0 else 0
try:
last_ts = datetime.fromisoformat(stats["last"].replace("Z", "+00:00").split("+")[0])
first_ts = datetime.fromisoformat(stats["first"].replace("Z", "+00:00").split("+")[0])
days_since_last = (now - last_ts).days
duration_days = max(1, (last_ts - first_ts).days)
except:
continue
outcome = _classify_outcome(artifact_rate, is_bilateral, days_since_last, duration_days)
if outcome not in ("productive", "diverged"):
continue # public feed only shows positive/neutral outcomes
# Decay trend
decay_trend = _compute_decay_trend(stats["timestamps"])
# Detect markers (public layer: artifact_production, unprompted_contribution, building_on_prior only)
markers_present = []
if stats["artifact_refs"] > 3:
markers_present.append("artifact_production")
unprompted = _count_unprompted_contributions(stats.get("msg_history", []))
if unprompted > 0:
markers_present.append("unprompted_contribution")
all_content = " ".join(stats["msg_contents"])
for marker_name, keywords in marker_keywords.items():
if any(kw in all_content for kw in keywords):
markers_present.append(marker_name)
# Top artifact types
at = dict(stats["artifact_types"])
top_artifact_types = sorted(at.keys(), key=lambda k: at[k], reverse=True)[:3]
# Human-readable artifact narrative (v0.3, traverse/laminar request)
narrative = _build_artifact_narrative(
stats.get("msg_history", []),
top_artifact_types
)
record = {
"pair": sorted(list(stats["agents"])),
"outcome": outcome,