agentleFS
airweave-aiairweave-ai/airweave/.cursor/rules/connector-cursors.mdc

airweave / rules

Cursor rule6.6k starsChanged 8 months agoMITArchived repositoryView on GitHub

Cursors enable incremental syncs by tracking progress between executions using typed Pydantic schemas. Instead of untyped dicts, each source defines a cursor schema with validated fields. Create a Pydantic model in platform/cursors/{source_name}.py: Common patterns: Single field (API token): Multiple fields (per-resource): Complex composite (metadata + per-resource): Single field: Multiple fields:

The file

We split this connector-cursors.mdc into the rules it gives an agent

4 rules. About 0 are common, 3 are distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Create a Pydantic model in platform/cursors/{source_name}.py:

    line 28
  2. Distinctive:

    Update cursor incrementally: - Don't wait until sync completes

    line 175
  3. Distinctive:

    Serialize datetimes: - Use ISO format

    line 190
  4. Distinctive:

    Create typed cursor schema

    line 235

≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
connector-cursors.mdc
---
globs: **/sync/**,**/sources/**
alwaysApply: false
---
# Connector Cursors - Typed Incremental Sync

## Overview

Cursors enable **incremental syncs** by tracking progress between executions using **typed Pydantic schemas**. Instead of untyped dicts, each source defines a cursor schema with validated fields.

## Architecture

### Lifecycle
```
1. SyncFactory loads cursor from DB → instantiates typed Pydantic schema
2. Factory injects cursor into source via source.set_cursor()
3. Source reads cursor.data (dict), updates with cursor.update(**fields)
4. Orchestrator saves cursor.get() back to DB after sync
```

### Key Components
- **Cursor Schema** (`platform/cursors/{source}.py`): Pydantic model defining cursor structure
- **Runtime Cursor** (`SyncCursor`): Wrapper providing `update()` and `data` API
- **Source Decorator**: `cursor_class=MyCursor` links source to schema (direct class reference, not string!)

## Creating a Cursor Schema

Create a Pydantic model in `platform/cursors/{source_name}.py`:

```python
from pydantic import Field
from ._base import BaseCursor

class GmailCursor(BaseCursor):
    """Gmail incremental sync cursor using history API."""
    history_id: str = Field(default="", description="Gmail history ID")
```

**Common patterns**:

**Single field** (API token):
```python
class GoogleDriveCursor(BaseCursor):
    start_page_token: str = Field(default="", description="Drive Changes API token")
```

**Multiple fields** (per-resource):
```python
class AirtableCursor(BaseCursor):
    table_cursors: Dict[str, str] = Field(
        default_factory=dict,
        description="Per-table cursor values (table_id -> last_modified_time)"
    )
```

**Complex composite** (metadata + per-resource):
```python
class OutlookMailCursor(BaseCursor):
    delta_link: Optional[str] = Field(None, description="Primary delta link")
    folder_delta_links: Dict[str, str] = Field(default_factory=dict)
    folder_names: Dict[str, str] = Field(default_factory=dict)
```

## Using Cursors in Sources

### 1. Import and Register Cursor

```python
from airweave.platform.cursors import GmailCursor

@source(
    name="Gmail",
    short_name="gmail",
    # ...
    supports_continuous=True,
    cursor_class=GmailCursor,  # Direct class reference - typed!
)
class GmailSource(BaseSource):
    ...
```

### 2. Read Cursor Data

```python
async def generate_entities(self) -> AsyncGenerator[BaseEntity, None]:
    # Get cursor as dict
    cursor_data = self.cursor.data if self.cursor else {}
    last_history_id = cursor_data.get("history_id")

    if last_history_id:
        self.logger.info(f"📊 Incremental sync from history_id={last_history_id}")
        async for entity in self._fetch_incremental(last_history_id):
            yield entity
    else:
        self.logger.info("🔄 Full sync (no cursor)")
        async for entity in self._fetch_all():
            yield entity
```

### 3. Update Cursor

**Single field**:
```python
if self.cursor:
    self.cursor.update(history_id=new_history_id)
```

**Multiple fields**:
```python
if self.cursor:
    self.cursor.update(
        last_repository_pushed_at=pushed_at,
        repo_name=repo_name,
        branch=branch_name,
    )
```

**Dict field**:
```python
if self.cursor:
    # Get current dict
    cursor_data = self.cursor.data
    table_cursors = cursor_data.get("table_cursors", {})

    # Update dict
    table_cursors[f"{schema}.{table}"] = timestamp.isoformat()

    # Write back
    self.cursor.update(table_cursors=table_cursors)
```

## Complete Example

```python
# platform/cursors/github.py
from pydantic import Field
from ._base import BaseCursor

class GitHubCursor(BaseCursor):
    last_repository_pushed_at: str = Field(default="")
    repo_name: Optional[str] = Field(default=None)

# platform/sources/github.py
from airweave.platform.cursors import GitHubCursor

@source(
    name="GitHub",
    short_name="github",
    cursor_class=GitHubCursor,
    supports_continuous=True,
)
class GitHubSource(BaseSource):

    async def generate_entities(self):
        cursor_data = self.cursor.data if self.cursor else {}
        last_pushed_at = cursor_data.get("last_repository_pushed_at")

        if last_pushed_at:
            self.logger.info(f"Incremental sync from {last_pushed_at}")

        async for repo in self._fetch_repos():
            # Process repo...
            yield repo_entity

            # Update cursor
            if self.cursor:
                self.cursor.update(
                    last_repository_pushed_at=repo.pushed_at,
                    repo_name=repo.name,
                )
```

## Best Practices

1. **Update cursor incrementally** - Don't wait until sync completes
   ```python
   async for entity in fetch_entities():
       yield entity
       self.cursor.update(field=entity.timestamp)  # Update as you go
   ```

2. **Always log sync mode** - Help debugging
   ```python
   if last_cursor:
       self.logger.info(f"📊 Incremental sync from {last_cursor}")
   else:
       self.logger.info("🔄 Full sync (first run)")
   ```

3. **Serialize datetimes** - Use ISO format
   ```python
   self.cursor.update(timestamp=dt.isoformat())
   ```

4. **Handle missing cursor** - First sync has no cursor
   ```python
   cursor_data = self.cursor.data if self.cursor else {}
   ```

5. **Check cursor before updating**
   ```python
   if self.cursor:
       self.cursor.update(field=value)
   ```

## Common Pitfalls

❌ **Updating only at end**
```python
# Bad - cursor lost if sync fails
async for entity in entities:
    yield entity
self.cursor.update(last_id=entity.id)  # Only once at end
```

✅ **Update incrementally**
```python
# Good - cursor tracks progress
async for entity in entities:
    yield entity
    if self.cursor:
        self.cursor.update(last_id=entity.id)  # Update each time
```

## System Behavior

**The system automatically**:
- Loads cursor from database before sync (via `sync_cursor_service`)
- Instantiates typed Pydantic model (validates structure)
- Injects cursor into source
- Saves cursor after successful sync
- Skips loading cursor for force_full_sync (but still saves it)

**Sources only need to**:
1. Create typed cursor schema
2. Register via `cursor_class=` decorator
3. Read with `cursor.data`
4. Update with `cursor.update(**fields)`

**Result**: Type-safe incremental syncs with automatic validation and persistence.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.