Files
dev 65e7a0a97c eval: advisory instruction feedback from Claude Code sessions
`ajieval sessions` pairs each human prompt with what the assistant did
just before it, and asks Jev whether the prompt was a correction and which
repository rule (AGENTS.md, the aji-jev skill, commit memory) the corrected
behaviour broke. Excerpts are truncated and credential-like strings
redacted; answers stay in a local log, and each prompt is sent once.

`sessions report` proposes clarifying a rule only when corrections pointing
to it recur across sessions (thresholds in triage.json); it never edits
instructions. `sessions hook` is meant for a personal SessionEnd hook: it
returns at once and scans in the background, and does nothing without a
TypeSafe key, which may now also come from ~/.config/typesafe/api_key.
2026-10-07 22:37:24 +03:00

183 lines
7.7 KiB
Python

"""Advisory failure classification with a System One model (TypeSafe Jev).
Jev answers typed questions about a small state with calibrated
probabilities. Here it suggests the protocol §27 category, the place a
failure was caught and the §38 cause of a failed run. A suggestion is never
a verdict: it is stored next to the human classification, and only
`triage.json` thresholds decide whether `triage` may count it.
Boundaries (tools/eval only; never the verifier, CI gates or conformance):
- only runs of the `dev` and `validation` sets are sent; the held-out
`test` set never leaves the machine (protocol §29);
- the state is minimal (task id, outcome, diagnostic codes, the tails of
the last failing commands), because unrelated detail lowers accuracy;
- the questions below are the single reviewable definition.
TYPESAFE_API_KEY bearer token (never recorded); if unset, the first
line of ~/.config/typesafe/api_key
TYPESAFE_BASE_URL default https://api.typesafe.ai
"""
import datetime
import json
import os
import urllib.error
import urllib.request
from . import util
MODEL = "jev-latest"
SENDABLE_SETS = ("dev", "validation")
COMMANDS = 3
OUTPUT_TAIL = 1500
CATEGORIES = {
"SPEC_UNDERSTANDING": "the program solves a different problem than the task asks",
"SYNTAX": "the program does not parse",
"TYPE": "type errors: mismatched, unknown or ill-formed types",
"OWNERSHIP": "moves, use after move, missing release of an owned value",
"BORROW": "borrow conflicts, mutable aliasing, borrows that outlive their owner",
"RESOURCE": "resources (files, sockets, regions, tasks) not closed or closed twice",
"BOUNDS": "out-of-bounds index or length errors",
"FUNCTIONAL": "the program runs but its output or behaviour is wrong",
"CONCURRENCY": "data races, wrong task or channel structure",
"DEADLOCK": "tasks wait on each other forever",
"ATOMIC_ORDERING": "wrong atomic memory ordering",
"PERFORMANCE": "correct but too slow or too large for the task limits",
"BUDGET": "the agent ran out of tokens or tool calls",
"TIMEOUT": "a command or the run hit its time limit",
"AGENT_GAVE_UP": "the agent stopped without a working solution",
"TOOL_FAILURE": "the harness, sandbox or toolchain itself failed",
}
CAUGHT_BY = {
"verifier": "a verifier or compiler diagnostic rejected the program",
"runtime": "the program trapped or failed while running",
"test": "the program ran to completion but a test rejected its output",
}
CAUSES = {
"language": "the language semantics themselves make the correct program hard to express",
"documentation": "the specification or reference does not explain the needed rule clearly",
"agent_bundle": "the agent reference bundle or quick reference lacks or misstates what was needed",
"diagnostics": "a diagnostic was misleading or did not say how to fix the program",
"harness": "the evaluation harness, sandbox or evaluator misbehaved",
"model_capability": "the rules were clear and available; the model failed to apply them",
"task_ambiguity": "the task statement is ambiguous or underspecified",
}
class JevError(Exception):
pass
def questions(aji):
q = {
"category": {"type": "choice", "instructions": "Which primary failure category best describes why this run failed?", "criteria": CATEGORIES},
"cause": {"type": "choice", "instructions": "Where does the failure originate?", "criteria": CAUSES},
}
if aji:
q["caught_by"] = {"type": "choice", "instructions": "What first caught the failure?", "criteria": CAUGHT_BY}
return q
def _commands(r, run_dir):
"""(command, exit code, output) for every command of the run."""
from . import native
if r.get("track") == "B":
path = os.path.join(run_dir, "transcript.jsonl")
return native.command_events(r["agent"]["name"], path) if os.path.isfile(path) else []
path = os.path.join(run_dir, "events.jsonl")
if not os.path.isfile(path):
return []
out = []
with open(path) as f:
for line in f:
e = json.loads(line)
if e.get("event") == "command":
out.append((e.get("command") or "", e.get("exit"), e.get("output") or ""))
return out
def state(r, run_dir):
"""The minimal state for one failed run."""
from . import report
cmds = _commands(r, run_dir)
failing = [c for c in cmds if c[1] not in (0, None)] or cmds
m = r.get("metrics", {})
return {
"task": r["task"]["id"],
"language": r["language"]["name"],
"termination": m.get("termination"),
"verdict": {k: v for k, v in (r.get("verdict") or {}).items() if k in ("accepted", "gates", "error")},
"failed_verifier_cycles": m.get("failed_verifier_cycles"),
"failed_test_cycles": m.get("failed_test_cycles"),
"diagnostic_codes": report._diagnostic_codes(r, run_dir, [c[2] for c in cmds]),
"last_failing_commands": [{"command": c[0][:300], "exit": c[1], "output_tail": c[2][-OUTPUT_TAIL:]} for c in failing[-COMMANDS:]],
}
def check_sendable(r):
s = r["task"].get("set", "dev")
if s not in SENDABLE_SETS:
raise JevError(f"task {r['task']['id']} is in the {s!r} set; only {', '.join(SENDABLE_SETS)} runs are sent to Jev (protocol §29)")
if r.get("accepted"):
raise JevError(f"run {r['run_id']} was accepted; only failed runs are classified (protocol §27)")
def ask(state_obj, qs, post=None):
"""One System One request; returns the `answers` map."""
body = {"state": state_obj, "model": os.environ.get("TYPESAFE_DEFAULT_MODEL", MODEL), "questions": qs}
resp = (post or _post)(body)
answers = resp.get("answers")
if not isinstance(answers, dict) or set(answers) != set(qs):
raise JevError(f"unexpected response: answers for {sorted(answers or {})}, asked {sorted(qs)}")
return resp.get("model"), answers
KEY_FILE = os.path.join(os.path.expanduser("~"), ".config", "typesafe", "api_key")
def api_key():
key = os.environ.get("TYPESAFE_API_KEY")
if key:
return key
try:
with open(KEY_FILE) as f:
return f.readline().strip() or None
except OSError:
return None
def _post(body):
key = api_key()
if not key:
raise JevError(f"TYPESAFE_API_KEY is not set and {KEY_FILE} is missing")
url = os.environ.get("TYPESAFE_BASE_URL", "https://api.typesafe.ai").rstrip("/") + "/v1/systemone"
req = urllib.request.Request(url, data=json.dumps(body).encode(), method="POST",
headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=60) as f:
return json.loads(f.read())
except urllib.error.HTTPError as e:
raise JevError(f"TypeSafe API: HTTP {e.code}: {e.read()[:500].decode(errors='replace')}") from None
except urllib.error.URLError as e:
raise JevError(f"TypeSafe API: {e.reason}") from None
def suggest(run_dir, post=None):
"""Asks Jev about one failed run; returns the suggestion record."""
r = util.read_json(os.path.join(run_dir, "run.json"))
check_sendable(r)
st = state(r, run_dir)
qs = questions(r["language"]["name"] in ("aji_air", "aji_source"))
model, answers = ask(st, qs, post)
return {
"source": "jev",
"model": model,
"at": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"),
"state_hash": util.sha256_text(json.dumps(st, sort_keys=True)),
"questions_hash": util.sha256_text(json.dumps(qs, sort_keys=True)),
"answers": {k: {"choice": a.get("choice"), "confidence": a.get("confidence"), "probabilities": a.get("probabilities")} for k, a in answers.items()},
}