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.
Files changed (152) hide show
  1. courant/__init__.py +26 -0
  2. courant/case/__init__.py +0 -0
  3. courant/case/_foam_reader.py +269 -0
  4. courant/case/config.py +134 -0
  5. courant/case/mesh.py +135 -0
  6. courant/case/reads.py +90 -0
  7. courant/case/schemes.py +99 -0
  8. courant/case/solvers.py +170 -0
  9. courant/cli/__init__.py +0 -0
  10. courant/cli/commands/__init__.py +6 -0
  11. courant/cli/commands/audit.py +40 -0
  12. courant/cli/commands/convergence.py +68 -0
  13. courant/cli/commands/ctest.py +76 -0
  14. courant/cli/commands/doctor.py +162 -0
  15. courant/cli/commands/gate.py +88 -0
  16. courant/cli/commands/live.py +73 -0
  17. courant/cli/commands/mcp.py +57 -0
  18. courant/cli/commands/preflight.py +36 -0
  19. courant/cli/commands/spec.py +231 -0
  20. courant/cli/commands/tour.py +122 -0
  21. courant/cli/commands/update.py +213 -0
  22. courant/cli/commands/verify.py +222 -0
  23. courant/cli/config.py +244 -0
  24. courant/cli/guard.py +69 -0
  25. courant/cli/main.py +130 -0
  26. courant/cli/tail.py +351 -0
  27. courant/config.py +155 -0
  28. courant/converge/__init__.py +57 -0
  29. courant/converge/assess.py +823 -0
  30. courant/converge/exact.py +112 -0
  31. courant/converge/render.py +182 -0
  32. courant/converge/scale.py +87 -0
  33. courant/converge/sentences.py +82 -0
  34. courant/converge/series.py +413 -0
  35. courant/converge/steady.py +261 -0
  36. courant/converge/tables.py +1019 -0
  37. courant/converge/transient.py +314 -0
  38. courant/ctest/__init__.py +6 -0
  39. courant/ctest/build.py +82 -0
  40. courant/ctest/data/judge-v0.labels.jsonl +31 -0
  41. courant/ctest/data/judge-v0.tasks.jsonl.gz +0 -0
  42. courant/ctest/judges/__init__.py +27 -0
  43. courant/ctest/judges/constant.py +18 -0
  44. courant/ctest/judges/courant.py +23 -0
  45. courant/ctest/judges/llm.py +166 -0
  46. courant/ctest/run.py +74 -0
  47. courant/ctest/schema.py +46 -0
  48. courant/ctest/score.py +91 -0
  49. courant/ctest/splits.py +20 -0
  50. courant/data/__init__.py +46 -0
  51. courant/data/certification.json +1 -0
  52. courant/data/certified_codes.json +18 -0
  53. courant/data/demo/icoFoam_cavity__cfl_blowup.case.json +68 -0
  54. courant/data/demo/icoFoam_cavity__cfl_blowup.log.gz +0 -0
  55. courant/data/demo/icoFoam_cavity__healthy.case.json +68 -0
  56. courant/data/demo/icoFoam_cavity__healthy.log.gz +0 -0
  57. courant/data/demo/icoFoam_cavity__transport_units.case.json +68 -0
  58. courant/data/demo/icoFoam_cavity__transport_units.log.gz +0 -0
  59. courant/data/demo/pitzDaily_fixed_budget.tar.gz +0 -0
  60. courant/data/schemas/audit.1.json +129 -0
  61. courant/data/schemas/cache.1.json +77 -0
  62. courant/data/schemas/convergence.1.json +112 -0
  63. courant/data/schemas/error-rates.1.json +53 -0
  64. courant/data/schemas/preflight.1.json +250 -0
  65. courant/data/schemas/record.1.json +155 -0
  66. courant/data/schemas/release-signature.1.json +39 -0
  67. courant/data/schemas/spec.1.json +258 -0
  68. courant/data/schemas/support.1.json +80 -0
  69. courant/data/schemas/verdict.1.json +716 -0
  70. courant/data/schemas/verdict.2.json +752 -0
  71. courant/diagnosis/__init__.py +0 -0
  72. courant/diagnosis/bundle.py +168 -0
  73. courant/diagnosis/checkers.py +919 -0
  74. courant/diagnosis/deterministic.py +110 -0
  75. courant/diagnosis/findings.py +107 -0
  76. courant/diagnosis/kb.py +188 -0
  77. courant/diagnosis/kb_data.py +253 -0
  78. courant/diagnosis/llm.py +299 -0
  79. courant/diagnosis/redact.py +425 -0
  80. courant/diagnosis/schema.py +83 -0
  81. courant/events/__init__.py +35 -0
  82. courant/events/core.py +194 -0
  83. courant/events/diverged.py +55 -0
  84. courant/gate/__init__.py +1 -0
  85. courant/gate/config.py +150 -0
  86. courant/gate/run.py +295 -0
  87. courant/live/__init__.py +16 -0
  88. courant/live/engine.py +155 -0
  89. courant/live/watch.py +164 -0
  90. courant/llm/__init__.py +59 -0
  91. courant/llm/allowlist.py +60 -0
  92. courant/llm/anthropic.py +137 -0
  93. courant/llm/budget.py +491 -0
  94. courant/llm/door.py +1071 -0
  95. courant/llm/errors.py +105 -0
  96. courant/llm/openrouter.py +118 -0
  97. courant/llm/policy.py +268 -0
  98. courant/llm/transport.py +48 -0
  99. courant/mcp/__init__.py +7 -0
  100. courant/mcp/server.py +113 -0
  101. courant/mcp/tools.py +177 -0
  102. courant/record/__init__.py +22 -0
  103. courant/record/filter.py +99 -0
  104. courant/record/record.py +149 -0
  105. courant/release.py +205 -0
  106. courant/signing.py +99 -0
  107. courant/spec/__init__.py +31 -0
  108. courant/spec/check.py +353 -0
  109. courant/spec/deck.py +455 -0
  110. courant/spec/extract.py +181 -0
  111. courant/spec/impossible.py +197 -0
  112. courant/spec/model.py +194 -0
  113. courant/taxonomy.py +219 -0
  114. courant/verification/__init__.py +30 -0
  115. courant/verification/_fluid_reader.py +228 -0
  116. courant/verification/bounding.py +84 -0
  117. courant/verification/checks.py +369 -0
  118. courant/verification/convergence.py +257 -0
  119. courant/verification/fields.py +38 -0
  120. courant/verification/grade.py +101 -0
  121. courant/verification/suite.py +30 -0
  122. courant/verify/__init__.py +37 -0
  123. courant/verify/about.py +100 -0
  124. courant/verify/audit.py +209 -0
  125. courant/verify/batch.py +141 -0
  126. courant/verify/cache.py +329 -0
  127. courant/verify/checks.py +37 -0
  128. courant/verify/html.py +330 -0
  129. courant/verify/ingest.py +115 -0
  130. courant/verify/junit.py +48 -0
  131. courant/verify/outcome.py +74 -0
  132. courant/verify/pack.py +106 -0
  133. courant/verify/pipeline.py +396 -0
  134. courant/verify/policy.py +167 -0
  135. courant/verify/preflight.py +166 -0
  136. courant/verify/render.py +174 -0
  137. courant/verify/schema.py +398 -0
  138. courant/verify/sentences.py +137 -0
  139. courant/verify/support.py +142 -0
  140. courant/verify/verdict2.py +235 -0
  141. courant/watcher/__init__.py +13 -0
  142. courant/watcher/anomaly.py +244 -0
  143. courant/watcher/exitcode.py +23 -0
  144. courant/watcher/parser.py +435 -0
  145. courant/watcher/watcher.py +49 -0
  146. courant_dev-0.5.0.dist-info/METADATA +146 -0
  147. courant_dev-0.5.0.dist-info/RECORD +152 -0
  148. courant_dev-0.5.0.dist-info/WHEEL +5 -0
  149. courant_dev-0.5.0.dist-info/entry_points.txt +3 -0
  150. courant_dev-0.5.0.dist-info/licenses/LICENSE +202 -0
  151. courant_dev-0.5.0.dist-info/licenses/NOTICE +4 -0
  152. courant_dev-0.5.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,88 @@
1
+ """`courant gate`: the check a CI job runs (TRD GATE-7, GATE-8).
2
+
3
+ Verifies the runs a repository names, writes a Markdown job summary and an evidence pack per
4
+ run, and exits 0 when the check passes. It is what the `courant-gate` GitHub Action calls: every
5
+ Action input arrives here as an environment variable (`COURANT_GATE_*`), so the Action has no
6
+ logic of its own and the same check runs on a laptop.
7
+
8
+ Exit codes:
9
+ - 0 the check passes
10
+ - 1 a run was judged and fails the check
11
+ - 4 something could not be judged: a configuration error, a pattern that matches no run, a run
12
+ with no output, an unreadable input
13
+
14
+ Settings come from `courant.toml` in --root (or --config), then these flags, which add one
15
+ more [[run]] group and override the top-level keys. An unknown key in `courant.toml` is an
16
+ error. Read-only apart from --packs-dir, --pack-store and --summary. No network.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import sys
22
+ from pathlib import Path
23
+
24
+ import typer
25
+
26
+
27
+ def _split(values: list[str] | None) -> list[str]:
28
+ """A list option from the Action arrives as one newline- or comma-separated string."""
29
+ out: list[str] = []
30
+ for v in values or []:
31
+ out += [p.strip() for chunk in v.splitlines() for p in chunk.split(",") if p.strip()]
32
+ return out
33
+
34
+
35
+ def gate(
36
+ root: str = typer.Option(".", "--root", envvar="COURANT_GATE_ROOT", help="The repository root; globs and paths are relative to it."),
37
+ config: str = typer.Option(None, "--config", envvar="COURANT_GATE_CONFIG", help="The settings file (default: courant.toml in --root, if it exists)."),
38
+ paths: list[str] = typer.Option(None, "--paths", envvar="COURANT_GATE_PATHS", help="Case globs: case directories and solver logs. Newline- or comma-separated from the Action."),
39
+ outputs: list[str] = typer.Option(None, "--outputs", envvar="COURANT_GATE_OUTPUTS", help="Where each run's log and results are: a directory with one entry per run name."),
40
+ spec: str = typer.Option(None, "--spec", envvar="COURANT_GATE_SPEC", help="The task specification (courant.spec/1) the runs were asked to meet."),
41
+ spec_sha256: str = typer.Option(None, "--spec-sha256", envvar="COURANT_GATE_SPEC_SHA256", help="The hash the specification was locked at. Required with --spec."),
42
+ fail_on: str = typer.Option(None, "--fail-on", envvar="COURANT_GATE_FAIL_ON", help="not-accept (default): anything but accept fails. reject: an insufficient run passes."),
43
+ pack_store: str = typer.Option(None, "--pack-store", envvar="COURANT_GATE_PACK_STORE", help="Also keep each run's evidence pack at this path in the repository."),
44
+ courant_version: str = typer.Option(None, "--courant-version", envvar="COURANT_GATE_COURANT_VERSION", help="Refuse to run under another Courant version ('latest' pins nothing)."),
45
+ packs_dir: str = typer.Option(None, "--packs-dir", envvar="COURANT_GATE_PACKS_DIR", help="Write each run's evidence pack here (the Action uploads it as an artefact)."),
46
+ summary: str = typer.Option(None, "--summary", envvar="COURANT_GATE_SUMMARY", help="Append the Markdown summary to this file ($GITHUB_STEP_SUMMARY in a workflow)."),
47
+ jobs: int = typer.Option(1, "--jobs", min=1, help="Verify this many runs at once."),
48
+ cache_on: bool = typer.Option(False, "--cache", help="Use the verdict cache ($COURANT_CACHE_DIR). Off by default: a CI runner is a shared, throw-away machine."),
49
+ debug: bool = typer.Option(False, "--debug", help="Print the traceback of an unexpected error."),
50
+ ) -> None:
51
+ """The CI check: verify the named runs, write the summary and the packs, pass or fail."""
52
+ from courant.gate.config import ConfigError, GateConfig, load_config, make_group, merged
53
+ from courant.gate.run import render_summary, run_gate
54
+ from courant.verify.cache import VerdictCache
55
+
56
+ root_path = Path(root)
57
+ try:
58
+ cfg_path = Path(config) if config else root_path / "courant.toml"
59
+ if config and not cfg_path.is_file():
60
+ raise ConfigError(f"no such settings file: {config}")
61
+ base = load_config(cfg_path) if cfg_path.is_file() else GateConfig()
62
+ group = None
63
+ if _split(paths):
64
+ group = make_group(_split(paths), _split(outputs), spec or None, spec_sha256 or None,
65
+ where="the Action's inputs")
66
+ elif outputs or spec or spec_sha256:
67
+ raise ConfigError("`outputs`, `spec` and `spec-sha256` apply to `paths`, which is empty")
68
+ cfg = merged(base, group=group, fail_on=fail_on or None, pack_store=pack_store or None,
69
+ courant_version=courant_version or None)
70
+ result = run_gate(root_path, cfg, packs_dir=packs_dir or None, jobs=jobs,
71
+ cache=VerdictCache() if cache_on else None)
72
+ except ConfigError as exc:
73
+ print(f"courant gate: {exc}", file=sys.stderr)
74
+ raise typer.Exit(4) from exc
75
+ except Exception as exc: # GATE-10: no traceback
76
+ if debug:
77
+ raise
78
+ from courant import __version__
79
+
80
+ print(f"courant gate: internal error (courant {__version__}): "
81
+ f"{type(exc).__name__}: {exc}. Rerun with --debug for the traceback.", file=sys.stderr)
82
+ raise typer.Exit(4) from exc
83
+ text = render_summary(result)
84
+ sys.stdout.write(text)
85
+ if summary:
86
+ with open(summary, "a", encoding="utf-8") as fh:
87
+ fh.write(text)
88
+ raise typer.Exit(result.exit_code)
@@ -0,0 +1,73 @@
1
+ """`courant watch`: follow a running solve and say, while it runs, whether it has failed or settled.
2
+
3
+ Read-only (TRD LIVE-1). It never sends a signal, never edits the case and never writes into
4
+ it. To act on its advice, let your own job script use the exit code:
5
+
6
+ courant watch ./case --exit-on-fail || scancel "$SLURM_JOB_ID"
7
+
8
+ Exit codes:
9
+ - 0: the run finished and the verdict is accept (or `--once` and it is still running);
10
+ - 2: reject, or FAILING with `--exit-on-fail`;
11
+ - 3: insufficient, or the log went idle without the solver's End;
12
+ - 4: no log could be found.
13
+
14
+ The previous product's copilot, which applied fixes, is still available as `courant copilot`.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import sys
20
+ from pathlib import Path
21
+
22
+ import typer
23
+
24
+
25
+ def watch(
26
+ case: str = typer.Argument(..., help="The case directory to follow, or a solver log file."),
27
+ log: str = typer.Option(None, "--log", "-l", help="The log to follow. Default: the solver log in the case (it may not exist yet)."),
28
+ interval: float = typer.Option(2.0, "--interval", help="Seconds between evaluations (raised automatically to keep the watcher light)."),
29
+ as_json: bool = typer.Option(False, "--json", help="One JSON object per state change, then the verdict."),
30
+ exit_on_fail: bool = typer.Option(False, "--exit-on-fail", help="Exit 2 at the first FAILING state, so a job script can act."),
31
+ once: bool = typer.Option(False, "--once", help="Evaluate what is written now and exit."),
32
+ idle_timeout: float = typer.Option(600.0, "--idle-timeout", help="Give up after the log has not grown for this long (s)."),
33
+ start_timeout: float = typer.Option(600.0, "--start-timeout", help="How long to wait for the log to appear (s)."),
34
+ ) -> None:
35
+ """Follow a running solve, read-only: FAILING or converged as it happens, the verdict when it ends."""
36
+ from courant.cli.tail import Chunk, LogTail, find_log, wait_for_log
37
+ from courant.live.watch import run_watch
38
+
39
+ path = Path(case)
40
+ case_dir: Path | None
41
+ if path.is_file():
42
+ log_path = path
43
+ case_dir = path.parent if (path.parent / "system").is_dir() else None
44
+ elif path.is_dir():
45
+ case_dir = path
46
+ found = Path(log) if log else (find_log(path) if once else
47
+ wait_for_log(path, timeout=start_timeout))
48
+ if found is None:
49
+ print(f"courant watch: no solver log (log.<solver>) in {path}", file=sys.stderr)
50
+ raise typer.Exit(4)
51
+ log_path = Path(found)
52
+ else:
53
+ print(f"courant watch: no such case or log: {path}", file=sys.stderr)
54
+ raise typer.Exit(4)
55
+
56
+ def emit(line: str) -> None:
57
+ print(line, flush=True)
58
+
59
+ if not as_json:
60
+ emit(f"Courant is watching {(case_dir or log_path).name} · {log_path.name} · read-only: "
61
+ f"it reports, it never stops or edits the run")
62
+ if once:
63
+ chunks = [Chunk(text=log_path.read_text(errors="replace"), offset=0)]
64
+ else:
65
+ chunks = LogTail(log_path, idle_timeout=idle_timeout, start_timeout=start_timeout).follow()
66
+ try:
67
+ outcome = run_watch(chunks, case_dir=case_dir, log_path=log_path, emit=emit,
68
+ as_json=as_json, exit_on_fail=exit_on_fail, interval=interval,
69
+ once=once)
70
+ except KeyboardInterrupt:
71
+ print("\n stopped watching; the run itself is untouched", file=sys.stderr)
72
+ raise typer.Exit(130) from None
73
+ raise typer.Exit(outcome.exit_code)
@@ -0,0 +1,57 @@
1
+ """`courant mcp`: the MCP server, from the same binary (TRD PKG-8).
2
+
3
+ courant mcp --root ~/runs # stdio; give this command to Claude Code, Cursor, ...
4
+
5
+ Equivalent to `courant-mcp`. Every tool is read-only and confined to the roots given.
6
+
7
+ courant mcp --print-config --root ~/runs # the client configuration, for Claude Code and Codex
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import shlex
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ import typer
18
+
19
+
20
+ def client_config(roots: list[str]) -> str:
21
+ """The configuration a client needs to start this server (GATE-6): Claude Code's command
22
+ and `.mcp.json`, and Codex's `config.toml`. Generated from one argument list, so the three
23
+ cannot disagree; a test parses the JSON and the TOML."""
24
+ args = ["mcp", *(a for r in roots for a in ("--root", r))]
25
+ shell = " ".join(shlex.quote(a) for a in ["claude", "mcp", "add", "courant", "--",
26
+ "courant", *args])
27
+ mcp_json = json.dumps({"mcpServers": {"courant": {"command": "courant", "args": args}}},
28
+ indent=2)
29
+ toml_args = ", ".join(json.dumps(a) for a in args)
30
+ from courant import DISTRIBUTION
31
+
32
+ return (f"# Needs `courant` on PATH: pip install '{DISTRIBUTION}[mcp]' (PyPI's `courant` is "
33
+ f"another project), or the single-file binary.\n\n"
34
+ f"# Claude Code, from a shell:\n{shell}\n\n"
35
+ f"# Claude Code or Cursor, in .mcp.json:\n{mcp_json}\n\n"
36
+ f"# Codex, in ~/.codex/config.toml:\n[mcp_servers.courant]\n"
37
+ f'command = "courant"\nargs = [{toml_args}]\n')
38
+
39
+
40
+ def mcp(
41
+ root: list[str] = typer.Option(None, "--root", help="A directory the agent may read runs from. Repeatable. Default: the current directory."),
42
+ print_config: bool = typer.Option(False, "--print-config", help="Print the client configuration (Claude Code, Cursor, Codex) for this server and exit."),
43
+ ) -> None:
44
+ """Serve Courant's read-only tools to an AI agent over MCP (stdio)."""
45
+ if print_config:
46
+ sys.stdout.write(client_config([str(Path(r).resolve())
47
+ for r in (root or ["."])]))
48
+ raise typer.Exit(0)
49
+ import importlib.util
50
+
51
+ if importlib.util.find_spec("mcp") is None: # the optional extra is missing
52
+ print("courant mcp needs the MCP extra: pip install 'courant-dev[mcp]' "
53
+ "(this build was made without it)", file=sys.stderr)
54
+ raise typer.Exit(4)
55
+ from courant.mcp.server import build
56
+
57
+ build(list(root) if root else ["."]).run("stdio")
@@ -0,0 +1,36 @@
1
+ """`courant preflight`: catch a broken setup before the solver runs (TRD PRE-1).
2
+
3
+ Exit codes:
4
+ - 0: NO_SETUP_FAULT_FOUND;
5
+ - 2: SETUP_FAULT;
6
+ - 3: NOT_ASSESSABLE (no readable configuration);
7
+ - 4: the input could not be read.
8
+
9
+ Read-only and offline. No log is needed, because nothing has run yet.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import sys
15
+
16
+ import typer
17
+
18
+ EXIT = {"NO_SETUP_FAULT_FOUND": 0, "SETUP_FAULT": 2, "NOT_ASSESSABLE": 3}
19
+
20
+
21
+ def preflight(
22
+ case: str = typer.Argument(..., help="A case directory, before (or after) it runs."),
23
+ case_json: str = typer.Option(None, "--case-json", help="A captured configuration sidecar (*.case.json) instead of a case directory."),
24
+ as_json: bool = typer.Option(False, "--json", help="Print the canonical preflight JSON."),
25
+ ) -> None:
26
+ """Check a case's setup before the solver spends anything: tolerances, relaxation, boundaries, units, mesh."""
27
+ from courant.verify.ingest import InputError
28
+ from courant.verify.preflight import preflight_path, render_text
29
+
30
+ try:
31
+ p = preflight_path(case, case_json)
32
+ except (InputError, OSError, ValueError) as exc:
33
+ print(f"courant preflight: {exc}", file=sys.stderr)
34
+ raise typer.Exit(4) from exc
35
+ sys.stdout.write(p.to_json() if as_json else render_text(p))
36
+ raise typer.Exit(EXIT[p.verdict])
@@ -0,0 +1,231 @@
1
+ """`courant spec`: write, lock and check a task specification (PRD 2.0 P2-SPEC).
2
+
3
+ courant spec init ./reference_case -o spec.json --task "pitzDaily, inlet 10 m/s"
4
+ courant spec hash spec.json # lock it before the run
5
+ courant spec check ./agent_case --spec spec.json # conformance only, before or after a run
6
+ courant verify ./agent_case --spec spec.json --spec-sha256 <hash>
7
+
8
+ `check` needs no log: conformance is decided by the case as set up, so it can run before the
9
+ solver spends anything. Exit codes: 0 every named value matches; 2 a value does not; 3 a
10
+ value could not be read, or the specification is impossible in itself (SPEC-9); 4 the inputs
11
+ could not be read.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import sys
17
+ from pathlib import Path
18
+
19
+ import typer
20
+
21
+ app = typer.Typer(help="Write, lock and check a task specification (courant.spec/1).",
22
+ no_args_is_help=True, add_completion=False)
23
+
24
+
25
+ @app.command("init")
26
+ def init(
27
+ case: str = typer.Argument(..., help="The reference case the task is written against."),
28
+ out: str = typer.Option(None, "-o", "--out", help="Write the specification here (default: stdout)."),
29
+ task: str = typer.Option(None, "--task", help="One line saying what the task asks for."),
30
+ no_mesh: bool = typer.Option(False, "--no-mesh", help="Leave the mesh cell counts out (they are a modelling choice)."),
31
+ ) -> None:
32
+ """Draft a specification from a reference case. Review it, then lock it with `courant spec hash`."""
33
+ from courant.spec import draft_spec
34
+
35
+ if not Path(case).is_dir():
36
+ print(f"courant spec init: no such case directory: {case}", file=sys.stderr)
37
+ raise typer.Exit(4)
38
+ try:
39
+ spec = draft_spec(case, task=task, include_mesh=not no_mesh)
40
+ except ValueError as exc:
41
+ print(f"courant spec init: {exc}", file=sys.stderr)
42
+ raise typer.Exit(4) from exc
43
+ text = spec.to_json()
44
+ if out:
45
+ Path(out).write_text(text)
46
+ from courant.spec import spec_sha256
47
+
48
+ print(f"specification written: {out} ({len(spec.items)} values) · sha256 "
49
+ f"{spec_sha256(out)}", file=sys.stderr)
50
+ else:
51
+ sys.stdout.write(text)
52
+
53
+
54
+ @app.command("hash")
55
+ def hash_(spec: str = typer.Argument(..., help="A courant.spec/1 file.")) -> None:
56
+ """Print the SHA-256 that locks this specification. Record it before the run."""
57
+ from courant.spec import SpecError, load_spec
58
+
59
+ try:
60
+ _, sha = load_spec(spec)
61
+ except SpecError as exc:
62
+ print(f"courant spec hash: {exc}", file=sys.stderr)
63
+ raise typer.Exit(4) from exc
64
+ print(sha)
65
+
66
+
67
+ @app.command("check")
68
+ def check(
69
+ case: str = typer.Argument(..., help="The case to check, before or after its run."),
70
+ spec: str = typer.Option(..., "--spec", help="The task specification (courant.spec/1)."),
71
+ spec_sha256: str = typer.Option(None, "--spec-sha256", help="The hash it was locked at."),
72
+ as_json: bool = typer.Option(False, "--json", help="Print the conformance block as JSON."),
73
+ ) -> None:
74
+ """Is this case the problem that was asked? Every named value, compared to the case."""
75
+ from courant.spec import SpecError, check_conformance, load_spec
76
+ from courant.verify.schema import canonical_json
77
+
78
+ if not Path(case).is_dir():
79
+ print(f"courant spec check: no such case directory: {case}", file=sys.stderr)
80
+ raise typer.Exit(4)
81
+ try:
82
+ spec_model, sha = load_spec(spec)
83
+ except SpecError as exc:
84
+ print(f"courant spec check: {exc}", file=sys.stderr)
85
+ raise typer.Exit(4) from exc
86
+ locked = spec_sha256.strip().lower() if spec_sha256 else None
87
+ block = check_conformance(spec_model, case, spec_sha256=sha, locked_sha256=locked)
88
+ if locked and locked != sha:
89
+ print(f"SPECIFICATION CHANGED {spec} is {sha[:12]}, locked at {locked[:12]}")
90
+ raise typer.Exit(3)
91
+ if block.invalid: # SPEC-9: nothing was compared
92
+ if as_json:
93
+ sys.stdout.write(canonical_json(block.model_dump(mode="json")))
94
+ else:
95
+ print(f"SPECIFICATION IMPOSSIBLE {spec} cannot be met by any case; nothing was "
96
+ "compared")
97
+ for why in block.invalid:
98
+ print(f" ✗ {why}")
99
+ raise typer.Exit(3)
100
+ if as_json:
101
+ sys.stdout.write(canonical_json(block.model_dump(mode="json")))
102
+ else:
103
+ ok = sum(1 for i in block.items if i.conforms)
104
+ head = ("CONFORMS" if not block.nonconformant and not block.unreadable
105
+ else "DOES NOT CONFORM" if block.nonconformant else "NOT FULLY CHECKED")
106
+ print(f"{head} {ok} of {len(block.items)} specified values match · spec {sha[:12]}")
107
+ width = max(len(i.name) for i in block.items)
108
+ for i in block.items:
109
+ mark = "✓" if i.conforms else "✗" if i.conforms is False else "?"
110
+ detail = (f"{i.found}" if i.conforms else
111
+ (i.note or f"{i.found} in the case, {i.specified} specified")
112
+ if i.conforms is False else f"not checked: {i.note}")
113
+ print(f" {mark} {i.name:<{width}} {detail}")
114
+ raise typer.Exit(2 if block.nonconformant else 3 if block.unreadable else 0)
115
+
116
+
117
+ @app.command("extract")
118
+ def extract(
119
+ task_file: str = typer.Argument(..., help="The task, in words (a text file)."),
120
+ out: str = typer.Option(None, "-o", "--out", help="Write the specification here (default: stdout only)."),
121
+ model: str = typer.Option(None, "--model", help="Pin a model id; the door still decides whether it may take the call."),
122
+ data: str = typer.Option("customer", "--data", help="'customer' (the default: only zero-data-retention endpoints) or 'public' for a task from public tutorials."),
123
+ ) -> None:
124
+ """Draft a specification from a task in words through the model door (SPEC-7).
125
+
126
+ The draft is shown, hashed and marked extracted. Until a person confirms it
127
+ (`courant spec confirm --by NAME`) it is not binding: a mismatch can only make a verdict
128
+ insufficient, never reject. If no model may extract it, the exit code is 4 (SPEC-8: only a model
129
+ measured by RRD RM-23).
130
+ """
131
+ from courant.spec import spec_sha256
132
+ from courant.spec.extract import ExtractionError, extract_spec
133
+
134
+ path = Path(task_file)
135
+ if not path.is_file():
136
+ print(f"courant spec extract: no such task file: {task_file}", file=sys.stderr)
137
+ raise typer.Exit(4)
138
+ if data not in ("customer", "public"):
139
+ print("courant spec extract: --data is 'customer' or 'public'", file=sys.stderr)
140
+ raise typer.Exit(4)
141
+ from courant.llm import LLMError, contact_notice, default_door
142
+
143
+ door = default_door()
144
+ # Asked before anything touches the network (docs/NETWORK.md): a call the door refuses
145
+ # contacts nothing; one it lets through names its host first.
146
+ chosen = door.eligible(task="spec-extract", data=data, model=model)
147
+ if not chosen:
148
+ why = door.why_not(task="spec-extract", data=data, model=model)
149
+ print(f"courant spec extract: no model may extract this specification: {why}. Nothing "
150
+ "was contacted. Write it by hand, or draft it from a reference case (courant spec "
151
+ "init).", file=sys.stderr)
152
+ raise typer.Exit(4)
153
+ print(f"courant spec extract: {contact_notice(chosen[0].provider)}; the task's text is sent",
154
+ file=sys.stderr)
155
+ try:
156
+ result = extract_spec(path.read_text(errors="replace"), door=door, data=data,
157
+ model=model)
158
+ except LLMError as exc:
159
+ print(f"courant spec extract: no model may extract this specification: {exc.message} "
160
+ "Write it by hand, or draft it from a reference case (courant spec init).",
161
+ file=sys.stderr)
162
+ raise typer.Exit(4) from exc
163
+ except ExtractionError as exc:
164
+ print(f"courant spec extract: {exc}", file=sys.stderr)
165
+ raise typer.Exit(4) from exc
166
+ text = result.spec.to_json()
167
+ sys.stdout.write(text) # shown, before anything relies on it
168
+ for why in result.dropped:
169
+ print(f" left out: {why}", file=sys.stderr)
170
+ where = ""
171
+ if out:
172
+ Path(out).write_text(text)
173
+ where = f"{out} · sha256 {spec_sha256(out)} · "
174
+ print(f"specification extracted by {result.model}: {where}{len(result.spec.items)} values, "
175
+ "UNCONFIRMED. It can only lower a verdict to insufficient until a person reviews it: "
176
+ "courant spec confirm SPEC --by NAME", file=sys.stderr)
177
+
178
+
179
+ @app.command("confirm")
180
+ def confirm_(
181
+ spec: str = typer.Argument(..., help="A courant.spec/1 file, typically an extracted one."),
182
+ by: str = typer.Option(..., "--by", help="Who reviewed it."),
183
+ date: str = typer.Option(None, "--date", help="The review date, YYYY-MM-DD (default: today, UTC)."),
184
+ out: str = typer.Option(None, "-o", "--out", help="Write the confirmed specification here (default: in place)."),
185
+ ) -> None:
186
+ """Record a person's review in the specification and print its new hash (SPEC-7).
187
+
188
+ A confirmed specification is binding: its values can reject. Lock the new hash.
189
+ """
190
+ from datetime import UTC, datetime
191
+
192
+ from courant.spec import SpecError, load_spec, spec_sha256
193
+ from courant.spec.extract import confirm
194
+
195
+ try:
196
+ spec_model, _ = load_spec(spec)
197
+ confirmed = confirm(spec_model, by=by,
198
+ date=date or datetime.now(UTC).date().isoformat())
199
+ except (SpecError, ValueError) as exc:
200
+ print(f"courant spec confirm: {exc}", file=sys.stderr)
201
+ raise typer.Exit(4) from exc
202
+ target = out or spec
203
+ Path(target).write_text(confirmed.to_json())
204
+ print(spec_sha256(target))
205
+ print(f"confirmed by {confirmed.provenance.confirmed_by} on "
206
+ f"{confirmed.provenance.confirmed_date}: {target} is binding; lock this hash",
207
+ file=sys.stderr)
208
+
209
+
210
+ @app.command("lock")
211
+ def lock(spec: str = typer.Argument(..., help="A courant.spec/1 file.")) -> None:
212
+ """Print the SHA-256 that locks this specification, and say whether it binds (SPEC-7).
213
+
214
+ Record the hash before the run and pass it as --spec-sha256. An extracted specification
215
+ nobody confirmed locks like any other, and still only lowers a verdict to insufficient.
216
+ """
217
+ from courant.spec import SpecError, load_spec
218
+ from courant.spec.extract import binding
219
+
220
+ try:
221
+ spec_model, sha = load_spec(spec)
222
+ except SpecError as exc:
223
+ print(f"courant spec lock: {exc}", file=sys.stderr)
224
+ raise typer.Exit(4) from exc
225
+ print(sha)
226
+ if binding(spec_model):
227
+ print(f"{spec}: binding; a value the case does not match rejects the run", file=sys.stderr)
228
+ else:
229
+ print(f"{spec}: extracted by {spec_model.provenance.model or 'a model'} and UNCONFIRMED; "
230
+ "a mismatch only makes the verdict insufficient. To make it binding: courant spec "
231
+ "confirm --by NAME, then lock the new hash", file=sys.stderr)
@@ -0,0 +1,122 @@
1
+ """`courant demo`: ten seconds that show what Courant does, on runs it ships (TRD PKG-6).
2
+
3
+ Offline, one core, read-only. Nothing is written outside a temporary folder unless
4
+ `--keep DIR` is given. The runs are real OpenFOAM v2406 output, packaged in `courant/data/`:
5
+ a healthy cavity, the same cavity with a timestep ten times too large, and pitzDaily run to a
6
+ fixed 2,000-iteration budget with monitors.
7
+
8
+ It calls the same functions `courant verify` and `courant convergence` call. A demo with its
9
+ own code path would be a demo of nothing.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import shutil
15
+ import sys
16
+ import tempfile
17
+ import time
18
+ from pathlib import Path
19
+
20
+ import typer
21
+
22
+
23
+ def demo(
24
+ keep: str = typer.Option(None, "--keep", help="Write the report and evidence pack here instead of a temporary folder."),
25
+ ) -> None:
26
+ """See Courant verify four real runs, offline, in seconds."""
27
+ from courant.converge import from_run_inputs
28
+ from courant.converge.render import five_lines
29
+ from courant.data import DEMO, certification, extract_demo_case
30
+ from courant.verify import from_path, verify_inputs
31
+ from courant.verify.html import render_html
32
+ from courant.verify.pack import write_pack
33
+
34
+ t0 = time.perf_counter()
35
+ out = Path(keep) if keep else Path(tempfile.mkdtemp(prefix="courant-demo-"))
36
+ out.mkdir(parents=True, exist_ok=True)
37
+
38
+ def say(line: str = "") -> None:
39
+ print(line, flush=True)
40
+
41
+ say("Courant demo · offline · read-only · four real OpenFOAM v2406 runs")
42
+ say()
43
+
44
+ runs = [("1", "A healthy run", "icoFoam cavity, as OpenFOAM ships it", "icoFoam_cavity__healthy"),
45
+ ("2", "A broken run", "the same cavity with a timestep ten times too large",
46
+ "icoFoam_cavity__cfl_blowup")]
47
+ for n, title, what, name in runs:
48
+ work = out / name
49
+ work.mkdir(exist_ok=True)
50
+ for ext in (".log.gz", ".case.json"):
51
+ shutil.copy(DEMO / f"{name}{ext}", work / f"{name}{ext}")
52
+ inputs = from_path(work / f"{name}.log.gz", work / f"{name}.case.json")
53
+ v = verify_inputs(inputs)
54
+ say(f"{n} {title}: {what}")
55
+ say(f" {v.verdict} (rule {v.rule}, grade {v.grade or '-'})")
56
+ for r in v.reasons[:2] if v.verdict != "accept" else []:
57
+ say(f" why {r.code}: {r.summary}")
58
+ if v.verdict != "accept" and v.probable_causes:
59
+ say(f" cause {v.probable_causes[0].code} ({v.probable_causes[0].name})")
60
+ if v.next_action:
61
+ say(f" next {v.next_action}")
62
+ say()
63
+
64
+ # Preflight: a setup fault caught before the solver would have run at all.
65
+ from courant.verify.preflight import preflight_path
66
+
67
+ name = "icoFoam_cavity__transport_units"
68
+ work = out / name
69
+ work.mkdir(exist_ok=True)
70
+ for ext in (".log.gz", ".case.json"):
71
+ shutil.copy(DEMO / f"{name}{ext}", work / f"{name}{ext}")
72
+ pre = preflight_path("unused", work / f"{name}.case.json")
73
+ say("3 Before the run: the cavity with its viscosity in the wrong units (courant preflight)")
74
+ say(f" {pre.verdict} before the first timestep")
75
+ for r in pre.reasons[:1]:
76
+ say(f" why {r.code}: {r.summary}")
77
+ if pre.next_action:
78
+ say(f" next {pre.next_action}")
79
+ say()
80
+
81
+ case = extract_demo_case(out)
82
+ inputs = from_path(case)
83
+ v = verify_inputs(inputs)
84
+ conv = from_run_inputs(inputs)
85
+ say("4 A steady run with a fixed budget: pitzDaily, 2,000 iterations, monitors on the walls "
86
+ "and the inlet")
87
+ say(f" {v.verdict} (rule {v.rule}, grade {v.grade or '-'}); convergence {conv.status}")
88
+ for ln in five_lines(conv):
89
+ say(f" {ln}")
90
+ say()
91
+ report = out / "report.html"
92
+ report.write_text(render_html(v, inputs))
93
+ pack = write_pack(v, out / "pack", case.name, None)
94
+ from courant.verify.audit import audit
95
+
96
+ doc = audit(out)
97
+ t = doc["totals"]
98
+ settled = [r for r in doc["runs"] if r.get("wasted_fraction") is not None]
99
+ say(f"5 The compute audit over these {t['runs']} runs (courant audit)")
100
+ say(f" {t['trustworthy']} of {t['readable']} trustworthy · {t['runs_setup_fault']} of "
101
+ f"{t['readable']} with a setup fault preflight finds before the start · on "
102
+ f"{t['runs_settled']} of {t['runs_with_monitors']} monitored runs the answer settled"
103
+ + (f", with {100 * settled[0]['wasted_fraction']:.1f}% of its iterations still to run"
104
+ if len(settled) == 1 else ""))
105
+ say(" On your runs it totals the core-hours, and the cost at your rate.")
106
+ say()
107
+ say("6 Evidence")
108
+ say(f" report {report}")
109
+ say(f" pack {pack}/ (re-derive it: courant verify --check-pack {pack} --root {case})")
110
+ say()
111
+ cert = certification() or {}
112
+ card = (cert.get("scorecard") or {}).get("all") or {}
113
+ if card:
114
+ far, frr = card.get("far", {}), card.get("frr", {})
115
+ say(f"What Courant measured about itself, on {card.get('n', 31)} real runs: false accepts "
116
+ f"{far.get('n')} of {far.get('of')}, false alarms {frr.get('n')} of {frr.get('of')} "
117
+ f"(courant verify --about).")
118
+ say(f"Done in {time.perf_counter() - t0:.1f} s. Nothing outside {out} was written, no solver "
119
+ f"was run, and no network was used.")
120
+ if not keep:
121
+ say("The folder is temporary; pass --keep DIR to keep the report.")
122
+ sys.stdout.flush()