Skip to content

context

context

Error context for self-healing diagnosis.

Captures all diagnostic information needed to analyze failures and determine appropriate remediation.

Attributes

Classes

ErrorContext dataclass

ErrorContext(error_code, error_message, error_category, exception=None, exit_code=None, signal=None, stdout_tail='', stderr_tail='', config_path=None, config=None, workspace=None, sheet_number=0, working_directory=None, environment=dict(), retry_count=0, max_retries=0, previous_errors=list(), raw_config_yaml=None, validation_details=list(), metadata=dict())

Rich context gathered when an error occurs.

Provides all information needed by the diagnosis engine and remedies to understand and potentially fix the error.

Attributes:

Name Type Description
error_code str

Structured error code (e.g., E601, E304)

error_message str

Human-readable error description

error_category str

High-level category (preflight, configuration, etc.)

exception Exception | None

Original exception if available

exit_code int | None

Process exit code (if applicable)

signal int | None

Termination signal (if applicable)

stdout_tail str

Last portion of stdout output

stderr_tail str

Last portion of stderr output

config_path Path | None

Path to the job configuration file

config JobConfig | None

Parsed JobConfig object

workspace Path | None

Workspace directory path

sheet_number int

Current sheet number

working_directory Path | None

Backend working directory

environment dict[str, str]

Relevant environment variables

retry_count int

Number of retries attempted

max_retries int

Maximum retries configured

previous_errors list[str]

Error codes from previous attempts

Methods:
from_checkpoint_sheet classmethod
from_checkpoint_sheet(sheet, sheet_num, *, workspace='', config_path=None, config=None)

Adapt persisted checkpoint fields without relying on baton counters.

Source code in src/marianne/healing/context.py
@classmethod
def from_checkpoint_sheet(
    cls,
    sheet: "SheetState",
    sheet_num: int,
    *,
    workspace: str = "",
    config_path: str | None = None,
    config: "JobConfig | None" = None,
) -> "ErrorContext":
    """Adapt persisted checkpoint fields without relying on baton counters."""
    history = [dict(entry) for entry in sheet.attempt_history if isinstance(entry, dict)]
    return cls(
        error_code=sheet.error_code or "E009",
        error_message=sheet.error_message or "",
        error_category=sheet.error_category.value if sheet.error_category else "execution",
        exit_code=sheet.exit_code,
        signal=sheet.exit_signal,
        stdout_tail=sheet.stdout_tail or "",
        stderr_tail=sheet.stderr_tail or "",
        workspace=Path(workspace) if workspace else None,
        working_directory=Path(workspace) if workspace else None,
        config_path=Path(config_path) if config_path else None,
        config=config,
        sheet_number=sheet_num,
        retry_count=sheet.attempt_count,
        max_retries=config.retry.max_retries if config else 0,
        previous_errors=[entry["error_code"] for entry in history
                         if isinstance(entry.get("error_code"), str)],
        metadata={
            "attempt_history": history,
            "instrument_fallback_history": [
                dict(entry) for entry in sheet.instrument_fallback_history
                if isinstance(entry, dict)
            ],
        },
    )
from_execution_result classmethod
from_execution_result(result, config, config_path, sheet_number, error_code, error_message, error_category, retry_count=0, max_retries=0, previous_errors=None)

Create context from an execution result.

Parameters:

Name Type Description Default
result ExecutionResult

The failed execution result.

required
config JobConfig

Job configuration.

required
config_path Path | None

Path to config file.

required
sheet_number int

Current sheet number.

required
error_code str

Classified error code.

required
error_message str

Error message.

required
error_category str

Error category.

required
retry_count int

Current retry count.

0
max_retries int

Maximum retries allowed.

0
previous_errors list[str] | None

Error codes from previous attempts.

None

Returns:

Type Description
ErrorContext

ErrorContext with all diagnostic information.

Source code in src/marianne/healing/context.py
@classmethod
def from_execution_result(
    cls,
    result: "ExecutionResult",
    config: "JobConfig",
    config_path: Path | None,
    sheet_number: int,
    error_code: str,
    error_message: str,
    error_category: str,
    retry_count: int = 0,
    max_retries: int = 0,
    previous_errors: list[str] | None = None,
) -> "ErrorContext":
    """Create context from an execution result.

    Args:
        result: The failed execution result.
        config: Job configuration.
        config_path: Path to config file.
        sheet_number: Current sheet number.
        error_code: Classified error code.
        error_message: Error message.
        error_category: Error category.
        retry_count: Current retry count.
        max_retries: Maximum retries allowed.
        previous_errors: Error codes from previous attempts.

    Returns:
        ErrorContext with all diagnostic information.
    """
    import os

    # Capture relevant environment variables
    env_vars = {
        "PATH": os.environ.get("PATH", ""),
        "HOME": os.environ.get("HOME", ""),
        "ANTHROPIC_API_KEY": "***" if os.environ.get("ANTHROPIC_API_KEY") else "",
    }

    return cls(
        error_code=error_code,
        error_message=error_message,
        error_category=error_category,
        exit_code=result.exit_code,
        signal=result.exit_signal,
        stdout_tail=result.stdout[-HEALING_CONTEXT_TAIL_CHARS:] if result.stdout else "",
        stderr_tail=result.stderr[-HEALING_CONTEXT_TAIL_CHARS:] if result.stderr else "",
        config_path=config_path,
        config=config,
        workspace=config.workspace,
        sheet_number=sheet_number,
        working_directory=config.workspace,
        environment=env_vars,
        retry_count=retry_count,
        max_retries=max_retries,
        previous_errors=previous_errors or [],
    )
from_preflight_error classmethod
from_preflight_error(config, config_path, error_code, error_message, sheet_number=0, raw_yaml=None)

Create context from a preflight check failure.

Preflight errors occur before execution starts, so there's no ExecutionResult. This is common for validation errors like missing workspace directories or invalid templates.

Parameters:

Name Type Description Default
config JobConfig

Job configuration.

required
config_path Path | None

Path to config file.

required
error_code str

Preflight error code.

required
error_message str

Error description.

required
sheet_number int

Sheet number (0 if global).

0
raw_yaml str | None

Raw YAML content for template analysis.

None

Returns:

Type Description
ErrorContext

ErrorContext for preflight failures.

Source code in src/marianne/healing/context.py
@classmethod
def from_preflight_error(
    cls,
    config: "JobConfig",
    config_path: Path | None,
    error_code: str,
    error_message: str,
    sheet_number: int = 0,
    raw_yaml: str | None = None,
) -> "ErrorContext":
    """Create context from a preflight check failure.

    Preflight errors occur before execution starts, so there's
    no ExecutionResult. This is common for validation errors
    like missing workspace directories or invalid templates.

    Args:
        config: Job configuration.
        config_path: Path to config file.
        error_code: Preflight error code.
        error_message: Error description.
        sheet_number: Sheet number (0 if global).
        raw_yaml: Raw YAML content for template analysis.

    Returns:
        ErrorContext for preflight failures.
    """
    import os

    env_vars = {
        "PATH": os.environ.get("PATH", ""),
        "HOME": os.environ.get("HOME", ""),
    }

    return cls(
        error_code=error_code,
        error_message=error_message,
        error_category="preflight",
        config_path=config_path,
        config=config,
        workspace=config.workspace,
        sheet_number=sheet_number,
        working_directory=config.workspace,
        environment=env_vars,
        raw_config_yaml=raw_yaml,
    )
from_sheet_state classmethod
from_sheet_state(sheet, sheet_number, error_category='execution', *, workspace=None, config_path=None, config=None)

Create context from the baton's per-sheet execution state (#201).

The baton drives healing from a SheetState (the unified SheetExecutionState), not a full ExecutionResult/JobConfig — so this reads what the baton has (error code/message, exit code/signal, output tails, attempt counts) and accepts workspace/config_path explicitly (the baton stores them on its job record).

Forward-compatible for #133: it can later accept observer/resource data as additional optional fields without reshaping callers.

Source code in src/marianne/healing/context.py
@classmethod
def from_sheet_state(
    cls,
    sheet: "SheetState",
    sheet_number: int,
    error_category: str = "execution",
    *,
    workspace: Path | None = None,
    config_path: Path | None = None,
    config: "JobConfig | None" = None,
) -> "ErrorContext":
    """Create context from the baton's per-sheet execution state (#201).

    The baton drives healing from a ``SheetState`` (the unified
    SheetExecutionState), not a full ``ExecutionResult``/``JobConfig`` — so
    this reads what the baton has (error code/message, exit code/signal,
    output tails, attempt counts) and accepts ``workspace``/``config_path``
    explicitly (the baton stores them on its job record).

    Forward-compatible for #133: it can later accept observer/resource data
    as additional optional fields without reshaping callers.
    """
    import os

    env_vars = {
        "PATH": os.environ.get("PATH", ""),
        "HOME": os.environ.get("HOME", ""),
        "ANTHROPIC_API_KEY": "***" if os.environ.get("ANTHROPIC_API_KEY") else "",
    }

    return cls(
        error_code=sheet.error_code or "E009",
        error_message=sheet.error_message or "",
        error_category=error_category,
        exit_code=sheet.exit_code,
        signal=sheet.exit_signal,
        stdout_tail=sheet.stdout_tail or "",
        stderr_tail=sheet.stderr_tail or "",
        config_path=config_path,
        config=config,
        workspace=workspace,
        sheet_number=sheet_number,
        working_directory=workspace,
        environment=env_vars,
        retry_count=sheet.normal_attempts,
        max_retries=sheet.max_retries,
    )
get_context_summary
get_context_summary()

Get a summary of context for logging/display.

Returns:

Type Description
dict[str, Any]

Dictionary with key context information.

Source code in src/marianne/healing/context.py
def get_context_summary(self) -> dict[str, Any]:
    """Get a summary of context for logging/display.

    Returns:
        Dictionary with key context information.
    """
    return {
        "error_code": self.error_code,
        "error_category": self.error_category,
        "sheet_number": self.sheet_number,
        "retry_count": self.retry_count,
        "exit_code": self.exit_code,
        "workspace": str(self.workspace) if self.workspace else None,
        "has_stdout": bool(self.stdout_tail),
        "has_stderr": bool(self.stderr_tail),
    }