Build on Phases 1-8. Adds the project side of the frozen Hub contract
(central_ai_llm_master/docs/ask-contract.md) and the alert engine from
AGENTS.md §4 FR-12/FR-13, §8, §11 Phase 9.
- hub: internal/hub implements AskRequest/AskResponse/NotifyRequest and a
deterministic, read-only Answerer. It answers screen time today/yesterday,
what is blocked now, and device presence, scoped to one child or all kids.
Screen time is the foreground-app total per device-day; the domain total is
used only when a device reports no apps, so a report carrying both is never
double-counted.
- apprise: internal/apprise is a small Apprise API client (stored key or
stateless URL mode, optional bearer token, typed notifications).
- alert: internal/alert evaluates device state on an interval and raises one
Apprise alert per transition: a limit hit (a device becomes blocked) or a
device offline longer than the threshold. A never-seen device is never
alerted, and the first observation seeds state without replaying an old
limit. The alert is recorded before delivery, with its delivery outcome.
- store: migration 005 adds `alerts` (delivery outcome, audited) and
`alert_state` (per-device dedup). New usage reads from the telemetry detail
table so the daily answer can be checked independently.
- web: GET /capabilities, POST /ask (read-only) and POST /notify behind the
shared CONTROL_HUB_TOKEN, separate from the session and admin API tokens.
/notify accepts the contract's {from,level,message,person} and delivers it
through Apprise (the future tamper-report path, FR-17).
- cmd/control: start the alert engine (CONTROL_ALERTS_ENABLED,
CONTROL_ALERT_OFFLINE_AFTER, CONTROL_ALERT_INTERVAL) and add `alerts` and
`usage` subcommands for read-only inspection.
- deploy/verify-phase9.sh + `make verify-phase9` prove the definition of done;
version 0.7.0-phase9.
Measured on .13 (2026-10-13):
- GET /capabilities -> internet_use_control topics.
- POST /ask "how long have the kids been on screens today?" -> "The kids have
had 1h 22m of screen time today." (total_seconds=4925); the independent
count from the telemetry detail table is also 4925 (app=4925, domain=4800).
- A manual lock raised a delivered limit alert (id 4); an MQTT offline status
raised a delivered offline alert (id 5); POST /notify delivered (id 6). All
three report delivered=1 in `alerts`.
Tests: gofmt, go vet ./... and go test ./... pass in golang:1.25-alpine.
Co-Authored-By: Paperclip <noreply@paperclip.ing>
179 lines
5.2 KiB
Go
179 lines
5.2 KiB
Go
package alert
|
|
|
|
import (
|
|
"context"
|
|
"log/slog"
|
|
"testing"
|
|
"time"
|
|
|
|
"gitea.lab.audasmedia.com.au/sam/internet_use_control/internal/store"
|
|
)
|
|
|
|
type fakeStore struct {
|
|
devices []store.Device
|
|
eff map[int64]store.EffectiveState
|
|
states map[int64]store.AlertState
|
|
alerts []*store.Alert
|
|
nextID int64
|
|
}
|
|
|
|
func newFakeStore(devices ...store.Device) *fakeStore {
|
|
return &fakeStore{
|
|
devices: devices,
|
|
eff: map[int64]store.EffectiveState{},
|
|
states: map[int64]store.AlertState{},
|
|
}
|
|
}
|
|
|
|
func (f *fakeStore) ListDevices(context.Context) ([]store.Device, error) { return f.devices, nil }
|
|
|
|
func (f *fakeStore) EffectiveState(_ context.Context, dev store.Device, _ time.Time) (store.EffectiveState, error) {
|
|
return f.eff[dev.ID], nil
|
|
}
|
|
|
|
func (f *fakeStore) AlertStates(context.Context) (map[int64]store.AlertState, error) {
|
|
out := make(map[int64]store.AlertState, len(f.states))
|
|
for k, v := range f.states {
|
|
out[k] = v
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (f *fakeStore) SetAlertState(_ context.Context, deviceID int64, locked, offline bool) error {
|
|
f.states[deviceID] = store.AlertState{Locked: locked, Offline: offline}
|
|
return nil
|
|
}
|
|
|
|
func (f *fakeStore) CreateAlert(_ context.Context, deviceID *int64, kind, message string) (*store.Alert, error) {
|
|
f.nextID++
|
|
a := &store.Alert{ID: f.nextID, DeviceID: deviceID, Kind: kind, Message: message}
|
|
f.alerts = append(f.alerts, a)
|
|
return a, nil
|
|
}
|
|
|
|
func (f *fakeStore) MarkAlertDelivered(_ context.Context, id int64, errMsg string) error {
|
|
for _, a := range f.alerts {
|
|
if a.ID == id {
|
|
a.Delivered = errMsg == ""
|
|
a.Error = errMsg
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
type fakeNotifier struct {
|
|
configured bool
|
|
sent []string
|
|
err error
|
|
}
|
|
|
|
func (f *fakeNotifier) Configured() bool { return f.configured }
|
|
|
|
func (f *fakeNotifier) SendType(_ context.Context, _, body, _ string) error {
|
|
if f.err != nil {
|
|
return f.err
|
|
}
|
|
f.sent = append(f.sent, body)
|
|
return nil
|
|
}
|
|
|
|
func newEngine(st *fakeStore, n *fakeNotifier, now time.Time) *Engine {
|
|
e := New(st, n, slog.New(slog.DiscardHandler), 30*time.Minute, time.UTC)
|
|
e.Now = func() time.Time { return now }
|
|
return e
|
|
}
|
|
|
|
func TestSeedThenLimitTransition(t *testing.T) {
|
|
now := time.Date(2026, 10, 13, 20, 30, 0, 0, time.UTC)
|
|
until := now.Add(30 * time.Minute)
|
|
fs := newFakeStore(store.Device{ID: 1, Name: "Harry's phone", Child: "Harry"})
|
|
fs.eff[1] = store.EffectiveState{DeviceID: 1, Locked: false, Reason: ""}
|
|
fn := &fakeNotifier{configured: true}
|
|
e := newEngine(fs, fn, now)
|
|
|
|
// First observation seeds the state and raises nothing.
|
|
e.Evaluate(context.Background())
|
|
if len(fs.alerts) != 0 {
|
|
t.Fatalf("seed raised %d alerts, want 0", len(fs.alerts))
|
|
}
|
|
if st := fs.states[1]; st.Locked {
|
|
t.Fatalf("seeded state = %#v, want unlocked", st)
|
|
}
|
|
|
|
// A schedule turns on: exactly one limit alert.
|
|
fs.eff[1] = store.EffectiveState{DeviceID: 1, Locked: true, Reason: "schedule", Until: &until}
|
|
e.Evaluate(context.Background())
|
|
if len(fs.alerts) != 1 {
|
|
t.Fatalf("alerts = %d, want 1", len(fs.alerts))
|
|
}
|
|
if fs.alerts[0].Kind != store.AlertLimit {
|
|
t.Errorf("kind = %q, want limit", fs.alerts[0].Kind)
|
|
}
|
|
if !fs.alerts[0].Delivered {
|
|
t.Error("alert was not marked delivered")
|
|
}
|
|
if len(fn.sent) != 1 {
|
|
t.Fatalf("notifier sent %d, want 1", len(fn.sent))
|
|
}
|
|
|
|
// No new alert while the condition stays true.
|
|
e.Evaluate(context.Background())
|
|
if len(fs.alerts) != 1 {
|
|
t.Fatalf("repeat evaluation raised %d alerts, want 1", len(fs.alerts))
|
|
}
|
|
}
|
|
|
|
func TestOfflineTransition(t *testing.T) {
|
|
now := time.Date(2026, 10, 13, 15, 0, 0, 0, time.UTC)
|
|
old := now.Add(-2 * time.Hour)
|
|
fs := newFakeStore(store.Device{ID: 2, Name: "Finn's computer", Child: "Finn", Online: true})
|
|
fs.eff[2] = store.EffectiveState{DeviceID: 2}
|
|
fn := &fakeNotifier{configured: true}
|
|
e := newEngine(fs, fn, now)
|
|
e.Evaluate(context.Background()) // seed online
|
|
|
|
fs.devices[0].Online = false
|
|
fs.devices[0].LastSeen = &old
|
|
e.Evaluate(context.Background())
|
|
|
|
if len(fs.alerts) != 1 || fs.alerts[0].Kind != store.AlertOffline {
|
|
t.Fatalf("alerts = %#v, want one offline alert", fs.alerts)
|
|
}
|
|
if len(fn.sent) != 1 {
|
|
t.Fatalf("notifier sent %d, want 1", len(fn.sent))
|
|
}
|
|
}
|
|
|
|
func TestNeverSeenDeviceIsNotOffline(t *testing.T) {
|
|
now := time.Date(2026, 10, 13, 15, 0, 0, 0, time.UTC)
|
|
fs := newFakeStore(store.Device{ID: 3, Name: "New device", Child: "Harry", Online: false})
|
|
fs.eff[3] = store.EffectiveState{DeviceID: 3}
|
|
e := newEngine(fs, &fakeNotifier{configured: true}, now)
|
|
|
|
e.Evaluate(context.Background()) // seed
|
|
e.Evaluate(context.Background()) // still no last_seen
|
|
if len(fs.alerts) != 0 {
|
|
t.Fatalf("alerts = %d, want 0 for a never-seen device", len(fs.alerts))
|
|
}
|
|
}
|
|
|
|
func TestUndeliveredWhenNotConfigured(t *testing.T) {
|
|
now := time.Date(2026, 10, 13, 20, 30, 0, 0, time.UTC)
|
|
until := now.Add(30 * time.Minute)
|
|
fs := newFakeStore(store.Device{ID: 1, Name: "Harry's phone", Child: "Harry"})
|
|
fs.eff[1] = store.EffectiveState{DeviceID: 1}
|
|
fn := &fakeNotifier{configured: false}
|
|
e := newEngine(fs, fn, now)
|
|
e.Evaluate(context.Background())
|
|
|
|
fs.eff[1] = store.EffectiveState{DeviceID: 1, Locked: true, Reason: "schedule", Until: &until}
|
|
e.Evaluate(context.Background())
|
|
|
|
if len(fs.alerts) != 1 {
|
|
t.Fatalf("alerts = %d, want 1", len(fs.alerts))
|
|
}
|
|
if fs.alerts[0].Delivered {
|
|
t.Error("alert marked delivered with an unconfigured notifier")
|
|
}
|
|
}
|