diff --git a/skills/continuous-learning-v2/hooks/observe.sh b/skills/continuous-learning-v2/hooks/observe.sh index cea7f3cda..ffd9ae1a3 100755 --- a/skills/continuous-learning-v2/hooks/observe.sh +++ b/skills/continuous-learning-v2/hooks/observe.sh @@ -39,135 +39,27 @@ if [ -z "$INPUT_JSON" ]; then exit 0 fi -_is_windows_app_installer_stub() { - # Windows 10/11 ships an "App Execution Alias" stub at - # %LOCALAPPDATA%\Microsoft\WindowsApps\python.exe - # %LOCALAPPDATA%\Microsoft\WindowsApps\python3.exe - # Both are symlinks to AppInstallerPythonRedirector.exe which, when Python - # is not installed from the Store, neither launches Python nor honors "-c". - # Calls to it hang or print a bare "Python " line, silently breaking every - # JSON-parsing step in this hook. Detect and skip such stubs here. - local _candidate="$1" - [ -z "$_candidate" ] && return 1 - local _resolved - _resolved="$(command -v "$_candidate" 2>/dev/null || true)" - [ -z "$_resolved" ] && return 1 - case "$_resolved" in - *AppInstallerPythonRedirector.exe|*AppInstallerPythonRedirector.EXE) return 0 ;; - esac - # Also resolve one level of symlink on POSIX-like shells (Git Bash, WSL). - if command -v readlink >/dev/null 2>&1; then - local _target - _target="$(readlink -f "$_resolved" 2>/dev/null || readlink "$_resolved" 2>/dev/null || true)" - case "$_target" in - *AppInstallerPythonRedirector.exe|*AppInstallerPythonRedirector.EXE) return 0 ;; - esac - fi - return 1 -} - -_python_install_manager_launcher() { - # With the Python Install Manager, python3/python in - # %LOCALAPPDATA%\Microsoft\WindowsApps - # are App Execution Aliases. Every start of one makes Windows run an App - # Installer update check (AppXDeploymentServer event 603), and this hook - # starts Python several times per tool call. The Install Manager's global - # shortcuts in %LOCALAPPDATA%\Python\bin start the same runtime without that - # check, so print the shortcut for $1 when it is an alias and one exists. - # Microsoft Store Python has no such shortcut and keeps its alias. Only the - # current user's WindowsApps counts: an alias from anywhere else is left alone. - # The alias is also kept when it may not be the Install Manager's (Store - # Python provides the same name, and either package can own it) and when - # PYTHON_MANAGER_DEFAULT picks the runtime, which the alias honours and the - # shortcut, generated for one runtime, does not. - local _candidate="$1" _resolved _local _store - [ -n "${LOCALAPPDATA:-}" ] || return 1 - [ -z "${PYTHON_MANAGER_DEFAULT:-}" ] || return 1 - _resolved="$(command -v "$_candidate" 2>/dev/null || true)" - case "$_resolved" in */*) ;; *) return 1 ;; esac - # Git Bash accepts C:/... paths, so swapping separators avoids a cygpath start. - _local="${LOCALAPPDATA//\\//}" - _local="${_local%/}" - # command -v prints /c/... (or a mount such as /tmp/...) while LOCALAPPDATA - # is C:\..., so ask whether the two name the same directory instead of - # comparing strings. - [ "${_resolved%/*}" -ef "$_local/Microsoft/WindowsApps" ] || return 1 - # A glob, not a command, so this check starts no process. - for _store in "$_local"/Microsoft/WindowsApps/PythonSoftwareFoundation.Python.3*/"${_candidate}.exe"; do - [ -e "$_store" ] && return 1 - done - [ -f "$_local/Python/bin/${_candidate}.exe" ] && [ -x "$_local/Python/bin/${_candidate}.exe" ] || return 1 - printf '%s\n' "$_local/Python/bin/${_candidate}.exe" -} - -resolve_python_cmd() { - if [ -n "${CLV2_PYTHON_CMD:-}" ] && command -v "$CLV2_PYTHON_CMD" >/dev/null 2>&1; then - printf '%s\n' "$CLV2_PYTHON_CMD" - return 0 - fi - - if command -v python3 >/dev/null 2>&1 && ! _is_windows_app_installer_stub python3; then - _python_install_manager_launcher python3 || printf '%s\n' python3 - return 0 - fi - - if command -v python >/dev/null 2>&1 && ! _is_windows_app_installer_stub python; then - _python_install_manager_launcher python || printf '%s\n' python - return 0 - fi - - return 1 -} - -PYTHON_CMD="$(resolve_python_cmd 2>/dev/null || true)" -if [ -z "$PYTHON_CMD" ]; then - echo "[observe] No python interpreter found, skipping observation" >&2 - exit 0 -fi - -# Propagate our stub-aware selection so detect-project.sh (which is sourced -# below) does not re-resolve and silently fall back to the App Installer stub. -# detect-project.sh honors an already-set CLV2_PYTHON_CMD. -export CLV2_PYTHON_CMD="${CLV2_PYTHON_CMD:-$PYTHON_CMD}" - # ───────────────────────────────────────────── -# Extract cwd from stdin for project detection +# Script location # ───────────────────────────────────────────── - -# Extract cwd from the hook JSON to use for project detection. -# If cwd is a subdirectory inside a git repo, resolve it to the repo root so -# observations attach to the project instead of a nested path. -STDIN_CWD=$(echo "$INPUT_JSON" | "$PYTHON_CMD" -c ' -import json, os, sys -try: - data = json.load(sys.stdin) - cwd = data.get("cwd", "") - cwd = cwd[:4096] if isinstance(cwd, str) else "" - if isinstance(cwd, str) and os.path.isabs(cwd) and os.path.isdir(cwd): - print(os.path.realpath(cwd)) - else: - print("") -except (KeyError, OSError, TypeError, ValueError): - print("") -' 2>/dev/null || echo "") - -# Only a validated, absolute payload cwd may select a project. Missing, -# relative, or non-existent paths must not fall through to detect-project.sh's -# inherited-process-cwd discovery, which can attach an observation to an -# unrelated repository that happened to launch the hook. -if [ -n "$STDIN_CWD" ] && [ -d "$STDIN_CWD" ]; then - _GIT_ROOT=$(git -C "$STDIN_CWD" rev-parse --show-toplevel 2>/dev/null || true) - if [ -n "$_GIT_ROOT" ]; then - export CLAUDE_PROJECT_DIR="$_GIT_ROOT" - unset CLV2_NO_PROJECT - else - unset CLAUDE_PROJECT_DIR - export CLV2_NO_PROJECT=1 - fi -else - unset CLAUDE_PROJECT_DIR - export CLV2_NO_PROJECT=1 -fi +# +# This hook runs before and after every tool call. Each external command is a +# process launch: a few milliseconds on Linux/macOS, but 80-280 ms under Git +# Bash on Windows, where ~50 launches per run added up to several seconds. The +# hot path therefore uses parameter expansion and shell builtins wherever an +# external command is not required, and batches the Python work into as few +# interpreter starts as possible. +# Git Bash may be handed a Windows path (C:\...\observe.sh); dirname accepted +# both separators there, so normalize before splitting. +_CLV2_SELF="$0" +case "${OSTYPE:-}" in + msys*|cygwin*|win32*) _CLV2_SELF="${_CLV2_SELF//\\//}" ;; +esac +case "$_CLV2_SELF" in + */*) SCRIPT_DIR="${_CLV2_SELF%/*}" ;; + *) SCRIPT_DIR="." ;; +esac +SKILL_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" # ───────────────────────────────────────────── # Lightweight config and automated session guards @@ -176,17 +68,31 @@ fi # IMPORTANT: keep these guards above detect-project.sh. # Sourcing detect-project.sh creates project-scoped directories and updates # projects.json, so automated sessions must return before that point. +# +# The guards that need nothing from stdin also run before the first interpreter +# start, so a disabled or skipped session costs no Python or git launch. # shellcheck disable=SC1091 -. "$(dirname "$0")/../scripts/lib/homunculus-dir.sh" +. "${SCRIPT_DIR}/../scripts/lib/homunculus-dir.sh" CONFIG_DIR="$(_clv2_resolve_homunculus_dir)" # Skip if disabled (check both default and CLV2_CONFIG-derived locations) if [ -f "$CONFIG_DIR/disabled" ]; then exit 0 fi -if [ -n "${CLV2_CONFIG:-}" ] && [ -f "$(dirname "$CLV2_CONFIG")/disabled" ]; then - exit 0 +if [ -n "${CLV2_CONFIG:-}" ]; then + # As with $0 above: Git Bash may be given C:\...\config.json. + _CLV2_CONFIG_PATH_NORM="$CLV2_CONFIG" + case "${OSTYPE:-}" in + msys*|cygwin*|win32*) _CLV2_CONFIG_PATH_NORM="${_CLV2_CONFIG_PATH_NORM//\\//}" ;; + esac + case "$_CLV2_CONFIG_PATH_NORM" in + */*) _CLV2_CONFIG_PARENT="${_CLV2_CONFIG_PATH_NORM%/*}" ;; + *) _CLV2_CONFIG_PARENT="." ;; + esac + if [ -f "${_CLV2_CONFIG_PARENT:-/}/disabled" ]; then + exit 0 + fi fi # Prevent observe.sh from firing on non-human sessions to avoid: @@ -209,8 +115,233 @@ esac # Layer 3: cooperative skip env var for automated sessions. [ "${ECC_SKIP_OBSERVE:-0}" = "1" ] && exit 0 +# ───────────────────────────────────────────── +# Python interpreter +# ───────────────────────────────────────────── + +_is_windows_app_installer_stub() { + # Windows 10/11 ships an "App Execution Alias" stub at + # %LOCALAPPDATA%\Microsoft\WindowsApps\python.exe + # %LOCALAPPDATA%\Microsoft\WindowsApps\python3.exe + # Both are symlinks to AppInstallerPythonRedirector.exe which, when Python + # is not installed from the Store, neither launches Python nor honors "-c". + # Calls to it hang or print a bare "Python " line, silently breaking every + # JSON-parsing step in this hook. Detect and skip such stubs here. + local _candidate="$1" + [ -z "$_candidate" ] && return 1 + local _resolved="" + # hash + BASH_CMDS yields the resolved path without a command-substitution + # subshell (bash >= 4). Older shells fall through to `command -v`. + if [ "${BASH_VERSINFO[0]:-0}" -ge 4 ] && hash "$_candidate" 2>/dev/null; then + _resolved="${BASH_CMDS[$_candidate]:-}" + fi + if [ -z "$_resolved" ]; then + _resolved="$(command -v "$_candidate" 2>/dev/null || true)" + fi + [ -z "$_resolved" ] && return 1 + case "$_resolved" in + *AppInstallerPythonRedirector.exe|*AppInstallerPythonRedirector.EXE) return 0 ;; + esac + # The alias stubs only exist under ...\Microsoft\WindowsApps\, so only a + # candidate resolved there needs its symlink followed. Everywhere else this + # saves a readlink launch on every tool call. + case "$_resolved" in + */[Ww]indows[Aa]pps/*) ;; + *) return 1 ;; + esac + # Also resolve one level of symlink on POSIX-like shells (Git Bash, WSL). + if command -v readlink >/dev/null 2>&1; then + local _target + _target="$(readlink -f "$_resolved" 2>/dev/null || readlink "$_resolved" 2>/dev/null || true)" + case "$_target" in + *AppInstallerPythonRedirector.exe|*AppInstallerPythonRedirector.EXE) return 0 ;; + esac + fi + return 1 +} + +# Sets _CLV2_LAUNCHER_PATH instead of printing, so the hot path can ask for the +# launcher without a command-substitution subshell. +_clv2_pick_install_manager_launcher() { + # With the Python Install Manager, python3/python in + # %LOCALAPPDATA%\Microsoft\WindowsApps + # are App Execution Aliases. Every start of one makes Windows run an App + # Installer update check (AppXDeploymentServer event 603), and this hook + # starts Python several times per tool call. The Install Manager's global + # shortcuts in %LOCALAPPDATA%\Python\bin start the same runtime without that + # check, so select the shortcut for $1 when it is an alias and one exists. + # Microsoft Store Python has no such shortcut and keeps its alias. Only the + # current user's WindowsApps counts: an alias from anywhere else is left alone. + # The alias is also kept when it may not be the Install Manager's (Store + # Python provides the same name, and either package can own it) and when + # PYTHON_MANAGER_DEFAULT picks the runtime, which the alias honours and the + # shortcut, generated for one runtime, does not. + _CLV2_LAUNCHER_PATH="" + local _candidate="$1" _resolved="" _local _store + [ -n "${LOCALAPPDATA:-}" ] || return 1 + [ -z "${PYTHON_MANAGER_DEFAULT:-}" ] || return 1 + # hash + BASH_CMDS yields the resolved path without a command-substitution + # subshell (bash >= 4). Older shells fall through to `command -v`. + if [ "${BASH_VERSINFO[0]:-0}" -ge 4 ] && hash "$_candidate" 2>/dev/null; then + _resolved="${BASH_CMDS[$_candidate]:-}" + fi + if [ -z "$_resolved" ]; then + _resolved="$(command -v "$_candidate" 2>/dev/null || true)" + fi + case "$_resolved" in */*) ;; *) return 1 ;; esac + # Git Bash accepts C:/... paths, so swapping separators avoids a cygpath start. + _local="${LOCALAPPDATA//\\//}" + _local="${_local%/}" + # The resolved path is /c/... (or a mount such as /tmp/...) while LOCALAPPDATA + # is C:\..., so ask whether the two name the same directory instead of + # comparing strings. + [ "${_resolved%/*}" -ef "$_local/Microsoft/WindowsApps" ] || return 1 + # A glob, not a command, so this check starts no process. + for _store in "$_local"/Microsoft/WindowsApps/PythonSoftwareFoundation.Python.3*/"${_candidate}.exe"; do + [ -e "$_store" ] && return 1 + done + [ -f "$_local/Python/bin/${_candidate}.exe" ] && [ -x "$_local/Python/bin/${_candidate}.exe" ] || return 1 + _CLV2_LAUNCHER_PATH="$_local/Python/bin/${_candidate}.exe" +} + +_python_install_manager_launcher() { + _clv2_pick_install_manager_launcher "$1" || return 1 + printf '%s\n' "$_CLV2_LAUNCHER_PATH" +} + +# Sets _CLV2_RESOLVED_PYTHON instead of printing, so the hot path can resolve +# the interpreter without a command-substitution subshell. +_clv2_pick_python_cmd() { + _CLV2_RESOLVED_PYTHON="" + + if [ -n "${CLV2_PYTHON_CMD:-}" ] && command -v "$CLV2_PYTHON_CMD" >/dev/null 2>&1; then + _CLV2_RESOLVED_PYTHON="$CLV2_PYTHON_CMD" + return 0 + fi + + if command -v python3 >/dev/null 2>&1 && ! _is_windows_app_installer_stub python3; then + if _clv2_pick_install_manager_launcher python3; then + _CLV2_RESOLVED_PYTHON="$_CLV2_LAUNCHER_PATH" + else + _CLV2_RESOLVED_PYTHON="python3" + fi + return 0 + fi + + if command -v python >/dev/null 2>&1 && ! _is_windows_app_installer_stub python; then + if _clv2_pick_install_manager_launcher python; then + _CLV2_RESOLVED_PYTHON="$_CLV2_LAUNCHER_PATH" + else + _CLV2_RESOLVED_PYTHON="python" + fi + return 0 + fi + + return 1 +} + +resolve_python_cmd() { + _clv2_pick_python_cmd || return 1 + printf '%s\n' "$_CLV2_RESOLVED_PYTHON" +} + +_CLV2_RESOLVED_PYTHON="" +_clv2_pick_python_cmd 2>/dev/null || true +PYTHON_CMD="$_CLV2_RESOLVED_PYTHON" +if [ -z "$PYTHON_CMD" ]; then + echo "[observe] No python interpreter found, skipping observation" >&2 + exit 0 +fi + +# Propagate our stub-aware selection so detect-project.sh (which is sourced +# below) does not re-resolve and silently fall back to the App Installer stub. +# detect-project.sh honors an already-set CLV2_PYTHON_CMD. +export CLV2_PYTHON_CMD="${CLV2_PYTHON_CMD:-$PYTHON_CMD}" + +# ───────────────────────────────────────────── +# Read cwd, agent_id and the observer flag in one interpreter start +# ───────────────────────────────────────────── + +# Resolve the observer config path now so its "enabled" flag can be read by +# the same Python start that parses stdin (used by the lazy-start block below). +if [ -n "${CLV2_CONFIG:-}" ]; then + CONFIG_FILE="$CLV2_CONFIG" +elif [ -f "${CONFIG_DIR}/config.json" ]; then + CONFIG_FILE="${CONFIG_DIR}/config.json" +else + CONFIG_FILE="${SKILL_ROOT}/config.json" +fi +# Use effective config path for both existence check and reading +EFFECTIVE_CONFIG="$CONFIG_FILE" +_CLV2_CONFIG_FOR_PY="" +if [ -f "$EFFECTIVE_CONFIG" ]; then + _CLV2_CONFIG_FOR_PY="$EFFECTIVE_CONFIG" +fi + +# One value per line: cwd, agent_id, observer.enabled. A value that fails to +# parse is emitted empty (or "false"), matching the previous separate calls. +_CLV2_STDIN_FIELDS=$(CLV2_CONFIG_PATH="$_CLV2_CONFIG_FOR_PY" "$PYTHON_CMD" -c ' +import json, os, sys + +# Each value is checked against the stdout encoding on its own (cp1252 through a +# pipe on native Windows Python), so one unprintable value is emitted empty +# instead of failing the whole write and hiding the other two. +def one_line(value): + text = str(value).replace("\r", " ").replace("\n", " ") + text.encode(sys.stdout.encoding or "utf-8") + return text + +try: + data = json.load(sys.stdin) +except Exception: + data = None + +# Only an absolute, existing directory is reported, in canonical form; anything +# else is emitted empty so it cannot select a project (see below). +try: + cwd = data.get("cwd", "") + cwd = cwd[:4096] if isinstance(cwd, str) else "" + if os.path.isabs(cwd) and os.path.isdir(cwd): + cwd = one_line(os.path.realpath(cwd)) + else: + cwd = "" +except Exception: + cwd = "" + +try: + agent_id = one_line(data.get("agent_id", "")) +except Exception: + agent_id = "" + +enabled = "false" +config_path = os.environ.get("CLV2_CONFIG_PATH", "") +if config_path: + try: + with open(config_path) as f: + cfg = json.load(f) + enabled = str(cfg.get("observer", {}).get("enabled", False)).lower() + except Exception: + enabled = "false" + +sys.stdout.write(cwd + "\n" + agent_id + "\n" + enabled + "\n") +' 2>/dev/null <<< "$INPUT_JSON" || true) + +STDIN_CWD="" +_ECC_AGENT_ID="" +_CLV2_OBSERVER_ENABLED="false" +if [ -n "$_CLV2_STDIN_FIELDS" ]; then + { + IFS= read -r STDIN_CWD + IFS= read -r _ECC_AGENT_ID + IFS= read -r _CLV2_OBSERVER_ENABLED + } <<< "$_CLV2_STDIN_FIELDS" || true + # Native Windows Python writes CRLF; drop the CR each inner line keeps. + STDIN_CWD="${STDIN_CWD%$'\r'}" + _ECC_AGENT_ID="${_ECC_AGENT_ID%$'\r'}" + _CLV2_OBSERVER_ENABLED="${_CLV2_OBSERVER_ENABLED%$'\r'}" +fi + # Layer 4: subagent sessions are automated by definition. -_ECC_AGENT_ID=$(echo "$INPUT_JSON" | "$PYTHON_CMD" -c "import json,sys; print(json.load(sys.stdin).get('agent_id',''))" 2>/dev/null || true) [ -n "$_ECC_AGENT_ID" ] && exit 0 # Layer 5: known observer-session path exclusions. @@ -226,11 +357,33 @@ if [ -n "$STDIN_CWD" ]; then fi # ───────────────────────────────────────────── -# Project detection +# Resolve stdin cwd to its repository root # ───────────────────────────────────────────── -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -SKILL_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" +# If cwd is a subdirectory inside a git repo, resolve it to the repo root so +# observations attach to the project instead of a nested path. + +# Only a validated, absolute payload cwd may select a project. Missing, +# relative, or non-existent paths must not fall through to detect-project.sh's +# inherited-process-cwd discovery, which can attach an observation to an +# unrelated repository that happened to launch the hook. +if [ -n "$STDIN_CWD" ] && [ -d "$STDIN_CWD" ]; then + _GIT_ROOT=$(git -C "$STDIN_CWD" rev-parse --show-toplevel 2>/dev/null || true) + if [ -n "$_GIT_ROOT" ]; then + export CLAUDE_PROJECT_DIR="$_GIT_ROOT" + unset CLV2_NO_PROJECT + else + unset CLAUDE_PROJECT_DIR + export CLV2_NO_PROJECT=1 + fi +else + unset CLAUDE_PROJECT_DIR + export CLV2_NO_PROJECT=1 +fi + +# ───────────────────────────────────────────── +# Project detection +# ───────────────────────────────────────────── # Source shared project detection helper # This sets: PROJECT_ID, PROJECT_NAME, PROJECT_ROOT, PROJECT_DIR @@ -244,22 +397,58 @@ PYTHON_CMD="${CLV2_PYTHON_CMD:-$PYTHON_CMD}" OBSERVATIONS_FILE="${PROJECT_DIR}/observations.jsonl" MAX_FILE_SIZE_MB=10 -# Auto-purge observation files older than 30 days (runs once per session) -PURGE_MARKER="${PROJECT_DIR}/.last-purge" -if [ ! -f "$PURGE_MARKER" ] || [ "$(find "$PURGE_MARKER" -mtime +1 2>/dev/null)" ]; then - find "${PROJECT_DIR}" -name "observations-*.jsonl" -mtime +30 -delete 2>/dev/null || true - touch "$PURGE_MARKER" 2>/dev/null || true +# Housekeeping (old-file purge and size-based archiving) needs find and du, +# so it runs only when project detection was not served from its cache: at +# least once a day per project, and on every call when the cache is off or +# unavailable. The observations file can therefore exceed MAX_FILE_SIZE_MB by +# at most one day of records before it is archived. +if [ "${_CLV2_PROJECT_CACHE_HIT:-0}" != "1" ]; then + # Auto-purge observation files older than 30 days (runs once per session) + PURGE_MARKER="${PROJECT_DIR}/.last-purge" + if [ ! -f "$PURGE_MARKER" ] || [ "$(find "$PURGE_MARKER" -mtime +1 2>/dev/null)" ]; then + find "${PROJECT_DIR}" -name "observations-*.jsonl" -mtime +30 -delete 2>/dev/null || true + touch "$PURGE_MARKER" 2>/dev/null || true + fi + + # Archive if file too large (atomic: rename with unique suffix to avoid race) + if [ -f "$OBSERVATIONS_FILE" ]; then + file_size_mb=$(du -m "$OBSERVATIONS_FILE" 2>/dev/null | cut -f1) + if [ "${file_size_mb:-0}" -ge "$MAX_FILE_SIZE_MB" ]; then + archive_dir="${PROJECT_DIR}/observations.archive" + mkdir -p "$archive_dir" + mv "$OBSERVATIONS_FILE" "$archive_dir/observations-$(date +%Y%m%d-%H%M%S)-$$.jsonl" 2>/dev/null || true + fi + fi fi -# Parse using Python via stdin pipe (safe for all JSON payloads) -# Pass HOOK_PHASE via env var since Claude Code does not include hook type in stdin JSON -PARSED=$(echo "$INPUT_JSON" | HOOK_PHASE="$HOOK_PHASE" "$PYTHON_CMD" -c ' -import json -import sys -import os +# ───────────────────────────────────────────── +# Parse, scrub and write the observation in one interpreter start +# ───────────────────────────────────────────── +# +# HOOK_PHASE goes in via env var since Claude Code does not include the hook +# type in stdin JSON. Exit status 3 means the payload could not be parsed; the +# shell then records a scrubbed parse_error instead (block below). +export PROJECT_ID_ENV="$PROJECT_ID" +export PROJECT_NAME_ENV="$PROJECT_NAME" +export OBSERVATION_CWD_ENV="$STDIN_CWD" + +_CLV2_WRITE_RC=0 +HOOK_PHASE="$HOOK_PHASE" "$PYTHON_CMD" -c ' +import json, sys, os, re +import signal + +def _clv2_bail(*_): + print("[observe] SIGALRM timeout: in-flight observation dropped before write (#2300)", file=sys.stderr) + sys.exit(0) +try: + signal.signal(signal.SIGALRM, _clv2_bail) + signal.alarm(8) # self-terminate before the async hook 10s timeout can orphan us (#2278) +except Exception: + pass +import time try: - data = json.load(sys.stdin) + data = json.loads(sys.stdin.read()) # Determine event type from CLI argument passed via env var. # Claude Code does NOT include a "hook_type" field in the stdin JSON, @@ -274,7 +463,6 @@ try: if tool_output is None: tool_output = data.get("tool_output", data.get("output", "")) session_id = data.get("session_id", "unknown") - tool_use_id = data.get("tool_use_id", "") cwd = data.get("cwd", "") cwd = cwd[:4096] if isinstance(cwd, str) else "" @@ -288,25 +476,89 @@ try: tool_response_str = json.dumps(tool_output)[:5000] else: tool_response_str = str(tool_output)[:5000] +except Exception: + sys.exit(3) - print(json.dumps({ - "parsed": True, - "event": event, - "tool": tool_name, - "input": tool_input_str if event == "tool_start" else None, - "output": tool_response_str if event == "tool_complete" else None, - "session": session_id, - "tool_use_id": tool_use_id, - "cwd": cwd - })) -except Exception as e: - print(json.dumps({"parsed": False, "error": str(e)})) -') +observation = { + "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "event": event, + "tool": tool_name, + "session": session_id, + "project_id": os.environ.get("PROJECT_ID_ENV", "global"), + "project_name": os.environ.get("PROJECT_NAME_ENV", "global") +} -# Check if parsing succeeded -PARSED_OK=$(echo "$PARSED" | "$PYTHON_CMD" -c "import json,sys; print(json.load(sys.stdin).get('parsed', False))" 2>/dev/null || echo "False") +# Scrub secrets, including JSON-escaped quotes/backslashes in serialized tool I/O. +# This is defense in depth; arbitrary content still requires a metadata-only capture boundary. +# Includes optional auth scheme (e.g., "Bearer", "Basic") before token +# Linear-time secret matcher. Bounded quantifiers and a fixed set of auth +# schemes (instead of a generic [A-Za-z]+\s+ that overlapped the value class) +# prevent the catastrophic backtracking that pegged python at 100% CPU (#2278). +# The value class is disjoint from the separators, so it runs to the end of the +# token: a long labeled key is redacted whole instead of leaving its tail. +_SECRET_RE = re.compile( + r"(?i)((?:api[_-]?key|token|secret|password|authorization|credentials?|auth)(?:_access_key|_key)?)" + r"""(["'"'"'\s:=\\]{1,8})""" + r"((?:bearer|basic|token|bot)\s+)?" + r"([A-Za-z0-9_\-/.+=]{8,})" +) +# Value-shaped secrets that carry no keyword: PEM private key blocks (to END or +# end of the truncated text), GitHub tokens, AWS key IDs, Anthropic and OpenAI +# style sk- keys, JWTs (eyJ header, payload, optional signature) and DSN +# passwords (scheme://user:PASSWORD@host keeps scheme and user). Each branch is +# anchored on a literal prefix and uses bounded or non-overlapping classes (#2278); +# the sk- and JWT classes run to the end of the token so a long value is never +# half redacted. +# Tokens may follow a JSON escape (\n, \t, \uXXXX) since dict I/O is encoded +# before scrubbing; a DSN cut by truncation before its "@" ends at \Z, +# except a bare trailing host:port after http(s):// such as http://localhost:3000; +# any other scheme (postgres://app:1234) is redacted even when the password is numeric (#3568). +# PEM blocks run first: a label such as secret= in front of the BEGIN marker +# would otherwise let _SECRET_RE eat "-----BEGIN" and hide the block from this match. +_PEM_RE = re.compile(r"-----BEGIN[A-Z ]{0,40}PRIVATE KEY-----[\s\S]*?(?:-----END[A-Z ]{0,40}PRIVATE KEY-----|\Z)") +_SECRET_VALUE_RE = re.compile( + r"(?:(?= 5000 + val = _PEM_RE.sub("[REDACTED]", val) + val = _SECRET_RE.sub(lambda m: m.group(1) + m.group(2) + (m.group(3) or "") + "[REDACTED]", val) + val = _SECRET_VALUE_RE.sub(lambda m: (m.group(2) or "") + "[REDACTED]", val) + return _CUT_TAIL_RE.sub("[REDACTED]", val) if cut else val + +# Prefer the canonical cwd that passed the project-selection boundary. Retain a +# bounded rejected string as diagnostic metadata without ever using it to select +# a project. Apply the same secret scrubber as tool I/O because path components +# can still contain credentials or tokens (for example, generated checkout names). +cwd = os.environ.get("OBSERVATION_CWD_ENV", "") or cwd +if cwd: + observation["cwd"] = scrub(cwd) + +input_value = tool_input_str if event == "tool_start" else None +output_value = tool_response_str if event == "tool_complete" else None + +if input_value: + observation["input"] = scrub(input_value) +if output_value is not None: + observation["output"] = scrub(output_value) + +print(json.dumps(observation)) +' <<< "$INPUT_JSON" >> "$OBSERVATIONS_FILE" || _CLV2_WRITE_RC=$? + +if [ "$_CLV2_WRITE_RC" -eq 3 ]; then # Fallback: log raw input for debugging (scrub secrets before persisting) timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ") export TIMESTAMP="$timestamp" @@ -372,115 +624,11 @@ print(json.dumps({"timestamp": os.environ["TIMESTAMP"], "event": "parse_error", exit 0 fi -# Archive if file too large (atomic: rename with unique suffix to avoid race) -if [ -f "$OBSERVATIONS_FILE" ]; then - file_size_mb=$(du -m "$OBSERVATIONS_FILE" 2>/dev/null | cut -f1) - if [ "${file_size_mb:-0}" -ge "$MAX_FILE_SIZE_MB" ]; then - archive_dir="${PROJECT_DIR}/observations.archive" - mkdir -p "$archive_dir" - mv "$OBSERVATIONS_FILE" "$archive_dir/observations-$(date +%Y%m%d-%H%M%S)-$$.jsonl" 2>/dev/null || true - fi +# Any other failure keeps the previous behavior: the hook exits non-zero. +if [ "$_CLV2_WRITE_RC" -ne 0 ]; then + exit "$_CLV2_WRITE_RC" fi -# Build and write observation (now includes project context) -# Scrub common secret patterns from tool I/O before persisting -timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ") - -export PROJECT_ID_ENV="$PROJECT_ID" -export PROJECT_NAME_ENV="$PROJECT_NAME" -export OBSERVATION_CWD_ENV="$STDIN_CWD" -export TIMESTAMP="$timestamp" - -echo "$PARSED" | "$PYTHON_CMD" -c ' -import json, sys, os, re -import signal - -def _clv2_bail(*_): - print("[observe] SIGALRM timeout: in-flight observation dropped before write (#2300)", file=sys.stderr) - sys.exit(0) -try: - signal.signal(signal.SIGALRM, _clv2_bail) - signal.alarm(8) # self-terminate before the async hook 10s timeout can orphan us (#2278) -except Exception: - pass - -parsed = json.load(sys.stdin) -observation = { - "timestamp": os.environ["TIMESTAMP"], - "event": parsed["event"], - "tool": parsed["tool"], - "session": parsed["session"], - "project_id": os.environ.get("PROJECT_ID_ENV", "global"), - "project_name": os.environ.get("PROJECT_NAME_ENV", "global") -} - -# Scrub secrets, including JSON-escaped quotes/backslashes in serialized tool I/O. -# This is defense in depth; arbitrary content still requires a metadata-only capture boundary. -# Includes optional auth scheme (e.g., "Bearer", "Basic") before token -# Linear-time secret matcher. Bounded quantifiers and a fixed set of auth -# schemes (instead of a generic [A-Za-z]+\s+ that overlapped the value class) -# prevent the catastrophic backtracking that pegged python at 100% CPU (#2278). -# The value class is disjoint from the separators, so it runs to the end of the -# token: a long labeled key is redacted whole instead of leaving its tail. -_SECRET_RE = re.compile( - r"(?i)((?:api[_-]?key|token|secret|password|authorization|credentials?|auth)(?:_access_key|_key)?)" - r"""(["'"'"'\s:=\\]{1,8})""" - r"((?:bearer|basic|token|bot)\s+)?" - r"([A-Za-z0-9_\-/.+=]{8,})" -) -# Value-shaped secrets that carry no keyword: PEM private key blocks (to END or -# end of the truncated text), GitHub tokens, AWS key IDs, Anthropic and OpenAI -# style sk- keys, JWTs (eyJ header, payload, optional signature) and DSN -# passwords (scheme://user:PASSWORD@host keeps scheme and user). Each branch is -# anchored on a literal prefix and uses bounded or non-overlapping classes (#2278); -# the sk- and JWT classes run to the end of the token so a long value is never -# half redacted. -# Tokens may follow a JSON escape (\n, \t, \uXXXX) since dict I/O is encoded -# before scrubbing; a DSN cut by truncation before its "@" ends at \Z, -# except a bare trailing host:port after http(s):// such as http://localhost:3000; -# any other scheme (postgres://app:1234) is redacted even when the password is numeric (#3568). -# PEM blocks run first: a label such as secret= in front of the BEGIN marker -# would otherwise let _SECRET_RE eat "-----BEGIN" and hide the block from this match. -_PEM_RE = re.compile(r"-----BEGIN[A-Z ]{0,40}PRIVATE KEY-----[\s\S]*?(?:-----END[A-Z ]{0,40}PRIVATE KEY-----|\Z)") -_SECRET_VALUE_RE = re.compile( - r"(?:(?= 5000 - val = _PEM_RE.sub("[REDACTED]", val) - val = _SECRET_RE.sub(lambda m: m.group(1) + m.group(2) + (m.group(3) or "") + "[REDACTED]", val) - val = _SECRET_VALUE_RE.sub(lambda m: (m.group(2) or "") + "[REDACTED]", val) - return _CUT_TAIL_RE.sub("[REDACTED]", val) if cut else val - -# Prefer the canonical cwd that passed the project-selection boundary. Retain a -# bounded rejected string as diagnostic metadata without ever using it to select -# a project. Apply the same secret scrubber as tool I/O because path components -# can still contain credentials or tokens (for example, generated checkout names). -cwd = os.environ.get("OBSERVATION_CWD_ENV", "") or parsed.get("cwd", "") -if cwd: - observation["cwd"] = scrub(cwd) - -if parsed["input"]: - observation["input"] = scrub(parsed["input"]) -if parsed["output"] is not None: - observation["output"] = scrub(parsed["output"]) - -print(json.dumps(observation)) -' >> "$OBSERVATIONS_FILE" - # Lazy-start observer if enabled but not running (first-time setup) # Use flock for atomic check-then-act to prevent race conditions # Fallback for macOS (no flock): use lockfile or skip @@ -601,23 +749,10 @@ if [ -f "${CONFIG_DIR}/disabled" ]; then OBSERVER_ENABLED=false else OBSERVER_ENABLED=false - if [ -n "${CLV2_CONFIG:-}" ]; then - CONFIG_FILE="$CLV2_CONFIG" - elif [ -f "${CONFIG_DIR}/config.json" ]; then - CONFIG_FILE="${CONFIG_DIR}/config.json" - else - CONFIG_FILE="${SKILL_ROOT}/config.json" - fi - # Use effective config path for both existence check and reading - EFFECTIVE_CONFIG="$CONFIG_FILE" + # CONFIG_FILE / EFFECTIVE_CONFIG were resolved before stdin parsing, and the + # "enabled" flag was read by that same interpreter start. if [ -f "$EFFECTIVE_CONFIG" ] && [ -n "$PYTHON_CMD" ]; then - _enabled=$(CLV2_CONFIG_PATH="$EFFECTIVE_CONFIG" "$PYTHON_CMD" -c " -import json, os -with open(os.environ['CLV2_CONFIG_PATH']) as f: - cfg = json.load(f) -print(str(cfg.get('observer', {}).get('enabled', False)).lower()) -" 2>/dev/null || echo "false") - if [ "$_enabled" = "true" ]; then + if [ "${_CLV2_OBSERVER_ENABLED:-false}" = "true" ]; then OBSERVER_ENABLED=true fi fi diff --git a/skills/continuous-learning-v2/scripts/detect-project.sh b/skills/continuous-learning-v2/scripts/detect-project.sh index ddf8f4150..015210553 100755 --- a/skills/continuous-learning-v2/scripts/detect-project.sh +++ b/skills/continuous-learning-v2/scripts/detect-project.sh @@ -19,8 +19,22 @@ # 3. git repo root path (fallback, machine-specific) # 4. "global" (no project context detected) +# This file is sourced on every tool call. Each external command is a process +# launch, which costs a few milliseconds on Linux/macOS but 80-280 ms under Git +# Bash on Windows, so the hot path uses parameter expansion and shell builtins +# wherever an external command is not required. +# Git Bash may be handed a Windows path (C:\...\detect-project.sh); dirname +# accepted both separators there, so normalize before splitting. +_CLV2_DETECT_PROJECT_SELF="${BASH_SOURCE[0]}" +case "${OSTYPE:-}" in + msys*|cygwin*|win32*) _CLV2_DETECT_PROJECT_SELF="${_CLV2_DETECT_PROJECT_SELF//\\//}" ;; +esac +case "$_CLV2_DETECT_PROJECT_SELF" in + */*) _CLV2_DETECT_PROJECT_SCRIPT_DIR="${_CLV2_DETECT_PROJECT_SELF%/*}" ;; + *) _CLV2_DETECT_PROJECT_SCRIPT_DIR="." ;; +esac # shellcheck disable=SC1091 -. "$(dirname "${BASH_SOURCE[0]}")/lib/homunculus-dir.sh" +. "${_CLV2_DETECT_PROJECT_SCRIPT_DIR}/lib/homunculus-dir.sh" _CLV2_HOMUNCULUS_DIR="$(_clv2_resolve_homunculus_dir)" _CLV2_PROJECTS_DIR="${_CLV2_HOMUNCULUS_DIR}/projects" _CLV2_REGISTRY_FILE="${_CLV2_HOMUNCULUS_DIR}/projects.json" @@ -44,7 +58,13 @@ _clv2_resolve_python_cmd() { return 1 } -_CLV2_PYTHON_CMD="$(_clv2_resolve_python_cmd 2>/dev/null || true)" +if [ -n "${CLV2_PYTHON_CMD:-}" ] && command -v "$CLV2_PYTHON_CMD" >/dev/null 2>&1; then + # Already resolved by the caller (observe.sh exports it): reuse it without + # paying for a command-substitution subshell. + _CLV2_PYTHON_CMD="$CLV2_PYTHON_CMD" +else + _CLV2_PYTHON_CMD="$(_clv2_resolve_python_cmd 2>/dev/null || true)" +fi CLV2_PYTHON_CMD="$_CLV2_PYTHON_CMD" export CLV2_PYTHON_CMD @@ -317,8 +337,163 @@ atomic_write_json(registry_path, registry) ' 2>/dev/null || true } +# ───────────────────────────────────────────── +# Per-directory detection cache +# ───────────────────────────────────────────── +# +# Full detection launches git twice, python twice, sed six times and mkdir +# seven times, and rewrites projects.json. The answer rarely changes, so it is +# cached per (CLV2_NO_PROJECT, CLAUDE_PROJECT_DIR, PWD) for the rest of the day. +# +# A cached entry is rejected, and full detection reruns, when: +# - it was written on another day (so the registry last_seen still refreshes +# at least daily) +# - the repository's .git/config is not older than the entry (remote added +# or changed, which changes the project id) +# - the project storage directory or the project root no longer exists +# - the stored id is not a shape detection can produce +# +# Only a project whose own .git/config can be watched is cached. Linked +# worktrees, submodules and non-git CLAUDE_PROJECT_DIR roots are detected on +# every call, as is a "global" result reached because no repository was found. +# +# Set CLV2_PROJECT_CACHE=0 to disable. The day stamp needs printf '%(...)T' +# (bash >= 4.2); older shells such as the macOS system bash 3.2 skip the cache +# and detect on every call, exactly as before. +_CLV2_PROJECT_CACHE_HIT=0 +_CLV2_PROJECT_CACHE_FILE="" +_CLV2_PROJECT_CACHE_KEY="" +_CLV2_PROJECT_CACHE_DAY="" +_CLV2_PROJECT_CACHE_VERSION="clv2-project-cache-1" + +_clv2_project_cache_prepare() { + [ "${CLV2_PROJECT_CACHE:-1}" = "0" ] && return 1 + if [ "${BASH_VERSINFO[0]:-0}" -lt 4 ] || + { [ "${BASH_VERSINFO[0]:-0}" -eq 4 ] && [ "${BASH_VERSINFO[1]:-0}" -lt 2 ]; }; then + return 1 + fi + + local key="${CLV2_NO_PROJECT:-0}|${CLAUDE_PROJECT_DIR:-}|${PWD}" + # The entry is line-based, so a key that spans lines cannot be stored. + case "$key" in *$'\n'*|*$'\r'*) return 1 ;; esac + + local name="${key//[^A-Za-z0-9._-]/_}" + [ "${#name}" -gt 200 ] && return 1 + + printf -v _CLV2_PROJECT_CACHE_DAY '%(%Y%m%d)T' -1 + _CLV2_PROJECT_CACHE_KEY="$key" + _CLV2_PROJECT_CACHE_FILE="${_CLV2_HOMUNCULUS_DIR}/.project-cache/${name}" + return 0 +} + +_clv2_project_cache_load() { + local file="$_CLV2_PROJECT_CACHE_FILE" + [ -n "$file" ] && [ -f "$file" ] || return 1 + + local version day key id name root gitcfg + { + IFS= read -r version && IFS= read -r day && IFS= read -r key && + IFS= read -r id && IFS= read -r name && IFS= read -r root && + IFS= read -r gitcfg + } < "$file" 2>/dev/null || return 1 + + [ "$version" = "$_CLV2_PROJECT_CACHE_VERSION" ] || return 1 + [ "$day" = "$_CLV2_PROJECT_CACHE_DAY" ] || return 1 + # Sanitized file names can collide; the stored key is the real identity. + [ "$key" = "$_CLV2_PROJECT_CACHE_KEY" ] || return 1 + + # The id becomes a path segment, so accept only what detection can emit: + # "global", the "fallback" literal, or 12 lowercase hex characters. + local dir + case "$id" in + global) + [ -z "$root" ] || return 1 + dir="$_CLV2_HOMUNCULUS_DIR" + ;; + fallback) dir="${_CLV2_PROJECTS_DIR}/${id}" ;; + ''|*[!0-9a-f]*) return 1 ;; + *) + [ "${#id}" -eq 12 ] || return 1 + dir="${_CLV2_PROJECTS_DIR}/${id}" + ;; + esac + [ -d "$dir" ] || return 1 + + if [ "$id" != "global" ]; then + # A project entry is only stored together with the .git/config that + # produced its id (see _clv2_project_cache_store), and is trusted only + # while the entry is strictly newer than that file. Equal timestamps count + # as stale so a change in the same clock tick is not missed on filesystems + # with coarse mtimes. + [ -n "$gitcfg" ] && [ -f "$gitcfg" ] || return 1 + if ! [ "$file" -nt "$gitcfg" ]; then + return 1 + fi + # The root feeds CLV2_OBSERVER_SENTINEL_FILE; it must still be a directory. + [ -n "$root" ] && [ -d "$root" ] || return 1 + fi + + _CLV2_PROJECT_ID="$id" + _CLV2_PROJECT_NAME="$name" + _CLV2_PROJECT_ROOT="$root" + _CLV2_PROJECT_DIR="$dir" + _CLV2_PROJECT_CACHE_HIT=1 + return 0 +} + +_clv2_project_cache_store() { + local file="$_CLV2_PROJECT_CACHE_FILE" + [ -n "$file" ] || return 0 + + # "global" reached by fallthrough (no repository found) is not cached, so a + # directory that becomes a repository later is picked up on the next call. + # An explicit CLV2_NO_PROJECT=1 is part of the key and is safe to cache. + if [ "$_CLV2_PROJECT_ID" = "global" ] && [ "${CLV2_NO_PROJECT:-0}" != "1" ]; then + return 0 + fi + + case "${_CLV2_PROJECT_NAME}${_CLV2_PROJECT_ROOT}" in *$'\n'*|*$'\r'*) return 0 ;; esac + + local gitcfg="" + if [ -n "$_CLV2_PROJECT_ROOT" ] && [ -f "${_CLV2_PROJECT_ROOT}/.git/config" ]; then + gitcfg="${_CLV2_PROJECT_ROOT}/.git/config" + fi + + # A project is cached only when its own .git/config can be watched for + # changes. Linked worktrees and submodules (.git is a file; the config that + # decides the id lives elsewhere) and non-git CLAUDE_PROJECT_DIR roots have + # no such file here, so they are detected on every call, as before. + if [ "$_CLV2_PROJECT_ID" != "global" ] && [ -z "$gitcfg" ]; then + return 0 + fi + + local dir="${file%/*}" + local tmp="${file}.$$" + if [ ! -d "$dir" ]; then + mkdir -p "$dir" 2>/dev/null || return 0 + fi + + # Write then rename so a concurrent reader never sees a partial entry. + if printf '%s\n' \ + "$_CLV2_PROJECT_CACHE_VERSION" \ + "$_CLV2_PROJECT_CACHE_DAY" \ + "$_CLV2_PROJECT_CACHE_KEY" \ + "$_CLV2_PROJECT_ID" \ + "$_CLV2_PROJECT_NAME" \ + "$_CLV2_PROJECT_ROOT" \ + "$gitcfg" > "$tmp" 2>/dev/null; then + mv -f "$tmp" "$file" 2>/dev/null || rm -f "$tmp" 2>/dev/null || true + fi + return 0 +} + # Auto-detect on source -_clv2_detect_project +if _clv2_project_cache_prepare && _clv2_project_cache_load; then + : +else + _clv2_detect_project + _clv2_project_cache_store +fi # Convenience aliases for callers (short names pointing to prefixed vars) PROJECT_ID="$_CLV2_PROJECT_ID" diff --git a/tests/hooks/clv2-pymanager-launcher.test.js b/tests/hooks/clv2-pymanager-launcher.test.js index 4fccfb3cc..81b39dc2a 100644 --- a/tests/hooks/clv2-pymanager-launcher.test.js +++ b/tests/hooks/clv2-pymanager-launcher.test.js @@ -10,11 +10,12 @@ * same runtime without that check, so observe.sh runs those when they exist. * * Stand-in aliases and launchers are shell scripts that log which one ran and - * the CLV2_PYTHON_CMD observe.sh exported for detect-project.sh. A `disabled` - * file in the homunculus dir makes observe.sh exit right after its first - * Python call, so nothing else in the hook runs. One test leaves the hook - * enabled so it reaches detect-project.sh, whose project-id hash call the - * stand-ins mark as `detect-project`. + * the CLV2_PYTHON_CMD observe.sh exported for detect-project.sh. observe.sh + * reads cwd and agent_id from the payload in its first Python call and exits + * right after it for a subagent, so the stand-ins answer that call with an + * agent id and nothing else in the hook runs. One test answers without an + * agent id so the hook reaches detect-project.sh, whose project-id hash call + * the stand-ins mark as `detect-project`. * * Run with: node tests/hooks/clv2-pymanager-launcher.test.js */ @@ -91,7 +92,7 @@ function makeTree({ enabled = false } = {}) { for (const dir of [dirs.alias, dirs.launcher, dirs.regular, dirs.project, dirs.tools, dirs.home]) { fs.mkdirSync(dir, { recursive: true }); } - if (!enabled) fs.writeFileSync(path.join(dirs.home, 'disabled'), ''); + dirs.agentId = enabled ? '' : 'stand-in-subagent'; return dirs; } @@ -100,7 +101,7 @@ function makeTree({ enabled = false } = {}) { function writePython(dir, name, label) { fs.writeFileSync( path.join(dir, name), - `#!/bin/sh\necho "${label}|$CLV2_PYTHON_CMD\${_CLV2_HASH_INPUT:+|detect-project}" >> "$T_LOG"\ncase "$2" in *cwd*) [ -n "$T_PROJECT" ] && printf '%s\\n' "$T_PROJECT" ;; esac\n[ -n "\${_CLV2_HASH_INPUT:-}" ] && printf '0123456789ab\\n'\n`, + `#!/bin/sh\necho "${label}|$CLV2_PYTHON_CMD\${_CLV2_HASH_INPUT:+|detect-project}" >> "$T_LOG"\ncase "$2" in *agent_id*) printf '%s\\n%s\\n' "$T_PROJECT" "$T_AGENT_ID" ;; esac\n[ -n "\${_CLV2_HASH_INPUT:-}" ] && printf '0123456789ab\\n'\n`, { mode: 0o755 } ); } @@ -113,6 +114,7 @@ function run(dirs, pathDirs, env = {}, { checkStatus = true } = {}) { baseEnv.CLAUDE_CODE_ENTRYPOINT = 'cli'; baseEnv.LOCALAPPDATA = dirs.local; baseEnv.T_INPUT = JSON.stringify({ cwd: '' }); + baseEnv.T_AGENT_ID = dirs.agentId; const merged = { ...baseEnv, ...env }; for (const [key, value] of Object.entries(merged)) { if (value === undefined) delete merged[key]; diff --git a/tests/hooks/detect-project-cache.test.js b/tests/hooks/detect-project-cache.test.js new file mode 100644 index 000000000..4149e96cf --- /dev/null +++ b/tests/hooks/detect-project-cache.test.js @@ -0,0 +1,463 @@ +/** + * Tests for the per-directory project detection cache in detect-project.sh. + * + * detect-project.sh is sourced by observe.sh before and after every tool call. + * Full detection launches git, python, sed and mkdir many times, which is cheap + * on Linux/macOS but costs seconds per call under Git Bash on Windows. The + * cache serves a repeat call from one small file, and these tests pin when it + * may and may not be trusted: + * + * - a repeat call is a hit, returns the same project, and launches no git + * - a changed remote (.git/config newer than the entry) forces re-detection + * - an entry from another day forces re-detection + * - a missing project directory forces re-detection + * - an id that detection could not have produced is rejected + * - CLV2_PROJECT_CACHE=0 turns the cache off + * - a fallthrough "global" result is not cached + * + * Run with: node tests/hooks/detect-project-cache.test.js + */ + +// Skip on Windows — these tests invoke bash scripts directly +if (process.platform === 'win32') { + console.log('Skipping bash-dependent detection cache tests on Windows\n'); + process.exit(0); +} + +const assert = require('assert'); +const path = require('path'); +const fs = require('fs'); +const os = require('os'); +const { execFileSync, spawnSync } = require('child_process'); + +let passed = 0; +let failed = 0; + +function test(name, fn) { + try { + fn(); + console.log(` ✓ ${name}`); + passed++; + } catch (err) { + console.log(` ✗ ${name}`); + console.log(` Error: ${err.message}`); + failed++; + } +} + +function createTempDir() { + return fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-detect-cache-test-')); +} + +function cleanupDir(dir) { + try { + fs.rmSync(dir, { recursive: true, force: true }); + } catch { + // ignore cleanup errors + } +} + +const repoRoot = path.resolve(__dirname, '..', '..'); +const skillRoot = path.join(repoRoot, 'skills', 'continuous-learning-v2'); +const detectProjectPath = path.join(skillRoot, 'scripts', 'detect-project.sh'); +const observePath = path.join(skillRoot, 'hooks', 'observe.sh'); + +// The cache needs printf '%(...)T' (bash >= 4.2). On older shells such as the +// macOS system bash it is skipped by design, so there is nothing to test. +function bashSupportsCache() { + const r = spawnSync('bash', ['-c', 'printf "%s.%s" "${BASH_VERSINFO[0]}" "${BASH_VERSINFO[1]}"'], { + encoding: 'utf8' + }); + if (r.error || r.status !== 0) return false; + const [major, minor] = r.stdout.trim().split('.').map(Number); + return major > 4 || (major === 4 && minor >= 2); +} + +function git(cwd, ...args) { + execFileSync('git', args, { cwd, stdio: 'ignore' }); +} + +function makeRepo(parent, name, remote) { + const repo = path.join(parent, name); + fs.mkdirSync(repo, { recursive: true }); + git(repo, 'init', '-q'); + if (remote) git(repo, 'remote', 'add', 'origin', remote); + // An entry is trusted only while it is strictly newer than .git/config. + // Backdate the config so that holds even where mtimes (or the shell's -nt) + // only resolve whole seconds. + const past = new Date(Date.now() - 10000); + fs.utimesSync(path.join(repo, '.git', 'config'), past, past); + return repo; +} + +function baseEnv(homeDir, extra = {}) { + const env = { ...process.env, HOME: homeDir, USERPROFILE: homeDir }; + delete env.CLAUDE_PROJECT_DIR; + delete env.CLV2_NO_PROJECT; + delete env.CLV2_HOMUNCULUS_DIR; + delete env.XDG_DATA_HOME; + delete env.CLV2_PROJECT_CACHE; + return { ...env, ...extra }; +} + +// Source detect-project.sh from `cwd` and return what it resolved. +function detect(cwd, homeDir, extraEnv = {}) { + const script = [ + 'source "$DETECT_PROJECT"', + 'printf "%s\\n" "$PROJECT_ID" "$PROJECT_NAME" "$PROJECT_ROOT" "$PROJECT_DIR" "$_CLV2_PROJECT_CACHE_HIT"' + ].join('\n'); + const r = spawnSync('bash', ['-c', script], { + cwd, + encoding: 'utf8', + timeout: 60000, + env: baseEnv(homeDir, { DETECT_PROJECT: detectProjectPath, ...extraEnv }) + }); + assert.strictEqual(r.status, 0, `detect-project.sh should source cleanly, stderr: ${r.stderr}`); + const [id, name, root, dir, hit] = r.stdout.split('\n'); + return { id, name, root, dir, hit }; +} + +function homunculusDir(homeDir) { + return path.join(homeDir, '.local', 'share', 'ecc-homunculus'); +} + +function cacheEntries(homeDir) { + const dir = path.join(homunculusDir(homeDir), '.project-cache'); + if (!fs.existsSync(dir)) return []; + return fs.readdirSync(dir).map((f) => path.join(dir, f)); +} + +function rewriteCacheLine(file, index, value) { + const lines = fs.readFileSync(file, 'utf8').split('\n'); + lines[index] = value; + fs.writeFileSync(file, lines.join('\n')); +} + +// Put a `git` wrapper first on PATH that records each call, then runs real git. +function gitSpy(dir) { + const real = execFileSync('bash', ['-c', 'command -v git'], { encoding: 'utf8' }).trim(); + const binDir = path.join(dir, 'spy-bin'); + const log = path.join(dir, 'git-calls.log'); + fs.mkdirSync(binDir, { recursive: true }); + fs.writeFileSync( + path.join(binDir, 'git'), + ['#!/usr/bin/env bash', `printf '%s\\n' "$*" >> "$GIT_SPY_LOG"`, `exec "${real}" "$@"`, ''].join('\n'), + { mode: 0o755 } + ); + return { + env: { PATH: `${binDir}${path.delimiter}${process.env.PATH}`, GIT_SPY_LOG: log }, + calls: () => (fs.existsSync(log) ? fs.readFileSync(log, 'utf8').split('\n').filter(Boolean).length : 0) + }; +} + +console.log('\n=== detect-project.sh detection cache ===\n'); + +if (!bashSupportsCache()) { + console.log('Skipping: bash < 4.2 does not use the detection cache\n'); + process.exit(0); +} + +test('a repeat call is served from the cache with identical results', () => { + const tmp = createTempDir(); + try { + const home = path.join(tmp, 'home'); + fs.mkdirSync(home); + const repo = makeRepo(tmp, 'alpha', 'https://github.com/example/alpha.git'); + + const first = detect(repo, home); + const second = detect(repo, home); + + assert.strictEqual(first.hit, '0', 'first call must run full detection'); + assert.strictEqual(second.hit, '1', 'second call must be a cache hit'); + assert.match(first.id, /^[0-9a-f]{12}$/, 'project id should be a 12-char hex hash'); + assert.deepStrictEqual( + { id: second.id, name: second.name, root: second.root, dir: second.dir }, + { id: first.id, name: first.name, root: first.root, dir: first.dir }, + 'a cache hit must return exactly what detection returned' + ); + assert.strictEqual(cacheEntries(home).length, 1, 'one cache entry should exist'); + } finally { + cleanupDir(tmp); + } +}); + +test('a cache hit launches no git process', () => { + const tmp = createTempDir(); + try { + const home = path.join(tmp, 'home'); + fs.mkdirSync(home); + const repo = makeRepo(tmp, 'beta', 'https://github.com/example/beta.git'); + const spy = gitSpy(tmp); + + detect(repo, home, spy.env); + const afterMiss = spy.calls(); + assert.ok(afterMiss > 0, 'full detection should call git'); + + const second = detect(repo, home, spy.env); + assert.strictEqual(second.hit, '1'); + assert.strictEqual(spy.calls(), afterMiss, 'a cache hit must not call git'); + } finally { + cleanupDir(tmp); + } +}); + +test('a changed remote invalidates the entry and yields the new project id', () => { + const tmp = createTempDir(); + try { + const home = path.join(tmp, 'home'); + fs.mkdirSync(home); + const repo = makeRepo(tmp, 'gamma', 'https://github.com/example/gamma.git'); + + const first = detect(repo, home); + git(repo, 'remote', 'set-url', 'origin', 'https://github.com/example/gamma-renamed.git'); + // Make the config unambiguously newer than the entry, whatever the + // filesystem's timestamp granularity. + const future = new Date(Date.now() + 5000); + fs.utimesSync(path.join(repo, '.git', 'config'), future, future); + + const second = detect(repo, home); + assert.strictEqual(second.hit, '0', 'a newer .git/config must force re-detection'); + assert.notStrictEqual(second.id, first.id, 'the project id must follow the new remote'); + } finally { + cleanupDir(tmp); + } +}); + +test('an entry written on another day is not trusted', () => { + const tmp = createTempDir(); + try { + const home = path.join(tmp, 'home'); + fs.mkdirSync(home); + const repo = makeRepo(tmp, 'delta', 'https://github.com/example/delta.git'); + + const first = detect(repo, home); + const [entry] = cacheEntries(home); + rewriteCacheLine(entry, 1, '19990101'); + + const second = detect(repo, home); + assert.strictEqual(second.hit, '0', 'a stale day stamp must force re-detection'); + assert.strictEqual(second.id, first.id); + assert.notStrictEqual( + fs.readFileSync(entry, 'utf8').split('\n')[1], + '19990101', + 're-detection should refresh the entry' + ); + } finally { + cleanupDir(tmp); + } +}); + +test('a missing project directory forces re-detection and is recreated', () => { + const tmp = createTempDir(); + try { + const home = path.join(tmp, 'home'); + fs.mkdirSync(home); + const repo = makeRepo(tmp, 'epsilon', 'https://github.com/example/epsilon.git'); + + const first = detect(repo, home); + fs.rmSync(first.dir, { recursive: true, force: true }); + + const second = detect(repo, home); + assert.strictEqual(second.hit, '0', 'a deleted project dir must force re-detection'); + assert.ok(fs.existsSync(path.join(second.dir, 'instincts', 'personal')), 'project structure should be recreated'); + } finally { + cleanupDir(tmp); + } +}); + +test('an id detection could not have produced is rejected', () => { + const tmp = createTempDir(); + try { + const home = path.join(tmp, 'home'); + fs.mkdirSync(home); + const repo = makeRepo(tmp, 'zeta', 'https://github.com/example/zeta.git'); + + const first = detect(repo, home); + const [entry] = cacheEntries(home); + fs.mkdirSync(path.join(tmp, 'escaped')); + + for (const bad of ['../../../../escaped', 'ABCDEF012345', 'abc', `${first.id}/..`]) { + rewriteCacheLine(entry, 3, bad); + const again = detect(repo, home); + assert.strictEqual(again.hit, '0', `tampered id ${JSON.stringify(bad)} must not be a hit`); + assert.strictEqual(again.id, first.id, 'detection should restore the real id'); + assert.ok( + again.dir.endsWith(`/projects/${first.id}`), + `PROJECT_DIR must stay under the projects directory, got ${again.dir}` + ); + } + } finally { + cleanupDir(tmp); + } +}); + +test('CLV2_PROJECT_CACHE=0 disables the cache', () => { + const tmp = createTempDir(); + try { + const home = path.join(tmp, 'home'); + fs.mkdirSync(home); + const repo = makeRepo(tmp, 'eta', 'https://github.com/example/eta.git'); + + const first = detect(repo, home, { CLV2_PROJECT_CACHE: '0' }); + const second = detect(repo, home, { CLV2_PROJECT_CACHE: '0' }); + + assert.strictEqual(first.hit, '0'); + assert.strictEqual(second.hit, '0', 'with the cache off every call must detect'); + assert.strictEqual(second.id, first.id); + assert.strictEqual(cacheEntries(home).length, 0, 'no cache entry should be written'); + } finally { + cleanupDir(tmp); + } +}); + +test('a fallthrough "global" result is not cached, so a later git init is seen', () => { + const tmp = createTempDir(); + try { + const home = path.join(tmp, 'home'); + fs.mkdirSync(home); + const dir = path.join(tmp, 'plain'); + fs.mkdirSync(dir); + + const before = detect(dir, home); + assert.strictEqual(before.id, 'global'); + assert.strictEqual(cacheEntries(home).length, 0, 'global-by-fallthrough must not be cached'); + + git(dir, 'init', '-q'); + const after = detect(dir, home); + assert.notStrictEqual(after.id, 'global', 'the new repository must be detected on the next call'); + } finally { + cleanupDir(tmp); + } +}); + +test('an explicit CLV2_NO_PROJECT=1 result is cached under its own key', () => { + const tmp = createTempDir(); + try { + const home = path.join(tmp, 'home'); + fs.mkdirSync(home); + const repo = makeRepo(tmp, 'theta', 'https://github.com/example/theta.git'); + + const first = detect(repo, home, { CLV2_NO_PROJECT: '1' }); + const second = detect(repo, home, { CLV2_NO_PROJECT: '1' }); + assert.strictEqual(first.id, 'global'); + assert.strictEqual(second.hit, '1'); + assert.strictEqual(second.id, 'global'); + + // The same directory without the flag is a different key and a real project. + const project = detect(repo, home); + assert.strictEqual(project.hit, '0'); + assert.match(project.id, /^[0-9a-f]{12}$/); + } finally { + cleanupDir(tmp); + } +}); + +test('a linked worktree is never cached (its config lives outside the worktree)', () => { + const tmp = createTempDir(); + try { + const home = path.join(tmp, 'home'); + fs.mkdirSync(home); + const repo = makeRepo(tmp, 'kappa'); + git(repo, '-c', 'user.email=test@example.com', '-c', 'user.name=Test', 'commit', '-q', '--allow-empty', '-m', 'init'); + const worktree = path.join(tmp, 'kappa-wt'); + git(repo, 'worktree', 'add', '-q', worktree); + + const first = detect(worktree, home); + const second = detect(worktree, home); + assert.match(first.id, /^[0-9a-f]{12}$/); + assert.strictEqual(second.hit, '0', 'a worktree has no watchable .git/config, so it must not be cached'); + assert.strictEqual(second.id, first.id); + + // Adding a remote in the main repository changes the id; the worktree + // must follow on the very next call. + git(repo, 'remote', 'add', 'origin', 'https://github.com/example/kappa.git'); + const third = detect(worktree, home); + assert.notStrictEqual(third.id, first.id, 'the worktree must pick up the new remote immediately'); + } finally { + cleanupDir(tmp); + } +}); + +test('a non-git CLAUDE_PROJECT_DIR root is never cached', () => { + const tmp = createTempDir(); + try { + const home = path.join(tmp, 'home'); + fs.mkdirSync(home); + const dir = path.join(tmp, 'plain-project'); + fs.mkdirSync(dir); + + const first = detect(dir, home, { CLAUDE_PROJECT_DIR: dir }); + const second = detect(dir, home, { CLAUDE_PROJECT_DIR: dir }); + assert.match(first.id, /^[0-9a-f]{12}$/, 'an explicit non-git root is a path-hash project'); + assert.strictEqual(second.hit, '0', 'a root without .git/config must not be cached'); + assert.strictEqual(cacheEntries(home).length, 0); + } finally { + cleanupDir(tmp); + } +}); + +test('an entry whose project root no longer exists is rejected', () => { + const tmp = createTempDir(); + try { + const home = path.join(tmp, 'home'); + fs.mkdirSync(home); + const repo = makeRepo(tmp, 'lambda', 'https://github.com/example/lambda.git'); + + detect(repo, home); + const [entry] = cacheEntries(home); + rewriteCacheLine(entry, 5, path.join(tmp, 'does-not-exist')); + + const second = detect(repo, home); + assert.strictEqual(second.hit, '0', 'a root that is not a directory must force re-detection'); + } finally { + cleanupDir(tmp); + } +}); + +test('observe.sh records the same project on a cache hit as on a miss', () => { + const tmp = createTempDir(); + try { + const home = path.join(tmp, 'home'); + fs.mkdirSync(home); + const repo = makeRepo(tmp, 'iota', 'https://github.com/example/iota.git'); + const payload = JSON.stringify({ + session_id: 'cache-test', + cwd: repo, + tool_name: 'Read', + tool_input: { file_path: 'README.md' } + }); + + for (let i = 0; i < 2; i += 1) { + const r = spawnSync('bash', [observePath, 'pre'], { + cwd: repo, + input: payload, + encoding: 'utf8', + timeout: 60000, + env: baseEnv(home, { CLAUDE_CODE_ENTRYPOINT: 'cli', ECC_HOOK_PROFILE: 'standard', ECC_SKIP_OBSERVE: '0' }) + }); + assert.strictEqual(r.status, 0, `observe.sh should exit 0, stderr: ${r.stderr}`); + } + + assert.strictEqual(cacheEntries(home).length, 1, 'observe.sh should leave one cache entry'); + const projectsDir = path.join(homunculusDir(home), 'projects'); + const [projectId] = fs.readdirSync(projectsDir); + const records = fs + .readFileSync(path.join(projectsDir, projectId, 'observations.jsonl'), 'utf8') + .split('\n') + .filter(Boolean) + .map((line) => JSON.parse(line)); + + assert.strictEqual(records.length, 2, 'both calls should record an observation'); + assert.strictEqual(records[0].project_id, projectId); + assert.deepStrictEqual( + { id: records[1].project_id, name: records[1].project_name, event: records[1].event }, + { id: records[0].project_id, name: records[0].project_name, event: 'tool_start' } + ); + } finally { + cleanupDir(tmp); + } +}); + +console.log(`\nPassed: ${passed}`); +console.log(`Failed: ${failed}`); +process.exit(failed > 0 ? 1 : 0);