Skip to content

Commit a6f380f

Browse files
ispaydeuaffaan-m
andauthored
feat: active hours + idle detection gates for session-guardian (anomalyco#413)
* feat: add project cooldown log to prevent rapid observer re-spawn Adds session-guardian.sh, called by observer-loop.sh before each Haiku spawn. It reads ~/.claude/observer-last-run.log and blocks the cycle if the same project was observed within OBSERVER_INTERVAL_SECONDS (default 300s). Prevents self-referential loops where a spawned session triggers observe.sh, which signals the observer before the cooldown has elapsed. Uses a mkdir-based lock for safe concurrent access across multiple simultaneously-observed projects. Log entries use tab-delimited format to handle paths containing spaces. Fails open on lock contention. Config: OBSERVER_INTERVAL_SECONDS default: 300 OBSERVER_LAST_RUN_LOG default: ~/.claude/observer-last-run.log No external dependencies. Works on macOS, Linux, Windows (Git Bash/MSYS2). * feat: extend session-guardian with time window and idle detection gates Adds Gate 1 (active hours check) and Gate 3 (system idle detection) to session-guardian.sh, building on the per-project cooldown log from PR 1. Gate 1 — Time Window: - OBSERVER_ACTIVE_HOURS_START/END (default 800–2300 local time) - Uses date +%k%M with 10# prefix to avoid octal crash at midnight - Toolless on all platforms; set both vars to 0 to disable Gate 3 — Idle Detection: - macOS: ioreg + awk (built-in, no deps) - Linux: xprintidle if available, else fail open - Windows (Git Bash/MSYS2): PowerShell GetLastInputInfo via Add-Type - Unknown/headless: always returns 0 (fail open) - OBSERVER_MAX_IDLE_SECONDS=0 disables gate Fixes in this commit: - 10# base-10 prefix prevents octal arithmetic crash on midnight minutes containing digits 8 or 9 (e.g. 00:08 = "008" is invalid octal) - PowerShell output piped through tr -d '\r' to strip Windows CRLF; also uses [long] cast to avoid TickCount 32-bit overflow after 24 days - mktemp now uses log file directory instead of TMPDIR to ensure same-filesystem mv on Linux (atomic rename instead of copy+unlink) - mkdir -p failure exits 0 (fail open) rather than crashing under set -e - Numeric validation on last_spawn prevents arithmetic error on corrupt log Gate execution order: 1 (time, ~0ms) → 2 (cooldown, ~1ms) → 3 (idle, ~50ms) * fix: harden session guardian gates --------- Co-authored-by: Affaan Mustafa <[email protected]>
1 parent c52a28a commit a6f380f

2 files changed

Lines changed: 156 additions & 0 deletions

File tree

‎skills/continuous-learning-v2/agents/observer-loop.sh‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,12 @@ analyze_observations() {
3838
return
3939
fi
4040

41+
# session-guardian: gate observer cycle (active hours, cooldown, idle detection)
42+
if ! bash "$(dirname "$0")/session-guardian.sh"; then
43+
echo "[$(date)] Observer cycle skipped by session-guardian" >> "$LOG_FILE"
44+
return
45+
fi
46+
4147
prompt_file="$(mktemp "${TMPDIR:-/tmp}/ecc-observer-prompt.XXXXXX")"
4248
cat > "$prompt_file" <<PROMPT
4349
Read ${OBSERVATIONS_FILE} and identify patterns for the project ${PROJECT_NAME} (user corrections, error resolutions, repeated workflows, tool preferences).
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
#!/usr/bin/env bash
2+
# session-guardian.sh — Observer session guard
3+
# Exit 0 = proceed. Exit 1 = skip this observer cycle.
4+
# Called by observer-loop.sh before spawning any Claude session.
5+
#
6+
# Config (env vars, all optional):
7+
# OBSERVER_INTERVAL_SECONDS default: 300 (per-project cooldown)
8+
# OBSERVER_LAST_RUN_LOG default: ~/.claude/observer-last-run.log
9+
# OBSERVER_ACTIVE_HOURS_START default: 800 (8:00 AM local, set to 0 to disable)
10+
# OBSERVER_ACTIVE_HOURS_END default: 2300 (11:00 PM local, set to 0 to disable)
11+
# OBSERVER_MAX_IDLE_SECONDS default: 1800 (30 min; set to 0 to disable)
12+
#
13+
# Gate execution order (cheapest first):
14+
# Gate 1: Time window check (~0ms, string comparison)
15+
# Gate 2: Project cooldown log (~1ms, file read + mkdir lock)
16+
# Gate 3: Idle detection (~5-50ms, OS syscall; fail open)
17+
18+
set -euo pipefail
19+
20+
INTERVAL="${OBSERVER_INTERVAL_SECONDS:-300}"
21+
LOG_PATH="${OBSERVER_LAST_RUN_LOG:-$HOME/.claude/observer-last-run.log}"
22+
ACTIVE_START="${OBSERVER_ACTIVE_HOURS_START:-800}"
23+
ACTIVE_END="${OBSERVER_ACTIVE_HOURS_END:-2300}"
24+
MAX_IDLE="${OBSERVER_MAX_IDLE_SECONDS:-1800}"
25+
26+
# ── Gate 1: Time Window ───────────────────────────────────────────────────────
27+
# Skip observer cycles outside configured active hours (local system time).
28+
# Uses HHMM integer comparison. Works on BSD date (macOS) and GNU date (Linux).
29+
# Supports overnight windows such as 2200-0600.
30+
# Set both ACTIVE_START and ACTIVE_END to 0 to disable this gate.
31+
if [ "$ACTIVE_START" -ne 0 ] || [ "$ACTIVE_END" -ne 0 ]; then
32+
current_hhmm=$(date +%k%M | tr -d ' ')
33+
current_hhmm_num=$(( 10#${current_hhmm:-0} ))
34+
active_start_num=$(( 10#${ACTIVE_START:-800} ))
35+
active_end_num=$(( 10#${ACTIVE_END:-2300} ))
36+
37+
within_active_hours=0
38+
if [ "$active_start_num" -lt "$active_end_num" ]; then
39+
if [ "$current_hhmm_num" -ge "$active_start_num" ] && [ "$current_hhmm_num" -lt "$active_end_num" ]; then
40+
within_active_hours=1
41+
fi
42+
else
43+
if [ "$current_hhmm_num" -ge "$active_start_num" ] || [ "$current_hhmm_num" -lt "$active_end_num" ]; then
44+
within_active_hours=1
45+
fi
46+
fi
47+
48+
if [ "$within_active_hours" -ne 1 ]; then
49+
echo "session-guardian: outside active hours (${current_hhmm}, window ${ACTIVE_START}-${ACTIVE_END})" >&2
50+
exit 1
51+
fi
52+
fi
53+
54+
# ── Gate 2: Project Cooldown Log ─────────────────────────────────────────────
55+
# Prevent the same project being observed faster than OBSERVER_INTERVAL_SECONDS.
56+
# Key: PROJECT_DIR when provided by the observer, otherwise git root path.
57+
# Uses mkdir-based lock for safe concurrent access. Skips the cycle on lock contention.
58+
# stderr uses basename only — never prints the full absolute path.
59+
60+
project_root="${PROJECT_DIR:-}"
61+
if [ -z "$project_root" ] || [ ! -d "$project_root" ]; then
62+
project_root="$(git rev-parse --show-toplevel 2>/dev/null || echo "$PWD")"
63+
fi
64+
project_name="$(basename "$project_root")"
65+
now="$(date +%s)"
66+
67+
mkdir -p "$(dirname "$LOG_PATH")" || {
68+
echo "session-guardian: cannot create log dir, proceeding" >&2
69+
exit 0
70+
}
71+
72+
_lock_dir="${LOG_PATH}.lock"
73+
if ! mkdir "$_lock_dir" 2>/dev/null; then
74+
# Another observer holds the lock — skip this cycle to avoid double-spawns
75+
echo "session-guardian: log locked by concurrent process, skipping cycle" >&2
76+
exit 1
77+
else
78+
trap 'rm -rf "$_lock_dir"' EXIT INT TERM
79+
80+
last_spawn=0
81+
last_spawn=$(awk -F '\t' -v key="$project_root" '$1 == key { value = $2 } END { if (value != "") print value }' "$LOG_PATH" 2>/dev/null) || true
82+
last_spawn="${last_spawn:-0}"
83+
[[ "$last_spawn" =~ ^[0-9]+$ ]] || last_spawn=0
84+
85+
elapsed=$(( now - last_spawn ))
86+
if [ "$elapsed" -lt "$INTERVAL" ]; then
87+
rm -rf "$_lock_dir"
88+
trap - EXIT INT TERM
89+
echo "session-guardian: cooldown active for '${project_name}' (last spawn ${elapsed}s ago, interval ${INTERVAL}s)" >&2
90+
exit 1
91+
fi
92+
93+
# Update log: remove old entry for this project, append new timestamp (tab-delimited)
94+
tmp_log="$(mktemp "$(dirname "$LOG_PATH")/observer-last-run.XXXXXX")"
95+
awk -F '\t' -v key="$project_root" '$1 != key' "$LOG_PATH" > "$tmp_log" 2>/dev/null || true
96+
printf '%s\t%s\n' "$project_root" "$now" >> "$tmp_log"
97+
mv "$tmp_log" "$LOG_PATH"
98+
99+
rm -rf "$_lock_dir"
100+
trap - EXIT INT TERM
101+
fi
102+
103+
# ── Gate 3: Idle Detection ────────────────────────────────────────────────────
104+
# Skip cycles when no user input received for too long. Fail open if idle time
105+
# cannot be determined (Linux without xprintidle, headless, unknown OS).
106+
# Set OBSERVER_MAX_IDLE_SECONDS=0 to disable this gate.
107+
108+
get_idle_seconds() {
109+
local _raw
110+
case "$(uname -s)" in
111+
Darwin)
112+
_raw=$( { /usr/sbin/ioreg -c IOHIDSystem \
113+
| /usr/bin/awk '/HIDIdleTime/ {print int($NF/1000000000); exit}'; } \
114+
2>/dev/null ) || true
115+
printf '%s\n' "${_raw:-0}" | head -n1
116+
;;
117+
Linux)
118+
if command -v xprintidle >/dev/null 2>&1; then
119+
_raw=$(xprintidle 2>/dev/null) || true
120+
echo $(( ${_raw:-0} / 1000 ))
121+
else
122+
echo 0 # fail open: xprintidle not installed
123+
fi
124+
;;
125+
*MINGW*|*MSYS*|*CYGWIN*)
126+
_raw=$(powershell.exe -NoProfile -NonInteractive -Command \
127+
"try { \
128+
Add-Type -MemberDefinition '[DllImport(\"user32.dll\")] public static extern bool GetLastInputInfo(ref LASTINPUTINFO p); [StructLayout(LayoutKind.Sequential)] public struct LASTINPUTINFO { public uint cbSize; public int dwTime; }' -Name WinAPI -Namespace PInvoke; \
129+
\$l = New-Object PInvoke.WinAPI+LASTINPUTINFO; \$l.cbSize = 8; \
130+
[PInvoke.WinAPI]::GetLastInputInfo([ref]\$l) | Out-Null; \
131+
[int][Math]::Max(0, [long]([Environment]::TickCount - [long]\$l.dwTime) / 1000) \
132+
} catch { 0 }" \
133+
2>/dev/null | tr -d '\r') || true
134+
printf '%s\n' "${_raw:-0}" | head -n1
135+
;;
136+
*)
137+
echo 0 # fail open: unknown platform
138+
;;
139+
esac
140+
}
141+
142+
if [ "$MAX_IDLE" -gt 0 ]; then
143+
idle_seconds=$(get_idle_seconds)
144+
if [ "$idle_seconds" -gt "$MAX_IDLE" ]; then
145+
echo "session-guardian: user idle ${idle_seconds}s (threshold ${MAX_IDLE}s), skipping" >&2
146+
exit 1
147+
fi
148+
fi
149+
150+
exit 0

0 commit comments

Comments
 (0)