File size: 1,856 Bytes
7124acf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"""Keep a paid run's console output next to its result file (added 2026-09-23).

The result JSONs hold scores; the console holds the WHY — every rejected planner
attempt with its validator error, retrieval distances, per-turn steps. Before this, that
text lived only in whatever terminal or temp file launched the run, and was lost with it.

`start_run_log` tees stdout + stderr into `<results>/logs/<name>_<stamp>.log` for the
rest of the process. Call it first in `main`, before anything logs: structlog's default
logger binds the stream on first use. ANSI colour codes are stripped from the file.
"""

from __future__ import annotations

import re
import sys
from datetime import datetime
from pathlib import Path
from typing import TextIO

_ANSI = re.compile(r"\x1b\[[0-9;]*m")


class _Tee:
    def __init__(self, console: TextIO, file: TextIO) -> None:
        self._console, self._file = console, file

    def write(self, s: str) -> int:
        self._console.write(s)
        self._file.write(_ANSI.sub("", s))
        return len(s)

    def flush(self) -> None:
        self._console.flush()
        self._file.flush()

    def isatty(self) -> bool:
        return self._console.isatty()

    def __getattr__(self, name: str):  # encoding, fileno, … — whatever callers ask for
        return getattr(self._console, name)


def run_stamp() -> str:
    return datetime.now().strftime("%Y-%m-%d_%H%M%S")


def start_run_log(results_dir: Path, name: str, stamp: str) -> Path:
    """Tee this process's stdout/stderr into `results_dir/logs/{name}_{stamp}.log`."""
    logs = results_dir / "logs"
    logs.mkdir(parents=True, exist_ok=True)
    path = logs / f"{name}_{stamp}.log"
    fh = path.open("w", encoding="utf-8")
    sys.stdout = _Tee(sys.stdout, fh)
    sys.stderr = _Tee(sys.stderr, fh)
    print(f"[run log] {path}")
    return path