Skip to content

API documentation

Automatically generated API reference of the Mellea Skills Compiler.

mellea_skills_compiler

Mellea Skills Compiler — Agent specification certification pipeline.

Transforms agent skill specifications into policy-governed, certified pipelines with evidence packages documenting risks, compliance posture, and runtime governance.

Modules:

certification

Modules:

  • classification –
  • data –
  • exceptions –
  • ingest –

    Mellea Skills Compiler — Ingest an OpenClaw SKILL.md and certify it.

  • input_resolver –

    Input resolution for mellea-skills run command.

  • pipeline –

    Mellea Skills Compiler — Full Pipeline: SKILL.md → decomposed pipeline → Guardian → certification.

  • policy –

    AI Atlas Nexus policy generation for Mellea Skills Compiler.

  • report –

    Generate a certification report with audit trail evidence showing which requirements are

Functions:

  • skill_to_use_case –

    Compose a use-case description from parsed skill + sensitivity.

skill_to_use_case

skill_to_use_case(parsed: dict[str, Any], sensitivity: dict[str, Any]) -> str

Compose a use-case description from parsed skill + sensitivity.

classification

Functions:

classify_governance_requirements
classify_governance_requirements(manifest: PolicyManifest, nexus) -> ComplianceSummary

Classify each governance requirement as AUTOMATED, PARTIAL, or MANUAL based on pipeline controls from pipeline_control_mappings.yaml.

Parameters:

  • manifest (PolicyManifest) –

    description

  • nexus (_type_) –

    description

Returns:

classify_skill_sensitivity
classify_skill_sensitivity(tools: list[str], body: str) -> dict

Classify skill sensitivity from tool list and body keywords.

── Tool sensitivity classification ───────────────────────────────
Simple lookup: tool name → sensitivity tier + operation types.
Grounded in POSIX permission model (R/W/X) and Google OAuth
3-tier sensitivity (non-sensitive / sensitive / restricted).
PROVENANCE: claude-suggested — validate tool classifications

Returns: tier, operations, and body-detected capabilities.

data

Functions:

Attributes:

PACKAGEDIR module-attribute
PACKAGEDIR = Path(__file__).parent.absolute()
get_data_path
get_data_path()

exceptions

Classes:

CertificationInterrupted
CertificationInterrupted(signal_number: int)

Bases: KeyboardInterrupt

Attributes:

signal_number instance-attribute
signal_number = signal_number

ingest

Mellea Skills Compiler — Ingest an OpenClaw SKILL.md and certify it.

Pipeline
  1. Parse SKILL.md (YAML frontmatter + markdown body)
  2. Classify tool sensitivity tier (lookup table, no regex)
  3. Compose use-case description for Nexus
  4. Nexus risk identification → policy manifest
  5. Compliance classification
  6. Certification report

Functions:

  • ingest_one –

    Risk Analysis and Policy Generation Pipeline for Mellea skill

Attributes:

LOGGER module-attribute
ingest_one
ingest_one(spec_path: Path, dry_run: bool = False, risk_model: Optional[str] = None, inference_engine_type: InferenceEngineType = OLLAMA) -> None

Risk Analysis and Policy Generation Pipeline for Mellea skill

Parameters:

  • skill_name (str) –

    Mellea Skill spec path.

  • dry_run (bool, default: False ) –

    Preview without making LLM calls. Defaults to False.

  • risk_model (Optional[str], default: None ) –

    Model to use for Risk and Action Identification. The inference_engine param must support the model. If set to None, the default model for the inference engine will be used.

  • inference_engine (InferenceEngineType) –

    Service to use for LLM inference. Defaults to InferenceEngineType.OLLAMA.

input_resolver

Input resolution for mellea-skills run command.

Implements Stage 1 of the deep-research recommendations: - Multi-source input handling (file, raw, stdin, fixture) - Mutual exclusion checking - Signature-aware parameter mapping

Classes:

Functions:

  • resolve_input –

    Resolve input from multiple possible sources.

Attributes:

LOGGER module-attribute
InputResolutionError

Bases: Exception

Raised when input resolution fails.

resolve_input
resolve_input(pipeline_fn: Callable, input: Optional[str] = None, fixture_id: Optional[str] = None, fixtures: Optional[List[Fixture]] = None) -> Fixture

Resolve input from multiple possible sources.

Implements Stage 1 mutual exclusion and resolution logic.

Parameters:

  • pipeline_fn (Callable) –

    The pipeline function to run

  • input (Optional[str], default: None ) –

    --input value (may include @file/@- syntax)

  • fixture_id (Optional[str], default: None ) –

    Fixture identifier

  • fixtures (Optional[List[Fixture]], default: None ) –

    List of available fixtures

Returns:

  • Fixture –

    ResolvedInput with context dict and metadata

pipeline

Mellea Skills Compiler — Full Pipeline: SKILL.md → decomposed pipeline → Guardian → certification.

End-to-end demonstration
  1. Ingest a SKILL.md → parse, classify sensitivity, compose use-case
  2. Identify risks via AI Atlas Nexus → policy manifest
  3. Configure Guardian hooks from manifest (pre + post generation)
  4. Run test fixtures through the DECOMPOSED pipeline → Guardian intercepts every m.instruct() call inside the pipeline → Audit trail captures every generation + Guardian verdict
  5. Compliance classification
  6. Certification report with runtime evidence

Functions:

  • full_pipeline –

    Full Certification Pipeline for Mellea skill

  • run_pipeline –

    Full Certification Pipeline for Mellea skill

Attributes:

LOGGER module-attribute
console module-attribute
console: Console = Console(log_time=True)
full_pipeline
full_pipeline(pipeline_dir: Path, guardian_mode: GuardianMode, n_fixtures: int = 3, risk_model: Optional[str] = None, guardian_model: Optional[str] = None, inference_engine_type: InferenceEngineType = OLLAMA) -> RunResult

Full Certification Pipeline for Mellea skill

Parameters:

  • pipeline_dir (Path) –

    Compiled Mellea skill pipeline directory.

  • guardian_mode (GuardianMode) –

    Run pipeline in enforce mode (block on risk detection), audit mode or with guardian assessment disabled.

  • n_fixtures (int, default: 3 ) –

    Specify the number of fixtures to evaluate for the certification process. Defaults to 3.

  • risk_model (Optional[str], default: None ) –

    Model to use for Risk and Action Identification. The inference_engine param must support the model. If set to None, the default model for the inference engine will be used.

  • guardian_model (Optional[str], default: None ) –

    Model to use for Risk Assessment. The inference_engine param must support the model. If set to None, the default guardian model for the inference engine will be used.

  • inference_engine_type (InferenceEngineType, default: OLLAMA ) –

    Service to use for LLM inference. Defaults to InferenceEngineType.OLLAMA.

Returns:

  • RunResult ( RunResult ) –

    Result object containing run directory, input parameters, guardian verdicts, and status.

run_pipeline
run_pipeline(pipeline_dir: Path, guardian_mode: GuardianMode, fixture_id: Optional[str] = None, input: Optional[str] = None, guardian_model: Optional[str] = None, inference_engine_type: InferenceEngineType = OLLAMA) -> RunResult

Full Certification Pipeline for Mellea skill

Parameters:

  • pipeline_dir (Path) –

    Compiled Mellea skill pipeline directory.

  • guardian_mode (GuardianMode) –

    Run pipeline in enforce mode (block on risk detection), audit mode or with guardian assessment disabled.

  • fixture_id (str, default: None ) –

    fixture_id to run through the Mellea pipeline. If None, uses input parameter.

  • input (str, default: None ) –

    input specification to run through the Mellea pipeline. Supports five input types.

  • guardian_model (Optional[str], default: None ) –

    Model to use for Risk Assessment. The inference_engine param must support the model. If set to None, the default guardian model for the inference engine will be used.

  • inference_engine_type (InferenceEngineType, default: OLLAMA ) –

    Service to use for LLM inference. Defaults to InferenceEngineType.OLLAMA.

Returns:

  • RunResult ( RunResult ) –

    Result object containing run directory, input parameters, guardian verdicts, and status.

policy

AI Atlas Nexus policy generation for Mellea Skills Compiler.

Functions:

Attributes:

LOGGER module-attribute
generate_policy_manifest
generate_policy_manifest(use_case: str, nexus, inference_engine, governance_taxonomies: Optional[List[str]] = None) -> PolicyManifest

Identify applicable risks and governance actions to produce a multi-taxonomy policy manifest.

Parameters:

  • use_case (str) –

    Natural language description of the agent's purpose.

  • nexus (AIAtlasNexus) –

    AI Atlas Nexus instance.

  • inference_engine (InferenceEngine) –

    Service to use for LLM inference. Defaults to InferenceEngineType.OLLAMA.

  • governance_taxonomies (Optional[List[str]], default: None ) –

    List of taxonomy IDs for governance actions.

Returns: PolicyManifest with Guardian risks and governance actions.

generate_policy_markdown
generate_policy_markdown(manifest: PolicyManifest) -> str

Generate a human-readable .md policy document from a manifest.

Includes
  • Guardian runtime risk checks (what the hooks monitor)
  • NIST AI RMF governance actions (organisational requirements)
  • Credo UCF controls (specific mitigation measures)
  • Guardrail configuration table
  • Audit trail specification
guardian_criteria_id
guardian_criteria_id(tag: str) -> str

Convert a Nexus tag (unethical-behavior) to a Guardian criteria id (unethical_behavior).

load_policy_manifest
load_policy_manifest(manifest_path: Path) -> PolicyManifest

Search for policy_manifest.json in standard locations.

Checks the skill root first (portable), then the audit directory.

report

Generate a certification report with audit trail evidence showing which requirements are satisfied and how.

Functions:

Attributes:

EVIDENCE_EXTRACTORS module-attribute
EVIDENCE_EXTRACTORS: dict[str, Any] = {'pc-content-safety': _extract_guardian_evidence, 'pc-input-screening': _extract_io_evidence, 'pc-generation-audit': _extract_audit_evidence, 'pc-component-audit': _extract_audit_evidence, 'pc-validation-audit': _extract_audit_evidence, 'pc-latency-monitoring': _extract_performance_evidence, 'pc-incident-flagging': _extract_incident_evidence, 'pc-policy-traceability': _extract_audit_evidence}
generate_certification_report
generate_certification_report(manifest: PolicyManifest, compliance: ComplianceSummary, audit_trail: list[dict], audit_path: str = '') -> str

Generate a Markdown certification report with evidence.

Parameters:

Returns:

  • str ( str ) –

    description

load_audit_trail
load_audit_trail(path: str | Path) -> list[dict]

Load JSONL audit trail into a list of dicts.

cli

Functions:

  • certify –

    Run full certification pipeline on a compiled skill.

  • compile –

    Compile Mellea skill specification into a Mellea pipeline using mellea-fy Claude command.

  • export –

    Export a compiled Mellea skill to a deployment target (langgraph, claude-code, mcp, or pi).

  • ingest –

    Run risk analysis on a skill specification.

  • main –

    Mellea Skills Compiler CLI - Agent specification certification pipeline.

  • run –

    Run Mellea Skill Pipeline.

  • validate –

    Run Step 7 structural lints and (unless --no-run) the fixture smoke-check.

  • version –

    Print the installed mellea-skills-compiler package version.

Attributes:

LOGGER module-attribute

app module-attribute

app: Typer = typer.Typer(no_args_is_help=True)

certify

certify(ctx: Context, pipeline_dir: Annotated[str, Argument(help='Compiled skill pipeline directory.', rich_help_panel=Arguments)], n_fixtures: Annotated[int, Option(-n, help='Number of fixtures to evaluate.')] = 3, enforce: Annotated[bool, Option(--enforce, -e, help='Run pipeline in enforce mode (block on risk detection)')] = False, risk_model: Annotated[Optional[str], Option(--risk - model, help='Model to use for Risk and Action Identification. The `--inference-engine` option must support the model. If set to None, the default model for the inference engine will be used.')] = None, guardian_model: Annotated[Optional[str], Option(--guardian - model, help='Model to use for Risk Assessment. The `--inference-engine` option must support the model. If set to None, the default guardian model for the inference engine will be used.')] = None, inference_engine: Annotated[Literal['ollama', 'vllm'], Option(--inference - engine, callback=lambda x: upper(), help='Service to use for LLM inference. Supported: ollama')] = 'ollama') -> None

Run full certification pipeline on a compiled skill.

Performs comprehensive certification including risk identification, compliance classification, and runtime Guardian checks.

compile

compile(ctx: Context, spec_path: Annotated[str, Argument(help='Path to the Mellea skill specification or the folder containing the skill specs.')], model: Annotated[Optional[str], Option(--model, -m, help='Claude model for compiling a skill. Default to Sonnet.')] = None, timeout: Annotated[int, Option(--timeout, -t, help='Compile session timeout in seconds. Default to 4500 (75min).')] = 4500, repair_mode: Annotated[bool, Option(-r, --repair - mode, help='Identify and correct any errors effectively in Mellea skill compilation.')] = False, skip_smoke_check: Annotated[bool, Option(--skip - smoke - check, help='Skip the post-compile fixture smoke-check (default OFF).')] = False, refresh_cache: Annotated[bool, Option(--refresh - cache, help='Force refresh of grounding caches (~/.cache/mellea-skills-compiler/) before compile.')] = False, skill_backend: Annotated[Optional[str], Option(--skill - backend, help='Override the LLM backend used by the compiled skill at runtime (default from mellea_skills_compiler/compile/claude/data/runtime_defaults.json).')] = None, skill_model: Annotated[Optional[str], Option(--skill - model, help='Override the model id used by the compiled skill at runtime (default from mellea_skills_compiler/compile/claude/data/runtime_defaults.json).')] = None, backend: Annotated[str, Option(--backend, -b, help="Compilation backend to use ['claude', 'bob', 'pi'].")] = 'claude', provider: Annotated[Optional[str], Option(--provider, help="Provider for the pi compilation backend (e.g. 'anthropic', 'ollama'). Only used with --backend pi; ignored otherwise. Defaults to pi's defaultProvider when not set. Without --model, pi's defaultModel is used, and with it its defaultProvider.")] = None) -> None

Compile Mellea skill specification into a Mellea pipeline using mellea-fy Claude command.

After mellea-fy returns successfully, automatically chains into validate: runs the structural lints (Step 7) and (unless --no-run) executes one fixture against the LLM backend. A green compile means compiled + lints passed + smoke-check passed (or skipped because backend was unreachable).

export

export(ctx: Context, package_path: Annotated[str, Argument(help='Path to the compiled skill directory (must contain melleafy.json).')], target: Annotated[str, Option(--target, -t, help='Deployment target: langgraph | claude-code | mcp | pi')], force: Annotated[bool, Option(--force, -f, help='Overwrite output directory if it already exists.')] = False, enforce: Annotated[bool, Option(--enforce, -e, help='Register Guardian in enforce mode (blocks on risk detection). Default: audit-only.')] = False)

Export a compiled Mellea skill to a deployment target (langgraph, claude-code, mcp, or pi).

Output is written to /- inside the skill directory.

NOTE: This command is experimental. Output structure and CLI interface may change in future releases without a deprecation period.

ingest

ingest(ctx: Context, spec_path: Annotated[str, Argument(help='Mellea Skill spec path', rich_help_panel=Arguments)], dry_run: Annotated[bool, Option(--dry - run, help='Preview without making LLM calls', show_default=True)] = False, risk_model: Annotated[Optional[str], Option(--risk - model, help='Model to use for Risk and Action Identification. The `--inference-engine` option must support the model. If set to None, the default model for the inference engine will be used.')] = None, inference_engine: Annotated[Literal['ollama', 'vllm'], Option(--inference - engine, -i, callback=lambda x: upper(), help='Service to use for LLM inference. Supported: ollama')] = 'ollama') -> None

Run risk analysis on a skill specification.

Analyzes the skill spec to identify risks and generate a policy document without running full certification.

main

main() -> None

Mellea Skills Compiler CLI - Agent specification certification pipeline.

Transform AI agent skill specifications into certified, governed pipelines with comprehensive risk analysis and compliance reporting.

Environment variables

MELLEA_PROFILE=1 Enable profiling for compile/run/certify (captures worker threads; outputs per-thread summary and top 40 functions by total time).

run

run(ctx: Context, pipeline_dir: Annotated[str, Argument(help='Compiled skill pipeline directory.')], fixture_id: Annotated[Optional[str], Option(-f, --fixture, help='Use a pre-canned fixture.')] = None, input: Annotated[Optional[str], Option(--input, -i, help="Input value. Raw string or Use 'file://' to read from file, '-' for stdin.")] = None, enforce: Annotated[bool, Option(--enforce, -e, help='Block execution when Guardian detects risks (default: audit-only).')] = False, no_guardian: Annotated[bool, Option(--no - guardian, -ng, help='Skip Guardian checks even if a policy manifest exists.')] = False, guardian_model: Annotated[Optional[str], Option(--guardian - model, help='Model to use for Risk Assessment. The `--inference-engine` option must support the model. If set to None, the default guardian model for the inference engine will be used.')] = None, inference_engine: Annotated[Literal['ollama', 'vllm'], Option(--inference - engine, callback=lambda x: upper(), help='Service to use for LLM inference. Supported: ollama')] = 'ollama') -> None

Run Mellea Skill Pipeline.

Input sources (mutually exclusive): --input, -i Raw value; 'file://' reads from file, '-' from stdin --fixture Use a pre-canned fixture

validate

validate(ctx: Context, pipeline_dir: Annotated[str, Argument(help='Compiled skill pipeline directory (e.g. skills/<name>/<name>_mellea/).')], no_run: Annotated[bool, Option(--no - run, help='Skip the post-lint fixture smoke-check (default ON).')] = False, all_fixtures: Annotated[bool, Option(--all, help='Run all fixtures (default: first only).')] = False)

Run Step 7 structural lints and (unless --no-run) the fixture smoke-check.

Exit codes

0 — lints passed, smoke-check passed or skipped (backend unreachable) 11 — at least one lint failed 12 — smoke-check failed (lint pass, but a fixture raised an exception)

version

version(ctx: Context)

Print the installed mellea-skills-compiler package version.

compile

Modules:

backend

Backend abstraction layer for mellea-skills compilation.

This module defines the protocol that all compilation backends must implement, enabling support for multiple compilation engines (Claude Code, IBM Bob, local LLMs, etc.) while maintaining a consistent interface.

The abstraction layer consists of: - CompilationBackend: Protocol defining the contract for compilation backends - CompilationContext: Input parameters for compilation - CompilationResult: Output from compilation process - BackendRegistry: Registry for managing available backends

Example usage

from mellea_skills_compiler.compile.backend import get_backend, CompilationContext backend = get_backend("claude") context = CompilationContext( ... spec_path=Path("skill/spec.md"), ... package_dir=Path("output/skill_mellea"), ... intermediate_dir=Path("output/skill_mellea/intermediate"), ... ) result = backend.compile(context) if result.success: ... print(f"Compiled to {result.package_dir}")

Classes:

Attributes:

global_registry module-attribute
global_registry: BackendRegistry = BackendRegistry()
BackendRegistry
BackendRegistry()

Registry for managing available compilation backends.

This class provides a centralized registry for backend implementations, allowing dynamic registration and retrieval of backends by name.

Backends are registered with a string identifier (e.g., "claude", "bob") and can be retrieved by that identifier. The registry ensures that: - Backend names are unique (no duplicate registrations) - Unknown backends raise clear errors - Available backends can be listed for CLI help text

Example

from mellea_skills_compiler.compile.backend import BackendRegistry from mellea_skills_compiler.compile.backends.claude import ClaudeCodeBackend

registry = BackendRegistry() registry.register_backend("claude", ClaudeCodeBackend)

backend = registry.get_backend("claude") print(backend.get_backend_name()) Claude Code

print(registry.list_backends()) ['claude']

Initialize an empty backend registry.

Methods:

get_backend
get_backend(identifier: str) -> CompilationBackend

Retrieve a backend by identifier.

Parameters:

  • identifier (str) –

    Backend identifier (e.g., "claude", "bob")

Returns:

Raises:

  • ValueError –

    If no backend with this identifier is registered

Example

registry = BackendRegistry() registry.register_backend(ClaudeCodeBackend) backend = registry.get_backend("claude") print(backend.name()) Claude Code

list_backends
list_backends() -> List[str]

List all registered backend identifiers.

Returns:

  • List[str] –

    Sorted list of backend identifiers

Example

registry = BackendRegistry() registry.register_backend("claude", ClaudeCodeBackend) registry.register_backend("bob", BobBackend) print(registry.list_backends()) ['bob', 'claude']

register_backend
register_backend(backend_class: Type[CompilationBackend]) -> None

Register a backend implementation.

Parameters:

Raises:

  • ValueError –

    If a backend with this name is already registered

Example

registry = BackendRegistry() registry.register_backend(ClaudeCodeBackend) registry.register_backend(BobBackend)

CompilationBackend

Bases: Protocol

Protocol defining the interface for compilation backends.

All compilation backends (Claude Code, IBM Bob, local LLMs, etc.) must implement this protocol to be compatible with the mellea-skills-compiler framework.

The protocol defines four core methods that backends must provide: 1. identifier() - Return identifier for usage across APIs 2. name() - Return human-readable backend name for logging purpose 3. compile() - Execute the full compilation workflow 4. validate_environment() - Check if backend prerequisites are met 5. supports_repair_mode() - Indicate repair mode capability

Backends are responsible for: - Decomposing skill specifications into Mellea pipeline components - Generating all required artifacts (config.py, schemas.py, tools.py, etc.) - Handling errors and timeouts gracefully - Providing clear error messages for debugging

Example implementation

class MyBackend: ... def compile(self, context: CompilationContext) -> CompilationResult: ... # Implementation here ... return CompilationResult(success=True, package_dir=context.package_dir) ... ... def validate_environment(self) -> tuple[bool, Optional[str]]: ... return True, None ... ... def get_backend_name(self) -> str: ... return "My Custom Backend" ... ... def supports_repair_mode(self) -> bool: ... return False

Methods:

  • compile –

    Execute the full compilation workflow.

  • identifier –

    Return internal identifer for the given compiler

  • name –

    Return human-readable backend name for logging and display.

  • supports_repair_mode –

    Indicate whether this backend supports repair mode.

  • validate_environment –

    Check if backend prerequisites are met.

compile

Execute the full compilation workflow.

This method orchestrates the 10-step compilation process: 1. Parse specification and extract metadata 2. Generate inventory of required components 3. Classify skill type and complexity 4. Map specification elements to Mellea primitives 5. Generate dependency plan 6. Emit configuration (config.py) 7. Emit schemas (schemas.py) 8. Emit tools (tools.py) 9. Emit pipeline (pipeline.py) 10. Emit fixtures for testing

Parameters:

  • context (CompilationContext) –

    Compilation parameters including paths, model, timeout, etc.

Returns:

  • CompilationResult –

    CompilationResult with success status, output paths, and metadata

Raises:

  • RuntimeError –

    If compilation fails due to backend-specific errors

  • TimeoutError –

    If compilation exceeds context.timeout (if timeout > 0)

Example

backend = get_backend("claude") context = CompilationContext( ... spec_path=Path("weather/spec.md"), ... package_dir=Path("weather_mellea"), ... intermediate_dir=Path("weather_mellea/intermediate"), ... ) result = backend.compile(context) if result.success: ... print(f"Success! Package at {result.package_dir}") ... else: ... print(f"Failed: {result.error_message}")

identifier staticmethod
identifier() -> str

Return internal identifer for the given compiler

Returns:

  • str –

    A short compiler identifer e.g. bob, claude

name
name() -> str

Return human-readable backend name for logging and display.

This name is used in: - Log messages ("Using compilation backend: Claude Code") - Error messages ("Backend 'Claude Code' failed: ...") - CLI help text ("Available backends: claude, bob")

Returns:

  • str –

    A short, descriptive name (e.g., "Claude Code", "IBM Bob", "Local Llama")

Example

backend = get_backend("claude") print(backend.get_backend_name()) Claude Code

supports_repair_mode
supports_repair_mode() -> bool

Indicate whether this backend supports repair mode.

Repair mode is a specialized workflow that attempts to fix compilation errors by analyzing failed artifacts and regenerating specific components. Not all backends may support this advanced feature.

Returns:

  • bool –

    True if backend implements repair mode, False otherwise

Example

backend = get_backend("claude") if backend.supports_repair_mode(): ... context.repair_mode = True ... else: ... print("Repair mode not available for this backend")

validate_environment
validate_environment() -> tuple[bool, Optional[str]]

Check if backend prerequisites are met.

This method verifies that the backend can execute successfully by checking: - Required CLI tools are installed and accessible - API credentials are configured (if needed) - Network connectivity (if needed) - Any other backend-specific requirements

This should be called before attempting compilation to provide early, actionable error messages to users.

Returns:

  • bool –

    A tuple of (is_valid, error_message) where:

  • Optional[str] –
    • is_valid: True if all prerequisites are met, False otherwise
  • tuple[bool, Optional[str]] –
    • error_message: None if valid, or a helpful error message explaining what's missing and how to fix it
Example

backend = get_backend("claude") is_valid, error = backend.validate_environment() if not is_valid: ... print(f"Backend not ready: {error}") ... print("Please install Claude Code: https://docs.anthropic.com/...")

CompilationContext dataclass
CompilationContext(spec_path: Path, package_dir: Path, intermediate_dir: Path, model: Optional[str] = None, timeout: int = 0, repair_mode: bool = False, skill_backend: Optional[str] = None, skill_model: Optional[str] = None, defaults_source: Optional[str] = None, refresh_cache: bool = False, provider: Optional[str] = None)

Input context for compilation process.

This dataclass encapsulates all parameters needed to execute a compilation, providing a clean interface between the CLI/API layer and backend implementations.

Attributes:

  • spec_path (Path) –

    Path to the input specification file (spec.md or SKILL.md)

  • package_dir (Path) –

    Directory where the compiled Mellea package will be written

  • intermediate_dir (Path) –

    Directory for intermediate artifacts (JSON, logs, etc.)

  • model (Optional[str]) –

    Optional model identifier for the compilation backend (e.g., "claude-3-7-sonnet-20250219")

  • timeout (int) –

    Maximum time in seconds for compilation (0 = no timeout)

  • repair_mode (bool) –

    If True, use repair workflow instead of full compilation

  • skill_backend (Optional[str]) –

    Runtime backend for the compiled skill (e.g., "claude", "bob")

  • skill_model (Optional[str]) –

    Runtime model for the compiled skill

  • defaults_source (Optional[str]) –

    Source of where the backend values came from (e.g. "command-line", "file")

  • refresh_cache (bool) –

    If True, force refresh of cached artifacts

  • provider (Optional[str]) –

    Optional provider identifier for the compilation backend (pi-only; e.g. "anthropic", "ollama"). Ignored by backends that don't support provider selection.

Example

context = CompilationContext( ... spec_path=Path("weather/spec.md"), ... package_dir=Path("weather_mellea"), ... intermediate_dir=Path("weather_mellea/intermediate"), ... model="claude-3-7-sonnet-20250219", ... timeout=300, ... )

defaults_source class-attribute instance-attribute
defaults_source: Optional[str] = None
intermediate_dir instance-attribute
intermediate_dir: Path
model class-attribute instance-attribute
model: Optional[str] = None
package_dir instance-attribute
package_dir: Path
provider class-attribute instance-attribute
provider: Optional[str] = None
refresh_cache class-attribute instance-attribute
refresh_cache: bool = False
repair_mode class-attribute instance-attribute
repair_mode: bool = False
skill_backend class-attribute instance-attribute
skill_backend: Optional[str] = None
skill_model class-attribute instance-attribute
skill_model: Optional[str] = None
spec_path instance-attribute
spec_path: Path
timeout class-attribute instance-attribute
timeout: int = 0
CompilationResult dataclass
CompilationResult(success: bool, package_dir: Path, error_message: Optional[str] = None, intermediate_artifacts: dict[str, Path] = dict(), metadata: dict[str, Any] = dict())

Result of a compilation process.

This dataclass encapsulates the outcome of a compilation attempt, including success status, output locations, error information, and backend-specific metadata.

Attributes:

Example

result = CompilationResult( ... success=True, ... package_dir=Path("weather_mellea"), ... intermediate_artifacts={ ... "inventory": Path("weather_mellea/intermediate/inventory.json"), ... "classification": Path("weather_mellea/intermediate/classification.json"), ... }, ... metadata={"model": "claude-3-7-sonnet-20250219", "duration_seconds": 45.2}, ... )

error_message class-attribute instance-attribute
error_message: Optional[str] = None
intermediate_artifacts class-attribute instance-attribute
intermediate_artifacts: dict[str, Path] = field(default_factory=dict)
metadata class-attribute instance-attribute
metadata: dict[str, Any] = field(default_factory=dict)
package_dir instance-attribute
package_dir: Path
success instance-attribute
success: bool

backends

Backend implementations for mellea-skills compilation.

This package contains concrete implementations of the CompilationBackend protocol, each wrapping a different compilation engine (Claude Code, IBM Bob, pi, etc.).

Available backends: - claude: Uses Anthropic's Claude Code CLI for compilation - bob: Uses IBM Bob CLI for compilation - pi: Uses the pi coding agent for compilation

Modules:

  • bob –

    Bob backend implementation for mellea-skills compilation.

  • claude –

    Claude Code backend implementation for mellea-skills compilation.

  • pi –

    Pi backend implementation for mellea-skills compilation.

Classes:

  • BOBBackend –

    Bob backend for mellea-skills compilation.

  • ClaudeCodeBackend –

    Claude Code backend for mellea-skills compilation.

  • PiBackend –

    Pi backend for mellea-skills compilation.

BOBBackend

Bob backend for mellea-skills compilation.

This backend implements the CompilationBackend protocol by wrapping the existing Bob subprocess approach. It invokes the Bob CLI with the /mellea-fy or /mellea-fy-repair slash commands to decompose skill specifications into Mellea pipeline components.

The backend handles: - Bob subprocess invocation with appropriate arguments - JSON streaming output parsing to track compilation progress - Timeout handling and graceful termination - Error handling and cleanup of resources

Example

backend = BOBBackend()

Validate environment before use

is_valid, error = backend.validate_environment() if not is_valid: ... raise RuntimeError(f"Bob not available: {error}")

Execute compilation

context = CompilationContext( ... spec_path=Path("weather/spec.md"), ... package_dir=Path("weather_mellea"), ... timeout=300, ... repair_mode=False, ... ) result = backend.compile(context)

Methods:

  • compile –

    Execute the full compilation workflow using Bob.

  • identifier –

    Internal identifer for the given compiler

  • name –

    Return human-readable backend name for logging and display.

  • validate_environment –

    Check if Bob CLI and API credentials are available.

compile

Execute the full compilation workflow using Bob.

This method orchestrates the 10-step compilation process by invoking the Bob CLI with the /mellea-fy or /mellea-fy-repair slash command.

The compilation workflow: 1. Validate the specified model is available via Anthropic API 2. Build the Bob command-line arguments 3. Invoke Bob subprocess with system prompt and settings 4. Parse JSON streaming output to track progress 5. Handle timeout if context.timeout > 0 6. Detect compilation completion or errors 7. Clean up proxy server and subprocess 8. Return CompilationResult with success status and artifacts

Parameters:

  • context (CompilationContext) –

    Compilation parameters including paths, model, timeout, etc.

Returns:

  • CompilationResult –

    CompilationResult with success status, package directory, and metadata.

  • CompilationResult –

    On success, result.success=True and result.package_dir contains the

  • CompilationResult –

    compiled Mellea package. On failure, result.success=False and

  • CompilationResult –

    result.error_message contains a description of what went wrong.

Raises:

  • RuntimeError –

    If Bob is not available or configured incorrectly

  • TimeoutError –

    If compilation exceeds context.timeout (when timeout > 0)

Example

backend = BOBBackend() context = CompilationContext( ... spec_path=Path("weather/spec.md"), ... package_dir=Path("weather_mellea"), ... timeout=300, ... repair_mode=False, ... ) result = backend.compile(context) if result.success: ... print(f"Package created at {result.package_dir}") ... else: ... print(f"Compilation failed: {result.error_message}")

identifier staticmethod
identifier() -> str

Internal identifer for the given compiler

Returns:

  • str ( str ) –

    Return Compiler identifer - "bob"

name
name() -> str

Return human-readable backend name for logging and display.

Returns:

  • str –

    The string "IBM Bob"

Example

backend = BOBBackend() print(f"Using backend: {backend.name()}") Using backend: IBM Bob

validate_environment
validate_environment() -> tuple[bool, Optional[str]]

Check if Bob CLI and API credentials are available.

This method verifies that all prerequisites for using Bob are met: 1. Bob CLI is installed and accessible in PATH 2. Bob SSO authentication or Bob API key (BOB_API_KEY) is is configured.

This should be called before attempting compilation to provide early, actionable error messages to users.

Returns:

  • bool –

    A tuple of (is_valid, error_message) where is_valid is True

  • Optional[str] –

    when Bob is usable and error_message contains a remediation

  • tuple[bool, Optional[str]] –

    hint when validation fails.

Example

backend = BOBBackend() is_valid, error = backend.validate_environment() if not is_valid: ... print(f"Cannot use Bob backend: {error}")

ClaudeCodeBackend

Claude Code backend for mellea-skills compilation.

This backend implements the CompilationBackend protocol by wrapping the existing Claude Code subprocess approach. It invokes the Claude Code CLI with the /mellea-fy or /mellea-fy-repair slash commands to decompose skill specifications into Mellea pipeline components.

The backend handles: - Model validation via Anthropic API - Local proxy server setup to strip context_management from requests - Claude Code subprocess invocation with appropriate arguments - JSON streaming output parsing to track compilation progress - Timeout handling and graceful termination - Error handling and cleanup of resources

Architecture: - Uses a local proxy server to modify API requests before forwarding to Anthropic - Runs Claude Code in project mode (-p) with restricted tools (Read, Write, Edit) - Streams JSON output to track compilation steps and detect completion - Enforces deny rules via settings file to prevent overwriting wrapper-rendered files

Example

backend = ClaudeCodeBackend()

Validate environment before use

is_valid, error = backend.validate_environment() if not is_valid: ... raise RuntimeError(f"Claude Code not available: {error}")

Execute compilation

context = CompilationContext( ... spec_path=Path("weather/spec.md"), ... package_dir=Path("weather_mellea"), ... intermediate_dir=Path("weather_mellea/intermediate"), ... model="claude-3-7-sonnet-20250219", ... ) result = backend.compile(context)

Methods:

  • compile –

    Execute the full compilation workflow using Claude Code.

  • identifier –

    Internal identifer for the given compiler

  • name –

    Return human-readable backend name for logging and display.

  • supports_repair_mode –

    Indicate that Claude Code supports repair mode.

  • validate_environment –

    Check if Claude Code CLI and API credentials are available.

compile

Execute the full compilation workflow using Claude Code.

This method orchestrates the 10-step compilation process by invoking the Claude Code CLI with the /mellea-fy or /mellea-fy-repair slash command.

The compilation workflow: 1. Validate the specified model is available via Anthropic API 2. Start a local proxy server to strip context_management from requests 3. Build the Claude Code command-line arguments 4. Invoke Claude Code subprocess with system prompt and settings 5. Parse JSON streaming output to track progress 6. Handle timeout if context.timeout > 0 7. Detect compilation completion or errors 8. Clean up proxy server and subprocess 9. Return CompilationResult with success status and artifacts

Parameters:

  • context (CompilationContext) –

    Compilation parameters including paths, model, timeout, etc.

Returns:

  • CompilationResult –

    CompilationResult with success status, package directory, and metadata.

  • CompilationResult –

    On success, result.success=True and result.package_dir contains the

  • CompilationResult –

    compiled Mellea package. On failure, result.success=False and

  • CompilationResult –

    result.error_message contains a description of what went wrong.

Raises:

  • RuntimeError –

    If Claude Code is not available or configured incorrectly

  • TimeoutError –

    If compilation exceeds context.timeout (when timeout > 0)

Example

backend = ClaudeCodeBackend() context = CompilationContext( ... spec_path=Path("weather/spec.md"), ... package_dir=Path("weather_mellea"), ... intermediate_dir=Path("weather_mellea/intermediate"), ... model="claude-3-7-sonnet-20250219", ... timeout=300, ... repair_mode=False, ... ) result = backend.compile(context) if result.success: ... print(f"Package created at {result.package_dir}") ... else: ... print(f"Compilation failed: {result.error_message}")

identifier staticmethod
identifier() -> str

Internal identifer for the given compiler

Returns:

  • str ( str ) –

    Return Compiler identifer - "claude"

name
name() -> str

Return human-readable backend name for logging and display.

Returns:

  • str –

    The string "Claude Code"

Example

backend = ClaudeCodeBackend() print(f"Using backend: {backend.name()}") Using backend: Claude Code

supports_repair_mode
supports_repair_mode() -> bool

Indicate that Claude Code supports repair mode.

Claude Code supports repair mode via the /mellea-fy-repair slash command, which attempts to fix compilation errors by analyzing failed artifacts and regenerating specific components.

Returns:

  • bool –

    True (Claude Code supports repair mode)

Example

backend = ClaudeCodeBackend() if backend.supports_repair_mode(): ... print("Repair mode available") ... context.repair_mode = True

validate_environment
validate_environment() -> tuple[bool, Optional[str]]

Check if Claude Code CLI and API credentials are available.

This method verifies that all prerequisites for using Claude Code are met: 1. Claude Code CLI is installed and accessible in PATH 2. Anthropic API credentials are configured (ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN) 3. The API credentials are valid by checking that models can be listed

This should be called before attempting compilation to provide early, actionable error messages to users.

Returns:

  • bool –

    A tuple of (is_valid, error_message) where is_valid is True

  • Optional[str] –

    when Claude Code is usable and error_message contains a remediation

  • tuple[bool, Optional[str]] –

    hint when validation fails.

Example

backend = ClaudeCodeBackend() is_valid, error = backend.validate_environment() if not is_valid: ... print(f"Cannot use Claude Code backend: {error}")

PiBackend

Pi backend for mellea-skills compilation.

This backend implements the CompilationBackend protocol by wrapping the pi CLI in one-shot (-p --mode json) mode. It invokes the /mellea-fy or /mellea-fy-repair prompt template to decompose skill specifications into Mellea pipeline components.

Example

backend = PiBackend() is_valid, error = backend.validate_environment() if not is_valid: ... raise RuntimeError(f"Pi not available: {error}") context = CompilationContext( ... spec_path=Path("weather/spec.md"), ... package_dir=Path("weather_mellea"), ... intermediate_dir=Path("weather_mellea/intermediate"), ... timeout=300, ... repair_mode=False, ... ) result = backend.compile(context)

Methods:

  • compile –

    Execute the full compilation workflow using pi.

  • identifier –

    Return internal identifier for the given compiler.

  • name –

    Return human-readable backend name for logging and display.

  • supports_repair_mode –

    Indicate whether this backend supports repair mode.

  • validate_environment –

    Check if pi CLI and credentials are available.

compile

Execute the full compilation workflow using pi.

If context.repair_mode is True but no prior compilation exists (intermediate/classification.json is absent), this falls back to a fresh /mellea-fy run instead of /mellea-fy-repair — pi's own agentic judgment sometimes pauses to ask for confirmation when the repair template's Step-0 routing entry names /mellea-fy-classify as the resume sub-command in one-shot mode, rather than proceeding automatically the way the template instructs. Requesting /mellea-fy directly for this case sidesteps that pause; ClaudeCodeBackend follows the same template correctly and needs no such workaround.

Parameters:

  • context (CompilationContext) –

    Compilation parameters including paths, model, timeout, etc.

Returns:

identifier staticmethod
identifier() -> str

Return internal identifier for the given compiler.

Returns:

  • str ( str ) –

    "pi"

name
name() -> str

Return human-readable backend name for logging and display.

Returns:

  • str –

    The string "Pi"

supports_repair_mode
supports_repair_mode() -> bool

Indicate whether this backend supports repair mode.

Returns:

  • bool –

    True, since PiBackend supports the /mellea-fy-repair workflow.

validate_environment
validate_environment(provider: Optional[str] = None) -> tuple[bool, Optional[str]]

Check if pi CLI and credentials are available.

Parameters:

  • provider (Optional[str], default: None ) –

    Provider to check credentials for (e.g. "anthropic", "ollama"). Defaults to "anthropic" when not supplied, matching the other two backends' effective default — this is intentionally NOT pi's own CLI-level default of "google".

Returns:

bob

Bob backend implementation for mellea-skills compilation.

This module implements the CompilationBackend protocol using IBM Bob CLI as the compilation engine. It wraps the existing subprocess-based approach that invokes the /mellea-fy and /mellea-fy-repair slash commands.

The BOBBackend is responsible for: - Validating that Bob CLI is installed and configured - Invoking Bob with appropriate arguments and system prompts - Handling timeouts and errors gracefully - Cleaning up resources (subprocesses) on completion or failure

This backend requires: - Bob shell installed and accessible in PATH - Valid IBM Bob API key - BOB_API_KEY

Classes:

  • BOBBackend –

    Bob backend for mellea-skills compilation.

Functions:

Attributes:

LOGGER module-attribute
LOGGER = configure_logger()
console module-attribute
console = Console(log_time=True)
BOBBackend

Bob backend for mellea-skills compilation.

This backend implements the CompilationBackend protocol by wrapping the existing Bob subprocess approach. It invokes the Bob CLI with the /mellea-fy or /mellea-fy-repair slash commands to decompose skill specifications into Mellea pipeline components.

The backend handles: - Bob subprocess invocation with appropriate arguments - JSON streaming output parsing to track compilation progress - Timeout handling and graceful termination - Error handling and cleanup of resources

Example

backend = BOBBackend()

Validate environment before use

is_valid, error = backend.validate_environment() if not is_valid: ... raise RuntimeError(f"Bob not available: {error}")

Execute compilation

context = CompilationContext( ... spec_path=Path("weather/spec.md"), ... package_dir=Path("weather_mellea"), ... timeout=300, ... repair_mode=False, ... ) result = backend.compile(context)

Methods:

  • compile –

    Execute the full compilation workflow using Bob.

  • identifier –

    Internal identifer for the given compiler

  • name –

    Return human-readable backend name for logging and display.

  • validate_environment –

    Check if Bob CLI and API credentials are available.

compile

Execute the full compilation workflow using Bob.

This method orchestrates the 10-step compilation process by invoking the Bob CLI with the /mellea-fy or /mellea-fy-repair slash command.

The compilation workflow: 1. Validate the specified model is available via Anthropic API 2. Build the Bob command-line arguments 3. Invoke Bob subprocess with system prompt and settings 4. Parse JSON streaming output to track progress 5. Handle timeout if context.timeout > 0 6. Detect compilation completion or errors 7. Clean up proxy server and subprocess 8. Return CompilationResult with success status and artifacts

Parameters:

  • context (CompilationContext) –

    Compilation parameters including paths, model, timeout, etc.

Returns:

  • CompilationResult –

    CompilationResult with success status, package directory, and metadata.

  • CompilationResult –

    On success, result.success=True and result.package_dir contains the

  • CompilationResult –

    compiled Mellea package. On failure, result.success=False and

  • CompilationResult –

    result.error_message contains a description of what went wrong.

Raises:

  • RuntimeError –

    If Bob is not available or configured incorrectly

  • TimeoutError –

    If compilation exceeds context.timeout (when timeout > 0)

Example

backend = BOBBackend() context = CompilationContext( ... spec_path=Path("weather/spec.md"), ... package_dir=Path("weather_mellea"), ... timeout=300, ... repair_mode=False, ... ) result = backend.compile(context) if result.success: ... print(f"Package created at {result.package_dir}") ... else: ... print(f"Compilation failed: {result.error_message}")

identifier staticmethod
identifier() -> str

Internal identifer for the given compiler

Returns:

  • str ( str ) –

    Return Compiler identifer - "bob"

name
name() -> str

Return human-readable backend name for logging and display.

Returns:

  • str –

    The string "IBM Bob"

Example

backend = BOBBackend() print(f"Using backend: {backend.name()}") Using backend: IBM Bob

validate_environment
validate_environment() -> tuple[bool, Optional[str]]

Check if Bob CLI and API credentials are available.

This method verifies that all prerequisites for using Bob are met: 1. Bob CLI is installed and accessible in PATH 2. Bob SSO authentication or Bob API key (BOB_API_KEY) is is configured.

This should be called before attempting compilation to provide early, actionable error messages to users.

Returns:

  • bool –

    A tuple of (is_valid, error_message) where is_valid is True

  • Optional[str] –

    when Bob is usable and error_message contains a remediation

  • tuple[bool, Optional[str]] –

    hint when validation fails.

Example

backend = BOBBackend() is_valid, error = backend.validate_environment() if not is_valid: ... print(f"Cannot use Bob backend: {error}")

authenticate_bob
authenticate_bob(prompt: str = '2+3=') -> Tuple[bool, str]

Test the bob run command and report success/failure.

claude

Claude Code backend implementation for mellea-skills compilation.

This module implements the CompilationBackend protocol using Anthropic's Claude Code CLI as the compilation engine. It wraps the existing subprocess-based approach that invokes the /mellea-fy and /mellea-fy-repair slash commands.

The ClaudeCodeBackend is responsible for: - Validating that Claude Code CLI is installed and configured - Setting up a local proxy to strip context_management from API requests - Invoking Claude Code with appropriate arguments and system prompts - Parsing the JSON streaming output to track compilation progress - Handling timeouts and errors gracefully - Cleaning up resources (proxy server, subprocesses) on completion or failure

This backend requires: - Claude Code CLI installed and accessible in PATH - Valid Anthropic API credentials (ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN) - Network access to Anthropic API (or configured ANTHROPIC_BASE_URL)

Example usage

from mellea_skills_compiler.compile.backends.claude import ClaudeCodeBackend from mellea_skills_compiler.compile.backend import CompilationContext

backend = ClaudeCodeBackend() is_valid, error = backend.validate_environment() if not is_valid: ... print(f"Cannot use Claude Code: {error}") ... exit(1)

context = CompilationContext( ... spec_path=Path("weather/spec.md"), ... package_dir=Path("weather_mellea"), ... intermediate_dir=Path("weather_mellea/intermediate"), ... model="claude-3-7-sonnet-20250219", ... timeout=300, ... )

result = backend.compile(context) if result.success: ... print(f"Compiled successfully to {result.package_dir}") ... else: ... print(f"Compilation failed: {result.error_message}")

Classes:

Attributes:

LOGGER module-attribute
LOGGER = logging.getLogger(__name__)
console module-attribute
console = Console(log_time=True)
ClaudeCodeBackend

Claude Code backend for mellea-skills compilation.

This backend implements the CompilationBackend protocol by wrapping the existing Claude Code subprocess approach. It invokes the Claude Code CLI with the /mellea-fy or /mellea-fy-repair slash commands to decompose skill specifications into Mellea pipeline components.

The backend handles: - Model validation via Anthropic API - Local proxy server setup to strip context_management from requests - Claude Code subprocess invocation with appropriate arguments - JSON streaming output parsing to track compilation progress - Timeout handling and graceful termination - Error handling and cleanup of resources

Architecture: - Uses a local proxy server to modify API requests before forwarding to Anthropic - Runs Claude Code in project mode (-p) with restricted tools (Read, Write, Edit) - Streams JSON output to track compilation steps and detect completion - Enforces deny rules via settings file to prevent overwriting wrapper-rendered files

Example

backend = ClaudeCodeBackend()

Validate environment before use

is_valid, error = backend.validate_environment() if not is_valid: ... raise RuntimeError(f"Claude Code not available: {error}")

Execute compilation

context = CompilationContext( ... spec_path=Path("weather/spec.md"), ... package_dir=Path("weather_mellea"), ... intermediate_dir=Path("weather_mellea/intermediate"), ... model="claude-3-7-sonnet-20250219", ... ) result = backend.compile(context)

Methods:

  • compile –

    Execute the full compilation workflow using Claude Code.

  • identifier –

    Internal identifer for the given compiler

  • name –

    Return human-readable backend name for logging and display.

  • supports_repair_mode –

    Indicate that Claude Code supports repair mode.

  • validate_environment –

    Check if Claude Code CLI and API credentials are available.

compile

Execute the full compilation workflow using Claude Code.

This method orchestrates the 10-step compilation process by invoking the Claude Code CLI with the /mellea-fy or /mellea-fy-repair slash command.

The compilation workflow: 1. Validate the specified model is available via Anthropic API 2. Start a local proxy server to strip context_management from requests 3. Build the Claude Code command-line arguments 4. Invoke Claude Code subprocess with system prompt and settings 5. Parse JSON streaming output to track progress 6. Handle timeout if context.timeout > 0 7. Detect compilation completion or errors 8. Clean up proxy server and subprocess 9. Return CompilationResult with success status and artifacts

Parameters:

  • context (CompilationContext) –

    Compilation parameters including paths, model, timeout, etc.

Returns:

  • CompilationResult –

    CompilationResult with success status, package directory, and metadata.

  • CompilationResult –

    On success, result.success=True and result.package_dir contains the

  • CompilationResult –

    compiled Mellea package. On failure, result.success=False and

  • CompilationResult –

    result.error_message contains a description of what went wrong.

Raises:

  • RuntimeError –

    If Claude Code is not available or configured incorrectly

  • TimeoutError –

    If compilation exceeds context.timeout (when timeout > 0)

Example

backend = ClaudeCodeBackend() context = CompilationContext( ... spec_path=Path("weather/spec.md"), ... package_dir=Path("weather_mellea"), ... intermediate_dir=Path("weather_mellea/intermediate"), ... model="claude-3-7-sonnet-20250219", ... timeout=300, ... repair_mode=False, ... ) result = backend.compile(context) if result.success: ... print(f"Package created at {result.package_dir}") ... else: ... print(f"Compilation failed: {result.error_message}")

identifier staticmethod
identifier() -> str

Internal identifer for the given compiler

Returns:

  • str ( str ) –

    Return Compiler identifer - "claude"

name
name() -> str

Return human-readable backend name for logging and display.

Returns:

  • str –

    The string "Claude Code"

Example

backend = ClaudeCodeBackend() print(f"Using backend: {backend.name()}") Using backend: Claude Code

supports_repair_mode
supports_repair_mode() -> bool

Indicate that Claude Code supports repair mode.

Claude Code supports repair mode via the /mellea-fy-repair slash command, which attempts to fix compilation errors by analyzing failed artifacts and regenerating specific components.

Returns:

  • bool –

    True (Claude Code supports repair mode)

Example

backend = ClaudeCodeBackend() if backend.supports_repair_mode(): ... print("Repair mode available") ... context.repair_mode = True

validate_environment
validate_environment() -> tuple[bool, Optional[str]]

Check if Claude Code CLI and API credentials are available.

This method verifies that all prerequisites for using Claude Code are met: 1. Claude Code CLI is installed and accessible in PATH 2. Anthropic API credentials are configured (ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN) 3. The API credentials are valid by checking that models can be listed

This should be called before attempting compilation to provide early, actionable error messages to users.

Returns:

  • bool –

    A tuple of (is_valid, error_message) where is_valid is True

  • Optional[str] –

    when Claude Code is usable and error_message contains a remediation

  • tuple[bool, Optional[str]] –

    hint when validation fails.

Example

backend = ClaudeCodeBackend() is_valid, error = backend.validate_environment() if not is_valid: ... print(f"Cannot use Claude Code backend: {error}")

pi

Pi backend implementation for mellea-skills compilation.

This module implements the CompilationBackend protocol using the pi coding agent (@earendil-works/pi-coding-agent) as the compilation engine. It wraps a subprocess-based approach that invokes the /mellea-fy and /mellea-fy-repair prompt templates.

The PiBackend is responsible for: - Validating that the pi CLI is installed and credentials resolve - Invoking pi with appropriate arguments - Parsing the --mode json event stream to track compilation progress - Handling timeouts and errors gracefully - Cleaning up resources (subprocess) on completion or failure

This backend requires: - pi CLI installed and accessible in PATH - Provider credentials configured for pi (checked via pi auth check)

Classes:

  • PiBackend –

    Pi backend for mellea-skills compilation.

Attributes:

LOGGER module-attribute
LOGGER = configure_logger()
console module-attribute
console = Console(log_time=True)
PiBackend

Pi backend for mellea-skills compilation.

This backend implements the CompilationBackend protocol by wrapping the pi CLI in one-shot (-p --mode json) mode. It invokes the /mellea-fy or /mellea-fy-repair prompt template to decompose skill specifications into Mellea pipeline components.

Example

backend = PiBackend() is_valid, error = backend.validate_environment() if not is_valid: ... raise RuntimeError(f"Pi not available: {error}") context = CompilationContext( ... spec_path=Path("weather/spec.md"), ... package_dir=Path("weather_mellea"), ... intermediate_dir=Path("weather_mellea/intermediate"), ... timeout=300, ... repair_mode=False, ... ) result = backend.compile(context)

Methods:

  • compile –

    Execute the full compilation workflow using pi.

  • identifier –

    Return internal identifier for the given compiler.

  • name –

    Return human-readable backend name for logging and display.

  • supports_repair_mode –

    Indicate whether this backend supports repair mode.

  • validate_environment –

    Check if pi CLI and credentials are available.

compile

Execute the full compilation workflow using pi.

If context.repair_mode is True but no prior compilation exists (intermediate/classification.json is absent), this falls back to a fresh /mellea-fy run instead of /mellea-fy-repair — pi's own agentic judgment sometimes pauses to ask for confirmation when the repair template's Step-0 routing entry names /mellea-fy-classify as the resume sub-command in one-shot mode, rather than proceeding automatically the way the template instructs. Requesting /mellea-fy directly for this case sidesteps that pause; ClaudeCodeBackend follows the same template correctly and needs no such workaround.

Parameters:

  • context (CompilationContext) –

    Compilation parameters including paths, model, timeout, etc.

Returns:

identifier staticmethod
identifier() -> str

Return internal identifier for the given compiler.

Returns:

  • str ( str ) –

    "pi"

name
name() -> str

Return human-readable backend name for logging and display.

Returns:

  • str –

    The string "Pi"

supports_repair_mode
supports_repair_mode() -> bool

Indicate whether this backend supports repair mode.

Returns:

  • bool –

    True, since PiBackend supports the /mellea-fy-repair workflow.

validate_environment
validate_environment(provider: Optional[str] = None) -> tuple[bool, Optional[str]]

Check if pi CLI and credentials are available.

Parameters:

  • provider (Optional[str], default: None ) –

    Provider to check credentials for (e.g. "anthropic", "ollama"). Defaults to "anthropic" when not supplied, matching the other two backends' effective default — this is intentionally NOT pi's own CLI-level default of "google".

Returns:

claude_directives

Functions:

Attributes:

LOGGER module-attribute
LOGGER = configure_logger()
build_pi_system_prompt
build_pi_system_prompt(backend: str, model_id: str, source: str, mellea_package_dir: Path, prompts_dir: Path, schemas_dir: Path) -> str

Same directive as build_system_prompt, worded for pi.

Pi has no deny-rule equivalent to Claude Code's --settings, so PiBackend makes the wrapper-rendered paths read-only placeholders for the run instead; this tells pi a write there fails with a permission error.

Pi expands only the invoked template, not the sub-commands it names, so this tells pi to Read each sub-command's template file (under prompts_dir) before that step.

build_system_prompt
build_system_prompt(backend: str, model_id: str, source: str, mellea_package_dir: Path) -> str

Assemble the instruction string passed to the mellea-fy slash command.

Combines the existing autonomous-run directive with the resolved backend and model_id values, plus a notice listing the paths the wrapper renders authoritatively from JSON (the LLM cannot Write/Edit them — denied via --settings). This tells the LLM to emit the IR JSON instead of trying to write the rendered source itself, so the first attempt is correct rather than denied-then-retried.

mellea_package_dir is the wrapper-derived Rule OUT-2 path (e.g. weather_mellea) substituted into the prompt body so the LLM uses the same path the wrapper computes for mirror_dir_contents_to_target and the post-session *_mellea discovery.

resolve_runtime_defaults
resolve_runtime_defaults(skill_backend_override: Optional[str], skill_model_override: Optional[str]) -> tuple[str, str, str]

Pick the backend and model_id to bake into the compiled skill.

Precedence: CLI overrides win, then the defaults file, then a built-in fallback if the file is missing or unreadable. Returns (backend, model_id, source) where source records where the values came from for the compile log.

write_compile_settings
write_compile_settings(intermediate_dir: Path, package_dir: Path) -> Path

Write a per-invocation Claude Code --settings file with the deny rules.

Path-scoped Write/Edit denies prevent the LLM from clobbering files the wrapper will render after the slash command exits. acceptEdits permission mode does NOT override deny — Anthropic's evaluation order is deny → mode → allow (verified end-to-end in the synthetic deny-rule test).

Important: the deny rule paths must match what the LLM actually tries to write. Claude Code interprets relative paths against the subprocess cwd (the user's shell cwd, typically the repo root). So the deny path must be the full path-from-cwd to the package, not just the bare package name. Earlier versions used package_name/<rel>, which mis-scoped the deny to <cwd>/<package_name>/<rel> and confused the LLM into creating the package at the wrong location.

write_runtime_directive
write_runtime_directive(intermediate_dir: Path, backend: str, model_id: str, source: str) -> Path

Save the chosen backend and model_id alongside the package.

The post-compile lint reads this file to confirm the generated config.py actually used these values (and didn't drift from what we instructed).

compiler

Functions:

  • compile –

    Compile an agent specification into a Mellea skill package.

  • validate –

    Shared implementation for the validate command and the compile auto-chain.

Attributes:

IGNORE_COMPANION_DIRS_ITEMS module-attribute
IGNORE_COMPANION_DIRS_ITEMS = ['audit', 'pyproject.toml']
LOGGER module-attribute
LOGGER = configure_logger()
console module-attribute
console = Console(log_time=True)
compile
compile(spec_path: Path, model: Optional[str] = None, timeout: int = 4500, repair_mode: bool = False, skip_smoke_check: bool = False, refresh_cache: bool = False, skill_backend: Optional[str] = None, skill_model: Optional[str] = None, backend: str = 'claude', provider: Optional[str] = None) -> None

Compile an agent specification into a Mellea skill package.

Validates the backend environment, mirrors companion directories into the package, pre-populates grounding artefacts (API ref and doc index), and delegates the actual LLM-driven compilation to the chosen backend. On success, writers are rendered and the package is validated.

Parameters:

  • spec_path (Path) –

    Path to the skill specification — either a spec.md / SKILL.md file or a skill directory that contains one.

  • model (Optional[str], default: None ) –

    Model identifier passed to the compilation backend (i.e. the model that writes the code), e.g. "claude-opus-4-5". When None the backend's own default is used. Defaults to None.

  • timeout (int, default: 4500 ) –

    Maximum wall-clock seconds allowed for the backend compilation step. Defaults to 4500.

  • repair_mode (bool, default: False ) –

    When True the backend runs a repair workflow that inspects a partial or failed previous run and resumes from where it left off, rather than starting a fresh compilation. Defaults to False.

  • skip_smoke_check (bool, default: False ) –

    When True the post-compile validation step skips executing the skill's test fixtures, performing only static checks. Defaults to False.

  • refresh_cache (bool, default: False ) –

    When True forces regeneration of cached grounding artefacts (mellea_api_ref.json and mellea_doc_index.json) even if up-to-date copies already exist. Defaults to False.

  • skill_backend (Optional[str], default: None ) –

    Runtime inference backend that the compiled skill will use when executed by end-users. Overrides the project-level runtime_defaults.json when supplied. Defaults to None.

  • skill_model (Optional[str], default: None ) –

    Runtime model identifier that the compiled skill will use when executed, e.g. "granite4.1:3b". Overrides the project-level runtime_defaults.json when supplied. Defaults to None.

  • backend (str, default: 'claude' ) –

    Compilation backend identifier used to look up the backend implementation from the global registry (e.g. "claude", "bob"). Defaults to "claude".

  • provider (Optional[str], default: None ) –

    Provider identifier passed to the compilation backend when it supports provider selection (pi-only currently, e.g. "anthropic", "ollama"). Ignored by backends that don't support it. Defaults to None.

Raises:

  • RuntimeError –

    If the requested backend is unavailable or if compilation or post-compile validation fails.

  • ValueError –

    If spec_path has an extension other than .md.

  • FileNotFoundError –

    If spec_path does not exist on disk.

validate
validate(package_dir: Path, *, no_run: bool, all_fixtures: bool) -> None

Shared implementation for the validate command and the compile auto-chain.

grounding

Deterministic grounding artifact generation for the mellea-fy pipeline.

This module produces mellea_api_ref.json and mellea_doc_index.json in the compile pipeline's intermediate directory before the slash command runs. The slash command itself runs with --allowed-tools Read,Write,Edit and so cannot introspect the installed mellea package or fetch https://docs.mellea.ai/. Doing it here means Steps 2.5e and 2.5f of the slash command have real grounding data to consume rather than silently degrading to static fallbacks.

Both functions are idempotent and cache results under ~/.cache/mellea-skills-compiler/. The api_ref cache is keyed by the installed mellea version; the doc_index cache uses a configurable TTL (default 24h) with a stale-cache fallback if the network is unreachable.

Functions:

Attributes:

CACHE_DIR module-attribute
CACHE_DIR = Path.home() / '.cache' / 'mellea-skills-compiler'
CORE_MODULES module-attribute
CORE_MODULES = {'mellea.stdlib.requirements', 'mellea.stdlib.sampling', 'mellea.backends.model_options', 'mellea.stdlib.tools.shell', 'mellea.stdlib.sampling.presets', 'mellea.stdlib.requirements.python_reqs', 'mellea.stdlib.requirements.plotting', 'mellea.stdlib.requirements.rag', 'mellea.stdlib.context.compactor'}
LOGGER module-attribute
LOGGER = configure_logger()
write_mellea_api_ref
write_mellea_api_ref(intermediate_dir: Path, refresh: bool = False) -> Path

Write mellea_api_ref.json to intermediate_dir.

Cached by installed mellea version under ~/.cache/mellea-skills-compiler/api_ref_<version>.json. If mellea is not installed, writes the grounding_unavailable: true shape and returns.

write_mellea_doc_index
write_mellea_doc_index(intermediate_dir: Path, refresh: bool = False, ttl_hours: int = 24) -> Path

Write mellea_doc_index.json to intermediate_dir.

Cached at ~/.cache/mellea-skills-compiler/doc_index.json with a ttl_hours TTL (default 24h). On fetch failure, reuses a stale cache if one exists; otherwise writes the static 2026-04-28 fallback list.

lints

Step 7 structural lints — Python implementations.

AST-precise structural checks where LLM application has proven unreliable and the drift modes have caused post-compile breakage in shipped skills. The remaining lints documented in .claude/commands/mellea-fy-validate.md are still applied by the LLM during Step 7 of the slash command.

Classes:

Functions:

Attributes:

LintFailure dataclass
LintFailure(file: str, line: Optional[int], column: Optional[int], message: str, rule_ref: Optional[str] = None)

Attributes:

column instance-attribute
column: Optional[int]
file instance-attribute
file: str
line instance-attribute
line: Optional[int]
message instance-attribute
message: str
rule_ref class-attribute instance-attribute
rule_ref: Optional[str] = None
LintResult dataclass
LintResult(lint_id: str, verdict: str, files_checked: int = 0, skipped_reason: Optional[str] = None, failures: List[LintFailure] = list())

Attributes:

failures class-attribute instance-attribute
failures: List[LintFailure] = field(default_factory=list)
files_checked class-attribute instance-attribute
files_checked: int = 0
lint_id instance-attribute
lint_id: str
skipped_reason class-attribute instance-attribute
skipped_reason: Optional[str] = None
verdict instance-attribute
verdict: str
LintRunResult dataclass
LintRunResult(overall_verdict: str, lints: List[LintResult], package_path: str, checked_at: str)

Attributes:

checked_at instance-attribute
checked_at: str
failed property
failed: bool
lints instance-attribute
lints: List[LintResult]
overall_verdict instance-attribute
overall_verdict: str
package_path instance-attribute
package_path: str
lint_bundled_asset_path_resolution
lint_bundled_asset_path_resolution(package_dir: Path) -> LintResult

Reject any path-join construction that resolves a bundled-asset path via anything other than Path(__file__).parent.

lint_fixture_data_files_exist
lint_fixture_data_files_exist(package_dir: Path) -> LintResult

A fixture must not reference a relative data file absent from the package.

File-input skills pass paths as fixture inputs (e.g. examples/x.json). If the referenced file is not bundled in the package, the fixture cannot run — the smoke-check raises an opaque FileNotFoundError and an installed skill would too. Fail fast here, naming the fixture, input key, and missing path, instead of surfacing it only at runtime. Reads intermediate/fixtures_emission.json (the fixture inputs the package was rendered from). General to any file-input skill; absolute paths and non-path-like strings are ignored.

lint_fixture_pydantic_coercion
lint_fixture_pydantic_coercion(package_dir: Path) -> LintResult

Fixture inputs must not pass bare dicts where run_pipeline expects Pydantic models.

lint_fixtures_loader_contract
lint_fixtures_loader_contract(package_dir: Path) -> LintResult

<package>/fixtures/__init__.py must export ALL_FIXTURES or FIXTURES.

lint_format_annotation
lint_format_annotation(package_dir: Path) -> LintResult

m.instruct(...) calls whose result is parsed must include format=.

Detection
  1. AST-parse pipeline.py / slots.py / constrained_slots.py.
  2. For every Call that is m.instruct(...) assigned to a Name target (thunk = m.instruct(...)), record whether it has format= and which variable holds the result.
  3. Walk for subsequent uses of that variable as:
    • argument to <Model>.model_validate_json(<thunk>.value)
    • first positional arg to _parse_instruct_result(<thunk>, ...)
    • first positional arg to _safe_parse_with_fallback(<thunk>, ...)
  4. If any such parse-use is found AND the original instruct call had no format= kwarg → hard failure on the m.instruct call line.
lint_grounding_context_types
lint_grounding_context_types(package_dir: Path) -> LintResult

Every grounding_context= dict-literal value should be a string.

Verdict
  • fail if any definite-collection violation
  • warning if only ambiguous findings
  • pass otherwise
lint_import_side_effects
lint_import_side_effects(package_dir: Path) -> LintResult

No module-level Calls outside the documented allowlist.

Bare ast.Expr whose value is a Call (e.g. load_dotenv() at the top of a file) executes at import time; flagged. Module-level assignments where the RHS is a Call are flagged only when the callee is known to be side-effecting (network/env mutation) — allowing safe patterns like LOGGER = logging.getLogger(__name__).

lint_import_soundness
lint_import_soundness(package_dir: Path) -> LintResult

Every mellea.* import path must exist in mellea_api_ref.json:.modules.

lint_instruct_result_parse_before_access
lint_instruct_result_parse_before_access(package_dir: Path) -> LintResult

KB1: m.instruct(format=Model) returns a thunk, not a Pydantic model.

The thunk MUST be parsed before any field access. Exempt patterns: - _parse_instruct_result(thunk, M) - _safe_parse_with_fallback(thunk, M, **defaults) - M.model_validate_json(thunk.value)

lint_parseable
lint_parseable(package_dir: Path) -> LintResult

Every .py file under the package must parse, and <pkg>.pipeline must import.

Two checks, executed in order:

  1. Per-file parseability: ast.parse(p.read_text()) for every .py file directly under <package_dir>/ and <package_dir>/fixtures/.
  2. Package importability: python -c "import <package_name>.pipeline" executed as a clean subprocess from <package_dir>.parent. This surfaces wrong external import paths (e.g. mellea.stdlib.strategies instead of mellea.stdlib.sampling) that ast.parse() cannot detect.

Why a subprocess: importing the package directly in the lint process would pollute namespace, risk hanging on import side effects, or get masked by cached sys.modules entries. A clean child process surfaces exactly the error a downstream consumer (pip install + python -c) would see.

Missing pipeline.py: returns one ERROR failure naming the absent entry module. Tier 1 should hard-fail loudly so the slash-command gate halts before Tier ⅔ lints run on a package with no entry.

Scope: files directly under <package_dir>/ and <package_dir>/fixtures/ only.

lint_prefix_persona
lint_prefix_persona(package_dir: Path) -> LintResult

m.instruct(prefix=<config_constant>) is misuse (KB7).

prefix= is for structured-output continuation; not for persona / system-prompt injection.

lint_raw_llm_json_parse
lint_raw_llm_json_parse(package_dir: Path) -> LintResult

Require raw m.instruct/simple_validate text to use the JSON response helper.

lint_runtime_defaults_bound
lint_runtime_defaults_bound(package_dir: Path) -> LintResult

The compiled config.py must use the backend and model_id we instructed.

Compares the BACKEND and MODEL_ID constants in /config.py against the values recorded at /intermediate/runtime_directive.json (which captures what the compile pipeline injected via the system prompt). If the LLM ignored the directive and emitted different values, this fails loudly.

Skipped when the directive file is absent — usually because the package was compiled with an older pipeline that did not write the directive.

lint_session_boundary
lint_session_boundary(package_dir: Path) -> LintResult

Each start_session(...) block must use at most one distinct format type.

lint_session_method_arity
lint_session_method_arity(package_dir: Path) -> LintResult

MelleaSession method calls must supply required positional arguments.

lint_stdlib_arg_types
lint_stdlib_arg_types(package_dir: Path) -> LintResult

Flag clearly-non-dict arguments passed to Mellea API grounding_context= kwargs.

Narrow MVP scope: only checks grounding_context= on session-method calls in the instruct/chat/act family.

lint_validation_fn_not_called_directly
lint_validation_fn_not_called_directly(package_dir: Path) -> LintResult

Reject any direct call to <req>.validation_fn(...) in generated code.

run_lints
run_lints(package_dir: Path) -> LintRunResult

Run all implemented Step 7 structural lints; write step_7_report.json.

metadata

Classes:

  • CompileMetadata –

    Top-level record written to compile_metadata.json after a successful compile.

Attributes:

LOGGER module-attribute
LOGGER = configure_logger()
CompileMetadata
CompileMetadata(mellea_package_dir: Path)

Top-level record written to compile_metadata.json after a successful compile.

This is a singleton that must be initialized via init() before any write methods are called. The singleton is reset on each init() call to support multiple compile runs in the same process.

Usage

CompileMetadata.init(mellea_package_dir) CompileMetadata.record_args(...) CompileMetadata.record_backend(...) CompileMetadata.record_melleafy() CompileMetadata.record_completion()

Methods:

init classmethod
init(mellea_package_dir: Path) -> None

Initialize (or reset) the singleton for a new compile run.

record_args classmethod
record_args(**compile_args) -> None
record_backend classmethod
record_backend(backend: Literal['claude', 'bob'], backend_model: Optional[str] = None, provider: Optional[str] = None) -> None
record_completion classmethod
record_completion() -> None
record_melleafy classmethod
record_melleafy(mellea_dir) -> None

models

Classes:

RenderResult dataclass
RenderResult(name: str, status: str, detail: Optional[str] = None, diff_lines_added: int = 0, diff_lines_removed: int = 0)

Attributes:

detail class-attribute instance-attribute
detail: Optional[str] = None
diff_lines_added class-attribute instance-attribute
diff_lines_added: int = 0
diff_lines_removed class-attribute instance-attribute
diff_lines_removed: int = 0
name instance-attribute
name: str
status instance-attribute
status: str
WriterSpec dataclass
WriterSpec(name: str, emission_relpath: str, output_relpath: str, writer: ModuleType, output_kind: str = 'file')

One renderable artifact: emission JSON in → Python source on disk out.

output_kind controls how the writer is invoked: - "file" (default): writer module exposes render(emission) -> str and the renderer writes the returned text to output_relpath. - "directory": writer module exposes write(emission, dir_path) -> list[Path] and the renderer wipes output_relpath (preserving the dir itself) before invoking, so the writer is the sole producer of the dir's contents.

Attributes:

emission_relpath instance-attribute
emission_relpath: str
name instance-attribute
name: str
output_kind class-attribute instance-attribute
output_kind: str = 'file'
output_relpath instance-attribute
output_relpath: str
writer instance-attribute
writer: ModuleType

proxy

Classes:

ContextMgmtStrippingProxy

Bases: BaseHTTPRequestHandler

Local proxy that strips context_management from Anthropic API requests.

The IBM LiteLLM proxy rejects context_management as an unknown parameter. Claude Code sends it automatically. This proxy intercepts requests from the claude subprocess, strips the field, and forwards to the real upstream.

Methods:

do_GET
do_GET()
do_POST
do_POST()
handle_error
handle_error(request, client_address)
log_message
log_message(fmt, *args)

smoke_check

Post-lint fixture smoke-check (Step 7's --run mode).

Executes one fixture (or all, if all_fixtures=True) from the compiled package and classifies the outcome into one of three verdicts:

  • passed — fixture executed without exception.
  • failed — fixture raised an exception other than backend-unreachable. Exit code 12 (distinct from lint failure exit code 11).
  • skipped — LLM backend unreachable (Ollama not running, timeout, auth error). Exit code 0 with a stderr warning so CI without an LLM stays green while still nudging local users.

Writes intermediate/step_7b_report.json. Does NOT trigger the repair loop — fixture failures require human review per mellea-fy-validate.md.

Classes:

Functions:

  • run_smoke_check –

    Execute one (or all) fixtures and write step_7b_report.json.

Attributes:

LOGGER module-attribute
LOGGER = configure_logger()
SmokeFixtureResult dataclass
SmokeFixtureResult(fixture_id: str, verdict: str, duration_seconds: float, skipped_reason: Optional[str] = None, failure_message: Optional[str] = None, failure_traceback: Optional[str] = None)

Attributes:

duration_seconds instance-attribute
duration_seconds: float
failure_message class-attribute instance-attribute
failure_message: Optional[str] = None
failure_traceback class-attribute instance-attribute
failure_traceback: Optional[str] = None
fixture_id instance-attribute
fixture_id: str
skipped_reason class-attribute instance-attribute
skipped_reason: Optional[str] = None
verdict instance-attribute
verdict: str
SmokeRunResult dataclass
SmokeRunResult(overall_verdict: str, fixtures: List[SmokeFixtureResult] = list(), package_path: str = '', checked_at: str = '')

Attributes:

checked_at class-attribute instance-attribute
checked_at: str = ''
exit_code property
exit_code: int
fixtures class-attribute instance-attribute
fixtures: List[SmokeFixtureResult] = field(default_factory=list)
overall_verdict instance-attribute
overall_verdict: str
package_path class-attribute instance-attribute
package_path: str = ''
run_smoke_check
run_smoke_check(package_dir: Path, all_fixtures: bool = False) -> SmokeRunResult

Execute one (or all) fixtures and write step_7b_report.json.

Parameters:

  • package_dir (Path) –

    compiled package directory (e.g. <skill>/<name>_mellea).

  • all_fixtures (bool, default: False ) –

    if False (default), only the first fixture in ALL_FIXTURES is executed. If True, every fixture is run sequentially.

writers

Modules:

  • config_writer –

    Deterministic writer: config_emission JSON → config.py Python source.

  • fixtures_writer –

    Deterministic writer: fixtures_emission JSON → fixtures/ subpackage.

  • renderer –

    The writers (config_writer.py, fixtures_writer.py, ...) were originally

config_writer

Deterministic writer: config_emission JSON → config.py Python source.

Input must conform to .claude/schemas/config_emission.schema.json. Output is ready to write directly to /config.py.

Functions:

  • render –

    Render a config_emission JSON object as Python source.

  • write –

    Write rendered config.py source to path.

render
render(emission: dict[str, Any] | str) -> str

Render a config_emission JSON object as Python source.

Parameters:

  • emission (dict[str, Any] | str) –

    dict conforming to config_emission.schema.json, or a JSON string.

Returns:

  • str –

    Python source string with constants grouped by C-category and annotated

  • str –

    with PROVENANCE comments where source location is available.

write
write(emission: dict[str, Any] | str, path: str | Path) -> None

Write rendered config.py source to path.

fixtures_writer

Deterministic writer: fixtures_emission JSON → fixtures/ subpackage.

Input must conform to .claude/schemas/fixtures_emission.schema.json. Output is a set of files written into /fixtures/:

fixtures/__init__.py        — exports ALL_FIXTURES: list[Callable]
fixtures/<id>.py            — one per fixture, defines make_<id>() factory

Each factory is a zero-arg callable that returns (inputs: dict, fixture_id: str, description: str) — the contract enforced by mellea_skills_compiler.toolkit.file_utils.load_fixtures.

The model never writes Python source for fixtures directly. This makes drift shapes (pytest-style tests, INPUT-only modules, etc.) structurally unreachable.

Functions:

  • render_fixture –

    Render a single fixture spec as the contents of fixtures/.py.

  • render_init –

    Render fixtures/init.py exporting ALL_FIXTURES.

  • write –

    Write the rendered fixtures/ subpackage to fixtures_dir.

render_fixture
render_fixture(fixture: dict[str, Any]) -> str

Render a single fixture spec as the contents of fixtures/.py.

render_init
render_init(fixtures: list[dict[str, Any]], coverage_doc: str | None = None) -> str

Render fixtures/init.py exporting ALL_FIXTURES.

write
write(emission: dict[str, Any] | str, fixtures_dir: str | Path) -> list[Path]

Write the rendered fixtures/ subpackage to fixtures_dir.

Parameters:

  • emission (dict[str, Any] | str) –

    dict conforming to fixtures_emission.schema.json, or a JSON string.

  • fixtures_dir (str | Path) –

    target directory (typically /fixtures/). Created if absent.

Returns:

  • list[Path] –

    List of paths written, in deterministic order: init.py first, then per-fixture files.

renderer

The writers (config_writer.py, fixtures_writer.py, ...) were originally documented as "the LLM follows them" — but the slash command runs with --allowed-tools Read,Write,Edit and cannot execute Python. So in practice the LLM was mentally rendering the writer's output, which is unreliable for anything more complex than config.py.

This module moves writer invocation into the compile pipeline, where Python actually runs. Two operating modes:

  • WARN (observation only): render via the writer, diff against the file the LLM wrote, log a warning if they differ, do NOT overwrite.
  • ENFORCE: render via the writer, write authoritatively, deletes whatever the LLM put there. Combine with Write(...) deny rules in --settings to prevent the LLM writing the path in the first place.
Migration plan
  1. WARN mode for config_writer (this commit) — gather evidence the diffs are stable and bounded across compiles.
  2. After ~5 clean compiles, flip config_writer to ENFORCE + add deny rule.
  3. Repeat for fixtures_writer.

Each writer module exposes a render(emission: dict) -> str function returning Python source text. The wrapper reads the emission JSON the LLM emitted, calls render(), and either compares-and-warns or writes-authoritatively.

Functions:

  • render_writers –

    Render every writer in specs against the package and log outcomes.

Attributes:

DEFAULT_WRITER_SPECS module-attribute
DEFAULT_WRITER_SPECS = [WriterSpec(name='config.py', emission_relpath='intermediate/config_emission.json', output_relpath='config.py', writer=config_writer), WriterSpec(name='fixtures/', emission_relpath='intermediate/fixtures_emission.json', output_relpath='fixtures', output_kind='directory', writer=fixtures_writer)]
LOGGER module-attribute
LOGGER = configure_logger()
render_writers
render_writers(package_dir: Path, *, enforce: bool = False) -> List[RenderResult]

Render every writer in specs against the package and log outcomes.

With enforce=False (default for migration phase), only logs WARN on diff and never overwrites. With enforce=True, the writer's output becomes the authoritative source for the artifact.

constants

Single-source constants used across the compiler and its export targets.

Keeping the mellea dependency pin here (instead of hardcoded strings in pyproject.toml, three export-target templates, and the mellea-fy generate-step doc) lets every rendered artefact reference the same value and lets a single regression test enforce consistency (see tests/mellea_skills_compiler/test_pin_consistency.py).

The pyproject.toml pin cannot be derived from this constant at build time (PDM reads dependency strings statically), so it is kept in sync by the test above rather than by import. If you change MELLEA_PIN, also update pyproject.toml and .claude/commands/mellea-fy-generate.md.

Attributes:

MELLEA_PIN module-attribute

MELLEA_PIN = 'mellea[hooks]>=0.7.0,<0.8'

enums

Classes:

BOBMessageType

Bases: StrEnum

Attributes:

ERROR class-attribute instance-attribute
ERROR = auto()
MESSAGE class-attribute instance-attribute
MESSAGE = auto()
RESULT class-attribute instance-attribute
RESULT = auto()
TOOL_USE class-attribute instance-attribute
TOOL_USE = auto()

ClaudeMessageType

Bases: StrEnum

Attributes:

ASSISTANT class-attribute instance-attribute
ASSISTANT = auto()
SYSTEM class-attribute instance-attribute
SYSTEM = auto()
TEXT class-attribute instance-attribute
TEXT = auto()

CoverageLevel

Bases: Enum

Attributes:

AUTOMATED class-attribute instance-attribute
AUTOMATED = 'AUTOMATED'
MANUAL class-attribute instance-attribute
MANUAL = 'MANUAL'
PARTIAL class-attribute instance-attribute
PARTIAL = 'PARTIAL'

GovernanceTaxonomy

Bases: StrEnum

Default taxonomy identifiers

Methods:

Attributes:

CREDO_UCF class-attribute instance-attribute
CREDO_UCF = 'credo-ucf'
IBM_GRANITE_GUARDIAN class-attribute instance-attribute
IBM_GRANITE_GUARDIAN = 'ibm-granite-guardian'
NIST_AI_RMF class-attribute instance-attribute
NIST_AI_RMF = 'nist-ai-rmf'
OWASP_ASI class-attribute instance-attribute
OWASP_ASI = 'owasp-asi'
list classmethod
list() -> List[str]

GuardianMode

Bases: StrEnum

Attributes:

AUDIT class-attribute instance-attribute
AUDIT = 'audit'
DISABLED class-attribute instance-attribute
DISABLED = 'disabled'
ENFORCE class-attribute instance-attribute
ENFORCE = 'enforce'

GuardianScore

Bases: StrEnum

Attributes:

ERROR class-attribute instance-attribute
ERROR = 'Error'
FAILED class-attribute instance-attribute
FAILED = 'Failed'
NO class-attribute instance-attribute
NO = 'No'
YES class-attribute instance-attribute
YES = 'Yes'

HookStage

Bases: StrEnum

Methods:

Attributes:

POST class-attribute instance-attribute
POST = 'post'
PRE class-attribute instance-attribute
PRE = 'pre'
TOOLS_POST class-attribute instance-attribute
TOOLS_POST = 'tools_post'
TOOLS_PRE class-attribute instance-attribute
TOOLS_PRE = 'tools_pre'
list classmethod
list() -> List[str]

InferenceEngineType

Bases: Enum

Enum to contain possible values for inference engine types

Methods:

Attributes:

OLLAMA class-attribute instance-attribute
OLLAMA = auto()
VLLM class-attribute instance-attribute
VLLM = auto()
list classmethod
list() -> List[str]

InferenceModel

Bases: StrEnum

Default model identifiers

Attributes:

CLAUDE_MODEL class-attribute instance-attribute
CLAUDE_MODEL = 'sonnet'
OLLAMA_GUARDIAN_MODEL class-attribute instance-attribute
OLLAMA_GUARDIAN_MODEL = 'ibm/granite3.3-guardian:8b'
OLLAMA_RISK_MODEL class-attribute instance-attribute
OLLAMA_RISK_MODEL = 'granite4.1:3b'
VLLM_GUARDIAN_MODEL class-attribute instance-attribute
VLLM_GUARDIAN_MODEL = 'ibm-granite/granite-guardian-3.3-8b'
VLLM_RISK_MODEL class-attribute instance-attribute
VLLM_RISK_MODEL = 'ibm-granite/granite-4.1-3b'

InferenceModelType

Bases: Enum

Default model types

Attributes:

GUARDIAN_MODEL class-attribute instance-attribute
GUARDIAN_MODEL = auto()
RISK_MODEL class-attribute instance-attribute
RISK_MODEL = auto()

NexusRiskSource

Bases: StrEnum

Attributes:

AI_ATLAS_NEXUS class-attribute instance-attribute
AI_ATLAS_NEXUS = 'ai-atlas-nexus'
DEFAULT_FALLBACK class-attribute instance-attribute
DEFAULT_FALLBACK = 'default-fallback'

PiMessageType

Bases: StrEnum

Attributes:

AGENT_END class-attribute instance-attribute
AGENT_END = auto()
AGENT_SETTLED class-attribute instance-attribute
AGENT_SETTLED = auto()
AGENT_START class-attribute instance-attribute
AGENT_START = auto()
MESSAGE_END class-attribute instance-attribute
MESSAGE_END = auto()
MESSAGE_START class-attribute instance-attribute
MESSAGE_START = auto()
MESSAGE_UPDATE class-attribute instance-attribute
MESSAGE_UPDATE = auto()
SESSION class-attribute instance-attribute
SESSION = auto()
TURN_END class-attribute instance-attribute
TURN_END = auto()
TURN_START class-attribute instance-attribute
TURN_START = auto()

SpecFileFormat

Bases: StrEnum

Default spec file identifiers

Attributes:

SKILL_FILE_MD class-attribute instance-attribute
SKILL_FILE_MD = 'SKILL.md'
SPEC_FILE_MD class-attribute instance-attribute
SPEC_FILE_MD = 'spec.md'

export

Modules:

  • exporter –

    Export pipeline: 5 stages (validate → load → translate → emit → lint).

  • targets –

exporter

Export pipeline: 5 stages (validate → load → translate → emit → lint).

Classes:

Functions:

  • run_export –
  • stage1_validate –

    Read and validate melleafy.json. Returns raw manifest dict.

  • stage2_load –

    Parse manifest fields, derive entry point, detect policy manifest.

  • stage3_translate –

    Build TranslationPlan from LoadedContext. Dispatches to target module.

  • stage4_emit –

    Write all files. Uses .partial/ pattern for atomic write.

  • stage5_lint –

    Basic structural lint on emitted files. Halts with exit code 4 on failure.

Attributes:

EXPORT_VERSION module-attribute
EXPORT_VERSION = '0.1.0'
MIN_MANIFEST_VERSION module-attribute
MIN_MANIFEST_VERSION = Version('1.0.0')
SUPPORTED_TARGETS module-attribute
SUPPORTED_TARGETS = {'langgraph', 'claude-code', 'mcp', 'pi'}
AdapterFile dataclass
AdapterFile(relative_path: str, content: str)

Attributes:

content instance-attribute
content: str
relative_path instance-attribute
relative_path: str
EmitResult dataclass
EmitResult(out_path: Path, files_written: int, bytes_written: int)

Attributes:

bytes_written instance-attribute
bytes_written: int
files_written instance-attribute
files_written: int
out_path instance-attribute
out_path: Path
Invocation dataclass
Invocation(package_path: Path, target: str, out_path: Optional[Path] = None, force: bool = False, enforce: bool = False)

Attributes:

enforce class-attribute instance-attribute
enforce: bool = False
force class-attribute instance-attribute
force: bool = False
out_path class-attribute instance-attribute
out_path: Optional[Path] = None
package_path instance-attribute
package_path: Path
target instance-attribute
target: str
LoadedContext dataclass
LoadedContext(invocation: Invocation, manifest: dict, package_source_dir: Path, python_package_dir: Path, supporting_asset_dirs: list[Path], entry_module: str, sig: ParsedSignature, load_warnings: list[str] = list(), policy_manifest_path: Optional[Path] = None)

Attributes:

entry_module instance-attribute
entry_module: str
invocation instance-attribute
invocation: Invocation
load_warnings class-attribute instance-attribute
load_warnings: list[str] = field(default_factory=list)
manifest instance-attribute
manifest: dict
package_source_dir instance-attribute
package_source_dir: Path
policy_manifest_path class-attribute instance-attribute
policy_manifest_path: Optional[Path] = None
python_package_dir instance-attribute
python_package_dir: Path
sig instance-attribute
supporting_asset_dirs instance-attribute
supporting_asset_dirs: list[Path]
ParsedSignature dataclass
ParsedSignature(function_name: str, params: list[dict], return_type: str, pattern: str)

Parsed from manifest entry_signature string.

Attributes:

function_name instance-attribute
function_name: str
params instance-attribute
params: list[dict]
pattern instance-attribute
pattern: str
return_type instance-attribute
return_type: str
TranslationPlan dataclass
TranslationPlan(graph_name: str, adapter_files: list[AdapterFile], bundled_package_name: str, warnings: list[str] = list(), deployment_guidance: str = '', has_policy_manifest: bool = False, enforce: bool = False)

Attributes:

adapter_files instance-attribute
adapter_files: list[AdapterFile]
bundled_package_name instance-attribute
bundled_package_name: str
deployment_guidance class-attribute instance-attribute
deployment_guidance: str = ''
enforce class-attribute instance-attribute
enforce: bool = False
graph_name instance-attribute
graph_name: str
has_policy_manifest class-attribute instance-attribute
has_policy_manifest: bool = False
warnings class-attribute instance-attribute
warnings: list[str] = field(default_factory=list)
run_export
run_export(inv: Invocation) -> EmitResult
stage1_validate
stage1_validate(inv: Invocation) -> dict

Read and validate melleafy.json. Returns raw manifest dict.

stage2_load
stage2_load(inv: Invocation, manifest: dict) -> LoadedContext

Parse manifest fields, derive entry point, detect policy manifest.

stage3_translate
stage3_translate(loaded: LoadedContext) -> TranslationPlan

Build TranslationPlan from LoadedContext. Dispatches to target module.

stage4_emit
stage4_emit(plan: TranslationPlan, loaded: LoadedContext) -> EmitResult

Write all files. Uses .partial/ pattern for atomic write.

stage5_lint
stage5_lint(result: EmitResult, loaded: LoadedContext, plan: TranslationPlan) -> None

Basic structural lint on emitted files. Halts with exit code 4 on failure.

targets

Modules:

  • claude_code –

    Claude Code target: translate a LoadedContext into a TranslationPlan.

  • langgraph –

    LangGraph target: translate a LoadedContext into a TranslationPlan.

  • mcp –

    MCP target: translate a LoadedContext into a TranslationPlan.

  • pi –

    Pi target: translate a LoadedContext into a TranslationPlan.

claude_code

Claude Code target: translate a LoadedContext into a TranslationPlan.

Supported modalities

synchronous_oneshot — sync Python subprocess via scripts/run.sh streaming — unbuffered async streaming via scripts/run.sh conversational_session — session carry-forward via --session JSON arg

Functions:

Attributes:

SUPPORTED_MODALITIES module-attribute
SUPPORTED_MODALITIES = {'synchronous_oneshot', 'streaming', 'conversational_session'}
translate_claude_code
translate_claude_code(loaded: 'LoadedContext') -> 'TranslationPlan'
langgraph

LangGraph target: translate a LoadedContext into a TranslationPlan.

Supported modalities

synchronous_oneshot — async node wrapping sync pipeline via asyncio.to_thread streaming — async node with get_stream_writer(), graph.astream_events() conversational_session — async node, MemorySaver checkpointer, thread_id config scheduled — async node + langgraph.json schedules block event_triggered — async node, event dict state, platform webhook heartbeat — async node, MemorySaver + HEARTBEAT_THREAD_ID constant + cron schedule

All non-streaming nodes are generated as async def wrapping the synchronous Mellea pipeline via asyncio.to_thread. This prevents blocking LangGraph's ASGI event loop when the pipeline makes synchronous I/O calls (e.g. Ollama, file writes).

Functions:

Attributes:

SUPPORTED_MODALITIES module-attribute
SUPPORTED_MODALITIES = {'synchronous_oneshot', 'streaming', 'conversational_session', 'scheduled', 'event_triggered', 'heartbeat'}
translate_langgraph
translate_langgraph(loaded: 'LoadedContext') -> 'TranslationPlan'
mcp

MCP target: translate a LoadedContext into a TranslationPlan.

Supported modalities

synchronous_oneshot — sync @mcp.tool() wrapping run_pipeline streaming — async @mcp.tool() collecting async generator chunks conversational_session — sync @mcp.tool() (session state managed by pipeline) scheduled — sync @mcp.tool() (schedule is handled externally) event_triggered — sync @mcp.tool() with payload passthrough heartbeat — sync @mcp.tool() (heartbeat state managed by pipeline)

Functions:

translate_mcp
translate_mcp(loaded: 'LoadedContext') -> 'TranslationPlan'
pi

Pi target: translate a LoadedContext into a TranslationPlan.

Supported modalities

synchronous_oneshot — sync Python subprocess via scripts/run.sh streaming — unbuffered async streaming via scripts/run.sh conversational_session — session carry-forward via --session JSON arg

Functions:

Attributes:

SUPPORTED_MODALITIES module-attribute
SUPPORTED_MODALITIES = {'synchronous_oneshot', 'streaming', 'conversational_session'}
translate_pi
translate_pi(loaded: 'LoadedContext') -> 'TranslationPlan'

inference

Classes:

Attributes:

INFERENCE_ENGINE_CACHE module-attribute

INFERENCE_ENGINE_CACHE: Dict[tuple, Any] = {}

OLLAMA_API_URL module-attribute

OLLAMA_API_URL: str = os.environ.get('OLLAMA_HOST') or os.environ.get('OLLAMA_API_URL') or 'http://localhost:11434'

VLLM_API_KEY_GUARDIAN_MODEL module-attribute

VLLM_API_KEY_GUARDIAN_MODEL: Optional[str] = os.environ.get('VLLM_API_KEY_GUARDIAN_MODEL', None)

VLLM_API_KEY_RISK_MODEL module-attribute

VLLM_API_KEY_RISK_MODEL: Optional[str] = os.environ.get('VLLM_API_KEY_RISK_MODEL', None)

VLLM_API_URL_GUARDIAN_MODEL module-attribute

VLLM_API_URL_GUARDIAN_MODEL: Optional[str] = os.environ.get('VLLM_API_URL_GUARDIAN_MODEL', None)

VLLM_API_URL_RISK_MODEL module-attribute

VLLM_API_URL_RISK_MODEL: Optional[str] = os.environ.get('VLLM_API_URL_RISK_MODEL', None)

InferenceService

InferenceService(inference_engine_type: Optional[InferenceEngineType] = None)

Methods:

Attributes:

inference_engine_class property
inference_engine_class
inference_engine_type instance-attribute
inference_engine_type = inference_engine_type if inference_engine_type else InferenceEngineType.OLLAMA
credentials
credentials(model_type: InferenceModelType) -> Optional[Dict[str, Any]]
guardian
guardian(model_name_or_path: Optional[str] = None, parameters: Optional[Dict[str, Any]] = None)
guardian_engine classmethod
guardian_engine(model_name_or_path: Optional[str] = None, inference_engine_type: Optional[InferenceEngineType] = None)
risk
risk(model_name_or_path: Optional[str] = None, parameters: Optional[Dict[str, Any]] = None)
risk_engine classmethod
risk_engine(model_name_or_path: Optional[str] = None, inference_engine_type: Optional[InferenceEngineType] = None)

models

Classes:

Attributes:

LOGGER module-attribute

LOGGER = configure_logger()

ComplianceSummary

Attributes:

automated property
classifications instance-attribute
classifications: list[RequirementClassification]
counts property
counts: dict[str, int]
manual property
partial property

Fixture

Attributes:

context instance-attribute
context: Dict[str, Any]
description instance-attribute
description: str
id instance-attribute
id: str

FixtureResult

Methods:

Attributes:

error_details class-attribute instance-attribute
error_details: Optional[Dict[str, Any]] = None
fixture instance-attribute
fixture: Fixture
output class-attribute instance-attribute
output: Optional[Any] = None
status instance-attribute
status: Literal['success', 'failed', 'blocked']
blocked classmethod
blocked(fixture: Fixture, e: PluginViolationError)
failed classmethod
failed(fixture: Fixture, e: Exception)
success classmethod
success(fixture: Fixture, output: Any)

GovernanceAction

A governance action/mitigation from NIST, Credo UCF, or other taxonomy.

Attributes:

categorized_as class-attribute instance-attribute
categorized_as: Optional[Union[str, List[str]]] = None
category class-attribute instance-attribute
category: str = ''
description instance-attribute
description: str
id instance-attribute
id: str
name instance-attribute
name: str
source instance-attribute
source: str
via_risk class-attribute instance-attribute
via_risk: str = ''

GuardianVerdict

Result of a single Guardian risk check.

Attributes:

hook_stage instance-attribute
hook_stage: HookStage
label instance-attribute
label: str
raw_output instance-attribute
raw_output: str
risk instance-attribute
risk: str
timestamp class-attribute instance-attribute
timestamp: str = field(default_factory=lambda: datetime.now(UTC).isoformat())

NexusRisk

A risk identified by AI Atlas Nexus for this use case.

Risks fall into two tiers based on their Nexus tag field: - Native (is_native=True): Guardian has a calibrated assessment path for this risk. guardian_prompt is the bare tag (e.g. "harm", "jailbreak", "social_bias"). - Custom (is_native=False): No built-in Guardian dimension. guardian_prompt is the description text, sent as custom criteria.

Attributes:

description instance-attribute
description: str
guardian_prompt instance-attribute
guardian_prompt: str
is_native class-attribute instance-attribute
is_native: bool = False
name instance-attribute
name: str
source instance-attribute
source: str
taxonomy class-attribute instance-attribute

PolicyManifest

Policy manifest linking a use case to Guardian checks + governance guidance.

Methods:

Attributes:

additional_risks instance-attribute
additional_risks: list[NexusRisk]
generated_at class-attribute instance-attribute
generated_at: str = field(default_factory=lambda: datetime.now(UTC).isoformat())
governance_actions class-attribute instance-attribute
governance_actions: list[GovernanceAction] = field(default_factory=list)
governance_taxonomies class-attribute instance-attribute
governance_taxonomies: list[str] = field(default_factory=list)
model class-attribute instance-attribute
model: str = field(default_factory=str)
risk_names property
risk_names: list[str]

List of Guardian risk names for each identified risk.

risk_prompts property
risk_prompts: list[str]

List of Guardian prompts for each identified risk.

risks instance-attribute
risks: list[NexusRisk]
taxonomy instance-attribute
taxonomy: Union[str, List[str]]
use_case instance-attribute
use_case: str
from_json classmethod
from_json(path: Path) -> PolicyManifest

Load a PolicyManifest from a JSON file produced by to_json().

to_dict
to_dict() -> dict[str, Any]
to_json
to_json(path: Optional[Path] = None) -> str

RequirementClassification

Attributes:

action instance-attribute
coverage instance-attribute
coverage: CoverageLevel
matched_controls class-attribute instance-attribute
matched_controls: list[str] = field(default_factory=list)

RunResult

Methods:

Attributes:

artifact_paths class-attribute instance-attribute
artifact_paths: Dict[str, Path] = field(default_factory=dict)
error_details class-attribute instance-attribute
error_details: Optional[Dict[str, Any]] = None
guardian_verdicts class-attribute instance-attribute
guardian_verdicts: Optional[Dict[str, List[GuardianVerdict]]] = None
input_parameters instance-attribute
input_parameters: Dict[str, Any]
run_dir class-attribute instance-attribute
run_dir: Optional[Path] = None
status instance-attribute
status: Literal['success', 'failed']
failed classmethod
failed(**kwargs)
success classmethod
success(**kwargs)

plugins

Runtime governance hooks for Mellea pipelines.

Modules:

  • audit –

    Audit trail hook — records every pipeline event to a JSONL LOGGER.

  • guardian –

    Granite Guardian audit hook for Mellea pipelines.

Classes:

Attributes:

LOGGER module-attribute

LOGGER = configure_logger()

BasePlugin

Bases: ABC

Methods:

deregister
deregister() -> None

Remove plugin from the global registry.

register
register()

Add plugin to the global registry.

summary abstractmethod
summary() -> dict

audit

Audit trail hook — records every pipeline event to a JSONL LOGGER.

Captures generation calls, Guardian verdicts, component lifecycle events, and validation outcomes. Designed to compose with GuardianAuditPlugin (priority 40) — this hook runs at priority 100 so Guardian verdicts are available in user_metadata by the time we LOGGER.

Usage

from audit_trail_hook import AuditTrailPlugin plugin = AuditTrailPlugin(log_path="audit.jsonl") register(plugin)

Classes:

Attributes:

LOGGER module-attribute
LOGGER = configure_logger()
AuditTrailPlugin
AuditTrailPlugin(log_path: Path, guardian_plugin: Optional[GuardianPlugin] = None)

Bases: BasePlugin, Plugin

Append-only JSONL audit trail for GraniteClawHub PoC.

Each entry contains
  • timestamp, hook_type, session_id, request_id
  • event-specific data (prompt preview, output preview, verdicts, etc.)
  • optional policy_id for traceability to organisational policy

The priority (100) ensures this runs after all transform/sequential hooks, so user_metadata is fully populated (e.g. Guardian verdicts at pri 40).

Methods:

Attributes:

guardian_plugin instance-attribute
guardian_plugin = guardian_plugin
log_path instance-attribute
log_path = log_path
policy_id instance-attribute
policy_id = f'nexus-{list(set([risk.taxonomy for risk in guardian_plugin.risks]))}' if guardian_plugin and guardian_plugin.risks else ''
deregister
deregister() -> None

Remove plugin from the global registry.

log_batch_error async
log_batch_error(payload: Any, ctx: Any) -> None

Log a batch generation error.

log_batch_post_call async
log_batch_post_call(payload: Any, ctx: Any) -> None

Log each item of a batch generation with its Guardian verdicts.

log_batch_pre_call async
log_batch_pre_call(payload: Any, ctx: Any) -> None

Log a batch generation about to fire.

log_component_error async
log_component_error(payload: Any, ctx: Any) -> None
log_component_start async
log_component_start(payload: Any, ctx: Any) -> None
log_component_success async
log_component_success(payload: Any, ctx: Any) -> None
log_generation_error async
log_generation_error(payload: Any, ctx: Any) -> None

Log a failed generation. Uses public ModelOutputThunk.error.

Added in mellea 0.7 (#1307). Without this, failed generations left no audit record and Guardian verdicts on them were positional-only.

log_post_call async
log_post_call(payload: Any, ctx: Any) -> None

Log LLM output and any Guardian verdicts.

log_pre_call async
log_pre_call(payload: Any, ctx: Any) -> None

Log the prompt being sent to the LLM.

log_tool_post async
log_tool_post(payload: Any, ctx: Any) -> None

Log tool result after execution.

log_tool_pre async
log_tool_pre(payload: Any, ctx: Any) -> None

Log tool call before execution.

log_validation async
log_validation(payload: Any, ctx: Any) -> None
register
register()

Add plugin to the global registry.

summary
summary() -> dict

Return a summary of the audit trail for display.

guardian

Granite Guardian audit hook for Mellea pipelines.

Intercepts generation_post_call, sends the LLM output to Granite Guardian and records the safety verdict in user_metadata for downstream audit hooks.

Two modes
  • AUDIT (default): observe-only, verdicts are logged but generation proceeds.
  • ENFORCE: SEQUENTIAL mode, returns block() when any risk is flagged, raising PluginViolationError to halt the pipeline.

Usage (audit mode — observe only): from guardian_hook import GuardianAuditPlugin plugin = GuardianAuditPlugin(risks=["harm", "jailbreak"]) register(plugin)

Usage (enforce mode — blocks on risk): from guardian_hook import GuardianAuditPlugin plugin = GuardianAuditPlugin(risks=["harm", "jailbreak"], enforce=True) register(plugin)

Classes:

Attributes:

GUARDIAN_CACHE_MAXSIZE module-attribute
GUARDIAN_CACHE_MAXSIZE = 512
GUARDIAN_RETRY_ATTEMPTS module-attribute
GUARDIAN_RETRY_ATTEMPTS = 2
LOGGER module-attribute
LOGGER = configure_logger()
console module-attribute
console = Console()
GuardianAuditPlugin
GuardianAuditPlugin(risks: List[NexusRisk], inference_engine: Optional[InferenceEngineType] = None)

Bases: GuardianPlugin, Plugin

Observe-only Guardian hook (AUDIT mode).

Scans every LLM output against Granite Guardian risk checks. Verdicts are logged and stored but generation is never blocked.

For enforcement mode, use GuardianAuditPlugin.from_manifest(manifest, enforce=True) which returns a GuardianEnforcePlugin instead.

Methods:

  • check_batch_error –

    Batch generation error: record ERROR verdicts (observe-only).

  • check_batch_input –

    Pre-batch generation: observed only.

  • check_batch_output –

    Post-batch generation: assess each item and record verdicts (observe-only).

  • check_error –

    Generation error: record an ERROR verdict per risk (observe-only).

  • check_input –

    Pre-generation: assess input prompt for risks (observe-only).

  • check_output –

    Post-generation: assess LLM output for risks (observe-only).

  • check_tool_input –

    Pre-tool: log the tool call about to be executed (observe-only).

  • check_tool_output –

    Post-tool: scan tool output for risks (observe-only).

  • deregister –

    Remove plugin from the global registry.

  • register –
  • summary –

Attributes:

all_verdicts instance-attribute
all_verdicts: List[GuardianVerdict] = []
inference_engine instance-attribute
inference_engine = inference_engine
risks instance-attribute
risks = risks
verdicts_by_generation_id instance-attribute
verdicts_by_generation_id: Dict[str, List[GuardianVerdict]] = {}
check_batch_error async
check_batch_error(payload: Any, ctx: Any) -> None

Batch generation error: record ERROR verdicts (observe-only).

check_batch_input async
check_batch_input(payload: Any, ctx: Any) -> None

Pre-batch generation: observed only.

check_batch_output async
check_batch_output(payload: Any, ctx: Any) -> None

Post-batch generation: assess each item and record verdicts (observe-only).

check_error async
check_error(payload: Any, ctx: Any) -> None

Generation error: record an ERROR verdict per risk (observe-only).

check_input async
check_input(payload: Any, ctx: Any) -> None

Pre-generation: assess input prompt for risks (observe-only).

check_output async
check_output(payload: Any, ctx: Any) -> None

Post-generation: assess LLM output for risks (observe-only).

check_tool_input async
check_tool_input(payload: Any, ctx: Any) -> None

Pre-tool: log the tool call about to be executed (observe-only).

For Pattern 3 (LLM-directed tool calls via ModelOption.TOOLS). Pattern 2 tool calls don't go through Mellea hooks — they use code-level governance instead.

check_tool_output async
check_tool_output(payload: Any, ctx: Any) -> None

Post-tool: scan tool output for risks (observe-only).

Sends the tool output through Guardian risk checks to detect harmful, biased, or sensitive content returned by external tools.

deregister
deregister() -> None

Remove plugin from the global registry.

register
register() -> None
summary
summary() -> Dict[str, List[GuardianVerdict]]
GuardianEnforcePlugin
GuardianEnforcePlugin(risks: List[NexusRisk], inference_engine: Optional[InferenceEngineType] = None)

Bases: GuardianPlugin, Plugin

Enforcement Guardian hook (SEQUENTIAL mode).

Scans every LLM output against Granite Guardian risk checks. If any risk is flagged, returns block() to halt the pipeline with a PluginViolationError.

Methods:

Attributes:

all_verdicts instance-attribute
all_verdicts: List[GuardianVerdict] = []
inference_engine instance-attribute
inference_engine = inference_engine
risks instance-attribute
risks = risks
verdicts_by_generation_id instance-attribute
verdicts_by_generation_id: Dict[str, List[GuardianVerdict]] = {}
deregister
deregister() -> None

Remove plugin from the global registry.

enforce_batch_error async
enforce_batch_error(payload: Any, ctx: Any) -> None

Batch generation error: record ERROR verdicts.

enforce_batch_input async
enforce_batch_input(payload: Any, ctx: Any) -> None

Pre-batch generation: observed only. See check_batch_input.

enforce_batch_output async
enforce_batch_output(payload: Any, ctx: Any) -> None

Post-batch generation: assess each item and record verdicts.

We deliberately do NOT block on batch outputs: the batch path is used by budget-forcing sampling where blocking would kill the sampling loop. Verdicts are recorded so the certifier can flag the run post-hoc.

enforce_error async
enforce_error(payload: Any, ctx: Any) -> None

Generation error: record an ERROR verdict per risk.

SEQUENTIAL enforcement is meaningless on an error path — there is no output to block. AUDIT mode is used deliberately so failed generations still leave an audit record. See check_error on :class:GuardianAuditPlugin.

enforce_input async
enforce_input(payload: Any, ctx: Any) -> Any

Pre-generation: block if input prompt has risks.

enforce_output async
enforce_output(payload: Any, ctx: Any) -> Any

Post-generation: block if LLM output has risks.

enforce_tool_input async
enforce_tool_input(payload: Any, ctx: Any) -> Any

Pre-tool: log the tool call (enforcement reserved for post-invoke).

enforce_tool_output async
enforce_tool_output(payload: Any, ctx: Any) -> Any

Post-tool: block if tool output contains risks.

register
register() -> None
summary
summary() -> Dict[str, List[GuardianVerdict]]
GuardianPlugin
GuardianPlugin(risks: List[NexusRisk], inference_engine)

Bases: BasePlugin

Shared state and factory methods for Guardian plugins.

Create plugin from a Nexus PolicyManifest.

Parameters:

  • manifest –

    A PolicyManifest with guardian_risks and risk_names.

  • enforce –

    If True, returns a GuardianEnforcePlugin (SEQUENTIAL mode) that blocks generation when risks are detected.

  • inference_engine –

    The inference engine, defaults to Ollama

Methods:

Attributes:

all_verdicts instance-attribute
all_verdicts: List[GuardianVerdict] = []
inference_engine instance-attribute
inference_engine = inference_engine
risks instance-attribute
risks = risks
verdicts_by_generation_id instance-attribute
verdicts_by_generation_id: Dict[str, List[GuardianVerdict]] = {}
deregister
deregister() -> None

Remove plugin from the global registry.

register
register() -> None
summary
summary() -> Dict[str, List[GuardianVerdict]]
GuardianPluginFactory

Methods:

create staticmethod
create(guardian_mode: GuardianMode, *args, **kwargs) -> GuardianPlugin

toolkit

Modules:

cache_strategy

LRU caching strategy for reusable hooks and services.

Classes:

  • LRUCache –

    Thread-safe LRU cache with configurable maximum size.

Functions:

  • hash_key –

    Compute SHA256 hash of concatenated string parts for use in cache keys.

LRUCache
LRUCache(maxsize: int = 512)

Thread-safe LRU cache with configurable maximum size.

When the cache reaches maxsize, the least-recently-used (oldest) entry is evicted on the next insertion. Accessing an existing key promotes it to the end (most recently used).

Initialize LRU cache.

Parameters:

  • maxsize (int, default: 512 ) –

    Maximum number of entries before eviction begins.

Methods:

  • get –

    Get a value from the cache by key.

  • set –

    Set a key-value pair in the cache.

Attributes:

maxsize instance-attribute
maxsize = maxsize
get
get(key: Any) -> Optional[Any]

Get a value from the cache by key.

Returns None if not found. Accessing an existing key promotes it to the end (most recently used).

set
set(key: Any, value: Any) -> None

Set a key-value pair in the cache.

If the key already exists, it is moved to the end (marked most recently used). If the cache is at capacity, the least recently used (oldest) entry is removed.

hash_key
hash_key(*parts: str) -> str

Compute SHA256 hash of concatenated string parts for use in cache keys.

file_utils

Functions:

Attributes:

LOGGER module-attribute
LOGGER = configure_logger()
console module-attribute
console = Console()
load_fixtures
load_fixtures(pipeline_dir: Path) -> List[Fixture]

Load fixtures from the skill's fixtures/ directory.

Supports two conventions: - ALL_FIXTURES: list of factory functions returning (inputs, id, description) - FIXTURES: list of dicts with 'id' and 'context' keys

load_skill_pipeline
load_skill_pipeline(pipeline_dir: Path)
mirror_dir_contents_to_target
mirror_dir_contents_to_target(source_dir: Path, target_dir: Path, include_only: Optional[List[str]] = None, ignore_patterns: Optional[List[str]] = None) -> List[str]

Mirror directory contents from source to target directory.

Copies all files and subdirectories from source_dir into target_dir, excluding items in the ignore list. If include_only provided, copy only those items. Skips copying if the target directory is inside the source to prevent infinite recursion.

Parameters:

  • source_dir Path –

    Source directory to copy from

  • target_dir Path –

    Destination directory (created if it doesn't exist)

  • include_only List[str], optional –

    Include items in the given list only. Default is None.

  • ignore_patterns List[str], optional –

    List of file/directory names to skip. Default is None.

Returns:

  • List[str] –

    List of item names that were successfully copied

Raises:

  • OSError –

    If file operations fail

Example

mirror_dir_contents_to_target( ... Path("/skill"), ... Path("/skill/skill_mellea"), ... ignore_patterns=["audit", "pyproject.toml"] ... ) ['scripts', 'references', 'spec.md']

parse_spec_file
parse_spec_file(spec_path: Path) -> dict

Parse a SKILL.md file into frontmatter dict + markdown body.

logging

Classes:

Functions:

Attributes:

COLORS module-attribute
COLORS = {'DEBUG': '\x1b[36m', 'INFO': '\x1b[32m', 'WARNING': '\x1b[33m', 'ERROR': '\x1b[31m', 'RESET': '\x1b[0m'}
ColoredFormatter

Bases: Formatter

Methods:

format
format(record)
configure_logger
configure_logger(name: str = 'MelleaSkills')

profiling

Performance profiling utilities.

Functions:

Attributes:

  • F –
F module-attribute
F = TypeVar('F', bound=Callable)
profile_if_enabled
profile_if_enabled(func: F) -> F

Wrap a function to profile it if MELLEA_PROFILE env var is set.

Uses yappi to profile all threads (main, fixture workers, asyncio.to_thread workers, etc.), capturing time from ThreadPoolExecutor fan-out in certify and Guardian's asyncio.to_thread LLM calls that cProfile would miss.

Set MELLEA_PROFILE=1 to enable profiling of the command. Profiling results include per-thread summaries and top 40 functions by total time, printed to stdout after the command completes.

Requires yappi: install via pip install -e '.[profile]'

Example

MELLEA_PROFILE=1 mellea-skills compile spec.yaml MELLEA_PROFILE=1 mellea-skills certify -n 3