Manual
Almnck.
Price: 50ⓐ

Celestial Date-Stamping Implementation Plan

For Claude: REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.

Goal: Store date-specific sun and moon images so each page displays the sky from its publication or almanac day, with phase-accurate default moons for historical dates.

Architecture: a-celestial gains --date and --generate-defaults flags, saving images to date-keyed directories under assets/celestial/ with a latest symlink. celestial.js resolves the page’s date, loads date-specific images with fallback to phase-accurate defaults, and uses a hybrid Date for position calculation. frontpage-nav.js calls an exposed API on HTMX swap.

Tech Stack: Python (PIL/Pillow, numpy), JavaScript (vanilla), NASA SDO + Dial-A-Moon APIs

Important: Be kind to NASA’s servers. Rate-limit all HTTP requests (1–2 second delays between fetches). Use polite User-Agent headers. Never hammer endpoints in loops without backoff.


Task 1: Restructure assets/celestial/ directory layout

Move existing root-level images into a dated directory and create the latest symlink.

Files: - Move: assets/celestial/sun.png → assets/celestial/2026-02-17/sun.png - Move: assets/celestial/moon.png → assets/celestial/2026-02-17/moon.png - Create: assets/celestial/latest → symlink to 2026-02-17/ - Create: assets/celestial/default/ (empty, placeholder for Task 3)

Step 1: Create directory structure and move files

cd $ALMANACK_ROOT
mkdir -p assets/celestial/2026-02-17
mkdir -p assets/celestial/default
git mv assets/celestial/sun.png assets/celestial/2026-02-17/sun.png
git mv assets/celestial/moon.png assets/celestial/2026-02-17/moon.png
cd assets/celestial && ln -s 2026-02-17 latest && cd ../..

Step 2: Update .gitignore if needed

Check that assets/celestial/ subdirectories are tracked. The symlink latest should be committed to git (git stores symlinks as text pointers).

Step 3: Commit

git add assets/celestial/
git commit -m "refactor: move celestial images to date-keyed directory with latest symlink"

Task 2: Update a-celestial script for date-keyed output

Modify bin/a-celestial to support --date, --set-latest, and --generate-defaults flags. The default (no --date) uses today’s date and updates the latest symlink.

Files: - Modify: bin/a-celestial

Step 1: Add --date and --set-latest arguments

Add to the argument parser:

parser.add_argument("--date", type=str, default=None,
    help="Date to fetch images for (YYYY-MM-DD). Default: today.")
parser.add_argument("--set-latest", action="store_true",
    help="Update the 'latest' symlink (automatic when --date is omitted)")
parser.add_argument("--generate-defaults", action="store_true",
    help="Generate phase-accurate default moon images and a generic sun")

Step 2: Refactor get_moon_frame() to accept a date string

Change signature to get_moon_frame(date_str=None). When date_str is provided, use it instead of datetime.now():

def get_moon_frame(date_str=None):
    """Query the Dial-A-Moon API for frame number and metadata."""
    if date_str:
        time_str = date_str + "T12:00"
    else:
        now = datetime.now(timezone.utc)
        time_str = now.strftime("%Y-%m-%dT%H:%M")
    url = DIALAMOON_API.format(time=time_str)
    data = fetch_json(url, "Dial-A-Moon API")
    # ... rest unchanged

Step 3: Refactor download_moon() to derive plain TIF URL from API response

Currently MOON_PLAIN_BASE is hardcoded to the 2026 visualization (a005587). The Dial-A-Moon API returns the visualization base URL in the image URL field, which varies by year. Extract it dynamically:

def get_plain_tif_url(api_data):
    """Derive the plain TIF URL from the Dial-A-Moon API response.

    The API returns a JPEG URL like:
      https://svs.gsfc.nasa.gov/vis/a000000/a005500/a005587/frames/730x730_1x1_30p/moon.0613.jpg
    We need:
      https://svs.gsfc.nasa.gov/vis/a000000/a005500/a005587/frames/1920x1080_16x9_30p/plain/moon.0613.tif

    Returns (url, frame_number) or (None, frame_number) if plain frames unavailable.
    """
    import re
    img_url = api_data["image"]["url"]
    filename = api_data["image"]["filename"]
    frame = int(filename.split(".")[1])

    # Extract visualization base path
    m = re.match(r"(https://svs\.gsfc\.nasa\.gov/vis/a\d+/a\d+/a\d+/)", img_url)
    if not m:
        return None, frame

    vis_base = m.group(1)
    plain_url = f"{vis_base}frames/1920x1080_16x9_30p/plain/moon.{frame:04d}.tif"
    return plain_url, frame


def download_moon(api_data, output_dir):
    """Download the plain moon TIF for the given API response.

    Falls back to the JPEG if plain TIF is unavailable (older visualizations).
    """
    plain_url, frame = get_plain_tif_url(api_data)

    if plain_url:
        try:
            data = fetch_url(plain_url, f"Moon frame {frame} (plain TIF with alpha)")
            path = output_dir / "moon_raw.tif"
            path.write_bytes(data)
            return path
        except SystemExit:
            print(f"    Plain TIF unavailable, falling back to JPEG")

    # Fallback: download the JPEG from the API response
    jpg_url = api_data["image"]["url"]
    data = fetch_url(jpg_url, f"Moon frame {frame} (JPEG fallback)")
    path = output_dir / "moon_raw.jpg"
    path.write_bytes(data)
    return path

Note: fetch_url currently calls sys.exit(1) on failure. Change it to raise an exception instead, and handle sys.exit only in main(). Or wrap the TIF attempt in a try/except that catches SystemExit.

Step 4: Add historical SDO sun download

The SDO browse archive works for 2025–2026 but returns 403 for some older years. Add a function that tries the archive, falling back gracefully:

SDO_BROWSE_BASE = "https://sdo.gsfc.nasa.gov/assets/img/browse"

def download_sun_for_date(date_str, output_dir):
    """Download an SDO AIA 304 image for a specific date.

    Scrapes the browse archive directory listing to find the image
    closest to noon UTC. Falls back to None if the archive is
    unavailable for that date.

    Be kind: one directory listing + one image download, max.
    """
    import re
    import time

    parts = date_str.split("-")
    year, month, day = parts[0], parts[1], parts[2]

    browse_url = f"{SDO_BROWSE_BASE}/{year}/{month}/{day}/"
    print(f"    Checking SDO archive for {date_str}...")

    try:
        req = Request(browse_url, headers=REQUEST_HEADERS)
        with urlopen(req, timeout=30) as resp:
            html = resp.read().decode()
    except URLError as e:
        print(f"    SDO archive unavailable for {date_str}: {e}")
        return None

    # Find all 1024_0304 images
    pattern = rf"{year}{month}{day}_(\d{{6}})_1024_0304\.jpg"
    timestamps = re.findall(pattern, html)
    if not timestamps:
        print(f"    No AIA 304 images found for {date_str}")
        return None

    # Pick the one closest to noon UTC (120000)
    closest = min(timestamps, key=lambda t: abs(int(t) - 120000))
    img_filename = f"{year}{month}{day}_{closest}_1024_0304.jpg"
    img_url = f"{browse_url}{img_filename}"

    time.sleep(1)  # Be kind to NASA

    data = fetch_url(img_url, f"SDO AIA 304 ({date_str}, {closest} UTC)")
    path = output_dir / "sun_raw.jpg"
    path.write_bytes(data)
    return path

Step 5: Add symlink management

def update_latest_symlink(celestial_dir, date_str):
    """Update the 'latest' symlink to point at the given date directory."""
    latest = celestial_dir / "latest"
    if latest.is_symlink() or latest.exists():
        latest.unlink()
    latest.symlink_to(date_str)
    print(f"  Updated latest → {date_str}")

Step 6: Refactor main() for date-keyed output

def main():
    parser = argparse.ArgumentParser(...)
    parser.add_argument("--sun-only", action="store_true")
    parser.add_argument("--moon-only", action="store_true")
    parser.add_argument("--preview", action="store_true")
    parser.add_argument("--date", type=str, default=None,
        help="Date to fetch (YYYY-MM-DD). Default: today.")
    parser.add_argument("--set-latest", action="store_true",
        help="Update 'latest' symlink (automatic without --date)")
    parser.add_argument("--generate-defaults", action="store_true",
        help="Generate phase-accurate default moon images")
    args = parser.parse_args()

    if args.generate_defaults:
        generate_defaults()
        return

    almanack_root = os.environ.get("ALMANACK_ROOT")
    base_dir = Path(almanack_root) / "assets" / "celestial" if almanack_root else Path("assets") / "celestial"

    # Determine date
    if args.date:
        date_str = args.date
        auto_latest = False
    else:
        date_str = datetime.now().strftime("%Y-%m-%d")
        auto_latest = True

    output_dir = base_dir / date_str
    output_dir.mkdir(parents=True, exist_ok=True)

    do_sun = not args.moon_only
    do_moon = not args.sun_only
    results = []

    with tempfile.TemporaryDirectory(prefix="celestial-") as tmp:
        tmp_dir = Path(tmp)

        if do_sun:
            print("\n☉ Sun")
            if args.date:
                raw = download_sun_for_date(date_str, tmp_dir)
                if raw is None:
                    print("    Using 'latest' sun instead")
                    raw = download_sun(tmp_dir)
            else:
                raw = download_sun(tmp_dir)
            sun_path = output_dir / "sun.png"
            process_sun(raw, sun_path)
            results.append(sun_path)

        if do_moon:
            print("\n☽ Moon")
            import time
            time.sleep(1)  # Be kind between sun and moon requests
            frame, moon_data = get_moon_frame(date_str if args.date else None)
            raw = download_moon(moon_data, tmp_dir)
            moon_path = output_dir / "moon.png"
            process_moon(raw, moon_path, moon_data)
            results.append(moon_path)

    # Update symlink
    if auto_latest or args.set_latest:
        update_latest_symlink(base_dir, date_str)

    print("\n✓ Done!")
    for p in results:
        print(f"  {p}")

    if args.preview and results:
        import subprocess
        subprocess.run(["open", "-a", "Preview"] + [str(p) for p in results])

Step 7: Test manually

source bin/a-activate
# Verify today's date works (should be identical to old behaviour, but date-keyed)
a-celestial --preview
ls -la assets/celestial/latest
ls assets/celestial/$(date +%Y-%m-%d)/

# Verify --date works for a known frontpage date
a-celestial --date 2026-01-26 --moon-only --preview
ls assets/celestial/2026-01-26/

Step 8: Commit

git add bin/a-celestial
git commit -m "feat: a-celestial --date for historical fetches, date-keyed output with latest symlink"

Task 3: Generate default phase-accurate moon images

Add --generate-defaults to a-celestial that fetches eight representative moon phases from Dial-A-Moon and a generic sun.

Files: - Modify: bin/a-celestial

Step 1: Define phase representatives

We need eight specific dates where the moon is at each major phase. Use 2026 dates (known to have plain TIF frames). Compute from the synodic period:

# Reference new moon: 2026-01-29 (known from astronomy tables)
# Synodic period: 29.530588 days
# Phases are: new (0), waxing-crescent (~3.7d), first-quarter (~7.4d),
#   waxing-gibbous (~11.1d), full (~14.8d), waning-gibbous (~18.4d),
#   last-quarter (~22.1d), waning-crescent (~25.8d)

PHASE_DATES = {
    "new":              "2026-01-29",
    "waxing-crescent":  "2026-02-02",
    "first-quarter":    "2026-02-05",
    "waxing-gibbous":   "2026-02-09",
    "full":             "2026-02-12",
    "waning-gibbous":   "2026-02-16",
    "last-quarter":     "2026-02-20",
    "waning-crescent":  "2026-02-24",
}

Verify these against the Dial-A-Moon API before hardcoding — adjust dates if the API reports a significantly different phase.

Step 2: Implement generate_defaults()

def generate_defaults():
    """Generate default celestial images: one sun + eight phase moons."""
    import time

    almanack_root = os.environ.get("ALMANACK_ROOT")
    base_dir = Path(almanack_root) / "assets" / "celestial" if almanack_root else Path("assets") / "celestial"
    default_dir = base_dir / "default"
    default_dir.mkdir(parents=True, exist_ok=True)

    with tempfile.TemporaryDirectory(prefix="celestial-") as tmp:
        tmp_dir = Path(tmp)

        # Generic sun (use latest SDO image)
        print("\n☉ Default Sun")
        raw = download_sun(tmp_dir)
        sun_path = default_dir / "sun.png"
        process_sun(raw, sun_path)

        # Phase-accurate moons
        for phase_name, date_str in PHASE_DATES.items():
            print(f"\n☽ Default Moon — {phase_name} ({date_str})")
            time.sleep(2)  # Be kind to NASA between each fetch
            frame, moon_data = get_moon_frame(date_str)
            raw = download_moon(moon_data, tmp_dir)
            moon_path = default_dir / f"moon-{phase_name}.png"
            process_moon(raw, moon_path, moon_data)

    print("\n✓ Default images generated!")
    print(f"  {default_dir}/")
    for p in sorted(default_dir.iterdir()):
        print(f"    {p.name}")

Step 3: Run it

a-celestial --generate-defaults --preview
ls assets/celestial/default/

Verify all nine images look correct (1 sun + 8 moon phases).

Step 4: Commit

git add assets/celestial/default/ bin/a-celestial
git commit -m "feat: generate phase-accurate default moon images for historical dates"

Task 4: Update celestial.js for date-aware image loading

Modify celestial.js to resolve the page date, load date-specific images with fallback, and use a hybrid Date for position calculations.

Files: - Modify: assets/js/celestial.js

Step 1: Add date resolution function

/**
 * Resolve which date's celestial images this page should display.
 *
 * Priority:
 * 1. ?fp= query parameter (front-page navigation context)
 * 2. Almanac-day from the page (parsed from #frontpage-date or URL path)
 * 3. Today's date
 *
 * Returns "YYYY-MM-DD" string.
 */
function resolvePageDate() {
  // 1. Check ?fp= parameter
  var fp = new URLSearchParams(window.location.search).get("fp");
  if (fp && /^\d{4}-\d{2}-\d{2}$/.test(fp)) return fp;

  // 2. Parse almanac-day from #frontpage-date
  //    The element contains e.g. "Wednesday<br>January 23rd<br>06024"
  //    or on the front page: "Tuesday<br>February 17th<br>02026"
  var el = document.getElementById("frontpage-date");
  if (el) {
    var text = el.textContent || el.innerText || "";
    var parsed = parseDateFromDisplay(text);
    if (parsed) return parsed;
  }

  // 3. Today
  var now = new Date();
  return now.getFullYear() + "-" +
    String(now.getMonth() + 1).padStart(2, "0") + "-" +
    String(now.getDate()).padStart(2, "0");
}

/**
 * Parse a display date like "Wednesday January 23rd 06024" into "YYYY-MM-DD".
 * Handles Long Now year format (leading 0) and BCE dates.
 * Returns null if unparseable.
 */
function parseDateFromDisplay(text) {
  // Normalise: collapse whitespace/newlines
  text = text.replace(/\s+/g, " ").trim();

  var months = {
    january: 1, february: 2, march: 3, april: 4,
    may: 5, june: 6, july: 7, august: 8,
    september: 9, october: 10, november: 11, december: 12
  };

  // Pattern: "DayName Month DayNum[suffix] Year"
  // Year may start with 0 (Long Now) and may end with "BCE"
  var m = text.match(/(\w+)\s+(\d+)\w*\s+(\d+)\s*(BCE)?/i);
  if (!m) return null;

  var monthName = m[1].toLowerCase();
  var month = months[monthName];
  if (!month) return null;

  var day = parseInt(m[2], 10);
  var year = parseInt(m[3], 10);
  if (m[4]) year = -year; // BCE

  return year + "-" +
    String(month).padStart(2, "0") + "-" +
    String(day).padStart(2, "0");
}

Step 2: Add moon phase classification for default fallback

/**
 * Classify moon age (0–29.5 days) into one of eight phase names.
 * Used to select the correct default moon image.
 */
function moonPhaseClass(date) {
  var refNewMoon = new Date(Date.UTC(2000, 0, 6, 18, 14));
  var daysSinceRef = (date - refNewMoon) / 86400000;
  var synodicPeriod = 29.530588;
  var age = ((daysSinceRef % synodicPeriod) + synodicPeriod) % synodicPeriod;
  var eighth = synodicPeriod / 8;

  if (age < eighth * 0.5) return "new";
  if (age < eighth * 1.5) return "waxing-crescent";
  if (age < eighth * 2.5) return "first-quarter";
  if (age < eighth * 3.5) return "waxing-gibbous";
  if (age < eighth * 4.5) return "full";
  if (age < eighth * 5.5) return "waning-gibbous";
  if (age < eighth * 6.5) return "last-quarter";
  if (age < eighth * 7.5) return "waning-crescent";
  return "new";
}

Step 3: Add image loading with fallback

/**
 * Load celestial images for a given date string.
 * Falls back to /static/celestial/default/ on 404.
 */
function loadCelestialImages(sunImg, moonImg, dateStr) {
  var datePath = "/static/celestial/" + dateStr + "/";
  var defaultPath = "/static/celestial/default/";

  // Sun: try date-specific, fall back to default
  sunImg.onerror = function () {
    sunImg.onerror = null; // prevent infinite loop
    sunImg.src = defaultPath + "sun.png";
  };
  sunImg.src = datePath + "sun.png";

  // Moon: try date-specific, fall back to phase-accurate default
  moonImg.onerror = function () {
    moonImg.onerror = null;
    // Parse date to compute phase
    var parts = dateStr.split("-");
    var d = new Date(parseInt(parts[0], 10), parseInt(parts[1], 10) - 1, parseInt(parts[2], 10), 12, 0, 0);
    var phase = moonPhaseClass(d);
    moonImg.src = defaultPath + "moon-" + phase + ".png";
  };
  moonImg.src = datePath + "moon.png";
}

Step 4: Add hybrid date construction

/**
 * Build a hybrid Date: the page's calendar day with the browser's current time.
 * This makes position calculations reflect the page's epoch (solar declination,
 * moon synodic position) while the bodies still move across the arc in real time.
 */
function hybridDate(dateStr) {
  var parts = dateStr.split("-");
  var year = parseInt(parts[0], 10);
  var month = parseInt(parts[1], 10) - 1;
  var day = parseInt(parts[2], 10);
  var now = new Date();
  return new Date(year, month, day, now.getHours(), now.getMinutes(), now.getSeconds());
}

Step 5: Expose __celestialSetDate and refactor init()

Refactor init() to store references to the images and current date, then expose a function for external callers:

function init() {
  var masthead = document.querySelector(".masthead");
  var frontispiece = document.querySelector(".frontispiece");
  if (!masthead || !frontispiece) return;

  var currentDateStr = resolvePageDate();

  var sunImg = createCelestialImg("/static/celestial/latest/sun.png", "Current sun (SDO AIA 304)");
  var moonImg = createCelestialImg("/static/celestial/latest/moon.png", "Current moon (NASA SVS)");

  masthead.insertBefore(moonImg, masthead.firstChild);
  masthead.insertBefore(sunImg, masthead.firstChild);

  // Load date-specific images
  loadCelestialImages(sunImg, moonImg, currentDateStr);

  function update() {
    var now = window.__celestialTime || hybridDate(currentDateStr);
    var sun = sunPosition(now);
    var moon = moonPosition(now);

    var sunPos = skyToMasthead(sun.altitude, sun.azimuth);
    var moonPos = skyToMasthead(moon.altitude, moon.azimuth);

    positionBody(sunImg, sunPos, frontispiece, masthead);
    positionBody(moonImg, moonPos, frontispiece, masthead);

    // Expose sun's page-pixel position for sundial lighting
    var mhRect2 = masthead.getBoundingClientRect();
    var sunRect = sunImg.getBoundingClientRect();
    window.__sunPosition = {
      x: sunRect.left + sunRect.width / 2 + window.scrollX,
      y: sunRect.top + sunRect.height / 2 + window.scrollY,
      visible: sunPos.opacity > 0.1,
    };
  }

  var loaded = 0;
  function onLoad() {
    loaded++;
    if (loaded >= 2) update();
  }
  sunImg.addEventListener("load", onLoad);
  moonImg.addEventListener("load", onLoad);

  window.addEventListener("resize", update);
  window.__celestialUpdate = update;
  setInterval(update, 60 * 1000);

  // Expose date-change API for HTMX navigation
  window.__celestialSetDate = function (dateStr) {
    currentDateStr = dateStr;
    loaded = 0;
    loadCelestialImages(sunImg, moonImg, dateStr);
    // Images will trigger onLoad → update() when they arrive
  };
}

Step 6: Test manually in browser

make serve
# Visit http://localhost:1969/ — should show today's sun/moon from latest/
# Visit http://localhost:1969/?fp=2026-01-26 — should try 2026-01-26/ images
# Visit an article page — should use almanac-day images
# Open console, run: window.__celestialSetDate("2026-02-13")
# Should swap images and reposition

Step 7: Commit

git add assets/js/celestial.js
git commit -m "feat: celestial.js date-aware image loading with hybrid positioning and phase fallback"

Task 5: Update frontpage-nav.js to notify celestial on HTMX swap

Files: - Modify: assets/js/frontpage-nav.js

Step 1: Add __celestialSetDate call to onSwapComplete()

In the existing onSwapComplete function, after the updateNavigation(fp) call:

// Update celestial images for the new frontpage date
if (window.__celestialSetDate) {
  window.__celestialSetDate(fp);
}

Step 2: Test HTMX navigation

make serve
# Visit http://localhost:1969/
# Click "Previously" to navigate to an older front page
# Verify the sun/moon images change (or fall back to defaults)
# Check browser console for 404s → should gracefully fall back

Step 3: Commit

git add assets/js/frontpage-nav.js
git commit -m "feat: notify celestial.js on HTMX navigation to swap sky images"

Task 6: Update zodiac.js to use hybrid date

The zodiac constellation positions should also reflect the page’s date, not just the current time.

Files: - Modify: assets/js/zodiac.js

Step 1: Read the celestial date and use hybrid date

In the render() function, replace:

const now = window.__celestialTime || new Date();

With:

// Use hybrid date: page's calendar day + browser's clock time
// __celestialDateStr is set by celestial.js and updated on navigation
var dateStr = window.__celestialDateStr;
var now;
if (window.__celestialTime) {
  now = window.__celestialTime;
} else if (dateStr) {
  var parts = dateStr.split("-");
  var clock = new Date();
  now = new Date(parseInt(parts[0], 10), parseInt(parts[1], 10) - 1,
                 parseInt(parts[2], 10), clock.getHours(),
                 clock.getMinutes(), clock.getSeconds());
} else {
  now = new Date();
}

Step 2: Expose currentDateStr from celestial.js

In celestial.js, after setting currentDateStr, add:

window.__celestialDateStr = currentDateStr;

And in __celestialSetDate:

window.__celestialDateStr = dateStr;

Also trigger a zodiac re-render:

if (window.__zodiacRender) window.__zodiacRender();

Step 3: Test

make serve
# Navigate to an article with a different almanac-day
# Check that zodiac constellations shift appropriately for the season

Step 4: Commit

git add assets/js/celestial.js assets/js/zodiac.js
git commit -m "feat: zodiac constellations use hybrid date matching celestial.js"

Task 7: Update URL references

Update all references from /static/celestial/sun.png to /static/celestial/latest/sun.png.

Files: - Modify: assets/js/celestial.js (already handled in Task 4 — createCelestialImg calls use latest/)

Step 1: Search for any remaining references

cd $ALMANACK_ROOT
grep -rn "celestial/sun\|celestial/moon" --include="*.js" --include="*.html" --include="*.css" --include="*.py" src/ assets/

Update any found references to use /static/celestial/latest/ as the initial/fallback path.

Step 2: Verify build copies correctly

make build
ls web/static/celestial/
ls web/static/celestial/latest/
ls web/static/celestial/default/

shutil.copytree should dereference the latest symlink into a real directory containing the actual files.

Step 3: Commit

git add -A
git commit -m "fix: update all celestial URL references to date-keyed paths"

Task 8: Backfill existing front-page dates

Fetch real NASA images for the front-page dates we already have.

Files: - Create: assets/celestial/2026-01-26/sun.png, moon.png - Create: assets/celestial/2026-02-13/sun.png, moon.png

Step 1: Fetch images for each known front-page date

source bin/a-activate

# Be kind: wait between fetches
a-celestial --date 2026-01-26
sleep 5
a-celestial --date 2026-02-13

Step 2: Also fetch for almanac-days in the NASA data range (2024–2026)

Check which almanac-days are fetchable:

# These almanac-days are in the NASA range:
# 2024-01-01 (look-back-up) — SDO might be 403, moon should work
# 2026-01-03 (regolith-with-latitude)
# 2026-01-14 (logic-day)
# 2026-01-26 (logiebair) — already done above
# 1921-02-13 (kropotkins-funeral) — moon only (old vis, no plain TIF; will fall back to JPEG)

a-celestial --date 2026-01-03 --moon-only
sleep 5
a-celestial --date 2026-01-14 --moon-only
sleep 5
a-celestial --date 2024-01-01 --moon-only
sleep 5
a-celestial --date 1921-02-13 --moon-only

For dates where the sun fails to download, they’ll gracefully fall back to the default sun in the browser.

Step 3: Verify and commit

ls assets/celestial/*/
git add assets/celestial/
git commit -m "feat: backfill celestial images for existing frontpage and almanac dates"

Task 9: Write tests

Add tests for the date resolution and phase classification logic.

Files: - Create: src/tests/test_celestial.py

Step 1: Write unit tests for the Python changes

Since the a-celestial changes are in a standalone script (not a Django management command), we can test the key functions by importing from it. However, it’s simpler to test the JS logic. For Python, we test the URL construction and symlink logic:

"""Tests for celestial date-stamping logic."""

import os
import pytest
from pathlib import Path


class TestCelestialDirectoryStructure:
    """Verify the celestial directory layout is correct."""

    def test_latest_symlink_exists(self):
        root = os.environ.get("ALMANACK_ROOT", ".")
        latest = Path(root) / "assets" / "celestial" / "latest"
        assert latest.is_symlink(), "assets/celestial/latest should be a symlink"

    def test_latest_points_to_date_directory(self):
        root = os.environ.get("ALMANACK_ROOT", ".")
        latest = Path(root) / "assets" / "celestial" / "latest"
        target = os.readlink(latest)
        # Target should be a YYYY-MM-DD directory name
        import re
        assert re.match(r"\d{4}-\d{2}-\d{2}", target), \
            f"latest symlink should point to a YYYY-MM-DD dir, got: {target}"

    def test_latest_has_sun_and_moon(self):
        root = os.environ.get("ALMANACK_ROOT", ".")
        latest = Path(root) / "assets" / "celestial" / "latest"
        assert (latest / "sun.png").exists(), "latest/sun.png missing"
        assert (latest / "moon.png").exists(), "latest/moon.png missing"

    def test_default_directory_has_phase_moons(self):
        root = os.environ.get("ALMANACK_ROOT", ".")
        default = Path(root) / "assets" / "celestial" / "default"
        expected_phases = [
            "moon-new.png", "moon-waxing-crescent.png",
            "moon-first-quarter.png", "moon-waxing-gibbous.png",
            "moon-full.png", "moon-waning-gibbous.png",
            "moon-last-quarter.png", "moon-waning-crescent.png",
        ]
        for phase_file in expected_phases:
            assert (default / phase_file).exists(), f"default/{phase_file} missing"

    def test_default_has_sun(self):
        root = os.environ.get("ALMANACK_ROOT", ".")
        default = Path(root) / "assets" / "celestial" / "default"
        assert (default / "sun.png").exists(), "default/sun.png missing"

Step 2: Run tests

make test-unit

Expected: Tests pass if the celestial images have been generated. Tests will fail if run before Tasks 1–3 and 8 (the image generation tasks). This is intentional — they verify the deployment state.

Step 3: Commit

git add src/tests/test_celestial.py
git commit -m "test: verify celestial directory structure and image availability"

Task 10: Final integration test and cleanup

Step 1: Full build and verify

make sync && make build
# Check the built site
ls web/static/celestial/
ls web/static/celestial/latest/
ls web/static/celestial/default/
ls web/static/celestial/2026-02-13/

Step 2: Test in browser

make serve
  • Visit / — sun and moon from today (latest)
  • Visit /?fp=2026-01-26 — sun and moon from Jan 26
  • Visit /?fp=2026-02-13 — sun and moon from Feb 13
  • Visit an article directly (e.g. /6024/1/26/logiebair/) — uses almanac-day
  • Visit an article for a historical date — should fall back to phase-accurate default moon
  • Navigate with prev/next — images should swap
  • Check that sun rides higher for summer dates, lower for winter dates
  • Check that moon position shifts with date (different point in synodic cycle)

Step 3: Run full test suite

make test

Step 4: Clean up old root-level images if any remain

# Verify no orphaned files
ls -la assets/celestial/*.png 2>/dev/null
# Should be empty — all images now in subdirectories

Step 5: Final commit

git add -A
git commit -m "feat: celestial date-stamping complete — per-page skyseals with phase-accurate fallbacks"