# Migration Guide

This guide covers migration between major versions of the ThinkHive SDK.

---

## v3.x to v4.0

### Breaking Changes

#### `apiVersion` Removed from `InitOptions`

The `apiVersion` configuration option has been removed. The SDK now handles API routing internally -- modules automatically route to the correct API version.

```diff
  init({
    apiKey: 'th_xxx',
    serviceName: 'my-agent',
-   apiVersion: 'v3',
  });
```

#### Default Endpoint Changed

The default endpoint is now `https://app.thinkhive.ai` (previously pointed to the staging Cloud Run URL).

```diff
  // If you were relying on the old default, no action needed —
  // the new default points to production.
  // If you explicitly set the old staging URL, remove it:
  init({
    apiKey: 'th_xxx',
    serviceName: 'my-agent',
-   endpoint: 'https://thinkhivemind-h25z7pvd3q-uc.a.run.app',
  });
```

#### Calibration API Changes

`calibration.recordOutcome()` and `calibration.reliabilityDiagram()` have been removed. Use `calibration.status()` to check calibration state.

```diff
- await calibration.recordOutcome({
-   runId: run.id,
-   predictionType: 'churn_risk',
-   predictedValue: 0.7,
-   actualOutcome: 1,
- });
-
- const diagram = await calibration.reliabilityDiagram(agentId);

  // Still available:
  const status = await calibration.status(agentId, 'churn_risk');
```

#### OTLP Init Requires API Key

Initializing the SDK with only an `agentId` is no longer sufficient for OTLP-based tracing. You must provide an `apiKey`.

```diff
  init({
+   apiKey: 'th_xxx',
    agentId: 'agent-123',
    serviceName: 'my-agent',
  });
```

#### Version Bump

The SDK version is now `4.0.0`. Update your `package.json`:

```diff
  "dependencies": {
-   "@thinkhive/sdk": "^3.3.0"
+   "@thinkhive/sdk": "^4.0.0"
  }
```

---

## v2.x to v3.0

This section covers migration from ThinkHive SDK v2.x to v3.0.

## Breaking Changes

### Package Name Change

```diff
- npm install thinkhive-sdk
+ npm install @thinkhive/sdk
```

Update your imports:

```diff
- import ThinkHive from 'thinkhive-sdk';
+ import ThinkHive from '@thinkhive/sdk';
```

### Minimum Node.js Version

- **v2.x**: Node.js 16+
- **v3.0**: Node.js 18+

### Core Concepts Change

v3 is **run-centric**, not trace-centric:

| v2 Concept | v3 Concept |
|------------|------------|
| `trace` | `run` (atomic unit) |
| `TraceOptions` | `RunOptions` |
| `explainer.analyze()` | `runs.create()` + `claims.getRunAnalysis()` |
| `businessContext` | `customerContext` (time-series snapshot) |
| Analysis results | Claims (facts vs inferences) |

## Migration Steps

### 1. Update Initialization

```typescript
// v2
import { init } from 'thinkhive-sdk';

init({
  apiKey: 'th_xxx',
  serviceName: 'my-agent',
});

// v3+
import { init } from '@thinkhive/sdk';

init({
  apiKey: 'th_xxx',
  serviceName: 'my-agent',
});
```

### 2. Migrate Trace Creation to Runs

```typescript
// v2 - Trace-based
import { explainer } from 'thinkhive-sdk';

const result = await explainer.analyze({
  userMessage: 'Help me with my order',
  agentResponse: 'I found your order...',
  outcome: 'success',
  businessContext: {
    customerId: 'cust_123',
    transactionValue: 500,
  },
});

// v3 - Run-based
import { runs, claims } from '@thinkhive/sdk';

// Create a run
const run = await runs.create({
  agentId: 'agent_123',
  conversationMessages: [
    { role: 'user', content: 'Help me with my order' },
    { role: 'assistant', content: 'I found your order...' },
  ],
  outcome: 'resolved',
  customerContext: {
    customerId: 'cust_123',
    arr: 50000,           // Customer ARR at run time
    healthScore: 85,       // Health score at run time
    capturedAt: new Date().toISOString(),
  },
});

// Get analysis with claims (facts vs inferences)
const analysis = await claims.getRunAnalysis(run.id);
```

### 3. Migrate Business Context to Customer Context Snapshots

v3 uses **time-series snapshots** instead of current values:

```typescript
// v2 - Current values
const result = await explainer.analyze({
  userMessage: '...',
  agentResponse: '...',
  businessContext: {
    customerId: 'cust_123',
    transactionValue: 500,
  },
});

// v3 - Point-in-time snapshots
import { customerContext, runs } from '@thinkhive/sdk';

// First, capture customer metrics
const snapshot = await customerContext.captureSnapshot('cust_123', {
  arr: 100000,
  healthScore: 85,
  segment: 'enterprise',
});

// Use the snapshot in your run
const run = await runs.create({
  agentId: 'agent_123',
  conversationMessages: [...],
  customerContext: {
    customerId: 'cust_123',
    arr: snapshot.arr,
    healthScore: snapshot.healthScore,
    capturedAt: snapshot.capturedAt,
  },
});
```

### 4. Migrate to Claims API (Facts vs Inferences)

v3 separates facts from inferences:

```typescript
// v2 - Single analysis result
const result = await explainer.analyze({...});
console.log(result.summary);
console.log(result.outcome.verdict);

// v3 - Claims with evidence
import { claims, isFact, isInference } from '@thinkhive/sdk';

const analysis = await claims.getRunAnalysis(run.id);

// Get all claims
for (const claim of analysis.claims) {
  console.log(`[${claim.claimType}] ${claim.claimText}`);
  console.log(`Confidence: ${claim.confidence}`);

  if (isFact(claim)) {
    console.log('This is an observed fact');
  } else if (isInference(claim)) {
    console.log('This is an LLM inference');
  }
}

// Get facts vs inferences summary
const summary = await claims.summary({ runId: run.id });
console.log(`Facts: ${summary.observed.count}`);
console.log(`Inferences: ${summary.inferred.count}`);
```

### 5. Add Ticket Linking (New in v3)

```typescript
import { runs, generateZendeskMarker, linkRunToZendeskTicket } from '@thinkhive/sdk';

// Method 1: Embed marker in agent response
const run = await runs.create({
  agentId: 'agent_123',
  conversationMessages: [...],
});

const marker = generateZendeskMarker(run.id);
const responseWithMarker = `Your order is on the way! ${marker}`;
// Send responseWithMarker to Zendesk

// Method 2: Explicit linking
await linkRunToZendeskTicket(run.id, '12345');
```

### 6. Add Calibration Tracking (New in v3)

```typescript
import { calibration } from '@thinkhive/sdk';

// Check calibration status
const status = await calibration.status('agent_123', 'churn_risk');
console.log(`Brier score: ${status.brierScore}`);
console.log(`Is calibrated: ${status.isCalibrated}`);
```

## Deprecated APIs

The following v2 APIs still work but are deprecated:

```typescript
// Deprecated - use runs.create() + claims.getRunAnalysis()
import { explainer } from '@thinkhive/sdk';
const result = await explainer.analyze({...}); // Still works

// Deprecated types
import type { TraceOptions, BusinessContext } from '@thinkhive/sdk';
// Use RunOptions, CustomerContextSnapshot instead
```

## New Instrumentation

### OpenAI Assistants

```typescript
import { wrapAssistantRun } from '@thinkhive/sdk/instrumentation/openai';

const run = await wrapAssistantRun(
  () => openai.beta.threads.runs.create(threadId, { assistant_id: assistantId }),
  { assistantId, threadId }
);
```

### LangGraph

```typescript
import { wrapLangGraphNode, wrapLangGraphExecution } from '@thinkhive/sdk/instrumentation/langchain';

// Wrap individual nodes
workflow.addNode('agent', wrapLangGraphNode('agent', agentFunction));

// Wrap entire workflow
const result = await wrapLangGraphExecution('support_workflow', () =>
  compiledGraph.invoke({ messages: [...] })
);
```

## TypeScript Changes

```typescript
// v2 types
import type { TraceOptions, SpanData, BusinessContext } from 'thinkhive-sdk';

// v3 types
import type {
  RunOptions,
  RunOutcome,
  ConversationMessage,
  CustomerContextSnapshot,
  Claim,
  ClaimType,
  AnalysisResult,
  LinkMethod,
  CalibrationStatus,
} from '@thinkhive/sdk';
```

## Need Help?

- Documentation: https://docs.thinkhive.ai
- API Reference: https://api.thinkhive.ai/docs
- Support: support@thinkhive.ai
