"""Versioned, strict configuration models."""
from __future__ import annotations
import os
import re
from pathlib import Path
from typing import Any, Literal
import yaml
from pydantic import Field, ValidationError, field_validator, model_validator
from .models import SCHEMA_VERSION, RunMode, StrictModel
from .net import NetworkPolicy
SAFE_COMPONENT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
def _is_safe_component(value: str) -> bool:
return bool(SAFE_COMPONENT.fullmatch(value))
class DetectionConfig(StrictModel):
source: Literal["X", "x", "raw", "layer"]
key: str = ""
required: bool = False
semantics: str = "> 0"
@model_validator(mode="after")
def require_layer_key(self) -> DetectionConfig:
if self.source.lower() == "layer" and not self.key.strip():
raise ValueError("detection layer key must not be blank")
return self
class RepresentationConfig(StrictModel):
source: Literal["X", "x", "raw", "layer"]
key: str = ""
feature_space: str | None = None
ranking_backend: str
ontology_compatible: bool = False
detection: DetectionConfig | None = None
peak_to_gene_path: str = ""
motif_mapping_path: str = ""
weight: float = Field(default=1.0, gt=0)
@model_validator(mode="after")
def require_layer_key(self) -> RepresentationConfig:
if self.source.lower() == "layer" and not self.key.strip():
raise ValueError("representation layer key must not be blank")
if self.peak_to_gene_path and self.motif_mapping_path:
raise ValueError(
"a representation must choose peak-to-gene or motif mapping, not both"
)
if not self.ranking_backend.strip():
raise ValueError("ranking_backend must not be blank")
return self
class GraphRepresentationConfig(StrictModel):
source: Literal["obsm", "X", "x", "layer"]
key: str = ""
class AssayConfig(StrictModel):
modality: str = "root"
kind: Literal["rna", "protein", "atac", "gene_activity", "spatial", "other"]
feature_space: str
feature_id_column: str = ""
gene_mapping_path: str = ""
capabilities: list[str] = Field(default_factory=list)
graph_representations: list[GraphRepresentationConfig] = Field(default_factory=list)
representations: dict[str, RepresentationConfig]
class InputKeysConfig(StrictModel):
canonical_parent: str
scope: str
stored_resolutions: list[str] = Field(default_factory=list)
embedding: str = ""
spatial: str = ""
donor: str = ""
capture: str = ""
doublet_class: str = ""
doublet_score: str = ""
sex: str = ""
batch: str = ""
@field_validator("canonical_parent", "scope")
@classmethod
def named_obs_column(cls, value: str) -> str:
if not value.strip():
raise ValueError(
"input.keys.canonical_parent and input.keys.scope name obs columns"
)
return value
class InputConfig(StrictModel):
kind: Literal["h5ad", "h5mu"]
path: str
expected_sha256: str = ""
assays: dict[str, AssayConfig]
keys: InputKeysConfig
required_obs_keys: list[str] = Field(default_factory=list)
guide_columns: list[str] = Field(default_factory=list)
technical_metrics: dict[str, str] = Field(default_factory=dict)
@model_validator(mode="after")
def valid_source(self) -> InputConfig:
if not self.path.strip():
raise ValueError("input.path must not be blank")
if self.expected_sha256 and not re.fullmatch(r"[0-9a-f]{64}", self.expected_sha256):
raise ValueError("input.expected_sha256 must be a lowercase SHA-256 hex digest")
if not self.assays:
raise ValueError("input.assays must declare at least one assay")
return self
class RunConfig(StrictModel):
run_id: str
output_root: str
mode: RunMode = RunMode.EVIDENCE_ONLY
immutable: bool = True
@model_validator(mode="after")
def safe_run_path(self) -> RunConfig:
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}", self.run_id):
raise ValueError("run.run_id must be a safe 1-128 character path component")
if not self.output_root.strip():
raise ValueError("run.output_root must not be blank")
if not self.immutable:
raise ValueError("run.immutable must remain true")
return self
class ProviderConfig(StrictModel):
kind: Literal[
"local_markers",
"ontology",
"remote_ontology",
"live_ontology",
"reference",
"cached_table",
"remote_table",
"corpus",
]
path: str = ""
url: str = ""
sha256: str = ""
version: str = "unversioned"
label_key: str = ""
parent_key: str = ""
cache_path: str = ""
timeout_seconds: float = Field(default=30.0, gt=0)
context: dict[str, str] = Field(default_factory=dict)
@model_validator(mode="after")
def provider_contract(self) -> ProviderConfig:
if (
self.kind in {"local_markers", "ontology", "reference", "cached_table", "corpus"}
and not self.path
):
raise ValueError(f"{self.kind} provider requires path")
if self.kind == "corpus":
if self.version == "unversioned" or not re.fullmatch(r"[0-9a-f]{64}", self.sha256):
raise ValueError("corpus provider requires version and a lowercase SHA-256 digest")
if self.kind == "reference" and not self.label_key:
raise ValueError("reference provider requires label_key")
if self.kind in {"remote_table", "remote_ontology"}:
missing = [
name
for name, value in {
"url": self.url,
"cache_path": self.cache_path,
"sha256": self.sha256,
"version": self.version,
}.items()
if not value or value == "unversioned"
]
if missing:
raise ValueError(f"{self.kind} provider misses: {', '.join(missing)}")
if not re.fullmatch(r"[0-9a-f]{64}", self.sha256):
raise ValueError(f"{self.kind} sha256 must be a lowercase SHA-256 digest")
if self.kind == "live_ontology":
# A live service has no stable digest — that is the point of querying it —
# so this provider pins the endpoint instead and hashes each response it
# stores. It corroborates an authoritative ontology; it never replaces one.
if not self.url.startswith("https://"):
raise ValueError("live_ontology provider requires an https url")
if self.sha256 or self.cache_path or self.path:
raise ValueError(
"live_ontology provider takes only url, version, and timeout_seconds"
)
return self
class KnowledgeConfig(StrictModel):
providers: list[ProviderConfig] = Field(default_factory=list)
require_local_grounding_for_labels: bool = True
# offline: no request leaves the process. institution: localhost and
# allowed_hosts only. online: any host. See net.py.
network: Literal["offline", "institution", "online"] = "offline"
allowed_hosts: list[str] = Field(default_factory=list)
@model_validator(mode="before")
@classmethod
def legacy_remote_switch(cls, value: Any) -> Any:
# Configs written before `network` existed say true/false here.
if isinstance(value, dict) and "allow_optional_remote_enhancement" in value:
value = dict(value)
legacy = value.pop("allow_optional_remote_enhancement")
value.setdefault("network", "online" if legacy else "offline")
return value
@property
def allow_optional_remote_enhancement(self) -> bool:
return self.network != "offline"
@property
def policy(self) -> NetworkPolicy:
return NetworkPolicy(self.network, tuple(self.allowed_hosts))
@field_validator("require_local_grounding_for_labels")
@classmethod
def preserve_local_grounding(cls, value: bool) -> bool:
if not value:
raise ValueError("knowledge.require_local_grounding_for_labels must remain true")
return value
class CanonicalPartitionConfig(StrictModel):
parent_key: str
expected_parent_count: int = Field(ge=1)
class EligibilityConfig(StrictModel):
min_cells: int = Field(default=50, ge=2)
min_donors: int | None = Field(default=None, ge=1)
min_captures: int | None = Field(default=None, ge=1)
rare_exceptions_require_approval: bool = True
@field_validator("rare_exceptions_require_approval")
@classmethod
def preserve_rare_exception_gate(cls, value: bool) -> bool:
if not value:
raise ValueError(
"adaptive.eligibility.rare_exceptions_require_approval must remain true"
)
return value
class AuditConfig(StrictModel):
guide_entropy_min: float = Field(default=0.6, ge=0, le=1)
meaningful_minority_fraction: float = Field(default=0.1, ge=0, le=1)
doublet_fraction_max: float | None = Field(default=None, ge=0, le=1)
donor_max_fraction: float | None = Field(default=None, ge=0, le=1)
capture_max_fraction: float | None = Field(default=None, ge=0, le=1)
technical_effect_size_max: float | None = Field(default=0.15, ge=0)
technical_metric_robust_z_max: float = Field(default=3.0, ge=0)
incompatible_program_fraction_min: float | None = Field(default=0.15, ge=0, le=1)
incompatible_program_columns: list[str] = Field(default_factory=list)
class StoredCandidateConfig(StrictModel):
min_parent_purity: float = Field(default=0.9, ge=0, le=1)
min_parent_fraction: float = Field(default=0.03, gt=0, lt=1)
max_parent_fraction: float = Field(default=0.95, gt=0, le=1)
adjacent_jaccard_min: float = Field(default=0.8, ge=0, le=1)
min_adjacent_matches: int = Field(default=1, ge=1)
class ParentLocalConfig(StrictModel):
enabled: bool = True
max_passes_per_parent: int = Field(default=1, ge=0, le=1)
resolutions: list[float] = Field(default_factory=lambda: [0.2, 0.4, 0.8])
stability_metric: Literal["ari", "jaccard"] = "ari"
stability_threshold_strictly_greater_than: float = Field(default=0.8, ge=0, le=1)
reference_seeds: list[int] = Field(default_factory=lambda: [0, 1, 2, 3, 4])
reject_one_cluster: bool = True
select: Literal["lowest_stable_biologically_resolving"] = (
"lowest_stable_biologically_resolving"
)
knn_k: int = Field(default=15, ge=2)
bootstrap_fraction: float = Field(default=0.8, gt=0.5, le=1)
@field_validator("reject_one_cluster")
@classmethod
def preserve_one_cluster_rejection(cls, value: bool) -> bool:
if not value:
raise ValueError("adaptive.parent_local.reject_one_cluster must remain true")
return value
class AdaptiveConfig(StrictModel):
outcomes: list[str]
eligibility: EligibilityConfig
audit: AuditConfig
stored_candidates: StoredCandidateConfig
parent_local: ParentLocalConfig
class ComparatorConfig(StrictModel):
roles: list[Literal["parent_remainder", "closest_sibling"]]
closest_sibling_strategy: Literal["embedding_centroid"] = "embedding_centroid"
@model_validator(mode="after")
def require_independent_comparators(self) -> ComparatorConfig:
required = {"parent_remainder", "closest_sibling"}
if len(self.roles) != 2 or set(self.roles) != required:
raise ValueError(
"comparators.roles must contain parent_remainder and closest_sibling exactly once"
)
return self
class GpuContractConfig(StrictModel):
name_contains: str
compute_capability: str
class MarkerConfig(StrictModel):
rapids_singlecell_version: str = ""
rapids_distribution: str = ""
cuda_major: int | None = None
cpu_fallback: bool = False
allowed_gpu_contracts: list[GpuContractConfig] = Field(default_factory=list)
wilcoxon: dict[str, Any] = Field(default_factory=dict)
logreg: dict[str, Any] = Field(default_factory=dict)
# De novo ranking (parent_remainder and closest_sibling) uses at most this many
# seeded cells per cluster. Program scoring, labels and other steps keep all cells.
ranking_max_cells_per_cluster: int | None = Field(default=None, ge=1)
ranking_seed: int = 0
# Directory for cached ranking frames; empty means no cache.
ranking_cache_dir: str = ""
@field_validator("cpu_fallback")
@classmethod
def prohibit_gpu_fallback(cls, value: bool) -> bool:
if value:
raise ValueError("CPU fallback is prohibited for RAPIDS lanes")
return value
class EvidenceLaneConfig(StrictModel):
assay: str
representation: str
lane_key: str | None = None
required_for_acceptance: bool = True
class ClassifierConfig(StrictModel):
name: str
method: Literal["celltypist", "popv"]
model: str
python_executable: str = ""
reference: str = ""
reference_label: str = ""
counts_layer: str = "counts"
reference_counts_layer: str = "counts"
methods: list[str] = Field(default_factory=lambda: ["CELLTYPIST", "Support_Vector", "XGboost"])
required: bool = False # decision row 10: advisory unless the user sets it
label_map: dict[str, str] = Field(default_factory=dict)
@model_validator(mode="after")
def valid_classifier(self) -> ClassifierConfig:
if not _is_safe_component(self.name):
raise ValueError("classifier name must be a safe path component")
if not self.model.strip():
raise ValueError("classifier requires a local model path")
if self.method == "popv" and (not self.reference or not self.reference_label):
raise ValueError("popv requires a local reference and reference_label")
return self
class IsolationConfig(StrictModel):
"""Decision row 21: the corpus may not be learned from the test split's donors."""
donor_split: str = Field(min_length=1)
test_split: str = Field(min_length=1)
dataset_id: str = ""
class AnnotationConfig(StrictModel):
enabled: bool = False
assay: str = ""
representation: str = ""
corpus_assay: str = ""
study_id: str = ""
classifiers: list[ClassifierConfig] = Field(default_factory=list)
min_classifier_agreement: float = Field(default=0.5, gt=0, le=1)
min_state_fraction: float = Field(default=0.5, gt=0, le=1)
# Decision row 17: a cell supports a state when at least this share of the
# state's positive genes is detected in it and no negative gene is.
min_state_positive_fraction: float = Field(default=0.5, gt=0, le=1)
seed: int = Field(default=0, ge=0)
isolation: IsolationConfig | None = None
# Development only (user decision, 2026-11-10): also call `imported` and `proposed`
# corpus records. It needs `isolation`, and such a run can never be written back.
development_candidates: bool = False
# Output directory of an annotation-consensus run. It chooses the label of each cluster;
# `annotation import-consensus` checks it against the plan's vocabulary and cells. The
# directory may be empty when the config is written, because the run needs the plan's
# vocabulary first. The decision receipt hashes what the import reads.
consensus_directory: str = ""
class EvidenceConfig(StrictModel):
lanes: list[EvidenceLaneConfig] = Field(default_factory=list)
adjusted_pvalue_max: float = Field(default=0.05, gt=0, le=1)
require_both_marker_methods: bool = True
require_both_comparators: bool = True
required_candidate_gates: list[str] = Field(default_factory=list)
parent_vocabulary: dict[str, str] = Field(default_factory=dict)
min_positive_coverage: float = Field(default=0.35, ge=0, le=1)
max_negative_violation: float = Field(default=0.25, ge=0, le=1)
min_confidence: float = Field(default=0.55, ge=0, le=1)
min_margin: float = Field(default=0.10, ge=0)
max_normalized_entropy: float = Field(default=0.85, ge=0, le=1)
@model_validator(mode="after")
def preserve_independent_crosschecks(self) -> EvidenceConfig:
if not self.require_both_marker_methods:
raise ValueError("evidence.require_both_marker_methods must remain true")
if not self.require_both_comparators:
raise ValueError("evidence.require_both_comparators must remain true")
return self
class ReviewConfig(StrictModel):
critic_passes: list[str] = Field(default_factory=list)
require_reconciliation: bool = True
require_explicit_human_approval: bool = True
type_and_state_separate: bool = True
@model_validator(mode="after")
def preserve_scientific_safeguards(self) -> ReviewConfig:
if not self.require_reconciliation:
raise ValueError("review.require_reconciliation must remain true")
if not self.require_explicit_human_approval:
raise ValueError("review.require_explicit_human_approval must remain true")
if not self.type_and_state_separate:
raise ValueError("review.type_and_state_separate must remain true")
return self
class HpcConfig(StrictModel):
cpu_resources: dict[str, Any] = Field(default_factory=dict)
gpu_resources: dict[str, Any] = Field(default_factory=dict)
class BiologicalContextConfig(StrictModel):
"""Biological and reporting facts that cannot be inferred safely from the object."""
organism: str = ""
tissue: str = ""
developmental_stage: str = ""
condition: str = ""
technology: Literal[
"dissociated", "whole_transcriptome_spatial", "targeted_panel", "other"
] = "other"
experimental_context: str = ""
composition_covariates: list[str] = Field(default_factory=list)
vocabulary_contract: str = ""
reference_contract: str = "local_only"
visualization_key: str = ""
writeback_prefix: str = "cell_curator"
def unresolved(self) -> list[str]:
required = {
"organism": self.organism,
"tissue": self.tissue,
"developmental_stage": self.developmental_stage,
"condition": self.condition,
"experimental_context": self.experimental_context,
"vocabulary_contract": self.vocabulary_contract,
"reference_contract": self.reference_contract,
"writeback_prefix": self.writeback_prefix,
}
unresolved = [name for name, value in required.items() if not value.strip()]
if self.technology == "other":
unresolved.append("technology")
return unresolved
class GuidanceConfig(StrictModel):
"""Interactive/non-interactive gate contract for the three-stage workflow."""
interactive: bool = True
preauthorized: bool = False
reviewer: str = ""
pause_after_each_level: bool = True
assumptions: list[str] = Field(default_factory=list)
hierarchy_levels: list[str] = Field(default_factory=lambda: ["L1"])
context: BiologicalContextConfig = Field(default_factory=BiologicalContextConfig)
@model_validator(mode="after")
def validate_preauthorization(self) -> GuidanceConfig:
if not self.hierarchy_levels or any(not item.strip() for item in self.hierarchy_levels):
raise ValueError("guidance.hierarchy_levels must contain non-blank level names")
if len(set(self.hierarchy_levels)) != len(self.hierarchy_levels):
raise ValueError("guidance.hierarchy_levels must be unique and ordered")
if self.preauthorized and self.interactive:
raise ValueError("preauthorized runs must set guidance.interactive=false")
if not self.interactive:
missing = self.context.unresolved()
if not self.preauthorized:
missing.append("guidance.preauthorized=true")
if not self.reviewer.strip():
missing.append("guidance.reviewer")
if not self.assumptions:
missing.append("guidance.assumptions")
if missing:
raise ValueError(
"non-interactive operation requires complete recorded context and "
"pre-authorization; missing: " + ", ".join(missing)
)
return self
[docs]
class CellCuratorConfig(StrictModel):
schema_version: int
run: RunConfig
knowledge: KnowledgeConfig = Field(default_factory=KnowledgeConfig)
input: InputConfig
canonical_partitions: dict[str, CanonicalPartitionConfig]
adaptive: AdaptiveConfig
comparators: ComparatorConfig
markers: MarkerConfig
evidence: EvidenceConfig
review: ReviewConfig
hpc: HpcConfig = Field(default_factory=HpcConfig)
guidance: GuidanceConfig = Field(default_factory=GuidanceConfig)
annotation: AnnotationConfig = Field(default_factory=AnnotationConfig)
[docs]
@field_validator("schema_version")
@classmethod
def current_schema(cls, value: int) -> int:
if value != SCHEMA_VERSION:
raise ValueError(f"schema_version must be {SCHEMA_VERSION}")
return value
[docs]
@model_validator(mode="after")
def references_exist(self) -> CellCuratorConfig:
if (
self.run.mode is RunMode.ANNOTATION
and self.knowledge.require_local_grounding_for_labels
):
grounding_kinds = {"local_markers", "reference", "cached_table", "corpus"}
if not any(item.kind in grounding_kinds for item in self.knowledge.providers):
raise ValueError(
"annotation mode requires a local marker, labeled reference, or cached-table "
"provider for biological grounding"
)
if self.annotation.enabled:
if self.evidence.min_confidence <= 0 or self.evidence.min_margin <= 0:
raise ValueError("corpus annotation requires positive confidence and margin thresholds")
if self.guidance.hierarchy_levels != ["L1"]:
raise ValueError(
"corpus annotation covers L1 only: deeper levels need a hierarchical "
"consensus call, which cell-curator does not support yet"
)
if self.annotation.assay not in self.input.assays:
raise ValueError("annotation.assay must name an input assay")
if self.annotation.representation not in self.input.assays[self.annotation.assay].representations:
raise ValueError("annotation.representation must name an assay representation")
if not any(provider.kind == "corpus" for provider in self.knowledge.providers):
raise ValueError("annotation.enabled requires a pinned corpus provider")
names = [item.name for item in self.annotation.classifiers]
if len(names) != len(set(names)):
raise ValueError("annotation classifier names must be unique")
gpu_lane = False
lane_keys: set[str] = set()
lane_pairs: set[tuple[str, str]] = set()
for assay_id, assay in self.input.assays.items():
if not _is_safe_component(assay_id):
raise ValueError(f"assay name is not a safe path component: {assay_id!r}")
for representation_name in assay.representations:
if not _is_safe_component(representation_name):
raise ValueError(
"representation name is not a safe path component: "
f"{representation_name!r}"
)
for level in self.guidance.hierarchy_levels:
if not _is_safe_component(level):
raise ValueError(f"hierarchy level is not a safe path component: {level!r}")
if self.adaptive.eligibility.min_donors is not None and not self.input.keys.donor:
raise ValueError("adaptive.eligibility.min_donors requires input.keys.donor")
if self.adaptive.eligibility.min_captures is not None and not self.input.keys.capture:
raise ValueError("adaptive.eligibility.min_captures requires input.keys.capture")
for lane in self.evidence.lanes:
if lane.assay not in self.input.assays:
raise ValueError(f"evidence lane refers to unknown assay {lane.assay!r}")
assay = self.input.assays[lane.assay]
if lane.representation not in assay.representations:
raise ValueError(
f"assay {lane.assay!r} lacks representation {lane.representation!r}"
)
backend = assay.representations[lane.representation].ranking_backend.lower()
gpu_lane = gpu_lane or backend in {"rapids_singlecell", "rapids-singlecell"}
key = lane.lane_key or f"{lane.assay}__{lane.representation}"
if not _is_safe_component(key):
raise ValueError(f"evidence lane key is not a safe path component: {key!r}")
if key in lane_keys:
raise ValueError(f"evidence lane key is duplicated: {key}")
lane_keys.add(key)
pair = (lane.assay, lane.representation)
if pair in lane_pairs:
raise ValueError(
"evidence assay/representation pair is duplicated: "
f"{lane.assay}/{lane.representation}"
)
lane_pairs.add(pair)
if gpu_lane:
missing = []
if not self.markers.rapids_singlecell_version:
missing.append("markers.rapids_singlecell_version")
if not self.markers.rapids_distribution:
missing.append("markers.rapids_distribution")
if self.markers.cuda_major is None:
missing.append("markers.cuda_major")
if not self.markers.allowed_gpu_contracts:
missing.append("markers.allowed_gpu_contracts")
if missing:
raise ValueError(
"RAPIDS lanes require a complete fail-closed GPU contract: "
+ ", ".join(missing)
)
return self
def anchor_relative_paths(config: CellCuratorConfig, *, config_dir: Path) -> CellCuratorConfig:
"""Resolve relative run, input, and provider paths against ``config_dir``.
Relative paths would otherwise be resolved against the process working
directory at the moment each artifact is opened. That is invisible in a
terminal, where the cwd rarely moves, but it breaks scripts run from
elsewhere and notebooks whose cwd differs between cells or across a kernel
restart — surfacing as a misleading "input object does not exist" rather
than as a path problem.
This rewrites only the in-memory model. The configuration file's bytes are
never touched, so every ``sha256(config_path)`` recorded for provenance and
compared on resume keeps matching regardless of the caller's cwd.
"""
from .contracts import ContractError
updates: dict[str, Any] = {}
output_root = Path(config.run.output_root)
if not output_root.is_absolute():
anchored = (config_dir / output_root).resolve()
legacy = output_root.resolve() # what cwd-relative resolution would pick
if anchored != legacy:
anchored_state = anchored / config.run.run_id / "run_state.json"
legacy_state = legacy / config.run.run_id / "run_state.json"
if legacy_state.is_file() and not anchored_state.is_file():
raise ContractError(
"run.output_root is relative and ambiguous: an existing run is "
f"recorded under {legacy_state.parent} (resolved against the current "
f"working directory) but not under {anchored_state.parent} (resolved "
"against the configuration file's own directory, which is the anchor "
"used from this version onward). Set run.output_root to an absolute "
"path to state unambiguously which run to resume."
)
updates["run"] = config.run.model_copy(update={"output_root": str(anchored)})
input_path = Path(config.input.path)
if not input_path.is_absolute():
updates["input"] = config.input.model_copy(
update={"path": str((config_dir / input_path).resolve())}
)
classifiers = []
for classifier in config.annotation.classifiers:
paths = {
name: (os.path.abspath(config_dir / value) if name == "python_executable"
else str((config_dir / value).resolve()))
for name in ("model", "reference", "python_executable")
if (value := getattr(classifier, name)) and not Path(value).is_absolute()
}
classifiers.append(classifier.model_copy(update=paths))
annotation_updates: dict[str, Any] = {"classifiers": classifiers} if classifiers else {}
isolation = config.annotation.isolation
if isolation and not Path(isolation.donor_split).is_absolute():
annotation_updates["isolation"] = isolation.model_copy(
update={"donor_split": str((config_dir / isolation.donor_split).resolve())}
)
if annotation_updates:
updates["annotation"] = config.annotation.model_copy(update=annotation_updates)
anchored_providers = []
provider_changed = False
for provider in config.knowledge.providers:
provider_updates: dict[str, Any] = {}
if provider.path and not Path(provider.path).is_absolute():
provider_updates["path"] = str((config_dir / provider.path).resolve())
if provider.cache_path and not Path(provider.cache_path).is_absolute():
provider_updates["cache_path"] = str((config_dir / provider.cache_path).resolve())
if provider_updates:
provider_changed = True
anchored_providers.append(provider.model_copy(update=provider_updates))
else:
anchored_providers.append(provider)
if provider_changed:
updates["knowledge"] = config.knowledge.model_copy(
update={"providers": anchored_providers}
)
return config.model_copy(update=updates) if updates else config
[docs]
def load_config(path: str | Path) -> CellCuratorConfig:
source = Path(path)
try:
value = yaml.safe_load(source.read_text())
except (OSError, yaml.YAMLError) as exc:
raise ValueError(f"could not read configuration {source}: {exc}") from exc
if not isinstance(value, dict):
raise ValueError("configuration must be a YAML mapping")
try:
config = CellCuratorConfig.model_validate(value)
except ValidationError as exc:
raise ValueError(f"invalid cell-curator configuration: {exc}") from exc
return anchor_relative_paths(config, config_dir=source.resolve().parent)
def configuration_schema() -> dict[str, Any]:
"""Return the canonical machine-readable schema for configuration version 3."""
schema = CellCuratorConfig.model_json_schema()
schema["$id"] = "urn:cell-curator:schema:configuration:3"
schema["x-cell-curator-schema-version"] = SCHEMA_VERSION
return schema