返回 CodeWhale
check-provider-registry.py
根目录 / scripts / check-provider-registry.py
1 #!/usr/bin/env python3
2 """Check that docs/PROVIDERS.md tracks the shipped provider registry.
3
4 This is intentionally lightweight. It does not try to generate prose; it checks
5 the stable identifiers and default strings that are easy for docs to drift from:
6
7 - canonical ProviderKind IDs
8 - provider TOML tables
9 - descriptor-owned released presentation identities
10 - shipped-provider table rows
11 - reviewed catalog provider selection rows
12 - default provider model/base URL constants
13 """
14
15 from __future__ import annotations
16
17 import json
18 import re
19 import sys
20 from pathlib import Path
21
22
23 ROOT = Path(__file__).resolve().parents[1]
24 CONFIG_RS = ROOT / "crates" / "config" / "src" / "lib.rs"
25 # ProviderKind's enum + identity impl were split out of lib.rs into this module.
26 PROVIDER_KIND_RS = ROOT / "crates" / "config" / "src" / "provider_kind.rs"
27 PROVIDER_RS = ROOT / "crates" / "config" / "src" / "provider.rs"
28 TUI_CONFIG_RS = ROOT / "crates" / "runtime" / "src" / "config.rs"
29 # Default provider model/base-URL constants were split out of config.rs into
30 # this leaf module (#3311); read them from there for the default-string check.
31 PROVIDER_DATA = ROOT / "crates" / "config" / "assets" / "provider_descriptors.json"
32 PROVIDERS_MD = ROOT / "docs" / "PROVIDERS.md"
33 CONFIGURATION_MD = ROOT / "docs" / "CONFIGURATION.md"
34 WEB_FACTS_LIB = ROOT / "web" / "scripts" / "facts-lib.mjs"
35 WEB_FACTS_DRIFT = ROOT / "web" / "lib" / "facts-drift.ts"
36 WEB_FACTS_GENERATED = ROOT / "web" / "lib" / "facts.generated.ts"
37 README_MD = ROOT / "README.md"
38 CONFIG_EXAMPLE_TOML = ROOT / "config.example.toml"
39 PROVIDER_READINESS_RS = ROOT / "crates" / "engine" / "src" / "provider_readiness.rs"
40 TUI_LIB_RS = ROOT / "crates" / "tui" / "src" / "lib.rs"
41
42
43 LEGACY_PROVIDER_TOMBSTONE_IDS = {"antigravity"}
44 LEGACY_PROVIDER_TOMBSTONE_TABLES = {"antigravity"}
45 LEGACY_PROVIDER_SELECTION_IDS = {"antigravity", "agy"}
46
47 # `custom` is the dynamic OpenAI-compatible meta-provider (#1519): a single
48 # catch-all `[providers.custom]` table that backs arbitrary user-defined
49 # endpoints, not a canonical shipped provider with a docs row. It is excluded
50 # from the provider-table drift check.
51 META_PROVIDER_TABLES = {"custom"}
52 SHARED_PROVIDER_TABLES = {
53 "siliconflow-CN": "siliconflow_cn",
54 }
55 HUGGINGFACE_ALIASES = {"huggingface", "hugging-face", "hugging_face", "hf"}
56 HUGGINGFACE_API_KEY_ENV_ORDER = ["HUGGINGFACE_API_KEY", "HF_TOKEN"]
57 HUGGINGFACE_BASE_URL_ENV_ORDER = ["HUGGINGFACE_BASE_URL", "HF_BASE_URL"]
58 HUGGINGFACE_MODEL_ENV_ORDER = ["HUGGINGFACE_MODEL", "HF_MODEL"]
59 SENSITIVE_IDENTIFIER_RE = re.compile(r"(?i)(api[_-]?key|token|secret|password|credential)")
60 SENSITIVE_BEARER_RE = re.compile(r"(?i)(authorization:\s*bearer\s+)\S+")
61 SENSITIVE_ASSIGNMENT_RE = re.compile(
62 r"(?i)\b(api[_-]?key|token|secret|password|credential)(\s*[:=]\s*)\S+"
63 )
64
65
66 def read(path: Path) -> str:
67 return path.read_text(encoding="utf-8")
68
69
70 def display_public_value(value: str) -> str:
71 if SENSITIVE_IDENTIFIER_RE.search(value):
72 return "<redacted sensitive identifier>"
73 return value
74
75
76 def redact_sensitive_text(value: str) -> str:
77 value = SENSITIVE_BEARER_RE.sub(r"\1<redacted>", value)
78 value = SENSITIVE_ASSIGNMENT_RE.sub(r"\1\2<redacted>", value)
79 return SENSITIVE_IDENTIFIER_RE.sub("<redacted sensitive identifier>", value)
80
81
82 def require_index(source: str, needle: str, context: str, start: int = 0) -> int:
83 try:
84 return source.index(needle, start)
85 except ValueError:
86 raise ValueError(f"{context}: missing {needle!r}") from None
87
88
89 def markdown_section(source: str, heading: str) -> str:
90 start = require_index(source, heading, "docs/PROVIDERS.md")
91 next_heading = source.find("\n## ", start + len(heading))
92 end = len(source) if next_heading == -1 else next_heading
93 return source[start:end]
94
95
96 def extract_match_block(
97 source: str, signature: str, context: str, start: int = 0
98 ) -> str:
99 start = require_index(source, signature, context, start)
100 match_start = require_index(source, "match", f"match block after {signature!r}", start)
101 brace_start = require_index(source, "{", f"match block after {signature!r}", match_start)
102 depth = 0
103 for index in range(brace_start, len(source)):
104 char = source[index]
105 if char == "{":
106 depth += 1
107 elif char == "}":
108 depth -= 1
109 if depth == 0:
110 return source[brace_start + 1 : index]
111 raise ValueError(f"could not parse match block after {signature!r}")
112
113
114 def provider_data() -> dict:
115 data = json.loads(read(PROVIDER_DATA))
116 if data.get("schema_version") != 3 or len(data.get("providers", [])) != 52:
117 raise ValueError("unsupported or incomplete provider metadata")
118 rows = [*data["providers"], data.get("legacy_tui", {})]
119 fields = ("id", "kind", "tui_wire_tag", "config_key", "catalog_id", "catalog_source_id")
120 if len(rows) != 53 or any(any(not isinstance(row.get(field), str) or not row[field] for field in fields) for row in rows):
121 raise ValueError("incomplete released presentation metadata")
122 for field in ("id", "tui_wire_tag", "tui_order"):
123 if len({row.get(field) for row in rows}) != len(rows):
124 raise ValueError(f"duplicate presentation {field}")
125 if {row["tui_order"] for row in rows} != set(range(len(rows))):
126 raise ValueError("noncontiguous released presentation order")
127 if data["legacy_tui"]["kind"] not in {row["kind"] for row in data["providers"]}:
128 raise ValueError("legacy presentation has no intrinsic provider")
129 return data
130
131
132 def parse_aliases_for_variant(source: str, enum_name: str, variant: str, context: str) -> set[str]:
133 # Both selectors delegate aliases to the same descriptor-backed facade.
134 for row in provider_data()["providers"]:
135 if row["kind"] == variant:
136 return {row["id"], *row["aliases"]}
137 raise ValueError(f"{context}: missing descriptor for {variant}")
138
139
140 def provider_kind_ids(config_rs: str) -> dict[str, str]:
141 rows = provider_data()["providers"]
142 ids = {row["kind"]: row["id"] for row in rows if row["kind"] != "Custom"}
143 if len({row["kind"] for row in rows}) != len(rows) or len({row["id"] for row in rows}) != len(rows):
144 raise ValueError("duplicate built-in descriptor identity")
145 return ids
146
147
148 def provider_kind_catalog_ids(provider_kind_rs: str, variant_to_id: dict[str, str]) -> set[str]:
149 if not re.search(r"pub const ALL:.*?=\s*crate::descriptors::SELECTABLE_PROVIDER_KINDS;", provider_kind_rs):
150 raise ValueError("ProviderKind::ALL must use generated descriptor selection")
151 return {row["id"] for row in provider_data()["providers"] if row["selectable"]}
152
153
154 def presentation_provider_ids() -> set[str]:
155 data = provider_data()
156 return {row["id"] for row in [*data["providers"], data["legacy_tui"]] if row["kind"] != "Custom"}
157
158
159 def provider_tables(config_rs: str) -> set[str]:
160 struct_start = require_index(
161 config_rs, "pub struct ProvidersToml", "crates/config/src/provider_toml.rs"
162 )
163 struct_end = require_index(config_rs, "\n}", "ProvidersToml struct", struct_start)
164 fields = re.findall(
165 r"pub\s+([a-z0-9_]+)\s*:\s*ProviderConfigToml",
166 config_rs[struct_start:struct_end],
167 )
168 if not fields:
169 raise ValueError("ProvidersToml returned no provider tables")
170 return set(fields)
171
172
173 def shipped_provider_rows(providers_md: str) -> set[str]:
174 table = markdown_section(providers_md, "## Shipped Providers")
175 return set(re.findall(r"^\|\s*`([^`]+)`\s*\|", table, flags=re.MULTILINE))
176
177
178 def shipped_provider_tables(providers_md: str) -> set[str]:
179 table = markdown_section(providers_md, "## Shipped Providers")
180 return set(re.findall(r"\|\s*`\[providers\.([a-z0-9_]+)\]`\s*\|", table))
181
182
183 def documented_selectable_provider_ids(providers_md: str) -> set[str]:
184 marker = require_index(providers_md, "in that order:", "docs/PROVIDERS.md")
185 start = require_index(providers_md, "\n\n", "provider selection list", marker) + 2
186 end = require_index(providers_md, "\n\n", "provider selection list", start)
187 return set(re.findall(r"`([^`]+)`", providers_md[start:end]))
188
189
190 def report_provider_kind_selector_contract(provider_kind_rs: str) -> list[str]:
191 start = require_index(
192 provider_kind_rs,
193 "pub fn parse(value: &str) -> Option<Self>",
194 "ProviderKind::parse",
195 )
196 end = require_index(
197 provider_kind_rs, "pub fn parse_config_identity", "ProviderKind::parse", start
198 )
199 selector = provider_kind_rs[start:end]
200 if "Self::ALL" not in selector and "Self::all()" not in selector:
201 return [
202 "ProviderKind::parse must gate registry aliases through the selectable "
203 "ProviderKind::ALL catalog"
204 ]
205 return []
206
207
208 def report_tui_catalog_contract(tui_config_rs: str) -> list[str]:
209 errors = []
210 if re.search(r"(?:enum|impl|type)\s+ApiProvider\b|KIND_LOOKUP|FROM_KIND_LOOKUP", tui_config_rs):
211 errors.append("TUI must not define a duplicate provider enum or ordinal bridge")
212 # The exact private historical enum in config/tests.rs is the serde
213 # counterpart, not a production owner. Check every other Rust consumer.
214 counterpart = ROOT / "crates/tui/src/config_stay_tests/config.rs"
215 for path in (ROOT / "crates").rglob("*.rs"):
216 source = read(path)
217 if path != counterpart and re.search(r"\bApiProvider\b", source):
218 errors.append(f"retired provider enum consumer: {path.relative_to(ROOT)}")
219 if re.search(r"KIND_LOOKUP|FROM_KIND_LOOKUP|ProviderKind::from_kind\(", source):
220 errors.append(f"retired provider ordinal bridge: {path.relative_to(ROOT)}")
221 for function_name in (
222 "active_provider_identity",
223 "provider_identities",
224 "resolve_provider_selection_identity",
225 "verify_provider_identity",
226 ):
227 if not re.search(rf"\bpub(?:\(crate\))?\s+fn\s+{function_name}\b", tui_config_rs):
228 errors.append(f"missing canonical config identity boundary: {function_name}")
229 descriptor_source = read(ROOT / "crates/config/src/descriptors.rs")
230 if "PROVIDER_COMPATIBILITY" not in descriptor_source or "pub fn compatibility_for_selector" not in descriptor_source:
231 errors.append("released presentation identities must use the existing generated descriptor owner")
232 if "is_legacy_antigravity_identity(requested)" not in tui_config_rs:
233 errors.append("explicit provider selection must refuse retired Antigravity aliases")
234 return errors
235
236
237 def report_tombstone_runtime_contract(
238 provider_kind_rs: str, provider_readiness_rs: str, tui_lib_rs: str
239 ) -> list[str]:
240 """The tombstone must resolve under every legacy spelling and never read
241 as a credentialed or advertised slot on a running-product surface."""
242
243 errors: list[str] = []
244 start = require_index(
245 provider_kind_rs,
246 "pub fn parse_config_identity(value: &str) -> Option<Self>",
247 "ProviderKind::parse_config_identity",
248 )
249 end = require_index(
250 provider_kind_rs, "pub fn secret_store_slot", "ProviderKind::parse_config_identity", start
251 )
252 config_identity = provider_kind_rs[start:end]
253 if "parse_retired_alias" not in config_identity:
254 errors.append(
255 "ProviderKind::parse_config_identity must resolve retired registry aliases "
256 "(`agy`) so every selection surface can name the tombstone"
257 )
258
259 if (
260 "provider == ProviderKind::Antigravity"
261 not in provider_readiness_rs
262 ):
263 errors.append(
264 "provider_readiness::credential_state_for_provider must classify "
265 "ProviderKind::Antigravity as CredentialState::Legacy"
266 )
267
268 if "for provider in doctor_api_key_providers()" not in tui_lib_rs or (
269 "*provider != codewhale_config::ProviderKind::Antigravity" not in tui_lib_rs
270 ):
271 errors.append(
272 "`codewhale doctor` API Keys rows must iterate doctor_api_key_providers() "
273 "with the retired Antigravity slot filtered out"
274 )
275 return errors
276
277
278 def report_antigravity_public_contract(
279 providers_md: str,
280 configuration_md: str,
281 web_facts_lib: str,
282 web_facts_drift: str,
283 web_facts_generated: str,
284 readme_md: str,
285 config_example_toml: str,
286 ) -> list[str]:
287 """Keep the retired provider as one safe, non-runnable docs tombstone."""
288
289 errors: list[str] = []
290 heading = "### Legacy Antigravity tombstone"
291 heading_count = providers_md.count(heading)
292 if heading_count != 1:
293 errors.append(
294 "docs/PROVIDERS.md must contain exactly one legacy Antigravity tombstone "
295 f"heading (found {heading_count})"
296 )
297 tombstone = ""
298 outside_tombstone = providers_md
299 else:
300 start = providers_md.index(heading)
301 next_heading = re.search(r"\n#{1,3} ", providers_md[start + len(heading) :])
302 end = (
303 len(providers_md)
304 if next_heading is None
305 else start + len(heading) + next_heading.start()
306 )
307 tombstone = providers_md[start:end]
308 outside_tombstone = providers_md[:start] + providers_md[end:]
309
310 normalized_tombstone = " ".join(tombstone.split())
311 required_tombstone_copy = [
312 "not a Codewhale provider",
313 "cannot be selected or run",
314 "non-runnable migration tombstone",
315 "`codewhale auth clear --provider antigravity`",
316 "Codewhale-owned legacy configuration and consent metadata",
317 "does not sign out of, revoke, read, or otherwise alter any official Google or Antigravity session",
318 "supported `google` provider",
319 "`GEMINI_API_KEY`",
320 ]
321 missing_tombstone_copy = [
322 required
323 for required in required_tombstone_copy
324 if required not in normalized_tombstone
325 ]
326 if missing_tombstone_copy:
327 errors.append(
328 "legacy Antigravity tombstone is missing required safety or migration copy "
329 f"({len(missing_tombstone_copy)} checks failed)"
330 )
331 clear_command = "`codewhale auth clear --provider antigravity`"
332 legacy_provider_forms = [
333 match.lower()
334 for match in re.findall(
335 r"--provider\s+(antigravity|agy)\b", providers_md, flags=re.IGNORECASE
336 )
337 ]
338 if providers_md.count(clear_command) != 1 or legacy_provider_forms != [
339 "antigravity"
340 ]:
341 errors.append(
342 "docs/PROVIDERS.md must contain the Codewhale-owned Antigravity "
343 "clear command as its only --provider antigravity/agy form"
344 )
345 setup_guidance = re.search(
346 r"\bagy\b|\boauth\b|\blog(?:in|\s+in)\b|\bsign\s+in\b|"
347 r"\bimport\b|\bexternal-consent\b|/provider\s+(?:antigravity|agy)\b|"
348 r"CODEWHALE_PROVIDER\s*=\s*(?:antigravity|agy)\b",
349 tombstone,
350 flags=re.IGNORECASE,
351 )
352 if setup_guidance:
353 errors.append(
354 "legacy Antigravity tombstone contains login, OAuth import, consent, "
355 "or provider-selection guidance"
356 )
357
358 if re.search(r"\b(?:antigravity|agy)\b", outside_tombstone, flags=re.IGNORECASE):
359 errors.append(
360 "docs/PROVIDERS.md mentions Antigravity/agy outside its legacy tombstone"
361 )
362 if re.search(r"\b(?:antigravity|agy)\b", configuration_md, flags=re.IGNORECASE):
363 errors.append("docs/CONFIGURATION.md advertises retired Antigravity state")
364 if re.search(r"\b(?:antigravity|agy)\b", readme_md, flags=re.IGNORECASE):
365 errors.append("README.md advertises retired Antigravity state")
366 if re.search(r"\b(?:antigravity|agy)\b", config_example_toml, flags=re.IGNORECASE):
367 errors.append("config.example.toml advertises retired Antigravity state")
368 if "[providers.google]" not in config_example_toml or not re.search(
369 r"GEMINI_API_KEY", config_example_toml
370 ):
371 errors.append(
372 "config.example.toml must document the supported `google` Gemini route "
373 "with GEMINI_API_KEY"
374 )
375
376 forbidden_markers = {
377 "Antigravity API-key environment guidance": "ANTIGRAVITY_API_KEY",
378 "Antigravity ADC environment guidance": "AGY_ADC_AUTH",
379 "Antigravity base-URL environment guidance": "ANTIGRAVITY_BASE_URL",
380 "Antigravity model environment guidance": "ANTIGRAVITY_MODEL",
381 "private cloud-code endpoint guidance": "cloudcode-pa",
382 "private cloud-code protocol guidance": "cloud-code",
383 "official CLI credential-store guidance": "state.vscdb",
384 "official CLI OAuth-state guidance": "antigravityUnifiedStateSync",
385 "runnable legacy provider selection": 'provider = "antigravity"',
386 "runnable legacy provider table": "[providers.antigravity]",
387 }
388 public_sources = {
389 "docs/PROVIDERS.md": providers_md,
390 "docs/CONFIGURATION.md": configuration_md,
391 "web/scripts/facts-lib.mjs": web_facts_lib,
392 "web/lib/facts-drift.ts": web_facts_drift,
393 "web/lib/facts.generated.ts": web_facts_generated,
394 "README.md": readme_md,
395 "config.example.toml": config_example_toml,
396 }
397 for context, source in public_sources.items():
398 for description, marker in forbidden_markers.items():
399 if marker.lower() in source.lower():
400 errors.append(f"{context} contains forbidden {description}")
401
402 projection = read(ROOT / "web/lib/provider-descriptors.mjs")
403 if 'row.retired || row.kind === "Antigravity" || row.kind === "Custom"' not in projection:
404 errors.append("shared website descriptor projection must exclude retired/Antigravity/custom rows")
405 for context, source in [("web/scripts/facts-lib.mjs", web_facts_lib), ("web/lib/facts-drift.ts", web_facts_drift)]:
406 if "parseProviderDescriptors" not in source:
407 errors.append(f"{context} must use the shared validated descriptor projection")
408 if re.search(r"^\s*Antigravity\s*:", source, flags=re.MULTILINE):
409 errors.append(f"{context} maps legacy Antigravity to public provider facts")
410 if re.search(r"\bagy\b", source, flags=re.IGNORECASE):
411 errors.append(f"{context} exposes the legacy agy alias")
412
413 if re.search(
414 r"\b(?:antigravity|agy)\b", web_facts_generated, flags=re.IGNORECASE
415 ):
416 errors.append("web/lib/facts.generated.ts exposes legacy Antigravity/agy")
417
418 return errors
419
420
421 def static_registry_provider_rows(providers_md: str) -> set[str]:
422 table = markdown_section(providers_md, "## Static Model Registry")
423 return set(re.findall(r"^\|\s*`([^`]+)`\s*\|", table, flags=re.MULTILINE))
424
425
426 def model_registry_providers(variant_to_id: dict[str, str]) -> set[str]:
427 # The reviewed catalog selections are the only shipping model roster.
428 # Reading tests or caller literals cannot reconstruct it.
429 data = json.loads(read(ROOT / "crates/config/assets/catalog_corrections.json"))
430 reviewed = data.get("reviewed")
431 if not isinstance(reviewed, dict) or not reviewed.get("revision"):
432 raise ValueError("reviewed catalog metadata missing")
433 rows = reviewed.get("selections")
434 if not isinstance(rows, list) or not rows:
435 raise ValueError("reviewed catalog selections missing")
436 ids = {row.get("provider") for row in rows if isinstance(row, dict)}
437 if None in ids or ids - set(variant_to_id.values()):
438 raise ValueError("reviewed catalog uses missing/unknown provider identity")
439 return ids
440
441
442 def default_strings(tui_config_rs: str) -> set[str]:
443 data = provider_data()
444 rows = {row["id"]: row for row in data["providers"]}
445 values = dict(data["compatibility_constants"])
446 for name, ref in data["constant_refs"].items():
447 row = rows[ref["provider"]]
448 values[name] = (row["credential_help"] if ref["field"] == "credential_url" else row)[ref["field"]]
449 defaults = {value for name, value in values.items()
450 if re.fullmatch(r"DEFAULT_[A-Z0-9_]+(?:MODEL|BASE_URL)", name)
451 and name != "DEFAULT_DEEPSEEKCN_BASE_URL"
452 and not name.startswith("DEFAULT_ANTIGRAVITY_")}
453 if not defaults:
454 raise ValueError("no default provider metadata found")
455 return defaults
456
457
458 def missing_default_strings(providers_md: str, defaults: set[str]) -> list[str]:
459 # Inline-code validation should not let fenced TOML/bash examples pair a
460 # stray backtick with later prose; strip fenced blocks before scanning.
461 inline_source = re.sub(r"```.*?```", "", providers_md, flags=re.DOTALL)
462 code_spans = set(re.findall(r"`([^`]+)`", inline_source))
463 return sorted(defaults - code_spans)
464
465
466 def report_set(label: str, expected: set[str], actual: set[str]) -> list[str]:
467 errors = []
468 missing = sorted(expected - actual)
469 extra = sorted(actual - expected)
470 if missing:
471 errors.append(f"{label} missing: {', '.join(missing)}")
472 if extra:
473 errors.append(f"{label} extra: {', '.join(extra)}")
474 return errors
475
476
477 def report_presentation_identity_drift(canonical_ids: set[str], presentation_ids: set[str]) -> list[str]:
478 legacy = provider_data()["legacy_tui"]["id"]
479 return report_set("released presentation identities", canonical_ids | {legacy}, presentation_ids)
480
481
482 def report_huggingface_coverage(
483 config_rs: str, provider_rs: str, tui_config_rs: str, providers_md: str
484 ) -> list[str]:
485 errors = []
486
487 config_aliases = parse_aliases_for_variant(
488 config_rs, "ProviderKind", "Huggingface", "crates/config/src/lib.rs"
489 )
490 tui_aliases = parse_aliases_for_variant(
491 tui_config_rs, "ProviderIdentity", "Huggingface", "crates/runtime/src/config.rs"
492 )
493 errors += report_set(
494 "ProviderKind Hugging Face aliases",
495 HUGGINGFACE_ALIASES,
496 config_aliases & HUGGINGFACE_ALIASES,
497 )
498 errors += report_set(
499 "descriptor presentation Hugging Face aliases",
500 HUGGINGFACE_ALIASES,
501 tui_aliases & HUGGINGFACE_ALIASES,
502 )
503
504 inline_source = re.sub(r"```.*?```", "", providers_md, flags=re.DOTALL)
505 code_spans = set(re.findall(r"`([^`]+)`", inline_source))
506 errors += report_set(
507 "documented Hugging Face aliases",
508 HUGGINGFACE_ALIASES,
509 code_spans & HUGGINGFACE_ALIASES,
510 )
511
512 # API-key lookup order is descriptor-owned; actual TUI environment
513 # resolution remains independently checked below.
514 auth_label = "Hugging Face auth env precedence"
515 row = next(row for row in provider_data()["providers"] if row["kind"] == "Huggingface")
516 if row["env_vars"] != HUGGINGFACE_API_KEY_ENV_ORDER:
517 errors.append("Hugging Face descriptor auth env precedence differs")
518 for label, env_order in [
519 (auth_label, HUGGINGFACE_API_KEY_ENV_ORDER),
520 ("Hugging Face base URL env precedence", HUGGINGFACE_BASE_URL_ENV_ORDER),
521 ("Hugging Face model env precedence", HUGGINGFACE_MODEL_ENV_ORDER),
522 ]:
523 if label != auth_label:
524 errors += report_env_lookup_order(
525 label, config_rs, env_order, "crates/config/src/lib.rs"
526 )
527 errors += report_env_lookup_order(
528 label, tui_config_rs, env_order, "crates/runtime/src/config.rs"
529 )
530 errors += report_string_order(label, providers_md, env_order, "docs/PROVIDERS.md")
531
532 return errors
533
534
535 def report_env_lookup_order(
536 label: str, source: str, expected_order: list[str], context: str
537 ) -> list[str]:
538 non_blank_chain = "env_non_blank(&[" + ", ".join(f'"{name}"' for name in expected_order) + "])"
539 if non_blank_chain in source:
540 return []
541 lookup_needles = [f'std::env::var("{name}")' for name in expected_order]
542 return report_string_order(label, source, lookup_needles, context)
543
544
545 def report_string_order(
546 label: str, source: str, expected_order: list[str], context: str
547 ) -> list[str]:
548 contains_sensitive_expected_value = any(
549 SENSITIVE_IDENTIFIER_RE.search(value) for value in expected_order
550 )
551 positions = []
552 for needle in expected_order:
553 index = source.find(needle)
554 if index == -1:
555 if contains_sensitive_expected_value:
556 return [f"{label} missing required entry in {context}"]
557 return [f"{label} missing {display_public_value(needle)!r} in {context}"]
558 positions.append(index)
559 if positions != sorted(positions):
560 if contains_sensitive_expected_value:
561 return [f"{label} has wrong order in {context}"]
562 return [
563 f"{label} has wrong order in {context}: expected "
564 + " before ".join(display_public_value(value) for value in expected_order)
565 ]
566 return []
567
568
569 def provider_table_name(provider_id: str) -> str:
570 return SHARED_PROVIDER_TABLES.get(provider_id, provider_id.replace("-", "_"))
571
572
573 def main() -> int:
574 try:
575 config_rs = "\n".join(read(path) for path in sorted(CONFIG_RS.parent.glob("*.rs")) if path.name != "tests.rs")
576 provider_kind_rs = read(PROVIDER_KIND_RS)
577 tui_config_rs = read(TUI_CONFIG_RS)
578 providers_md = read(PROVIDERS_MD)
579 configuration_md = read(CONFIGURATION_MD)
580 web_facts_lib = read(WEB_FACTS_LIB)
581 web_facts_drift = read(WEB_FACTS_DRIFT)
582 web_facts_generated = read(WEB_FACTS_GENERATED)
583 readme_md = read(README_MD)
584 config_example_toml = read(CONFIG_EXAMPLE_TOML)
585 provider_readiness_rs = read(PROVIDER_READINESS_RS)
586 tui_lib_rs = read(TUI_LIB_RS)
587
588 variant_to_id = provider_kind_ids(config_rs)
589 canonical_ids = set(variant_to_id.values())
590 selectable_provider_ids = provider_kind_catalog_ids(
591 provider_kind_rs, variant_to_id
592 )
593 presentation_ids = presentation_provider_ids()
594 public_provider_ids = canonical_ids - LEGACY_PROVIDER_TOMBSTONE_IDS
595 expected_tables = {
596 provider_table_name(provider_id) for provider_id in public_provider_ids
597 }
598 runtime_tables = expected_tables | LEGACY_PROVIDER_TOMBSTONE_TABLES
599
600 errors: list[str] = []
601 errors += report_presentation_identity_drift(canonical_ids, presentation_ids)
602 errors += report_provider_kind_selector_contract(provider_kind_rs)
603 errors += report_tui_catalog_contract(tui_config_rs)
604 errors += report_tombstone_runtime_contract(
605 provider_kind_rs, provider_readiness_rs, tui_lib_rs
606 )
607 errors += report_set(
608 "legacy provider identities in ProviderKind::ALL",
609 set(),
610 selectable_provider_ids & LEGACY_PROVIDER_SELECTION_IDS,
611 )
612 errors += report_set(
613 "documented selectable provider IDs",
614 selectable_provider_ids,
615 documented_selectable_provider_ids(providers_md),
616 )
617 errors += report_huggingface_coverage(
618 config_rs, read(PROVIDER_RS), tui_config_rs, providers_md
619 )
620 errors += report_antigravity_public_contract(
621 providers_md,
622 configuration_md,
623 web_facts_lib,
624 web_facts_drift,
625 web_facts_generated,
626 readme_md,
627 config_example_toml,
628 )
629 errors += report_set(
630 "shipped provider rows",
631 public_provider_ids,
632 shipped_provider_rows(providers_md),
633 )
634 errors += report_set(
635 "provider TOML tables",
636 runtime_tables,
637 provider_tables(config_rs) - META_PROVIDER_TABLES,
638 )
639 errors += report_set(
640 "documented provider TOML tables",
641 expected_tables,
642 shipped_provider_tables(providers_md),
643 )
644 errors += report_set(
645 "reviewed catalog selection rows",
646 model_registry_providers(variant_to_id),
647 static_registry_provider_rows(providers_md),
648 )
649
650 missing_defaults = missing_default_strings(providers_md, default_strings(tui_config_rs))
651 if missing_defaults:
652 errors.append(
653 "docs/PROVIDERS.md does not mention default strings as Markdown code spans: "
654 + ", ".join(missing_defaults)
655 )
656 except ValueError as err:
657 errors = [str(err)]
658
659 if errors:
660 print("Provider registry drift check failed:", file=sys.stderr)
661 for error in errors:
662 print(f"- {redact_sensitive_text(error)}", file=sys.stderr)
663 return 1
664
665 print("Provider registry drift check passed.")
666 return 0
667
668
669 if __name__ == "__main__":
670 raise SystemExit(main())
671
671 lines PYTHON