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.
This commit is contained in:
1 parent
dde801c653
commit
65e7a0a97c
6 files changed
+352
-4
No files matched your search
@@ -8,6 +8,7 @@
|
||||
python3 -m ajieval classify RUN_DIR --suggest [--auto-accept]
|
||||
python3 -m ajieval triage runs/ [--plan PLAN.json] [--json]
|
||||
python3 -m ajieval calibrate runs/
|
||||
python3 -m ajieval sessions hook|scan TRANSCRIPT|report
|
||||
"""
|
||||
|
||||
import argparse
|
||||
@@ -18,7 +19,7 @@ import sys
|
||||
|
||||
import datetime
|
||||
|
||||
from . import freeze, jev, languages, native, record, report, triage, util
|
||||
from . import freeze, jev, languages, native, record, report, sessions, triage, util
|
||||
|
||||
# Protocol §27 categories and §38 causes; their descriptions (the questions
|
||||
# Jev answers) are defined once, in jev.py.
|
||||
@@ -269,6 +270,13 @@ def main(argv=None):
|
||||
cb.add_argument("--json", action="store_true")
|
||||
cb.set_defaults(fn=triage.main_calibrate)
|
||||
|
||||
se = sub.add_parser("sessions", help="advisory feedback on AGENTS.md, skills and memory from Claude Code session corrections")
|
||||
se.add_argument("action", choices=["hook", "scan", "report"])
|
||||
se.add_argument("transcript", nargs="?", help="scan: a Claude Code transcript (.jsonl)")
|
||||
se.add_argument("--config")
|
||||
se.add_argument("--json", action="store_true")
|
||||
se.set_defaults(fn=sessions.main)
|
||||
|
||||
v = sub.add_parser("vsr", help="B1 §6.1: verified success rate per agent × language with 95 %% Wilson intervals")
|
||||
v.add_argument("paths", nargs="+")
|
||||
v.add_argument("--tasks", help="comma-separated task ids to include (e.g. the medium ones)")
|
||||
|
||||
@@ -13,7 +13,8 @@ Boundaries (tools/eval only; never the verifier, CI gates or conformance):
|
||||
the last failing commands), because unrelated detail lowers accuracy;
|
||||
- the questions below are the single reviewable definition.
|
||||
|
||||
TYPESAFE_API_KEY bearer token (required, never recorded)
|
||||
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
|
||||
"""
|
||||
|
||||
@@ -134,10 +135,24 @@ def ask(state_obj, qs, post=None):
|
||||
return resp.get("model"), answers
|
||||
|
||||
|
||||
def _post(body):
|
||||
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("TYPESAFE_API_KEY is not set")
|
||||
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"})
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
"""Skill and instruction feedback from Claude Code sessions (advisory).
|
||||
|
||||
At the end of a session (a SessionEnd hook) every human prompt is paired
|
||||
with what the assistant did just before it, and Jev answers two questions:
|
||||
is the prompt a correction of the assistant, and which repository rule, if
|
||||
any, the corrected behaviour broke. Answers go to a local log only. `report`
|
||||
proposes clarifying a rule when corrections pointing to it recur across
|
||||
sessions; it never edits AGENTS.md, a skill or memory.
|
||||
|
||||
What is sent: the tail of the assistant's text and tool commands before the
|
||||
prompt, and the prompt, both truncated and with credential-like strings
|
||||
redacted. Nothing is sent without a TypeSafe key.
|
||||
|
||||
python3 -m ajieval sessions hook # SessionEnd hook: reads the hook JSON on stdin, scans in the background
|
||||
python3 -m ajieval sessions scan TRANSCRIPT.jsonl
|
||||
python3 -m ajieval sessions report [--json]
|
||||
"""
|
||||
|
||||
import collections
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from . import jev, triage, util
|
||||
|
||||
LOG_DIR = os.path.join(os.path.expanduser("~"), ".cache", "aji-sessions")
|
||||
LOG = os.path.join(LOG_DIR, "events.jsonl")
|
||||
ASSISTANT_TAIL = 1200
|
||||
PROMPT_MAX = 800
|
||||
EXCERPT = 240
|
||||
|
||||
# id -> (where the rule lives, the rule as Jev reads it). The single
|
||||
# reviewable definition; changing it changes `rules_hash`.
|
||||
RULES = {
|
||||
"spec_precedence": ("AGENTS.md", "docs/spec is normative; reference, examples, README and RFCs never override it"),
|
||||
"vertical_feature": ("AGENTS.md", "a new language feature lands through every layer: spec, AIR, verifier, interpreter, .aji syntax, Quick Reference, and conformance tests in AIR and .aji"),
|
||||
"memory_concurrency_checklist": ("AGENTS.md", "a change to ownership, aliasing, atomics, tasks, resources, FFI or unsafe code states the invariant, verifier rule, runtime rule, valid and rejected examples, diagnostics, interpreter behaviour and compatibility"),
|
||||
"testing_policy": ("AGENTS.md", "every verifier rule has a positive and a negative conformance test and a stable diagnostic code"),
|
||||
"air_format_frozen": ("AGENTS.md", "the meaning of AIR format 0 never changes; every extension belongs to a registered feature"),
|
||||
"no_benchmark_tuning": ("AGENTS.md", "the language is never shaped to a benchmark task, the M/C corpus or held-out data"),
|
||||
"no_wall_clock": ("AGENTS.md", "runs and tests end by fuel, never by wall-clock timeouts"),
|
||||
"open_questions": ("AGENTS.md", "unresolved specification gaps are logged in docs/design/open-questions.md instead of guessed"),
|
||||
"rfc_complexity": ("AGENTS.md", "an RFC introducing a semantic feature includes an Agent complexity impact section"),
|
||||
"verify_before_done": ("AGENTS.md", "build, unit tests, conformance and zig fmt are run before work is reported done"),
|
||||
"commit_rules": ("memory: no-commit-attribution", "commits are made only when asked, unsigned, without attribution trailers"),
|
||||
"jev_limits": (".claude/skills/aji-jev/SKILL.md", "Jev is used only in tools/eval, only as advice, only on dev and validation data"),
|
||||
"scope": ("AGENTS.md (no rule yet)", "do what was asked: no unrequested changes, files or scope"),
|
||||
"none": (None, "the prompt does not point to any of these rules"),
|
||||
}
|
||||
|
||||
SECRETISH = re.compile(r"<SECRET:[^>]*>|\b(?:sk|pk|ghp|gho|xox[bap])[-_][A-Za-z0-9_-]{12,}|\b[A-Za-z0-9+/_-]{40,}\b")
|
||||
|
||||
|
||||
def redact(text):
|
||||
return SECRETISH.sub("[redacted]", text)
|
||||
|
||||
|
||||
def rules_hash():
|
||||
return util.sha256_text(json.dumps(RULES, sort_keys=True))
|
||||
|
||||
|
||||
def questions():
|
||||
return {
|
||||
"correction": {"type": "noul", "instructions": "Does the user's prompt correct, reject or redirect what the assistant just did?",
|
||||
"criteria": {"true": "the user says the assistant's action or answer was wrong, unwanted or incomplete",
|
||||
"false": "a new request, an answer to a question, approval, or thanks"}},
|
||||
"rule": {"type": "choice", "instructions": "Which repository rule did the assistant's corrected behaviour break?",
|
||||
"criteria": {k: v[1] for k, v in RULES.items()}},
|
||||
}
|
||||
|
||||
|
||||
def _text(content):
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
return "\n".join(b.get("text", "") for b in content or [] if isinstance(b, dict) and b.get("type") == "text")
|
||||
|
||||
|
||||
def episodes(transcript_path):
|
||||
"""(uuid, session, assistant tail, prompt) for every human prompt that
|
||||
follows assistant activity."""
|
||||
out, before, session = [], [], None
|
||||
with open(transcript_path, encoding="utf-8", errors="replace") as f:
|
||||
for line in f:
|
||||
try:
|
||||
e = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if e.get("isSidechain") or e.get("type") not in ("user", "assistant"):
|
||||
continue
|
||||
session = session or e.get("sessionId")
|
||||
content = (e.get("message") or {}).get("content")
|
||||
if e["type"] == "assistant":
|
||||
for b in content if isinstance(content, list) else []:
|
||||
if b.get("type") == "text":
|
||||
before.append(b.get("text", ""))
|
||||
elif b.get("type") == "tool_use":
|
||||
inp = b.get("input") or {}
|
||||
before.append(f"[{b.get('name')}] " + str(inp.get("command") or inp.get("file_path") or inp.get("description") or "")[:160])
|
||||
continue
|
||||
if e.get("isMeta"):
|
||||
continue
|
||||
prompt = content if isinstance(content, str) else (_text(content) if all(b.get("type") == "text" for b in content or []) else None)
|
||||
if not prompt or prompt.lstrip().startswith("<"):
|
||||
continue
|
||||
if before:
|
||||
out.append((e.get("uuid"), session, redact("\n".join(before))[-ASSISTANT_TAIL:], redact(prompt)[:PROMPT_MAX]))
|
||||
before = []
|
||||
return out
|
||||
|
||||
|
||||
def seen(log=LOG):
|
||||
if not os.path.isfile(log):
|
||||
return set()
|
||||
with open(log) as f:
|
||||
return {json.loads(l).get("uuid") for l in f if l.strip()}
|
||||
|
||||
|
||||
def scan(transcript_path, post=None, log=LOG):
|
||||
"""Classifies the transcript's unseen episodes; appends one line each."""
|
||||
done = seen(log)
|
||||
qs, rh = questions(), rules_hash()
|
||||
os.makedirs(os.path.dirname(log), exist_ok=True)
|
||||
n = 0
|
||||
for uuid, session, assistant, prompt in episodes(transcript_path):
|
||||
if uuid in done:
|
||||
continue
|
||||
model, a = jev.ask({"assistant_before": assistant, "user_prompt": prompt}, qs, post)
|
||||
rec = {"uuid": uuid, "session": session, "at": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"),
|
||||
"model": model, "rules_hash": rh, "correction": a["correction"].get("noul"),
|
||||
"rule": a["rule"].get("choice"), "rule_confidence": a["rule"].get("confidence"), "prompt_excerpt": prompt[:EXCERPT]}
|
||||
with open(log, "a") as f:
|
||||
f.write(json.dumps(rec) + "\n")
|
||||
n += 1
|
||||
return n
|
||||
|
||||
|
||||
def report(cfg, log=LOG):
|
||||
c = cfg["sessions"]
|
||||
groups = collections.defaultdict(list)
|
||||
if os.path.isfile(log):
|
||||
with open(log) as f:
|
||||
for line in f:
|
||||
r = json.loads(line)
|
||||
if r.get("rules_hash") != rules_hash() or (r.get("correction") or 0) < c["min_correction"]:
|
||||
continue
|
||||
if r.get("rule") in (None, "none") or (r.get("rule_confidence") or 0) < c["min_rule_confidence"]:
|
||||
groups["unattributed"].append(r)
|
||||
continue
|
||||
groups[r["rule"]].append(r)
|
||||
rows = []
|
||||
for rule, rs in sorted(groups.items(), key=lambda kv: -len(kv[1])):
|
||||
sessions = {r["session"] for r in rs}
|
||||
rows.append({"rule": rule, "target": RULES.get(rule, (None,))[0], "corrections": len(rs), "sessions": len(sessions),
|
||||
"proposed": rule != "unattributed" and len(rs) >= c["min_events"] and len(sessions) >= c["min_sessions"],
|
||||
"excerpts": [r["prompt_excerpt"] for r in rs[-3:]]})
|
||||
return rows
|
||||
|
||||
|
||||
def render(rows):
|
||||
out = ["## Instruction feedback from sessions\n"]
|
||||
props = [r for r in rows if r["proposed"]]
|
||||
out.append(f"{len(props)} proposal(s). A proposal means: clarify or strengthen the rule where it lives; it is not a decision.\n")
|
||||
for r in props:
|
||||
out += [f"### {r['rule']} → {r['target']}\n", f"- {r['corrections']} corrections in {r['sessions']} sessions",
|
||||
f"- rule as read: {RULES[r['rule']][1]}"] + [f"- example: {x!r}" for x in r["excerpts"]] + [""]
|
||||
rest = [r for r in rows if not r["proposed"]]
|
||||
if rest:
|
||||
out += ["| rule | corrections | sessions |", "|---|---|---|"] + [f"| {r['rule']} | {r['corrections']} | {r['sessions']} |" for r in rest]
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def hook():
|
||||
"""SessionEnd hook: returns at once; the scan runs detached."""
|
||||
try:
|
||||
data = json.load(sys.stdin)
|
||||
except ValueError:
|
||||
return
|
||||
path = data.get("transcript_path")
|
||||
if not path or not os.path.isfile(path) or not jev.api_key():
|
||||
return
|
||||
os.makedirs(LOG_DIR, exist_ok=True)
|
||||
with open(os.path.join(LOG_DIR, "hook.log"), "a") as logf:
|
||||
subprocess.Popen([sys.executable, "-m", "ajieval", "sessions", "scan", path], cwd=os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
|
||||
stdin=subprocess.DEVNULL, stdout=logf, stderr=logf, start_new_session=True)
|
||||
|
||||
|
||||
def main(a):
|
||||
if a.action == "hook":
|
||||
return hook()
|
||||
if a.action == "scan":
|
||||
try:
|
||||
print(f"{scan(a.transcript)} episode(s) classified", file=sys.stderr)
|
||||
except jev.JevError as e:
|
||||
raise SystemExit(f"sessions scan: {e}")
|
||||
return
|
||||
rows = report(triage.load_config(a.config))
|
||||
print(json.dumps(rows, indent=2) if a.json else render(rows))
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Session feedback (ajieval sessions), offline: transcript parsing,
|
||||
redaction, idempotent scans and the report thresholds."""
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, os.path.dirname(HERE))
|
||||
|
||||
from ajieval import sessions # noqa: E402
|
||||
|
||||
CFG = {"sessions": {"min_correction": 0.7, "min_rule_confidence": 0.6, "min_events": 2, "min_sessions": 2}}
|
||||
|
||||
|
||||
def entry(kind, content, uuid, session="s1", **kw):
|
||||
return dict({"type": kind, "uuid": uuid, "sessionId": session, "message": {"role": kind, "content": content}}, **kw)
|
||||
|
||||
|
||||
def transcript(path, session="s1", prompt="no, you must not commit without asking"):
|
||||
rows = [
|
||||
entry("user", "first request", "u0", session),
|
||||
entry("assistant", [{"type": "text", "text": "Done, committed."}, {"type": "tool_use", "name": "Bash", "input": {"command": "git commit -m x"}}], "a1", session),
|
||||
entry("user", [{"type": "tool_result", "content": "ok"}], "t1", session),
|
||||
entry("user", "<command-name>/foo</command-name>", "c1", session),
|
||||
entry("user", "meta", "m1", session, isMeta=True),
|
||||
entry("assistant", [{"type": "text", "text": "Key is sk-ABCDEFGHIJKLMNOPQRSTUV"}], "a2", session),
|
||||
entry("user", prompt, "u1", session),
|
||||
entry("assistant", [{"type": "text", "text": "side"}], "x1", session, isSidechain=True),
|
||||
]
|
||||
with open(path, "w") as f:
|
||||
for r in rows:
|
||||
f.write(json.dumps(r) + "\n")
|
||||
|
||||
|
||||
def canned(correction=0.9, rule="commit_rules", confidence=0.8):
|
||||
calls = []
|
||||
|
||||
def post(body):
|
||||
calls.append(body)
|
||||
return {"model": "jev-test", "answers": {"correction": {"type": "noul", "noul": correction},
|
||||
"rule": {"type": "choice", "choice": rule, "confidence": confidence}}}
|
||||
return post, calls
|
||||
|
||||
|
||||
class Sessions(unittest.TestCase):
|
||||
def test_episodes_skip_tool_results_meta_commands_and_sidechains(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
p = os.path.join(d, "t.jsonl")
|
||||
transcript(p)
|
||||
eps = sessions.episodes(p)
|
||||
self.assertEqual([e[0] for e in eps], ["u1"])
|
||||
uuid, session, assistant, prompt = eps[0]
|
||||
self.assertIn("[Bash] git commit -m x", assistant)
|
||||
self.assertIn("[redacted]", assistant)
|
||||
self.assertNotIn("sk-ABCDEFGHIJ", assistant)
|
||||
self.assertEqual((session, prompt), ("s1", "no, you must not commit without asking"))
|
||||
|
||||
def test_scan_is_idempotent_and_sends_only_the_episode(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
p, log = os.path.join(d, "t.jsonl"), os.path.join(d, "log", "events.jsonl")
|
||||
transcript(p)
|
||||
post, calls = canned()
|
||||
self.assertEqual(sessions.scan(p, post, log), 1)
|
||||
self.assertEqual(sessions.scan(p, post, log), 0)
|
||||
self.assertEqual(len(calls), 1)
|
||||
self.assertEqual(set(calls[0]["state"]), {"assistant_before", "user_prompt"})
|
||||
self.assertIn("none", calls[0]["questions"]["rule"]["criteria"])
|
||||
|
||||
def test_report_needs_recurrence_across_sessions(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
log = os.path.join(d, "events.jsonl")
|
||||
for i, s in enumerate(["s1", "s1"]):
|
||||
p = os.path.join(d, f"t{i}.jsonl")
|
||||
transcript(p, s, prompt=f"wrong {i}")
|
||||
with open(p) as f:
|
||||
rows = [json.loads(l) for l in f]
|
||||
with open(p, "w") as f:
|
||||
for r in rows:
|
||||
r["uuid"] = f"{r['uuid']}-{i}"
|
||||
f.write(json.dumps(r) + "\n")
|
||||
sessions.scan(p, canned()[0], log)
|
||||
rows = sessions.report(CFG, log)
|
||||
self.assertEqual((rows[0]["rule"], rows[0]["corrections"], rows[0]["proposed"]), ("commit_rules", 2, False))
|
||||
p = os.path.join(d, "t9.jsonl")
|
||||
transcript(p, "s2")
|
||||
sessions.scan(p, canned()[0], log)
|
||||
rows = sessions.report(CFG, log)
|
||||
self.assertTrue(rows[0]["proposed"])
|
||||
self.assertIn("memory: no-commit-attribution", sessions.render(rows))
|
||||
|
||||
def test_low_confidence_and_non_corrections_are_not_attributed(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
log = os.path.join(d, "events.jsonl")
|
||||
p = os.path.join(d, "t.jsonl")
|
||||
transcript(p)
|
||||
sessions.scan(p, canned(correction=0.2)[0], log)
|
||||
self.assertEqual(sessions.report(CFG, log), [])
|
||||
os.remove(log)
|
||||
sessions.scan(p, canned(confidence=0.3)[0], log)
|
||||
self.assertEqual(sessions.report(CFG, log)[0]["rule"], "unattributed")
|
||||
|
||||
def test_hook_without_key_does_nothing(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
p = os.path.join(d, "t.jsonl")
|
||||
transcript(p)
|
||||
with patch("ajieval.jev.api_key", return_value=None), patch("subprocess.Popen") as popen, \
|
||||
patch("sys.stdin", io.StringIO(json.dumps({"transcript_path": p}))):
|
||||
sessions.hook()
|
||||
popen.assert_not_called()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -3,6 +3,7 @@
|
||||
"calibrated": false,
|
||||
"min_confidence": {"category": 0.8, "cause": 0.8, "caught_by": 0.8},
|
||||
"proposal": {"min_events": 3, "min_tasks": 2, "min_agents": 2},
|
||||
"sessions": {"min_correction": 0.7, "min_rule_confidence": 0.6, "min_events": 3, "min_sessions": 2},
|
||||
"routes": {
|
||||
"diagnostics": {"layer": "diagnostic text", "target": "src/diag.zig, docs/reference/error-codes.md", "action": "patch the message and add a test; PR review"},
|
||||
"agent_bundle": {"layer": "agent bundle", "target": "docs/agent/, Quick Reference", "action": "patch; PR review; only between experiment iterations"},
|
||||
|
||||
Reference in new issue
Block a user