Add activity tracker server, Hyprland agent and Gitea image publishing
Test and publish / test (push) Successful in 2m38s
Test and publish / publish (push) Failing after 2m30s

The Go API on PostgreSQL ingests desktop, browser, presence, manual and
Health Auto Export events and serves activities and daily goal summaries.
The Hyprland agent records window focus, idle and lock intervals.

The CI workflow publishes adam-french.co.uk/adamf/activity-tracker to the
Gitea registry and rolls the web_server stack onto it. The image probes
itself through a new `tracker healthcheck` command, because distroless
has no wget.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-14 20:38:12 +01:00
co-authored by Claude Opus 5.5
parent 0cbbb76dee
commit f4ce04875c
29 changed files with 2810 additions and 0 deletions
+172
View File
@@ -0,0 +1,172 @@
// Command hypr-agent records focused-window time on Hyprland and uploads it
// to the tracker server.
//
// hypr-agent run run the collector (usually via systemd --user)
// hypr-agent idle|resume sent by hypridle on-timeout / on-resume
// hypr-agent lock|unlock sent around your screen locker
package main
import (
"context"
"errors"
"flag"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"time"
"ccp/internal/agent/hypr"
"ccp/internal/ingest"
)
func main() {
if len(os.Args) < 2 {
fmt.Fprintln(os.Stderr, "usage: hypr-agent run|idle|resume|lock|unlock [flags]")
os.Exit(2)
}
var err error
switch cmd := os.Args[1]; {
case cmd == "run":
err = run(os.Args[2:])
case hypr.Commands[cmd]:
err = hypr.SendControl(cmd)
default:
err = fmt.Errorf("unknown command %q", cmd)
}
if err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}
func run(args []string) error {
fs := flag.NewFlagSet("run", flag.ContinueOnError)
server := fs.String("server", os.Getenv("TRACKER_URL"), "tracker server base URL [TRACKER_URL]")
key := fs.String("key", os.Getenv("TRACKER_API_KEY"), "API key [TRACKER_API_KEY]")
keyFile := fs.String("key-file", os.Getenv("TRACKER_API_KEY_FILE"), "file containing the API key [TRACKER_API_KEY_FILE]")
titles := fs.Bool("titles", envBool("HYPR_AGENT_TITLES", true), "record window titles [HYPR_AGENT_TITLES]")
redact := fs.String("redact", os.Getenv("HYPR_AGENT_REDACT"), "regexp; matching titles are replaced with [redacted] [HYPR_AGENT_REDACT]")
minDur := fs.Duration("min-duration", 2*time.Second, "drop focus intervals shorter than this")
flush := fs.Duration("flush", time.Minute, "upload interval")
bufPath := fs.String("buffer", defaultBufferPath(), "pending-events file")
if err := fs.Parse(args); err != nil {
return err
}
if *server == "" {
return errors.New("--server (or TRACKER_URL) is required")
}
if *keyFile != "" {
b, err := os.ReadFile(*keyFile)
if err != nil {
return err
}
*key = strings.TrimSpace(string(b))
}
if *key == "" {
return errors.New("--key, --key-file, TRACKER_API_KEY or TRACKER_API_KEY_FILE is required")
}
var redactRe *regexp.Regexp
if *redact != "" {
var err error
if redactRe, err = regexp.Compile(*redact); err != nil {
return fmt.Errorf("--redact: %w", err)
}
}
log := slog.New(slog.NewTextHandler(os.Stderr, nil))
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
buf, err := hypr.OpenBuffer(*bufPath)
if err != nil {
return fmt.Errorf("open buffer: %w", err)
}
up := &hypr.Uploader{
URL: *server,
Key: *key,
Buf: buf,
Client: &http.Client{Timeout: 15 * time.Second},
Log: log,
}
sess := &hypr.Sessionizer{
MinDuration: *minDur,
Emit: func(e ingest.Event) {
if err := buf.Add(e); err != nil {
log.Error("buffer event", "err", err)
}
},
}
cleanTitle := func(f hypr.Focus) hypr.Focus {
switch {
case !*titles:
f.Title = ""
case redactRe != nil && redactRe.MatchString(f.Title):
f.Title = "[redacted]"
}
return f
}
focus := make(chan hypr.FocusEvent, 64)
control := make(chan hypr.ControlEvent, 8)
errc := make(chan error, 2)
go func() { errc <- hypr.Listen(ctx, focus, log) }()
go func() { errc <- hypr.ServeControl(ctx, control) }()
go up.Run(ctx, *flush)
log.Info("hypr-agent started", "server", *server, "pending", buf.Len())
loop:
for {
select {
case <-ctx.Done():
break loop
case err := <-errc:
if err != nil {
stop()
return err
}
case f := <-focus:
sess.Focus(f.At, cleanTitle(f.Focus))
case c := <-control:
switch c.Command {
case "idle":
sess.Pause(c.At, "idle")
case "lock":
sess.Pause(c.At, "locked")
case "resume", "unlock":
sess.Resume(c.At)
}
}
}
sess.Close(time.Now())
flushCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := up.Flush(flushCtx); err != nil {
log.Warn("final upload failed; events kept for next run", "err", err, "pending", buf.Len())
}
return nil
}
func defaultBufferPath() string {
dir := os.Getenv("XDG_STATE_HOME")
if dir == "" {
home, _ := os.UserHomeDir()
dir = filepath.Join(home, ".local", "state")
}
return filepath.Join(dir, "hypr-agent", "buffer.jsonl")
}
func envBool(key string, def bool) bool {
if v, err := strconv.ParseBool(os.Getenv(key)); err == nil {
return v
}
return def
}
+256
View File
@@ -0,0 +1,256 @@
// Command tracker runs the activity tracker server and its admin commands.
package main
import (
"context"
"errors"
"flag"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"text/tabwriter"
"time"
_ "time/tzdata" // the distroless image has no zoneinfo
"github.com/jackc/pgx/v5/pgxpool"
"ccp/internal/api"
"ccp/internal/config"
"ccp/internal/migrations"
"ccp/internal/store"
)
const usage = `usage: tracker <command> [flags]
commands:
serve run the HTTP server
migrate apply database migrations and exit
healthcheck exit 0 if the local server is ready (for Docker HEALTHCHECK)
apikey create --name NAME --kind KIND register a device and print its API key
apikey list list devices
apikey revoke --name NAME revoke a device's API key
goal add --kind KIND [--label L] --op '>=|<=' --target DURATION
goal list
goal rm --id ID
`
func main() {
if len(os.Args) < 2 {
fmt.Fprint(os.Stderr, usage)
os.Exit(2)
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if err := run(ctx, os.Args[1], os.Args[2:]); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}
func run(ctx context.Context, cmd string, args []string) error {
// Handled before config.Load: the probe needs no database of its own, only
// the listen address, and the distroless image has no wget or curl to do it.
if cmd == "healthcheck" {
return healthcheck(ctx)
}
cfg, err := config.Load()
if err != nil {
return err
}
pool, err := pgxpool.New(ctx, cfg.DatabaseURL)
if err != nil {
return fmt.Errorf("connect database: %w", err)
}
defer pool.Close()
st := store.New(pool)
switch cmd {
case "serve":
return serve(ctx, cfg, pool, st)
case "migrate":
return migrations.Up(ctx, pool)
case "apikey":
return apikeyCmd(ctx, st, args)
case "goal":
return goalCmd(ctx, st, args)
default:
fmt.Fprint(os.Stderr, usage)
return fmt.Errorf("unknown command %q", cmd)
}
}
func serve(ctx context.Context, cfg config.Config, pool *pgxpool.Pool, st *store.Store) error {
log := slog.New(slog.NewJSONHandler(os.Stdout, nil))
if cfg.AutoMigrate {
if err := migrations.Up(ctx, pool); err != nil {
return err
}
log.Info("migrations applied")
}
srv := &http.Server{
Addr: cfg.ListenAddr,
Handler: api.New(st, cfg.Location, log),
ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 60 * time.Second,
WriteTimeout: 60 * time.Second,
}
errc := make(chan error, 1)
go func() {
log.Info("listening", "addr", cfg.ListenAddr, "tz", cfg.Location.String())
errc <- srv.ListenAndServe()
}()
select {
case err := <-errc:
return err
case <-ctx.Done():
}
log.Info("shutting down")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return srv.Shutdown(shutdownCtx)
}
// healthcheck asks the server in this container for /readyz, which also pings
// the database, so "healthy" means the tracker can actually store events.
func healthcheck(ctx context.Context) error {
addr := os.Getenv("LISTEN_ADDR")
if addr == "" {
addr = ":8080"
}
host, port, err := net.SplitHostPort(addr)
if err != nil {
return fmt.Errorf("LISTEN_ADDR: %w", err)
}
if host == "" || host == "0.0.0.0" || host == "::" {
host = "localhost"
}
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+net.JoinHostPort(host, port)+"/readyz", nil)
if err != nil {
return err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("readyz: %s", resp.Status)
}
return nil
}
func apikeyCmd(ctx context.Context, st *store.Store, args []string) error {
if len(args) == 0 {
return errors.New("apikey needs a subcommand: create, list, revoke")
}
fs := flag.NewFlagSet("apikey "+args[0], flag.ContinueOnError)
name := fs.String("name", "", "device name, e.g. laptop-hypr")
kind := fs.String("kind", "", "collector kind, e.g. hyprland, browser, health, presence")
if err := fs.Parse(args[1:]); err != nil {
return err
}
switch args[0] {
case "create":
if *name == "" || *kind == "" {
return errors.New("--name and --kind are required")
}
d, key, err := st.CreateDevice(ctx, *name, *kind)
if err != nil {
return err
}
fmt.Printf("device %q (id %d) created.\nAPI key (shown once): %s\n", d.Name, d.ID, key)
case "list":
devs, err := st.ListDevices(ctx)
if err != nil {
return err
}
tw := tabwriter.NewWriter(os.Stdout, 0, 4, 2, ' ', 0)
fmt.Fprintln(tw, "ID\tNAME\tKIND\tLAST SEEN\tSTATUS")
for _, d := range devs {
seen, status := "never", "active"
if d.LastSeenAt != nil {
seen = d.LastSeenAt.Local().Format(time.DateTime)
}
if d.RevokedAt != nil {
status = "revoked"
}
fmt.Fprintf(tw, "%d\t%s\t%s\t%s\t%s\n", d.ID, d.Name, d.Kind, seen, status)
}
return tw.Flush()
case "revoke":
if *name == "" {
return errors.New("--name is required")
}
if err := st.RevokeDevice(ctx, *name); err != nil {
return err
}
fmt.Printf("device %q revoked\n", *name)
default:
return fmt.Errorf("unknown apikey subcommand %q", args[0])
}
return nil
}
func goalCmd(ctx context.Context, st *store.Store, args []string) error {
if len(args) == 0 {
return errors.New("goal needs a subcommand: add, list, rm")
}
fs := flag.NewFlagSet("goal "+args[0], flag.ContinueOnError)
kind := fs.String("kind", "", "activity kind, e.g. tab_focus, walk, at_desk")
label := fs.String("label", "", "optional label, e.g. youtube.com (empty = any)")
op := fs.String("op", "", "'>=' (at least) or '<=' (at most)")
target := fs.Duration("target", 0, "daily target, e.g. 1h30m")
id := fs.String("id", "", "goal id")
if err := fs.Parse(args[1:]); err != nil {
return err
}
switch args[0] {
case "add":
if *kind == "" || (*op != ">=" && *op != "<=") || *target <= 0 {
return errors.New("--kind, --op ('>=' or '<=') and --target are required")
}
g, err := st.CreateGoal(ctx, store.Goal{Kind: *kind, Label: *label, Op: *op, TargetS: int64(target.Seconds())})
if err != nil {
return err
}
fmt.Printf("goal %d added\n", g.ID)
case "list":
goals, err := st.Goals(ctx)
if err != nil {
return err
}
tw := tabwriter.NewWriter(os.Stdout, 0, 4, 2, ' ', 0)
fmt.Fprintln(tw, "ID\tKIND\tLABEL\tOP\tTARGET/DAY")
for _, g := range goals {
fmt.Fprintf(tw, "%d\t%s\t%s\t%s\t%s\n", g.ID, g.Kind, g.Label, g.Op, time.Duration(g.TargetS)*time.Second)
}
return tw.Flush()
case "rm":
n, err := strconv.ParseInt(*id, 10, 64)
if err != nil {
return errors.New("--id must be a number")
}
if err := st.DeleteGoal(ctx, n); err != nil {
return err
}
fmt.Printf("goal %d removed\n", n)
default:
return fmt.Errorf("unknown goal subcommand %q", args[0])
}
return nil
}