> ## Documentation Index
> Fetch the complete documentation index at: https://docs.moda.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Ci dashboard monitoring

# CI monitoring in Admin → Infrastructure → CI

This dashboard is admin-only. It reads stored Actions observations and office Mac
heartbeats through the application backend, never through Replicas workspace
authentication. No collector or Mac installation is enabled by this change alone.
This dashboard changes neither routing nor runner registration. Capacity trials and pool setup are coordinated separately; the monitor never assumes a single slot or four slots.

## Enable after merge and backend deployment

1. Apply the backend database migration with the normal release process.
2. Provision separate random `CI_MONITOR_INGEST_KEY` and
   `CI_MONITOR_HEARTBEAT_KEY` on the deployed backend through the supported
   secrets manager. The ingest key may write Actions polls and read tracked
   active run IDs; the heartbeat key may only submit Mac telemetry. Neither key
   grants dashboard read access. Do not reuse `MODA_INTERNAL_API_KEY`, a GitHub
   provider token, or a Replicas workspace token.
3. Configure repository Actions secret `CI_MONITOR_INGEST_KEY`, repository
   variable `CI_MONITOR_API_URL` (HTTPS backend API base including `/api`, for
   example `https://<backend-host>/api`), then set repository variable
   `CI_MONITOR_ENABLED=true`. The job uses its short-lived `GITHUB_TOKEN` with
   `contents:read` and `actions:read`. No permanent GitHub token is required.
4. Dispatch **CI Dashboard Monitor** on main and check the admin view. Its
   default-branch checkout never runs a PR's scripts or artifacts, including
   when a fork PR triggers the workflow-run event.
5. Coordinate a separate, narrowly scoped installation of
   `scripts/ci/monitor/mac-heartbeat.py` as the dedicated standard `moda-ci`
   user. Keep the script, private environment file, wrapper and logs under
   `~/replicas/<installing-workspace-id>/`. Provision `CI_MONITOR_API_URL` and
   **only** `CI_MONITOR_HEARTBEAT_KEY` in a mode-0600 environment file. Use a
   launchd LaunchAgent or equivalent approved scheduler to run it every minute;
   the wrapper sources that file and invokes `python3 mac-heartbeat.py`. Do not
   place the token in command arguments or a world-readable plist. Validate
   `python3 mac-heartbeat.py --print` locally first, then one authenticated POST.
   This PR intentionally does not install an agent or change Mac services.

Missing secret values must be requested through
`replicas environment vars request CI_MONITOR_INGEST_KEY CI_MONITOR_HEARTBEAT_KEY`
when coordinating setup; do not paste secrets into chat. That form supplies
workspace variables, so an administrator must also provision the actual deployed
backend/Actions/Mac destinations through their supported secret configuration.

## Collection and limits

The hosted workflow runs every five minutes and on PR Checks / Main Full Suite
requested, started and completed events. GitHub schedules can be delayed; there
is no claimed sub-minute freshness or independence from a GitHub outage. Its
runner is hosted Blacksmith, never the office Mac. Queue/health evaluation is
stored visibly by the backend and freshness remains visible when collection
stops. The existing CI Failure Alerts mechanism covers monitor workflow failures;
this feature sends no separate Slack messages for runner health. Runner/queue
incidents, recovery and cooldown state belong in the admin dashboard.

Each poll reads the previous 24 hours of runs, separate queued/in-progress run
lists (including old queues), any event run, and up to 100 previously tracked
active run IDs from the backend. This reconciles completion of old runs after
24 hours. Jobs use `filter=all`, with identity **run ID : attempt : job ID**;
repeated polls update that identity instead of increasing throughput. Collection
has a 270-second budget, 180-request cap, 100 rows per page, three pages per run
list, five per job list and two per artifact/runner list. Payloads are capped at
1,000 job attempts. Partial coverage is explicitly reported in limitations; it
must never be treated as a complete inventory or measured billing.

The API runner inventory can return 403 with the workflow's least-privilege
`GITHUB_TOKEN`. That is reported as **unknown**, never offline. A separate
heartbeat proves only that the Mac telemetry collector reached the backend;
runner listener availability additionally requires successful runner inventory
or active job evidence. No recent jobs alone does not prove offline.

The Mac script samples only read-only system counters: battery charge and power
source from `pmset`; interval CPU idle from `top`; load average and swap usage
from `sysctl`; VM pressure level when macOS exposes it. Unsupported or denied
counters are `null`. It does not enumerate personal files/process arguments,
read keychain/iMessage, stop VMs/services, or change concurrency. The hardware
capacity decision should use fresh interval samples, not assumptions about AC
power or idle status.

## Tests, cache and costs

JUnit collection currently supports the existing unambiguous full frontend and
backend Vitest shard artifacts named
`test-results-<suite>-full-<shard>-of-<total>-attempt-<attempt>`. It verifies the
artifact metadata's run ID, attempt and SHA and the API job's matrix name. It
counts primary `junit.xml` testcase outcomes; retry reports are excluded. Missing,
expired, oversized, unsafe or unmatched artifacts produce unavailable counts.
Package/turbo/related-mode reports are not silently assigned to unrelated jobs.

Artifact and log downloads are limited to 5 MiB each; expanded ZIP size is also
bounded. XML declarations with DTDs/entities are rejected, archive paths are
never extracted, and no artifact code is executed. GitHub authorization headers
are removed on artifact/log redirects. Backend keys are never forwarded through
redirects.

Cache-hit classification requires the current task's `@moda/<suite>:test: cache
hit` or `cache miss`/`cache bypass` line. Without it, `cacheHit=null`, even when
JUnit counts exist. Replayed JUnit counts describe a previous cached result and
must not be presented as new test execution. Other jobs without JUnit remain
unavailable; job success is not a test count.

Runtime-based hosted cost/savings are estimates only. They exclude measured
Blacksmith bills, subscription discounts, minimum billing, Mac purchase,
electricity and maintenance. The existing Costs → CI attribution pipeline remains
the source for allocated provider billing. The new dashboard must label any
configured per-minute-rate calculation as an estimate and leave unavailable
rates blank. Optional backend configuration `CI_MONITOR_HOSTED_USD_PER_MINUTE` and
`CI_MONITOR_MAC_EQUIVALENT_HOSTED_USD_PER_MINUTE` must be positive administrator-verified
USD rates for the actual hosted fleet and comparable Mac workload respectively.
The counterfactual assumes equal wall time; heterogeneous fleet averages and CPU
speed differences can make it inaccurate. Both default to unavailable.
Hosted-versus-Mac runtime and utilization are measured only across
the stated poll/heartbeat coverage; current telemetry is required to interpret
capacity. Backend retention is 90 days for job attempts and 30 days for samples.

## Validate and roll back

Run `python3 -m unittest discover -s scripts/ci/monitor -p 'test_*.py'` and
`bun test scripts/ci-failure-alerts.test.ts`. Then dispatch the enabled collector,
verify an Actions attempt appears once across repeated polls, inspect real
telemetry freshness, and verify denied runner permission remains unknown. For a
queue/offline drill, use an isolated test backend; do not interrupt the runner.

To stop writes, set `CI_MONITOR_ENABLED=false` and disable only the installed
heartbeat scheduler. Revoke the two dedicated keys. The existing admin view
shows stale/unavailable data; stored metrics expire according to retention.
Reverting this feature must not alter the runner listener, routing or existing
CI Failure Alerts behavior for other workflows. No deploy or Mac install was
performed while implementing this PR.

## Stored observation history

`GET /api/admin/ci-monitor?hours=1|24|168|720` includes `history` alongside the
current job inventory. This remains protected by the existing JWT and admin
guards. The history window returns at most 240 buckets per series, anchored at
its exact `from` timestamp. SQL selects the latest actual sample in each bucket
and supplies the count of stored minute samples. This is a representative
observation, not a CPU average, queue average or reconstructed execution trace.
Missing buckets remain absent and null hardware counters remain null; the client
must show gaps rather than interpolate or substitute zero.

Heartbeat minute samples retain 30 days. A new poll-observation table retains
90 days, with cleanup on poll ingestion. Poll observations are deduplicated to
the latest sample per minute; a partial flag is preserved if any retained
minute/bucket sample had incomplete coverage. No historical poll observations
are backfilled from final job results or the latest runner state. Queue/active
counts group by hosted/Mac pool, workload (including shard identity), and assigned
listener name; unassigned jobs retain a null listener. Groups are capped at 64
per observation and omitted groups mark coverage partial. Counted attempts are
unique by run/attempt/job identity.

Optional listener inventory and capacity are saved with each poll, not inferred
from hardware samples. Configured capacity requires an explicit, unique roster
of up to 32 listeners and matching slot count, source
`configured-listener-roster`, and a contemporaneous observation timestamp. Legacy
polls have unavailable capacity. A host heartbeat never establishes that any
named runner listener is online. Multiple listeners share one physical host
telemetry sample; their CPU, memory and battery are not summed. Configured
capacity is a declared limit, not evidence of safe physical-host concurrency.
Structured hosted and Mac-equivalent rates remain unavailable until explicitly
configured and continue to describe estimates rather than measured billing.

## Listener mapping and capacity changes

Before activating a multi-listener pool, coordinate with its owner and configure
repository variable `CI_MONITOR_MAC_RUNNER_NAMES` with the exact comma-separated
listener roster on the physical Mac (1–32 unique names). Configure
`CI_MONITOR_MAC_POOL_LABEL` if queued jobs use a shared host-pool label other than
legacy `office-macbook`. These monitor variables do not register listeners or
change workflow routing. Unconfigured capacity remains unknown; it is not inferred
from the number of observed concurrent jobs. A configured roster records slots,
source and observation time in each poll, even if inventory permission is absent.
Listener online/busy/offline state still requires actual evidence and is never
inherited from a shared host heartbeat. CPU, load, memory and power are graphed
once per physical host. Historical periods without contemporaneous capacity
cannot be retrospectively normalized using today's roster.

See [CI observability design](ci-observability-design.md) for chart semantics,
research rationale, cohort comparability, bounded drilldowns and fixture policy.

## Opt-in laptop fleet (MOD-424)

The fleet is separate from the legacy office heartbeat and hosted Actions poll.
It lives under the same **Admin → Infrastructure → CI** entry. Device reporting
proves host telemetry delivery only; it does not establish runner availability,
job success, or cause of host pressure. This implementation does not enroll a
laptop, change runner routing, or enable either collector in production.

### Enrollment and removal

Apply `20261130040000_ci_monitor_fleet` through the normal backend release.
An administrator and the laptop owner must agree to enrollment. Use a dedicated
standard CI user. Create a private directory under `~/replicas/<workspace-id>/`
with mode 0700. Copy `fleet-agent.py` and `fleet-launchagent.py` there. Do not use
sudo. Run Python 3 with `fleet-agent.py --config <directory>/config.json --configure`. The interactive prompt asks for the HTTPS backend API base URL,
including `/api`. This generates a random UUIDv4 and a 256-bit credential locally
in a new mode-0600 file. It prints **only** the public UUID and SHA-256 credential
hash. No central heartbeat key is read, copied, rotated, or sent to the browser.

In the CI dashboard, expand **Enroll an opted-in device**. Enter the public UUID,
a neutral hardware label and the credential hash. This uses the existing JWT
and admin guard on both the Next.js proxy and backend. Registration authorizes
only that device's ingest path; credential A cannot report as device B. Neither
device credentials nor the legacy heartbeat key grant dashboard read access.
Hashes are write-only registration data; snapshot responses never include them.
The registry is capped at 64 devices, including revoked records. Duplicate IDs
or credential hashes fail registration. Revocation is permanent for that ID;
a new opt-in enrollment uses a new identity and credential, never reuses an ID.

Run `fleet-agent.py --config <directory>/config.json --print` first, then run it
without `--print` in the foreground. Confirm accepted real samples before using
`fleet-launchagent.py --directory <directory>` to install the per-user agent.
The installer verifies its directory and runs a counter-only check before
bootstrap. It adds only `com.moda.ci-fleet-telemetry` with background process type
and lower scheduling priority. It does not change power, personal accounts,
VMs, listeners or concurrency. No secret goes in arguments, plist or logs.
There is no KeepAlive restart loop or offline backlog. Logs expose status codes
only. Authentication failure stops collection. Scheduling every 15 seconds is
inside one Python process, not repeated launchd process startups.

Use **Revoke** and confirm in Admin to reject new samples immediately. Run
`fleet-launchagent.py --directory <directory> --remove` on the laptop to stop and
remove only this agent. Delete the private config when no longer needed.
Uninstall does not revoke server authorization; revoke as well. Never delete
or change other LaunchAgents. Restart the installed job explicitly after a
transient error that stopped the process; inspect `launchctl print
gui/$(id -u)/com.moda.ci-fleet-telemetry` locally. No installation or restart was
performed as part of implementing this feature.

### Frequency, bounds and freshness

The agent samples every 15 seconds, with bounded three-second sensor commands
and a five-second upload timeout. It drops failed uploads, never buffers or
replays stale data, and never follows redirects with its credential. The visible
dashboard polls every 15 seconds, skips hidden-tab requests and prevents
concurrent poll overlap. All requests use no-store. Device tokens are stable
until removal; they are never sent in URLs. Payloads contain only allowlisted
numeric counters and state enums, at most 4 KiB after JSON parsing. The fleet
route also has a 4 KiB HTTP JSON parser limit before the general body parser.
One accepted sample per ten seconds per device is enforced under a database row
lock across server instances. Revocation takes the same row lock through UPDATE.
No untrusted timestamp can move a device's server last-seen forward.

Device clocks must be within 60 seconds of receipt. Equal or decreasing sample
timestamps cannot overwrite current values or add history. A device is reporting
through 45 seconds after server receipt, stale after 45 seconds, and offline after
180 seconds. Never-seen and revoked are separate states. These states continue
to age in the browser when network reads fail. A reporting state is reachability,
not a claim that the host is healthy. The UI labels non-reporting readings as
historical. Device time and server receipt are both shown.

Charts return only the selected device's last hour, at most 121 latest actual
samples in 30-second buckets. Gaps are not interpolated. At most 64 latest device
samples appear in the fleet overview. History is available for 24 hours, with
physical cleanup on subsequent ingestion; no dormant-device cron is enabled.
Latest sample payloads older than 24 hours are omitted on read and cleared on
subsequent ingest. Identity, revocation and last-seen metadata persist so an old
credential cannot silently regain access. With collection stopped, historical
rows can remain on disk until the next ingest but are outside the read window.

### Sensor meanings and unsupported values

This version supports macOS using standard-user system counters. It never reads
process names, command lines, application content, Wi-Fi names, personal files,
keychain data, or provider credentials. Unsupported or denied sensors are null,
including the first rate interval and any counter decrease. Zero means an actual
measured zero. The agent does not estimate CPU temperature. Thermal pressure is
currently unavailable with this standard-library collector. `pmset -g therm`
CPU\_Speed\_Limit, when the OS exposes it, is shown separately as a reported speed
limit; it is not a temperature or a reconstructed thermal-pressure state.

* CPU: the second interval sample from `top`, 0–100% across all logical CPUs.
  Load average is a separate host signal, not CI usage. Logical cores are not
  interchangeable performance units on heterogeneous Apple Silicon.
* RAM used: active + wired + compressor physical pages from `vm_stat`, not a
  sum of applications and not total minus cache. Total RAM comes from sysctl.
  Memory pressure comes from the OS pressure enum. Swap used comes from sysctl;
  swap-in/out bytes per second use `vm_stat` counter deltas and its page size.
* Disk free: available filesystem bytes at `/`. Read/write rates sum exposed
  IOBlockStorageDriver byte counters; unsupported drivers remain unavailable.
* Network rates: non-loopback link-interface byte-counter deltas. Virtual/bridge
  interfaces can count the same traffic more than once. This is host activity,
  not unique WAN traffic or attribution to CI. No interface names are uploaded.
* Battery and AC source come from `pmset -g batt` and stay null when absent.
* CI CPU is also 0–100% across all logical CPUs. CI RSS is the sum of an explicit
  process group's resident sets; shared pages can count more than once. A 25%
  concurrency budget is a scheduling target, **not a hard CPU cap**, affinity,
  per-process limit, or evidence that a laptop has 75% idle capacity.

CI attribution is opt-in separately. `fleet-ci-group.py --state <private-file> --budget-percent 25 <CI command and arguments>` wraps exactly one CI job in a new
session and writes an owned 0600 marker every five seconds. It does not activate
CI, change workflow routing, or enforce limits. An observer can use the marker
with `fleet-agent.py --config <config> --ci-state <private-file>`. The default
LaunchAgent omits attribution until its owner deliberately configures this path.
The collector verifies marker freshness (30 seconds), owner, leader PID, group ID
and leader start time before reading numeric process-group counters. Missing,
expired, mismatched, exited or reused identities give unknown jobs/usage, not
idle. Only processes present at both interval boundaries contribute to CPU rates; short-lived children between samples are not measured. Membership changes make that interval CPU unavailable rather than attributing a cumulative-counter jump to the current interval. CI process escape from the group cannot be attributed and is excluded.
Withdrawals are only allowlisted scheduler/owner states: none, owner-paused,
battery, memory-pressure, thermal-pressure, budget, unknown. The wrapper reports
none while its job runs; a scheduler may renew the same private marker contract
with a known reason. An explicitly idle scheduler can set leaderPid/leaderStart
to null to report zero active jobs with its budget/reason. Host sensor pressure
never invents a scheduling withdrawal. The fleet routing PRs remain unchanged.

### Verification boundary

Unit tests cover sensor nulls, counter resets, private files, redirect refusal,
PID identity, CPU denominator, validation and freshness. Disposable PostgreSQL
tests cover concurrent rate limiting, isolation, revocation, ordering and history
retention. Browser fixtures are labeled synthetic and include pressure, stale,
offline, revoked, never-seen and unsupported sensors. They prove rendering only.
Before calling this live: deploy the migration/backend/UI through the normal
release, obtain owner access, enroll one opted-in laptop, verify a real accepted
sample and at least two timestamp advances, compare counters to local tools,
check withdrawal/CI marker integration with a real job, verify revocation and
removal, and measure agent CPU/RSS/network overhead with and without collection.
Hardware overhead and sensor support remain **unverified until measured**. No
power, capacity, runner, personal-account, VM or production-config change is
part of this implementation.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.