diff options
| author | Morgan Lunt <morganl@anthropic.com> | 2026-09-25 12:06:43 -0700 |
|---|---|---|
| committer | Morgan Lunt <morganl@anthropic.com> | 2026-09-25 12:06:43 -0700 |
| commit | c8874f5ad883e26428f483ffa4d537cc81489e64 (patch) | |
| tree | 191df20989c34e9808757726f4b75740ce523c5f /plugins/code-modernization/scripts | |
| parent | 363af43603ecdb1bdbed7303764b6daeeec7c37f (diff) | |
code-modernization: count failures and the machine's python, once per versionmorganl/code-modernization-consolidated
Usage counts now say what the plugin runs on (system, python status and version, path problems) and which kind of failure happens: a missing or placeholder python, a permission block, a model error, or an error in the plugin's own script. Failures are classified on the machine into a fixed list and only the code is sent, once per kind per session. A session-start ping, once per plugin version, counts machines where nobody gets as far as typing a command. When python cannot run, the shell wrapper reports that itself, and on Windows it falls back to python or the py launcher.
Diffstat (limited to 'plugins/code-modernization/scripts')
| -rw-r--r-- | plugins/code-modernization/scripts/telemetry.py | 206 | ||||
| -rw-r--r-- | plugins/code-modernization/scripts/telemetry.sh | 135 | ||||
| -rw-r--r-- | plugins/code-modernization/scripts/tests/test_telemetry.py | 222 |
3 files changed, 523 insertions, 40 deletions
diff --git a/plugins/code-modernization/scripts/telemetry.py b/plugins/code-modernization/scripts/telemetry.py index ada1d953..5079e684 100644 --- a/plugins/code-modernization/scripts/telemetry.py +++ b/plugins/code-modernization/scripts/telemetry.py @@ -1,8 +1,10 @@ #!/usr/bin/env python3 """Usage counts for the code-modernization plugin. Whole numbers only, never text. - telemetry.py command UserPromptSubmit hook: which of the plugin's commands was typed + telemetry.py command UserPromptSubmit hook: which of the plugin's commands was typed, and on what kind of machine telemetry.py state Stop hook: how far the newest system under analysis/ has got + telemetry.py run Stop hook: how the last rule extraction went (agents started, lost, unverified) + telemetry.py failure hook after a python command, a failed tool call or a failed model call: what kind of failure telemetry.py show [DIR] [--prompt TEXT] [--json] print what the hooks would send for the workspace DIR (default: this folder) @@ -23,11 +25,13 @@ import hashlib import itertools import json import os +import platform import re import signal import stat import sys import tempfile +import threading import time sys.dont_write_bytecode = True # a hook must not leave files in the plugin's own folder @@ -39,9 +43,10 @@ MAX_KEYS, CAP = 20, 10 ** 9 TRUE = {"1", "true", "on", "yes"} # The most a key can carry: a hostile artifact cannot make a count bigger than this. Counts from 100 up are rounded to two # significant figures; enumerations and the step bitmask are exact. -LIMITS = {"pv": 999999, "cmd": 99, "perm": 6, "has_source": 1, "fresh": 1, "systems": 99, "goal": 4, "lang": 99, "done": 65535, "phases": 99} +LIMITS = {"pv": 999999, "cmd": 99, "perm": 6, "has_source": 1, "fresh": 1, "systems": 99, "goal": 4, "lang": 99, "done": 65535, "phases": 99, + "os": 9, "py": 9, "pyv": 999, "pathf": 7, "tool": 99, "kind": 99, "api": 99, "err": 99, "err_at": 99999} COUNT_LIMIT = 10 ** 7 -EXACT = {"pv", "cmd", "perm", "has_source", "fresh", "goal", "lang", "done"} +EXACT = {"pv", "cmd", "perm", "has_source", "fresh", "goal", "lang", "done", "os", "py", "pyv", "pathf", "tool", "kind", "api", "err", "err_at"} NAME = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}") LINE_WIDTH = 600 # longer lines are cut before anything is parsed, so no artifact can make a pattern slow @@ -51,6 +56,32 @@ COMMANDS = {"": 1, "preflight": 2, "assess": 3, "map": 4, "extract-rules": 5, "r PANE = {"panel": 20, "review-pane": 21, "sign": 22} OTHER_COMMAND = 99 PERMISSION_MODES = {"default": 1, "acceptEdits": 2, "plan": 3, "auto": 4, "bypassPermissions": 5, "dontAsk": 6} +TOOLS = {"Bash": 1, "Read": 2, "Edit": 3, "Write": 3, "MultiEdit": 3, "NotebookEdit": 3, "Glob": 4, "Grep": 4, "Agent": 5, "Task": 5, "Workflow": 6, + "AskUserQuestion": 7, "Skill": 8, "WebFetch": 9, "WebSearch": 9} +# What went wrong, decided here from the text of a failure and never sent: first match wins. 1-5 are about the interpreter and the plugin's own scripts. +FAILURE_KINDS = [ + (2, re.compile(r"python was not found|run without arguments to install from the microsoft store", re.I)), + (3, re.compile(r"xcode-select: note|no developer tools were found|command line developer tools", re.I)), + (1, re.compile(r"\b(?:python3?|py)(?:\.exe)?: (?:command )?not found|command not found: (?:python3?|py)\b|'(?:python3?|py)' is not recognized|python3?: no such file|env: .?python3?.?: no such file", re.I)), + (4, re.compile(r"syntaxerror|requires python 3|invalid syntax", re.I)), + (6, re.compile(r"permission to use|was denied|denied by|not allowed|blocked by|auto mode", re.I)), + (7, re.compile(r"eacces|permission denied|access is denied", re.I)), + (8, re.compile(r"timed out|timeout|etimedout", re.I)), + (11, re.compile(r"enospc|no space left|out of memory|cannot allocate memory|disk quota", re.I)), + (10, re.compile(r"econnrefused|enotfound|could not resolve host|certificate|\bssl\b|proxy|unauthori[sz]ed|\b401\b|\b403\b|\b429\b", re.I)), + (9, re.compile(r"no such file|cannot find the path|enoent|does not exist|not found", re.I)), + (12, re.compile(r"scriptpath|unknown tool|workflow|subagent", re.I)), +] +API_ERRORS = [ + (1, re.compile(r"rate.?limit|\b429\b", re.I)), + (2, re.compile(r"authenticat|unauthori[sz]ed|invalid.?api.?key|\b40[13]\b|oauth", re.I)), + (3, re.compile(r"billing|credit|payment|quota", re.I)), + (6, re.compile(r"max.?output|max_tokens|too long", re.I)), + (7, re.compile(r"timeout|timed out|network|econn|connection", re.I)), + (5, re.compile(r"server.?error|overloaded|\b5\d\d\b|internal", re.I)), + (4, re.compile(r"invalid.?request|\b400\b|unrecognized_model|not_found", re.I)), +] +ERROR_CODES = [(UnicodeError, 8), (KeyError, 1), (ValueError, 2), (OSError, 3), (TypeError, 4), (AttributeError, 5), (RecursionError, 6), (MemoryError, 7)] COMMAND_RE = re.compile(r"^/(?P<ns>code-modernization:)?modernize(?:-(?P<verb>[a-z][a-z-]*))?(?=\s|$)") GOALS = {"understand": 1, "uplift": 2, "transform": 3, "reimagine": 4} @@ -110,8 +141,27 @@ MEANING = collections.OrderedDict([ ("v_not", "modules judged NOT PROVEN"), ("sec_crit", "critical security findings"), ("sec_high", "high security findings"), + ("os", "system: 1 macOS, 2 Linux, 3 Windows, 4 Windows subsystem for Linux, 0 other"), + ("py", "how python worked: 0 python3 ran, 1 none found, 2 macOS developer-tools stub, 3 python3 present but broken (the Windows Store stub), " + "4 python3 unusable but python or py ran, 5 too old, 6 the script crashed"), + ("pyv", "python version as major*100 + minor (311 is 3.11)"), + ("pathf", "the folder's path: 1 has a space, 2 has non-ASCII characters, 4 is over 200 characters (added up)"), + ("tool", "the tool that failed: 1 Bash, 2 Read, 3 Edit or Write, 4 Glob or Grep, 5 agent, 6 Workflow, 7 asking the person, 8 skill, 9 web, 10 a connector, 99 other"), + ("kind", "what went wrong: 1 python or another interpreter missing, 2 the Windows Store python stub, 3 the macOS developer-tools stub, 4 python too old or a syntax error, " + "5 one of the plugin's scripts raised an error, 6 blocked by a permission rule or policy, 7 a file permission was denied, 8 timed out, 9 a file or folder was not found, " + "10 network, certificate or sign-in, 11 disk or memory, 12 workflow or agent trouble, 99 other"), + ("api", "a model call ended a turn: 1 rate limit, 2 sign-in failed, 3 billing, 4 invalid request, 5 server error or overloaded, 6 output too long, 7 network or timeout, 99 unknown"), + ("err", "the plugin's own script raised: 1 KeyError, 2 ValueError, 3 OSError, 4 TypeError, 5 AttributeError, 6 RecursionError, 7 MemoryError, 8 UnicodeError, 99 other"), + ("err_at", "the line of telemetry.py where it raised"), + ("agents", "agents the last rule extraction started"), + ("wf_failed", "modules or agents that extraction lost"), + ("wf_skip", "modules that extraction skipped"), + ("wf_unver", "rules that extraction could not verify"), ]) -COMMAND_KEYS = ("pv", "cmd", "perm", "has_source", "fresh", "systems", "goal", "done") +COMMAND_KEYS = ("pv", "cmd", "perm", "has_source", "fresh", "systems", "goal", "done", "os", "py", "pyv", "pathf") +RUN_KEYS = ("pv", "agents", "wf_failed", "wf_skip", "wf_unver") +FAILURE_KEYS = ("pv", "os", "py", "pyv", "pathf", "tool", "kind", "api") +ERROR_KEYS = ("pv", "os", "py", "pyv", "err", "err_at") STATE_KEYS = ("pv", "goal", "lang", "done", "map_kloc", "rules", "p0", "rev_ok", "rev_wrong", "phases", "built", "eq_cases", "eq_diff", "eq_appr", "v_proven", "v_partly", "v_not", "sec_crit", "sec_high") @@ -322,6 +372,39 @@ def snapshot(cwd, system): return out +def os_code(): + """1 macOS, 2 Linux, 3 Windows, 4 WSL, 0 other. The shell wrapper knows best (uname); this is the fallback.""" + given = os.environ.get("CODE_MODERNIZATION_OS", "") + if given.isdigit(): + return min(int(given), 9) + system = platform.system().lower() + if system == "linux": + try: + with open("/proc/version", encoding="utf-8", errors="replace") as fh: + return 4 if "microsoft" in fh.read().lower() else 2 + except OSError: + return 2 + return {"darwin": 1, "windows": 3}.get(system, 0) + + +def python_status(): + """0 when python3 itself ran this; the shell wrapper says 4 when it had to fall back to python or py.""" + given = os.environ.get("CODE_MODERNIZATION_PY", "") + return min(int(given), 9) if given.isdigit() else 0 + + +def path_flags(cwd): + """The bits of a folder path that break scripts on Windows: 1 a space, 2 a non-ASCII character, 4 over 200 characters.""" + given = os.environ.get("CODE_MODERNIZATION_PATHF", "") + if given.isdigit(): + return min(int(given), 7) + return (1 if " " in cwd else 0) + (2 if any(ord(c) > 126 for c in cwd) else 0) + (4 if len(cwd) > 200 else 0) + + +def environment(cwd): + return [("os", os_code()), ("py", python_status()), ("pyv", sys.version_info[0] * 100 + sys.version_info[1]), ("pathf", path_flags(cwd))] + + def system_word(words): """The first plain word of a command's arguments, which is the system's name (a flag's value is not).""" skip = False @@ -360,7 +443,65 @@ def command_metrics(prompt, cwd, permission_mode=None): perm = PERMISSION_MODES.get(permission_mode, 0) if isinstance(permission_mode, str) else 0 return collections.OrderedDict([("pv", plugin_version()), ("cmd", cmd), ("perm", perm), ("has_source", int("--source" in words)), ("fresh", int(snap is None)), ("systems", min(len(systems), 99)), - ("goal", snap["goal"] if snap else 0), ("done", snap["done"] if snap else 0)]) + ("goal", snap["goal"] if snap else 0), ("done", snap["done"] if snap else 0)] + environment(cwd)) + + +def health_metrics(cwd): + """Once per version and machine (the shell wrapper keeps count): what the plugin is running on.""" + return collections.OrderedDict([("pv", plugin_version())] + environment(cwd)) + + +def run_metrics(cwd): + """How the newest system's last rule extraction went, from the statistics the workflow wrote, or None.""" + for _, system in systems_in(cwd)[:5]: + src = br.Source(cwd, system) + result, _ = src.json(os.path.join(src.adir, "rules_result.json"), "rules_result.json") + stats = result.get("stats") if isinstance(result, dict) and isinstance(result.get("stats"), dict) else None + if stats is None: + continue + size = lambda key: len(stats[key]) if isinstance(stats.get(key), list) else 0 # noqa: E731 + return collections.OrderedDict([("pv", plugin_version()), ("agents", whole(stats.get("agents"))), ("wf_failed", size("failedModules") + size("droppedModules")), + ("wf_skip", size("skippedModules")), ("wf_unver", whole(stats.get("unverified")))]) + return None + + +def tool_code(name): + name = str(name or "") + return TOOLS.get(name) or (10 if name.startswith("mcp__") else 99) + + +def failure_kind(text): + """A code for what went wrong, decided from the failure's own text (which is never sent), or None when it says nothing useful.""" + text = str(text or "")[:8000] + if "Traceback" in text and ("code-modernization" in text or "scripts/" in text or "scripts\\" in text): + return 5 + for code, pattern in FAILURE_KINDS: + if pattern.search(text): + return code + return None + + +def failure_metrics(data, cwd): + """One failure as numbers: a failed tool call, or a model call that ended a turn. None when there is nothing to say.""" + event, session = str(data.get("hook_event_name") or ""), str(data.get("session_id") or "") + base = [("pv", plugin_version())] + environment(cwd) + if event == "StopFailure": + text = " ".join(str(data.get(k) or "") for k in ("error", "error_type", "error_details", "message"))[:2000] + api = next((code for code, pattern in API_ERRORS if pattern.search(text)), 99) + tag, extra = "api%d" % api, [("api", api)] + else: + if data.get("is_interrupt") is True: + return None + tool, error = tool_code(data.get("tool_name")), str(data.get("error") or "") + kind = failure_kind(error) + if kind is None: + if tool == 1 and re.fullmatch(r"\s*Exit code \d+\s*", error): + return None # a command that simply exited non-zero, often on purpose + kind = 99 + tag, extra = "t%dk%d" % (tool, kind), [("tool", tool), ("kind", kind)] + if remember("fail|%s|%s" % (session, tag), "1") != "new": # once per session and kind, so a loop of failures is one number + return None + return collections.OrderedDict(base + extra) def state_metrics(cwd): @@ -445,7 +586,7 @@ def remember(key, digest): return "same" seen.pop(key, None) seen[key] = digest - seen = dict(list(seen.items())[-50:]) + seen = dict(list(seen.items())[-200:]) tmp = "%s.%d" % (file, os.getpid()) with open(tmp, "w", encoding="utf-8") as fh: json.dump(seen, fh) @@ -461,14 +602,22 @@ def digest_of(metrics): def hook(mode): """Run one hook. Whatever an artifact holds, a turn is never held up for more than a few seconds.""" - if not hasattr(signal, "SIGALRM"): - return run_hook(mode) - signal.signal(signal.SIGALRM, lambda *_: os._exit(0)) - signal.alarm(3) - try: - run_hook(mode) - finally: - signal.alarm(0) + if hasattr(signal, "SIGALRM"): + signal.signal(signal.SIGALRM, lambda *_: os._exit(0)) + signal.alarm(3) + try: + run_hook(mode) + finally: + signal.alarm(0) + else: # Windows has no alarm signal: a timer thread gives up instead + timer = threading.Timer(3, os._exit, [0]) + timer.daemon = True + timer.start() + try: + run_hook(mode) + finally: + timer.cancel() + timer.join(1) def run_hook(mode): @@ -485,11 +634,16 @@ def run_hook(mode): if mode == "command": metrics = command_metrics(data.get("prompt"), cwd, data.get("permission_mode")) why = "not one of the plugin's commands" + elif mode == "health": + metrics, why = health_metrics(cwd), "" + elif mode == "failure": + metrics = failure_metrics(data, cwd) + why = "nothing worth counting, or the same kind was already sent this session" else: - metrics = state_metrics(cwd) + metrics = run_metrics(cwd) if mode == "run" else state_metrics(cwd) why = "the plugin has left no files here" if metrics is not None: - key = hashlib.sha1(os.path.realpath(cwd).encode()).hexdigest()[:16] + key = hashlib.sha1((os.path.realpath(cwd) + mode).encode()).hexdigest()[:16] status = remember(key, digest_of(ok(metrics))) if status != "new": metrics, why = None, "the counts are the same as last time" if status == "same" else "the state file cannot be written" @@ -539,12 +693,23 @@ def show(args): "nothing: that is not one of the plugin's commands") +def report_error(err, line): + """The plugin's own script raised: send which kind and where, once, never the message.""" + if off_reason(): + return + code = next((c for kind, c in ERROR_CODES if isinstance(err, kind)), 99) + if remember("err|%s|%s|%s" % (plugin_version(), code, line), "1") == "new": + print(json.dumps({"metrics": ok(collections.OrderedDict([("pv", plugin_version()), ("os", os_code()), ("py", python_status()), + ("pyv", sys.version_info[0] * 100 + sys.version_info[1]), ("err", code), ("err_at", line)]))}, + separators=(",", ":")), flush=True) + + def main(argv): mode = argv[1] if len(argv) > 1 else "" try: if mode == "show": show(argv[2:]) - elif mode in ("command", "state"): + elif mode in ("command", "state", "run", "failure", "health"): hook(mode) else: print(__doc__) @@ -554,7 +719,12 @@ def main(argv): tb = err.__traceback__ while tb and tb.tb_next: tb = tb.tb_next - note("%s: error %s at line %s" % (mode, type(err).__name__, tb.tb_lineno if tb else "?")) + line = tb.tb_lineno if tb else 0 + note("%s: error %s at line %s" % (mode, type(err).__name__, line)) + try: + report_error(err, line) + except Exception: # reporting a problem must not become one + pass return 0 diff --git a/plugins/code-modernization/scripts/telemetry.sh b/plugins/code-modernization/scripts/telemetry.sh index 10f82054..dec61413 100644 --- a/plugins/code-modernization/scripts/telemetry.sh +++ b/plugins/code-modernization/scripts/telemetry.sh @@ -1,26 +1,129 @@ #!/bin/sh -# The plugin's two usage-count hooks: telemetry.sh command|state, with the hook's JSON on stdin. +# The plugin's usage-count hooks: telemetry.sh command|state|run|failure|health, with the hook's JSON on stdin. # It starts Python only when the plugin is in use here: a plugin command was typed, or the folder holds files the plugin -# wrote under analysis/. A person who merely has the plugin installed never runs anything, and a Mac without developer -# tools never sees the "install command line tools" dialog that a bare python3 would raise. -# What is counted, and how to turn it off: see the Telemetry section of the README and scripts/telemetry.py. +# wrote under analysis/, or (for a failure) the failing command names the plugin. The one exception is `health`, once per +# plugin version and machine at session start: what the plugin runs on, so that a machine where nobody gets as far as typing +# a command is still counted once. A Mac without developer tools never sees the "install command line tools" dialog that a +# bare python3 would raise. +# When Python itself cannot run (missing, the Windows Store stub, too old, crashing) this script says so in numbers, +# because Python cannot report its own absence. What is counted, and how to turn it off: see the Telemetry section of +# the README and scripts/telemetry.py. mode="$1" input=$(cat) +here=$(dirname "$0") + +in_use() { + for f in analysis/*/INTENT.md analysis/*/PREFLIGHT.md analysis/*/MODERNIZATION_BRIEF.md analysis/*/BUSINESS_RULES.md \ + analysis/*/DELTA_CATALOG.md analysis/*/VERIFICATION.json analysis/*/RULE_REVIEWS.json analysis/*/AI_NATIVE_SPEC.md; do + [ -f "$f" ] && return 0 + done + return 1 +} + case "$mode" in command) printf '%s' "$input" | grep -Eq '"prompt"[[:space:]]*:[[:space:]]*"[[:space:]]*/(code-modernization:)?modernize' || exit 0 ;; - state) - found= - for f in analysis/*/INTENT.md analysis/*/PREFLIGHT.md analysis/*/MODERNIZATION_BRIEF.md analysis/*/BUSINESS_RULES.md \ - analysis/*/DELTA_CATALOG.md analysis/*/VERIFICATION.json analysis/*/RULE_REVIEWS.json analysis/*/AI_NATIVE_SPEC.md; do - [ -f "$f" ] && found=1 && break - done - [ -n "$found" ] || exit 0 ;; + state|run) in_use || exit 0 ;; + failure) in_use || printf '%s' "$input" | grep -q 'code-modernization' || exit 0 ;; + health) ;; *) exit 0 ;; esac -py=$(command -v python3) || exit 0 -if [ "$py" = /usr/bin/python3 ] && [ "$(uname)" = Darwin ]; then - xcode-select -p >/dev/null 2>&1 || exit 0 + +# The off switches count here as well, so nothing at all is sent, not even a python problem. +for v in "$CODE_MODERNIZATION_TELEMETRY" "$CLAUDE_PLUGIN_OPTION_TELEMETRY"; do + case "$v" in ''|1|true|TRUE|True|on|ON|On|yes|YES|Yes) ;; *) exit 0 ;; esac +done +case "$DISABLE_TELEMETRY$CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC" in *1*|*true*|*TRUE*|*yes*|*on*) exit 0 ;; esac + +# Which system this is: 1 macOS, 2 Linux, 3 Windows (Git Bash, MSYS, Cygwin), 4 WSL, 0 other. +case "$(uname -s 2>/dev/null)" in + Darwin) os=1 ;; + Linux) if grep -qi microsoft /proc/version 2>/dev/null; then os=4; else os=2; fi ;; + MINGW*|MSYS*|CYGWIN*) os=3 ;; + *) os=0 ;; +esac + +# Things about the folder that break scripts on Windows: 1 a space in the path, 2 a non-ASCII character, 4 a long path. +pathf=0 +case "$PWD" in *" "*) pathf=$((pathf + 1)) ;; esac +printf '%s' "$PWD" | LC_ALL=C grep -q '[^ -~]' && pathf=$((pathf + 2)) +[ "${#PWD}" -gt 200 ] && pathf=$((pathf + 4)) + +# The plugin's version as major*10000 + minor*100 + patch, read without Python. +set -- $(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)".*/\1 \2 \3/p' "$here/../.claude-plugin/plugin.json" 2>/dev/null | head -1) +pv=$(( ${1:-0} * 10000 + ${2:-0} * 100 + ${3:-0} )) + +# health is sent once per plugin version and machine: a marker file in the plugin's data folder says it was. +marker="" +if [ "$mode" = health ]; then + d=${CLAUDE_PLUGIN_DATA:-} + [ -d "$d" ] || d="${TMPDIR:-/tmp}/code-modernization-$(id -u 2>/dev/null || echo 0)" + mkdir -p -m 700 "$d" 2>/dev/null + [ -d "$d" ] && [ ! -L "$d" ] && [ -O "$d" ] || exit 0 + marker="$d/health-sent-$pv" + [ -e "$marker" ] && exit 0 +fi +mark() { [ -n "$marker" ] && : > "$marker"; } + +# One line of numbers, for the cases where Python cannot speak for itself. +emit() { + printf '{"metrics":{"pv":%s' "$pv" + for kv in "$@"; do printf ',"%s":%s' "${kv%%:*}" "${kv#*:}"; done + printf '}}\n' +} + +# Run the Python script with one interpreter; sets out and rc. $2 is the python status the script should report. +run_python() { + out=$(printf '%s' "$input" | CODE_MODERNIZATION_OS="$os" CODE_MODERNIZATION_PY="$2" CODE_MODERNIZATION_PATHF="$pathf" \ + PYTHONDONTWRITEBYTECODE=1 $1 "$here/telemetry.py" "$mode" 2>/dev/null) + rc=$? +} + +# python3 first, as everywhere else in the plugin. It is never run on a Mac without developer tools (that raises a dialog). +first=1 # 1 none found, 2 macOS stub, 3 present but broken (the Windows Store stub), 5 too old, 6 the script crashed +p3=$(command -v python3 2>/dev/null) +if [ -n "$p3" ]; then + if [ "$os" = 1 ] && [ "$p3" = /usr/bin/python3 ] && ! xcode-select -p >/dev/null 2>&1; then + first=2 + else + run_python python3 0 + if [ "$rc" = 0 ]; then + [ -n "$out" ] && { mark; printf '%s\n' "$out"; } + exit 0 + fi + ver=$(python3 -c 'import sys; print(sys.version_info[0] * 100 + sys.version_info[1])' 2>/dev/null) + case "$ver" in ''|*[!0-9]*) first=3 ;; *) if [ "$ver" -lt 308 ]; then first=5; else first=6; fi ;; esac + fi fi -# never leave bytecode behind in the plugin's own folder -printf '%s' "$input" | PYTHONDONTWRITEBYTECODE=1 "$py" "$(dirname "$0")/telemetry.py" "$mode" + +# Windows in particular: python3 may be missing or a stub while python or the py launcher works. +for c in python "py -3"; do + command -v "${c%% *}" >/dev/null 2>&1 || continue + run_python "$c" 4 + if [ "$rc" = 0 ]; then + [ -n "$out" ] && { mark; printf '%s\n' "$out"; } + exit 0 + fi +done + +# No interpreter could run the script. Say so in numbers, for a command the person typed or an interpreter failure. +case "$mode" in + command) + verb=$(printf '%s' "$input" | grep -Eo '"prompt"[[:space:]]*:[[:space:]]*"[[:space:]]*/(code-modernization:)?modernize[a-z-]*' | head -1) + ns=""; case "$verb" in *code-modernization:*) ns=1 ;; esac + verb=${verb##*modernize} + case "$verb" in + ""|-) c=1 ;; -preflight) c=2 ;; -assess) c=3 ;; -map) c=4 ;; -extract-rules) c=5 ;; -review) c=6 ;; -brief) c=7 ;; + -transform) c=8 ;; -uplift) c=9 ;; -reimagine) c=10 ;; -verify) c=11 ;; -harden) c=12 ;; -status) c=13 ;; + -panel) c=20 ;; -review-pane) c=21 ;; -sign) c=22 ;; + *) c=99; [ -n "$ns" ] || exit 0 ;; + esac + emit "cmd:$c" "os:$os" "py:$first" "pyv:0" "pathf:$pathf" ;; + health) + mark + emit "os:$os" "py:$first" "pyv:0" "pathf:$pathf" ;; + failure) + if printf '%s' "$input" | grep -Eqi "(python3?|py)(\.exe)?: (command )?not found|'(python3?|py)' is not recognized|Python was not found|python3?: No such file"; then + emit "os:$os" "py:$first" "tool:1" "kind:1" + fi ;; +esac exit 0 diff --git a/plugins/code-modernization/scripts/tests/test_telemetry.py b/plugins/code-modernization/scripts/tests/test_telemetry.py index 75c1d063..c65130cd 100644 --- a/plugins/code-modernization/scripts/tests/test_telemetry.py +++ b/plugins/code-modernization/scripts/tests/test_telemetry.py @@ -11,6 +11,7 @@ import shutil import subprocess import sys import tempfile +import threading import time import unittest from unittest import mock @@ -324,12 +325,13 @@ class Sending(Base): self.hook("command", {"cwd": self.ws, "prompt": "/modernize"}) with mock.patch.dict(os.environ, {"CODE_MODERNIZATION_TELEMETRY": "0"}): self.hook("state", {"cwd": self.ws}) - with mock.patch.object(tm, "state_metrics", side_effect=KeyError("x")), mock.patch.object(sys, "stdin", io.StringIO("{}")): + with mock.patch.object(tm, "state_metrics", side_effect=KeyError("x")), mock.patch.object(sys, "stdin", io.StringIO("{}")), \ + contextlib.redirect_stdout(io.StringIO()): tm.main(["telemetry.py", "state"]) with open(log, encoding="utf-8") as fh: text = fh.read() for want in ("state: sent 19 values", "state: not sent, the counts are the same as last time", "state: not sent, the plugin has left no files here", - "command: not sent, not one of the plugin's commands", "command: sent 8 values", "state: not sent, CODE_MODERNIZATION_TELEMETRY is off", + "command: not sent, not one of the plugin's commands", "command: sent 12 values", "state: not sent, CODE_MODERNIZATION_TELEMETRY is off", "state: error KeyError at line"): self.assertIn(want, text) self.assertNotIn(self.tmp, text) @@ -483,6 +485,142 @@ class Hardening(Base): self.assertEqual(signal.alarm(0), 0) +class Environment(Base): + """What the plugin says about the machine it runs on.""" + + def test_the_shell_wrappers_answers_are_used_and_bounded(self): + with mock.patch.dict(os.environ, {"CODE_MODERNIZATION_OS": "3", "CODE_MODERNIZATION_PY": "4", "CODE_MODERNIZATION_PATHF": "5"}): + got = tm.command_metrics("/modernize", self.ws) + self.assertEqual((got["os"], got["py"], got["pathf"]), (3, 4, 5)) + self.assertEqual(got["pyv"], sys.version_info[0] * 100 + sys.version_info[1]) + with mock.patch.dict(os.environ, {"CODE_MODERNIZATION_OS": "77", "CODE_MODERNIZATION_PY": "-1", "CODE_MODERNIZATION_PATHF": "x"}): + got = tm.command_metrics("/modernize", self.ws) + self.assertEqual((got["os"], got["py"]), (9, 0)) + self.assertIn(got["os"], range(0, 10)) + + def test_this_machine_is_recognised_without_the_wrapper(self): + self.assertIn(tm.os_code(), (1, 2, 3, 4)) + self.assertEqual(tm.python_status(), 0) + + def test_a_path_that_breaks_scripts_is_flagged_in_bits(self): + self.assertEqual([tm.path_flags(p) for p in ("/plain/path", "/has a space", "/caf\u00e9", "/a b/caf\u00e9", "/" + "x" * 250, "/a b/caf\u00e9/" + "x" * 250)], + [0, 1, 2, 3, 4, 7]) + + def test_health_carries_only_the_environment(self): + got = json.loads(self.hook("health", {"cwd": self.ws}))["metrics"] + self.assertEqual(sorted(got), sorted(tm.HEALTH_KEYS if hasattr(tm, "HEALTH_KEYS") else ["pv", "os", "py", "pyv", "pathf"])) + self.assertTrue(all(type(v) is int for v in got.values())) + + +class Failures(Base): + """A failure becomes a tool number and a kind number. Its text is read here and never sent.""" + + CASES = [("Bash", "Exit code 127\nbash: python3: command not found", 1), ("Bash", "Exit code 127\n(eval):1: command not found: python3", 1), + ("Bash", "'python3' is not recognized as an internal or external command", 1), ("Bash", "env: python3: No such file or directory", 1), + ("Bash", "Python was not found; run without arguments to install from the Microsoft Store.", 2), + ("Bash", "xcode-select: note: no developer tools were found at '/Applications/Xcode.app'", 3), + ("Bash", "Exit code 1\n File \"x.py\", line 3\nSyntaxError: invalid syntax", 4), + ("Bash", "Traceback (most recent call last):\n File \"/x/code-modernization/1.0.0/scripts/build_report.py\", line 9\nKeyError: 'a'", 5), + ("Edit", "Permission for this action was denied by the auto mode classifier", 6), ("Bash", "Permission to use Bash with command x has been denied.", 6), + ("Write", "EACCES: permission denied, open '/x'", 7), ("Bash", "Exit code 124\ncommand timed out after 120s", 8), + ("Read", "File does not exist. Note: your current working directory is /x.", 9), ("Bash", "Exit code 127\n(eval):1: command not found: python3_not_a_real_program", 9), + ("WebFetch", "connect ECONNREFUSED 127.0.0.1:443", 10), ("Bash", "npm ERR! 401 Unauthorized", 10), ("Bash", "ENOSPC: no space left on device", 11), + ("Workflow", "scriptPath must be inside the working directory", 12), ("Read", "something nobody has seen before", 99)] + + def fail(self, tool, error, session="s1", **more): + return tm.failure_metrics({"hook_event_name": "PostToolUseFailure", "tool_name": tool, "error": error, "session_id": session, **more}, self.ws) + + def test_each_kind_of_failure_gets_its_code(self): + for tool, text, want in self.CASES: + self.assertEqual(tm.failure_kind(text) or 99, want, text) + for name, want in (("Bash", 1), ("Read", 2), ("MultiEdit", 3), ("Grep", 4), ("Task", 5), ("Workflow", 6), ("AskUserQuestion", 7), ("Skill", 8), ("WebSearch", 9), + ("mcp__x__y", 10), ("Whatever", 99), (None, 99)): + self.assertEqual(tm.tool_code(name), want, name) + + def test_a_failure_is_numbers_only_and_once_per_kind_per_session(self): + first = self.fail("Bash", "Exit code 127\nbash: python3: command not found") + self.assertEqual((first["tool"], first["kind"]), (1, 1)) + self.assertEqual(list(first), ["pv", "os", "py", "pyv", "pathf", "tool", "kind"]) + self.assertTrue(all(type(v) is int for v in tm.ok(first).values())) + self.assertNotIn("python", json.dumps(tm.ok(first))) + self.assertIsNone(self.fail("Bash", "Exit code 127\nbash: python3: command not found")) + self.assertIsNotNone(self.fail("Bash", "Exit code 127\nbash: python3: command not found", session="s2")) + self.assertIsNotNone(self.fail("Bash", "ENOSPC: no space left on device")) + self.assertIsNotNone(self.fail("Read", "ENOSPC: no space left on device")) + + def test_a_plain_non_zero_exit_and_an_interruption_say_nothing(self): + self.assertIsNone(self.fail("Bash", "Exit code 1")) + self.assertIsNone(self.fail("Bash", " Exit code 2 ")) + self.assertIsNone(self.fail("Bash", "Exit code 127\nbash: python3: command not found", is_interrupt=True)) + self.assertIsNotNone(self.fail("Bash", "Exit code 1\ngrep: unmatched [")) + + def test_hostile_failure_text_never_crashes_and_never_leaves(self): + for text in ("x" * 2_000_000, "\x00\x01" * 5000, "\u202e" * 3000, None, 5, {"a": 1}, ["Traceback"] * 100): + got = self.fail("Bash", text, session="h%s" % id(text)) + if got is not None: + self.assertTrue(all(type(v) is int for v in got.values())) + secret = self.fail("Bash", "ENOSPC while writing /home/alice/secret-project/passwords.txt", session="p") + self.assertNotIn("alice", json.dumps(tm.ok(secret))) + + def test_a_model_call_that_ended_a_turn_is_one_code(self): + for text, want in (("rate_limit", 1), ("authentication_failed", 2), ("billing_error", 3), ("invalid_request", 4), ("server_error", 5), ("overloaded_error", 5), + ("max_output_tokens", 6), ("request timeout", 7), ("", 99), ("something new", 99)): + got = tm.failure_metrics({"hook_event_name": "StopFailure", "error": text, "session_id": "m-" + text}, self.ws) + self.assertEqual(got["api"], want, text) + self.assertNotIn("tool", got) + + def test_the_hook_prints_one_line_of_numbers_and_then_nothing(self): + payload = {"cwd": self.ws, "hook_event_name": "PostToolUseFailure", "tool_name": "Read", "error": "File does not exist.", "session_id": "z"} + line = json.loads(self.hook("failure", payload))["metrics"] + self.assertEqual((line["tool"], line["kind"]), (2, 9)) + self.assertEqual(self.hook("failure", payload), "") + + +class Runs(Base): + def test_the_last_extraction_is_counted_from_its_own_statistics(self): + put(self.ws, "analysis/sys/rules_result.json", {"stats": {"agents": 172, "failedModules": ["a", "b"], "droppedModules": ["c"], "skippedModules": ["d"], "unverified": 5}}) + got = tm.ok(tm.run_metrics(self.ws)) + self.assertEqual(dict(got), {"pv": tm.plugin_version(), "agents": 170, "wf_failed": 3, "wf_skip": 1, "wf_unver": 5}) + self.assertTrue(self.hook("run", {"cwd": self.ws})) + self.assertEqual(self.hook("run", {"cwd": self.ws}), "") + + def test_no_statistics_or_odd_ones_say_nothing_or_zeros(self): + self.assertIsNone(tm.run_metrics(self.ws)) + put(self.ws, "analysis/sys/rules_result.json", {"stats": {"agents": "many", "failedModules": "x", "unverified": [1]}}) + got = tm.ok(tm.run_metrics(self.ws)) + self.assertEqual((got["agents"], got["wf_failed"], got["wf_skip"], got["wf_unver"]), (0, 0, 0, 0)) + + +class OwnErrors(Base): + def crash(self, error): + out = io.StringIO() + with mock.patch.object(tm, "state_metrics", side_effect=error), mock.patch.object(sys, "stdin", io.StringIO("{}")), contextlib.redirect_stdout(out): + self.assertEqual(tm.main(["telemetry.py", "state"]), 0) + return out.getvalue() + + def test_the_plugins_own_errors_are_sent_as_a_kind_and_a_line_once(self): + first = self.crash(ValueError("secret text about /home/alice")) + line = json.loads(first)["metrics"] + self.assertEqual(line["err"], 2) + self.assertGreater(line["err_at"], 0) + self.assertNotIn("secret", first) + self.assertEqual(self.crash(ValueError("again")), "") + self.assertEqual(json.loads(self.crash(UnicodeDecodeError("utf-8", b"", 0, 1, "bad")))["metrics"]["err"], 8) + self.assertEqual(json.loads(self.crash(KeyError("k")))["metrics"]["err"], 1) + self.assertEqual(json.loads(self.crash(RuntimeError("odd")))["metrics"]["err"], 99) + + def test_an_error_is_not_reported_when_counts_are_off(self): + with mock.patch.dict(os.environ, {"CODE_MODERNIZATION_TELEMETRY": "0"}): + self.assertEqual(self.crash(KeyError("k")), "") + + def test_without_an_alarm_signal_a_timer_stands_in_and_is_cancelled(self): + class NoAlarm: + pass + with mock.patch.object(tm, "signal", NoAlarm()): + self.assertTrue(self.hook("state", {"cwd": self.ws})) + self.assertEqual([t for t in threading.enumerate() if isinstance(t, threading.Timer)], []) + + class Shell(unittest.TestCase): """scripts/telemetry.sh must start Python only when the plugin is in use.""" @@ -520,9 +658,78 @@ class Shell(unittest.TestCase): self.assertEqual(self.run_hook("command", {"prompt": "/commit"}), "") self.assertEqual(self.run_hook("state", {"cwd": elsewhere}, cwd=elsewhere), "") self.assertEqual(self.run_hook("nonsense", {}), "") - # no python at all: still quiet, still exit 0 + # no python at all: quiet for a turn's end, and a typed command is reported in numbers by the shell itself self.assertEqual(self.run_hook("state", {"cwd": self.ws}, path=no_python), "") - self.assertEqual(self.run_hook("command", {"prompt": "/modernize"}, path=no_python), "") + said = json.loads(self.run_hook("command", {"prompt": "/modernize"}, path=no_python))["metrics"] + self.assertEqual((said["cmd"], said["py"], said["pyv"]), (1, 1, 0)) + + def toolbox(self, name, **fake): + """A PATH folder holding only the tools the wrapper uses plus fake ones: name=script text, or "python" for the real interpreter.""" + d = os.path.join(self.tmp, name) + os.makedirs(d) + for tool in ("grep", "dirname", "sed", "head", "id", "mkdir", "cat", "uname"): + if tool not in fake and shutil.which(tool): + os.symlink(shutil.which(tool), os.path.join(d, tool)) + for tool, body in fake.items(): + path = os.path.join(d, tool) + if body == "python": + os.symlink(sys.executable, path) + else: + with open(path, "w") as fh: + fh.write(body) + os.chmod(path, 0o755) + return d + + def say(self, mode, payload, **kw): + out = self.run_hook(mode, payload, **kw) + return json.loads(out)["metrics"] if out else None + + def test_windows_is_recognised_and_a_missing_python_is_reported_by_the_shell(self): + box = self.toolbox("win", uname="#!/bin/sh\necho MINGW64_NT-10.0-19045\n") + got = self.say("command", {"prompt": "/code-modernization:modernize-verify x"}, path=box) + self.assertEqual((got["os"], got["py"], got["cmd"], got["pyv"]), (3, 1, 11, 0)) + + def test_the_windows_store_placeholder_is_a_broken_python3_and_python_is_used_instead(self): + stub = "#!/bin/sh\necho 'Python was not found; run without arguments to install from the Microsoft Store.' >&2\nexit 49\n" + box = self.toolbox("store", python3=stub, uname="#!/bin/sh\necho MSYS_NT-10.0\n") + self.assertEqual(self.say("command", {"prompt": "/modernize"}, path=box)["py"], 3) # nothing else to fall back to + box = self.toolbox("store2", python3=stub, python="python", uname="#!/bin/sh\necho MSYS_NT-10.0\n") + got = self.say("command", {"prompt": "/modernize"}, path=box) # python does the work, and says so + self.assertEqual((got["os"], got["py"], got["cmd"]), (3, 4, 1)) + self.assertEqual(got["pyv"], sys.version_info[0] * 100 + sys.version_info[1]) + + def test_a_python_that_is_too_old_and_one_that_crashes_are_told_apart(self): + old = "#!/bin/sh\ncase \"$1\" in -c) echo 307 ;; *) exit 1 ;; esac\n" + crash = "#!/bin/sh\ncase \"$1\" in -c) echo 311 ;; *) exit 1 ;; esac\n" + self.assertEqual(self.say("command", {"prompt": "/modernize"}, path=self.toolbox("old", python3=old))["py"], 5) + self.assertEqual(self.say("command", {"prompt": "/modernize"}, path=self.toolbox("crash", python3=crash))["py"], 6) + + def test_health_is_sent_once_per_version_even_when_python_is_missing(self): + box = self.toolbox("nopy") + first = self.say("health", {"cwd": self.ws}, path=box) + self.assertEqual((first["py"], sorted(first)), (1, ["os", "pathf", "pv", "py", "pyv"])) + self.assertIsNone(self.say("health", {"cwd": self.ws}, path=box)) + self.assertTrue(any(n.startswith("health-sent-") for n in os.listdir(self.data))) + + def test_health_from_python_is_sent_once_and_the_off_switch_stops_it(self): + self.assertEqual(self.say("health", {"cwd": self.ws}, env={"CODE_MODERNIZATION_TELEMETRY": "0"}), None) + self.assertFalse(any(n.startswith("health-sent-") for n in os.listdir(self.data))) + first = self.say("health", {"cwd": self.ws}) + self.assertEqual(first["py"], 0) + self.assertIsNone(self.say("health", {"cwd": self.ws})) + + def test_a_python_failure_is_reported_by_the_shell_when_python_cannot_run(self): + box = self.toolbox("nopy2") + put(self.ws, "analysis/sys/PREFLIGHT.md", "# x\n") + got = self.say("failure", {"tool_name": "Bash", "error": "Exit code 127\nbash: python3: command not found"}, path=box) + self.assertEqual((got["tool"], got["kind"], got["py"]), (1, 1, 1)) + self.assertIsNone(self.say("failure", {"tool_name": "Read", "error": "File does not exist."}, path=box)) + + def test_a_folder_with_a_space_and_an_accent_is_flagged(self): + odd = os.path.join(self.tmp, "my caf\u00e9 work") + os.makedirs(odd) + got = self.say("command", {"prompt": "/modernize"}, cwd=odd) + self.assertEqual(got["pathf"], 3) def test_python_starts_only_where_the_plugin_has_left_its_files(self): marker = os.path.join(self.tmp, "started") @@ -563,14 +770,17 @@ class Shipped(unittest.TestCase): def test_the_hooks_call_scripts_that_exist_and_are_asynchronous(self): hooks = json.loads(self.read("hooks", "hooks.json"))["hooks"] - self.assertEqual(sorted(hooks), ["Stop", "UserPromptSubmit"]) + want = {"UserPromptSubmit": ["command"], "Stop": ["state", "run"], "SessionStart": ["health"], "PostToolUseFailure": ["failure"], "StopFailure": ["failure"]} + self.assertEqual(sorted(hooks), sorted(want)) for event, groups in hooks.items(): + modes = [] for group in groups: for h in group["hooks"]: self.assertTrue(h["asyncRewake"]) script = re.search(r"\$\{CLAUDE_PLUGIN_ROOT\}/(scripts/\w+\.sh)", h["command"]).group(1) self.assertTrue(os.path.isfile(os.path.join(PLUGIN, script)), script) - self.assertTrue(h["command"].rstrip().endswith("command" if event == "UserPromptSubmit" else "state")) + modes.append(h["command"].split()[-1]) + self.assertEqual(modes, want[event], event) def test_the_manifest_has_a_version_and_the_option_that_turns_counts_off(self): manifest = json.loads(self.read(".claude-plugin", "plugin.json")) |
