Skip to content

Experience Layer Contracts (v0 Draft) ​

These contracts fit the existing v0 ecosystem (render_request/render_context_reply). The Experience API exposes an ingest endpoint; retrieval results are embedded into slices.experience[] in render_context_reply.v0.

ExperienceEvent.v0 (ingest) ​

Fields (P0 unless noted)

- version: "v0"
- id: uuid
- request_id: string
- ts_ms: number (epoch ms)
- actor: { type: "user" | "agent", id: string }
- channel: "tool" | "chat" | "code" | "api"
- intent: string
- input?: { text?: string, ids?: string[] }
- output?: { text?: string, ids?: string[] }
- outcome: { status: "success" | "fail" | "partial", error_code?: string }
- entities?: string[]            # L1 entity IDs
- refs?: string[]                # L1 doc IDs or URLs
- privacy: { mode: "allow" | "redact" | "block", pii?: boolean }
- feedback?: { rating?: number, tags?: string[], note?: string }
- kv_policy_hint?: "pin" | "compress" | "evict"
- ttl_ms?: number

P1 optional fields (agreed)

- source_app?: string
- session_id?: string
- project_id?: string
- tenant_id?: string
- tool_name?: string             # concrete tool identifier when channel=="tool"
- locale?: string                # e.g., "en-US"
- repo?: string                  # optional for dev flows
- branch?: string                # optional for dev flows

Response

  • 200 { stored: true, id: uuid }

ExperienceUnit.v0 (summary) ​

Fields

- version: "v0"
- id: uuid
- from_event_ids: string[]
- summary: string                 # 1–3 sentences, privacy-safe
- embedding_ref?: string          # reference to stored vector
- entities?: string[]
- refs?: string[]
- recency_ts_ms: number
- quality_score?: number          # 0..1
- privacy: { mode: "allow" | "redact" | "block" }
- storage?: { size_bytes?: number, compression_ratio?: number }

Retrieval embedding in render_context_reply.v0 ​

Add to slices.experience[]:

- unit_id: string
- summary?: string                # omitted if privacy.mode == "block"
- refs?: string[]
- score: number
- reason?: string                 # short explanation for ranking

Production Implementation Framework ​

API Endpoint Configuration ​

Experience Ingestion API:

yaml
experience_api:
  endpoints:
    ingest: 
      path: "/api/v1/experience"
      method: POST
      content_type: "application/json"
      rate_limits:
        per_minute: 1000
        burst: 50
      timeout_ms: 5000
      
    health:
      path: "/api/v1/experience/health"
      method: GET
      response_format: "application/json"

Comprehensive Testing Framework ​

typescript
describe('L4 Contract Validation Tests', () => {
  describe('ExperienceEvent.v0 Schema Validation', () => {
    test('validates required fields', async () => {
      const valid_event = {
        version: "v0",
        id: "550e8400-e29b-41d4-a716-446655440000",
        request_id: "req_123",
        ts_ms: Date.now(),
        actor: { type: "user", id: "user_123" },
        channel: "tool",
        intent: "debug authentication flow",
        outcome: { status: "success" },
        privacy: { mode: "redact", pii: false }
      };
      
      const validation_result = await validateExperienceEvent(valid_event);
      expect(validation_result.valid).toBe(true);
      expect(validation_result.errors).toHaveLength(0);
    });
    
    test('rejects malformed events', async () => {
      const invalid_event = {
        version: "v0",
        // Missing required fields: id, request_id, ts_ms, etc.
        actor: { type: "invalid_type", id: "user_123" }
      };
      
      const validation_result = await validateExperienceEvent(invalid_event);
      expect(validation_result.valid).toBe(false);
      expect(validation_result.errors).toContain('Missing required field: id');
    });
  });
  
  describe('Privacy Mode Handling', () => {
    test('handles redact mode correctly', async () => {
      const event_with_pii = {
        version: "v0",
        id: "test_id_001",
        input: { text: "User john.doe@company.com needs help" },
        privacy: { mode: "redact", pii: true }
      };
      
      const processed = await processExperienceEvent(event_with_pii);
      expect(processed.input.text).not.toContain('john.doe@company.com');
      expect(processed.input.text).toContain('[EMAIL_REDACTED]');
    });
    
    test('blocks sensitive content in block mode', async () => {
      const sensitive_event = {
        privacy: { mode: "block", pii: true },
        output: { text: "API key: sk-secret123" }
      };
      
      const processed = await processExperienceEvent(sensitive_event);
      expect(processed.blocked).toBe(true);
      expect(processed.output).toBeUndefined();
    });
  });
});

Production Monitoring ​

yaml
experience_contracts_monitoring:
  metrics:
    - name: l4_contract_validation_failures
      type: counter
      labels: [field_name, error_type]
      
    - name: l4_privacy_mode_distribution
      type: gauge  
      labels: [privacy_mode]
      
    - name: l4_event_processing_duration_seconds
      type: histogram
      buckets: [0.001, 0.005, 0.01, 0.05, 0.1]
      
  alerts:
    - name: L4ContractValidationFailures
      condition: rate(l4_contract_validation_failures[5m]) > 0.05
      severity: warning
      
    - name: L4PrivacyModeBlockHigh
      condition: l4_privacy_mode_distribution{privacy_mode="block"} > 0.3
      severity: warning

Error Handling Framework ​

typescript
interface L4ContractError {
  code: 'SCHEMA_VIOLATION' | 'PRIVACY_BREACH' | 'MISSING_REQUIRED_FIELD' | 'INVALID_FORMAT';
  message: string;
  field?: string;
  details?: {
    expected_format?: string;
    received_value?: string;
    suggestions?: string[];
  };
}

// Error Response Examples
const contract_error_responses = {
  schema_violation: {
    error: {
      code: 'SCHEMA_VIOLATION',
      message: 'Actor type must be "user" or "agent"',
      field: 'actor.type',
      details: {
        expected_format: '"user" | "agent"',
        received_value: '"system"',
        suggestions: ['Use "user" for human actors', 'Use "agent" for AI actors']
      }
    }
  }
};

Examples ​

Complete Event Ingestion Example ​

json
{
  "version": "v0",
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "request_id": "req_20250907_001",
  "ts_ms": 1725696000000,
  "actor": { 
    "type": "user", 
    "id": "dev_user_123" 
  },
  "channel": "tool",
  "intent": "implement JWT authentication middleware",
  "input": { 
    "text": "Need to secure API endpoints with JWT validation",
    "ids": ["doc_auth_spec_v1"] 
  },
  "output": { 
    "text": "Created middleware with token validation and error handling",
    "ids": ["code_jwt_middleware_ts", "test_jwt_spec_ts"] 
  },
  "outcome": { 
    "status": "success" 
  },
  "entities": ["ent.jwt", "ent.middleware", "ent.authentication"],
  "refs": ["doc:security/auth.md", "code:middleware/jwt.ts"],
  "privacy": { 
    "mode": "allow", 
    "pii": false 
  },
  "feedback": { 
    "rating": 5, 
    "tags": ["helpful", "complete"], 
    "note": "Perfect implementation with good test coverage" 
  },
  "kv_policy_hint": "pin",
  "session_id": "sess_dev_morning_20250907",
  "project_id": "proj_ecommerce_platform"
}

Experience Unit Generation Example ​

json
{
  "version": "v0",
  "id": "unit_jwt_impl_20250907",
  "from_event_ids": [
    "550e8400-e29b-41d4-a716-446655440000",
    "550e8400-e29b-41d4-a716-446655440001"
  ],
  "summary": "Successfully implemented JWT authentication middleware with comprehensive token validation and error handling for API endpoints.",
  "embedding_ref": "emb_jwt_middleware_summary_384d",
  "entities": ["ent.jwt", "ent.middleware", "ent.authentication"],
  "refs": ["doc:security/auth.md", "code:middleware/jwt.ts"],
  "recency_ts_ms": 1725696000000,
  "quality_score": 0.92,
  "privacy": { 
    "mode": "allow" 
  },
  "storage": { 
    "size_bytes": 2048, 
    "compression_ratio": 0.65 
  }
}

Retrieval Integration Example ​

json
{
  "slices": {
    "experience": [
      {
        "unit_id": "unit_jwt_impl_20250907",
        "summary": "Successfully implemented JWT authentication middleware with comprehensive token validation and error handling for API endpoints.",
        "refs": ["doc:security/auth.md", "code:middleware/jwt.ts"],
        "score": 0.89,
        "reason": "entities overlap: ent.jwt, ent.middleware; high quality score; recent"
      }
    ]
  }
}