Skip to content

Commit 80a3ce5

Browse files
Merge pull request #59 from SimulaMet/feat/agent-safe-dev-lifecycle
Agent-safe dev/spin lifecycle manager
2 parents 1a17e8c + de4a34f commit 80a3ce5

12 files changed

Lines changed: 123 additions & 943 deletions

File tree

‎AGENTS.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,21 @@
11
# AGENTS.md
22

3+
## First action in any coding-agent session
4+
5+
Run `uv run manage.py dev agent-info` from the checkout. It describes the
6+
supported local lifecycle commands, ownership, automatic port allocation,
7+
worktree isolation, cleanup and restart rules. Run `uv run manage.py dev status`
8+
before launching services. `uv run manage.py dev` is idempotent: if the current
9+
worktree already has a live owner, it reports the URL and exits.
10+
11+
**Never use `pkill`, `kill -9`, `lsof -ti ... | xargs kill`, or the old `devctl.sh`
12+
port-clearing logic.** Ordinary Django Python edits use runserver autoreload;
13+
template edits require only a browser refresh. Hatchet worker Python code does
14+
not automatically reload in the current architecture; coordinate a full
15+
`dev restart` only when no audit must be interrupted. Do not point another
16+
worktree's Python at the main checkout server and claim that branch's code
17+
was tested. `reset`/`uninstall` destroy data and require explicit permission.
18+
319
SimpleAudit Studio — an audit platform for LLM systems. It wraps the external
420
SimpleAudit engine (Target → Auditor → Judge runs over versioned scenario sets)
521
with a Django web UI, a durable worker, and an optional Open WebUI chat module.

‎README.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,15 @@ uv run manage.py setup_local
4343
uv run manage.py dev
4444
```
4545

46+
For an existing instance, `dev` reuses it rather than restarting the entire
47+
stack. Run `uv run manage.py dev status` to see the actual port. Run
48+
`uv run manage.py dev agent-info` for detailed agent-safe instructions.
49+
`dev down` stops without data loss, `dev reset` recreates clean local data,
50+
and `dev uninstall` removes owned state and app-scoped uv caches. The same
51+
lifecycle actions are available as `uvx --from simpleaudit-studio spin ACTION`.
52+
See [development lifecycle](docs/development-lifecycle.md) for isolation and
53+
safety details.
54+
4655
The app opens at <http://localhost:8000> with live reload. Use `--no-browser` to skip opening a browser.
4756

4857
## What it does

‎devctl.sh‎

100755100644
Lines changed: 13 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -12,107 +12,18 @@
1212
# Ports: Studio :8001, OWUI :8080, Caddy :8000
1313
set -euo pipefail
1414

15-
PORT_STUDIO=8001
16-
PORT_OWUI=8080
17-
PORT_CADDY=8000
18-
PIDFILE="$HOME/.simpleaudit-studio/dev.pid"
19-
LOGFILE="$HOME/.simpleaudit-studio/dev.log"
20-
DB="dev.sqlite3"
21-
22-
REPO="$(cd "$(dirname "$0")" && pwd)"
23-
24-
_kill_port() {
25-
local port=$1
26-
local pids
27-
pids=$(lsof -ti :"$port" 2>/dev/null || true)
28-
if [[ -n "$pids" ]]; then
29-
# shellcheck disable=SC2086
30-
kill -9 $pids 2>/dev/null || true
31-
fi
32-
}
33-
34-
stop() {
35-
echo "Stopping stack (ports $PORT_STUDIO $PORT_OWUI $PORT_CADDY)..."
36-
for p in "$PORT_STUDIO" "$PORT_OWUI" "$PORT_CADDY"; do _kill_port "$p"; done
37-
# Also kill any lingering manage.py dev processes
38-
local mpids
39-
mpids=$(pgrep -f "manage.py dev" 2>/dev/null || true)
40-
if [[ -n "$mpids" ]]; then
41-
# shellcheck disable=SC2086
42-
kill -9 $mpids 2>/dev/null || true
43-
fi
44-
rm -f "$PIDFILE"
45-
sleep 2
46-
# Verify
47-
local remaining
48-
remaining=$(lsof -ti :$PORT_STUDIO,$PORT_OWUI,$PORT_CADDY 2>/dev/null || true)
49-
if [[ -n "$remaining" ]]; then
50-
echo "WARNING: ports still occupied: $remaining"
51-
else
52-
echo "Stopped."
53-
fi
54-
}
55-
56-
start() {
57-
if [[ -f "$PIDFILE" ]] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
58-
echo "Already running (PID $(cat "$PIDFILE")). Use 'restart' to restart."
59-
return 0
60-
fi
61-
stop # ensure clean slate
62-
63-
# Clear stale bytecode so code changes are always picked up
64-
find "$REPO" -path "*__pycache__" -type d -exec rm -rf {} + 2>/dev/null || true
65-
66-
echo "Starting stack (Studio :$PORT_STUDIO, OWUI :$PORT_OWUI, Caddy :$PORT_CADDY)..."
67-
mkdir -p "$(dirname "$LOGFILE")"
68-
69-
cd "$REPO"
70-
export SIMULACHAT_API_KEY="${SIMULACHAT_API_KEY:-${CUSTOM_SIMULACHAT_KEY:-}}"
71-
SIMPLEAUDIT_LOCAL_SQLITE=1 \
72-
SIMPLEAUDIT_SQLITE_PATH="$DB" \
73-
SIMPLEAUDIT_BROWSER_PORT="$PORT_CADDY" \
74-
nohup uv run manage.py dev --port "$PORT_STUDIO" > "$LOGFILE" 2>&1 &
75-
local pid=$!
76-
echo "$pid" > "$PIDFILE"
77-
echo "Started (PID $pid). Log: $LOGFILE"
78-
79-
# Wait for health
80-
local i
81-
for i in $(seq 1 40); do
82-
if curl -s -o /dev/null -w "%{http_code}" "http://127.0.0.1:$PORT_STUDIO/healthz" 2>/dev/null | grep -q 200; then
83-
echo "Studio healthy."
84-
local owui
85-
owui=$(curl -s "http://127.0.0.1:$PORT_OWUI/chat/health" 2>/dev/null || echo "")
86-
local caddy
87-
caddy=$(curl -s -o /dev/null -w "%{http_code}" "http://127.0.0.1:$PORT_CADDY/" 2>/dev/null || echo "000")
88-
echo "OWUI: ${owui:-down} Caddy(8000): HTTP $caddy"
89-
return 0
90-
fi
91-
sleep 2
92-
done
93-
echo "ERROR: Studio did not become healthy in 80s. Check $LOGFILE"
94-
return 1
95-
}
96-
97-
status() {
98-
local h
99-
h=$(curl -s -o /dev/null -w "%{http_code}" "http://127.0.0.1:$PORT_STUDIO/healthz" 2>/dev/null || echo "000")
100-
local o
101-
o=$(curl -s "http://127.0.0.1:$PORT_OWUI/chat/health" 2>/dev/null || echo "down")
102-
local c
103-
c=$(curl -s -o /dev/null -w "%{http_code}" "http://127.0.0.1:$PORT_CADDY/" 2>/dev/null || echo "000")
104-
echo "Studio(:$PORT_STUDIO): HTTP $h"
105-
echo "OWUI(:$PORT_OWUI): $o"
106-
echo "Caddy(:$PORT_CADDY): HTTP $c"
107-
if [[ -f "$PIDFILE" ]]; then
108-
echo "PID file: $(cat "$PIDFILE")"
109-
fi
110-
}
111-
15+
# Compatibility wrapper delegating to the ownership-safe lifecycle manager.
16+
# The legacy kill-by-port cleanup was removed: no path here may terminate a
17+
# process by port, name, or broad pattern (another agent's worktree included).
18+
_REPO="$(cd "$(dirname "$0")" && pwd)"
11219
case "${1:-}" in
113-
start) start ;;
114-
stop) stop ;;
115-
status) status ;;
116-
restart) stop; start ;;
117-
*) echo "Usage: $0 {start|stop|status|restart}"; exit 1 ;;
20+
start)
21+
mkdir -p "$HOME/.local/state/simpleaudit-studio"
22+
(cd "$_REPO" && nohup uv run manage.py dev --no-browser \
23+
>> "$HOME/.local/state/simpleaudit-studio/devctl.log" 2>&1 </dev/null &)
24+
exit 0 ;;
25+
stop) cd "$_REPO"; exec uv run manage.py dev down ;;
26+
status) cd "$_REPO"; exec uv run manage.py dev status ;;
27+
restart) cd "$_REPO"; exec uv run manage.py dev restart --no-browser ;;
28+
*) echo "Usage: $0 {start|stop|status|restart}"; exit 2 ;;
11829
esac

simpleaudit_patch_delivery/development-lifecycle.md renamed to docs/development-lifecycle.md

File renamed without changes.

‎infra/management/commands/dev.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,4 +65,5 @@ def handle(self, *args, **options):
6565
embedded=True,
6666
no_reload=options["no_reload"],
6767
no_browser=options["no_browser"],
68+
no_force_kill=True, # never evict another agent's stack
6869
)

‎infra/management/commands/dev_server.py‎

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,7 @@ def handle(self, *args, **options):
261261
chat_enabled=_chat_config.ENABLED,
262262
chat_internal_port=_chat_config.INTERNAL_PORT,
263263
chat_upstream_url=_chat_config.UPSTREAM,
264-
force_kill=not options["no_force_kill"],
264+
force_kill=False, # no implicit process termination in development
265265
yes=options["yes"],
266266
command_hint="manage.py dev --port <free port>",
267267
)
@@ -447,9 +447,39 @@ def report():
447447
return process
448448

449449
def _stop_web(self, web_proc):
450-
if web_proc is not None:
451-
web_proc.terminate()
452-
web_proc.wait(timeout=5)
450+
"""Stop the auto-reload web server (guard → reloader parent → server).
451+
452+
Terminating only the guard can leave an orphaned runserver holding the
453+
internal port, because the reloader parent does not always notice the
454+
guard's death in time. We therefore SIGTERM the runserver processes by
455+
PID (never by process group — the reloader tree shares the owner's
456+
process group with Caddy/Open WebUI, which must keep running) and then
457+
wait for the guard to exit.
458+
"""
459+
if web_proc is None:
460+
return
461+
self._terminate_runserver_tree(web_proc.pid)
462+
import subprocess
463+
464+
try:
465+
web_proc.wait(timeout=8)
466+
except subprocess.TimeoutExpired:
467+
logger.warning("web server did not stop in time; left as-is")
468+
469+
@staticmethod
470+
def _terminate_runserver_tree(guard_pid: int) -> None:
471+
"""SIGTERM the runserver processes under ``guard_pid`` (by PID, not pgid)."""
472+
import psutil
473+
474+
try:
475+
guard = psutil.Process(guard_pid)
476+
except psutil.NoSuchProcess:
477+
return
478+
for proc in guard.children(recursive=True):
479+
try:
480+
proc.terminate()
481+
except psutil.NoSuchProcess:
482+
pass
453483

454484
def _stop_chat(self):
455485
try:

‎manage.py‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,32 @@ def main() -> None:
2727

2828
if command == "dev":
2929
os.environ.setdefault("SIMPLEAUDIT_MODE", "dev")
30-
single_process = runtime.is_single_process_run(command, argv)
30+
# Handle lifecycle requests before django.setup(), migrations, or any
31+
# imports that lock in chat ports/settings.
32+
from pathlib import Path
33+
34+
from simpleaudit_studio.lifecycle import ACTIONS, Instance, act, start
35+
36+
instance = Instance("dev", Path(__file__).resolve().parent)
37+
rest = sys.argv[2:]
38+
action = rest[0] if rest and rest[0] in ACTIONS else None
39+
if act(instance, action, yes="--yes" in rest):
40+
return
41+
if action in {"reset", "restart"}:
42+
sys.argv = [sys.argv[0], "dev"] + [x for x in rest[1:] if x != "--yes"]
43+
rest = sys.argv[2:]
44+
requested = int(os.environ.get("PORT", "8000"))
45+
explicit = False
46+
for index, arg in enumerate(rest):
47+
if arg == "--port" and index + 1 < len(rest):
48+
requested = int(rest[index + 1])
49+
explicit = True
50+
elif arg.startswith("--port="):
51+
requested = int(arg.split("=", 1)[1])
52+
explicit = True
53+
if not start(instance, requested_port=requested, explicit_port=explicit):
54+
return
55+
single_process = runtime.is_single_process_run(command, sys.argv)
3156
# Zero-Docker modes imply SQLite for the domain DB. Decide before Django
3257
# loads settings: a Postgres `.env` would otherwise make settings import
3358
# the Postgres driver first.

‎simpleaudit_patch_delivery/SimpleAuditStudio_agent_verification_seed.md‎

Lines changed: 0 additions & 72 deletions
This file was deleted.

0 commit comments

Comments
 (0)