> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pryveo.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Shared Memory System

> Access centralized user data with fine-grained permissions

# Shared Memory System

Pryveo's Shared Memory system transforms the platform into a comprehensive AI OS layer by providing apps with access to centralized user data—calendar events, files, browsing history, contacts, and more—all with fine-grained permission control.

<Card title="Privacy First" icon="shield-check" color="#10b981">
  All shared memory data stays on the user's device. Apps request specific permissions, and every access is logged in an audit trail.
</Card>

## Overview

Instead of each app maintaining its own isolated data silos, Pryveo offers a unified knowledge base that apps can access with explicit user permission.

### Available Data Types

<CardGroup cols={2}>
  <Card title="User Profile" icon="user">
    Name, email, preferences, timezone
  </Card>

  <Card title="Calendar Events" icon="calendar">
    Upcoming meetings, all-day events, locations
  </Card>

  <Card title="File Index" icon="folder">
    Indexed files with content snippets
  </Card>

  <Card title="Browsing History" icon="globe">
    Recently visited websites and pages
  </Card>

  <Card title="Conversations" icon="messages">
    Chat history across all apps
  </Card>

  <Card title="Contacts" icon="users">
    Personal and professional contacts
  </Card>

  <Card title="Clipboard History" icon="clipboard">
    Recent clipboard entries
  </Card>
</CardGroup>

## Architecture

```mermaid theme={null}
graph TB
    A[WASM Apps] -->|Request with Permissions| B[Shared Memory Manager]
    B -->|Check Access| C[Permission Checker]
    B -->|Log Access| D[Audit Log]
    B -->|Read/Write| E[SQLite Database]
    F[Data Providers] -->|Sync| E
    F -->|Calendar Sync| G[macOS Calendar]
    F -->|File Watching| H[File System]
    F -->|History Parsing| I[Browsers]
    F -->|Clipboard Monitor| J[System Clipboard]
```

## Permissions

Apps must declare shared memory permissions in their `manifest.json`:

```json theme={null}
{
  "id": "com.example.myapp",
  "name": "My App",
  "permissions": {
    "permissions": [
      "shared_memory_calendar_read",
      "shared_memory_files_read",
      "shared_memory_contacts_read"
    ],
    "reasons": {
      "shared_memory_calendar_read": "To show your upcoming schedule",
      "shared_memory_files_read": "To help you find documents",
      "shared_memory_contacts_read": "To suggest meeting participants"
    }
  }
}
```

### Permission Types

| Permission                          | Description                           |
| ----------------------------------- | ------------------------------------- |
| `shared_memory_user_profile`        | Read/write user profile               |
| `shared_memory_calendar_read`       | Read calendar events                  |
| `shared_memory_calendar_write`      | Create/update/delete events           |
| `shared_memory_calendar`            | Full calendar access (read + write)   |
| `shared_memory_files_read`          | Search indexed files                  |
| `shared_memory_browsing_history`    | Read browsing history                 |
| `shared_memory_conversations_read`  | Read conversation history             |
| `shared_memory_conversations_write` | Create conversations, append messages |
| `shared_memory_conversations`       | Full conversation access              |
| `shared_memory_contacts_read`       | Read contacts                         |
| `shared_memory_contacts_write`      | Create/update/delete contacts         |
| `shared_memory_contacts`            | Full contacts access                  |
| `shared_memory_clipboard_history`   | Read clipboard history                |

<Note>
  Write permissions automatically grant read access. For example, `shared_memory_calendar_write` implies `shared_memory_calendar_read`.
</Note>

## SDK Usage

### User Profile

```rust theme={null}
use pryveo_sdk::prelude::*;

fn main_app() -> Result<()> {
    // Get user profile
    let profile = get_user_profile()?;
    log(LogLevel::Info, &format!("Hello, {}!", 
        profile.name.unwrap_or("User".to_string())))?;
    
    Ok(())
}
```

### Calendar Events

```rust theme={null}
use pryveo_sdk::prelude::*;

fn show_upcoming_events() -> Result<()> {
    // List events (None for all dates)
    let events = list_calendar_events(None, None)?;
    
    for event in events.iter().take(5) {
        log(LogLevel::Info, &format!("📅 {} - {}", 
            event.title, 
            event.start_time))?;
            
        if let Some(location) = &event.location {
            log(LogLevel::Info, &format!("   📍 {}", location))?;
        }
    }
    
    Ok(())
}
```

### File Search

```rust theme={null}
use pryveo_sdk::prelude::*;

fn search_documents() -> Result<()> {
    // Search for files containing "rust"
    let files = search_files("rust", 10)?;
    
    for file in files {
        log(LogLevel::Info, &format!("Found: {} ({})", 
            file.filename, 
            file.path))?;
            
        if let Some(snippet) = file.content_snippet {
            log(LogLevel::Info, &format!("  Preview: {}", snippet))?;
        }
    }
    
    Ok(())
}
```

### Browsing History

```rust theme={null}
use pryveo_sdk::prelude::*;

fn search_history() -> Result<()> {
    // Search browsing history
    let entries = search_browsing_history("github", 5)?;
    
    for entry in entries {
        log(LogLevel::Info, &format!("🌐 {}", 
            entry.title.unwrap_or("Untitled".to_string())))?;
        log(LogLevel::Info, &format!("   {}", entry.url))?;
    }
    
    Ok(())
}
```

### Conversations

```rust theme={null}
use pryveo_sdk::prelude::*;

fn manage_conversations() -> Result<()> {
    // List all conversations
    let convos = list_conversations()?;
    log(LogLevel::Info, &format!("You have {} conversations", convos.len()))?;
    
    // Create new conversation
    let messages = vec![
        Message {
            role: "user".to_string(),
            content: "Hello!".to_string(),
            timestamp: chrono::Utc::now().to_rfc3339(),
        }
    ];
    let convo_id = create_conversation(&messages)?;
    
    // Append to conversation
    let new_message = Message {
        role: "assistant".to_string(),
        content: "Hi there!".to_string(),
        timestamp: chrono::Utc::now().to_rfc3339(),
    };
    append_to_conversation(&convo_id, &new_message)?;
    
    Ok(())
}
```

### Contacts

```rust theme={null}
use pryveo_sdk::prelude::*;

fn list_my_contacts() -> Result<()> {
    let contacts = list_contacts()?;
    
    for contact in contacts {
        log(LogLevel::Info, &format!("👤 {}", contact.name))?;
        if let Some(email) = contact.email {
            log(LogLevel::Info, &format!("   ✉️  {}", email))?;
        }
    }
    
    Ok(())
}
```

### Clipboard History

```rust theme={null}
use pryveo_sdk::prelude::*;

fn recent_clipboard() -> Result<()> {
    // Get last 5 clipboard entries
    let entries = list_clipboard_history(5)?;
    
    for (i, entry) in entries.iter().enumerate() {
        log(LogLevel::Info, &format!("{}. \"{}\"", 
            i + 1, 
            truncate(&entry.content, 50)))?;
    }
    
    Ok(())
}
```

## Data Providers

Shared memory data is populated by **data providers** that run in the background:

### Calendar Provider

* **macOS**: Integrates with Calendar.app via AppleScript
* **Windows**: Outlook/Windows Calendar integration (planned)
* **Linux**: Evolution/Thunderbird support (planned)
* **Sync**: Every 10 minutes

### File Watcher

* Uses `notify` crate for real-time file system monitoring
* Indexes text files with content snippets
* Supports 20+ file types (rs, js, py, md, json, etc.)
* Respects `.gitignore` patterns
* Watches user-configured directories

### Browser Monitor

* Parses browser history databases
* Supported browsers: Chrome, Firefox, Safari, Edge, Brave
* Platform-specific database paths
* Syncs every 5 minutes
* Last 1000 entries per browser

### Clipboard History

* Monitors system clipboard changes
* Polls every 500ms
* Stores last 100 entries (configurable)
* Text content only

## Privacy Controls

Users have complete control over shared memory:

### Privacy Dashboard

Access via the Privacy tab in Pryveo:

1. **Data Summary**: View how much data is stored
2. **Audit Log**: See every app access with timestamp
3. **Permission Management**: Grant/revoke per-app permissions
4. **Data Export**: Download all data as JSON
5. **Data Deletion**: Clear specific data types
6. **Provider Settings**: Enable/disable data collection

### Permission Flow

```mermaid theme={null}
sequenceDiagram
    App->>Permission Checker: Request calendar access
    Permission Checker->>Manifest: Check declared permissions
    Manifest-->>Permission Checker: Permission listed
    Permission Checker->>User: Show permission prompt
    User-->>Permission Checker: Grant/Deny
    Permission Checker->>Audit Log: Log decision
    Permission Checker-->>App: Access granted/denied
```

## Error Handling

```rust theme={null}
use pryveo_sdk::prelude::*;

fn safe_calendar_access() -> Result<()> {
    match list_calendar_events(None, None) {
        Ok(events) => {
            log(LogLevel::Info, &format!("Found {} events", events.len()))?;
        }
        Err(e) => {
            // Permission denied or not available
            log(LogLevel::Warn, &format!("Calendar access failed: {}", e))?;
            log(LogLevel::Info, "Request calendar permission in manifest.json")?;
        }
    }
    
    Ok(())
}
```

## Best Practices

<AccordionGroup>
  <Accordion title="Request Only What You Need">
    Only request shared memory permissions that are essential for your app's functionality. Users are more likely to grant specific, justified permissions.
  </Accordion>

  <Accordion title="Provide Clear Reasons">
    Always include a `reasons` field explaining why each permission is needed. Be specific and user-friendly.
  </Accordion>

  <Accordion title="Handle Missing Data Gracefully">
    Not all users will have all data types populated. Handle empty results and errors elegantly.
  </Accordion>

  <Accordion title="Respect Privacy">
    Even with permission, use shared memory data responsibly. Don't store sensitive data in logs or external storage.
  </Accordion>

  <Accordion title="Minimize Data Access">
    Only access shared memory when needed. Batch operations and cache results appropriately.
  </Accordion>
</AccordionGroup>

## Complete Example

See [LifeOS Assistant](/lifeos-assistant) for a complete working example that demonstrates all shared memory features.

## API Reference

### Types

```rust theme={null}
pub struct UserProfile {
    pub name: Option<String>,
    pub email: Option<String>,
    pub preferences: Option<serde_json::Value>,
    pub timezone: Option<String>,
}

pub struct CalendarEvent {
    pub id: String,
    pub title: String,
    pub description: Option<String>,
    pub start_time: String, // ISO 8601
    pub end_time: String,
    pub location: Option<String>,
    pub all_day: bool,
    pub source: Option<String>,
    pub created_at: String,
    pub updated_at: String,
}

pub struct FileEntry {
    pub id: String,
    pub path: String,
    pub filename: String,
    pub content_snippet: Option<String>,
    pub file_type: Option<String>,
    pub size_bytes: Option<i64>,
    pub last_modified: String,
    pub indexed_at: String,
}

pub struct BrowsingHistoryEntry {
    pub id: String,
    pub url: String,
    pub title: Option<String>,
    pub visit_time: String,
    pub duration_seconds: Option<i64>,
    pub source_browser: Option<String>,
    pub created_at: String,
}

pub struct Conversation {
    pub id: String,
    pub app_id: String,
    pub title: Option<String>,
    pub messages: Vec<Message>,
    pub created_at: String,
    pub updated_at: String,
}

pub struct Message {
    pub role: String, // "user" | "assistant" | "system"
    pub content: String,
    pub timestamp: String,
}

pub struct Contact {
    pub id: String,
    pub name: String,
    pub email: Option<String>,
    pub phone: Option<String>,
    pub notes: Option<String>,
    pub created_at: String,
    pub updated_at: String,
}

pub struct ClipboardEntry {
    pub id: String,
    pub content: String,
    pub content_type: String,
    pub timestamp: String,
}
```

### Functions

```rust theme={null}
// User Profile
pub fn get_user_profile() -> Result<UserProfile>
pub fn update_user_profile(profile: &UserProfile) -> Result<()>

// Calendar
pub fn list_calendar_events(start: Option<String>, end: Option<String>) -> Result<Vec<CalendarEvent>>
pub fn create_calendar_event(event: &CalendarEvent) -> Result<String>
pub fn update_calendar_event(event: &CalendarEvent) -> Result<()>
pub fn delete_calendar_event(event_id: &str) -> Result<()>

// Files
pub fn search_files(query: &str, limit: usize) -> Result<Vec<FileEntry>>
pub fn get_file_content(file_id: &str) -> Result<String>

// Browsing History
pub fn search_browsing_history(query: &str, limit: usize) -> Result<Vec<BrowsingHistoryEntry>>

// Conversations
pub fn list_conversations() -> Result<Vec<Conversation>>
pub fn create_conversation(messages: &[Message]) -> Result<String>
pub fn append_to_conversation(conv_id: &str, message: &Message) -> Result<()>

// Contacts
pub fn list_contacts() -> Result<Vec<Contact>>
pub fn create_contact(contact: &Contact) -> Result<String>
pub fn update_contact(contact: &Contact) -> Result<()>
pub fn delete_contact(contact_id: &str) -> Result<()>

// Clipboard History
pub fn list_clipboard_history(limit: usize) -> Result<Vec<ClipboardEntry>>
```

<Note>
  All functions require appropriate permissions declared in `manifest.json` and granted by the user.
</Note>

## Platform Support

| Feature           | macOS | Windows | Linux |
| ----------------- | ----- | ------- | ----- |
| User Profile      | ✅     | ✅       | ✅     |
| Calendar Sync     | ✅     | 🚧      | 🚧    |
| File Indexing     | ✅     | ✅       | ✅     |
| Browser History   | ✅     | ✅       | ✅     |
| Conversations     | ✅     | ✅       | ✅     |
| Contacts          | ✅     | 🚧      | 🚧    |
| Clipboard History | ✅     | ✅       | ✅     |

✅ = Fully supported | 🚧 = Planned

<Tip>
  Contribute platform-specific implementations! See the [developer guide](/app-development) for details.
</Tip>
