diff --git a/.planning/quick/260712-4ft-roaming-realistic-random-cursor-movement/PLAN.md b/.planning/quick/260712-4ft-roaming-realistic-random-cursor-movement/PLAN.md
new file mode 100644
index 0000000..c1f5bc7
--- /dev/null
+++ b/.planning/quick/260712-4ft-roaming-realistic-random-cursor-movement/PLAN.md
@@ -0,0 +1,308 @@
+---
+phase: quick-260712-roaming
+plan: 01
+type: execute
+wave: 1
+depends_on: []
+files_modified:
+ - internal/activity/domain/planner.go
+ - internal/activity/domain/planner_test.go
+ - internal/activity/domain/activity.go
+ - internal/activity/domain/activity_test.go
+ - internal/activity/port/pointer.go
+ - internal/activity/port/mock/mock_pointer.go
+ - internal/activity/service/keeper_service.go
+ - internal/activity/service/keeper_service_test.go
+ - internal/activity/adapter/cgpointer.go
+ - internal/activity/adapter/cgpointer_test.go
+ - cmd/sysmon/main.go
+autonomous: true
+requirements: [ROAM-01, ROAM-02, ROAM-03, ROAM-04, ROAM-05, ROAM-06]
+must_haves:
+ truths:
+ - "On each -interval tick the cursor glides to a fresh uniformly-random on-screen point over multiple small steps."
+ - "The cursor never leaves the main display bounds and shows no cumulative drift (absolute clamped targets)."
+ - "SIGINT/SIGTERM stops the loop promptly, including mid-glide, with exit code 0."
+ - "-interval controls the gap between roams; -quiet still raises the slog level."
+ - "Domain and service build under GOOS=linux (cgo/os-free); cgo stays in the darwin adapter only."
+ artifacts:
+ - internal/activity/domain/planner.go
+ - internal/activity/domain/planner_test.go
+ - internal/activity/port/pointer.go
+ - internal/activity/port/mock/mock_pointer.go
+ - internal/activity/service/keeper_service.go
+ - internal/activity/service/keeper_service_test.go
+ - internal/activity/adapter/cgpointer.go
+ - cmd/sysmon/main.go
+ key_links:
+ - "service.KeeperService drives domain.Planner output through port.Pointer.MoveTo in order, checking ctx between steps."
+ - "cmd/sysmon/main.go wires adapter.CGPointer into KeeperService with an injected *rand.Rand and *slog.Logger."
+ - "port.Pointer mock is regenerated from the new interface so service tests compile."
+---
+
+
+Replace the invisible 1px there-and-back nudge with realistic random cursor
+roaming. On each -interval tick the service asks a pure domain planner for a
+glide path from the current cursor position to a fresh uniformly-random target
+inside the main-display bounds, then drives the pointer through that path with
+short inter-step pauses, stopping promptly on ctx cancellation (including
+mid-glide).
+
+Purpose: deliver the visible, human-like activity behavior the user wants while
+preserving the hexagonal layering (pure cgo-free domain + service, cgo isolated
+to the darwin adapter) and the zero-runtime-dependency constraint.
+
+Output: a new domain movement planner with deterministic tests; a reshaped
+Pointer port (MoveTo/Position/Bounds) with a regenerated mock; a rewritten
+KeeperService that roams once per tick; a CoreGraphics adapter implementing
+absolute move / current position / main-display bounds; updated main.go wiring;
+all gates green.
+
+
+
+@$HOME/.claude/gsd-core/workflows/execute-plan.md
+@$HOME/.claude/gsd-core/templates/summary.md
+
+
+
+@docs/TASK-roaming.md
+@docs/TASK.md
+@.golangci.yml
+@internal/activity/domain/activity.go
+@internal/activity/port/pointer.go
+@internal/activity/service/keeper_service.go
+@internal/activity/adapter/cgpointer.go
+@cmd/sysmon/main.go
+@internal/activity/port/mock/mock_pointer.go
+
+Notes for the executor:
+- Go 1.26.5. `testing/synctest` is stable (graduated 1.25) — use `synctest.Test`
+ / `synctest.Wait` for deterministic timing in service tests.
+- `math/rand/v2` is stdlib and allowed in the runtime binary.
+- Runtime deps stay stdlib-only; test-only deps (testify, go.uber.org/mock)
+ are unchanged. NO testcontainers.
+- The lint config builds with `-build-tags darwin` and treats generated files
+ as strict-exempt, so the regenerated mock must keep its
+ `// Code generated by MockGen. DO NOT EDIT.` header.
+- English only in all code, comments, and docs. No AI mentions.
+- Old-code handling: the there-and-back nudge is REMOVED, not repurposed.
+ `domain.Offset` / `NewOffset` / `ErrNonPositiveOffset` and their tests are
+ deleted (roaming uses absolute clamped targets, so a relative offset value
+ object no longer has meaning); `Interval` is kept as-is.
+
+
+
+
+
+ Task 1: Pure domain movement planner + deterministic tests
+ internal/activity/domain/planner.go, internal/activity/domain/planner_test.go
+
+ - Planner exposes a method that, given current position (x, y), screen
+ bounds (width, height), and an injected random source, returns an ordered
+ slice of intermediate points ending exactly at a random target.
+ - Random source is injected behind a small seam (an interface with the
+ float/int-picking methods the planner needs, satisfied by *math/rand/v2
+ Rand) so tests feed a deterministic stub and assert exact paths.
+ - Target is uniform within bounds and clamped to [0,width) x [0,height);
+ never negative, never >= width/height.
+ - Path is continuous: consecutive points differ by a bounded step (no
+ teleport); path length is on the order of ~20-60 steps.
+ - Path's last element equals the target.
+ - Edge cases covered by tests: cursor already at a corner; a 1x1 screen
+ (bounds width=1,height=1 -> only valid point is (0,0)); target equal to
+ current position (path is well-formed, ends at current point).
+ - Invalid bounds (width<=0 or height<=0) return an error, no panic.
+
+
+ Create Package-doc-free additions to `internal/activity/domain` (the package
+ doc already lives in activity.go). Define a random-source seam interface
+ named for its role (e.g. a source that yields an int in [0,n) and/or a
+ float in [0,1)); *math/rand/v2 Rand satisfies it via its existing methods —
+ keep the interface to only the methods actually used so it stays minimal and
+ lint-clean. Define a `Planner` type with a constructor and a single method
+ that plans a glide path: pick a uniform random target inside bounds, clamp
+ to [0,width) x [0,height), then interpolate from current position to target
+ over a bounded number of small steps, returning the ordered intermediate
+ points with the target as the final element. Choose a fixed step count in
+ the ~20-60 range (implementation detail); derive per-step deltas so no step
+ exceeds a bounded magnitude. Keep the file cgo-free and os-free (no time, no
+ C) so it builds under GOOS=linux. Respect the lint config: keep functions
+ under the funlen/cyclop limits (split helpers if needed), name any numeric
+ constants rather than leaving bare magic numbers in logic (mnd), and add
+ godot-compliant doc comments on exported identifiers.
+ Write `planner_test.go` (testify + a hand-injected deterministic source that
+ is NOT a mockgen mock — this is domain, no port involved) asserting the
+ behaviors above including all three edge cases.
+
+
+ go test -race ./internal/activity/domain/... && GOOS=linux GOARCH=amd64 go build ./internal/activity/domain/...
+
+ Planner tests pass with -race; domain package builds under GOOS=linux; targets proven in-bounds, path continuous and ending at target, all edge cases green.
+
+
+
+ Task 2: Reshape Pointer port and regenerate the mock
+ internal/activity/port/pointer.go, internal/activity/port/mock/mock_pointer.go
+
+ Rewrite `port/pointer.go`: replace `Nudge(dx, dy int) error` with an
+ absolute-movement, position-reading, bounds-reading port. Keep it cohesive
+ on a single `Pointer` interface (per spec this is your call — one port is
+ the most cohesive here): `MoveTo(x, y int) error`, `Position() (x, y int,
+ err error)`, and a bounds accessor returning main-display width/height (e.g.
+ `Bounds() (w, h int, err error)`). Update the `//go:generate mockgen`
+ directive to target `Pointer` with the new methods (destination and package
+ unchanged: `mock/mock_pointer.go`, package `mock`). Keep godot-compliant doc
+ comments. Then regenerate the mock by running the go:generate directive
+ (`cd internal/activity/port && go generate ./...`, using the pinned
+ go.uber.org/mock mockgen); do not hand-edit the generated file, and keep the
+ `// Code generated by MockGen. DO NOT EDIT.` header so it stays lint-exempt.
+ NOTE: this task intentionally leaves the tree non-building (service, adapter,
+ and main still reference the old API); Tasks 3-5 restore green. That is
+ acceptable within this coarse plan — the full build gate runs at Task 6.
+
+
+ go build ./internal/activity/port/... && grep -q 'func (m \*MockPointer) MoveTo' internal/activity/port/mock/mock_pointer.go && grep -q 'func (m \*MockPointer) Position' internal/activity/port/mock/mock_pointer.go && grep -q 'func (m \*MockPointer) Bounds' internal/activity/port/mock/mock_pointer.go
+
+ port package compiles; regenerated mock exposes MoveTo, Position, and Bounds; no Nudge remains in the port or mock.
+
+
+
+ Task 3: Rewrite KeeperService to roam once per tick + synctest/mock tests
+ internal/activity/service/keeper_service.go, internal/activity/service/keeper_service_test.go
+
+ - On each ticker tick: read current position via Position(), read bounds via
+ Bounds(), ask domain.Planner for a glide path, then call MoveTo for each
+ path point in order with a short inter-step pause.
+ - Exactly one roam per tick.
+ - ctx cancellation between steps stops the glide promptly (remaining MoveTo
+ calls are NOT made) and Run returns nil.
+ - ctx cancellation while idle on the ticker also returns nil promptly.
+ - Errors from Position/Bounds/MoveTo are logged and the tick is abandoned
+ without crashing (loop continues to next tick).
+ - Quiet/log behavior preserved via the injected *slog.Logger.
+
+
+ Rewrite `keeper_service.go`. `KeeperService` now depends on `port.Pointer`,
+ the injected `*slog.Logger`, a validated `domain.Interval`, and a
+ `*domain.Planner` (constructed in cmd with an injected random source). Drop
+ the `offset domain.Offset` field and the `nudgeCycle`/`nudgePause`
+ there-and-back logic entirely. Add a package constant for the inter-step
+ pause (a fraction of a few-hundred-ms glide; named constant, not a bare
+ literal, for mnd). In Run's tick handler: get Position, get Bounds, call the
+ planner for the path, then iterate the path calling MoveTo per point,
+ selecting between the pause timer and ctx.Done() between steps so a cancel
+ breaks out immediately; check ctx after the roam and return nil if done.
+ Keep functions under funlen/cyclop limits (extract a `roam(ctx)` helper).
+ Rewrite `keeper_service_test.go` using testify + the regenerated mockgen
+ mock + `testing/synctest`: assert one roam per tick, MoveTo called with the
+ planner's path points in order (use gomock ordered expectations / InOrder),
+ prompt stop on ctx cancel mid-glide (cancel after N MoveTo calls, assert no
+ further MoveTo), and idle-cancel returns nil. Feed the service a planner
+ built from a deterministic random source so expected MoveTo args are exact.
+
+
+ go test -race ./internal/activity/service/... && GOOS=linux GOARCH=amd64 go build ./internal/activity/service/...
+
+ Service tests pass with -race; service builds under GOOS=linux; mid-glide cancel proven to stop before remaining MoveTo calls; one roam per tick verified in order.
+
+
+
+ Task 4: CoreGraphics adapter — Position, Bounds, absolute MoveTo
+ internal/activity/adapter/cgpointer.go, internal/activity/adapter/cgpointer_test.go
+
+ Rewrite the cgo body in `cgpointer.go` (keep `//go:build darwin`). Replace
+ the relative `nudge` C helper with three helpers: current position via
+ `CGEventGetLocation` on a `CGEventCreate(NULL)` event; main-display bounds
+ via `CGDisplayBounds(CGMainDisplayID())` returning width/height; and an
+ absolute move that builds a MouseMoved event with
+ `CGEventCreateMouseEvent(NULL, kCGEventMouseMoved, CGPointMake(x,y),
+ kCGMouseButtonLeft)` and posts it with `CGEventPost(kCGHIDEventTap, ...)`.
+ Release EVERY CoreFoundation object created (CFRelease on each CGEventRef,
+ matching the existing pattern); on any NULL-create failure release nothing
+ NULL and signal failure. Implement the Go methods `Position() (x, y int,
+ err error)`, `Bounds() (w, h int, err error)`, and `MoveTo(x, y int) error`
+ on `CGPointer`, converting C doubles to int. Keep `AccessibilityTrusted()`
+ unchanged. Update `ErrNudgeFailed` naming to reflect the new operations
+ (e.g. a move-failed and a position/bounds-failed sentinel, errname-compliant
+ `Err...` names). Update `cgpointer_test.go` for the new API — this file is
+ darwin-only and typically asserts constructor/interface-conformance and
+ error sentinels rather than posting real events (no CI mouse movement).
+ Ensure `*CGPointer` still satisfies `port.Pointer` (compile-time assertion).
+
+
+ go build ./internal/activity/adapter/... && go vet ./internal/activity/adapter/...
+
+ adapter builds and vets under darwin; CGPointer implements Position, Bounds, MoveTo and still satisfies port.Pointer; every CFRelease pairs with its create.
+
+
+
+ Task 5: Wire main.go and remove dead nudge/Offset domain code
+ cmd/sysmon/main.go, internal/activity/domain/activity.go, internal/activity/domain/activity_test.go
+
+ Update `cmd/sysmon/main.go`: keep -interval (default 10s) and -quiet with
+ the same slog-level behavior. Remove the `nudgeOffset` constant, the
+ `domain.NewOffset` validation, and the offset argument to the service.
+ Construct a `*math/rand/v2 Rand` (seeded from a nondeterministic source such
+ as `rand.NewChaCha8` with a random seed or the top-level generator via
+ `rand.New` — runtime randomness, stdlib only), build the `domain.Planner`
+ with it, and pass planner + pointer + logger + validInterval into the
+ updated `service.NewKeeperService`. Update the flag help text and the
+ package/command doc comment to describe random roaming instead of the 1px
+ nudge. Keep the AccessibilityTrusted() preflight warn and the
+ signal.NotifyContext SIGINT/SIGTERM + clean exit 0 path. Then delete the now
+ dead domain offset code: remove `Offset`, `NewOffset`, and
+ `ErrNonPositiveOffset` from `activity.go` and their cases from
+ `activity_test.go`, keeping `Interval`/`NewInterval` intact. Fix the
+ package/file doc comments so no stale nudge references remain. Ensure no
+ literal string that a negative grep gate keys on is left in comments.
+
+
+ go build ./... && go test -race ./internal/activity/domain/... && ! grep -rn 'Nudge\|nudgeOffset\|NewOffset' cmd internal/activity/domain internal/activity/service internal/activity/port/pointer.go
+
+ Whole module builds; domain tests pass; no Nudge/Offset references remain outside the (now-removed) legacy paths; main wires planner + pointer + interval with runtime randomness and clean signal handling.
+
+
+
+ Task 6: Full-gate verification
+ (no source changes; verification only)
+
+ Run the complete gate set the task requires and fix any residual issues.
+ Confirm the runtime binary stays stdlib-only (inspect that only
+ math/rand/v2 and stdlib are imported by cmd/ and the non-adapter internal
+ packages) and that go.mod's require block still lists only testify and
+ go.uber.org/mock. Confirm the regenerated mock is lint-exempt (generated
+ header present) and that golangci-lint reports 0 issues. If any gate fails,
+ fix and re-run all gates.
+
+
+ go build ./... && golangci-lint run ./... && go test -race ./... && GOOS=linux GOARCH=amd64 go build ./internal/activity/domain/... ./internal/activity/port/... ./internal/activity/service/...
+
+ go build ./... clean; golangci-lint run ./... reports 0 issues; go test -race ./... passes; domain+port+service build under GOOS=linux/amd64; runtime deps unchanged (stdlib + math/rand/v2 only).
+
+
+
+
+
+Acceptance-criteria mapping (docs/TASK-roaming.md):
+- AC "cursor visibly glides to a new random on-screen point, multiple steps,
+ never off-screen, no drift" -> Tasks 1 (planner bounds/clamp/continuity),
+ 3 (service drives full path), 4 (absolute MoveTo).
+- AC "-interval controls the gap; -quiet raises log level" -> Tasks 3, 5.
+- AC "SIGINT/SIGTERM stops promptly incl. mid-glide; exit 0" -> Tasks 3
+ (mid-glide cancel), 5 (signal wiring + exit 0).
+- AC "runtime zero third-party deps; test deps unchanged" -> Tasks 5, 6.
+- AC "hexagonal layering intact (domain pure/cgo-free; service on domain+port;
+ cgo only in darwin adapter)" -> Tasks 1, 3 (GOOS=linux builds), 4 (build tag).
+- AC "go build / golangci-lint 0 issues / go test -race; GOOS=linux builds" ->
+ Task 6 full gate.
+- AC "planner and service covered incl. edge cases" -> Tasks 1, 3.
+
+
+
+All six tasks complete; Task 6 gate fully green; every docs/TASK-roaming.md
+acceptance checkbox is satisfiable by the delivered code and tests.
+
+
+
diff --git a/.planning/quick/260712-4ft-roaming-realistic-random-cursor-movement/REVIEW-2.md b/.planning/quick/260712-4ft-roaming-realistic-random-cursor-movement/REVIEW-2.md
new file mode 100644
index 0000000..89207bc
--- /dev/null
+++ b/.planning/quick/260712-4ft-roaming-realistic-random-cursor-movement/REVIEW-2.md
@@ -0,0 +1,145 @@
+---
+phase: quick-260712-roaming
+reviewed: 2026-07-12T00:00:00Z
+depth: standard
+files_reviewed: 9
+files_reviewed_list:
+ - internal/activity/domain/planner.go
+ - internal/activity/domain/planner_test.go
+ - internal/activity/domain/activity.go
+ - internal/activity/domain/activity_test.go
+ - internal/activity/port/pointer.go
+ - internal/activity/service/keeper_service.go
+ - internal/activity/service/keeper_service_test.go
+ - internal/activity/adapter/cgpointer.go
+ - internal/activity/adapter/cgpointer_test.go
+ - cmd/sysmon/main.go
+findings:
+ critical: 0
+ warning: 0
+ info: 2
+ total: 2
+status: issues_found
+---
+
+# Roaming Feature Review — Pass #2 (post review #1 fixes)
+
+**Reviewed:** 2026-07-12
+**Depth:** standard
+**Files Reviewed:** 10
+**Status:** issues_found (info-only; no blockers, no warnings)
+
+## Summary
+
+All five review #1 findings were verified fixed, correctly, with no regressions:
+
+- **CR-01 (clamp out-of-bounds start)** — fixed correctly. `Plan` now clamps
+ `curX`/`curY` via a new `clamp(v, size)` helper (`planner.go:73-74,84-92`)
+ before calling `interpolate`. Verified numerically for both directions
+ (`curX=-500` -> `0`, `curX=5000` with `width=1920` -> `1919`) and confirmed
+ that clamping both endpoints of a linear interpolation to `[0,size)` makes
+ every intermediate point provably in-bounds (lerp between two in-bounds
+ integers cannot overshoot either endpoint). Covered by the new
+ `TestPlanner_Plan_ClampsOutOfBoundsStart` test, which asserts every path
+ point stays in `[0,w) x [0,h)` starting from `(-500, 5000)` against a
+ `1920x1080` bound. `go test -race` passes.
+- **WR-01 (reuse one timer instead of `time.After` per step)** — fixed
+ correctly. `drive()` now allocates a single `time.NewTimer(stepPause)`
+ before the loop, calls `timer.Reset(stepPause)` after each `MoveTo`, and
+ `defer timer.Stop()` on function exit (`keeper_service.go:107-126`).
+ Verified this is correct under Go 1.26's timer semantics (this project's
+ `go.mod` requires `go 1.26.5`, well past the Go 1.23 timer-channel
+ redesign): `Reset` on an already-drained-by-select timer needs no manual
+ drain, and `Reset` on a timer that hasn/t fired yet (the first-iteration
+ case, since the timer is constructed already running) is likewise safe.
+ Traced a live (non-synctest) 40-iteration run of the identical loop shape
+ and confirmed no stale-fire drift (elapsed time tracked expected duration).
+ All `synctest`-based service tests (`TestKeeperService_MidGlideCancelStopsPromptly`
+ et al.) pass under `-race`, including the ctx-cancel-mid-glide path that
+ exercises the timer/ctx.Done() select race. No goroutine or timer leak: the
+ `defer timer.Stop()` runs on every return path (MoveTo error, ctx cancel,
+ natural path completion).
+- **WR-02 (rounding comment clarity)** — fixed; `roundingScale` doc comment
+ now spells out the round-half-up algebra (`planner.go:12-16`). Nit-level,
+ addressed as suggested.
+- **IN-01 (bounds re-read per roam)** — addressed with an explanatory comment
+ (`keeper_service.go:88-89`) noting this is intentional (picks up
+ resolution/monitor changes). No behavior change requested or made; correct.
+- **IN-02 (adapter `Bounds()` always-nil contract)** — addressed with an
+ expanded doc comment (`cgpointer.go:96-100`) documenting the containment
+ relationship with `domain.Planner`'s `ErrInvalidBounds` guard. Correct and
+ matches the actual code path.
+
+`go build ./...`, `go vet ./...`, `golangci-lint run ./...` (strict config,
+0 issues), and `go test -race -count=1 ./...` all pass. `GOOS=linux go build`
+succeeds for `domain`, `port`, and `service`. `gofmt -l` reports no files.
+Layering remains correct: domain has no cgo/os import, service imports only
+domain+port, cgo is confined to the adapter behind `//go:build darwin`, every
+`CGEventCreate*` is still paired with `CFRelease`.
+
+No new Critical or Warning-tier defects were introduced by the fix commit.
+Two Info-level nits found, one of which is a genuine (if harmless) doc-comment
+placement bug introduced by the fix itself.
+
+## Info
+
+### IN-01: Misplaced/orphaned doc comment left behind by the CR-01 test insertion
+
+**File:** `internal/activity/domain/planner_test.go:166-170, 191`
+**Issue:** The new `TestPlanner_Plan_ClampsOutOfBoundsStart` test (and its own
+correct doc comment) was inserted *before* `TestPlanner_Plan_EdgeCase_OnePixelScreen`
+in the file, but the original doc comment that belonged to
+`TestPlanner_Plan_EdgeCase_OnePixelScreen` (lines 166-167: "TestPlanner_Plan_EdgeCase_OnePixelScreen
+covers a 1x1 screen: the only valid point is (0, 0), so every path point must
+be (0, 0).") was left in place above the new test instead of being moved down
+with it. The result:
+- Lines 166-170 now read as one merged, incorrect comment block: two lines
+ that describe `TestPlanner_Plan_EdgeCase_OnePixelScreen` immediately
+ followed by two lines that describe `TestPlanner_Plan_ClampsOutOfBoundsStart`
+ -- all sitting directly above `func TestPlanner_Plan_ClampsOutOfBoundsStart`.
+- `TestPlanner_Plan_EdgeCase_OnePixelScreen` itself (line 191) now has no doc
+ comment at all.
+
+This is purely cosmetic (does not affect test correctness, `go vet`, or
+`golangci-lint`'s `godot` linter, which only checks comment punctuation, not
+semantic placement) but it is a genuine, real defect: a reader of this file
+will misread lines 166-167 as describing the function immediately below them.
+**Fix:** Move the orphaned comment down to sit above its correct function:
+```go
+}
+
+// TestPlanner_Plan_ClampsOutOfBoundsStart verifies that a starting position
+// outside the display bounds -- as Position() can report on a multi-monitor
+// setup -- is clamped, so no glide step lands off the main display.
+func TestPlanner_Plan_ClampsOutOfBoundsStart(t *testing.T) {
+ ...
+}
+
+// TestPlanner_Plan_EdgeCase_OnePixelScreen covers a 1x1 screen: the only
+// valid point is (0, 0), so every path point must be (0, 0).
+func TestPlanner_Plan_EdgeCase_OnePixelScreen(t *testing.T) {
+ ...
+}
+```
+
+### IN-02: No test exercises the exact upper-boundary clamp value (`curX == width`)
+
+**File:** `internal/activity/domain/planner_test.go:171-189`
+**Issue:** `TestPlanner_Plan_ClampsOutOfBoundsStart` covers a comfortably
+out-of-bounds start (`curX=-500`, `curY=5000` against `w=1920,h=1080`), which
+exercises both the `v < 0` and `v > size-1` branches of `clamp`, but not the
+exact boundary value `v == size` (e.g. `curX = 1920` for `width = 1920`),
+which is the smallest input that should still clamp to `size-1` via the
+`v > size-1` branch rather than passing through unclamped. The current
+implementation is correct at this boundary (verified numerically:
+`clamp(1920, 1920) == 1919`), so this is a coverage gap, not a bug.
+**Fix:** Add one boundary-value assertion, e.g. extend
+`TestPlanner_Plan_ClampsOutOfBoundsStart` (or a small table test) with
+`curX = width` and `curY = height` and assert the resulting path's first
+point has `X < width` and `Y < height`.
+
+---
+
+_Reviewed: 2026-07-12_
+_Reviewer: Claude (gsd-code-reviewer)_
+_Depth: standard_
diff --git a/.planning/quick/260712-4ft-roaming-realistic-random-cursor-movement/REVIEW.md b/.planning/quick/260712-4ft-roaming-realistic-random-cursor-movement/REVIEW.md
new file mode 100644
index 0000000..899ccf8
--- /dev/null
+++ b/.planning/quick/260712-4ft-roaming-realistic-random-cursor-movement/REVIEW.md
@@ -0,0 +1,209 @@
+---
+phase: quick-260712-roaming
+reviewed: 2026-07-12T00:00:00Z
+depth: standard
+files_reviewed: 9
+files_reviewed_list:
+ - internal/activity/domain/planner.go
+ - internal/activity/domain/planner_test.go
+ - internal/activity/domain/activity.go
+ - internal/activity/domain/activity_test.go
+ - internal/activity/port/pointer.go
+ - internal/activity/service/keeper_service.go
+ - internal/activity/service/keeper_service_test.go
+ - internal/activity/adapter/cgpointer.go
+ - internal/activity/adapter/cgpointer_test.go
+ - cmd/sysmon/main.go
+findings:
+ critical: 1
+ warning: 2
+ info: 2
+ total: 5
+status: issues_found
+---
+
+# Roaming Feature Review — Pass #1
+
+**Reviewed:** 2026-07-12
+**Depth:** standard
+**Files Reviewed:** 9 (+ cmd/sysmon/main_test.go read for context)
+**Status:** issues_found
+
+## Summary
+
+This is a well-built, small, hexagonally-clean feature. `go build ./...`,
+`golangci-lint run ./...` (0 issues), and `go test -race ./...` all pass;
+domain/port/service build under `GOOS=linux`. The `RandomSource` seam is
+minimal and correctly injected; planner tests are genuinely deterministic
+(verified `TestPlanner_Plan_DeterministicGivenSameSource`); the interpolation
+math was traced numerically (monotonic, bounded step, exact final-target
+arrival, no drift, correct for both positive and negative deltas via
+`floorDiv`) and is sound. cgo memory management in the adapter is correct:
+every `CGEventCreate*` is paired with `CFRelease`, `CGDisplayBounds`/
+`CGMainDisplayID` create no CF object (nothing to release), no `CFRelease(NULL)`
+path exists, `//go:build darwin` is present, and `*CGPointer` still satisfies
+`port.Pointer`. Layering is correct: domain has no cgo/os imports and builds
+under `GOOS=linux`; service imports only `domain` + `port`, never `adapter`.
+Ctx cancellation is checked between every `MoveTo` in `drive()`, and the
+mid-glide-cancel test proves no further `MoveTo` calls happen after cancel.
+
+One real correctness gap found against the acceptance criteria: the planner
+never clamps or validates the *current* position it interpolates from, only
+the random *target*. On a real multi-monitor Mac, `Position()` can legitimately
+return coordinates outside the main display's `[0,width)x[0,height)` (e.g. a
+secondary monitor placed to the left has negative global x). The domain layer
+silently interpolates from that out-of-bounds start, so the first several
+glide steps of a roam can be off the main display — directly contradicting the
+"never off-screen" acceptance criterion in a realistic, not contrived,
+scenario. See CR-01.
+
+## Critical Issues
+
+### CR-01: Glide path is not bounds-clamped when the current position is outside the main display
+
+**File:** `internal/activity/domain/planner.go:62-71`
+**Issue:** `Plan` validates `width`/`height` and draws a target uniformly in
+`[0,width) x [0,height)`, but `curX`/`curY` (the position `interpolate` glides
+*from*) are used as-is, with no clamping and no test coverage for the case
+where they fall outside `[0,width)x[0,height)`. On a real Mac with a
+secondary display, `CGEventGetLocation` (via `adapter.CGPointer.Position()`)
+returns coordinates in the *global* desktop coordinate space, not the main
+display's local space — a monitor placed to the left of the main display
+produces negative x, a monitor placed above produces negative y, and a
+monitor placed to the right/below produces x/y beyond the main display's
+width/height. Since `interpolate` linearly walks from `(curX, curY)` to the
+clamped target, the earliest steps of the glide remain off the main display
+(and can even be at negative coordinates) until the interpolation catches up.
+This is a direct violation of the spec's "whole screen, bounded... never
+off-screen" acceptance criterion (`docs/TASK-roaming.md:28-30`) and of
+`PLAN.md`'s truth "The cursor never leaves the main display bounds ... no
+cumulative drift". Verified numerically: `Plan`-equivalent interpolation from
+`curX=-500` to a target of `960` inside a `1920`-wide main display yields
+intermediate steps of `-463`, `-317`, ... — genuinely off-display coordinates
+posted via `MoveTo`.
+**Fix:** Clamp `curX`/`curY` into `[0,width) x [0,height)` before calling
+`interpolate`, so the glide always starts and stays inside the main display's
+bounds even if the OS-reported current position is elsewhere:
+```go
+func (p *Planner) Plan(curX, curY, width, height int) ([]Point, error) {
+ if width <= 0 || height <= 0 {
+ return nil, ErrInvalidBounds
+ }
+
+ curX = clamp(curX, width)
+ curY = clamp(curY, height)
+
+ targetX := p.rnd.IntN(width)
+ targetY := p.rnd.IntN(height)
+
+ return interpolate(curX, curY, targetX, targetY), nil
+}
+
+// clamp confines v to [0, n).
+func clamp(v, n int) int {
+ if v < 0 {
+ return 0
+ }
+ if v >= n {
+ return n - 1
+ }
+ return v
+}
+```
+Add a planner test with `curX`/`curY` outside `[0,width)x[0,height)` (both
+negative and >= bound) asserting every path point, including the first,
+stays within `[0,width)x[0,height)`.
+
+## Warnings
+
+### WR-01: `time.After` allocates a new timer every glide step instead of reusing one
+
+**File:** `internal/activity/service/keeper_service.go:112-116`
+**Issue:** `drive` calls `time.After(stepPause)` inside the per-point loop.
+Each call allocates a new `time.Timer` that is not eligible for reuse and,
+if `ctx.Done()` fires first, is never explicitly stopped (it is left to be
+GC'd once it fires ~8ms later). With `stepCount = 40`, a single roam
+allocates up to 40 timers. This is not a leak in the classic sense (they do
+get GC'd), but it is unidiomatic Go for a hot loop and is exactly the pattern
+`time.After`'s own godoc warns against reusing in tight loops. Given this
+project's stated efficiency goals (near-zero idle CPU / lightweight
+footprint), a single reused timer is the more correct pattern.
+**Fix:** Use one `time.NewTimer`, `Reset` it each iteration, and `Stop` it on
+early exit:
+```go
+func (k *KeeperService) drive(ctx context.Context, path []domain.Point) {
+ timer := time.NewTimer(stepPause)
+ defer timer.Stop()
+
+ for _, pt := range path {
+ if err := k.pointer.MoveTo(pt.X, pt.Y); err != nil {
+ k.logger.Error("move failed", "err", err)
+ return
+ }
+
+ select {
+ case <-timer.C:
+ timer.Reset(stepPause)
+ case <-ctx.Done():
+ return
+ }
+ }
+}
+```
+
+### WR-02: `roundingScale` name/doc slightly obscures the actual purpose (round-half-up bias, not "doubling the denominator" as an end in itself)
+
+**File:** `internal/activity/domain/planner.go:13-15, 103-110`
+**Issue:** The comment says "roundingScale doubles the interpolation
+denominator so integer division can round to the nearest pixel instead of
+truncating toward zero" — accurate, but the name `roundingScale` combined
+with the `lerpAxis` comment ("Round-to-nearest via adding half the
+denominator before truncating division") requires the reader to reconstruct
+that `roundingScale = 2` exists purely to let `+ total` represent "add half
+of `total*roundingScale`" without needing a fractional `total/2`. This is a
+classic round-half-up-via-integer-arithmetic trick; it works (verified
+numerically, monotonic and drift-free for a wide sweep of positive/negative
+deltas), but a reader unfamiliar with the trick has to work harder than
+necessary. Not a correctness issue — purely a readability nit.
+**Fix:** Consider renaming to `roundHalfScale` or adding one more line to the
+`lerpAxis` doc comment spelling out the algebra
+(`numerator/ (total*2) == round(delta*step/total)`), or extracting the
+`+ total` term into a named `halfStep := total * roundingScale / 2` — wait,
+that reintroduces truncation; simplest is just a slightly more explicit
+comment. Optional; low priority.
+
+## Info
+
+### IN-01: `Bounds()` is re-queried every tick even though the main display's dimensions essentially never change mid-session
+
+**File:** `internal/activity/service/keeper_service.go:88-92`
+**Issue:** Every `roam()` call re-reads `Bounds()` via cgo. This is not a
+performance defect in the sense that's in scope for this review (a single
+cgo call per 10s tick is trivially cheap), but it is worth noting for anyone
+later trying to reduce cgo call surface — genuinely out of v1 scope per the
+review lens, included here only as a nit.
+**Fix:** None required; no action needed unless display-bounds caching
+becomes desirable for other reasons (e.g. detecting external-display
+attach/detach mid-run, which is arguably a *feature*, not a bug).
+
+### IN-02: `getBounds`'s "always succeeds" comment is not fully defensive against a 0x0 or negative bounds return
+
+**File:** `internal/activity/adapter/cgpointer.go:27-34, 96-101`
+**Issue:** `Bounds()` trusts `CGDisplayBounds(CGMainDisplayID())` and never
+returns an error — reasonable per Apple's API contract (a running macOS
+session always has a main display with positive dimensions), but if this
+ever returned a degenerate rect (e.g. transient state during
+display-configuration change / sleep-wake), `int(w)`/`int(h)` could yield 0,
+and the resulting `Bounds()` values would flow straight into
+`domain.Planner.Plan`, which already returns `ErrInvalidBounds` for
+`width<=0 || height<=0` and is handled/logged by `roam()` without crashing.
+So the failure mode is already contained by the domain+service boundary;
+this is purely a note that the containment is implicit (relies on Plan's
+guard) rather than validated at the adapter boundary itself. No fix required
+given the existing containment; flagging for awareness only.
+
+---
+
+_Reviewed: 2026-07-12_
+_Reviewer: Claude (gsd-code-reviewer)_
+_Depth: standard_
diff --git a/.planning/quick/260712-4ft-roaming-realistic-random-cursor-movement/SUMMARY.md b/.planning/quick/260712-4ft-roaming-realistic-random-cursor-movement/SUMMARY.md
new file mode 100644
index 0000000..9b44e3c
--- /dev/null
+++ b/.planning/quick/260712-4ft-roaming-realistic-random-cursor-movement/SUMMARY.md
@@ -0,0 +1,28 @@
+---
+status: complete
+---
+
+# Quick task: realistic random cursor roaming
+
+Replaced the invisible 1px nudge with realistic random roaming. Each `-interval`
+tick, the cursor glides over ~40 small steps to a fresh uniform-random point
+within the main display bounds, honoring ctx cancellation between steps. Old
+`Nudge`/`Offset` code removed; `Interval` kept.
+
+- **domain**: pure `Planner` with an injected `RandomSource` seam (satisfied by
+ `*math/rand/v2.Rand`); clamped targets; deterministic tests (bounds,
+ continuity, ends-at-target, corner / 1x1 / target==current).
+- **port**: `Pointer` reshaped to `Position()` / `Bounds()` / `MoveTo(x,y)`;
+ mock regenerated via mockgen.
+- **service**: `KeeperService` roams once per tick, driving the path through
+ `MoveTo`; synctest + mock tests.
+- **adapter**: `CGPointer` implements Position/Bounds/MoveTo via CoreGraphics
+ (`//go:build darwin`), releasing every CoreFoundation object.
+- **cmd**: runtime-seeded `*rand.Rand` + planner injected; `-interval`/`-quiet`/
+ signal-exit-0 and the accessibility preflight unchanged.
+
+Runtime binary stays stdlib-only; test deps testify + go.uber.org/mock only.
+Gates green: `go build ./...`, `golangci-lint run ./...` (0 issues),
+`go test -race ./...`, and `GOOS=linux` build of domain/port/service.
+
+Branch: `feat/random-roaming` (commits 043c51a..5bc019b).
diff --git a/cmd/sysmon/main.go b/cmd/sysmon/main.go
index c18042d..bd08c7d 100644
--- a/cmd/sysmon/main.go
+++ b/cmd/sysmon/main.go
@@ -1,13 +1,15 @@
// Command sysmon keeps macOS "active" by posting a real mouse-move event on a
// fixed interval, which resets the system idle timer so the screen does not
-// sleep. The cursor is nudged one pixel and back, so it stays effectively in
-// place.
+// sleep. On each interval the cursor glides to a fresh random on-screen
+// point over several small steps, so the motion looks like a person actually
+// moving the mouse.
package main
import (
"context"
"flag"
"log/slog"
+ "math/rand/v2"
"os"
"os/signal"
"syscall"
@@ -18,12 +20,8 @@ import (
"sysmon/internal/activity/service"
)
-const (
- // defaultInterval is how often the cursor is nudged by default.
- defaultInterval = 10 * time.Second
- // nudgeOffset is the pixel shift applied then reversed on each nudge.
- nudgeOffset = 1
-)
+// defaultInterval is how often the cursor roams by default.
+const defaultInterval = 10 * time.Second
// Process exit codes.
const (
@@ -40,7 +38,7 @@ func main() {
// the process exit code. It is separated from main so that deferred cleanup
// (stopping the signal-notify context) always runs before the process exits.
func run() int {
- interval := flag.Duration("interval", defaultInterval, "how often to nudge the cursor (e.g. 10s, 30s, 1m)")
+ interval := flag.Duration("interval", defaultInterval, "how often to roam the cursor to a new random point (e.g. 10s, 30s, 1m)")
quiet := flag.Bool("quiet", false, "suppress routine logs; still print warnings and errors")
flag.Parse()
@@ -58,14 +56,6 @@ func run() int {
logger.Error("invalid interval", "err", err, "value", interval.String())
return exitUsage
}
- // nudgeOffset is a positive compile-time constant, so this never errors
- // today; it still goes through the domain constructor so the offset is
- // validated the same way as the interval.
- offset, err := domain.NewOffset(nudgeOffset)
- if err != nil {
- logger.Error("invalid offset", "err", err, "value", nudgeOffset)
- return exitUsage
- }
// Preflight: without Accessibility permission macOS silently drops the
// synthetic mouse events, so warn once at startup rather than looking like
@@ -78,7 +68,14 @@ func run() int {
defer stop()
pointer := adapter.NewCGPointer()
- keeper := service.NewKeeperService(pointer, logger, validInterval, offset)
+ // rand.NewPCG is seeded from the package-level generator, which
+ // math/rand/v2 auto-seeds from a nondeterministic runtime source. This
+ // gives the planner real runtime randomness while staying stdlib-only.
+ // Cursor-roaming targets are not security-sensitive, so a
+ // non-cryptographic PRNG is the right, stdlib-only tool here.
+ rnd := rand.New(rand.NewPCG(rand.Uint64(), rand.Uint64())) //nolint:gosec // roaming targets are not security-sensitive
+ planner := domain.NewPlanner(rnd)
+ keeper := service.NewKeeperService(pointer, logger, validInterval, planner)
if err := keeper.Run(ctx); err != nil {
logger.Error("sysmon exited with error", "err", err)
diff --git a/docs/TASK-roaming.md b/docs/TASK-roaming.md
new file mode 100644
index 0000000..218846f
--- /dev/null
+++ b/docs/TASK-roaming.md
@@ -0,0 +1,104 @@
+# Task: Realistic random cursor roaming
+
+## Goal
+
+Change sysmon's activity behavior from the current invisible 1px nudge-and-back
+to **realistic, random cursor roaming across the whole screen**. On each
+interval the cursor should glide to a new random on-screen point in a way that
+looks like a person actually moving the mouse -- a smooth multi-step path, not a
+teleport. Every interval picks a fresh random destination.
+
+This supersedes the Phase 1 nudge behavior. It still serves the same purpose
+(keep the machine active / idle timer reset) but the movement is now visible and
+human-like by design, which is what the user actually wants.
+
+## Motivation
+
+The 1px nudge kept the system awake but was imperceptible; the user wants the
+cursor to visibly roam as if in active use.
+
+## Functional requirements
+
+1. **Random destination each interval.** On every tick, choose a random target
+ point uniformly within the current screen bounds. Always a new random point.
+2. **Realistic glide.** Move to the target over several small steps with short
+ pauses between them, so the motion looks continuous and human, not an instant
+ jump. (Reasonable defaults: on the order of ~20-60 steps spread over a few
+ hundred milliseconds; exact numbers are implementation detail.)
+3. **Whole screen, bounded.** The cursor may go anywhere on the main display but
+ never off-screen. No cumulative drift (targets are absolute, clamped to
+ screen bounds).
+4. **Interval.** Reuse the existing `-interval` flag (default 10s). The interval
+ is the gap between the *start* of successive roams.
+5. **Interruptible.** SIGINT/SIGTERM must stop the loop promptly, including mid
+ glide (do not force-finish a long glide). Clean exit code 0.
+6. **Quiet mode.** `-quiet` keeps raising the log level (unchanged).
+
+## Non-functional requirements
+
+- **Runtime stays zero-dependency.** Use only the standard library
+ (`math/rand/v2` is fine) plus the existing cgo/CoreGraphics adapter. No new
+ third-party runtime deps.
+- **Lightweight.** Between roams the process sleeps on the ticker (near-zero idle
+ CPU). The glide is a brief burst of small moves, then idle again.
+- **Hexagonal architecture preserved** (see docs/TASK.md section 10).
+
+## Design (hexagonal placement)
+
+- **domain** -- a pure, deterministic movement planner. Given the current cursor
+ position, the screen bounds, and an injected random source, it produces the
+ sequence of intermediate points (the glide path) toward a random target.
+ - Inject the randomness (e.g. an interface or a `*rand.Rand`) so tests are
+ deterministic. The domain must stay free of cgo/os and build under
+ `GOOS=linux`.
+ - Targets are clamped to `[0, width) x [0, height)`.
+- **port** -- extend the driven side so the service can:
+ - read the current pointer position,
+ - read the screen bounds,
+ - move the pointer to an absolute (x, y).
+ Keep the port minimal and cohesive. The existing `Pointer.Nudge` may be
+ replaced by `MoveTo(x, y int) error` plus `Position() (x, y int, err error)`
+ and a screen-bounds accessor (either on the same port or a small `Screen`
+ port). Regenerate the mockgen mock from the updated interface(s).
+- **service** -- `KeeperService` (or a renamed keeper) on each tick asks the
+ planner for a glide path from the current position, then drives the adapter
+ through the path with the small inter-step pauses, honoring ctx cancellation
+ between steps.
+- **adapter** -- `CGPointer` gains the CoreGraphics implementations: current
+ position (`CGEventGetLocation`), screen bounds
+ (`CGDisplayBounds(CGMainDisplayID())`), and absolute move + posted
+ MouseMoved event. Keep it behind `//go:build darwin`, release every
+ CoreFoundation object.
+
+## Testing (locked stack -- see docs/prompts and testing conventions)
+
+- **testify** for assertions; **mockgen** (`go.uber.org/mock`) for mocks
+ generated from the updated port interface(s); **testing/synctest** for
+ deterministic timing. No hand-written fakes. No testcontainers.
+- Planner tests use an injected deterministic random source and assert:
+ targets are within bounds, path is continuous (steps bounded), path ends at
+ the target, edge cases (cursor already at a corner, 1x1 screen, target equals
+ current position).
+- Service tests (synctest + mock) assert: one roam per tick, the path is driven
+ through `MoveTo` in order, prompt stop on ctx cancel mid-glide, and quiet/log
+ behavior.
+- Domain + service stay cgo-free (`GOOS=linux go build`).
+
+## Acceptance criteria
+
+- [ ] On each interval the cursor visibly glides to a new random on-screen point,
+ smoothly (multiple steps), never off-screen, no drift.
+- [ ] `-interval` still controls the gap; `-quiet` still raises the log level.
+- [ ] SIGINT/SIGTERM stops promptly, including mid-glide; exit code 0.
+- [ ] Runtime binary has zero third-party dependencies; test-only deps unchanged.
+- [ ] Hexagonal layering intact: domain pure and cgo-free; service depends only
+ on domain + port; cgo only in adapter behind `//go:build darwin`.
+- [ ] `go build ./...`, `golangci-lint run ./...` (0 issues), `go test -race ./...`
+ all pass; domain + service build under `GOOS=linux`.
+- [ ] Planner and service covered by tests incl. edge cases.
+
+## Out of scope
+
+- Non-macOS adapters, LaunchAgent autostart, working-hours window (still v2).
+- Configurable glide speed/step count as user flags (may be a later follow-up;
+ sensible fixed defaults are enough here).
diff --git a/internal/activity/adapter/cgpointer.go b/internal/activity/adapter/cgpointer.go
index daea01f..8ee16fa 100644
--- a/internal/activity/adapter/cgpointer.go
+++ b/internal/activity/adapter/cgpointer.go
@@ -9,20 +9,37 @@ package adapter
#cgo LDFLAGS: -framework ApplicationServices -framework CoreGraphics
#include
-// nudge moves the cursor by (dx, dy) from its current position and posts a real
-// MouseMoved event -- that event is what resets the system idle timer, unlike a
-// plain cursor reposition. It returns 0 on success, or -1 if CoreGraphics could
-// not create an event (leaving the cursor untouched), so it never releases a
-// NULL reference.
-static int nudge(int dx, int dy) {
+// getPosition reads the current cursor location. It returns 0 on success (x
+// and y populated) or -1 if CoreGraphics could not create the query event,
+// leaving x and y untouched.
+static int getPosition(double *x, double *y) {
CGEventRef cur = CGEventCreate(NULL);
if (cur == NULL) {
return -1;
}
CGPoint p = CGEventGetLocation(cur);
CFRelease(cur);
+ *x = p.x;
+ *y = p.y;
+ return 0;
+}
- CGPoint np = CGPointMake(p.x + dx, p.y + dy);
+// getBounds reads the main display's width and height in pixels. It always
+// succeeds: CGDisplayBounds/CGMainDisplayID create no CoreFoundation object
+// that needs releasing.
+static void getBounds(double *w, double *h) {
+ CGRect bounds = CGDisplayBounds(CGMainDisplayID());
+ *w = bounds.size.width;
+ *h = bounds.size.height;
+}
+
+// moveTo posts a real MouseMoved event at the absolute point (x, y) -- that
+// event is what resets the system idle timer, unlike a plain cursor
+// reposition. It returns 0 on success, or -1 if CoreGraphics could not
+// create the event (leaving the cursor untouched), so it never releases a
+// NULL reference.
+static int moveTo(double x, double y) {
+ CGPoint np = CGPointMake(x, y);
CGEventRef move = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved, np, kCGMouseButtonLeft);
if (move == NULL) {
return -1;
@@ -40,26 +57,59 @@ static int accessibilityTrusted(void) {
*/
import "C"
-import "errors"
+import (
+ "errors"
+
+ "sysmon/internal/activity/port"
+)
-// ErrNudgeFailed is returned when CoreGraphics could not create the event
+// ErrPositionFailed is returned when CoreGraphics could not create the
+// event needed to read the pointer's current position.
+var ErrPositionFailed = errors.New("coregraphics failed to read pointer position")
+
+// ErrMoveFailed is returned when CoreGraphics could not create the event
// needed to move the pointer. The cursor is left untouched in that case.
-var ErrNudgeFailed = errors.New("coregraphics failed to create mouse event")
+var ErrMoveFailed = errors.New("coregraphics failed to create mouse event")
// CGPointer implements port.Pointer using CoreGraphics on macOS.
type CGPointer struct{}
+// Compile-time assertion that *CGPointer still satisfies port.Pointer.
+var _ port.Pointer = (*CGPointer)(nil)
+
// NewCGPointer constructs a CGPointer.
func NewCGPointer() *CGPointer {
return &CGPointer{}
}
-// Nudge moves the system pointer by (dx, dy) and posts a real MouseMoved event
-// via CoreGraphics. It returns ErrNudgeFailed if the event could not be created
-// (the cursor is left untouched in that case).
-func (c *CGPointer) Nudge(dx, dy int) error {
- if C.nudge(C.int(dx), C.int(dy)) != 0 {
- return ErrNudgeFailed
+// Position returns the pointer's current (x, y) location in screen pixels.
+// It returns ErrPositionFailed if CoreGraphics could not create the query
+// event.
+func (c *CGPointer) Position() (int, int, error) {
+ var x, y C.double
+ if C.getPosition(&x, &y) != 0 {
+ return 0, 0, ErrPositionFailed
+ }
+ return int(x), int(y), nil
+}
+
+// Bounds returns the main display's width and height in pixels. The error is
+// always nil here: CGDisplayBounds(CGMainDisplayID()) always yields positive
+// dimensions for the main display. The error is kept in the signature for
+// interface symmetry (other adapters may fail) and because domain.Planner
+// still guards non-positive bounds with ErrInvalidBounds.
+func (c *CGPointer) Bounds() (int, int, error) {
+ var w, h C.double
+ C.getBounds(&w, &h)
+ return int(w), int(h), nil
+}
+
+// MoveTo posts a real MouseMoved event placing the pointer at the absolute
+// (x, y) location via CoreGraphics. It returns ErrMoveFailed if the event
+// could not be created (the cursor is left untouched in that case).
+func (c *CGPointer) MoveTo(x, y int) error {
+ if C.moveTo(C.double(x), C.double(y)) != 0 {
+ return ErrMoveFailed
}
return nil
}
diff --git a/internal/activity/adapter/cgpointer_test.go b/internal/activity/adapter/cgpointer_test.go
index 0da2717..77e4d51 100644
--- a/internal/activity/adapter/cgpointer_test.go
+++ b/internal/activity/adapter/cgpointer_test.go
@@ -9,29 +9,66 @@ import (
"github.com/stretchr/testify/require"
"sysmon/internal/activity/adapter"
+ "sysmon/internal/activity/port"
)
-// TestNewCGPointer asserts construction never returns nil.
+// TestNewCGPointer asserts construction never returns nil and that CGPointer
+// satisfies port.Pointer.
func TestNewCGPointer(t *testing.T) {
t.Parallel()
p := adapter.NewCGPointer()
require.NotNil(t, p)
+
+ var _ port.Pointer = p
+}
+
+// TestCGPointer_Position_Succeeds is a non-disruptive smoke test: reading
+// the current position never moves the cursor, so it is safe to run in CI
+// regardless of Accessibility permission (CoreGraphics can read the cursor
+// location without that permission).
+func TestCGPointer_Position_Succeeds(t *testing.T) {
+ t.Parallel()
+
+ p := adapter.NewCGPointer()
+
+ x, y, err := p.Position()
+
+ require.NoError(t, err)
+ assert.GreaterOrEqual(t, x, 0)
+ assert.GreaterOrEqual(t, y, 0)
}
-// TestCGPointer_Nudge_ZeroOffset is a non-disruptive smoke test: a (0, 0)
-// nudge posts a real MouseMoved event at the cursor's current location, so
-// the cursor does not visibly move regardless of whether the test process
-// has macOS Accessibility permission. CoreGraphics can still create and post
-// the event without that permission (the event is only silently dropped by
-// the system on delivery), so this call is expected to succeed in CI.
-func TestCGPointer_Nudge_ZeroOffset(t *testing.T) {
+// TestCGPointer_Bounds_ReturnsPositiveDimensions asserts the main display's
+// bounds are read as positive width/height.
+func TestCGPointer_Bounds_ReturnsPositiveDimensions(t *testing.T) {
t.Parallel()
p := adapter.NewCGPointer()
- err := p.Nudge(0, 0)
+ w, h, err := p.Bounds()
+
+ require.NoError(t, err)
+ assert.Positive(t, w)
+ assert.Positive(t, h)
+}
+
+// TestCGPointer_MoveTo_ToCurrentPosition is a non-disruptive smoke test:
+// moving to the cursor's own current position posts a real MouseMoved event
+// without visibly moving the cursor, so it is expected to succeed in CI
+// regardless of whether the test process has macOS Accessibility permission
+// (CoreGraphics can still create and post the event; the system only drops
+// it silently on delivery without that permission).
+func TestCGPointer_MoveTo_ToCurrentPosition(t *testing.T) {
+ t.Parallel()
+
+ p := adapter.NewCGPointer()
+
+ x, y, err := p.Position()
+ require.NoError(t, err)
+
+ err = p.MoveTo(x, y)
require.NoError(t, err)
}
diff --git a/internal/activity/domain/activity.go b/internal/activity/domain/activity.go
index 1ee162a..7e4cfd0 100644
--- a/internal/activity/domain/activity.go
+++ b/internal/activity/domain/activity.go
@@ -13,11 +13,7 @@ import (
// to NewInterval.
var ErrNonPositiveInterval = errors.New("interval must be greater than zero")
-// ErrNonPositiveOffset is returned when a non-positive pixel value is
-// supplied to NewOffset.
-var ErrNonPositiveOffset = errors.New("offset must be greater than zero")
-
-// Interval is a validated positive duration between nudges.
+// Interval is a validated positive duration between roams.
type Interval struct {
d time.Duration
}
@@ -36,21 +32,3 @@ func NewInterval(d time.Duration) (Interval, error) {
func (i Interval) Duration() time.Duration {
return i.d
}
-
-// Offset is the validated pixel shift magnitude applied then reversed on
-// each nudge.
-type Offset int
-
-// NewOffset validates px and returns an Offset wrapping it. It rejects any
-// value that is zero or negative.
-func NewOffset(px int) (Offset, error) {
- if px <= 0 {
- return 0, ErrNonPositiveOffset
- }
- return Offset(px), nil
-}
-
-// Int returns the wrapped pixel value.
-func (o Offset) Int() int {
- return int(o)
-}
diff --git a/internal/activity/domain/activity_test.go b/internal/activity/domain/activity_test.go
index d66d447..527fb7e 100644
--- a/internal/activity/domain/activity_test.go
+++ b/internal/activity/domain/activity_test.go
@@ -46,39 +46,6 @@ func TestNewInterval(t *testing.T) {
}
}
-func TestNewOffset(t *testing.T) {
- t.Parallel()
-
- tests := []struct {
- name string
- px int
- wantErr bool
- }{
- {name: "positive offset is accepted", px: 1, wantErr: false},
- {name: "zero offset is rejected", px: 0, wantErr: true},
- {name: "negative offset is rejected", px: -1, wantErr: true},
- {name: "very large offset is accepted (boundary)", px: math.MaxInt, wantErr: false},
- {name: "math.MinInt offset is rejected (boundary)", px: math.MinInt, wantErr: true},
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- t.Parallel()
-
- got, err := domain.NewOffset(tt.px)
-
- if tt.wantErr {
- require.ErrorIs(t, err, domain.ErrNonPositiveOffset)
- assert.Equal(t, domain.Offset(0), got)
- return
- }
-
- require.NoError(t, err)
- assert.Equal(t, tt.px, got.Int())
- })
- }
-}
-
// TestInterval_Duration_RoundTrip asserts that Duration() returns exactly the
// value passed to NewInterval, with no rounding or truncation.
func TestInterval_Duration_RoundTrip(t *testing.T) {
@@ -99,27 +66,3 @@ func TestInterval_Duration_RoundTrip(t *testing.T) {
assert.Equal(t, d, iv.Duration())
}
}
-
-// TestOffset_Int_RoundTrip asserts that Int() returns exactly the pixel value
-// passed to NewOffset.
-func TestOffset_Int_RoundTrip(t *testing.T) {
- t.Parallel()
-
- values := []int{1, 2, 40, 1000, math.MaxInt}
-
- for _, px := range values {
- off, err := domain.NewOffset(px)
- require.NoError(t, err)
- assert.Equal(t, px, off.Int())
- }
-}
-
-// TestErrorsAreDistinct guards against a future refactor accidentally
-// aliasing the two sentinel errors, which would make errors.Is checks
-// ambiguous between Interval and Offset validation failures.
-func TestErrorsAreDistinct(t *testing.T) {
- t.Parallel()
-
- require.NotErrorIs(t, domain.ErrNonPositiveInterval, domain.ErrNonPositiveOffset)
- require.NotErrorIs(t, domain.ErrNonPositiveOffset, domain.ErrNonPositiveInterval)
-}
diff --git a/internal/activity/domain/planner.go b/internal/activity/domain/planner.go
new file mode 100644
index 0000000..f914807
--- /dev/null
+++ b/internal/activity/domain/planner.go
@@ -0,0 +1,141 @@
+package domain
+
+import "errors"
+
+// Movement planning constants. stepCount is fixed rather than configurable:
+// it is an implementation detail of what "looks like a human glide" (see
+// docs/TASK-roaming.md), not a user-facing setting.
+const (
+ // stepCount is the number of intermediate points a glide path is split
+ // into, chosen to land in the human-like ~20-60 step range.
+ stepCount = 40
+ // roundingScale doubles both the numerator and denominator of the
+ // interpolation division. That lets us add `total` (which equals half of
+ // the doubled denominator) before dividing, implementing round-half-up to
+ // the nearest pixel instead of truncation toward zero.
+ roundingScale = 2
+)
+
+// ErrInvalidBounds is returned when Plan is given a non-positive width or
+// height, since a zero or negative screen dimension has no valid target
+// point.
+var ErrInvalidBounds = errors.New("bounds must be positive")
+
+// RandomSource is the minimal seam through which Planner draws randomness.
+// It is satisfied by *math/rand/v2.Rand (via its IntN method), so production
+// code can inject real runtime randomness while tests inject a deterministic
+// stub. The interface only lists the method Planner actually calls, keeping
+// it minimal.
+type RandomSource interface {
+ // IntN returns a pseudo-random int in [0, n). It must not be called with
+ // n <= 0.
+ IntN(n int) int
+}
+
+// Point is a single (x, y) coordinate of a glide path, in screen pixels.
+type Point struct {
+ X int
+ Y int
+}
+
+// Planner produces glide paths for the cursor-roaming use case: given a
+// current position and screen bounds, it plans a sequence of small steps
+// ending at a fresh uniformly-random target. Planner is pure and
+// deterministic given its injected RandomSource, has no cgo or os
+// dependency, and builds under GOOS=linux.
+type Planner struct {
+ rnd RandomSource
+}
+
+// NewPlanner constructs a Planner using rnd as its source of randomness.
+func NewPlanner(rnd RandomSource) *Planner {
+ return &Planner{rnd: rnd}
+}
+
+// Plan returns an ordered glide path from (curX, curY) to a fresh uniformly
+// random target inside [0, width) x [0, height), clamped to those bounds.
+// The path is continuous (no teleporting step) and its last element is
+// always exactly the target. width and height must be positive, or Plan
+// returns ErrInvalidBounds. When the screen is 1x1, the only valid point is
+// (0, 0) and Plan returns a path that stays there. When the random target
+// equals the current position, Plan still returns a well-formed path ending
+// at that same point.
+func (p *Planner) Plan(curX, curY, width, height int) ([]Point, error) {
+ if width <= 0 || height <= 0 {
+ return nil, ErrInvalidBounds
+ }
+
+ // Clamp the starting position into this display's bounds before planning.
+ // Position() can report global desktop coordinates -- negative, or beyond
+ // the main display -- when the cursor sits on a secondary monitor.
+ // Interpolating from an out-of-bounds start would send the first glide
+ // steps off-screen, violating the "never off-screen" guarantee.
+ curX = clamp(curX, width)
+ curY = clamp(curY, height)
+
+ targetX := p.rnd.IntN(width)
+ targetY := p.rnd.IntN(height)
+
+ return interpolate(curX, curY, targetX, targetY), nil
+}
+
+// clamp constrains v to the valid pixel range [0, size-1] for an axis of the
+// given size. size is guaranteed positive by the caller.
+func clamp(v, size int) int {
+ if v < 0 {
+ return 0
+ }
+ if v > size-1 {
+ return size - 1
+ }
+ return v
+}
+
+// interpolate builds the ordered intermediate points from (fromX, fromY) to
+// (toX, toY) over stepCount steps, with the final element exactly equal to
+// the target. Using integer division with rounding at each step keeps every
+// step's delta bounded and avoids cumulative drift, since the last step
+// always lands exactly on the target rather than an accumulated
+// approximation.
+func interpolate(fromX, fromY, toX, toY int) []Point {
+ path := make([]Point, 0, stepCount)
+
+ for i := 1; i <= stepCount; i++ {
+ path = append(path, lerpPoint(fromX, fromY, toX, toY, i, stepCount))
+ }
+
+ // Guarantee exact arrival regardless of integer rounding above.
+ path[len(path)-1] = Point{X: toX, Y: toY}
+
+ return path
+}
+
+// lerpPoint linearly interpolates between (fromX, fromY) and (toX, toY) at
+// step/total of the way there, rounding to the nearest integer pixel.
+func lerpPoint(fromX, fromY, toX, toY, step, total int) Point {
+ return Point{
+ X: lerpAxis(fromX, toX, step, total),
+ Y: lerpAxis(fromY, toY, step, total),
+ }
+}
+
+// lerpAxis linearly interpolates a single axis between from and to at
+// step/total of the way there, rounding to the nearest integer.
+func lerpAxis(from, to, step, total int) int {
+ delta := to - from
+ // Round-to-nearest via adding half the denominator before truncating
+ // division, handling negative delta correctly since total is always
+ // positive.
+ numerator := delta*step*roundingScale + total
+ return from + floorDiv(numerator, total*roundingScale)
+}
+
+// floorDiv returns the floor of a/b for a positive b, matching mathematical
+// rounding for both positive and negative a (unlike Go's truncating "/").
+func floorDiv(a, b int) int {
+ q := a / b
+ if a%b != 0 && (a < 0) != (b < 0) {
+ q--
+ }
+ return q
+}
diff --git a/internal/activity/domain/planner_test.go b/internal/activity/domain/planner_test.go
new file mode 100644
index 0000000..f05b58b
--- /dev/null
+++ b/internal/activity/domain/planner_test.go
@@ -0,0 +1,347 @@
+package domain_test
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "sysmon/internal/activity/domain"
+)
+
+// stubSource is a hand-injected deterministic domain.RandomSource -- NOT a
+// mockgen mock, since this is a domain test with no port involved. It
+// returns each value in seq in order, then repeats the last value forever
+// (so a test only needs to specify as many draws as it cares about).
+type stubSource struct {
+ seq []int
+ i int
+}
+
+func newStubSource(seq ...int) *stubSource {
+ return &stubSource{seq: seq}
+}
+
+func (s *stubSource) IntN(n int) int {
+ var v int
+ if s.i < len(s.seq) {
+ v = s.seq[s.i]
+ s.i++
+ } else if len(s.seq) > 0 {
+ v = s.seq[len(s.seq)-1]
+ }
+ if v >= n {
+ v = n - 1
+ }
+ if v < 0 {
+ v = 0
+ }
+ return v
+}
+
+func TestPlanner_Plan_TargetWithinBoundsAndPathEndsAtTarget(t *testing.T) {
+ t.Parallel()
+
+ rnd := newStubSource(37, 12)
+ p := domain.NewPlanner(rnd)
+
+ path, err := p.Plan(0, 0, 100, 50)
+
+ require.NoError(t, err)
+ require.NotEmpty(t, path)
+
+ last := path[len(path)-1]
+ assert.Equal(t, 37, last.X)
+ assert.Equal(t, 12, last.Y)
+
+ for _, pt := range path {
+ assert.GreaterOrEqual(t, pt.X, 0)
+ assert.Less(t, pt.X, 100)
+ assert.GreaterOrEqual(t, pt.Y, 0)
+ assert.Less(t, pt.Y, 50)
+ }
+}
+
+func TestPlanner_Plan_PathLengthInHumanRange(t *testing.T) {
+ t.Parallel()
+
+ rnd := newStubSource(80, 40)
+ p := domain.NewPlanner(rnd)
+
+ path, err := p.Plan(0, 0, 100, 100)
+
+ require.NoError(t, err)
+ assert.GreaterOrEqual(t, len(path), 20)
+ assert.LessOrEqual(t, len(path), 60)
+}
+
+func TestPlanner_Plan_PathIsContinuousNoTeleport(t *testing.T) {
+ t.Parallel()
+
+ rnd := newStubSource(999, 1)
+ p := domain.NewPlanner(rnd)
+
+ // Start far from the (clamped) target so the bounded-step property is
+ // actually exercised over a large distance.
+ path, err := p.Plan(0, 0, 1000, 2)
+
+ require.NoError(t, err)
+ require.NotEmpty(t, path)
+
+ const maxStepMagnitude = 100 // generous bound: total distance / (stepCount/2)
+
+ prevX, prevY := 0, 0
+ for _, pt := range path {
+ dx := pt.X - prevX
+ if dx < 0 {
+ dx = -dx
+ }
+ dy := pt.Y - prevY
+ if dy < 0 {
+ dy = -dy
+ }
+ assert.LessOrEqual(t, dx, maxStepMagnitude, "step in X exceeded bounded magnitude")
+ assert.LessOrEqual(t, dy, maxStepMagnitude, "step in Y exceeded bounded magnitude")
+ prevX, prevY = pt.X, pt.Y
+ }
+}
+
+func TestPlanner_Plan_InvalidBounds(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ width int
+ height int
+ }{
+ {name: "zero width", width: 0, height: 10},
+ {name: "zero height", width: 10, height: 0},
+ {name: "negative width", width: -5, height: 10},
+ {name: "negative height", width: 10, height: -5},
+ {name: "both zero", width: 0, height: 0},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ rnd := newStubSource(0, 0)
+ p := domain.NewPlanner(rnd)
+
+ path, err := p.Plan(0, 0, tt.width, tt.height)
+
+ require.ErrorIs(t, err, domain.ErrInvalidBounds)
+ assert.Nil(t, path)
+ })
+ }
+}
+
+// TestPlanner_Plan_EdgeCase_CursorAlreadyAtCorner covers the cursor starting
+// exactly at a bounds corner: the path must still stay in-bounds and end at
+// the (possibly distant) random target.
+func TestPlanner_Plan_EdgeCase_CursorAlreadyAtCorner(t *testing.T) {
+ t.Parallel()
+
+ rnd := newStubSource(0, 0)
+ p := domain.NewPlanner(rnd)
+
+ // Cursor starts at the bottom-right corner of a 200x100 screen.
+ path, err := p.Plan(199, 99, 200, 100)
+
+ require.NoError(t, err)
+ require.NotEmpty(t, path)
+
+ last := path[len(path)-1]
+ assert.Equal(t, 0, last.X)
+ assert.Equal(t, 0, last.Y)
+
+ for _, pt := range path {
+ assert.GreaterOrEqual(t, pt.X, 0)
+ assert.Less(t, pt.X, 200)
+ assert.GreaterOrEqual(t, pt.Y, 0)
+ assert.Less(t, pt.Y, 100)
+ }
+}
+
+// TestPlanner_Plan_ClampsOutOfBoundsStart verifies that a starting position
+// outside the display bounds -- as Position() can report on a multi-monitor
+// setup -- is clamped, so no glide step lands off the main display. It covers
+// negative, far-positive, and exact-boundary (curX == width) starts.
+func TestPlanner_Plan_ClampsOutOfBoundsStart(t *testing.T) {
+ t.Parallel()
+
+ const w, h = 1920, 1080
+
+ starts := []struct {
+ name string
+ curX, curY int
+ }{
+ {"negative both", -500, -9000},
+ {"far positive both", 999999, 5000},
+ {"exact boundary equals size", w, h},
+ {"mixed sign", -1, h + 1},
+ }
+
+ for _, s := range starts {
+ t.Run(s.name, func(t *testing.T) {
+ t.Parallel()
+
+ p := domain.NewPlanner(newStubSource(100, 200))
+
+ path, err := p.Plan(s.curX, s.curY, w, h)
+ require.NoError(t, err)
+ require.NotEmpty(t, path)
+
+ for _, pt := range path {
+ assert.GreaterOrEqual(t, pt.X, 0)
+ assert.Less(t, pt.X, w)
+ assert.GreaterOrEqual(t, pt.Y, 0)
+ assert.Less(t, pt.Y, h)
+ }
+ })
+ }
+}
+
+// TestPlanner_Plan_EdgeCase_OnePixelScreen covers a 1x1 screen: the only valid
+// point is (0, 0), so every path point must be (0, 0).
+func TestPlanner_Plan_EdgeCase_OnePixelScreen(t *testing.T) {
+ t.Parallel()
+
+ rnd := newStubSource(0, 0)
+ p := domain.NewPlanner(rnd)
+
+ path, err := p.Plan(0, 0, 1, 1)
+
+ require.NoError(t, err)
+ require.NotEmpty(t, path)
+
+ for _, pt := range path {
+ assert.Equal(t, domain.Point{X: 0, Y: 0}, pt)
+ }
+}
+
+// TestPlanner_Plan_EdgeCase_TargetEqualsCurrent covers a random draw that
+// lands exactly on the current position: the path must still be
+// well-formed (right length, in-bounds) and every point equals the current
+// position since there is nowhere to glide to.
+func TestPlanner_Plan_EdgeCase_TargetEqualsCurrent(t *testing.T) {
+ t.Parallel()
+
+ rnd := newStubSource(42, 17)
+ p := domain.NewPlanner(rnd)
+
+ path, err := p.Plan(42, 17, 100, 100)
+
+ require.NoError(t, err)
+ require.NotEmpty(t, path)
+
+ for _, pt := range path {
+ assert.Equal(t, domain.Point{X: 42, Y: 17}, pt)
+ }
+
+ last := path[len(path)-1]
+ assert.Equal(t, 42, last.X)
+ assert.Equal(t, 17, last.Y)
+}
+
+// TestPlanner_Plan_VeryLargeScreen covers a very large screen resolution
+// (e.g. a wide multi-monitor span): the target must still land within
+// bounds and the path must end exactly at it.
+func TestPlanner_Plan_VeryLargeScreen(t *testing.T) {
+ t.Parallel()
+
+ const w, h = 8000, 5000
+
+ rnd := newStubSource(7999, 4999)
+ p := domain.NewPlanner(rnd)
+
+ path, err := p.Plan(0, 0, w, h)
+
+ require.NoError(t, err)
+ require.NotEmpty(t, path)
+
+ last := path[len(path)-1]
+ assert.Equal(t, 7999, last.X)
+ assert.Equal(t, 4999, last.Y)
+
+ for _, pt := range path {
+ assert.GreaterOrEqual(t, pt.X, 0)
+ assert.Less(t, pt.X, w)
+ assert.GreaterOrEqual(t, pt.Y, 0)
+ assert.Less(t, pt.Y, h)
+ }
+}
+
+// TestPlanner_Plan_BoundedStepDeltaFarStartToFarTarget asserts that gliding
+// across a very large screen -- from one far corner to the opposite one --
+// still produces a path where every consecutive step's delta is bounded
+// (no single giant jump), by checking the largest observed step is well
+// under a naive direct-distance/1 jump.
+func TestPlanner_Plan_BoundedStepDeltaFarStartToFarTarget(t *testing.T) {
+ t.Parallel()
+
+ const w, h = 8000, 5000
+
+ rnd := newStubSource(w-1, h-1)
+ p := domain.NewPlanner(rnd)
+
+ path, err := p.Plan(0, 0, w, h)
+ require.NoError(t, err)
+ require.NotEmpty(t, path)
+
+ // A single unbounded jump would be up to ~(w-1) or ~(h-1) in one step.
+ // With stepCount steps spreading the distance evenly, each step should
+ // be roughly distance/stepCount; allow a generous margin above that.
+ const maxStepMagnitude = 500
+
+ prevX, prevY := 0, 0
+ for _, pt := range path {
+ dx := pt.X - prevX
+ if dx < 0 {
+ dx = -dx
+ }
+ dy := pt.Y - prevY
+ if dy < 0 {
+ dy = -dy
+ }
+ assert.LessOrEqual(t, dx, maxStepMagnitude, "step in X exceeded bounded magnitude")
+ assert.LessOrEqual(t, dy, maxStepMagnitude, "step in Y exceeded bounded magnitude")
+ prevX, prevY = pt.X, pt.Y
+ }
+}
+
+// TestPlanner_Plan_DeterministicGivenSameSource asserts that two Planners
+// fed the same sequence of draws produce byte-for-byte identical paths --
+// the core determinism guarantee the injected RandomSource seam exists for.
+func TestPlanner_Plan_DeterministicGivenSameSource(t *testing.T) {
+ t.Parallel()
+
+ p1 := domain.NewPlanner(newStubSource(55, 23))
+ p2 := domain.NewPlanner(newStubSource(55, 23))
+
+ path1, err1 := p1.Plan(10, 10, 200, 150)
+ path2, err2 := p2.Plan(10, 10, 200, 150)
+
+ require.NoError(t, err1)
+ require.NoError(t, err2)
+ assert.Equal(t, path1, path2)
+}
+
+// TestPlanner_Plan_DifferentSeedProducesDifferentPath complements
+// TestPlanner_Plan_DeterministicGivenSameSource: a different draw sequence
+// (different "seed") from the same starting position must produce a
+// distinct path, confirming the path is actually a function of the injected
+// randomness rather than a constant.
+func TestPlanner_Plan_DifferentSeedProducesDifferentPath(t *testing.T) {
+ t.Parallel()
+
+ p1 := domain.NewPlanner(newStubSource(55, 23))
+ p2 := domain.NewPlanner(newStubSource(90, 61))
+
+ path1, err1 := p1.Plan(10, 10, 200, 150)
+ path2, err2 := p2.Plan(10, 10, 200, 150)
+
+ require.NoError(t, err1)
+ require.NoError(t, err2)
+ assert.NotEqual(t, path1, path2)
+}
diff --git a/internal/activity/port/mock/mock_pointer.go b/internal/activity/port/mock/mock_pointer.go
index afbd82a..4a0cb1a 100644
--- a/internal/activity/port/mock/mock_pointer.go
+++ b/internal/activity/port/mock/mock_pointer.go
@@ -39,16 +39,48 @@ func (m *MockPointer) EXPECT() *MockPointerMockRecorder {
return m.recorder
}
-// Nudge mocks base method.
-func (m *MockPointer) Nudge(dx, dy int) error {
+// Bounds mocks base method.
+func (m *MockPointer) Bounds() (int, int, error) {
m.ctrl.T.Helper()
- ret := m.ctrl.Call(m, "Nudge", dx, dy)
+ ret := m.ctrl.Call(m, "Bounds")
+ ret0, _ := ret[0].(int)
+ ret1, _ := ret[1].(int)
+ ret2, _ := ret[2].(error)
+ return ret0, ret1, ret2
+}
+
+// Bounds indicates an expected call of Bounds.
+func (mr *MockPointerMockRecorder) Bounds() *gomock.Call {
+ mr.mock.ctrl.T.Helper()
+ return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bounds", reflect.TypeOf((*MockPointer)(nil).Bounds))
+}
+
+// MoveTo mocks base method.
+func (m *MockPointer) MoveTo(x, y int) error {
+ m.ctrl.T.Helper()
+ ret := m.ctrl.Call(m, "MoveTo", x, y)
ret0, _ := ret[0].(error)
return ret0
}
-// Nudge indicates an expected call of Nudge.
-func (mr *MockPointerMockRecorder) Nudge(dx, dy any) *gomock.Call {
+// MoveTo indicates an expected call of MoveTo.
+func (mr *MockPointerMockRecorder) MoveTo(x, y any) *gomock.Call {
+ mr.mock.ctrl.T.Helper()
+ return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MoveTo", reflect.TypeOf((*MockPointer)(nil).MoveTo), x, y)
+}
+
+// Position mocks base method.
+func (m *MockPointer) Position() (int, int, error) {
+ m.ctrl.T.Helper()
+ ret := m.ctrl.Call(m, "Position")
+ ret0, _ := ret[0].(int)
+ ret1, _ := ret[1].(int)
+ ret2, _ := ret[2].(error)
+ return ret0, ret1, ret2
+}
+
+// Position indicates an expected call of Position.
+func (mr *MockPointerMockRecorder) Position() *gomock.Call {
mr.mock.ctrl.T.Helper()
- return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Nudge", reflect.TypeOf((*MockPointer)(nil).Nudge), dx, dy)
+ return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Position", reflect.TypeOf((*MockPointer)(nil).Position))
}
diff --git a/internal/activity/port/pointer.go b/internal/activity/port/pointer.go
index 29f3293..05796f6 100644
--- a/internal/activity/port/pointer.go
+++ b/internal/activity/port/pointer.go
@@ -5,8 +5,16 @@ package port
//go:generate mockgen -destination=mock/mock_pointer.go -package=mock sysmon/internal/activity/port Pointer
-// Pointer abstracts moving the system pointer by a relative offset and
-// posting a synthetic mouse-moved event, which resets the OS idle timer.
+// Pointer abstracts reading and moving the system pointer: reading its
+// current position, reading the main-display bounds, and posting a
+// synthetic absolute mouse-moved event, which resets the OS idle timer.
type Pointer interface {
- Nudge(dx, dy int) error
+ // Position returns the pointer's current (x, y) location in screen
+ // pixels.
+ Position() (x, y int, err error)
+ // Bounds returns the main display's width and height in pixels.
+ Bounds() (w, h int, err error)
+ // MoveTo posts a synthetic mouse-moved event placing the pointer at the
+ // absolute (x, y) location.
+ MoveTo(x, y int) error
}
diff --git a/internal/activity/service/keeper_service.go b/internal/activity/service/keeper_service.go
index 530a4fb..a6dfcc7 100644
--- a/internal/activity/service/keeper_service.go
+++ b/internal/activity/service/keeper_service.go
@@ -1,6 +1,6 @@
// Package service contains the KeeperService use case: the ticker loop that
-// drives Pointer.Nudge on a fixed interval. It depends only on domain and
-// port, never on adapter.
+// drives a roam (a planned glide path) through Pointer on a fixed interval.
+// It depends only on domain and port, never on adapter.
package service
import (
@@ -12,53 +12,54 @@ import (
"sysmon/internal/activity/port"
)
-// nudgePause is the delay between the forward and backward nudge of a single
-// cycle. It is an implementation detail of the there-and-back move, not a
-// user-facing setting, so it is a package constant rather than a parameter.
-const nudgePause = 40 * time.Millisecond
+// stepPause is the delay between successive MoveTo calls within a single
+// roam's glide path. It is an implementation detail of what makes the
+// motion look human (a brief burst of small moves), not a user-facing
+// setting, so it is a package constant rather than a parameter.
+const stepPause = 8 * time.Millisecond
-// KeeperService implements port.Keeper: it drives a ticker loop that nudges
-// the pointer there and back on each tick, and stops cleanly when ctx is
-// cancelled.
+// KeeperService implements port.Keeper: it drives a ticker loop that, on
+// each tick, roams the pointer to a fresh random on-screen target via a
+// planned glide path, and stops cleanly when ctx is cancelled.
type KeeperService struct {
pointer port.Pointer
logger *slog.Logger
interval domain.Interval
- offset domain.Offset
+ planner *domain.Planner
}
-// NewKeeperService constructs a KeeperService. pointer and logger are injected
-// dependencies (never package globals), which is what makes this service
-// unit-testable without a real mouse or macOS Accessibility. interval and
-// offset are validated domain value objects, so the ticker can never receive a
-// non-positive duration and the two settings cannot be swapped by accident.
-func NewKeeperService(pointer port.Pointer, logger *slog.Logger, interval domain.Interval, offset domain.Offset) *KeeperService {
+// NewKeeperService constructs a KeeperService. pointer and logger are
+// injected dependencies (never package globals), which is what makes this
+// service unit-testable without a real mouse or macOS Accessibility.
+// interval is a validated domain value object, so the ticker can never
+// receive a non-positive duration. planner is the pure domain component
+// that turns a current position and screen bounds into a glide path.
+func NewKeeperService(pointer port.Pointer, logger *slog.Logger, interval domain.Interval, planner *domain.Planner) *KeeperService {
return &KeeperService{
pointer: pointer,
logger: logger,
interval: interval,
- offset: offset,
+ planner: planner,
}
}
-// Run starts the nudge ticker loop and blocks until ctx is done. On each tick
-// it nudges the pointer forward by offset, pauses, then nudges it back by the
-// same offset (there-and-back), so the cursor stays effectively in place while
-// a real move event is posted. Run returns nil on clean cancellation.
+// Run starts the roam ticker loop and blocks until ctx is done. On each tick
+// it plans and drives exactly one glide path to a fresh random on-screen
+// target. Run returns nil on clean cancellation, including cancellation that
+// lands in the middle of a glide.
func (k *KeeperService) Run(ctx context.Context) error {
ticker := time.NewTicker(k.interval.Duration())
defer ticker.Stop()
- offset := k.offset.Int()
k.logger.Info("sysmon started", "interval", k.interval.Duration())
for {
select {
case <-ticker.C:
- k.nudgeCycle(ctx, offset)
- // nudgeCycle has already run its compensating back-nudge (even if
- // ctx was cancelled during the pause). If ctx is now done, stop
- // here instead of waiting for the next tick.
+ k.roam(ctx)
+ // roam may have returned early because ctx was cancelled
+ // mid-glide. If so, stop here instead of waiting for the next
+ // tick.
if ctx.Err() != nil {
k.logger.Info("sysmon stopped")
return nil
@@ -70,26 +71,59 @@ func (k *KeeperService) Run(ctx context.Context) error {
}
}
-// nudgeCycle performs one there-and-back nudge. The pause between the two
-// nudges is interruptible: if ctx is cancelled during it, the pause ends early
-// but the compensating back-nudge STILL runs, so the cursor returns to its
-// original position before shutdown. The only path that skips the back-nudge
-// is a failed forward nudge (the cursor never moved).
-func (k *KeeperService) nudgeCycle(ctx context.Context, offset int) {
- if err := k.pointer.Nudge(offset, 0); err != nil {
- // The forward nudge failed, so the cursor never moved -- do NOT send
- // the compensating back-nudge, which would leave it offset the other
- // way. Skipping it keeps the cursor where it was.
- k.logger.Error("nudge failed", "err", err)
+// roam performs exactly one roam: read the current position and screen
+// bounds, ask the planner for a glide path, then drive the pointer through
+// that path in order with a short pause between steps. ctx is checked
+// between every step so a cancellation stops the glide promptly, without
+// making the remaining MoveTo calls. Errors from Position, Bounds, or
+// MoveTo are logged and abandon the current roam without crashing the
+// loop.
+func (k *KeeperService) roam(ctx context.Context) {
+ x, y, err := k.pointer.Position()
+ if err != nil {
+ k.logger.Error("read position failed", "err", err)
return
}
- select {
- case <-time.After(nudgePause):
- case <-ctx.Done():
+ // Bounds are read on every roam (not cached) so a resolution change or a
+ // monitor being plugged/unplugged is picked up without restarting.
+ w, h, err := k.pointer.Bounds()
+ if err != nil {
+ k.logger.Error("read bounds failed", "err", err)
+ return
+ }
+
+ path, err := k.planner.Plan(x, y, w, h)
+ if err != nil {
+ k.logger.Error("plan glide path failed", "err", err)
+ return
}
- if err := k.pointer.Nudge(-offset, 0); err != nil {
- k.logger.Error("nudge back failed", "err", err)
+ k.drive(ctx, path)
+}
+
+// drive walks path in order, calling MoveTo for each point with a short
+// inter-step pause, stopping immediately if ctx is cancelled between steps.
+func (k *KeeperService) drive(ctx context.Context, path []domain.Point) {
+ // Reuse one timer across the whole glide instead of allocating a fresh
+ // one per step (time.After), keeping the burst lightweight. Start it
+ // stopped so the first inter-step gap is exactly stepPause (not
+ // stepPause plus the first MoveTo's duration).
+ timer := time.NewTimer(stepPause)
+ timer.Stop()
+ defer timer.Stop()
+
+ for _, pt := range path {
+ if err := k.pointer.MoveTo(pt.X, pt.Y); err != nil {
+ k.logger.Error("move failed", "err", err)
+ return
+ }
+
+ timer.Reset(stepPause)
+ select {
+ case <-timer.C:
+ case <-ctx.Done():
+ return
+ }
}
}
diff --git a/internal/activity/service/keeper_service_test.go b/internal/activity/service/keeper_service_test.go
index 9817a0a..7656793 100644
--- a/internal/activity/service/keeper_service_test.go
+++ b/internal/activity/service/keeper_service_test.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"log/slog"
+ mathrand "math/rand/v2"
"sync"
"testing"
"testing/synctest"
@@ -18,10 +19,10 @@ import (
"go.uber.org/mock/gomock"
)
-// errNudge is a local sentinel used to simulate a Pointer failure in these
-// tests. It must never be adapter.ErrNudgeFailed: service tests stay
-// cgo-free and must not import internal/activity/adapter.
-var errNudge = errors.New("nudge sentinel failure")
+// errPointer is a local sentinel used to simulate a Pointer failure in these
+// tests. It must never be one of adapter's error sentinels: service tests
+// stay cgo-free and must not import internal/activity/adapter.
+var errPointer = errors.New("pointer sentinel failure")
// mustInterval builds a validated domain.Interval, failing the test on error.
func mustInterval(t *testing.T, d time.Duration) domain.Interval {
@@ -31,45 +32,127 @@ func mustInterval(t *testing.T, d time.Duration) domain.Interval {
return iv
}
-// mustOffset builds a validated domain.Offset, failing the test on error.
-func mustOffset(t *testing.T, px int) domain.Offset {
- t.Helper()
- off, err := domain.NewOffset(px)
- require.NoError(t, err)
- return off
+// stubSource is a hand-injected deterministic domain.RandomSource so the
+// planner (and therefore the expected MoveTo path) is exact and
+// reproducible in these service tests.
+type stubSource struct {
+ seq []int
+ i int
+}
+
+func newStubSource(seq ...int) *stubSource {
+ return &stubSource{seq: seq}
+}
+
+func (s *stubSource) IntN(n int) int {
+ var v int
+ if s.i < len(s.seq) {
+ v = s.seq[s.i]
+ s.i++
+ } else if len(s.seq) > 0 {
+ v = s.seq[len(s.seq)-1]
+ }
+ if v >= n {
+ v = n - 1
+ }
+ if v < 0 {
+ v = 0
+ }
+ return v
+}
+
+// mustPlanner builds a domain.Planner fed a stub source, so the path it
+// produces is deterministic and known ahead of time by the test.
+func mustPlanner(seq ...int) *domain.Planner {
+ return domain.NewPlanner(newStubSource(seq...))
}
-func TestKeeperService_NudgesPerTick(t *testing.T) {
+// inOrder is a typed wrapper around gomock.InOrder, which takes ...any: it
+// lets call sites build a []*gomock.Call and spread it without a manual
+// per-test conversion loop.
+func inOrder(calls []*gomock.Call) {
+ args := make([]any, len(calls))
+ for i, c := range calls {
+ args[i] = c
+ }
+ gomock.InOrder(args...)
+}
+
+// expectPath sets up ordered gomock expectations for Position, Bounds, and
+// then a MoveTo call per point in path, returning nil errors throughout.
+// The last MoveTo invokes onLastMove (if non-nil) so tests can trigger a
+// side effect (e.g. cancel ctx) exactly once the whole path has been
+// driven.
+func expectPath(pointer *mock.MockPointer, curX, curY, w, h int, path []domain.Point, onLastMove func()) {
+ calls := []*gomock.Call{
+ pointer.EXPECT().Position().Return(curX, curY, nil),
+ pointer.EXPECT().Bounds().Return(w, h, nil),
+ }
+ for i, pt := range path {
+ if i == len(path)-1 && onLastMove != nil {
+ calls = append(calls, pointer.EXPECT().MoveTo(pt.X, pt.Y).DoAndReturn(func(_, _ int) error {
+ onLastMove()
+ return nil
+ }))
+ continue
+ }
+ calls = append(calls, pointer.EXPECT().MoveTo(pt.X, pt.Y).Return(nil))
+ }
+ inOrder(calls)
+}
+
+func TestKeeperService_OneRoamPerTick_MoveToInOrder(t *testing.T) {
t.Parallel()
synctest.Test(t, func(t *testing.T) {
ctrl := gomock.NewController(t)
pointer := mock.NewMockPointer(ctrl)
- const (
- interval = 10 * time.Second
- ticks = 3
- )
+ const interval = 10 * time.Second
- gomock.InOrder(
- pointer.EXPECT().Nudge(1, 0).Return(nil),
- pointer.EXPECT().Nudge(-1, 0).Return(nil),
- pointer.EXPECT().Nudge(1, 0).Return(nil),
- pointer.EXPECT().Nudge(-1, 0).Return(nil),
- pointer.EXPECT().Nudge(1, 0).Return(nil),
- pointer.EXPECT().Nudge(-1, 0).Return(nil),
- )
+ // Two independent planners fed the identical draw sequence: one to
+ // precompute the expected path for the mock expectations, one wired
+ // into the service. They must be distinct instances -- calling Plan
+ // on the same *domain.Planner twice would advance its stub source
+ // twice and desync the service's actual draws from this precomputed
+ // path.
+ expectedPath, err := domain.NewPlanner(newStubSource(37, 12)).Plan(0, 0, 100, 50)
+ require.NoError(t, err)
+ planner := domain.NewPlanner(newStubSource(37, 12))
+
+ ctx, cancel := context.WithCancel(t.Context())
+
+ expectPath(pointer, 0, 0, 100, 50, expectedPath, cancel)
logger := slog.New(slog.DiscardHandler)
- svc := service.NewKeeperService(pointer, logger, mustInterval(t, interval), mustOffset(t, 1))
+ svc := service.NewKeeperService(pointer, logger, mustInterval(t, interval), planner)
- ctx, cancel := context.WithCancel(t.Context())
done := make(chan error, 1)
go func() { done <- svc.Run(ctx) }()
- time.Sleep(ticks * interval)
+ time.Sleep(interval)
synctest.Wait()
+ require.NoError(t, <-done)
+ })
+}
+
+func TestKeeperService_StopsOnContextCancel(t *testing.T) {
+ t.Parallel()
+
+ synctest.Test(t, func(t *testing.T) {
+ ctrl := gomock.NewController(t)
+ pointer := mock.NewMockPointer(ctrl)
+
+ planner := mustPlanner(1, 1)
+ logger := slog.New(slog.DiscardHandler)
+ svc := service.NewKeeperService(pointer, logger, mustInterval(t, time.Second), planner)
+
+ ctx, cancel := context.WithCancel(t.Context())
+ done := make(chan error, 1)
+ go func() { done <- svc.Run(ctx) }()
+
+ synctest.Wait()
cancel()
synctest.Wait()
@@ -77,69 +160,94 @@ func TestKeeperService_NudgesPerTick(t *testing.T) {
})
}
-// TestKeeperService_CompensatesOnCancelDuringPause exercises the exact path
-// added by review #1: cancellation landing strictly inside the inter-nudge
-// pause. The forward nudge triggers cancel(), so the pause select takes the
-// ctx.Done arm, and the compensating back-nudge must still fire before Run
-// returns.
-func TestKeeperService_CompensatesOnCancelDuringPause(t *testing.T) {
+// TestKeeperService_MidGlideCancelStopsPromptly cancels ctx after exactly N
+// MoveTo calls have landed and asserts no further MoveTo calls are made --
+// the core "interruptible mid-glide" guarantee.
+func TestKeeperService_MidGlideCancelStopsPromptly(t *testing.T) {
t.Parallel()
synctest.Test(t, func(t *testing.T) {
ctrl := gomock.NewController(t)
pointer := mock.NewMockPointer(ctrl)
+ path, err := domain.NewPlanner(newStubSource(80, 40)).Plan(0, 0, 100, 100)
+ require.NoError(t, err)
+ require.Greater(t, len(path), 5, "test needs a path long enough to cancel partway through")
+ planner := domain.NewPlanner(newStubSource(80, 40))
+
+ const cancelAfter = 3
+
ctx, cancel := context.WithCancel(t.Context())
+ defer cancel()
- gomock.InOrder(
- pointer.EXPECT().Nudge(1, 0).DoAndReturn(func(_, _ int) error {
- cancel() // cancel while we are about to enter the pause
- return nil
- }),
- pointer.EXPECT().Nudge(-1, 0).Return(nil), // must still compensate
- )
+ calls := []*gomock.Call{
+ pointer.EXPECT().Position().Return(0, 0, nil),
+ pointer.EXPECT().Bounds().Return(100, 100, nil),
+ }
+ for i := range cancelAfter {
+ pt := path[i]
+ if i == cancelAfter-1 {
+ calls = append(calls, pointer.EXPECT().MoveTo(pt.X, pt.Y).DoAndReturn(func(_, _ int) error {
+ cancel()
+ return nil
+ }))
+ continue
+ }
+ calls = append(calls, pointer.EXPECT().MoveTo(pt.X, pt.Y).Return(nil))
+ }
+ inOrder(calls)
+ // No expectations for path[cancelAfter:] -- gomock's controller fails
+ // the test if any of those MoveTo calls are made.
logger := slog.New(slog.DiscardHandler)
- svc := service.NewKeeperService(pointer, logger, mustInterval(t, time.Second), mustOffset(t, 1))
+ svc := service.NewKeeperService(pointer, logger, mustInterval(t, time.Second), planner)
done := make(chan error, 1)
go func() { done <- svc.Run(ctx) }()
- time.Sleep(time.Second) // let exactly one tick fire
+ time.Sleep(time.Second)
synctest.Wait()
require.NoError(t, <-done)
})
}
-func TestKeeperService_StopsOnContextCancel(t *testing.T) {
+// TestKeeperService_PositionErrorAbandonsTickWithoutCrash asserts a
+// Position failure is logged and the tick is abandoned (no Bounds/MoveTo
+// calls), without crashing the loop.
+func TestKeeperService_PositionErrorAbandonsTickWithoutCrash(t *testing.T) {
t.Parallel()
synctest.Test(t, func(t *testing.T) {
ctrl := gomock.NewController(t)
pointer := mock.NewMockPointer(ctrl)
+ ctx, cancel := context.WithCancel(t.Context())
+
+ pointer.EXPECT().Position().DoAndReturn(func() (int, int, error) {
+ cancel()
+ return 0, 0, errPointer
+ })
+ // No Bounds/MoveTo expectations: gomock fails the test if called.
+
+ planner := mustPlanner(1, 1)
logger := slog.New(slog.DiscardHandler)
- svc := service.NewKeeperService(pointer, logger, mustInterval(t, time.Second), mustOffset(t, 1))
+ svc := service.NewKeeperService(pointer, logger, mustInterval(t, time.Second), planner)
- ctx, cancel := context.WithCancel(t.Context())
done := make(chan error, 1)
go func() { done <- svc.Run(ctx) }()
- synctest.Wait()
- cancel()
+ time.Sleep(time.Second)
synctest.Wait()
require.NoError(t, <-done)
})
}
-// TestKeeperService_ForwardNudgeFailureSkipsBackNudge exercises nudgeCycle's
-// early-return path: when the forward nudge fails, the cursor never moved,
-// so the compensating back-nudge (-1, 0) must NOT be sent. The failing call
-// also cancels ctx (via DoAndReturn) so Run observes ctx.Err() != nil right
-// after nudgeCycle returns and stops without waiting for another tick.
-func TestKeeperService_ForwardNudgeFailureSkipsBackNudge(t *testing.T) {
+// TestKeeperService_BoundsErrorAbandonsTickWithoutCrash asserts a Bounds
+// failure is logged and the tick is abandoned (no MoveTo calls), without
+// crashing the loop.
+func TestKeeperService_BoundsErrorAbandonsTickWithoutCrash(t *testing.T) {
t.Parallel()
synctest.Test(t, func(t *testing.T) {
@@ -148,30 +256,31 @@ func TestKeeperService_ForwardNudgeFailureSkipsBackNudge(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
- pointer.EXPECT().Nudge(1, 0).DoAndReturn(func(_, _ int) error {
+ pointer.EXPECT().Position().Return(5, 5, nil)
+ pointer.EXPECT().Bounds().DoAndReturn(func() (int, int, error) {
cancel()
- return errNudge
+ return 0, 0, errPointer
})
- // No expectation for Nudge(-1, 0): gomock's controller will fail the
- // test if it is called, since only the forward nudge was recorded.
+ // No MoveTo expectations: gomock fails the test if called.
+ planner := mustPlanner(1, 1)
logger := slog.New(slog.DiscardHandler)
- svc := service.NewKeeperService(pointer, logger, mustInterval(t, time.Second), mustOffset(t, 1))
+ svc := service.NewKeeperService(pointer, logger, mustInterval(t, time.Second), planner)
done := make(chan error, 1)
go func() { done <- svc.Run(ctx) }()
- time.Sleep(time.Second) // let exactly one tick fire
+ time.Sleep(time.Second)
synctest.Wait()
require.NoError(t, <-done)
})
}
-// TestKeeperService_BackNudgeFailureIsTolerated asserts that a failed back
-// nudge is logged but does not stop the loop: the second tick still runs
-// both nudges normally.
-func TestKeeperService_BackNudgeFailureIsTolerated(t *testing.T) {
+// TestKeeperService_MoveErrorAbandonsRoamAndContinues asserts a MoveTo
+// failure partway through a path is logged and stops that roam early, but
+// the loop continues to the next tick and roams normally there.
+func TestKeeperService_MoveErrorAbandonsRoamAndContinues(t *testing.T) {
t.Parallel()
synctest.Test(t, func(t *testing.T) {
@@ -179,33 +288,66 @@ func TestKeeperService_BackNudgeFailureIsTolerated(t *testing.T) {
pointer := mock.NewMockPointer(ctrl)
ctx, cancel := context.WithCancel(t.Context())
-
+ defer cancel()
+
+ // Draw sequence covers both ticks: (1,1) is the first tick's target,
+ // (7,3) is the second's. The planner wired into the service draws
+ // both in order across its two Plan calls (one per tick), so a
+ // second, independently-seeded planner with the SAME sequence is
+ // used here purely to precompute the expected paths -- reusing the
+ // service's own planner instance would double-consume the sequence.
+ firstPath, err := domain.NewPlanner(newStubSource(1, 1, 7, 3)).Plan(0, 0, 10, 10)
+ require.NoError(t, err)
+ planner := domain.NewPlanner(newStubSource(1, 1, 7, 3))
+
+ // First tick: Position/Bounds succeed, first MoveTo fails -> roam
+ // abandoned, no further MoveTo calls this tick.
gomock.InOrder(
- pointer.EXPECT().Nudge(1, 0).Return(nil),
- pointer.EXPECT().Nudge(-1, 0).Return(errNudge),
- pointer.EXPECT().Nudge(1, 0).Return(nil),
- pointer.EXPECT().Nudge(-1, 0).DoAndReturn(func(_, _ int) error {
- cancel()
- return nil
- }),
+ pointer.EXPECT().Position().Return(0, 0, nil),
+ pointer.EXPECT().Bounds().Return(10, 10, nil),
+ pointer.EXPECT().MoveTo(firstPath[0].X, firstPath[0].Y).Return(errPointer),
)
+ // Second tick: full roam succeeds normally; last MoveTo cancels ctx.
+ secondPath, err := domain.NewPlanner(newStubSource(7, 3)).Plan(2, 2, 10, 10)
+ require.NoError(t, err)
+
+ secondCalls := []*gomock.Call{
+ pointer.EXPECT().Position().Return(2, 2, nil),
+ pointer.EXPECT().Bounds().Return(10, 10, nil),
+ }
+ for i, pt := range secondPath {
+ if i == len(secondPath)-1 {
+ secondCalls = append(secondCalls, pointer.EXPECT().MoveTo(pt.X, pt.Y).DoAndReturn(func(_, _ int) error {
+ cancel()
+ return nil
+ }))
+ continue
+ }
+ secondCalls = append(secondCalls, pointer.EXPECT().MoveTo(pt.X, pt.Y).Return(nil))
+ }
+ inOrder(secondCalls)
+
logger := slog.New(slog.DiscardHandler)
- svc := service.NewKeeperService(pointer, logger, mustInterval(t, time.Second), mustOffset(t, 1))
+ svc := service.NewKeeperService(pointer, logger, mustInterval(t, time.Second), planner)
done := make(chan error, 1)
go func() { done <- svc.Run(ctx) }()
- time.Sleep(2 * time.Second) // let two ticks fire
+ time.Sleep(2 * time.Second)
synctest.Wait()
require.NoError(t, <-done)
})
}
-// TestKeeperService_CustomOffset asserts that a non-default Offset value is
-// forwarded verbatim to Pointer.Nudge in both directions.
-func TestKeeperService_CustomOffset(t *testing.T) {
+// TestKeeperService_InvalidBoundsAbandonsTickWithoutCrash asserts that when
+// Bounds() returns a non-positive dimension, the real domain.Planner rejects
+// it with domain.ErrInvalidBounds, roam logs the error and abandons the
+// tick, and no MoveTo call is ever made. A real planner (backed by a PCG
+// source) is used here rather than the stub, since the point under test is
+// Plan's own bounds validation, not a specific stubbed draw.
+func TestKeeperService_InvalidBoundsAbandonsTickWithoutCrash(t *testing.T) {
t.Parallel()
synctest.Test(t, func(t *testing.T) {
@@ -214,16 +356,58 @@ func TestKeeperService_CustomOffset(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
- gomock.InOrder(
- pointer.EXPECT().Nudge(3, 0).Return(nil),
- pointer.EXPECT().Nudge(-3, 0).DoAndReturn(func(_, _ int) error {
- cancel()
- return nil
- }),
- )
+ pointer.EXPECT().Position().Return(0, 0, nil)
+ pointer.EXPECT().Bounds().DoAndReturn(func() (int, int, error) {
+ cancel()
+ return 0, 0, nil
+ })
+ // No MoveTo expectations: gomock fails the test if called, since
+ // Plan must reject (0, 0) bounds with domain.ErrInvalidBounds before
+ // any glide step is produced.
+
+ planner := domain.NewPlanner(mathrand.New(mathrand.NewPCG(1, 2))) //nolint:gosec // test randomness, not security
+ logger := slog.New(slog.DiscardHandler)
+ svc := service.NewKeeperService(pointer, logger, mustInterval(t, time.Second), planner)
+
+ done := make(chan error, 1)
+ go func() { done <- svc.Run(ctx) }()
+
+ time.Sleep(time.Second)
+ synctest.Wait()
+
+ require.NoError(t, <-done)
+ })
+}
+
+// TestKeeperService_MoveErrorOnFirstStepAbandonsGlideImmediately asserts
+// that when the very first MoveTo of a roam fails, drive stops immediately:
+// no subsequent MoveTo call is made for the rest of that path, and Run still
+// returns nil since the failure is only logged, not propagated.
+func TestKeeperService_MoveErrorOnFirstStepAbandonsGlideImmediately(t *testing.T) {
+ t.Parallel()
+
+ synctest.Test(t, func(t *testing.T) {
+ ctrl := gomock.NewController(t)
+ pointer := mock.NewMockPointer(ctrl)
+
+ ctx, cancel := context.WithCancel(t.Context())
+
+ path, err := domain.NewPlanner(newStubSource(80, 40)).Plan(0, 0, 100, 100)
+ require.NoError(t, err)
+ require.Greater(t, len(path), 1, "test needs at least one further step that must NOT be called")
+ planner := domain.NewPlanner(newStubSource(80, 40))
+
+ pointer.EXPECT().Position().Return(0, 0, nil)
+ pointer.EXPECT().Bounds().Return(100, 100, nil)
+ pointer.EXPECT().MoveTo(path[0].X, path[0].Y).DoAndReturn(func(_, _ int) error {
+ cancel()
+ return errPointer
+ })
+ // No further MoveTo expectations: gomock fails the test if any of
+ // path[1:] is ever called.
logger := slog.New(slog.DiscardHandler)
- svc := service.NewKeeperService(pointer, logger, mustInterval(t, time.Second), mustOffset(t, 3))
+ svc := service.NewKeeperService(pointer, logger, mustInterval(t, time.Second), planner)
done := make(chan error, 1)
go func() { done <- svc.Run(ctx) }()
@@ -284,15 +468,15 @@ func TestKeeperService_LogsStartAndStop(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
- pointer.EXPECT().Nudge(1, 0).Return(nil)
- pointer.EXPECT().Nudge(-1, 0).DoAndReturn(func(_, _ int) error {
- cancel()
- return nil
- })
+ path, err := domain.NewPlanner(newStubSource(1, 1)).Plan(0, 0, 10, 10)
+ require.NoError(t, err)
+ planner := domain.NewPlanner(newStubSource(1, 1))
+
+ expectPath(pointer, 0, 0, 10, 10, path, cancel)
handler := newCapturingHandler()
logger := slog.New(handler)
- svc := service.NewKeeperService(pointer, logger, mustInterval(t, interval), mustOffset(t, 1))
+ svc := service.NewKeeperService(pointer, logger, mustInterval(t, interval), planner)
done := make(chan error, 1)
go func() { done <- svc.Run(ctx) }()
@@ -330,3 +514,46 @@ func TestKeeperService_LogsStartAndStop(t *testing.T) {
assert.True(t, sawStopped, "expected a sysmon stopped record")
})
}
+
+// TestKeeperService_RoamStaysInBoundsFromOutOfBoundsStart asserts the
+// service-to-adapter "never off-screen" contract at that seam: even when
+// Position() reports an out-of-bounds start (as a multi-monitor Mac does with
+// global desktop coordinates), every MoveTo the service issues lands inside
+// [0, w) x [0, h).
+func TestKeeperService_RoamStaysInBoundsFromOutOfBoundsStart(t *testing.T) {
+ t.Parallel()
+
+ synctest.Test(t, func(t *testing.T) {
+ const w, h = 1920, 1080
+
+ ctrl := gomock.NewController(t)
+ pointer := mock.NewMockPointer(ctrl)
+
+ ctx, cancel := context.WithCancel(t.Context())
+
+ pointer.EXPECT().Position().Return(-500, 5000, nil)
+ pointer.EXPECT().Bounds().Return(w, h, nil)
+ pointer.EXPECT().MoveTo(gomock.Any(), gomock.Any()).DoAndReturn(func(x, y int) error {
+ assert.GreaterOrEqual(t, x, 0)
+ assert.Less(t, x, w)
+ assert.GreaterOrEqual(t, y, 0)
+ assert.Less(t, y, h)
+ return nil
+ }).MinTimes(1)
+
+ logger := slog.New(slog.DiscardHandler)
+ planner := domain.NewPlanner(mathrand.New(mathrand.NewPCG(1, 2))) //nolint:gosec // test randomness, not security
+ svc := service.NewKeeperService(pointer, logger, mustInterval(t, time.Second), planner)
+
+ done := make(chan error, 1)
+ go func() { done <- svc.Run(ctx) }()
+
+ time.Sleep(time.Second) // let exactly one roam fire
+ synctest.Wait()
+
+ cancel()
+ synctest.Wait()
+
+ require.NoError(t, <-done)
+ })
+}