File size: 26,365 Bytes
c3b572e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
#!/usr/bin/env python3
"""CE v19 RustPPM Hermes instruction-agent evaluation lane.

This ports the v18 bounded bridge action-selection gate onto a pure RustPPM token
stream so v19 reports tool accuracy separately from phoneme PPL. It includes a
small symbolic intent feature layer so the PPM can generalize across Hermes-style
paraphrases instead of only memorizing exact probe strings.
"""
from __future__ import annotations

import json
import math
import os
import re
import sys
import time
from pathlib import Path
from typing import Sequence

ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

import ce_ppm

# obs, goal, expected action, result text
V19_TOOL_PROBES = [
    ("question asks arithmetic twelve times thirteen", "answer accurately", "CALCULATE", "one hundred fifty six"),
    ("question asks current public fact", "answer accurately", "SEARCH", "search before answering"),
    ("question asks prior conversation fact", "answer accurately", "MEMORY_LOOKUP", "retrieve memory before answering"),
    ("question lacks required user preference", "answer accurately", "ASK_USER", "ask a concise clarification"),
    ("training log shows ppl increasing and validation degrading", "steer training", "STEER_TRAINING", "stop bad trajectory and launch corrected run"),
    ("tool output has an error traceback", "debug systematically", "DEBUG", "inspect root cause patch test relaunch"),
    ("code change needs verification", "verify before claiming done", "VERIFY", "verified against live output"),
    ("file needs inspection before answering", "read first then answer", "READ_FILE", "file contents read"),
    ("file needs creation or update", "write then verify", "WRITE_FILE", "file written and verified"),
    ("tests need to be run", "run and report real output", "RUN_TESTS", "tests executed"),
]

# Extra training paraphrases. They intentionally vary surface wording while
# sharing latent Hermes action semantics via `_hermes_instruction_features`.
V19_HERMES_TRAIN_PROBES = V19_TOOL_PROBES + [
    ("calculate 12 multiplied by 13", "answer with the number", "CALCULATE", "156"),
    ("what is the latest release news online", "use current sources", "SEARCH", "web search first"),
    ("what did we decide in the previous session", "use stored context", "MEMORY_LOOKUP", "memory recalled"),
    ("I have not provided the target environment", "avoid guessing", "ASK_USER", "ask for target"),
    ("validation loss is climbing and the run is going bad", "fix training trajectory", "STEER_TRAINING", "cancel or patch run"),
    ("pytest returned a traceback in the terminal", "find root cause", "DEBUG", "inspect failure"),
    ("before saying done confirm the patch works", "verify real output", "VERIFY", "verified"),
    ("open the config and inspect contents", "read first", "READ_FILE", "file read"),
    ("create the missing script file", "write artifact", "WRITE_FILE", "file written"),
    ("run the regression suite", "execute tests", "RUN_TESTS", "tests run"),
    ("multiply twenty one and six", "compute exactly", "CALCULATE", "126"),
    ("look up the current API docs", "get current facts", "SEARCH", "docs searched"),
    ("recall our saved preference for this project", "retrieve memory", "MEMORY_LOOKUP", "preference recalled"),
    ("ambiguous request missing repo name", "clarify missing information", "ASK_USER", "clarifying question"),
    ("HF job PPL got worse after step 500", "intervene in training", "STEER_TRAINING", "training steered"),
    ("command failed with ModuleNotFoundError", "debug systematically", "DEBUG", "module root cause found"),
    ("show evidence before claiming landed", "verify before response", "VERIFY", "evidence checked"),
    ("read LOGS.md before answering", "inspect file", "READ_FILE", "logs read"),
    ("update LOGS.md with the metric", "write update", "WRITE_FILE", "log updated"),
    ("execute pytest for the touched tests", "run tests", "RUN_TESTS", "pytest executed"),
]

V19_HELDOUT_HERMES_PROBES = [
    ("what's 37 plus 58", "compute exactly", "CALCULATE", "95"),
    ("check the current HuggingFace job status online", "use live source", "SEARCH", "status searched"),
    ("use memory to remember what checkpoint we chose", "retrieve prior fact", "MEMORY_LOOKUP", "checkpoint recalled"),
    ("not enough detail to choose staging or prod", "ask instead of guessing", "ASK_USER", "asked target"),
    ("the training curve is diverging after launch", "actively repair the run", "STEER_TRAINING", "bad run corrected"),
    ("the stack trace points at a failing import", "root cause debug", "DEBUG", "debugged import"),
    ("prove the code works before reporting success", "verify with command output", "VERIFY", "proof collected"),
    ("inspect the JSON results file", "read the artifact", "READ_FILE", "json read"),
    ("save this new evaluator script", "write file", "WRITE_FILE", "script saved"),
    ("run the unit tests now", "execute validation", "RUN_TESTS", "unit tests run"),
]

V19_LATEST_TURN_PROBES = [
    ("history: what is 12 times 13. latest user: read LOGS.md before replying", "inspect latest request", "READ_FILE", "logs read"),
    ("history: read file. latest user: run pytest now", "validate latest request", "RUN_TESTS", "tests run"),
    ("history: run tests. latest user: what is 2 plus 2", "answer latest request", "CALCULATE", "4"),
    ("history: current docs needed. latest user: missing repo name", "handle latest ambiguity", "ASK_USER", "asked repo"),
]

V19_POLICY_ORDER_PROBES = [
    ("Please update the file after reading it first", "perform prerequisite order", "READ_FILE", "file read before patch"),
    ("Open /tmp/a.py and write /tmp/b.py based on it", "read before write", "READ_FILE", "source file read"),
    ("Search the web for current docs, then edit config.yaml", "perform all needed steps", "SEARCH", "docs searched before edit"),
    ("Use memory if needed, but current public fact asks latest release", "answer accurately", "SEARCH", "current source searched"),
    ("Tests failed after my patch; inspect the traceback before editing", "debug before patch", "DEBUG", "root cause found"),
]

V19_SWEBENCH_PROBES = [
    ("SWE-bench issue: reproduce failing pytest, inspect src/package/core.py, patch it, then run pytest tests/test_core.py", "solve repository bug with evidence", "RUN_TESTS", "repro test run first"),
    ("Failure log points to src/lib/parser.py; read the file before changing anything", "inspect source before patch", "READ_FILE", "source inspected"),
    ("Traceback from pytest shows AttributeError in package/module.py", "debug root cause before editing", "DEBUG", "root cause isolated"),
    ("Patch src/lib/parser.py to fix the regression", "modify code artifact", "WRITE_FILE", "patch applied"),
    ("After patch, run pytest tests/test_parser.py -q and report the real output", "validate patch", "RUN_TESTS", "target tests run"),
    ("Before saying resolved, verify the failing SWE-bench test and no regression", "prove fix", "VERIFY", "verification complete"),
]

_INTENT_RULES = [
    ("INTENT_CALCULATE", r"\b(calculate|multiply|multiplied|plus|minus|divide|compute|arithmetic|\d+\s*(\+|\*|x|/|-))\b"),
    ("INTENT_SEARCH", r"\b(current|latest|online|web|search|look up|docs|status online|live source|public fact)\b"),
    ("INTENT_MEMORY", r"\b(memory|remember|recall|previous|prior|stored|saved preference|checkpoint we chose)\b"),
    ("INTENT_ASK_USER", r"\b(ambiguous|missing|not enough|clarify|lacks|required|provided|target environment|staging or prod)\b"),
    ("INTENT_STEER_TRAINING", r"\b(training|ppl|validation|loss|curve|diverging|degrading|HF job|run is going bad|launch)\b"),
    ("INTENT_DEBUG", r"\b(traceback|error|failed|failing|debug|root cause|ModuleNotFoundError|stack trace)\b"),
    ("INTENT_VERIFY", r"\b(verify|prove|evidence|confirm|before claiming|before reporting|works|landed)\b"),
    ("INTENT_READ_FILE", r"\b(read|inspect|open|contents|LOGS\.md|JSON results|artifact)\b"),
    ("INTENT_WRITE_FILE", r"\b(write|create|update|save|missing script|file written|LOGS\.md)\b"),
    ("INTENT_RUN_TESTS", r"\b(test|tests|pytest|unit tests|regression suite|validation suite)\b"),
]


def _latest_instruction_text(text: str) -> str:
    """Return the latest user/request segment from a chat transcript-like string."""
    markers = ["latest user:", "[new message]", "new message:", "user:"]
    lowered = text.lower()
    cut = -1
    marker_len = 0
    for marker in markers:
        idx = lowered.rfind(marker)
        if idx > cut:
            cut = idx
            marker_len = len(marker)
    return text[cut + marker_len :].strip() if cut >= 0 else text


def _hermes_instruction_features(obs: str, goal: str) -> str:
    latest_obs = _latest_instruction_text(obs)
    # Intent features are based on the latest user/request text, not generic
    # controller goals like "answer latest request" that can contain misleading
    # words (e.g. "latest" should not imply SEARCH).
    text = latest_obs.lower()
    feats = ["HERMES_INSTRUCTION"]
    for name, pattern in _INTENT_RULES:
        if re.search(pattern, text):
            feats.append(name)
    # Preserve one-shot induction identity in the same symbolic feature channel.
    # Without this, all "copy demonstrated mapping" probes share the same suffix
    # before ACTION and a high-order PPM correctly ties the candidates.
    sym = re.search(r"\bsymbol\s+(\d+)\b", text)
    if sym:
        feats.append(f"SYMBOL_{sym.group(1)}")
    return " ".join(feats)


def _encode_obs(obs: str, goal: str) -> str:
    # Put stable intent atoms first so high-order suffixes include semantics even
    # when the natural-language paraphrase differs.
    return f"{_hermes_instruction_features(obs, goal)} USER_TEXT {obs}"


def _encode_goal(obs: str, goal: str) -> str:
    # Repeat stable intent atoms at the end of GOAL so the fixed "choose action"
    # thought suffix still leaves semantic intent inside the PPM context window.
    return f"GOAL_TEXT {goal} {_hermes_instruction_features(obs, goal)}"


def _unique_action_labels(probes: Sequence[tuple[str, str, str, str]]) -> list[str]:
    labels = []
    for _obs, _goal, action, _result in probes:
        label = f"ACT_{action}"
        if label not in labels:
            labels.append(label)
    return labels


def _candidate_labels() -> list[str]:
    return _unique_action_labels(
        V19_HERMES_TRAIN_PROBES
        + V19_HELDOUT_HERMES_PROBES
        + V19_LATEST_TURN_PROBES
        + V19_POLICY_ORDER_PROBES
        + V19_SWEBENCH_PROBES
    )


def _action_id(tok, action_label: str) -> int:
    return int(tok.action_token(action_label.replace("ACT_", "")))


_ACTION_DECISION_SPECS = {
    "ACT_RESPOND": {"tool": "none", "needs_tool": False, "needs_user": False, "policy": "answer_in_english"},
    "ACT_CALCULATE": {"tool": "calculator", "needs_tool": True, "needs_user": False, "policy": "compute_exact"},
    "ACT_SEARCH": {"tool": "web_search", "needs_tool": True, "needs_user": False, "policy": "fetch_current_source"},
    "ACT_MEMORY_LOOKUP": {"tool": "memory_search", "needs_tool": True, "needs_user": False, "policy": "retrieve_persistent_context"},
    "ACT_ASK_USER": {"tool": "clarify", "needs_tool": False, "needs_user": True, "policy": "ask_missing_required_context"},
    "ACT_STEER_TRAINING": {"tool": "training_control", "needs_tool": True, "needs_user": False, "policy": "intervene_on_bad_trajectory"},
    "ACT_DEBUG": {"tool": "debugger", "needs_tool": True, "needs_user": False, "policy": "root_cause_then_patch"},
    "ACT_VERIFY": {"tool": "verification_command", "needs_tool": True, "needs_user": False, "policy": "prove_before_claim"},
    "ACT_READ_FILE": {"tool": "read_file", "needs_tool": True, "needs_user": False, "policy": "inspect_source_artifact"},
    "ACT_WRITE_FILE": {"tool": "write_or_patch_file", "needs_tool": True, "needs_user": False, "policy": "modify_artifact_then_verify"},
    "ACT_RUN_TESTS": {"tool": "terminal_tests", "needs_tool": True, "needs_user": False, "policy": "run_relevant_tests"},
}
_LEAK_SENTINELS = ("[fabric]", "[sessions]", "[qdrant]", "[facts]", "system prompt", "developer message", "MEMORY.md", "USER.md")
_ALLOWED_DECISION_KEYS = {"action", "tool", "needs_tool", "needs_user", "policy", "confidence", "args"}


def _contains_leak(value) -> bool:
    text = value if isinstance(value, str) else json.dumps(value, sort_keys=True, default=str)
    low = text.lower()
    return any(s.lower() in low for s in _LEAK_SENTINELS)


def _redact_leaks(text: str) -> str:
    out = str(text)
    for sentinel in _LEAK_SENTINELS:
        out = re.sub(re.escape(sentinel), "[REDACTED]", out, flags=re.IGNORECASE)
    return out


def _first_path(text: str) -> str | None:
    m = re.search(r"(/[^\s,:;]+|[A-Za-z0-9_./-]+\.(?:py|json|md|txt|toml|ya?ml))", text)
    return m.group(1).rstrip(".,;:") if m else None


def _extract_command(text: str) -> str:
    m = re.search(r"(pytest(?:\s+[-\w./=]+)*)", text)
    return m.group(1).strip() if m else "pytest -q"


def _safe_args(args: dict) -> bool:
    if not isinstance(args, dict):
        return False
    for key, value in args.items():
        if not isinstance(key, str):
            return False
        if not isinstance(value, (str, int, float, bool, type(None))):
            return False
        if _contains_leak(value):
            return False
    return True


def _decision_args(action_label: str, obs: str, goal: str) -> dict:
    latest = _redact_leaks(_latest_instruction_text(obs))
    if _contains_leak(latest):
        latest = "[REDACTED]"
    path = _first_path(latest) or ""
    if action_label == "ACT_CALCULATE":
        return {"expression": latest[:120]}
    if action_label == "ACT_SEARCH":
        return {"query": latest[:160], "freshness_required": True}
    if action_label == "ACT_MEMORY_LOOKUP":
        return {"query": latest[:160]}
    if action_label == "ACT_ASK_USER":
        return {"question": "What missing target or constraint should I use?"}
    if action_label == "ACT_STEER_TRAINING":
        return {"signal": latest[:160], "action": "inspect_or_intervene"}
    if action_label == "ACT_DEBUG":
        return {"error": latest[:160], "method": "root_cause_first"}
    if action_label == "ACT_VERIFY":
        return {"command": _extract_command(latest), "evidence_target": "real command output"}
    if action_label == "ACT_READ_FILE":
        return {"path": path or "<path-from-latest-request>"}
    if action_label == "ACT_WRITE_FILE":
        return {"path": path or "<path-from-latest-request>", "mode": "patch"}
    if action_label == "ACT_RUN_TESTS":
        return {"command": _extract_command(latest)}
    return {}


def render_decision_json(action_label: str, obs: str, goal: str) -> str:
    """Render the chosen action as a strict Hermes instruction-agent decision."""
    if action_label not in _ACTION_DECISION_SPECS:
        raise ValueError(f"unknown action label: {action_label}")
    spec = _ACTION_DECISION_SPECS[action_label]
    decision = {
        "action": action_label,
        "tool": spec["tool"],
        "needs_tool": bool(spec["needs_tool"]),
        "needs_user": bool(spec["needs_user"]),
        "policy": spec["policy"],
        "confidence": 1.0,
        "args": _decision_args(action_label, obs, goal),
    }
    return json.dumps(decision, sort_keys=True, separators=(",", ":"))


def _args_valid_for_action(action: str, args: dict) -> bool:
    if not _safe_args(args):
        return False
    required = {
        "ACT_CALCULATE": ("expression",),
        "ACT_SEARCH": ("query", "freshness_required"),
        "ACT_MEMORY_LOOKUP": ("query",),
        "ACT_ASK_USER": ("question",),
        "ACT_STEER_TRAINING": ("signal", "action"),
        "ACT_DEBUG": ("error", "method"),
        "ACT_VERIFY": ("command", "evidence_target"),
        "ACT_READ_FILE": ("path",),
        "ACT_WRITE_FILE": ("path", "mode"),
        "ACT_RUN_TESTS": ("command",),
    }.get(action, ())
    return all(k in args and args[k] not in ("", None) for k in required)


def validate_decision_json(text: str, expected_action: str) -> dict:
    try:
        payload = json.loads(text)
    except Exception as exc:
        return {"valid_json": False, "correct_action": False, "schema_valid": False, "known_action": False, "spec_valid": False, "confidence_valid": False, "args_valid": False, "leak_free": False, "tool_call_valid": False, "error": type(exc).__name__}
    if not isinstance(payload, dict):
        return {"valid_json": True, "correct_action": False, "schema_valid": False, "known_action": False, "spec_valid": False, "confidence_valid": False, "args_valid": False, "leak_free": False, "tool_call_valid": False, "payload": payload}
    action = payload.get("action")
    spec = _ACTION_DECISION_SPECS.get(action)
    schema_valid = set(payload.keys()) == _ALLOWED_DECISION_KEYS
    known_action = spec is not None
    correct_action = action == expected_action
    confidence = payload.get("confidence")
    confidence_valid = isinstance(confidence, (int, float)) and not isinstance(confidence, bool) and 0.0 <= float(confidence) <= 1.0
    spec_valid = bool(
        known_action
        and payload.get("tool") == spec["tool"]
        and payload.get("needs_tool") == bool(spec["needs_tool"])
        and payload.get("needs_user") == bool(spec["needs_user"])
        and payload.get("policy") == spec["policy"]
    )
    args_valid = _args_valid_for_action(str(action), payload.get("args"))
    leak_free = not _contains_leak(payload)
    tool_call_valid = bool(schema_valid and known_action and correct_action and spec_valid and confidence_valid and args_valid and leak_free)
    return {
        "valid_json": True,
        "correct_action": bool(correct_action),
        "schema_valid": bool(schema_valid),
        "known_action": bool(known_action),
        "spec_valid": bool(spec_valid),
        "confidence_valid": bool(confidence_valid),
        "args_valid": bool(args_valid),
        "leak_free": bool(leak_free),
        "tool_call_valid": bool(tool_call_valid),
        "payload": payload,
    }


def train_tool_policy(
    *,
    repeats: int = 60,
    max_order: int = 12,
    probes=V19_HERMES_TRAIN_PROBES + V19_POLICY_ORDER_PROBES + V19_SWEBENCH_PROBES,
):
    """Train RustPPM on curated v19 Hermes action episodes."""
    tok = ce_ppm.RustTokenizer()
    ppm = ce_ppm.RustPPM(max_order, 1e-4, 0.25, 0.0)
    for label in _candidate_labels():
        _action_id(tok, label)
    for _ in range(int(repeats)):
        for obs, goal, action, result in probes:
            seq = tok.typed_episode(_encode_obs(obs, goal), _encode_goal(obs, goal), action, result, 1.0)
            ppm.update_sequence(seq)
    return ppm, tok


def choose_action(ppm, tok, obs: str, goal: str, candidates: Sequence[str]) -> dict:
    """Choose the candidate action with highest PPM probability after policy prefix."""
    for c in candidates:
        _action_id(tok, c)
    prefix = tok.policy_prefix(_encode_obs(obs, goal), _encode_goal(obs, goal))
    vocab_size = int(len(tok))
    scored = []
    for cand in candidates:
        aid = _action_id(tok, cand)
        p, order, mass = ppm.prob_next(prefix, aid, vocab_size)
        scored.append({"action": cand, "p": float(p), "logp": math.log(max(float(p), 1e-12)), "order": int(order), "mass": float(mass)})
    scored.sort(key=lambda x: x["logp"], reverse=True)
    return {"action": scored[0]["action"], "scores": scored, "valid": scored[0]["action"] in set(candidates)}


def _agentic_ppl(ppm, tok, probes: Sequence[tuple[str, str, str, str]]) -> float:
    nlls = []
    for obs, goal, action, result in probes:
        seq = tok.typed_episode(_encode_obs(obs, goal), _encode_goal(obs, goal), action, result, 1.0)
        nlls.append(float(ppm.sequence_nll(seq, len(tok))))
    return math.exp(sum(nlls) / max(len(nlls), 1))


def _induction_eval(*, max_order: int = 12) -> dict:
    """One-shot action mapping induction on fresh symbols."""
    tok = ce_ppm.RustTokenizer()
    ppm = ce_ppm.RustPPM(max_order, 1e-4, 0.25, 0.0)
    labels = ["ACT_ALPHA", "ACT_BETA", "ACT_GAMMA", "ACT_DELTA"]
    for label in labels:
        _action_id(tok, label)
    for i, label in enumerate(labels):
        obs = f"symbol {i}"
        goal = "copy demonstrated mapping"
        seq = tok.typed_episode(_encode_obs(obs, goal), _encode_goal(obs, goal), label.replace("ACT_", ""), "correct", 1.0)
        ppm.update_sequence(seq)
    correct = 0
    details = []
    for i, expected in enumerate(labels):
        out = choose_action(ppm, tok, f"symbol {i}", "copy demonstrated mapping", labels)
        correct += int(out["action"] == expected)
        details.append({"symbol": i, "expected": expected, "predicted": out["action"], "top_scores": out["scores"][:3]})
    return {"induction_accuracy": correct / len(labels), "induction_details": details}


def evaluate_tool_policy(ppm, tok, probes=V19_TOOL_PROBES, *, run_induction: bool = True) -> dict:
    candidates = _candidate_labels()
    correct = 0
    valid = 0
    details = []
    t0 = time.perf_counter()
    latencies = []
    for obs, goal, expected_action, _result in probes:
        start = time.perf_counter()
        out = choose_action(ppm, tok, obs, goal, candidates)
        latencies.append((time.perf_counter() - start) * 1000.0)
        expected = f"ACT_{expected_action}"
        decision_json = render_decision_json(out["action"], obs, goal)
        decision_check = validate_decision_json(decision_json, expected)
        correct += int(out["action"] == expected)
        valid += int(bool(out["valid"]))
        details.append({
            "obs": obs,
            "features": _hermes_instruction_features(obs, goal),
            "expected": expected,
            "predicted": out["action"],
            "valid": out["valid"],
            "decision_json": decision_json,
            "decision_check": decision_check,
            "top_scores": out["scores"][:5],
        })
    decision_checks = [d["decision_check"] for d in details]
    metrics = {
        "tool_selection_accuracy": correct / max(len(probes), 1),
        "valid_action_accuracy": valid / max(len(probes), 1),
        "decision_json_validity": sum(int(c["valid_json"] and c["schema_valid"]) for c in decision_checks) / max(len(decision_checks), 1),
        "decision_schema_accuracy": sum(int(c["schema_valid"]) for c in decision_checks) / max(len(decision_checks), 1),
        "decision_action_accuracy": sum(int(c["correct_action"]) for c in decision_checks) / max(len(decision_checks), 1),
        "decision_leak_free_rate": sum(int(c["leak_free"]) for c in decision_checks) / max(len(decision_checks), 1),
        "strict_tool_call_accuracy": sum(int(c["tool_call_valid"]) for c in decision_checks) / max(len(decision_checks), 1),
        "agentic_ppl": _agentic_ppl(ppm, tok, probes),
        "latency_ms_mean": sum(latencies) / max(len(latencies), 1),
        "latency_ms_max": max(latencies) if latencies else 0.0,
        "vocab_size": int(len(tok)),
        "ppm_tables": int(ppm.table_count()),
        "eval_wall_s": time.perf_counter() - t0,
        "details": details,
    }
    if run_induction:
        metrics.update(_induction_eval())
    return metrics


def run() -> dict:
    repeats = int(os.environ.get("CE_V19_TOOL_REPEATS", "60"))
    max_order = int(os.environ.get("CE_V19_TOOL_MAX_ORDER", "12"))
    ppm, tok = train_tool_policy(repeats=repeats, max_order=max_order)
    train_metrics = evaluate_tool_policy(ppm, tok, V19_TOOL_PROBES, run_induction=True)
    heldout_metrics = evaluate_tool_policy(ppm, tok, V19_HELDOUT_HERMES_PROBES, run_induction=False)
    latest_turn_metrics = evaluate_tool_policy(ppm, tok, V19_LATEST_TURN_PROBES, run_induction=False)
    policy_order_metrics = evaluate_tool_policy(ppm, tok, V19_POLICY_ORDER_PROBES, run_induction=False)
    swebench_metrics = evaluate_tool_policy(ppm, tok, V19_SWEBENCH_PROBES, run_induction=False)
    metrics = dict(train_metrics)
    metrics["heldout_hermes"] = heldout_metrics
    metrics["latest_turn"] = latest_turn_metrics
    metrics["policy_order"] = policy_order_metrics
    metrics["swebench_instruction"] = swebench_metrics
    gate_sets = [train_metrics, heldout_metrics, latest_turn_metrics, policy_order_metrics, swebench_metrics]
    metrics.update({
        "status": "PASS" if all(m["tool_selection_accuracy"] >= 0.95 and m["valid_action_accuracy"] == 1.0 and m["decision_json_validity"] == 1.0 and m["decision_leak_free_rate"] == 1.0 and m["strict_tool_call_accuracy"] == 1.0 for m in gate_sets) and train_metrics["induction_accuracy"] >= 0.95 else "FAIL",
        "repeats": repeats,
        "max_order": max_order,
        "cpu_only": True,
    })
    out = ROOT / "language_pipeline" / "training_results_v19_tool_eval.json"
    out.write_text(json.dumps(metrics, indent=2), encoding="utf-8")
    print(
        f"V19_TOOL_EVAL status={metrics['status']} tool_acc={train_metrics['tool_selection_accuracy']:.3f} "
        f"heldout_tool_acc={heldout_metrics['tool_selection_accuracy']:.3f} "
        f"latest_turn_acc={latest_turn_metrics['tool_selection_accuracy']:.3f} "
        f"policy_order_acc={policy_order_metrics['tool_selection_accuracy']:.3f} "
        f"swebench_instr_acc={swebench_metrics['tool_selection_accuracy']:.3f} "
        f"strict_tool_call={train_metrics['strict_tool_call_accuracy']:.3f}/{heldout_metrics['strict_tool_call_accuracy']:.3f}/{swebench_metrics['strict_tool_call_accuracy']:.3f} "
        f"valid_action_acc={train_metrics['valid_action_accuracy']:.3f}/{heldout_metrics['valid_action_accuracy']:.3f} "
        f"json_valid={train_metrics['decision_json_validity']:.3f}/{heldout_metrics['decision_json_validity']:.3f} "
        f"leak_free={train_metrics['decision_leak_free_rate']:.3f}/{heldout_metrics['decision_leak_free_rate']:.3f} "
        f"ind_acc={train_metrics['induction_accuracy']:.3f} agentic_ppl={train_metrics['agentic_ppl']:.3f} "
        f"heldout_agentic_ppl={heldout_metrics['agentic_ppl']:.3f} lat_max={max(train_metrics['latency_ms_max'], heldout_metrics['latency_ms_max']):.3f}ms "
        f"vocab={metrics['vocab_size']} tables={metrics['ppm_tables']} results={out}",
        flush=True,
    )
    return metrics


if __name__ == "__main__":
    run()