courant-dev 0.5.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.
- courant/__init__.py +26 -0
- courant/case/__init__.py +0 -0
- courant/case/_foam_reader.py +269 -0
- courant/case/config.py +134 -0
- courant/case/mesh.py +135 -0
- courant/case/reads.py +90 -0
- courant/case/schemes.py +99 -0
- courant/case/solvers.py +170 -0
- courant/cli/__init__.py +0 -0
- courant/cli/commands/__init__.py +6 -0
- courant/cli/commands/audit.py +40 -0
- courant/cli/commands/convergence.py +68 -0
- courant/cli/commands/ctest.py +76 -0
- courant/cli/commands/doctor.py +162 -0
- courant/cli/commands/gate.py +88 -0
- courant/cli/commands/live.py +73 -0
- courant/cli/commands/mcp.py +57 -0
- courant/cli/commands/preflight.py +36 -0
- courant/cli/commands/spec.py +231 -0
- courant/cli/commands/tour.py +122 -0
- courant/cli/commands/update.py +213 -0
- courant/cli/commands/verify.py +222 -0
- courant/cli/config.py +244 -0
- courant/cli/guard.py +69 -0
- courant/cli/main.py +130 -0
- courant/cli/tail.py +351 -0
- courant/config.py +155 -0
- courant/converge/__init__.py +57 -0
- courant/converge/assess.py +823 -0
- courant/converge/exact.py +112 -0
- courant/converge/render.py +182 -0
- courant/converge/scale.py +87 -0
- courant/converge/sentences.py +82 -0
- courant/converge/series.py +413 -0
- courant/converge/steady.py +261 -0
- courant/converge/tables.py +1019 -0
- courant/converge/transient.py +314 -0
- courant/ctest/__init__.py +6 -0
- courant/ctest/build.py +82 -0
- courant/ctest/data/judge-v0.labels.jsonl +31 -0
- courant/ctest/data/judge-v0.tasks.jsonl.gz +0 -0
- courant/ctest/judges/__init__.py +27 -0
- courant/ctest/judges/constant.py +18 -0
- courant/ctest/judges/courant.py +23 -0
- courant/ctest/judges/llm.py +166 -0
- courant/ctest/run.py +74 -0
- courant/ctest/schema.py +46 -0
- courant/ctest/score.py +91 -0
- courant/ctest/splits.py +20 -0
- courant/data/__init__.py +46 -0
- courant/data/certification.json +1 -0
- courant/data/certified_codes.json +18 -0
- courant/data/demo/icoFoam_cavity__cfl_blowup.case.json +68 -0
- courant/data/demo/icoFoam_cavity__cfl_blowup.log.gz +0 -0
- courant/data/demo/icoFoam_cavity__healthy.case.json +68 -0
- courant/data/demo/icoFoam_cavity__healthy.log.gz +0 -0
- courant/data/demo/icoFoam_cavity__transport_units.case.json +68 -0
- courant/data/demo/icoFoam_cavity__transport_units.log.gz +0 -0
- courant/data/demo/pitzDaily_fixed_budget.tar.gz +0 -0
- courant/data/schemas/audit.1.json +129 -0
- courant/data/schemas/cache.1.json +77 -0
- courant/data/schemas/convergence.1.json +112 -0
- courant/data/schemas/error-rates.1.json +53 -0
- courant/data/schemas/preflight.1.json +250 -0
- courant/data/schemas/record.1.json +155 -0
- courant/data/schemas/release-signature.1.json +39 -0
- courant/data/schemas/spec.1.json +258 -0
- courant/data/schemas/support.1.json +80 -0
- courant/data/schemas/verdict.1.json +716 -0
- courant/data/schemas/verdict.2.json +752 -0
- courant/diagnosis/__init__.py +0 -0
- courant/diagnosis/bundle.py +168 -0
- courant/diagnosis/checkers.py +919 -0
- courant/diagnosis/deterministic.py +110 -0
- courant/diagnosis/findings.py +107 -0
- courant/diagnosis/kb.py +188 -0
- courant/diagnosis/kb_data.py +253 -0
- courant/diagnosis/llm.py +299 -0
- courant/diagnosis/redact.py +425 -0
- courant/diagnosis/schema.py +83 -0
- courant/events/__init__.py +35 -0
- courant/events/core.py +194 -0
- courant/events/diverged.py +55 -0
- courant/gate/__init__.py +1 -0
- courant/gate/config.py +150 -0
- courant/gate/run.py +295 -0
- courant/live/__init__.py +16 -0
- courant/live/engine.py +155 -0
- courant/live/watch.py +164 -0
- courant/llm/__init__.py +59 -0
- courant/llm/allowlist.py +60 -0
- courant/llm/anthropic.py +137 -0
- courant/llm/budget.py +491 -0
- courant/llm/door.py +1071 -0
- courant/llm/errors.py +105 -0
- courant/llm/openrouter.py +118 -0
- courant/llm/policy.py +268 -0
- courant/llm/transport.py +48 -0
- courant/mcp/__init__.py +7 -0
- courant/mcp/server.py +113 -0
- courant/mcp/tools.py +177 -0
- courant/record/__init__.py +22 -0
- courant/record/filter.py +99 -0
- courant/record/record.py +149 -0
- courant/release.py +205 -0
- courant/signing.py +99 -0
- courant/spec/__init__.py +31 -0
- courant/spec/check.py +353 -0
- courant/spec/deck.py +455 -0
- courant/spec/extract.py +181 -0
- courant/spec/impossible.py +197 -0
- courant/spec/model.py +194 -0
- courant/taxonomy.py +219 -0
- courant/verification/__init__.py +30 -0
- courant/verification/_fluid_reader.py +228 -0
- courant/verification/bounding.py +84 -0
- courant/verification/checks.py +369 -0
- courant/verification/convergence.py +257 -0
- courant/verification/fields.py +38 -0
- courant/verification/grade.py +101 -0
- courant/verification/suite.py +30 -0
- courant/verify/__init__.py +37 -0
- courant/verify/about.py +100 -0
- courant/verify/audit.py +209 -0
- courant/verify/batch.py +141 -0
- courant/verify/cache.py +329 -0
- courant/verify/checks.py +37 -0
- courant/verify/html.py +330 -0
- courant/verify/ingest.py +115 -0
- courant/verify/junit.py +48 -0
- courant/verify/outcome.py +74 -0
- courant/verify/pack.py +106 -0
- courant/verify/pipeline.py +396 -0
- courant/verify/policy.py +167 -0
- courant/verify/preflight.py +166 -0
- courant/verify/render.py +174 -0
- courant/verify/schema.py +398 -0
- courant/verify/sentences.py +137 -0
- courant/verify/support.py +142 -0
- courant/verify/verdict2.py +235 -0
- courant/watcher/__init__.py +13 -0
- courant/watcher/anomaly.py +244 -0
- courant/watcher/exitcode.py +23 -0
- courant/watcher/parser.py +435 -0
- courant/watcher/watcher.py +49 -0
- courant_dev-0.5.0.dist-info/METADATA +146 -0
- courant_dev-0.5.0.dist-info/RECORD +152 -0
- courant_dev-0.5.0.dist-info/WHEEL +5 -0
- courant_dev-0.5.0.dist-info/entry_points.txt +3 -0
- courant_dev-0.5.0.dist-info/licenses/LICENSE +202 -0
- courant_dev-0.5.0.dist-info/licenses/NOTICE +4 -0
- courant_dev-0.5.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""``courant update`` — replace this agent with the current release.
|
|
2
|
+
|
|
3
|
+
The API refuses agents below a minimum version with a 426, and the transport
|
|
4
|
+
tells the user to run this. A command that is advertised in an error message and
|
|
5
|
+
does not exist is worse than no command at all, so it exists.
|
|
6
|
+
|
|
7
|
+
Two installations, two different answers:
|
|
8
|
+
|
|
9
|
+
* **packaged binary** — download the release for this platform, verify the
|
|
10
|
+
release's signed checksums (OPS-7: the Ed25519 signature of ``SHA256SUMS``
|
|
11
|
+
under the release key pinned in this build, ``courant.release``), and swap it
|
|
12
|
+
in atomically. Same download and verification path as
|
|
13
|
+
the installer, because it is the same problem.
|
|
14
|
+
* **pip install** — do not touch it. Uninstalling a package from inside the
|
|
15
|
+
process that imported it is a way to leave a machine with no working agent
|
|
16
|
+
at all. Print the pip command and stop, having contacted nothing.
|
|
17
|
+
|
|
18
|
+
Its purpose is a network call, and it says so before it makes one: a packaged binary's update
|
|
19
|
+
downloads the release and its signed checksums from github.com (``RELEASES``), nothing else. It
|
|
20
|
+
contacts nothing when it is a pip installation or when ``--check`` is given (docs/NETWORK.md).
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import json
|
|
26
|
+
import os
|
|
27
|
+
import platform
|
|
28
|
+
import shutil
|
|
29
|
+
import stat
|
|
30
|
+
import sys
|
|
31
|
+
import tempfile
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
|
|
34
|
+
import typer
|
|
35
|
+
from rich.console import Console
|
|
36
|
+
|
|
37
|
+
from courant import DISTRIBUTION, RELEASE_REPO, __version__, release
|
|
38
|
+
from courant.release import SUMS, SUMS_SIG, ReleaseError, check_version, verify_asset
|
|
39
|
+
|
|
40
|
+
console = Console()
|
|
41
|
+
|
|
42
|
+
REPO = RELEASE_REPO
|
|
43
|
+
RELEASES = f"https://github.com/{REPO}/releases"
|
|
44
|
+
#: What this command contacts, said before it does (docs/NETWORK.md).
|
|
45
|
+
CONTACTS = "github.com"
|
|
46
|
+
PIP_UPGRADE = f"pip install --upgrade {DISTRIBUTION}"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def target_triple() -> str | None:
|
|
50
|
+
"""The release asset name for this machine, or None if we do not ship one."""
|
|
51
|
+
system = platform.system().lower()
|
|
52
|
+
machine = platform.machine().lower()
|
|
53
|
+
|
|
54
|
+
os_name = {"linux": "linux", "darwin": "darwin"}.get(system)
|
|
55
|
+
arch = {"x86_64": "x86_64", "amd64": "x86_64",
|
|
56
|
+
"arm64": "arm64", "aarch64": "arm64"}.get(machine)
|
|
57
|
+
|
|
58
|
+
return f"{os_name}-{arch}" if os_name and arch else None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def is_packaged() -> bool:
|
|
62
|
+
return bool(getattr(sys, "frozen", False))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def update(
|
|
66
|
+
version: str = typer.Option(
|
|
67
|
+
"latest", "--version", "-v", help="Version to install, e.g. 0.2.0."
|
|
68
|
+
),
|
|
69
|
+
check: bool = typer.Option(
|
|
70
|
+
False, "--check", help="Report what would happen; contact nothing, change nothing."
|
|
71
|
+
),
|
|
72
|
+
allow_downgrade: bool = typer.Option(
|
|
73
|
+
False, "--allow-downgrade",
|
|
74
|
+
help="With --version: install a release older than this one."
|
|
75
|
+
),
|
|
76
|
+
) -> None:
|
|
77
|
+
"""Update this Courant binary to the current release, downloaded from github.com.
|
|
78
|
+
|
|
79
|
+
The one visible command whose purpose is a network call: a packaged binary downloads the
|
|
80
|
+
release and its signed checksums from github.com. A pip installation is managed by pip, and this
|
|
81
|
+
prints the pip command and contacts nothing.
|
|
82
|
+
"""
|
|
83
|
+
console.print(f"This agent: [cyan]{__version__}[/cyan]")
|
|
84
|
+
|
|
85
|
+
if not is_packaged():
|
|
86
|
+
# A pip-installed agent is managed by pip. Anything else we did here
|
|
87
|
+
# would fight the user's environment.
|
|
88
|
+
console.print(
|
|
89
|
+
"\nThis is a [bold]pip[/bold] installation, so pip owns it:\n"
|
|
90
|
+
f" [cyan]{PIP_UPGRADE}[/cyan]\n"
|
|
91
|
+
" [dim]Nothing was contacted.[/dim]\n"
|
|
92
|
+
)
|
|
93
|
+
raise typer.Exit(0)
|
|
94
|
+
|
|
95
|
+
triple = target_triple()
|
|
96
|
+
if triple is None:
|
|
97
|
+
console.print(
|
|
98
|
+
f"\n[yellow]No published binary for "
|
|
99
|
+
f"{platform.system()}/{platform.machine()}.[/yellow]\n"
|
|
100
|
+
f" [cyan]{PIP_UPGRADE}[/cyan]\n"
|
|
101
|
+
" [dim]Nothing was contacted.[/dim]\n"
|
|
102
|
+
)
|
|
103
|
+
raise typer.Exit(1)
|
|
104
|
+
|
|
105
|
+
if version != "latest":
|
|
106
|
+
try:
|
|
107
|
+
check_version(version.lstrip("v"), version.lstrip("v"), __version__, allow_downgrade)
|
|
108
|
+
except ReleaseError as exc:
|
|
109
|
+
console.print(f"\n[red]Refusing:[/red] {exc}. [dim]Nothing was contacted.[/dim]\n")
|
|
110
|
+
raise typer.Exit(1) from None
|
|
111
|
+
|
|
112
|
+
base = (f"{RELEASES}/latest/download" if version == "latest"
|
|
113
|
+
else f"{RELEASES}/download/v{version.lstrip('v')}")
|
|
114
|
+
asset = f"courant-{triple}"
|
|
115
|
+
|
|
116
|
+
if check:
|
|
117
|
+
console.print(f"Would download [cyan]{base}/{asset}[/cyan] from {CONTACTS}. "
|
|
118
|
+
"[dim]Nothing was contacted.[/dim]")
|
|
119
|
+
raise typer.Exit(0)
|
|
120
|
+
|
|
121
|
+
destination = Path(sys.executable).resolve()
|
|
122
|
+
console.print(f" [dim]contacting {CONTACTS}: downloading {asset}, the release's "
|
|
123
|
+
f"{SUMS} and its signature from {RELEASES}[/dim]")
|
|
124
|
+
|
|
125
|
+
try:
|
|
126
|
+
payload = _download(f"{base}/{asset}")
|
|
127
|
+
sums = _download_optional(f"{base}/{SUMS}")
|
|
128
|
+
signature = _download_optional(f"{base}/{SUMS_SIG}")
|
|
129
|
+
except Exception as exc: # noqa: BLE001 — every failure here is the network
|
|
130
|
+
console.print(
|
|
131
|
+
f"\n[red]Could not download the update from {CONTACTS}:[/red] {exc}\n"
|
|
132
|
+
f" [dim]{RELEASES}[/dim]\n"
|
|
133
|
+
)
|
|
134
|
+
raise typer.Exit(1) from None
|
|
135
|
+
|
|
136
|
+
# OPS-7: the signature is verified before anything is replaced, against the release key
|
|
137
|
+
# pinned in this build, never the key the signature file names.
|
|
138
|
+
if sums is None or signature is None:
|
|
139
|
+
console.print(f"\n[red]The release has no signed {SUMS} — refusing to install.[/red]\n")
|
|
140
|
+
raise typer.Exit(1)
|
|
141
|
+
try:
|
|
142
|
+
verify_asset(asset, payload, sums, json.loads(signature.decode()),
|
|
143
|
+
public_key=release.RELEASE_PUBLIC_KEY,
|
|
144
|
+
requested=version if version == "latest" else version.lstrip("v"),
|
|
145
|
+
current=__version__, allow_older=allow_downgrade)
|
|
146
|
+
except (ReleaseError, ValueError) as exc:
|
|
147
|
+
console.print(
|
|
148
|
+
f"\n[red]The release signature does not check — refusing to install:[/red] {exc}\n"
|
|
149
|
+
f" [dim]Please report this: https://github.com/{REPO}/issues[/dim]\n"
|
|
150
|
+
)
|
|
151
|
+
raise typer.Exit(1) from None
|
|
152
|
+
|
|
153
|
+
try:
|
|
154
|
+
_replace(destination, payload)
|
|
155
|
+
except PermissionError:
|
|
156
|
+
console.print(
|
|
157
|
+
f"\n[red]No permission to write[/red] {destination}\n"
|
|
158
|
+
" [dim]Installed system-wide? Re-run with the rights to replace it, "
|
|
159
|
+
"or reinstall to your home directory:[/dim]\n"
|
|
160
|
+
" [cyan]curl -fsSL https://github.com/courantdev/courant/releases/latest/download/install.sh | sh[/cyan]\n"
|
|
161
|
+
)
|
|
162
|
+
raise typer.Exit(1) from None
|
|
163
|
+
except Exception as exc: # noqa: BLE001
|
|
164
|
+
console.print(f"\n[red]Could not replace the binary:[/red] {exc}\n")
|
|
165
|
+
raise typer.Exit(1) from None
|
|
166
|
+
|
|
167
|
+
console.print(f"\n[green]Updated.[/green] [dim]{destination}[/dim]")
|
|
168
|
+
console.print(" [dim]courant version[/dim]")
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
# ---------------------------------------------------------------------------
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _download(url: str) -> bytes:
|
|
175
|
+
import httpx
|
|
176
|
+
|
|
177
|
+
with httpx.Client(follow_redirects=True, timeout=60.0) as client:
|
|
178
|
+
response = client.get(url)
|
|
179
|
+
response.raise_for_status()
|
|
180
|
+
return response.content
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _download_optional(url: str) -> bytes | None:
|
|
184
|
+
try:
|
|
185
|
+
return _download(url)
|
|
186
|
+
except Exception: # noqa: BLE001 — a missing checksum or signature is refused by the caller
|
|
187
|
+
return None
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _replace(destination: Path, payload: bytes) -> None:
|
|
191
|
+
"""Swap the running binary for a new one, atomically.
|
|
192
|
+
|
|
193
|
+
Written next to the target and renamed over it. Two reasons that ordering
|
|
194
|
+
matters: ``rename`` within a filesystem is atomic, so an interrupted update
|
|
195
|
+
cannot leave a truncated executable on PATH; and POSIX lets you replace the
|
|
196
|
+
file of a *running* process, which is exactly what we are doing.
|
|
197
|
+
"""
|
|
198
|
+
directory = destination.parent
|
|
199
|
+
handle, staged = tempfile.mkstemp(prefix=".courant-update-", dir=directory)
|
|
200
|
+
try:
|
|
201
|
+
with os.fdopen(handle, "wb") as fh:
|
|
202
|
+
fh.write(payload)
|
|
203
|
+
os.chmod(staged, os.stat(destination).st_mode | stat.S_IXUSR)
|
|
204
|
+
|
|
205
|
+
# Keep the old binary until the new one is proven to start. An update
|
|
206
|
+
# that leaves a machine with no working agent is worse than a stale one.
|
|
207
|
+
backup = destination.with_suffix(".old")
|
|
208
|
+
shutil.copy2(destination, backup)
|
|
209
|
+
os.replace(staged, destination)
|
|
210
|
+
backup.unlink(missing_ok=True)
|
|
211
|
+
except Exception:
|
|
212
|
+
Path(staged).unlink(missing_ok=True)
|
|
213
|
+
raise
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""`courant verify`: a verdict on a completed run, with its evidence (TRD VER-10).
|
|
2
|
+
|
|
3
|
+
It writes `courant.verdict/2` (accept, reject or insufficient, with its basis; TRD GATE-1..3),
|
|
4
|
+
and `courant.verdict/1` behind `--schema 1` for one minor release (ARC-16).
|
|
5
|
+
|
|
6
|
+
Exit codes:
|
|
7
|
+
- 0 accept (TRUSTWORTHY in version 1)
|
|
8
|
+
- 2 reject (NOT_TRUSTWORTHY)
|
|
9
|
+
- 3 insufficient (NOT_ASSESSABLE)
|
|
10
|
+
- 4 the inputs could not be read
|
|
11
|
+
- 5 --check-pack or --check-record found a difference
|
|
12
|
+
|
|
13
|
+
stdout carries the report. stderr carries diagnostics. Read-only: nothing in
|
|
14
|
+
the case is written, no solver is run, no socket is opened.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import sys
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
import typer
|
|
23
|
+
|
|
24
|
+
from courant.cli.guard import guarded
|
|
25
|
+
|
|
26
|
+
#: Either major's answer to its exit code (GATE-1: the same three codes).
|
|
27
|
+
EXIT = {"TRUSTWORTHY": 0, "NOT_TRUSTWORTHY": 2, "NOT_ASSESSABLE": 3,
|
|
28
|
+
"accept": 0, "reject": 2, "insufficient": 3}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def certification_summary() -> str:
|
|
32
|
+
"""The rates published for this version, read only from the packaged results (GATE-12,
|
|
33
|
+
CERT-3, PKG-5). One implementation: `courant.verify.about`."""
|
|
34
|
+
from courant.verify import about
|
|
35
|
+
|
|
36
|
+
return about.render_text()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@guarded("verify")
|
|
40
|
+
def verify(
|
|
41
|
+
path: str = typer.Argument(None, help="A case directory, or a solver log (.log or .log.gz)."),
|
|
42
|
+
case_json: str = typer.Option(None, "--case-json", help="Captured configuration sidecar (*.case.json)."),
|
|
43
|
+
as_json: bool = typer.Option(False, "--json", help="Print the canonical verdict JSON."),
|
|
44
|
+
report: str = typer.Option(None, "--report", help="'md' prints a Markdown report; 'html' prints a self-contained HTML report."),
|
|
45
|
+
html: str = typer.Option(None, "--html", help="Write the self-contained HTML report to this file."),
|
|
46
|
+
junit: str = typer.Option(None, "--junit", help="With --batch: write JUnit XML here, one test per run."),
|
|
47
|
+
about: bool = typer.Option(False, "--about", help="Print this version's published error rates (false accepts, false alarms, abstentions, each with its denominator and confidence interval); with --json or --report md, as data or Markdown."),
|
|
48
|
+
pack: str = typer.Option(None, "--pack", help="Write an evidence pack (verdict.json, report.md, inputs.manifest) here."),
|
|
49
|
+
check_pack: str = typer.Option(None, "--check-pack", help="Re-verify a pack from its inputs; exit 5 if anything differs."),
|
|
50
|
+
record: str = typer.Option(None, "--record", help="Write a verified record (courant.record/1: the specification, the verdict, provenance and the full manifest) here."),
|
|
51
|
+
check_record: str = typer.Option(None, "--check-record", help="Re-derive a record from its inputs; exit 5 if anything differs."),
|
|
52
|
+
producer: str = typer.Option(None, "--producer", help="With --record: who or what produced the run (an agent and its version)."),
|
|
53
|
+
requester: str = typer.Option(None, "--requester", help="With --record: who asked for the run."),
|
|
54
|
+
root: str = typer.Option(None, "--root", help="Where a pack's or a record's inputs live (for --check-pack and --check-record; default: cwd)."),
|
|
55
|
+
batch: str = typer.Option(None, "--batch", help="Verify every run under this directory."),
|
|
56
|
+
spec: str = typer.Option(None, "--spec", help="The task specification (courant.spec/1) the run was asked to satisfy; every value it names is checked against the case."),
|
|
57
|
+
spec_sha256: str = typer.Option(None, "--spec-sha256", help="The hash the specification was locked at before the run (courant spec hash). A specification that no longer matches it makes the verdict insufficient."),
|
|
58
|
+
jobs: int = typer.Option(1, "--jobs", min=1, help="With --batch: verify this many runs at once (default 1). The results are identical to a serial run."),
|
|
59
|
+
no_cache: bool = typer.Option(False, "--no-cache", help="With --batch: do not read or write the verdict cache ($COURANT_CACHE_DIR, else ~/.cache/courant/verdicts)."),
|
|
60
|
+
cache_on: bool = typer.Option(False, "--cache", help="With --batch: use the verdict cache even where CI is set (it is off there by default)."),
|
|
61
|
+
checks: str = typer.Option("default", "--checks", help="'next' also runs the checks that ship behind this flag for one minor release before they are on by default (GATE-13); the verdict records it. One run at a time: not with --batch, --pack or --record."),
|
|
62
|
+
schema: int = typer.Option(2, "--schema", help="The verdict schema to write: 2 (courant.verdict/2, the default) or 1 (courant.verdict/1, the previous major, kept for one minor release)."),
|
|
63
|
+
debug: bool = typer.Option(False, "--debug", help="Print the traceback of an internal error instead of one line."),
|
|
64
|
+
) -> None:
|
|
65
|
+
"""Verify a completed simulation: accept, reject or insufficient, with its basis."""
|
|
66
|
+
from courant.verify import InputError, render_json, render_markdown, render_text
|
|
67
|
+
from courant.verify.verdict2 import SCHEMAS, in_schema
|
|
68
|
+
|
|
69
|
+
if schema not in SCHEMAS:
|
|
70
|
+
print(f"courant verify: --schema must be 1 or 2, not {schema}", file=sys.stderr)
|
|
71
|
+
raise typer.Exit(4)
|
|
72
|
+
|
|
73
|
+
from courant.verify.checks import MODES
|
|
74
|
+
|
|
75
|
+
if checks not in MODES:
|
|
76
|
+
print(f"courant verify: --checks must be one of {', '.join(MODES)}, not {checks}",
|
|
77
|
+
file=sys.stderr)
|
|
78
|
+
raise typer.Exit(4)
|
|
79
|
+
if checks == "next" and (batch or pack or record):
|
|
80
|
+
print("courant verify: --checks next verifies one run; packs, records and batches use "
|
|
81
|
+
"the default checks", file=sys.stderr)
|
|
82
|
+
raise typer.Exit(4)
|
|
83
|
+
|
|
84
|
+
if about:
|
|
85
|
+
from courant.verify import about as _about
|
|
86
|
+
|
|
87
|
+
if as_json:
|
|
88
|
+
from courant.verify.schema import canonical_json
|
|
89
|
+
|
|
90
|
+
sys.stdout.write(canonical_json(_about.error_rates()))
|
|
91
|
+
elif report == "md":
|
|
92
|
+
sys.stdout.write(_about.render_markdown())
|
|
93
|
+
else:
|
|
94
|
+
sys.stdout.write(certification_summary())
|
|
95
|
+
raise typer.Exit(0)
|
|
96
|
+
if check_pack:
|
|
97
|
+
from courant.verify.pack import check_pack as _check
|
|
98
|
+
|
|
99
|
+
ok, message = _check(check_pack, root or ".")
|
|
100
|
+
print(("OK " if ok else "MISMATCH ") + message)
|
|
101
|
+
raise typer.Exit(0 if ok else 5)
|
|
102
|
+
if check_record:
|
|
103
|
+
from courant.record import check_record as _check_record
|
|
104
|
+
|
|
105
|
+
ok, message = _check_record(check_record, root or ".")
|
|
106
|
+
print(("OK " if ok else "MISMATCH ") + message)
|
|
107
|
+
raise typer.Exit(0 if ok else 5)
|
|
108
|
+
if (producer or requester) and not record:
|
|
109
|
+
print("courant verify: --producer and --requester need --record", file=sys.stderr)
|
|
110
|
+
raise typer.Exit(4)
|
|
111
|
+
if record and batch:
|
|
112
|
+
print("courant verify: --record writes one run's record; it cannot go with --batch",
|
|
113
|
+
file=sys.stderr)
|
|
114
|
+
raise typer.Exit(4)
|
|
115
|
+
if batch:
|
|
116
|
+
from courant.verify.batch import summarise, verify_batch
|
|
117
|
+
from courant.verify.cache import VerdictCache
|
|
118
|
+
|
|
119
|
+
if cache_on and no_cache:
|
|
120
|
+
print("courant verify: --cache and --no-cache contradict each other", file=sys.stderr)
|
|
121
|
+
raise typer.Exit(4)
|
|
122
|
+
import os
|
|
123
|
+
|
|
124
|
+
no_cache = no_cache or (not cache_on and bool(os.environ.get("CI")))
|
|
125
|
+
if spec_sha256 and not spec:
|
|
126
|
+
print("courant verify: --spec-sha256 needs --spec", file=sys.stderr)
|
|
127
|
+
raise typer.Exit(4)
|
|
128
|
+
settings = Path(batch) / "courant.toml"
|
|
129
|
+
if settings.is_file():
|
|
130
|
+
# GATE-8: a repository's courant.toml names the runs, their outputs and their
|
|
131
|
+
# specifications; an unknown key in it is an error, never a silent default.
|
|
132
|
+
from courant.gate.config import ConfigError, load_config
|
|
133
|
+
from courant.gate.run import judge_groups
|
|
134
|
+
|
|
135
|
+
if spec or spec_sha256:
|
|
136
|
+
print("courant verify: --spec and --spec-sha256 do not combine with the "
|
|
137
|
+
"courant.toml in this directory", file=sys.stderr)
|
|
138
|
+
raise typer.Exit(4)
|
|
139
|
+
try:
|
|
140
|
+
judged, problems, hits = judge_groups(
|
|
141
|
+
Path(batch).resolve(), load_config(settings), jobs=jobs,
|
|
142
|
+
cache=None if no_cache else VerdictCache())
|
|
143
|
+
except ConfigError as exc:
|
|
144
|
+
print(f"courant verify: {exc}", file=sys.stderr)
|
|
145
|
+
raise typer.Exit(4) from exc
|
|
146
|
+
unjudged = [(Path(batch) / p.run, None, p.error) for p in problems]
|
|
147
|
+
results = [(j.target, None if j.verdict is None else in_schema(j.verdict, schema),
|
|
148
|
+
j.error) for j in judged] + unjudged
|
|
149
|
+
if not no_cache:
|
|
150
|
+
print(f"cache: {hits} of {len(judged)} runs served from the cache", file=sys.stderr)
|
|
151
|
+
else:
|
|
152
|
+
done = verify_batch(batch, jobs=jobs, cache=None if no_cache else VerdictCache(),
|
|
153
|
+
spec=spec, spec_locked_sha256=spec_sha256)
|
|
154
|
+
results = [(t, None if v is None else in_schema(v, schema), e)
|
|
155
|
+
for t, v, e in done.results]
|
|
156
|
+
if not no_cache:
|
|
157
|
+
print(f"cache: {done.hits} of {done.hits + done.misses} runs served from the "
|
|
158
|
+
"cache", file=sys.stderr)
|
|
159
|
+
base = Path(batch).resolve() if settings.is_file() else Path(batch)
|
|
160
|
+
for target, v, err in results:
|
|
161
|
+
rel = target.relative_to(base) if target.is_relative_to(base) else target
|
|
162
|
+
print(f"{'ERROR' if err else v.verdict:16s} {'' if err else v.rule:8s} "
|
|
163
|
+
f"{'-' if err or not v.grade else v.grade} {rel}" + (f" ({err})" if err else ""))
|
|
164
|
+
line, code = summarise(results, schema)
|
|
165
|
+
print(line)
|
|
166
|
+
if junit:
|
|
167
|
+
from courant.verify.junit import render_junit
|
|
168
|
+
|
|
169
|
+
Path(junit).write_text(render_junit(results, base))
|
|
170
|
+
print(f"junit written: {junit}", file=sys.stderr)
|
|
171
|
+
raise typer.Exit(code)
|
|
172
|
+
if not path:
|
|
173
|
+
print("give a case directory or a log file (see --help)", file=sys.stderr)
|
|
174
|
+
raise typer.Exit(4)
|
|
175
|
+
from courant.verify import from_path, verify_inputs, with_spec
|
|
176
|
+
|
|
177
|
+
if spec_sha256 and not spec:
|
|
178
|
+
print("courant verify: --spec-sha256 needs --spec", file=sys.stderr)
|
|
179
|
+
raise typer.Exit(4)
|
|
180
|
+
try:
|
|
181
|
+
inputs = from_path(path, case_json)
|
|
182
|
+
if spec:
|
|
183
|
+
inputs = with_spec(inputs, spec, spec_sha256)
|
|
184
|
+
if checks == "next":
|
|
185
|
+
inputs = inputs.model_copy(update={"checks": "next"})
|
|
186
|
+
verdict = in_schema(verify_inputs(inputs), schema)
|
|
187
|
+
except InputError as exc:
|
|
188
|
+
print(f"courant verify: {exc}", file=sys.stderr)
|
|
189
|
+
raise typer.Exit(4) from exc
|
|
190
|
+
if html:
|
|
191
|
+
from courant.verify.html import render_html
|
|
192
|
+
|
|
193
|
+
Path(html).write_text(render_html(verdict, inputs))
|
|
194
|
+
print(f"report written: {html}", file=sys.stderr)
|
|
195
|
+
|
|
196
|
+
if pack:
|
|
197
|
+
from pathlib import Path as _P
|
|
198
|
+
|
|
199
|
+
from courant.verify.pack import write_pack
|
|
200
|
+
|
|
201
|
+
out = write_pack(verdict, pack, _P(path).name, _P(case_json).name if case_json else None,
|
|
202
|
+
spec_path=spec, spec_locked_sha256=spec_sha256)
|
|
203
|
+
print(f"pack written: {out}/ (verdict.json, report.md, inputs.manifest)", file=sys.stderr)
|
|
204
|
+
if record:
|
|
205
|
+
from courant.record import write_record
|
|
206
|
+
|
|
207
|
+
out = write_record(verdict, record, target_name=Path(path).name,
|
|
208
|
+
case_json_name=Path(case_json).name if case_json else None,
|
|
209
|
+
spec_path=spec, spec_locked_sha256=spec_sha256,
|
|
210
|
+
producer=producer, requester=requester)
|
|
211
|
+
print(f"record written: {out}", file=sys.stderr)
|
|
212
|
+
if as_json:
|
|
213
|
+
sys.stdout.write(render_json(verdict))
|
|
214
|
+
elif report == "md":
|
|
215
|
+
sys.stdout.write(render_markdown(verdict))
|
|
216
|
+
elif report == "html":
|
|
217
|
+
from courant.verify.html import render_html
|
|
218
|
+
|
|
219
|
+
sys.stdout.write(render_html(verdict, inputs))
|
|
220
|
+
else:
|
|
221
|
+
sys.stdout.write(render_text(verdict))
|
|
222
|
+
raise typer.Exit(EXIT[verdict.verdict])
|
courant/cli/config.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"""Local CLI state — ``~/.courant/``.
|
|
2
|
+
|
|
3
|
+
config.toml user settings, hand-editable
|
|
4
|
+
credentials.json the API token, mode 0600
|
|
5
|
+
queue.db events pending upload (see queue.py)
|
|
6
|
+
|
|
7
|
+
Two rules:
|
|
8
|
+
|
|
9
|
+
1. **Credentials never live in config.toml.** People paste config files into
|
|
10
|
+
issues and commit them to dotfile repos. The token lives in its own
|
|
11
|
+
0600 file that nothing invites you to share.
|
|
12
|
+
2. **Everything works with no config at all.** ``courant analyze`` must run on a
|
|
13
|
+
cluster with no account, no network, and no writable home directory. Missing
|
|
14
|
+
config is a normal state, not an error.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
import stat
|
|
22
|
+
import tomllib
|
|
23
|
+
from dataclasses import dataclass, field
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from typing import Any
|
|
26
|
+
|
|
27
|
+
DEFAULT_API_URL = "https://api.courant.dev"
|
|
28
|
+
|
|
29
|
+
CONFIG_DIR_ENV = "COURANT_HOME"
|
|
30
|
+
API_URL_ENV = "COURANT_API_URL"
|
|
31
|
+
TOKEN_ENV = "COURANT_TOKEN" # for CI, where a device flow has no browser
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def config_dir() -> Path:
|
|
35
|
+
"""``~/.courant`` unless ``COURANT_HOME`` overrides it (tests, CI, sandboxes)."""
|
|
36
|
+
return Path(os.environ.get(CONFIG_DIR_ENV, Path.home() / ".courant"))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _ensure_dir() -> Path:
|
|
40
|
+
d = config_dir()
|
|
41
|
+
d.mkdir(parents=True, mode=0o700, exist_ok=True)
|
|
42
|
+
return d
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
# ---------------------------------------------------------------------------
|
|
46
|
+
# Credentials
|
|
47
|
+
# ---------------------------------------------------------------------------
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True, slots=True)
|
|
51
|
+
class Credentials:
|
|
52
|
+
token: str
|
|
53
|
+
org_id: str
|
|
54
|
+
org_name: str = ""
|
|
55
|
+
plan: str = ""
|
|
56
|
+
api_url: str = DEFAULT_API_URL
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def prefix(self) -> str:
|
|
60
|
+
"""Safe to print or log — identifies the token without exposing it."""
|
|
61
|
+
return self.token[:12] if self.token else ""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def credentials_path() -> Path:
|
|
65
|
+
return config_dir() / "credentials.json"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def load_credentials() -> Credentials | None:
|
|
69
|
+
"""Environment first, then disk. ``None`` means "not logged in", not an error.
|
|
70
|
+
|
|
71
|
+
``COURANT_TOKEN`` exists for CI and headless machines where no browser can
|
|
72
|
+
complete a device flow.
|
|
73
|
+
"""
|
|
74
|
+
env_token = os.environ.get(TOKEN_ENV)
|
|
75
|
+
if env_token:
|
|
76
|
+
return Credentials(
|
|
77
|
+
token=env_token,
|
|
78
|
+
org_id=os.environ.get("COURANT_ORG_ID", ""),
|
|
79
|
+
api_url=os.environ.get(API_URL_ENV, DEFAULT_API_URL),
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
path = credentials_path()
|
|
83
|
+
if not path.exists():
|
|
84
|
+
return None
|
|
85
|
+
try:
|
|
86
|
+
data = json.loads(path.read_text())
|
|
87
|
+
return Credentials(
|
|
88
|
+
token=data["token"],
|
|
89
|
+
org_id=data.get("org_id", ""),
|
|
90
|
+
org_name=data.get("org_name", ""),
|
|
91
|
+
plan=data.get("plan", ""),
|
|
92
|
+
api_url=data.get("api_url", DEFAULT_API_URL),
|
|
93
|
+
)
|
|
94
|
+
except (json.JSONDecodeError, KeyError, OSError):
|
|
95
|
+
# A corrupt credentials file must not brick the CLI — `courant login`
|
|
96
|
+
# has to remain reachable to fix it.
|
|
97
|
+
return None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def save_credentials(creds: Credentials) -> Path:
|
|
101
|
+
"""Write 0600. The mode is set before the token is written, so the secret
|
|
102
|
+
is never briefly world-readable on a shared login node."""
|
|
103
|
+
_ensure_dir()
|
|
104
|
+
path = credentials_path()
|
|
105
|
+
|
|
106
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
107
|
+
with os.fdopen(fd, "w") as fh:
|
|
108
|
+
json.dump(
|
|
109
|
+
{
|
|
110
|
+
"token": creds.token,
|
|
111
|
+
"org_id": creds.org_id,
|
|
112
|
+
"org_name": creds.org_name,
|
|
113
|
+
"plan": creds.plan,
|
|
114
|
+
"api_url": creds.api_url,
|
|
115
|
+
},
|
|
116
|
+
fh,
|
|
117
|
+
indent=2,
|
|
118
|
+
)
|
|
119
|
+
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR)
|
|
120
|
+
return path
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def clear_credentials() -> bool:
|
|
124
|
+
path = credentials_path()
|
|
125
|
+
if path.exists():
|
|
126
|
+
path.unlink()
|
|
127
|
+
return True
|
|
128
|
+
return False
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
# ---------------------------------------------------------------------------
|
|
132
|
+
# Settings
|
|
133
|
+
# ---------------------------------------------------------------------------
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@dataclass
|
|
137
|
+
class Settings:
|
|
138
|
+
"""``config.toml``, with defaults for everything."""
|
|
139
|
+
|
|
140
|
+
api_url: str = DEFAULT_API_URL
|
|
141
|
+
|
|
142
|
+
mode: str = "copilot" # observe | copilot | autopilot
|
|
143
|
+
max_attempts: int = 3
|
|
144
|
+
notify: list[str] = field(default_factory=lambda: ["desktop"])
|
|
145
|
+
|
|
146
|
+
share_case_metadata: bool = True
|
|
147
|
+
# Off by default and asked once, in plain language, after the third
|
|
148
|
+
# successful diagnosis. The corpus is the moat, but taking it silently
|
|
149
|
+
# would betray the trust the product is built on (Product Bible §06).
|
|
150
|
+
contribute_corpus: bool = False
|
|
151
|
+
|
|
152
|
+
watch_directories: list[str] = field(default_factory=list)
|
|
153
|
+
poll_ms: int = 500
|
|
154
|
+
|
|
155
|
+
fix_allow: list[str] = field(default_factory=lambda: ["numerics", "schemes"])
|
|
156
|
+
fix_deny: list[str] = field(default_factory=lambda: ["mesh"])
|
|
157
|
+
|
|
158
|
+
def effective_api_url(self, creds: Credentials | None = None) -> str:
|
|
159
|
+
"""Precedence: env > credentials > config > default.
|
|
160
|
+
|
|
161
|
+
Credentials outrank config so that logging into staging does not
|
|
162
|
+
silently keep pointing the agent at production.
|
|
163
|
+
"""
|
|
164
|
+
if os.environ.get(API_URL_ENV):
|
|
165
|
+
return os.environ[API_URL_ENV].rstrip("/")
|
|
166
|
+
if creds and creds.api_url:
|
|
167
|
+
return creds.api_url.rstrip("/")
|
|
168
|
+
return self.api_url.rstrip("/")
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def config_path() -> Path:
|
|
172
|
+
return config_dir() / "config.toml"
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def load_settings() -> Settings:
|
|
176
|
+
path = config_path()
|
|
177
|
+
if not path.exists():
|
|
178
|
+
return Settings()
|
|
179
|
+
try:
|
|
180
|
+
raw = tomllib.loads(path.read_text())
|
|
181
|
+
except (tomllib.TOMLDecodeError, OSError):
|
|
182
|
+
# A malformed config falls back to defaults rather than refusing to
|
|
183
|
+
# run. An engineer at 3 a.m. should not be blocked by a stray bracket.
|
|
184
|
+
return Settings()
|
|
185
|
+
|
|
186
|
+
api = raw.get("api", {})
|
|
187
|
+
defaults = raw.get("defaults", {})
|
|
188
|
+
privacy = raw.get("privacy", {})
|
|
189
|
+
watch = raw.get("watch", {})
|
|
190
|
+
fix = raw.get("fix", {})
|
|
191
|
+
|
|
192
|
+
return Settings(
|
|
193
|
+
api_url=api.get("url", DEFAULT_API_URL),
|
|
194
|
+
mode=defaults.get("mode", "copilot"),
|
|
195
|
+
max_attempts=int(defaults.get("max_attempts", 3)),
|
|
196
|
+
notify=list(defaults.get("notify", ["desktop"])),
|
|
197
|
+
share_case_metadata=bool(privacy.get("share_case_metadata", True)),
|
|
198
|
+
contribute_corpus=bool(privacy.get("contribute_corpus", False)),
|
|
199
|
+
watch_directories=list(watch.get("directories", [])),
|
|
200
|
+
poll_ms=int(watch.get("poll_ms", 500)),
|
|
201
|
+
fix_allow=list(fix.get("allow", ["numerics", "schemes"])),
|
|
202
|
+
fix_deny=list(fix.get("deny", ["mesh"])),
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _toml_value(value: Any) -> str:
|
|
207
|
+
if isinstance(value, bool):
|
|
208
|
+
return "true" if value else "false"
|
|
209
|
+
if isinstance(value, (int, float)):
|
|
210
|
+
return str(value)
|
|
211
|
+
if isinstance(value, list):
|
|
212
|
+
return "[" + ", ".join(_toml_value(v) for v in value) + "]"
|
|
213
|
+
return json.dumps(str(value)) # correct TOML string escaping
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def save_settings(settings: Settings) -> Path:
|
|
217
|
+
"""Write config.toml.
|
|
218
|
+
|
|
219
|
+
Hand-rolled rather than pulling in a TOML writer: the schema is small and
|
|
220
|
+
fixed, and every dependency is one more thing that has to build for four
|
|
221
|
+
platforms in the packaged binary.
|
|
222
|
+
"""
|
|
223
|
+
_ensure_dir()
|
|
224
|
+
path = config_path()
|
|
225
|
+
|
|
226
|
+
sections = {
|
|
227
|
+
"api": {"url": settings.api_url},
|
|
228
|
+
"defaults": {"mode": settings.mode, "max_attempts": settings.max_attempts,
|
|
229
|
+
"notify": settings.notify},
|
|
230
|
+
"privacy": {"share_case_metadata": settings.share_case_metadata,
|
|
231
|
+
"contribute_corpus": settings.contribute_corpus},
|
|
232
|
+
"watch": {"directories": settings.watch_directories, "poll_ms": settings.poll_ms},
|
|
233
|
+
"fix": {"allow": settings.fix_allow, "deny": settings.fix_deny},
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
lines = ["# Courant CLI configuration — https://docs.courant.dev/cli/config",
|
|
237
|
+
"# Credentials are NOT stored here; see credentials.json.", ""]
|
|
238
|
+
for section, values in sections.items():
|
|
239
|
+
lines.append(f"[{section}]")
|
|
240
|
+
lines.extend(f"{key} = {_toml_value(val)}" for key, val in values.items())
|
|
241
|
+
lines.append("")
|
|
242
|
+
|
|
243
|
+
path.write_text("\n".join(lines))
|
|
244
|
+
return path
|