|
| 1 | +"""Source template for the CLI recording shims that ``SandboxConfig.record_cli`` generates. |
| 2 | +
|
| 3 | +The rendered script runs INSIDE the sandbox, where ``coder_eval`` is not |
| 4 | +installed, so it imports nothing from this package: its configuration arrives as |
| 5 | +embedded literals and everything else comes from the standard library. |
| 6 | +
|
| 7 | +Keeping the template here rather than inline in :mod:`coder_eval.sandbox` lets |
| 8 | +:func:`render_recorder` be exercised directly (render, execute, read the log) |
| 9 | +without standing up a sandbox. |
| 10 | +""" |
| 11 | + |
| 12 | +import json |
| 13 | + |
| 14 | +from coder_eval.models import RecordedCli |
| 15 | + |
| 16 | + |
| 17 | +# Written beside the shims, inside the generated recorder directory, so the log |
| 18 | +# travels with them if the sandbox root moves. |
| 19 | +LOG_FILENAME = "calls.jsonl" |
| 20 | + |
| 21 | +_TEMPLATE = '''\ |
| 22 | +#!/usr/bin/env python3 |
| 23 | +"""Recording shim for `{tool}` - generated by coder_eval SandboxConfig.record_cli. |
| 24 | +
|
| 25 | +Appends one JSON record per invocation to {log_filename} beside this script, in |
| 26 | +the format the `cli_called` success criterion reads. Do not edit: regenerated on |
| 27 | +every sandbox setup. |
| 28 | +""" |
| 29 | +
|
| 30 | +import json |
| 31 | +import os |
| 32 | +import sys |
| 33 | +import time |
| 34 | +
|
| 35 | +TOOL = {tool!r} |
| 36 | +EXIT_CODE = {exit_code!r} |
| 37 | +STDOUT_TEXT = {stdout!r} |
| 38 | +STDERR_TEXT = {stderr!r} |
| 39 | +
|
| 40 | +SHIM_DIR = os.path.dirname(os.path.abspath(__file__)) |
| 41 | +LOG_PATH = os.path.join(SHIM_DIR, {log_filename!r}) |
| 42 | +
|
| 43 | +
|
| 44 | +def record(argv, exit_code): |
| 45 | + """Append this invocation to the log. |
| 46 | +
|
| 47 | + Best-effort: a logging failure must never break the command the agent ran, |
| 48 | + which would turn an evidence problem into a behaviour problem. |
| 49 | +
|
| 50 | + argv is stored as a LIST. A space-joined string cannot distinguish |
| 51 | + `--flag "two words"` from two arguments, which is the whole reason this log |
| 52 | + exists instead of a flattened command line. stdin is deliberately never |
| 53 | + read: it would block whenever the sandbox leaves it on an open pipe, and in |
| 54 | + passthrough mode it would consume the payload the real tool needs. |
| 55 | + """ |
| 56 | + entry = {{ |
| 57 | + "ts": round(time.time(), 3), |
| 58 | + "tool": TOOL, |
| 59 | + "argv": list(argv), |
| 60 | + "exit": exit_code, |
| 61 | + }} |
| 62 | + try: |
| 63 | + # ensure_ascii escapes non-ASCII and any stray surrogate from |
| 64 | + # undecodable argv bytes, so an exotic argument cannot make this write |
| 65 | + # raise and silently drop the record. |
| 66 | + with open(LOG_PATH, "a", encoding="utf-8", newline="\\n") as handle: |
| 67 | + handle.write(json.dumps(entry) + "\\n") |
| 68 | + except OSError: |
| 69 | + pass |
| 70 | +
|
| 71 | +
|
| 72 | +def main(argv): |
| 73 | + """Record the invocation, then fail like the tool would with nothing behind it. |
| 74 | +
|
| 75 | + Nothing is executed: no network, no auth, no side effects. A test that needs |
| 76 | + the real tool's behavior recorded instead should supply its own wrapper under |
| 77 | + mock_path_dirs -- proxying a live executable is a different job from stubbing |
| 78 | + one, and this shim deliberately does only the second. |
| 79 | + """ |
| 80 | + record(argv[1:], EXIT_CODE) |
| 81 | + if STDOUT_TEXT: |
| 82 | + sys.stdout.write(STDOUT_TEXT) |
| 83 | + if STDERR_TEXT: |
| 84 | + sys.stderr.write(STDERR_TEXT) |
| 85 | + return EXIT_CODE |
| 86 | +
|
| 87 | +
|
| 88 | +if __name__ == "__main__": |
| 89 | + sys.exit(main(sys.argv)) |
| 90 | +''' |
| 91 | + |
| 92 | + |
| 93 | +def render_recorder(spec: RecordedCli) -> str: |
| 94 | + """Render the shim source for one ``record_cli`` entry.""" |
| 95 | + return _TEMPLATE.format( |
| 96 | + tool=spec.tool, |
| 97 | + exit_code=spec.exit_code, |
| 98 | + stdout=spec.stdout, |
| 99 | + stderr=spec.stderr, |
| 100 | + log_filename=LOG_FILENAME, |
| 101 | + ) |
| 102 | + |
| 103 | + |
| 104 | +def parse_log(text: str) -> list[dict[str, object]]: |
| 105 | + """Parse recorder-log text into records, skipping unparseable lines. |
| 106 | +
|
| 107 | + Shared with tests and any caller that wants the log without duplicating the |
| 108 | + JSON-Lines handling in :mod:`coder_eval.criteria.cli_called`. |
| 109 | + """ |
| 110 | + records: list[dict[str, object]] = [] |
| 111 | + for line in text.splitlines(): |
| 112 | + stripped = line.strip() |
| 113 | + if not stripped: |
| 114 | + continue |
| 115 | + try: |
| 116 | + parsed = json.loads(stripped) |
| 117 | + except ValueError: |
| 118 | + continue |
| 119 | + if isinstance(parsed, dict): |
| 120 | + records.append(parsed) |
| 121 | + return records |
0 commit comments