Skip to content

feat(supervise): make watcher liveness daemon-owned and always-on - #100

Closed
harsh9200 wants to merge 4 commits into
kunchenguid:mainfrom
harsh9200:fm/watcher-guardian-w3
Closed

harsh9200 wants to merge 4 commits into
kunchenguid:mainfrom
harsh9200:fm/watcher-guardian-w3

Conversation

@harsh9200

Copy link
Copy Markdown

Intent

The developer was working on the firstmate agent-supervision system and needed to fix a structural flaw where the watcher process (bin/fm-watch.sh) was one-shot and relied entirely on firstmate re-arming it every turn, so a skipped re-arm silently stopped supervision (which had already caused a ~69-minute gap). Their goal was to promote the supervisor daemon (bin/fm-supervise-daemon.sh) from afk-only to an always-on, per-home liveness guardian with two modes in one long-lived process: afk-on behavior unchanged, and a new present/afk-off mode that only restores the watcher and injects exactly one nudge when it detects a genuine liveness lapse (work in flight plus a missing or stale beacon). They imposed strict constraints: maintain exactly one watcher and one lock owner with no double-arming under any race, keep everything home-scoped with no broad pkill that could kill sibling or secondmate homes, start the daemon at bootstrap and recovery (not just /afk), and never inject for routine wakes. Required deliverables included a guardian-arm script, rewrites of AGENTS.md sections 8/5/3/2 and the afk SKILL.md, and tests covering all seven acceptance criteria. They also mandated exactly one Codex review pass over the committed diff (focused on the double-watcher race, home-scoping, and the inject-when-present rule) before running the no-mistakes validation pipeline, treating an external spec file as authoritative while keeping the present-mode change minimal and validating hard since this is the live fleet's supervision backbone.

What Changed

  • Promoted the supervisor daemon (bin/fm-supervise-daemon.sh) from afk-only to an always-on, per-home liveness guardian: one long-lived process now runs two modes toggled in-process by state/.afk. Present mode (afk off) does not own the watcher and only restores a lapsed watcher plus injects exactly one nudge when it detects a genuine liveness lapse (work in flight with a missing or stale beacon); away mode behavior is unchanged. Restore and signaling stay home-scoped via the lock-recorded pid, never a broad pkill.
  • Added bin/fm-guardian-arm.sh, a singleton-safe starter that no-ops when a live daemon already holds the home (with a pid-identity check on the pidfile so a recycled pid is not mistaken for the daemon), and wired bin/fm-bootstrap.sh to arm it at session start so the watcher is guaranteed alive without depending on per-turn re-arm discipline.
  • Rewrote the relevant AGENTS.md sections and afk/SKILL.md, refreshed docs/, README.md, and CONTRIBUTING.md, and added tests/fm-guardian.test.sh and tests/fm-guardian-present-e2e.test.sh covering all seven acceptance criteria (lapse detection, exactly-one-nudge cooldown, fresh-beacon/no-work no-ops, singleton-safe restore with no fork stacking, home-scoped takeover, and the afk B->A->B transition).

Risk Assessment

✅ Low: The change is well-bounded, extensively tested (12 units + 3 e2e covering all seven acceptance criteria), home-scoped and singleton-safe with real-process verification, docs consistent with code, and the round-1 fix correctly applied; the only remaining items are well-mitigated info-level tradeoffs.

Testing

Ran the two new guardian suites and four adjacent suites under the repo's CI command on macOS bash 3.2 with tmux 3.6b; all passed. Beyond the passing tests, I drove the real supervisor daemon through the exact failure mode the change targets (a missed watcher re-arm) and captured the operator-visible result: the daemon restored the watcher itself and delivered exactly one sentinel-marked liveness nudge to firstmate's pane, produced no routine-wake spam, and shut down cleanly. No screenshot/GIF artifact applies because this is a backend tmux-supervision daemon with no rendered UI; the equivalent product-level evidence is the captured supervisor-pane transcript and daemon log, both saved to the evidence dir.

Evidence: Real-daemon lapse->restore->single-nudge->clean-shutdown transcript

### SETUP: ship task in flight, watcher re-arm lapsed (no beacon) beacon present before daemon: NO ### daemon started in PRESENT mode (afk OFF), pid 45073 beacon restored by daemon: YES watcher lock pid now held: 45155 ### firstmate's pane received: INJECTION supervision liveness lapsed - draining the wake-queue and resuming nudge count: 1 ### no routine spam: nudges before idle window: 1 after 6s healthy: 1 ### clean shutdown: pidfile removed YES; singleton lock removed YES; forked watcher reaped YES

### SETUP: a ship task is in flight, but the watcher re-arm has lapsed (no beacon)
beacon present before daemon: NO

### Starting the always-on supervisor daemon in PRESENT mode (afk OFF)...
daemon pid: 45073

### Waiting for the guardian to detect the lapse, restore the watcher, and nudge once...
beacon restored by daemon: YES
watcher lock pid now held: 45155

### What firstmate's pane received (INJECTION = sentinel-marked internal message):
----------------------------------------------------------------------
INJECTION	supervision liveness lapsed - draining the wake-queue and resuming
----------------------------------------------------------------------
nudge count: 1

### Confirming NO routine spam: watcher healthy, 6s of silence expected...
nudges before idle window: 1   after 6s healthy: 1   (must stay 1)

### Relevant daemon log lines:

### Clean shutdown on SIGTERM...
pidfile removed:       YES
singleton lock removed: YES
forked watcher reaped: YES

### Artifacts written to /var/folders/cs/7fdvl2j92sd9x9t5l763vn_c0000gn/T/no-mistakes-evidence/01KW2XVRE176FSJJNNSMN8ZBZM
Evidence: Supervisor pane content firstmate actually received (sentinel-marked injection)

INJECTION supervision liveness lapsed - draining the wake-queue and resuming

INJECTION	supervision liveness lapsed - draining the wake-queue and resuming
Evidence: Daemon log: always-on two-mode startup + present-mode liveness restore

daemon starting; always-on, two-mode; afk=off (afk on=away/own+escalate, off=present/liveness-guardian); guardian_tick=2s; guard_grace=2s afk off: released watcher ownership (present mode: liveness guardian only) guardian: liveness lapse — restored watcher and nudged firstmate daemon shutting down

[2026-06-27T03:50:29+0530] daemon starting (pid 47096); always-on, two-mode; target=%0; target_source=FM_SUPERVISOR_TARGET; afk=off (afk on=away/own+escalate, off=present/liveness-guardian); guardian_tick=2s; guard_grace=2s; inject_skip='heartbeat'; stale_escalate=999999s; batch=0s
[2026-06-27T03:50:29+0530] afk off: released watcher ownership (present mode: liveness guardian only)
[2026-06-27T03:50:32+0530] guardian: liveness lapse — restored watcher and nudged firstmate
[2026-06-27T03:50:38+0530] daemon shutting down
Evidence: Present-mode e2e suite output (criteria 1,3,4,6)

ok - present: a liveness lapse restores the watcher and nudges exactly once, then stays silent (criteria 1, 3) ok - afk toggles mode in one running process: B->A self-handles+escalates, A->B returns to present (criterion 4) ok - clean shutdown: SIGTERM removes the pidfile + lock and reaps the forked watcher (criterion 6) all present-mode guardian e2e tests passed

ok - present: a liveness lapse restores the watcher and nudges exactly once, then stays silent (criteria 1, 3)
ok - afk toggles mode in one running process: B->A self-handles+escalates, A->B returns to present (criterion 4)
ok - clean shutdown: SIGTERM removes the pidfile + lock and reaps the forked watcher (criterion 6)
all present-mode guardian e2e tests passed

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

⚠️ **Review** - 2 infos
  • ℹ️ bin/fm-supervise-daemon.sh:902 - The daemon's supervisor target (FM_SUPERVISOR_TARGET) is discovered once at startup from TMUX_PANE and never refreshed in the loop. Because the daemon is now always-on and deliberately survives firstmate restarts (bootstrap/recovery's guardian-arm no-ops for a live daemon), a firstmate that restarts in a different/reused tmux pane leaves the daemon holding a stale target. Blast radius is small and well-mitigated: the core guarantee (restoring the watcher) does not depend on the pane, and _inject_marked defers when the pane is gone, with fm-guard.sh's banner as the human-visible backstop; only nudge delivery degrades (deferred if the pane is gone, or mis-delivered in the rare reused-pane case). There is also no documented daemon-restart path to force a target refresh. Noting as a deliberate tradeoff of the survive-restart design.
  • ℹ️ bin/fm-guardian-arm.sh:37 - daemon_alive() trusts the pidfile's pid with only a kill -0 liveness check, no identity verification (unlike the daemon's own portable lock, which checks pid-identity). After an unclean daemon death (kill -9 / OOM, which leaves a stale pidfile), if that pid is later recycled to an unrelated live process, guardian-arm will falsely conclude the daemon is running and no-op, so no liveness guardian gets started for as long as that recycled process lives. The daemon's lock protects against double-running but not against this false no-op. Impact is bounded: liveness then falls back to firstmate's own re-arm plus the fm-guard.sh banner (pre-change behavior), so supervision degrades rather than goes silent. A cheap hardening would be to confirm the pid is actually a fm-supervise-daemon process before trusting the pidfile.

🔧 Fix: harden guardian-arm daemon_alive with pid-identity check
2 infos still open:

  • ℹ️ bin/fm-supervise-daemon.sh:728 - guardian_restore_watcher decides reap+re-fork via ! kill -0 "$GUARDIAN_WATCHER_PID". Verified on this macOS host that kill -0 returns failure for an unreaped zombie child, so the path works on the target platform. On Linux, kill -0 returns success for an unreaped zombie, so a guardian-forked watcher that exited but is not yet reaped would be treated as alive and never re-forked, weakening the guardian's self-restore. Mirrors the preexisting Mode A idiom at line 1082 and is well-mitigated: firstmate's nudged re-arm and the cooldown-gated re-nudge still recover supervision. Latent cross-platform robustness point, not a regression.
  • ℹ️ bin/fm-supervise-daemon.sh:744 - guardian_step restores the guardian's own untracked watcher fork BEFORE nudging firstmate (line 744 then 747). firstmate's post-nudge re-arm (fm-watch-arm.sh:133-136) then no-ops against the guardian's now-healthy watcher, so firstmate never reclaims a harness-tracked watcher. An idle present-mode firstmate would receive subsequent wakes only via the durable wake-queue plus the guardian's next ~FM_GUARD_GRACE-latency re-nudge instead of its fast harness notification, until it happens to re-arm during a watcher-down window. Bounded and strictly better than the prior silent-gap behavior, but a latency tradeoff in the post-lapse recovery path worth confirming is intended; nudging before restoring would let firstmate reclaim its fast path immediately.
✅ **Test** - passed

✅ No issues found.

  • ./tests/fm-guardian.test.sh - 12 deterministic units mapping to all 7 acceptance criteria (lapse detection, exactly-one-nudge cooldown, fresh-beacon no-op, no-work no-op, restore+single-nudge, sentinel-marked & not-afk-gated nudge, singleton-safe restore, no fork stacking, no broad pkill / home-scoped takeover, guard banner still fires, guardian-arm no-op vs recycled-pid identity check)
  • ./tests/fm-guardian-present-e2e.test.sh - real daemon on a private tmux socket: present-mode lapse restores watcher + nudges exactly once then stays silent (criteria 1,3); afk B->A->B mode toggle in one process (criterion 4); SIGTERM clean shutdown removes pidfile+lock and reaps forked watcher (criterion 6)
  • Manual evidence harness driving the real bin/fm-supervise-daemon.sh in present mode: captured the supervisor pane content firstmate receives, the restored beacon/lock, and the daemon log (lapse -> restore -> single marked nudge -> 6s silence -> clean shutdown)
  • Regression run: ./tests/fm-afk-inject-e2e.test.sh, ./tests/fm-daemon.test.sh, ./tests/fm-send-secondmate-marker.test.sh, ./tests/fm-bootstrap.test.sh, ./tests/fm-watcher-lock.test.sh - all exit 0
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

Promote bin/fm-supervise-daemon.sh from an afk-only engine to a per-home,
always-on liveness guardian with two in-process modes that state/.afk toggles:

- Away (afk on): unchanged - own the watcher, self-handle routine wakes,
  escalate batched captain-relevant digests (presence-gated injection).
- Present (afk off, new): own nothing; firstmate's own re-arm is primary.
  Every FM_GUARDIAN_TICK, if work is in flight and the liveness beacon is
  missing or older than FM_GUARD_GRACE, the guardian restores the watcher via
  the singleton-safe path and injects exactly one re-arm/drain nudge. It never
  injects for a routine wake. A missed re-arm self-heals within a tick instead
  of silently stopping supervision (the prior ~69-minute failure mode).

Ownership stays singleton: the guardian forks fm-watch.sh (its own lock makes a
redundant fork stand down) and the B->A takeover stops only a pid the lock
proves is THIS home's watcher - never a broad pkill. afk is a policy toggle,
never daemon existence.

- bin/fm-guardian-arm.sh: new singleton-safe starter; detached, survives a
  firstmate restart.
- bin/fm-bootstrap.sh: start the guardian at session start (best-effort, quiet).
- AGENTS.md sections 3/5/8 + afk SKILL.md: liveness is daemon-guaranteed; re-arm
  is now a redundant backstop; /afk only flips injection policy and never stops
  the daemon; recovery starts the guardian.
- fm-guard.sh unchanged: still the loud pull-based defense-in-depth banner.
- Tests: fm-guardian.test.sh (units + singleton + home-scoping invariant) and
  fm-guardian-present-e2e.test.sh (real-daemon lapse->restore->one nudge->clean
  shutdown) cover all 7 acceptance criteria. Also harden two existing tests'
  byte checks against a PATH `od` shim (Open Design CLI) shadowing coreutils.
Codex review's one flagged concern was A/B transition responsiveness (the daemon
notices mode flips only at the top of its loop). Analysis confirms it is safe -
the present and away loops both re-check afk every ~1s, the singleton lock
prevents a double watcher during any transition window, and inject_msg stays
afk-gated - but the in-process toggle through the live loop was not directly
tested. Add a real-daemon transition test to fm-guardian-present-e2e: afk on ->
the same process takes watcher ownership and escalates a captain status (away);
afk off -> it returns to the liveness guardian and does not escalate a routine
status (present). Also set FM_ESCALATE_BATCH_SECS=0 / FM_STALE_ESCALATE_SECS high
in the e2e daemon so the away-mode digest flushes deterministically. This closes
criterion 4 (afk entering/exiting) through the running daemon. No production code
change - Codex found no real bug.
@noppGithub

Copy link
Copy Markdown

Completed by https://github.com/noppGithub/tourround/pull/158 (filterable audit history viewer, cross-tenant denials recorded, sensitive exports logged).

fritznoff pushed a commit to fritznoff/starship that referenced this pull request Nov 2, 2026
…iting the launcher's (kunchenguid#100)

* fix(bin): pin FM_HERDR_PROJECT_* to the spawned task

A herdr worker otherwise inherits the launching pane's project identity, which can name an unrelated repo. Spawn now sets the task's own project when presentation applies and clears both variables otherwise.

* no-mistakes(document): sync zellij/cmux spawn-command comments with FM_HERDR_PROJECT pin

* no-mistakes: apply CI fixes

* fix(tests): read full argv so path-scoped teardown reaps Linux CI children

Truncated ps output hid the fixture path, so isolation teardown skipped the long-runner and serial 2 hit the 20-minute cap.

* fix(tests): detach isolation children so a missed reap cannot pin CI

Serial 2 hung after the teardown assertion because leftover writers kept the test-runner pipe open until the 20-minute job cap.

* fix(tests): exec a fixture binary so Linux bash cannot drop the reap path

Linux bash exec-optimizes a last-command sleep, so the isolation child became pathless and serial 2 failed path-scoped teardown.

* fix(tests): reap Linux isolation children via /proc exe and children

pgrep-only descendant walks and argv matching still missed the fixture binary on Ubuntu CI.

* fix(tests): reap fixture-dir executables even when pgrep misses the child

Ubuntu CI left the isolation long-runner alive because it was not in the parent-pid walk, even though exe lived in the mktemp dir.

* fix(tests): reap fixture-dir cmdlines and quote a shellcheck false positive

The isolation busy-loop exe is bash, so Linux teardown must match the fixture path in argv; quoting proc-starttime silences SC2100.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants