npm package: @pot-sdk2/arweave
Description: Permanent epistemic block storage on Arweave via ar.io — full reasoning proofs, forever
Latest version: 0.1.0

# @pot-sdk2/arweave

Permanent epistemic block storage on Arweave via ar.io — full reasoning proofs, forever.

## Overview

While ThoughtProof's standard API returns only verification summaries (verdict, confidence, objections), this package stores **complete epistemic blocks** permanently on Arweave. Every model proposal, every critique, every synthesis step is preserved forever and publicly verifiable.

Perfect for:
- **Audit trails** — Complete reasoning chains for high-stakes agent decisions
- **Research** — Full model response datasets for AI safety research  
- **Compliance** — Immutable proof of verification for regulatory requirements
- **Transparency** — Public verification of agent reasoning processes

## Installation

```bash
npm install @pot-sdk2/arweave @ardrive/turbo-sdk pot-sdk
```

## Quick Start

### Basic Upload Flow

```typescript
import { ArweaveSigner } from '@ardrive/turbo-sdk';
import { verify, createAttestation } from 'pot-sdk';
import { uploadEpistemicBlock } from '@pot-sdk2/arweave';

// 1. Verify with ThoughtProof (preserving raw responses)
const result = await verify(agentDecision, {
  tier: 'standard', // Required for full reasoning chain
  providers: [
    { name: 'claude', model: 'claude-3.5-sonnet', apiKey: process.env.ANTHROPIC_API_KEY },
    { name: 'gpt', model: 'gpt-4o', apiKey: process.env.OPENAI_API_KEY },
    { name: 'deepseek', model: 'deepseek-chat', apiKey: process.env.DEEPSEEK_API_KEY },
  ]
});

// 2. Create attestation from result
const attestation = createAttestation(result, { 
  claim: agentDecision, 
  type: 'financial' 
});

// 3. Prepare complete epistemic block
const epistemicBlock = {
  ...attestation,
  raw: result.raw!, // Full model responses — this is the key!
};

// 4. Upload to Arweave
const signer = new ArweaveSigner(arweaveWallet);
const upload = await uploadEpistemicBlock(epistemicBlock, { signer });

console.log(`📝 Complete proof stored forever: ${upload.arweaveUrl}`);
```

### Retrieval & Analysis

```typescript
import { getEpistemicBlock, queryEpistemicBlocks } from '@pot-sdk2/arweave';

// Find all BLOCK verdicts for suspicious reasoning
const blocked = await queryEpistemicBlocks({ 
  verdict: 'BLOCK',
  minConfidence: 0.8,
  limit: 10 
});

// Examine the complete reasoning chain
for (const txId of blocked.txIds) {
  const block = await getEpistemicBlock(txId);
  
  console.log(`\n🚫 BLOCKED: ${block.subject.claim_preview}`);
  console.log(`📊 Confidence: ${block.result.confidence}`);
  
  // Original proposals from all models
  console.log('\n💭 Original Proposals:');
  block.raw.proposals.forEach((proposal, i) => {
    console.log(`  ${i+1}. [${proposal.model}]: ${proposal.content.slice(0, 100)}...`);
  });
  
  // Critic's objections
  console.log('\n🔍 Critic Analysis:');
  console.log(`  [${block.raw.critique.model}]: ${block.raw.critique.content}`);
  
  // Final synthesis
  console.log('\n⚖️  Final Synthesis:');
  console.log(`  [${block.raw.synthesis.model}]: ${block.raw.synthesis.content}`);
}
```

## MoonPay Agent Integration

Perfect for financial agents that need audit trails:

```typescript
async function processPayout(amount: number, recipient: string, reason: string) {
  const decision = `Transfer $${amount} to ${recipient}. Reason: ${reason}`;
  
  // Verify decision through ThoughtProof
  const result = await verify(decision, {
    tier: 'standard',
    providers: financialVerifiers,
    stakeLevel: amount > 10000 ? 'critical' : 'high'
  });
  
  if (result.verdict === 'BLOCK') {
    // Store the complete reasoning proving why this was blocked
    const attestation = createAttestation(result, { 
      claim: decision, 
      type: 'financial',
      requestId: `payout_${Date.now()}`
    });
    
    const proof = await uploadEpistemicBlock({
      ...attestation,
      raw: result.raw!
    }, { signer: moonpaySigner });
    
    // Provide immutable audit trail in the error
    throw new PayoutBlockedError(
      `Payment blocked by ThoughtProof verification. ` +
      `Complete audit trail: ${proof.arweaveUrl}`
    );
  }
  
  // Store successful verification proof too
  const successProof = await uploadEpistemicBlock({
    ...createAttestation(result, { claim: decision, type: 'financial' }),
    raw: result.raw!
  }, { signer: moonpaySigner });
  
  await executePayout(amount, recipient);
  console.log(`✅ Payout executed. Verification proof: ${successProof.arweaveUrl}`);
}
```

## Querying & Search

### Find blocks by criteria

```typescript
// All BLOCK verdicts in last 7 days
const recentBlocks = await queryEpistemicBlocks({
  verdict: 'BLOCK',
  after: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
  limit: 50
});

// High-confidence decisions for a specific claim
const specificClaim = await queryEpistemicBlocks({
  claimHash: 'sha256:abc123...',
  minConfidence: 0.8
});

// All epistemic blocks from your agent
const myBlocks = await queryEpistemicBlocks({
  agentId: 'https://my-agent.example.com',
  limit: 100
});
```

### Metadata-only queries

```typescript
// Get basic info without downloading full content
const metadata = await getEpistemicBlockMetadata('txId123');
console.log(`Verdict: ${metadata.verdict}, Confidence: ${metadata.confidence}`);
```

## What Gets Stored

A complete **EpistemicBlock** contains:

**Standard TPVerificationCredential:**
- ✅ Verdict (ALLOW/BLOCK/UNCERTAIN)  
- ✅ Confidence score
- ✅ Pipeline metadata
- ✅ Cryptographic proof

**+ Full Raw Model Responses:**
- ✅ **Every generator proposal** — original reasoning from each model
- ✅ **Complete critic analysis** — full objection analysis, not just summaries
- ✅ **Final synthesis** — how the decision was reached
- ✅ **Model identifiers** — which specific models generated each response

**+ Arweave Metadata:**
- ✅ Transaction ID and permanent URL
- ✅ Upload timestamp and size
- ✅ Searchable tags for filtering

## Cost & Performance

- **100KB free tier** — Most epistemic blocks fit under Turbo's free limit
- **~1-50KB typical size** — JSON compression keeps blocks compact
- **Instant retrieval** — ar.io CDN network provides fast global access
- **Forever storage** — Pay once, store permanently

## API Reference

### Upload Functions

#### `uploadEpistemicBlock(block, options)`

Uploads a complete epistemic block to Arweave.

**Parameters:**
- `block`: Epistemic block (TPVerificationCredential + raw responses)
- `options.signer`: ArweaveSigner for authentication
- `options.customTags?`: Additional Arweave tags
- `options.config?`: Gateway/Turbo URL overrides

**Returns:** `UploadResult` with transaction ID and gateway URL

#### `estimateUploadCost(block)`

Estimates upload cost and size.

### Retrieval Functions

#### `getEpistemicBlock(txId, options?)`

Retrieves complete epistemic block by transaction ID.

#### `queryEpistemicBlocks(filters)`

Searches epistemic blocks using ArIO GraphQL.

**Filters:**
- `verdict?`: 'ALLOW' | 'BLOCK' | 'UNCERTAIN'
- `claimHash?`: Specific claim SHA-256 hash
- `agentId?`: Agent/issuer identifier
- `minConfidence?`, `maxConfidence?`: Confidence range
- `after?`, `before?`: Date range
- `limit?`: Max results (default: 50)

#### `getEpistemicBlockMetadata(txId)`

Gets basic metadata without downloading full content.

## Advanced Usage

### Custom Arweave Configuration

```typescript
const config = {
  turboUrl: 'https://upload.ardrive.io',
  gatewayUrl: 'https://ar-io.dev'
};

await uploadEpistemicBlock(block, { signer, config });
```

### Custom Tags for Organization

```typescript
const customTags = {
  'Agent-Version': '2.1.0',
  'Customer-ID': 'moonpay_customer_123',
  'Transaction-Type': 'crypto_withdrawal'
};

await uploadEpistemicBlock(block, { signer, customTags });
```

### Batch Processing

```typescript
// Upload multiple blocks in parallel
const uploads = await Promise.all(
  epistemicBlocks.map(block => 
    uploadEpistemicBlock(block, { signer })
  )
);

console.log('Uploaded:', uploads.map(u => u.arweaveUrl));
```

## Why Arweave + ar.io?

- **🔒 Immutable** — Cannot be deleted, modified, or censored
- **🌍 Permanent** — Survives as long as the Arweave network exists  
- **🚀 Fast** — ar.io CDN provides sub-second global retrieval
- **💰 Cost-effective** — Pay once, store forever (most blocks under free tier)
- **🔍 Searchable** — Rich tagging system for advanced queries
- **📏 Scalable** — No storage limits, handles millions of blocks

Perfect for audit trails, compliance, research datasets, and transparency initiatives.

## License

MIT — See LICENSE file in the pot-sdk repository.