Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
13c396e
Refactor day_template.py to improve structure and clarity; add submis…
cak Dec 1, 2026
0c1f9aa
Refactor test_day_template.py: streamline tests and update cell markers
cak Dec 1, 2026
b85501d
Update Great Docs configuration to set user guide as homepage
cak Dec 1, 2026
0b8cf28
Add user guide for getting started with Elf
cak Dec 1, 2026
72e149a
Update README.md: streamline instructions for creating and running pu…
cak Dec 1, 2026
eeb6fc6
Refactor day_template.py: update comments for clarity and remove unne…
cak Dec 1, 2026
171c16d
Update Great Docs configuration: streamline settings and adjust user …
cak Dec 1, 2026
af12bec
Update project URLs in pyproject.toml and adjust dependency groups
cak Dec 1, 2026
ee1d4e3
Update CI workflow: enhance documentation build steps and add linting
cak Dec 1, 2026
59e422d
Add command-line workflows documentation
cak Dec 1, 2026
ae89036
Update getting started guide: clarify installation instructions and u…
cak Dec 1, 2026
d31c7d5
Update README.md: revise documentation links, enhance interactive tem…
cak Dec 1, 2026
115fa1e
Enhance documentation across multiple modules: clarify function descr…
cak Dec 1, 2026
1156e7e
Update CI workflow: modify dependency installation and Quarto version…
cak Dec 1, 2026
12d166b
Update great-docs.yml: set dynamic to false and enhance reference sec…
cak Dec 1, 2026
662521f
Refactor AocMessageType and submission handling: remove ALREADY_COMPL…
cak Dec 1, 2026
56855e0
Update user agent URL and enhance AOCClient documentation: clarify re…
cak Dec 1, 2026
d1dc81d
Refactor day_template.py: enhance input handling and session manageme…
cak Dec 1, 2026
b3c4838
Refactor open_page function: enhance error handling for web browser o…
cak Dec 1, 2026
58075c8
Refactor test_check_cached_guesses: rename to ignore ambiguous legacy…
cak Dec 1, 2026
0bf5328
Enhance open command tests: improve output assertions and add browser…
cak Dec 1, 2026
d7f4fd3
Refactor template API mocks: enhance session handling and update test…
cak Dec 1, 2026
20f7e23
Add test for incorrect level submission handling and cache behavior
cak Dec 1, 2026
8c27afd
Update getting started guide: clarify session cookie handling before …
cak Dec 1, 2026
3b0933f
Bump version to 1.2.1 in pyproject.toml
cak Dec 1, 2026
c506f41
Update CHANGELOG for version 1.2.1: document fixes and changes to puz…
cak Dec 1, 2026
c512995
Update README: clarify guess cache behavior and browser launch error …
cak Dec 1, 2026
61b3f61
update lock file
cak Dec 1, 2026
de6ba01
Refactor cache file lock usage: remove stale_after parameter for subm…
cak Dec 1, 2026
6976da8
Refactor cache file locking mechanism: replace stale_after with OS-sp…
cak Dec 1, 2026
496c084
Remove stale_after parameter from cache_file_lock in get_leaderboard …
cak Dec 1, 2026
ad57c58
Refactor SUBMIT handling in day_template: ensure consistent initializ…
cak Dec 1, 2026
b9df012
Refactor cache lock tests: improve timeout handling and reclaim logic
cak Dec 1, 2026
96c1cc2
Refactor test_rendered_template_runs_only_selected_part: simplify par…
cak Dec 1, 2026
516089c
Update getting started guide: clarify submission process and reset be…
cak Dec 1, 2026
30ec504
Update README: clarify operating-system lock behavior and submission …
cak Dec 1, 2026
c6a4f2a
Update CHANGELOG: clarify requirements for newly generated puzzle fil…
cak Dec 1, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions .github/workflows/docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,18 @@ jobs:
- name: Install package and dependencies
run: |
python -m pip install uv
uv sync --locked
uv sync --locked --no-default-groups --group docs

- name: Set up Quarto
uses: quarto-dev/quarto-actions/setup@v2
with:
version: "1.9.38"
version: "1.11.9"

- name: Lint docs
run: uv run --locked --no-default-groups --group docs great-docs lint

- name: Build docs
run: uv run great-docs build
run: uv run --locked --no-default-groups --group docs great-docs build

- name: Save docs artifact
uses: actions/upload-artifact@v7
Expand All @@ -46,7 +49,7 @@ jobs:

- name: How to preview this build locally
if: github.event_name == 'pull_request'
run: uv run great-docs ci notice --run ${{ github.run_id }} --pr ${{ github.event.number }}
run: uv run --locked --no-default-groups --group docs great-docs ci notice --run ${{ github.run_id }} --pr ${{ github.event.number }}

- name: Upload build timings
uses: actions/upload-artifact@v7
Expand Down
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,21 @@

Notable user-facing changes to elf are documented here.

## 1.2.1

### Fixed

- A wrong-level reply no longer blocks a valid Part 2 retry. Elf ignores ambiguous completion entries from older guess caches.
- Newly generated puzzle files require a fresh opt-in for each submission and a recomputed answer after an Advent of Code session change.
- Cache locks now use operating-system locking to prevent a waiting process from deleting another process’s lock.
- `elf open` reports browser launch failures and prints the URL for manual use.

### Changed

- Streamlined the interactive puzzle template and documented the Positron workflow.
- Expanded the getting-started guide, CLI workflows, and Python API reference at [typeerror.com/elf](https://typeerror.com/elf/). The repository moves to [typeerror/elf](https://github.com/typeerror/elf).
- Refreshed locked dependencies and updated the Quarto version used by docs CI.

## 1.2.0 — 2026-11-15

### Added
Expand Down
47 changes: 33 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
# elf: Advent of Code helper for Python

<p align="center">
<img src="https://snally.com/assets/elf-logo.png" width="200" alt="elf logo">
</p>

A fast, modern Advent of Code CLI with caching, guardrails, leaderboards, and a lightweight Python API.

Read the [Elf documentation](https://typeerror.com/elf/) for the getting-started guide, CLI workflows, and Python API reference.

Works on macOS, Linux, and Windows. Most networked commands require an AoC session cookie (`AOC_SESSION`).

<p align="center">
Expand Down Expand Up @@ -123,7 +121,7 @@ If this variable is not set or does not look like an email address, elf falls ba
Your User-Agent header will look like `elf/<version> (you@example.com)`.
This helps Eric identify the person sending the traffic while still including the library name.

If the warning fires, elf instead sends `elf/<version> (+https://github.com/snally-dev/elf)` so AoC still sees a recognizable identifier even without your email.
If the warning fires, elf instead sends `elf/<version> (+https://github.com/typeerror/elf)` so AoC still sees a recognizable identifier even without your email.

## Quick Start

Expand Down Expand Up @@ -214,6 +212,7 @@ Behaviors:
- Year and day are required to avoid accidental submissions.
- Detects locked puzzles (future days or future years) and shows unlock timestamp.
- Identifies too high / too low / duplicate guesses from local cache
- Keeps wrong-level replies out of the guess cache so you can retry after the part unlocks
- Honors and persists AoC's exact cooldown deadline; falls back to 60 seconds if the response format is unfamiliar
- Never sleeps or automatically retries a submission—you remain in control of every POST
- Writes to guess cache automatically (per part)
Expand Down Expand Up @@ -300,6 +299,7 @@ Prints stars for each day.
### `elf open`

Opens puzzle pages in your browser.
If the browser cannot launch, elf prints the URL to stderr and exits with code `1`.

```sh
Usage: elf open [YEAR] [DAY]
Expand Down Expand Up @@ -346,7 +346,7 @@ do not fail the command; cache-access errors return exit code `1`.
- Guess history stored under: `<cache>/accounts/<fingerprint>/<year>/<day>/guesses.csv`
- Private leaderboard JSON is scoped by event, board ID, and account/view-key fingerprint and cached for at least 15 minutes
- New cache files use private permissions where supported and are replaced atomically to avoid partial files after interruption
- Cross-process lock files prevent concurrent leaderboard refreshes and lost guess-history writes; abandoned locks expire safely
- Operating-system locks serialize leaderboard refreshes and guess-history writes. A process exit releases its locks automatically. Finish any running elf 1.2.0 commands before using 1.2.1 against the same cache.
- Duplicate/high/low guesses are short‑circuited locally when possible
- Cooldown responses retain AoC's server-provided retry deadline; historical entries without one use a 60-second fallback
- Guardrails rely on your local guess history only (new machines/cleared cache = fresh)
Expand Down Expand Up @@ -393,22 +393,22 @@ print(status)

### Interactive Puzzle Template

Create a solution file from elf's [interactive template](https://github.com/snally-dev/elf/blob/main/elf/templates/day_template.py):
Create a solution file from elf's [interactive template](https://github.com/typeerror/elf/blob/main/elf/templates/day_template.py):

```sh
elf new 2025 1
elf new 2025 2 --output solutions/2025/day02.py
```

By default this creates `YEAR/dayDD.py`; parent directories are created as needed, and elf refuses to overwrite an existing path. Configure `AOC_SESSION` as described above, open the generated file in Positron, VS Code, Spyder, or another Python editor, and run the `# %%` cells from top to bottom. The first input cell retrieves the puzzle input through elf's private, account-scoped cache instead of writing input into your project tree. `raw`, `lines`, `data`, `part1_answer`, and `part2_answer` remain at module scope so they appear in the active session's Variables pane and can be inspected between runs.
By default, Elf creates `YEAR/dayDD.py`, creating parent directories as needed. It refuses to overwrite existing files.

The same file works as a normal script:
We recommend [Positron](https://positron.posit.co/download.html) for working through puzzles interactively. Open your puzzle project, select the Python interpreter where you installed elf, and run individual `# %%` cells. Use the Variables pane to inspect `raw`, `lines`, `data`, and your answers as you work.

```sh
python 2025/day01.py
```
Set `PART` to `1` or `2` in **Setup**. To try an example, paste it into `sample` in **Load Input** and set `USE_SAMPLE = True`. Run **Setup** through the selected part.

Running it in a separate terminal process does not populate an IDE's existing interactive session because the Variables pane reflects only its active Python process. Answer submission is intentionally commented out in the final cell; run a submission line manually only after checking the corresponding answer.
For a real submission, set `USE_SAMPLE = False`, rerun **Setup** through the selected part, and inspect the answer. Set `SUBMIT = True` in the console, then run **Submit**. The file also runs with `python 2025/day01.py` and defaults to submission off.

If your Advent of Code session changes, rerun from **Load Input** through the selected part before submitting. The template checks that the session used to load the input matches the session used to submit the answer. Each submission requires a fresh opt-in.

### Puzzle Helpers

Expand Down Expand Up @@ -528,7 +528,26 @@ Alternatively, you can still run:
python -m pytest
```

Running `python -m pytest` directly requires `pytest` to be installed in your environment. Install it via `pip install pytest>=9.0.1` (or use `uv sync --group dev` and `uv run pytest`) before running the command outside of `uv`.
Running `python -m pytest` directly requires `pytest` to be installed in your environment. Install it via `pip install "pytest>=9.0.1"` (or use `uv sync --group dev` and `uv run pytest`) before running the command outside of `uv`.

### Build the documentation

Install [Quarto](https://quarto.org/docs/get-started/), then run these commands from the repository root.

```sh
uv sync --locked --group docs
uv run --locked --group docs great-docs lint
uv run --locked --group docs great-docs build
uv run --locked --group docs great-docs preview
```

Edit the guides in `user_guide/` and the API reference in the public Python docstrings. The rendered site is written to `great-docs/_site/`.

### Hosting and releases

The docs workflow deploys to GitHub Pages from `typeerror/elf`. To serve it at `https://typeerror.com/elf/`, configure `typeerror.com` on the account’s Pages site. In the `elf` repository’s Pages settings, select **GitHub Actions** as the source and leave the project-level custom domain blank so the project inherits the account domain. [GitHub Pages custom domains](https://docs.github.com/en/pages/configuring-a-custom-domain-for-your-github-pages-site/about-custom-domains-and-github-pages)

The release workflow uses PyPI Trusted Publishing. Configure the `elf` project on PyPI with owner `typeerror`, repository `elf`, workflow `publish.yml`, and environment `pypi`. [PyPI Trusted Publishing setup](https://docs.pypi.org/trusted-publishers/adding-a-publisher/)

## Special Thanks

Expand Down
49 changes: 30 additions & 19 deletions elf/answer.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ class AocMessageType(Enum):
TOO_HIGH = auto()
TOO_LOW = auto()
RECENT_SUBMISSION = auto()
ALREADY_COMPLETED = auto()
INCORRECT = auto()
WRONG_LEVEL = auto()
UNEXPECTED = auto()
Expand All @@ -86,13 +85,15 @@ def classify_message(content: str) -> AocMessageType:
if not content:
return AocMessageType.EMPTY

# Specific outcomes take precedence when an article also contains the
# generic incorrect-answer or wrong-level text.
checks: list[tuple[str, AocMessageType]] = [
("That's the right answer", AocMessageType.CORRECT),
("too high", AocMessageType.TOO_HIGH),
("too low", AocMessageType.TOO_LOW),
("You gave an answer too recently", AocMessageType.RECENT_SUBMISSION),
("Did you already complete it", AocMessageType.ALREADY_COMPLETED),
("You don't seem to be solving the right level", AocMessageType.WRONG_LEVEL),
("Did you already complete it", AocMessageType.WRONG_LEVEL),
("That's not the right answer", AocMessageType.INCORRECT),
]

Expand Down Expand Up @@ -163,7 +164,7 @@ def submit_answer(
# result. Guess-cache writes use their own shorter-lived lock.
submission_lock = cache_file.with_name(f"{cache_file.name}.submission")
try:
with cache_file_lock(submission_lock, timeout=30.0, stale_after=60.0):
with cache_file_lock(submission_lock, timeout=30.0):
if cache_file.exists():
cached = check_cached_guesses(
year=year,
Expand Down Expand Up @@ -198,7 +199,7 @@ def submit_to_aoc(
answer: int | str,
session_token: str,
) -> SubmissionResult:
# --- Network layer --------------------------------------------------------
"""Submit once, interpret the response, and record the outcome."""

try:
with AOCClient(session_token=session_token) as client:
Expand All @@ -211,8 +212,6 @@ def submit_to_aoc(
except httpx.RequestError as exc:
raise SubmissionError(f"Network error while connecting to Advent of Code: {exc}") from exc

# --- HTTP status handling -------------------------------------------------

if response.status_code == 404:
if "unlocks it for you" in response.text:
raise SubmissionError("Puzzle not yet unlocked.")
Expand Down Expand Up @@ -241,12 +240,11 @@ def submit_to_aoc(
"Update AOC_SESSION with a valid 'session' cookie from your browser."
)

# Extract <article> content
# The outcome appears in the article, apart from page navigation.
parser = AocResponseParser()
parser.feed(response.text)
content = parser.text()

# Determine result type
message_type = classify_message(content)
retry_at: datetime | None = None
match message_type:
Expand All @@ -266,12 +264,16 @@ def submit_to_aoc(
status = SubmissionStatus.WAIT
retry_at = _parse_wait_retry_at(content) or datetime.now(UTC) + WAIT_CACHE_TTL
message = _wait_message(retry_at, cached=False)
case AocMessageType.ALREADY_COMPLETED:
message = get_already_completed_message()
status = SubmissionStatus.COMPLETED
case AocMessageType.WRONG_LEVEL:
message = get_wrong_level_message()
status = SubmissionStatus.INCORRECT
# AoC has not judged this answer. The same guess may be valid
# once its part is available.
return SubmissionResult(
guess=answer,
result=SubmissionStatus.INCORRECT,
message=get_wrong_level_message(),
is_correct=False,
is_cached=False,
)
case AocMessageType.INCORRECT:
message = get_incorrect_answer_message(answer)
status = SubmissionStatus.INCORRECT
Expand Down Expand Up @@ -317,6 +319,7 @@ def write_guess_cache(
session_token: str | None = None,
retry_at: datetime | None = None,
) -> None:
"""Record a guess without exposing a partially rewritten CSV to readers."""
cache_file = get_cache_guess_file(year, day, session_token)

timestamp = datetime.now(UTC).isoformat()
Expand All @@ -330,7 +333,7 @@ def write_guess_cache(
}

try:
with cache_file_lock(cache_file, timeout=10.0, stale_after=30.0):
with cache_file_lock(cache_file, timeout=10.0):
existing = cache_file.read_text(encoding="utf-8") if cache_file.exists() else ""
atomic_write_text(cache_file, _updated_guess_cache(existing, row))
except Exception as exc:
Expand All @@ -345,6 +348,12 @@ def check_cached_guesses(
numeric_answer: int | None,
session_token: str | None = None,
) -> CachedGuessCheck:
"""Resolve the strongest locally known outcome for a guess in one part.

Completion takes precedence over active cooldown, duplicate, and numeric
bounds checks. An exact match for a previously correct answer retains
its correct status. UNKNOWN leaves the submission decision to the caller.
"""
guesses = read_guesses(year, day, session_token=session_token)
now = datetime.now(UTC)

Expand All @@ -357,6 +366,10 @@ def check_cached_guesses(
for g in guesses:
if g.part != level:
continue
# Older versions recorded ambiguous wrong-level replies as COMPLETED.
# Only a cached correct answer establishes that the part is solved.
if g.status is SubmissionStatus.COMPLETED:
continue

# A later response supersedes an earlier local cooldown entry.
if g.status is SubmissionStatus.WAIT and _wait_is_active(g, now):
Expand All @@ -374,9 +387,7 @@ def check_cached_guesses(
duplicate_guess = g

match g:
# A correct answer proves the part is complete just as surely as a
# later "already completed" response.
case Guess(status=SubmissionStatus.CORRECT | SubmissionStatus.COMPLETED):
case Guess(status=SubmissionStatus.CORRECT):
completed_guess = g

# Bounds checking (int only)
Expand Down Expand Up @@ -435,7 +446,7 @@ def check_cached_guesses(
message=get_cached_duplicate_message(answer, duplicate_guess),
)

# Infer bounds
# A rejected boundary also rules out guesses farther from the answer.
if numeric_answer is not None:
match (highest_low, lowest_high):
case (h_low, _) if (
Expand All @@ -459,7 +470,6 @@ def check_cached_guesses(
message=get_cached_high_message(answer, l_high),
)

# No bounds found
return CachedGuessCheck(
guess=answer,
previous_guess=None,
Expand Down Expand Up @@ -512,6 +522,7 @@ def _parse_wait_retry_at(content: str, *, now: datetime | None = None) -> dateti


def _retry_at(guess: Guess) -> datetime:
"""Recover the retry deadline for current and legacy guess logs."""
if guess.retry_at is not None:
return (
guess.retry_at
Expand Down
14 changes: 11 additions & 3 deletions elf/aoc_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from .constants import VERSION

_user_agent_prefix = f"elf/{VERSION}"
_default_user_agent = "+https://github.com/snally-dev/elf"
_default_user_agent = "+https://github.com/typeerror/elf"


def _build_http_client() -> httpx.Client:
Expand Down Expand Up @@ -58,6 +58,12 @@ def _validate_user_agent(user_agent: str | None) -> bool:


class AOCClient:
"""Transport for AoC endpoints with explicit HTTP client ownership.

Use as a context manager to close the default client. When a caller
supplies an HTTP client, the caller owns its configuration and lifetime.
"""

def __init__(
self,
session_token: str | None,
Expand Down Expand Up @@ -85,8 +91,9 @@ def _get_with_retries(
backoff: float = 0.5,
params: dict[str, str] | None = None,
) -> httpx.Response:
"""
Basic retry wrapper for idempotent GETs to smooth over transient network hiccups.
"""Retry transport failures on GET with exponential backoff.

HTTP responses are returned for the endpoint to interpret.
"""
attempt = 0
while True:
Expand Down Expand Up @@ -124,6 +131,7 @@ def submit_answer(self, year: int, day: int, answer: str, part: int) -> httpx.Re
"""
Submit an answer for a specific year, day, and part.
"""
# Use a single POST because a timeout can occur after AoC accepts it.
data = {"level": str(part), "answer": answer}
response = self._post(f"/{year}/day/{day}/answer", data=data)
return response
Expand Down
Loading
Loading