mirror of
https://github.com/affaan-m/ECC.git
synced 2026-11-23 08:15:29 +00:00
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.
This commit is contained in:
1 parent
36708d4e93
commit
155b4d254f
5 files changed
+359
-80
No files matched your search
@@ -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": [
|
||||
|
||||
@@ -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
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
@@ -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 "://<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
|
||||
@@ -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
|
||||
|
||||
@@ -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 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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.<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('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);
|
||||
Reference in new issue
Block a user