Commit graph

626 commits

Author SHA1 Message Date
48dc4b852e
feat: add Phoenix support for agent-side ping monitoring
Enables Phoenix to send PING jobs to agents and receive monitoring
check results, fixing the "unknown" status for devices assigned to
local (non-cloud) agents.

Changes:
- Rename JobType::MONITOR to JobType::PING in protobuf for clarity
- Add validate_monitoring_check_message() to Validator module
- Add "monitoring_check" channel handler to receive ping results
- Implement store_monitoring_check() to save results to database
- Add build_ping_job() to generate PING jobs for agents
- Update build_jobs_for_device() to include ping jobs when
  monitoring_enabled=true

Phoenix now sends PING jobs alongside SNMP/MikroTik jobs, and agents
send back MonitoringCheck results that are stored in the
monitoring_checks table with proper agent_token_id tracking.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-08 13:44:21 -06:00
fb8ffde119
fix: prevent site assignment when sites are disabled for org
When an organization has sites disabled (use_sites=false), the API
now automatically removes any site_id from device creation requests,
ensuring devices are assigned directly to the organization instead.

This prevents Terraform (and other API clients) from creating devices
in sites when sites functionality is disabled for the organization.

Fixes issue where Terraform could bypass site restrictions via API.
2026-02-08 13:24:48 -06:00
b823b5e848
feat: display cloud poller name on device page
Show the specific cloud poller name (e.g., dfw, lon) alongside "Cloud"
when a device is assigned to a cloud poller. Displays as "Cloud (dfw)"
instead of just "Cloud" for better visibility of which poller is being used.

When no agent is assigned, continues to show just "Cloud".
2026-02-08 11:40:58 -06:00
10b1168044
refactor: round latency graph values to 1 decimal place
Display latency values with single decimal precision (e.g., 114.1ms)
for improved readability in graphs. This ensures consistency between
the raw chart data and tooltip formatting.
2026-02-08 11:13:39 -06:00
16b833d077
fix: correct LoggerFileBackend API usage to fix Oban startup
The previous commit (90e8964) introduced an incorrect LoggerBackends.add/2
call that prevented Oban from starting, causing all discovery jobs to remain
stuck in "available" state without being processed.

Root cause: LoggerBackends.add expects a tuple {module, id} as the first
argument, not the module alone with configuration options.

Fix: Use the correct API pattern:
1. Add backend with tuple identifier: {LoggerFileBackend, :file_log}
2. Configure separately with Logger.configure_backend/2

This resolves device discovery being completely broken - all background
jobs (discovery, polling, monitoring) now process correctly.
2026-02-08 11:07:45 -06:00
90e89641b7
fix logging backend 2026-02-08 10:55:08 -06:00
6b4c098de8
fix warnings 2026-02-08 10:50:27 -06:00
631d03536e
security: add session inactivity timeout and comprehensive security documentation
Session Security Enhancements:
- Add 30-minute inactivity timeout to UpdateSessionActivity plug
- Automatic logout with user notification after inactivity
- Session timeout check happens on every request
- Graceful logout with flash message
- Refactored for Credo compliance (reduced nesting depth)

Security Documentation:
- Create comprehensive SECURITY.md covering all security features
- Document authentication, authorization, and encryption
- List OWASP Top 10 mitigations
- Include security checklist for developers
- Document recent security fixes and improvements

Verification:
- Password reset already rate-limited (confirmed)
- All 6,145 tests passing
- Zero Credo issues
- Zero security warnings

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-08 10:47:44 -06:00
fb1d4c564f
security: fix critical vulnerabilities and atom exhaustion risks
Critical fixes:
- Add [:safe] option to binary_to_term to prevent RCE attacks
- Implement whitelist validation for String.to_atom conversions
- Add input validation before String.to_existing_atom usage

Changes:
- MIB compiler and cache: Use safe binary deserialization
- SNMP contexts: Whitelist protocol, device type, and source atoms
- API controllers: Validate error message keys before atom conversion
- Reduce function nesting to comply with Credo standards

All 6,145 tests passing with zero Credo issues.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-08 10:30:30 -06:00
d431931cfe
update hammer 2026-02-08 10:08:31 -06:00
8d4333b237
fix superadmin page 2026-02-07 11:58:56 -06:00
3931a9c14a
more tests and fixes 2026-02-07 11:50:18 -06:00
141c775230
fix: discovery retry, disabled assignment cascade, and silent spawn crashes
- Move last_discovery_at update to after successful processing so failed
  discoveries are retried on the next poll cycle instead of being blocked
  for 24 hours
- Add disabled assignment check to agent polling target query so devices
  with enabled=false assignments don't leak through site/org cascade
- Wrap spawned polling data processing in try/rescue so crashes are logged
  instead of silently disappearing
2026-02-07 09:17:28 -06:00
3eb3d4890e
Merge branch 'feature/job-monitoring-dashboard'
# Conflicts:
#	lib/towerops/workers/device_poller_worker.ex
#	lib/towerops/workers/discovery_worker.ex
2026-02-06 19:01:08 -06:00
137d7c83ec
test: add comprehensive integration tests for monitoring dashboard
Added integration tests for real-time updates and metrics display.
Also fixed dialyzer warnings in worker event broadcasting by removing
unreachable error handling branches.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 18:41:08 -06:00
070241d15a
feat: add queue depth display to health metrics
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 18:37:21 -06:00
1eaf6d9ac5
feat: build recent activity timeline with color-coded events
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 18:35:55 -06:00
8bceb6dce2
feat: build comprehensive health metrics panel with success rates
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 18:34:43 -06:00
1e45b1609b
feat: build detailed problems section UI for stuck and failed jobs
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 18:33:21 -06:00
daa223c49d
feat: enhance active operations display with device context
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 18:32:06 -06:00
2fb0101bab
feat: add job monitoring link to admin dashboard
Add Job Monitoring card to admin dashboard with:
- Hero icon for visual identification
- Brief description of monitoring capabilities
- Link to /admin/monitoring dashboard

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 18:28:41 -06:00
bb9e6f0b0c
feat: create MonitoringLive base structure with PubSub subscription
Add LiveView for real-time job monitoring dashboard:
- Subscribe to job:lifecycle PubSub topic for live updates
- Display health metrics (completed, failed, avg duration, active jobs)
- Show active operations with real-time updates
- Display problems section (stuck/failed job counts)
- Add router entry under /admin/monitoring

Tests verify PubSub subscription and basic rendering.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 18:27:40 -06:00
be073fa4b7
feat: integrate lifecycle event broadcasting into DiscoveryWorker
Add Events.broadcast_job_event calls to track job lifecycle:
- :started when job begins executing
- :completed when job finishes (including :discard status)
- :failed when job crashes with error
- Track duration in seconds for all job executions

Wrap main logic in try/rescue to ensure events broadcast even on crash.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 18:24:48 -06:00
a2778d9b7c
feat: integrate lifecycle event broadcasting into DevicePollerWorker
Add Events.broadcast_job_event calls to track job lifecycle:
- :started when job begins executing
- :completed/:failed when job finishes
- Track duration in seconds for all job executions

Broadcast events enable real-time monitoring of polling operations.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 18:23:52 -06:00
9f30d366b1 feat: add PubSub event broadcasting for job lifecycle
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 16:36:34 -06:00
9b0b000263
feat: add health metrics calculation module
Create JobMonitoring.Metrics module with calculate_all/0 to provide
comprehensive metrics including execution counts, success rates,
queue depths, and average execution times.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 16:31:27 -06:00
adbaeef83d
feat: add failed jobs and recent completions queries
Add list_failed_jobs/0 to return retryable and cancelled jobs
and list_recent_completions/1 to return completed, cancelled,
or discarded jobs with configurable limit.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 16:29:19 -06:00
d845f372d0
feat: add stuck job detection with per-worker thresholds
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 16:21:23 -06:00
92f835bf9d
refactor: add type spec to list_active_jobs 2026-02-06 16:19:54 -06:00
35c7328831
feat: add JobMonitoring context with list_active_jobs query
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 16:15:18 -06:00
e3e47fb82f
fix: include SNMPv3 fields in API device responses
The API was not returning SNMPv3 fields (security_level, username,
auth_protocol, auth_password, priv_protocol, priv_password) in device
responses, causing Terraform provider to see inconsistent state between
plan and apply.

Updated both format_device/1 and format_device_details/1 to include
all SNMPv3 fields in JSON responses.
2026-02-06 14:05:15 -06:00
7f7b722965
feat: add SNMPv3 credential logging for debugging
Log SNMPv3 credentials being sent to agents (with passwords redacted) to help diagnose authentication issues. Shows security level, username, auth/priv protocols, and whether passwords are present.
2026-02-06 13:48:35 -06:00
5f04d716ba
fix: handle device deletion during discovery
Previously, if a device was deleted while a discovery job was in progress, the wait_loop would crash with Ecto.NoResultsError when trying to check if discovery had completed.

Now uses get_device_with_details which returns nil for missing devices, and gracefully returns {:error, :device_deleted} instead of crashing.
2026-02-06 13:06:37 -06:00
6a29ee1671
fix: Split agent polling queries to isolate SNMP failures
Changed from one large WALK query with all OIDs to separate WALK queries
per table type. This prevents a failure in one unsupported table (like ARP
on a device that doesn't support it) from killing the entire polling
operation.

Before: Single WALK with neighbor + ARP + MAC + IP + HOST-RESOURCES OIDs
After: Separate WALKs for each table type

This makes polling more resilient - if a device doesn't support ARP tables
or HOST-RESOURCES-MIB, those WALKs will fail individually while neighbors,
MAC tables, and IP addresses can still succeed.

Fixes agent errors where a single SNMP receive error was killing the
entire poller thread and failing all subsequent operations with
'Poller thread died'.
2026-02-06 12:30:52 -06:00
184c2bc999
fix: Use snmp_device.id for sync_processors and sync_storage
Fixes KeyError when processing processors/storage during agent polling.
The sync_processors and sync_storage functions expect device.id to be
the snmp_device id, not the main device id.

Changed from:
  %{device_id: device.id}

To:
  %{id: device.snmp_device.id}

This matches the expected structure for these sync functions which
query where snmp_device_id == device.id.
2026-02-06 12:06:30 -06:00
c6ec9ab891
fix: Handle nil vlan_id in MAC address upsert queries
Fixes ArgumentError when upserting MAC addresses with nil vlan_id.
Ecto doesn't allow direct comparison with nil in queries - must use
is_nil/1 instead.

Changed upsert_mac_address to build dynamic query that uses is_nil(m.vlan_id)
when vlan_id is nil, or direct comparison when it has a value.

Error was:
  Comparison with nil is forbidden as it is unsafe.
  Instead write a query with is_nil/1
2026-02-06 12:00:29 -06:00
26e5d20510
fix: Add device_id to interfaces for neighbor discovery in agent polling
Fixes KeyError when processing neighbor discovery during agent polling.
NeighborDiscovery.discover_neighbors/2 requires interfaces to have a
:device_id field for building neighbor records, but interfaces from the
database only have :snmp_device_id.

Solution matches the approach in DevicePollerWorker which adds device_id
to interfaces before calling discover_neighbors.
2026-02-06 11:26:00 -06:00
f17ee2183c
fix: Use server-side timestamps for agent polling metrics
Replaces agent-supplied timestamps with server-side DateTime.utc_now()
to prevent clock drift issues between agents from causing weird graphs.

All metrics now use consistent server time regardless of polling method:
- Agent polling (via WebSocket): server time on receipt
- Phoenix polling (direct SNMP): server time on poll (already correct)

This ensures time-series data aligns correctly when graphing metrics
from devices polled by different agents with potentially different
system clocks.
2026-02-06 11:23:26 -06:00
bf4fee4846
feat: Add comprehensive agent polling for all discoverable data
Extended agent polling to collect all available SNMP data during regular
polls, not just sensors and interfaces. This ensures data stays current
and reduces reliance on periodic discovery runs.

Changes:
- Added polling queries for: neighbors (LLDP/CDP), ARP tables, MAC tables,
  IP addresses, HOST-RESOURCES processors and storage
- Process additional data using Replay adapter pattern to reuse existing
  parsing logic from discovery modules
- Made discovery helper functions public for reuse in polling context:
  save_neighbors/2, save_arp_entries/3, sync_ip_addresses/2,
  sync_processors/2, sync_storage/2
- Optimized by fetching interfaces once and reusing across operations
- Fixed compilation warnings by using proper guard syntax (list != [])

Technical details:
- Detection threshold: polls with more OIDs than sensors+interfaces
  are processed for additional data
- Background processing: spawns async process to avoid blocking metric
  recording
- Replay adapter: allows reusing discovery parsing logic without
  re-querying SNMP device
2026-02-06 11:18:36 -06:00
5f0549908e
Add IP address table walks to agent discovery queries
Fixes missing IP addresses tab on device page after agent-based discovery.

Issue:
Discovery was not collecting IP address data because the agent's
discovery job didn't include IP address table OID walks.

Root cause:
build_discovery_queries() walked interface tables, sensors, vendor MIBs,
and neighbors, but was missing the IP-MIB address tables.

Changes:
- Add new SnmpQuery to walk IP address tables during discovery:
  - 1.3.6.1.2.1.4.20 (ipAddrTable - IPv4, deprecated but widely supported)
  - 1.3.6.1.2.1.4.34 (ipAddressTable - RFC 4293, unified IPv4/IPv6)

This matches the OIDs used by Phoenix's direct discovery in
lib/towerops/snmp/profiles/base.ex discover_all_ip_addresses/1.

Result:
Agent now collects IP address data during discovery, which is then
synced to the database and displayed in the IP Addresses tab.

Tests: 5578 tests passing (1 pre-existing failure in unrelated Dahua test)
2026-02-06 11:05:59 -06:00
4db953bafa
Add dev-only INFO logging for IP address discovery
Shows IP address discovery and sync results at INFO level in dev
environment only to help diagnose discovery issues.

Changes:
- Add log_ip_discovery_results/2 helper to log discovered IPs
- Enhanced sync_ip_addresses/2 to log IPv4/IPv6 counts and removals
- Only logs at INFO level when env is :dev, uses DEBUG in prod

Example output in dev:
  Discovered IP addresses: 5 IPv4, 2 IPv6 (total: 7)
  Synced IP addresses: 5 IPv4, 2 IPv6, removed 1

This helps diagnose why IP addresses tab isn't showing on device page.
2026-02-06 11:01:10 -06:00
d03ad72aec
Increase max OID values limit from 1,000 to 50,000
Fixes discovery failures on enterprise network devices with many
interfaces and routing table entries.

Issue:
Discovery was failing with "too_many_oids - OID values map exceeds
1000 entries" on SNMPv3 devices. Enterprise routers/switches during
discovery can easily return 10k-50k OIDs from:
- 100+ interfaces with 20-30 OIDs each
- System info, routing tables, ARP tables, neighbor tables
- Various MIB objects

The original limit of 1,000 was too restrictive for real-world devices
while still being intended as DoS protection.

Changes:
- Increase @max_oid_values from 1,000 to 50,000
- Update test to generate 50,100 OIDs (exceeds new limit)
- Add comment explaining why limit is set to 50k

This maintains DoS protection (prevents multi-million OID attacks)
while accommodating realistic device discovery scenarios.

All tests passing (5578 tests, 0 failures).
2026-02-06 10:41:30 -06:00
a4dd7210d8
Improve error logging for SNMP result validation failures
Add detailed error logging to show specific validation error type and
message when SNMP results fail validation. Also handle base64 decode
failures separately.

This will help diagnose validation issues introduced by recent strict
protobuf validation changes (commit 8044a6d1).
2026-02-06 10:36:37 -06:00
0a978746e1
Fix all Credo issues
Resolves 26 Credo warnings/issues:

Code Readability (2 issues):
- Break long line in mac_address.ex (line 316 > 120 chars)
- Break long @spec in agents.ex (line 332 > 120 chars)

Refactoring Opportunities (2 issues):
- Reduce cyclomatic complexity in device_live/form.ex
  - Extract helper functions to simplify SNMPv3 credential resolution
  - Split logic into smaller, focused functions
- Reduce nesting depth in snmp_oid.ex
  - Extract nested logic into separate helper functions

Warnings (22 issues):
- Fix comparison warning in validator.ex
  - Split validate_sensor_value/1 into separate clauses for int/float
  - Add credo directive for valid NaN check (value != value)
- Replace 21 expensive length/1 checks with Enum.empty?/1
  - Change assertions from `assert length(list) >= 1` to `refute Enum.empty?(list)`
  - Change assertions from `assert length(list) > 0` to `refute Enum.empty?(list)`
  - Affected files: device_poller_worker_test.exs, mib_test.exs,
    snmp_tokenizer_test.exs, parser_test.exs, error_test.exs, compiler_test.exs

All tests passing (5578 tests, 0 failures).
Credo now reports: "found no issues"
2026-02-06 10:31:09 -06:00
ed50257d8a
fix snmp v3 test 2026-02-06 10:21:54 -06:00
4d980ed58a
Fix Dialyzer :exact_compare warnings for NaN/infinity checks
Fixes 3 Dialyzer warnings about impossible comparisons when checking for NaN
and infinity values in sensor validation.

Problem:
Dialyzer correctly identified that comparing a float with atoms (:nan,
:infinity, :neg_infinity) using == can never evaluate to true. The previous
code attempted to validate sensor values by comparing with these atoms, which
is incorrect in Erlang/Elixir.

Solution:
Use proper float comparison techniques:
- NaN detection: value != value (NaN is the only value that doesn't equal itself)
- Infinity detection: value > 1.0e308 or value < -1.0e308 (beyond max float range)

This approach correctly identifies special float values without impossible
comparisons that Dialyzer flags.

Dialyzer results:
- Before: Total errors: 509, Skipped: 506
- After: Total errors: 506, Skipped: 506
- Status: done (passed successfully), EXIT CODE: 0

All 3434 tests passing. Validation logic now correctly identifies NaN and
infinity values while satisfying Dialyzer type analysis.
2026-02-06 10:02:46 -06:00
0a0ec23fc9
Fix all compilation warnings for --warnings-as-errors
Resolves all warnings in agent_channel.ex and validator.ex to enable strict
compilation mode.

agent_channel.ex changes:
- Removed unused aliases: AgentError, AgentHeartbeat, CredentialTestResult, SnmpResult
- Removed unused typep declarations: device_id, job_id, agent_token_id
- Prefixed unused variable with underscore: binary -> _binary
- Grouped handle_in/3 clauses together (moved credential_test_result handler)
- Removed @doc from private functions (safe_base64_decode)
- Removed unused private function safe_base64_encode/1

validator.ex changes:
- Removed unused alias: MikrotikSentence
- Prefixed unused parameter with underscore in validate_counter: field -> _field
- Commented out unused module attributes: @max_oid_length, @max_port, @max_interval_seconds
- Removed redundant validate_response_time(0.0) clause (covered by general case)
- Updated validate_response_time guard to use >= 0.0 instead of pattern matching on 0.0

All tests passing (3434 tests). Compilation now succeeds with --warnings-as-errors.
2026-02-06 09:57:04 -06:00
0c77dd84e7
Add strict typespecs to all Oban worker perform/1 functions
Adds @spec annotations to all Oban worker perform/1 functions to improve
static analysis and documentation. Return types are specific to each worker's
actual behavior:

Workers returning 🆗
- BackupSummaryWorker
- BackupTimeoutWorker
- DeviceMonitorWorker
- DevicePollerWorker
- JobHealthCheckWorker
- NeighborCleanupWorker

Workers with complex returns:
- DiscoveryWorker: :ok | :discard
- FirmwareVersionFetcherWorker: :ok | {:error, term()}
- LoginHistoryCleanupWorker: {:ok, %{deleted: non_neg_integer(), anonymized_deleted: non_neg_integer()}}
- MikrotikBackupWorker: :ok | {:error, String.t()}
- SessionCleanupWorker: {:ok, %{sessions_deleted: non_neg_integer()}}

Analysis found that none of these workers have complex job parameters that
would benefit from embedded schemas - all use either no parameters or simple
device_id strings passed in job args.

StaleAgentWorker already had a typespec on find_stale_agents/0 from previous work.

All 98 worker tests passing after changes.
2026-02-06 09:50:51 -06:00
e363fbc691
Implement MacAddress and SnmpOid custom Ecto types
Continues the pattern of using custom Ecto types to create rich domain objects
and avoid primitive obsession. Adds two new custom types following the
established pattern from IPAddress.

## MacAddress Custom Type

Provides structured MAC address handling with:
- Multiple input format support (colon, hyphen, dot-separated, compact)
- Normalization to colon-separated lowercase (canonical format)
- SNMP binary format conversion (6-byte binary)
- Format conversion helpers (:colon, :hyphen, :dot, :compact)
- Comprehensive validation and error handling

### Supported Formats
- Colon: `00:11:22:33:44:55`
- Hyphen: `00-11-22-33-44-55`
- Dot (Cisco): `0011.2233.4455`
- Compact: `001122334455`
- SNMP binary: `<<0, 17, 34, 51, 68, 85>>`

All formats normalize to lowercase colon-separated format for consistency.

## SnmpOid Custom Type

Provides structured SNMP OID handling with:
- OID format validation (numeric and named)
- Normalization to dotted-decimal with leading dot
- OID resolution via SnmpKit (named → numeric)
- Helper functions (parent, child_of?, append)
- Integer list representation support

### Supported Formats
- Dotted-decimal: `.1.3.6.1.2.1.1.1.0`
- Numeric (no leading dot): `1.3.6.1.2.1.1.1.0`
- Named OID: `sysDescr.0` (with automatic resolution)
- Integer list: `[1, 3, 6, 1, 2, 1, 1, 1, 0]`

## Benefits

- **Type Safety**: Structured data with validation at cast time
- **Normalization**: Consistent storage format regardless of input
- **Rich API**: Helper functions for common operations
- **Zero Migration Cost**: No database changes needed
- **Better Errors**: Clear validation errors instead of DB constraint violations
- **Domain Modeling**: Code works with %MacAddress{} and %SnmpOid{} instead of strings

## Database Storage

Both types store as VARCHAR in the database:
- MacAddress: VARCHAR(17) - colon-separated format
- SnmpOid: VARCHAR(255) - dotted-decimal format with leading dot

## Test Coverage

Added comprehensive test suites:
- MacAddress: 47 tests covering all formats, roundtrips, edge cases
- SnmpOid: 49 tests covering OID operations, validation, helpers
- All 96 tests passing 

## Usage Example

```elixir
# Before (primitive obsession)
field :mac_address, :string
field :sensor_oid, :string

# After (rich domain types)
field :mac_address, Towerops.EctoTypes.MacAddress
field :sensor_oid, Towerops.EctoTypes.SnmpOid

# Usage
changeset
|> cast(attrs, [:mac_address, :sensor_oid])
# Validation happens automatically in cast/1
```

Files:
- lib/towerops/ecto_types/mac_address.ex (330 lines)
- lib/towerops/ecto_types/snmp_oid.ex (340 lines)
- test/towerops/ecto_types/mac_address_test.exs (380 lines)
- test/towerops/ecto_types/snmp_oid_test.exs (390 lines)
2026-02-06 09:41:54 -06:00
3fff0db784
Add comprehensive typespecs to agent-related modules
Adds @spec annotations to all public functions in agent-related modules for
better static analysis and documentation.

Changes:
- Added 17 typespecs to Towerops.Agents context module
  - All CRUD operations (create, read, update, delete, revoke)
  - Assignment management functions
  - Agent token resolution and lookup functions
  - PubSub broadcast function
- Added 9 typespecs to Towerops.Agents.Stats module
  - Agent health and metrics statistics
  - Device assignment breakdowns
  - Latency analysis and reassignment candidate detection
- Added typespec to Towerops.Workers.StaleAgentWorker
  - find_stale_agents/0 function
- Preserved existing typespecs in AgentChannel (socket types)

Benefits:
- Improved code documentation with clear function signatures
- Better static analysis via dialyzer
- Clearer API contracts for all agent management functions
- Type-safe UUID handling throughout agent system
2026-02-06 09:33:44 -06:00