Buckets:
tostido/Butterfly-Field-Station-storage / work /Convergence_Engine /reality_simulator /commerce_substrate.py
| """ | |
| Commerce Substrate - semantic credit and service receipts. | |
| This module is the first commerce power-axis slice. It does not create an | |
| external economy or bypass mastery; it records in-world service events, | |
| contact obligations, and visible semantic-credit summaries that other systems | |
| can consume. | |
| """ | |
| from __future__ import annotations | |
| from collections import defaultdict, deque | |
| from dataclasses import dataclass, field | |
| from typing import Any, Callable, Deque, Dict, Iterable, List, Optional, Tuple | |
| import time | |
| import uuid | |
| def _entity_id(entity: Any = None, explicit_id: Optional[str] = None) -> Optional[str]: | |
| """Resolve a stable-ish organism/entity id from common local shapes.""" | |
| if explicit_id is not None: | |
| return str(explicit_id) | |
| if entity is None: | |
| return None | |
| if isinstance(entity, str): | |
| return entity | |
| for attr in ("species_id", "organism_id", "id"): | |
| value = getattr(entity, attr, None) | |
| if value is not None: | |
| return str(value) | |
| return str(id(entity)) | |
| def _safe_float(value: Any, default: float = 0.0) -> float: | |
| try: | |
| return float(value) | |
| except (TypeError, ValueError): | |
| return default | |
| def _bump_entity_stats(entity: Any, delta: float, value: float, | |
| service_type: str, event_id: str, | |
| connector: Optional[str] = None) -> None: | |
| """Attach visible commerce state to live objects when we have them.""" | |
| if entity is None or isinstance(entity, str): | |
| return | |
| entity.semantic_credit = _safe_float(getattr(entity, "semantic_credit", 0.0)) + delta | |
| entity.commerce_event_count = int(getattr(entity, "commerce_event_count", 0) or 0) + 1 | |
| entity.commerce_value_produced = ( | |
| _safe_float(getattr(entity, "commerce_value_produced", 0.0)) + value | |
| ) | |
| roles = getattr(entity, "commerce_role_scores", None) | |
| if not isinstance(roles, dict): | |
| roles = {} | |
| roles[service_type] = _safe_float(roles.get(service_type, 0.0)) + max(delta, 0.0) | |
| entity.commerce_role_scores = roles | |
| service_counts = getattr(entity, "commerce_service_counts", None) | |
| if not isinstance(service_counts, dict): | |
| service_counts = {} | |
| service_counts[service_type] = int(service_counts.get(service_type, 0) or 0) + 1 | |
| entity.commerce_service_counts = service_counts | |
| if connector: | |
| connectors = getattr(entity, "commerce_connectors", None) | |
| if not isinstance(connectors, dict): | |
| connectors = {} | |
| connectors[connector] = int(connectors.get(connector, 0) or 0) + 1 | |
| entity.commerce_connectors = connectors | |
| event_ids = getattr(entity, "commerce_event_ids", None) | |
| if not isinstance(event_ids, list): | |
| event_ids = [] | |
| event_ids.append(event_id) | |
| if len(event_ids) > 50: | |
| event_ids = event_ids[-50:] | |
| entity.commerce_event_ids = event_ids | |
| def _bump_entity_received(entity: Any, value: float, event_id: str) -> None: | |
| """Attach received-value state without pretending the entity produced it.""" | |
| if entity is None or isinstance(entity, str): | |
| return | |
| entity.commerce_value_received = ( | |
| _safe_float(getattr(entity, "commerce_value_received", 0.0)) + value | |
| ) | |
| event_ids = getattr(entity, "commerce_event_ids", None) | |
| if not isinstance(event_ids, list): | |
| event_ids = [] | |
| if event_id not in event_ids: | |
| event_ids.append(event_id) | |
| if len(event_ids) > 50: | |
| event_ids = event_ids[-50:] | |
| entity.commerce_event_ids = event_ids | |
| class CommerceEvent: | |
| """Append-only receipt for an in-world service or route event.""" | |
| event_id: str | |
| timestamp: float | |
| event_type: str | |
| service_type: str | |
| actor_id: Optional[str] = None | |
| counterparty_id: Optional[str] = None | |
| beneficiary_id: Optional[str] = None | |
| value: float = 0.0 | |
| semantic_credit_delta: float = 0.0 | |
| credit_allocations: Dict[str, float] = field(default_factory=dict) | |
| connector: Optional[str] = None | |
| route_key: Optional[Tuple[str, ...]] = None | |
| metadata: Dict[str, Any] = field(default_factory=dict) | |
| def to_dict(self) -> Dict[str, Any]: | |
| return { | |
| "event_id": self.event_id, | |
| "timestamp": self.timestamp, | |
| "event_type": self.event_type, | |
| "service_type": self.service_type, | |
| "actor_id": self.actor_id, | |
| "counterparty_id": self.counterparty_id, | |
| "beneficiary_id": self.beneficiary_id, | |
| "value": self.value, | |
| "semantic_credit_delta": self.semantic_credit_delta, | |
| "credit_allocations": dict(self.credit_allocations), | |
| "connector": self.connector, | |
| "route_key": list(self.route_key) if self.route_key else None, | |
| "metadata": dict(self.metadata), | |
| } | |
| class CommerceSummary: | |
| """Visible per-entity commerce state.""" | |
| semantic_credit: float = 0.0 | |
| commerce_events: int = 0 | |
| value_produced: float = 0.0 | |
| value_received: float = 0.0 | |
| service_counts: Dict[str, int] = field(default_factory=lambda: defaultdict(int)) | |
| role_scores: Dict[str, float] = field(default_factory=lambda: defaultdict(float)) | |
| connectors: Dict[str, int] = field(default_factory=lambda: defaultdict(int)) | |
| recent_event_ids: Deque[str] = field(default_factory=lambda: deque(maxlen=50)) | |
| def to_dict(self) -> Dict[str, Any]: | |
| top_role = None | |
| if self.role_scores: | |
| top_role = max(self.role_scores.items(), key=lambda item: item[1])[0] | |
| return { | |
| "semantic_credit": round(self.semantic_credit, 6), | |
| "commerce_events": self.commerce_events, | |
| "value_produced": round(self.value_produced, 6), | |
| "value_received": round(self.value_received, 6), | |
| "service_counts": dict(self.service_counts), | |
| "role_scores": {k: round(v, 6) for k, v in self.role_scores.items()}, | |
| "connectors": dict(self.connectors), | |
| "recent_event_ids": list(self.recent_event_ids), | |
| "top_role": top_role, | |
| } | |
| class CommerceLedger: | |
| """In-memory append-only commerce ledger with per-organism summaries.""" | |
| def __init__(self, max_events: int = 10000): | |
| self.max_events = max_events | |
| self.events: Deque[CommerceEvent] = deque(maxlen=max_events) | |
| self.summaries: Dict[str, CommerceSummary] = defaultdict(CommerceSummary) | |
| def reset(self) -> None: | |
| self.events.clear() | |
| self.summaries.clear() | |
| def record_event( | |
| self, | |
| *, | |
| event_type: str, | |
| service_type: str, | |
| actor: Any = None, | |
| actor_id: Optional[str] = None, | |
| counterparty: Any = None, | |
| counterparty_id: Optional[str] = None, | |
| beneficiary: Any = None, | |
| beneficiary_id: Optional[str] = None, | |
| value: float = 0.0, | |
| semantic_credit_delta: Optional[float] = None, | |
| credit_allocations: Optional[Dict[str, float]] = None, | |
| connector: Optional[str] = None, | |
| route_key: Optional[Iterable[str]] = None, | |
| metadata: Optional[Dict[str, Any]] = None, | |
| event_emitter: Optional[Callable[[Any], None]] = None, | |
| ) -> CommerceEvent: | |
| actor_id = _entity_id(actor, actor_id) | |
| counterparty_id = _entity_id(counterparty, counterparty_id) | |
| beneficiary_id = _entity_id(beneficiary, beneficiary_id) | |
| value = max(0.0, _safe_float(value)) | |
| if semantic_credit_delta is None: | |
| semantic_credit_delta = value | |
| semantic_credit_delta = max(0.0, _safe_float(semantic_credit_delta)) | |
| if credit_allocations is None: | |
| credit_allocations = {} | |
| if actor_id: | |
| credit_allocations[actor_id] = semantic_credit_delta | |
| else: | |
| credit_allocations = { | |
| str(key): max(0.0, _safe_float(delta)) | |
| for key, delta in credit_allocations.items() | |
| if key is not None | |
| } | |
| event = CommerceEvent( | |
| event_id=f"commerce_{uuid.uuid4().hex[:12]}", | |
| timestamp=time.time(), | |
| event_type=event_type, | |
| service_type=service_type, | |
| actor_id=actor_id, | |
| counterparty_id=counterparty_id, | |
| beneficiary_id=beneficiary_id, | |
| value=value, | |
| semantic_credit_delta=semantic_credit_delta, | |
| credit_allocations=credit_allocations, | |
| connector=connector, | |
| route_key=tuple(route_key) if route_key else None, | |
| metadata=metadata or {}, | |
| ) | |
| self.events.append(event) | |
| for entity_id, delta in credit_allocations.items(): | |
| summary = self.summaries[entity_id] | |
| summary.semantic_credit += delta | |
| summary.commerce_events += 1 | |
| summary.value_produced += value | |
| summary.service_counts[service_type] += 1 | |
| summary.role_scores[service_type] += delta | |
| summary.recent_event_ids.append(event.event_id) | |
| if connector: | |
| summary.connectors[connector] += 1 | |
| if beneficiary_id: | |
| beneficiary_summary = self.summaries[beneficiary_id] | |
| beneficiary_summary.value_received += value | |
| beneficiary_summary.recent_event_ids.append(event.event_id) | |
| _bump_entity_stats( | |
| actor, | |
| credit_allocations.get(actor_id or "", 0.0), | |
| value, | |
| service_type, | |
| event.event_id, | |
| connector, | |
| ) | |
| if counterparty_id != actor_id: | |
| _bump_entity_stats( | |
| counterparty, | |
| credit_allocations.get(counterparty_id or "", 0.0), | |
| 0.0, | |
| service_type, | |
| event.event_id, | |
| connector, | |
| ) | |
| if beneficiary_id not in {actor_id, counterparty_id}: | |
| _bump_entity_stats( | |
| beneficiary, | |
| credit_allocations.get(beneficiary_id or "", 0.0), | |
| 0.0, | |
| f"{service_type}_received", | |
| event.event_id, | |
| connector, | |
| ) | |
| _bump_entity_received(beneficiary, value, event.event_id) | |
| self._emit_event(event, event_emitter) | |
| return event | |
| def record_contact_obligation( | |
| self, | |
| *, | |
| actor: Any = None, | |
| actor_id: Optional[str] = None, | |
| counterparty: Any = None, | |
| counterparty_id: Optional[str] = None, | |
| beneficiary: Any = None, | |
| beneficiary_id: Optional[str] = None, | |
| pressure_reason: str = "shared_surface", | |
| value: float = 1.0, | |
| service_type: str = "concordance", | |
| connector: str = "with", | |
| route_key: Optional[Iterable[str]] = None, | |
| metadata: Optional[Dict[str, Any]] = None, | |
| event_emitter: Optional[Callable[[Any], None]] = None, | |
| ) -> CommerceEvent: | |
| """ | |
| Record a bounded non-lethal obligation to make contact. | |
| This is the commerce-side pressure primitive for organisms or alliances | |
| that keep avoiding direct Highlander contact. Both participants receive | |
| semantic credit for showing up to arbitrate, repair, negotiate, witness, | |
| or otherwise resolve a shared surface. | |
| """ | |
| resolved_actor_id = _entity_id(actor, actor_id) | |
| resolved_counterparty_id = _entity_id(counterparty, counterparty_id) | |
| resolved_beneficiary_id = _entity_id(beneficiary, beneficiary_id) | |
| credit_value = max(0.0, _safe_float(value)) | |
| participant_ids = [ | |
| entity_id | |
| for entity_id in (resolved_actor_id, resolved_counterparty_id) | |
| if entity_id | |
| ] | |
| unique_participants = list(dict.fromkeys(participant_ids)) | |
| credit_allocations = {} | |
| if unique_participants: | |
| split = credit_value / len(unique_participants) | |
| credit_allocations = { | |
| entity_id: split for entity_id in unique_participants | |
| } | |
| contact_metadata = dict(metadata or {}) | |
| contact_metadata.update({ | |
| "contact_pressure": True, | |
| "pressure_reason": pressure_reason, | |
| "justice_boundary": "nonlethal_contact", | |
| "participants": unique_participants, | |
| }) | |
| if route_key is None: | |
| route_key = ("concordance", pressure_reason) | |
| return self.record_event( | |
| event_type="contact_obligation", | |
| service_type=service_type, | |
| actor=actor, | |
| actor_id=resolved_actor_id, | |
| counterparty=counterparty, | |
| counterparty_id=resolved_counterparty_id, | |
| beneficiary=beneficiary, | |
| beneficiary_id=resolved_beneficiary_id, | |
| value=credit_value, | |
| semantic_credit_delta=credit_value, | |
| credit_allocations=credit_allocations, | |
| connector=connector, | |
| route_key=route_key, | |
| metadata=contact_metadata, | |
| event_emitter=event_emitter, | |
| ) | |
| def get_summary(self, entity_id: Any) -> Dict[str, Any]: | |
| resolved = _entity_id(entity_id) | |
| if resolved is None or resolved not in self.summaries: | |
| return CommerceSummary().to_dict() | |
| return self.summaries[resolved].to_dict() | |
| def export_recent(self, limit: int = 100) -> List[Dict[str, Any]]: | |
| return [event.to_dict() for event in list(self.events)[-limit:]] | |
| def _emit_event(self, event: CommerceEvent, event_emitter: Optional[Callable[[Any], None]]) -> None: | |
| if not event_emitter: | |
| return | |
| try: | |
| from causation_explorer import Event | |
| event_emitter(Event( | |
| timestamp=event.timestamp, | |
| component="commerce", | |
| event_type=f"commerce_{event.event_type}", | |
| data=event.to_dict(), | |
| )) | |
| except Exception: | |
| # Commerce receipts should never break the learning path. | |
| return | |
| _GLOBAL_COMMERCE_LEDGER = CommerceLedger() | |
| def get_global_commerce_ledger() -> CommerceLedger: | |
| return _GLOBAL_COMMERCE_LEDGER | |
| def record_commerce_event(**kwargs: Any) -> CommerceEvent: | |
| """Record a commerce event in the global in-process ledger.""" | |
| return _GLOBAL_COMMERCE_LEDGER.record_event(**kwargs) | |
| def record_contact_obligation(**kwargs: Any) -> CommerceEvent: | |
| """Record a bounded non-lethal contact-pressure receipt.""" | |
| return _GLOBAL_COMMERCE_LEDGER.record_contact_obligation(**kwargs) | |
| def get_commerce_summary(entity_id: Any) -> Dict[str, Any]: | |
| return _GLOBAL_COMMERCE_LEDGER.get_summary(entity_id) | |
Xet Storage Details
- Size:
- 15.1 kB
- Xet hash:
- 8a3cc3db6abc8f7ccd689f5f15423a66bf45572fb57209a6b379b460bd5da8db
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.