File size: 4,329 Bytes
8ca7ba0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
from __future__ import annotations

import json
from pathlib import Path
from typing import Any

import yaml  # type: ignore[import-untyped]

from packages.generative import GenerativeClient, RelaySettings
from packages.supervisor.models import QualityReport, RepairPlan


class RepairPlanner:
    """Produces schema-validated plans from a configuration-owned action catalog."""

    def __init__(self, policy_path: Path | None, stagnation_repeat_limit: int) -> None:
        self.repeat_limit = stagnation_repeat_limit
        self.config: dict[str, Any] = {}
        if policy_path and policy_path.is_file():
            self.config = yaml.safe_load(policy_path.read_text(encoding="utf-8")) or {}

    def plan(
        self,
        report: QualityReport,
        *,
        parent_version: str,
        signature_occurrences: int,
    ) -> RepairPlan | None:
        failed = [gate for gate in report.gates if not gate.passed and gate.severity == "severe"]
        gate_ids = sorted(gate.gate_id for gate in failed)
        strategies = self._matching_strategies(gate_ids)
        strategy_index = (max(signature_occurrences, 1) - 1) // self.repeat_limit
        if strategy_index >= len(strategies):
            return None
        selected = strategies[strategy_index]
        steps = json.loads(
            json.dumps(selected["steps"]).replace("PLACEHOLDER_PARENT", parent_version)
        )
        affected_entities = sorted(
            {
                entity_id
                for gate in failed
                for entity_id in gate.affected_entities
            }
        )
        if affected_entities:
            for step in steps:
                if (
                    step.get("action") == "rerun_branch"
                    and step.get("stage") == "furniture"
                    and not step.get("entity_ids")
                ):
                    step["entity_ids"] = affected_entities
        template = {
            "schema_version": "1.0",
            "parent_version": parent_version,
            "failure_signature": report.failure_signature or "unknown",
            "strategy": str(selected["strategy"]),
            "steps": steps,
            "expected_improvement": str(
                selected.get("expected_improvement", "resolve failed gates")
            ),
        }
        if (
            self.config.get("agent_planning", {}).get("enabled", False)
            and RelaySettings.status_from_env()["configured"]
        ):
            template = self._agent_select(
                template,
                strategies[strategy_index:],
                gate_ids,
                parent_version,
            )
        return RepairPlan.model_validate(template)

    def _matching_strategies(self, gate_ids: list[str]) -> list[dict[str, Any]]:
        matched = []
        for item in self.config.get("strategies", []):
            gates = set(item.get("when_gates", []))
            if "*" in gates or gates.intersection(gate_ids):
                matched.append(item)
        return matched

    @staticmethod
    def _agent_select(
        template: dict[str, Any],
        strategies: list[dict[str, Any]],
        gate_ids: list[str],
        parent_version: str,
    ) -> dict[str, Any]:
        prompt = (
            "Choose exactly one repair strategy for the failed RoboHouseGen gates. "
            "Do not invent actions or fields. Return the selected strategy JSON verbatim.\n"
            f"Failed gates: {json.dumps(gate_ids)}\n"
            f"Allowed strategies: {json.dumps(strategies)}"
        )
        raw = GenerativeClient(RelaySettings.from_env()).generate_text(prompt)
        try:
            chosen = json.loads(raw[raw.index("{") : raw.rindex("}") + 1])
        except (ValueError, json.JSONDecodeError):
            return template
        allowed = next(
            (item for item in strategies if item.get("strategy") == chosen.get("strategy")), None
        )
        if allowed is None:
            return template
        return {
            **template,
            "strategy": allowed["strategy"],
            "steps": json.loads(
                json.dumps(allowed["steps"]).replace("PLACEHOLDER_PARENT", parent_version)
            ),
            "expected_improvement": allowed.get("expected_improvement", "resolve failed gates"),
        }