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– -
cli– -
compile– -
constants–Single-source constants used across the compiler and its export targets.
-
enums– -
export– -
inference– -
models– -
plugins–Runtime governance hooks for Mellea pipelines.
-
toolkit–
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
¶
Compose a use-case description from parsed skill + sensitivity.
classification
¶
Functions:
-
classify_governance_requirements–Classify each governance requirement as AUTOMATED, PARTIAL, or MANUAL
-
classify_skill_sensitivity–Classify skill sensitivity from tool list and body keywords.
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:
-
ComplianceSummary(ComplianceSummary) –description
classify_skill_sensitivity
¶
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:
exceptions
¶
Classes:
CertificationInterrupted
¶
CertificationInterrupted(signal_number: int)
ingest
¶
Mellea Skills Compiler — Ingest an OpenClaw SKILL.md and certify it.
Pipeline
- Parse SKILL.md (YAML frontmatter + markdown body)
- Classify tool sensitivity tier (lookup table, no regex)
- Compose use-case description for Nexus
- Nexus risk identification → policy manifest
- Compliance classification
- Certification report
Functions:
-
ingest_one–Risk Analysis and Policy Generation Pipeline for Mellea skill
Attributes:
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_engineparam 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:
-
InputResolutionError–Raised when input resolution fails.
Functions:
-
resolve_input–Resolve input from multiple possible sources.
Attributes:
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
- Ingest a SKILL.md → parse, classify sensitivity, compose use-case
- Identify risks via AI Atlas Nexus → policy manifest
- Configure Guardian hooks from manifest (pre + post generation)
- Run test fixtures through the DECOMPOSED pipeline → Guardian intercepts every m.instruct() call inside the pipeline → Audit trail captures every generation + Guardian verdict
- Compliance classification
- Certification report with runtime evidence
Functions:
-
full_pipeline–Full Certification Pipeline for Mellea skill
-
run_pipeline–Full Certification Pipeline for Mellea skill
Attributes:
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_engineparam 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_engineparam 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_engineparam 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:
-
generate_policy_manifest–Identify applicable risks and governance actions to produce a multi-taxonomy policy manifest.
-
generate_policy_markdown–Generate a human-readable .md policy document from a manifest.
-
guardian_criteria_id–Convert a Nexus tag (
unethical-behavior) to a Guardian criteria id (unethical_behavior). -
load_policy_manifest–Search for policy_manifest.json in standard locations.
Attributes:
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
¶
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:
-
generate_certification_report–Generate a Markdown certification report with evidence.
-
load_audit_trail–Load JSONL audit trail into a list of dicts.
Attributes:
-
EVIDENCE_EXTRACTORS(dict[str, Any]) –
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:
-
manifest(PolicyManifest) –description
-
compliance(ComplianceSummary) –description
-
audit_trail(list[dict]) –description
-
audit_path(str, default:'') –description. Defaults to "".
Returns:
-
str(str) –description
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:
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
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
¶
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)
compile
¶
Modules:
-
backend–Backend abstraction layer for mellea-skills compilation.
-
backends–Backend implementations for mellea-skills compilation.
-
claude_directives– -
compiler– -
grounding–Deterministic grounding artifact generation for the mellea-fy pipeline.
-
lints–Step 7 structural lints — Python implementations.
-
metadata– -
models– -
proxy– -
smoke_check–Post-lint fixture smoke-check (Step 7's
--runmode). -
writers–
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:
-
BackendRegistry–Registry for managing available compilation backends.
-
CompilationBackend–Protocol defining the interface for compilation backends.
-
CompilationContext–Input context for compilation process.
-
CompilationResult–Result of a compilation process.
Attributes:
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–Retrieve a backend by identifier.
-
list_backends–List all registered backend identifiers.
-
register_backend–Register a backend implementation.
get_backend
¶
get_backend(identifier: str) -> CompilationBackend
Retrieve a backend by identifier.
Parameters:
-
identifier(str) –Backend identifier (e.g., "claude", "bob")
Returns:
-
CompilationBackend–An instance of the requested backend
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
¶
register_backend
¶
register_backend(backend_class: Type[CompilationBackend]) -> None
Register a backend implementation.
Parameters:
-
backend_class(Type[CompilationBackend]) –Class implementing the CompilationBackend protocol
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
¶
compile(context: CompilationContext) -> CompilationResult
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
¶
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, ... )
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:
-
success(bool) –True if compilation completed successfully, False otherwise
-
package_dir(Path) –Path to the compiled Mellea package directory
-
error_message(Optional[str]) –Human-readable error description if success=False, None otherwise
-
intermediate_artifacts(dict[str, Path]) –Mapping of artifact names to their file paths (e.g., {"inventory": Path("intermediate/inventory.json")})
-
metadata(dict[str, Any]) –Backend-specific metadata (e.g., model used, tokens consumed, timing info)
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}, ... )
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
¶
compile(context: CompilationContext) -> CompilationResult
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}")
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
¶
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)whereis_validisTrue -
Optional[str]–when Bob is usable and
error_messagecontains 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
¶
compile(context: CompilationContext) -> CompilationResult
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
¶
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)whereis_validisTrue -
Optional[str]–when Claude Code is usable and
error_messagecontains 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
¶
compile(context: CompilationContext) -> CompilationResult
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:
-
CompilationResult–CompilationResult with success status, package directory, and metadata.
-
CompilationResult–Also fails if pi exits 0 without producing
-
CompilationResult–intermediate/classification.json— a clean exit with no output -
CompilationResult–(e.g. pi stopped to ask a question in one-shot mode) is not success —
-
CompilationResult–or without the
*_emission.jsonfiles the renderer needs (the -
CompilationResult–model ended its turn partway through the pipeline).
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
¶
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:
-
authenticate_bob–Test the bob run command and report success/failure.
Attributes:
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
¶compile(context: CompilationContext) -> CompilationResult
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}")
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
¶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)whereis_validisTrue -
Optional[str]–when Bob is usable and
error_messagecontains 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}")
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:
-
ClaudeCodeBackend–Claude Code backend for mellea-skills compilation.
Attributes:
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
¶compile(context: CompilationContext) -> CompilationResult
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
¶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)whereis_validisTrue -
Optional[str]–when Claude Code is usable and
error_messagecontains 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:
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
¶compile(context: CompilationContext) -> CompilationResult
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:
-
CompilationResult–CompilationResult with success status, package directory, and metadata.
-
CompilationResult–Also fails if pi exits 0 without producing
-
CompilationResult–intermediate/classification.json— a clean exit with no output -
CompilationResult–(e.g. pi stopped to ask a question in one-shot mode) is not success —
-
CompilationResult–or without the
*_emission.jsonfiles the renderer needs (the -
CompilationResult–model ended its turn partway through the pipeline).
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
¶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:
-
build_pi_system_prompt–Same directive as
build_system_prompt, worded for pi. -
build_system_prompt–Assemble the instruction string passed to the mellea-fy slash command.
-
resolve_runtime_defaults–Pick the backend and model_id to bake into the compiled skill.
-
write_compile_settings–Write a per-invocation Claude Code --settings file with the deny rules.
-
write_runtime_directive–Save the chosen backend and model_id alongside the package.
Attributes:
-
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
¶
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 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
¶
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
¶
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.mdfile 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". WhenNonethe 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
Truethe 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
Truethe post-compile validation step skips executing the skill's test fixtures, performing only static checks. Defaults to False. -
refresh_cache(bool, default:False) –When
Trueforces regeneration of cached grounding artefacts (mellea_api_ref.jsonandmellea_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.jsonwhen 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-levelruntime_defaults.jsonwhen 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_pathhas an extension other than.md. -
FileNotFoundError–If
spec_pathdoes not exist on disk.
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:
-
write_mellea_api_ref–Write
mellea_api_ref.jsontointermediate_dir. -
write_mellea_doc_index–Write
mellea_doc_index.jsontointermediate_dir.
Attributes:
-
CACHE_DIR– -
CORE_MODULES– -
LOGGER–
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'}
write_mellea_api_ref
¶
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.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:
-
lint_bundled_asset_path_resolution–Reject any path-join construction that resolves a bundled-asset path
-
lint_fixture_data_files_exist–A fixture must not reference a relative data file absent from the package.
-
lint_fixture_pydantic_coercion–Fixture inputs must not pass bare dicts where run_pipeline expects Pydantic models.
-
lint_fixtures_loader_contract–<package>/fixtures/__init__.pymust export ALL_FIXTURES or FIXTURES. -
lint_format_annotation–m.instruct(...)calls whose result is parsed must includeformat=. -
lint_grounding_context_types–Every
grounding_context=dict-literal value should be a string. -
lint_import_side_effects–No module-level Calls outside the documented allowlist.
-
lint_import_soundness–Every
mellea.*import path must exist inmellea_api_ref.json:.modules. -
lint_instruct_result_parse_before_access–KB1:
m.instruct(format=Model)returns a thunk, not a Pydantic model. -
lint_parseable–Every
.pyfile under the package must parse, and<pkg>.pipelinemust import. -
lint_prefix_persona–m.instruct(prefix=<config_constant>)is misuse (KB7). -
lint_raw_llm_json_parse–Require raw m.instruct/simple_validate text to use the JSON response helper.
-
lint_runtime_defaults_bound–The compiled config.py must use the backend and model_id we instructed.
-
lint_session_boundary–Each
start_session(...)block must use at most one distinct format type. -
lint_session_method_arity–MelleaSession method calls must supply required positional arguments.
-
lint_stdlib_arg_types–Flag clearly-non-dict arguments passed to Mellea API
grounding_context=kwargs. -
lint_validation_fn_not_called_directly–Reject any direct call to
<req>.validation_fn(...)in generated code. -
run_lints–Run all implemented Step 7 structural lints; write step_7_report.json.
Attributes:
-
ALL_LINTS(Tuple[Callable[[Path], LintResult], ...]) –
ALL_LINTS
module-attribute
¶
ALL_LINTS: Tuple[Callable[[Path], LintResult], ...] = (lint_fixtures_loader_contract, lint_fixture_data_files_exist, lint_bundled_asset_path_resolution, lint_runtime_defaults_bound, lint_session_method_arity, lint_instruct_result_parse_before_access, lint_format_annotation, lint_raw_llm_json_parse, lint_session_boundary, lint_validation_fn_not_called_directly, lint_fixture_pydantic_coercion, lint_grounding_context_types, lint_stdlib_arg_types, lint_prefix_persona, lint_parseable, lint_import_soundness, lint_import_side_effects)
LintFailure
dataclass
¶
LintFailure(file: str, line: Optional[int], column: Optional[int], message: str, rule_ref: Optional[str] = None)
Attributes:
LintResult
dataclass
¶
LintResult(lint_id: str, verdict: str, files_checked: int = 0, skipped_reason: Optional[str] = None, failures: List[LintFailure] = list())
Attributes:
-
failures(List[LintFailure]) – -
files_checked(int) – -
lint_id(str) – -
skipped_reason(Optional[str]) – -
verdict(str) –
failures
class-attribute
instance-attribute
¶
failures: List[LintFailure] = field(default_factory=list)
LintRunResult
dataclass
¶
LintRunResult(overall_verdict: str, lints: List[LintResult], package_path: str, checked_at: str)
Attributes:
-
checked_at(str) – -
failed(bool) – -
lints(List[LintResult]) – -
overall_verdict(str) – -
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
- AST-parse pipeline.py / slots.py / constrained_slots.py.
- For every
Callthat ism.instruct(...)assigned to a Name target (thunk = m.instruct(...)), record whether it hasformat=and which variable holds the result. - 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>, ...)
- argument to
- 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
failif any definite-collection violationwarningif only ambiguous findingspassotherwise
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:
- Per-file parseability:
ast.parse(p.read_text())for every.pyfile directly under<package_dir>/and<package_dir>/fixtures/. - 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.strategiesinstead ofmellea.stdlib.sampling) thatast.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
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.jsonafter a successful compile.
Attributes:
-
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–Initialize (or reset) the singleton for a new compile run.
-
record_args– -
record_backend– -
record_completion– -
record_melleafy–
models
¶
Classes:
-
RenderResult– -
WriterSpec–One renderable artifact: emission JSON in → Python source on disk out.
RenderResult
dataclass
¶
RenderResult(name: str, status: str, detail: Optional[str] = None, diff_lines_added: int = 0, diff_lines_removed: int = 0)
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(str) – -
name(str) – -
output_kind(str) – -
output_relpath(str) – -
writer(ModuleType) –
proxy
¶
Classes:
-
ContextMgmtStrippingProxy–Local proxy that strips context_management from Anthropic API requests.
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_POST– -
handle_error– -
log_message–
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–
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(float) – -
failure_message(Optional[str]) – -
failure_traceback(Optional[str]) – -
fixture_id(str) – -
skipped_reason(Optional[str]) – -
verdict(str) –
SmokeRunResult
dataclass
¶
SmokeRunResult(overall_verdict: str, fixtures: List[SmokeFixtureResult] = list(), package_path: str = '', checked_at: str = '')
Attributes:
-
checked_at(str) – -
exit_code(int) – -
fixtures(List[SmokeFixtureResult]) – -
overall_verdict(str) – -
package_path(str) –
fixtures
class-attribute
instance-attribute
¶
fixtures: List[SmokeFixtureResult] = field(default_factory=list)
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:
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
Functions:
-
render–Render a config_emission JSON object as Python source.
-
write–Write rendered config.py source to path.
render
¶
Render a config_emission JSON object as Python source.
Parameters:
Returns:
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/__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 a single fixture spec as the contents of fixtures/
render_init
¶
Render fixtures/init.py exporting ALL_FIXTURES.
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
- WARN mode for
config_writer(this commit) — gather evidence the diffs are stable and bounded across compiles. - After ~5 clean compiles, flip
config_writerto ENFORCE + add deny rule. - 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
specsagainst 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)]
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:
enums
¶
Classes:
-
BOBMessageType– -
ClaudeMessageType– -
CoverageLevel– -
GovernanceTaxonomy–Default taxonomy identifiers
-
GuardianMode– -
GuardianScore– -
HookStage– -
InferenceEngineType–Enum to contain possible values for inference engine types
-
InferenceModel–Default model identifiers
-
InferenceModelType–Default model types
-
NexusRiskSource– -
PiMessageType– -
SpecFileFormat–Default spec file identifiers
ClaudeMessageType
¶
CoverageLevel
¶
GovernanceTaxonomy
¶
GuardianMode
¶
GuardianScore
¶
InferenceEngineType
¶
InferenceModel
¶
PiMessageType
¶
Bases: StrEnum
Attributes:
-
AGENT_END– -
AGENT_SETTLED– -
AGENT_START– -
MESSAGE_END– -
MESSAGE_START– -
MESSAGE_UPDATE– -
SESSION– -
TURN_END– -
TURN_START–
export
¶
Modules:
exporter
¶
Export pipeline: 5 stages (validate → load → translate → emit → lint).
Classes:
-
AdapterFile– -
EmitResult– -
Invocation– -
LoadedContext– -
ParsedSignature–Parsed from manifest entry_signature string.
-
TranslationPlan–
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:
AdapterFile
dataclass
¶
EmitResult
dataclass
¶
Invocation
dataclass
¶
Invocation(package_path: Path, target: str, out_path: Optional[Path] = None, force: bool = False, enforce: bool = False)
Attributes:
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(str) – -
invocation(Invocation) – -
load_warnings(list[str]) – -
manifest(dict) – -
package_source_dir(Path) – -
policy_manifest_path(Optional[Path]) – -
python_package_dir(Path) – -
sig(ParsedSignature) – -
supporting_asset_dirs(list[Path]) –
ParsedSignature
dataclass
¶
Parsed from manifest entry_signature string.
Attributes:
-
function_name(str) – -
params(list[dict]) – -
pattern(str) – -
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(list[AdapterFile]) – -
bundled_package_name(str) – -
deployment_guidance(str) – -
enforce(bool) – -
graph_name(str) – -
has_policy_manifest(bool) – -
warnings(list[str]) –
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:
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:
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:
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:
inference
¶
Classes:
Attributes:
-
INFERENCE_ENGINE_CACHE(Dict[tuple, Any]) – -
OLLAMA_API_URL(str) – -
VLLM_API_KEY_GUARDIAN_MODEL(Optional[str]) – -
VLLM_API_KEY_RISK_MODEL(Optional[str]) – -
VLLM_API_URL_GUARDIAN_MODEL(Optional[str]) – -
VLLM_API_URL_RISK_MODEL(Optional[str]) –
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_RISK_MODEL
module-attribute
¶
VLLM_API_URL_GUARDIAN_MODEL
module-attribute
¶
VLLM_API_URL_RISK_MODEL
module-attribute
¶
InferenceService
¶
InferenceService(inference_engine_type: Optional[InferenceEngineType] = None)
Methods:
-
credentials– -
guardian– -
guardian_engine– -
risk– -
risk_engine–
Attributes:
inference_engine_type
instance-attribute
¶
inference_engine_type = inference_engine_type if inference_engine_type else InferenceEngineType.OLLAMA
guardian
¶
guardian_engine
classmethod
¶
guardian_engine(model_name_or_path: Optional[str] = None, inference_engine_type: Optional[InferenceEngineType] = None)
risk_engine
classmethod
¶
risk_engine(model_name_or_path: Optional[str] = None, inference_engine_type: Optional[InferenceEngineType] = None)
models
¶
Classes:
-
ComplianceSummary– -
Fixture– -
FixtureResult– -
GovernanceAction–A governance action/mitigation from NIST, Credo UCF, or other taxonomy.
-
GuardianVerdict–Result of a single Guardian risk check.
-
NexusRisk–A risk identified by AI Atlas Nexus for this use case.
-
PolicyManifest–Policy manifest linking a use case to Guardian checks + governance guidance.
-
RequirementClassification– -
RunResult–
Attributes:
-
LOGGER–
ComplianceSummary
¶
Attributes:
-
automated(list[RequirementClassification]) – -
classifications(list[RequirementClassification]) – -
counts(dict[str, int]) – -
manual(list[RequirementClassification]) – -
partial(list[RequirementClassification]) –
Fixture
¶
FixtureResult
¶
GovernanceAction
¶
GuardianVerdict
¶
Result of a single Guardian risk check.
Attributes:
-
hook_stage(HookStage) – -
label(str) – -
raw_output(str) – -
risk(str) – -
timestamp(str) –
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(str) – -
guardian_prompt(str) – -
is_native(bool) – -
name(str) – -
source(str) – -
taxonomy(str) –
taxonomy
class-attribute
instance-attribute
¶
taxonomy: str = GovernanceTaxonomy.IBM_GRANITE_GUARDIAN
PolicyManifest
¶
Policy manifest linking a use case to Guardian checks + governance guidance.
Methods:
Attributes:
-
additional_risks(list[NexusRisk]) – -
generated_at(str) – -
governance_actions(list[GovernanceAction]) – -
governance_taxonomies(list[str]) – -
model(str) – -
risk_names(list[str]) –List of Guardian risk names for each identified risk.
-
risk_prompts(list[str]) –List of Guardian prompts for each identified risk.
-
risks(list[NexusRisk]) – -
taxonomy(Union[str, List[str]]) – -
use_case(str) –
generated_at
class-attribute
instance-attribute
¶
governance_actions
class-attribute
instance-attribute
¶
governance_actions: list[GovernanceAction] = field(default_factory=list)
governance_taxonomies
class-attribute
instance-attribute
¶
from_json
classmethod
¶
from_json(path: Path) -> PolicyManifest
Load a PolicyManifest from a JSON file produced by to_json().
RequirementClassification
¶
RunResult
¶
Methods:
Attributes:
-
artifact_paths(Dict[str, Path]) – -
error_details(Optional[Dict[str, Any]]) – -
guardian_verdicts(Optional[Dict[str, List[GuardianVerdict]]]) – -
input_parameters(Dict[str, Any]) – -
run_dir(Optional[Path]) – -
status(Literal['success', 'failed']) –
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–
BasePlugin
¶
Bases: ABC
Methods:
-
deregister–Remove plugin from the global registry.
-
register–Add plugin to the global registry.
-
summary–
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:
-
AuditTrailPlugin–Append-only JSONL audit trail for GraniteClawHub PoC.
Attributes:
-
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:
-
deregister–Remove plugin from the global registry.
-
log_batch_error–Log a batch generation error.
-
log_batch_post_call–Log each item of a batch generation with its Guardian verdicts.
-
log_batch_pre_call–Log a batch generation about to fire.
-
log_component_error– -
log_component_start– -
log_component_success– -
log_generation_error–Log a failed generation. Uses public
ModelOutputThunk.error. -
log_post_call–Log LLM output and any Guardian verdicts.
-
log_pre_call–Log the prompt being sent to the LLM.
-
log_tool_post–Log tool result after execution.
-
log_tool_pre–Log tool call before execution.
-
log_validation– -
register–Add plugin to the global registry.
-
summary–Return a summary of the audit trail for display.
Attributes:
-
guardian_plugin– -
log_path– -
policy_id–
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 ''
log_batch_error
async
¶
Log a batch generation error.
log_batch_post_call
async
¶
Log each item of a batch generation with its Guardian verdicts.
log_batch_pre_call
async
¶
Log a batch generation about to fire.
log_generation_error
async
¶
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 LLM output and any Guardian verdicts.
log_pre_call
async
¶
Log the prompt being sent to the LLM.
log_tool_post
async
¶
Log tool result after execution.
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:
-
GuardianAuditPlugin–Observe-only Guardian hook (AUDIT mode).
-
GuardianEnforcePlugin–Enforcement Guardian hook (SEQUENTIAL mode).
-
GuardianPlugin–Shared state and factory methods for Guardian plugins.
-
GuardianPluginFactory–
Attributes:
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(List[GuardianVerdict]) – -
inference_engine– -
risks– -
verdicts_by_generation_id(Dict[str, List[GuardianVerdict]]) –
verdicts_by_generation_id
instance-attribute
¶
verdicts_by_generation_id: Dict[str, List[GuardianVerdict]] = {}
check_batch_error
async
¶
Batch generation error: record ERROR verdicts (observe-only).
check_batch_input
async
¶
Pre-batch generation: observed only.
check_batch_output
async
¶
Post-batch generation: assess each item and record verdicts (observe-only).
check_error
async
¶
Generation error: record an ERROR verdict per risk (observe-only).
check_input
async
¶
Pre-generation: assess input prompt for risks (observe-only).
check_output
async
¶
Post-generation: assess LLM output for risks (observe-only).
check_tool_input
async
¶
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
¶
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.
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:
-
deregister–Remove plugin from the global registry.
-
enforce_batch_error–Batch generation error: record ERROR verdicts.
-
enforce_batch_input–Pre-batch generation: observed only. See
check_batch_input. -
enforce_batch_output–Post-batch generation: assess each item and record verdicts.
-
enforce_error–Generation error: record an ERROR verdict per risk.
-
enforce_input–Pre-generation: block if input prompt has risks.
-
enforce_output–Post-generation: block if LLM output has risks.
-
enforce_tool_input–Pre-tool: log the tool call (enforcement reserved for post-invoke).
-
enforce_tool_output–Post-tool: block if tool output contains risks.
-
register– -
summary–
Attributes:
-
all_verdicts(List[GuardianVerdict]) – -
inference_engine– -
risks– -
verdicts_by_generation_id(Dict[str, List[GuardianVerdict]]) –
verdicts_by_generation_id
instance-attribute
¶
verdicts_by_generation_id: Dict[str, List[GuardianVerdict]] = {}
enforce_batch_error
async
¶
Batch generation error: record ERROR verdicts.
enforce_batch_input
async
¶
Pre-batch generation: observed only. See check_batch_input.
enforce_batch_output
async
¶
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
¶
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
¶
Pre-generation: block if input prompt has risks.
enforce_output
async
¶
Post-generation: block if LLM output has risks.
enforce_tool_input
async
¶
Pre-tool: log the tool call (enforcement reserved for post-invoke).
enforce_tool_output
async
¶
Post-tool: block if tool output contains risks.
GuardianPlugin
¶
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:
-
deregister–Remove plugin from the global registry.
-
register– -
summary–
Attributes:
-
all_verdicts(List[GuardianVerdict]) – -
inference_engine– -
risks– -
verdicts_by_generation_id(Dict[str, List[GuardianVerdict]]) –
verdicts_by_generation_id
instance-attribute
¶
verdicts_by_generation_id: Dict[str, List[GuardianVerdict]] = {}
toolkit
¶
Modules:
-
cache_strategy–LRU caching strategy for reusable hooks and services.
-
file_utils– -
logging– -
profiling–Performance profiling utilities.
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:
Attributes:
-
maxsize–
get
¶
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).
file_utils
¶
Functions:
-
load_fixtures–Load fixtures from the skill's fixtures/ directory.
-
load_skill_pipeline– -
mirror_dir_contents_to_target–Mirror directory contents from source to target directory.
-
parse_spec_file–Parse a SKILL.md file into frontmatter dict + markdown body.
Attributes:
load_fixtures
¶
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
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:
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']
profiling
¶
Performance profiling utilities.
Functions:
-
profile_if_enabled–Wrap a function to profile it if MELLEA_PROFILE env var is set.
Attributes:
-
F–
profile_if_enabled
¶
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