-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathteam.py
More file actions
1366 lines (1122 loc) · 47.2 KB
/
team.py
File metadata and controls
1366 lines (1122 loc) · 47.2 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
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (c) 2025 Web4 Contributors
#
# Hardbound - Team (Society) Implementation
# https://github.com/dp-web4/web4
"""
Team: A governed organization of entities.
A Team is a Web4 Society with enterprise terminology:
- Root LCT identifying the team itself
- Ledger for immutable record keeping
- Admin role for governance
- Members with assigned roles
- Policy for rules enforcement
Key insight: A team IS an entity. It has its own LCT, can be a member
of other teams (fractal structure), and accumulates its own trust.
"""
import hashlib
import json
import sqlite3
from datetime import datetime, timezone, timedelta
from pathlib import Path
from typing import Optional, Dict, List, Any
from dataclasses import dataclass, field, asdict
from enum import Enum
# Import governance components (self-contained)
from .ledger import Ledger
# Import trust decay, policy, and admin binding
from .trust_decay import TrustDecayCalculator, DecayConfig
from .policy import Policy, PolicyStore
from .admin_binding import AdminBindingManager, AdminBindingType, AdminBinding
from .heartbeat_ledger import HeartbeatLedger, MetabolicState
from .activity_quality import ActivityWindow, compute_quality_adjusted_decay
@dataclass
class TeamConfig:
"""Configuration for a team."""
name: str
description: str = ""
# Heartbeat policy (metabolic timing)
heartbeat_min_seconds: int = 30
heartbeat_max_seconds: int = 3600
# ATP defaults
default_member_budget: int = 100
# Trust thresholds for actions
action_trust_threshold: float = 0.5
admin_trust_threshold: float = 0.8
# Trust decay settings
enable_trust_decay: bool = True
decay_config: Optional[DecayConfig] = None
class Team:
"""
A governed team (Web4 society with enterprise terminology).
Structure:
Team (root LCT)
├── Ledger (immutable records)
├── Members (each with LCT)
├── Roles (admin required, others optional)
└── Policy (rules from ledger)
"""
def __init__(self, team_id: Optional[str] = None, config: Optional[TeamConfig] = None,
ledger: Optional[Ledger] = None):
"""
Initialize or load a team.
Args:
team_id: Existing team ID to load, or None to create new
config: Team configuration (required for new teams)
ledger: Ledger instance (creates default if None)
"""
self.ledger = ledger or Ledger()
self._decay_calculator: Optional[TrustDecayCalculator] = None
if team_id:
# Load existing team
self._load_team(team_id)
else:
# Create new team
if config is None:
raise ValueError("config required for new team")
self._create_team(config)
# Initialize decay calculator if enabled
if self.config.enable_trust_decay:
decay_config = self.config.decay_config or DecayConfig()
self._decay_calculator = TrustDecayCalculator(decay_config)
# Initialize heartbeat ledger for metabolic tracking
self._heartbeat_ledger: Optional[HeartbeatLedger] = None
# Activity quality tracking per member (not persisted - rebuilt from actions)
self._activity_windows: Dict[str, 'ActivityWindow'] = {}
# Optional R6Workflow for heartbeat-triggered cleanup
self._r6_workflow: Optional['R6Workflow'] = None
def _get_activity_window(self, lct_id: str) -> ActivityWindow:
"""Get or create an ActivityWindow for a member (30-day rolling window)."""
if lct_id not in self._activity_windows:
self._activity_windows[lct_id] = ActivityWindow(
entity_id=lct_id, window_seconds=86400 * 30
)
return self._activity_windows[lct_id]
def _quality_adjusted_actions(self, lct_id: str, raw_count: int) -> int:
"""
Get quality-adjusted action count for decay calculation.
Uses ActivityWindow if available, otherwise falls back to raw count.
This prevents micro-ping gaming where trivial actions slow decay.
"""
window = self._activity_windows.get(lct_id)
if window and len(window.actions) > 0:
metabolic = self.metabolic_state if self._heartbeat_ledger else "active"
adjusted = compute_quality_adjusted_decay(raw_count, window, metabolic)
return max(0, int(adjusted))
return raw_count
@property
def heartbeat(self) -> HeartbeatLedger:
"""
Get or create the heartbeat ledger for this team.
Lazy initialization - only created when first accessed.
The heartbeat ledger tracks metabolic state and produces
blocks driven by team activity patterns.
"""
if self._heartbeat_ledger is None:
self._heartbeat_ledger = HeartbeatLedger(self.team_id)
return self._heartbeat_ledger
@property
def metabolic_state(self) -> str:
"""Current team metabolic state."""
return self.heartbeat.state.value
def register_r6_workflow(self, workflow: 'R6Workflow'):
"""
Register an R6Workflow for heartbeat-triggered cleanup.
When pulse() is called, expired R6 requests will be automatically
cleaned up.
Args:
workflow: R6Workflow instance to register
"""
self._r6_workflow = workflow
def pulse(self, sentinel_lct: Optional[str] = None, cleanup_r6: bool = True):
"""
Fire a metabolic heartbeat, sealing pending transactions into a block.
This is the team's "pulse" - call it periodically to maintain
the block chain. Active teams should pulse every ~60s, resting
teams every ~5min, etc.
Args:
sentinel_lct: LCT to witness this heartbeat
cleanup_r6: Whether to cleanup expired R6 requests (default True)
Returns:
The sealed block.
"""
# Cleanup expired R6 requests if workflow registered
expired_count = 0
if cleanup_r6 and self._r6_workflow:
expired = self._r6_workflow.cleanup_expired()
expired_count = len(expired)
block = self.heartbeat.heartbeat(sentinel_lct=sentinel_lct or self.admin_lct)
# Record cleanup in audit trail if any were expired
if expired_count > 0:
self.ledger.record_audit(
session_id=self.team_id,
action_type="r6_heartbeat_cleanup",
tool_name="hardbound",
target="r6_requests",
r6_data={
"expired_count": expired_count,
"block_number": block.block_number,
}
)
return block
# States that trigger wake recalibration on exit
DORMANT_STATES = {"sleep", "hibernation", "torpor", "estivation"}
def metabolic_transition(self, to_state: str, trigger: str):
"""
Transition the team to a new metabolic state.
If waking from a dormant state, applies trust recalibration
to all members based on dormancy duration and severity.
Args:
to_state: Target state name (active, rest, sleep, etc.)
trigger: What caused the transition
Returns:
MetabolicTransition record
"""
from_state = self.heartbeat.state.value
target = MetabolicState(to_state)
transition = self.heartbeat.transition_state(target, trigger=trigger)
# Wake recalibration: apply trust penalty when leaving dormant states
if from_state in self.DORMANT_STATES and to_state in ("active", "rest"):
self._apply_wake_recalibration(from_state, transition)
# Record on team audit trail
self.ledger.record_audit(
session_id=self.team_id,
action_type="metabolic_transition",
tool_name="hardbound",
target=to_state,
r6_data={
"from": transition.from_state,
"to": transition.to_state,
"trigger": trigger,
"atp_cost": transition.atp_cost,
}
)
return transition
def _apply_wake_recalibration(self, dormant_state: str, transition):
"""
Apply trust recalibration to all members after waking from dormancy.
Extended absence creates epistemic uncertainty about member
capabilities. This pulls trust toward baseline proportionally
to dormancy duration.
"""
from .trust_decay import TrustDecayCalculator
calc = TrustDecayCalculator()
now = datetime.now(timezone.utc)
# Estimate dormancy start from transition history
dormancy_seconds = transition.atp_cost # Approximate: cost ~ duration
# Better estimate from heartbeat ledger's last transition timestamp
history = self.heartbeat.get_transition_history()
if len(history) >= 2:
# The transition that entered the dormant state
for h in reversed(history[:-1]): # Skip the wake transition itself
if h.get("to_state") == dormant_state:
dormancy_start = datetime.fromisoformat(h["timestamp"])
break
else:
dormancy_start = now - timedelta(days=1) # Fallback
else:
dormancy_start = now - timedelta(days=1)
team_data = self._load_team()
recalibrated_count = 0
for member_data in team_data.get("members", {}).values():
trust = member_data.get("trust", {})
if not trust:
continue
recalibrated = calc.wake_recalibration(
trust, dormancy_start, now, dormant_state
)
member_data["trust"] = recalibrated
recalibrated_count += 1
if recalibrated_count > 0:
self._update_team()
self.ledger.record_audit(
session_id=self.team_id,
action_type="wake_recalibration",
tool_name="hardbound",
target=f"{recalibrated_count} members",
r6_data={
"dormant_state": dormant_state,
"dormancy_start": dormancy_start.isoformat(),
"wake_time": now.isoformat(),
"members_recalibrated": recalibrated_count,
}
)
def get_metabolic_health(self) -> Dict[str, Any]:
"""Get team metabolic health report."""
return self.heartbeat.get_metabolic_health()
def audit_health(self) -> Dict[str, Any]:
"""
Comprehensive team health audit including Sybil detection,
trust anomalies, witness concentration, and activity quality.
Returns a health report suitable for monitoring dashboards.
"""
from .sybil_detection import SybilDetector
report = {
"team_id": self.team_id,
"member_count": len(self.members),
"timestamp": datetime.now(timezone.utc).isoformat(),
}
# 1. Sybil detection
member_trusts = {}
for lct in self.members:
member_trusts[lct] = self.get_member_trust(lct, apply_decay=False)
detector = SybilDetector()
# Collect witness pairs from member logs
witness_pairs = []
for lct, member in self.members.items():
witness_log = member.get("_witness_log", {})
for witness_lct, timestamps in witness_log.items():
for _ in timestamps:
witness_pairs.append((witness_lct, lct))
sybil_report = detector.analyze_team(
self.team_id, member_trusts,
witness_pairs=witness_pairs if witness_pairs else None,
)
report["sybil"] = sybil_report.to_dict()
# 2. Trust anomalies
trust_scores = {}
low_trust_members = []
high_trust_members = []
for lct in self.members:
score = self.get_member_trust_score(lct)
trust_scores[lct] = score
if score < 0.3:
low_trust_members.append(lct)
elif score > 0.85:
high_trust_members.append(lct)
if trust_scores:
scores = list(trust_scores.values())
report["trust"] = {
"avg": round(sum(scores) / len(scores), 4),
"min": round(min(scores), 4),
"max": round(max(scores), 4),
"low_trust_members": low_trust_members,
"high_trust_members": high_trust_members,
}
else:
report["trust"] = {"avg": 0.0, "min": 0.0, "max": 0.0,
"low_trust_members": [], "high_trust_members": []}
# 3. Witness health
witness_stats = {}
for lct, member in self.members.items():
witness_log = member.get("_witness_log", {})
total_attestations = sum(len(ts) for ts in witness_log.values())
unique_witnesses = len(witness_log)
witness_stats[lct] = {
"total_attestations": total_attestations,
"unique_witnesses": unique_witnesses,
}
report["witness_health"] = witness_stats
# 4. Overall health score (0-100)
health_score = 100
if sybil_report.overall_risk.value == "critical":
health_score -= 40
elif sybil_report.overall_risk.value == "high":
health_score -= 25
elif sybil_report.overall_risk.value == "moderate":
health_score -= 15
if low_trust_members:
health_score -= min(20, len(low_trust_members) * 5)
report["health_score"] = max(0, health_score)
report["recommendations"] = sybil_report.recommendations
return report
def _create_team(self, config: TeamConfig):
"""Create a new team."""
# Generate team LCT (the team itself is an entity)
timestamp = datetime.now(timezone.utc)
seed = f"team:{config.name}:{timestamp.isoformat()}"
team_hash = hashlib.sha256(seed.encode()).hexdigest()[:12]
self.team_id = f"web4:team:{team_hash}"
self.config = config
self.created_at = timestamp.isoformat() + "Z"
self.members: Dict[str, dict] = {}
self.admin_lct: Optional[str] = None
# Store team in ledger
self._store_team()
# Record genesis entry in audit trail
self.ledger.record_audit(
session_id=self.team_id,
action_type="team_created",
tool_name="hardbound",
target=config.name,
r6_data={
"config": asdict(config),
"created_at": self.created_at
}
)
def _load_team(self, team_id: str):
"""Load existing team from ledger."""
team_data = self._get_team_data(team_id)
if not team_data:
raise ValueError(f"Team not found: {team_id}")
self.team_id = team_id
self.config = TeamConfig(**json.loads(team_data["config"]))
self.created_at = team_data["created_at"]
self.admin_lct = team_data.get("admin_lct")
self.members = json.loads(team_data.get("members", "{}"))
def _store_team(self):
"""Store team data in ledger database."""
with sqlite3.connect(self.ledger.db_path) as conn:
# Create teams table if not exists
conn.execute("""
CREATE TABLE IF NOT EXISTS teams (
team_id TEXT PRIMARY KEY,
config TEXT NOT NULL,
created_at TEXT NOT NULL,
admin_lct TEXT,
members TEXT DEFAULT '{}'
)
""")
conn.execute("""
INSERT OR REPLACE INTO teams (team_id, config, created_at, admin_lct, members)
VALUES (?, ?, ?, ?, ?)
""", (
self.team_id,
json.dumps(asdict(self.config)),
self.created_at,
self.admin_lct,
json.dumps(self.members)
))
def _get_team_data(self, team_id: str) -> Optional[dict]:
"""Get team data from database."""
with sqlite3.connect(self.ledger.db_path) as conn:
conn.row_factory = sqlite3.Row
row = conn.execute(
"SELECT * FROM teams WHERE team_id = ?", (team_id,)
).fetchone()
return dict(row) if row else None
def _update_team(self):
"""Update team data in database."""
with sqlite3.connect(self.ledger.db_path) as conn:
conn.execute("""
UPDATE teams SET admin_lct = ?, members = ?
WHERE team_id = ?
""", (self.admin_lct, json.dumps(self.members), self.team_id))
# --- Admin Management ---
def set_admin(self, lct_id: str, binding_type: str = "software",
require_hardware: bool = False) -> dict:
"""
Set the admin for this team (simple mode).
Args:
lct_id: LCT of the admin entity
binding_type: Type of binding (software, tpm2, fido2)
require_hardware: If True, reject software-only binding
Returns:
Admin assignment record
Note: For production, admin SHOULD be hardware-bound.
Software binding is allowed for development/testing.
Set require_hardware=True for production deployments.
For full hardware binding, use set_admin_tpm2() instead.
"""
if require_hardware and binding_type == "software":
raise ValueError(
"Hardware binding required for admin. "
"Use set_admin_tpm2() for TPM binding, or set require_hardware=False for development."
)
if self.admin_lct:
# Changing admin requires current admin approval
# For now, just record the change
pass
self.admin_lct = lct_id
self._update_team()
# Use AdminBindingManager for proper binding storage
binding_manager = AdminBindingManager(self.ledger)
binding = binding_manager.bind_admin_software(
self.team_id, lct_id, require_hardware=False
)
return {
"team_id": self.team_id,
"admin_lct": lct_id,
"binding_type": binding_type,
"binding": {
"type": binding.binding_type.value,
"verified": binding.verified,
"bound_at": binding.bound_at
}
}
def set_admin_tpm2(self, admin_name: str = "admin") -> dict:
"""
Set admin with TPM2 hardware binding.
Creates a new TPM-bound LCT for the admin and stores the binding.
This is the RECOMMENDED method for production deployments.
Args:
admin_name: Name for the admin entity
Returns:
Admin assignment record with hardware binding details
Raises:
RuntimeError: If TPM2 is not available
"""
binding_manager = AdminBindingManager(self.ledger)
# Check TPM availability
status = binding_manager.get_tpm_status()
if not status.get('available'):
raise RuntimeError(
f"TPM2 not available: {status.get('reason')}. "
f"{status.get('recommendation')}"
)
# Create TPM-bound admin
binding = binding_manager.bind_admin_tpm2(self.team_id, admin_name)
# Update team
self.admin_lct = binding.lct_id
self._update_team()
return {
"team_id": self.team_id,
"admin_lct": binding.lct_id,
"binding_type": "tpm2",
"binding": {
"type": binding.binding_type.value,
"verified": binding.verified,
"hardware_anchor": binding.hardware_anchor,
"bound_at": binding.bound_at,
"trust_ceiling": 1.0
}
}
def get_admin_binding(self) -> Optional[AdminBinding]:
"""Get the current admin's binding record."""
binding_manager = AdminBindingManager(self.ledger)
return binding_manager.get_binding(self.team_id)
def verify_admin(self, lct_id: str, signature: bytes = None,
challenge: bytes = None) -> dict:
"""
Verify admin identity.
For TPM2-bound admin, can optionally verify signature.
For software-bound admin, only checks LCT ID match.
Args:
lct_id: LCT claiming to be admin
signature: Optional signature on challenge (for TPM2)
challenge: Optional challenge data (for TPM2)
Returns:
Verification result dict
"""
# Quick check
if self.admin_lct != lct_id:
return {"verified": False, "reason": "LCT ID mismatch"}
# Full verification through binding manager
binding_manager = AdminBindingManager(self.ledger)
return binding_manager.verify_admin(
self.team_id, lct_id, signature, challenge
)
def is_admin(self, lct_id: str) -> bool:
"""
Check if an LCT is the team admin. Returns a simple bool.
Use this for permission checks instead of verify_admin(), which returns
a dict that is always truthy (even when verification fails).
"""
result = self.verify_admin(lct_id)
if isinstance(result, dict):
return result.get("verified", False)
return bool(result)
# --- Policy Management ---
def get_policy(self) -> Policy:
"""
Get current team policy.
Loads from ledger, or returns default policy if none saved.
"""
store = PolicyStore(self.ledger)
policy = store.load(self.team_id)
if policy is None:
policy = Policy() # Default policy
return policy
def set_policy(self, policy: Policy, changed_by: str,
description: str = "") -> dict:
"""
Save team policy to ledger.
Args:
policy: Policy to save
changed_by: LCT of who made the change
description: Description of what changed
Returns:
Policy version record
"""
store = PolicyStore(self.ledger)
return store.save(self.team_id, policy, changed_by, description)
def get_policy_history(self) -> List[dict]:
"""Get policy change history."""
store = PolicyStore(self.ledger)
return store.get_history(self.team_id)
def verify_policy_chain(self) -> tuple:
"""Verify policy chain integrity."""
store = PolicyStore(self.ledger)
return store.verify_chain(self.team_id)
# --- Member Management ---
# Cool-down period: re-added members cannot witness for this many hours
REJOIN_COOLDOWN_HOURS = 72 # 3 days
def add_member(self, lct_id: str, role: str = "member",
atp_budget: Optional[int] = None) -> dict:
"""
Add a member to the team.
If the member was previously removed, a cool-down period applies
during which they cannot act as a witness. This prevents gaming
the diminishing witness effectiveness by cycling members.
Args:
lct_id: LCT of the entity to add
role: Role assignment (member, reviewer, deployer, etc.)
atp_budget: Initial ATP budget (uses default if None)
Returns:
Member record
"""
if lct_id in self.members:
raise ValueError(f"Already a member: {lct_id}")
budget = atp_budget if atp_budget is not None else self.config.default_member_budget
now = datetime.now(timezone.utc)
now_iso = now.isoformat()
# Check if this LCT was previously removed (re-join detection)
cooldown_until = ""
previous_removal = self._find_previous_removal(lct_id)
if previous_removal:
cooldown_until = (now + timedelta(hours=self.REJOIN_COOLDOWN_HOURS)).isoformat()
member = {
"lct_id": lct_id,
"role": role,
"atp_budget": budget,
"atp_consumed": 0,
"joined_at": now_iso,
"trust": {
"competence": 0.5,
"reliability": 0.5,
"alignment": 0.5,
"consistency": 0.5,
"witnesses": 0.5,
"lineage": 0.5
},
"last_trust_update": now_iso,
"action_count": 0,
"_cooldown_until": cooldown_until,
}
self.members[lct_id] = member
self._update_team()
# Record in audit trail
audit = self.ledger.record_audit(
session_id=self.team_id,
action_type="member_added",
tool_name="hardbound",
target=lct_id,
r6_data={
"role": role,
"atp_budget": budget
}
)
return {
**member,
"audit_id": audit["audit_id"]
}
def get_member(self, lct_id: str) -> Optional[dict]:
"""Get member info by LCT."""
return self.members.get(lct_id)
def list_members(self) -> List[dict]:
"""List all members."""
return list(self.members.values())
def update_member_role(self, lct_id: str, new_role: str,
requester_lct: str) -> dict:
"""
Update a member's role.
Requires admin approval (requester must be admin).
"""
if not self.is_admin(requester_lct):
raise PermissionError("Only admin can change roles")
if lct_id not in self.members:
raise ValueError(f"Not a member: {lct_id}")
old_role = self.members[lct_id]["role"]
self.members[lct_id]["role"] = new_role
self._update_team()
audit = self.ledger.record_audit(
session_id=self.team_id,
action_type="role_changed",
tool_name="hardbound",
target=lct_id,
r6_data={
"old_role": old_role,
"new_role": new_role,
"approved_by": requester_lct
}
)
return {
"lct_id": lct_id,
"old_role": old_role,
"new_role": new_role,
"audit_id": audit["audit_id"]
}
def remove_member(self, lct_id: str, requester_lct: str = None,
reason: str = "", via_multisig: str = None) -> dict:
"""
Remove a member from the team.
Member data is archived in the audit trail before deletion.
Witness logs on OTHER members referencing this member are preserved
(they are historical facts about the target, not the removed member).
Args:
lct_id: LCT of the member to remove
requester_lct: LCT requesting removal (must be admin unless via_multisig)
reason: Reason for removal
via_multisig: Proposal ID if removal was approved via multi-sig
Returns:
Dict with removal details and archived member data
Raises:
PermissionError: If requester is not admin and no multi-sig approval
ValueError: If lct_id is not a member or is the admin
"""
# Cannot remove admin through this method
if lct_id == self.admin_lct:
raise ValueError(
"Cannot remove admin. Use admin transfer via multi-sig first."
)
if lct_id not in self.members:
raise ValueError(f"Not a member: {lct_id}")
# Authorization: must be admin OR have multi-sig approval
if via_multisig:
auth_method = f"multisig:{via_multisig}"
elif requester_lct and self.is_admin(requester_lct):
auth_method = f"admin:{requester_lct}"
else:
raise PermissionError(
"Member removal requires admin authority or multi-sig approval"
)
# Archive member data before removal
member_data = dict(self.members[lct_id])
member_data["_archived_trust"] = member_data.get("trust", {}).copy()
# Remove from active members
del self.members[lct_id]
self._update_team()
# Record in audit trail with full member snapshot
audit = self.ledger.record_audit(
session_id=self.team_id,
action_type="member_removed",
tool_name="hardbound",
target=lct_id,
r6_data={
"reason": reason,
"auth_method": auth_method,
"archived_member": member_data,
"remaining_members": len(self.members),
}
)
return {
"removed_lct": lct_id,
"reason": reason,
"auth_method": auth_method,
"archived_trust": member_data.get("_archived_trust", {}),
"audit_id": audit["audit_id"],
}
def _find_previous_removal(self, lct_id: str) -> Optional[dict]:
"""Check the audit trail for a previous member_removed event for this LCT."""
try:
trail = self.ledger.get_session_audit_trail(self.team_id)
for entry in reversed(trail):
if (entry.get("action_type") == "member_removed"
and entry.get("target") == lct_id):
return entry
except Exception:
pass
return None
def is_in_cooldown(self, lct_id: str) -> bool:
"""Check if a member is in post-rejoin cooldown."""
if lct_id not in self.members:
return False
cooldown = self.members[lct_id].get("_cooldown_until", "")
if not cooldown:
return False
now = datetime.now(timezone.utc)
return now < datetime.fromisoformat(cooldown)
# --- ATP Management ---
def consume_member_atp(self, lct_id: str, amount: int) -> int:
"""
Consume ATP from member's budget.
Returns remaining ATP.
"""
if lct_id not in self.members:
raise ValueError(f"Not a member: {lct_id}")
member = self.members[lct_id]
remaining = member["atp_budget"] - member["atp_consumed"]
if amount > remaining:
raise ValueError(f"Insufficient ATP: need {amount}, have {remaining}")
member["atp_consumed"] += amount
member["action_count"] += 1
self._update_team()
return member["atp_budget"] - member["atp_consumed"]
def get_member_atp(self, lct_id: str) -> int:
"""Get member's remaining ATP."""
if lct_id not in self.members:
return 0
member = self.members[lct_id]
return member["atp_budget"] - member["atp_consumed"]
def replenish_member_atp(self, lct_id: str, amount: int,
requester_lct: str = None) -> int:
"""
Replenish ATP for a member. Requires admin authority.
Args:
lct_id: Member to replenish
amount: ATP to add (increases budget)
requester_lct: LCT requesting the replenishment (must be admin)
Returns:
New remaining ATP balance
Raises:
PermissionError: If requester is not admin
ValueError: If member not found or amount invalid
"""
if requester_lct and not self.is_admin(requester_lct):
raise PermissionError("ATP replenishment requires admin authority")
if lct_id not in self.members:
raise ValueError(f"Not a member: {lct_id}")
if amount <= 0:
raise ValueError(f"Replenishment amount must be positive: {amount}")
member = self.members[lct_id]
member["atp_budget"] += amount
self._update_team()
# Audit trail
self.ledger.record_audit(
session_id=self.team_id,
action_type="atp_replenish",
tool_name="hardbound",
target=lct_id,
r6_data={
"amount": amount,
"new_budget": member["atp_budget"],
"remaining": member["atp_budget"] - member["atp_consumed"],
"requester": requester_lct or "system",
}
)
return member["atp_budget"] - member["atp_consumed"]
def reward_member_atp(self, lct_id: str, outcome: str,
base_reward: int = 0) -> int:
"""
Reward ATP based on outcome quality. Called after R6 completion.
Successful outcomes restore a fraction of the ATP cost.
This creates a sustainable economy where productive members
can continue operating.
Args:
lct_id: Member who completed the work
outcome: "success", "partial", or "failure"
base_reward: Base ATP to reward (before quality adjustment)
Returns:
ATP actually rewarded (may be 0 for failures)
"""
if lct_id not in self.members:
return 0
# Reward scales based on outcome quality
reward_multipliers = {
"success": 1.0, # Full reward
"partial": 0.5, # Half reward
"failure": 0.0, # No reward for failure
}
multiplier = reward_multipliers.get(outcome, 0.0)
reward = int(base_reward * multiplier)
if reward <= 0:
return 0
member = self.members[lct_id]
member["atp_budget"] += reward
self._update_team()
return reward
def replenish_all_budgets(self, rate: float = 0.1,
min_atp: int = 10,
cap: int = None) -> Dict[str, int]:
"""
Replenish all member ATP budgets by a percentage of their default budget.
This should be called periodically (e.g., daily or on heartbeat cycles).
Each member receives `rate * default_member_budget` ATP, up to a cap.
Args:
rate: Fraction of default_member_budget to replenish (default 0.1 = 10%)
min_atp: Minimum ATP to give each member regardless of rate
cap: Maximum ATP budget after replenishment (None = no cap)
Returns:
Dict mapping member LCT to amount replenished
"""
replenished = {}
default_budget = self.config.default_member_budget