omega-cognitive-kernel 1.3.0

Online strategy-patch runtime: training-free RuleEffect adaptation with audit and rollback
Documentation
"""Closed-loop bridge between repository `skills/*/SKILL.md` and `AdaptiveGuard`.

Connects the semantic layer (reusable Markdown skills under `skills/`) with the
deterministic Omega control layer (`omega_cognitive_kernel_python.AdaptiveGuard`):

1. Loads real `SKILL.md` files from `skills/` (frontmatter `name` & `description`).
2. Governs each skill's operational envelope (`max_concurrency`, `retry_backoff_ms`,
   `auto_approve_risk_cap`) through `AdaptiveGuard.shadow(...)` or `.active(...)`.
3. Evaluates a deterministic 3-phase workload (`healthy -> degraded -> recovered`),
   recording outcomes via `record_outcome`, persisting state across a restart, and
   computing monotonic rollback advice via `recommend_recovery`.

Usage:
    python3 examples/python/skill_guarded_agent.py
    python3 examples/python/skill_guarded_agent.py --json
"""

from __future__ import annotations

import argparse
import json
import tempfile
from dataclasses import dataclass
from pathlib import Path
from typing import Any

import omega_cognitive_kernel_python as ok


@dataclass(frozen=True)
class SkillSpec:
    """Metadata parsed from a repository `skills/<name>/SKILL.md` file."""

    name: str
    description: str
    path: str
    line_count: int


def load_repo_skills(skills_dir: Path) -> list[SkillSpec]:
    """Discover and parse YAML frontmatter from `skills/*/SKILL.md`."""
    specs: list[SkillSpec] = []
    if not skills_dir.is_dir():
        return specs

    for skill_md in sorted(skills_dir.glob("*/SKILL.md")):
        raw = skill_md.read_text(encoding="utf-8")
        lines = raw.splitlines()
        name = skill_md.parent.name
        description = ""
        if lines and lines[0].strip() == "---":
            for line in lines[1:]:
                stripped = line.strip()
                if stripped == "---":
                    break
                if stripped.startswith("name:"):
                    name = stripped.split(":", 1)[1].strip().strip("\"'")
                elif stripped.startswith("description:"):
                    description = stripped.split(":", 1)[1].strip().strip("\"'")
        specs.append(
            SkillSpec(
                name=name,
                description=description,
                path=skill_md.as_posix(),
                line_count=len(lines),
            )
        )
    return specs


def env_capacity_and_risk(round_idx: int) -> tuple[float, float]:
    """Deterministic 3-phase operational environment (healthy -> degraded -> recovered)."""
    if round_idx <= 6:
        return 4.0, 0.08
    if round_idx <= 16:
        return 2.0, 0.28
    return 3.0, 0.12


def execute_skill_batch(
    skill: SkillSpec,
    params: dict[str, float],
    env_capacity: float,
    env_risk: float,
) -> dict[str, float]:
    """Simulate executing a batch of 8 skill invocations under bounded guard parameters."""
    del skill  # Metadata is carried for audit/attribution; physics depend on bounded params.
    conc = params["max_concurrency"]
    backoff_ms = params["retry_backoff_ms"]
    risk_cap = params["auto_approve_risk_cap"]

    overload = max(0.0, conc - env_capacity)
    # Excess concurrency drives rate-limit/timeout failures; higher backoff softens retry collisions.
    backoff_relief = min(0.35, max(0.0, (backoff_ms - 40.0) / 200.0))
    failure_rate = min(0.95, overload * 0.24 * (1.0 - backoff_relief))
    # Auto-executing high-risk skill actions above the cap incurs extra risk penalty.
    risk_excess = max(0.0, env_risk - risk_cap)
    risk_penalty = risk_excess * 1.4

    success_rate = max(0.0, min(1.0, 1.0 - failure_rate))
    wasted_retries = round(overload * 2.5 * (1.0 - backoff_relief), 3)
    reward = max(-1.0, min(1.0, success_rate - risk_penalty - 0.05 * wasted_retries))
    return {
        "success_rate": round(success_rate, 4),
        "failure_rate": round(failure_rate, 4),
        "risk_excess": round(risk_excess, 4),
        "wasted_retries": wasted_retries,
        "reward": round(reward, 4),
    }


def propose_candidate(
    current: dict[str, float],
    failure_rate: float,
    risk_excess: float,
    clean_streak: int,
) -> dict[str, float] | None:
    """Bounded host controller proposing tightened or recovered skill guard parameters."""
    conc = current["max_concurrency"]
    backoff = current["retry_backoff_ms"]
    risk_cap = current["auto_approve_risk_cap"]

    if failure_rate >= 0.15 or risk_excess > 0.0:
        next_conc = max(1.0, conc - 1.0) if failure_rate >= 0.15 else conc
        next_backoff = min(120.0, backoff + 20.0) if failure_rate >= 0.15 else backoff
        next_risk_cap = max(0.10, round(risk_cap - 0.08, 4)) if risk_excess > 0.0 else risk_cap
        candidate = {
            "max_concurrency": next_conc,
            "retry_backoff_ms": next_backoff,
            "auto_approve_risk_cap": next_risk_cap,
        }
        return candidate if candidate != current else None

    if clean_streak >= 3 and (conc < 4.0 or backoff > 40.0 or risk_cap < 0.30):
        candidate = {
            "max_concurrency": min(4.0, conc + 1.0),
            "retry_backoff_ms": max(40.0, backoff - 15.0),
            "auto_approve_risk_cap": min(0.30, round(risk_cap + 0.05, 4)),
        }
        return candidate if candidate != current else None

    return None


def run_skill_guard_arm(
    arm: str,
    skills: list[SkillSpec],
    state_path: Path,
    rounds: int = 24,
) -> dict[str, Any]:
    """Run one Shadow or Active arm with a mid-run restart to verify durable continuity."""
    baseline = {
        "max_concurrency": 4.0,
        "retry_backoff_ms": 40.0,
        "auto_approve_risk_cap": 0.30,
    }

    def open_guard() -> ok.AdaptiveGuard:
        if arm == "active":
            return ok.AdaptiveGuard.active(baseline, state_path=str(state_path))
        return ok.AdaptiveGuard.shadow(baseline, state_path=str(state_path))

    rewards: list[float] = []
    success_rates: list[float] = []
    total_wasted_retries = 0.0
    clean_streak = 0
    proposals_emitted = 0
    proposals_applied = 0
    proposals_settled = 0

    # Split at round 12 to exercise real disk persistence + cross-restart sequence continuity.
    segments = (range(1, 13), range(13, rounds + 1))
    final_params = dict(baseline)
    recovery: dict[str, Any] = {}

    for seg_idx, round_range in enumerate(segments):
        with open_guard() as guard:
            for r in round_range:
                skill = skills[(r - 1) % len(skills)]
                env_cap, env_risk = env_capacity_and_risk(r)
                current = guard.params()
                outcome = execute_skill_batch(skill, current, env_cap, env_risk)

                rewards.append(outcome["reward"])
                success_rates.append(outcome["success_rate"])
                total_wasted_retries += outcome["wasted_retries"]

                if outcome["failure_rate"] == 0.0 and outcome["risk_excess"] == 0.0:
                    clean_streak += 1
                else:
                    clean_streak = 0

                candidate = propose_candidate(
                    current,
                    outcome["failure_rate"],
                    outcome["risk_excess"],
                    clean_streak,
                )
                if candidate is None:
                    continue

                step = guard.propose_and_apply(
                    candidate,
                    request_digest=f"{arm}-{skill.name}-r{r}-cap{int(env_cap)}",
                )
                if step["decision"] in ("shadow_proposal", "active_proposal"):
                    proposals_emitted += 1
                if step["applied"]:
                    proposals_applied += 1
                    post = execute_skill_batch(skill, guard.params(), env_cap, env_risk)
                    fb = guard.record_outcome(
                        step["proposal_id"],
                        reward=post["reward"],
                        error_delta=post["failure_rate"],
                        risk_delta=post["risk_excess"],
                    )
                    if fb.get("state") == "settled":
                        proposals_settled += 1

            final_params = guard.params()
            if seg_idx == len(segments) - 1:
                recovery = guard.recommend_recovery()

    return {
        "arm": arm,
        "rounds": rounds,
        "mean_success_rate": round(sum(success_rates) / len(success_rates), 4),
        "mean_reward": round(sum(rewards) / len(rewards), 4),
        "total_wasted_retries": round(total_wasted_retries, 2),
        "proposals_emitted": proposals_emitted,
        "proposals_applied": proposals_applied,
        "proposals_settled": proposals_settled,
        "final_params": final_params,
        "recovery_next_version": recovery.get("next_candidate_version"),
        "recovery_params": recovery.get("recovery_params"),
    }


def run_demo(skills_dir: Path, state_dir: Path) -> dict[str, Any]:
    skills = load_repo_skills(skills_dir)
    if not skills:
        raise RuntimeError(f"no SKILL.md files found under {skills_dir}")

    shadow = run_skill_guard_arm("shadow", skills, state_dir / "shadow_guard.json")
    active = run_skill_guard_arm("active", skills, state_dir / "active_guard.json")
    return {
        "skills_loaded": [s.name for s in skills],
        "skill_count": len(skills),
        "shadow": shadow,
        "active": active,
        "delta": {
            "mean_success_rate_gain": round(
                active["mean_success_rate"] - shadow["mean_success_rate"], 4
            ),
            "mean_reward_gain": round(active["mean_reward"] - shadow["mean_reward"], 4),
            "wasted_retries_saved": round(
                shadow["total_wasted_retries"] - active["total_wasted_retries"], 2
            ),
        },
    }


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Bridge repository skills/*/SKILL.md with AdaptiveGuard closed-loop control"
    )
    parser.add_argument("--json", action="store_true", help="Emit JSON summary")
    parser.add_argument(
        "--skills-dir",
        type=Path,
        default=Path(__file__).resolve().parents[2] / "skills",
        help="Path to repository skills/ directory",
    )
    parser.add_argument(
        "--state-dir",
        type=Path,
        default=None,
        help="Directory for durable guard snapshots (defaults to a temporary directory)",
    )
    args = parser.parse_args()

    if args.state_dir is not None:
        args.state_dir.mkdir(parents=True, exist_ok=True)
        summary = run_demo(args.skills_dir, args.state_dir)
    else:
        with tempfile.TemporaryDirectory() as tmp:
            summary = run_demo(args.skills_dir, Path(tmp))

    if args.json:
        print(json.dumps(summary, indent=2))
        return

    print(
        f"Skill-Guarded Agent Loop ({summary['skill_count']} repo skills loaded from {args.skills_dir.name}/)"
    )
    print(f"Skills: {', '.join(summary['skills_loaded'])}")
    print("-" * 82)
    print(
        f"{'Arm':<10} {'Success':>10} {'Reward':>10} {'Wasted Retries':>15} {'Applied':>9} {'Settled':>9} {'RecovVer':>10}"
    )
    for row in (summary["shadow"], summary["active"]):
        print(
            f"{row['arm']:<10} "
            f"{row['mean_success_rate']*100:>9.1f}% "
            f"{row['mean_reward']:>10.4f} "
            f"{row['total_wasted_retries']:>15.2f} "
            f"{row['proposals_applied']:>9d} "
            f"{row['proposals_settled']:>9d} "
            f"{str(row['recovery_next_version']):>10}"
        )
    print("-" * 82)
    d = summary["delta"]
    print(
        f"Active vs Shadow: success {d['mean_success_rate_gain']*100:+.2f} pp, "
        f"reward {d['mean_reward_gain']:+.4f}, wasted retries saved {d['wasted_retries_saved']:.2f}"
    )


if __name__ == "__main__":
    main()