Phase 9: Hub API and Apprise alerts (/capabilities, /ask, /notify)
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>
This commit is contained in:
@@ -16,14 +16,17 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"gitea.lab.audasmedia.com.au/sam/internet_use_control/internal/alert"
|
||||
"gitea.lab.audasmedia.com.au/sam/internet_use_control/internal/auth"
|
||||
"gitea.lab.audasmedia.com.au/sam/internet_use_control/internal/config"
|
||||
"gitea.lab.audasmedia.com.au/sam/internet_use_control/internal/hub"
|
||||
"gitea.lab.audasmedia.com.au/sam/internet_use_control/internal/mqtt"
|
||||
"gitea.lab.audasmedia.com.au/sam/internet_use_control/internal/store"
|
||||
"gitea.lab.audasmedia.com.au/sam/internet_use_control/internal/web"
|
||||
@@ -66,6 +69,12 @@ func main() {
|
||||
case "rollup":
|
||||
rollup(os.Args[2:])
|
||||
return
|
||||
case "alerts":
|
||||
alertsCommand(os.Args[2:])
|
||||
return
|
||||
case "usage":
|
||||
usageCommand(os.Args[2:])
|
||||
return
|
||||
case "version":
|
||||
fmt.Println(version)
|
||||
return
|
||||
@@ -178,6 +187,22 @@ func run() error {
|
||||
return err
|
||||
}
|
||||
|
||||
// Phase 9: the alert engine turns a limit hit or a too-long offline spell
|
||||
// into one Apprise message to Sam (FR-13). It is optional; /ask and
|
||||
// /notify keep working without it.
|
||||
if cfg.AlertsEnabled {
|
||||
engine := alert.New(st, srv.Apprise(), log, cfg.AlertOfflineAfter, cfg.ScheduleLocation)
|
||||
engine.Interval = cfg.AlertInterval
|
||||
go engine.Run(ctx)
|
||||
if !cfg.AppriseConfigured() {
|
||||
log.Warn("alerts are enabled but Apprise is not configured; alerts will be recorded as undelivered")
|
||||
} else {
|
||||
log.Info("alert engine started", "offline_after", cfg.AlertOfflineAfter.String())
|
||||
}
|
||||
} else {
|
||||
log.Info("alert engine disabled")
|
||||
}
|
||||
|
||||
httpServer := &http.Server{
|
||||
Addr: cfg.Addr,
|
||||
Handler: srv.Handler(),
|
||||
@@ -305,6 +330,122 @@ func runMaintenance(ctx context.Context, log *slog.Logger, st *store.Store) {
|
||||
}
|
||||
}
|
||||
|
||||
// alertsCommand prints the most recent alerts, newest first, one per line as
|
||||
// tab-separated fields:
|
||||
//
|
||||
// <id>\t<kind>\t<delivered|pending>\t<created>\t<device>\t<message>
|
||||
//
|
||||
// It is a read-only operational view. The Phase 9 verification script uses it
|
||||
// to check that an alert was raised and delivered.
|
||||
func alertsCommand(args []string) {
|
||||
dbPath := env("CONTROL_DB_PATH", "/data/control.db")
|
||||
limit := 20
|
||||
for i := 0; i < len(args); i++ {
|
||||
switch args[i] {
|
||||
case "--db", "-db":
|
||||
if i+1 < len(args) {
|
||||
dbPath = args[i+1]
|
||||
i++
|
||||
}
|
||||
case "--limit", "-limit":
|
||||
if i+1 < len(args) {
|
||||
if n, err := strconv.Atoi(args[i+1]); err == nil {
|
||||
limit = n
|
||||
}
|
||||
i++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
st, err := store.Open(dbPath)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "control:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer st.Close()
|
||||
if err := st.Migrate(context.Background()); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "control:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
list, err := st.ListAlerts(context.Background(), limit)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "control:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
for _, a := range list {
|
||||
delivered := "pending"
|
||||
if a.Delivered {
|
||||
delivered = "delivered"
|
||||
}
|
||||
device := a.DeviceName
|
||||
if device == "" {
|
||||
device = "-"
|
||||
}
|
||||
fmt.Printf("%d\t%s\t%s\t%s\t%s\t%s\n",
|
||||
a.ID, a.Kind, delivered, a.CreatedAt.Format(time.RFC3339), device, a.Message)
|
||||
}
|
||||
}
|
||||
|
||||
// usageCommand prints one day's per-device screen time. --detail reads the raw
|
||||
// telemetry detail table instead of the derived rollup, so an operator can
|
||||
// check the daily answer independently.
|
||||
func usageCommand(args []string) {
|
||||
dbPath := env("CONTROL_DB_PATH", "/data/control.db")
|
||||
day := time.Now().Format("2006-01-02")
|
||||
detail := false
|
||||
for i := 0; i < len(args); i++ {
|
||||
switch args[i] {
|
||||
case "--db", "-db":
|
||||
if i+1 < len(args) {
|
||||
dbPath = args[i+1]
|
||||
i++
|
||||
}
|
||||
case "--day", "-day":
|
||||
if i+1 < len(args) {
|
||||
day = args[i+1]
|
||||
i++
|
||||
}
|
||||
case "--detail", "-detail":
|
||||
detail = true
|
||||
}
|
||||
}
|
||||
|
||||
st, err := store.Open(dbPath)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "control:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer st.Close()
|
||||
ctx := context.Background()
|
||||
if err := st.Migrate(ctx); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "control:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
source := "rollup"
|
||||
var rows []store.DeviceDayUsage
|
||||
if detail {
|
||||
source = "detail"
|
||||
rows, err = st.DetailUsageByDeviceForDay(ctx, day)
|
||||
} else {
|
||||
rows, err = st.UsageByDeviceForDay(ctx, day)
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "control:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
fmt.Printf("day=%s source=%s\n", day, source)
|
||||
total := 0
|
||||
for _, u := range rows {
|
||||
screen := hub.ScreenSeconds(u.AppSeconds, u.DomainSeconds)
|
||||
total += screen
|
||||
fmt.Printf("%s\t%s\tapp=%d\tdomain=%d\tscreen=%d\n",
|
||||
u.Name, u.Child, u.AppSeconds, u.DomainSeconds, screen)
|
||||
}
|
||||
fmt.Printf("total_screen=%d\n", total)
|
||||
}
|
||||
|
||||
// rollup rebuilds the daily usage rollup from the telemetry detail table. It is
|
||||
// idempotent and safe to run while the service is up; it exits non-zero on a
|
||||
// failure so a script can tell.
|
||||
|
||||
Reference in New Issue
Block a user