pyfcstm.diagnostics.codes

Loader for the structured diagnostic code registry.

This module loads codes.yaml (the single source of truth for diagnostic codes emitted by pyfcstm diagnostic pipelines) at import time and exposes the parsed table as CODE_REGISTRY. Downstream consumers — including the research_ideas LLM agent loop, IDE integrations, and the future jsfcstm visualization layer — can mirror this registry to drive their own dispatch logic without depending on exception message text.

The loader performs structural validation on import so that schema drift in codes.yaml fails fast. Validation failures raise CodesSchemaError (subclass of ValueError), so callers can distinguish “the diagnostics package is structurally broken” from a generic business-level ValueError further up the stack.

The module contains:

  • CodeFieldSpec - Per-field schema describing a refs payload key.

  • CodeSpec - Full specification for one diagnostic code.

  • CodesSchemaError - Raised when codes.yaml is structurally invalid.

  • CODE_REGISTRY - Mapping code -> CodeSpec loaded at import time.

  • load_codes() - Parse a YAML file path and return the registry.

Note

_ALLOWED_REF_TYPES and _ALLOWED_SEVERITIES are documentation-level enumerations used to validate the YAML schema. They do not enforce runtime isinstance checks on emitted ModelDiagnostic.refs values — type-checking refs payloads at emit time is the emitter’s responsibility. The schema’s job is to give downstream tooling a contract to mirror, not to act as a runtime type system.

Example:

>>> from pyfcstm.diagnostics import CODE_REGISTRY
>>> spec = CODE_REGISTRY['E_UNDEFINED_VAR']
>>> spec.severity
'error'
>>> 'var_name' in spec.refs_schema
True

CODE_REGISTRY

pyfcstm.diagnostics.codes.CODE_REGISTRY: Mapping[str, CodeSpec]

Mapping code -> CodeSpec loaded from codes.yaml at import time.

The mapping is wrapped in types.MappingProxyType so downstream callers cannot mutate the registry by accident.

CodesSchemaError

class pyfcstm.diagnostics.codes.CodesSchemaError[source]

Raised when codes.yaml is structurally invalid.

Subclasses ValueError so generic except ValueError handlers still catch it, but downstream tooling that wants to distinguish “diagnostics package broken” from a domain-level ValueError can use a tighter handler.

CodeFieldSpec

class pyfcstm.diagnostics.codes.CodeFieldSpec(name: str, type: str, required: bool, description: str, enum: Tuple[str, ...] | None = None, item_enum: Tuple[str, ...] | None = None, exact_values: Tuple[str, ...] | None = None)[source]

Schema for a single field inside CodeSpec.refs_schema.

Parameters:
  • name (str) – Field name as it will appear in ModelDiagnostic.refs.

  • type (str) – Field type token. Must be one of the allowed type tokens documented at the top of codes.yaml.

  • required (bool) – Whether this field must be present when the diagnostic is emitted.

  • description (str) – Human-readable explanation of the field.

  • enum (Optional[Tuple[str, ...]]) – Optional tuple of allowed string values for the field. When present, downstream emit-test infrastructure (and any future runtime validator) checks that refs[field] is a member of the tuple. None means the field has no enumeration constraint.

  • item_enum (Optional[Tuple[str, ...]]) – Optional tuple of allowed string values for items in a list[str] field. None means list members are unconstrained beyond being strings.

  • exact_values (Optional[Tuple[str, ...]]) – Optional exact ordered value contract for a list[str] field. None means the list may contain any ordered members allowed by item_enum and the base type token.

Example:

>>> spec = CodeFieldSpec(
...     name='target_templates',
...     type='list[str]',
...     required=True,
...     description='Target templates.',
...     exact_values=('c', 'c_poll'),
... )
>>> spec.exact_values
('c', 'c_poll')

ForLlmSpec

class pyfcstm.diagnostics.codes.ForLlmSpec(summary: str, recommended_actions: Tuple[Mapping[str, Any], ...], do_not: Tuple[str, ...])[source]

Structured guidance attached to a diagnostic code for downstream LLM consumers.

Emitted E_*, W_*, and I_* codes carry this payload so that LLM agent loops can read structured fix recommendations instead of regex-ing the human-readable message. All catalogued codes are expected to provide this field unless the loader is explicitly handling a forward-compatibility case.

Parameters:
  • summary (str) – One-line description aimed at LLM consumers.

  • recommended_actions (Tuple[Mapping[str, Any], ...]) – Ordered list of concrete fix suggestions. Each entry is a free-form dict; downstream tooling is expected to treat the list as a hint rather than a closed schema.

  • do_not (Tuple[str, ...]) – List of anti-pattern strings the LLM should avoid.

SuggestedFixSpec

class pyfcstm.diagnostics.codes.SuggestedFixSpec(kind: str, target: str, anchor_ref: str, text_template: str, rationale: str)[source]

Structured auto-fix metadata declared by codes.yaml.

Parameters:
  • kind (str) – Edit operation kind: insert, delete, or replace.

  • target (str) – Semantic target kind, such as variable_definition.

  • anchor_ref (str) – Reference to a field in the emitted refs payload, written as refs.<field>.

  • text_template (str) – Optional edit text template. insert and replace use it; delete normally leaves it empty.

  • rationale (str) – Short reason suitable for LLM/UI display.

CodeSpec

class pyfcstm.diagnostics.codes.CodeSpec(code: str, severity: str, description: str, refs_schema: Mapping[str, CodeFieldSpec], example_dsl: str | None = None, capability: str = 'pure_static', for_llm: ForLlmSpec | None = None, emit_tier: str = 'static_pipeline', suggested_fix: SuggestedFixSpec | None = None, span_object: str | None = None)[source]

Full specification for a single diagnostic code.

Parameters:
  • code (str) – Stable code identifier (e.g. 'E_UNDEFINED_VAR').

  • severity (str) – 'error', 'warning', or 'info'.

  • description (str) – Human-readable description of when the code fires.

  • refs_schema (Mapping[str, CodeFieldSpec]) – Mapping field_name -> CodeFieldSpec describing the structured payload for diagnostics with this code. The mapping itself is a types.MappingProxyType so downstream callers cannot mutate the registry by accident.

  • example_dsl (str, optional) – Minimal DSL snippet that triggers the code, defaults to None.

  • capability (str, optional) – Which analysis tier this code belongs to. Layer 2 declares this required when present; unset means 'pure_static' for grandfathered Layer 1 codes.

  • for_llm (ForLlmSpec, optional) – Structured guidance for downstream LLM consumers. Expected on catalogued codes so downstream tooling can consume structured remediation guidance. Still typed as Optional so the loader can tolerate forward-compatibility cases.

  • emit_tier (str, optional) – Which emit pipeline actually fires this code. 'static_pipeline' (default) means the code fires during parse_dsl_node_to_state_machine / the equivalent jsfcstm collectDocumentDiagnostics static analysis pass. 'lookup_api' means the code only fires through explicit runtime resolver APIs (e.g. State.resolve_event) and is never produced by the static pipeline. 'partial_static_pipeline' marks codes whose static-pipeline emit is implemented on one end only (typically jsfcstm) — downstream LLM consumers should not block waiting for the missing end. 'verify_pipeline' marks diagnostics emitted only by optional Python verify integration. 'catalog_only' marks a shared catalog contract that no runtime pipeline emits yet. The field lets dispatchers register handlers based on the actual emit channel.

  • span_object (str, optional) – Semantic source object identified by the primary diagnostic span. Repository entries declare this to make source-slice assertions and downstream UI behavior explicit.

required_fields() List[str][source]

Return the names of fields that must be present in refs.

Returns:

List of required field names in declaration order.

Return type:

List[str]

load_codes

pyfcstm.diagnostics.codes.load_codes(path: str) Dict[str, CodeSpec][source]

Load and validate a codes.yaml file from disk.

Parameters:

path (str) – Filesystem path to the YAML file.

Returns:

Mapping code -> CodeSpec parsed from the file.

Return type:

Dict[str, CodeSpec]

Raises:
  • FileNotFoundError – If path does not exist.

  • CodesSchemaError – If the YAML structure does not match the expected schema, or if a code uses an unknown severity / type token. Subclasses ValueError for backwards compatibility with generic except ValueError handlers.

Example:

>>> import os
>>> from pyfcstm.diagnostics.codes import load_codes
>>> path = os.path.join(os.path.dirname(__file__), 'codes.yaml')