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
courant/signing.py ADDED
@@ -0,0 +1,99 @@
1
+ """Ed25519 signatures: the one implementation of signing and verifying (TRD OPS-7, SEC-5).
2
+
3
+ A release's checksums (`courant.release`) are signed with an Ed25519 key that is held outside
4
+ every repository and checked against the public key pinned in the build. The private key is read
5
+ from the file a path or an environment variable names, at the moment of signing, refused if it
6
+ lies inside a repository, and never logged, printed or copied: only its public half is written.
7
+
8
+ `cryptography` is imported only inside the functions that need it.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ from pathlib import Path
15
+
16
+
17
+ class SignatureError(ValueError):
18
+ """A key or a signature that cannot be used. The message never contains key material."""
19
+
20
+
21
+ def repository_root(path: str | Path) -> Path | None:
22
+ """The repository `path` lies in, if any (a parent holding `.git`, file or directory)."""
23
+ p = Path(path).expanduser().resolve()
24
+ for d in (p, *p.parents):
25
+ if (d / ".git").exists():
26
+ return d
27
+ return None
28
+
29
+
30
+ def load_private(path: str | Path | None, env: str):
31
+ """The Ed25519 private key at `path`, else at the file the variable `env` names."""
32
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
33
+ from cryptography.hazmat.primitives.serialization import load_pem_private_key
34
+
35
+ where = path or os.environ.get(env)
36
+ if not where:
37
+ raise SignatureError(f"no signing key: set {env} to the key file (H-SIGNING-KEY)")
38
+ repo = repository_root(where)
39
+ if repo is not None:
40
+ raise SignatureError(f"refusing to read a signing key inside the repository at {repo}")
41
+ where = Path(where).expanduser().resolve()
42
+ try:
43
+ key = load_pem_private_key(where.read_bytes(), password=None)
44
+ except (OSError, ValueError, TypeError) as exc:
45
+ # Never echo the file's content: only that it could not be read as a key.
46
+ raise SignatureError(f"the signing key at {where} could not be read as an Ed25519 "
47
+ "private key") from exc
48
+ if not isinstance(key, Ed25519PrivateKey):
49
+ raise SignatureError("the signing key is not an Ed25519 key")
50
+ return key
51
+
52
+
53
+ def public_key_hex(private_key) -> str:
54
+ from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
55
+
56
+ return private_key.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw).hex()
57
+
58
+
59
+ def public_bytes(public_key: str | Path) -> bytes:
60
+ """A published public key (32 bytes as hex, or a short file holding that) as raw bytes."""
61
+ text = str(public_key)
62
+ p = Path(text)
63
+ if len(text) < 200 and p.is_file():
64
+ text = p.read_text().strip()
65
+ try:
66
+ raw = bytes.fromhex(text.strip())
67
+ except ValueError as exc:
68
+ raise SignatureError("a public key is 32 bytes, hex") from exc
69
+ if len(raw) != 32:
70
+ raise SignatureError("a public key is 32 bytes, hex")
71
+ return raw
72
+
73
+
74
+ def sign_with(key, data: bytes) -> tuple[str, str]:
75
+ """(public key hex, signature hex) of `data` under a loaded private key."""
76
+ return public_key_hex(key), key.sign(data).hex()
77
+
78
+
79
+ def sign_bytes(data: bytes, *, key_path: str | Path | None = None,
80
+ env: str) -> tuple[str, str]:
81
+ """(public key hex, signature hex) of `data` under the key `key_path` or `env` names."""
82
+ return sign_with(load_private(key_path, env), data)
83
+
84
+
85
+ def verify_bytes(data: bytes, signature_hex: str, public_key: str | Path) -> bool:
86
+ """Whether `signature_hex` signs `data` under the published public key."""
87
+ from cryptography.exceptions import InvalidSignature
88
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
89
+
90
+ try:
91
+ Ed25519PublicKey.from_public_bytes(public_bytes(public_key)).verify(
92
+ bytes.fromhex(signature_hex), data)
93
+ except (InvalidSignature, ValueError, SignatureError):
94
+ return False
95
+ return True
96
+
97
+
98
+ __all__ = ["SignatureError", "load_private", "public_bytes", "public_key_hex",
99
+ "repository_root", "sign_bytes", "sign_with", "verify_bytes"]
@@ -0,0 +1,31 @@
1
+ """Task specifications and deck-versus-spec conformance (PRD 2.0 P2-SPEC).
2
+
3
+ Without a specification, Courant decides whether a run is *valid*. With one, it decides
4
+ whether the run is *the problem that was asked*: every value the specification names is
5
+ compared to the case, deterministically, and a run that solved a different problem is
6
+ rejected however well it converged (RRD RM-18).
7
+
8
+ from courant.spec import load_spec, check_conformance, draft_spec
9
+ spec, sha = load_spec("spec.json")
10
+ block = check_conformance(spec, "./case", spec_sha256=sha)
11
+
12
+ Read-only, deterministic, no network (INV-5).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from courant.spec.check import check_conformance, conforms, draft_spec
18
+ from courant.spec.model import (
19
+ SPEC_SCHEMA,
20
+ Provenance,
21
+ Spec,
22
+ SpecError,
23
+ SpecItem,
24
+ load_spec,
25
+ spec_sha256,
26
+ )
27
+
28
+ __all__ = [
29
+ "SPEC_SCHEMA", "Provenance", "Spec", "SpecError", "SpecItem",
30
+ "check_conformance", "conforms", "draft_spec", "load_spec", "spec_sha256",
31
+ ]
courant/spec/check.py ADDED
@@ -0,0 +1,353 @@
1
+ """Deck-versus-spec conformance, and a specification drafted from a case (PRD 2.0 P2-SPEC-2).
2
+
3
+ Conformance answers one question deterministically: is this case the problem that was asked?
4
+ RRD RM-18 measured why it matters: on 20 real runs with the right physics and the wrong
5
+ input, the reference-free verdict caught 8 (every one a numerical consequence of the fault);
6
+ against the task specification, 20 of 20, with 0 of 7 false nonconformances on the untouched
7
+ tutorials.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import math
13
+ from pathlib import Path
14
+
15
+ from courant.spec import deck
16
+ from courant.spec.model import SPEC_SCHEMA, Spec, SpecItem
17
+
18
+
19
+ # ---------------------------------------------------------------- comparison
20
+ def _fmt(v) -> str | None:
21
+ if v is None:
22
+ return None
23
+ if isinstance(v, str):
24
+ return v
25
+ if isinstance(v, (list, tuple)):
26
+ return "(" + " ".join(_num(x) for x in v) + ")"
27
+ return _num(v)
28
+
29
+
30
+ def _num(x: float) -> str:
31
+ x = float(x)
32
+ return str(int(x)) if x.is_integer() and abs(x) < 1e15 else repr(x)
33
+
34
+
35
+ def _close(spec: float, found: float, rel: float, abs_tol: float | None) -> bool:
36
+ tol = max(abs_tol or 0.0, rel * abs(spec))
37
+ if tol == 0.0:
38
+ return found == spec
39
+ return abs(found - spec) <= tol
40
+
41
+
42
+ def bounded_quantity(item: SpecItem, found) -> float | None:
43
+ """SPEC-12: the one number a bound is compared with. A scalar is itself; a vector, its
44
+ magnitude; a blockMeshDict's hex cell counts, the total number of cells. None for text."""
45
+ if found is None or isinstance(found, str):
46
+ return None
47
+ if item.blocks == "cells":
48
+ counts = [float(x) for x in found]
49
+ if len(counts) % 3:
50
+ return None
51
+ return float(sum(counts[i] * counts[i + 1] * counts[i + 2]
52
+ for i in range(0, len(counts), 3)))
53
+ if isinstance(found, (list, tuple)):
54
+ return math.sqrt(sum(float(x) ** 2 for x in found))
55
+ return float(found)
56
+
57
+
58
+ def within(item: SpecItem, found) -> bool | None:
59
+ """SPEC-12: whether the found quantity lies inside the item's bound (inclusive)."""
60
+ q = bounded_quantity(item, found)
61
+ if q is None:
62
+ return None
63
+ return (item.min is None or q >= item.min) and (item.max is None or q <= item.max)
64
+
65
+
66
+ def _bound(item: SpecItem) -> str:
67
+ if item.min is not None and item.max is not None:
68
+ return f"in [{_num(item.min)}, {_num(item.max)}]"
69
+ return f"≥ {_num(item.min)}" if item.min is not None else f"≤ {_num(item.max)}"
70
+
71
+
72
+ def conforms(item: SpecItem, found, *, rel: float, angle_deg: float) -> bool | None:
73
+ """Whether `found` meets the item. None when there is nothing to compare."""
74
+ if item.bounded:
75
+ return within(item, found)
76
+ want = item.sha256 if item.sha256 is not None else item.value
77
+ if want is None or found is None:
78
+ return None
79
+ if item.exact:
80
+ if isinstance(want, str) or isinstance(found, str):
81
+ return str(want).lower() == str(found).lower()
82
+ return [float(x) for x in want] == [float(x) for x in found]
83
+ if isinstance(want, str) or isinstance(found, str):
84
+ return str(want) == str(found)
85
+ want_l = list(want) if isinstance(want, (list, tuple)) else None
86
+ found_l = list(found) if isinstance(found, (list, tuple)) else None
87
+ if want_l is None and found_l is None:
88
+ return _close(float(want), float(found), rel, item.abs_tol)
89
+ if want_l is None or found_l is None or len(want_l) != len(found_l):
90
+ return False
91
+ if len(want_l) == 3: # a vector: magnitude, then direction
92
+ ns = math.sqrt(sum(x * x for x in want_l))
93
+ nf = math.sqrt(sum(x * x for x in found_l))
94
+ if not _close(ns, nf, rel, item.abs_tol):
95
+ return False
96
+ if ns == 0.0 or nf == 0.0:
97
+ return ns == nf or nf <= (item.abs_tol or 0.0)
98
+ cos = sum(a * b for a, b in zip(want_l, found_l)) / (ns * nf)
99
+ return math.degrees(math.acos(max(-1.0, min(1.0, cos)))) <= angle_deg
100
+ return all(_close(float(a), float(b), rel, item.abs_tol) for a, b in zip(want_l, found_l))
101
+
102
+
103
+ def _dims_match(item: SpecItem, found_dims) -> bool | None:
104
+ if item.dimensions is None or found_dims is None:
105
+ return None
106
+
107
+ def pad(d):
108
+ d = [float(x) for x in d]
109
+ return d + [0.0] * (7 - len(d))
110
+
111
+ return pad(item.dimensions) == pad(found_dims)
112
+
113
+
114
+ def _specified(item: SpecItem) -> str | None:
115
+ if item.bounded:
116
+ return _bound(item)
117
+ return _fmt(item.sha256 if item.sha256 is not None else item.value)
118
+
119
+
120
+ def _tolerance(item: SpecItem, rel: float, angle_deg: float) -> str:
121
+ if item.bounded:
122
+ return "bound"
123
+ if item.exact:
124
+ return "exact"
125
+ if isinstance(item.value, str):
126
+ return "exact"
127
+ parts = [f"{100 * rel:g}%"]
128
+ if item.abs_tol:
129
+ parts.append(f"or {_num(item.abs_tol)}")
130
+ if isinstance(item.value, (list, tuple)) and len(item.value) == 3:
131
+ parts.append(f"{angle_deg:g}°")
132
+ return ", ".join(parts)
133
+
134
+
135
+ # ---------------------------------------------------------------- the check
136
+ def check_conformance(spec: Spec | dict, case_dir: str | Path | None, *, spec_sha256: str,
137
+ locked_sha256: str | None = None):
138
+ """The conformance block for one case. Never raises on a case it cannot read."""
139
+ from courant.spec.impossible import impossibilities
140
+ from courant.verify.schema import ConformanceBlock, ConformanceItem
141
+
142
+ if isinstance(spec, dict):
143
+ spec = Spec.model_validate(spec)
144
+ invalid = impossibilities(spec)
145
+ if invalid:
146
+ # VER-5.11: no case can conform to an impossible specification, so the case is not
147
+ # compared to it (and not read for it).
148
+ items = tuple(ConformanceItem(
149
+ name=item.name, file=item.file, location=item.location,
150
+ specified=_specified(item), found=None, conforms=None,
151
+ tolerance=_tolerance(item, spec.rel_tol, spec.angle_tol_deg),
152
+ modelling_choice=item.modelling_choice,
153
+ note="not compared: the specification is impossible in itself")
154
+ for item in spec.items)
155
+ return ConformanceBlock(
156
+ spec_schema=SPEC_SCHEMA, spec_sha256=spec_sha256, locked_sha256=locked_sha256,
157
+ task=spec.task, items=items, checked=0, nonconformant=0, unreadable=len(items),
158
+ invalid=invalid)
159
+ items: list[ConformanceItem] = []
160
+ for item in spec.items:
161
+ rel = item.rel_tol if item.rel_tol is not None else spec.rel_tol
162
+ angle = item.angle_tol_deg if item.angle_tol_deg is not None else spec.angle_tol_deg
163
+ if case_dir is None:
164
+ found = deck.Found(None, item.file, "only a log was given; the case directory is needed")
165
+ else:
166
+ found = deck.read(case_dir, item)
167
+ ok = conforms(item, found.value, rel=rel, angle_deg=angle)
168
+ if ok is None and found.missing: # absent from a file read in full (VER-15)
169
+ ok = False
170
+ note = found.note
171
+ shown = found.value
172
+ basis = found.basis
173
+ if item.bounded and found.faces is not None:
174
+ # SPEC-12 on a per-face list: every face must lie inside the bound, never the mode.
175
+ qs = [bounded_quantity(item, f) for f in found.faces]
176
+ if any(q is None for q in qs):
177
+ ok, note = None, "a per-face list whose values a bound cannot be applied to"
178
+ else:
179
+ lo, hi = min(qs), max(qs)
180
+ ok = all(within(item, f) for f in found.faces)
181
+ shown = lo if lo == hi else f"{_num(lo)} to {_num(hi)}"
182
+ basis = f"every one of {len(qs)} face values ({_num(lo)} to {_num(hi)})"
183
+ if not ok:
184
+ note = f"face values {_num(lo)} to {_num(hi)} in the case, {_bound(item)} specified"
185
+ elif item.bounded and found.value is not None:
186
+ q = bounded_quantity(item, found.value)
187
+ shown = q if q is not None else found.value
188
+ if ok is None:
189
+ note = "a bound applies to a number; the case holds text"
190
+ elif ok is False:
191
+ note = f"{_fmt(q)} in the case, {_bound(item)} specified"
192
+ dims_ok = _dims_match(item, found.dimensions)
193
+ if ok is not None and dims_ok is False:
194
+ ok = False
195
+ note = (f"dimensions {_fmt(found.dimensions)} in the case, "
196
+ f"{_fmt(item.dimensions)} specified")
197
+ items.append(ConformanceItem(
198
+ name=item.name, file=found.file, location=item.location,
199
+ specified=_specified(item),
200
+ found=_fmt(shown), conforms=ok, tolerance=_tolerance(item, rel, angle),
201
+ modelling_choice=item.modelling_choice, note=note, basis=basis))
202
+ return ConformanceBlock(
203
+ spec_schema=SPEC_SCHEMA, spec_sha256=spec_sha256, locked_sha256=locked_sha256,
204
+ task=spec.task, items=tuple(items),
205
+ checked=sum(1 for i in items if i.conforms is not None),
206
+ nonconformant=sum(1 for i in items if i.conforms is False),
207
+ unreadable=sum(1 for i in items if i.conforms is None))
208
+
209
+
210
+ # ---------------------------------------------------------------- drafting a spec
211
+ #: Boundary conditions whose parameters are part of the problem, and the entry that holds
212
+ #: each. A wall function's `value`, or a `calculated` patch's, is an initial guess, not a
213
+ #: boundary condition anyone asked for, and is left out.
214
+ _BC_PARAMETERS = {
215
+ "fixedValue": ("value",),
216
+ "movingWallVelocity": ("value",),
217
+ "inletOutlet": ("inletValue",),
218
+ "outletInlet": ("outletValue",),
219
+ "totalPressure": ("p0",),
220
+ "prghPressure": ("p",),
221
+ "prghTotalPressure": ("p0",),
222
+ "fixedGradient": ("gradient",),
223
+ "flowRateInletVelocity": ("volumetricFlowRate", "massFlowRate"),
224
+ "turbulentIntensityKineticEnergyInlet": ("intensity",),
225
+ "turbulentMixingLengthDissipationRateInlet": ("mixingLength",),
226
+ "turbulentMixingLengthFrequencyInlet": ("mixingLength",),
227
+ }
228
+
229
+ #: (file, block path, key, name, modelling choice) for the properties a task names.
230
+ _PROPERTIES = (
231
+ ("constant/transportProperties", (), "nu", "nu", False),
232
+ ("constant/physicalProperties", (), "nu", "nu", False),
233
+ ("constant/thermophysicalProperties", ("mixture", "transport"), "mu", "mu", False),
234
+ ("constant/thermophysicalProperties", ("mixture", "thermodynamics"), "Cp", "Cp", False),
235
+ ("constant/thermophysicalProperties", ("mixture", "specie"), "molWeight", "molWeight", False),
236
+ ("constant/transportProperties", (), "sigma", "surface tension", False),
237
+ ("constant/g", (), "value", "gravity", False),
238
+ ("system/controlDict", (), "application", "solver", True),
239
+ ("system/controlDict", (), "endTime", "endTime", False),
240
+ ("system/blockMeshDict", (), "scale", "mesh scale", False),
241
+ ("system/blockMeshDict", (), "convertToMeters", "mesh scale", False),
242
+ ("constant/turbulenceProperties", (), "simulationType", "turbulence regime", True),
243
+ ("constant/turbulenceProperties", ("RAS",), "RASModel", "turbulence model", True),
244
+ ("constant/turbulenceProperties", ("LES",), "LESModel", "turbulence model", True),
245
+ ("constant/momentumTransport", (), "simulationType", "turbulence regime", True),
246
+ ("constant/momentumTransport", ("RAS",), "model", "turbulence model", True),
247
+ ("constant/momentumTransport", ("LES",), "model", "turbulence model", True),
248
+ )
249
+
250
+ _PHASES_FILE = "constant/transportProperties"
251
+ _TEXT_KEYS = {"application", "simulationType", "RASModel", "LESModel", "model"}
252
+
253
+
254
+ def _probe(case: Path, item: SpecItem):
255
+ found = deck.read(case, item)
256
+ return found.value
257
+
258
+
259
+ def draft_spec(case_dir: str | Path, *, task: str | None = None,
260
+ include_mesh: bool = True) -> Spec:
261
+ """A specification of the problem this case sets up: its boundary-condition parameters,
262
+ material properties, body forces, run length, geometry scale and modelling choices.
263
+
264
+ Meant to be generated from the *reference* case a task is written against, reviewed, and
265
+ then locked before any agent runs (`courant spec hash`). Only values the reader can
266
+ actually read are included, so a draft checked against its own case always conforms.
267
+ """
268
+ case = Path(case_dir)
269
+ items: list[SpecItem] = []
270
+ names: set[str] = set()
271
+
272
+ def add(**kw) -> None:
273
+ if kw["name"] in names:
274
+ return
275
+ try:
276
+ item = SpecItem(**kw)
277
+ except ValueError:
278
+ return
279
+ if _probe(case, item) is None:
280
+ return
281
+ names.add(item.name)
282
+ items.append(item)
283
+
284
+ # Boundary-condition parameters. Fields are listed from 0/ and 0.orig/; each value is read
285
+ # the way conformance will read it, so one rewritten by the run (setFields) comes from
286
+ # 0.orig/ and one that cannot be read at all is left out of the draft.
287
+ fields = sorted({p.name for d in ("0", "0.orig") if (case / d).is_dir()
288
+ for p in (case / d).iterdir()
289
+ if p.is_file() and not p.name.startswith(".") and not p.name.endswith(".orig")})
290
+ for name in fields:
291
+ src = "0" if (case / "0" / name).is_file() else "0.orig"
292
+ text, _ = deck._read_text(case, f"{src}/{name}")
293
+ bf = deck.block(text or "", "boundaryField")
294
+ if bf is None:
295
+ continue
296
+ for patch, body in deck.blocks(bf):
297
+ bc_type = deck.entry(body, "type")
298
+ for key in _BC_PARAMETERS.get(bc_type or "", ()):
299
+ if deck.entry(body, key) is None:
300
+ continue
301
+ label = patch if not any(c in patch for c in "()|*.[") else f'"{patch}"'
302
+ item_kw = {"name": f"{name} at {label}" + ("" if key == "value" else f" ({key})"),
303
+ "file": f"0/{name}", "patch": patch,
304
+ "key": None if key == "value" else key}
305
+ found = deck.read(case, SpecItem(**item_kw, value=0.0))
306
+ if found.value is None:
307
+ continue
308
+ add(**item_kw, value=found.value)
309
+
310
+ # Properties, forces, run control, modelling choices.
311
+ for file, path, key, name, choice in _PROPERTIES:
312
+ if not (case / file).is_file():
313
+ continue
314
+ is_text = key in _TEXT_KEYS
315
+ probe = SpecItem(name=name, file=file, path=path, key=key,
316
+ value="x" if is_text else 0.0)
317
+ found = deck.read(case, probe)
318
+ if found.value is None:
319
+ continue
320
+ dims = found.dimensions if found.dimensions else None
321
+ add(name=name, file=file, path=path, key=key, value=found.value,
322
+ dimensions=dims, modelling_choice=choice)
323
+
324
+ # Per-phase properties (multiphase cases name their phases).
325
+ phases_raw = deck.entry(deck._read_text(case, _PHASES_FILE)[0] or "", "phases")
326
+ if phases_raw:
327
+ for phase in phases_raw.strip("() ").split():
328
+ for key in ("nu", "rho"):
329
+ probe = SpecItem(name=f"{phase} {key}", file=_PHASES_FILE, path=(phase,),
330
+ key=key, value=0.0)
331
+ found = deck.read(case, probe)
332
+ if found.value is not None:
333
+ add(name=f"{phase} {key}", file=_PHASES_FILE, path=(phase,), key=key,
334
+ value=found.value, dimensions=found.dimensions or None)
335
+
336
+ # The mesh: cell counts are a modelling choice; surface geometry is identity.
337
+ if include_mesh and (case / "system/blockMeshDict").is_file():
338
+ cells = _probe(case, SpecItem(name="c", file="system/blockMeshDict", blocks="cells",
339
+ value=(0.0,)))
340
+ if cells:
341
+ add(name="mesh cells", file="system/blockMeshDict", blocks="cells",
342
+ value=tuple(cells), modelling_choice=True)
343
+ tri = case / "constant" / "triSurface"
344
+ if tri.is_dir():
345
+ for surf in sorted(p for p in tri.iterdir()
346
+ if p.suffix.lower() in (".stl", ".obj", ".vtk", ".ftr", ".gz")):
347
+ rel = f"constant/triSurface/{surf.name}"
348
+ add(name=f"geometry {surf.name}", file=rel,
349
+ sha256=deck.read(case, SpecItem(name="g", file=rel, sha256="0")).value)
350
+
351
+ if not items:
352
+ raise ValueError(f"nothing in {case} could be read into a specification")
353
+ return Spec(schema=SPEC_SCHEMA, task=task, items=tuple(items))