Daemon and CLI reference
The agent-watchdog daemon monitors Claude Code and Codex sessions, evaluates context and cache alerts, and publishes status for the CLI and menu bar app. It runs locally on macOS, finds terminal sessions through the session store cmux keeps, and alerts through macOS notifications. It never writes into cmux or types into an agent’s terminal.
For installation and everyday use, start with docs/usage.md. This reference
covers discovery, metrics, commands, configuration, and the status file.
Both agents support context alerts. Claude Code also supports estimated cache expiry alerts; Codex cache expiry is unavailable. A missing metric never counts as zero and does not trigger an action that depends on it.
What it does
Every poll (default every 30 seconds) the watchdog:
- Discovers sessions (cmux session store first, then a transcript scan).
- Reads the tail of each session’s transcript to get the latest token usage, model, last activity time, and prompt-cache TTL.
- Evaluates the rules: context warning, context critical, cache expiring while idle.
- Posts a macOS notification through Notification Center (via
osascript). - Persists per-session alert state so restarts do not re-alert.
- Writes a JSON status file for the menu bar app (see “Status file”; disable with
--no-status-file).
Beside the poll, a daemon that writes a status file also collects today’s
local token activity and subagent rows on its own bounded timer (see
Local activity and subagent rows), and
answers the menu bar’s Generate handoff requests through handoff generate
(see Commands). Neither appears in the CLI’s own output.
How sessions are found
The table below describes Claude Code discovery. For Codex rollout scanning, see Codex sessions.
| Source | Path | Surface known | Lifecycle known |
|---|---|---|---|
| cmux session store | ~/.cmuxterm/claude-hook-sessions.json |
yes | yes (running, idle, needsInput, unknown) |
| Transcript scan | ~/.claude/projects/*/*.jsonl |
no | no (unknown) |
The store is authoritative: it carries the session’s pid, surfaceId,
workspaceId, lifecycle, and transcript path. The surface and workspace ids are
published in the status file so the menu bar can focus the session.
One lifecycle is corrected from the transcript. About a minute into every idle,
Claude Code sends its “Claude is waiting for your input” notification, and cmux
reports needsInput from then until the next prompt. A session at a real
prompt, such as a permission request or a question, always has a tool call
waiting for its result. So a needsInput session whose transcript ends with a
reply that finished its turn, with no tool call open, is reported idle, and
cache-expiry alerts reach it. So is one whose transcript ends with Claude
Code’s “[Request interrupted by user” marker, as after a rejected permission
prompt, which runs no Stop hook. Any other needsInput session stays
needsInput.
The transcript scan (opt out with --no-scan-transcripts) catches sessions that
run outside cmux or are missing from the store. It skips files named
agent-*.jsonl (subagent transcripts) and files not modified within
--stale-after. Scanned sessions have lifecycle unknown, so the idle test for
cache-expiry alerts relies on --idle-after alone.
Sessions with no activity in the last --stale-after (default 6h) are ignored from
both sources.
Each session and subagent row in the status file carries
inactivity: { inactive, since }. A session is inactive when its lifecycle is
idle or unknown, its last activity is known and not ahead of the clock, at
least --inactive-after (default 30m) has passed since it, and its prompt
cache is not worth handing off; running and needsInput never are. The last
activity (since) is the latest transcript evidence: for Codex the later of
the newest entry and the rollout file’s mtime, for Claude the later of the last
assistant entry and the transcript file’s mtime, which moves while a tool runs.
Claude’s lastActivityAt, and with it the cache estimate and the idle test,
still use the last assistant entry. A session with a warm prompt cache worth
handing off stays in the active list: while its context is known and at or
above --cache-min-context and its cache deadline is still ahead (the same
conditions that make the cache-expiry alert eligible), it is never inactive, so
that alert never points at a hidden row. The menu bar moves families whose
members are all inactive into its collapsed Inactive section.
The field is computed like level, so status --json carries it too, and the
setting only affects presentation: rules and notifications ignore it.
Codex sessions and unavailable metrics
By default both claude and codex are monitored. Use --harnesses codex or
"harnesses": ["codex"] to select one. --session codex:<prefix> distinguishes
sessions when raw IDs overlap. Claude’s existing window and TTL settings apply
only to Claude; use --codex-context-window to override Codex capacity.
Codex discovery reads the cmux hook store and recent rollout transcripts below
<codex-home>/sessions. The fallback scan checks the 32 newest existing date
folders and at most 512 rollout files per poll; older sessions outside those
limits require a cmux store entry. Recently resumed files within those folders
are found by modification time even when the folder date is old. Context is derived from the latest usable current-request
usage, with capacity supplied by the session or the explicit override. Lifetime
usage totals are not context size. Compaction invalidates old usage until a new
sample arrives. The observed transcript shape reports Codex CLI 0.153.4.
Transcript formats vary by Codex version; unknown metrics appear
as unavailable and do not trigger dependent actions.
Codex cache TTL and expiry remain unavailable. Cache-hit token counters do not establish an expiry deadline. Context alerts, notifications and status remain available independently.
Status schema v2 includes separate model-provider identity, nullable metrics,
context source/sample time, parent session identity and a harness ID on events. Unknown context has level unknown;
the menu bar displays an unavailable indicator. The menu bar also accepts v1
status files. watch --json uses the same nullable metric semantics.
How Claude context and cache expiry are computed
Transcripts are JSON lines. The watchdog reads the tail of the file in growing
windows (256 KB, 1 MB, 4 MB, then the whole file) until it finds the last
non-sidechain assistant entry that carries usage, and caches the result per
file by size and mtime so unchanged transcripts are not re-read every poll.
-
Context tokens =
input_tokens + cache_creation_input_tokens + cache_read_input_tokensof that entry. Missing numbers count as zero. Sidechain (subagent) entries and synthetic entries without usage are skipped. -
Last activity = that entry’s timestamp.
-
Cache TTL:
cache_creation.ephemeral_1h_input_tokens > 0means one hour; otherwiseephemeral_5m_input_tokens > 0means five minutes; otherwise the default of one hour.--cache-ttloverrides detection. -
Cache expiry = last activity + TTL.
-
Context window is an estimate. There is no ground truth in the transcript. Resolution order: exact
--model-windowmatch, longest-prefix--model-windowmatch, model ids containing[1m]or ending in-1m(1,000,000), the built-in table below (longest prefix), then--context-window(default 200000). Claude Code may run a model at a smaller window than the table depending on the plan; if the percentages look wrong, set--model-window <model>=<tokens>.Model id prefix Window claude-fable-,claude-mythos-1,000,000 claude-opus-5,claude-opus-4-8,claude-opus-4-7,claude-opus-4-61,000,000 claude-sonnet-5,claude-sonnet-4-61,000,000 claude-haiku-200,000 other claude-sonnet-,claude-opus-(4.5 and earlier)200,000 anything else --context-window -
Auto-compact: Claude Code compacts on its own somewhere above roughly 90% of its window; the exact point depends on the version and the real window size, which the watchdog only estimates. Keep
--critical-contextwell below it (default 75) so the watchdog reacts before compaction discards working context.
Commands
| Command | What it does |
|---|---|
watch (default) |
Poll loop. Handles SIGINT/SIGTERM and writes a final status document on exit. |
status |
One-shot table: provider, short session id, directory, model, tokens/window, percentage, lifecycle, last activity age, cache expiry, surface, handoff location. Exit 0. With --json, one status document in the status-file schema instead (see “Status file”). |
install |
Write settings flags into the config file, write ~/Library/LaunchAgents/com.wholeclove.agent-watchdog.plist running watch with only the CLI-only flags, then load it with launchctl (see “Install as a launchd agent”). With --menubar-bin, also install the menu bar app. |
uninstall |
Unload and remove the launchd agent (and the menu bar agent when present). The config file is kept. |
link |
Symlink the built binary into ~/.local/bin/agent-watchdog (or --dir). With --menubar-bin, also link agent-watchdog-menubar. |
config schema |
Print the JSON Schema for the config file and the settings window (see “Settings schema”). config with no action or an unknown one exits 2 with a usage line. |
config validate [<path>] |
Check a config file (default: the --config path or ~/.config/agent-watchdog/config.json) and exit 0 with ok, or 2 with one line per error; --json prints { "ok": true } or { "ok": false, "errors": [{ "options", "message" }] } instead (see “Config file”). A missing file is valid. |
--help lists every flag with its default; --version prints the version.
usage-bridge bind <label> and usage-bridge ingest [-- <renderer> <args...>]
are setup and ingestion helpers for the Claude bridge.
They do not report account usage in the CLI.
handoff generate is an internal helper for the menu bar’s Generate handoff
action, not a command to run by hand. The menu bar runs the daemon binary with
a fixed argument array (--provider, --session, --cwd, --request-id,
--requested-at, --json, plus --config <path> when the daemon runs with
a custom config path and --state-file <path> with the daemon’s effective
state file, which wins over the config file’s value) and reads the single JSON result it prints; the exit
code is 0 whenever a result was printed, whatever its state, 2 for a usage or
config error, and 1 for a runtime failure. Requests are
journaled in <state-file>.handoff.json before anything is dispatched, and the
daemon projects capability and request state into the status file as an
optional actions field per session. Generation runs only through a
registered, verified provider adapter; a harness without one reports
generation as unsupported.
For Codex sessions the adapter runs an ephemeral fork of the exact thread
(codex exec fork <id> --ephemeral --skip-git-repo-check --json --output-schema <schema> -o <output> -c 'sandbox_mode="read-only"' <prompt>) in the session’s working directory with CODEX_HOME set to
codex-home, stdin closed, and cmux’s per-invocation hook injection switched
off (CMUX_CODEX_HOOKS_DISABLED=1); the fork reads the saved rollout, leaves
it untouched, persists no rollout of its own, and its structured last message
is what the helper validates and publishes. The executable is codex on the
helper’s PATH unless openai-codex-path names one, the same setting the
allowance reader uses. Generation is available when that CLI is 0.157.1 or
newer and a login exists (auth.json under codex-home, an API key in the
environment, or codex login status reporting one); otherwise the session
reports adapter-unavailable and the daemon log names the reason. Only a session cmux reports as idle is
dispatched: Codex has no idle signal of its own, so a session discovered by
transcript scan alone (no cmux surface) is refused as busy. One generation is
one model call sized by the session’s context, counted as the user’s own
usage. The fork’s schema and output live under <state-file>.handoff-work/
for the duration of the request.
For Claude Code sessions the adapter runs a non-persisted fork of the exact
session (claude -p --resume <id> --fork-session --no-session-persistence --model <session model> --tools "" --strict-mcp-config --disable-slash-commands --safe-mode --output-format json --json-schema <schema> <prompt>, the model forwarded when the session names one) in the
session’s working directory with stdin closed and
CMUX_CLAUDE_HOOKS_DISABLED=1 in its environment, so the cmux claude
wrapper injects nothing when the helper itself runs from a cmux pane; the
fork reads the saved transcript, leaves it byte-identical, writes no
transcript of its own, and its structured_output is what the helper
validates and publishes. --safe-mode keeps the user’s hooks, plugins, MCP
servers and CLAUDE.md out of the generation; --tools "" leaves the model
nothing but the structured answer. The executable is claude on the helper’s
PATH, then ~/.local/bin/claude (where the native installer puts it, which a
launch agent’s PATH does not include). Generation is available when that CLI
is 2.1.283 or newer; otherwise the session reports adapter-unavailable and
the daemon log names the reason. The adapter accepts only a session whose
transcript sits under ~/.claude/projects/<slug>/<id>.jsonl for the working
directory it names, and dispatches it only with evidence that it is idle: cmux
reporting idle, or claude agents --json listing the session as idle.
A listing outranks cmux. cmux reports a session waiting for input from
Claude Code’s idle notification onward, and the daemon corrects that to
idle only when the transcript shows the turn ended, so an idle listing
dispatches the session either way. A
listing of busy or waiting (a permission prompt or other dialog) is
refused, naming what it waits for. Without a listing, a session cmux reports
waiting for input is refused, and a session neither can vouch for, such as
one created with claude -p, is refused as busy. One generation is one model call sized by the session’s context, with
no prompt-cache read on the first fork, counted as the user’s own usage. The
fork gets SIGTERM after eight minutes and SIGKILL five seconds later if it
is still there, and is reported as failed; the helper itself answers
uncertain after two minutes and keeps settling the outcome.
Limits of manual generation, as the menu bar presents them:
- Fork first. Both harnesses generate from a fork of the saved transcript. The live session is never stopped, cleared, compacted, or sent input, and it does not learn that a handoff was written.
- Busy means no dispatch. A session mid-turn (
running) or at a real prompt is refused assession-busybefore anything is journaled. Codex sessions found by transcript scan alone are always refused this way, since nothing reports them idle; after the first refusal the menu bar keeps Generate disabled for such a row until its lifecycle changes. - The helper lingers. After printing its answer the helper can stay alive to settle a request that is still generating (up to its 600-second settling cap), then journals the outcome, which the daemon projects on its next poll. It keeps running when its caller goes away: if the menu bar app quits or closes the helper’s pipes mid-generation, the helper still finishes and records the request.
- Uncertain settles on its own. A request the helper stopped waiting for
reads
uncertainuntil the journal settles it. The daemon settles it too: when both the helper and its fork are gone, the next check marks the request failed, so Generate works again, and a helper that is still alive but wedged stops blocking once the dispatch is older than the generation and settling window, about 12 minutes. There is nohandoff acknowledgecommand to abandon a request by hand. - A cancelled Codex fork is killed. When the helper is aborted, the Codex fork gets SIGTERM and, five seconds later, SIGKILL if it is still running; its work directory is kept until the outcome is journaled.
- Executables come from settings or PATH. A menu bar app or launch agent
does not inherit a shell’s PATH. Set
openai-codex-pathwhencodexis not on the helper’s PATH; Claude is looked up on PATH and at~/.local/bin/claude, with no setting of its own yet.
See Harness capabilities for the per-harness gaps.
Plan-usage collection
The daemon can collect subscription allowances independently of session context monitoring and publish them for the menu bar. Monitoring follows each enabled harness by default. Configure it separately in the menu bar’s Settings…; an explicit on or off choice overrides the harness selection. OpenAI/Codex and Anthropic/Claude have separate source settings, warning and critical percentages, and notification toggles. Save and restart the daemon to apply changes. See plan usage for the user-facing behavior.
Codex collection reads the configured Codex home’s signed-in account through
codex app-server; it never starts a model turn. The executable can be set
explicitly with openai-codex-path, which is useful when a launch agent’s PATH
does not include Codex. Collection runs independently from session polling.
Source failures do not delay session alerts, and stale or unattributable usage
cannot trigger account notifications.
The status file carries optional accountUsage, usageFailures, and
usageEvents fields for the menu bar. Public account entries contain a safe
label and source-confidence marker, not a raw account ID, email, or credential.
The CLI’s status report remains a session report. Collection never reads
authentication files directly or changes provider settings.
Claude usage probe
Claude collection runs Claude Code’s own usage command headless every
anthropic-usage-interval (default 5m, 2m to 1h):
claude -p /usage --output-format stream-json --verbose --no-session-persistence --safe-mode --strict-mcp-config
It spends no tokens. --no-session-persistence keeps each read from writing a
transcript the daemon would then watch as a session; --safe-mode and
--strict-mcp-config keep hooks, plugins, project instructions, and MCP
servers out of it. It runs in the daemon’s state directory with the daemon’s
environment (Claude Code needs HOME, USER, and LOGNAME to find its
sign-in). The executable is anthropic-claude-path when set, otherwise
~/.local/bin/claude, then claude on PATH. Raw output is never logged or
stored.
Rows are classified on their kind: the session row becomes the 5-hour
allowance, the all-models weekly row the 7-day allowance, and each per-model
weekly row its own window (for example meter seven_day_model:fable, label
“7-day allowance (Fable)”), so a new model needs no code change. Unknown kinds
are ignored and malformed rows are dropped. The probe’s start time is the
observation time, so fresh readings (up to two intervals old) get levels from
the configured warning and critical percentages and can send Claude allowance
alerts. Claude reports only percentages, so exhaustion alerts are not
available; a full window raises the critical alert.
A fresh probe reading replaces the bridge’s windows for the whole account; the
two are never mixed. Claude Code labels this output experimental: if the probe
is off (--no-anthropic-usage-probe), failing, or stale, the daemon falls back
to the status-line bridge below, and the failure appears as a usage source
issue such as probe_timeout, probe_not_found, probe_report_missing, or
probe_malformed_output. Failed reads retry after one minute at the earliest
and one interval at the latest.
Claude usage bridge
Claude’s documented status-line payload provides quota percentages and reset times but no verifiable observation time and no per-model windows. Bridge readings are therefore historical, unknown-age, and never alert. They are the fallback for the usage probe above.
agent-watchdog install configures this bridge automatically for enabled
Claude monitoring when the Claude configuration directory exists. It changes
only the user statusLine setting, retains any renderer through passthrough,
and creates a binding only if none exists. Reinstalling keeps the binding and
recorded usage. --print previews without writing; --no-setup-usage opts out.
Sign-in and the first supported Claude status-line sample are still required.
See the installation checklist.
For manual setup, create an explicit local source binding before ingesting samples:
agent-watchdog usage-bridge bind 'Claude account'
Enable Anthropic usage monitoring in Settings. Configure your Claude status line to send its original JSON input to the quiet helper:
agent-watchdog usage-bridge ingest
That helper prints no quota report. If you already use a status-line renderer, keep it: the passthrough form forwards the original input to an executable and its arguments and relays the renderer’s output:
/absolute/path/to/agent-watchdog usage-bridge ingest -- /absolute/path/to/renderer arg1
Set this command manually in your status-line configuration after adapting the
paths. An existing shell expression should remain in your own renderer script;
the helper accepts an executable and argument list. The helper itself does not
rewrite Claude settings. Automatic installation configures this command and
passes an existing shell expression to /bin/sh -c as one quoted argument;
uninstall restores the original command if it is still managed by watchdog. The quiet form is also
available for a script that already handles feeding input to its renderer.
Both helper forms and the daemon use anthropic-usage-state; pass
--anthropic-usage-state <path> when using a custom path. Use the same path for
binding, ingestion, and daemon monitoring. State holds only normalized quota
fields, a user-selected label, opaque source identifiers, and bounded replay
tracking. It does not store the original status-line JSON or session ID.
The helper stops a passthrough renderer that runs longer than
anthropic-usage-renderer-timeout (5s by default, 500ms to 30s). Set it in the
config file or Settings rather than on the status-line command, which the
installer owns; the helper reads it on every refresh, so no restart is needed.
Claude Code enforces no deadline of its own, but it cancels a running
status-line command when the next update arrives.
A renderer that fails or exceeds its time limit does not cost the usage
sample: when the full status-line input arrived and is valid, the helper still
saves it. Claude Code discards the helper’s error output, so the helper also
records its latest failure (for example renderer_error or malformed_json)
in the bridge state. The daemon reports it as a usage source issue such as
bridge_renderer_error while no newer reading has arrived, or for 15 minutes
after it happened. The bridge keeps up to 128 recent Claude sessions and drops
the least recently heard from first, so new sessions always keep reporting.
Run usage-bridge bind again after changing Claude accounts. Rebinding clears
prior samples. For each allowance, the bridge displays the highest reported
percentage in the latest reported reset window. Usage increases and later reset
windows update the display; replays from older sessions cannot move it backward.
Existing frozen state recovers from its saved readings without rebinding.
These are historical readings with unknown observation age. A lower correction
within the same reset window cannot replace the high-water mark. Neither a new
receipt nor a changed reset establishes freshness, and bridge readings never
send Claude allowance alerts. Once a window’s reset time passes with no newer reading, the
status file keeps the window and its reset time but reports its percentage as
null, since the old value no longer describes current usage; the menu bar
shows it as unavailable until a reading for the next window arrives. An absent
window stays historical until another reading arrives; an idle or stopped
Claude session may supply no new quota data.
Flags
Durations accept ms, s, m, h, and d units, combined (2h30m) or decimal (1.5h), or a plain number of seconds. Percentages are 0 to 100. Every value is validated with a clear error and exit code 2.
See the generated option reference for all flags, defaults, command scope, config eligibility, and harness applicability.
Settings schema
agent-watchdog config schema prints a JSON Schema (draft 2020-12) describing
the daemon’s settings: one property per option that can live in a config file,
typed by how it is edited (durations as strings, percentages as numbers with a
0 to 100 range, multi-value enums such as harnesses as arrays of allowed
values, repeatable flags as arrays of strings), plus an x-groups list the
settings window renders from.
The same document is checked in at schema/settings.schema.json so editors and
the menu bar app can read it without running the CLI.
Every entry in src/cli/options.ts must carry settings metadata, either
'cli-only' (never in a file or the window: help, version, once, json,
no-status-file, config, no-config, tolerate-config-error, print,
dir, menubar-bin) or a group, control kind, and
help text. options.spec.ts checks the metadata and fails when the checked-in
schema no longer matches the options, so after changing an option run:
yarn workspace @agent-watchdog/watchdog build
yarn workspace @agent-watchdog/watchdog schema
and commit the regenerated file. The settings window is described in
docs/plans/settings-ui.md.
Config file
Every file-eligible setting can also live in ~/.config/agent-watchdog/config.json
(--config <path> reads another file, --no-config reads none), one JSON object
whose keys are the option names exactly as they appear on the command line:
{
"$schema": "/path/to/agent-watchdog/apps/watchdog/schema/settings.schema.json",
"warn-context": 40,
"cache-lead": "15m",
"scan-transcripts": false,
"harnesses": ["claude"],
"cwd": ["~/projects/a", "~/projects/b"]
}
Values are typed by the option’s control: toggles are booleans
("scan-transcripts": false is --no-scan-transcripts), durations are strings in
the flag syntax, percentages and numbers are numbers (a numeric string is accepted
too), paths are strings, repeatable flags are arrays of strings, and multi-value
enums such as harnesses are arrays of the allowed values. $schema is allowed and ignored by the daemon; point it
at the checked-in schema/settings.schema.json so an editor validates hand edits. Anything else the CLI
would reject, the file is rejected for as well: an unknown key, a CLI-only flag
(json, once, no-status-file, config, …), a wrong type, a percentage
outside 0 to 100, an unknown enum value, or the critical threshold at or below the
warning one. config validate [<path>] runs exactly those checks; use it after
a hand edit.
Precedence is flag > file > built-in default. The file only fills in
settings no flag set. install never bakes a setting into the launch agent;
it writes settings flags into this file and moves settings an older install
baked into the plist here too, so the file is the one place the daemon’s
settings live (see “Install as a launchd agent”). Two rules read the flags
only, never the file: watch --once skips the status file unless
--status-file was given as a flag (a path in the file does not count), and
the file’s own path comes from --config or --no-config. The status document
reports where every setting came from in configSources.
A bad file. watch, status, install, uninstall, and link exit 2
with the error, the way a bad flag does, so a mistake stops a foreground run
(--no-config skips the file when you need to run one of them regardless). Under launchd the
daemon must stay alive (KeepAlive would otherwise restart it into a loop with
nothing watching sessions), so install always bakes --tolerate-config-error
into the daemon plist, whether or not you pass it. A foreground watch exits 2
on a bad file unless you pass the flag yourself. With that flag the daemon
starts on flags plus built-in defaults,
logs the failure at error level, posts one macOS notification saying the config
file was ignored, and publishes configError
(message, path, at) in every status document until it is restarted with a
fixed file. config schema and config validate never read the file for their
own settings, so they keep working while it is broken.
Handoff files
Every poll, the Claude provider checks whether the session’s handoff file exists
at either documented location, by stat alone (it never scans the transcript):
<cwd>/handoff-<sessionId>.md, the repo root; or/private/tmp/claude-<uid>/<project-slug>/<sessionId>/scratchpad/handoff-<sessionId>.md, the session’s scratchpad, where<project-slug>is the dash-encoded working directory that also names the session’s~/.claude/projects/<slug>transcript directory.
When both exist, the newer mtime wins. The result is the session’s handoff
field in the status document and watch --json, the HANDOFF column of
status, and, when a session goes from no file to a file, one handoff event
in the status document plus an info log line. The check repeats every poll, so
a deleted file drops the field back to null. Nothing is notified and a missing
handoff is never alerted on. If the repo must stay clean, add handoff-*.md to
its .gitignore or have the agent write to the scratchpad.
The Codex provider checks for handoff-codex-<sessionId>.md in the session’s
working directory (location repo), or in the directory named by
--codex-handoff-dir when it is set (location external). There is no
scratchpad location for Codex. Everything else (the handoff field, the
HANDOFF column, the handoff event) behaves the same for both harnesses.
When you ask an agent for a handoff, request a fixed structure so the next session (or the user) can pick the work up without re-deriving anything. A header with the time, the session id, and the repo with its branch and commit, then these sections, in order:
# Handoff
- Written at: 2026-09-12T14:03:27.000Z
- Session: aaaaaaaa-0000-4000-8000-000000000001
- Repo: /Users/me/projects/agent-watchdog (branch feat/handoff-template, commit 04d43cf)
## Milestone
The objective this session is working toward.
## Plans and references
- docs/plans/handoff-template.md
- PR #12, ticket ABC-42, the design doc being followed
## State
What is done, what is in flight, and what the working tree looks like.
## Decisions
Choices made and why.
## Open questions
Anything unresolved that the next session or the user must settle.
## Next steps
1. The most important step first.
2. Then the rest.
Rules
- Warning: notify once when usage reaches
--warn-context. - Critical: notify once when usage reaches
--critical-context. The notification asks you to have the agent write a handoff. - Cache expiry: when usage is at or above
--cache-min-context, the cache is still alive but expires within--cache-lead, and the session is idle (lifecycleidle, or no activity for--idle-after), notify once. A cache that has already expired never triggers this rule: a handoff is no cheaper than continuing at that point (statusshows how long ago it lapsed, such as12m ago). - Hysteresis: each threshold fires once per crossing and re-arms when usage drops 5 points below it (after compaction or a new context). The cache-expiry alert re-arms when the cache is refreshed (expiry moves outside the lead) or usage drops below the minimum minus 5.
- State: kept in the state file so restarts do not re-alert. Sessions not seen for 24 hours are dropped, so a session that sits idle longer than that re-alerts once when it resumes above a threshold.
Status file
After every poll (including --dry-run, which simulates notifications but still
writes this file) the daemon
writes ~/.local/state/agent-watchdog/status.json (--status-file, next to
state.json; --no-status-file disables it). The write is atomic: <path>.<pid>.tmp
is written and renamed into place, so a reader never sees a partial file. On a
clean shutdown (SIGINT, SIGTERM) it is written one last time with stoppedAt set.
watch --once never writes the default status file, not even the final stoppedAt
document, so a one-shot run next to the installed daemon cannot make the menu bar
app report the daemon as stopped. To capture a one-shot run’s document, pass
--status-file <path> explicitly; it is then written after the poll and once more
with stoppedAt set, exactly as for the long-running daemon. agent-watchdog status --json prints the same document to stdout
without touching any file (daemonPid, startedAt, stoppedAt are null,
events is empty, at is now).
The reader is meant to render the file as-is: level is already derived from the
daemon’s --warn-context and --critical-context, so a reader never re-implements
thresholds. Schema (version 2; every timestamp is ISO-8601 with milliseconds and
a Z suffix):
| Field | Type | Meaning |
|---|---|---|
version |
2 |
Schema version. |
daemonPid |
number or null | Pid of the writing daemon; null from status --json. |
startedAt |
timestamp / null | When the daemon started. |
at |
timestamp | When this document was produced (end of the poll). |
stoppedAt |
timestamp / null | Set only by the final write of a clean shutdown. |
intervalMs |
number | Poll interval. |
config |
object | warnContextPct, criticalContextPct, cacheMinContextPct, cacheLeadMs, dryRun, plus settings: every file-eligible option by its name (warn-context, …) with the value the daemon runs with, normalized (durations in milliseconds, lists and multi-value enums as arrays, paths expanded, null for an optional setting that is not set). |
configFile |
object or null | { path, loadedAt, changedSinceLoad }: the config file consulted, when it was read (the daemon’s start), and whether its mtime differs from the one read, or it appeared or disappeared since (checked before every write; a restart applies the change). Null under --no-config. |
configSources |
object | Per file-eligible option name (warn-context, …), cli, file, or default: where the running value came from. |
configError |
object or null | { message, path, at } while the daemon runs on flags and defaults because its config file was ignored under --tolerate-config-error; null when the file loaded or none was consulted. |
sessions[] |
array | One entry per session after --session/--cwd filtering, in discovery order (status --json sorts by percentage). |
sessions[].provider |
string | Harness ID: claude or codex. |
sessions[].modelProvider |
string or null | Backend identity reported by the harness, separate from harness ID. |
sessions[].sessionId, shortId |
string | Full id and its first 8 characters. |
sessions[].cwd, dirName |
string | Working directory and its basename. |
sessions[].model |
string | Model id from the transcript. |
sessions[].contextTokens, contextWindow |
number or null | Tokens in context and the estimated window. |
sessions[].contextPct |
number or null | Usage percentage, rounded to one decimal. |
sessions[].level |
ok, warn, critical, unknown |
critical at or above criticalContextPct, warn at or above warnContextPct, else ok. |
sessions[].lifecycle |
string | running, idle, needsInput, unknown. |
sessions[].source |
store or scan |
How the session was discovered. |
sessions[].lastActivityAt, cacheExpiresAt |
timestamp | Last assistant activity and estimated cache expiry. |
sessions[].cacheTtlMs |
number or null | Detected or forced cache TTL. |
sessions[].surfaceId, workspaceId |
string or null | cmux ids; null for scanned sessions. |
sessions[].handoff |
object or null | { path, writtenAt, location } when the session’s handoff file exists (handoff-<sessionId>.md for Claude Code, handoff-codex-<sessionId>.md for Codex) in the working directory (location repo), the Claude session scratchpad (scratchpad), or --codex-handoff-dir (external); path is absolute, writtenAt is the file’s mtime. Newer file wins; null when absent. |
sessions[].actions |
object or absent | Optional, from a daemon with the handoff coordinator: { schemaVersion: 1, handoff: { capability, reason, request } }. capability is supported, unsupported, or unknown; reason is a reason code such as adapter-unavailable; request is the latest journaled request for the session (requestId, state, updatedAt, reason) or null. Absent from status --json. |
events[] |
array | The last 20 events of the daemon’s lifetime, newest last: notifications and handoff sightings. Empty from status --json. |
providerFailures |
array | Harness IDs and diagnostic reasons for incomplete discovery; an empty array means no adapter failures. |
events[].at |
timestamp | Poll in which the action ran. |
events[].provider |
string | Harness ID for the event. |
events[].sessionId, shortId, dirName |
string | The session it concerned. |
events[].kind |
notify, handoff |
Notification sent, or a handoff file appeared for the session. An older daemon’s inject events are read by the menu bar as an unknown kind. |
events[].level |
warn, critical, info |
Notification level; always info for handoff events. |
events[].text |
string | <title>: <body> for notifications; <dirName>: handoff written at <path> for handoff events. |
events[].dryRun |
boolean | True when the action was only simulated (--dry-run). Always false for handoff events. |
Process internals (pid, transcript path, executable) are deliberately absent.
Staleness rule for readers: the daemon rewrites the file every intervalMs, so
treat now - at > 2.5 * intervalMs as “daemon not running” (crashed, killed, or
its polls are failing: a failed poll writes nothing rather than claiming there are
no sessions). A non-null stoppedAt means it stopped cleanly. The events buffer
lives in memory only; a restart starts it empty.
Local activity and subagent rows
The daemon’s status file also carries two optional sections that
status --json, watch --json, and the terminal table never include; they
exist for the menu bar alone:
sessionActivity(its ownschemaVersion1): today’s locally observed token activity per session and per family, with coverage, reasons, and the aggregation cutoff. Contract and reader:src/activity/model.ts. Completed and historical sessions stay in it after they leavesessions[]. A disabled harness is left out and reported asharness-disabled;--no-scan-transcriptslimits discovery to the store-listed sessions and their subagents and reportsscan-disabled. These are observed tokens, not plan allowance or cost.childSessions(schemaVersion1): live subagent context rows, each built from the child’s own transcript like asessions[]entry, pluschildHealth(lifecycle evidence;unknownunless a parent transcript proves more),cacheEvidence,focusTarget: null, andcapabilityGaps.harnesses[]records per harness when the rows were read and whether the last read failed. Children never appear insessions[], so rules and alerts are unchanged.
Collection runs on its own timer (the poll interval, at least 5 seconds) in
passes bounded to about 250 ms and 8 MiB of transcript reads, so the session
poll never waits for it. Accounting state lives in <state-file>.activity.json
(seven days of numeric records, no transcript text) with a
<state-file>.activity.json.lock naming the owning daemon; a second daemon on
the same state file leaves activity alone. A failed collection keeps the last
published section, whose cutoffAt then ages.
Coverage stays partial until every transcript in scope has been read to its
end; a pass that stops early, even on a batch with nothing to count, leaves the
source pending. A Claude transcript line longer than one read window is
skipped and its source marked unsupported-format, so accounting moves on
instead of stalling on it. A Codex line that is still being written is kept
until it is complete, or consumed as malformed once the file has been quiet
for 60 seconds, so coverage can read partial for up to about a minute while
a Codex turn is written. A family whose root session did no work of its own
today is still published with its members’ totals; the root then has no
record of its own.
Harness capabilities
What each harness supplies, where it comes from, and what is missing. A missing capability is reported as unknown, not reported, or unsupported; it is never shown as zero or as fresh.
| Feature | Claude Code | Codex |
|---|---|---|
| Context | Supported. The last non-sidechain assistant usage in the transcript; the window is estimated from the model table or overrides (see How Claude context and cache expiry are computed). |
Supported. The latest usable current-request usage in the rollout; capacity from the session or --codex-context-window (see Codex sessions). |
| Cache expiry | Estimated: last activity plus the TTL detected from the transcript’s cache-creation fields. Not observed from the provider, and the observation time is not reported. | Not reported. Codex records no cache deadline; cache-hit counters do not establish one. |
| Activity totals | Supported. One observation per assistant message.id from root and subagent transcripts; own work is input plus output, with cache reads a portion of input. Records carry no model provider, so the menu bar names the harness instead. |
Supported. token_usage_record per response_id; cumulative counters are compared, never summed. A fork’s inherited prefix is not counted, and growth without a proven baseline is reported as unallocated with partial coverage. |
| Child discovery | Supported. <project>/<sessionId>/subagents/agent-*.jsonl, linked through the entries’ sessionId and .meta.json parentAgentId. Children reach the status file through childSessions. |
Supported. session_meta.parent_thread_id in each rollout. A child the session poll already lists stays an ordinary sessions[] row with its own actions; others reach childSessions. |
| Child health | Unknown. Claude writes no completion marker in the child, the parent, or .meta.json, so every Claude subagent reports unknown with no evidence. |
From the parent transcript: started, interacted, completed, or interrupted, with its observation time. |
| Manual handoff | Supported with Claude Code 2.1.283 or newer: a non-persisted, safe-mode fork, dispatched only when claude agents lists the session idle or cmux reports it idle. One real generation through the menu bar has been verified. |
Supported with Codex CLI 0.157.1 or newer and a login: an ephemeral read-only fork, dispatched only for a session cmux reports idle. Transcript-scan sessions are refused as busy. One real generation has been verified: a disposable session in a cmux pane, one handoff generate, succeeded with the artifact, result and journal hashes matching and the rollout unchanged. The session must be started through cmux’s codex wrapper, the normal way in cmux, so that cmux reports it idle. |
Known gaps:
- Claude child health stays unknown until Claude Code writes a completion marker somewhere the daemon can read. Subagent rows therefore never show a Claude subagent as finished.
- The Claude child listing is not metered. Claude subagent rows are read on the activity timer from the provider’s own listing, bounded by its per-poll file cap and tail cache, but not counted against the activity pass’s time and byte budget as Codex child reads are.
- No section total from the daemon.
sessionActivitypublishes per-session and per-family totals only. The menu bar’s headline is its sum of each session’s own total, and it counts sessions without a figure as not measured. Follow-up: the daemon should publish the section total and the unmeasured count itself. - A disabled harness can leave coverage partial for days. A source that
was still pending when its harness was disabled, or left scope, keeps
scan-budget-exhaustedin the top-level coverage until retention prunes it, up to seven days. - Change detection differs between harnesses. Claude cursors fingerprint the 4 KB before the read offset and Codex cursors 256 bytes, and their rules for skipping an unchanged file differ. The Codex discovery index lives in memory, so a daemon restart probes every rollout again.
- A local slash command keeps
needsInput. After a command Claude Code answers locally, such as/context, the transcript does not end with a finished reply, so a session cmux reports as waiting for input staysneedsInputinstead of being corrected toidle. Cache-expiry alerts do not reach it until the next turn; Generate still dispatches whenclaude agentslists it idle. - The popover’s session list is not lazy. Every row is built on each refresh, at roughly 3 ms and 1 MB per row, which becomes noticeable beyond about 250 rows. Follow-up: a lazy list.
- The popover’s header does not scroll. On a very short screen, a header holding several notices plus a message line can clip the title and the footer. This needs a visible screen area well below any current Mac’s.
- Legacy stuck
uncertainentries need a manual clear. Current builds settle a request whose helper and fork died, but a Claude Code request leftuncertainby an earlier build when its helper and fork died mid-generation (for example after the menu bar quit or a crash) carries evidence the current build cannot check, so it never settles and Generate stays disabled for that session. There is nohandoff acknowledgecommand yet. To clear it, stop the daemon, delete the session’s entry (keyedclaude:<sessionId>) underentriesin the journal<state-file>.handoff.json(by default~/.local/state/agent-watchdog/state.json.handoff.json), and start the daemon again. - Session filters do not narrow activity.
--sessionand--cwdlimit context monitoring, not activity collection.
Examples
With the defaults:
agent-watchdog watch
Alerts at custom thresholds:
agent-watchdog watch --warn-context 50 --critical-context 80
Cache-expiry alerts for sessions above 20% context, 15 minutes ahead:
agent-watchdog watch --cache-min-context 20 --cache-lead 15m
See what would happen without doing anything:
agent-watchdog watch --once --dry-run --verbose
Machine-readable output per poll (one line of raw session snapshots plus their actions; this is not the status-file schema):
agent-watchdog watch --json --no-status-file
The current sessions as one JSON document in the status-file schema, without running the daemon:
agent-watchdog status --json
Install as a launchd agent
A packaged download (see apps/site/README.md) ships as a single
agent-watchdog executable with a Node runtime built in, not the
dist/bin/agent-watchdog.js tree a source checkout builds. In that mode the
daemon reads its version from a package.json asset embedded in the
executable rather than a sibling file on disk, and expects
schema/settings.schema.json as a real file next to the binary — install
writes the config file’s $schema pointer there. Everything below works the
same either way; where the two differ (the plist’s ProgramArguments, the
PATH it bakes, what link symlinks) is called out under “The plist”
below.
Build first, then install with the settings you want the daemon to run with:
yarn workspace @agent-watchdog/watchdog build
node apps/watchdog/dist/bin/agent-watchdog.js install --warn-context 40 --critical-context 80
What goes where. install splits its flags in two:
- Settings (every flag that can live in the config file: thresholds, polling,
session filters, paths,
--verbose,--dry-run) are written to~/.config/agent-watchdog/config.json, or to the file named by--config. Only the keys given are written; other keys already in the file are kept. The file is written whole under a temporary name and renamed into place, gets a$schemapointer to the checked-in schema when it is created, and is run through the same checks asconfig validatefirst: if the merged file would be invalid (say--critical-context 50over a file that setswarn-contextto 60),installprints the error, writes nothing, and exits 2. Change a setting later by editing the file (or through the settings window) and restarting the daemon; no reinstall needed. - CLI-only flags that apply to
watch(--json,--no-status-file,--config <path>,--no-config) are baked into the plist, plus--tolerate-config-error, whichinstallalways adds so the daemon survives a bad config file (see “Config file”).--configis baked so the daemon reads the same fileinstallwrote.--no-configtogether with a settings flag is an error (exit 2): with no file the setting would have nowhere to go, andinstallnever bakes one.
Older installs. Before the config file existed, install baked every
flag into the plist. When a plist is already installed, install reads it
(plutil -convert json) before replacing it and looks at the settings baked
after watch:
- With no config file yet, those settings are moved into the new file and
each one is printed (
moved --warn-context 60 from the launch agent into ...). A flag given to thisinstallwins over a baked value of the same setting (replaced --warn-context 60 ... with --warn-context 40). - With a config file already present, the baked settings are dropped with a
notice (
dropped --warn-context 60: ...) and the file is left alone, so a reinstall never silently changes settings the file manages. Set them in the file if you still want them. - A baked flag this build no longer knows is skipped with a notice instead of failing the install.
The plist. install writes
~/Library/LaunchAgents/com.wholeclove.agent-watchdog.plist. Its
ProgramArguments depend on how the daemon is running: from a source
checkout, absolute paths for node then the built script; from a single
downloaded executable, just that executable’s absolute path, with no node
entry — either way followed by watch and the same flags. The PATH it
bakes follows the same split: from a source checkout, the directory of the
node binary that ran install (there is none to add for a downloaded
install), then /opt/homebrew/bin, /usr/local/bin, /usr/bin, and /bin
(for osascript, launchctl, and the Codex CLI). RunAtLoad
and KeepAlive are enabled, ProcessType is Standard (not Background,
whose throttled disk reads can stall the daemon’s session scan for minutes),
and it logs to
~/Library/Logs/agent-watchdog/stdout.log and stderr.log. It then boots out
any previous instance and waits (up to 5 seconds) for launchd to finish tearing
it down, loads the agent with launchctl bootstrap gui/<uid> (retrying a few
times while launchd is still busy, then falling back to launchctl load -w),
and verifies with launchctl print that launchd kept the job. If it did not,
install prints an error saying the agent is not loaded and exits 1 instead of
claiming success; re-run it once launchd has settled. link follows the same
split: it symlinks the built script from a source checkout, or the executable
itself from a downloaded install.
Preview. install --print writes nothing: it prints the plist, then
any migration notices prefixed with would have, then, when the config file
would change, would write <path>: followed by the file’s new contents.
Uninstall. uninstall boots the agent out, waits for launchd to report it
gone, and removes the plist, so uninstall && install back to back is safe.
The config file is kept (it says so when one exists); delete it by hand to
reset the settings.
Rebuilding does not require reinstalling: the plist points at dist/, so
launchctl kickstart -k gui/$(id -u)/com.wholeclove.agent-watchdog restarts it
on the new build. The same restart command picks up a changed config file.
To also start the menu bar app at login, build it and pass its binary:
yarn workspace @agent-watchdog/menubar build
node apps/watchdog/dist/bin/agent-watchdog.js install --menubar-bin \
apps/menubar/.build/release/agent-watchdog-menubar
--menubar-bin must name an existing executable file (exit code 2 otherwise).
install then also writes
~/Library/LaunchAgents/com.wholeclove.agent-watchdog-menubar.plist (RunAtLoad,
KeepAlive off so quitting the app sticks until next login, ProcessType
Interactive, the same PATH, logs to menubar.stdout.log and menubar.stderr.log
in the same log directory) and loads it. install --print prints both plists.
uninstall boots out and removes the menu bar agent too when its plist is present.
Running from a cmux terminal
yarn workspace @agent-watchdog/watchdog build
node apps/watchdog/dist/bin/agent-watchdog.js link
agent-watchdog status
link symlinks ~/.local/bin/agent-watchdog to the built script and marks it
executable; yarn build must have run first. Use --dir for another directory and
make sure it is on your PATH. With --menubar-bin <path> it also symlinks
agent-watchdog-menubar in the same directory to that binary. An existing entry is
replaced only when it is already a symlink; a real file is never touched.
Menu bar app
apps/menubar is a native macOS menu bar app. Its popover reads the status file
and shows allowance cards, each session’s level, cache, and handoff, and the
sessionActivity totals and childSessions rows; it never re-derives thresholds
or parses transcripts, and its Generate handoff button runs handoff generate.
See apps/menubar/README.md for building and running it, and “Status file”
above for what it reads.
Troubleshooting
- Notifications do not appear: every notification is posted through
osascriptand shows under the Script Editor identity; allow it in System Settings, Notifications, and check Focus. The daemon never runs cmux. - Sessions missing from the store: the store is written by cmux’s Claude Code
hooks. Sessions started outside cmux, or before the hooks were installed, only
appear through the transcript scan (no surface for the menu bar to focus,
lifecycle
unknown). Check~/.cmuxterm/claude-hook-sessions.jsonand runagent-watchdog status --verbose. - Wrong window size: percentages are estimates from the built-in model table
(or
--context-windowfor unknown ids). A session above 100% means the real window is larger; add--model-window <model>=<tokens>for the model shown instatus. - No alerts after a restart: state is persisted; use a fresh
--state-fileor delete the default one to re-alert. - Daemon seems stuck after an upgrade: run
agent-watchdog installagain (or checklaunchctl print gui/$(id -u)/com.wholeclove.agent-watchdogfor ProcessType). An older plist withProcessTypeBackgroundlets macOS throttle the daemon’s disk reads until it stops writing status. Reinstalling rewrites it asStandardand reloads the agent. - launchd agent not running: check
~/Library/Logs/agent-watchdog/stderr.logandlaunchctl print gui/$(id -u)/com.wholeclove.agent-watchdog.installwaits for a previous instance to unload and verifies the job after loading it, so aninstallthat printedloaded via ...and exited 0 did leave a job behind; aninstallthat ended withis not loaded(exit 1) means launchd refused or dropped the job, usually because a bootout was still in flight. Re-runinstall; if it keeps failing,launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.wholeclove.agent-watchdog.plistshows launchd’s own error. - Menu bar app says the daemon is not running: the status file is older than
2.5 poll intervals. Check the daemon logs above; a
status file write failedline means the path is not writable.
Extending with a new harness
Implement SessionProvider from src/providers/provider.ts, then register its
factory in src/providers/registry.ts. Both watch and status use this registry.
The compatibility field provider identifies the harness; modelProvider identifies
its backend independently. Put backend window/cache policies in src/model-providers
and session decoding in the adapter. Shared cmux store parsing lives in
src/hosts/cmux/store.ts.
Use null for unavailable context/cache metrics. Keep harness parsing out of the rules and presentation layers. Add fixture tests for each supported transcript shape.
Development
yarn workspace @agent-watchdog/watchdog build
yarn workspace @agent-watchdog/watchdog typecheck
yarn workspace @agent-watchdog/watchdog lint:check
yarn workspace @agent-watchdog/watchdog test
The rules engine (src/rules.ts) is pure and fully unit-tested; transcript
parsing, cmux store decoding, the notifier and action executor, and launchd
generation are tested with in-memory fakes. Nothing shells out in tests.