okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge main dbb2d168c (picture-reader fix, GGML_NO_BACKTRACE) into f-own-int2503b206b

main
129.5 KiB2282 linesraw
1"""Shared terminal command grammar and stable exit codes."""
2
3from __future__ import annotations
4
5import argparse
6import contextlib
7import io
8import json
9import math
10import os
11import re
12import subprocess
13import sys
14import time
15from pathlib import Path
16
17from strata_control import profiles
18
19ROOT = Path(__file__).resolve().parents[1]
20
21#: Backend families, as the engine package manifest records them. Kept here so the argument parsers
22#: stay declarative without importing the tuning module on every CLI start.
23BACKENDS = ("metal", "cuda", "hip", "sycl", "cpu")
24from strata_control.doctor import inspect as inspect_components
25from strata_control.profiles import ProfileError
26from strata_cli.client import ClientError, Endpoint
27from strata_cli import monitor_commands, tune_commands
28
29
30class _VersionAction(argparse.Action):
31    """--version on one line: argparse's own version action wraps the text at the terminal width, and a path to the
32    interpreter is the thing a user (and the packaging smoke test) wants to read back whole."""
33
34    def __call__(self, parser, namespace, values, option_string=None):
35        import strata_cli
36        sys.stdout.write(f"strata {strata_cli.PRODUCT_VERSION} (build {strata_cli.version()}; python {sys.version.split()[0]} at {sys.executable})\n")
37        parser.exit()
38
39
40def parser() -> argparse.ArgumentParser:
41    ap = argparse.ArgumentParser(prog="strata", description="Strata serving and terminal clients")
42    ap.add_argument("--version", action=_VersionAction, nargs=0,
43                    help="print the version and the interpreter this terminal runs on")
44    sp = ap.add_subparsers(dest="command", required=True)
45    serve = sp.add_parser("serve", help="start the existing Strata inference server in the foreground")
46    serve.add_argument("--profile", "--config", dest="config", required=True, metavar="CONFIG.json")
47    serve.add_argument("--engine", choices=("strata", "mock"), default="strata",
48                       help="strata: the engine in the run config (default); mock: a scripted engine for client tests, "
49                            "no GPU and no model")
50    serve.add_argument("--host")
51    serve.add_argument("--port", type=int)
52    serve.add_argument("--parallel", type=int, help="requested concurrent engine slots")
53    serve.add_argument("--batch-groups", help="requested pipeline groups (auto or positive integer)")
54    serve.add_argument("--max-queue", type=int, help="maximum pending inference calls beyond effective slots")
55    serve.add_argument("--queue-timeout", type=float, help="seconds to wait for the first engine turn (0.1..600)")
56    serve.add_argument("--batch-telemetry", action=argparse.BooleanOptionalAction, default=None,
57                       help="sample actual engine decode-window rows for the monitor (opt-in)")
58    serve.add_argument("--offline", action="store_true", help="disable remote image fetches and MCP/tool subprocesses")
59    serve.add_argument("--ready-file", help="absolute path for a new instance record (use a private directory)")
60    serve.add_argument("--shutdown-timeout", type=float, default=30,
61                       help="seconds to drain owned inference calls on stop (0..300)")
62    serve.add_argument("--plan", action="store_true", help="validate and print the effective launch without starting")
63    serve.add_argument("--output", choices=("human", "json", "jsonl"), default="human",
64                       help="human output, JSON plan, or JSONL foreground lifecycle")
65    serve.add_argument("--json", action="store_true", help="alias for --plan --output json")
66    serve.add_argument("--quiet", action="store_true", help="suppress human informational output")
67
68    profile = sp.add_parser("profile", help="edit saved serving overrides outside setup's run config")
69    profile_sp = profile.add_subparsers(dest="profile_command", required=True)
70    profile_create = profile_sp.add_parser("create", help="save a named profile from an installed run config")
71    profile_create.add_argument("name")
72    profile_create.add_argument("--from-config", required=True, metavar="CONFIG.json")
73    profile_create.add_argument("--output", choices=("human", "json"), default="human")
74    profile_list = profile_sp.add_parser("list", help="list saved profiles")
75    profile_list.add_argument("--output", choices=("human", "json"), default="human")
76    profile_show = profile_sp.add_parser("show", help="show a profile and optional effective settings")
77    profile_show.add_argument("name")
78    profile_show.add_argument("--effective", action="store_true")
79    profile_show.add_argument("--output", choices=("human", "json"), default="human")
80    profile_validate = profile_sp.add_parser("validate", help="check the profile and referenced run config")
81    profile_validate.add_argument("name")
82    profile_validate.add_argument("--output", choices=("human", "json"), default="human")
83    profile_set = profile_sp.add_parser("set", help="set typed serving overrides, e.g. parallel=8")
84    profile_set.add_argument("name")
85    profile_set.add_argument("assignments", nargs="+")
86    profile_set.add_argument("--plan", action="store_true", help="show changes without saving")
87    profile_set.add_argument("--output", choices=("human", "json"), default="human")
88    profile_source = profile_sp.add_parser("use-config", help="point a saved profile at another run config file")
89    profile_source.add_argument("name")
90    profile_source.add_argument("--from-config", required=True, metavar="CONFIG.json")
91    profile_source.add_argument("--plan", action="store_true", help="show the source change without saving")
92    profile_source.add_argument("--if-revision", metavar="REVISION",
93                                help="fail if the saved profile changed since preview")
94    profile_source.add_argument("--output", choices=("human", "json"), default="human")
95    profile_edit = profile_sp.add_parser("edit", help="edit a temporary JSON copy in VISUAL or EDITOR")
96    profile_edit.add_argument("name")
97    profile_edit.add_argument("--output", choices=("human", "json"), default="human")
98    profile_history = profile_sp.add_parser("history", help="list saved profile revisions")
99    profile_history.add_argument("name")
100    profile_history.add_argument("--output", choices=("human", "json"), default="human")
101    profile_rollback = profile_sp.add_parser("rollback", help="restore a saved profile revision")
102    profile_rollback.add_argument("name")
103    profile_rollback.add_argument("--to", required=True, metavar="REVISION")
104    profile_rollback.add_argument("--output", choices=("human", "json"), default="human")
105
106    repair = sp.add_parser("repair-access", help="give you back Strata files that a run as administrator locked (Windows)")
107    repair.add_argument("--output", choices=("human", "json"), default="human")
108    doctor = sp.add_parser("doctor", help="read-only check of installed engine components")
109    doctor.add_argument("--profile", help="saved profile name or run config JSON path")
110    doctor.add_argument("--components", action="store_true", help="include component inventory (default)")
111    doctor.add_argument("--live", action="store_true", help="query host GPUs and compare selected device indices")
112    doctor.add_argument("--output", choices=("human", "json"), default="human")
113    components = sp.add_parser("components", help="read-only installed component inventory")
114    components_sp = components.add_subparsers(dest="components_command", required=True)
115    components_verify = components_sp.add_parser("verify", help="check required files for an installed profile")
116    components_verify.add_argument("--profile", required=True)
117    components_verify.add_argument("--live", action="store_true", help="query host GPUs and compare selected device indices")
118    components_verify.add_argument("--output", choices=("human", "json"), default="human")
119    components_plan = components_sp.add_parser(
120        "plan", help="read a component-package manifest and say whether it may be used here")
121    components_plan.add_argument("manifest", help="path to the component manifest (JSON)")
122    components_plan.add_argument("--backend", default=None,
123                                 help="the backend family to check the component against")
124    components_plan.add_argument("--target", default=None,
125                                 help="override the platform key, for checking another machine's "
126                                      "manifest on this one")
127    components_plan.add_argument("--output", choices=("human", "json"), default="human")
128    components_backend = components_sp.add_parser(
129        "backends", help="the OS and backend combinations that are committed to, and what is not")
130    components_backend.add_argument("--output", choices=("human", "json"), default="human")
131    components_engine = components_sp.add_parser(
132        "engine", help="which engine package in the local component folder this PC would start (never downloads)")
133    components_engine.add_argument("--backend", default=None, help="ask for one backend family instead of detecting it")
134    components_engine.add_argument("--components-dir", default=None,
135                                   help="the component folder (default: STRATA_COMPONENTS_DIR or the per-user folder)")
136    components_engine.add_argument("--full", action="store_true", help="hash every file, not only the entrypoint")
137    components_engine.add_argument("--output", choices=("human", "json"), default="human")
138    from strata_cli import update_cmd
139    update_parsers = update_cmd.add_parsers(sp, components_sp)
140    models = sp.add_parser("models", help="inspect setup-written local model run configs")
141    models_sp = models.add_subparsers(dest="models_command", required=True)
142    models_list = models_sp.add_parser("list", help="list local installed-model config candidates")
143    models_scope = models_list.add_mutually_exclusive_group()
144    models_scope.add_argument("--installed", action="store_true", help="limit discovery to local setup run configs")
145    models_scope.add_argument("--served", action="store_true", help="inspect the currently served model")
146    models_list.add_argument("--install-dir", help="absolute path to a Strata installation")
147    models_list.add_argument("--url", help="Strata server root; remote connections require HTTPS")
148    models_list.add_argument("--connection", help="saved read-only connection")
149    models_list.add_argument("--credential-env", help="environment variable containing the server credential")
150    models_list.add_argument("--timeout", type=float, help="bounded request timeout in seconds")
151    models_list.add_argument("--output", choices=("human", "json"), default="human")
152    models_inspect = models_sp.add_parser("inspect", help="inspect a local model run config and its components")
153    models_inspect.add_argument("model_id")
154    models_inspect.add_argument("--install-dir", help="absolute path to a Strata installation")
155    models_inspect.add_argument("--output", choices=("human", "json"), default="human")
156    models_import = models_sp.add_parser("import", help="preview an existing GGUF file set without adopting it")
157    models_import.add_argument("path", metavar="PATH")
158    models_import.add_argument("--plan", action="store_true", required=True,
159                               help="inspect only; adoption requires a qualified model workflow")
160    models_import.add_argument("--output", choices=("human", "json"), default="human")
161    models_move = models_sp.add_parser("move", help="move the model files (models, packs, mtp) to another folder: copied, checked, then the old copies removed")
162    models_move.add_argument("to", metavar="NEW_FOLDER", nargs="?", help="not needed with --resume, --leave or --status")
163    models_move.add_argument("--resume", action="store_true", help="finish a move that was interrupted")
164    models_move.add_argument("--leave", action="store_true", help="give up an interrupted move: keep the old folder and remove the partial copies")
165    models_move.add_argument("--status", action="store_true", help="say whether a move was interrupted (changes nothing)")
166    models_move.add_argument("--from", dest="source", metavar="OLD_FOLDER", help="the folder the models are in now (default: the data folder in use)")
167    models_move.add_argument("--install-dir", help="absolute path to a Strata installation whose run configs should follow the files")
168    models_move.add_argument("--plan", action="store_true", help="say what would happen and change nothing")
169    models_move.add_argument("--cancel-file", metavar="PATH", help="stop (safely) when this file appears")
170    models_move.add_argument("--output", choices=("human", "json", "jsonl"), default="human")
171    from strata_cli import drafting_cmd
172    drafting_cmd.add_parser(sp)
173    from strata_cli import split_cmd
174    split_cmd.add_parser(sp)
175    engine = sp.add_parser("engine", help="engine tuning and component actions")
176    engine_sp = engine.add_subparsers(dest="engine_command", required=True)
177    calibrate = engine_sp.add_parser("calibrate", help="measure, review and apply engine tuning")
178    calibrate.add_argument("--profile", required=True)
179    calibrate_actions = calibrate.add_mutually_exclusive_group(required=True)
180    calibrate_actions.add_argument("--plan", action="store_true", help="read-only calibration preflight")
181    calibrate_actions.add_argument("--measure", action="store_true", help="run decode sweep and save a report")
182    calibrate_actions.add_argument("--review-result", metavar="REPORT.json", help="show a candidate and its freshness")
183    calibrate_actions.add_argument("--apply-result", metavar="REPORT.json", help="smoke-test and apply a fresh report")
184    calibrate_actions.add_argument("--review-rollback", metavar="REPORT.json",
185                                   help="check whether an applied result can be restored")
186    calibrate_actions.add_argument("--rollback-result", metavar="REPORT.json",
187                                   help="smoke-test and restore the configuration before an application")
188    calibrate.add_argument("--out", metavar="REPORT.json", help="new report path for --measure")
189    calibrate.add_argument("--exclusive", action="store_true", help="assert all model instances using these devices are stopped")
190    calibrate.add_argument("--output", choices=("human", "json"), default="human")
191    install = sp.add_parser(
192        "install",
193        help="the explicit installer: engine, models, Python packages (starting and serving never do this)")
194    install.add_argument("--update", action="store_true",
195                         help="update an existing install (what UPDATE.bat / update.sh run) instead of setting one up")
196    install.add_argument("setup_args", nargs=argparse.REMAINDER,
197                         help="options passed to setup.py, e.g. --family qwen --model Q2_0 --yes")
198    runtime = sp.add_parser(
199        "runtime", help="manage an owned local Strata server instance",
200        description="`runtime start` starts a background service: the engine keeps serving after this terminal "
201                    "closes and until `runtime stop` (or the process named by --die-with-pid ends). "
202                    "`strata serve` is the foreground form: it ends with this terminal.")
203    runtime_sp = runtime.add_subparsers(dest="runtime_command", required=True)
204    runtime_start = runtime_sp.add_parser(
205        "start", help="start a saved profile as a background service under the local owner host (it keeps "
206                      "serving after this terminal closes; stop it with `runtime stop`)")
207    runtime_start.add_argument("--profile", required=True)
208    runtime_start.add_argument("--die-with-pid", type=int, metavar="PID",
209                               help="stop the instance (drained) when this process ends; for an app that owns it")
210    runtime_start.add_argument("--plan", action="store_true")
211    runtime_start.add_argument("--wait", type=float, default=300)
212    runtime_start.add_argument("--shutdown-timeout", type=float, default=30)
213    runtime_start.add_argument("--output", choices=("human", "json"), default="human")
214    runtime_status = runtime_sp.add_parser("status", help="inspect an owned local instance")
215    runtime_status.add_argument("--profile", required=True)
216    runtime_status.add_argument("--output", choices=("human", "json"), default="human")
217    runtime_verify = runtime_sp.add_parser("verify", help="recheck the owned API and one-token generation")
218    runtime_verify.add_argument("--profile", required=True)
219    runtime_verify.add_argument("--wait", type=float, default=300)
220    runtime_verify.add_argument("--load", action="store_true", help="load an unloaded model for the generation check")
221    runtime_verify.add_argument("--plan", action="store_true", help="preview the owned instance and verification effect")
222    runtime_verify.add_argument("--if-owner-id", metavar="OWNER_ID",
223                                help="require the owner shown by verify --plan")
224    runtime_verify.add_argument("--if-instance-id", metavar="INSTANCE_ID",
225                                help="require the instance shown by verify --plan")
226    runtime_verify.add_argument("--output", choices=("human", "json"), default="human")
227    runtime_stop = runtime_sp.add_parser("stop", help="drain and stop an owned local instance")
228    runtime_stop.add_argument("--profile", required=True)
229    runtime_stop.add_argument("--plan", action="store_true", help="review the current owner and instance")
230    runtime_stop.add_argument("--wait", type=float, default=330)
231    runtime_stop.add_argument("--if-owner-id", help="require the owner ID from --plan")
232    runtime_stop.add_argument("--if-instance-id", help="require the instance ID from --plan")
233    runtime_stop.add_argument("--output", choices=("human", "json"), default="human")
234    runtime_cleanup = runtime_sp.add_parser(
235        "cleanup", help="end servers and engines Strata started whose owner is gone (each is checked by PID, "
236                        "start time and command line first; a running instance is never touched)")
237    runtime_cleanup.add_argument("--profile", help="only this profile's leftovers")
238    runtime_cleanup.add_argument("--output", choices=("human", "json"), default="human")
239    runtime_restart = runtime_sp.add_parser("restart", help="drain and rerun an owned saved profile")
240    runtime_restart.add_argument("--profile", required=True)
241    runtime_restart.add_argument("--plan", action="store_true", help="compare current and saved launch without draining")
242    runtime_restart.add_argument("--allow-source-switch", action="store_true",
243                                 help="permit a new source config file when the old file remains available for rollback")
244    runtime_restart.add_argument("--allow-source-migration", action="store_true",
245                                 help="permit edited run config bytes using a private rollback snapshot")
246    runtime_restart.add_argument("--wait", type=float, default=1000)
247    runtime_restart.add_argument("--startup-wait", type=float, default=300)
248    runtime_restart.add_argument("--if-profile-revision", metavar="REVISION")
249    runtime_restart.add_argument("--if-owner-id", metavar="OWNER_ID",
250                                 help="require the owner ID shown in --plan")
251    runtime_restart.add_argument("--if-instance-id", metavar="INSTANCE_ID",
252                                 help="require the instance ID shown in --plan")
253    runtime_restart.add_argument("--if-source-sha256", metavar="SHA256",
254                                 help="require the candidate source bytes shown in --plan")
255    runtime_restart.add_argument("--output", choices=("human", "json"), default="human")
256    ops = sp.add_parser("ops", help="edit and run typed local operator recipes")
257    ops_sp = ops.add_subparsers(dest="ops_command", required=True)
258    ops_items = []
259    for action in ("init", "list", "create", "show", "edit", "set", "history", "rollback",
260                   "plan", "run", "runs", "result"):
261        item = ops_sp.add_parser(action)
262        ops_items.append(item)
263        if action == "result":
264            item.add_argument("operation_id")
265        elif action not in ("init", "list", "runs"):
266            item.add_argument("name")
267        item.add_argument("--profile", required=True)
268        item.add_argument("--output", choices=("human", "json"), default="human")
269        if action == "runs":
270            item.add_argument("--limit", type=int, default=20)
271        if action == "create":
272            item.add_argument("--kind", choices=("runtime.restart", "engine.calibrate.measure",
273                                                       "components.verify"), required=True)
274        if action == "set":
275            item.add_argument("assignment", metavar="KEY=VALUE")
276            item.add_argument("--plan", action="store_true")
277        if action == "rollback":
278            item.add_argument("--to", required=True, metavar="REVISION")
279        if action == "run":
280            item.add_argument("--exclusive", action="store_true",
281                              help="assert exclusive device access for a calibration measurement")
282            item.add_argument("--if-revision", metavar="REVISION",
283                              help="fail if the saved recipe changed since preview")
284            item.add_argument("--if-profile-revision", metavar="REVISION",
285                              help="fail if the saved serving profile changed since preview")
286            item.add_argument("--if-owner-id", metavar="OWNER_ID",
287                              help="require the runtime owner shown in a restart recipe plan")
288            item.add_argument("--if-instance-id", metavar="INSTANCE_ID",
289                              help="require the runtime instance shown in a restart recipe plan")
290            item.add_argument("--if-source-sha256", metavar="SHA256",
291                              help="require the candidate run-config bytes shown in a restart recipe plan")
292    bench = sp.add_parser("bench", help="explicit serving benchmark with local JSON evidence")
293    bench_sp = bench.add_subparsers(dest="bench_command", required=True)
294    bench_run = bench_sp.add_parser("run", help="the standard benchmark (docs/BENCHMARK_PROTOCOL.md), or a serving suite")
295    bench_source = bench_run.add_mutually_exclusive_group(required=True)
296    bench_source.add_argument("--profile", help="saved serving profile or installed run config")
297    bench_source.add_argument("--url", help="server root; remote connections require HTTPS")
298    bench_run.add_argument("--suite", choices=("standard-v1", "serving-smoke", "parallel-mixed-v1", "parallel-overload-v1",
299                                               "parallel-cancel-v1", "parallel-prefill-cancel-v1"),
300                           default="standard-v1",
301                           help="standard-v1 (default) follows docs/BENCHMARK_PROTOCOL.md; the others are serving suites for your own comparisons")
302    bench_run.add_argument("--concurrency", type=int, default=None,
303                           help="serving suites: simultaneous requests (1..16, or 1..64 for parallel-overload-v1; default 4)")
304    bench_run.add_argument("--repeat", type=int, default=None, help="serving suites: repeat measured phases (1..5; default 1)")
305    bench_run.add_argument("--condition", help="serving suites: operator label for this run, e.g. baseline or monitor-default")
306    bench_run.add_argument("--require-managed-match", action="store_true",
307                           help="serving suites: require the local owner host and current profile to match the serving instance")
308    bench_run.add_argument("--request-timeout", type=float, default=None,
309                           help="serving suites: seconds per request (1..600; default 120). The standard suite fixes it at 1800")
310    bench_run.add_argument("--out", metavar="NEW_DIRECTORY",
311                           help="new output directory (required for serving suites). Standard suite: a new folder "
312                                "<date>-standard-<gpu>-<run id> under ./bench/results or ./bench-results")
313    bench_run.add_argument("--credential-env", default="STRATA_API_KEY")
314    bench_run.add_argument("--telemetry-credential-env", default=None)
315    bench_run.add_argument("--output", choices=("human", "json"), default="human")
316    standard = bench_run.add_argument_group("standard suite (docs/BENCHMARK_PROTOCOL.md)")
317    standard.add_argument("--optional-concurrency", action="store_true",
318                          help="also run the optional stage: four short requests released together, three rounds")
319    standard.add_argument("--no-start", action="store_true",
320                          help="with --profile: never start the engine; use only a server that is already running")
321    standard.add_argument("--load-timeout", type=float, default=1800, metavar="SECONDS",
322                          help="with --profile: how long to wait for the engine to load the model (default 1800)")
323    standard.add_argument("--track", choices=("default", "custom"), default="custom",
324                          help="default: an unmodified release's setup-generated settings; custom (the default here): anything else")
325    standard.add_argument("--track-notes", default=None, metavar="TEXT",
326                          help="the release and setup choices (default track) or the changes made (custom track)")
327    standard.add_argument("--model-revision", metavar="REV", help="immutable revision of the quantization repository")
328    standard.add_argument("--source-revision", metavar="REV", help="revision of the original Qwen/Qwen3.8-Flash-Next weights")
329    standard.add_argument("--tokenizer-revision", metavar="REV")
330    standard.add_argument("--quantization", metavar="NAME", help="when it cannot be read from the model file names")
331    standard.add_argument("--custom-pack", metavar="TEXT", help="describe a prepared pack or custom expert profile")
332    standard.add_argument("--background", action="append", metavar="TEXT", help="a program that ran during the benchmark (repeatable)")
333    standard.add_argument("--build-options", metavar="LIST", help="comma-separated build options of a source build")
334    standard.add_argument("--skip-model-hash", action="store_true",
335                          help="do not hash the model files (the run is then marked nonconforming)")
336    bench_cancel = bench_sp.add_parser("cancel", help="stop the exact active saved-profile benchmark")
337    bench_cancel.add_argument("--profile", required=True, help="saved serving profile")
338    bench_cancel.add_argument("--path", required=True, help="absolute run directory or results.json")
339    bench_cancel.add_argument("--output", choices=("human", "json"), default="human")
340    bench_report = bench_sp.add_parser("report", help="summarize an existing benchmark report")
341    bench_report.add_argument("path")
342    bench_report.add_argument("--output", choices=("human", "json", "markdown"), default="human")
343    bench_report.add_argument("--out", metavar="NEW_FILE", help="write Markdown to a new file")
344    bench_compare = bench_sp.add_parser("compare", help="compare two saved runs with workload checks")
345    bench_compare.add_argument("baseline")
346    bench_compare.add_argument("candidate")
347    bench_compare.add_argument("--output", choices=("human", "json", "markdown"), default="human")
348    bench_compare.add_argument("--out", metavar="NEW_FILE", help="write Markdown to a new file")
349    timeskip = sp.add_parser(
350        "timeskip", help="retain a good result, try a bounded improvement, check it and decide")
351    timeskip_sp = timeskip.add_subparsers(dest="timeskip_command", required=True)
352
353    ts_run = timeskip_sp.add_parser("run", help="checkpoint, attempt a revision, check it and decide")
354    ts_run.add_argument("--workspace", required=True,
355                        help="the directory holding the work (and, optionally, .strata/checks.json)")
356    ts_run.add_argument("--prompt", required=True, help="what the revision should achieve")
357    ts_run.add_argument("--attempts", type=int, default=2,
358                        help="bounded revision attempts (0 = checkpoint and check the baseline only); "
359                             "the specification's default is two")
360    ts_run.add_argument("--revise-command", default=None,
361                        help="the command that performs ONE revision attempt. It runs with the "
362                             "candidate directory as its working directory, receives the prompt in "
363                             "STRATA_TIMESKIP_PROMPT and the attempt number in "
364                             "STRATA_TIMESKIP_ATTEMPT, and must not touch the workspace. Without it "
365                             "no revision is attempted, which yields an inconclusive run rather than "
366                             "a fabricated improvement.")
367    ts_run.add_argument("--state-dir", default=None,
368                        help="where runs are recorded (default: $STRATA_TIMESKIP_DIR or "
369                             "$XDG_STATE_HOME/strata/time-skip, %%LOCALAPPDATA%%\\Strata\\time-skip on Windows)")
370    ts_run.add_argument("--output", choices=("human", "json"), default="human")
371
372    ts_status = timeskip_sp.add_parser("status", help="read a run's durable state and evidence")
373    ts_status.add_argument("run_id")
374    ts_status.add_argument("--state-dir", default=None)
375    ts_status.add_argument("--output", choices=("human", "json"), default="human")
376
377    ts_list = timeskip_sp.add_parser("list", help="list recorded runs")
378    ts_list.add_argument("--state-dir", default=None)
379    ts_list.add_argument("--output", choices=("human", "json"), default="human")
380
381    ts_apply = timeskip_sp.add_parser(
382        "apply", help="apply the retained result, refusing if the destination changed")
383    ts_apply.add_argument("run_id")
384    ts_apply.add_argument("--workspace", default=None,
385                          help="destination (default: the workspace the run recorded)")
386    ts_apply.add_argument("--attempt", type=int, default=None,
387                          help="apply this revision attempt (chosen by the person after review) "
388                               "instead of the retained checkpoint")
389    ts_apply.add_argument("--dry-run", action="store_true",
390                          help="report what would change without writing anything")
391    ts_apply.add_argument("--restore", action="store_true",
392                          help="put the original back instead of applying the result")
393    ts_apply.add_argument("--state-dir", default=None)
394    ts_apply.add_argument("--output", choices=("human", "json"), default="human")
395
396    tune = sp.add_parser("tune", help="bounded engine-configuration search with retained evidence")
397    tune_sp = tune.add_subparsers(dest="tune_command", required=True)
398
399    tune_plan = tune_sp.add_parser("plan", help="show exactly what a sweep would search, and why not")
400    tune_plan.add_argument("--engine", required=True, help="the engine binary to interrogate and measure")
401    tune_plan.add_argument("--backend", required=True, choices=list(BACKENDS),
402                          help="the backend family the engine package claims")
403    tune_plan.add_argument("--model", required=True, help="the model identifier the measurements belong to")
404    tune_plan.add_argument("--objective", choices=("generation", "prefill", "latency"),
405                           default="generation")
406    tune_plan.add_argument("--trials", type=int, default=16, help="the bounded short sweep (default 16)")
407    tune_plan.add_argument("--time", dest="total_time", type=float, default=1800.0,
408                           help="displayed total-time bound in seconds")
409    tune_plan.add_argument("--repeats", type=int, default=3,
410                           help="paired repeats per candidate (default 3, the specification's floor)")
411    tune_plan.add_argument("--hold", action="append", default=[],
412                           help="hold a dimension constant instead of searching it (repeatable)")
413    tune_plan.add_argument("--output", choices=("human", "json"), default="human")
414
415    tune_run = tune_sp.add_parser(
416        "run", help="run a bounded sweep: measure the baseline and candidates, then report")
417    tune_run.add_argument("--engine", required=True, help="the engine binary to measure")
418    tune_run.add_argument("--backend", required=True, choices=list(BACKENDS))
419    tune_run.add_argument("--model", required=True, help="the model the measurements belong to")
420    tune_run.add_argument("--objective", choices=("generation", "prefill", "latency"),
421                          default="generation")
422    tune_run.add_argument("--trials", type=int, default=16,
423                          help="bounded number of candidate configurations (default 16)")
424    tune_run.add_argument("--time", dest="total_time", type=float, default=1800.0,
425                          help="displayed total-time bound in seconds")
426    tune_run.add_argument("--repeats", type=int, default=3,
427                          help="paired repeats per candidate (default 3, the specification's floor)")
428    tune_run.add_argument("--prompt-tokens", type=int, default=512,
429                          help="the workload's prompt length; fixed for the whole sweep")
430    tune_run.add_argument("--max-new", type=int, default=128,
431                          help="the workload's output length; fixed for the whole sweep")
432    tune_run.add_argument("--mode", choices=("protocol", "api"), default="protocol",
433                          help="protocol measures the engine's own serve protocol (cheap, for every "
434                               "candidate); api drives the real HTTP API the agent uses (the "
435                               "confirmation, and the only mode that reflects a user's wait)")
436    tune_run.add_argument("--api-prompt", default="In one short sentence, what is a hash table?",
437                          help="the prompt the api mode sends")
438    tune_run.add_argument("--api-expect", default=None,
439                          help="a regular expression the answer must match for the run to count as "
440                               "correct; without it correctness is not checked")
441    tune_run.add_argument("--api-port", type=int, default=8123)
442    tune_run.add_argument("--config", default=None,
443                          help="the run configuration the api mode starts the worker with")
444    tune_run.add_argument("--boot-timeout", type=float, default=600.0,
445                          help="how long one candidate may take to become ready")
446    tune_run.add_argument("--request-timeout", type=float, default=600.0,
447                          help="how long one measured request may take")
448    tune_run.add_argument("--model-path", default=None,
449                          help="the model's file, so the sweep's identity is a content digest rather "
450                               "than a name. Without it the record is incomparable to everything, "
451                               "which is safer than being falsely comparable.")
452    tune_run.add_argument("--context", type=int, default=None,
453                          help="the context the measurements were taken at")
454    tune_run.add_argument("--full-digests", action="store_true",
455                          help="hash the model and engine completely instead of sampling; slower but "
456                               "the strongest identity")
457    tune_run.add_argument("--hold", action="append", default=[],
458                          help="hold a dimension constant instead of searching it (repeatable)")
459    tune_run.add_argument("--state-dir", default=None)
460    tune_run.add_argument("--output", choices=("human", "json"), default="human")
461
462    tune_apply = tune_sp.add_parser(
463        "apply", help="apply a reviewed recommendation, after verifying the candidate runs")
464    tune_apply.add_argument("job_id", help="the completed sweep whose recommendation to apply")
465    tune_apply.add_argument("--config", default=None,
466                            help="the run configuration to change (strata-<model>.json)")
467    tune_apply.add_argument("--model-path", default=None,
468                            help="the model file, to re-check the identity before writing")
469    tune_apply.add_argument("--context", type=int, default=None)
470    tune_apply.add_argument("--state-dir", default=None)
471    tune_apply.add_argument("--output", choices=("human", "json"), default="human")
472
473    tune_rollback = tune_sp.add_parser("rollback", help="restore the configuration before an apply")
474    tune_rollback.add_argument("application_id")
475    tune_rollback.add_argument("--state-dir", default=None)
476    tune_rollback.add_argument("--output", choices=("human", "json"), default="human")
477
478    tune_status = tune_sp.add_parser("status", help="read a job's durable state and report")
479    tune_status.add_argument("job_id")
480    tune_status.add_argument("--state-dir", default=None)
481    tune_status.add_argument("--output", choices=("human", "json"), default="human")
482
483    tune_list = tune_sp.add_parser("list", help="list recorded jobs")
484    tune_list.add_argument("--state-dir", default=None)
485    tune_list.add_argument("--output", choices=("human", "json"), default="human")
486
487    tune_commands.add_tune_auto(tune_sp)
488    tune_commands.add_presets(sp)
489    from strata_cli.launch import cmd as launch_cmd
490    launch_cmd.add_parsers(sp)
491    monitor_commands.add_status(sp)
492    monitor_commands.add_monitor(sp)
493    monitor_commands.add_logs(sp)
494    monitor_commands.add_connections(sp)
495    code = sp.add_parser("code", help="coding client for the shared Desktop harness")
496    code.add_argument("--workspace")
497    code.add_argument("--resume")
498    code.add_argument("--quiet", action="store_true", help="suppress human informational output")
499    code_sp = code.add_subparsers(dest="code_command")
500    code_run = code_sp.add_parser("run", help="scripted harness turn (requires the shared harness component)")
501    code_run.add_argument("--prompt-file", required=True)
502    code_run.add_argument("--policy", required=True)
503    code_run.add_argument("--output", choices=("jsonl",), default="jsonl")
504    code_run.add_argument("--quiet", action="store_true", default=argparse.SUPPRESS,
505                          help="suppress human informational output")
506    code_sessions = code_sp.add_parser("sessions", help="shared harness sessions")
507    code_sessions.add_argument("action", choices=("list",))
508    code_sessions.add_argument("--output", choices=("human", "json"), default="human")
509    for one_shot in (profile_create, profile_list, profile_show, profile_validate, profile_set,
510                     profile_source, profile_edit, profile_history, profile_rollback, doctor,
511                     components_verify, models_list, models_inspect, models_import, models_move, calibrate,
512                     runtime_start, runtime_status, runtime_verify, runtime_stop, runtime_cleanup, runtime_restart,
513                     *ops_items, bench_run, bench_report, bench_compare, code_sessions, *update_parsers):
514        one_shot.add_argument("--json", action="store_true", help="alias for --output json")
515        one_shot.add_argument("--quiet", action="store_true", default=argparse.SUPPRESS,
516                              help="suppress human informational output")
517    return ap
518
519
520def _file_words(exc: BaseException) -> str:
521    try:
522        from strata_control import longpath
523    except ImportError:
524        return f"local file operation failed ({type(exc).__name__})"
525    return longpath.file_words(exc)
526
527
528def _error(message: str, code: int, machine: bool = False) -> int:
529    if machine:
530        print(json.dumps({"schema_version": 1, "ok": False, "error": {"code": code, "message": message}}))
531    else:
532        print(f"strata: {message}", file=sys.stderr)
533    return code
534
535
536def _success(payload: dict, *, machine: bool, human: str | None = None) -> int:
537    if machine:
538        print(json.dumps({"schema_version": 1, "ok": True, **payload}, ensure_ascii=False, allow_nan=False))
539    elif human is not None:
540        print(human)
541    else:
542        print(json.dumps(payload, indent=2, ensure_ascii=False))
543    return 0
544
545
546def _source(ref: str) -> tuple[Path, dict | None, str | None, dict]:
547    path, saved, revision = profiles.resolve(ref)
548    return path, saved, revision, profiles.read_run_config(path)
549
550
551def _models(a: argparse.Namespace) -> int:
552    from strata_control import models
553    if a.models_command == "import":
554        result = models.plan_import(a.path)
555        if result["issues"]:
556            if a.output == "json":
557                print(json.dumps({"schema_version": 1, "ok": False, "plan": result},
558                                 ensure_ascii=False, allow_nan=False))
559            else:
560                print(_import_problem(result), file=sys.stderr)
561            return 5
562        return _success({"plan": result}, machine=a.output == "json", human=_import_words(result))
563    if a.models_command == "move":
564        return _models_move(a)
565    if a.models_command == "list":
566        if a.served:
567            if a.install_dir:
568                return _error("--install-dir applies only to local installed models", 2, a.output == "json")
569            from strata_cli import connections
570            resolved = connections.resolve(url=a.url, connection=a.connection,
571                                           credential_env=a.credential_env, timeout=a.timeout)
572            endpoint = Endpoint(resolved["url"], _usable_key(os.environ.get(resolved["credential_env"])),
573                                resolved["timeout_s"], resolved["prefix"])
574            snapshot = endpoint.snapshot()
575            model = snapshot["model"]
576            rows = ([{"id": model["id"], "loaded": model["loaded"],
577                      "instance_id": snapshot["instance"]["id"], "execution_compatibility": "unverified"}]
578                    if model["id"] else [])
579            result = {"scope": "served_current_instance", "server": endpoint.base_url,
580                      "models": rows, "model_count": len(rows),
581                      "note": "current instance only; not an installed-model inventory"}
582            return _success(result, machine=a.output == "json",
583                            human="\n".join(f"{row['id']}  " +
584                                            ("loaded" if row["loaded"] is True else
585                                             "unloaded" if row["loaded"] is False else "load state unknown")
586                                            for row in rows) or "No model ID reported by this server")
587        if a.url or a.connection or a.credential_env or a.timeout is not None:
588            return _error("connection options require --served", 2, a.output == "json")
589        result = models.list_installed(a.install_dir)
590        lines = [f"{item['id']}  {item['component_status']}  "
591                 f"{item.get('name', item.get('error', ''))}" for item in result["models"]]
592        if not lines:
593            where = ", ".join(result.get("install_dirs") or [result["install_dir"]])
594            lines = [f"No installed models found. Looked in: {where}. "
595                     "If your models are somewhere else, add --install-dir FOLDER (the folder with the strata-*.json files), "
596                     "or run `strata launch` to set one up."]
597        return _success(result, machine=a.output == "json", human="\n".join(lines))
598    result = models.inspect(a.model_id, a.install_dir)
599    item = result["model"]
600    return _success(result, machine=a.output == "json",
601                    human=f"{item['id']}: {item['component_status']}; engine compatibility unverified\n"
602                    f"Config: {item['source_config']}\n"
603                    f"Components: {len(result['components']['components'])}, "
604                    f"issues: {len(result['components']['issues'])}")
605
606
607def _import_problem(plan: dict) -> str:
608    """Why `models import --plan` refused, in plain words (the codes stay in --output json)."""
609    from strata_control import models as own_models
610    words = own_models.problem_words(plan.get("issues") or [], missing=plan.get("missing_shards"))
611    text = f"These files cannot be used as they are: {words}."
612    holds = next((m for m in plan.get("messages") or [] if "holds" in m), "")
613    if holds:
614        text += " " + holds
615    return text
616
617
618def _models_move(a: argparse.Namespace) -> int:
619    from strata_control import discovery, models, models_move as mm
620    machine = a.output in ("json", "jsonl")
621    old = Path(a.source) if a.source else discovery.data_dir(Path.home() / "Strata")[0]
622    if a.status or a.resume or a.leave:
623        return _models_move_unfinished(a, old)
624    if not a.to:
625        print("strata: name the new folder, or use --resume / --leave / --status for an interrupted move.", file=sys.stderr)
626        return 2
627    new = Path(a.to).expanduser()
628    if a.plan:
629        result = mm.plan(old, new)
630        if machine:
631            print(json.dumps({"schema_version": 1, "ok": result["ok"], "plan": result}, ensure_ascii=False, allow_nan=False))
632        else:
633            print(result["issue"]["message"] if result["issue"] else
634                  f"{len(result['models'])} model(s), {result['models_bytes'] / 1e9:.1f} GB; {result['free_bytes'] / 1e9:.1f} GB free in {new}.")
635        return 0 if result["ok"] else 5
636    try:
637        installs = [models.resolve_install(a.install_dir)[0]] if a.install_dir else [p for p, _s in models.all_installs()]
638    except Exception:
639        installs = []
640    configs = [c for i in installs for c in mm.config_files(i)]
641    cancel = Path(a.cancel_file) if a.cancel_file else None
642
643    def show(event: dict) -> None:
644        if a.output == "jsonl":
645            print(json.dumps(event, ensure_ascii=False, allow_nan=False), flush=True)
646        elif not machine:
647            print(f"\r{event['done'] / 1e9:.1f} of {event['total'] / 1e9:.1f} GB  {event['file']}", end="", flush=True)
648    try:
649        summary = mm.move(old, new, on_progress=show, cancelled=(lambda: cancel.exists()) if cancel else None, configs=configs)
650    except mm.MoveError as e:
651        extra = getattr(e, "summary", {})
652        if machine:
653            print(json.dumps({"schema_version": 1, "ok": False, "error": {"code": e.code, "message": str(e), "details": e.details}, **extra}, ensure_ascii=False))
654        else:
655            print(f"\nstrata: {e} {e.details}".rstrip(), file=sys.stderr)
656        return 5
657    if machine:
658        print(json.dumps({"schema_version": 1, "ok": True, "event": "result", **summary}, ensure_ascii=False))
659    else:
660        print("\n" + ("Your models are moved." if summary["done"] else "Moving stopped. Nothing was lost."))
661    return 0 if summary["done"] else 6
662
663
664def _interrupted_words(st: dict) -> str:
665    return (f"A move of your models was interrupted. They are in {st['from']} and {st['to']}. "
666            "Finish it: strata models move --resume. Leave it (keep the models in the first folder): strata models move --leave.")
667
668
669def _models_move_unfinished(a: argparse.Namespace, old: Path) -> int:
670    """`strata models move --status | --resume | --leave`: the move the last run left unfinished (A move was interrupted. Finish it or leave it)."""
671    from strata_control import models, models_move as mm
672    machine = a.output in ("json", "jsonl")
673    st = mm.interrupted(old)
674    if a.status:
675        if machine:
676            print(json.dumps({"schema_version": 1, "ok": True, "interrupted": st}, ensure_ascii=False, allow_nan=False))
677        else:
678            print(_interrupted_words(st) if st else "No move was interrupted.")
679        return 0
680    if not st:
681        if machine:
682            print(json.dumps({"schema_version": 1, "ok": False, "error": {"code": "nothing", "message": "No move was interrupted.", "details": ""}}))
683        else:
684            print("strata: no move was interrupted.", file=sys.stderr)
685        return 5
686    try:
687        installs = [models.resolve_install(a.install_dir)[0]] if a.install_dir else [p for p, _s in models.all_installs()]
688    except Exception:
689        installs = []
690    configs = [c for i in installs for c in mm.config_files(i)]
691    if a.leave:
692        try:
693            result = mm.leave(Path(st["from"]), Path(st["to"]), configs=configs)
694        except mm.MoveError as e:
695            if machine:
696                print(json.dumps({"schema_version": 1, "ok": False, "error": {"code": e.code, "message": str(e), "details": e.details}}, ensure_ascii=False))
697            else:
698                print(f"strata: {e} {e.details}".rstrip(), file=sys.stderr)
699            return 5
700        if machine:
701            print(json.dumps({"schema_version": 1, "ok": True, "event": "result", "left": True, **result}, ensure_ascii=False))
702        else:
703            print(f"Done. Your models stay in {st['from']}; the partial copies in {st['to']} were removed.")
704        return 0
705    a.to, a.source, a.resume, a.status, a.leave = st["to"], st["from"], False, False, False
706    return _models_move(a)
707
708
709def _import_words(plan: dict) -> str:
710    """The plain-words result of `strata models import --plan`: what the files are, what is already set up, what changes (nothing)."""
711    cand = plan.get("candidate_selection") or {}
712    lines = [f"{plan['file_count']} GGUF file(s): {plan['file_set_status']}"]
713    if cand.get("family"):
714        lines.append(f"These files are Strata's {cand['family']} {cand['model']}.")
715    done = plan.get("already_set_up")
716    if done:
717        have = [name for key, name in (("pack", "prepared model data"), ("mtp", "draft layer"), ("mmproj", "picture reader")) if done.get(key)]
718        if done.get("config"):
719            lines.append(f"Already set up: {done['config']}" + (f" (with the {', '.join(have)})" if have else ""))
720        elif have:
721            lines.append(f"Prepared files found beside it: {', '.join(have)}.")
722    lines.append(f"Adoption: {plan['adoption_status']}")
723    lines.append("No files changed")
724    return "\n".join(lines)
725
726
727def _redact_argv(args: list[str]) -> list[str]:
728    out = []
729    conceal_next = False
730    for item in args:
731        if conceal_next:
732            out.append("<redacted>")
733            conceal_next = False
734            continue
735        if item.startswith("-") and any(word in item.lower() for word in ("key", "token", "secret", "password", "credential")):
736            if "=" in item:
737                out.append(item.partition("=")[0] + "=<redacted>")
738            else:
739                out.append(item)
740                conceal_next = True
741        else:
742            out.append(item)
743    return out
744
745
746def _effective(cfg: dict, saved: dict | None, cli: argparse.Namespace | None = None) -> tuple[dict, dict]:
747    overrides = saved["overrides"] if saved else {}
748    values = {}
749    origins = {}
750    for key, default in (("host", "127.0.0.1"), ("port", 8095), ("parallel", None),
751                         ("batch_groups", None), ("max_queue", None), ("queue_timeout", None),
752                         ("offline", False), ("batch_telemetry", False)):
753        explicit = getattr(cli, key, None) if cli is not None else None
754        if key == "offline" and explicit is False:
755            explicit = None
756        if explicit is not None:
757            value, origin = explicit, "command"
758        elif key in overrides:
759            value, origin = overrides[key], "saved_profile"
760        elif key in cfg:
761            value, origin = cfg[key], "run_config"
762        elif key == "batch_telemetry" and "STRATA_BATCH_TELEMETRY" in os.environ:
763            value, origin = os.environ["STRATA_BATCH_TELEMETRY"] == "1", "environment"
764        else:
765            value, origin = default, "default"
766        values[key], origins[key] = value, origin
767    profiles.validate_overrides({key: value for key, value in values.items() if key in
768                                  ("host", "port", "parallel", "batch_groups", "max_queue", "queue_timeout",
769                                   "offline", "batch_telemetry")
770                                  and value is not None})
771    if values["queue_timeout"] is not None and values["max_queue"] is None:
772        raise ProfileError("queue_timeout requires max_queue to bound pending calls")
773    if values["parallel"] is not None and any(flag in cfg["args"] for flag in ("--batch", "--slots")):
774        # (the all-cards split engine's run config, split_config's "split_engine_note", always carries --batch; the server turns "parallel" into its lane count)
775        if origins["parallel"] != "run_config" and not cfg.get("split_engine_note"):
776            raise ProfileError("parallel override conflicts with --batch/--slots in run config args")
777    if values["batch_groups"] is not None and "--batch-groups" in cfg["args"]:
778        raise ProfileError("batch_groups override conflicts with --batch-groups in run config args")
779    if values["offline"] and (cfg.get("mcp_servers") or cfg.get("before_load")):
780        raise ProfileError("offline serving requires MCP servers and before_load to be absent")
781    return values, origins
782
783
784def _launch_plan(ref: str, cli: argparse.Namespace | None = None) -> tuple[dict, list[str]]:
785    path, saved, revision, cfg = _source(ref)
786    values, origins = _effective(cfg, saved, cli)
787    host = values["host"]
788    from serve.server import api_key_of, explicit_no_key, key_list
789    raw_key = os.environ.get("STRATA_API_KEY") or cfg.get("api_key", "")
790    if not explicit_no_key(raw_key):
791        try:
792            key_list(api_key_of(raw_key))
793        except ValueError:
794            raise ProfileError("the inference API key is invalid", 5) from None
795    # A key is recommended on a network, never required: the server warns once at start (owner decision 2026-10-20).
796    server_args = ["--engine", getattr(cli, "engine", "strata"), "--config", str(path), "--host", str(host),
797                   "--port", str(values["port"])]
798    if cli is not None:
799        server_args += ["--shutdown-timeout", str(cli.shutdown_timeout)]
800    for key, flag in (("parallel", "--parallel"), ("batch_groups", "--batch-groups"),
801                      ("max_queue", "--max-queue"), ("queue_timeout", "--queue-timeout")):
802        if values[key] is not None and origins[key] != "run_config":
803            server_args += [flag, str(values[key])]
804    if values["offline"]:
805        server_args.append("--offline")
806    if origins["batch_telemetry"] not in ("run_config", "default"):
807        server_args.append("--batch-telemetry" if values["batch_telemetry"] else "--no-batch-telemetry")
808    ready_path = None
809    if cli is not None and cli.ready_file:
810        from serve.ready import preflight as ready_preflight
811        ready_path = str(ready_preflight(cli.ready_file))
812        server_args += ["--ready-file", ready_path]
813    effective_cfg = {**cfg, "args": list(cfg["args"])}
814    if values["parallel"] is not None:
815        effective_cfg["parallel"] = values["parallel"]
816    if values["batch_groups"] is not None:
817        effective_cfg["args"] += ["--batch-groups", str(values["batch_groups"])]
818    from serve.server import engine_args
819    notes = io.StringIO()
820    with contextlib.redirect_stdout(notes):
821        engine_argv = engine_args(effective_cfg)
822    plan = {"profile": saved["id"] if saved else None, "profile_revision": revision,
823            "source_config": str(path), "model_name": cfg.get("model_name"),
824            "effective": values, "origin": origins, "server_argv": server_args,
825            "ready_file": ready_path,
826            "engine_exe": cfg["exe"], "engine_argv": _redact_argv(engine_argv),
827            "notes": [line for line in notes.getvalue().splitlines() if line]}
828    return plan, server_args
829
830
831def _serve_error(a: argparse.Namespace, message: str, code: int = 2) -> int:
832    if a.output == "jsonl":
833        print(json.dumps({"schema_version": 1, "event": "failed", "at": time.time(),
834                          "exit_code": code, "error": {"message": message}},
835                         ensure_ascii=False, allow_nan=False))
836        return code
837    return _error(message, code, a.output == "json")
838
839
840def _serve_jsonl(server_main, args: list[str], plan: dict, *, quiet: bool = False) -> int:
841    output = sys.stdout
842    output_open = True
843    ready = False
844    stopped = False
845    fields = {"starting": ("profile", "model_id", "pid"),
846              "ready": ("instance_id", "pid", "api_url", "bound_host", "bound_port",
847                        "model_id", "model_state", "api_state"),
848              "stopping": ("instance_id", "reason"),
849              "draining": ("instance_id", "pending_requests", "deadline_s"),
850              "stopped": ("instance_id", "reason", "drained", "cancelled_requests", "exit_code"),
851              "failed": ("phase", "exit_code")}
852
853    def emit(kind: str, values: dict) -> None:
854        nonlocal output_open, ready, stopped
855        if kind not in fields:
856            return
857        ready |= kind == "ready"
858        stopped |= kind == "stopped"
859        if not output_open:
860            return
861        record = {"schema_version": 1, "event": kind, "at": time.time(),
862                  **{key: values[key] for key in fields[kind] if key in values}}
863        try:
864            output.write(json.dumps(record, ensure_ascii=False, allow_nan=False) + "\n")
865            output.flush()
866        except BrokenPipeError:
867            # Losing a log consumer must not kill an owned inference service.
868            output_open = False
869
870    emit("starting", {"profile": plan["profile"], "model_id": plan["model_name"], "pid": os.getpid()})
871    try:
872        with (open(os.devnull, "w", encoding="utf-8") if quiet else
873              contextlib.nullcontext(sys.stderr)) as human_output:
874            with contextlib.redirect_stdout(human_output):
875                result = server_main(args, lifecycle_event=emit, interrupt_exit_code=130)
876    except SystemExit as exc:
877        result = exc.code if type(exc.code) is int else 6
878        if result == 0 and not ready:
879            result = 6
880        if not isinstance(exc.code, int):
881            print("strata: foreground service startup failed; inspect the profile and component checks",
882                  file=sys.stderr)
883        emit("failed", {"phase": "startup" if not ready else "running", "exit_code": result})
884        return result
885    except KeyboardInterrupt:
886        emit("failed", {"phase": "startup" if not ready else "running", "exit_code": 130})
887        return 130
888    except Exception as exc:
889        print(f"strata: foreground service failed ({type(exc).__name__})", file=sys.stderr)
890        emit("failed", {"phase": "startup" if not ready else "running", "exit_code": 6})
891        return 6
892    if not ready:
893        emit("failed", {"phase": "startup", "exit_code": result or 6})
894        return result or 6
895    if not stopped:
896        emit("failed" if result else "stopped",
897             {"phase": "running", "exit_code": result,
898              "reason": "normal", "drained": result == 0})
899    return result
900
901
902def _serve_foreground(server_main, args: list[str], plan: dict, *, output: str, quiet: bool) -> int:
903    if output == "jsonl":
904        return _serve_jsonl(server_main, args, plan, quiet=quiet)
905    if quiet:
906        with open(os.devnull, "w", encoding="utf-8") as human_output:
907            with contextlib.redirect_stdout(human_output):
908                result = server_main(args, interrupt_exit_code=130)
909        if result == 8:
910            print("strata: shutdown drain deadline expired; owned requests were cancelled", file=sys.stderr)
911        elif result:
912            print(f"strata: foreground service exited with code {result}", file=sys.stderr)
913        return result
914    return server_main(args, interrupt_exit_code=130)
915
916
917def _serve(a: argparse.Namespace) -> int:
918    if a.output == "json" and not a.plan:
919        return _serve_error(a, "--output json requires --plan; use --output jsonl for foreground events")
920    if a.output == "jsonl" and a.plan:
921        return _serve_error(a, "--plan uses --output human or json; jsonl is for foreground events")
922    if a.port is not None and not 0 <= a.port <= 65535:
923        return _serve_error(a, "--port must be in 0..65535")
924    if a.parallel is not None and not 1 <= a.parallel <= 1024:
925        return _serve_error(a, "--parallel must be in 1..1024")
926    if a.max_queue is not None and not 0 <= a.max_queue <= 4096:
927        return _serve_error(a, "--max-queue must be in 0..4096")
928    if a.queue_timeout is not None and (not math.isfinite(a.queue_timeout)
929                                        or not 0.1 <= a.queue_timeout <= 600):
930        return _serve_error(a, "--queue-timeout must be finite seconds in 0.1..600")
931    if not 0 <= a.shutdown_timeout <= 300:
932        return _serve_error(a, "--shutdown-timeout must be in 0..300 seconds")
933    try:
934        if a.batch_groups is not None:
935            profiles.validate_overrides({"batch_groups": a.batch_groups if a.batch_groups == "auto"
936                                          else int(a.batch_groups) if a.batch_groups.isdecimal() else a.batch_groups})
937        plan, args = _launch_plan(a.config, a)
938    except ValueError as exc:
939        if a.output == "jsonl":
940            return _serve_error(a, str(exc), getattr(exc, "exit_code", 2))
941        raise
942    if a.plan:
943        return _success({"plan": plan}, machine=a.output == "json")
944    from serve.server import main as server_main
945    if os.name not in ("posix", "nt"):
946        return _serve_foreground(server_main, args, plan, output=a.output, quiet=a.quiet)
947    from strata_control import runtime
948    try:
949        lease = runtime.acquire_activity_lease(shared=True)
950    except ValueError as exc:
951        if a.output == "jsonl":
952            return _serve_error(a, str(exc), getattr(exc, "exit_code", 6))
953        raise
954    try:
955        return _serve_foreground(server_main, args, plan, output=a.output, quiet=a.quiet)
956    finally:
957        os.close(lease)
958
959
960def _profile_command(a: argparse.Namespace) -> int:
961    machine = a.output == "json"
962    if a.profile_command == "create":
963        saved, revision = profiles.create(a.name, a.from_config)
964        return _success({"profile": saved, "revision": revision}, machine=machine,
965                        human=f"Saved profile {a.name} at revision {revision}")
966    if a.profile_command == "list":
967        items = profiles.list_profiles()
968        human = "\n".join(f"{item['id']}  {item.get('revision', item.get('error'))}" for item in items) or "No saved profiles"
969        return _success({"profiles": items}, machine=machine, human=human)
970    saved, revision = profiles.load(a.name)
971    if a.profile_command == "use-config":
972        proposed, previous = profiles.propose_source(a.name, a.from_config)
973        if previous != revision:
974            raise ProfileError("profile changed during source preview; plan it again", 6)
975        if a.if_revision is not None and a.if_revision != previous:
976            raise ProfileError("profile changed after preview; plan it again before selecting a config", 6)
977        change = {"before": saved["source_config"], "after": proposed["source_config"]}
978        if a.plan:
979            return _success({"profile": a.name, "revision": previous, "source_config": change,
980                             "model_name": profiles.read_run_config(Path(proposed["source_config"])).get("model_name"),
981                             "would_save": change["before"] != change["after"]}, machine=machine,
982                            human=f"Config: {change['before']} -> {change['after']}")
983        saved, revision = profiles.save(a.name, proposed, expected_revision=previous)
984        return _success({"profile": saved, "previous_revision": previous, "revision": revision,
985                         "source_config": change}, machine=machine,
986                        human=f"Saved source config for {a.name}: {change['before']} -> {change['after']}; "
987                              "running instance unchanged")
988    if a.profile_command == "set":
989        proposed, previous = profiles.propose_values(a.name, a.assignments)
990        changes = {key: {"before": saved["overrides"].get(key), "after": value}
991                   for key, value in proposed["overrides"].items() if saved["overrides"].get(key) != value}
992        if a.plan:
993            return _success({"profile": a.name, "revision": previous, "changes": changes,
994                             "would_save": bool(changes)}, machine=machine)
995        saved, revision = profiles.save(a.name, proposed, expected_revision=previous)
996        return _success({"profile": saved, "previous_revision": previous, "revision": revision,
997                         "changes": changes}, machine=machine,
998                        human=f"Saved profile {a.name}: {previous} -> {revision}\n" +
999                              "\n".join(f"  {key}: {value['before']!r} -> {value['after']!r}" for key, value in changes.items()))
1000    if a.profile_command == "edit":
1001        previous_value = saved
1002        saved, previous, revision = profiles.edit(a.name)
1003        changes = {key: {"before": previous_value.get(key), "after": saved.get(key)}
1004                   for key in saved if previous_value.get(key) != saved.get(key)}
1005        return _success({"profile": saved, "previous_revision": previous, "revision": revision,
1006                         "changes": changes}, machine=machine,
1007                        human=f"Saved profile {a.name}: {previous} -> {revision}")
1008    if a.profile_command == "history":
1009        entries = profiles.history(a.name)
1010        return _success({"profile": a.name, "history": entries}, machine=machine,
1011                        human="\n".join(f"{item['revision']}  {'current' if item.get('current') else 'saved'}"
1012                                        for item in entries))
1013    if a.profile_command == "rollback":
1014        saved, previous, revision = profiles.rollback(a.name, a.to)
1015        return _success({"profile": saved, "previous_revision": previous, "revision": revision}, machine=machine,
1016                        human=f"Restored profile {a.name}: {previous} -> {revision}; running instances are unchanged")
1017    result = {"profile": saved, "revision": revision}
1018    if a.profile_command == "validate" or a.effective:
1019        plan, _ = _launch_plan(a.name)
1020        result["plan"] = plan
1021    return _success(result, machine=machine, human=(f"Profile {a.name} is valid at revision {revision}"
1022                    if a.profile_command == "validate" else None))
1023
1024
1025def _doctor(a: argparse.Namespace) -> int:
1026    machine = a.output == "json"
1027    ref = getattr(a, "profile", None)
1028    path, saved, _ = profiles.resolve(ref) if ref else (None, None, None)
1029    report = inspect_components(path, profile_id=saved["id"] if saved else None,
1030                                live=getattr(a, "live", False))
1031    if machine:
1032        print(json.dumps({"schema_version": 1, "ok": report["ok"], "report": report},
1033                         ensure_ascii=False, allow_nan=False))
1034    else:
1035        for item in report["components"]:
1036            detail = item.get("path") or item.get("reason") or \
1037                (f"version {item['version']}" if item.get("version") else "")
1038            print(f"{item['status']:>16}  {item['name']}  {detail}")
1039        for issue in report["issues"]:
1040            print(f"{issue['severity']}: {issue['code']}: {issue['message']}")
1041        live_probe = report["live_gpu_probe"]
1042        if live_probe is not None:
1043            print(f"Live GPU probe: {live_probe['status']}")
1044            for card in live_probe["cards"]:
1045                print(f"  GPU {card['index']}: {card['name']} | {str(card['memory_mib']) + ' MiB' if card['memory_mib'] is not None else 'unified memory'} | "
1046                      f"driver {card['driver_version']} | {card['uuid']}")
1047    return 0 if report["ok"] else 5
1048
1049
1050def _direct_calibration(ref: str, kind: str, report_path: Path, action) -> tuple[str | None, dict]:
1051    """Saved profiles share the local journal; explicit run-config paths keep legacy behavior."""
1052    _, saved, revision = profiles.resolve(ref)
1053    if saved is None:
1054        return None, action()
1055    from strata_control import journal
1056    return journal.run_direct(saved["id"], kind, revision,
1057                              {"report_path": str(report_path.expanduser().resolve()), "exclusive_ack": True},
1058                              action)
1059
1060
1061def _calibration(a: argparse.Namespace) -> int:
1062    from strata_control import calibration
1063    machine = a.output == "json"
1064    if (a.out and not a.measure) or (a.exclusive and not (a.measure or a.apply_result or a.rollback_result)):
1065        return _error("--out is only for --measure; --exclusive is only for --measure, --apply-result "
1066                      "or --rollback-result", 2, machine)
1067    if a.measure:
1068        if not a.exclusive or not a.out:
1069            return _error("--measure requires --exclusive and --out REPORT.json", 2, machine)
1070        with contextlib.redirect_stdout(sys.stderr):
1071            operation_id, result = _direct_calibration(a.profile, "engine.calibrate.measure", Path(a.out),
1072                lambda: {"ok": True, "report_path": str(Path(a.out).resolve()),
1073                         "report": calibration.measure(a.profile, Path(a.out), exclusive_ack=True,
1074                                  say=lambda message: print(message, file=sys.stderr))})
1075        return _success({"report": result["report"], "path": str(Path(a.out).resolve()),
1076                         **({"operation_id": operation_id} if operation_id else {})}, machine=machine,
1077                        human=f"Calibration measured; review {Path(a.out).resolve()} before applying")
1078    if a.review_result:
1079        result = calibration.review(a.profile, Path(a.review_result))
1080        result["before_args"] = _redact_argv(result["before_args"])
1081        result["after_args"] = _redact_argv(result["after_args"])
1082        if machine:
1083            print(json.dumps({"schema_version": 1, "ok": result["applicable"], "review": result},
1084                             ensure_ascii=False, allow_nan=False))
1085        else:
1086            print(json.dumps(result, indent=2, ensure_ascii=False))
1087        return 0 if result["applicable"] else 6
1088    if a.apply_result:
1089        if not a.exclusive:
1090            return _error("--apply-result requires --exclusive", 2, machine)
1091        with contextlib.redirect_stdout(sys.stderr):
1092            operation_id, result = _direct_calibration(a.profile, "engine.calibrate.apply", Path(a.apply_result),
1093                lambda: {"ok": True, "application": calibration.apply_result(
1094                    a.profile, Path(a.apply_result), exclusive_ack=True)})
1095        return _success({"application": result["application"],
1096                         **({"operation_id": operation_id} if operation_id else {})}, machine=machine,
1097                        human=f"Calibration applied; rollback evidence: {result['application']['application_record']}")
1098    if a.review_rollback:
1099        result = calibration.review_rollback(a.profile, Path(a.review_rollback))
1100        if machine:
1101            print(json.dumps({"schema_version": 1, "ok": result["applicable"], "rollback_review": result},
1102                             ensure_ascii=False, allow_nan=False))
1103        else:
1104            print(json.dumps(result, indent=2, ensure_ascii=False))
1105        return 0 if result["applicable"] else 6
1106    if a.rollback_result:
1107        if not a.exclusive:
1108            return _error("--rollback-result requires --exclusive", 2, machine)
1109        with contextlib.redirect_stdout(sys.stderr):
1110            operation_id, result = _direct_calibration(a.profile, "engine.calibrate.rollback",
1111                Path(a.rollback_result), lambda: {"ok": True, "rollback": calibration.rollback_result(
1112                    a.profile, Path(a.rollback_result), exclusive_ack=True)})
1113        return _success({"rollback": result["rollback"],
1114                         **({"operation_id": operation_id} if operation_id else {})}, machine=machine,
1115                        human="Previous calibration configuration restored; restart the model to use it")
1116    plan = calibration.preview(a.profile)
1117    components = plan["component_preflight"]
1118    if machine:
1119        print(json.dumps({"schema_version": 1, "ok": components["ok"], "plan": plan},
1120                         ensure_ascii=False, allow_nan=False))
1121    else:
1122        print(f"Calibration plan for {plan['model_name'] or Path(plan['source_config']).name}")
1123        print(f"Run config: {plan['source_config']}")
1124        print("Measure engine settings for roughly 15–30 minutes with exclusive GPU access.")
1125        print("This preview did not start the engine or change configuration.")
1126        if not components["ok"]:
1127            print("Required components are missing; run strata doctor --profile first.")
1128    return 0 if components["ok"] else 5
1129
1130
1131def _bench(a: argparse.Namespace) -> int:
1132    from strata_cli import bench
1133    machine = a.output == "json"
1134    if a.bench_command in ("report", "compare") and a.out and a.output != "markdown":
1135        return _error("--out requires --output markdown", 2, machine)
1136    if a.bench_command == "report":
1137        from strata_cli import bench_standard
1138        standard_report = bench_standard.load_if_standard(Path(a.path))
1139        if standard_report is not None:
1140            if a.output == "markdown":
1141                rendered = bench_standard.report_markdown(standard_report)
1142                if a.out:
1143                    bench.write_markdown(Path(a.out), rendered)
1144                    print(f"Markdown report: {Path(a.out).resolve()}")
1145                else:
1146                    print(rendered, end="")
1147                return 0
1148            return _success({"summary": {"format": standard_report["format"], "run_id": standard_report["run"]["id"],
1149                                         "status": standard_report["run"]["status"],
1150                                         "quality": standard_report["quality"],
1151                                         "summaries": standard_report["summaries"]}}, machine=machine,
1152                            human=bench_standard.format_plain(standard_report))
1153        report = bench.load(Path(a.path))
1154        result = bench.summary(report)
1155        if a.output == "markdown":
1156            rendered = bench.markdown_report(report)
1157            if a.out:
1158                bench.write_markdown(Path(a.out), rendered)
1159                print(f"Markdown report: {Path(a.out).resolve()}")
1160            else:
1161                print(rendered, end="")
1162            return 0
1163        return _success({"summary": result}, machine=machine,
1164                        human=bench.format_summary(result))
1165    if a.bench_command == "compare":
1166        result = bench.compare(bench.load(Path(a.baseline)), bench.load(Path(a.candidate)))
1167        if a.output == "markdown":
1168            rendered = bench.markdown_comparison(result)
1169            if a.out:
1170                bench.write_markdown(Path(a.out), rendered)
1171                print(f"Markdown comparison: {Path(a.out).resolve()}")
1172            else:
1173                print(rendered, end="")
1174            return 0
1175        return _success({"comparison": result}, machine=machine,
1176                        human=bench.format_comparison(result))
1177    if a.bench_command == "cancel":
1178        from strata_control import benchmarking, profiles
1179        if not Path(a.path).is_absolute():
1180            return _error("benchmark cancel path must be absolute", 2, machine)
1181        profiles.load(a.profile)
1182        result = benchmarking.request_cancel(a.profile, Path(a.path))
1183        return _success(result, machine=machine,
1184                        human="Cancellation requested; check the saved report for the final outcome.")
1185    if not a.credential_env.isidentifier() or (a.telemetry_credential_env and
1186                                               not a.telemetry_credential_env.isidentifier()):
1187        return _error("credential options must name environment variables", 2, machine)
1188    if a.suite == "standard-v1":
1189        return _bench_standard(a, machine)
1190    if a.out is None:
1191        return _error("--out is required for the serving suites", 2, machine)
1192    a.concurrency = 4 if a.concurrency is None else a.concurrency
1193    a.repeat = 1 if a.repeat is None else a.repeat
1194    a.request_timeout = 120 if a.request_timeout is None else a.request_timeout
1195    maximum = 64 if a.suite == "parallel-overload-v1" else 16
1196    if not 1 <= a.concurrency <= maximum or not 1 <= a.repeat <= 5 or not 1 <= a.request_timeout <= 600:
1197        return _error(f"concurrency must be 1..{maximum}, repeat 1..5 and request timeout 1..600 seconds", 2,
1198                      machine)
1199    if a.require_managed_match and not a.profile:
1200        return _error("--require-managed-match needs a saved --profile", 2, machine)
1201    profile_identity = None
1202    if a.profile:
1203        path, saved, revision, cfg = _source(a.profile)
1204        if a.require_managed_match and saved is None:
1205            return _error("--require-managed-match needs a saved profile name", 2, machine)
1206        plan, _ = _launch_plan(a.profile)
1207        host = plan["effective"]["host"]
1208        host = "127.0.0.1" if host in ("0.0.0.0", "::") else host
1209        authority = f"[{host}]" if ":" in host and not host.startswith("[") else host
1210        url = f"http://{authority}:{plan['effective']['port']}"
1211        import hashlib
1212        profile_identity = {"profile": saved["id"] if saved else None, "revision": revision,
1213                            "source_config": str(path), "source_sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
1214                            "model_name": cfg.get("model_name"), "gpu": cfg.get("gpu")}
1215    else:
1216        url = a.url
1217    key = _usable_key(os.environ.get(a.credential_env))
1218    endpoint = Endpoint(url, key, timeout=10)
1219    telemetry = Endpoint(url, _usable_key(os.environ.get(a.telemetry_credential_env)) if a.telemetry_credential_env else key,
1220                         timeout=3)
1221    from strata_control.benchmarking import benchmark_lease
1222    lease = benchmark_lease(saved["id"], Path(a.out)) if a.profile and saved else contextlib.nullcontext()
1223    with lease, contextlib.redirect_stdout(sys.stderr):
1224        report = bench.run(endpoint, telemetry, Path(a.out), suite=a.suite,
1225                           concurrency=a.concurrency, repeat=a.repeat,
1226                           request_timeout=a.request_timeout, profile_identity=profile_identity,
1227                           condition=a.condition, require_managed_match=a.require_managed_match)
1228    compact = bench.summary(report)
1229    if machine:
1230        print(json.dumps({"schema_version": 1, "ok": report["successful"],
1231                          "path": str((Path(a.out) / "results.json").resolve()), "summary": compact},
1232                         ensure_ascii=False, allow_nan=False))
1233    else:
1234        print(bench.format_summary(compact))
1235        print(f"Evidence: {Path(a.out).resolve() / 'results.json'}")
1236    return 0 if report["successful"] else 6
1237
1238
1239def _usable_key(value):
1240    """An API key from the environment: "none" (any case) is the server's word for no key, so it is no key (#4483)."""
1241    from strata_cli.bench_facts import usable_key
1242    return usable_key(value)
1243
1244
1245def _bench_standard(a: argparse.Namespace, machine: bool) -> int:
1246    """`strata bench run` for docs/BENCHMARK_PROTOCOL.md: against a running server (--url, or a profile that is already serving),
1247    or by starting the profile's engine for the run and stopping it afterwards."""
1248    from strata_cli import bench_facts, bench_standard
1249    fixed = [name for name, value in (("--concurrency", a.concurrency), ("--repeat", a.repeat),
1250                                      ("--request-timeout", a.request_timeout), ("--condition", a.condition),
1251                                      ("--require-managed-match", a.require_managed_match or None),
1252                                      ("--telemetry-credential-env", a.telemetry_credential_env))
1253             if value is not None]
1254    if fixed:
1255        return _error(f"{', '.join(fixed)} do not apply to the standard suite: the protocol fixes the workload "
1256                      "(use --suite serving-smoke for a serving benchmark)", 2, machine)
1257    if not a.credential_env.isidentifier():
1258        return _error("credential options must name environment variables", 2, machine)
1259    if not 1 <= a.load_timeout <= 86400:
1260        return _error("--load-timeout must be 1..86400 seconds", 2, machine)
1261    plan = None
1262    saved = None
1263    key = _usable_key(os.environ.get(a.credential_env))
1264    if a.profile:
1265        _, saved, _, cfg = _source(a.profile)
1266        plan, _ = _launch_plan(a.profile)
1267        plan = {**plan, "config": cfg}
1268        host = plan["effective"]["host"]
1269        host = "127.0.0.1" if host in ("0.0.0.0", "::") else host
1270        authority = f"[{host}]" if ":" in host and not host.startswith("[") else host
1271        url = f"http://{authority}:{plan['effective']['port']}"
1272        if not key and cfg.get("api_key") and str(cfg["api_key"]).strip().lower() != "none":
1273            from serve.server import api_key_of, key_list
1274            keys = key_list(api_key_of(cfg["api_key"]))
1275            key = keys[0] if keys else None
1276    else:
1277        url = a.url
1278    from strata_cli.client import server_url
1279    target = bench_standard.Target(server_url(url), key)
1280    redact = bench_facts.redactor(key or "")
1281    command = redact("strata " + " ".join(str(part) for part in (a.raw_argv or ["bench", "run", "--suite", "standard-v1"])))
1282    declared = {"track": a.track, "track_notes": a.track_notes or "no notes given by the operator",
1283                "model_revision": a.model_revision, "source_revision": a.source_revision,
1284                "tokenizer_revision": a.tokenizer_revision, "quantization": a.quantization,
1285                "custom_pack": a.custom_pack, "background": a.background or [],
1286                "build_options": [x.strip() for x in a.build_options.split(",") if x.strip()] if a.build_options else None}
1287    out = Path(a.out) if a.out else None
1288    out_root = None if out else (Path.cwd() / "bench" / "results" if (Path.cwd() / "bench" / "results").is_dir()
1289                                 else Path.cwd() / "bench-results")
1290    from strata_control.benchmarking import benchmark_lease
1291    import shutil
1292    import tempfile
1293    lease = benchmark_lease(saved["id"], out) if saved else contextlib.nullcontext()
1294    proc, scratch, engine_log, run_log, log_start = None, None, None, None, 0
1295    stop_problem = None
1296    try:
1297        with lease, bench_standard.term_is_interrupt(), contextlib.redirect_stdout(sys.stderr):
1298            def log(message: str) -> None:
1299                print(message, file=sys.stderr, flush=True)
1300            if a.profile and target.get("/health", timeout=5) is None:
1301                if a.no_start:
1302                    raise ProfileError("no server is answering at the profile's address and --no-start was given", 5)
1303                scratch = Path(tempfile.mkdtemp(prefix="strata-bench-"))
1304                engine_log = scratch / "engine.log"
1305                run_log = Path(str(plan["config"]["log"])).expanduser() if isinstance(plan["config"].get("log"), str) else None
1306                log_start = run_log.stat().st_size if run_log is not None and run_log.is_file() else 0
1307                proc = bench_standard.start_engine(a.profile, target, engine_log, log, a.load_timeout)
1308            elif a.profile:
1309                log("using the server that is already running at this profile's address; it will not be stopped")
1310            doc, out_dir = bench_standard.run(target, out, out_root=out_root, optional_concurrency=a.optional_concurrency,
1311                                              declared=declared, plan=plan, engine_log=engine_log, command=command, log=log,
1312                                              engine_run_log=(run_log, log_start) if proc is not None else None,
1313                                              started_engine=proc is not None, hash_model=not a.skip_model_hash)
1314    finally:
1315        stop_problem = bench_standard.stop_engine(proc)
1316        if not isinstance(stop_problem, str):
1317            stop_problem = None
1318        if scratch is not None:
1319            shutil.rmtree(scratch, ignore_errors=True)
1320    ok = doc["run"]["status"] == "complete"
1321    if stop_problem:   # #3438: a stop that failed is not a normal finish: the engine may still hold the port and the GPU
1322        ok = False
1323        print(f"\nERROR: the engine this run started could not be stopped: {stop_problem}. It may still hold the server port "
1324              "and the GPU: stop it by hand before the next run. This run is marked FAILED.", file=sys.stderr, flush=True)
1325        try:
1326            (out_dir / "ENGINE-NOT-STOPPED.txt").write_text(stop_problem + "\n", encoding="utf-8")
1327        except OSError:
1328            pass
1329    path = out_dir / "results.json"
1330    if machine:
1331        print(json.dumps({"schema_version": 1, "ok": ok, "path": str(path.resolve()), "status": "failed" if stop_problem else doc["run"]["status"], "engine_stop_error": stop_problem,
1332                          "quality": doc["quality"], "summaries": doc["summaries"]}, ensure_ascii=False, allow_nan=False))
1333    else:
1334        print(bench_standard.format_plain(doc))
1335        print(f"\nReport: {out_dir.resolve() / 'README.md'}\nResult: {path.resolve()}")
1336    return 0 if ok else 6
1337
1338
1339def _runtime(a: argparse.Namespace) -> int:
1340    from strata_control import management
1341    machine = a.output == "json"
1342    if a.runtime_command == "cleanup":
1343        from strata_control import runtime
1344        result = runtime.cleanup(a.profile)
1345        if machine:
1346            print(json.dumps({"schema_version": 1, **result}, ensure_ascii=False, allow_nan=False))
1347        else:
1348            print(f"ended {len(result['ended'])} leftover process(es)" +
1349                  (f"; {len(result['stuck'])} would not end" if result["stuck"] else "") +
1350                  (f"; {len(result['unverifiable'])} could not be identified here and were left alone"
1351                   if result["unverifiable"] else ""))
1352        return 0 if result["ok"] else result["exit_code"]
1353    result = management.runtime_action(
1354        a.runtime_command, a.profile, plan=getattr(a, "plan", False),
1355        die_with_pid=getattr(a, "die_with_pid", None),
1356        wait=getattr(a, "wait", 300),
1357        shutdown_timeout=getattr(a, "shutdown_timeout", 30),
1358        startup_wait=getattr(a, "startup_wait", 300), load=getattr(a, "load", False),
1359        if_profile_revision=getattr(a, "if_profile_revision", None),
1360        if_owner_id=getattr(a, "if_owner_id", None),
1361        if_instance_id=getattr(a, "if_instance_id", None),
1362        allow_source_switch=getattr(a, "allow_source_switch", False),
1363        allow_source_migration=getattr(a, "allow_source_migration", False),
1364        if_source_sha256=getattr(a, "if_source_sha256", None))
1365    if a.runtime_command in ("start", "stop", "verify") and a.plan and result.get("ok"):
1366        return _success({"plan": result["plan"]}, machine=machine)
1367    if machine:
1368        print(json.dumps({"schema_version": 1, **result}, ensure_ascii=False, allow_nan=False))
1369    else:
1370        readiness_label = {"generation_ready": "generation checked",
1371                           "unloaded": "API verified; model unloaded"}.get(result.get("readiness_state"))
1372        print(f"{a.profile}: {result.get('state', 'unknown')}" +
1373              (f"  instance {result['instance_id']}" if result.get("instance_id") else "") +
1374              (f"  {result['api_url']}" if result.get("api_url") else "") +
1375              ("  config/launch verified" if result.get("launch_attested") else "") +
1376              (f"  {readiness_label}" if readiness_label else "") +
1377              (f"  {result['error']}" if result.get("error") else ""))
1378        if not result["ok"] and a.runtime_command in ("start", "restart", "verify"):
1379            for line in _engine_log_hint(a.profile):
1380                print(line, file=sys.stderr)
1381    return 0 if result["ok"] else result.get("exit_code", 6)
1382
1383
1384def _engine_log_hint(profile: str) -> list[str]:
1385    """Where the engine wrote why it stopped, and its last lines: "server_exited" alone names nothing to read."""
1386    try:
1387        path, _saved, _revision = profiles.resolve(profile)
1388        log = profiles.read_run_config(path).get("log")
1389        if not isinstance(log, str) or not log:
1390            return []
1391        text = Path(log).expanduser().read_text(encoding="utf-8", errors="replace")
1392    except (ProfileError, OSError, ValueError, KeyError):
1393        return []
1394    lines = [line.strip() for line in text.splitlines() if line.strip()]
1395    tail = lines[-3:]
1396    return [f"engine log: {log}"] + [f"  {line[:300]}" for line in tail]
1397
1398
1399def _ops(a: argparse.Namespace) -> int:
1400    from strata_control import journal, recipes
1401    machine = a.output == "json"
1402    action = a.ops_command
1403    if action == "init":
1404        created = recipes.initialize(a.profile)
1405        return _success({"profile": a.profile, "created": created}, machine=machine,
1406                        human=("Created: " + ", ".join(created) if created else "Recipes already initialized"))
1407    if action == "list":
1408        items = recipes.list_recipes(a.profile)
1409        return _success({"profile": a.profile, "recipes": items}, machine=machine,
1410                        human="\n".join(f"{item['id']}  {item.get('kind', item.get('error'))}" for item in items)
1411                              or "No recipes; use strata ops init --profile NAME")
1412    if action == "runs":
1413        runs = journal.list_runs(a.profile, limit=a.limit)
1414        return _success({"profile": a.profile, "runs": runs}, machine=machine,
1415                        human="\n".join(f"{item['operation_id']}  {item.get('state', item.get('error'))}"
1416                                        for item in runs) or "No operation runs recorded")
1417    if action == "result":
1418        record = journal.load(a.profile, a.operation_id)
1419        return _success({"record": record}, machine=machine)
1420    if action == "create":
1421        recipe, revision = recipes.create(a.profile, a.name, a.kind)
1422        return _success({"recipe": recipe, "revision": revision}, machine=machine,
1423                        human=f"Created recipe {a.name} ({a.kind}) at {revision}")
1424    if action == "show":
1425        recipe, revision = recipes.load(a.profile, a.name)
1426        return _success({"recipe": recipe, "revision": revision}, machine=machine)
1427    if action == "edit":
1428        recipe, previous, revision = recipes.edit(a.profile, a.name)
1429        return _success({"recipe": recipe, "previous_revision": previous, "revision": revision},
1430                        machine=machine, human=f"Saved recipe {a.name}: {previous} -> {revision}")
1431    if action == "set":
1432        recipe, revision = recipes.propose_value(a.profile, a.name, a.assignment)
1433        if a.plan:
1434            current, _ = recipes.load(a.profile, a.name)
1435            return _success({"recipe": recipe, "revision": revision, "would_save": recipe != current}, machine=machine)
1436        saved, new_revision = recipes.save(a.profile, a.name, recipe, revision)
1437        return _success({"recipe": saved, "previous_revision": revision, "revision": new_revision},
1438                        machine=machine, human=f"Saved recipe {a.name}: {revision} -> {new_revision}")
1439    if action == "history":
1440        entries = recipes.history(a.profile, a.name)
1441        return _success({"profile": a.profile, "recipe": a.name, "history": entries}, machine=machine,
1442                        human="\n".join(f"{item['revision']}  {'current' if item.get('current') else 'saved'}"
1443                                        for item in entries))
1444    if action == "rollback":
1445        recipe, previous, revision = recipes.rollback(a.profile, a.name, a.to)
1446        return _success({"recipe": recipe, "previous_revision": previous, "revision": revision},
1447                        machine=machine, human=f"Restored recipe {a.name}: {previous} -> {revision}")
1448    if action == "plan":
1449        plan = recipes.plan(a.profile, a.name)
1450        ok = plan["operation"]["ok"]
1451        if machine:
1452            print(json.dumps({"schema_version": 1, "ok": ok, "plan": plan}, ensure_ascii=False, allow_nan=False))
1453        else:
1454            print(json.dumps(plan, indent=2, ensure_ascii=False))
1455        return 0 if ok else plan["operation"].get("exit_code", 5)
1456    recipe, _ = recipes.load(a.profile, a.name)
1457    if a.exclusive and recipe["kind"] != "engine.calibrate.measure":
1458        return _error("--exclusive applies only to calibration recipes", 2, machine)
1459    with contextlib.redirect_stdout(sys.stderr):
1460        operation = recipes.run(a.profile, a.name, exclusive_ack=a.exclusive,
1461                                expected_revision=a.if_revision,
1462                                expected_profile_revision=a.if_profile_revision,
1463                                expected_owner_id=a.if_owner_id,
1464                                expected_instance_id=a.if_instance_id,
1465                                expected_source_sha256=a.if_source_sha256)
1466    ok = operation["result"]["ok"]
1467    if machine:
1468        print(json.dumps({"schema_version": 1, "ok": ok, "operation": operation},
1469                         ensure_ascii=False, allow_nan=False))
1470    else:
1471        print(json.dumps(operation, indent=2, ensure_ascii=False))
1472    return 0 if ok else operation["result"].get("exit_code", 5)
1473
1474
1475def _timeskip(a: argparse.Namespace) -> int:
1476    """Real Time-skip: retain, revise, check, decide.
1477
1478    The decision is evidence-driven and the terminal states are honest: a run whose checks are
1479    missing, unevaluable or unchanged ends inconclusive and asks the user to review, and cancelling
1480    or crashing leaves the last complete checkpoint selected. No timer decides anything here.
1481    """
1482    from strata_control import time_skip
1483
1484    def state_root() -> Path:
1485        if getattr(a, "state_dir", None):
1486            return Path(a.state_dir)
1487        env = os.environ.get("STRATA_TIMESKIP_DIR")
1488        if env:
1489            return Path(env)
1490        from strata_control.paths import state_base
1491        return state_base() / "time-skip"
1492
1493    store = time_skip.TimeSkipStore(state_root())
1494
1495    if a.timeskip_command == "list":
1496        runs = store.list()
1497        if a.output == "json":
1498            return _success({"runs": runs}, machine=True)
1499        if not runs:
1500            print("no Time-skip runs recorded")
1501            return 0
1502        for r in runs:
1503            decision = (r.get("decision") or {}).get("outcome") or "-"
1504            print(f"{r['id'][:12]}  {str(r.get('state','?')):<18} {decision:<12} "
1505                  f"{(r.get('prompt') or '')[:48]}")
1506        return 0
1507
1508    if a.timeskip_command == "status":
1509        try:
1510            data = store.get(a.run_id)
1511        except time_skip.TimeSkipError as e:
1512            return _error(str(e), 2, a.output == "json")
1513        if a.output == "json":
1514            return _success({"run": data}, machine=True)
1515        print(f"run       {data['id']}")
1516        print(f"state     {data['state']}")
1517        print(f"workspace {data['workspace']}")
1518        print(f"prompt    {data['prompt']}")
1519        for cp in data.get("checkpoints", []):
1520            outcomes = ", ".join(f"{c['id']}={c['outcome']}" for c in cp.get("checks", [])) or "no checks"
1521            print(f"  {cp['id']:<16} {cp['digest'][:12]}  {outcomes}")
1522        for att in data.get("attempts", []):
1523            print(f"  attempt {att['index']}: {att.get('decision')} - {att.get('reason','')}")
1524        dec = data.get("decision") or {}
1525        if dec:
1526            print(f"decision  {dec.get('outcome')} ({dec.get('reason')})")
1527            print(f"retained  {dec.get('retained')}")
1528            if dec.get("needs_user_review"):
1529                print("          needs user review: the evidence does not justify an automatic choice")
1530        return 0
1531
1532    if a.timeskip_command == "apply":
1533        try:
1534            data = store.get(a.run_id)
1535        except time_skip.TimeSkipError as e:
1536            return _error(str(e), 2, a.output == "json")
1537        run = _reopen_run(store, data)
1538        destination = Path(a.workspace) if a.workspace else None
1539        try:
1540            if a.restore:
1541                outcome = run.restore_original(destination)
1542                if a.output == "json":
1543                    return _success({"restore": outcome}, machine=True)
1544                print(f"restored {outcome['checkpoint']} to {destination or data['workspace']}")
1545                return 0
1546            outcome = run.apply(destination, dry_run=a.dry_run, attempt=a.attempt)
1547        except time_skip.TimeSkipError as e:
1548            return _error(str(e), 2, a.output == "json")
1549        if outcome.get("conflict"):
1550            # A concurrent user edit is a conflict to report, never something to overwrite.
1551            return _error(outcome["reason"], 6, a.output == "json")
1552        if not outcome.get("applied") and not outcome.get("dry_run"):
1553            return _error(outcome.get("reason", "apply did not complete"), 6, a.output == "json")
1554        if a.output == "json":
1555            return _success({"apply": outcome}, machine=True)
1556        if outcome.get("dry_run"):
1557            print("would write: " + (", ".join(outcome.get("would_write") or []) or "(nothing)"))
1558            if outcome.get("would_remove"):
1559                print("would remove: " + ", ".join(outcome["would_remove"]))
1560            return 0
1561        print("applied " + (", ".join(outcome.get("wrote") or []) or "(no changes)"))
1562        print(f"rollback copy: {outcome.get('rollback')}")
1563        return 0
1564
1565    # run
1566    workspace = Path(a.workspace)
1567    if not workspace.is_dir():
1568        return _error(f"workspace is not a directory: {workspace}", 2, a.output == "json")
1569    try:
1570        checks = store.load_checks(workspace)
1571    except (time_skip.TimeSkipError, ValueError, OSError) as e:
1572        return _error(f"could not read .strata/checks.json: {e}", 2, a.output == "json")
1573    if not checks:
1574        print("strata: no checks are declared for this workspace (.strata/checks.json); the run "
1575              "will checkpoint and report inconclusive rather than claim an improvement",
1576              file=sys.stderr)
1577
1578    run = time_skip.TimeSkipRun(state_root(), workspace, a.prompt, checks, max_attempts=a.attempts)
1579
1580    def revise(candidate: Path, prompt: str, attempt: int):
1581        if not a.revise_command:
1582            return None
1583        env = {**os.environ, "STRATA_TIMESKIP_PROMPT": prompt,
1584               "STRATA_TIMESKIP_ATTEMPT": str(attempt)}
1585        proc = subprocess.run(a.revise_command, shell=True, cwd=str(candidate), env=env,
1586                              capture_output=True, text=True, errors="replace")
1587        if proc.returncode != 0:
1588            raise time_skip.TimeSkipError(
1589                f"the revision command failed (exit {proc.returncode}): "
1590                f"{(proc.stderr or proc.stdout or '')[-300:]}")
1591        return (proc.stdout or "").strip()[-500:] or None
1592
1593    result = run.run(revise)
1594    if a.output == "json":
1595        if result["state"] in ("failed", "interrupted"):
1596            return _error(result.get("error") or result["state"], 6, True)
1597        return _success({"run": result}, machine=True)
1598    print(f"run {result['id']} -> {result['state']}")
1599    for att in result.get("attempts", []):
1600        print(f"  attempt {att['index']}: {att.get('decision')} - {att.get('reason','')}")
1601    dec = result.get("decision") or {}
1602    if dec:
1603        print(f"  decision: {dec.get('outcome')} ({dec.get('reason')})")
1604        if dec.get("needs_user_review"):
1605            print("  the evidence does not justify an automatic choice; compare and select")
1606    print(f"  inspect: strata timeskip status {result['id']}")
1607    print(f"  preview: strata timeskip apply {result['id']} --dry-run")
1608    if result["state"] in ("failed", "interrupted"):
1609        return _error(result.get("error") or result["state"], 6, False)
1610    return 0
1611
1612
1613def _reopen_run(store, data: dict):
1614    """Rebuild a run object from its durable record so apply/restore survive a restart."""
1615    from strata_control import time_skip
1616    run = time_skip.TimeSkipRun(store.root, Path(data["workspace"]), data["prompt"], [],
1617                                run_id=data["id"])
1618    run.state = data.get("state", run.state)
1619    run.checkpoints = [time_skip.Checkpoint(**cp) for cp in data.get("checkpoints", [])]
1620    run.attempts = [time_skip.Attempt(**att) for att in data.get("attempts", [])]
1621    run.selected_checkpoint = data.get("selected_checkpoint")
1622    run.decision = data.get("decision")
1623    run.events = data.get("events", [])
1624    run.started_at = data.get("started_at", run.started_at)
1625    run.finished_at = data.get("finished_at")
1626    return run
1627
1628
1629def _engine_arg(value: str, backend: str) -> Path:
1630    """`--engine` is a path, or `component:strata-engine` for the engine package installed for this PC."""
1631    from strata_control import engine_component
1632    if engine_component.is_reference(value):
1633        try:
1634            return Path(engine_component.expand(value, {"backend": backend}))
1635        except engine_component.EngineMissing as exc:
1636            raise ProfileError(str(exc), 5) from None
1637    return Path(value)
1638
1639
1640def _tune(a: argparse.Namespace) -> int:
1641    """Engine tuning: a bounded search that returns a recommendation, never an automatic change.
1642
1643    `plan` is the review surface. It reports which dimensions the selected backend may search and
1644    *why* the rest were excluded, so a sweep can never measure a configuration the engine would
1645    refuse. Running a sweep is a separate, longer step and is deliberately not exposed here yet: it
1646    needs a measurement harness for the selected engine, and this Mac has no workload to measure.
1647    """
1648    from strata_control import tuning
1649    machine = a.output == "json"
1650
1651    def state_root() -> Path:
1652        if getattr(a, "state_dir", None):
1653            return Path(a.state_dir)
1654        env = os.environ.get("STRATA_TUNE_DIR")
1655        if env:
1656            return Path(env)
1657        from strata_control.paths import state_base
1658        return state_base() / "tuning"
1659
1660    if a.tune_command == "auto":
1661        return tune_commands.auto(a)
1662
1663    if a.tune_command == "list":
1664        root = state_root()
1665        jobs = []
1666        if root.is_dir():
1667            for d in sorted(root.iterdir()):
1668                f = d / "job.json"
1669                if f.is_file():
1670                    try:
1671                        data = json.loads(f.read_text(encoding="utf-8"))
1672                    except (OSError, ValueError):
1673                        continue
1674                    jobs.append({"id": data.get("id"), "state": data.get("state"),
1675                                 "backend": (data.get("plan") or {}).get("backend"),
1676                                 "objective": (data.get("plan") or {}).get("objective")})
1677        if machine:
1678            return _success({"jobs": jobs}, machine=True)
1679        if not jobs:
1680            print("no tuning jobs recorded")
1681            return 0
1682        for j in jobs:
1683            print(f"{str(j['id'])[:12]}  {str(j['state']):<10} {str(j['backend']):<8} {j['objective']}")
1684        return 0
1685
1686    if a.tune_command == "status":
1687        root = state_root()
1688        f = root / a.job_id / "job.json"
1689        if not f.is_file():
1690            return _error(f"no tuning job {a.job_id}", 2, machine)
1691        data = json.loads(f.read_text(encoding="utf-8"))
1692        if machine:
1693            return _success({"job": data}, machine=True)
1694        print(f"job       {data['id']}")
1695        print(f"state     {data['state']}")
1696        plan = data.get("plan") or {}
1697        print(f"backend   {plan.get('backend')}  objective {plan.get('objective')}")
1698        rep = data.get("report") or {}
1699        if rep:
1700            print(f"metric    {rep.get('metric')} (higher is better: {rep.get('higher_is_better')})")
1701            print(f"trials    {rep.get('trials_run')} of {plan.get('max_trials')}")
1702            base = rep.get("baseline") or {}
1703            if base:
1704                print(f"baseline  median {base.get('median')} over {base.get('measured')} runs")
1705            if rep.get("recommendation_available"):
1706                rec = rep["recommendation"]
1707                print(f"recommend index {rec['candidate_index']} median {rec['median']} "
1708                      f"(baseline {rec['baseline_median']})")
1709                print(f"          args: {' '.join(f'{k} {v}' for k, v in rec['args'].items())}")
1710            else:
1711                print(f"recommend none - {rep.get('reason')}")
1712            for f_ in rep.get("failures") or []:
1713                print(f"  failed  #{f_['index']} {f_['status']}: {f_['reason'][:90]}")
1714        return 0
1715
1716    if a.tune_command == "run":
1717        return _tune_run(a, store_root=state_root())
1718    if a.tune_command == "apply":
1719        return _tune_apply(a, store_root=state_root())
1720    if a.tune_command == "rollback":
1721        return _tune_rollback(a, store_root=state_root())
1722
1723    # plan
1724    engine = _engine_arg(a.engine, a.backend)
1725    plan = tuning.plan_tuning(engine, a.backend, a.model, a.objective,
1726                              {"note": "the workload is supplied by the measurement harness"},
1727                              hold=a.hold, max_trials=a.trials, total_time_s=a.total_time,
1728                              repeats=a.repeats, devices=[],
1729                              model_path=getattr(a, "model_path", None))
1730    if machine:
1731        return _success({"plan": plan.to_dict()}, machine=True)
1732    print(f"engine    {plan.engine}")
1733    print(f"flags     {'read from the binary' if plan.engine_flags_known else 'could not be read; the static table was used and this is recorded'}")
1734    print(f"backend   {plan.backend}   objective {plan.objective}   repeats {plan.repeats}")
1735    print(f"bounds    at most {plan.max_trials} trials, {plan.total_time_s:.0f}s total")
1736    print("searches:")
1737    for d in plan.dimensions:
1738        mark = "  (benchmark only: never exported)" if d["benchmark_only"] else ""
1739        print(f"  {d['id']:<18} {', '.join(d['flags'])}  values {d['values']}{mark}")
1740    if not plan.dimensions:
1741        print("  (none: this backend offers no searchable dimension)")
1742    print("excluded:")
1743    for e in plan.excluded:
1744        print(f"  {e['id']:<18} {e['reason']}")
1745    print()
1746    print("Applying a result is a separate step; a sweep never writes the active profile.")
1747    return 0
1748
1749
1750def _tune_run(a: argparse.Namespace, *, store_root: Path) -> int:
1751    """Run a bounded sweep and write its report.
1752
1753    The measurement is `tune_engine.EngineHarness`: it boots the engine with one candidate's flags,
1754    sends the fixed workload and reads the engine's own protocol output. Nothing here invents a
1755    number — a candidate that cannot be measured is recorded with the engine's reason and excluded
1756    from selection.
1757
1758    Two honest limitations are printed with the result rather than buried:
1759
1760      * the winner is measured through the engine's own serve protocol, **not** through the full
1761        HTTP API the Harness uses, so the recommendation still needs the exported-configuration
1762        retest the qualification kit describes before it is trusted;
1763      * no profile is written. Applying is a separate, reversible step.
1764    """
1765    from strata_control import tune_engine, tuning
1766
1767    engine = _engine_arg(a.engine, a.backend)
1768    if not engine.exists():
1769        return _error(f"no engine binary at {engine}", 2, a.output == "json")
1770
1771    plan = tuning.plan_tuning(
1772        engine, a.backend, a.model, a.objective,
1773        {"prompt_tokens": a.prompt_tokens, "max_new": a.max_new, "seed": 1, "temperature": 0.0},
1774        hold=a.hold, max_trials=a.trials, total_time_s=a.total_time, repeats=a.repeats, devices=[],
1775        model_path=Path(a.model_path) if a.model_path else None, context=a.context,
1776        full_digests=a.full_digests)
1777
1778    workload = {"prompt_tokens": a.prompt_tokens, "max_new": a.max_new, "seed": 1, "temperature": 0.0}
1779    if a.mode == "api":
1780        from strata_control import tune_api
1781        if not a.config:
1782            return _error("--mode api needs --config: the worker is started from a run "
1783                          "configuration so the candidate's flags are the ones it boots with",
1784                          2, a.output == "json")
1785        if not a.api_expect:
1786            return _error("--mode api needs --api-expect: without an expectation a fast wrong answer "
1787                          "cannot be told from a fast right one", 2, a.output == "json")
1788        measure = tune_api.make_api_measure(
1789            python=sys.executable, serve_dir=Path(__file__).resolve().parents[1],
1790            config_path=Path(a.config), prompt=a.api_prompt, max_new=a.max_new,
1791            expect=a.api_expect, port=a.api_port, boot_timeout_s=a.boot_timeout,
1792            request_timeout_s=a.request_timeout)
1793    else:
1794        measure = tune_engine.make_measure(engine, workload=workload)
1795
1796    if a.output != "json":
1797        searched = ", ".join(d["id"] for d in plan.dimensions) or "(nothing)"
1798        print(f"sweeping {searched}")
1799        if a.mode == "api":
1800            print(f"measuring through the HTTP API at port {a.api_port}, "
1801                  f"checking the answer against {a.api_expect!r}")
1802        else:
1803            print("measuring the engine's own serve protocol")
1804        print(f"backend {plan.backend} · objective {plan.objective} · repeats {plan.repeats} · "
1805              f"at most {plan.max_trials} trials / {plan.total_time_s:.0f}s")
1806        if not plan.dimensions:
1807            print("strata: this backend offers no searchable dimension for this engine, so the "
1808                  "sweep will measure the baseline and stop", file=sys.stderr)
1809
1810    job = tuning.Tuner(store_root, plan, measure)
1811    result = job.run()
1812
1813    if a.output == "json":
1814        return _success({"job": result}, machine=True)
1815
1816    rep = result.get("report") or {}
1817    print(f"job {result['id']} -> {result['state']}")
1818    base = rep.get("baseline") or {}
1819    if base:
1820        print(f"  baseline  median {base.get('median')} over {base.get('measured')} runs")
1821    total = rep.get("combinations_total") or 0
1822    ran = rep.get("trials_run", 0)
1823    if rep.get("trials_are_a_prefix") and total:
1824        # Say plainly that this was a prefix of the space. Otherwise "4 trials" reads as "4 was all
1825        # there was", and a partial search gets mistaken for a complete one.
1826        print(f"  trials    {ran} of {plan.max_trials} allowed, from {total} possible combinations "
1827              f"(a prefix of the enumeration)")
1828    else:
1829        print(f"  trials    {ran} of {plan.max_trials}")
1830    for f in rep.get("failures") or []:
1831        print(f"  failed    #{f['index']} {f['status']}: {f['reason'][:90]}")
1832    if rep.get("drift") and rep.get("drift_material"):
1833        d = rep["drift"]
1834        print(f"  drift     baseline {d['first']:.1f} -> {d['last']:.1f} "
1835              f"({d['relative'] * 100:+.1f}%) — the comparison is weaker than the repeat count suggests")
1836    elif rep.get("drift"):
1837        d = rep["drift"]
1838        print(f"  drift     baseline {d['first']:.1f} -> {d['last']:.1f} "
1839              f"({d['relative'] * 100:+.1f}%) — within noise")
1840    if rep.get("recommendation_available"):
1841        rec = rep["recommendation"]
1842        args = " ".join(f"{k} {v}" for k, v in rec["args"].items()) or "(no flags)"
1843        print(f"  recommend index {rec['candidate_index']}: {args}")
1844        print(f"            median {rec['median']:.1f} against a baseline of {rec['baseline_median']:.1f}")
1845    else:
1846        print(f"  recommend none — {rep.get('reason')}")
1847    print()
1848    if a.mode == "api":
1849        print("  measured through the worker's HTTP API, which is what a user waits for.")
1850    else:
1851        print("  measured through the engine's own serve protocol, which is not what a user waits")
1852        print("  for. Confirm any recommendation with --mode api before trusting it.")
1853    print("  Apply it as a separate reviewed step: strata tune apply <job>. No profile has changed.")
1854    print(f"  report: strata tune status {result['id']}")
1855    return 0
1856
1857
1858def _tune_apply(a: argparse.Namespace, *, store_root: Path) -> int:
1859    """Apply a recommendation to a run configuration, after verifying the candidate runs.
1860
1861    The verification is a real start: the candidate configuration is booted and required to produce at
1862    least one token before the file is touched. A sweep cannot see that failure, because a sweep
1863    measures generation on a configuration it never writes.
1864    """
1865    from strata_control import tune_apply, tune_history
1866
1867    job = _load_job(store_root, a.job_id)
1868    if job is None:
1869        return _error(f"no tuning job {a.job_id} in {store_root}", 2, a.output == "json")
1870
1871    config = Path(a.config) if a.config else _find_config_for(job)
1872    if config is None or not config.exists():
1873        return _error("no run configuration found; pass --config strata-<model>.json",
1874                      2, a.output == "json")
1875
1876    identity = None
1877    if a.model_path or (job.get("plan") or {}).get("identity"):
1878        try:
1879            engine_path = Path((job.get("plan") or {}).get("engine") or "")
1880            identity = tune_history.comparison_key(
1881                engine=tune_history.file_identity(engine_path),
1882                model=tune_history.file_identity(Path(a.model_path)) if a.model_path
1883                else {"path": None, "exists": False, "method": None, "digest": None, "bytes": None},
1884                backend=(job.get("plan") or {}).get("backend") or "",
1885                workload=((job.get("report") or {}).get("metric") and
1886                          _workload_of(job)) or {},
1887                context=(job.get("plan") or {}).get("context"))
1888        except Exception:  # noqa: BLE001 - an unavailable identity means "cannot verify", below
1889            identity = None
1890
1891    # The recorded sweep has to carry a model digest before anything is written. A sweep planned
1892    # without `--model-path` records `model_digest: null`, and `null` does not equal any real digest,
1893    # so such a recommendation can never be matched to what is installed -- which means it cannot be
1894    # applied, however plausible its numbers look. This is a refusal, not a warning.
1895    recorded = ((job.get("report") or {}).get("identity") or {})
1896    if not recorded.get("model_digest"):
1897        return _error(
1898            "the sweep recorded no model digest, so its recommendation cannot be matched to the "
1899            "installed weights; re-run the sweep with --model-path and apply that result instead",
1900            2, a.output == "json")
1901    if a.model_path and identity is not None and not identity.get("model_digest"):
1902        return _error(f"no model file at {a.model_path}", 2, a.output == "json")
1903    if identity is None:
1904        return _error("the sweep's identity could not be re-derived; refusing to apply a "
1905                      "configuration that may have been measured against different bytes",
1906                      2, a.output == "json")
1907
1908    try:
1909        result = tune_apply.apply_recommendation(
1910            job=job, config_path=config, current_identity=identity, state_dir=store_root,
1911            verify=None)          # a real verification needs a model; the plan is still checked
1912    except tune_apply.ApplyError as e:
1913        return _error(str(e), e.code, a.output == "json")
1914
1915    if a.output == "json":
1916        return _success(result, machine=True)
1917    plan = result["plan"]
1918    print(f"applied to {plan['config_path']}")
1919    for item in plan["added"]:
1920        print(f"  + {item}")
1921    for item in plan["removed"]:
1922        print(f"  - {item}")
1923    print(f"  before {plan['before_sha256'][:16]}  after {plan['after_sha256'][:16]}")
1924    print(f"  rollback: strata tune rollback {result['application']['application_id']}")
1925    print()
1926    print("  The candidate was NOT verified against a running model: no supported model fits this")
1927    print("  machine. The configuration was checked for staleness, identity and diff, and the")
1928    print("  previous bytes were retained. Verify generation before relying on this configuration.")
1929    return 0
1930
1931
1932def _find_config_for(job: dict) -> Path | None:
1933    """The run configuration for the sweep's model, found next to the repository."""
1934    from strata_control import tune_apply
1935    model = (job.get("plan") or {}).get("model") or ""
1936    candidates = tune_apply.find_config_files(Path.cwd())
1937    if not candidates:
1938        return None
1939    for path in candidates:
1940        if model and model.lower() in path.stem.lower():
1941            return path
1942    return candidates[0] if len(candidates) == 1 else None
1943
1944
1945def _workload_of(job: dict) -> dict:
1946    return dict(((job.get("plan") or {}).get("identity") or {}).get("workload") or {})
1947
1948
1949def _load_job(store_root: Path, job_id: str) -> dict | None:
1950    if not re.fullmatch(r"[0-9a-f]{8,64}", str(job_id or "")):
1951        return None
1952    path = Path(store_root) / job_id / "job.json"
1953    if not path.exists():
1954        return None
1955    try:
1956        return json.loads(path.read_text(encoding="utf-8"))
1957    except (OSError, json.JSONDecodeError):
1958        return None
1959
1960
1961def _tune_rollback(a: argparse.Namespace, *, store_root: Path) -> int:
1962    from strata_control import tune_apply
1963    try:
1964        result = tune_apply.rollback(application_id=a.application_id, state_dir=store_root)
1965    except tune_apply.ApplyError as e:
1966        return _error(str(e), e.code, a.output == "json")
1967    if a.output == "json":
1968        return _success(result, machine=True)
1969    print(f"restored {result['restored']}")
1970    print(f"  application {result['application']['application_id']} marked rolled back")
1971    return 0
1972
1973
1974def _components_plan(a: argparse.Namespace) -> int:
1975    """Read a component manifest and report whether it may be used on this machine.
1976
1977    This is the input that decides what gets downloaded and unpacked, so it is read strictly and the
1978    platform and backend gates are applied before anything is fetched. An unsupported combination is
1979    reported as unsupported rather than attempted.
1980    """
1981    from strata_control import components
1982    path = Path(a.manifest)
1983    if not path.exists():
1984        return _error(f"no component manifest at {path}", 2, a.output == "json")
1985    try:
1986        component = components.parse_manifest(path.read_text(encoding="utf-8"))
1987    except components.ComponentError as e:
1988        return _error(str(e), e.code, a.output == "json")
1989
1990    target = a.target or components.host_platform()
1991    reasons = components.check_compatible(component, target=target, backend=a.backend)
1992    payload = {
1993        "id": component.id, "version": component.version, "kind": component.kind,
1994        "backend": component.backend, "target": target,
1995        "platforms": list(component.platforms), "cache_key": component.cache_key,
1996        "usable": not reasons, "reasons": reasons,
1997        "artifacts": [{"name": art.name, "bytes": art.bytes, "sha256": art.sha256,
1998                       "format": art.format} for art in component.artifacts],
1999        "total_bytes": sum(art.bytes for art in component.artifacts),
2000        "requires": list(component.requires), "entrypoint": component.entrypoint,
2001    }
2002    if a.output == "json":
2003        return _success(payload, machine=True)
2004    print(f"{component.id} {component.version}  ({component.kind}"
2005          + (f", {component.backend}" if component.backend else "") + ")")
2006    print(f"  platforms  {', '.join(component.platforms)}")
2007    print(f"  target     {target}")
2008    print(f"  payload    {payload['total_bytes'] / (1 << 20):.1f} MiB in "
2009          f"{len(component.artifacts)} artifact(s)")
2010    print(f"  cache key  {component.cache_key[:16]} (the bytes, not the version label)")
2011    if a.backend:
2012        print(f"  backend    {a.backend}")
2013    print(f"  usable     {'yes' if payload['usable'] else 'NO'}")
2014    for reason in reasons:
2015        print(f"    - {reason}")
2016    if component.requires:
2017        print(f"  requires   {', '.join(component.requires)}")
2018    print("  nothing was downloaded, unpacked or changed")
2019    return 0
2020
2021
2022def _components_engine(a: argparse.Namespace) -> int:
2023    """Which engine package the local component folder offers this PC. Read-only; a missing engine is a notice with a
2024    non-zero exit (5), never a fetch."""
2025    from strata_control import engine_component
2026    root = Path(a.components_dir) if a.components_dir else None
2027    try:
2028        report = engine_component.status(root, backend=a.backend, full=a.full)
2029    except engine_component.ComponentProblem as exc:
2030        return _error(str(exc), 2, a.output == "json")
2031    code = 0 if report["usable"] else 5
2032    if a.output == "json":
2033        print(json.dumps({"schema_version": 1, "ok": report["usable"], **report}, ensure_ascii=False))
2034        return code
2035    print(f"component folder  {report['components_dir']}")
2036    print(f"this PC           {report['platform']}, {report['backend'] or 'no GPU found'} ({report['backend_source']})")
2037    for item in report["installed"]:
2038        print(f"  installed       {item['version']} {item['platform']}-{item['backend']}  {item['root']}")
2039    for item in report["problems"]:
2040        print(f"  unusable        {item['folder']}: {item['problem']}")
2041    if report["usable"]:
2042        print(f"engine            {report['engine']['exe']}  (version {report['engine']['version']})")
2043    else:
2044        print(report["notice"], file=sys.stderr)
2045    for row in report.get("shapes") or []:             # the engines of model shapes, only on a PC that has one (strata_control/shape_engine.py)
2046        print(f"engine for {row['shape']}  " + (f"{row['engine']['exe']}  (version {row['engine']['version']})" if row["usable"] else str(row.get("notice"))))
2047    notice = engine_component.cached_notice(root)
2048    if notice:
2049        print(notice)
2050    print("nothing was downloaded or changed")
2051    return code
2052
2053
2054def _components_backends(a: argparse.Namespace) -> int:
2055    """The committed OS and backend matrix, so an unsupported combination is visible up front."""
2056    from strata_control import components
2057    here = components.host_platform()
2058    rows = []
2059    for backend, platforms in sorted(components.BACKEND_MATRIX.items()):
2060        rows.append({"backend": backend, "platforms": list(platforms), "here": here in platforms})
2061    if a.output == "json":
2062        return _success({"host": here, "matrix": rows}, machine=True)
2063    print(f"this machine is {here}")
2064    print()
2065    for row in rows:
2066        mark = "supported here" if row["here"] else "not supported here"
2067        print(f"  {row['backend']:<6} {', '.join(row['platforms']):<45} {mark}")
2068    print()
2069    print("  Unsupported combinations are not attempted. A combination that is listed but has not")
2070    print("  been qualified on real hardware is prepared, not claimed: see packaging/README.md.")
2071    return 0
2072
2073
2074def _install(a: argparse.Namespace) -> int:
2075    """The one place the terminal acquires anything: it hands over to the installer (setup.py) of a full Strata
2076    folder, which is where pip, the engine and the models are fetched. A folder without it (the terminal archive)
2077    says so and names what to do instead."""
2078    installer = Path(os.environ.get("STRATA_INSTALL_DIR") or ROOT) / "setup.py"
2079    if not installer.is_file():
2080        return _error("this folder has no installer (setup.py). Engines, models and updates are installed from a "
2081                      "full Strata folder with SETUP.bat / ./setup.sh and UPDATE.bat / ./update.sh; "
2082                      "set STRATA_INSTALL_DIR to that folder to run it from here. To update the engine and Control "
2083                      "from the signed update feed, run `strata update`", 5)
2084    extra = [x for x in a.setup_args if x != "--"]
2085    env = dict(os.environ)
2086    if (ROOT / "python").is_dir() and (ROOT / "VERSION").is_file():
2087        # the Terminal bundle: its installer only downloads and prepares the model (no pip, no engine fetch, no compiler)
2088        env["STRATA_CONTROL_INSTALL"] = "1"
2089        from strata_cli.launch.catalog import install_root
2090        env.setdefault("STRATA_INSTALL_DIR", str(install_root()))
2091    return subprocess.call([sys.executable, str(installer), "--update" if a.update else "--setup", *extra],
2092                           cwd=str(installer.parent), env=env)
2093
2094
2095def _access_retry(a: argparse.Namespace, error: BaseException) -> int | None:
2096    """A file in Strata's own per-user folders that this user cannot open (a run as administrator made it) is repaired once
2097    and the command runs again; if that does not help the person gets one plain sentence, with the technical text after it."""
2098    try:
2099        from strata_control import private_files
2100    except ImportError:
2101        return None
2102    if not (isinstance(error, PermissionError) or "PermissionError" in str(error)):
2103        return None
2104    as_json = bool(getattr(a, "json", False) or getattr(a, "output", None) in ("json", "jsonl"))
2105    in_use = private_files.is_sharing_violation(error)
2106    if getattr(a, "_access_retried", False):
2107        message = private_files.IN_USE_MESSAGE if in_use else private_files.ACCESS_MESSAGE
2108        return _error(f"{message} (details: {error})", 5, as_json)
2109    a._access_retried = True
2110    if in_use:
2111        time.sleep(1.5)                                  # a scanner or a sync tool lets go of the file in a moment; repairing would not help
2112    else:
2113        private_files.repair_known_roots()
2114    return _run(a)
2115
2116
2117def _repair_access(a: argparse.Namespace) -> int:
2118    from strata_control import private_files
2119    report = private_files.repair_known_roots()
2120    if getattr(a, "output", "human") == "json":
2121        print(json.dumps({"ok": not report["failed"], **report}))
2122    else:
2123        print(f"checked {report['checked']} entries, repaired {report['repaired']}, could not repair {report['failed']}")
2124        if report["failed"]:
2125            print(private_files.ACCESS_MESSAGE)
2126    return 0 if not report["failed"] else 5
2127
2128
2129def _run(a: argparse.Namespace) -> int:
2130    try:
2131        if a.command == "serve":
2132            return _serve(a)
2133        if a.command == "install":
2134            return _install(a)
2135        if a.command == "repair-access":
2136            return _repair_access(a)
2137        if a.command == "profile":
2138            return _profile_command(a)
2139        if a.command == "components" and a.components_command == "plan":
2140            return _components_plan(a)
2141        if a.command == "components" and a.components_command == "backends":
2142            return _components_backends(a)
2143        if a.command == "components" and a.components_command == "engine":
2144            return _components_engine(a)
2145        if a.command == "update" or (a.command == "components" and a.components_command in ("update", "rollback", "install-file", "engines", "use", "remove")):
2146            from strata_cli import update_cmd
2147            return update_cmd.run(a)
2148        if a.command in ("doctor", "components"):
2149            return _doctor(a)
2150        if a.command == "models":
2151            return _models(a)
2152        if a.command == "engine":
2153            return _calibration(a)
2154        if a.command == "drafting":
2155            from strata_cli import drafting_cmd as _drafting_cmd
2156            return _drafting_cmd.run(a)
2157        if a.command == "split-engine":
2158            from strata_cli import split_cmd as _split_cmd
2159            return _split_cmd.run(a)
2160        if a.command == "bench":
2161            return _bench(a)
2162        if a.command == "timeskip":
2163            return _timeskip(a)
2164        if a.command == "presets":
2165            return tune_commands.presets_command(a)
2166        if a.command in ("launch", "connect"):
2167            from strata_cli.launch import cmd as launch_cmd
2168            return launch_cmd.run_launch(a) if a.command == "launch" else launch_cmd.run_connect(a)
2169        if a.command == "tune":
2170            return _tune(a)
2171        if a.command == "runtime":
2172            return _runtime(a)
2173        if a.command == "ops":
2174            return _ops(a)
2175        if a.command == "code":
2176            return _error("the shared Desktop harness component is not installed; coding sessions are unavailable", 5,
2177                          getattr(a, "output", None) in ("json", "jsonl"))
2178        return monitor_commands.run(a)
2179    except ValueError as e:
2180        retried = _access_retry(a, e)
2181        if retried is not None:
2182            return retried
2183        if a.command == "serve" and a.output == "jsonl":
2184            return _serve_error(a, str(e), getattr(e, "exit_code", 2))
2185        return _error(str(e), getattr(e, "exit_code", 2),
2186                      bool(getattr(a, "json", False) or getattr(a, "output", None) in ("json", "jsonl")))
2187    except BrokenPipeError:
2188        return 0
2189    except OSError as e:
2190        retried = _access_retry(a, e)
2191        if retried is not None:
2192            return retried
2193        if a.command == "serve" and a.output == "jsonl":
2194            return _serve_error(a, _file_words(e), 6)
2195        return _error(_file_words(e), 6,
2196                      bool(getattr(a, "output", None) in ("json", "jsonl")))
2197    except ClientError as e:
2198        if a.command == "serve" and a.output == "jsonl":
2199            return _serve_error(a, str(e), e.exit_code)
2200        return _error(str(e), e.exit_code,
2201                      bool(getattr(a, "json", False) or getattr(a, "output", None) in ("json", "jsonl")))
2202    except KeyboardInterrupt:
2203        if a.command == "serve" and a.output == "jsonl":
2204            return _serve_error(a, "interrupted; operation completion may be unknown", 130)
2205        return _error("interrupted; operation completion may be unknown", 130,
2206                      bool(getattr(a, "json", False) or getattr(a, "output", None) in ("json", "jsonl")))
2207
2208
2209class _QuietCapture:
2210    """Keep the last human output to show only when an operation fails."""
2211
2212    def __init__(self, limit: int = 64 * 1024):
2213        self.limit = limit
2214        self.text = ""
2215        self.truncated = False
2216
2217    def write(self, value: str) -> int:
2218        if len(self.text) + len(value) > self.limit:
2219            self.truncated = True
2220        self.text = (self.text + value)[-self.limit:]
2221        return len(value)
2222
2223    def flush(self) -> None:
2224        pass
2225
2226    def getvalue(self) -> str:
2227        return self.text
2228
2229
2230def _install_argv(argv: list[str]) -> list[str]:
2231    """`strata install` hands everything after it to setup.py (`strata install --family qwen --model IQ3_XXS --yes`). argparse cannot do that
2232    by itself: an option it does not know ahead of the first plain word (--source, --family) was refused as "unrecognized arguments", or
2233    split from its value (#4188). So the options of setup.py go behind a `--`, and only `--update` and --help stay strata's own."""
2234    if not argv or argv[0] != "install":
2235        return argv
2236    rest = list(argv[1:])
2237    if rest and rest[0] in ("-h", "--help"):
2238        return argv
2239    update = "--update" in rest
2240    if update:
2241        rest.remove("--update")
2242    return ["install", *(["--update"] if update else []), "--", *rest]
2243
2244
2245def main(argv: list[str] | None = None) -> int:
2246    try:
2247        from strata_control.childenv import quiet_crash_env
2248        quiet_crash_env()                        # every program Strata starts inherits it: ggml never starts gdb on a user's machine
2249    except ImportError:                          # a thin bundle ships without strata_control
2250        pass
2251    try:
2252        from strata_control import private_files
2253        private_files.adopt_user_defaults()      # what this process creates belongs to the user even when it runs as administrator
2254    except ImportError:                          # a thin bundle ships without strata_control
2255        pass
2256    ap = parser()
2257    raw = list(sys.argv[1:] if argv is None else argv)
2258    a, extras = ap.parse_known_args(_install_argv(raw))
2259    a.raw_argv = raw
2260    if extras:
2261        if getattr(a, "command", None) in ("launch", "connect"):
2262            from strata_cli.launch import cmd as launch_cmd
2263            print("strata: " + launch_cmd.unknown_option_message(a.command, extras, ap), file=sys.stderr)
2264            return 2
2265        ap.error("unrecognized arguments: " + " ".join(extras))
2266    if getattr(a, "json", False) and a.command not in ("status", "monitor", "logs", "connection", "config"):
2267        if a.output == "jsonl":
2268            return _serve_error(a, "--json is one-shot only; use --output jsonl for foreground events")
2269        a.output = "json"
2270    if not getattr(a, "quiet", False) or getattr(a, "output", "human") in ("json", "jsonl"):
2271        return _run(a)
2272    if a.command in ("status", "monitor", "logs", "connection", "config") or \
2273            (a.command == "serve" and not a.plan):
2274        return _run(a)
2275    captured = _QuietCapture()
2276    with contextlib.redirect_stdout(captured):
2277        code = _run(a)
2278    if code and captured.getvalue():
2279        if captured.truncated:
2280            sys.stderr.write("strata: earlier human output omitted in quiet mode\n")
2281        sys.stderr.write(captured.getvalue())
2282    return code