# API Reference | Tractatus Framework
Complete API reference for Tractatus Framework - endpoints, authentication, request/response formats, and examples.

# API Reference

Complete reference for the Tractatus Framework REST API. All endpoints return JSON and require proper authentication where indicated.

Base URL: `http://localhost:9000/api`

📄 OpenAPI Specification: Download OpenAPI 3.0 YAML

Use this specification with Swagger UI, Postman, or any OpenAPI-compatible tool for interactive API exploration.

💻 Code Examples: JavaScript | Python

Complete integration examples for authentication, documents, governance services, and audit logs.

## Authentication

POST `/auth/login`

Authenticate and receive JWT token.

#### Request Body

    {
      "email": "admin@tractatus.local",
      "password": "your_password"
    }

#### Response

    {
      "success": true,
      "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
      "user": {
        "email": "admin@tractatus.local",
        "role": "admin"
      }
    }

GET `/auth/me` 🔒 Requires Auth

Get current user information.

#### Headers

    Authorization: Bearer {token}

#### Response

    {
      "success": true,
      "user": {
        "id": "68e3a6fb21af2fd194bf4b50",
        "email": "admin@tractatus.local",
        "role": "admin"
      }
    }

## Documents

GET `/documents`

Get list of all documents.

#### Query Parameters

limit | Number of results (default: 50)
skip | Pagination offset (default: 0)
quadrant | Filter by quadrant (STRATEGIC, OPERATIONAL, etc.)

#### Response

#

    {
      "success": true,
      "documents": [
        {
          "_id": "672f821b6e820c0c7a0e0d55",
          "title": "Introduction to the Tractatus Framework",
          "slug": "introduction-to-the-tractatus-framework",
          "quadrant": "STRATEGIC",
          "content_html": "Introduction...",
          "toc": [{ "level": 1, "text": "Introduction", "slug": "introduction" }],
          "created_at": "2025-10-07T10:30:00Z"
        }
      ],
      "total": 12
    }

GET `/documents/:identifier`

Get document by ID or slug.

#### Parameters

identifier | Document ID or slug

#### Response

#

    {
      "success": true,
      "document": {
        "_id": "672f821b6e820c0c7a0e0d55",
        "title": "Introduction to the Tractatus Framework",
        "slug": "introduction-to-the-tractatus-framework",
        "content_html": "IntroductionThe Tractatus framework...",
        "toc": [...]
      }
    }

GET `/documents/search`

Full-text search across documents.

#### Query Parameters

q | Search query (required)

#### Response

    {
      "success": true,
      "results": [
        {
          "title": "Core Concepts",
          "slug": "core-concepts",
          "score": 0.92,
          "excerpt": "...boundary enforcement..."
        }
      ]
    }

## Governance Services

Note: All governance endpoints require admin authentication. These services implement architectural AI safety through runtime enforcement.

GET `/governance` 🔒 Admin Only

Get overall governance framework status.

#### Headers

    Authorization: Bearer {admin_token}

#### Response

    {
      "success": true,
      "governance": {
        "active": true,
        "services": {
          "classifier": { "enabled": true, "status": "operational" },
          "validator": { "enabled": true, "status": "operational" },
          "boundary": { "enabled": true, "status": "operational" },
          "pressure": { "enabled": true, "status": "operational" },
          "metacognitive": { "enabled": true, "status": "selective" }
        },
        "instruction_count": 28,
        "last_validation": "2025-10-12T10:00:00Z"
      }
    }

### 1. InstructionPersistenceClassifier

Classifies instructions by quadrant (STRATEGIC/OPERATIONAL/TACTICAL/SYSTEM) and assigns persistence levels.

POST `/governance/classify` 🔒 Admin Only

Classify an instruction and get its quadrant, persistence level, and temporal scope.

#### Request Body

    {
      "text": "Always use MongoDB on port 27027",
      "context": {
        "source": "user",
        "session_id": "sess_123"
      }
    }

#### Response

    {
      "success": true,
      "classification": {
        "quadrant": "SYSTEM",
        "persistence": "HIGH",
        "temporal_scope": "PROJECT",
        "verification_required": "MANDATORY",
        "reasoning": "Port configuration affects system infrastructure",
        "confidence": 0.95
      }
    }

#### Quadrant Types

STRATEGIC | Values, ethics, mission, Te Tiriti commitments
OPERATIONAL | Architecture, deployment, configuration
TACTICAL | Bug fixes, features, code changes
SYSTEM | Environment, infrastructure, database, tooling
STOCHASTIC | One-off requests, experimental, temporary

### 2. CrossReferenceValidator

Prevents training pattern override ("27027 failure mode") by validating actions against stored instructions.

POST `/governance/validate` 🔒 Admin Only

Validate a proposed action against instruction history to detect conflicts.

#### Request Body

    {
      "action": {
        "type": "database_config",
        "target": "MongoDB",
        "parameters": {
          "port": 27017
        }
      },
      "context": {
        "messages": [],
        "session_id": "sess_123"
      }
    }

#### Response (Conflict Detected)

    {
      "success": true,
      "validation": {
        "status": "REJECTED",
        "reason": "Pattern recognition override detected",
        "conflicts": [
          {
            "instruction_id": "inst_008",
            "text": "Always use MongoDB on port 27027",
            "quadrant": "SYSTEM",
            "persistence": "HIGH"
          }
        ],
        "recommendation": "Use port 27027 as explicitly instructed"
      }
    }

#### Validation Status Types

APPROVED | No conflicts, proceed safely
REJECTED | Conflicts with HIGH persistence instructions
WARNING | Potential conflicts, proceed with caution

### 3. BoundaryEnforcer

Blocks values decisions requiring human judgment (privacy, ethics, strategic direction).

POST `/governance/enforce` 🔒 Admin Only

Check if a decision crosses into values territory and requires human approval.

#### Request Body

    {
      "action": {
        "type": "policy_change",
        "description": "Update privacy policy to enable more tracking",
        "impact": "user_privacy"
      },
      "context": {
        "requested_by": "user",
        "reason": "improve analytics"
      }
    }

#### Response (Blocked)

    {
      "success": true,
      "enforcement": {
        "decision": "BLOCK",
        "category": "VALUES_DECISION",
        "reason": "Privacy vs. analytics trade-off requires human judgment",
        "boundary_crossed": "privacy",
        "requires_approval": true,
        "alternatives": [
          "Implement privacy-preserving analytics (Plausible/Fathom)",
          "Consult user on acceptable tracking level",
          "Review compliance with sovereignty principles"
        ]
      }
    }

#### Boundary Categories

privacy | User data, tracking, surveillance
ethics | Moral trade-offs, fairness, harm
sovereignty | Indigenous rights, Te Tiriti, CARE principles
strategic | Mission changes, major pivots

### 4. ContextPressureMonitor

Multi-factor session health tracking to detect degradation before failures occur.

POST `/governance/pressure` 🔒 Admin Only

Analyze session context pressure across multiple factors.

#### Request Body

    {
      "context": {
        "tokenUsage": 120000,
        "tokenBudget": 200000,
        "messageCount": 45,
        "errorCount": 3,
        "complexOperations": 8,
        "sessionDuration": 3600
      }
    }

#### Response

    {
      "success": true,
      "pressure": {
        "level": "ELEVATED",
        "score": 62.5,
        "factors": {
          "token_usage": { "value": 60, "weight": 0.4, "status": "ELEVATED" },
          "message_depth": { "value": 45, "weight": 0.2, "status": "NORMAL" },
          "error_rate": { "value": 6.7, "weight": 0.3, "status": "ELEVATED" },
          "complexity": { "value": 8, "weight": 0.1, "status": "HIGH" }
        },
        "recommendation": "INCREASE_VERIFICATION",
        "actions": [
          "Review recent errors for patterns",
          "Consider session checkpoint at 75% tokens",
          "Reduce concurrent complex operations"
        ],
        "next_checkpoint": 150000
      }
    }

#### Pressure Levels

NORMAL | 0-40% - Standard operation
ELEVATED | 41-60% - Increase verification
HIGH | 61-80% - Consider checkpoint
CRITICAL | 81-95% - Session handoff recommended
DANGEROUS | 96-100% - Quality degradation likely

### 5. MetacognitiveVerifier

AI self-checks for complex operations to detect scope creep and misalignment.

POST `/governance/verify` 🔒 Admin Only

Verify proposed action through metacognitive self-assessment.

#### Request Body

    {
      "action": {
        "type": "refactor",
        "scope": "Refactor 47 files across 5 system areas",
        "complexity": "high"
      },
      "reasoning": {
        "intent": "Improve code organization",
        "approach": "Extract shared utilities, consolidate duplicates",
        "risks": "Potential breaking changes"
      },
      "context": {
        "requested": "Refactor authentication module",
        "original_scope": "single module"
      }
    }

#### Response

    {
      "success": true,
      "verification": {
        "decision": "REQUIRE_REVIEW",
        "confidence": 0.45,
        "concerns": [
          {
            "type": "SCOPE_CREEP",
            "severity": "HIGH",
            "detail": "Proposed scope (47 files, 5 areas) exceeds request (1 module)"
          },
          {
            "type": "COMPLEXITY",
            "severity": "MEDIUM",
            "detail": "High-risk refactoring without test coverage verification"
          }
        ],
        "criteria": {
          "alignment": 0.3,
          "coherence": 0.8,
          "completeness": 0.9,
          "safety": 0.4,
          "alternatives_considered": 0.5
        },
        "recommendation": "Reduce scope to requested authentication module first",
        "alternatives": [
          "Refactor authentication module only (aligned with request)",
          "Create phased refactoring plan with user approval",
          "Run comprehensive tests before broader refactoring"
        ]
      }
    }

#### Verification Decisions

APPROVED | High confidence (>0.85), proceed
REQUIRE_REVIEW | Medium confidence (0.5-0.85), seek approval
REJECTED | Low confidence (<0.5), do not proceed

### 6. AuditLogger

Comprehensive audit trail of all governance decisions and framework activity.

GET `/audit/audit-logs` 🔒 Admin Only

Retrieve audit logs with filtering and pagination.

#### Query Parameters

limit | Number of results (default: 50, max: 100)
skip | Pagination offset (default: 0)
service | Filter by service (classifier, validator, etc.)
status | Filter by status (APPROVED, REJECTED, etc.)
from | Start date (ISO 8601 format)

#### Response

    {
      "success": true,
      "logs": [
        {
          "_id": "672f8xxx",
          "service": "CrossReferenceValidator",
          "action": "validate_action",
          "status": "REJECTED",
          "details": {
            "conflict": "Pattern override detected (port 27017 vs 27027)",
            "instruction_id": "inst_008"
          },
          "timestamp": "2025-10-12T10:15:30Z",
          "session_id": "sess_123"
        },
        {
          "_id": "672f8yyy",
          "service": "BoundaryEnforcer",
          "action": "enforce_boundary",
          "status": "BLOCKED",
          "details": {
            "category": "VALUES_DECISION",
            "boundary": "privacy"
          },
          "timestamp": "2025-10-12T09:45:22Z",
          "session_id": "sess_122"
        }
      ],
      "total": 145,
      "limit": 50,
      "skip": 0
    }

GET `/audit/audit-analytics` 🔒 Admin Only

Get aggregated analytics on audit activity.

#### Response

    {
      "success": true,
      "analytics": {
        "total_events": 1245,
        "by_service": {
          "CrossReferenceValidator": 425,
          "BoundaryEnforcer": 78,
          "ContextPressureMonitor": 312,
          "InstructionPersistenceClassifier": 298,
          "MetacognitiveVerifier": 132
        },
        "by_status": {
          "APPROVED": 1089,
          "REJECTED": 78,
          "WARNING": 45,
          "BLOCKED": 33
        },
        "rejection_rate": 6.3,
        "period": {
          "start": "2025-10-01T00:00:00Z",
          "end": "2025-10-12T23:59:59Z",
          "days": 12
        }
      }
    }

## Admin Endpoints

All admin endpoints require authentication with admin role.

GET `/admin/stats` 🔒 Admin Only

Get dashboard statistics.

#### Response

    {
      "success": true,
      "documents": 12,
      "pending": 3,
      "approved": 45,
      "users": 5
    }

GET `/admin/moderation` 🔒 Admin Only

Get items in moderation queue.

#### Response

    {
      "success": true,
      "items": [
        {
          "_id": "672f8xxx",
          "type": "blog_post",
          "title": "Understanding Boundary Enforcement",
          "status": "pending",
          "submitted_at": "2025-10-07T11:00:00Z"
        }
      ]
    }

## Error Codes

Code | Description
--- | ---
400 | Bad Request - Invalid parameters
401 | Unauthorized - Missing or invalid token
403 | Forbidden - Insufficient permissions
404 | Not Found - Resource does not exist
409 | Conflict - Duplicate resource (e.g., slug)
500 | Internal Server Error

#### Error Response Format

    {
      "success": false,
      "message": "Error description",
      "error": "ERROR_CODE"
    }