From d2db7871fe19b2008f54ba3f4d1f95b89e81f7df Mon Sep 17 00:00:00 2001 From: montjeffrey Date: Tue, 17 Nov 2026 14:20:54 -0500 Subject: [PATCH 1/5] perf(clv2): cut observe hook process launches observe.sh runs before and after every tool call and launched about 50 external processes per run. Each costs a few milliseconds on Linux/macOS but 80-280 ms under Git Bash on Windows, where one run took 5-7 s. - Read cwd, agent_id and observer.enabled in one Python start, and parse, scrub and write the observation in one more (was six). The redaction patterns are unchanged. - Cache project detection per (CLV2_NO_PROJECT, CLAUDE_PROJECT_DIR, PWD) for the rest of the day. An entry is rejected when .git/config is not older than it, when the project dir or root is gone, or when the id is not a shape detection can produce. Worktrees, submodules and non-git roots are never cached. CLV2_PROJECT_CACHE=0 disables it; bash < 4.2 skips it. - Run the stdin-independent guards before the first interpreter start. - Run the find/du housekeeping only when detection was not cached. - Replace dirname/readlink/subshell calls on the hot path with builtins. Measured on Windows 11 / Git Bash, warm cache: 5.2-5.8 s -> 1.1-1.2 s per run. Output compared against the previous script on 19 payloads (records, redaction, registry, counters, exit codes): identical. Behavior changes: projects.json last_seen refreshes at least daily instead of every call; observations.jsonl may exceed the 10 MB cap by up to a day of records before archiving; the App Installer stub check only follows symlinks for paths under WindowsApps. --- .../continuous-learning-v2/hooks/observe.sh | 707 +++++++++++------- .../scripts/detect-project.sh | 181 ++++- tests/hooks/clv2-pymanager-launcher.test.js | 16 +- tests/hooks/detect-project-cache.test.js | 463 ++++++++++++ 4 files changed, 1071 insertions(+), 296 deletions(-) create mode 100644 tests/hooks/detect-project-cache.test.js 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); From 36708d4e93210354a47b086711913a6f9fd3cd73 Mon Sep 17 00:00:00 2001 From: montjeffrey Date: Tue, 17 Nov 2026 12:08:12 -0500 Subject: [PATCH 2/5] chore(context): refresh skill-triggers registry digest for the clv2 script changes --- manifests/context-packs/skill-triggers@1.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/manifests/context-packs/skill-triggers@1.json b/manifests/context-packs/skill-triggers@1.json index dca98a820..2d91feda8 100644 --- a/manifests/context-packs/skill-triggers@1.json +++ b/manifests/context-packs/skill-triggers@1.json @@ -10,7 +10,7 @@ "id": "hand-seeded", "source": "manual-curation-pending-regeneration" }, - "registryDigest": "cf9879ff972740a7d2af9b56a0f682870375d3abc75eea9164bd2b1838fd5b81", + "registryDigest": "61b0be39df2da66ae892aa95c3d344ec32a9bf03d3538c6545580bdb1fe16a02", "schemaVersion": 1, "triggers": { "skill:agent-runtime-gateway-smoke-test": [ From 155b4d254fce5f36c234a069501e09f489dca321 Mon Sep 17 00:00:00 2001 From: Jeffrey Montoya Date: Wed, 18 Nov 2026 04:25:30 -0500 Subject: [PATCH 3/5] fix(clv2): validate the detection cache against the live origin Address the review findings on the observe hook trim: - Cache entries store the credential-stripped origin detection read, and a hit compares it with `git remote get-url origin`, so included, global and GIT_CONFIG_* origins and a config change during detection are all caught. - Keep the payload cwd byte for byte (a directory name may hold a newline). - Follow a symlinked python stub outside WindowsApps on Windows-like shells. - Run housekeeping once a day from its own per-project marker, independent of the detection cache. --- manifests/context-packs/skill-triggers@1.json | 2 +- .../continuous-learning-v2/hooks/observe.sh | 100 +++++-- .../scripts/detect-project.sh | 86 +++--- tests/hooks/clv2-pymanager-launcher.test.js | 2 +- tests/hooks/detect-project-cache.test.js | 249 ++++++++++++++++-- 5 files changed, 359 insertions(+), 80 deletions(-) diff --git a/manifests/context-packs/skill-triggers@1.json b/manifests/context-packs/skill-triggers@1.json index 2d91feda8..dd99b2c48 100644 --- a/manifests/context-packs/skill-triggers@1.json +++ b/manifests/context-packs/skill-triggers@1.json @@ -10,7 +10,7 @@ "id": "hand-seeded", "source": "manual-curation-pending-regeneration" }, - "registryDigest": "61b0be39df2da66ae892aa95c3d344ec32a9bf03d3538c6545580bdb1fe16a02", + "registryDigest": "24385666bb04a9945f13fa7dd8f9f30edb1c1e809da1419d5f8841cd8183715a", "schemaVersion": 1, "triggers": { "skill:agent-runtime-gateway-smoke-test": [ diff --git a/skills/continuous-learning-v2/hooks/observe.sh b/skills/continuous-learning-v2/hooks/observe.sh index ffd9ae1a3..c55b1db37 100755 --- a/skills/continuous-learning-v2/hooks/observe.sh +++ b/skills/continuous-learning-v2/hooks/observe.sh @@ -142,12 +142,21 @@ _is_windows_app_installer_stub() { 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. + # The alias stubs live under ...\Microsoft\WindowsApps\, so a candidate + # resolved there always has its link followed. Anywhere else only a symbolic + # link can lead to the stub, and only where Windows programs can run at all + # (Git Bash, Cygwin, WSL). Both checks are builtins, so an ordinary file, and + # any python3 on plain Linux or macOS (usually a symlink), costs no readlink + # launch on every tool call. case "$_resolved" in */[Ww]indows[Aa]pps/*) ;; - *) return 1 ;; + *) + [ -L "$_resolved" ] || return 1 + case "${OSTYPE:-}" in + msys*|cygwin*|win32*) ;; + *) [ -n "${WSL_DISTRO_NAME:-}${WSL_INTEROP:-}" ] || return 1 ;; + esac + ;; esac # Also resolve one level of symlink on POSIX-like shells (Git Bash, WSL). if command -v readlink >/dev/null 2>&1; then @@ -278,31 +287,38 @@ 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. +# Output: agent_id on line 1, observer.enabled on line 2, then cwd as everything +# after that, closed by a "." so trailing characters survive $(...). cwd is the +# only value that must arrive byte for byte (a directory name may contain a +# newline on POSIX), so it is the one that is not confined to a line. 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", " ") +def printable(text): text.encode(sys.stdout.encoding or "utf-8") return text +def one_line(value): + return printable(str(value).replace("\r", " ").replace("\n", " ")) + 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). +# Only an absolute, existing directory is reported, in canonical form and with +# its characters unchanged; 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)) + cwd = printable(os.path.realpath(cwd)) else: cwd = "" except Exception: @@ -323,23 +339,33 @@ if config_path: except Exception: enabled = "false" -sys.stdout.write(cwd + "\n" + agent_id + "\n" + enabled + "\n") +# newline="" keeps a newline inside cwd from becoming CRLF on native Windows. +out = sys.stdout +try: + out.reconfigure(newline="") +except Exception: + pass +out.write(agent_id + "\n" + enabled + "\n" + cwd + ".") ' 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 +# Accept the output only in its complete shape: two lines, then cwd closed by +# ".". Anything else (Python failed part-way) leaves all three at their safe +# defaults. +case "$_CLV2_STDIN_FIELDS" in + *$'\n'*$'\n'*.) + _ECC_AGENT_ID="${_CLV2_STDIN_FIELDS%%$'\n'*}" + _CLV2_STDIN_REST="${_CLV2_STDIN_FIELDS#*$'\n'}" + _CLV2_OBSERVER_ENABLED="${_CLV2_STDIN_REST%%$'\n'*}" + STDIN_CWD="${_CLV2_STDIN_REST#*$'\n'}" + STDIN_CWD="${STDIN_CWD%.}" + # A Python that could not switch off newline translation writes CRLF. + _ECC_AGENT_ID="${_ECC_AGENT_ID%$'\r'}" + _CLV2_OBSERVER_ENABLED="${_CLV2_OBSERVER_ENABLED%$'\r'}" + ;; +esac # Layer 4: subagent sessions are automated by definition. [ -n "$_ECC_AGENT_ID" ] && exit 0 @@ -398,11 +424,24 @@ OBSERVATIONS_FILE="${PROJECT_DIR}/observations.jsonl" MAX_FILE_SIZE_MB=10 # 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 +# so it runs once a day per project instead of on every call. The day it last +# ran is kept in its own marker inside the project directory, so the guarantee +# does not depend on who filled the detection cache (start-observer.sh sources +# detect-project.sh too, and does no housekeeping). The observations file can +# therefore exceed MAX_FILE_SIZE_MB by at most one day of records before it is +# archived. Shells without printf '%(...)T' (bash < 4.2) cannot read the day +# without a launch and keep running it on every call, as before. +_CLV2_HOUSEKEEPING_MARKER="${PROJECT_DIR}/.housekeeping-day" +_CLV2_HOUSEKEEPING_TODAY="" +_CLV2_HOUSEKEEPING_LAST="" +if [ "${BASH_VERSINFO[0]:-0}" -gt 4 ] || + { [ "${BASH_VERSINFO[0]:-0}" -eq 4 ] && [ "${BASH_VERSINFO[1]:-0}" -ge 2 ]; }; then + printf -v _CLV2_HOUSEKEEPING_TODAY '%(%Y%m%d)T' -1 + if [ -f "$_CLV2_HOUSEKEEPING_MARKER" ]; then + IFS= read -r _CLV2_HOUSEKEEPING_LAST < "$_CLV2_HOUSEKEEPING_MARKER" 2>/dev/null || true + fi +fi +if [ -z "$_CLV2_HOUSEKEEPING_TODAY" ] || [ "$_CLV2_HOUSEKEEPING_LAST" != "$_CLV2_HOUSEKEEPING_TODAY" ]; 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 @@ -419,6 +458,11 @@ if [ "${_CLV2_PROJECT_CACHE_HIT:-0}" != "1" ]; then mv "$OBSERVATIONS_FILE" "$archive_dir/observations-$(date +%Y%m%d-%H%M%S)-$$.jsonl" 2>/dev/null || true fi fi + + # Recorded after the work, so an interrupted run is repeated by the next call. + if [ -n "$_CLV2_HOUSEKEEPING_TODAY" ]; then + printf '%s\n' "$_CLV2_HOUSEKEEPING_TODAY" > "$_CLV2_HOUSEKEEPING_MARKER" 2>/dev/null || true + fi fi # ───────────────────────────────────────────── diff --git a/skills/continuous-learning-v2/scripts/detect-project.sh b/skills/continuous-learning-v2/scripts/detect-project.sh index 015210553..f8ffb33b1 100755 --- a/skills/continuous-learning-v2/scripts/detect-project.sh +++ b/skills/continuous-learning-v2/scripts/detect-project.sh @@ -180,6 +180,8 @@ _clv2_detect_project() { fi local raw_remote_url="$remote_url" + # Remembered for the detection cache: the origin this id was derived from. + _CLV2_PROJECT_REMOTE_SEEN="$raw_remote_url" # Strip embedded credentials from remote URL (e.g., https://ghp_xxxx@github.com/...) if [ -n "$remote_url" ]; then @@ -343,19 +345,27 @@ atomic_write_json(registry_path, registry) # # 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. +# cached per (CLV2_NO_PROJECT, CLAUDE_PROJECT_DIR, PWD) for the rest of the day; +# a hit costs one git launch (none for a cached "global"). # # 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) +# - git no longer reports the origin the entry was derived from (remote +# added, changed or removed, 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. +# The origin is asked from git on every hit (one `git remote get-url`) rather +# than inferred from file timestamps: the effective origin can come from the +# repository config, a file it includes, the global or system config, or +# GIT_CONFIG_* variables, and only git resolves all of those. The entry stores +# the origin that detection itself read, so an entry written while the config +# was being changed fails this comparison too. +# +# Only a repository with its own .git/config file 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 @@ -364,7 +374,19 @@ _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_VERSION="clv2-project-cache-2" +_CLV2_PROJECT_REMOTE_SEEN="" +_CLV2_PROJECT_CACHE_REMOTE="" + +# Drop embedded credentials (https://token@host/...) so they never reach the +# cache file. Same rule as the sed in _clv2_detect_project, without a launch: +# the leftmost "://@" becomes "://". +_clv2_project_cache_remote() { + _CLV2_PROJECT_CACHE_REMOTE="$1" + if [[ "$1" =~ ://[^@]+@ ]]; then + _CLV2_PROJECT_CACHE_REMOTE="${1/"${BASH_REMATCH[0]}"/://}" + fi +} _clv2_project_cache_prepare() { [ "${CLV2_PROJECT_CACHE:-1}" = "0" ] && return 1 @@ -390,11 +412,11 @@ _clv2_project_cache_load() { local file="$_CLV2_PROJECT_CACHE_FILE" [ -n "$file" ] && [ -f "$file" ] || return 1 - local version day key id name root gitcfg + local version day key id name root remote { 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 + IFS= read -r remote } < "$file" 2>/dev/null || return 1 [ "$version" = "$_CLV2_PROJECT_CACHE_VERSION" ] || return 1 @@ -420,17 +442,19 @@ _clv2_project_cache_load() { [ -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. + # The root feeds CLV2_OBSERVER_SENTINEL_FILE; it must still be a directory, + # and still a repository with its own .git/config file (see the store side). [ -n "$root" ] && [ -d "$root" ] || return 1 + [ -f "${root}/.git/config" ] || return 1 + # The id is derived from the origin, so the entry is trusted only while + # git reports the same origin that detection read when it wrote the entry. + # A repository without an origin stores an empty line and must still have + # none. Without git the origin cannot be confirmed, so nothing is trusted. + command -v git >/dev/null 2>&1 || return 1 + local live + live=$(git -C "$root" remote get-url origin 2>/dev/null || true) + _clv2_project_cache_remote "$live" + [ "$_CLV2_PROJECT_CACHE_REMOTE" = "$remote" ] || return 1 fi _CLV2_PROJECT_ID="$id" @@ -454,17 +478,17 @@ _clv2_project_cache_store() { 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 + local remote="" + if [ "$_CLV2_PROJECT_ID" != "global" ]; then + # A project is cached only when it is a repository with its own .git + # directory. Linked worktrees and submodules (.git is a file; their id can + # also depend on the main worktree) and non-git CLAUDE_PROJECT_DIR roots + # are detected on every call, as before. + [ -n "$_CLV2_PROJECT_ROOT" ] && [ -f "${_CLV2_PROJECT_ROOT}/.git/config" ] || return 0 + _clv2_project_cache_remote "$_CLV2_PROJECT_REMOTE_SEEN" + remote="$_CLV2_PROJECT_CACHE_REMOTE" + # The entry is line-based; an origin that spans lines cannot be stored. + case "$remote" in *$'\n'*|*$'\r'*) return 0 ;; esac fi local dir="${file%/*}" @@ -481,7 +505,7 @@ _clv2_project_cache_store() { "$_CLV2_PROJECT_ID" \ "$_CLV2_PROJECT_NAME" \ "$_CLV2_PROJECT_ROOT" \ - "$gitcfg" > "$tmp" 2>/dev/null; then + "$remote" > "$tmp" 2>/dev/null; then mv -f "$tmp" "$file" 2>/dev/null || rm -f "$tmp" 2>/dev/null || true fi return 0 diff --git a/tests/hooks/clv2-pymanager-launcher.test.js b/tests/hooks/clv2-pymanager-launcher.test.js index 81b39dc2a..caa2d3a89 100644 --- a/tests/hooks/clv2-pymanager-launcher.test.js +++ b/tests/hooks/clv2-pymanager-launcher.test.js @@ -101,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 *agent_id*) printf '%s\\n%s\\n' "$T_PROJECT" "$T_AGENT_ID" ;; 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\\nfalse\\n%s.' "$T_AGENT_ID" "$T_PROJECT" ;; esac\n[ -n "\${_CLV2_HASH_INPUT:-}" ] && printf '0123456789ab\\n'\n`, { mode: 0o755 } ); } diff --git a/tests/hooks/detect-project-cache.test.js b/tests/hooks/detect-project-cache.test.js index 4149e96cf..b96c621d9 100644 --- a/tests/hooks/detect-project-cache.test.js +++ b/tests/hooks/detect-project-cache.test.js @@ -7,8 +7,12 @@ * 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 + * - a repeat call is a hit, returns the same project, and launches git once + * (to ask for the origin) + * - a changed origin forces re-detection wherever it is configured: the + * repository config, a file it includes, or the global config + * - an entry that holds an origin git does not report is rejected + * - credentials embedded in the origin never reach the cache file * - 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 @@ -82,16 +86,17 @@ function makeRepo(parent, name, remote) { 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 }; + // HOME is a fresh directory, so no global git config leaks in. The system + // config and any GIT_CONFIG_* overrides from the caller are shut out too. + const env = { ...process.env, HOME: homeDir, USERPROFILE: homeDir, GIT_CONFIG_NOSYSTEM: '1' }; + for (const name of Object.keys(env)) { + if (/^GIT_CONFIG_(COUNT|KEY_\d+|VALUE_\d+|GLOBAL|SYSTEM|PARAMETERS)$/.test(name)) delete env[name]; + } + delete env.XDG_CONFIG_HOME; delete env.CLAUDE_PROJECT_DIR; delete env.CLV2_NO_PROJECT; delete env.CLV2_HOMUNCULUS_DIR; @@ -144,9 +149,11 @@ function gitSpy(dir) { ['#!/usr/bin/env bash', `printf '%s\\n' "$*" >> "$GIT_SPY_LOG"`, `exec "${real}" "$@"`, ''].join('\n'), { mode: 0o755 } ); + const lines = () => (fs.existsSync(log) ? fs.readFileSync(log, 'utf8').split('\n').filter(Boolean) : []); 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) + calls: () => lines().length, + lines }; } @@ -181,7 +188,7 @@ test('a repeat call is served from the cache with identical results', () => { } }); -test('a cache hit launches no git process', () => { +test('a cache hit launches git once, only to ask for the origin', () => { const tmp = createTempDir(); try { const home = path.join(tmp, 'home'); @@ -191,11 +198,32 @@ test('a cache hit launches no git process', () => { detect(repo, home, spy.env); const afterMiss = spy.calls(); - assert.ok(afterMiss > 0, 'full detection should call git'); + assert.ok(afterMiss > 1, 'full detection should call git more than once'); const second = detect(repo, home, spy.env); assert.strictEqual(second.hit, '1'); - assert.strictEqual(spy.calls(), afterMiss, 'a cache hit must not call git'); + const onHit = spy.lines().slice(afterMiss); + assert.strictEqual(onHit.length, 1, `a cache hit must call git exactly once, got: ${onHit.join(' | ')}`); + assert.match(onHit[0], /remote get-url origin$/, 'the one call must be the origin lookup'); + } finally { + cleanupDir(tmp); + } +}); + +test('a cached "global" result launches no git process', () => { + const tmp = createTempDir(); + try { + const home = path.join(tmp, 'home'); + fs.mkdirSync(home); + const dir = path.join(tmp, 'anywhere'); + fs.mkdirSync(dir); + const spy = gitSpy(tmp); + + detect(dir, home, { ...spy.env, CLV2_NO_PROJECT: '1' }); + const afterMiss = spy.calls(); + const second = detect(dir, home, { ...spy.env, CLV2_NO_PROJECT: '1' }); + assert.strictEqual(second.hit, '1'); + assert.strictEqual(spy.calls(), afterMiss, 'a cached global result has no origin to confirm'); } finally { cleanupDir(tmp); } @@ -210,14 +238,124 @@ test('a changed remote invalidates the entry and yields the new project id', () 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); + // The decision must not depend on file times: make the config look older + // than the cache entry. + const past = new Date(Date.now() - 3600 * 1000); + fs.utimesSync(path.join(repo, '.git', 'config'), past, past); const second = detect(repo, home); - assert.strictEqual(second.hit, '0', 'a newer .git/config must force re-detection'); + assert.strictEqual(second.hit, '0', 'a different origin must force re-detection'); assert.notStrictEqual(second.id, first.id, 'the project id must follow the new remote'); + + const third = detect(repo, home); + assert.strictEqual(third.hit, '1', 'the re-detected result is cached again'); + assert.strictEqual(third.id, second.id); + } finally { + cleanupDir(tmp); + } +}); + +test('an origin changed in an included config file invalidates the entry', () => { + const tmp = createTempDir(); + try { + const home = path.join(tmp, 'home'); + fs.mkdirSync(home); + const repo = makeRepo(tmp, 'gamma-inc'); + const included = path.join(tmp, 'remote.inc'); + const writeIncluded = (url) => + fs.writeFileSync(included, `[remote "origin"]\n\turl = ${url}\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n`); + writeIncluded('https://github.com/example/included-a.git'); + git(repo, 'config', 'include.path', included); + + const first = detect(repo, home); + assert.strictEqual(detect(repo, home).hit, '1', 'unchanged included origin is a hit'); + + // .git/config itself is untouched; only the included file changes. + writeIncluded('https://github.com/example/included-b.git'); + const second = detect(repo, home); + assert.strictEqual(second.hit, '0', 'an origin changed in an included file must force re-detection'); + assert.notStrictEqual(second.id, first.id, 'the project id must follow the included origin'); + } finally { + cleanupDir(tmp); + } +}); + +test('an origin rewritten by the global config invalidates the entry', () => { + const tmp = createTempDir(); + try { + const home = path.join(tmp, 'home'); + fs.mkdirSync(home); + const repo = makeRepo(tmp, 'gamma-global', 'https://github.com/example/global-a.git'); + + const first = detect(repo, home); + assert.strictEqual(detect(repo, home).hit, '1'); + + // url..insteadOf in ~/.gitconfig changes what git reports as origin. + fs.writeFileSync( + path.join(home, '.gitconfig'), + '[url "https://mirror.example/"]\n\tinsteadOf = https://github.com/\n' + ); + const second = detect(repo, home); + assert.strictEqual(second.hit, '0', 'an origin rewritten outside the repository must force re-detection'); + assert.notStrictEqual(second.id, first.id); + } finally { + cleanupDir(tmp); + } +}); + +test('an entry holding an origin git does not report is rejected', () => { + const tmp = createTempDir(); + try { + const home = path.join(tmp, 'home'); + fs.mkdirSync(home); + const repo = makeRepo(tmp, 'gamma-race', 'https://github.com/example/race-b.git'); + + const first = detect(repo, home); + // What a detection that raced a config change would leave behind: an + // entry derived from origin A while the repository now says B. + const [entry] = cacheEntries(home); + rewriteCacheLine(entry, 6, 'https://github.com/example/race-a.git'); + + const second = detect(repo, home); + assert.strictEqual(second.hit, '0', 'an entry for another origin must not be trusted'); + assert.strictEqual(second.id, first.id); + } finally { + cleanupDir(tmp); + } +}); + +test('a repository without an origin is cached until one is added', () => { + const tmp = createTempDir(); + try { + const home = path.join(tmp, 'home'); + fs.mkdirSync(home); + const repo = makeRepo(tmp, 'gamma-local'); + + const first = detect(repo, home); + assert.strictEqual(detect(repo, home).hit, '1', 'no origin then, no origin now: a hit'); + + git(repo, 'remote', 'add', 'origin', 'https://github.com/example/gamma-local.git'); + const second = detect(repo, home); + assert.strictEqual(second.hit, '0', 'a newly added origin must force re-detection'); + assert.notStrictEqual(second.id, first.id); + } finally { + cleanupDir(tmp); + } +}); + +test('credentials embedded in the origin are not written to the cache', () => { + const tmp = createTempDir(); + try { + const home = path.join(tmp, 'home'); + fs.mkdirSync(home); + const repo = makeRepo(tmp, 'gamma-cred', 'https://someuser:not-a-real-token@github.com/example/cred.git'); + + detect(repo, home); + const [entry] = cacheEntries(home); + const text = fs.readFileSync(entry, 'utf8'); + assert.ok(!text.includes('not-a-real-token'), 'the cache entry must not hold the credential'); + assert.ok(text.includes('https://github.com/example/cred.git'), 'the entry holds the origin without credentials'); + assert.strictEqual(detect(repo, home).hit, '1', 'the stripped origin still matches on the next call'); } finally { cleanupDir(tmp); } @@ -352,7 +490,7 @@ test('an explicit CLV2_NO_PROJECT=1 result is cached under its own key', () => { } }); -test('a linked worktree is never cached (its config lives outside the worktree)', () => { +test('a linked worktree is never cached (it has no .git directory of its own)', () => { const tmp = createTempDir(); try { const home = path.join(tmp, 'home'); @@ -365,7 +503,7 @@ test('a linked worktree is never cached (its config lives outside the 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.hit, '0', 'a worktree has no .git directory of its own, so it must not be cached'); assert.strictEqual(second.id, first.id); // Adding a remote in the main repository changes the id; the worktree @@ -458,6 +596,79 @@ test('observe.sh records the same project on a cache hit as on a miss', () => { } }); +function runObserve(repo, home, payload) { + 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}`); +} + +test('observe.sh housekeeping runs once a day whoever filled the detection cache', () => { + const tmp = createTempDir(); + try { + const home = path.join(tmp, 'home'); + fs.mkdirSync(home); + const repo = makeRepo(tmp, 'mu', 'https://github.com/example/mu.git'); + const payload = JSON.stringify({ session_id: 'hk', cwd: repo, tool_name: 'Read', tool_input: {} }); + + runObserve(repo, home, payload); + const projectsDir = path.join(homunculusDir(home), 'projects'); + const projectDir = path.join(projectsDir, fs.readdirSync(projectsDir)[0]); + const observations = path.join(projectDir, 'observations.jsonl'); + const marker = path.join(projectDir, '.housekeeping-day'); + const archiveDir = path.join(projectDir, 'observations.archive'); + assert.match(fs.readFileSync(marker, 'utf8').trim(), /^\d{8}$/, 'the first call records the housekeeping day'); + + // Over the size cap, housekeeping already done today: nothing is archived. + fs.appendFileSync(observations, `${'x'.repeat(1024 * 1024 - 1)}\n`.repeat(11)); + runObserve(repo, home, payload); + const archived = () => (fs.existsSync(archiveDir) ? fs.readdirSync(archiveDir).length : 0); + assert.strictEqual(archived(), 0, 'housekeeping must not repeat on the same day'); + + // The cache is filled (as another caller of detect-project.sh would leave + // it) but this project has had no housekeeping today: it must run. + fs.rmSync(marker); + assert.strictEqual(cacheEntries(home).length, 1); + runObserve(repo, home, payload); + assert.strictEqual(archived(), 1, 'the oversized file must be archived on a cache hit'); + assert.ok(fs.existsSync(marker), 'the housekeeping day is recorded again'); + } finally { + cleanupDir(tmp); + } +}); + +test('observe.sh keeps a payload cwd whose name contains a newline intact', () => { + const tmp = createTempDir(); + try { + const home = path.join(tmp, 'home'); + fs.mkdirSync(home); + // "line\nbreak" is one directory; "line break" is a different, real + // repository that must not be selected in its place. + const odd = path.join(tmp, 'line\nbreak'); + fs.mkdirSync(odd); + makeRepo(tmp, 'line break', 'https://github.com/example/decoy.git'); + const payload = JSON.stringify({ session_id: 'nl', cwd: odd, tool_name: 'Read', tool_input: {} }); + + runObserve(tmp, home, payload); + + const hom = homunculusDir(home); + assert.ok(!fs.existsSync(path.join(hom, 'projects')), 'the look-alike repository must not be selected'); + const [record] = fs + .readFileSync(path.join(hom, 'observations.jsonl'), 'utf8') + .split('\n') + .filter(Boolean) + .map((line) => JSON.parse(line)); + assert.strictEqual(record.project_id, 'global', 'a non-repository cwd records under global'); + assert.strictEqual(record.cwd, fs.realpathSync(odd), 'the recorded cwd is the real directory, newline included'); + } finally { + cleanupDir(tmp); + } +}); + console.log(`\nPassed: ${passed}`); console.log(`Failed: ${failed}`); process.exit(failed > 0 ? 1 : 0); From b10fc604bdd4d0a6be57ce7fafcda2a26225da6a Mon Sep 17 00:00:00 2001 From: Jeffrey Montoya Date: Wed, 18 Nov 2026 14:11:00 -0500 Subject: [PATCH 4/5] refactor(clv2): drop the two unused python resolver wrappers `_python_install_manager_launcher` and `resolve_python_cmd` only wrapped the new `_clv2_pick_*` helpers for printing and nothing calls them any more (shellcheck SC2329). Refresh the registry digest for the script change. --- manifests/context-packs/skill-triggers@1.json | 2 +- skills/continuous-learning-v2/hooks/observe.sh | 10 ---------- 2 files changed, 1 insertion(+), 11 deletions(-) diff --git a/manifests/context-packs/skill-triggers@1.json b/manifests/context-packs/skill-triggers@1.json index dd99b2c48..32dff3c6c 100644 --- a/manifests/context-packs/skill-triggers@1.json +++ b/manifests/context-packs/skill-triggers@1.json @@ -10,7 +10,7 @@ "id": "hand-seeded", "source": "manual-curation-pending-regeneration" }, - "registryDigest": "24385666bb04a9945f13fa7dd8f9f30edb1c1e809da1419d5f8841cd8183715a", + "registryDigest": "5205bb7d63ca24328d2808837dd9cc07e4c660cd023eddde8fd7d4b8ff3a6d6d", "schemaVersion": 1, "triggers": { "skill:agent-runtime-gateway-smoke-test": [ diff --git a/skills/continuous-learning-v2/hooks/observe.sh b/skills/continuous-learning-v2/hooks/observe.sh index c55b1db37..9d3d9cb18 100755 --- a/skills/continuous-learning-v2/hooks/observe.sh +++ b/skills/continuous-learning-v2/hooks/observe.sh @@ -213,11 +213,6 @@ _clv2_pick_install_manager_launcher() { _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() { @@ -249,11 +244,6 @@ _clv2_pick_python_cmd() { 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" From ea7e77664a5ffb709a91c2cac38a3960ae4c62cd Mon Sep 17 00:00:00 2001 From: Jeffrey Montoya Date: Wed, 18 Nov 2026 15:38:30 -0500 Subject: [PATCH 5/5] fix(clv2): keep the config timestamp check, normalize observer.enabled Address the second round of review findings: - Cache: trust an entry only while it is newer than the repository .git/config as well as while git reports the stored origin, so a core.worktree change that moves the root is not served stale. - observe.sh: emit observer.enabled as a literal true or false so a value containing a newline cannot shift the fields that follow. - Tests: remove GIT_DIR, GIT_WORK_TREE, GIT_INDEX_FILE, GIT_COMMON_DIR and GIT_PREFIX from the detection test environment; add a config-change test and an observer.enabled newline test. Refresh the registry digest. --- manifests/context-packs/skill-triggers@1.json | 2 +- .../continuous-learning-v2/hooks/observe.sh | 4 +- .../scripts/detect-project.sh | 13 +++- tests/hooks/detect-project-cache.test.js | 77 ++++++++++++++++++- 4 files changed, 87 insertions(+), 9 deletions(-) diff --git a/manifests/context-packs/skill-triggers@1.json b/manifests/context-packs/skill-triggers@1.json index 32dff3c6c..3b26ae3b2 100644 --- a/manifests/context-packs/skill-triggers@1.json +++ b/manifests/context-packs/skill-triggers@1.json @@ -10,7 +10,7 @@ "id": "hand-seeded", "source": "manual-curation-pending-regeneration" }, - "registryDigest": "5205bb7d63ca24328d2808837dd9cc07e4c660cd023eddde8fd7d4b8ff3a6d6d", + "registryDigest": "461dbb0857be6b07bc6df8c17f18705485ba5cd80c64376f8decea9909e83220", "schemaVersion": 1, "triggers": { "skill:agent-runtime-gateway-smoke-test": [ diff --git a/skills/continuous-learning-v2/hooks/observe.sh b/skills/continuous-learning-v2/hooks/observe.sh index 9d3d9cb18..4bc268b4c 100755 --- a/skills/continuous-learning-v2/hooks/observe.sh +++ b/skills/continuous-learning-v2/hooks/observe.sh @@ -325,7 +325,9 @@ if config_path: try: with open(config_path) as f: cfg = json.load(f) - enabled = str(cfg.get("observer", {}).get("enabled", False)).lower() + # Only the literal values may leave this block: a user-written string + # with a newline in it would shift the fields that follow. + enabled = "true" if str(cfg.get("observer", {}).get("enabled", False)).lower() == "true" else "false" except Exception: enabled = "false" diff --git a/skills/continuous-learning-v2/scripts/detect-project.sh b/skills/continuous-learning-v2/scripts/detect-project.sh index f8ffb33b1..310523323 100755 --- a/skills/continuous-learning-v2/scripts/detect-project.sh +++ b/skills/continuous-learning-v2/scripts/detect-project.sh @@ -351,14 +351,16 @@ atomic_write_json(registry_path, registry) # 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 (a setting that +# decides the root or the id, such as core.worktree, was changed) # - git no longer reports the origin the entry was derived from (remote # added, changed or removed, 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 # -# The origin is asked from git on every hit (one `git remote get-url`) rather -# than inferred from file timestamps: the effective origin can come from the -# repository config, a file it includes, the global or system config, or +# The origin is asked from git on every hit (one `git remote get-url`), in +# addition to the timestamp check, because the effective origin can come from +# the repository config, a file it includes, the global or system config, or # GIT_CONFIG_* variables, and only git resolves all of those. The entry stores # the origin that detection itself read, so an entry written while the config # was being changed fails this comparison too. @@ -446,6 +448,11 @@ _clv2_project_cache_load() { # and still a repository with its own .git/config file (see the store side). [ -n "$root" ] && [ -d "$root" ] || return 1 [ -f "${root}/.git/config" ] || return 1 + # Settings in the repository's own config (core.worktree moves the root, + # a remote changes the id) are 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. + [ "$file" -nt "${root}/.git/config" ] || return 1 # The id is derived from the origin, so the entry is trusted only while # git reports the same origin that detection read when it wrote the entry. # A repository without an origin stores an empty line and must still have diff --git a/tests/hooks/detect-project-cache.test.js b/tests/hooks/detect-project-cache.test.js index b96c621d9..a11fb8a1b 100644 --- a/tests/hooks/detect-project-cache.test.js +++ b/tests/hooks/detect-project-cache.test.js @@ -11,6 +11,7 @@ * (to ask for the origin) * - a changed origin forces re-detection wherever it is configured: the * repository config, a file it includes, or the global config + * - a .git/config newer than the entry forces re-detection (core.worktree) * - an entry that holds an origin git does not report is rejected * - credentials embedded in the origin never reach the cache file * - an entry from another day forces re-detection @@ -77,8 +78,19 @@ function bashSupportsCache() { return major > 4 || (major === 4 && minor >= 2); } +// Variables that point git at a particular repository. The test runner already +// removes them; they are removed here too so the file also passes when run +// directly from a shell (or a git hook) that has them exported. +const GIT_LOCATION_VARS = ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR', 'GIT_PREFIX']; + +function scrubbedEnv(base) { + const env = { ...base }; + for (const name of GIT_LOCATION_VARS) delete env[name]; + return env; +} + function git(cwd, ...args) { - execFileSync('git', args, { cwd, stdio: 'ignore' }); + execFileSync('git', args, { cwd, stdio: 'ignore', env: scrubbedEnv(process.env) }); } function makeRepo(parent, name, remote) { @@ -86,13 +98,18 @@ function makeRepo(parent, name, remote) { 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 = {}) { // HOME is a fresh directory, so no global git config leaks in. The system // config and any GIT_CONFIG_* overrides from the caller are shut out too. - const env = { ...process.env, HOME: homeDir, USERPROFILE: homeDir, GIT_CONFIG_NOSYSTEM: '1' }; + const env = scrubbedEnv({ ...process.env, HOME: homeDir, USERPROFILE: homeDir, GIT_CONFIG_NOSYSTEM: '1' }); for (const name of Object.keys(env)) { if (/^GIT_CONFIG_(COUNT|KEY_\d+|VALUE_\d+|GLOBAL|SYSTEM|PARAMETERS)$/.test(name)) delete env[name]; } @@ -303,6 +320,28 @@ test('an origin rewritten by the global config invalidates the entry', () => { } }); +test('a changed .git/config forces re-detection even when the origin is unchanged', () => { + const tmp = createTempDir(); + try { + const home = path.join(tmp, 'home'); + fs.mkdirSync(home); + // No origin: nothing the origin check could notice. A setting such as + // core.worktree, which decides the project root, lives in this same file. + const repo = makeRepo(tmp, 'gamma-cfg'); + + detect(repo, home); + assert.strictEqual(detect(repo, home).hit, '1', 'an untouched config is a hit'); + + git(repo, 'config', 'core.worktree', repo); + const future = new Date(Date.now() + 5000); + fs.utimesSync(path.join(repo, '.git', 'config'), future, future); + + assert.strictEqual(detect(repo, home).hit, '0', 'a config newer than the entry must force re-detection'); + } finally { + cleanupDir(tmp); + } +}); + test('an entry holding an origin git does not report is rejected', () => { const tmp = createTempDir(); try { @@ -596,17 +635,47 @@ test('observe.sh records the same project on a cache hit as on a miss', () => { } }); -function runObserve(repo, home, payload) { +function runObserve(repo, home, payload, extraEnv = {}) { 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' }) + env: baseEnv(home, { CLAUDE_CODE_ENTRYPOINT: 'cli', ECC_HOOK_PROFILE: 'standard', ECC_SKIP_OBSERVE: '0', ...extraEnv }) }); assert.strictEqual(r.status, 0, `observe.sh should exit 0, stderr: ${r.stderr}`); } +test('observe.sh survives an observer.enabled value that contains a newline', () => { + const tmp = createTempDir(); + try { + const home = path.join(tmp, 'home'); + fs.mkdirSync(home); + const repo = makeRepo(tmp, 'nu', 'https://github.com/example/nu.git'); + // A hand-edited config whose flag spans two lines would shift the fields + // the first Python start prints, move text into the cwd, and send the + // observation to the no-project path instead of the repository. + const config = path.join(tmp, 'config.json'); + fs.writeFileSync(config, JSON.stringify({ observer: { enabled: 'false\nstray line' } })); + const payload = JSON.stringify({ session_id: 'en', cwd: repo, tool_name: 'Read', tool_input: {} }); + + runObserve(repo, home, payload, { CLV2_CONFIG: config }); + + const projectsDir = path.join(homunculusDir(home), 'projects'); + assert.ok(fs.existsSync(projectsDir), 'the observation must be stored under the repository project'); + const [projectId] = fs.readdirSync(projectsDir); + const [record] = fs + .readFileSync(path.join(projectsDir, projectId, 'observations.jsonl'), 'utf8') + .split('\n') + .filter(Boolean) + .map((line) => JSON.parse(line)); + assert.strictEqual(record.project_id, projectId); + assert.strictEqual(record.cwd, fs.realpathSync(repo), 'the recorded cwd is the payload cwd, nothing else'); + } finally { + cleanupDir(tmp); + } +}); + test('observe.sh housekeeping runs once a day whoever filled the detection cache', () => { const tmp = createTempDir(); try {