This repository has been archived on 2026-05-02. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
risv3-relay/tests/test_state.py
ac 540b4f5b01 feat: relay daemon skeleton — queue, dispatch, conversation, ntfy (#1)
First-PR scope from #1. Single-process Python daemon that relays
between Claude Code instances and chat-Claude (Anthropic API).

Components:

* relay.config — .env + config.yaml loader. Auto-generates ntfy
  topic on first run and persists it back to .env.
* relay.state — atomic file I/O via tempfile + rename, advisory
  flock at state/.lock to enforce single-instance.
* relay.conversation — append-only history with summarization.
  Triggers a summarize call when total chars exceed
  HISTORY_CHAR_CAP (default 400k); replaces history with the
  summary plus the most recent 10 turns.
* relay.anthropic_client — SDK wrapper. Marks the system prompt
  cacheable (5-min ephemeral cache); concatenates text blocks;
  estimates per-call cost from the Anthropic price table with
  cache-write/read accounted for.
* relay.queue — JSON envelope intake; oldest-by-mtime;
  malformed envelopes moved to queue/.rejected/.
* relay.dispatch — one-input-at-a-time per session
  (dispatch/<session_id>/input.txt). Won't overwrite a pending
  dispatch; queues internally and waits for CC to delete.
* relay.ntfy — best-effort POST to https://ntfy.sh/<topic>;
  failures logged but never block the main loop.
* relay.daemon — main loop. Polls jc_input.txt (priority) then
  queue/. Detects [NEEDS-JC] in the first 200 chars of any
  response and pauses dispatch until JC writes jc_input.txt.
  JC override supports @session-N: prefix for direct dispatch
  without an API call.
* relay.__main__ — CLI: relay run / relay status / relay topic.

Tests: 57 unit tests pass (config, state, conversation, queue,
dispatch, anthropic_client, ntfy, full daemon loop with a fake
client). One real-API smoke test marked real_api, opt-in via
pytest -m real_api; skips cleanly on credit-balance errors.

Out of scope for this PR (deferred to follow-ups): Flask status
endpoint, multi-session config in production, exponential
backoff, systemd unit, cost-tracking aggregation.

Closes #1.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 15:24:47 +00:00

103 lines
3.0 KiB
Python

from __future__ import annotations
import json
import os
import threading
from pathlib import Path
import pytest
from relay.state import InstanceLock, StateError, read_json, write_atomic, write_json_atomic
def test_write_atomic_round_trips(tmp_path: Path) -> None:
target = tmp_path / "f.json"
write_atomic(target, "hello")
assert target.read_text() == "hello"
def test_write_atomic_does_not_leave_temp_files(tmp_path: Path) -> None:
target = tmp_path / "f.json"
write_atomic(target, "hello")
siblings = [p.name for p in tmp_path.iterdir() if p != target]
assert siblings == []
def test_write_json_atomic_round_trips(tmp_path: Path) -> None:
target = tmp_path / "value.json"
payload = [{"k": "v"}, {"k2": "v2"}]
write_json_atomic(target, payload)
assert json.loads(target.read_text()) == payload
def test_read_json_returns_default_when_missing(tmp_path: Path) -> None:
assert read_json(tmp_path / "nope.json", default=[]) == []
assert read_json(tmp_path / "nope.json", default={"x": 1}) == {"x": 1}
def test_read_json_returns_default_when_empty(tmp_path: Path) -> None:
target = tmp_path / "empty.json"
target.write_text("")
assert read_json(target, default=[]) == []
def test_read_json_raises_on_corruption(tmp_path: Path) -> None:
target = tmp_path / "bad.json"
target.write_text("{not json")
with pytest.raises(StateError):
read_json(target, default=[])
def test_instance_lock_acquires_and_releases(tmp_path: Path) -> None:
lock = InstanceLock(tmp_path / ".lock")
lock.acquire()
try:
# PID written to file
assert (tmp_path / ".lock").read_text().strip() == str(os.getpid())
finally:
lock.release()
def test_instance_lock_rejects_second_acquirer(tmp_path: Path) -> None:
lock1 = InstanceLock(tmp_path / ".lock")
lock1.acquire()
try:
lock2 = InstanceLock(tmp_path / ".lock")
with pytest.raises(StateError):
lock2.acquire()
finally:
lock1.release()
def test_instance_lock_release_is_idempotent(tmp_path: Path) -> None:
lock = InstanceLock(tmp_path / ".lock")
lock.acquire()
lock.release()
lock.release() # second release should not raise
def test_concurrent_acquire_serializes(tmp_path: Path) -> None:
"""Confirm flock semantics: two threads acquiring the same lock can't overlap."""
lock_path = tmp_path / ".lock"
held: list[bool] = []
error_count = [0]
def worker():
lock = InstanceLock(lock_path)
try:
lock.acquire()
held.append(True)
lock.release()
except StateError:
error_count[0] += 1
threads = [threading.Thread(target=worker) for _ in range(2)]
for t in threads:
t.start()
for t in threads:
t.join()
# At least one succeeded; the other either succeeded after the first
# released, or failed to acquire (depending on scheduling).
assert sum(held) + error_count[0] == 2