# SDK Documentation

Client libraries and integration guides for Episteme (StemeDB).

---

## Go SDK

The official Go client library provides type-safe access to the Episteme API with built-in Ed25519 signing.

### Quick Start

```bash
go get github.com/orchard9/stemedb-go/steme
```

```go
import "github.com/orchard9/stemedb-go/steme"

// Generate keypair
signer, _ := steme.GenerateSigner()

// Create client
client := steme.NewClient("http://localhost:18180", signer)

// Assert a fact
assertion := steme.NewAssertion("Tesla_Inc", "has_revenue").
    WithNumber(96.7).
    WithConfidence(0.95).
    Build()

hash, _ := client.Assert(ctx, assertion)

// Query with conflict resolution
params := steme.NewQuery().
    WithSubject("Tesla_Inc").
    WithPredicate("has_revenue").
    WithLens(steme.LensConsensus).
    Build()

result, _ := client.Query(ctx, params)
```

### Documentation

- **[Go SDK Reference](./go-sdk.md)** - Complete API documentation
- **[Usage Guide](./go-usage-guide.md)** - Patterns and examples
- **[ADK-Go Integration](../references/go-adk/reference-guide.md)** - Building AI agents

---

## Features

### Fluent Builders

The SDK provides fluent builders for readable, type-safe API calls:

```go
// Assertions
assertion := steme.NewAssertion(subject, predicate).
    WithString(value).
    WithConfidence(0.9).
    WithSourceHash(hash).
    WithLifecycle("Approved").
    Build()

// Queries
params := steme.NewQuery().
    WithSubject("Semaglutide").
    WithPredicate("has_side_effect").
    WithLens(steme.LensSkeptic).
    WithAsOf(timestamp).
    Build()

// Votes
vote := steme.NewVote(assertionHash).
    WithWeight(0.8).
    Build()
```

### Automatic Signing

All assertions are automatically signed with Ed25519:

```go
signer, _ := steme.GenerateSigner()
client := steme.NewClient(endpoint, signer)

// Every assertion includes:
// - Timestamp
// - Agent public key
// - Ed25519 signature
```

### Lens Support

Query with different conflict resolution strategies:

```go
// Most recent wins
steme.LensRecency

// Weighted consensus
steme.LensConsensus

// Vote-aware resolution
steme.LensVoteAware

// Surface disagreement
steme.LensSkeptic

// Per-tier breakdown
steme.LensLayered

// Trust-aware authority
steme.LensTrustAware

// Epoch-aware filtering
steme.LensEpochAware
```

---

## AI Agent Integration

### ADK-Go Tools

The SDK integrates with Google ADK-Go for building AI agents:

```go
// Define tools for agents
func QueryKnowledge(ctx context.Context, subject, predicate string, lens string) (string, error) {
    resp, err := episteme.Query(ctx, &QueryParams{
        Subject:   subject,
        Predicate: predicate,
        Lens:      lens,
    })
    if err != nil {
        return "", err
    }
    return formatForAgent(resp), nil
}

func AssertFact(ctx context.Context, subject, predicate, object string) error {
    return episteme.Assert(ctx, &AssertionRequest{
        Subject:    subject,
        Predicate:  predicate,
        Object:     ObjectText(object),
        Confidence: 0.9,
    })
}
```

**[→ Full ADK-Go Guide](../references/go-adk/reference-guide.md)**

---

## Examples

### Basic Workflow

```go
package main

import (
    "context"
    "github.com/orchard9/stemedb-go/steme"
)

func main() {
    ctx := context.Background()

    // Initialize
    signer, _ := steme.GenerateSigner()
    client := steme.NewClient("http://localhost:18180", signer)

    // Write
    assertion := steme.NewAssertion("GLP1_Agonists", "cardiovascular_benefit").
        WithBoolean(true).
        WithConfidence(0.85).
        Build()

    hash, _ := client.Assert(ctx, assertion)

    // Read
    params := steme.NewQuery().
        WithSubject("GLP1_Agonists").
        WithPredicate("cardiovascular_benefit").
        WithLens(steme.LensConsensus).
        Build()

    result, _ := client.Query(ctx, params)
    // result.Winner.Object contains the resolved value
}
```

### Conflict Handling

```go
// Create competing claims
client1.Assert(ctx, steme.NewAssertion("Drug_X", "safety_profile").
    WithString("safe").
    WithConfidence(0.7).
    Build())

client2.Assert(ctx, steme.NewAssertion("Drug_X", "safety_profile").
    WithString("unsafe").
    WithConfidence(0.6).
    Build())

// Query with Skeptic lens to see disagreement
params := steme.NewQuery().
    WithSubject("Drug_X").
    WithPredicate("safety_profile").
    WithLens(steme.LensSkeptic).
    Build()

result, _ := client.Query(ctx, params)
// result.Status: "Contested"
// result.ConflictScore: 0.72
// result.Claims: [{value: "safe", ...}, {value: "unsafe", ...}]
```

### Time Travel

```go
// Query historical state
pastTime := time.Now().Add(-24 * time.Hour)

params := steme.NewQuery().
    WithSubject("Bitcoin").
    WithPredicate("price_usd").
    WithAsOf(pastTime).
    Build()

result, _ := client.Query(ctx, params)
// Returns what was believed 24 hours ago
```

---

## Error Handling

The SDK returns typed errors:

```go
hash, err := client.Assert(ctx, assertion)
if err != nil {
    switch err.(type) {
    case *steme.ValidationError:
        // Invalid assertion structure
    case *steme.SignatureError:
        // Signing failed
    case *steme.NetworkError:
        // Connection issues
    case *steme.QuotaExceededError:
        // Rate limited
    default:
        // Other errors
    }
}
```

---

## Configuration

### Client Options

```go
client := steme.NewClient(endpoint, signer,
    steme.WithTimeout(30*time.Second),
    steme.WithRetry(3),
    steme.WithUserAgent("MyApp/1.0"),
)
```

### Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `STEMEDB_ENDPOINT` | `http://localhost:18180` | API endpoint |
| `STEMEDB_TIMEOUT` | `30s` | Request timeout |
| `STEMEDB_RETRY_COUNT` | `3` | Retry attempts |

---

## Testing

### Mock Client

The SDK provides a mock for testing:

```go
import "github.com/orchard9/stemedb-go/steme/mock"

func TestMyCode(t *testing.T) {
    mockClient := mock.NewClient()

    // Configure expected calls
    mockClient.ExpectAssert(assertion).Return(hash, nil)
    mockClient.ExpectQuery(params).Return(result, nil)

    // Run your code
    myFunction(mockClient)

    // Verify expectations
    mockClient.AssertExpectations(t)
}
```

---

## Performance

### Batching

```go
// Batch assertions
batch := steme.NewBatch()
batch.Add(assertion1)
batch.Add(assertion2)
batch.Add(assertion3)

hashes, err := client.SubmitBatch(ctx, batch)
```

### Connection Pooling

The client automatically manages connection pooling:

```go
// Reuse the client across requests
var globalClient *steme.Client

func init() {
    signer, _ := steme.GenerateSigner()
    globalClient = steme.NewClient(endpoint, signer)
}
```

---

## Migration Guide

### From Direct HTTP

Before:
```go
// Manual HTTP + signing
body := marshal(assertion)
signature := sign(privateKey, body)
req := http.NewRequest("POST", endpoint+"/v1/assert", bytes.NewReader(body))
req.Header.Set("X-Signature", signature)
resp, _ := http.DefaultClient.Do(req)
```

After:
```go
// SDK handles it all
hash, _ := client.Assert(ctx, assertion)
```

---

## Resources

- **[API Reference](../../crates/stemedb-api/README.md)** - HTTP API documentation
- **[Architecture](../../architecture.md)** - System design
- **[Use Cases](../../use-cases/README.md)** - Real-world examples
- **[ADK-Go Examples](../references/go-adk/)** - Agent patterns

---

## Support

- **GitHub Issues**: Report bugs or request features
- **Examples**: See `sdk/go/examples/` directory
- **Integration Help**: Check [ADK-Go Integration](../references/go-adk/reference-guide.md)

---

**[← Back to Documentation Index](../README.md)**
