`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.
201 lines
9.6 KiB
Python
201 lines
9.6 KiB
Python
"""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))
|