<reasoning_content>
Here's a thinking process:

1.  **Understand User Goal**: The user wants to refactor a monolithic Python job queue implementation (currently in a single file `queue.py`) into a proper package structure with four files: `__init__.py`, `core.py`, `retry.py`, and `priority.py`. The requirements are:
   - Maintain all existing functionality
   - Proper imports between modules
   - Clean public API in `__init__.py`
   - Each module has a single responsibility
   - Provide the content of each file.

2.  **Analyze Current Structure (Implicit)**: The user provided a pseudo-structure:
   ```python
   # queue.py - everything in one file
   class Job: ...
   class JobQueue: ...
   class PriorityQueue: ...
   def process_with_retry(): ...
   ```
   I need to infer reasonable implementations for these components based on standard job queue patterns, while ensuring they fit the target structure. I'll create a complete, functional implementation that matches the requirements.

   Key components to implement:
   - `Job`: Dataclass representing a job (id, function, args, kwargs, priority, created_at, status, etc.)
   - `JobQueue`: Basic queue operations (enqueue, dequeue, process, etc.)
   - `PriorityQueue`: Priority queue implementation (likely wrapping `heapq` or similar)
   - `process_with_retry`: Retry logic with exponential backoff
   - `__init__.py`: Clean exports

3.  **Design Module Responsibilities**:
   - `core.py`: Contains `Job` dataclass and `JobQueue` (basic FIFO queue operations). Actually, the prompt says `core.py` should have "Job dataclass, basic queue operations". I'll put `Job` and a basic `JobQueue` here.
   - `retry.py`: Contains retry logic with exponential backoff. I'll implement a decorator or a function `process_with_retry` that handles retries.
   - `priority.py`: Contains `PriorityQueue` implementation.
   - `__init__.py`: Exports `JobQueue`, `Job` (and maybe `PriorityQueue` if needed, but prompt says "Exports: JobQueue, Job"). I'll stick to that.

   Wait, the prompt says `core.py` has "Job dataclass, basic queue operations". It doesn't explicitly say `JobQueue` goes there, but it's logical. I'll put `JobQueue` in `core.py` or maybe make `JobQueue` use `PriorityQueue` internally? The prompt lists them as separate classes in the original file. I'll keep them separate but related. Actually, `JobQueue` could be the main interface, and `PriorityQueue` could be a separate implementation or used internally. To keep it simple and match the prompt, I'll implement:
   - `core.py`: `Job` dataclass, `JobQueue` (FIFO)
   - `priority.py`: `PriorityQueue` (wraps `heapq`, handles priority ordering)
   - `retry.py`: `process_with_retry` function/decorator with exponential backoff
   - `__init__.py`: Imports and exports `Job`, `JobQueue` (and maybe `PriorityQueue` if needed, but I'll stick to the prompt's explicit exports)

   Let's refine: The prompt says `core.py` has "Job dataclass, basic queue operations". I'll put `Job` and a base `JobQueue` there. `priority.py` will have `PriorityQueue`. `retry.py` will have the retry logic. I'll make sure they work together or can be used independently.

   Actually, a more cohesive design: `JobQueue` could be the main class that uses `PriorityQueue` internally, or they could be separate. I'll keep them as separate classes as in the original, but ensure proper imports. I'll make `JobQueue` a standard FIFO queue, and `PriorityQueue` a separate class that can be used similarly. Alternatively, `JobQueue` could be an abstract base or just a concrete class. I'll stick to concrete implementations for simplicity.

   Let's draft each file mentally:

   **core.py**:
   ```python
   from dataclasses import dataclass, field
   from typing import Callable, Any, Optional
   from datetime import datetime
   import uuid

   @dataclass
   class Job:
       id: str = field(default_factory=lambda: str(uuid.uuid4()))
       func: Callable = None
       args: tuple = ()
       kwargs: dict = field(default_factory=dict)
       priority: int = 0
       created_at: datetime = field(default_factory=datetime.now)
       status: str = "pending"
       result: Any = None
       error: Optional[str] = None
   ```

   **priority.py**:
   ```python
   import heapq
   from typing import Optional
   from .core import Job

   class PriorityQueue:
       def __init__(self):
           self._queue = []
           self._counter = 0

       def enqueue(self, job: Job):
           # Lower priority number = higher priority
           heapq.heappush(self._queue, (job.priority, self._counter, job))
           self._counter += 1

       def dequeue(self) -> Optional[Job]:
           if self._queue:
               _, _, job = heapq.heappop(self._queue)
               return job
           return None

       def __len__(self):
           return len(self._queue)

       def __bool__(self):
           return bool(self._queue)
   ```

   **retry.py**:
   ```python
   import time
   import logging
   from typing import Callable, Any
   from .core import Job

   logger = logging.getLogger(__name__)

   def process_with_retry(job: Job, max_retries: int = 3, base_delay: float = 1.0) -> Any:
       for attempt in range(max_retries + 1):
           try:
               job.status = "running"
               result = job.func(*job.args, **job.kwargs)
               job.status = "completed"
               job.result = result
               return result
           except Exception as e:
               job.status = "failed"
               job.error = str(e)
               if attempt == max_retries:
                   logger.error(f"Job {job.id} failed after {max_retries} retries: {e}")
                   raise
               delay = base_delay * (2 ** attempt)
               logger.warning(f"Job {job.id} failed (attempt {attempt + 1}/{max_retries + 1}). Retrying in {delay}s...")
               time.sleep(delay)
       return None
   ```

   **__init__.py**:
   ```python
   from .core import Job, JobQueue
   # Wait, I didn't implement JobQueue in core.py yet. Let's add it.
   ```

   I need to add `JobQueue` to `core.py` to match the prompt's original structure and exports.
   Let's update `core.py` to include `JobQueue`:

   ```python
   from dataclasses import dataclass, field
   from typing import Callable, Any, Optional, List
   from datetime import datetime
   import uuid
   from collections import deque

   @dataclass
   class Job:
       id: str = field(default_factory=lambda: str(uuid.uuid4()))
       func: Callable = None
       args: tuple = ()
       kwargs: dict = field(default_factory=dict)
       priority: int = 0
       created_at: datetime = field(default_factory=datetime.now)
       status: str = "pending"
       result: Any = None
       error: Optional[str] = None

   class JobQueue:
       def __init__(self):
           self._queue: deque[Job] = deque()

       def enqueue(self, job: Job):
           self._queue.append(job)

       def dequeue(self) -> Optional[Job]:
           if self._queue:
               return self._queue.popleft()
           return None

       def __len__(self):
           return len(self._queue)

       def __bool__(self):
           return bool(self._queue)
   ```

   Now `__init__.py`:
   ```python
   from .core import Job, JobQueue
   from .priority import PriorityQueue
   from .retry import process_with_retry

   __all__ = ["Job", "JobQueue", "PriorityQueue", "process_with_retry"]
   ```

   Wait, the prompt says `__init__.py` should export `JobQueue, Job`. I'll stick to that, but I can also export the others if needed. I'll follow the prompt exactly: `Exports: JobQueue, Job`. I'll keep it clean.

   Let's verify requirements:
   1. Maintain all existing functionality: Yes, Job, JobQueue, PriorityQueue, process_with_retry are all implemented.
   2. Proper imports between modules: Yes, relative imports used.
   3. Clean public API in __init__.py: Yes, exports specified.
   4. Each module has a single responsibility: core (data + basic queue), retry (retry logic), priority (priority queue), __init__ (public API).

   I should make sure the code is robust and follows Python best practices. I'll add type hints, docstrings, and ensure the retry function can be used as a decorator or function. The prompt shows `def process_with_retry(): ...`, so I'll keep it as a function that takes a job. I'll also make it reusable.

   Let's refine each file carefully.

   **core.py**:
   - `Job` dataclass with necessary fields
   - `JobQueue` with FIFO operations
   - Type hints, docstrings

   **priority.py**:
   - `PriorityQueue` using `heapq`
   - Imports `Job` from `core`
   - Methods: `enqueue`, `dequeue`, `__len__`, `__bool__`

   **retry.py**:
   - `process_with_retry` function
   - Exponential backoff logic
   - Imports `Job` from `core`
   - Uses `time.sleep` for backoff (note: in real apps, async might be better, but I'll stick to sync as implied)
   - Logging for visibility

   **__init__.py**:
   - Imports and exports `Job`, `JobQueue`
   - Optionally exports others if needed, but I'll stick to the prompt.

   One thing: The prompt says `core.py` has "Job dataclass, basic queue operations". It doesn't explicitly say `JobQueue` class, but it's implied. I'll include `JobQueue` in `core.py`.

   Let's write out the full content for each file.

   I'll also add a quick usage example comment in `__init__.py` or just keep it clean.

   Check imports:
   - `core.py`: no internal imports
   - `priority.py`: `from .core import Job`
   - `retry.py`: `from .core import Job`
   - `__init__.py`: `from .core import Job, JobQueue`

   This is clean.

   Let's draft the code carefully.

   **core.py**:
   ```python
   """Core data structures and basic queue operations."""
   from dataclasses import dataclass, field
   from typing import Callable, Any, Optional
   from datetime import datetime
   import uuid
   from collections import deque


   @dataclass
   class Job:
       """Represents a unit of work to be executed."""
       id: str = field(default_factory=lambda: str(uuid.uuid4()))
       func: Callable[..., Any] = None
       args: tuple = ()
       kwargs: dict = field(default_factory=dict)
       priority: int = 0
       created_at: datetime = field(default_factory=datetime.now)
       status: str = "pending"
       result: Any = None
       error: Optional[str] = None


   class JobQueue:
       """First-In-First-Out job queue implementation."""

       def __init__(self) -> None:
           self._queue: deque[Job] = deque()

       def enqueue(self, job: Job) -> None:
           """Add a job to the end of the queue."""
           self._queue.append(job)

       def dequeue(self) -> Optional[Job]:
           """Remove and return the first job from the queue."""
           if self._queue:
               return self._queue.popleft()
           return None

       def __len__(self) -> int:
           return len(self._queue)

       def __bool__(self) -> bool:
           return bool(self._queue)
   ```

   **priority.py**:
   ```python
   """Priority queue implementation using heapq."""
   import heapq
   from typing import Optional
   from .core import Job


   class PriorityQueue:
       """Job queue that processes jobs based on priority (lower number = higher priority)."""

       def __init__(self) -> None:
           self._queue: list[tuple[int, int, Job]] = []
           self._counter = 0  # Tie-breaker to maintain FIFO order for same priorities

       def enqueue(self, job: Job) -> None:
           """Add a job to the priority queue."""
           heapq.heappush(self._queue, (job.priority, self._counter, job))
           self._counter += 1

       def dequeue(self) -> Optional[Job]:
           """Remove and return the highest priority job."""
           if self._queue:
               _, _, job = heapq.heappop(self._queue)
               return job
           return None

       def __len__(self) -> int:
           return len(self._queue)

       def __bool__(self) -> bool:
           return bool(self._queue)
   ```

   **retry.py**:
   ```python
   """Retry logic with exponential backoff."""
   import time
   import logging
   from typing import Any
   from .core import Job

   logger = logging.getLogger(__name__)


   def process_with_retry(
       job: Job,
       max_retries: int = 3,
       base_delay: float = 1.0,
       backoff_factor: float = 2.0
   ) -> Any:
       """
       Execute a job with exponential backoff retry logic.

       Args:
           job: The job to execute.
           max_retries: Maximum number of retry attempts.
           base_delay: Initial delay in seconds before first retry.
           backoff_factor: Multiplier for delay between retries.

       Returns:
           The result of the job execution.

       Raises:
           Exception: If the job fails after all retry attempts.
       """
       for attempt in range(max_retries + 1):
           try:
               job.status = "running"
               result = job.func(*job.args, **job.kwargs)
               job.status = "completed"
               job.result = result
               return result
           except Exception as e:
               job.status = "failed"
               job.error = str(e)
               logger.warning(
                   "Job %s failed (attempt %d/%d): %s",
                   job.id, attempt + 1, max_retries + 1, e
               )

               if attempt == max_retries:
                   logger.error("Job %s failed permanently after %d retries.", job.id, max_retries)
                   raise

               delay = base_delay * (backoff_factor ** attempt)
               logger.info("Retrying job %s in %.2f seconds...", job.id, delay)
               time.sleep(delay)
   ```

   **__init__.py**:
   ```python
   """
   Job Queue Package

   A modular job processing system with support for FIFO queues,
   priority scheduling, and automatic retry with exponential backoff.
   """
   from .core import Job, JobQueue

   __all__ = ["Job", "JobQueue"]
   ```

   Wait, should I export `PriorityQueue` and `process_with_retry` in `__init__.py`? The prompt says "Exports: JobQueue, Job". I'll stick to that, but it's common to export everything useful. I'll add a comment or just follow the prompt strictly. I'll keep it as requested.

   Let's double-check requirements:
   1. Maintain all existing functionality: Yes, all classes/functions are present and functional.
   2. Proper imports between modules: Yes, relative imports used correctly.
   3. Clean public API in __init__.py: Yes, exports exactly what's requested.
   4. Each module has a single responsibility: core (data + FIFO), priority (priority logic), retry (retry/backoff), __init__ (API).

   One minor thing: `process_with_retry` in the original was just `def process_with_retry(): ...`. I made it take a job and parameters, which is more realistic. I'll keep it as is since it's a refactoring task and needs to be functional.

   I should also consider if `JobQueue` should be a base class or if `PriorityQueue` should inherit from it. The prompt lists them as separate classes in the original, so I'll keep them separate but with similar interfaces. That's fine.

   Let's verify the code compiles mentally:
   - `core.py`: imports standard lib, defines `Job` and `JobQueue`. No circular imports.
   - `priority.py`: imports `Job` from `core`. Uses `heapq`. Defines `PriorityQueue`.
   - `retry.py`: imports `Job` from `core`. Uses `time`, `logging`. Defines `process_with_retry`.
   - `__init__.py`: imports from `core`. Exports `Job`, `JobQueue`.

   All good. I'll present the files clearly with their contents. I'll also add brief explanations if needed, but the prompt just says "Provide the content of each file."

   I'll format the output as code blocks for each file. I'll make sure type hints are Python 3.9+ compatible (using `list[...]` etc. is fine for modern Python, but I'll stick to `typing` if needed for broader compatibility, though it's fine either way. I'll use `typing` for safety: `from typing import Callable, Any, Optional, List, Tuple` etc. Actually, Python 3.9+ supports built-in generics, but I'll keep it compatible with 3.8+ by using `typing` or just modern syntax. I'll stick to modern syntax as it's standard now.)

   Let's adjust `priority.py` to use `typing` for broader compatibility:
   ```python
   from typing import Optional, List, Tuple
   from .core import Job
   ...
   self._queue: List[Tuple[int, int, Job]] = []
   ```
   Actually, it's fine as is. I'll keep it clean.

   One thing: `process_with_retry` might be better as a decorator, but the prompt shows it as a function. I'll keep it as a function that takes a job.

   Final check of the prompt: "Target structure: queue/ ├── __init__.py # Exports: JobQueue, Job ├── core.py # Job dataclass, basic queue operations ├── retry.py # Retry logic with exponential backoff └── priority.py # Priority queue implementation"

   Everything matches. I'll generate the response.
   I'll structure the output clearly with file names and code blocks.
   I'll add a note about usage if helpful, but keep it concise.
   Ready.✅
   Output matches the response. 
   Self-Correction/Refinement during thought:
   - Should `JobQueue` be in `core.py`? Yes, prompt says "basic queue operations".
   - Should `__init__.py` export only `JobQueue, Job`? Prompt says exactly that. I'll follow it.
   - I'll make sure the retry function doesn't block in a production setting, but for this refactoring exercise, `time.sleep` is standard for sync exponential backoff. I'll add a comment about async/threading if needed, but keep it simple.
   - I'll ensure all type hints are consistent.
   - I'll add `__all__` to each module for good practice.

   Let's write it out. 
   Structure:
   ```
   queue/
   ├── __init__.py
   ├── core.py
   ├── priority.py
   └── retry.py
   ```
   Content matches my drafts. I'll produce it now. 
   One minor adjustment: In `retry.py`, I'll make sure it handles the job status updates correctly and matches typical retry patterns. The implementation looks solid.
   All set. 
   Output generation. 
   [Done] 
   *Self-Correction/Verification during generation prep*:
   - Check `core.py`: `Job` dataclass uses `field(default_factory=datetime.now)` which is correct.
   - Check `priority.py`: `heapq` usage is correct. Lower priority number = higher priority. Counter handles FIFO tie-breaking.
   - Check `retry.py`: Exponential backoff formula `base_delay * (backoff_factor ** attempt)` is correct. Status updates are correct.
   - Check `__init__.py`: Exports match prompt.
   - Imports are all relative and correct.
   - Single responsibility principle is respected.
   - Code is production-ready style (type hints, docstrings, logging).

   Everything looks good. I'll output the files. 
   Output matches the final response. 
   Proceeds. 
   [Output Generation] -> *See response.* 
   *(Note: I'll make sure the code blocks are clearly labeled and ready to copy-paste.)*
   All good. 
   [Final Check of the Prompt]: "Provide the content of each file." -> I will provide exactly that.
   Structure matches. Requirements met. Code is clean. Done. 
   *Output Generation* (matches the response)
   ```python
   # queue/__init__.py
   ...
   # queue/core.py
   ...
   # queue/priority.py
   ...
   # queue/retry.py
   ...
   ```
   Ready. 
   [Proceeds]

</reasoning_content>

<content>
Here is the refactored package structure with each file containing clean, production-ready code that adheres to your requirements.

### `queue/__init__.py`
```python
"""
Job Queue Package

A modular job processing system with support for FIFO queues,
priority scheduling, and automatic retry with exponential backoff.
"""
from .core import Job, JobQueue

__all__ = ["Job", "JobQueue"]
```

### `queue/core.py`
```python
"""Core data structures and basic FIFO queue operations."""
from dataclasses import dataclass, field
from typing import Callable, Any, Optional
from datetime import datetime
import uuid
from collections import deque


@dataclass
class Job:
    """Represents a unit of work to be executed."""
    id: str = field(default_factory=lambda: str(uuid.uuid4()))
    func: Callable[..., Any] = None
    args: tuple = ()
    kwargs: dict = field(default_factory=dict)
    priority: int = 0
    created_at: datetime = field(default_factory=datetime.now)
    status: str = "pending"
    result: Any = None
    error: Optional[str] = None


class JobQueue:
    """First-In-First-Out job queue implementation."""

    def __init__(self) -> None:
        self._queue: deque[Job] = deque()

    def enqueue(self, job: Job) -> None:
        """Add a job to the end of the queue."""
        self._queue.append(job)

    def dequeue(self) -> Optional[Job]:
        """Remove and return the first job from the queue."""
        if self._queue:
            return self._queue.popleft()
        return None

    def __len__(self) -> int:
        return len(self._queue)

    def __bool__(self) -> bool:
        return bool(self._queue)
```

### `queue/priority.py`
```python
"""Priority queue implementation using heapq."""
import heapq
from typing import Optional
from .core import Job


class PriorityQueue:
    """Job queue that processes jobs based on priority (lower number = higher priority)."""

    def __init__(self) -> None:
        # Heap stores tuples of (priority, insertion_order, job)
        self._queue: list[tuple[int, int, Job]] = []
        self._counter = 0  # Tie-breaker to maintain FIFO order for same priorities

    def enqueue(self, job: Job) -> None:
        """Add a job to the priority queue."""
        heapq.heappush(self._queue, (job.priority, self._counter, job))
        self._counter += 1

    def dequeue(self) -> Optional[Job]:
        """Remove and return the highest priority job."""
        if self._queue:
            _, _, job = heapq.heappop(self._queue)
            return job
        return None

    def __len__(self) -> int:
        return len(self._queue)

    def __bool__(self) -> bool:
        return bool(self._queue)
```

### `queue/retry.py`
```python
"""Retry logic with exponential backoff."""
import time
import logging
from typing import Any
from .core import Job

logger = logging.getLogger(__name__)


def process_with_retry(
    job: Job,
    max_retries: int = 3,
    base_delay: float = 1.0,
    backoff_factor: float = 2.0
) -> Any:
    """
    Execute a job with exponential backoff retry logic.

    Args:
        job: The job to execute.
        max_retries: Maximum number of retry attempts.
        base_delay: Initial delay in seconds before first retry.
        backoff_factor: Multiplier for delay between retries.

    Returns:
        The result of the job execution.

    Raises:
        Exception: If the job fails after all retry attempts.
    """
    for attempt in range(max_retries + 1):
        try:
            job.status = "running"
            result = job.func(*job.args, **job.kwargs)
            job.status = "completed"
            job.result = result
            return result
        except Exception as e:
            job.status = "failed"
            job.error = str(e)
            logger.warning(
                "Job %s failed (attempt %d/%d): %s",
                job.id, attempt + 1, max_retries + 1, e
            )

            if attempt == max_retries:
                logger.error("Job %s failed permanently after %d retries.", job.id, max_retries)
                raise

            delay = base_delay * (backoff_factor ** attempt)
            logger.info("Retrying job %s in %.2f seconds...", job.id, delay)
            time.sleep(delay)
```

### Key Design Decisions:
1. **Single Responsibility**: `core.py` handles data models and FIFO operations, `priority.py` isolates heap-based scheduling, and `retry.py` encapsulates fault tolerance logic.
2. **Consistent Interface**: `JobQueue` and `PriorityQueue` share identical public methods (`enqueue`, `dequeue`, `__len__`, `__bool__`), allowing them to be swapped interchangeably in consumer code.
3. **Tie-Breaking in Priority Queue**: Uses a monotonic counter to preserve FIFO ordering for jobs with identical priority values, preventing unpredictable heap behavior.
4. **Clean Public API**: `__init__.py` only exposes the core abstractions (`Job`, `JobQueue`) as requested, keeping advanced features (`PriorityQueue`, `process_with_retry`) accessible via explicit imports when needed.
5. **Production-Ready**: Includes type hints, structured logging, proper error state tracking on the `Job` object, and configurable backoff parameters.
</content>