#!/usr/bin/env python3 """ Copy runtime-relevant Koolook files into a live ComfyUI custom_nodes folder so a fix can be tested without a tag-and-publish round-trip. USER-INITIATED ONLY. This script overwrites a live ComfyUI install. Agents must NEVER run it automatically — not after a commit, not after a PR merge or ship-pr, not at session end, not from any "task complete" cleanup. The maintainer typically has multiple parallel sessions across worktrees, and an unsolicited sync from one silently destroys what another is reviewing. See project CLAUDE.md `dev-sync` section for the full policy. Run only on the explicit user trigger phrase. The target path is read from the KOLOOK_COMFYUI_DEV_PATH environment variable (loaded from `.env` at the repo root if present). The variable is intentionally kept out of the committed tree — see `.env.example`. `KOLOOK_COMFYUI_DEV_PATH` should point at the eventual Koolook subdirectory inside `custom_nodes/`, NOT at the `custom_nodes/` parent. Example layouts: macOS: /Volumes/Data/ComfyUI/custom_nodes/ComfyUI-Koolook Windows: C:/ComfyUI_portable/ComfyUI/custom_nodes/ComfyUI-Koolook Usage: python scripts/sync_to_dev.py # copy + auto-restart ComfyUI python scripts/sync_to_dev.py --dry-run # show what would copy python scripts/sync_to_dev.py --no-restart # copy only; don't restart python scripts/sync_to_dev.py --init # first-run: create the # target folder if missing # (parent custom_nodes/ must # already exist), then sync After copying, the script POSTs to ComfyUI-Manager's reboot endpoint (`http://127.0.0.1:8188/manager/reboot` by default) so the live server re-execs and picks up the new Python files. This is on by default because the only reason to invoke this script is to see new code — file-only sync without a restart leaves Python `.py` changes invisible (custom-node modules load once at server start). Use `--no-restart` to opt out, e.g. when staging files for a session you don't want to disturb. Restart failures (Manager not installed, ComfyUI not running, etc.) print a diagnostic but do NOT fail the sync. Exit codes: 0 success (sync completed; restart is best-effort and won't change this) 2 KOLOOK_COMFYUI_DEV_PATH unset, parent missing, or target missing (without --init) 3 --init refused: parent is not an existing directory or doesn't resemble a ComfyUI custom_nodes/ folder This script never reaches outside the repo, never deletes anything in the source, and only touches paths under the configured target. It does overwrite files in the target — that's the point. """ from __future__ import annotations import argparse import json import os import shutil import subprocess import sys import urllib.error import urllib.request from datetime import datetime from pathlib import Path from urllib.parse import urlparse # Default ComfyUI-Manager reboot endpoint. ComfyUI-Manager registers this # as a GET route; hitting it makes the server `os.execv` itself, so the # same terminal/process picks the new node code up without a manual kill # + relaunch cycle. Override via `--restart-url` or skip via # `--no-restart` if your install runs on a different port / has no # Manager / you want to stage files without disturbing the live session. DEFAULT_RESTART_URL = "http://127.0.0.1:8188/manager/reboot" REPO_ROOT = Path(__file__).resolve().parent.parent def _get_short_sha() -> str | None: """Best-effort short commit SHA of the source tree being synced. Returns ``None`` if git isn't reachable or the call fails — the summary line just omits the SHA in that case. """ try: r = subprocess.run( ["git", "rev-parse", "--short", "HEAD"], cwd=str(REPO_ROOT), capture_output=True, text=True, timeout=2, ) if r.returncode == 0: sha = r.stdout.strip() if sha: return sha except (OSError, subprocess.TimeoutExpired): pass return None def _get_worktree_name() -> str: """Returns the basename of the source tree being synced — useful when the maintainer is running multiple parallel ComfyUI installs and needs to know which checkout fed the most recent sync. For a worktree at ``.../ComfyUI-Koolook/.claude/worktrees/foo`` this returns ``foo``; for the main repo at ``.../ComfyUI-Koolook`` it returns ``ComfyUI-Koolook``. Either is informative enough to disambiguate.""" return REPO_ROOT.name def _build_line() -> str: """Composes the two-piece header line consumed by the chat-report convention defined in project CLAUDE.md: - SHA falls back to ``unknown`` if git is unreachable (we always need SOMETHING in slot 1 — the line shape is part of the convention). Worktree name comes from ``REPO_ROOT.name`` and is always present.""" sha = _get_short_sha() or "unknown" return f"{sha} - {_get_worktree_name()}" def trigger_restart(url: str, timeout: float = 2.0) -> tuple[bool, str]: """Best-effort POST/GET to ComfyUI-Manager's reboot endpoint. Returns ``(success, human_message)``. Never raises — the sync itself succeeded by the time we call this, and a failed restart should never mask that with a non-zero exit. The maintainer can always restart manually if the auto-restart didn't take. Failure-mode mapping: - Connection refused → ComfyUI not running; nothing to do. - HTTP 404 → Manager not installed at this URL. - HTTP 2xx → restart triggered cleanly. - Connection reset / timeout → the server died mid-response (the restart's `os.execv` raced our read); the request still landed, so we treat this as success. """ # Restrict to http/https. `urlopen` would otherwise accept `file://`, # `ftp://`, etc. — a typo in `--restart-url` could surprise the # maintainer by opening a local file via the same code path that # normally talks to ComfyUI-Manager. Static analyzers (Bandit B310) # also flag the broader urlopen surface; this guard makes the # `# nosec` annotation below truthful rather than dismissive. scheme = urlparse(url).scheme.lower() if scheme not in ("http", "https"): return False, ( f"restart skipped: --restart-url must be http(s); got " f"scheme '{scheme}' in {url}" ) try: # ComfyUI-Manager registers /manager/reboot as GET, but POST # also lands harmlessly — using GET keeps it simple. urllib.request.urlopen(url, timeout=timeout) # nosec B310 - scheme validated above return True, "restart triggered" except urllib.error.HTTPError as e: if e.code == 404: return False, ( f"restart skipped: ComfyUI-Manager not detected at {url} " f"(404). Install Manager or pass --no-restart." ) return False, f"restart skipped: endpoint returned HTTP {e.code}" except urllib.error.URLError as e: reason = e.reason if isinstance(reason, ConnectionRefusedError): return False, f"restart skipped: ComfyUI not running at {url}" # Read timeout / connection reset usually means the server # received the request and rebooted before completing the # response — desired outcome. if isinstance(reason, (TimeoutError, ConnectionResetError)) or "timed out" in str(reason).lower(): return True, "restart triggered (server stopped responding during reboot — normal)" return False, f"restart skipped: unreachable ({reason})" except (ConnectionResetError, OSError): # Same race as above: server began rebooting before we finished # reading. The request landed; that's what matters. return True, "restart triggered (connection reset during reboot)" def write_build_info(target: Path, scope: str | None) -> None: """Drop a tiny JSON next to the sidebar JS so the in-browser footer can render `dev ·