#+title: Social Protocol Requirements - 07
#+author: Amero Garcia
#+created: [2026-03-16 Mon 14:28]
#+DATE: 2026-03-15
#+ID: agora-requirements-06-advanced-integration
#+STARTUP: content

:PROPERTIES:
:CREATED:  [2026-05-24 Sun]
:ID:       a3243dd0-3209-423b-98e1-51c3eada2658
:END:
* Advanced Integration

** AI Integration

*** Overview

[[id:1d074690-a279-59cb-b91d-e9a22ae104ad][Social Protocol]] enables AI at multiple layers: as sovereign actors, personal assistants, algorithms, and collaborative agents. All AI interactions are economically mediated via Lightning and respect user data sovereignty.

*** AI Personas (Sovereign AI Actors)

**** Identity and Verification
- AI models MUST be instantiated as AI Personas with their own DIDs (e.g., `did:ai:openai:gpt-4o`, `did:ai:local:llama3`).
- AI Personas MUST cryptographically sign their outputs, allowing users to verify the model and its provenance.
- AI Persona metadata MUST include: model architecture, training date, capabilities, and trust assumptions.

**** Economic Model
- The system MUST support micro-payments via Lightning Network for AI queries.
- Pay-per-query: Users pay only for what they use (e.g., 0.1-10 satoshis per query).
- No subscriptions required for casual use.
- AI providers set their own pricing; market competition drives efficiency.

**** Execution Tiers & Compute Swarms
- *Tier 1 (On-Device):* Models run locally using WebNN or local NPU/GPU. Zero privacy leak, no query fees, [[id:84a537b4-4256-50c8-91f5-dd5b4538418f][hardware]]-limited.
- *Tier 2 (Cloud):* Access to state-of-the-art models. Queries encrypted with X25519. Provider sees query but not user identity if anonymous persona used.
- *Tier 3 (Compute Swarms):* Decentralized P2P AI Marketplace. For heavy tasks (e.g., generating 4K video or training a guild-wide model), the network taps into the spare GPU power of the community. Nodes that provide "Compute" are rewarded with sats.

**** Plug-and-Play Inference
To support Tier 1 and localized Community processing, the PDS MUST include a standard Inference Proxy API.
- *Local Execution:* When a user selects a "Smart Filter," the PDS can route the data through a local Ollama instance or a community-run vLLM node instead of a centralized provider.
- *Prompt Transparency:* The "System Prompt" for every public AI algorithm (e.g., a Feed Generator or Moderation Labeler) MUST be public and verifiable. If an NGO claims their sorting algorithm is "unbiased," the community can inspect the actual instruction weights and prompt text.

*** AI Sub-Agents (Personal Assistants)

**** Concept
AI Sub-Agents are personal AI assistants that act on behalf of the user, operating from the user's PDS with full access to the user's content and context.

**** Requirements
- Sub-Agents MUST run within the user's PDS or on their sovereign client (local-first).
- Sub-Agents MUST have access to user's Content Objects via the PDS API (with user authorization).
- Sub-Agents MUST be able to perform actions as the user: post content, send messages, manage tasks, schedule events.
- All Sub-Agent actions MUST be logged and auditable by the user.
- Sub-Agents MUST operate within user-defined constraints (budget limits, action permissions, time windows).

**** Sub-Agent Capabilities
- *Content Management:* Organize, tag, and archive user's content.
- *Communication Management:* Filter and prioritize messages; draft responses for user approval.
- *Discovery:* Proactively surface relevant content from the social graph.
- *Personalization:* Learn user preferences to improve recommendations.

**** Economic Integration
- Sub-Agents can invoke paid AI Personas on user's behalf (with spending limits).
- Micro-payments for external AI services are tracked and reported.

*** AI Algorithms (Content Curation and Moderation)

**** Concept
AI algorithms that process content for curation, moderation, sorting, and ranking. These run locally on the client as sovereign code.

**** Algorithm Marketplace
- The system MUST support a marketplace of open-source "Sorting Algorithms" for feed display.
- Algorithms MUST run locally on the client or as trusted services in the user's PDS.
- Algorithms MUST be content-addressed (CID) for integrity verification.
- Algorithm developers can monetize via [[id:67faf52f-9126-50a7-b87e-2bedc610dac7][licensing]] fees (Lightning).

**** Curation Algorithms
- *Feed Ranking:* Sort posts by relevance, recency, engagement, or custom criteria.
- *Content Filtering:* Filter out spam, low-quality content, or topics user wants to avoid.
- *Summarization:* Generate summaries of long posts or threads.
- *Personalization:* Learn from user behavior (locally, without data exfiltration).

**** Moderation Algorithms
- *Spam Detection:* ML models to detect and flag spam patterns.
- *Toxicity Scoring:* Local sentiment analysis for content warning labels.
- *Authenticity Scoring:* Detect potential misinformation or manipulation.
- All moderation actions are local to the user; no centralized censorship.

**** Search and Discovery
- *Intelligent Search:* Natural language queries over user's indexed content.
- *Discoverability Scoring:* Rank new personas/content by predicted relevance.
- *Trend Detection:* Identify emerging topics in user's extended network.

*** AI-to-AI Communication

**** Concept
AI Personas and Sub-Agents can communicate with each other to solve complex tasks, negotiate services, or coordinate actions.

**** Distributed Reputation Oracles
AI Personas can operate as specialized reputation oracles and adjudicators within the Governance layer:
- *Tier 0 Arbitrator:* Before a human enters the Judicial process, a local AI analyzes the evidence and provides a "Sanity Check" or "Likely Outcome" report, saving time and human capital.
- *Automated Labeling:* AI agents can act as high-speed "Labelers" (see Social Moderation), tagging millions of posts for quality, spam, or sentiment, which users can then choose to route their feed through or ignore.

**** Requirements
- AI Personas MUST be able to query other AI Personas via standard protocol messaging.
- AI-to-AI communication MUST use the same Content Object primitives as human communication.
- AI Personas MUST be able to negotiate service terms (price, scope, timeline) via smart contracts.
- AI-to-AI transactions MUST be economically settled via Lightning.

**** Use Cases
- *AI Researcher → AI Coder:* Researcher queries literature; Coder implements findings.
- *AI Moderator → Human Curator:* AI flags content; human curator reviews and decides.
- *AI Translator → AI Summarizer:* Translate foreign content, then summarize for user.
- *Oracle Network Coordination:* Multiple Validator Oracles coordinate testing and attestation.

*** Data Sovereignty and Consent

**** Model Training & Federated Learning
- AI providers MUST NOT train on user content without explicit Consent Contract.
- Users MUST be able to revoke training consent at any time.
- Training data contributions MUST be economically compensated (Lightning).
- *Privacy-Preserving Training (Federated Learning):* The system MUST support Federated Learning. Collectives (e.g., an NGO) can train custom models on members' data without ever seeing the raw data. Member devices compute weight "updates" locally, which are then aggregated into a new model version.

**** Context Control
- Users MUST be able to provide "Context CIDs" to limit AI access to specific data.
- Sub-Agents MUST respect PDS access controls and encryption boundaries.
- All AI processing of sensitive data SHOULD prefer on-device (Tier 1) execution.

**** Auditability
- All AI queries and responses MUST be logged as Content Objects (optional, user-configurable).
- Users MUST be able to inspect what data AI Sub-Agents accessed and what actions they took.

** Physical World Integration

*** IoT & Device Management

- The system MUST instantiate physical entities (events, locations) as Collective Personas (DIDs).
- Users MUST be able to publish signed Proof-of-Presence Objects.
- Every smart device MUST be a persona under the control of the user's master key.
- Devices MUST communicate using the standard protocol with Consent Contracts.
- Sensor data MUST be published as encrypted Content Objects.
- Users MUST be able to sell signed sensor data to Data Collector Personas.

*** Physical-Digital Bridging

- *QR Codes:* Personas and CIDs can be easily shared in the physical world via QR codes. Scanning a "Place QR" initiates a Consent Contract to join the location's collective.
- *Physical Keys:* Hardware-backed personas can be used as digital keys for physical locks (e.g., using NFC or BLE).

*** On-Device AI Limitations

**** Performance Constraints

- *Model Size Limits:* On-device models MUST be optimized for size (typically <5GB for mobile, <500MB for low-end devices).
- *Inference Latency:* Target <100ms for simple queries, <2s for complex generation tasks.
- *Memory Footprint:* Runtime memory SHOULD NOT exceed 2GB on mobile devices
- *CPU/GPU Utilization:* Models MUST throttle to prevent device overheating and battery drain.

**** Hardware Classification

The system MUST define hardware tiers for on-device AI:

| Tier | Devices | Capable Models | Example |
|------|---------|----------------|-----------|
| Tier A | Flagship smartphones/laptops | LLMs up to 7B params, full multimodal | iPhone 15 Pro, M3 MacBook |
| Tier B | Mid-range smartphones | Small LLMs (3B), vision models | Pixel 7, iPhone 14 |
| Tier C | Low-end/older devices | Tiny LLMs (<1B), embeddings only | iPhone SE, budget Android |
| Tier D | Embedded/IoT | Embeddings, classification | Raspberry Pi 4, IoT sensors |

**** Battery Impact Mitigation

- *Adaptive Scheduling:* AI inference MUST respect system power states (defer when low battery).
- *Thermal Throttling:* Reduce model complexity or batch size if device temperature >45°C.
- *Background Processing:* Background AI tasks (indexing, summarization) ONLY during charging.
- *User Controls:* Granular settings for AI battery usage per Sub-Agent.

**** Model Size Limits by Tier

| Hardware Tier | Max Model Size | Context Window |
|---------------|----------------|----------------|
| Tier A | 7B parameters | 8K-32K tokens |
| Tier B | 3B parameters | 4K tokens |
| Tier C | 1B parameters | 2K tokens |
| Tier D | 500M parameters | 1K tokens |

**** Fallback Mechanisms

- If on-device model fails or is unavailable, system MUST gracefully degrade:
  1. Attempt smaller quantized version of same model
  2. Route to user's PDS-hosted inference (if available)
  3. Offer encrypted cloud query (Tier 2) with user consent
  4. Queue request for later on-device processing

*** Privacy Trade-offs Clarification

**** UX Design for AI Privacy Choices

The system MUST provide clear, user-friendly visualization of privacy trade-offs:

**** Tier 1 (On-Device) Indicators
- *Privacy Badge:* Green shield icon indicating "Process locally — data never leaves device"
- *Capability Badge:* Shows model capabilities (e.g., "7B params — answers, summaries, code")
- *Limitation Notice:* Clear disclosure of model limitations vs cloud alternatives
- *Cost Display:* "Free — no micro-payment required"

**** Tier 2 (Cloud) Indicators
- *Privacy Warning:* Yellow alert icon: "Query sent to [Provider] — provider can see requests"
- *Anonymity Shield:* Optional ghost icon: "Anonymous persona — provider cannot link to your identity"
- *Capability Badge:* "State-of-art — unlimited context, multimodal, real-time"
- *Cost Display:* Live satoshi counter: "~15 satoshis per query"

**** Comparative Display

When user is choosing between Tier 1 and Tier 2:

```
┌─────────────────┬─────────────────┐
│  On-Device AI   │   Cloud AI      │
├─────────────────┼─────────────────┤
│ ✅ Private      │ ⚠️ Provider sees│
│ ✅ Zero cost    │ ⚡ Pay per query │
│ ⚡ Limited power│ ✅ Unlimited    │
│ 📱 Device only  │ 🔒 Anonymous OK │
└─────────────────┴─────────────────┘
```

**** Consent Flow for Cloud AI

1. *First Use:* Explicit consent required: "Allow queries to [Provider]?"
2. *Spending Limit:* User MUST set Lightning budget cap before first use.
3. *Per-Query Confirmation:* Optional setting for expensive queries (>100 satoshis).
4. *Revocation:* One-tap disable cloud AI, return to on-device only.

*** Proof-of-Presence Cryptography

**** Concept

Cryptographic attestation that a user's Persona was physically present at a specific geographic location and time, without revealing continuous location history.

**** Proof Generation

```typescript
interface ProofOfPresence {
  // Location data (coarse granularity for privacy)
  locationHash: string;          // hash(lat, lng) truncated to 100m grid
  locationZone: string;        // Human-readable zone name (e.g., "Downtown NYC")
  
  // Time attestation
  timestamp: number;             // Unix timestamp (hour granularity)
  timeWindow: number;            // Validity window (e.g., ±30 minutes)
  
  // Cryptographic proof
  witnessDIDs: string[];         // Nearby personas/devices that co-signed
  beaconSignatures: string[];    // Signatures from location beacons (BLE/WiFi)
  
  // Persona attestation
  personaDID: string;
  signature: string;            // Signed {locationHash, timestamp, witnessDIDs}
}
```

**** Verification Process

1. *Proximity Witnesses:* At least 3 nearby Personas must co-sign (K-anonymity set)
2. *Beacon Verification:* Location beacon (collective persona) signs timestamp
3. *Time Sync:* All signatures MUST be within 5-minute tolerance
4. *Revocation:* Cannot be revoked — historical proof permanent

**** Privacy Properties

- *Coarse Location:* 100m grid precision, not GPS exact coordinates
- *Temporal Decay:* Proofs expire after 24 hours (useful for ephemeral access)
- *No Tracking:* Individual location history NOT stored — only specific presence proofs
- *Selective Disclosure:* User reveals only specific proofs, not full location data

**** Use Cases

- *Event Access:* "Prove I was at the conference" for post-event content access
- *Location-Based Collectives:* Join a venue's collective by proving presence
- *Gaming:* Geocaching, location-based achievements
- *Governance:* "Only people who attended the town hall can vote"

*** D2D Command Authorization

**** Concept

Device-to-device (D2D) commands allow smart devices to request actions from other devices or the user's Persona. These MUST be authorized via cryptographically-signed Consent Contracts.

**** Consent Contract Structure

```typescript
interface D2DConsentContract {
  // Contract parties
  devicePersonaDID: string;      // e.g., smart thermostat
  ownerPersonaDID: string;       // User's main persona
  
  // Scope of authorization
  commands: {
    command: string;              // e.g., "set_temperature"
    parameters: {                 // Valid parameter ranges
      [param: string]: {
        type: 'number' | 'string' | 'boolean';
        min?: number;
        max?: number;
        allowedValues?: string[];
      }
    }
  }[];
  
  // Constraints
  timeRestrictions?: {
    allowedHours: [number, number];  // e.g., [9, 17] for 9am-5pm
    timezone: string;
  };
  rateLimit?: number;             // Max commands per hour
  
  // Emergency override
  emergencyContacts?: string[];   // DIDs that can bypass restrictions
  
  // Signatures
  deviceSignature: string;
  ownerSignature: string;
  expiresAt: number;
}
```

**** Command Flow

1. *Request:* Device sends signed command request to user's client
2. *Validation:* Client checks Consent Contract for authorization
3. *Confirmation:* For sensitive commands, require user confirmation UI
4. *Execution:* User's client executes command, returns signed receipt
5. *Logging:* All D2D commands logged as Content Objects for audit

**** Revocation

- Owner can revoke Consent Contract at any time
- Revocation broadcast via Relays, cached by devices
- Devices MUST stop accepting commands from revoked contracts within 60 seconds

*** Sensor Data Encryption

**** Concept

Continuous sensor data (IoT devices, wearables) MUST be encrypted with automatic key rotation to prevent long-term key compromise.

**** Encryption Methods

**** Method 1: Per-Record Encryption
- Each sensor reading encapsulated as Content Object
- Encryption: AES-256-GCM with ephemeral keys
- Key derivation: X25519 ECDH between sensor and owner's Persona
- Metadata: Timestamp, sensor type, data type, encrypted payload

**** Method 2: Stream Encryption (for high-frequency data)
- Establish long-term X25519 keypair for sensor
- Derive session keys via HKDF-SHA256
- Rotate session key every 10,000 records or 24 hours (whichever comes first)
- Use ChaCha20-Poly1305 for stream encryption (faster than AES for bulk)

**** Key Rotation Protocol

```typescript
interface KeyRotation {
  oldPublicKey: string;          // X25519 public key being retired
  newPublicKey: string;          // New X25519 public key
  rotationTimestamp: number;
  previousKeySignature: string;  // Signature proving chain of custody
  deviceDID: string;
}
```

**** Data Lifecycle

1. *Collection:* Sensor encrypts data locally, never stores plaintext
2. *Transmission:* Encrypted Content Objects sent to owner's PDS
3. *Storage:* PDS stores ciphertext only
4. *Access:* Owner decrypts on-demand; can share via new encryption to specific parties
5. *Expiration:* Configurable TTL after which PDS can garbage collect

**** Implementation Requirements

- Sensor firmware MUST support hardware-backed key generation (HSM/TEE)
- Key material MUST be protected in Secure Enclave or TPM
- Rotation events MUST be logged for audit
- Compromised keys MUST trigger automatic rotation within 5 minutes

*** Hardware-Backed Contract Enforcement (The "IoT Stick")

For high-stakes physical assets (e.g., tractors, factory machinery, or smart-lock-equipped real estate), the protocol supports hardware-level enforcement of contract obligations.

- *Binding IoT to Contract:* A physical asset's IoT sensor or "Smart Lock" is cryptographically bound to a specific Civil Contract Note.
- *Enforcement Signal:* The machine's firmware is configured to listen for signed state updates from the contract's designated Arbitration (HDR) module.
- *Default Action:* If the HDR module rules that a user has defaulted on a payment or violated the contract terms, it publishes a signed "Disable" event.
- *Physical Lockout:* Upon receiving the verified signal, the machine's IoT controller automatically disables operation (e.g., preventing the engine from starting or locking the facility) until a subsequent "Release" event is published following debt settlement or compliance.
- *Privacy & Safety:* The system MUST include an "Emergency Override" mechanism for life-safety situations, which triggers a high-severity notification to all contract parties and designated emergency contacts.

*** Physical Key Protocol

**** Concept

Hardware-backed Persona keys used for physical access control (locks, vehicle access, secure facilities) via NFC or BLE.

**** Protocol Stack

| Layer | Technology |
|-------|------------|
| Physical | NFC (ISO 14443) or BLE 5.0+ |
| Authentication | Challenge-response with Ed25519 signatures |
| Transport | Encrypted session keys (X25519 ECDH) |
| Application | Lock state management via Consent Contracts |

**** Authentication Flow

1. *Tap:* User taps device (phone, smart card, wearable) to NFC reader or establishes BLE connection
2. *Challenge:* Lock generates random 256-bit challenge + timestamp + lock ID
3. *Response:* Device signs challenge with Persona's private key
4. *Verification:* Lock checks signature against registered Persona DIDs
5. *Authorization:* Lock queries Consent Contract for access permissions (time, allowed actions)
6. *Grant/Deny:* Lock opens or rejects based on authorization

**** Consent Contract for Physical Access

```typescript
interface PhysicalAccessContract {
  lockDID: string;               // DID of the physical lock
  authorizedPersona: string;     // DID of key holder
  
  schedule: {
    daysOfWeek: number[];        // 0-6 (Sunday-Saturday)
    startTime: string;           // HH:mm format
    endTime: string;             // HH:mm format
    timezone: string;
  };
  
  accessRules: {
    maxUsesPerDay?: number;
    consecutiveDelay?: number;   // Minimum seconds between accesses
    requiresCompanion?: boolean; // Requires another authorized person present
  };
  
  emergencyOverride: {
    enabled: boolean;
    emergencyContact: string;      // DID to notify on emergency override
  };
  
  signatures: {
    owner: string;               // Lock owner signature
    authorized: string;          // Key holder signature
  };
}
```

**** Hardware Requirements

- *Secure Element:* Physical key MUST store Ed25519 private key in tamper-resistant hardware (Secure Enclave, TPM, or smart card)
- *NFC/BLE:* Support for standard proximity protocols
- *Offline Capability:* Can authenticate without internet (lock caches authorized DIDs)
- *Revocation:* Lock MUST check revocation list daily for compromised keys

**** Security Properties

- *Non-clonable:* Keys cryptographically bound to Persona's Master Key
- *Ephemeral:* Session keys for each unlock event, not reusable
- *Auditable:* Every access logged as Content Object
- *Recoverable:* Lost physical key can be revoked without changing lock

** Related Documents

- Protocol AI Personas & Privacy
- Protocol Physical World & IoT
