npm package: @longarcstudios/caret
Description: Context Primitive Engine — Structured, sealed, attributable context for AI systems
Author: Long Arc Studios
Latest version: 0.2.1

# ^Caret

**Context Primitive Engine** — Structured, sealed, attributable context for AI systems.

[![npm version](https://badge.fury.io/js/%40longarcstudios%2Fcaret.svg)](https://www.npmjs.com/package/@longarcstudios/caret)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

---

## What is Caret?

Caret is the foundational context layer for AI systems. It provides:

- **Structured Context** — Not raw text, but typed semantic units with metadata
- **Cryptographic Sealing** — Every fragment is hash-sealed and tamper-evident
- **Full Provenance** — Know exactly where context came from and who vouches for it
- **Constraint Resolution** — Time, scope, trust, and signature requirements

**Architecture**: LLM at the edges, cryptography at the core.

---

## Installation

```bash
npm install @longarcstudios/caret
```

---

## Quick Start

```typescript
import { createCaret, maxAge, requireTrust } from '@longarcstudios/caret';

// Initialize the runtime
const caret = createCaret({
  seal_key: process.env.CARET_SEAL_KEY!, // At least 32 chars
});

// Seal content into a fragment
const fragment = await caret.seal({
  content: {
    policy: 'All PTO requests require manager approval',
    effective_date: '2024-01-01',
  },
  source: 'org://hr/policies/pto-2024',
  attribution: 'system',
  constraints: [
    maxAge('30d'),        // Valid for 30 days
    requireTrust(70),     // Minimum trust level 70
  ],
});

console.log(fragment.id);           // UUID
console.log(fragment.hash);         // SHA-256 hash
console.log(fragment.seal);         // HMAC seal
console.log(fragment.provenance);   // Full provenance chain
```

---

## Core Concepts

### Context Fragment

The atomic unit of structured context:

```typescript
interface ContextFragment<T = unknown> {
  id: FragmentId;              // UUID v4
  hash: Hash;                  // SHA-256 of content
  content: SemanticUnit<T>;    // Typed payload
  provenance: ProvenanceChain; // Where it came from
  sealed_at: Timestamp;        // When sealed
  seal: Seal;                  // HMAC for tamper detection
  constraints: Constraint[];   // Usage rules
  version: '1.0';
}
```

### Provenance Chain

Every fragment knows its history:

```typescript
const record = fragment.provenance.head;

console.log(record.source);       // 'org://hr/policies/pto-2024'
console.log(record.attribution);  // 'system' | 'operator' | 'user' | 'agent' | 'external' | 'derived'
console.log(record.trust_level);  // 0-100
console.log(record.timestamp);    // ISO-8601
console.log(record.parent_hash);  // Links to parent fragment
```

### Manifold Composition

Compose multiple fragments within a token budget:

```typescript
const manifold = await caret.compose([
  policyFragment,
  userContextFragment,
  agentStateFragment,
], { 
  ceiling: '8k tokens',
  strategy: 'priority',      // 'concatenate' | 'priority' | 'recency' | 'semantic'
  preserve_provenance: true,
});

console.log(manifold.composition.actual_tokens);     // Actual token count
console.log(manifold.composition.fragments_included); // How many fit
console.log(manifold.composition.fragments_excluded); // How many didn't
```

### Constraint Resolution

Resolve fragments through their constraints:

```typescript
const result = await caret.resolve(fragment, {
  domain: 'hr.company.com',
  min_trust: 50,
});

if (result.success) {
  // Fragment is valid for use
  console.log(result.fragment);
} else {
  // Check what failed
  console.log(result.violations);
}
```

---

## Constraints

Built-in constraint builders:

```typescript
import { 
  maxAge, 
  notBefore, 
  notAfter, 
  allowDomains, 
  requireTrust, 
  requireSignature 
} from '@longarcstudios/caret';

// Time constraints
maxAge('24h')                    // Expires after 24 hours
maxAge(86400000)                 // Same, in milliseconds
notBefore('2024-06-01T00:00:00Z') // Not valid before date
notAfter('2024-12-31T23:59:59Z')  // Not valid after date

// Scope constraints
allowDomains('*.company.com', 'partner.org')

// Trust constraints
requireTrust(80)                 // Minimum trust level

// Signature constraints
requireSignature()               // Any signature required
requireSignature(['alice', 'bob']) // Specific signers
```

---

## API Reference

### `createCaret(options)`

Create a Caret runtime instance.

```typescript
const caret = createCaret({
  seal_key: string;           // Required: HMAC key (32+ chars)
  default_trust?: number;     // Default: 50
  require_signatures?: boolean; // Default: false
  tokenizer?: 'cl100k' | 'p50k' | 'custom';
  custom_tokenizer?: (text: string) => number;
  store?: FragmentStore;      // Custom storage backend
});
```

### `caret.seal(options)`

Seal content into a fragment.

```typescript
const fragment = await caret.seal({
  content: T;                    // Any serializable content
  source: string;                // Source URI
  attribution: Attribution;      // Who created this
  trust_level?: number;          // 0-100
  constraints?: Constraint[];    // Usage rules
  parent?: ContextFragment;      // For derived fragments
  signature?: string;            // Optional signature
});
```

### `caret.compose(fragments, options)`

Compose fragments into a manifold.

```typescript
const manifold = await caret.compose(fragments, {
  ceiling: '8k tokens' | TokenCount;
  strategy?: CompositionStrategy;
  preserve_provenance?: boolean;
  min_trust?: TrustLevel;
});
```

### `caret.resolve(fragment, context?)`

Resolve a fragment through constraints.

```typescript
const result = await caret.resolve(fragment, {
  domain?: string;
  current_time?: Date;
  min_trust?: TrustLevel;
  required_attributions?: Attribution[];
  trusted_signers?: string[];
});
```

### `caret.verify(fragment)`

Verify fragment integrity.

```typescript
const isValid = await caret.verify(fragment);
```

---

## Ecosystem Integration

Caret powers the Long Arc ecosystem:

```
┌─────────────────────────────────────────┐
│            APPLICATION LAYER             │
│     mdash │ Ember │ Your Application     │
└─────────────────────┬───────────────────┘
                      │
┌─────────────────────▼───────────────────┐
│              CARET RUNTIME               │
│   Context Resolution │ Type Checking     │
│   Provenance Tracking │ Constraint Eval  │
└─────────────────────┬───────────────────┘
                      │
┌─────────────────────▼───────────────────┐
│             PRIMITIVE STORE              │
│        Cryptographic │ Immutable         │
└─────────────────────────────────────────┘
```

- **[mdash](https://mdash.sh)** — Agent governance with warrants and physics
- **[Ember](https://ember.mdash.sh)** — Human context for organizations

---

## Security Properties

| Property | Mechanism | Attack Defended |
|----------|-----------|-----------------|
| Tamper Detection | HMAC-SHA256 seals | Content modification |
| Content Integrity | SHA-256 hashing | Collision attacks |
| Provenance Integrity | Hash-linked chains | Chain tampering |
| Replay Prevention | UUID + Timestamp | Replay attacks |
| Attribution Verification | Trust levels | False attribution |

---

## License

MIT © [Long Arc Studios](https://longarcstudios.com)

---

**Built for the long arc of AI progress.**

[Website](https://caret.mdash.sh) · [GitHub](https://github.com/longarcstudios/caret) · [mdash](https://mdash.sh)