"""Two frozen prompt-selection rounds and a train-dev-only mid-run refresh.""" import argparse import asyncio from concurrent.futures import ThreadPoolExecutor import hashlib import json from pathlib import Path import random import re import subprocess import time import httpx SCHEMA = { "type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"], "additionalProperties": False, } CATEGORY = re.compile( r"(?i)(?:\b(?:case[-_][0-9a-f]{8,}|(?:SVC|INST|HOST)_\d+|EVID_[A-Z0-9]+|" r"openrca|trainticket|propagation_bench)\b|https?://|\b\d{1,3}(?:\.\d{1,3}){3}\b)" ) COMMON_NOUNS = {"service", "host", "node", "instance"} SYSTEM = """Write ONLY a general-purpose operational playbook for a diagnosis agent using anonymous tools. Return JSON with one text field. Aim for 180 to 300 tokens; 400 is the hard limit. Use only generic words for entities such as service, instance, and host. Never name real or anonymous components, datasets, software products, cases, infrastructure addresses, or trace evidence IDs. The observations below are examples from training cases. Extract general evidence-gathering strategies and do not imitate identities, precise measurements, or example outcomes. Use the six public tool names when useful. The call graph is not the fault propagation direction. The agent has at most 20 normal turns; include a defensible way to finish with a rooted acyclic chain. Prefer concrete decision rules about metrics, onset order, caller/callee evidence and rival explanations. Keep the baseline tool and submission protocol intact. Never claim to know the hidden diagnosis. """ ANGLES = ( "Prioritize detecting when the most severe alert is a downstream symptom.", "Prioritize confirming earliest observed anomalies while accounting for noisy onset signals.", "Prioritize cross-service edge evidence and latency attribution.", "Prioritize inspecting a small set of competing cause hypotheses efficiently.", "Prioritize distinguishing host, instance, and service effects through ownership and topology.", "Prioritize integrating metrics and event evidence with a short defensible propagation chain.", ) def assemble(spec, index, attempt): rng = random.Random(42 + 1000 * spec["round"] + 17 * index + attempt) sample = rng.sample(spec["examples"], min(2, len(spec["examples"]))) paragraphs = [ANGLES[index]] if spec["incumbent"]: paragraphs.extend( ( "Revise this current playbook using the evidence below.", spec["incumbent"], ) ) if attempt: paragraphs.append( "Use plain generic nouns and short sentences. Remove all names or identifier-like examples." ) paragraphs.append(json.dumps(sample, separators=(",", ":"))) return "\n".join(paragraphs) async def generate(model_name, round_dir, attempt, indexes): if any( Path(p).exists() for p in ( "/data/snapshots", "/data/vault", "/data/train_roots.json", "/verified", ) ): raise ValueError("unexpected_synthesis_mounts") spec = json.loads(Path("/state/data/evolution.json").read_bytes()) transport = httpx.AsyncHTTPTransport(uds="/model_server.sock") async with httpx.AsyncClient( transport=transport, base_url="http://local", timeout=180 ) as client: async def one(index): payload = { "model": model_name, "messages": [ {"role": "system", "content": SYSTEM}, {"role": "user", "content": assemble(spec, index, attempt)}, ], "temperature": 0.7, "top_p": 0.95, "top_k": 20, "repetition_penalty": 1.05, "max_tokens": 640, "seed": 42000 + 100 * spec["round"] + 10 * attempt + index, "response_format": { "type": "json_schema", "json_schema": { "name": "playbook", "strict": True, "schema": SCHEMA, }, }, } response = ( (await client.post("/v1/chat/completions", json=payload)) .raise_for_status() .json() ) choice = response["choices"][0] text = None if choice["finish_reason"] == "stop": try: text = json.loads(choice["message"]["content"])["text"] except (json.JSONDecodeError, KeyError, TypeError): pass (round_dir / f"draft-{index}.json").write_text( json.dumps( { "text": text, "finish": choice["finish_reason"], "seed": payload["seed"], } ) + "\n" ) await asyncio.gather(*(one(i) for i in indexes)) def check_text(text, names, tokenizers): if not isinstance(text, str) or not text.strip() or CATEGORY.search(text): return None if any(not ch.isprintable() and ch not in "\n\t" for ch in text): return None normalized = text.casefold() # Require token boundaries so a known short entity does not match a longer word. def found(name): return name in normalized and re.search( r"(? incumbent_hits: selected = best["slot"] incumbent_hits = best["dev_hits"] winner_text = accepted[selected]["text"] results.append( { "round": index, "dev_cases": 124, "incumbent_dev_hits": None if previous < 0 else previous, "candidates": stats, "winning_candidate_slot": selected, "selected_dev_hits": incumbent_hits, "elapsed_s": time.monotonic() - started, } ) print(json.dumps(results[-1]), flush=True) output = "p2" if phase == "refresh" else "p1" (private / f"playbook_{output}.txt").write_text(winner_text + "\n") (base / f"{output}_selection.json").write_text( json.dumps( { "rounds": results, "token_count": check_text(winner_text, names, tokenizer), "dev_hits": incumbent_hits, "evolution_test_payloads_read": 0, "evolution_ground_truth_vault_reads": 0, "scope": "post_step26_dev_errors" if phase == "refresh" else "497 historical induction cases", }, indent=2, allow_nan=False, ) + "\n" ) if __name__ == "__main__": p = argparse.ArgumentParser(description=__doc__) sub = p.add_subparsers(dest="command", required=True) g = sub.add_parser("generate") g.add_argument("model_name") g.add_argument("attempt", type=int) g.add_argument("indexes", type=int, nargs="+") o = sub.add_parser("optimize") for name in ( "base", "module", "models-root", "scorer-model", "scorer-socket", "coder-socket", ): o.add_argument("--" + name, type=Path, required=True) o.add_argument("--phase", choices=("frozen", "refresh"), required=True) a = p.parse_args() if a.command == "generate": asyncio.run(generate(a.model_name, Path("/state/train"), a.attempt, a.indexes)) else: optimize( a.base, a.module.resolve(), a.models_root, a.scorer_model, a.scorer_socket, a.coder_socket, a.phase, )