diff --git a/.claude/hooks/end-at-deliverable.sh b/.claude/hooks/end-at-deliverable.sh new file mode 100755 index 0000000..1e52f75 --- /dev/null +++ b/.claude/hooks/end-at-deliverable.sh @@ -0,0 +1,82 @@ +#!/usr/bin/env bash +# GENERATED — canonical source: PyAutoMind/policy/end_at_deliverable_hook.sh +# Installed into every checked-out repo as .claude/hooks/end-at-deliverable.sh by +# `python3 PyAutoMind/scripts/repos_sync.py --write`, and drift-checked by +# `--check`. Edit the canonical file, never a copy. +# +# --------------------------------------------------------------------------- +# Sessions end at their deliverable (PyAutoMind/policy/end_at_deliverable.md). +# +# A PreToolUse guard on the tools that outlive the turn. It exists because the +# prose rule was already written and was still broken twice: five batch members +# armed hourly check-ins on 2026-08-31 (fixed for batch members only), and on +# 2026-09-02/03 a mobile `/prm` re-armed a 60-minute `send_later` hourly from +# 02:39 to 12:11 UTC with no task active, leaving twenty fired one-shots and a +# drained usage window. A rule a session can talk itself past is not a rule, so +# this one is enforced by the harness. +# +# Registered under `hooks.PreToolUse` with the matcher +# ^(send_later|subscribe_pr_activity|ScheduleWakeup|CronCreate|RemoteTrigger|mcp__.*(send_later|subscribe_pr_activity).*)$ +# +# Allowed through: +# * `RemoteTrigger` with action list / get / list_runs / get_run_log — reading +# what already exists never outlives the turn; +# * anything at all when PYAUTO_ALLOW_TIMERS=1 — the human-authorised escape +# for a routine the human actually asked for. +# +# Everything else exits 2 (the harness treats stderr as the reason and blocks +# the call). An unreadable payload also exits 2: this fails closed, because the +# failure it guards against is silent and costs a night of usage. +set -uo pipefail + +# Human-authorised routine: the one way past this guard, and it has to be set +# deliberately in the environment. +[ "${PYAUTO_ALLOW_TIMERS:-}" = "1" ] && exit 0 + +payload="$(cat)" + +# python3 rather than jq: python3 is present everywhere this hook is installed +# (it is what the SessionStart hook guarantees), jq is not. The payload rides in +# the environment rather than on stdin so the heredoc keeps its own stdin. +PYAUTO_HOOK_PAYLOAD="$payload" python3 <<'PY' +import json +import os +import sys + +# Read-only RemoteTrigger actions: they inspect what exists and schedule nothing. +READ_ONLY_REMOTE_TRIGGER = {"list", "get", "list_runs", "get_run_log"} + +REASON = ( + "policy end_at_deliverable: sessions end at their deliverable " + "— {tool} would outlive the turn.\n" + "Report and stop; the human re-runs /prm. Set PYAUTO_ALLOW_TIMERS=1 only " + "for a routine the human asked for.\n" +) + + +def block(tool): + sys.stderr.write(REASON.format(tool=tool)) + raise SystemExit(2) + + +try: + event = json.loads(os.environ.get("PYAUTO_HOOK_PAYLOAD", "")) + if not isinstance(event, dict): + raise ValueError("PreToolUse payload is not a JSON object") + tool = event.get("tool_name") + if not isinstance(tool, str) or not tool: + raise ValueError("PreToolUse payload carries no tool_name") + tool_input = event.get("tool_input") + if not isinstance(tool_input, dict): + tool_input = {} +except Exception: + # Fail closed. A payload this hook cannot read is a call it cannot clear. + block("an unreadable tool call") + +if "RemoteTrigger" in tool: + action = tool_input.get("action") + if isinstance(action, str) and action in READ_ONLY_REMOTE_TRIGGER: + raise SystemExit(0) + +block(tool) +PY diff --git a/.claude/hooks/session-start.sh b/.claude/hooks/session-start.sh new file mode 100755 index 0000000..f58396f --- /dev/null +++ b/.claude/hooks/session-start.sh @@ -0,0 +1,754 @@ +#!/usr/bin/env bash +# GENERATED — canonical source: PyAutoMind/policy/session_start_hook.sh +# Installed into every checked-out repo as .claude/hooks/session-start.sh by +# `python3 PyAutoMind/scripts/repos_sync.py --write`, and drift-checked by +# `--check`. Edit the canonical file, never a copy. +# +# --------------------------------------------------------------------------- +# Python 3.12 is the default in Claude Code web/mobile sessions. +# +# The remote container ships /usr/local/bin/python{,3} -> /usr/bin/python3.11, +# a pip whose shebang is #!/usr/bin/python3, and a uv-managed tool set (pytest, +# ruff, black, mypy, pyright, flake8, poetry) every one of which was built on +# 3.11 — one minor version below the floor the organism set for itself in the +# Python 3.12 floor campaign, and below every CI leg it runs. The image's own +# `use-python 3.12` does not fix it: it moves the update-alternatives links +# under /usr/bin, which /usr/local/bin/python{,3} then shadow. +# +# This hook makes a session 3.12 on three surfaces: +# +# 1. a 3.12 virtualenv first on PATH — python, python3, pip, pytest; +# 2. the /usr/local/bin/python{,3} symlinks repointed at 3.12, so anything +# resolving PATH without this session's env (a subprocess with a scrubbed +# environment, a `#!/usr/bin/env python3` script) also gets 3.12; +# 3. the uv-managed tools rebuilt on 3.12 — mypy and flake8 read the +# interpreter's version, so on 3.11 they judged code against 3.11 rules — +# and then repaired, because (2) is what breaks each tool env's own +# `bin/python`, and a rebuild cannot fix a link it is handed. +# +# What it deliberately does NOT touch: the update-alternatives links under +# /usr/bin. Scripts with a literal `#!/usr/bin/python3` shebang follow those, +# and some of the image's own tools (conan) are installed for 3.11 only — a +# flip there breaks them for no gain the three surfaces above don't already +# give. +# +# Remote-only (a local checkout keeps whatever the developer's shell provides), +# idempotent (everything is skipped once it already reads 3.12, so the second +# repo's copy in the same session costs ~0.2s), and non-blocking: every step +# degrades to a logged warning rather than failing the session start. +# +# Per-repo dependencies: a repo that needs more than pytest + PyYAML declares it +# in .claude/session-python.txt — one pip argument per line (`-e .`, a package +# spec, `-r requirements.txt`; `#` comments ignored). Installed additively into +# the shared venv, so the file stays out of this generated hook and the hook +# stays byte-identical in every repo. +set -euo pipefail + +[ "${CLAUDE_CODE_REMOTE:-}" = "true" ] || exit 0 + +VENV="${PYAUTO_SESSION_VENV:-$HOME/.pyauto/session-py312}" +# pytest-xdist is a base dep, not a nicety: a remote container has 4 cores and +# the Brain suite takes 96s on one of them and 28s on four. A session that has +# to `pip install` before it can run tests fast will simply not run them fast. +BASE_DEPS=(pytest PyYAML pytest-xdist) + +# Which checkout is this copy of the hook installed in? +# +# NOT $CLAUDE_PROJECT_DIR. That is the session's project directory, which equals +# the repo only when the session holds exactly ONE repo. A session scoped to +# several organs clones them side by side under the project directory +# (/home/user/PyAutoMind, /home/user/PyAutoBrain, ...), and then +# $CLAUDE_PROJECT_DIR is their parent — so reading session-python.txt from it +# found nothing, silently, in exactly the sessions that hold the most repos. +# +# Derive it from where this script actually is, in both the installed and the +# canonical location. +HOOK_SELF="$(readlink -f "$0")" +case "$(dirname "$HOOK_SELF")" in + */.claude/hooks) REPO_DIR="$(cd "$(dirname "$HOOK_SELF")/../.." && pwd)" ;; + */policy) REPO_DIR="$(cd "$(dirname "$HOOK_SELF")/.." && pwd)" ;; + *) REPO_DIR="${CLAUDE_PROJECT_DIR:-$PWD}" ;; +esac +EXTRAS_FILE="$REPO_DIR/.claude/session-python.txt" + +# stderr, not stdout: a SessionStart hook's stdout is fed to the agent as +# session context. +log() { printf '[session-start] %s\n' "$*" >&2; } + +# And where is the WORKSPACE ROOT — the directory holding the checkouts? +# +# NOT `dirname "$REPO_DIR"`, which is what this was. That is the root only in a +# FLAT workspace. Group the checkouts into family directories and the parent of +# a repo is a family directory, which really exists, really is writable and +# really is not a repo — so every guard below passes and all three consumers go +# wrong in silence: $PYAUTO_ROOT is exported to the whole session as the family +# directory, a second `.claude/` root is written INTO it, and the unshallow +# sweep and the generated fan-out reach that one family instead of every +# checkout. +# +# The rule is the one `PyAutoBrain/bin/_pyauto_root.sh` already ships, in the +# same order, so the session and the Brain's resolvers cannot disagree: +# +# 1. an explicit $PYAUTO_ROOT — the operator's word, taken verbatim; +# 2. the nearest ANCESTOR holding a .pyauto-root marker — the only rule that +# survives the workspace growing subdirectories, because "does this +# directory hold a checkout?" is answered yes by a family directory the +# moment the checkouts move into one; +# 3. the parent of this checkout when it holds a sibling organ; +# 4. the parent regardless, reported as unverified. +# +# The resolver itself is used where it is reachable, so there is one +# implementation to correct. But it CANNOT be a dependency: this hook is +# installed into every repo and runs in containers that hold a single checkout, +# no PyAutoBrain and no marker anywhere above them — the session that most +# needs the hook is the one least likely to have a workspace around it. So the +# same rule runs inline wherever the resolver is absent, steps 3 and 4 never +# require a marker, and the resolver is read in a subshell that reports only +# its two answers: a resolver that is broken, or from a version this copy of +# the hook has never seen, can then never fail a session start. +PYAUTO_ROOT_MARKER=".pyauto-root" + +# The nearest ancestor of $1 holding the marker. A checkout is never its own +# workspace root, so the walk starts one level up. +marked_root() { + local d + d="$(dirname "$1")" + while [ "$d" != "/" ]; do + if [ -f "$d/$PYAUTO_ROOT_MARKER" ]; then + printf '%s' "$d" + return 0 + fi + d="$(dirname "$d")" + done + if [ -f "/$PYAUTO_ROOT_MARKER" ]; then + printf '%s' "/" + return 0 + fi + return 1 +} + +# A directory counts as a workspace root if it holds an organ checkout. Any +# organ: a remote session may hold exactly one, and it is still a root. +holds_an_organ() { + [ -d "$1/PyAutoBrain" ] || [ -d "$1/PyAutoMind" ] || [ -d "$1/PyAutoCortex" ] \ + || [ -d "$1/PyAutoMemory" ] || [ -d "$1/PyAutoEyes" ] || [ -d "$1/PyAutoHeart" ] \ + || [ -d "$1/PyAutoHands" ] || [ -d "$1/PyAutoNerves" ] || [ -d "$1/PyAutoGut" ] \ + || [ -d "$1/organs/PyAutoBrain" ] || [ -d "$1/organs/PyAutoMind" ] \ + || [ -d "$1/organs/PyAutoCortex" ] || [ -d "$1/organs/PyAutoMemory" ] \ + || [ -d "$1/organs/PyAutoEyes" ] || [ -d "$1/organs/PyAutoHeart" ] \ + || [ -d "$1/organs/PyAutoHands" ] || [ -d "$1/organs/PyAutoNerves" ] \ + || [ -d "$1/organs/PyAutoGut" ] +} + +# Assigns WORKSPACE_ROOT and WORKSPACE_ROOT_REASON rather than printing: one +# decision produces two answers, and a command substitution would drop the +# reason — which is the whole lesson of a defect whose every consequence was +# silent. +resolve_workspace_root() { + local helper answer + # 1. The operator's word, never second-guessed. The marker only decides + # how the reason reads, so a wrong value from a caller stays visible. + if [ -n "${PYAUTO_ROOT:-}" ]; then + WORKSPACE_ROOT="$PYAUTO_ROOT" + if [ -f "$WORKSPACE_ROOT/$PYAUTO_ROOT_MARKER" ]; then + WORKSPACE_ROOT_REASON="PYAUTO_ROOT" + else + WORKSPACE_ROOT_REASON="PYAUTO_ROOT (unverified - no $PYAUTO_ROOT_MARKER marker)" + fi + return 0 + fi + # The shared resolver, if this checkout can see one: either this checkout + # IS the Brain, or the Brain is beside it. + # + # Its answer is ACCEPTED ONLY IF IT CONTAINS THIS CHECKOUT, because the + # resolver anchors on the BRAIN checkout, not on this one. In a worktree + # bundle the bundle's PyAutoBrain is a symlink into the canonical + # workspace, so the resolver follows it and answers with the canonical + # root — and this session would then export somebody else's workspace to + # the whole session, write a `.claude/` root into it and unshallow its + # repos. Measured on this very bundle: the resolver said + # the canonical workspace for a hook running in a task bundle beside it. + # `scripts/session_bootstrap.sh` guards the same trap the same way; the + # test is "is it an ancestor", not "is the checkout directly under it", so + # a checkout inside a family directory still passes. + local repo_real root_real + repo_real="$(readlink -f "$REPO_DIR" 2>/dev/null || printf '%s' "$REPO_DIR")" + for helper in "$REPO_DIR/bin/_pyauto_root.sh" \ + "$(dirname "$REPO_DIR")/PyAutoBrain/bin/_pyauto_root.sh" \ + "$(dirname "$REPO_DIR")/organs/PyAutoBrain/bin/_pyauto_root.sh" \ + "$(dirname "$(dirname "$REPO_DIR")")/organs/PyAutoBrain/bin/_pyauto_root.sh"; do + [ -r "$helper" ] || continue + # `|` separates the two answers; no reason the resolver states contains + # one. The subshell drops this script's `set -euo pipefail` so that a + # resolver which fails, or which one day needs something this container + # does not have, degrades to the inline rule instead of to a dead + # session. + answer="$( ( + set +euo pipefail + # shellcheck source=/dev/null + . "$helper" >/dev/null 2>&1 + printf '%s|%s' "${PYAUTO_ROOT:-}" "${PYAUTO_ROOT_REASON:-}" + ) 2>/dev/null )" || answer="" + [ -n "${answer%%|*}" ] && [ -d "${answer%%|*}" ] || continue + root_real="$(readlink -f "${answer%%|*}" 2>/dev/null || printf '%s' "${answer%%|*}")" + case "$repo_real" in + "${root_real%/}"/*) ;; + *) continue ;; + esac + WORKSPACE_ROOT="${answer%%|*}" + WORKSPACE_ROOT_REASON="${answer#*|}" + return 0 + done + # 2. A marked ancestor — the root naming itself, which stays right however + # deep under it this checkout sits. + if answer="$(marked_root "$REPO_DIR")"; then + WORKSPACE_ROOT="$answer" + WORKSPACE_ROOT_REASON="$PYAUTO_ROOT_MARKER marker" + return 0 + fi + # 3. Beside this checkout — nothing above us says anything, so what sits + # beside us is all there is: a single-repo remote session, a CI matrix, + # a spawned template. 4. Failing that, the parent anyway: the best guess + # available, and a real path a diagnostic can name. + local parent + parent="$(dirname "$REPO_DIR")" + [ "$(basename "$parent")" = organs ] && parent="$(dirname "$parent")" + WORKSPACE_ROOT="$parent" + if holds_an_organ "$WORKSPACE_ROOT"; then + WORKSPACE_ROOT_REASON="beside this checkout" + else + WORKSPACE_ROOT_REASON="unverified (no sibling organ beside this checkout)" + fi +} +resolve_workspace_root + +is_py312() { + [ -x "$1" ] && "$1" -c 'import sys; raise SystemExit(sys.version_info[:2] != (3, 12))' >/dev/null 2>&1 +} + +find_base_python() { + local candidate + for candidate in /usr/bin/python3.12 /usr/local/bin/python3.12 \ + "$(command -v python3.12 2>/dev/null || true)"; do + if [ -n "$candidate" ] && is_py312 "$candidate"; then + printf '%s\n' "$candidate" + return 0 + fi + done + # No system 3.12 (a future base image could drop it) — uv can fetch one. + if command -v uv >/dev/null 2>&1; then + log "no system python3.12; asking uv to install one" + uv python install 3.12 >&2 || return 1 + candidate="$(uv python find 3.12 2>/dev/null || true)" + if [ -n "$candidate" ] && is_py312 "$candidate"; then + printf '%s\n' "$candidate" + return 0 + fi + fi + return 1 +} + +venv_ready() { + is_py312 "$VENV/bin/python" \ + && [ -x "$VENV/bin/pip" ] \ + && "$VENV/bin/python" -c 'import pytest, yaml, xdist' >/dev/null 2>&1 +} + +# 1. The interpreter a session types: python, python3, pip, pytest. +ensure_venv() { + local base_python + if venv_ready; then + log "reusing $VENV ($("$VENV/bin/python" -V 2>&1))" + return 0 + fi + if ! base_python="$(find_base_python)"; then + log "WARNING: no Python 3.12 in this container; PATH left unchanged" + return 1 + fi + log "building $VENV on $base_python" + rm -rf "$VENV" + mkdir -p "$(dirname "$VENV")" + # --system-site-packages makes the venv a strict SUPERSET of the base + # interpreter. That is what lets `point_system_default` make this venv the + # session's `python3` without silently removing anything the image + # installed: an isolated venv would swap one set of missing modules for + # another, and the session would find out through a ModuleNotFoundError + # that reads like broken code. + if command -v uv >/dev/null 2>&1; then + # --seed puts pip inside the venv too, so `pip install` targets 3.12 + # rather than falling through to the container's 3.11 /usr/bin/pip. + uv venv --seed --system-site-packages --python "$base_python" "$VENV" >&2 + uv pip install --python "$VENV/bin/python" --quiet "${BASE_DEPS[@]}" >&2 + else + "$base_python" -m venv --system-site-packages "$VENV" >&2 + "$VENV/bin/python" -m pip install --quiet --upgrade pip >&2 + "$VENV/bin/python" -m pip install --quiet "${BASE_DEPS[@]}" >&2 + fi + venv_ready || { log "WARNING: could not build a 3.12 venv at $VENV"; return 1; } +} + +# This repo's own dependencies, if it declares any. Additive and marked, so a +# session holding several repos installs each repo's set exactly once. +ensure_repo_extras() { + [ -r "$EXTRAS_FILE" ] || return 0 + local marker args=() + marker="$VENV/.extras-$(cksum <"$EXTRAS_FILE" | tr -d ' /')" + [ -e "$marker" ] && return 0 + while IFS= read -r line; do + line="${line%%#*}" + line="$(printf '%s' "$line" | tr -d '\r' | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')" + [ -n "$line" ] && args+=("$line") + done <"$EXTRAS_FILE" + [ ${#args[@]} -gt 0 ] || return 0 + log "installing this repo's declared deps: ${args[*]}" + if (cd "$(dirname "$(dirname "$EXTRAS_FILE")")" && "$VENV/bin/python" -m pip install --quiet "${args[@]}" >&2); then + : >"$marker" + else + log "WARNING: $EXTRAS_FILE install failed; continuing without it" + fi +} + +# 2. What PATH means without this session's env file. +# +# This leg is the one that matters most, because the env file is exactly what a +# multi-repo session does NOT get: Claude Code registers project hooks from the +# session's project directory, that directory is the repos' parent, and no hook +# runs there (see leg 5). So every Bash call in such a session resolves whatever +# the image put on PATH, and these two names are the fallback that has to be +# right on its own. +# +# It used to point them at the BASE interpreter — `point_system_default +# "$(readlink -f "$VENV/bin/python")"` resolved the venv's python straight +# through to /usr/bin/python3.12. That satisfied the version question and lost +# everything else: `python3 -m pytest` answered "No module named pytest", and +# the session's own venv, sitting one directory away with pytest in it, was +# unreachable from any shell. +# +# Two details make the fix work: +# +# * A wrapper script, not a symlink. Python resolves a symlinked executable +# before looking for `pyvenv.cfg`, so a symlink to $VENV/bin/python lands on +# the base interpreter's prefix and the venv is lost again — silently, and +# in the same shape as the bug being fixed. `exec`ing it keeps the venv. +# * --system-site-packages on the venv (see ensure_venv), so pointing the +# system default here adds the session's packages without removing the +# image's. +# Bounded, because this predicate is what runs a candidate interpreter — and +# the one failure mode worth surviving is an interpreter that never returns. +venv_backed() { + [ -x "$1" ] || return 1 + [ "$(timeout 20 "$1" -c 'import sys; print(sys.prefix)' 2>/dev/null)" = "$VENV" ] +} + +# Does following $1's symlinks pass through $2? A venv's python legitimately +# RESOLVES to the same base interpreter a system default points at, so comparing +# endpoints refuses safe rewrites. The question that matters is narrower: is the +# path being rewritten a link in the target's own chain — because then the +# wrapper execs itself. +links_through() { + local node="$1" needle="$2" hops=0 + needle="$(cd "$(dirname "$needle")" 2>/dev/null && printf '%s/%s' "$(pwd -P)" "$(basename "$needle")")" + while [ -L "$node" ] && [ "$hops" -lt 40 ]; do + node="$(cd "$(dirname "$node")" && cd "$(dirname "$(readlink "$node")")" 2>/dev/null && printf '%s/%s' "$(pwd -P)" "$(basename "$(readlink "$node")")")" + [ "$node" = "$needle" ] && return 0 + hops=$((hops + 1)) + done + return 1 +} + +# `rm -f` first, and it is not tidiness. /usr/local/bin/python3 is a SYMLINK to +# the real interpreter, and a redirect opens the link's TARGET: `cat >` there +# overwrites /usr/bin/python3.12 itself with this wrapper. The venv's own +# python symlinks to that same file, so the wrapper then execs itself — the +# container loses its interpreter and every `python3` spins at 100% CPU. Writing +# a fresh file at the path replaces the link instead of following it. +# +# `links_through` is the second half of the same guard: a target that reaches +# the destination through its own symlink chain builds the identical loop by the +# other route, so refuse rather than write it. +write_venv_shim() { + local dest="$1" target="$2" + [ -w "$(dirname "$dest")" ] || { log "WARNING: cannot rewrite $dest (not writable)"; return 1; } + [ -x "$target" ] || { log "WARNING: $target is not executable; leaving $dest alone"; return 1; } + if links_through "$target" "$dest"; then + log "WARNING: refusing to point $dest at $target — it links back through $dest" + return 1 + fi + rm -f "$dest" + cat >"$dest" < $VENV/bin/python (venv, with pytest and yaml)" \ + || log "WARNING: $bin/python3 is still $(timeout 20 "$bin/python3" -V 2>&1)" +} + +# 2b. The `pytest` that PATH actually finds. +# +# $HOME/.local/bin precedes /usr/local/bin, and it holds uv's tool shims — so +# fixing python3 alone still leaves bare `pytest` resolving to uv's ISOLATED +# pytest, which by design cannot see PyYAML or a repo's own extras. In this +# workspace that made `pytest` exit on four collection ImportErrors that read +# like broken source, in a session where the suite was in fact green. +# +# A session should have exactly one pytest, and it should be the venv's. +# Confined to uv's own shim directory: a distro-packaged pytest is not ours to +# overwrite. Runs after retool_uv_tools, which rewrites these same shims. +point_pytest_at_venv() { + local shim_dir="${HOME}/.local/bin" name path + [ -x "$VENV/bin/pytest" ] || return 0 + for name in pytest py.test; do + path="$(command -v "$name" 2>/dev/null)" || continue + [ -n "$path" ] || continue + case "$path" in + "$VENV"/*) continue ;; + "$shim_dir"/*) ;; + *) log "WARNING: $name resolves to $path, outside uv's shim dir — left alone"; continue ;; + esac + write_venv_shim "$path" "$VENV/bin/$name" \ + && log "$path -> $VENV/bin/$name (so \`$name\` sees this repo's deps)" + done +} + +# 2c. Every OTHER console script the venv owns. +# +# `pytest` and `python3` survive without the venv on PATH because 2 and 2b give +# each one its own shim. Nothing else does — and PATH is exactly what a +# multi-repo session never gets, because the env file that exports it is written +# by Claude Code around a hook it never registers (see leg 5). So a dependency +# declared in `.claude/session-python.txt` that ships a CONSOLE SCRIPT rather +# than an importable module was installed into the venv and then invisible. +# +# Measured, not hypothetical: PyAutoHands shells out to `ipynb-py-convert`, and +# with the package installed its suite still failed five tests with +# `FileNotFoundError: ipynb-py-convert` — the binary sitting in $VENV/bin, +# unreachable, while `--check` called the session healthy. A missing binary and +# an unreachable one are the same symptom, and neither says "environment". +# +# The claim policy is 2b's, because the reasoning is 2b's: a name we can reach +# only through uv's shim dir or not at all is ours to provide; a name the image +# owns elsewhere is not ours to overwrite. +point_venv_scripts_at_venv() { + local shim_dir="${HOME}/.local/bin" entry name path + [ -d "$VENV/bin" ] || return 0 + mkdir -p "$shim_dir" 2>/dev/null || return 0 + for entry in "$VENV"/bin/*; do + [ -f "$entry" ] && [ -x "$entry" ] || continue + name="$(basename "$entry")" + case "$name" in + # python/pip are legs 2 and the venv's own plumbing; pytest is 2b. + # The activate family is meant to be sourced, never executed. + python*|pip*|pytest|py.test|activate*|deactivate*|*.bat|*.ps1|*.csh|*.fish|*.nu) continue ;; + esac + path="$(command -v "$name" 2>/dev/null)" || path="" + case "$path" in + "$VENV"/*) continue ;; + "") ;; + "$shim_dir"/*) ;; + *) log "WARNING: $name resolves to $path, outside uv's shim dir — left alone"; continue ;; + esac + write_venv_shim "$shim_dir/$name" "$entry" \ + && log "$shim_dir/$name -> $entry (venv console script)" + done +} + +# 3. The uv-managed tools — rebuilt on 3.12 only where they are not already. +# +# Pinned to the version already installed: this hook changes the INTERPRETER a +# tool runs on, and nothing else. Unpinned, `uv tool install --force` fetches +# the latest release, which quietly moved mypy across a major version (1.19 -> +# 2.3) the first time this ran — a lint-result change nobody asked for, riding +# in on a Python upgrade. Falls back to unpinned only if the pin cannot be +# resolved for 3.12. +retool_uv_tools() { + command -v uv >/dev/null 2>&1 || return 0 + local tools_dir tool name version spec + tools_dir="$(uv tool dir 2>/dev/null || echo "$HOME/.local/share/uv/tools")" + [ -d "$tools_dir" ] || return 0 + for tool in "$tools_dir"/*/; do + name="$(basename "$tool")" + is_py312 "$tool/bin/python" && continue + version="$(uv tool list 2>/dev/null | awk -v n="$name" '$1 == n {print substr($2, 2); exit}')" + spec="$name" + [ -n "$version" ] && spec="$name==$version" + if uv tool install --python 3.12 --force "$spec" >/dev/null 2>&1 \ + || uv tool install --python 3.12 --force "$name" >/dev/null 2>&1; then + log "rebuilt ${spec} on 3.12" + else + log "WARNING: could not rebuild $name on 3.12; it stays on $("$tool/bin/python" -V 2>&1)" + fi + done +} + +# 3b. The link uv's rebuild cannot fix from inside. +# +# uv creates each tool env with `bin/python` as a SYMLINK to whatever `python3` +# was at install time — here `/usr/local/bin/python3`, which leg 2 has already +# replaced with a wrapper that `exec`s the session venv. Every tool env's python +# then resolves its prefix to the VENV: `sys.prefix` is the venv, the tool's own +# site-packages never reaches `sys.path`, and the console script dies with +# `ModuleNotFoundError: No module named 'flake8'` — with flake8 sitting +# installed two directories away. +# +# TWO paths reach that state, which is why this runs after leg 3 rather than +# only on the envs leg 3 rebuilt: leg 3 rebuilds a 3.11 tool and hands the new +# env the hijacked path, and leg 2 separately breaks every PRE-EXISTING tool env +# that already pointed there and that leg 3 skips (`is_py312 … && continue`). +# Running here covers both, because leg 2 runs before leg 3. +# +# Measured 2026-08-27, post-bootstrap: mypy, flake8, black, poetry and pyright +# all dead this way; `ruff` survived (a native binary) and `pytest` survived +# (leg 2b points its shim straight at the venv, which has pytest). The +# bootstrap's `--check` called every one of them "3.12 OK", because the +# interpreter they reach IS 3.12 — it is simply the wrong one. A session then +# lints clean by not linting at all, and CI is the thing that finds out. +# +# The fix is one link: a venv's `bin/python` must resolve to a BASE interpreter, +# never to a path this hook hijacks. +# +# This lived in `scripts/session_bootstrap.sh` for one pass, which is the wrong +# home. The bootstrap is what a MULTI-repo session runs; a SINGLE-repo session +# registers this hook and never calls the bootstrap, so it got leg 2's breakage +# and none of the repair. +repair_uv_tools() { + local tools_dir base tool link prefix + base="$("$VENV/bin/python" -c 'import sys, os; print(os.path.join(sys.base_prefix, "bin", "python3.12"))' 2>/dev/null)" || base="" + [ -x "$base" ] || base="$(command -v python3.12 2>/dev/null)" || base="" + [ -x "$base" ] || return 0 + tools_dir="${PYAUTO_UV_TOOLS_DIR:-$(uv tool dir 2>/dev/null || echo "$HOME/.local/share/uv/tools")}" + [ -d "$tools_dir" ] || return 0 + for tool in "$tools_dir"/*/; do + link="${tool}bin/python" + [ -L "$link" ] || continue + # Ask the interpreter where it thinks it lives, rather than tracing the + # link: `/usr/local/bin/python3` is a WRAPPER SCRIPT (a symlink there + # would lose the venv — leg 2's whole note), so `readlink -f` stops at + # the wrapper and reports nothing about the venv behind it. sys.prefix + # is the outcome; anything else is the mechanism. + prefix="$("$link" -c 'import sys; print(sys.prefix)' 2>/dev/null)" || continue + [ -n "$prefix" ] || continue + [ "$prefix" = "${tool%/}" ] && continue # resolves to its own env: correct + # Non-fatal like every other leg: an unwritable tools dir is a warning, + # never a failed session start. + ln -sfn "$base" "$link" || { + log "WARNING: could not repoint $(basename "${tool%/}") at $base" + continue + } + prefix="$("$link" -c 'import sys; print(sys.prefix)' 2>/dev/null)" || prefix="" + if [ "$prefix" = "${tool%/}" ]; then + log "repointed $(basename "${tool%/}") at $base (it resolved into $VENV, not its own env)" + else + log "WARNING: $(basename "${tool%/}") still resolves to ${prefix:-nothing} — it will not run" + fi + done +} + +# 4. Honest git history. +# +# A remote session clones shallow. `git merge-base --is-ancestor` then LIES +# across the graft boundary: it reports "not an ancestor" for a commit whose +# ancestry is simply not in the clone, and the ship/close-out skills act on that +# answer. A completion record already logged this the hard way +# (complete/2026/08/status-sh-repos-missing-source.md, "environment note"). +# +# These repos are small (single-digit MB of .git), so unshallowing costs a +# couple of seconds once per container and removes a whole class of wrong +# answer. Bounded and non-fatal: a slow or blocked network leaves a shallow +# clone and a warning, never a failed session start. +unshallow_checkout() { + local repo + repo="${1%/}/" # the callers glob, but do not rely on the trailing slash + [ -e "${repo}.git/shallow" ] || return 0 + log "unshallowing $(basename "${repo%/}") (shallow clones make ancestry checks lie)" + if timeout 120 git -C "$repo" fetch --unshallow --quiet 2>/dev/null \ + || timeout 120 git -C "$repo" fetch --depth=2147483647 --quiet 2>/dev/null; then + log " $(basename "${repo%/}"): full history ($(git -C "$repo" rev-list --count HEAD 2>/dev/null) commits)" + else + log " WARNING: $(basename "${repo%/}") is still shallow — run 'git fetch --unshallow' before trusting any ancestry check" + fi +} + +# Two levels, not one. A workspace is `/` or, once its checkouts +# are grouped, `//` — and a family directory has no `.git`, +# so a one-level walk steps straight over every checkout inside it and leaves +# them shallow while reporting nothing. A directory that IS a checkout is never +# descended into (a repo's own subdirectories are not siblings), and the walk +# stops at two levels because that is the shape of the workspace: an unbounded +# walk over every checked-out repo is not something a session start can afford. +ensure_full_clone() { + local entry child + for entry in "$WORKSPACE_ROOT"/*/; do + [ -d "$entry" ] || continue + if [ -e "${entry}.git" ]; then + unshallow_checkout "$entry" + continue + fi + for child in "$entry"*/; do + [ -d "$child" ] && [ -e "${child}.git" ] || continue + unshallow_checkout "$child" + done + done +} + +# 5. Make the NEXT session in this container start correctly. +# +# Claude Code registers project hooks from the session's project directory. In a +# one-repo session that IS the repo, and `/.claude/settings.json` is found. +# In a session holding several organs the project directory is their parent, +# which is not a repo and has no `.claude/` — so none of the per-repo hooks are +# registered and none of this script runs. That is why a multi-repo session came +# up on the container's Python 3.11: not a broken hook, an unreachable one. +# +# A repo cannot ship a file into its own parent, so install it at run time. The +# settings we write fan out to every sibling repo's own hook, so the layout +# stays "each repo owns its hook" and this file stays generated-from-one-source. +# It takes effect on the next session start in this container. +install_workspace_settings() { + # Target the WORKSPACE ROOT, derived from this checkout — not + # $CLAUDE_PROJECT_DIR, and not only when the two differ. + # + # The early return this replaces ("only in the multi-repo layout") made the + # whole leg unreachable. Writing the fan-out requires the hook to be + # running; the hook runs only in a session whose project dir is a repo — + # that is, a SINGLE-repo session — and the early return then skipped it as + # having nothing to add. So the one session type that could seed the + # container never did, and the multi-repo session that needed it never ran + # the hook to find out. Observed directly: a container with two single-repo + # sessions behind it still had no workspace-root settings, and the next + # session — three organs, project dir /home/user — fired no hook, ran on + # PATH's pytest, and left both clones shallow for three minutes until an + # unrelated verb happened to knock on session_bootstrap.sh. + # + # A single-repo session has the same sibling layout one directory up, so it + # can seed the root for free. Skip only if the root is itself a repo (then + # it owns its own hook) or is not writable. + local root="$WORKSPACE_ROOT" + [ -n "$root" ] && [ -d "$root" ] || return 0 + [ -d "$root/.git" ] && return 0 + + local settings="$root/.claude/settings.json" + local fanout="$root/.claude/hooks/session-start.sh" + [ -w "$root" ] || { log "WARNING: $root not writable ($WORKSPACE_ROOT_REASON); multi-repo sessions will keep skipping the hook"; return 0; } + + mkdir -p "$(dirname "$fanout")" + rm -f "$fanout" # never write through a symlink; see write_venv_shim + cat >"$fanout" <<'FANOUT' +#!/usr/bin/env bash +# GENERATED at session start by a PyAuto repo's own session-start hook. +# Runs every sibling repo's hook, because the workspace root is not a repo and +# therefore has no hook of its own. Each repo's hook is idempotent, so the +# second and later ones cost ~0.2s. +set -u +ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../.." && pwd)" + +# Run one checkout's hook. Non-zero only when there is no hook to run, which is +# how a family directory is told apart from a checkout. +run_repo_hook() { + hook="${1%/}/.claude/hooks/session-start.sh" + [ -x "$hook" ] || return 1 + CLAUDE_PROJECT_DIR="${1%/}" "$hook" || \ + printf '[session-start] WARNING: %s failed\n' "$hook" >&2 + return 0 +} + +# Two levels: the checkouts directly under the root, and those one level down +# inside a family directory once the workspace groups them. Anything that +# already carries a hook is run, never walked into. +for entry in "$ROOT"/*/; do + [ -d "$entry" ] || continue + run_repo_hook "$entry" && continue + for child in "$entry"*/; do + [ -d "$child" ] || continue + run_repo_hook "$child" || true + done +done +FANOUT + chmod 0755 "$fanout" + + if [ ! -f "$settings" ]; then + cat >"$settings" <<'SETTINGS' +{ + "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/session-start.sh" + } + ] + } + ] + } +} +SETTINGS + log "installed $settings ($WORKSPACE_ROOT_REASON) — multi-repo sessions in this container now run the hook" + fi +} + +# Git history and hook reachability have nothing to do with the interpreter, so +# they run first and unconditionally: a container where the 3.12 venv cannot be +# built still wants honest ancestry and a hook that fires next session. +# PYAUTO_SESSION_DEFINE_ONLY=1 defines every function and performs no action — +# the seam this hook's own tests use to drive one leg at a time against a +# temporary directory, instead of against the container they run in. Sourcing +# returns; executing exits. +if [ "${PYAUTO_SESSION_DEFINE_ONLY:-}" = "1" ]; then + return 0 2>/dev/null || exit 0 +fi + +# Run leg 3b on its own, without a session start. The door +# `scripts/session_bootstrap.sh` knocks on after it has run every repo's hook — +# a subprocess rather than a source, so this script's `set -euo pipefail` never +# leaks into a caller that is contractually "a bootstrap, never a gate". +if [ "${1:-}" = "--repair-uv-tools" ]; then + repair_uv_tools + exit 0 +fi + +ensure_full_clone +install_workspace_settings + +# PYAUTO_SESSION_SKIP_PYTHON=1 stops here — the seam the hook's own tests use to +# exercise the legs above without building an interpreter. +if [ "${PYAUTO_SESSION_SKIP_PYTHON:-}" = "1" ]; then + log "PYAUTO_SESSION_SKIP_PYTHON=1 — leaving the interpreter alone" + exit 0 +fi + +if ensure_venv; then + ensure_repo_extras + point_system_default + retool_uv_tools + repair_uv_tools + point_pytest_at_venv + point_venv_scripts_at_venv + # Every repo in the session registers this hook, so the second copy must not + # prepend the venv a second time. + if [ -n "${CLAUDE_ENV_FILE:-}" ] && ! grep -qs 'PYAUTO_SESSION_PY312=' "$CLAUDE_ENV_FILE"; then + { + echo "export PYAUTO_SESSION_PY312=\"$VENV\"" + echo "export VIRTUAL_ENV=\"$VENV\"" + echo "export PATH=\"$VENV/bin:\$PATH\"" + # The workspace root, so the Brain's shell/python resolvers agree + # with the session instead of each re-deriving it — and how it was + # reached, because an unverified root that a consumer inherits is + # exactly the answer that used to be wrong without saying so. + echo "export PYAUTO_ROOT=\"$WORKSPACE_ROOT\"" + echo "export PYAUTO_ROOT_REASON=\"$WORKSPACE_ROOT_REASON\"" + } >>"$CLAUDE_ENV_FILE" + fi + log "default python is now $("$VENV/bin/python" -V 2>&1) ($VENV/bin)" +fi diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..5578c7d --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,25 @@ +{ + "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/session-start.sh" + } + ] + } + ], + "PreToolUse": [ + { + "matcher": "^(send_later|subscribe_pr_activity|ScheduleWakeup|CronCreate|RemoteTrigger|mcp__.*(send_later|subscribe_pr_activity).*)$", + "hooks": [ + { + "type": "command", + "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/end-at-deliverable.sh" + } + ] + } + ] + } +} diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 0000000..bc3fdff --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,112 @@ +# lint.yml — PR / push-to-main gate. +# +# CPU-only. Runs on every PR and on push to main against the PyAutoLabs library +# MAINS (the stack a figure change is developed against): +# +# 1. ruff check + ruff format --check +# 2. gallery_build.py --check on the COMMITTED figures (GALLERY.md current) +# 3. pytest scripts/misc/test (hermetic gallery-builder tests) +# 4. lychee link-rot over every *.md (GALLERY.md's image links included) +# 5. run EVERY producer (imaging, interferometer, ellipse) for real, then gallery_build.py --check again — proves +# they still render on the mains and that the committed GALLERY.md lists +# exactly the figure set they produce (a stale committed gallery fails the +# PR). There is no pixel diff: re-rendered PNG bytes are not compared. +# +# Refreshing the committed PNGs on a release lives in `render.yml`. + +name: lint + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + lint: + runs-on: ubuntu-latest + timeout-minutes: 40 + env: + NUMBA_CACHE_DIR: /tmp/numba_cache + MPLCONFIGDIR: /tmp/matplotlib + PYTHONPATH: ${{ github.workspace }}/PyAutoNerves:${{ github.workspace }}/PyAutoFit:${{ github.workspace }}/PyAutoArray:${{ github.workspace }}/PyAutoGalaxy + steps: + - name: Checkout autogalaxy_visualization + uses: actions/checkout@v4 + with: + path: autogalaxy_visualization + + - name: Checkout PyAutoNerves + uses: actions/checkout@v4 + with: + repository: PyAutoLabs/PyAutoNerves + path: PyAutoNerves + - name: Checkout PyAutoFit + uses: actions/checkout@v4 + with: + repository: PyAutoLabs/PyAutoFit + path: PyAutoFit + - name: Checkout PyAutoArray + uses: actions/checkout@v4 + with: + repository: PyAutoLabs/PyAutoArray + path: PyAutoArray + - name: Checkout PyAutoGalaxy + uses: actions/checkout@v4 + with: + repository: PyAutoLabs/PyAutoGalaxy + path: PyAutoGalaxy + + - name: Set up Python 3.12 + uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Install runtime dependencies + run: | + python -m pip install --upgrade pip setuptools wheel + # Install each sibling checkout in dependency order: satisfies the full + # third-party dep chain without a hand-maintained list. PYTHONPATH (job + # env) still resolves the PyAuto* imports from the checkouts. + for r in PyAutoNerves PyAutoFit PyAutoArray PyAutoGalaxy; do + pip install "./$r[optional]" + done + + - name: Install lint tools + run: | + pip install ruff pytest + curl -sSfL https://github.com/lycheeverse/lychee/releases/latest/download/lychee-x86_64-unknown-linux-gnu.tar.gz \ + | tar -xz -C /usr/local/bin --strip-components=1 lychee-x86_64-unknown-linux-gnu/lychee + + - name: ruff check + working-directory: autogalaxy_visualization + run: ruff check . + + - name: ruff format --check + working-directory: autogalaxy_visualization + run: ruff format --check . + + - name: gallery_build.py --check (committed figures) + working-directory: autogalaxy_visualization + run: python gallery/gallery_build.py --check + + - name: pytest — scripts/misc/test/ + working-directory: autogalaxy_visualization + run: pytest scripts/misc/test/ -q + + - name: lychee — markdown link-rot + working-directory: autogalaxy_visualization + run: | + lychee \ + --exclude '^https://github\.com/.*/(issues|pull|commit|releases)/' \ + --exclude '^https://join\.slack\.com/' \ + --no-progress \ + --accept '200..=299,429' \ + --max-redirects 5 \ + $(find . -name '*.md' -not -path './output/*' -not -path './.claude/*') + + - name: Render every producer + gallery_build.py --check + working-directory: autogalaxy_visualization + run: bash gallery/gallery_run.sh --all diff --git a/.github/workflows/render.yml b/.github/workflows/render.yml new file mode 100644 index 0000000..27ed9f9 --- /dev/null +++ b/.github/workflows/render.yml @@ -0,0 +1,101 @@ +# render.yml — manual + on-PyAutoGalaxy-release figure refresh. +# +# Installs the RELEASED stack from PyPI (what users get), runs every producer via +# `gallery/gallery_run.sh --all`, rebuilds GALLERY.md and the tracked figure +# manifest `gallery/viz_manifest.yaml`, commits the refreshed PNGs + GALLERY.md + +# manifest back to main as `github-actions[bot]` with `[skip ci]`, and then fires a +# `repository_dispatch` (`eyes-refresh`) at PyAutoLabs/PyAutoEyes so the organ's +# cross-project dashboard re-reads the manifest. +# +# Triggers: +# - workflow_dispatch (manual, GitHub UI) +# - repository_dispatch type `pyautogalaxy-release`, sent by the release pipeline +# once a PyAutoGalaxy release is on PyPI (the sender in the Hands release +# pipeline is not wired yet; until then this runs by workflow_dispatch). +# +# Copied from autolens_visualization/.github/workflows/render.yml (itself adapted +# from autolens_profiling/.github/workflows/profile.yml). `[skip ci]` keeps +# lint.yml from re-running on the bot commit (it would loop); `contents: write` +# lets the bot push. The PyAutoEyes dispatch needs a cross-repo token: it uses +# `secrets.PAT_PYAUTOLABS` (the org PAT the Hands release pipeline uses), which must +# be granted to this repo and must cover PyAutoLabs/PyAutoEyes; without it the step +# warns and skips rather than failing the render. + +name: render + +on: + workflow_dispatch: + inputs: + autogalaxy_version: + description: "PyPI autogalaxy version to render with (blank = latest)" + required: false + default: "" + repository_dispatch: + types: [pyautogalaxy-release] + +permissions: + contents: write + +jobs: + render: + runs-on: ubuntu-latest + timeout-minutes: 60 + env: + NUMBA_CACHE_DIR: /tmp/numba_cache + MPLCONFIGDIR: /tmp/matplotlib + steps: + - name: Checkout autogalaxy_visualization + uses: actions/checkout@v4 + with: + token: ${{ secrets.GITHUB_TOKEN }} + + - name: Set up Python 3.12 + uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Install the released stack from PyPI + env: + VERSION: ${{ inputs.autogalaxy_version || github.event.client_payload.version || '' }} + run: | + python -m pip install --upgrade pip + if [ -n "$VERSION" ]; then + pip install "autogalaxy[optional]==$VERSION" + else + pip install "autogalaxy[optional]" + fi + python -c "import autogalaxy; print('autogalaxy', autogalaxy.__version__)" + + - name: Render figures + rebuild GALLERY.md + gallery/viz_manifest.yaml + run: bash gallery/gallery_run.sh --all + + - name: Commit and push refreshed figures + GALLERY.md + manifest + run: | + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git add -A scripts/*/images GALLERY.md gallery/viz_manifest.yaml + if git diff --cached --quiet; then + echo "No changes — exiting clean." + exit 0 + fi + version=$(python -c "import autogalaxy; print(autogalaxy.__version__)") + git commit -m "chore: re-render gallery with autogalaxy ${version} [skip ci] + + Triggered by ${{ github.event_name }} (run ${{ github.run_id }})." + git push origin HEAD:main + + - name: Tell the PyAutoEyes dashboard to refresh (repository_dispatch eyes-refresh) + env: + GH_TOKEN: ${{ secrets.PAT_PYAUTOLABS }} + run: | + if [ -z "$GH_TOKEN" ]; then + echo "::warning::PAT_PYAUTOLABS is not available to this repo — skipping the eyes-refresh dispatch to PyAutoLabs/PyAutoEyes." + exit 0 + fi + sha=$(git rev-parse HEAD) + gh api repos/PyAutoLabs/PyAutoEyes/dispatches \ + -f event_type=eyes-refresh \ + -f "client_payload[repo]=${{ github.repository }}" \ + -f "client_payload[sha]=${sha}" \ + -f "client_payload[manifest]=gallery/viz_manifest.yaml" + echo "Dispatched eyes-refresh to PyAutoLabs/PyAutoEyes (${{ github.repository }}@${sha})." diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..90d0af9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,22 @@ +__pycache__/ +*.pyc +.ruff_cache/ +.pytest_cache/ +output/ +*.log + +# JAX / numba / matplotlib caches (when not redirected via env vars) +.jax_cache/ +__jax_cache__/ +.numba_cache/ +.mplconfig/ + +# Local virtualenvs +.venv/ +venv/ + +# Visualizer outputs: PNG figures are TRACKED (they are the gallery); the FITS / CSV / +# JSON data products the visualizer also writes are bulky and not viewable on GitHub. +scripts/**/images/**/*.fits +scripts/**/images/**/*.csv +scripts/**/images/**/*.json diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..99c9da2 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,231 @@ +# autogalaxy_visualization — Agent Instructions + +This repo is the single home for **what PyAutoGalaxy figures look like**: it stores, in git, the +most up-to-date rendering of every figure the PyAutoGalaxy visualizers write during a model-fit, +on realistic HST-scale imaging and SMA-scale interferometer data, so visualization can be judged +and improved (by humans or AI chats against the source) without re-running a workspace fit. It is +a collection of standalone producer scripts, **not** an installable package — there is no +`pyproject.toml`. These are the canonical, agent-agnostic instructions for this repo; the +`README.md` is the human-facing overview and `GALLERY.md` is the browsable gallery. It is the +galaxy sibling of `lens/autolens_visualization` and mirrors its layout exactly. + +## Layering: project repo vs organ + +This is a **project repo** (category `project`, like `autolens_visualization`): it makes, stores +and tracks the galaxy figures — producers, simulators, datasets, `plots.yaml`, instruments, +tracked PNGs, `GALLERY.md`, the render harness. The organ **PyAutoEyes** is the cross-project +visualization dashboard over the `_visualization` project repos: it reads this repo's +tracked `gallery/viz_manifest.yaml` and links to the PNGs here; it renders nothing and copies no +figures. Judging figures is the Brain's Eyes conductor; figure changes land here (producer / +config) or in the libraries (plot API), never in the organ. + +## Repository Structure + +Producers are laid out **flat, one per domain** (`scripts//visualization*.py`), because +the Brain Eyes agent scans `scripts//*.py` non-recursively for stems containing +`visualization`: + +``` +scripts/ + imaging/visualization.py VisualizerImaging on dataset/imaging/hst + imaging/images/visualization/ its output: before-fit PNGs + parametric/ + delaunay/ + interferometer/visualization.py VisualizerInterferometer on dataset/interferometer/sma + interferometer/images/visualization/ + ellipse/visualization.py VisualizerEllipse on dataset/imaging/hst + ellipse/images/visualization/ before-fit + plain/ multipole/ multipole_scaled/ masked/ + misc/simulators/ imaging.py + interferometer.py (regenerate datasets) + misc/test/ hermetic pytest for the gallery builder +gallery/gallery_build.py GALLERY.md + gallery/viz_manifest.yaml + output/gallery/ +gallery/viz_manifest.yaml TRACKED, generated figure manifest (PyAutoEyes read contract) +gallery/gallery_run.sh run producers -> build -> --check +config/general.yaml layered over the library config (version check off) +config/visualize/plots.yaml the library default with EVERY toggle on +instruments/ imaging + interferometer presets (copied from autolens_visualization) +dataset/imaging/hst/ TRACKED, simulated here (Sersic bulge + Exponential disk) +dataset/interferometer/sma/ TRACKED, simulated here (190 visibilities, same galaxy) +_viz_cli.py repo-root finder, dataset paths, auto-simulate hook +GALLERY.md TRACKED, generated — never edit by hand +``` + +**What is tracked.** PNG figures under `scripts//images/**`, `GALLERY.md`, +`gallery/viz_manifest.yaml` and the datasets (FITS + `galaxies.json`). The FITS / CSV / JSON data +products the visualizers also write are gitignored (bulky, not viewable on GitHub), as is +`output/`. + +**Import model.** Producers find the repo root by walking up to the directory containing +`ruff.toml` (a depth-proof sentinel) and put it on `sys.path`, so `_viz_cli` and `instruments` +import by their top-level names. + +## Rendering + +From the repo root, with the library checkouts on `PYTHONPATH` (`source activate.sh`): + +```bash +bash gallery/gallery_run.sh --all # every producer, then build + --check (~90 s) +python scripts/imaging/visualization.py # one producer (~35 s) +python gallery/gallery_build.py # rebuild GALLERY.md + gallery/viz_manifest.yaml + output/gallery/ +python gallery/gallery_build.py --check # fail if GALLERY.md or the manifest is stale vs the PNGs on disk +``` + +Each producer wipes its own `scripts//images/visualization/` tree first, so the committed +PNG set is exactly what the last run produced. Commit the PNGs, `GALLERY.md` and +`gallery/viz_manifest.yaml` together. + +**The tracked manifest** (`gallery/viz_manifest.yaml`, schema 1) lists every committed PNG as +`{file, producer, domain, source, bytes, sha256}` (`source` = the per-source sub-folder — +`parametric` / `delaunay` for imaging and interferometer, `plain` / `multipole` / +`multipole_scaled` / `masked` for ellipse — or `""` for the before-fit figures), plus +`rendered_with:` (the autogalaxy / autoarray / autofit versions) and `generated:` (the date the +figures or stack last changed — carried over on an unchanged rebuild, so re-running is a git +no-op). There are no mtimes: it is reproducible from a checkout. `--check` ignores only +`generated:` and `rendered_with:`; any added, removed or byte-changed PNG fails it. It is the +read contract of the PyAutoEyes dashboard — change its shape only together with the organ. + +Each producer pushes `config/` via `conf.instance.push` (the all-true `plots.yaml`), loads its +tracked dataset, builds the simulator's **true model** (every parameter fixed), and calls +`Visualizer*.visualize_before_fit` once and `Visualizer*.visualize` once per source type +(`parametric/` = Sersic bulge + Exponential disk, `delaunay/` = Overlay image-mesh + `Delaunay` ++ `ConstantSplit`; for ellipse, one call per scenario), with a +`SimpleNamespace(image_path=..., output_path=...)` paths stub. The adapt image is the galaxy +image of the parametric fit, keyed `('galaxies', 'galaxy')`. + +**Toggles no PyAutoGalaxy plotter reads (yet).** `fit.subplot_fit_log10`, +`fit.subplot_galaxy_images` and `inversion.subplot_mappings` are true in `plots.yaml` but the +PyAutoGalaxy plotters do not consult them today, so no `fit_log10.png` or mappings figure +appears. `visualize_combined` / `visualize_before_fit_combined` are not rendered: they need +several analyses (a multi-dataset fit). In the ellipse domain the `data`, `data_no_ellipse` and +log10 variants all write `ellipse_fit.png`, so only the last-written variant survives — a +library-side naming collision, visible in the gallery. + +**Datasets.** Both were produced by this repo's simulators: + +```bash +python scripts/misc/simulators/imaging.py --instrument hst +python scripts/misc/simulators/interferometer.py --instrument sma +``` + +One galaxy at z=0.5 (Sersic bulge I=2.0, R=0.6", n=3 + Exponential disk I=1.0, R=1.6") in both. +The SMA visibilities are transformed from the preset's 3.5" circular real-space mask (the one +the producer fits with) with no over-sampling, because the disk extends past the mask and the +Interferometer dataset evaluates light profiles at sub-size 1 — so the true-model residuals are +noise. The `sma` preset's `noise_sigma` is 10.0 (autolens_profiling: 1000.0), so the dirty image +shows the galaxy instead of pure noise. The ellipse producer reuses the imaging dataset (the PSF +is ignored by ellipse fitting). The auto-simulate hook in `_viz_cli.py` only fires when +`data.fits` is absent — it never deletes a tracked dataset. + +## Adding a domain + +1. Add a simulator under `scripts/misc/simulators/` (or an instrument preset) and track its + dataset under `dataset///`. +2. Add a flat producer `scripts//visualization.py` modelled on the imaging one, writing + to `scripts//images/visualization/`. +3. Run `bash gallery/gallery_run.sh --all` and commit the PNGs + `GALLERY.md` + + `gallery/viz_manifest.yaml`. + +## Improving a figure (edit surfaces) + +- **config** — `config/visualize/plots.yaml` here: which figures are written at all. +- **plot API** — the plotting code in the libraries: `PyAutoGalaxy/autogalaxy/**/plot/`, + `PyAutoArray/autoarray/plot/` (library changes go through the normal library workflow, then + this repo is re-rendered). +- **script** — the producer in `scripts//visualization.py` (dataset, model, source types). + +## Eyes contracts + +Two readers depend on this repo's layout: + +- **The Brain Eyes conductor** (`organs/PyAutoBrain/agents/conductors/eyes/`) reviews it: + `bin/pyauto-brain eyes survey galaxy/autogalaxy_visualization` (or `/eyes review galaxy`). It + expects flat `scripts//visualization*.py` producers writing + `scripts//images//**`, a `gallery/gallery_run.sh` harness, and + `output/gallery/{gallery.html,viz_manifest.yaml}` (the latter a gitignored copy of the tracked + manifest). Accepted critiques are labelled `eyes-critique` and route through intake / + start_dev like any other change. +- **The PyAutoEyes dashboard** reads the tracked `gallery/viz_manifest.yaml` and links to the + PNGs; `render.yml` fires `repository_dispatch: eyes-refresh` at PyAutoLabs/PyAutoEyes after + each release re-render. + +Keep that layout when adding domains. + +## Testing + +The PR gate is `lint.yml` on Python 3.12 against the library mains (PyAutoNerves, PyAutoFit, +PyAutoArray, PyAutoGalaxy): + +```bash +ruff check . +ruff format --check . +python gallery/gallery_build.py --check +pytest scripts/misc/test -q +``` + +plus `lychee` on every `*.md`, then every producer runs for real followed by +`gallery_build.py --check` (a PR that changes the figure set without regenerating `GALLERY.md` +fails). `render.yml` (manual + `repository_dispatch: pyautogalaxy-release`) re-renders with the +released PyPI stack, commits PNGs + `GALLERY.md` + `gallery/viz_manifest.yaml` back as +`github-actions[bot]` `[skip ci]`, then dispatches `eyes-refresh` to PyAutoEyes (token: +`secrets.PAT_PYAUTOLABS`; the step warns and skips when the secret is unavailable). + +## Sandboxed / restricted runs + +```bash +NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib python scripts/imaging/visualization.py +``` + +## Bulk-edit safety + +When editing the same region across many scripts in one pass, only rewrite the targeted region. +**Never produce a whole-file write unless you have read the entire current file.** + +## Related Repos + +- `../PyAutoGalaxy` — the visualizers being rendered (plus `../../array/PyAutoArray`, + `../../fit/PyAutoFit`, `../../organs/PyAutoNerves` on `PYTHONPATH`). +- `../autogalaxy_workspace` — user-facing science scripts and tutorials. +- `../autogalaxy_workspace_test` — visualization *tests* (file/HDU assertions) the producers + here were ported from. +- `../../lens/autolens_visualization` — the lens sibling this repo mirrors; source of the + instrument presets, the gallery harness and the builder. +- `../../organs/PyAutoEyes` — the organ: cross-project visualization dashboard that aggregates + this repo via `gallery/viz_manifest.yaml` (links to the PNGs, never copies them). + +## Task Workflows + +When changing a producer, the config or a dataset, re-render (`gallery/gallery_run.sh --all`), +keep `ruff check .` / `ruff format --check .` clean, and commit the PNGs + `GALLERY.md` + +`gallery/viz_manifest.yaml` in the same PR. Do not commit machine-specific absolute paths. + + +## Never rewrite history + +Never rewrite pushed history on any repo with a remote — no `git init` over a +tracked repo, no force-push to `main`, no fresh-start "Initial commit", no +`filter-repo` / `filter-branch` / `rebase -i` on pushed branches. To get a +clean tree: `git fetch origin && git reset --hard origin/main && git clean -fd`. + + + +## Sessions end at their deliverable + +A session ends when it reports its deliverable — never arm anything that +outlives the turn to wait for CI, a review or a merge: no `send_later`, no +`subscribe_pr_activity`, no `CronCreate`, no `ScheduleWakeup`, no `/loop`, no +`RemoteTrigger` create/update/run. Judge once, report, stop; the human re-runs +`/prm` (or the batch review) when it is green. Measured: five batch members +armed hourly check-ins on 2026-08-31, and a mobile `/prm` re-armed a 60-minute +`send_later` hourly all night on 2026-09-03 with no task active, draining usage. + + + +## Where to file + +Questions, help with code or an analysis, ideas, bug reports and results from a +user or collaborator — or an agent acting for one — go to + in the matching category +(Help & Questions, Ideas & Proposals, Bugs & Errors, Show and tell; +Announcements is maintainers-only), never to this repo's Issues. An agent never +runs `gh issue create` for such a report: it drafts the title, category and +body and hands them to the human (sessions cannot create Discussions). Only the +development flow — Mind prompt → `/start_dev` → `/create_issue` → one issue per +task → PR — opens issues here. Why: `PyAutoMind/policy/community_surface.md`. + diff --git a/AI_POLICY.md b/AI_POLICY.md new file mode 100644 index 0000000..7b2ac72 --- /dev/null +++ b/AI_POLICY.md @@ -0,0 +1,5 @@ +# PyAuto AI Policy + +PyAutoLabs uses one AI policy across all of its repositories. + +Read the [canonical PyAuto AI Policy](https://github.com/PyAutoLabs/PyAutoScientist/blob/main/AI_POLICY.md). diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..8fc2b40 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,5 @@ +# autogalaxy_visualization — agent instructions +The canonical, agent-agnostic instructions live in `AGENTS.md`. Claude Code loads them +via the import below; if your tool does not process `@`-imports, open `AGENTS.md` in +this directory and read it directly. +@AGENTS.md diff --git a/GALLERY.md b/GALLERY.md new file mode 100644 index 0000000..8fb3f56 --- /dev/null +++ b/GALLERY.md @@ -0,0 +1,225 @@ +# PyAutoGalaxy Visualization Gallery + + + +Rendered with PyAutoGalaxy `2026.8.17.1` · 41 figures. + +Every figure below is what `VisualizerImaging` / `VisualizerInterferometer` / `VisualizerEllipse` write to a model-fit's `image/` folder, rendered on this repo's datasets with the true model. See [README.md](README.md) for how to improve one. + +## Contents + +- [ellipse](#ellipse) + - [visualization](#ellipse--visualization) (17 figures) + - [top level](#ellipse--visualization--top-level) + - [masked/](#ellipse--visualization--masked) + - [multipole/](#ellipse--visualization--multipole) + - [multipole_scaled/](#ellipse--visualization--multipole_scaled) + - [plain/](#ellipse--visualization--plain) +- [imaging](#imaging) + - [visualization](#imaging--visualization) (11 figures) + - [top level](#imaging--visualization--top-level) + - [delaunay/](#imaging--visualization--delaunay) + - [parametric/](#imaging--visualization--parametric) +- [interferometer](#interferometer) + - [visualization](#interferometer--visualization) (13 figures) + - [top level](#interferometer--visualization--top-level) + - [delaunay/](#interferometer--visualization--delaunay) + - [parametric/](#interferometer--visualization--parametric) + +## ellipse + +### ellipse / visualization + +#### ellipse / visualization / top level + +##### dataset + +![dataset](scripts/ellipse/images/visualization/dataset.png) + +#### ellipse / visualization / masked/ + +##### dataset + +![dataset](scripts/ellipse/images/visualization/masked/dataset.png) + +##### ellipse_fit + +![ellipse_fit](scripts/ellipse/images/visualization/masked/ellipse_fit.png) + +##### ellipse_residuals + +![ellipse_residuals](scripts/ellipse/images/visualization/masked/ellipse_residuals.png) + +##### fit_ellipse + +![fit_ellipse](scripts/ellipse/images/visualization/masked/fit_ellipse.png) + +#### ellipse / visualization / multipole/ + +##### dataset + +![dataset](scripts/ellipse/images/visualization/multipole/dataset.png) + +##### ellipse_fit + +![ellipse_fit](scripts/ellipse/images/visualization/multipole/ellipse_fit.png) + +##### ellipse_residuals + +![ellipse_residuals](scripts/ellipse/images/visualization/multipole/ellipse_residuals.png) + +##### fit_ellipse + +![fit_ellipse](scripts/ellipse/images/visualization/multipole/fit_ellipse.png) + +#### ellipse / visualization / multipole_scaled/ + +##### dataset + +![dataset](scripts/ellipse/images/visualization/multipole_scaled/dataset.png) + +##### ellipse_fit + +![ellipse_fit](scripts/ellipse/images/visualization/multipole_scaled/ellipse_fit.png) + +##### ellipse_residuals + +![ellipse_residuals](scripts/ellipse/images/visualization/multipole_scaled/ellipse_residuals.png) + +##### fit_ellipse + +![fit_ellipse](scripts/ellipse/images/visualization/multipole_scaled/fit_ellipse.png) + +#### ellipse / visualization / plain/ + +##### dataset + +![dataset](scripts/ellipse/images/visualization/plain/dataset.png) + +##### ellipse_fit + +![ellipse_fit](scripts/ellipse/images/visualization/plain/ellipse_fit.png) + +##### ellipse_residuals + +![ellipse_residuals](scripts/ellipse/images/visualization/plain/ellipse_residuals.png) + +##### fit_ellipse + +![fit_ellipse](scripts/ellipse/images/visualization/plain/fit_ellipse.png) + +## imaging + +### imaging / visualization + +#### imaging / visualization / top level + +##### adapt_images + +![adapt_images](scripts/imaging/images/visualization/adapt_images.png) + +##### dataset + +![dataset](scripts/imaging/images/visualization/dataset.png) + +#### imaging / visualization / delaunay/ + +##### fit + +![fit](scripts/imaging/images/visualization/delaunay/fit.png) + +##### galaxies + +![galaxies](scripts/imaging/images/visualization/delaunay/galaxies.png) + +##### galaxy_images + +![galaxy_images](scripts/imaging/images/visualization/delaunay/galaxy_images.png) + +##### inversion_0_0 + +![inversion_0_0](scripts/imaging/images/visualization/delaunay/inversion_0_0.png) + +##### of_galaxy_0 + +![of_galaxy_0](scripts/imaging/images/visualization/delaunay/of_galaxy_0.png) + +#### imaging / visualization / parametric/ + +##### fit + +![fit](scripts/imaging/images/visualization/parametric/fit.png) + +##### galaxies + +![galaxies](scripts/imaging/images/visualization/parametric/galaxies.png) + +##### galaxy_images + +![galaxy_images](scripts/imaging/images/visualization/parametric/galaxy_images.png) + +##### of_galaxy_0 + +![of_galaxy_0](scripts/imaging/images/visualization/parametric/of_galaxy_0.png) + +## interferometer + +### interferometer / visualization + +#### interferometer / visualization / top level + +##### adapt_images + +![adapt_images](scripts/interferometer/images/visualization/adapt_images.png) + +##### dataset + +![dataset](scripts/interferometer/images/visualization/dataset.png) + +#### interferometer / visualization / delaunay/ + +##### fit + +![fit](scripts/interferometer/images/visualization/delaunay/fit.png) + +##### fit_dirty_images + +![fit_dirty_images](scripts/interferometer/images/visualization/delaunay/fit_dirty_images.png) + +##### fit_real_space + +![fit_real_space](scripts/interferometer/images/visualization/delaunay/fit_real_space.png) + +##### galaxies + +![galaxies](scripts/interferometer/images/visualization/delaunay/galaxies.png) + +##### galaxy_images + +![galaxy_images](scripts/interferometer/images/visualization/delaunay/galaxy_images.png) + +##### inversion_0_0 + +![inversion_0_0](scripts/interferometer/images/visualization/delaunay/inversion_0_0.png) + +#### interferometer / visualization / parametric/ + +##### fit + +![fit](scripts/interferometer/images/visualization/parametric/fit.png) + +##### fit_dirty_images + +![fit_dirty_images](scripts/interferometer/images/visualization/parametric/fit_dirty_images.png) + +##### fit_real_space + +![fit_real_space](scripts/interferometer/images/visualization/parametric/fit_real_space.png) + +##### galaxies + +![galaxies](scripts/interferometer/images/visualization/parametric/galaxies.png) + +##### galaxy_images + +![galaxy_images](scripts/interferometer/images/visualization/parametric/galaxy_images.png) diff --git a/README.md b/README.md index 61a4820..43d15d1 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,89 @@ # autogalaxy_visualization -The permanent, rendered gallery of every PyAutoGalaxy visualizer output. +**[Browse the gallery → GALLERY.md](GALLERY.md)** -Stub — the full repository lands on `feature/eyes-galaxy-instance`. +The permanent, rendered gallery of every figure PyAutoGalaxy writes during a model-fit — the +**galaxy visualization project repo** of the PyAutoLabs organism. + +This repo owns the galaxy figures: the producer scripts, the simulators and datasets, the +all-on [`plots.yaml`](config/visualize/plots.yaml), the instrument presets, the tracked PNGs, +[`GALLERY.md`](GALLERY.md) and the render harness. The organ +[PyAutoEyes](https://github.com/PyAutoLabs/PyAutoEyes) is the cross-project visualization +dashboard: it reads this repo's tracked figure manifest +([`gallery/viz_manifest.yaml`](gallery/viz_manifest.yaml)) and links to the PNGs here — it never +renders or copies them. It is the sibling of +[autolens_visualization](https://github.com/PyAutoLabs/autolens_visualization), in the same shape. + +## Vision + +Until now, the only way to see what a PyAutoGalaxy figure looks like was to run a modelling +script and open its `output/` folder. This repo keeps the most up-to-date rendering of **every** +visualizer output in git — on realistic HST-scale imaging and SMA-scale interferometer data — so +there is one place to see every figure, judge it, and improve it (by hand or in an AI chat +pointed at the plotting source) without re-running anything. Imaging, interferometer and +ellipse (isophote) fitting today; multi-galaxy and multi-dataset (combined) figures next. + +Each figure is exactly what `VisualizerImaging` / `VisualizerInterferometer` / +`VisualizerEllipse` write to a fit's `image/` folder, rendered with the simulator's true model — +for imaging and interferometer a parametric (Sersic bulge + Exponential disk) galaxy and a +Delaunay pixelized galaxy; for ellipse fitting a plain ellipse, an m=4 multipole, a scaled m=4 +multipole and a tight-mask ellipse — with every toggle in +[`config/visualize/plots.yaml`](config/visualize/plots.yaml) switched on. + +## Render locally + +```bash +source activate.sh # library checkouts on PYTHONPATH (see the file) +bash gallery/gallery_run.sh --all # run every producer, rebuild GALLERY.md + manifest, --check +``` + +Or one domain: `python scripts/imaging/visualization.py`, then `python gallery/gallery_build.py`. +Commit the regenerated PNGs under `scripts//images/` together with `GALLERY.md` and +`gallery/viz_manifest.yaml` (every figure's producer, domain, source type, path, byte size and +sha256, plus the stack versions it was rendered with). On every PyAutoGalaxy release, +[`render.yml`](.github/workflows/render.yml) re-renders with the released stack, commits the +result and pings PyAutoEyes (`repository_dispatch: eyes-refresh`) to refresh its dashboard. + +Runtime on an 8-core laptop (CPU, NumPy path): imaging ~35 s, interferometer ~30 s, ellipse +~20 s (the masked scenario keeps the full 300-iteration mask-rejection loop and still renders in +about 4 s at HST scale). + +## Add a domain + +- Add a simulator (or instrument preset) under `scripts/misc/simulators/` and track its dataset + under `dataset///`. +- Add a flat producer `scripts//visualization.py` modelled on + [`scripts/imaging/visualization.py`](scripts/imaging/visualization.py). +- Run `bash gallery/gallery_run.sh --all` and commit the PNGs + `GALLERY.md` + + `gallery/viz_manifest.yaml`. + +## Improve a figure + +Three edit surfaces, from cheapest to deepest: + +- **Config** — [`config/visualize/plots.yaml`](config/visualize/plots.yaml): which figures are + written at all. +- **Plot API** — the plotting code in the libraries: `PyAutoGalaxy/autogalaxy/**/plot/`, + `PyAutoArray/autoarray/plot/`. Change it there (normal library workflow), then re-render here. +- **Script** — the producer in `scripts//visualization.py` (dataset, model, source types). + +The Brain Eyes agent runs the review loop on this repo: +`bin/pyauto-brain eyes survey galaxy/autogalaxy_visualization` (or `/eyes review galaxy`). +Accepted critiques are filed with the `eyes-critique` label. + +## Related repos + +- [PyAutoEyes](https://github.com/PyAutoLabs/PyAutoEyes) — the organ: the cross-project + visualization dashboard that aggregates this repo (reads `gallery/viz_manifest.yaml`, links to + the PNGs here). +- [autolens_visualization](https://github.com/PyAutoLabs/autolens_visualization) — the lens + sibling this repo mirrors (and the source of its instrument presets and harness). +- [autogalaxy_workspace](https://github.com/PyAutoLabs/autogalaxy_workspace) — user-facing + science scripts and tutorials. +- [autogalaxy_workspace_test](https://github.com/PyAutoLabs/autogalaxy_workspace_test) — + visualization tests (file / FITS-HDU assertions) the producers here were ported from. + +## Community & support + +- **Slack** — [PyAutoLens workspace](https://join.slack.com/t/pyautolens/shared_invite/zt-2cufp4eyf-fXfgMxRGuvg~bMrI3uOAxg) for questions (it hosts PyAutoGalaxy too). +- **Issues** — file figure bugs and visualization requests on this repo's [issue tracker](https://github.com/PyAutoLabs/autogalaxy_visualization/issues). diff --git a/_viz_cli.py b/_viz_cli.py new file mode 100644 index 0000000..8f1d211 --- /dev/null +++ b/_viz_cli.py @@ -0,0 +1,100 @@ +"""Shared helpers for the visualization producers and simulators. + +Copied from ``autolens_visualization/_viz_cli.py`` (a deliberately small subset of +``autolens_profiling/_profile_cli.py``): this repo +renders figures, it does not time anything, so only the pieces the simulators and +the ``scripts//visualization.py`` producers need are kept: + +- ``repo_root()`` — walk up from any file to the directory holding ``ruff.toml`` + (the depth-proof repo-root sentinel), so scripts work from any nesting level. +- ``bootstrap_sys_path()`` — put the repo root and ``scripts/misc/`` on + ``sys.path`` so ``instruments`` / ``_viz_cli`` / ``simulators`` import by name. +- ``dataset_path(dataset_type, instrument)`` — ``/dataset//``. +- ``auto_simulate_if_missing(...)`` — shell out to + ``scripts/misc/simulators/.py --instrument `` when a dataset is absent. + +Typical use at the top of a producer:: + + import sys + from pathlib import Path + + for _p in Path(__file__).resolve().parents: + if (_p / "ruff.toml").exists(): + sys.path.insert(0, str(_p)) + break + from _viz_cli import auto_simulate_if_missing, dataset_path, repo_root +""" + +from __future__ import annotations + +import subprocess +import sys +from pathlib import Path + + +def repo_root(start: Path | None = None) -> Path: + """Return the autogalaxy_visualization root (the directory containing ``ruff.toml``).""" + here = Path(start if start is not None else __file__).resolve() + for p in [here, *here.parents]: + if (p / "ruff.toml").exists(): + return p + raise RuntimeError("autogalaxy_visualization root (ruff.toml) not found") + + +def bootstrap_sys_path() -> Path: + """Put the repo root and ``scripts/misc`` on ``sys.path``; return the root.""" + root = repo_root() + for p in (root, root / "scripts" / "misc"): + if str(p) not in sys.path: + sys.path.insert(0, str(p)) + return root + + +def dataset_path(dataset_type: str, instrument: str) -> Path: + """``/dataset//``.""" + return repo_root() / "dataset" / dataset_type / instrument + + +def auto_simulate_if_missing( + dataset_dir: Path, + *, + dataset_type: str, + instrument: str, + workspace_root: Path | None = None, +) -> None: + """If ``dataset_dir`` is missing, run the matching simulator script. + + ``dataset_type`` maps to ``scripts/misc/simulators/.py`` + (``imaging`` / ``interferometer``). + + The gate is a plain ``data.fits`` existence check, deliberately NOT + ``ag.util.dataset.should_simulate``: that helper deletes datasets it judges to + belong to the other ``PYAUTO_SMALL_DATASETS`` regime, and this repo's datasets + are tracked in git so every figure is reproducible — a harness run with the + env var set must never wipe them. + """ + if (Path(dataset_dir) / "data.fits").exists(): + return + + root = workspace_root if workspace_root is not None else repo_root() + simulator_script = root / "scripts" / "misc" / "simulators" / f"{dataset_type}.py" + if not simulator_script.exists(): + raise FileNotFoundError( + f"Auto-simulate could not find simulator script at {simulator_script}." + ) + + print( + f" [auto-simulate] {dataset_dir} missing; invoking " + f"scripts/misc/simulators/{dataset_type}.py --instrument {instrument}" + ) + subprocess.run( + [ + sys.executable, + str(simulator_script), + "--instrument", + instrument, + "--output-root", + str(root), + ], + check=True, + ) diff --git a/activate.sh b/activate.sh new file mode 100644 index 0000000..90970a1 --- /dev/null +++ b/activate.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Activate a PyAuto venv and point PYTHONPATH at the PyAuto* library source +# checkouts, so the producers render against the libraries you are editing. +# +# Copied from autolens_visualization/activate.sh (itself adapted from +# autolens_profiling/activate.sh). This repo has no HPC leg: it resolves the +# libraries from the PyAutoLabs workspace layout this checkout sits in +# (galaxy/autogalaxy_visualization -> organs/PyAutoNerves, fit/PyAutoFit, +# array/PyAutoArray, galaxy/PyAutoGalaxy). Override with +# PYAUTO_LIB_BASE= for a flat layout, and +# PYAUTO_VENV= to activate a venv first. +# +# Usage (from anywhere): +# +# source galaxy/autogalaxy_visualization/activate.sh +# bash gallery/gallery_run.sh --all + +_viz_root="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +if [ -n "${PYAUTO_VENV:-}" ] && [ -f "$PYAUTO_VENV/bin/activate" ]; then + # shellcheck disable=SC1091 + source "$PYAUTO_VENV/bin/activate" +fi + +if [ -n "${PYAUTO_LIB_BASE:-}" ]; then + _libs="$PYAUTO_LIB_BASE/PyAutoNerves:$PYAUTO_LIB_BASE/PyAutoFit:$PYAUTO_LIB_BASE/PyAutoArray:$PYAUTO_LIB_BASE/PyAutoGalaxy" +else + _ws="$(cd "$_viz_root/../.." && pwd)" + _libs="$_ws/organs/PyAutoNerves:$_ws/fit/PyAutoFit:$_ws/array/PyAutoArray:$_ws/galaxy/PyAutoGalaxy" +fi + +export PYTHONPATH="$_libs${PYTHONPATH:+:$PYTHONPATH}" +export NUMBA_CACHE_DIR="${NUMBA_CACHE_DIR:-/tmp/numba_cache}" +export MPLCONFIGDIR="${MPLCONFIGDIR:-/tmp/matplotlib}" +mkdir -p "$NUMBA_CACHE_DIR" "$MPLCONFIGDIR" +unset _viz_root _ws _libs diff --git a/config/general.yaml b/config/general.yaml new file mode 100644 index 0000000..6f92155 --- /dev/null +++ b/config/general.yaml @@ -0,0 +1,2 @@ +version: + workspace_version_check: false # this repo renders against library mains locally and PyPI releases in CI; the mismatch warning is expected noise. diff --git a/config/visualize/plots.yaml b/config/visualize/plots.yaml new file mode 100644 index 0000000..fd2cf86 --- /dev/null +++ b/config/visualize/plots.yaml @@ -0,0 +1,61 @@ +# autogalaxy_visualization: the library default plots.yaml (autogalaxy/config/visualize/plots.yaml) +# with EVERY boolean switched to true, so the producers render the full visualizer surface. +# This file is the `config` edit surface of the Eyes agent: turning a figure on/off here +# changes what lands in scripts//images/ and GALLERY.md. +# FITS / CSV outputs stay enabled (they exercise the code path) but are gitignored. + +# The `plots` section customizes every image that is output to hard-disk during a model-fit. + +# For example, if `plots: fit: subplot_fit=True``, the ``subplot_fit.png`` subplot file will +# be plotted every time visualization is performed. + +# One setting is important for inspecting results via the dataset after a fit is complete: + +# -`fits_adapt_images`, This outputs `adapt_images.fits` which the database functionality may use to reperform fits. + +# It can be disabled to save on hard-disk space but will lead to certain database functionality being disabled. + +# The dataset itself is always output as `dataset.fits` to the `image` folder of every fit, and is not controlled +# by any setting here. + +subplot_format: [png] # Output format of all subplots, can be png, pdf or both (e.g. [png, pdf]) +fits_are_zoomed: false # If true, output .fits files are zoomed in on the center of the unmasked region image, saving hard-disk space. + +dataset: # Settings for plots of all datasets (e.g. Imaging, Interferometer). + subplot_dataset: true # Plot subplot containing all dataset quantities (e.g. the data, noise-map, etc.)? + +fit: # Settings for plots of all fits (e.g. FitImaging, FitInterferometer). + subplot_fit: true # Plot subplot of all fit quantities for any dataset (e.g. the model data, residual-map, etc.)? + subplot_fit_log10: true # Plot subplot of all fit quantities for any dataset using log10 color maps (e.g. the model data, residual-map, etc.)? + subplot_of_galaxies: true # Plot subplot of the model-image, subtracted image and other quantities of each galaxy? + subplot_galaxy_images: true # Plot subplot of the image of each galaxy in the model? + fits_fit: true # Output a .fits file containing the fit model data, residual map, normalized residual map and chi-squared? + fits_galaxy_images : true # Output a .fits file containing the images (e.g. without PSF convolution) of every galaxy? + fits_model_galaxy_images : true # Output a .fits file containing the model images (e.g. with PSF convolution) of every galaxy? + +fit_imaging: {} # Settings for plots of fits to imaging datasets (e.g. FitImaging). + +galaxies: # Settings for plots of galaxies (e.g. Galaxies). + subplot_galaxies: true # Plot subplot of all quantities in each galaxies group (e.g. images, convergence)? + subplot_galaxy_images: true # Plot subplot of the image of each galaxy in the model? + fits_galaxy_images: true # Output a .fits file containing images of every galaxy? + +inversion: # Settings for plots of inversions (e.g. InversionPlotter). + subplot_inversion: true # Plot subplot of all quantities in each inversion (e.g. reconstrucuted image, reconstruction)? + subplot_mappings: true # Plot subplot of the image-to-source pixels mappings of each pixelization? + csv_reconstruction: true # output source_plane_reconstruction_0.csv containing the source-plane mesh y, x, reconstruction and noise map values. + +adapt: # Settings for plots of adapt images used by adaptive pixelizations. + subplot_adapt_images: true # Plot subplot showing each adapt image used for adaptive pixelization? + fits_adapt_images: true # Output a .fits file containing the adapt images used for adaptive pixelization? + +fit_interferometer: # Settings for plots of fits to interferometer datasets (e.g. FitInterferometer). + subplot_fit_dirty_images: true # Plot subplot of the dirty-images of all interferometer datasets? + subplot_fit_real_space: true # Plot subplot of the real-space images of all interferometer datasets? + fits_dirty_images: true # output dirty_images.fits showing the dirty image, noise-map, model-data, resiual-map, normalized residual map and chi-squared map? + +fit_ellipse: # Settings for plots of ellipse fitting fits (e.g. FitEllipse) + subplot_fit_ellipse : true # Plot subplot of all fit quantities for ellipse fits (e.g. the model data, residual-map, etc.)? + data : true # Plot the data of the ellipse fit? + data_no_ellipse: true # Plot the data without the black data ellipses, which obscure noisy data? + ellipse_residuals: true # Plot the residuals of the ellipse fit? diff --git a/dataset/imaging/hst/data.fits b/dataset/imaging/hst/data.fits new file mode 100644 index 0000000..5cd3274 Binary files /dev/null and b/dataset/imaging/hst/data.fits differ diff --git a/dataset/imaging/hst/galaxies.json b/dataset/imaging/hst/galaxies.json new file mode 100644 index 0000000..e3a678c --- /dev/null +++ b/dataset/imaging/hst/galaxies.json @@ -0,0 +1,58 @@ +{ + "type": "list", + "values": [ + { + "type": "instance", + "class_path": "autogalaxy.galaxy.galaxy.Galaxy", + "arguments": { + "redshift": 0.5, + "label": null, + "bulge": { + "type": "instance", + "class_path": "autogalaxy.profiles.light.standard.sersic.Sersic", + "arguments": { + "ell_comps": { + "type": "tuple", + "values": [ + 0.05263157894736841, + 3.2227547345982974e-18 + ] + }, + "intensity": 2.0, + "sersic_index": 3.0, + "centre": { + "type": "tuple", + "values": [ + 0.0, + 0.0 + ] + }, + "effective_radius": 0.6 + } + }, + "disk": { + "type": "instance", + "class_path": "autogalaxy.profiles.light.standard.exponential.Exponential", + "arguments": { + "effective_radius": 1.6, + "ell_comps": { + "type": "tuple", + "values": [ + 0.152828012432548, + 0.08823529411764709 + ] + }, + "intensity": 1.0, + "centre": { + "type": "tuple", + "values": [ + 0.0, + 0.0 + ] + } + } + } + } + } + ] +} \ No newline at end of file diff --git a/dataset/imaging/hst/noise_map.fits b/dataset/imaging/hst/noise_map.fits new file mode 100644 index 0000000..5d6c07e Binary files /dev/null and b/dataset/imaging/hst/noise_map.fits differ diff --git a/dataset/imaging/hst/psf.fits b/dataset/imaging/hst/psf.fits new file mode 100644 index 0000000..daa6a9d Binary files /dev/null and b/dataset/imaging/hst/psf.fits differ diff --git a/dataset/interferometer/sma/data.fits b/dataset/interferometer/sma/data.fits new file mode 100644 index 0000000..40dc197 Binary files /dev/null and b/dataset/interferometer/sma/data.fits differ diff --git a/dataset/interferometer/sma/galaxies.json b/dataset/interferometer/sma/galaxies.json new file mode 100644 index 0000000..5c5114d --- /dev/null +++ b/dataset/interferometer/sma/galaxies.json @@ -0,0 +1,58 @@ +{ + "type": "list", + "values": [ + { + "type": "instance", + "class_path": "autogalaxy.galaxy.galaxy.Galaxy", + "arguments": { + "redshift": 0.5, + "label": null, + "bulge": { + "type": "instance", + "class_path": "autogalaxy.profiles.light.standard.sersic.Sersic", + "arguments": { + "intensity": 2.0, + "effective_radius": 0.6, + "centre": { + "type": "tuple", + "values": [ + 0.0, + 0.0 + ] + }, + "ell_comps": { + "type": "tuple", + "values": [ + 0.05263157894736841, + 3.2227547345982974e-18 + ] + }, + "sersic_index": 3.0 + } + }, + "disk": { + "type": "instance", + "class_path": "autogalaxy.profiles.light.standard.exponential.Exponential", + "arguments": { + "intensity": 1.0, + "ell_comps": { + "type": "tuple", + "values": [ + 0.152828012432548, + 0.08823529411764709 + ] + }, + "effective_radius": 1.6, + "centre": { + "type": "tuple", + "values": [ + 0.0, + 0.0 + ] + } + } + } + } + } + ] +} \ No newline at end of file diff --git a/dataset/interferometer/sma/noise_map.fits b/dataset/interferometer/sma/noise_map.fits new file mode 100644 index 0000000..ba127dd Binary files /dev/null and b/dataset/interferometer/sma/noise_map.fits differ diff --git a/dataset/interferometer/sma/uv_wavelengths.fits b/dataset/interferometer/sma/uv_wavelengths.fits new file mode 100644 index 0000000..386a44f Binary files /dev/null and b/dataset/interferometer/sma/uv_wavelengths.fits differ diff --git a/gallery/gallery_build.py b/gallery/gallery_build.py new file mode 100644 index 0000000..9b37444 --- /dev/null +++ b/gallery/gallery_build.py @@ -0,0 +1,458 @@ +""" +Gallery: Visualization Contact Sheet, Manifest and GALLERY.md +============================================================= + +Builds the three views of every figure the ``scripts//visualization*.py`` +producers have written under ``scripts//images/