Manual
Almnck.
Price: 50ⓐ

Horizon Sphere Implementation Plan

Status: Implemented. This plan was executed on 2026-02-17. The document below reflects the original plan; see the design document for as-built details including post-implementation interaction redesigns.

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

Goal: Replace the flat sine-arc celestial system with a 3D horizon sphere that shows sun and moon at correct astronomical positions, with an interactive armillary mode on click-drag.

Architecture: Single canvas in the masthead renders a 3D oblate dome. celestial.js is rewritten from scratch with astronomy, projection, drawing, interaction, and the public API. zodiac.js is adapted to render onto the shared canvas using the sphere projection. The existing <img> DOM approach is replaced entirely with canvas drawing.

Tech Stack: Vanilla JS (canvas 2D), CSS transitions, existing Playwright test infrastructure.

Design doc: doc/plans/2026-02-17-horizon-sphere.md

Reference implementation: doc/process/demos/horizon-realistic.html (working demo with all rendering code)


Pre-flight

Before starting, activate the environment and create a feature branch:

source bin/a-activate
git checkout -b feat/horizon-sphere

Run the existing test suite to establish a green baseline:

make test

Expected: all tests pass. Note the celestial animation browser tests — they will need updating later.


Task 1: Add Canvas Element to Template

Files: - Modify: src/almnck/templates/base.html:32-33

Step 1: Add the canvas element inside the masthead div

In src/almnck/templates/base.html, add a canvas element as the first child of .masthead:

    <div class="masthead">
        <canvas class="horizon-canvas" aria-hidden="true"></canvas>
        <div class="meta-left">{% block meta_left %}Since 4000 BCE{% endblock %}</div>

The canvas is aria-hidden (decorative) and will be sized/positioned by CSS and JS.

Step 2: Verify template renders

make serve &
curl -s http://localhost:1969/ | grep -c 'horizon-canvas'

Expected: 1

Step 3: Commit

git add src/almnck/templates/base.html
git commit -m "feat(template): add horizon-canvas element to masthead"

Task 2: Add Canvas CSS

Files: - Modify: assets/css/almanack.css

Step 1: Add horizon-canvas styles after the existing .celestial-body block (after line ~130)

Find the block starting with /* Celestial bodies: sun and moon */ (line 122) and replace through the .celestial-body rule with:

/* Celestial canvas: 3D horizon sphere behind the masthead text */
.horizon-canvas {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    z-index: 1;
}

/* When interactive (armillary mode), canvas captures drags */
.horizon-canvas.interactive {
    pointer-events: auto;
    cursor: grab;
    z-index: 10;
}

.horizon-canvas.dragging {
    cursor: grabbing;
}

/* Legacy: keep .celestial-body for any transition period */
.celestial-body {
    position: absolute;
    pointer-events: none;
    z-index: 0;
    user-select: none;
    -webkit-user-select: none;
    will-change: left, top, opacity;
}

Step 2: Add expandable masthead transition

Find .masthead { (line 105) and add a transition property after overflow: visible;:

    transition: padding-top 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94),
                padding-bottom 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94);

Add a new rule after the .masthead block:

.masthead.expanded {
    padding-top: 4em;
    padding-bottom: 3em;
}

Step 3: Update mobile breakpoint

Find the mobile hide rule (line ~993):

    /* Hide celestial bodies and zodiac on mobile — no room for the arc */
    .celestial-body,
    .zodiac-band {
        display: none !important;
    }

Replace with:

    /* Hide celestial display on mobile — no room for the sphere */
    .celestial-body,
    .zodiac-band,
    .horizon-canvas {
        display: none !important;
    }

Step 4: Verify styles load

make build
grep -c 'horizon-canvas' web/static/css/almanack.css

Expected: at least 3 (the three rules).

Step 5: Commit

git add assets/css/almanack.css
git commit -m "feat(css): horizon-canvas styles, expandable masthead transition, mobile hide"

Task 3: Write the New celestial.js — Astronomy Module

This is the core rewrite. We build celestial.js in stages, testing each layer. The new file replaces the old one entirely.

Files: - Create: assets/js/celestial.js (overwrite existing)

Step 1: Write the astronomy and projection core

Create the new assets/js/celestial.js with the IIFE shell, constants, astronomy functions, and 3D projection. These are ported from the demo (doc/process/demos/horizon-realistic.html lines 310–375) with the bug fixes applied.

/**
 * celestial.js — 3D horizon sphere for the Almanack masthead.
 *
 * Renders sun and moon at their astronomical positions on a 3D oblate
 * dome centred on the "Almnck." frontispiece. Click-drag reveals an
 * armillary sphere with diurnal paths, celestial equator, and cardinal
 * points. Time sweeps forward while expanded; eases back on release.
 *
 * Replaces the previous flat sine-arc system.
 *
 * Astronomy: simplified models (not an ephemeris). Solar declination from
 * day-of-year, hour angle from local clock time, latitude fixed at 40°N.
 * Moon position from synodic offset. Good enough for an almanack.
 *
 * Date-aware: resolves the page's almanac-day and loads date-specific
 * images from /static/celestial/{YYYY-MM-DD}/. Falls back to phase-accurate
 * defaults. On HTMX date navigation, bodies animate along sphere paths.
 */

(function () {
  "use strict";

  // ===== Constants =====

  var DEG = Math.PI / 180;
  var TAU = Math.PI * 2;
  var BODY_SIZE_SUN = 14;        // px base radius for sun image
  var BODY_SIZE_MOON = 10;       // px base radius for moon image
  var ARC_DURATION = 1200;       // ms, HTMX date-change animation
  var TIME_SPEED = 0.12;         // hours per frame during time sweep
  var DEFAULT_ROT = [-0.15, 0];  // default view: due south, slight down-tilt
  var DWELL_MS = 800;            // ms to linger after mouseup before collapsing

  // Reference epoch for moon age: 2000-01-06 18:14 UTC (new moon)
  // Days from that reference to 2026-01-01 00:00 UTC ≈ 9126.24
  var MOON_REF_DAYS_TO_2026 = 9491.24;
  var SYNODIC_PERIOD = 29.530588;

  // ===== Reduced motion =====

  function prefersReducedMotion() {
    return window.matchMedia &&
      window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  }

  // ===== Easing =====

  function easeInOutCubic(t) {
    return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
  }

  // ===== Date utilities =====

  /**
   * Resolve which date this page should display.
   * Priority: ?fp= param > #frontpage-date element > today.
   */
  function resolvePageDate() {
    var fp = new URLSearchParams(window.location.search).get("fp");
    if (fp && /^\d{4}-\d{2}-\d{2}$/.test(fp)) return fp;

    var el = document.getElementById("frontpage-date");
    if (el) {
      var parsed = parseDateFromDisplay(el.textContent || "");
      if (parsed) return parsed;
    }

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

  function parseDateFromDisplay(text) {
    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
    };
    var m = text.match(/(\w+)\s+(\d+)\w*\s+(\d+)\s*(BCE)?/i);
    if (!m) return null;
    var month = months[m[1].toLowerCase()];
    if (!month) return null;
    var day = parseInt(m[2], 10);
    var year = parseInt(m[3], 10);
    if (m[4]) year = -year;
    return year + "-" + String(month).padStart(2, "0") + "-" + String(day).padStart(2, "0");
  }

  /**
   * Day of year from a "YYYY-MM-DD" string.
   */
  function dayOfYear(dateStr) {
    var parts = dateStr.split("-");
    var y = parseInt(parts[0], 10), mo = parseInt(parts[1], 10) - 1, d = parseInt(parts[2], 10);
    var jan1 = new Date(y, 0, 1);
    var date = new Date(y, mo, d);
    return Math.floor((date - jan1) / 86400000) + 1;
  }

  /**
   * Current fractional hour from the browser clock.
   */
  function currentHour() {
    var now = new Date();
    return now.getHours() + now.getMinutes() / 60 + now.getSeconds() / 3600;
  }

  // ===== Astronomy =====

  /**
   * Sun position: altitude and azimuth in degrees.
   * hour: fractional hour (0–24+, continuous — no wrapping needed)
   * doy: day of year (1–366)
   */
  function sunPosition(hour, doy) {
    var lat = 40 * DEG;
    var decl = -23.44 * DEG * Math.cos((TAU / 365) * (doy + 10));
    var ha = (hour - 12) * 15 * DEG;
    var sinAlt = Math.sin(lat) * Math.sin(decl) +
                 Math.cos(lat) * Math.cos(decl) * Math.cos(ha);
    var alt = Math.asin(sinAlt) / DEG;
    var cosAz = (Math.sin(decl) - Math.sin(lat) * sinAlt) /
                (Math.cos(lat) * Math.cos(Math.asin(sinAlt)));
    var az = Math.acos(Math.max(-1, Math.min(1, cosAz))) / DEG;
    if (Math.sin(ha) > 0) az = 360 - az;
    return { alt: alt, az: az };
  }

  /**
   * Moon position: altitude, azimuth, and synodic age in days.
   * Uses continuous fractional day count to avoid Date-object discontinuities.
   */
  function moonPosition(hour, doy) {
    var lat = 40 * DEG;
    var daysFromRef = MOON_REF_DAYS_TO_2026 + (doy - 1) + (hour / 24);
    var age = ((daysFromRef % SYNODIC_PERIOD) + SYNODIC_PERIOD) % SYNODIC_PERIOD;
    var offset = age * (360 / SYNODIC_PERIOD);
    var sunDecl = -23.44 * DEG * Math.cos((TAU / 365) * (doy + 10));
    var moonDecl = sunDecl + 5 * DEG * Math.sin(age / SYNODIC_PERIOD * TAU);
    var moonHA = ((hour - 12) * 15 + offset) * DEG;
    // Normalise to [-π, π]
    moonHA = moonHA % TAU;
    if (moonHA > Math.PI) moonHA -= TAU;
    if (moonHA < -Math.PI) moonHA += TAU;
    var sinAlt = Math.sin(lat) * Math.sin(moonDecl) +
                 Math.cos(lat) * Math.cos(moonDecl) * Math.cos(moonHA);
    var alt = Math.asin(sinAlt) / DEG;
    var cosAz = (Math.sin(moonDecl) - Math.sin(lat) * sinAlt) /
                (Math.cos(lat) * Math.cos(Math.asin(sinAlt)));
    var az = Math.acos(Math.max(-1, Math.min(1, cosAz))) / DEG;
    if (Math.sin(moonHA) > 0) az = 360 - az;
    return { alt: alt, az: az, age: age };
  }

  /**
   * Moon phase class from age. Used for default image fallback.
   */
  function moonPhaseClass(age) {
    var eighth = SYNODIC_PERIOD / 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";
  }

  // ===== 3D Projection =====

  var _yScale = 1; // vertical compression (set per renderScene call)

  /**
   * Convert altitude/azimuth (degrees) to unit-sphere XYZ.
   * Y = up, X = west (negative = east), Z = north (negative = south).
   */
  function altAzToXYZ(alt, az) {
    var a = alt * DEG, b = az * DEG;
    return {
      x: -Math.sin(b) * Math.cos(a),
      y: Math.sin(a),
      z: Math.cos(b) * Math.cos(a)
    };
  }

  /**
   * Project a 3D point onto screen coordinates.
   * viewRot: [tiltX, spinY] in radians.
   * Returns {sx, sy, z, scale} where z is depth after rotation.
   */
  function project(x, y, z, cx, cy, radius, viewRot) {
    // Rotate around Y (horizontal spin)
    var cosY = Math.cos(viewRot[1]), sinY = Math.sin(viewRot[1]);
    var x1 = x * cosY - z * sinY, z1 = x * sinY + z * cosY;
    // Rotate around X (vertical tilt)
    var cosX = Math.cos(viewRot[0]), sinX = Math.sin(viewRot[0]);
    var y2 = y * cosX - z1 * sinX, z2 = y * sinX + z1 * cosX;
    // Perspective
    var scale = 1.8 / (1.8 + z2 * 0.3);
    return {
      sx: cx + x1 * radius * scale,
      sy: cy - y2 * radius * scale * _yScale,
      z: z2,
      scale: scale
    };
  }

  // ===== Image loading =====

  function celestialImageUrls(dateStr) {
    var path = "/static/celestial/" + dateStr + "/";
    return { sunUrl: path + "sun.png", moonUrl: path + "moon.png" };
  }

  function loadCelestialImages(sunImg, moonImg, dateStr) {
    var defaultPath = "/static/celestial/default/";
    var urls = celestialImageUrls(dateStr);

    sunImg.onerror = function () {
      sunImg.onerror = null;
      sunImg.src = defaultPath + "sun.png";
    };
    sunImg.src = urls.sunUrl;

    moonImg.onerror = function () {
      moonImg.onerror = null;
      var doy = dayOfYear(dateStr);
      var moon = moonPosition(12, doy);
      var phase = moonPhaseClass(moon.age);
      moonImg.src = defaultPath + "moon-" + phase + ".png";
    };
    moonImg.src = urls.moonUrl;
  }

  function preloadCelestialImages(dateStr) {
    var defaultPath = "/static/celestial/default/";
    var urls = celestialImageUrls(dateStr);

    function loadOne(primaryUrl, fallbackFn) {
      return new Promise(function (resolve) {
        var img = new Image();
        img.onload = function () { resolve(img.src); };
        img.onerror = function () {
          img.onerror = null;
          var fb = fallbackFn();
          var img2 = new Image();
          img2.onload = function () { resolve(img2.src); };
          img2.onerror = function () { resolve(img2.src); };
          img2.src = fb;
        };
        img.src = primaryUrl;
      });
    }

    return Promise.all([
      loadOne(urls.sunUrl, function () { return defaultPath + "sun.png"; }),
      loadOne(urls.moonUrl, function () {
        var doy = dayOfYear(dateStr);
        var moon = moonPosition(12, doy);
        return defaultPath + "moon-" + moonPhaseClass(moon.age) + ".png";
      })
    ]);
  }

  // ===== Drawing primitives =====

  function drawRing(ctx, cx, cy, radius, viewRot, tiltDeg, color, lineWidth, dashed) {
    ctx.beginPath();
    ctx.strokeStyle = color;
    ctx.lineWidth = lineWidth;
    if (dashed) ctx.setLineDash(dashed); else ctx.setLineDash([]);
    for (var i = 0; i <= 120; i++) {
      var angle = (i / 120) * TAU;
      var x = Math.cos(angle), z = Math.sin(angle);
      var tilt = tiltDeg * DEG;
      var y = z * Math.sin(tilt);
      z = z * Math.cos(tilt);
      var p = project(x, y, z, cx, cy, radius, viewRot);
      if (i === 0) ctx.moveTo(p.sx, p.sy); else ctx.lineTo(p.sx, p.sy);
    }
    ctx.stroke();
    ctx.setLineDash([]);
  }

  function drawHorizonDisc(ctx, cx, cy, radius, viewRot, color) {
    ctx.beginPath();
    for (var i = 0; i <= 80; i++) {
      var angle = (i / 80) * TAU;
      var p = project(Math.cos(angle) * 0.95, 0, Math.sin(angle) * 0.95, cx, cy, radius, viewRot);
      if (i === 0) ctx.moveTo(p.sx, p.sy); else ctx.lineTo(p.sx, p.sy);
    }
    ctx.closePath();
    ctx.fillStyle = color;
    ctx.fill();
  }

  function drawBody(ctx, alt, az, cx, cy, radius, viewRot, color, glowColor, size, img) {
    var pos = altAzToXYZ(alt, az);
    var p = project(pos.x, pos.y, pos.z, cx, cy, radius, viewRot);
    var r = size * p.scale;
    // Glow halo (uses its own alpha, not affected by caller's globalAlpha)
    if (glowColor) {
      var prevAlpha = ctx.globalAlpha;
      ctx.globalAlpha = 1;
      var grad = ctx.createRadialGradient(p.sx, p.sy, r * 0.3, p.sx, p.sy, r * 5);
      grad.addColorStop(0, glowColor);
      grad.addColorStop(1, "transparent");
      ctx.fillStyle = grad;
      ctx.fillRect(p.sx - r * 5, p.sy - r * 5, r * 10, r * 10);
      ctx.globalAlpha = prevAlpha;
    }
    // Body: image or fallback disc
    if (img && img.complete && img.naturalWidth > 0) {
      var imgSize = r * 2;
      ctx.drawImage(img, p.sx - imgSize / 2, p.sy - imgSize / 2, imgSize, imgSize);
    } else {
      ctx.beginPath();
      ctx.arc(p.sx, p.sy, r, 0, TAU);
      ctx.fillStyle = color;
      ctx.fill();
    }
    return { sx: p.sx, sy: p.sy }; // return screen position for __sunPosition
  }

  function drawHorizonGlow(ctx, alt, az, cx, cy, radius, viewRot, colorBase, intensity) {
    var strength;
    if (alt > 15) return;
    if (alt > 0) strength = (15 - alt) / 15 * 0.5;
    else if (alt > -25) strength = (25 + alt) / 25;
    else return;
    strength *= intensity;
    if (strength < 0.01) return;
    var pos = altAzToXYZ(0, az);
    var p = project(pos.x * 0.88, 0, pos.z * 0.88, cx, cy, radius, viewRot);
    var glowR = radius * 0.9 * Math.max(0.35, strength);
    var grad = ctx.createRadialGradient(p.sx, p.sy, 0, p.sx, p.sy, glowR);
    grad.addColorStop(0, colorBase.replace("ALPHA", (strength * 0.6).toFixed(3)));
    grad.addColorStop(0.35, colorBase.replace("ALPHA", (strength * 0.25).toFixed(3)));
    grad.addColorStop(0.7, colorBase.replace("ALPHA", (strength * 0.08).toFixed(3)));
    grad.addColorStop(1, "transparent");
    ctx.fillStyle = grad;
    ctx.fillRect(p.sx - glowR, p.sy - glowR, glowR * 2, glowR * 2);
  }

  // ===== Armillary drawing =====

  function drawGreatCircle(ctx, cx, cy, radius, viewRot, pole, color, lineWidth, dashed) {
    var arbitrary = Math.abs(pole.y) < 0.9 ? { x: 0, y: 1, z: 0 } : { x: 1, y: 0, z: 0 };
    var ux = pole.y * arbitrary.z - pole.z * arbitrary.y;
    var uy = pole.z * arbitrary.x - pole.x * arbitrary.z;
    var uz = pole.x * arbitrary.y - pole.y * arbitrary.x;
    var ulen = Math.sqrt(ux * ux + uy * uy + uz * uz);
    ux /= ulen; uy /= ulen; uz /= ulen;
    var vx = pole.y * uz - pole.z * uy;
    var vy = pole.z * ux - pole.x * uz;
    var vz = pole.x * uy - pole.y * ux;

    ctx.beginPath();
    ctx.strokeStyle = color;
    ctx.lineWidth = lineWidth;
    if (dashed) ctx.setLineDash(dashed); else ctx.setLineDash([]);
    var steps = 120;
    for (var i = 0; i <= steps; i++) {
      var angle = (i / steps) * TAU;
      var x = Math.cos(angle) * ux + Math.sin(angle) * vx;
      var y = Math.cos(angle) * uy + Math.sin(angle) * vy;
      var z = Math.cos(angle) * uz + Math.sin(angle) * vz;
      var p = project(x, y, z, cx, cy, radius, viewRot);
      if (i === 0) ctx.moveTo(p.sx, p.sy); else ctx.lineTo(p.sx, p.sy);
    }
    ctx.stroke();
    ctx.setLineDash([]);
  }

  function drawDiurnalPath(ctx, cx, cy, radius, viewRot, posFn, doy, color, lineWidth, dashed) {
    ctx.beginPath();
    ctx.strokeStyle = color;
    ctx.lineWidth = lineWidth;
    if (dashed) ctx.setLineDash(dashed); else ctx.setLineDash([]);
    var steps = 96;
    for (var i = 0; i <= steps; i++) {
      var hour = (i / steps) * 24;
      var pos = posFn(hour, doy);
      var xyz = altAzToXYZ(pos.alt, pos.az);
      var p = project(xyz.x, xyz.y, xyz.z, cx, cy, radius, viewRot);
      if (i === 0) ctx.moveTo(p.sx, p.sy); else ctx.lineTo(p.sx, p.sy);
    }
    ctx.stroke();
    ctx.setLineDash([]);
  }

  function drawArmillary(ctx, cx, cy, radius, viewRot, alpha, hour, doy) {
    if (alpha < 0.005) return;

    // Celestial equator (pole = NCP at lat 40°N)
    var ncp = altAzToXYZ(40, 0);
    drawGreatCircle(ctx, cx, cy, radius, viewRot, ncp,
      "rgba(184,137,46," + (0.45 * alpha).toFixed(3) + ")", 1.2 * alpha + 0.3);

    // Meridian ring (pole = East)
    var eastPole = altAzToXYZ(0, 90);
    drawGreatCircle(ctx, cx, cy, radius * 1.02, viewRot, eastPole,
      "rgba(184,137,46," + (0.25 * alpha).toFixed(3) + ")", 0.8 * alpha + 0.2);

    // Sun's diurnal path
    drawDiurnalPath(ctx, cx, cy, radius, viewRot, sunPosition, doy,
      "rgba(210,150,40," + (0.5 * alpha).toFixed(3) + ")", 1.5 * alpha + 0.5, [5, 4]);

    // Moon's diurnal path
    drawDiurnalPath(ctx, cx, cy, radius, viewRot, moonPosition, doy,
      "rgba(130,145,190," + (0.35 * alpha).toFixed(3) + ")", 1.0 * alpha + 0.3, [3, 4]);

    // Horizon ring reinforcement
    drawRing(ctx, cx, cy, radius, viewRot, 0,
      "rgba(160,135,85," + (0.3 * alpha).toFixed(3) + ")", alpha * 0.8);

    // Cardinal rivets
    [0, 90, 180, 270].forEach(function (az) {
      var pos = altAzToXYZ(0, az);
      var p = project(pos.x, 0, pos.z, cx, cy, radius, viewRot);
      ctx.beginPath();
      ctx.arc(p.sx, p.sy, (2.5 + alpha) * p.scale, 0, TAU);
      ctx.fillStyle = "rgba(184,137,46," + (0.6 * alpha).toFixed(3) + ")";
      ctx.fill();
    });

    // Cardinal labels
    if (alpha > 0.3) {
      var la = ((alpha - 0.3) / 0.7 * 0.6).toFixed(3);
      ctx.font = "bold 10px sans-serif";
      ctx.textAlign = "center";
      ctx.textBaseline = "middle";
      [{ az: 0, l: "N" }, { az: 90, l: "E" }, { az: 180, l: "S" }, { az: 270, l: "W" }].forEach(function (c) {
        var pos = altAzToXYZ(0, c.az);
        var p = project(pos.x * 1.08, 0, pos.z * 1.08, cx, cy, radius, viewRot);
        ctx.fillStyle = "rgba(184,137,46," + la + ")";
        ctx.fillText(c.l, p.sx, p.sy);
      });
    }
  }

  // ===== Scene composition =====

  /**
   * Render the complete scene onto a canvas context.
   *
   * state: { rot, hour, armillaryAlpha }
   * doy: day of year
   * sunImg, moonImg: Image objects
   * yScaleVal: vertical compression (<1 = oblate dome)
   *
   * Returns: { sunScreen } with page-relative sun position for sundial.
   */
  function renderScene(ctx, W, H, cx, cy, radius, state, doy, sunImg, moonImg, yScaleVal) {
    _yScale = yScaleVal || 1;
    var viewRot = state.rot;
    var hour = state.hour;
    var armAlpha = state.armillaryAlpha;
    var sun = sunPosition(hour, doy);
    var moon = moonPosition(hour, doy);

    ctx.clearRect(0, 0, W, H);

    // Sky wash
    var skyB = Math.max(0, Math.min(1, (sun.alt + 10) / 50));
    var skyGrad = ctx.createLinearGradient(cx, 0, cx, H);
    skyGrad.addColorStop(0, "rgba(160,180,210," + (0.04 + skyB * 0.06).toFixed(3) + ")");
    skyGrad.addColorStop(0.6, "transparent");
    ctx.fillStyle = skyGrad;
    ctx.fillRect(0, 0, W, H);

    // Horizon glow
    drawHorizonGlow(ctx, sun.alt, sun.az, cx, cy, radius, viewRot, "rgba(210,150,40,ALPHA)", 1.2);
    drawHorizonGlow(ctx, moon.alt, moon.az, cx, cy, radius, viewRot, "rgba(130,145,190,ALPHA)", 0.4);

    // Horizon disc + ring
    var dA = 0.06 + armAlpha * 0.05;
    drawHorizonDisc(ctx, cx, cy, radius, viewRot, "rgba(184,157,106," + dA.toFixed(3) + ")");
    var hA = 0.2 + armAlpha * 0.5;
    drawRing(ctx, cx, cy, radius, viewRot, 0, "rgba(160,135,85," + hA.toFixed(3) + ")", 0.7 + armAlpha * 1.8);

    // Armillary
    drawArmillary(ctx, cx, cy, radius, viewRot, armAlpha, hour, doy);

    // Zodiac constellations (call into zodiac.js if available)
    if (window.__zodiacRenderOnSphere) {
      window.__zodiacRenderOnSphere(ctx, cx, cy, radius, viewRot, hour, doy, _yScale);
    }

    // Bodies
    var sunF = sun.alt > 5 ? 1 : sun.alt > -15 ? (sun.alt + 15) / 20 : 0.08;
    var moonF = moon.alt > 5 ? 1 : moon.alt > -15 ? (moon.alt + 15) / 20 : 0.08;

    ctx.save();
    ctx.globalAlpha = Math.max(0.05, sunF * 0.85);
    var sunScreen = drawBody(ctx, sun.alt, sun.az, cx, cy, radius, viewRot,
      "rgba(195,120,20,0.9)",
      "rgba(230,165,40," + (sunF * 0.2).toFixed(3) + ")", BODY_SIZE_SUN, sunImg);
    ctx.restore();

    ctx.save();
    ctx.globalAlpha = Math.max(0.05, moonF * 0.8);
    drawBody(ctx, moon.alt, moon.az, cx, cy, radius, viewRot,
      "rgba(120,130,155,0.8)",
      "rgba(150,165,195," + (moonF * 0.12).toFixed(3) + ")", BODY_SIZE_MOON, moonImg);
    ctx.restore();

    return {
      sunScreen: sunScreen,
      sunVisible: sunF > 0.1
    };
  }

  // ===== Interaction & state machine =====

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

    // Check if hidden on mobile
    if (window.getComputedStyle(canvas).display === "none") return;

    var currentDateStr = resolvePageDate();
    var doy = dayOfYear(currentDateStr);

    // Preload images
    var sunImg = new Image();
    var moonImg = new Image();
    loadCelestialImages(sunImg, moonImg, currentDateStr);

    // Expose date for zodiac
    window.__celestialDateStr = currentDateStr;

    // --- State ---
    var state = {
      rot: [DEFAULT_ROT[0], DEFAULT_ROT[1]],
      hour: currentHour(),
      realHour: currentHour(),
      armillaryAlpha: 0,
      targetAlpha: 0,
      dragging: false
    };

    // --- Canvas sizing ---
    function sizeCanvas() {
      var rect = masthead.getBoundingClientRect();
      var dpr = window.devicePixelRatio || 1;
      var w = Math.round(rect.width), h = Math.round(rect.height);
      canvas.style.width = w + "px";
      canvas.style.height = h + "px";
      canvas.width = w * dpr;
      canvas.height = h * dpr;
      canvas.getContext("2d").scale(dpr, dpr);
      canvas._w = w;
      canvas._h = h;
    }

    // --- Sphere geometry (computed from layout) ---
    function computeGeometry() {
      var fpRect = frontispiece.getBoundingClientRect();
      var mhRect = masthead.getBoundingClientRect();
      var fpWidth = fpRect.width;
      var radius = (fpWidth / 2) * 1.15;
      var cx = (fpRect.left - mhRect.left) + fpWidth / 2;
      var cy = (fpRect.top - mhRect.top) + fpRect.height / 2;
      var headroom = cy;
      var yScale = Math.min(1, (headroom * 0.85) / radius);
      yScale = Math.max(0.3, yScale);
      return { cx: cx, cy: cy, radius: radius, yScale: yScale };
    }

    // --- Render ---
    function doRender() {
      var W = canvas._w, H = canvas._h;
      if (!W || !H) return;
      var geo = computeGeometry();
      var ctx = canvas.getContext("2d");
      var result = renderScene(ctx, W, H, geo.cx, geo.cy, geo.radius,
        state, doy, sunImg, moonImg, geo.yScale);

      // Expose sun position in page coords for sundial lighting
      if (result && result.sunScreen) {
        var canvasRect = canvas.getBoundingClientRect();
        window.__sunPosition = {
          x: canvasRect.left + result.sunScreen.sx + window.scrollX,
          y: canvasRect.top + result.sunScreen.sy + window.scrollY,
          visible: result.sunVisible
        };
      }
    }

    // --- Animation loop ---
    var animRaf = null;
    var returningRot = false;
    var timeAnimating = false;
    var timeReturning = false;

    function animateFrame() {
      var changed = false;

      // Armillary alpha
      var diff = state.targetAlpha - state.armillaryAlpha;
      if (Math.abs(diff) > 0.005) {
        var speed = diff > 0 ? 0.08 : 0.025;
        state.armillaryAlpha += diff * speed + Math.sign(diff) * 0.003;
        state.armillaryAlpha = Math.max(0, Math.min(1, state.armillaryAlpha));
        changed = true;
      } else {
        state.armillaryAlpha = state.targetAlpha;
      }

      // Rotation return
      if (returningRot) {
        var d0 = DEFAULT_ROT[0] - state.rot[0];
        var d1 = DEFAULT_ROT[1] - state.rot[1];
        if (Math.abs(d0) > 0.002 || Math.abs(d1) > 0.002) {
          state.rot[0] += d0 * 0.06;
          state.rot[1] += d1 * 0.06;
          changed = true;
        } else {
          state.rot[0] = DEFAULT_ROT[0];
          state.rot[1] = DEFAULT_ROT[1];
          returningRot = false;
        }
      }

      // Time sweep (continuous, no wrapping)
      if (timeAnimating) {
        state.hour += TIME_SPEED;
        changed = true;
      }

      // Time return (ease to realHour via shortest path)
      if (timeReturning) {
        var target = state.realHour;
        while (target < state.hour - 12) target += 24;
        while (target > state.hour + 12) target -= 24;
        var dh = target - state.hour;
        if (Math.abs(dh) > 0.02) {
          state.hour += dh * 0.06;
          changed = true;
        } else {
          state.hour = state.realHour;
          timeReturning = false;
        }
      }

      doRender();

      if (changed) {
        animRaf = requestAnimationFrame(animateFrame);
      } else {
        animRaf = null;
      }
    }

    function startAnimation() {
      if (!animRaf) animRaf = requestAnimationFrame(animateFrame);
    }

    function setTargetAlpha(a) {
      state.targetAlpha = a;
      startAnimation();
    }

    // --- Expand / collapse ---
    var expanded = false;
    var resizeRaf = null;

    function trackResize() {
      sizeCanvas();
      doRender();
      resizeRaf = requestAnimationFrame(trackResize);
    }

    function stopTrackResize() {
      if (resizeRaf) { cancelAnimationFrame(resizeRaf); resizeRaf = null; }
    }

    masthead.addEventListener("transitionend", function () {
      stopTrackResize();
      sizeCanvas();
      doRender();
    });

    function expand() {
      if (expanded) return;
      expanded = true;
      masthead.classList.add("expanded");
      canvas.classList.add("interactive");
      stopTrackResize();
      trackResize();
      setTargetAlpha(1);
      // Start time sweep from current display hour
      timeAnimating = true;
      timeReturning = false;
      startAnimation();
    }

    function collapse() {
      if (!expanded) return;
      expanded = false;
      masthead.classList.remove("expanded");
      canvas.classList.remove("interactive");
      stopTrackResize();
      trackResize();
      setTargetAlpha(0);
      // Return rotation + time
      returningRot = true;
      timeAnimating = false;
      timeReturning = true;
      startAnimation();
    }

    // --- Drag interaction ---
    var lastX, lastY;

    function onPointerDown(e) {
      // Only respond when canvas is interactive (ambient mode: pointer-events none)
      state.dragging = true;
      canvas.classList.add("dragging");
      returningRot = false;
      timeReturning = false;
      var pt = e.touches ? e.touches[0] : e;
      lastX = pt.clientX;
      lastY = pt.clientY;
      expand();
      e.preventDefault();
    }

    function onPointerMove(e) {
      if (!state.dragging) return;
      var pt = e.touches ? e.touches[0] : e;
      state.rot[1] += (pt.clientX - lastX) * 0.007;
      state.rot[0] += (pt.clientY - lastY) * 0.007;
      state.rot[0] = Math.max(-Math.PI / 2.8, Math.min(Math.PI / 2.8, state.rot[0]));
      lastX = pt.clientX;
      lastY = pt.clientY;
      doRender();
    }

    function onPointerUp() {
      if (!state.dragging) return;
      state.dragging = false;
      canvas.classList.remove("dragging");
      setTimeout(function () {
        if (!state.dragging) collapse();
      }, DWELL_MS);
    }

    canvas.addEventListener("mousedown", onPointerDown);
    canvas.addEventListener("touchstart", onPointerDown, { passive: false });
    window.addEventListener("mousemove", onPointerMove);
    window.addEventListener("touchmove", onPointerMove, { passive: true });
    window.addEventListener("mouseup", onPointerUp);
    window.addEventListener("touchend", onPointerUp);

    // --- Initial render ---
    sizeCanvas();
    // Make canvas interactive for clicks
    canvas.classList.add("interactive");
    doRender();

    // Fade in on image load
    var initialLoaded = 0;
    function onImgLoad() {
      initialLoaded++;
      if (initialLoaded >= 1) doRender();
    }
    sunImg.addEventListener("load", onImgLoad);
    moonImg.addEventListener("load", onImgLoad);

    // --- Periodic update (minute tick) ---
    function minuteUpdate() {
      if (state.dragging || timeAnimating || timeReturning) return;
      state.hour = currentHour();
      state.realHour = currentHour();
      doRender();
    }
    setInterval(minuteUpdate, 60000);
    window.__celestialUpdate = minuteUpdate;

    // --- Resize ---
    window.addEventListener("resize", function () {
      sizeCanvas();
      doRender();
    });

    // --- HTMX date change API ---
    // Animation state for date transitions
    var dateAnim = null;

    window.__celestialSetDate = function (dateStr) {
      // Capture starting positions
      var fromHour = state.hour;
      var fromDoy = doy;

      // Determine direction
      var direction = dateStr < currentDateStr ? -1 : dateStr > currentDateStr ? 1 : 0;

      // Cancel any in-flight date animation
      if (dateAnim) { cancelAnimationFrame(dateAnim.rafId); dateAnim = null; }

      // Update state
      currentDateStr = dateStr;
      window.__celestialDateStr = dateStr;
      var newDoy = dayOfYear(dateStr);
      var toHour = currentHour();

      // Preload new images
      var imagesReady = preloadCelestialImages(dateStr);
      var preloadedUrls = null;
      imagesReady.then(function (urls) { preloadedUrls = urls; });

      // Reduced motion: snap
      if (prefersReducedMotion()) {
        doy = newDoy;
        state.hour = toHour;
        state.realHour = toHour;
        imagesReady.then(function (urls) {
          sunImg.src = urls[0];
          moonImg.src = urls[1];
          doRender();
        });
        if (window.__zodiacRender) window.__zodiacRender();
        return;
      }

      // Animated transition: interpolate hour to sweep bodies along paths
      var startTime = null;
      var swapped = false;

      function doSwap() {
        if (swapped) return;
        swapped = true;
        if (preloadedUrls) {
          sunImg.src = preloadedUrls[0];
          moonImg.src = preloadedUrls[1];
        }
      }

      dateAnim = { rafId: 0 };

      function tick(timestamp) {
        if (!dateAnim) return;
        if (!startTime) startTime = timestamp;
        var elapsed = timestamp - startTime;
        var t = Math.min(elapsed / ARC_DURATION, 1);
        var eased = easeInOutCubic(t);

        // Swap images at mid-arc
        if (!swapped && t >= 0.5) {
          if (preloadedUrls) doSwap();
          else imagesReady.then(doSwap);
        }

        // Interpolate: doy snaps at midpoint, hour interpolates
        doy = t < 0.5 ? fromDoy : newDoy;
        state.hour = fromHour + (toHour - fromHour) * eased;
        state.realHour = toHour;
        doRender();

        if (t < 1) {
          dateAnim.rafId = requestAnimationFrame(tick);
        } else {
          doy = newDoy;
          state.hour = toHour;
          state.realHour = toHour;
          dateAnim = null;
          if (!swapped) imagesReady.then(function () { doSwap(); doRender(); });
          doRender();
        }
      }

      dateAnim.rafId = requestAnimationFrame(tick);

      // Zodiac snaps immediately
      if (window.__zodiacRender) window.__zodiacRender();
    };

    // Expose for tests
    window.__celestialAnimating = function () {
      return dateAnim !== null || animRaf !== null;
    };

    // Also expose moon position for potential future use
    window.__moonPosition = function () {
      var moon = moonPosition(state.hour, doy);
      var geo = computeGeometry();
      var pos = altAzToXYZ(moon.alt, moon.az);
      var p = project(pos.x, pos.y, pos.z, geo.cx, geo.cy, geo.radius, state.rot);
      var canvasRect = canvas.getBoundingClientRect();
      return {
        x: canvasRect.left + p.sx + window.scrollX,
        y: canvasRect.top + p.sy + window.scrollY,
        visible: moon.alt > -10
      };
    };
  }

  // --- Boot ---
  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", init);
  } else {
    init();
  }
})();

Step 2: Verify the file parses

node -e "const fs=require('fs'); try { new Function(fs.readFileSync('assets/js/celestial.js','utf8')); console.log('OK'); } catch(e) { console.error(e.message); process.exit(1); }"

Expected: OK

Step 3: Commit

git add assets/js/celestial.js
git commit -m "feat(celestial): rewrite as 3D horizon sphere

Replace flat sine-arc with oblate dome projection. Sun and moon at
correct astronomical positions. Click-drag expands masthead and reveals
armillary with diurnal paths, celestial equator, meridian, cardinal
points. Time sweeps forward while expanded; eases back on release.
Rotation returns to default south-facing view.

Bug fixes from demo:
- Moon hour angle normalised to [-π,π] (no doubling back)
- Moon age from continuous fractional days (no Date discontinuity)
- Azimuth sign from sin(HA) not HA>0

Preserved contracts: __celestialSetDate, __celestialUpdate,
__celestialAnimating, __sunPosition, __celestialDateStr."

Task 4: Adapt zodiac.js for Sphere Projection

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

Step 1: Rewrite zodiac.js to render onto the shared canvas

The new zodiac.js keeps the constellation data but replaces all rendering. Instead of creating its own canvas, it exports window.__zodiacRenderOnSphere which celestial.js calls during renderScene.

Replace the entire contents of assets/js/zodiac.js with:

/**
 * zodiac.js — Zodiac constellation patterns on the celestial sphere.
 *
 * Renders simplified stick-figure constellations as small dots projected
 * onto the 3D sphere surface. Called by celestial.js during renderScene
 * at the correct z-order (after horizon disc, before bodies).
 *
 * Back-face dots (on the far side of the sphere) are drawn dimmer.
 */

(function () {
  "use strict";

  var DEG = Math.PI / 180;
  var TAU = Math.PI * 2;

  // --- Constellation data ---
  // lon: ecliptic longitude of centre (degrees)
  // stars: [[x,y], ...] normalised 0–1 within bounding box
  // lines: [[idx, idx], ...] connections (unused in ambient, kept for armillary)

  var CONSTELLATIONS = [
    { name: "Aries", symbol: "\u2648", lon: 15, stars: [
        [0.3,0.2],[0.5,0.35],[0.7,0.5],[0.6,0.8]
      ], lines: [[0,1],[1,2],[2,3]] },
    { name: "Taurus", symbol: "\u2649", lon: 45, stars: [
        [0.2,0.3],[0.35,0.4],[0.5,0.35],[0.65,0.25],[0.8,0.3],
        [0.5,0.55],[0.3,0.7],[0.7,0.7]
      ], lines: [[0,1],[1,2],[2,3],[3,4],[2,5],[5,6],[5,7]] },
    { name: "Gemini", symbol: "\u264A", lon: 75, stars: [
        [0.3,0.1],[0.3,0.35],[0.3,0.6],[0.3,0.85],
        [0.7,0.1],[0.7,0.35],[0.7,0.6],[0.7,0.85]
      ], lines: [[0,1],[1,2],[2,3],[4,5],[5,6],[6,7],[1,5]] },
    { name: "Cancer", symbol: "\u264B", lon: 105, stars: [
        [0.3,0.3],[0.5,0.5],[0.7,0.3],[0.5,0.7],[0.4,0.45]
      ], lines: [[0,4],[4,1],[1,2],[1,3]] },
    { name: "Leo", symbol: "\u264C", lon: 135, stars: [
        [0.2,0.3],[0.35,0.15],[0.55,0.2],[0.7,0.15],[0.8,0.3],
        [0.65,0.5],[0.45,0.55],[0.3,0.75],[0.5,0.8]
      ], lines: [[0,1],[1,2],[2,3],[3,4],[4,5],[5,6],[6,0],[6,7],[7,8]] },
    { name: "Virgo", symbol: "\u264D", lon: 165, stars: [
        [0.3,0.15],[0.5,0.2],[0.7,0.15],[0.5,0.4],
        [0.3,0.55],[0.6,0.55],[0.4,0.8],[0.7,0.75]
      ], lines: [[0,1],[1,2],[1,3],[3,4],[3,5],[4,6],[5,7]] },
    { name: "Libra", symbol: "\u264E", lon: 195, stars: [
        [0.5,0.2],[0.3,0.5],[0.7,0.5],[0.2,0.8],[0.8,0.8]
      ], lines: [[0,1],[0,2],[1,3],[2,4]] },
    { name: "Scorpius", symbol: "\u264F", lon: 225, stars: [
        [0.15,0.2],[0.25,0.35],[0.35,0.3],[0.5,0.35],
        [0.6,0.45],[0.65,0.55],[0.6,0.65],[0.7,0.75],[0.8,0.85],[0.75,0.9]
      ], lines: [[0,1],[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9]] },
    { name: "Sagittarius", symbol: "\u2650", lon: 255, stars: [
        [0.3,0.2],[0.5,0.15],[0.7,0.25],[0.4,0.45],
        [0.6,0.45],[0.5,0.65],[0.3,0.8],[0.7,0.8]
      ], lines: [[0,1],[1,2],[0,3],[2,4],[3,4],[3,5],[4,5],[5,6],[5,7]] },
    { name: "Capricornus", symbol: "\u2651", lon: 285, stars: [
        [0.2,0.3],[0.4,0.2],[0.6,0.25],[0.8,0.35],
        [0.7,0.6],[0.4,0.7],[0.25,0.55]
      ], lines: [[0,1],[1,2],[2,3],[3,4],[4,5],[5,6],[6,0]] },
    { name: "Aquarius", symbol: "\u2652", lon: 315, stars: [
        [0.2,0.25],[0.4,0.2],[0.55,0.3],[0.7,0.25],
        [0.55,0.5],[0.4,0.65],[0.6,0.7],[0.5,0.85]
      ], lines: [[0,1],[1,2],[2,3],[2,4],[4,5],[4,6],[5,7],[6,7]] },
    { name: "Pisces", symbol: "\u2653", lon: 345, stars: [
        [0.2,0.4],[0.3,0.25],[0.45,0.3],[0.55,0.4],
        [0.65,0.3],[0.75,0.2],[0.85,0.35],
        [0.55,0.6],[0.45,0.75],[0.55,0.85]
      ], lines: [[0,1],[1,2],[2,3],[3,4],[4,5],[5,6],[3,7],[7,8],[8,9]] },
  ];

  var CONSTELLATION_SIZE = 20;  // px bounding box
  var STAR_RADIUS = 0.8;        // px per dot
  var STAR_COLOR = [184, 137, 46];  // saffron RGB
  var STAR_BASE_ALPHA = 0.3;
  var STAR_ACTIVE_ALPHA = 0.5;  // for the sun's current sign

  // --- Ecliptic position ---

  function sunEclipticLon(doy) {
    // Sun at vernal equinox (Mar 20, ~day 79) is at 0° ecliptic lon
    return ((doy - 79) * 0.9856 + 360) % 360;
  }

  /**
   * Convert ecliptic longitude to alt/az for a given hour and doy.
   *
   * The ecliptic longitude on the meridian (due south) equals the sun's
   * ecliptic longitude. Other longitudes are offset by their angular
   * distance, mapped to hour angle.
   */
  function eclipticLonToAltAz(lon, hour, doy) {
    var lat = 40 * DEG;
    var sunLon = sunEclipticLon(doy);
    // Offset from meridian ecliptic longitude
    var offset = lon - sunLon;
    // Normalise to -180..180
    offset = ((offset + 540) % 360) - 180;
    // Convert to hour angle: at the meridian, HA = sun's HA = (hour-12)*15
    var sunHA = (hour - 12) * 15;
    var ha = (sunHA + offset) * DEG;
    // Ecliptic has ~23.44° obliquity — approximate declination
    var eclObliquity = 23.44 * DEG;
    var lonRad = lon * DEG;
    var decl = Math.asin(Math.sin(eclObliquity) * Math.sin(lonRad));
    // Altitude
    var sinAlt = Math.sin(lat) * Math.sin(decl) +
                 Math.cos(lat) * Math.cos(decl) * Math.cos(ha);
    var alt = Math.asin(sinAlt) / DEG;
    // Azimuth
    var cosAz = (Math.sin(decl) - Math.sin(lat) * sinAlt) /
                (Math.cos(lat) * Math.cos(Math.asin(sinAlt)));
    var az = Math.acos(Math.max(-1, Math.min(1, cosAz))) / DEG;
    if (Math.sin(ha) > 0) az = 360 - az;
    return { alt: alt, az: az };
  }

  // --- Rendering ---

  /**
   * Render constellations onto the shared celestial canvas.
   * Called by celestial.js during renderScene.
   *
   * Uses the same altAzToXYZ and project functions via closure over
   * the parameters passed in. We inline the projection here since
   * zodiac.js doesn't share the celestial.js scope.
   */
  window.__zodiacRenderOnSphere = function (ctx, cx, cy, radius, viewRot, hour, doy, yScale) {
    var sunLon = sunEclipticLon(doy);

    CONSTELLATIONS.forEach(function (c) {
      // Compute centre alt/az
      var centre = eclipticLonToAltAz(c.lon, hour, doy);

      // Is this the sun's current constellation?
      var lonDiff = Math.abs(c.lon - sunLon);
      if (lonDiff > 180) lonDiff = 360 - lonDiff;
      var isActive = lonDiff < 15;
      var baseAlpha = isActive ? STAR_ACTIVE_ALPHA : STAR_BASE_ALPHA;

      // Project centre to screen to get local scale
      var centreXYZ = _altAzToXYZ(centre.alt, centre.az);
      var centreP = _project(centreXYZ.x, centreXYZ.y, centreXYZ.z, cx, cy, radius, viewRot, yScale);

      // Dim back-face dots
      var depthDim = Math.max(0.15, 1 - centreP.z);
      var alpha = baseAlpha * depthDim;

      ctx.fillStyle = "rgba(" + STAR_COLOR[0] + "," + STAR_COLOR[1] + "," + STAR_COLOR[2] + "," + alpha.toFixed(3) + ")";

      // Draw each star dot offset from centre
      var dotScale = centreP.scale * CONSTELLATION_SIZE;
      c.stars.forEach(function (s) {
        // Offset in local tangent plane (approximate: just add pixel offset)
        var sx = centreP.sx + (s[0] - 0.5) * dotScale;
        var sy = centreP.sy + (s[1] - 0.5) * dotScale * yScale;
        ctx.beginPath();
        ctx.arc(sx, sy, STAR_RADIUS * centreP.scale, 0, TAU);
        ctx.fill();
      });
    });
  };

  // Inline projection (same math as celestial.js, avoids cross-scope dependency)
  function _altAzToXYZ(alt, az) {
    var a = alt * DEG, b = az * DEG;
    return { x: -Math.sin(b) * Math.cos(a), y: Math.sin(a), z: Math.cos(b) * Math.cos(a) };
  }

  function _project(x, y, z, cx, cy, radius, viewRot, yScale) {
    var cosY = Math.cos(viewRot[1]), sinY = Math.sin(viewRot[1]);
    var x1 = x * cosY - z * sinY, z1 = x * sinY + z * cosY;
    var cosX = Math.cos(viewRot[0]), sinX = Math.sin(viewRot[0]);
    var y2 = y * cosX - z1 * sinX, z2 = y * sinX + z1 * cosX;
    var scale = 1.8 / (1.8 + z2 * 0.3);
    return {
      sx: cx + x1 * radius * scale,
      sy: cy - y2 * radius * scale * (yScale || 1),
      z: z2,
      scale: scale
    };
  }

  // Expose render for manual triggering
  window.__zodiacRender = function () {
    // In the new system, zodiac is rendered as part of celestial's renderScene.
    // This is called by celestial.js after date changes.
    // The actual work happens in __zodiacRenderOnSphere via the next doRender().
    if (window.__celestialUpdate) window.__celestialUpdate();
  };

})();

Step 2: Verify parse

node -e "const fs=require('fs'); try { new Function(fs.readFileSync('assets/js/zodiac.js','utf8')); console.log('OK'); } catch(e) { console.error(e.message); process.exit(1); }"

Expected: OK

Step 3: Commit

git add assets/js/zodiac.js
git commit -m "feat(zodiac): adapt for sphere projection

Constellations now render onto celestial.js's shared canvas via
__zodiacRenderOnSphere callback. Each constellation projected to
correct alt/az on the sphere surface. Back-face dots dimmed by
depth (max(0.15, 1-z')). Own canvas creation removed."

Task 5: Clean Up CSS — Remove Legacy Styles

Files: - Modify: assets/css/almanack.css

Step 1: Remove the legacy .celestial-body rule

Now that bodies are canvas-drawn, remove the .celestial-body block we kept in Task 2 for transition safety. Find and delete:

/* Legacy: keep .celestial-body for any transition period */
.celestial-body {
    position: absolute;
    pointer-events: none;
    z-index: 0;
    user-select: none;
    -webkit-user-select: none;
    will-change: left, top, opacity;
}

Step 2: Remove .zodiac-band from the mobile hide rule

The zodiac no longer creates its own canvas, so .zodiac-band is dead. Update the mobile hide rule:

    /* Hide celestial display on mobile — no room for the sphere */
    .horizon-canvas {
        display: none !important;
    }

Step 3: Commit

git add assets/css/almanack.css
git commit -m "chore(css): remove dead .celestial-body and .zodiac-band rules"

Task 6: Build and Smoke Test

Step 1: Build the static site

make sync && make build

Expected: no errors. The build copies assets/js/celestial.js and assets/js/zodiac.js into web/static/js/.

Step 2: Run the dev server and verify visually

make serve

Open http://localhost:1969/ in a browser. You should see:

  • Sun and moon floating above “Almnck.” at their correct positions
  • Faint horizon disc and glow visible
  • Click-drag on the masthead → masthead expands, armillary rings fade in, time sweeps forward
  • Release → 800ms dwell, then collapse, rotation returns, time eases back
  • Bodies use the photorealistic images from /static/celestial/

Step 3: Verify mobile hide

Open dev tools, set viewport to 375px wide. The canvas should be hidden.

Step 4: Commit

git add -A
git commit -m "chore: build and verify horizon sphere"

Task 7: Update Browser Tests

Files: - Modify: src/tests/test_celestial_animation.py

Step 1: Rewrite test helpers for canvas-drawn bodies

Bodies are no longer DOM elements with .style.left — they’re canvas-drawn. Tests now use the window.__sunPosition and window.__celestialAnimating APIs.

Replace the entire file with:

"""Tests for celestial sphere animation during HTMX date navigation.

Verifies that sun position changes smoothly when __celestialSetDate is called,
and that rapid date changes settle correctly. Uses Playwright against the dev
server.

Bodies are canvas-drawn (no DOM elements). Tests use the window.__sunPosition
and window.__celestialAnimating APIs.
"""

import pytest

pytestmark = pytest.mark.browser

FRONTPAGE_URL = "/?fp=2026-02-13"
ALT_DATE = "2026-01-26"
THIRD_DATE = "2026-01-03"


@pytest.fixture(scope="session")
def desktop_browser(playwright_instance):
    browser = playwright_instance.chromium.launch()
    yield browser
    browser.close()


@pytest.fixture
def desktop_context(desktop_browser, dev_server_url):
    context = desktop_browser.new_context(
        viewport={"width": 1280, "height": 900},
        base_url=dev_server_url,
    )
    yield context
    context.close()


@pytest.fixture
def page(desktop_context):
    page = desktop_context.new_page()
    yield page
    page.close()


def wait_for_celestial(page):
    """Wait until the celestial canvas has rendered (sun position exposed)."""
    page.wait_for_function(
        """() => {
            return window.__sunPosition && window.__sunPosition.x > 0;
        }""",
        timeout=10000,
    )


def get_sun_position(page):
    """Get sun position from the exposed API."""
    return page.evaluate(
        """() => {
            var sp = window.__sunPosition;
            return sp ? { x: sp.x, y: sp.y, visible: sp.visible } : null;
        }"""
    )


class TestCelestialSphereAnimation:
    """Verify animated sphere transitions on date change."""

    def test_sun_moves_during_animation(self, page, dev_server_url):
        """After __celestialSetDate, sun position should change gradually."""
        page.goto(FRONTPAGE_URL)
        wait_for_celestial(page)

        start = get_sun_position(page)
        assert start is not None, "Sun position should be exposed"

        # Trigger date change and sample at ~100ms
        page.evaluate("(date) => window.__celestialSetDate(date)", ALT_DATE)
        page.wait_for_timeout(100)

        mid = get_sun_position(page)

        # Wait for animation to finish
        page.wait_for_function(
            "() => !window.__celestialAnimating()",
            timeout=5000,
        )

        end = get_sun_position(page)

        # Sun should have moved
        sun_moved = abs(end["x"] - start["x"]) > 2
        if sun_moved:
            # Mid should be between start and end (or at least different from start)
            assert mid["x"] != start["x"] or mid["y"] != start["y"], (
                "Sun should be moving at 100ms into animation"
            )

    def test_rapid_date_changes_settle(self, page, dev_server_url):
        """Fire 3 rapid date changes — sun should settle without NaN."""
        page.goto(FRONTPAGE_URL)
        wait_for_celestial(page)

        page.evaluate(
            """(dates) => {
                window.__celestialSetDate(dates[0]);
                setTimeout(() => window.__celestialSetDate(dates[1]), 50);
                setTimeout(() => window.__celestialSetDate(dates[2]), 100);
            }""",
            [ALT_DATE, THIRD_DATE, FRONTPAGE_URL.split("=")[1]],
        )

        page.wait_for_function(
            "() => !window.__celestialAnimating()",
            timeout=5000,
        )
        page.wait_for_timeout(200)

        final = get_sun_position(page)
        assert final is not None, "Sun position should exist after rapid changes"
        assert not page.evaluate(
            "() => isNaN(window.__sunPosition.x) || isNaN(window.__sunPosition.y)"
        ), "Sun position should not be NaN"

    def test_reduced_motion_snaps(self, page, dev_server_url, desktop_browser):
        """With prefers-reduced-motion: reduce, position snaps immediately."""
        context = desktop_browser.new_context(
            viewport={"width": 1280, "height": 900},
            base_url=dev_server_url,
            reduced_motion="reduce",
        )
        try:
            rm_page = context.new_page()
            rm_page.goto(FRONTPAGE_URL)
            wait_for_celestial(rm_page)

            rm_page.evaluate(
                "(date) => window.__celestialSetDate(date)", ALT_DATE
            )
            rm_page.wait_for_timeout(50)

            is_animating = rm_page.evaluate("() => window.__celestialAnimating()")
            assert not is_animating, "Should snap immediately with reduced motion"

            rm_page.close()
        finally:
            context.close()

    def test_canvas_exists(self, page, dev_server_url):
        """Verify the horizon canvas element is present in the masthead."""
        page.goto(FRONTPAGE_URL)
        count = page.evaluate(
            "() => document.querySelectorAll('.horizon-canvas').length"
        )
        assert count == 1, "Should have exactly one horizon-canvas element"

    def test_canvas_hidden_on_mobile(self, page, dev_server_url, desktop_browser):
        """Canvas should be hidden at mobile viewport widths."""
        context = desktop_browser.new_context(
            viewport={"width": 375, "height": 812},
            base_url=dev_server_url,
        )
        try:
            mobile_page = context.new_page()
            mobile_page.goto(FRONTPAGE_URL)
            mobile_page.wait_for_timeout(500)

            display = mobile_page.evaluate(
                """() => window.getComputedStyle(
                    document.querySelector('.horizon-canvas')
                ).display"""
            )
            assert display == "none", "Canvas should be hidden on mobile"

            mobile_page.close()
        finally:
            context.close()

Step 2: Run the browser tests

make test-browser

Expected: all celestial animation tests pass. Other browser tests should still pass.

Step 3: Commit

git add src/tests/test_celestial_animation.py
git commit -m "test(celestial): update browser tests for canvas-drawn bodies

Bodies are now canvas-drawn, not DOM <img> elements. Tests use
window.__sunPosition and window.__celestialAnimating APIs.
Added: canvas element check, mobile hide check."

Task 8: Run Full Test Suite

Step 1: Run all tests

make test-all

Expected: all suites pass. Fix any failures before proceeding.

Step 2: Commit any fixes

git add -A
git commit -m "fix: resolve test failures from horizon sphere migration"

Task 9: Final Review & Squash

Step 1: Review the diff

git diff main --stat

Expected changes: - assets/js/celestial.js — rewritten (~1080 lines) - assets/js/zodiac.js — rewritten (~191 lines) - assets/css/almanack.css — modified (new canvas styles, expand transition, dead rule removal) - src/almnck/templates/base.html — one line added (canvas element) - src/tests/test_celestial_animation.py — rewritten for canvas API - src/tests/test_celestial_interaction.py — new interaction tests (~310 lines)

Step 2: Interactive rebase to clean up commits

git rebase -i main

Squash into logical commits: 1. feat: add horizon sphere canvas and CSS infrastructure 2. feat: rewrite celestial.js as 3D horizon sphere 3. feat: adapt zodiac.js for sphere projection 4. test: update browser tests for canvas-drawn bodies

Step 3: Final verification

make test
make serve  # visual check

Post-Plan Changes

The following changes were made after the initial 9-task plan was executed, in response to user testing:

Moon Reference Epoch Fix

MOON_REF_DAYS_TO_2026 was corrected from 9126.24 to 9491.24 (off by 365 days). Jan 3 2026 (Full Supermoon) was rendering as a waxing crescent.

Interaction Redesign

The original plan used click-and-drag anywhere on the canvas to activate the armillary. This was redesigned through three iterations to the current model: - Body click: clicking on sun or moon → instant armillary - Period click: clicking the “.” of “Almnck.” → instant armillary - Long-press: 400ms hold on masthead (except nav zone) → armillary - Short clicks on the frontispiece still navigate home. Nav links always work.

Time Control Redesign

Auto time sweep on expand was removed. Plain drag rotates only. Cmd/Ctrl+drag scrubs time. This gives explicit user control.

Meta-Left Time Display

When the armillary expands, .meta-left shows the day name + formatted time (e.g. “Wednesday, 1:00 PM”) and a modifier key hint (“⌘+drag for time” on Mac, “Ctrl+drag for time” elsewhere). Restored on collapse.

Interaction Tests

A new test file test_celestial_interaction.py was written with 12 tests covering: - Body click activation (sun and moon, with injected noon hour for determinism) - Period click activation - Long-press activation (frontpage and article pages) - Nav link click navigates normally - Logo click navigates home - Short masthead click does not activate - Long-press on nav does not activate - Meta-left shows time + modifier hint on expand - Meta-left restores on collapse


Summary

Task What Files
1 Add <canvas> to template base.html
2 Add CSS for canvas, expand, mobile almanack.css
3 Rewrite celestial.js (astronomy + 3D + interaction) celestial.js
4 Adapt zodiac.js for sphere rendering zodiac.js
5 Remove dead CSS rules almanack.css
6 Build & smoke test —
7 Update browser tests test_celestial_animation.py
8 Full test suite —
9 Review & squash —

| — | Interaction tests | test_celestial_interaction.py — body click, long-press, nav, meta-time |

Total: ~1270 lines of new JS, ~310 lines of new tests, ~20 lines of CSS changes, 1 line of HTML. Replaces ~990 lines of old JS.