# StemeDB ADK-Go Integration

ADK-Go tool wrappers for integrating AI agents with Episteme (StemeDB) using Google's Agent Development Kit.

## Overview

This package provides:

- **Tool Definitions**: Query, Assert, ConstraintCheck, Trace, Supersede
- **Callback Helpers**: Confidence escalation, constraint enforcement, audit logging
- **Agent Configuration**: Pre-configured setups for standard agent types

## Installation

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

## Quick Start

```go
package main

import (
    "context"
    "log"

    "github.com/orchard9/stemedb-go/adk"
    "github.com/orchard9/stemedb-go/steme"
)

func main() {
    // Create StemeDB client
    signer, _ := steme.GenerateSigner()
    client := steme.NewClient("http://localhost:18180", signer)

    // Get all Episteme tools
    tools := adk.AllTools(client)

    // Or get pre-configured agent setups
    configs := adk.AllConfigs(
        client,
        0.8, // confidence threshold
        setState,
        log.Printf,
    )

    // Use with your ADK agent
    // agent := configureAgent(configs["implementation"])
}

func setState(key string, value interface{}) {
    // Store session state
}
```

## Tools

### Query Tool

Query Episteme with lens-based conflict resolution.

```go
tool := adk.NewQueryTool(client)

input := adk.QueryInput{
    Subject:       "auth/jwt",
    Predicate:     "signing_algorithm",
    Lens:          "authority",
    Lifecycle:     "approved",
    MinConfidence: 0.8,
}

// Execute returns QueryOutput with resolved value
```

**Critical Rules:**
- Always filter by `lifecycle=approved` for production decisions
- Check confidence thresholds before acting
- Use appropriate lens (authority, consensus, recency)

### Assert Tool

Store knowledge with lifecycle and confidence.

```go
tool := adk.NewAssertTool(client)

input := adk.AssertInput{
    Subject:    "Tesla_Inc",
    Predicate:  "has_revenue",
    Object:     96.7,
    SourceHash: "0000...0000", // BLAKE3 hash of evidence
    Confidence: 0.95,
    Lifecycle:  "proposed", // Default to proposed
}

// Execute returns AssertOutput with content-addressed hash
```

**Critical Rules:**
- Always include `source_hash` for provenance
- Use confidence to express uncertainty (0.0-1.0)
- Default to `lifecycle=proposed` (not approved)
- Store conflicting sources without resolving

### Constraint Check Tool

Pre-flight validation for Implementation Agent.

```go
tool := adk.NewConstraintCheckTool(client)

input := adk.ConstraintCheckInput{
    Context: "auth_jwt",
}

// Execute returns ConstraintCheckOutput with must-use and forbidden patterns
```

**Critical Rules:**
- Implementation Agent MUST call before code generation
- Returns both positive (must_use) and negative (forbidden) constraints
- Enables contrastive learning ("use X, not Y, because Z")

### Trace Tool

Audit trail queries for incident investigation.

```go
tool := adk.NewTraceTool()

input := adk.TraceInput{
    AgentID: "deployment-agent",
    From:    "-6h",
    Subject: "auth/*",
}

// Execute returns TraceOutput with query history
```

**Use Cases:**
- On-Call SRE: "What did the agent query during the incident?"
- Human Supervisor: "What values did the agent see at that time?"
- Incident investigation: Sub-second trace queries

### Supersede Tool

Error correction with cascade tracking.

```go
tool := adk.NewSupersedeTool()

input := adk.SupersedeInput{
    Hash:   "bad_assertion_hash",
    Reason: "Proposal treated as approved",
    Type:   "Invalidate",
}

// Execute returns SupersedeOutput with affected assertions
```

**Use Cases:**
- Correct bad assertions
- Track downstream impact
- Incident remediation

## Callbacks

### Constraint Enforcement

Enforce constraints before code generation.

```go
callback := adk.ConstraintEnforcementCallback(client, []string{
    "write_code",
    "generate_config",
})

// Use in agent config
agent.BeforeToolCallback = callback
```

Blocks code generation if forbidden patterns would be used.

### Confidence Escalation

Escalate to human when confidence is too low.

```go
callback := adk.ConfidenceEscalationCallback(0.8, setState)

// Use in agent config
agent.AfterToolCallback = callback
```

Sets session state for human review when confidence < threshold.

### Audit Logging

Log all tool calls for debugging.

```go
callback := adk.AuditLoggingCallback(log.Printf)

// Use in agent config
agent.AfterToolCallback = callback
```

### Chaining Callbacks

Combine multiple callbacks.

```go
beforeCallback := adk.ChainBeforeCallbacks(
    adk.ConstraintEnforcementCallback(client, codeGenTools),
    customValidation,
)

afterCallback := adk.ChainAfterCallbacks(
    adk.ConfidenceEscalationCallback(0.8, setState),
    adk.AuditLoggingCallback(log.Printf),
)
```

## Agent Configurations

### Implementation Agent

Writes code against approved patterns only.

```go
config := adk.ConfigForImplementationAgent(client, log.Printf)
```

**Features:**
- Queries only approved patterns
- Checks constraints before code generation
- Blocks forbidden patterns
- Audit logging

**Workflow:**
1. Query approved pattern
2. Check constraints
3. Write code
4. Never use proposed/deprecated patterns

### Lead Orchestrator

Coordinates agent team based on knowledge state.

```go
config := adk.ConfigForLeadOrchestrator(
    client,
    0.8, // confidence threshold
    setState,
    log.Printf,
)
```

**Features:**
- Queries with appropriate lens
- Confidence threshold escalation
- Routes work to implementation or human
- Audit logging

**Workflow:**
1. Query current state
2. Check confidence
3. If high: route to implementation
4. If low: escalate to human

### Research Agent

Discovers and stores knowledge with source attribution.

```go
config := adk.ConfigForResearchAgent(client, log.Printf)
```

**Features:**
- Stores all sources (even conflicting)
- Expresses uncertainty via confidence
- Marks as proposed (not approved)
- Source provenance tracking

**Workflow:**
1. Research from multiple sources
2. Create assertion for each source
3. Don't resolve conflicts (store all)
4. Let orchestrator resolve via lens

### Human Supervisor

Investigates incidents and corrects knowledge.

```go
config := adk.ConfigForHumanSupervisor(client, log.Printf)
```

**Features:**
- Time-travel queries (as_of parameter)
- Trace queries
- Supersede for corrections
- Approve proposed assertions

**Workflow:**
1. Time-travel to incident
2. Trace agent queries
3. Identify bad assertion
4. Supersede with correction
5. Verify fix

### On-Call SRE

Fast incident investigation via trace queries.

```go
config := adk.ConfigForOnCallSRE(client, log.Printf)
```

**Features:**
- Sub-second trace queries
- Fast read-only investigation
- Escalation to supervisor for corrections

**Workflow (under 10 minutes):**
1. Trace: What did agent query?
2. Diff: What changed?
3. Identify: Which assertion is bad?
4. Escalate: Flag for supervisor

## Agent Coordination Pattern

```go
// Create multi-agent pipeline
client := steme.NewClient("http://localhost:18180", signer)

configs := adk.AllConfigs(client, 0.8, setState, log.Printf)

// Research Agent: Discovers knowledge
researchAgent := configureAgent(configs["research"])

// Lead Orchestrator: Routes based on confidence
leadAgent := configureAgent(configs["lead"])

// Implementation Agent: Writes code
implAgent := configureAgent(configs["implementation"])

// Sequential pipeline
pipeline := sequentialAgent(researchAgent, leadAgent, implAgent)
```

## Session State vs. Episteme

| Use Case | Mechanism | Why |
|----------|-----------|-----|
| Agent handoff in pipeline | Session State + OutputKey | Ephemeral, same conversation |
| Permanent org knowledge | Episteme Assert | Persists across sessions |
| "What was decided here?" | Session State | Temporary |
| "What should agents know forever?" | Episteme + lifecycle:approved | Permanent |
| Agent decision audit | Episteme QueryAudit | Immutable, time-travel |

## Testing

```bash
cd sdk/go/adk
go test -v
```

Tests include:
- Tool execution with mock client
- Confidence threshold enforcement
- Constraint checking
- Config creation
- Lifecycle/lens parsing

## Interface-Based Design

Since ADK-Go is not yet publicly released, this package uses interface-based design:

```go
// Generic tool interface
type Tool interface {
    Name() string
    Description() string
    Execute(ctx context.Context, input []byte) ([]byte, error)
}

// Generic client interface
type EpistemeClient interface {
    Query(ctx context.Context, params steme.QueryParams) (*steme.QueryResult, error)
    Assert(ctx context.Context, assertion steme.Assertion) (string, error)
}
```

This allows:
- Easy testing with mock clients
- Adaptation to any ADK implementation
- Standalone usage without ADK

## Examples

See `.claude/guides/integrations/adk-go-episteme.md` for complete examples:

- Multi-agent pipeline
- Confidence escalation
- Constraint enforcement
- Time-travel queries
- Incident investigation

## For More Information

- **Use case context**: [use-cases/agile-agent-team.md](../../../use-cases/agile-agent-team.md)
- **Integration guide**: [.claude/guides/integrations/adk-go-episteme.md](../../../.claude/guides/integrations/adk-go-episteme.md)
- **Base SDK**: [sdk/go/steme/](../steme/)
