trimrig 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,207 @@
1
+ Metadata-Version: 2.4
2
+ Name: trimrig
3
+ Version: 0.1.0
4
+ Summary: The Trimrig command line: workstreams, Blueprints, runs and shipping, from your terminal or CI.
5
+ Author: Nyvix
6
+ License-Expression: LicenseRef-Proprietary
7
+ Project-URL: Homepage, https://trimrig.com
8
+ Project-URL: Documentation, https://trimrig.com/#/help
9
+ Keywords: trimrig,ai evaluation,benchmarks,tasks,cli
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Environment :: Console
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Intended Audience :: Developers
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ Requires-Dist: typer>=0.12
17
+ Requires-Dist: httpx>=0.27
18
+ Requires-Dist: keyring>=25
19
+ Provides-Extra: dev
20
+ Requires-Dist: pytest>=8; extra == "dev"
21
+
22
+ # trimrig
23
+
24
+ The command line for [Trimrig](https://trimrig.com): manage workstreams from your terminal or CI. It is a client of Trimrig's public REST API and follows the same rules as the web app, roles included.
25
+
26
+ > Status: v0.1. Commands: `login`, `logout`, `whoami`, `workspace list|use`, `workstream list|archive|restore|delete`, `frame show|export|import|approve`, `run`, `status`, `ship`.
27
+
28
+ ## Install
29
+
30
+ ```sh
31
+ pip install trimrig # or: pipx install trimrig
32
+ trimrig --version
33
+ ```
34
+
35
+ Python 3.10 or newer. Upgrade with `pip install -U trimrig`.
36
+
37
+ ## Sign in
38
+
39
+ On your own computer:
40
+
41
+ ```sh
42
+ trimrig login
43
+ # Your code: BCDF-GHJK
44
+ # Approve it at https://trimrig.com/#/cli/approve/BCDF-GHJK
45
+ ```
46
+
47
+ Your browser opens; check that the code matches, pick the organization, and click **Approve**. The CLI receives a token and keeps it in your system keychain (Keychain on macOS, Credential Manager on Windows, Secret Service on Linux), never in a plain file.
48
+
49
+ ```sh
50
+ trimrig whoami # Ada Lovelace · Acme · admin (token from keychain)
51
+ trimrig logout # removes it from this computer
52
+ ```
53
+
54
+ `logout` only forgets the token on this computer. To switch it off everywhere, revoke it in **Settings → API tokens**.
55
+
56
+ ### In CI
57
+
58
+ Create a token in **Settings → API tokens** (it's shown once) and set it as a secret:
59
+
60
+ ```yaml
61
+ # GitHub Actions
62
+ env:
63
+ TRIMRIG_TOKEN: ${{ secrets.TRIMRIG_TOKEN }}
64
+ steps:
65
+ - run: pip install trimrig
66
+ - run: trimrig workstream list --json
67
+ ```
68
+
69
+ `TRIMRIG_TOKEN` always wins over a saved sign-in. A token acts as the person who created it, in that organization, with their current role.
70
+
71
+ ## Workstreams
72
+
73
+ ```sh
74
+ trimrig workstream list # active ones
75
+ trimrig workstream list --archived
76
+ trimrig workstream list --deleted # Admins: deleted in the last 30 days
77
+
78
+ trimrig workstream archive "Invoice Recon" # hide it; nothing is deleted
79
+ trimrig workstream restore "Invoice Recon" # from archived, or from deleted within 30 days (Admins)
80
+
81
+ trimrig workstream delete "Invoice Recon" # Admins
82
+ # This removes 2 runs, 5 tasks, 12 trials, 1 Blueprint versions, 3 sources and 17 stored files from Invoice Recon.
83
+ # It can be restored for 30 days (Settings → Deleted, or `trimrig workstream restore`).
84
+ # Type Invoice Recon to confirm: Invoice Recon
85
+ # Deleted Invoice Recon. Restorable until 2026-12-18.
86
+ ```
87
+
88
+ A workstream can be named by its exact name (any case), its id, or the first 8+ characters of its id. Delete is refused while a run is queued or running.
89
+
90
+ ## Blueprints (`frame`)
91
+
92
+ A workstream's Blueprint says what every task must look like: the folder structure, the rules, and the difficulty test. Runs are always built from an approved version.
93
+
94
+ ```sh
95
+ trimrig frame show "Invoice Recon" # the latest approved version
96
+ trimrig frame show "Invoice Recon" --draft # the draft being edited, with its open questions
97
+ trimrig frame show "Invoice Recon" -v 1.0 # a specific version
98
+
99
+ trimrig frame export "Invoice Recon" -o invoice-recon.json # keep it in git
100
+ trimrig frame import "Invoice Recon" invoice-recon.json # replace the draft with a file
101
+ trimrig frame import "Invoice Recon EU" invoice-recon.json --create # a new workstream from it
102
+
103
+ trimrig frame approve "Invoice Recon"
104
+ # 1 question to answer before approving:
105
+ # Q1 Which Python?
106
+ # 1. Python 3.12
107
+ # 2. Python 3.11
108
+ # Your answer (a number or your own words): 1
109
+ # Approved Invoice Recon Blueprint v2.0.
110
+ ```
111
+
112
+ In CI, answer open questions up front: `trimrig frame approve "Invoice Recon" --answer Q1="Python 3.12" --answer C1="Omit it"`. Without them `approve` exits with code 2 and lists what's open. An exported file keeps its answers, so importing it and approving again doesn't ask them twice.
113
+
114
+ ## Runs
115
+
116
+ ```sh
117
+ trimrig run --blueprint "Invoice Recon@1.0" --n 20 # @version optional: the latest approved
118
+ # Started run #3 of Invoice Recon from Blueprint v1.0: 20 tasks.
119
+
120
+ trimrig status # the run you just started
121
+ trimrig status "Invoice Recon#3" # or any run, by workstream and number (or its id)
122
+ trimrig status --watch # follow it until it ends
123
+ # Run #3 of Invoice Recon · Blueprint v1.0 · running · 12 building
124
+ # Run #3 of Invoice Recon · Blueprint v1.0 · finished · 17 ready, 3 review
125
+ # INV-014 in Review: Too easy for Route A: harden and re-test.
126
+
127
+ trimrig ship # the ready tasks as a ZIP, shipped as batch 1
128
+ # Saved invoice-recon-run3-batch1.zip (842 KB).
129
+ # Shipped batch 1: marked 17 tasks as shipped.
130
+ ```
131
+
132
+ `run` options: `--difficulty Easy|Medium|Hard|Mixed`, `--diversity Focused|Balanced|Wide`, `--repairs 0-5` (attempts before a task goes to Review), `--no-difficulty-test`, and `--watch` to start and follow in one go.
133
+
134
+ `status --watch` (and `run --watch`) exits 0 when the run finishes and 1 if it fails or stops (for example when a budget runs out), so CI can wait on it:
135
+
136
+ ```sh
137
+ trimrig run -b "Invoice Recon" --n 50 --watch && trimrig ship -o tasks.zip
138
+ ```
139
+
140
+ The ZIP has one folder per task (named by its code; `INV-014-r2` for a later revision) plus `manifest.json`: the Blueprint name and version, the run and batch, who shipped it and when, and for each task its revision, a SHA-256 per file and a content hash, its check results, and the difficulty verdict with each route's pass rate.
141
+
142
+ `ship` needs an Admin or Builder. It ships only what's ready and not yet shipped, as the run's next batch, and marks those tasks **Shipped** (one audit entry per batch). If two people ship at once, one gets the batch and the other is told there's nothing new. Shipped tasks never change: editing or re-proving one makes a new revision, which ships in a later batch.
143
+
144
+ ```sh
145
+ trimrig ship --again latest # the last batch again, byte for byte as shipped
146
+ trimrig ship --again 1 # batch 1
147
+ trimrig ship --again all # every shipped batch in one ZIP
148
+ trimrig ship --no-mark # a copy of what's ready now; marks nothing
149
+ ```
150
+
151
+ `--again` and `--no-mark` mark nothing, and anyone who can see the run may use them. The web app's Ship page (Run → **Ship N ready** / **Ship N new**) does the same.
152
+
153
+ ## Workspaces
154
+
155
+ ```sh
156
+ trimrig workspace list
157
+ trimrig workspace use Finance # the default for every command
158
+ trimrig workspace use none # clear it
159
+ trimrig workstream list -w Biology # or per command
160
+ ```
161
+
162
+ ## Flags on every command
163
+
164
+ | Flag | What it does |
165
+ |---|---|
166
+ | `--workspace NAME`, `-w` | Work in one workspace (name or id) |
167
+ | `--json` | Print JSON, for scripts; errors become `{"error": "...", "code": n}` |
168
+ | `--yes`, `-y` | Skip confirmation prompts (needed for `delete` outside a terminal) |
169
+
170
+ They work before or after the command: `trimrig --json workstream list` and `trimrig workstream list --json` are the same.
171
+
172
+ ## Exit codes
173
+
174
+ | Code | Meaning |
175
+ |---|---|
176
+ | 0 | OK |
177
+ | 1 | Error (for example a run is still active, or Trimrig couldn't be reached) |
178
+ | 2 | Bad input (a malformed request, a confirmation name that doesn't match, an ambiguous name) |
179
+ | 3 | Not found, or no permission (including not signed in, or a revoked token) |
180
+
181
+ ## Configuration
182
+
183
+ | Variable | Default |
184
+ |---|---|
185
+ | `TRIMRIG_TOKEN` | the token saved by `trimrig login` |
186
+ | `TRIMRIG_API_URL` | `https://api.trimrig.com` |
187
+ | `TRIMRIG_CONFIG_DIR` | your user config folder (`%APPDATA%\trimrig`, `~/.config/trimrig`) |
188
+
189
+ The config folder holds only preferences (organization name, default workspace), no secrets.
190
+
191
+ ## Development
192
+
193
+ ```sh
194
+ pip install -e "cli[dev]" # plus the backend's requirements, for the local API
195
+ python -m pytest cli/tests -q
196
+ ```
197
+
198
+ The tests start Trimrig's real API locally (with in-memory stand-ins for the database) and drive the CLI against it over HTTP.
199
+
200
+ ## Releasing
201
+
202
+ Publishing to PyPI is done by GitHub Actions (`.github/workflows/publish-cli.yml`) when a tag
203
+ like `cli-v0.1.1` is pushed. PyPI trusts that workflow directly, so no PyPI token is stored.
204
+
205
+ 1. Raise the version in `pyproject.toml` and `src/trimrig_cli/__init__.py` (they must match).
206
+ 2. Commit, then tag and push: `git tag cli-v0.1.1; git push origin cli-v0.1.1`.
207
+ 3. The workflow checks the tag matches the version, runs the tests, builds and publishes.
@@ -0,0 +1,9 @@
1
+ trimrig_cli/__init__.py,sha256=EbtV1ErDQckk7zlqceZHK1CHHyAI7_h_bqjXZKPpClc,99
2
+ trimrig_cli/client.py,sha256=RYhLb4BvjSFz1lddeSC3E0xzQS__5ricxTYIFDfXy44,4229
3
+ trimrig_cli/config.py,sha256=hCOZP6EGZcxA-J05iT6hLzHUfxlka7uPZ43FpyZLPUA,2903
4
+ trimrig_cli/main.py,sha256=OxBq1cW4lULNsmz6fMeDV6_h0XtIscifwzdJsVn96G4,33678
5
+ trimrig-0.1.0.dist-info/METADATA,sha256=uqDYp4ySukbCNVbGQuAIQr6ycUi2qCihVghk9dxaB60,8944
6
+ trimrig-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ trimrig-0.1.0.dist-info/entry_points.txt,sha256=dzCDcVYi73FQzHvPlrLnLq-SHwnCtDcj06zR6tP4_-w,49
8
+ trimrig-0.1.0.dist-info/top_level.txt,sha256=EvHDMjSYupRE1spMZfBGU321vT1p9ogKM6vJAX1UAfE,12
9
+ trimrig-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ trimrig = trimrig_cli.main:run
@@ -0,0 +1 @@
1
+ trimrig_cli
@@ -0,0 +1,3 @@
1
+ """The trimrig command line. A client of Trimrig's public REST API only."""
2
+
3
+ __version__ = "0.1.0"
trimrig_cli/client.py ADDED
@@ -0,0 +1,101 @@
1
+ """Talking to Trimrig's REST API, and turning its answers into exit codes.
2
+
3
+ Exit codes (stable, for scripts and CI):
4
+ 0 ok
5
+ 1 error (the API refused for another reason, a run is active, network trouble…)
6
+ 2 bad input (a malformed request, the wrong confirmation name)
7
+ 3 not found, or no permission (including not signed in)
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Any
13
+
14
+ import httpx
15
+
16
+ from . import __version__, config
17
+
18
+ OK, ERROR, BAD_INPUT, NOT_FOUND = 0, 1, 2, 3
19
+
20
+
21
+ class CliError(Exception):
22
+ def __init__(self, message: str, code: int = ERROR, data: dict | None = None) -> None:
23
+ super().__init__(message)
24
+ self.code = code
25
+ self.data = data or {} # the API's structured detail, e.g. open_questions
26
+
27
+
28
+ def _message(r: httpx.Response) -> str:
29
+ try:
30
+ j = r.json()
31
+ except ValueError:
32
+ return f"{r.status_code} {r.reason_phrase}"
33
+ d = j.get("detail") if isinstance(j, dict) else None
34
+ if isinstance(d, dict):
35
+ return str(d.get("message") or d.get("error") or d)
36
+ if isinstance(d, list): # FastAPI validation errors
37
+ return "; ".join(str(x.get("msg", x)) for x in d)
38
+ return str(d or j)
39
+
40
+
41
+ def code_for(status: int) -> int:
42
+ if status in (401, 403, 404):
43
+ return NOT_FOUND
44
+ if status in (400, 422):
45
+ return BAD_INPUT
46
+ return ERROR
47
+
48
+
49
+ class Api:
50
+ def __init__(self, base: str | None = None, token: str | None = None, transport: httpx.BaseTransport | None = None) -> None:
51
+ self.base = (base or config.api_url()).rstrip("/")
52
+ self.token = token
53
+ self._http = httpx.Client(base_url=self.base, timeout=60, transport=transport, headers={"User-Agent": f"trimrig-cli/{__version__}"})
54
+
55
+ def _headers(self) -> dict[str, str]:
56
+ return {"Authorization": f"Bearer {self.token}"} if self.token else {}
57
+
58
+ def request(self, method: str, path: str, *, json: Any = None, params: dict | None = None, auth: bool = True) -> Any:
59
+ if auth and not self.token:
60
+ raise CliError("You’re not signed in. Run `trimrig login`, or set TRIMRIG_TOKEN (Settings → API tokens).", NOT_FOUND)
61
+ try:
62
+ r = self._http.request(method, path, json=json, params={k: v for k, v in (params or {}).items() if v is not None}, headers=self._headers() if auth else {})
63
+ except httpx.HTTPError as e:
64
+ raise CliError(f"Couldn’t reach Trimrig at {self.base}: {type(e).__name__}. Check your connection, or TRIMRIG_API_URL.") from None
65
+ if r.status_code >= 400:
66
+ detail = {}
67
+ try:
68
+ d = r.json().get("detail")
69
+ detail = d if isinstance(d, dict) else {}
70
+ except (ValueError, AttributeError):
71
+ pass
72
+ raise CliError(_message(r), code_for(r.status_code), detail)
73
+ return r.json() if r.content else {}
74
+
75
+ def get(self, path: str, **kw) -> Any:
76
+ return self.request("GET", path, **kw)
77
+
78
+ def post(self, path: str, **kw) -> Any:
79
+ return self.request("POST", path, **kw)
80
+
81
+ def download(self, path: str, method: str = "GET") -> tuple[bytes, str | None, dict]:
82
+ """A file (the ship ZIP): its bytes, the name the API suggests, and the headers."""
83
+ if not self.token:
84
+ raise CliError("You’re not signed in. Run `trimrig login`, or set TRIMRIG_TOKEN.", NOT_FOUND)
85
+ try:
86
+ r = self._http.request(method, path, headers=self._headers(), timeout=600)
87
+ except httpx.HTTPError as e:
88
+ raise CliError(f"Couldn’t reach Trimrig at {self.base}: {type(e).__name__}.") from None
89
+ if r.status_code >= 400:
90
+ raise CliError(_message(r), code_for(r.status_code))
91
+ import re
92
+
93
+ m = re.search(r'filename="([^"]+)"', r.headers.get("content-disposition", ""))
94
+ return r.content, (m.group(1) if m else None), dict(r.headers)
95
+
96
+ def raw_post(self, path: str, json: Any) -> httpx.Response:
97
+ """For polling where a 400 is an expected answer (the device sign-in)."""
98
+ try:
99
+ return self._http.post(path, json=json)
100
+ except httpx.HTTPError as e:
101
+ raise CliError(f"Couldn’t reach Trimrig at {self.base}: {type(e).__name__}.") from None
trimrig_cli/config.py ADDED
@@ -0,0 +1,100 @@
1
+ """Where the CLI keeps things.
2
+
3
+ - The API address: TRIMRIG_API_URL, else https://api.trimrig.com.
4
+ - The token: TRIMRIG_TOKEN (for CI) wins; otherwise the one `trimrig login` saved
5
+ in the OS keychain (Keychain on macOS, Credential Manager on Windows, Secret
6
+ Service on Linux). It is never written to a plain file.
7
+ - Small preferences (the organization you're signed in to, the default
8
+ workspace): a JSON file in the user's config folder. No secrets in it.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import os
15
+ import sys
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ DEFAULT_API = "https://api.trimrig.com"
20
+ KEYRING_SERVICE = "trimrig"
21
+
22
+
23
+ def api_url() -> str:
24
+ return (os.environ.get("TRIMRIG_API_URL") or DEFAULT_API).rstrip("/")
25
+
26
+
27
+ def config_dir() -> Path:
28
+ if os.environ.get("TRIMRIG_CONFIG_DIR"):
29
+ return Path(os.environ["TRIMRIG_CONFIG_DIR"])
30
+ if sys.platform == "win32":
31
+ return Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming") / "trimrig"
32
+ return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "trimrig"
33
+
34
+
35
+ def _file() -> Path:
36
+ return config_dir() / "config.json"
37
+
38
+
39
+ def load() -> dict[str, Any]:
40
+ try:
41
+ return json.loads(_file().read_text(encoding="utf-8"))
42
+ except (OSError, ValueError):
43
+ return {}
44
+
45
+
46
+ def save(**changes: Any) -> None:
47
+ data = load()
48
+ for k, v in changes.items():
49
+ if v is None:
50
+ data.pop(k, None)
51
+ else:
52
+ data[k] = v
53
+ _file().parent.mkdir(parents=True, exist_ok=True)
54
+ _file().write_text(json.dumps(data, indent=2), encoding="utf-8")
55
+
56
+
57
+ class KeychainUnavailable(Exception):
58
+ pass
59
+
60
+
61
+ def _keyring():
62
+ try:
63
+ import keyring
64
+ from keyring.errors import KeyringError, NoKeyringError # noqa: F401
65
+ except ImportError as e: # pragma: no cover - keyring is a dependency
66
+ raise KeychainUnavailable("The keyring package isn’t installed.") from e
67
+ return keyring
68
+
69
+
70
+ def stored_token() -> str | None:
71
+ try:
72
+ return _keyring().get_password(KEYRING_SERVICE, api_url())
73
+ except Exception:
74
+ return None
75
+
76
+
77
+ def store_token(token: str) -> None:
78
+ try:
79
+ _keyring().set_password(KEYRING_SERVICE, api_url(), token)
80
+ except Exception as e:
81
+ raise KeychainUnavailable(
82
+ "Couldn’t save the token in your system keychain. On a server or in CI, create a token in "
83
+ "Settings → API tokens and set TRIMRIG_TOKEN instead."
84
+ ) from e
85
+
86
+
87
+ def forget_token() -> bool:
88
+ try:
89
+ _keyring().delete_password(KEYRING_SERVICE, api_url())
90
+ return True
91
+ except Exception:
92
+ return False
93
+
94
+
95
+ def token() -> tuple[str | None, str]:
96
+ """The token to use, and where it came from ('env' or 'keychain')."""
97
+ env = os.environ.get("TRIMRIG_TOKEN", "").strip()
98
+ if env:
99
+ return env, "env"
100
+ return stored_token(), "keychain"
trimrig_cli/main.py ADDED
@@ -0,0 +1,698 @@
1
+ """trimrig: the command line for Trimrig.
2
+
3
+ trimrig login sign in through your browser
4
+ trimrig workstream list your workstreams
5
+ trimrig workstream archive NAME hide one (restore any time)
6
+ trimrig workstream delete NAME Admins; asks you to type the name
7
+
8
+ Every command takes --workspace, --json and --yes. Exit codes: 0 ok, 1 error,
9
+ 2 bad input, 3 not found or no permission.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import functools
15
+ import json as jsonlib
16
+ import platform
17
+ import sys
18
+ import time
19
+ import webbrowser
20
+ from datetime import datetime, timezone
21
+ from typing import Annotated, Any, Callable, Optional
22
+
23
+ import typer
24
+
25
+ from . import __version__, config
26
+ from .client import BAD_INPUT, ERROR, NOT_FOUND, Api, CliError
27
+
28
+ app = typer.Typer(help="Trimrig from your terminal or CI: workstreams, Blueprints, runs and shipping.", no_args_is_help=True, add_completion=False)
29
+ workstream_app = typer.Typer(help="List, archive, restore and delete workstreams.", no_args_is_help=True)
30
+ workspace_app = typer.Typer(help="Workspaces in your organization.", no_args_is_help=True)
31
+ app.add_typer(workstream_app, name="workstream")
32
+ app.add_typer(workspace_app, name="workspace")
33
+
34
+ # ── Shared flags (accepted on every command, and before the command) ─────────
35
+
36
+ Workspace = Annotated[Optional[str], typer.Option("--workspace", "-w", help="Workspace name or id (default: `trimrig workspace use`).")]
37
+ Json = Annotated[bool, typer.Option("--json", help="Print JSON instead of text.")]
38
+ Yes = Annotated[bool, typer.Option("--yes", "-y", help="Don’t ask for confirmation.")]
39
+
40
+ _globals: dict[str, Any] = {"workspace": None, "json": False, "yes": False}
41
+
42
+
43
+ def _version(value: bool) -> None:
44
+ if value:
45
+ typer.echo(f"trimrig {__version__}")
46
+ raise typer.Exit()
47
+
48
+
49
+ @app.callback()
50
+ def _main(
51
+ workspace: Workspace = None,
52
+ json: Json = False,
53
+ yes: Yes = False,
54
+ version: Annotated[bool, typer.Option("--version", help="Show the version.", is_eager=True, callback=_version)] = False,
55
+ ) -> None:
56
+ _globals.update(workspace=workspace, json=json, yes=yes)
57
+
58
+
59
+ def _flags(workspace: str | None, json: bool, yes: bool) -> tuple[str | None, bool, bool]:
60
+ return (workspace or _globals["workspace"] or config.load().get("workspace"), json or _globals["json"], yes or _globals["yes"])
61
+
62
+
63
+ def handled(fn: Callable) -> Callable:
64
+ """Print errors plainly (or as JSON) and exit with the stable code."""
65
+
66
+ @functools.wraps(fn)
67
+ def wrapper(*a, **kw):
68
+ try:
69
+ return fn(*a, **kw)
70
+ except CliError as e:
71
+ if kw.get("json") or _globals["json"]:
72
+ typer.echo(jsonlib.dumps({"error": str(e), "code": e.code}))
73
+ else:
74
+ typer.secho(f"Error: {e}", err=True, fg=typer.colors.RED)
75
+ raise typer.Exit(e.code)
76
+
77
+ return wrapper
78
+
79
+
80
+ def interactive() -> bool:
81
+ """Is someone at a terminal to answer a prompt? (CI and pipes: no.)"""
82
+ return sys.stdin.isatty()
83
+
84
+
85
+ def api(auth: bool = True) -> Api:
86
+ tok, _ = config.token()
87
+ return Api(token=tok if auth else None)
88
+
89
+
90
+ def out(data: Any, json: bool, text: Callable[[], None]) -> None:
91
+ if json:
92
+ typer.echo(jsonlib.dumps(data, indent=2, default=str))
93
+ else:
94
+ text()
95
+
96
+
97
+ def ago(iso: str | None) -> str:
98
+ if not iso:
99
+ return ""
100
+ try:
101
+ t = datetime.fromisoformat(iso.replace("Z", "+00:00"))
102
+ except ValueError:
103
+ return iso
104
+ s = (datetime.now(timezone.utc) - t).total_seconds()
105
+ for unit, n in (("d", 86400), ("h", 3600), ("m", 60)):
106
+ if s >= n:
107
+ return f"{int(s // n)}{unit} ago"
108
+ return "just now"
109
+
110
+
111
+ # ── Sign-in ───────────────────────────────────────────────────────────────────
112
+
113
+
114
+ @app.command()
115
+ @handled
116
+ def login(workspace: Workspace = None, json: Json = False, yes: Yes = False, no_browser: Annotated[bool, typer.Option("--no-browser", help="Print the link instead of opening it.")] = False) -> None:
117
+ """Sign in through your browser. The token is kept in your system keychain."""
118
+ workspace, json, yes = _flags(workspace, json, yes)
119
+ a = api(auth=False)
120
+ start = a.post("/cli/device", json={"client_name": f"trimrig on {platform.node() or 'this computer'}"[:80]}, auth=False)
121
+ if not json:
122
+ typer.echo(f"Your code: {start['user_code']}")
123
+ typer.echo(f"Approve it at {start['verification_url']}")
124
+ if not no_browser:
125
+ try:
126
+ webbrowser.open(start["verification_url"])
127
+ except Exception:
128
+ pass
129
+ deadline = time.monotonic() + int(start.get("expires_in", 600))
130
+ while time.monotonic() < deadline:
131
+ time.sleep(max(1, int(start.get("interval", 3))))
132
+ r = a.raw_post("/cli/device/token", json={"device_code": start["device_code"]})
133
+ if r.status_code == 200:
134
+ got = r.json()
135
+ try:
136
+ config.store_token(got["access_token"])
137
+ except config.KeychainUnavailable as e:
138
+ raise CliError(str(e), ERROR) from None
139
+ config.save(org_id=got.get("org_id"), org_name=got.get("org_name"))
140
+ out({"signed_in": True, "org": got.get("org_name")}, json, lambda: typer.echo(f"Signed in to {got.get('org_name') or 'your organization'}. The token is in your system keychain."))
141
+ return
142
+ err = (r.json().get("detail") or {}).get("error") if r.headers.get("content-type", "").startswith("application/json") else None
143
+ if err == "pending":
144
+ continue
145
+ raise CliError({"denied": "The sign-in was denied in the browser.", "expired": "The code expired. Run `trimrig login` again."}.get(err or "", f"Sign-in failed ({err or r.status_code})."), ERROR)
146
+ raise CliError("The code expired before it was approved. Run `trimrig login` again.", ERROR)
147
+
148
+
149
+ @app.command()
150
+ @handled
151
+ def logout(workspace: Workspace = None, json: Json = False, yes: Yes = False) -> None:
152
+ """Remove the saved token from this computer."""
153
+ workspace, json, yes = _flags(workspace, json, yes)
154
+ gone = config.forget_token()
155
+ config.save(org_id=None, org_name=None)
156
+ out(
157
+ {"signed_out": gone},
158
+ json,
159
+ lambda: typer.echo("Signed out on this computer. To switch the token off everywhere, revoke it in Settings → API tokens." if gone else "There was no saved sign-in on this computer."),
160
+ )
161
+
162
+
163
+ @app.command()
164
+ @handled
165
+ def whoami(workspace: Workspace = None, json: Json = False, yes: Yes = False) -> None:
166
+ """Who you're signed in as, where, and with which role."""
167
+ workspace, json, yes = _flags(workspace, json, yes)
168
+ tok, source = config.token()
169
+ me = api().get("/me")
170
+ me["token_from"] = "TRIMRIG_TOKEN" if source == "env" else "keychain"
171
+ out(me, json, lambda: typer.echo(f"{me.get('name') or me.get('email')} · {me.get('org_name') or me.get('org_id')} · {me.get('role')} (token from {me['token_from']})"))
172
+
173
+
174
+ # ── Workspaces ────────────────────────────────────────────────────────────────
175
+
176
+
177
+ @workspace_app.command("list")
178
+ @handled
179
+ def workspace_list(workspace: Workspace = None, json: Json = False, yes: Yes = False) -> None:
180
+ """The workspaces in your organization."""
181
+ workspace, json, yes = _flags(workspace, json, yes)
182
+ rows = api().get("/workspaces")["workspaces"]
183
+
184
+ def text():
185
+ if not rows:
186
+ typer.echo("No workspaces yet: everything is in the organization as a whole.")
187
+ for w in rows:
188
+ typer.echo(f"{'*' if workspace and workspace.lower() in (w['name'].lower(), w['id']) else ' '} {w['name']} ({w['id'][:8]})")
189
+
190
+ out(rows, json, text)
191
+
192
+
193
+ @workspace_app.command("use")
194
+ @handled
195
+ def workspace_use(name: Annotated[str, typer.Argument(help="Workspace name or id; `none` to clear.")], json: Json = False, yes: Yes = False) -> None:
196
+ """Make a workspace the default for every command."""
197
+ _, json, yes = _flags(None, json, yes)
198
+ if name.lower() == "none":
199
+ config.save(workspace=None)
200
+ return out({"workspace": None}, json, lambda: typer.echo("No default workspace."))
201
+ rows = api().get("/workspaces")["workspaces"]
202
+ hit = next((w for w in rows if name.lower() in (w["name"].lower(), w["id"]) or w["id"].startswith(name)), None)
203
+ if not hit:
204
+ raise CliError(f"No workspace called {name!r}. See `trimrig workspace list`.", NOT_FOUND)
205
+ config.save(workspace=hit["name"])
206
+ out({"workspace": hit}, json, lambda: typer.echo(f"Default workspace: {hit['name']}"))
207
+
208
+
209
+ # ── Workstreams ───────────────────────────────────────────────────────────────
210
+
211
+
212
+ def _find(a: Api, ref: str, workspace: str | None, where: tuple[str, ...] = ("active", "archived")) -> dict:
213
+ """A workstream by exact name (any case), id, or id prefix (8+ characters)."""
214
+ pools = {"active": {}, "archived": {"archived": True}, "deleted": {"deleted": True}}
215
+ found: list[dict] = []
216
+ for key in where:
217
+ for w in a.get("/workstreams", params={**pools[key], "workspace": workspace})["workstreams"]:
218
+ w["state"] = key
219
+ if ref == w["id"] or (len(ref) >= 8 and w["id"].startswith(ref)) or ref.casefold() == w["name"].casefold():
220
+ found.append(w)
221
+ if not found:
222
+ raise CliError(f"No workstream called {ref!r}. See `trimrig workstream list`.", NOT_FOUND)
223
+ if len(found) > 1:
224
+ raise CliError(f"{len(found)} workstreams match {ref!r}; use the id instead: " + ", ".join(f"{w['name']} ({w['id'][:8]})" for w in found), BAD_INPUT)
225
+ return found[0]
226
+
227
+
228
+ @workstream_app.command("list")
229
+ @handled
230
+ def workstream_list(
231
+ archived: Annotated[bool, typer.Option("--archived", help="Show archived workstreams instead.")] = False,
232
+ deleted: Annotated[bool, typer.Option("--deleted", help="Show deleted ones still restorable (Admins).")] = False,
233
+ workspace: Workspace = None,
234
+ json: Json = False,
235
+ yes: Yes = False,
236
+ ) -> None:
237
+ """Your workstreams."""
238
+ workspace, json, yes = _flags(workspace, json, yes)
239
+ rows = api().get("/workstreams", params={"archived": archived or None, "deleted": deleted or None, "workspace": workspace})["workstreams"]
240
+
241
+ def text():
242
+ if not rows:
243
+ typer.echo("Nothing deleted in the last 30 days." if deleted else "Nothing archived." if archived else "No workstreams yet. Start one on trimrig.com.")
244
+ return
245
+ width = max(len(w["name"]) for w in rows)
246
+ for w in rows:
247
+ extra = f"removed for good {w['purge_after'][:10]}" if deleted else f"archived {ago(w.get('archived_at'))}" if archived else (w.get("stage") or "")
248
+ typer.echo(f"{w['name']:<{width}} {w['id'][:8]} {extra}")
249
+
250
+ out(rows, json, text)
251
+
252
+
253
+ @workstream_app.command("archive")
254
+ @handled
255
+ def workstream_archive(name: Annotated[str, typer.Argument(help="Workstream name or id.")], workspace: Workspace = None, json: Json = False, yes: Yes = False) -> None:
256
+ """Hide a workstream from lists. Nothing is deleted; restore it any time."""
257
+ workspace, json, yes = _flags(workspace, json, yes)
258
+ a = api()
259
+ w = _find(a, name, workspace, ("active", "archived"))
260
+ if w["state"] == "archived":
261
+ return out({"id": w["id"], "archived": True}, json, lambda: typer.echo(f"{w['name']} is already archived."))
262
+ a.post(f"/workstreams/{w['id']}/archive")
263
+ out({"id": w["id"], "archived": True}, json, lambda: typer.echo(f"Archived {w['name']}. Restore it with: trimrig workstream restore \"{w['name']}\""))
264
+
265
+
266
+ @workstream_app.command("restore")
267
+ @handled
268
+ def workstream_restore(name: Annotated[str, typer.Argument(help="Workstream name or id.")], workspace: Workspace = None, json: Json = False, yes: Yes = False) -> None:
269
+ """Bring back an archived workstream, or a deleted one within its 30 days (Admins)."""
270
+ workspace, json, yes = _flags(workspace, json, yes)
271
+ a = api()
272
+ try:
273
+ w = _find(a, name, workspace, ("archived", "active"))
274
+ except CliError as e:
275
+ if e.code != NOT_FOUND:
276
+ raise
277
+ w = _find(a, name, workspace, ("deleted",))
278
+ if w["state"] == "active":
279
+ return out({"id": w["id"], "restored": False}, json, lambda: typer.echo(f"{w['name']} isn’t archived or deleted."))
280
+ a.post(f"/workstreams/{w['id']}/{'undelete' if w['state'] == 'deleted' else 'restore'}")
281
+ out({"id": w["id"], "restored": True, "was": w["state"]}, json, lambda: typer.echo(f"Restored {w['name']}."))
282
+
283
+
284
+ @workstream_app.command("delete")
285
+ @handled
286
+ def workstream_delete(name: Annotated[str, typer.Argument(help="Workstream name or id.")], workspace: Workspace = None, json: Json = False, yes: Yes = False) -> None:
287
+ """Delete a workstream (Admins). Restorable for 30 days, then removed for good."""
288
+ workspace, json, yes = _flags(workspace, json, yes)
289
+ a = api()
290
+ w = _find(a, name, workspace, ("active", "archived"))
291
+ p = a.get(f"/workstreams/{w['id']}/delete-preview")
292
+ if p.get("active_runs"):
293
+ raise CliError(f"{w['name']} has a run queued or running. Stop it, or wait for it to finish, then delete.", ERROR)
294
+ if not yes:
295
+ if json or not interactive():
296
+ raise CliError("Deleting needs confirmation: run it in a terminal, or pass --yes.", BAD_INPUT)
297
+ typer.echo(
298
+ f"This removes {p['runs']} runs, {p['tasks']} tasks, {p['trials']} trials, {p['versions']} Blueprint versions, "
299
+ f"{p['sources']} sources and {p['files']} stored files from {w['name']}.\n"
300
+ "It can be restored for 30 days (Settings → Deleted, or `trimrig workstream restore`)."
301
+ )
302
+ typed = typer.prompt(f"Type {w['name']} to confirm")
303
+ if typed.strip() != w["name"]:
304
+ raise CliError("The name didn’t match, so nothing was deleted.", BAD_INPUT)
305
+ res = a.post(f"/workstreams/{w['id']}/delete", json={"confirm_name": w["name"]})
306
+ out({"id": w["id"], "deleted": True, **res}, json, lambda: typer.echo(f"Deleted {w['name']}. Restorable until {str(res.get('purge_after', ''))[:10]}."))
307
+
308
+
309
+ # ── Blueprints (frame) ────────────────────────────────────────────────────────
310
+
311
+ frame_app = typer.Typer(help="Show, export, import and approve a workstream's Blueprint.", no_args_is_help=True)
312
+ app.add_typer(frame_app, name="frame")
313
+
314
+ Version = Annotated[Optional[str], typer.Option("--version", "-v", help="A version like 1.0 (default: the latest approved).")]
315
+ Draft = Annotated[bool, typer.Option("--draft", help="The draft being edited, not an approved version.")]
316
+
317
+
318
+ def _blueprint(a: Api, name: str, workspace: str | None, version: str | None, draft: bool) -> dict:
319
+ w = _find(a, name, workspace)
320
+ return a.get(f"/workstreams/{w['id']}/blueprint", params={"version": version, "draft": draft or None})
321
+
322
+
323
+ @frame_app.command("show")
324
+ @handled
325
+ def frame_show(name: Annotated[str, typer.Argument(help="Workstream name or id.")], version: Version = None, draft: Draft = False, workspace: Workspace = None, json: Json = False, yes: Yes = False) -> None:
326
+ """The Blueprint: structure, rules, questions and the difficulty test."""
327
+ workspace, json, yes = _flags(workspace, json, yes)
328
+ b = _blueprint(api(), name, workspace, version, draft)
329
+ c = b["content"]
330
+
331
+ def text():
332
+ head = f"{b['workstream']['name']} · " + ("draft (not approved)" if b["kind"] == "draft" else f"Blueprint v{b['version']}, approved {b['approved_at'][:10]}")
333
+ typer.secho(head, bold=True)
334
+ if c.get("summary"):
335
+ typer.echo(c["summary"])
336
+ facts = c.get("facts") or {}
337
+ for k, v in (facts.items() if isinstance(facts, dict) else facts):
338
+ if v:
339
+ typer.echo(f" {str(k).capitalize()}: {v}")
340
+ typer.secho("\nStructure", bold=True)
341
+ for n in c.get("tree") or []:
342
+ typer.echo(f" {' ' * int(n.get('depth') or 0)}{n['path']} [{n.get('status', '')}]")
343
+ rules = [r for r in c.get("rules") or [] if not isinstance(r, dict) or r.get("on", True)]
344
+ if rules:
345
+ typer.secho("\nRules", bold=True)
346
+ for r in rules:
347
+ typer.echo(f" - {r['text'] if isinstance(r, dict) else r}")
348
+ answers = c.get("answers") or {}
349
+ if answers:
350
+ typer.secho("\nAnswered", bold=True)
351
+ for q in c.get("questions") or c.get("answered") or []:
352
+ if q.get("id") in answers:
353
+ typer.echo(f" {q['id']} {q.get('text', '')} → {answers[q['id']]}")
354
+ if b.get("open_questions"):
355
+ typer.secho("\nOpen questions (answer them to approve)", bold=True)
356
+ for q in b["open_questions"]:
357
+ typer.echo(f" {q['id']} {q['text']}" + (f" ({' / '.join(q['options'])})" if q.get("options") else ""))
358
+ pol = (c.get("validation") or {}).get("difficulty")
359
+ typer.secho("\nDifficulty test", bold=True)
360
+ if pol and pol.get("routes"):
361
+ cap = pol.get("cap") or {}
362
+ for r in pol["routes"]:
363
+ typer.echo(f" {r.get('name')}: {r.get('model')} · {r.get('setting', 'Default')} · {r.get('trials')} trials")
364
+ typer.echo(f" Pass cap: {'at most ' + str(cap.get('value')) + ('%' if cap.get('kind') == 'rate' else ' passes')}, with at least {cap.get('minValid', cap.get('min_valid'))} valid trials")
365
+ else:
366
+ typer.echo(" None: how hard tasks are isn’t measured.")
367
+
368
+ out(b, json, text)
369
+
370
+
371
+ @frame_app.command("export")
372
+ @handled
373
+ def frame_export(
374
+ name: Annotated[str, typer.Argument(help="Workstream name or id.")],
375
+ output: Annotated[Optional[str], typer.Option("--output", "-o", help="Write to this file instead of the screen.")] = None,
376
+ version: Version = None,
377
+ draft: Draft = False,
378
+ workspace: Workspace = None,
379
+ json: Json = False,
380
+ yes: Yes = False,
381
+ ) -> None:
382
+ """The Blueprint as JSON: keep it in git, edit it, import it elsewhere."""
383
+ workspace, json, yes = _flags(workspace, json, yes)
384
+ b = _blueprint(api(), name, workspace, version, draft)
385
+ text = jsonlib.dumps(b["content"], indent=2, ensure_ascii=False)
386
+ if not output:
387
+ typer.echo(text)
388
+ return
389
+ from pathlib import Path
390
+
391
+ p = Path(output)
392
+ if p.exists() and not yes:
393
+ if not interactive():
394
+ raise CliError(f"{output} already exists. Pass --yes to overwrite it.", BAD_INPUT)
395
+ typer.confirm(f"{output} exists. Overwrite?", abort=True)
396
+ p.write_text(text + "\n", encoding="utf-8")
397
+ label = "draft" if b["kind"] == "draft" else f"v{b['version']}"
398
+ out({"written": output, "kind": b["kind"], "version": b.get("version")}, json, lambda: typer.echo(f"Wrote {b['workstream']['name']} {label} to {output}"))
399
+
400
+
401
+ @frame_app.command("import")
402
+ @handled
403
+ def frame_import(
404
+ name: Annotated[str, typer.Argument(help="Workstream name or id (with --create: the new workstream's name).")],
405
+ file: Annotated[str, typer.Argument(help="A Blueprint JSON file (an export, or a draft).")],
406
+ create: Annotated[bool, typer.Option("--create", help="Make a new workstream from the file.")] = False,
407
+ workspace: Workspace = None,
408
+ json: Json = False,
409
+ yes: Yes = False,
410
+ ) -> None:
411
+ """Replace a workstream's draft with a file (approve it afterwards)."""
412
+ workspace, json, yes = _flags(workspace, json, yes)
413
+ from pathlib import Path
414
+
415
+ try:
416
+ doc = jsonlib.loads(Path(file).read_text(encoding="utf-8-sig"))
417
+ except OSError:
418
+ raise CliError(f"Couldn’t read {file}.", BAD_INPUT) from None
419
+ except ValueError as e:
420
+ raise CliError(f"{file} isn’t valid JSON: {e}", BAD_INPUT) from None
421
+ a = api()
422
+ if create:
423
+ made = a.post("/workstreams", json={"name": name, "blueprint": doc})
424
+ ws_id, ws_name = made["id"], made["name"]
425
+ shown = a.get(f"/workstreams/{ws_id}/blueprint", params={"draft": True})
426
+ opens = shown.get("open_questions") or []
427
+ else:
428
+ w = _find(a, name, workspace)
429
+ ws_id, ws_name = w["id"], w["name"]
430
+ opens = a.post(f"/workstreams/{ws_id}/blueprint/draft", json={"blueprint": doc}).get("open_questions") or []
431
+
432
+ def text():
433
+ typer.echo(f"{'Created' if create else 'Updated'} the draft of {ws_name}.")
434
+ if opens:
435
+ typer.echo(f"{len(opens)} open question{'s' if len(opens) != 1 else ''} to answer before approving:")
436
+ for q in opens:
437
+ typer.echo(f" {q['id']} {q['text']}")
438
+ typer.echo(f'Approve it with: trimrig frame approve "{ws_name}"')
439
+
440
+ out({"id": ws_id, "name": ws_name, "created": create, "open_questions": opens}, json, text)
441
+
442
+
443
+ def _pick(q: dict) -> str:
444
+ typer.echo(f"\n{q['id']} {q['text']}")
445
+ for i, o in enumerate(q.get("options") or [], 1):
446
+ typer.echo(f" {i}. {o}")
447
+ got = typer.prompt("Your answer" + (" (a number or your own words)" if q.get("options") else "")).strip()
448
+ opts = q.get("options") or []
449
+ return opts[int(got) - 1] if got.isdigit() and 1 <= int(got) <= len(opts) else got
450
+
451
+
452
+ @frame_app.command("approve")
453
+ @handled
454
+ def frame_approve(
455
+ name: Annotated[str, typer.Argument(help="Workstream name or id.")],
456
+ answer: Annotated[Optional[list[str]], typer.Option("--answer", "-a", help='Answer an open question: --answer Q1="Python 3.12" (repeat for more).')] = None,
457
+ workspace: Workspace = None,
458
+ json: Json = False,
459
+ yes: Yes = False,
460
+ ) -> None:
461
+ """Approve the draft as the next version. Runs are built from approved versions."""
462
+ workspace, json, yes = _flags(workspace, json, yes)
463
+ answers: dict[str, str] = {}
464
+ for item in answer or []:
465
+ if "=" not in item:
466
+ raise CliError(f"--answer takes ID=TEXT, like Q1=\"Python 3.12\" (got {item!r}).", BAD_INPUT)
467
+ k, v = item.split("=", 1)
468
+ answers[k.strip().upper()] = v.strip().strip('"')
469
+ a = api()
470
+ w = _find(a, name, workspace)
471
+ for _ in range(2):
472
+ try:
473
+ res = a.post(f"/workstreams/{w['id']}/blueprint/approve", json={"answers": answers})
474
+ break
475
+ except CliError as e:
476
+ opens = e.data.get("open_questions") or []
477
+ if not opens:
478
+ raise
479
+ if json or yes or not interactive():
480
+ listed = "; ".join(f"{q['id']}: {q['text']}" + (f" ({' / '.join(q['options'])})" if q.get("options") else "") for q in opens)
481
+ raise CliError(f"Answer the open questions first, with --answer ID=TEXT. {listed}", BAD_INPUT, {"open_questions": opens}) from None
482
+ typer.echo(f"{len(opens)} question{'s' if len(opens) != 1 else ''} to answer before approving:")
483
+ for q in opens:
484
+ answers[q["id"]] = _pick(q)
485
+ else: # pragma: no cover - the second try either works or raises
486
+ raise CliError("Couldn’t approve the Blueprint.", ERROR)
487
+ out(res, json, lambda: typer.echo(f"Approved {w['name']} Blueprint v{res['version']}. Start a run with: trimrig run --blueprint \"{w['name']}@{res['version']}\" --n 10"))
488
+
489
+
490
+ # ── Runs: run, status, ship ───────────────────────────────────────────────────
491
+
492
+
493
+ def _resolve_run(a: Api, ref: str | None, workspace: str | None) -> str:
494
+ """A run by id, by "Workstream#3", or (no ref) the last one started here."""
495
+ if not ref:
496
+ last = config.load().get("last_run")
497
+ if not last:
498
+ raise CliError('Which run? Pass its id or "Workstream#3" (or start one with `trimrig run`).', BAD_INPUT)
499
+ return last
500
+ if "#" in ref:
501
+ name, _, num = ref.rpartition("#")
502
+ if not num.isdigit():
503
+ raise CliError(f'Name a run as "Workstream#3" (got {ref!r}).', BAD_INPUT)
504
+ w = _find(a, name, workspace)
505
+ hit = next((r for r in a.get("/runs", params={"workstream": w["id"]})["runs"] if r["number"] == int(num)), None)
506
+ if not hit:
507
+ raise CliError(f"{w['name']} has no run #{num}.", NOT_FOUND)
508
+ return hit["run_id"]
509
+ return ref
510
+
511
+
512
+ def _status_line(r: dict) -> str:
513
+ order = ["ready", "review", "building", "proving", "repairing", "queued", "shipped", "skipped"]
514
+ counts = r.get("task_counts") or {}
515
+ parts = [f"{counts[k]} {k}" for k in order if counts.get(k)]
516
+ return f"Run #{r['number']} of {r['workstream']['name']} · Blueprint v{r['version']} · {r['status']}" + (f" · {', '.join(parts)}" if parts else "")
517
+
518
+
519
+ def _checks_line(r: dict) -> str:
520
+ """Checks: build 3/3 · baseline 3/3 · … · decoy 2/3 (1 failed), each task's latest attempt."""
521
+ parts = []
522
+ for name, by in (r.get("check_counts") or {}).items():
523
+ total = sum(by.values())
524
+ extra = ", ".join(f"{n} {k if k != 'error' else 'errored'}" for k, n in by.items() if k in ("fail", "error") and n)
525
+ extra = extra.replace(" fail", " failed")
526
+ parts.append(f"{name} {by.get('pass', 0)}/{total}" + (f" ({extra})" if extra else ""))
527
+ return " Checks: " + " · ".join(parts) if parts else ""
528
+
529
+
530
+ def _money(usd: float) -> str:
531
+ return f"${usd:,.2f}" if usd >= 0.995 or usd == 0 else f"${usd:.4f}".rstrip("0").rstrip(".") if usd < 0.01 else f"${usd:.3f}".rstrip("0")
532
+
533
+
534
+ def _cost_line(r: dict) -> str:
535
+ """Cost: $0.124 (models $0.118 · sandbox $0.0061), from what the providers reported."""
536
+ c = r.get("cost") or {}
537
+ if not c.get("recorded"):
538
+ return ""
539
+ line = f" Cost: {_money(float(c['total_usd']))} (models {_money(float(c['model_usd']))} · sandbox {_money(float(c['sandbox_usd']))})"
540
+ if c.get("unpriced_calls"):
541
+ models = ", ".join(m.split("::", 1)[-1] for m in c.get("unpriced_models") or [])
542
+ line += f"; {c['unpriced_calls']} model call{'s' if c['unpriced_calls'] != 1 else ''} without a price yet ({models}), not included"
543
+ return line
544
+
545
+
546
+ def _show_run(r: dict) -> None:
547
+ typer.echo(_status_line(r))
548
+ if _checks_line(r):
549
+ typer.echo(_checks_line(r))
550
+ if _cost_line(r):
551
+ typer.echo(_cost_line(r))
552
+ if r.get("stopped_reason"):
553
+ typer.echo(f" {r['stopped_reason']}")
554
+ for t in [t for t in r.get("tasks") or [] if t["status"] == "review"][:10]:
555
+ typer.echo(f" {t['code']} in Review: {t.get('review_reason') or t['title']}")
556
+ if r.get("done") and (r.get("task_counts") or {}).get("ready"):
557
+ typer.echo(f" Ship the ready tasks with: trimrig ship {r['run_id']}")
558
+
559
+
560
+ def _watch(a: Api, run_id: str, json: bool) -> dict:
561
+ last = None
562
+ while True:
563
+ r = a.get(f"/runs/{run_id}")
564
+ line = _status_line(r)
565
+ if line != last and not json:
566
+ typer.echo(line)
567
+ last = line
568
+ if r.get("done"):
569
+ return r
570
+ time.sleep(5)
571
+
572
+
573
+ @app.command("run")
574
+ @handled
575
+ def run_cmd(
576
+ blueprint: Annotated[str, typer.Option("--blueprint", "-b", help='The workstream and Blueprint version: "Invoice Recon@1.0" (no @version: the latest).')],
577
+ n: Annotated[int, typer.Option("--n", help="How many tasks to make (1–500).", min=1, max=500)],
578
+ difficulty: Annotated[str, typer.Option(help="Easy, Medium, Hard or Mixed.")] = "Medium",
579
+ diversity: Annotated[str, typer.Option(help="Focused, Balanced or Wide.")] = "Balanced",
580
+ repairs: Annotated[int, typer.Option(help="Repair attempts per task before it goes to Review (0–5).", min=0, max=5)] = 3,
581
+ no_difficulty_test: Annotated[bool, typer.Option("--no-difficulty-test", help="Skip the Blueprint's difficulty test for this run.")] = False,
582
+ watch: Annotated[bool, typer.Option("--watch", help="Follow the run until it ends.")] = False,
583
+ workspace: Workspace = None,
584
+ json: Json = False,
585
+ yes: Yes = False,
586
+ ) -> None:
587
+ """Start a run from an approved Blueprint. The worker builds and proves the tasks."""
588
+ workspace, json, yes = _flags(workspace, json, yes)
589
+ name, _, version = blueprint.rpartition("@") if "@" in blueprint else (blueprint, "", "")
590
+ pick = lambda value, options: next((o for o in options if o.lower() == value.lower()), None) # noqa: E731
591
+ diff, div = pick(difficulty, ("Easy", "Medium", "Hard", "Mixed")), pick(diversity, ("Focused", "Balanced", "Wide"))
592
+ if not diff or not div:
593
+ raise CliError("--difficulty is Easy, Medium, Hard or Mixed; --diversity is Focused, Balanced or Wide.", BAD_INPUT)
594
+ a = api()
595
+ w = _find(a, name, workspace, ("active",))
596
+ res = a.post("/runs", json={"workstream_id": w["id"], "version": version or "latest", "n": n, "difficulty": diff, "diversity": div, "repair_budget": repairs, "difficulty_test": not no_difficulty_test})
597
+ config.save(last_run=res["run_id"])
598
+ if not json:
599
+ typer.echo(f"Started run #{res['number']} of {w['name']} from Blueprint v{res['version']}: {n} task{'s' if n != 1 else ''}.")
600
+ if not watch:
601
+ typer.echo("Follow it with: trimrig status --watch")
602
+ if watch:
603
+ final = _watch(a, res["run_id"], json)
604
+ out(final, json, lambda: _show_run(final))
605
+ if final["status"] != "finished":
606
+ raise typer.Exit(ERROR)
607
+ return
608
+ if json:
609
+ typer.echo(jsonlib.dumps(res, indent=2))
610
+
611
+
612
+ @app.command()
613
+ @handled
614
+ def status(
615
+ run: Annotated[Optional[str], typer.Argument(help='A run id, or "Workstream#3". Default: the last run started here.')] = None,
616
+ watch: Annotated[bool, typer.Option("--watch", help="Keep going until the run ends (exit 0 if it finished, 1 if it failed or stopped).")] = False,
617
+ workspace: Workspace = None,
618
+ json: Json = False,
619
+ yes: Yes = False,
620
+ ) -> None:
621
+ """Where a run is: its status and how many tasks are ready or in Review."""
622
+ workspace, json, yes = _flags(workspace, json, yes)
623
+ a = api()
624
+ run_id = _resolve_run(a, run, workspace)
625
+ r = _watch(a, run_id, json) if watch else a.get(f"/runs/{run_id}")
626
+ out(r, json, lambda: _show_run(r))
627
+ if watch and r["status"] != "finished":
628
+ raise typer.Exit(ERROR)
629
+
630
+
631
+ @app.command()
632
+ @handled
633
+ def ship(
634
+ run: Annotated[Optional[str], typer.Argument(help='A run id, or "Workstream#3". Default: the last run started here.')] = None,
635
+ output: Annotated[Optional[str], typer.Option("--output", "-o", help="Where to save the ZIP (default: its own name, here).")] = None,
636
+ no_mark: Annotated[bool, typer.Option("--no-mark", help="Just download a copy of what's ready; mark nothing.")] = False,
637
+ again: Annotated[Optional[str], typer.Option("--again", help='Download a shipped batch again, exactly as it went out: a batch number, "latest" or "all".')] = None,
638
+ workspace: Workspace = None,
639
+ json: Json = False,
640
+ yes: Yes = False,
641
+ ) -> None:
642
+ """Ship a run: download the tasks that are ready and not yet shipped as the
643
+ run's next batch (a ZIP with one folder per task, plus manifest.json) and mark
644
+ them shipped. Admins and Builders. --again re-downloads a batch; --no-mark copies."""
645
+ workspace, json, yes = _flags(workspace, json, yes)
646
+ from pathlib import Path
647
+
648
+ if again is not None and no_mark:
649
+ raise CliError("Use --again or --no-mark, not both.", BAD_INPUT)
650
+ again = None if again is None else again.strip().lower()
651
+ if again is not None and again not in ("latest", "all") and not again.isdigit():
652
+ raise CliError('--again takes a batch number, "latest" or "all".', BAD_INPUT)
653
+ a = api()
654
+ run_id = _resolve_run(a, run, workspace)
655
+ p0 = Path(output) if output else None
656
+ if p0 and p0.exists() and not yes and not interactive(): # check before shipping, not after
657
+ raise CliError(f"{p0} already exists. Pass --yes to overwrite it, or -o another name.", BAD_INPUT)
658
+ if no_mark:
659
+ path, method = f"/runs/{run_id}/ship?scope=ready", "GET"
660
+ elif again == "all":
661
+ path, method = f"/runs/{run_id}/ship?scope=all", "GET"
662
+ elif again is not None:
663
+ path, method = f"/runs/{run_id}/ship?scope=batch" + ("" if again == "latest" else f"&batch={again}"), "GET"
664
+ else:
665
+ path, method = f"/runs/{run_id}/ship", "POST"
666
+ try:
667
+ data, suggested, headers = a.download(path, method=method)
668
+ except CliError as e:
669
+ if method == "POST" and "Nothing new to ship" in str(e):
670
+ raise CliError(str(e) + " Download a batch again with: trimrig ship --again latest (or a number, or all).", e.code, e.data) from None
671
+ raise
672
+ shipped = int(headers["x-trimrig-shipped"]) if "x-trimrig-shipped" in headers else None
673
+ batch = int(headers["x-trimrig-batch"]) if "x-trimrig-batch" in headers else None
674
+ p = Path(output or suggested or f"run-{run_id[:8]}.zip")
675
+ if p.exists() and not yes:
676
+ if not interactive():
677
+ raise CliError(f"{p} already exists. Pass --yes to overwrite it, or -o another name.", BAD_INPUT)
678
+ typer.confirm(f"{p} exists. Overwrite?", abort=True)
679
+ p.write_bytes(data)
680
+
681
+ def text():
682
+ typer.echo(f"Saved {p} ({len(data) / 1024:.0f} KB).")
683
+ if shipped is not None:
684
+ typer.echo(f"Shipped batch {batch}: marked {shipped} task{'s' if shipped != 1 else ''} as shipped.")
685
+ elif again is not None:
686
+ typer.echo("Downloaded again, exactly as shipped. Nothing was marked.")
687
+ else:
688
+ typer.echo("A copy of what's ready. Nothing was marked.")
689
+
690
+ out({"written": str(p), "bytes": len(data), "shipped": shipped, "batch": batch}, json, text)
691
+
692
+
693
+ def run() -> None:
694
+ app()
695
+
696
+
697
+ if __name__ == "__main__":
698
+ run()