omega-cognitive-kernel 1.4.0

Online strategy-patch runtime: training-free RuleEffect adaptation with audit and rollback
Documentation
"""Multi-upstream / multi-route namespace manager (`ScopedAdaptiveGuard`).

Isolates independent `AdaptiveGuard` instances per upstream route or tool scope
(e.g., `openai`, `github_api`, `search_tool`) inside a shared state directory,
supporting per-scope safety bounds (`set_bounds`), unified status inspection,
and aggregated Prometheus exposition with `scope="..."` labels.

Usage:
    python3 examples/python/scoped_adaptive_guard.py
"""

from __future__ import annotations

import re
import tempfile
import threading
from pathlib import Path
from typing import Any

import omega_cognitive_kernel_python as ok


def _safe_scope_filename(scope: str) -> str:
    cleaned = re.sub(r"[^A-Za-z0-9_.-]+", "_", scope.strip())
    if not cleaned:
        raise ValueError("scope name must not be empty")
    return f"{cleaned}.json"


def _escape_prom_label(value: str) -> str:
    return value.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n")


class ScopedAdaptiveGuard:
    """Thread-safe multi-route manager isolating one `AdaptiveGuard` per scope."""

    def __init__(self, state_dir: Path | str | None = None) -> None:
        self._lock = threading.RLock()
        self._state_dir = Path(state_dir) if state_dir is not None else None
        if self._state_dir is not None:
            self._state_dir.mkdir(parents=True, exist_ok=True)
        self._guards: dict[str, ok.AdaptiveGuard] = {}

    def register(
        self,
        scope: str,
        baseline: dict[str, float],
        *,
        mode: str = "shadow",
        bounds: dict[str, dict[str, float]] | None = None,
    ) -> ok.AdaptiveGuard:
        """Create or load an isolated `AdaptiveGuard` for `scope`."""
        state_path = (
            str(self._state_dir / _safe_scope_filename(scope))
            if self._state_dir is not None
            else None
        )
        mode_lower = mode.lower()
        if mode_lower == "active":
            guard = ok.AdaptiveGuard.active(baseline, state_path=state_path)
        elif mode_lower == "keep":
            guard = ok.AdaptiveGuard.keep(baseline, state_path=state_path)
        elif mode_lower == "shadow":
            guard = ok.AdaptiveGuard.shadow(baseline, state_path=state_path)
        else:
            raise ValueError(f"unsupported mode {mode!r}: expected keep, shadow, or active")

        if bounds is not None:
            guard.set_bounds(bounds)

        with self._lock:
            self._guards[scope] = guard
        return guard

    def guard(self, scope: str) -> ok.AdaptiveGuard:
        with self._lock:
            if scope not in self._guards:
                raise KeyError(f"unregistered guard scope: {scope!r}")
            return self._guards[scope]

    def scopes(self) -> list[str]:
        with self._lock:
            return sorted(self._guards.keys())

    def all_stats(self) -> dict[str, dict[str, Any]]:
        with self._lock:
            return {scope: g.stats() for scope, g in sorted(self._guards.items())}

    def to_prometheus_text(self) -> str:
        """Aggregate Prometheus metrics across all scopes, tagging each sample with `scope`."""
        with self._lock:
            items = sorted(self._guards.items())

        emitted_headers: set[str] = set()
        lines: list[str] = []
        for scope, guard in items:
            escaped_scope = _escape_prom_label(scope)
            for raw_line in guard.to_prometheus_text().splitlines():
                if not raw_line:
                    continue
                if raw_line.startswith("# "):
                    if raw_line not in emitted_headers:
                        emitted_headers.add(raw_line)
                        lines.append(raw_line)
                    continue
                if "{" in raw_line:
                    metric, rest = raw_line.split("{", 1)
                    lines.append(f'{metric}{{scope="{escaped_scope}",{rest}')
                else:
                    metric, value = raw_line.split(" ", 1)
                    lines.append(f'{metric}{{scope="{escaped_scope}"}} {value}')
        return "\n".join(lines) + ("\n" if lines else "")


def main() -> None:
    with tempfile.TemporaryDirectory() as tmp:
        mgr = ScopedAdaptiveGuard(tmp)
        llm = mgr.register(
            "openai",
            {"max_concurrency": 4.0, "retry_backoff_ms": 50.0},
            mode="active",
            bounds={"max_concurrency": {"min": 1.0, "max": 8.0, "max_step_delta": 2.0}},
        )
        gh = mgr.register(
            "github_api",
            {"max_concurrency": 6.0, "retry_backoff_ms": 40.0},
            mode="shadow",
        )
        step = llm.propose_and_apply({"max_concurrency": 2.0, "retry_backoff_ms": 80.0})
        llm.record_outcome(step["proposal_id"], reward=0.85)
        gh.propose_and_apply({"max_concurrency": 3.0, "retry_backoff_ms": 60.0})

        print("Scopes:", mgr.scopes())
        print(mgr.to_prometheus_text())


if __name__ == "__main__":
    main()