File size: 7,563 Bytes
ba70497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
"""One command: run the control tower on the 15 given events, grade them, then open the dashboard.

    python start.py                # everything, then http://127.0.0.1:8080 opens in the browser
    python start.py --rules        # skip the LLM reader even if Ollama is running (fast, ~5 seconds)
    python start.py --serve-only   # just open the dashboard on the results already on disk
    python start.py --no-browser   # don't open a browser tab
    python start.py --port 9000
    cd desktop && npm start        # the same dashboard in an Electron window

Works from any directory. Steps, in order:

    1. Check for Ollama and the reader model (TOWER_LLM_MODEL, default qwen3:1.7b). If it is not
       running or the model is not pulled, every step uses the rule reader instead, so the reports
       never show rule-reader results under an LLM name.
    2. python -m tower.run --notify dry-run --overwrite  -> runs/run1/  (Overview, Event feed)
    3. python tests/run_given.py                -> runs/given/       (Test reports, given suite)
       python tests/test_failures.py            (failed calls, missing information, model down)
    4. python tests/run_model.py                -> runs/model/       (run by hand: the model alone, no rule reader)
    5. python -m tower.ontology                 -> runs/ontology/    (Knowledge graph tables)
    6. Serve tower/ui/dashboard.html and open it.

A failed step is reported and the rest still run, so the dashboard always opens.
"""

from __future__ import annotations

import argparse
import json
import os
import subprocess
import sys
import threading
import time
import urllib.request
import webbrowser

HITACHI = os.path.dirname(os.path.abspath(__file__))
if HITACHI not in sys.path:
    sys.path.insert(0, HITACHI)

MODEL = os.environ.get("TOWER_LLM_MODEL", "qwen3:1.7b")
OLLAMA_URL = os.environ.get("OLLAMA_URL", "http://localhost:11434").rstrip("/")


def ollama_has_model() -> tuple[bool, str]:
    """(usable, reason). Usable means Ollama answers and MODEL is pulled."""
    try:
        with urllib.request.urlopen(f"{OLLAMA_URL}/api/tags", timeout=2) as response:
            names = {m.get("name") for m in json.load(response).get("models", [])}
    except Exception:  # noqa: BLE001 - any failure means "not available"
        return False, f"Ollama is not running at {OLLAMA_URL} (start it with: ollama serve)"
    if MODEL not in names and f"{MODEL}:latest" not in names:
        return False, f"model {MODEL} is not pulled (run: ollama pull {MODEL})"
    return True, f"Ollama is running with {MODEL}"


class _Tee:
    """Write to the terminal and to the run's log file (runs/logs/), which the dashboard's Logs page shows."""

    def __init__(self, *streams):
        self.streams = streams

    def write(self, text):
        for stream in self.streams:
            stream.write(text)
            stream.flush()
        return len(text)

    def flush(self):
        for stream in self.streams:
            stream.flush()


def step(label: str, args: list[str]) -> bool:
    """Run one step from the Hitachi folder, streaming its output. True if it exited 0."""
    print(f"\n▶ {label}\n  $ {' '.join(['python', *args])}", flush=True)
    started = time.time()
    proc = subprocess.Popen([sys.executable, "-u", *args], cwd=HITACHI, stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT, text=True, bufsize=1)
    for line in proc.stdout:  # pass each line through, so it lands in the log file too
        print(line, end="")
    code = proc.wait()
    took = time.time() - started
    print(f"  {'✓ done' if code == 0 else f'✗ failed (exit {code})'} in {took:.1f}s", flush=True)
    return code == 0


def bind_server(server, start: int):
    """A TowerServer on the first port from start upward that binds."""
    for port in range(start, start + 20):
        try:
            return server.TowerServer(("127.0.0.1", port), server.Handler), port
        except OSError:
            continue
    raise SystemExit(f"No free port between {start} and {start + 19}.")


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("--rules", action="store_true", help="use the rule reader only, even if Ollama is running")
    ap.add_argument("--serve-only", action="store_true", help="skip the runs and open the dashboard")
    ap.add_argument("--no-browser", action="store_true", help="don't open a browser tab")
    ap.add_argument("--port", type=int, default=8080, help="dashboard port (default 8080, or the next free one)")
    cli = ap.parse_args()
    sys.stdout.reconfigure(line_buffering=True)  # progress shows even when piped to a file
    if not cli.serve_only:
        logs = os.path.join(HITACHI, "runs", "logs")
        os.makedirs(logs, exist_ok=True)
        log_path = os.path.join(logs, time.strftime("start_%Y-%m-%d_%H-%M-%S.log"))
        sys.stdout = _Tee(sys.__stdout__, open(log_path, "w", encoding="utf-8"))
        print(f"python start.py {' '.join(sys.argv[1:])}   (log: runs/logs/{os.path.basename(log_path)})")

    failed = []
    if not cli.serve_only:
        if cli.rules:
            use_llm, why = False, "--rules given"
        else:
            use_llm, why = ollama_has_model()
        print(f"Reader: {'LLM ' + MODEL + ' + rule check' if use_llm else 'rules only'} ({why})")
        tower_reader = "llm" if use_llm else "rules"
        test_reader = "both" if use_llm else "rules"
        if use_llm:
            print("The LLM steps take a few minutes. Use --rules for a run in seconds.")

        steps = [
            ("Control tower on the 15 events", ["-m", "tower.run", "--reader", tower_reader, "--notify", "dry-run",
                                                "--overwrite"]),
            # The model's run above is graded from its saved log (replayed on a fresh world), so the
            # 15 events are not read by the model a second time.
            ("Given tests (docx TC1–TC6)", ["tests/run_given.py", "--reader", test_reader,
                                            *(["--from-run", "runs/run1"] if use_llm else [])]),
            ("Failure tests (failed calls, no information, model down)", ["tests/test_failures.py"]),
            ("Ontology export", ["-m", "tower.ontology"]),
        ]
        for label, args in steps:
            if not step(label, args):
                failed.append(label)

    if not cli.serve_only:
        try:
            from tower.ui import reports
            print(f"\nSummary -> {reports.write_summary()}")
        except Exception as exc:  # noqa: BLE001  the dashboard still opens
            print(f"\nCould not write runs/TEST_SUMMARY.md: {exc}")

    from tower.ui import server  # imported late: it reads TOWER_RUN_DIR at import time

    httpd, port = bind_server(server, cli.port)
    url = f"http://127.0.0.1:{port}"
    print("\n" + "─" * 60)
    if failed:
        print("Failed steps (the dashboard shows the last good results for these):")
        for label in failed:
            print(f"  ✗ {label}")
    print(f"Dashboard: {url}    (Ctrl-C to stop)")
    if not cli.no_browser:
        threading.Timer(0.5, webbrowser.open, args=(url,)).start()
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("\nStopped.")
    finally:
        try:
            from tower.ui import runner

            runner.stop()
        except Exception:  # noqa: BLE001 - shutting down anyway
            pass
        httpd.server_close()


if __name__ == "__main__":
    main()