ia_dev/gitea-issues/agent-loop-chat-iterations.sh

79 lines
2.8 KiB
Bash
Executable File

#!/usr/bin/env bash
# Bounded loop for chat: run mail retrieval N times, 1 minute between each.
# Use from Cursor chat when asked to "lance la boucle récupération emails puis attend 1 min et relance".
# Runs in foreground (no background); chat can run it for a few iterations to avoid timeout.
#
# Usage:
# ./gitea-issues/agent-loop-chat-iterations.sh [N] [--repeat]
# N = number of iterations (default 3). Each iteration: mail-list-unread.sh then sleep 60.
# --repeat = after N iterations, relaunch (infinite loop of N-by-N runs).
# Output and mail list (expéditeur, sujet) are appended to projects/<id>/logs/gitea-issues/agent-loop-chat-iterations.log.
#
set -euo pipefail
if [ -n "${HOME:-}" ] && [ -r "$HOME/.bashrc" ]; then
set +u
# shellcheck source=/dev/null
source "$HOME/.bashrc" 2>/dev/null || true
set -u
fi
[ -n "${HOME:-}" ] && [ -d "$HOME/.local/bin" ] && export PATH="$HOME/.local/bin:$PATH"
GITEA_ISSUES_DIR="${GITEA_ISSUES_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"
ROOT="$(cd "${GITEA_ISSUES_DIR}/../.." && pwd)"
export GITEA_ISSUES_DIR
export REPO_ROOT="${ROOT}"
cd "$ROOT"
# shellcheck source=lib.sh
source "${GITEA_ISSUES_DIR}/lib.sh" 2>/dev/null || true
LOGS_GITEA="${PROJECT_LOGS_DIR:-$ROOT/logs}/gitea-issues"
REPEAT=""
if [ "${1:-}" = "--repeat" ]; then
REPEAT=1
N="${2:-3}"
else
N="${1:-3}"
fi
if ! [[ "$N" =~ ^[0-9]+$ ]] || [ "$N" -lt 1 ]; then
echo "Usage: $0 [N] [--repeat] — N positive integer (default 3). --repeat = relancer à la fin." >&2
exit 1
fi
LOG_DIR="${LOGS_GITEA}"
LOG_FILE="${LOG_DIR}/agent-loop-chat-iterations.log"
mkdir -p "$LOG_DIR"
log_and_echo() {
echo "$1" | tee -a "$LOG_FILE"
}
# Test send at launch: one test email to nicolas.cantu@pm.me
log_and_echo "[agent-loop-chat] $(date -Iseconds) — test d'envoi vers nicolas.cantu@pm.me"
"${GITEA_ISSUES_DIR}/mail-send-reply.sh" --to "nicolas.cantu@pm.me" --subject "Test envoi - agent-loop-chat $(date +%Y-%m-%dT%H:%M:%S)" --body "Mail de test envoyé au lancement de agent-loop-chat-iterations.sh." 2>&1 | tee -a "$LOG_FILE"
if [ "${PIPESTATUS[0]:-0}" -eq 0 ]; then
log_and_echo "[agent-loop-chat] $(date -Iseconds) — test d'envoi OK"
else
log_and_echo "[agent-loop-chat] $(date -Iseconds) — test d'envoi échoué"
exit 1
fi
run_iterations() {
for i in $(seq 1 "$N"); do
log_and_echo "[agent-loop-chat] $(date -Iseconds) — iteration $i/$N"
"${GITEA_ISSUES_DIR}/mail-list-unread.sh" 2>&1 | tee -a "$LOG_FILE" || true
if [ "$i" -lt "$N" ]; then
log_and_echo "[agent-loop-chat] $(date -Iseconds) — attente 60 s avant prochaine itération"
sleep 60
fi
done
log_and_echo "[agent-loop-chat] $(date -Iseconds)$N itérations terminées"
}
while true; do
run_iterations
if [ -z "${REPEAT:-}" ]; then
break
fi
log_and_echo "[agent-loop-chat] $(date -Iseconds) — relance"
done