Merge PR #4016 observer launch optimization while preserving per-event log rotation

This commit is contained in:
haelyra committed 2026-11-19 15:20:18 -05:00
commit 390b8bc067
5 files changed
+1415 -297

No files matched your search

@@ -10,7 +10,7 @@
"id": "hand-seeded",
"source": "manual-curation-pending-regeneration"
},
"registryDigest": "9343c4f74ead89f41003be49c07644931e4c1c1adcdfbd84a2de2e8fa8c4819b",
"registryDigest": "a29cdc746ad4eca1d2f379e37b1aa6e0ee645b4c07ac82dab8f108fc4b544786",
"schemaVersion": 1,
"triggers": {
"skill:agent-runtime-gateway-smoke-test": [
+453 -286
View File
@@ -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,251 @@ 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 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/*) ;;
*)
[ -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
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"
}
# 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
}
_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
# 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 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 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 = printable(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)
# 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"
# 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"
# 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.
_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 +375,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 +415,72 @@ 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
# Old-file purging runs once a day per project. Size-based rotation still runs
# on every observation so the existing active-log size limit stays effective.
# Shells without printf '%(...)T' (bash < 4.2) retain per-call housekeeping.
_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
find "${PROJECT_DIR}" -name "observations-*.jsonl" -mtime +30 -delete 2>/dev/null || true
touch "$PURGE_MARKER" 2>/dev/null || true
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
# 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
# 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
# ─────────────────────────────────────────────
# 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 +495,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 +508,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"(?:(?<![A-Za-z0-9_])|(?<=\\[bfnrt])|(?<=\\u[0-9a-fA-F]{4}))(?:gh[pousr]_[A-Za-z0-9]{20,255}|github_pat_[A-Za-z0-9_]{20,255}|(?:AKIA|ASIA)[A-Z0-9]{16})\b"
r"|(?:(?<![A-Za-z0-9_-])|(?<=\\[bfnrt])|(?<=\\u[0-9a-fA-F]{4}))(?:sk-(?:ant|proj|svcacct|admin|or)-[A-Za-z0-9_-]{20,}|sk-[A-Za-z0-9]{20,}[A-Za-z0-9_-]*|eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*)"
r"""|(?<=://)(?:(?<=https://)|(?<=http://)|(?<!https://)(?<!http://)())([^\s:/@"\\]{1,256}:)(?(1)|(?!\d{1,5}\Z))[^\s@/"\\]{1,256}(?=@|\Z)"""
)
# A capture cut at its length limit can end inside an sk- key or JWT that the
# full patterns no longer match. Only applied when the text was actually cut,
# so a short output that happens to end in "sk-learn" stays readable.
_CUT_TAIL_RE = re.compile(
r"(?:(?<![A-Za-z0-9_-])|(?<=\\[bfnrt])|(?<=\\u[0-9a-fA-F]{4}))(?:sk-[A-Za-z0-9_-]*|eyJ[A-Za-z0-9_-]*(?:\.[A-Za-z0-9_-]*)?)\Z"
)
if [ "$PARSED_OK" != "True" ]; then
def scrub(val):
if val is None:
return None
val = str(val)
# Tool I/O is cut to 5000 chars before it reaches this process.
cut = len(val) >= 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 +656,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"(?:(?<![A-Za-z0-9_])|(?<=\\[bfnrt])|(?<=\\u[0-9a-fA-F]{4}))(?:gh[pousr]_[A-Za-z0-9]{20,255}|github_pat_[A-Za-z0-9_]{20,255}|(?:AKIA|ASIA)[A-Z0-9]{16})\b"
r"|(?:(?<![A-Za-z0-9_-])|(?<=\\[bfnrt])|(?<=\\u[0-9a-fA-F]{4}))(?:sk-(?:ant|proj|svcacct|admin|or)-[A-Za-z0-9_-]{20,}|sk-[A-Za-z0-9]{20,}[A-Za-z0-9_-]*|eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*)"
r"""|(?<=://)(?:(?<=https://)|(?<=http://)|(?<!https://)(?<!http://)())([^\s:/@"\\]{1,256}:)(?(1)|(?!\d{1,5}\Z))[^\s@/"\\]{1,256}(?=@|\Z)"""
)
# A capture cut at its length limit can end inside an sk- key or JWT that the
# full patterns no longer match. Only applied when the text was actually cut,
# so a short output that happens to end in "sk-learn" stays readable.
_CUT_TAIL_RE = re.compile(
r"(?:(?<![A-Za-z0-9_-])|(?<=\\[bfnrt])|(?<=\\u[0-9a-fA-F]{4}))(?:sk-[A-Za-z0-9_-]*|eyJ[A-Za-z0-9_-]*(?:\.[A-Za-z0-9_-]*)?)\Z"
)
def scrub(val):
if val is None:
return None
val = str(val)
# Tool I/O is cut to 5000 chars before it reaches this process.
cut = len(val) >= 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 +781,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
@@ -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
@@ -160,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
@@ -317,8 +339,192 @@ 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 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 (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`), 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.
#
# 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
# 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-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 "://<non-@ characters>@" 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
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 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 remote
} < "$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
# 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
# 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
# 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"
_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 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%/*}"
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" \
"$remote" > "$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"
+9 -7
View File
@@ -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\\nfalse\\n%s.' "$T_AGENT_ID" "$T_PROJECT" ;; 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];
+743
View File
@@ -0,0 +1,743 @@
/**
* 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 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
* - 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
* - 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);
}
// 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', env: scrubbedEnv(process.env) });
}
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 = {}) {
// 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 = 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];
}
delete env.XDG_CONFIG_HOME;
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 }
);
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: () => lines().length,
lines
};
}
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 git once, only to ask for the origin', () => {
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 > 1, 'full detection should call git more than once');
const second = detect(repo, home, spy.env);
assert.strictEqual(second.hit, '1');
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);
}
});
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');
// 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 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.<base>.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('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 {
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);
}
});
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 (it has no .git directory of its own)', () => {
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 .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
// 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);
}
});
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', ...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 purges daily but enforces the size cap on every call', () => {
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');
// Rotation must still run after daily housekeeping has completed.
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(), 1, 'the size cap must apply 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, 'a small active file must not rotate again');
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);