Skip to content

Interfaces & Contracts (L2) ​

This page defines L2 boundaries with upstream L1 (Noosphere), downstream Orchestration (L3), and cross-cutting Evaluation (L8).

Headers and common fields ​

  • Authorization: Authorization: Bearer <token> (if applicable)
  • Correlation: X-Request-ID, X-Agent-ID, X-User-ID (optional)
  • Budgets (hints): X-Budget-Time-Ms, X-Top-K

Ingestion API (curation/sync) ​

Endpoint: POST /api/v1/project-library/ingest.v0

Request body:

json
{
  "project_id": "proj_123",
  "items": [
    { "l1_document_id": "doc_1", "fragment": "#p3", "score_hint": 0.92 },
    { "l1_document_id": "doc_2" }
  ],
  "sync_cursor": "opaque",
  "idempotency_key": "batch_2025_09_01"
}

Response:

json
{ "stored": true, "upserted": 2, "skipped": 0, "cursor": "opaque_next" }

Semantics:

  • Idempotent upsert by (project_id, l1_document_id, fragment)
  • Deduplicate; preserve provenance (source repo/commit if known)
  • Errors: 400 invalid payload, 401/403 auth, 409 conflicting fragment, 429 budget, 500 server

Retrieval contract (invoked by L3) ​

Retrieval is typically invoked by Orchestration as part of a rendering plan. The contract below describes the object shape.

Request object:

json
{
  "project_id": "proj_123",
  "query": "vector database recall",
  "top_k": 6,
  "time_ms": 8,
  "filters": { "type": ["guide", "spec"], "freshness": ["hot", "warm"] }
}

Response object:

json
{
  "items": [
    {
      "id": "l2_42",
      "score": 0.81,
      "reason": "entity match",
      "l1_ref": "doc_1#p3",
      "freshness": "hot",
      "features": { "entity_overlap": 0.8, "source_reliability": 0.9 }
    }
  ],
  "stats": { "t_ms": 3 }
}

Guarantees:

  • Budget-aware: respects time_ms; applies degradation path if needed
  • Stable IDs; references back to L1 (l1_ref)

Production API Implementation βœ… ​

Live Agent-Friendly API (Railway Deployed):

bash
# SQL Query API (Production Ready)
curl -X POST "http://localhost:8000/v1/agent/query" \
  -H "Content-Type: application/json" \
  -d '{
    "sql_query": "SELECT title, authors FROM sources WHERE year > 2020 LIMIT 10",
    "agent_id": "research_assistant_v1",
    "agent_type": "research_analyst"
  }'

# Vector Search API  
curl -X POST "http://localhost:8000/v1/agent/vector-search" \
  -d '{
    "query": "machine learning interpretability",
    "similarity_threshold": 0.7,
    "limit": 10
  }'

Security Features (Implemented):

  • βœ… SQL injection protection with keyword blocking
  • βœ… Rate limiting: 60 queries/minute per agent
  • βœ… Audit logging with query hashing
  • βœ… Input validation and parameterization

Testing & Validation Framework ​

API Contract Testing:

typescript
describe('L2 Interface Validation', () => {
  test('ingestion API follows contract', async () => {
    const request = {
      project_id: "test_proj_123",
      items: [
        { l1_document_id: "doc_1", score_hint: 0.92 },
        { l1_document_id: "doc_2", fragment: "#section2" }
      ],
      sync_cursor: "test_cursor"
    };
    
    const response = await fetch('/api/v1/project-library/ingest.v0', {
      method: 'POST',
      body: JSON.stringify(request)
    });
    
    expect(response.status).toBe(200);
    const result = await response.json();
    expect(result).toHaveProperty('success');
    expect(result).toHaveProperty('upserted');
    expect(result).toHaveProperty('cursor');
  });
  
  test('retrieval meets performance SLA', async () => {
    const request = {
      project_id: "perf_test_proj",
      query: "database optimization techniques",
      top_k: 5,
      time_ms: 8
    };
    
    const start = Date.now();
    const response = await l2Client.retrieve(request);
    const latency = Date.now() - start;
    
    expect(latency).toBeLessThan(8); // p95 < 8ms SLA
    expect(response.items.length).toBeLessThanOrEqual(5);
    expect(response.stats.t_ms).toBeLessThan(8);
  });
});

Error Handling & Monitoring ​

Comprehensive Error Responses:

typescript
interface L2ErrorResponse {
  error: {
    code: 'INVALID_QUERY' | 'RATE_LIMITED' | 'AUTH_FAILED' | 'TIMEOUT';
    message: string;
    details?: {
      validation_errors?: string[];
      retry_after_seconds?: number;
      suggested_fixes?: string[];
    };
  };
  request_id: string;
  timestamp: string;
}

Production Monitoring:

yaml
l2_interface_monitoring:
  metrics:
    - name: l2_api_requests_total
      type: counter
      labels: [endpoint, status_code, agent_type]
      
    - name: l2_api_latency_seconds
      type: histogram
      buckets: [0.001, 0.005, 0.008, 0.015, 0.05]
      
  alerts:
    - name: L2APIHighErrorRate
      condition: rate(l2_api_requests_total{status_code=~"4..|5.."}[5m]) > 0.05
      severity: warning
  • No PII duplication; metadata only

Events (emitted) ​

  • library.item.created β€” when a new reference is added
  • library.item.updated β€” when features/freshness change
  • library.item.deprecated β€” when evicted or superseded

Payload (example):

json
{
  "event": "library.item.updated",
  "schema_version": "0.1",
  "request_id": "req_abc",
  "agent_id": "agent_xyz",
  "user_id": "user_42",
  "project_id": "proj_123",
  "item": { "id": "l2_42", "l1_document_id": "doc_1", "freshness": "warm", "pinned": false },
  "ts": "2025-09-06T10:10:00Z"
}

Events feed L8 evaluation (metrics/fixtures). See ../evaluation/schemas.md for event schema.

Versioning & compatibility ​

  • Version suffix on endpoints: .v0, .v1 when introducing changes
  • Backward-compatible changes: additive fields with defaults
  • Breaking changes: new versioned endpoint; deprecate previous with sunset policy

Security & privacy ​

  • Enforce L1 ACLs; L2 stores references and minimal metadata
  • No raw PII; redact sensitive attributes in features
  • Audit access via correlation fields (request_id, agent_id, user_id)

Error catalog ​

  • 400 β€” invalid input (schema violation)
  • 401/403 β€” missing or denied credentials
  • 409 β€” duplicate/conflicting fragment key
  • 429 β€” budget/throughput exceeded
  • 500 β€” unexpected error; include request_id for traceability

See also ​

  • ./data-models.md
  • ./indexing-and-ranking.md
  • ./operations.md
  • ../contracts/README.md