# KontextKube Sovereign OS v3.1.2: Bidirectional DocMesh Substrate Spec (TKT-9056)

```text
[5DHCP-TKT-9056-DOCMESH-SUBSTRATE]
Context Cube Vector: (X: 3, Y: 2, Face: 2) [Face 2: Execution & Settlement]
Authoritative Base-27 Saevcode: [SAEV-AAABENQAQD0WNNWGPXTQRRIBJFT]
Semantic Focus Drift Vector: ||Δv_f|| = 0.977560 (Cosine Drift: 0.477812) relative to thread root
Lineage Pedigree Link: Root(TKT-8001) → ... → Parent(TKT-9055) → Child(TKT-9056)
Substrate Vitality Slope (Sv): 2.59 / 9.9 (SSOT grounded in valkey-broker:6379, Rule 18 Parity Certified)
Target Architecture: Bidirectional Documentation CRD, Valkey Docs Keyspace, and GitOps Control Surface
```

---

## 1. Executive Summary & Design Philosophy

The traditional dichotomy between "code" and "documentation" produces chronic drift: markdown documentation rots while code evolves, or architectural specifications are modified without triggering corresponding implementation changes.

In **KontextKube Sovereign OS**, documentation is treated as a **first-class, active, typed distributed resource**. Docs and code form a closed, bidirectional control loop:
1. **Spec-as-Source:** When a specification changes (e.g. schema, API contract, CRD model), automated code-generation pipelines generate or update the target interfaces, clients, and controllers.
2. **Code-as-Telemetry:** When code or cluster state changes, the DocMesh Operator analyzes the AST and runtime telemetry to compute the **Documentation Drift Index ($\Delta_{doc}$)**, flagging stale specifications.
3. **The Wiki as a Live Control Surface:** The documentation browser is not a static HTML reader; it is an active control surface communicating with the Valkey SSOT and Kubernetes operator to trigger code-gen, audit invariant compliance, and anchor lineage proofs.

---

## 2. DocumentationArtifact Custom Resource Definition (CRD)

The `DocumentationArtifact` CRD formalizes every architectural component into a declarative Kubernetes resource.

```yaml
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: documentationartifacts.kontextkube.io
spec:
  group: kontextkube.io
  versions:
    - name: v1alpha1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          required:
            - spec
          properties:
            spec:
              type: object
              required:
                - ticketId
                - kind
                - sourceOfTruth
                - bindings
              properties:
                ticketId:
                  type: string
                  description: "Canonical 5DHCP Ticket ID (e.g., TKT-9056)"
                kind:
                  type: string
                  enum: [ConceptInventory, KernelSpec, DeploymentSpec, TelemetrySpec, GovernanceSpec]
                schemaVersion:
                  type: string
                  default: "1.0.0"
                sourceOfTruth:
                  type: string
                  enum: [code, spec, doc]
                  description: "Identifies whether changes originate in code, schema spec, or operator narrative"
                bindings:
                  type: array
                  description: "List of filesystem paths, CRDs, or cluster services bound to this specification"
                  items:
                    type: object
                    required:
                      - targetType
                      - targetUri
                    properties:
                      targetType:
                        type: string
                        enum: [filepath, crd, service, helm_chart]
                      targetUri:
                        type: string
                      checksum:
                        type: string
                        description: "SHA-256 hash of the bound resource at time of validation"
                payload:
                  type: object
                  properties:
                    model:
                      type: object
                      description: "Machine-readable OpenAPI/JSON Schema definition"
                    narrative:
                      type: string
                      description: "Human-readable markdown documentation"
            status:
              type: object
              properties:
                driftStatus:
                  type: string
                  enum: [IN_SYNC, DRIFT_DETECTED, GENERATION_PENDING, OUT_OF_ORDER]
                driftScore:
                  type: number
                  format: float
                lastReconciledAt:
                  type: string
                  format: date-time
                activeBindingHashes:
                  type: object
                  additionalProperties:
                    type: string
```

---

## 3. Valkey Real-Time Docs Keyspace

To allow microsecond lookup and sub-millisecond synchronization across all swarm agents (Gemini Antigravity, Qwen3, Copilot, DeepSeek), the DocMesh substrate maps specifications directly into Valkey:

| Keyspace Pattern | Redis Type | Purpose | TTL |
| :--- | :--- | :--- | :--- |
| `docs:spec:{ticket_id}` | `HASH` | Structured model, OpenAPI schema, JSON schema, version, kind | Persistent |
| `docs:narrative:{ticket_id}` | `STRING` | Authoritative raw Markdown narrative | Persistent |
| `docs:bindings:{ticket_id}` | `SET` | Set of bound filepaths, service names, and CRDs | Persistent |
| `docs:lineage:{ticket_id}` | `LIST` | Chronological list of parent-child ticket transitions | Persistent |
| `docs:drift:index` | `ZSET` | Scored set of tickets by drift score ($\Delta_{doc}$) | Persistent |
| `docs:stream:events` | `STREAM` | Append-only event log of spec revisions and codegen triggers | 7 Days |

---

## 4. DocMesh Operator & Reconciliation Engine

The `DocMeshOperator` runs inside the `apex-cortex` namespace as a native Kubernetes controller.

```python
"""
DocMesh Controller: Continuous Invariant Verification between Docs & Code.
"""
import hashlib
import json
import logging
from typing import Dict, Any

class DocMeshReconciler:
    def __init__(self, valkey_client, k8s_client):
        self.valkey = valkey_client
        self.k8s = k8s_client
        self.logger = logging.getLogger("DocMeshReconciler")

    def compute_sha256(self, content: bytes) -> str:
        return hashlib.sha256(content).hexdigest()

    async def reconcile_artifact(self, ticket_id: str, spec: Dict[str, Any]) -> Dict[str, Any]:
        """
        Calculates drift between the registered spec and active filesystem/cluster bindings.
        """
        bindings = spec.get("bindings", [])
        total_drift = 0.0
        drift_details = {}

        for binding in bindings:
            target_uri = binding["targetUri"]
            expected_hash = binding.get("checksum", "")
            
            # Read current content of target binding
            current_content = await self.fetch_binding_content(binding["targetType"], target_uri)
            current_hash = self.compute_sha256(current_content)
            
            if current_hash != expected_hash:
                drift_score = 1.0 # Binary drift or AST semantic distance
                total_drift += drift_score
                drift_details[target_uri] = {
                    "status": "DRIFT_DETECTED",
                    "expected_hash": expected_hash,
                    "actual_hash": current_hash
                }
            else:
                drift_details[target_uri] = {"status": "IN_SYNC", "hash": current_hash}

        drift_status = "IN_SYNC" if total_drift == 0.0 else "DRIFT_DETECTED"
        
        # Update Valkey keyspace
        await self.valkey.hset(f"docs:spec:{ticket_id}", mapping={
            "drift_status": drift_status,
            "drift_score": str(total_drift),
            "reconciled_at": "ISO-TIMESTAMP"
        })
        await self.valkey.zadd("docs:drift:index", {ticket_id: total_drift})

        return {
            "ticket_id": ticket_id,
            "drift_status": drift_status,
            "drift_score": total_drift,
            "details": drift_details
        }

    async def fetch_binding_content(self, target_type: str, uri: str) -> bytes:
        # Stub for Kubernetes API / git-sync filesystem read
        return b"content"
```

---

## 5. Bidirectional Code Generation Pipeline

When a developer or agent edits a `DocumentationArtifact` via the Wiki UI or Git PR:
1. **Spec Mutation Detected:** Valkey emits a `docs:stream:events` event: `{"event": "SPEC_UPDATED", "ticketId": "TKT-9056"}`.
2. **Schema Validation:** The `openapi-generator-cli` or `datamodel-code-generator` generates:
   - Pydantic models for FastAPI backend routes.
   - TypeScript interfaces for the React/Vite console.
   - Go structs for the Kubernetes controller.
3. **Automated PR / Patch Generation:** If GitOps auto-sync is enabled, the operator opens a PR with the generated code and matching AST checksums.
4. **Invariant Gate Approval:** Council consensus (Rule 21) reviews the unified spec diff and code diff together.

---

## 6. Live Wiki Control Surface Integration

The local wiki server on `http://localhost:8090` exposes the following active control routes:

- `GET /api/docs`: Returns all specifications with live `drift_status` and `bindings`.
- `GET /api/docs/{ticket_id}`: Returns parsed markdown, structured JSON schema, and lineage links.
- `POST /api/docs/{ticket_id}/reconcile`: Triggers the DocMesh Operator to recalculate drift on bound paths.
- `POST /api/docs/{ticket_id}/generate`: Invokes the code-generator to emit updated models and CRD manifests.
- `POST /api/docs/{ticket_id}/sync-valkey`: Flushes the narrative and schema into `valkey-broker:6379`.

Through this unified architecture, the documentation system operates as a live, bidirectional organ embedded within the KontextKube runtime.
