Skip to content

feat(bin): put persistent second mates to sleep and wake them on purpose - #32

Merged
twilwa merged 5 commits into
mainfrom
fm/fm-secondmate-sleep
Oct 7, 2026
Merged

twilwa merged 5 commits into
mainfrom
fm/fm-secondmate-sleep

Conversation

@twilwa

@twilwa twilwa commented Oct 6, 2026 •

Copy link
Copy Markdown
Owner

Why

Today a persistent second mate can only be retired (bin/fm-teardown.sh removes its home) or have its agent exited, which the liveness sweep undoes on the next tick or session start.
Every idle home still runs its own agent and supervision watcher, and those cycles multiply across homes on a shared host.
This adds a durable, deliberate sleep: the mate's agent, watcher, and process-event listeners stop, its home (data, backlog, held captain calls, clones, worktrees) is left untouched, and nothing brings it back until an explicit wake.

Design

bin/fm-secondmate-sleep.sh runs from the parent home with FM_HOME explicit; its header and --help own the marker format and every step.

  • sleep <id>... --by <who> --reason <text>, per registered local mate, each step idempotent, and a sleep that cannot complete writes no marker and names the refusing step:
    • registered: a local route in data/secondmates.md whose home carries its own seed marker; a remote route is refused for now. An fm-<id> spelling names <id> only when fm-<id> is not itself registered and <id> is.
    • idle: no in-flight work (state/*.meta) in the mate's own home, checked at admission and again under the per-mate liveness lock just before the stop.
    • agent: a running agent is asked to write down the open work it holds only in conversation, with the same request, gate, and bound as bin/fm-secondmate-restart.sh (now shared through bin/fm-secondmate-restart-lib.sh), and is stopped with bin/fm-control.sh <id> exit only after its correlated answer lands. An agent that was stopped at admission is probed again under the lock, and one that came back up meanwhile is refused unstopped.
    • watcher: the home's own bin/fm-watch-arm.sh --stop.
    • listeners: every process-event source with no held captain call bound to it is retired through the home's own owner-matched bin/fm-procevent.sh retire. A decision-bound source stays registered with its binding but does not run while the mate sleeps; a board answer given meanwhile is queued by Lavish and captured once the mate wakes and that listener relaunches.
    • marker: state/<id>.asleep in the parent home, with since=, by=, and reason= lines.
  • wake <id>... removes the marker, relaunches through the guarded liveness relaunch path (bin/fm-spawn.sh <id> --secondmate, which converges tracked files and inherited material), confirms the agent live, then runs the home's own bin/fm-procevent.sh reconcile once so kept listeners relaunch immediately. A wake with no marker is a no-op.
  • status [<id>...] prints each registered mate as asleep (since when, by whom, why) or awake.

Callers that now consult the marker

All read it through fm_secondmate_asleep in the new bin/fm-secondmate-sleep-lib.sh; none parses the file.

  • bin/fm-secondmate-liveness-lib.sh: the probe returns asleep before probing, so neither the session-start sweep nor the watcher tick relaunches an asleep mate.
  • bin/fm-bootstrap.sh: the liveness sweep prints one BOOTSTRAP_INFO line per asleep mate; startup convergence skips the instruction nudge, its retry, and the config-reread send for it (its home still fast-forwards).
  • bin/fm-watch.sh: the second-mate wake-loop stall check observes an asleep mate's queue as empty, so it neither rings the stopped pane nor raises a stall alarm.
  • bin/fm-update.sh: lists an asleep mate as asleep and keeps it out of restart-secondmates and nudge-secondmates.
  • bin/fm-secondmate-restart.sh: reports a hand-named asleep mate as asleep: and never asks, nudges, or restarts it; the summary gains an asleep count.
  • bin/fm-config-push.sh: skips an asleep home whole, leaving any pending reread generation for the wake launch.
  • bin/fm-send.sh: refuses any send to an asleep mate and names the wake command.
  • bin/fm-bearings-snapshot.sh: reports state: asleep with its reason and leaves its stopped endpoint out of unhealthy_endpoints; the bearings skill renders that row in Charted Next as an action-free warning.
  • bin/fm-teardown.sh: retirement removes the marker on both the local and remote paths, so a later mate under the same id does not start asleep; nothing else about retirement changed.

Docs: the secondmate-provisioning skill gains a Sleep and wake section, the AGENTS.md section 13 trigger line gains "sleeping or waking", docs/configuration.md names state/<id>.asleep, task-intake gains the routing sentence for an asleep mate's scope, the updatefirstmate skill reads the new asleep lines, and docs/scripts.md lists the two new scripts.

Reviewed and left alone

  • bin/fm-spawn.sh: the single launch owner; every automatic relaunch path is gated upstream, so a refusal there would only block deliberate recovery.
  • bin/fm-control.sh: an explicit control-plane verb on a named id is a deliberate operator action.
  • Remote convergence in bin/fm-bootstrap.sh and the remote branch of bin/fm-config-push.sh: sleep refuses remote routes, so no remote mate can be asleep.
  • bin/fm-fleet-snapshot.sh: the canonical snapshot stays a complete projection; bearings decorates it.
  • bin/fm-pending-reply-lib.sh: a request left unanswered at sleep time still escalates as a missed report, which surfaces the open loop rather than hiding it.

Review rounds applied

The no-mistakes pipeline reviewed this branch twice before the captain chose to ship it straight to the fork; both runs ended when a review fix round hit the pipeline's 30-minute agent limit, and the remaining fixes were applied by hand.

  • Round 1 (pipeline fix commit da9023eb): the idle check repeats under the liveness lock; teardown removes the marker; decision-bound listeners and their captain-hold bindings survive sleep; the fm- id alias resolves only when the exact id is not registered. A finding asking to drop status and the recorded who and why was rejected, since both are in the approved specification.
  • Round 2 (8917afdb): a kept listener's runner stops once the sleeping home stops renewing the process-event owner lease, so the docs and persist request now say a board answer is captured after wake, not during sleep, and wake reconciles the home's listeners immediately.
  • Final finding (34bcd202): the agent state is probed again under the liveness lock before the stop, so a mate relaunched between admission and the stop is refused instead of being marked asleep while running. The same commit makes the wake test give the woken home's real listener machinery a real sleep; the case's shortened sleep stub raced the listener launch on a loaded host and made that test flaky.

Checks run

Run locally on head 34bcd202, each inside a contained low-priority scope on a host at load 13 to 20:

  • bash tests/fm-secondmate-sleep.test.sh: 8 of 8 pass (T1-T8). T8 was confirmed failing against the script without the re-probe, and the extended wake test T4 was confirmed failing before the reconcile at wake.
  • bash tests/fm-secondmate-liveness.test.sh: 20 of 20 pass.
  • bash tests/fm-update.test.sh: 17 of 17 pass.
  • bash tests/fm-secondmate-restart.test.sh: 20 of 20 pass.
  • bash tests/fm-send-secondmate-marker.test.sh: 9 of 9 pass.
  • bin/fm-lint.sh: clean (ShellCheck 0.11.0, actionlint 1.7.12).
  • bin/fm-doc-audience-check.sh: ok surfaces=114 local_links=540.

The new cases in tests/fm-secondmate-harness.test.sh, tests/fm-bearings-snapshot.test.sh, and tests/fm-wake-queue.test.sh were run individually, red before green, while the first commit was written, but those whole files were not re-run on this head; tests/fm-teardown.test.sh's new case came from the pipeline's round-1 fix and was not run locally. bin/fm-test-run.sh --check-coverage passed after the new suite was registered in the secondmate family. CI runs the full suite.

Follow-ups

  • Remote routes cannot sleep yet; that needs the host-side agent exit, watcher stop, and listener retirement over bin/fm-on.sh.
  • Sleep could also refuse while the mate's parent-side steering inbox holds unacknowledged messages.
  • Capturing a board answer while the mate sleeps would need lease keeping for a sleeping home's decision-bound listeners.
  • bin/fm-secondmate-sleep.sh is 559 lines, about 97 of them the header that owns the marker and every step; it stays one domain but could split wake into its own file if it grows.

Summary by Sourcery

Introduce deliberate, durable sleeping for local persistent secondmates while ensuring explicit wake is the only path that restores their runtime services.

New Features:

  • Add explicit sleep, wake, and status commands for persistent local secondmates, preserving their homes while stopping their agents, watchers, and eligible listeners.
  • Persist durable sleep metadata and restore sleeping mates through guarded relaunch and listener reconciliation on explicit wake.

Bug Fixes:

  • Prevent liveness recovery, startup convergence, updates, config pushes, sends, watcher stall checks, and restart flows from reviving or steering intentionally sleeping mates.
  • Report sleeping mates as intentional warnings rather than dead or unavailable endpoints, and clear sleep markers during teardown.

Enhancements:

  • Share secondmate persistence handling between sleep and restart operations and centralize sleep-marker access.
  • Document sleep and wake behavior, routing expectations, operational state, and Bearings presentation.

CI:

  • Register the new secondmate sleep test suite and update the Bearings test-count check.

Documentation:

  • Document secondmate sleep and wake commands, marker state, routing behavior, and operational guidance.

Tests:

  • Add coverage for sleep and wake sequencing, refusal conditions, listener handling, liveness suppression, restart and update integration, send refusal, Bearings output, queue handling, and teardown cleanup.

twilwa added 4 commits October 6, 2026 22:39
bin/fm-secondmate-sleep.sh sleeps a registered local mate (persist its open
work under the restart gate, exit its agent, stop its watcher, retire its
process-event listeners, then write the parent-home state/<id>.asleep marker),
wakes it through the guarded liveness relaunch, and reports status. Liveness
recovery, the watcher's wake-loop check, startup convergence, config push,
/updatefirstmate's restart pass, fm-send, and bearings all read the marker
through bin/fm-secondmate-sleep-lib.sh and leave an asleep mate alone.
…ause in sleep

A decision-bound process-event source kept through sleep stays registered with
its binding, but its runner stops once the sleeping home stops renewing the
owner lease, so a board answer given meanwhile is queued by Lavish and captured
only after wake. Wake now runs the mate home's own fm-procevent.sh reconcile
once the agent is confirmed live, so that listener relaunches at once, and the
script header, the persist request, and the secondmate-provisioning section say
so instead of promising capture during sleep.
…ping it

A mate whose agent was stopped at admission needs no persist answer, but a
liveness relaunch could bring it back before its stop step, which then marked a
running agent asleep. The stop step now probes again under the per-mate
liveness lock and refuses at the agent step, unstopped, when the agent is back
up. One probe helper now serves admission, the stop step, and wake.

The wake test gives the woken home's real process-event machinery a real sleep:
the case's shortened sleep stub raced the listener's launch on a loaded host.
@sourcery-ai

sourcery-ai Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR implements an explicit local-secondmate sleep lifecycle: it atomically records intent only after safely stopping the agent, watcher, and eligible listeners, prevents all automatic recovery and steering paths from reviving or contacting sleeping mates, and provides a guarded wake path that relaunches the mate and reconciles retained listeners, with shared restart persistence logic, documentation, and broad regression coverage.

Sequence diagram for explicitly sleeping and waking a local secondmate

sequenceDiagram
    participant Operator
    participant Parent as ParentHome
    participant Mate as SecondmateHome
    participant Agent
    participant Listener as ProcessEventListeners

    Operator->>Parent: fm-secondmate-sleep.sh sleep id --by who --reason text
    Parent->>Parent: Check registered and idle
    Parent->>Agent: fm_secondmate_persist_ask()
    Agent-->>Parent: Correlated persistence answer
    Parent->>Agent: fm-control.sh id exit
    Parent->>Mate: fm-watch-arm.sh --stop
    Parent->>Listener: Retire unbound sources
    Parent->>Parent: fm_secondmate_asleep_write()
    Note over Parent,Mate: Home data and durable work remain untouched
    Operator->>Parent: fm-secondmate-sleep.sh wake id
    Parent->>Parent: fm_secondmate_asleep_clear()
    Parent->>Mate: fm-spawn.sh id --secondmate
    Mate-->>Parent: Agent confirmed live
    Parent->>Listener: procevent.sh reconcile
    Listener-->>Mate: Retained listeners relaunch
Loading

State diagram for the secondmate sleep lifecycle

stateDiagram-v2
    [*] --> Awake
    Awake --> Admission: sleep
    Admission --> Refused: not registered, remote, or in-flight work
    Admission --> Persisting: agent alive
    Admission --> Stopping: agent already stopped
    Persisting --> Refused: no correlated persistence answer
    Persisting --> Stopping: answer received
    Stopping --> Refused: agent changed, watcher/listener/marker step failed
    Stopping --> Asleep: marker written
    Asleep --> Asleep: automatic recovery and steering skipped
    Asleep --> Waking: wake
    Waking --> Awake: agent live and listeners reconciled
    Waking --> Awake: marker absent noop
    Waking --> RecoveryOwned: relaunch failed
    RecoveryOwned --> Awake: liveness recovery
Loading

File-Level Changes

Change Details Files
Adds an explicit, durable sleep/wake lifecycle for local persistent secondmates while preserving each mate’s home and durable work.
  • Introduces sleep, wake, and status commands with atomic parent-side markers containing timestamp, operator, and reason.
  • Validates registration, locality, idleness, agent persistence/stop, watcher shutdown, listener retirement, and liveness-lock races before marking a mate asleep.
  • Wakes through guarded spawn, confirms the agent, and reconciles retained process-event listeners.
  • Covers idempotency, refusal paths, listener bindings, alias handling, and teardown marker cleanup.
bin/fm-secondmate-sleep.sh
bin/fm-secondmate-sleep-lib.sh
bin/fm-teardown.sh
docs/configuration.md
docs/scripts.md
.agents/skills/secondmate-provisioning/SKILL.md
Centralizes sleep-marker interpretation and gates automatic secondmate supervision and convergence around it.
  • Makes liveness probes classify asleep mates before endpoint probing, preventing session-start and watcher relaunches.
  • Skips bootstrap nudges, config pushes, update restarts/nudges, and wake-loop stall escalation for asleep mates.
  • Refuses sends to asleep mates and reports the explicit wake command.
  • Updates Bearings and operational guidance to distinguish intentional sleep from dead or unavailable endpoints.
bin/fm-secondmate-liveness-lib.sh
bin/fm-bootstrap.sh
bin/fm-watch.sh
bin/fm-update.sh
bin/fm-config-push.sh
bin/fm-send.sh
bin/fm-bearings-snapshot.sh
AGENTS.md
.agents/skills/bearings/SKILL.md
.agents/skills/task-intake/SKILL.md
.agents/skills/updatefirstmate/SKILL.md
Shares the restart persistence protocol between restart and sleep flows.
  • Moves correlated persist-request creation, delivery, bounds, and reply tracking into the restart library.
  • Leaves restart behavior unchanged for awake mates while reporting asleep mates separately and excluding them from restart/nudge actions.
bin/fm-secondmate-restart-lib.sh
bin/fm-secondmate-restart.sh
Adds focused regression coverage and registers the new suite.
  • Tests sleep ordering, atomic refusal behavior, busy/remote/unregistered routes, wake relaunch and listener reconciliation, status, listener binding preservation, id aliases, and admission-to-stop races.
  • Adds integration checks for liveness, update, send, Bearings, bootstrap/config convergence, wake queues, and teardown cleanup.
  • Registers the sleep suite and extracts shared persistence test helpers.
tests/fm-secondmate-sleep.test.sh
tests/secondmate-persist-helpers.sh
tests/fm-secondmate-liveness.test.sh
tests/fm-secondmate-restart.test.sh
tests/fm-update.test.sh
tests/fm-send-secondmate-marker.test.sh
tests/fm-bearings-snapshot.test.sh
tests/fm-secondmate-harness.test.sh
tests/fm-wake-queue.test.sh
tests/fm-teardown.test.sh
bin/fm-test-run.sh

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 8 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="bin/fm-send.sh" line_range="463" />
<code_context>
 T=$RESOLVED_TARGET
 shift

+if [ -n "$TARGET_META" ] && [ "$(fm_meta_get "$TARGET_META" kind)" = secondmate ]; then
+  ASLEEP_ID=$(fm_send_id_from_meta "$TARGET_META")
+  if fm_secondmate_asleep "$STATE" "$ASLEEP_ID"; then
</code_context>
<issue_to_address>
**Sends reach a stopped mate**

When a send passes the marker check after sleep stops the agent but before it writes the marker, `fm-send` proceeds without coordinating with sleep, so it sends or records work for a stopped mate. The caller sees success for work the agent never receives, and the new marker prevents recovery from consuming it.

Serialize sends with the sleep transaction or otherwise ensure work accepted during sleep is durably queued for the mate.

Also at `bin/fm-secondmate-sleep.sh:339-359`.
</issue_to_address>

### Comment 2
<location path="bin/fm-secondmate-sleep.sh" line_range="339" />
<code_context>
+    esac
+  fi
+  if [ "${NEEDS_EXIT[i]}" = 1 ] && ! out=$(FM_HOME="$FM_HOME" FM_STATE_OVERRIDE="$STATE" \
+    "$SCRIPT_DIR/fm-control.sh" "$id" exit < /dev/null 2>&1); then
+    fm_secondmate_liveness_unlock "$id"
+    refuse "$i" agent "$(first_line "$out")"
</code_context>
<issue_to_address>
**Replacement agent stops without persistence**

When the agent that answered the persist request exits and a replacement becomes live before `stop_and_mark` acquires the liveness lock, `stop_and_mark` skips the under-lock agent probe when `NEEDS_EXIT[i]` is set and exits the replacement without asking it to persist. Its open conversational work can be lost.

Re-probe the agent under the liveness lock and request persistence from any replacement before exiting it.
</issue_to_address>

### Comment 3
<location path="bin/fm-secondmate-sleep.sh" line_range="284-286" />
<code_context>
+        return 1
+        ;;
+    esac
+    if ! out=$(run_in_mate_home "$home" fm-procevent.sh retire "$id" "${guard[@]+"${guard[@]}"}"); then
+      printf '%s: %s\n' "$id" "$(first_line "$out")"
+      return 1
+    fi
+  done
</code_context>
<issue_to_address>
**Failed sleep leaves listeners missing**

When a later listener retirement or another sleep step fails after the agent, watcher, or an earlier listener has already stopped, `retire_unbound_listeners` and `stop_and_mark` return without restoring earlier state. The sleep marker is absent, so the mate can resume with listeners permanently removed or with its agent or watcher stopped.

Make sleep failure transactional by restoring the agent, watcher, and any listeners already stopped or retired before returning.

Also at `bin/fm-secondmate-sleep.sh:344-357`.
</issue_to_address>

### Comment 4
<location path="bin/fm-secondmate-restart.sh" line_range="261-266" />
<code_context>
 errors=0
 while IFS='|' read -r id home _window meta; do
   [ -n "$id" ] || continue
+  if fm_secondmate_asleep "$STATE" "$id"; then
+    printf 'secondmate %s: skipped - %s; its inherited material converges when it wakes\n' \
+      "$id" "$(fm_secondmate_asleep_line)"
+    continue
+  fi
   if [ -z "$home" ]; then
     printf 'secondmate %s: skipped - no home= in %s and no registry home\n' "$id" "$meta"
</code_context>
<issue_to_address>
**Restart runs behind sleep marker**

When a restart passes its asleep check and sleep completes before the restart launches the agent, `fm-secondmate-restart.sh` launches without rechecking the marker or coordinating through the liveness lock, leaving a running agent while the mate is reported as asleep and beyond liveness supervision.

Coordinate restart launch with sleep through the liveness lock and recheck the asleep marker before relaunching.

Also at `bin/fm-secondmate-sleep.sh:339-354`.
</issue_to_address>

### Comment 5
<location path="bin/fm-secondmate-sleep.sh" line_range="262-284" />
<code_context>
+    [ -e "$path" ] || [ -L "$path" ] || continue
+    id=${path##*/}
+    id=${id%.source}
+    if out=$(run_in_mate_home "$home" fm-captain-hold.sh binding "$id"); then
+      continue
+    elif [ -n "$out" ]; then
+      printf '%s: %s\n' "$id" "$(first_line "$out")"
+      return 1
+    fi
+    guard=()
+    if ! fm_procevent_source_lock_acquire "$id"; then
+      printf '%s: cannot lock the source\n' "$id"
+      return 1
+    fi
+    fm_procevent_extension_registration_load_locked "$home/state" "$id"
+    owner_state=$?
+    fm_procevent_source_lock_release "$id"
+    case "$owner_state" in
+      0) guard=(--if-owner "$FM_PROCEVENT_EXTENSION_REGISTRATION_TOKEN") ;;
+      1) ;;
+      *)
+        printf '%s: cannot safely read its registration owner\n' "$id"
+        return 1
+        ;;
+    esac
+    if ! out=$(run_in_mate_home "$home" fm-procevent.sh retire "$id" "${guard[@]+"${guard[@]}"}"); then
+      printf '%s: %s\n' "$id" "$(first_line "$out")"
+      return 1
</code_context>
<issue_to_address>
**Held call loses its listener**

When a captain-call binding is published after the binding lookup but before source retirement, `retire_unbound_listeners` retires the source despite the new binding, leaving the held call bound to a missing listener. Its answer is not captured after wake.

Make the binding check and source retirement atomic so a source with a newly published captain-call binding is not retired.
</issue_to_address>

### Comment 6
<location path="bin/fm-teardown.sh" line_range="3769" />
<code_context>
   fm_backlog_atomic_transition remove "$STATE/$ID.meta" "task record" "$STATE" || return 1
   rm -f -- "$STATE/$ID.turn-ended" "$STATE/$ID.progress" \
     "$STATE/.secondmate-relaunch-$ID" "$STATE/.secondmate-relaunch-bound-$ID"
+  fm_secondmate_asleep_clear "$STATE" "$ID" || true
   printf 'teardown %s complete (remote %s:%s)\n' "$ID" "$remote_host" "$remote_home"
   return 0
</code_context>
<issue_to_address>
**Stale marker blocks a reprovisioned mate**

When sleep-marker removal fails, including when the marker path is a directory, `fm_secondmate_asleep_clear` cannot remove a directory with `rm -f`, and both teardown paths ignore its failure. Teardown can report completion while the marker remains, so a mate reprovisioned under that ID is treated as asleep and a directory marker cannot be cleared by wake.

Make marker clearing handle a directory marker and make teardown stop and report failure when marker removal fails.

Also at `bin/fm-teardown.sh:1010`, `bin/fm-secondmate-sleep-lib.sh:71`.
</issue_to_address>

### Comment 7
<location path="bin/fm-bearings-snapshot.sh" line_range="530-531" />
<code_context>
-          reason:(.current.reason // "-")} ]) as $secondmates_all
+          reason:(.current.reason // "-")}
+       | if $asleep[.id] != null then
+           .state = "asleep" | .doing = ($asleep[.id].line | trunc(120)) | .reason = $asleep[.id].reason
+         else . end ]) as $secondmates_all
   | ([ .tasks[]
        | select(.kind != "secondmate")
</code_context>
<issue_to_address>
**Asleep homes lack a warning row**

When a consumer uses the snapshot's `gates` array for Charted Next, the asleep decoration changes only the secondmate projection; the snapshot's `gates` array is assembled from catch-up and queued work, with no asleep-home row. A consumer following the Bearings skill's instruction to show asleep homes in Charted Next therefore has no warning row to render from `gates`.

Project asleep secondmates into the warning-gate data consumed for Charted Next, or update the consumer contract to render the asleep secondmate projection directly.
</issue_to_address>

### Comment 8
<location path="tests/fm-wake-queue.test.sh" line_range="646-647" />
<code_context>
+    FM_CHECK_INTERVAL=999999 FM_HEARTBEAT=999999 \
+    secondmate_stall_watch_leg "$dir" "second" cleared
+  [ ! -s "$state/.wake-queue" ] \
+    || fail "an asleep mate's queue fed the secondmate wake-loop escalation: $(cat "$state/.wake-queue")"
+  ! grep -F 'secondmate wake-loop stalled' "$dir/watch-first.out" "$dir/watch-second.out" >/dev/null \
+    || fail "an asleep mate was reported as a stalled wake loop"
+  [ ! -s "$dir/sent" ] || fail "an asleep mate's pane was rung: $(cat "$dir/sent")"
</code_context>
<issue_to_address>
**Queue preservation assertion checks parent state**

`test_asleep_secondmate_queue_does_not_feed_stall_escalation` puts the queued row in `$sub/state/.wake-queue` at line 632 but checks `$state/.wake-queue` here. If the sleep handling deletes the mate’s queue, this assertion still passes because it checks a different, absent file; the test does not catch that queued work was lost.

Assert that `"$sub/state/.wake-queue"` still contains the queued row after both stall-watch legs.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread bin/fm-send.sh
T=$RESOLVED_TARGET
shift

if [ -n "$TARGET_META" ] && [ "$(fm_meta_get "$TARGET_META" kind)" = secondmate ]; then

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Sends reach a stopped mate

When a send passes the marker check after sleep stops the agent but before it writes the marker, fm-send proceeds without coordinating with sleep, so it sends or records work for a stopped mate. The caller sees success for work the agent never receives, and the new marker prevents recovery from consuming it.

Serialize sends with the sleep transaction or otherwise ensure work accepted during sleep is durably queued for the mate.

Also at bin/fm-secondmate-sleep.sh:339-359.

Prompt for AI agents
In `bin/fm-send.sh` at line 463:

**Sends reach a stopped mate**

When a send passes the marker check after sleep stops the agent but before it writes the marker, `fm-send` proceeds without coordinating with sleep, so it sends or records work for a stopped mate. The caller sees success for work the agent never receives, and the new marker prevents recovery from consuming it.

Serialize sends with the sleep transaction or otherwise ensure work accepted during sleep is durably queued for the mate.

Also at `bin/fm-secondmate-sleep.sh:339-359`.

esac
fi
if [ "${NEEDS_EXIT[i]}" = 1 ] && ! out=$(FM_HOME="$FM_HOME" FM_STATE_OVERRIDE="$STATE" \
"$SCRIPT_DIR/fm-control.sh" "$id" exit < /dev/null 2>&1); then

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Replacement agent stops without persistence

When the agent that answered the persist request exits and a replacement becomes live before stop_and_mark acquires the liveness lock, stop_and_mark skips the under-lock agent probe when NEEDS_EXIT[i] is set and exits the replacement without asking it to persist. Its open conversational work can be lost.

Re-probe the agent under the liveness lock and request persistence from any replacement before exiting it.

Prompt for AI agents
In `bin/fm-secondmate-sleep.sh` at line 339:

**Replacement agent stops without persistence**

When the agent that answered the persist request exits and a replacement becomes live before `stop_and_mark` acquires the liveness lock, `stop_and_mark` skips the under-lock agent probe when `NEEDS_EXIT[i]` is set and exits the replacement without asking it to persist. Its open conversational work can be lost.

Re-probe the agent under the liveness lock and request persistence from any replacement before exiting it.

Comment on lines +284 to +286
if ! out=$(run_in_mate_home "$home" fm-procevent.sh retire "$id" "${guard[@]+"${guard[@]}"}"); then
printf '%s: %s\n' "$id" "$(first_line "$out")"
return 1

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Failed sleep leaves listeners missing

When a later listener retirement or another sleep step fails after the agent, watcher, or an earlier listener has already stopped, retire_unbound_listeners and stop_and_mark return without restoring earlier state. The sleep marker is absent, so the mate can resume with listeners permanently removed or with its agent or watcher stopped.

Make sleep failure transactional by restoring the agent, watcher, and any listeners already stopped or retired before returning.

Also at bin/fm-secondmate-sleep.sh:344-357.

Prompt for AI agents
In `bin/fm-secondmate-sleep.sh` at lines 284-286:

**Failed sleep leaves listeners missing**

When a later listener retirement or another sleep step fails after the agent, watcher, or an earlier listener has already stopped, `retire_unbound_listeners` and `stop_and_mark` return without restoring earlier state. The sleep marker is absent, so the mate can resume with listeners permanently removed or with its agent or watcher stopped.

Make sleep failure transactional by restoring the agent, watcher, and any listeners already stopped or retired before returning.

Also at `bin/fm-secondmate-sleep.sh:344-357`.

Comment thread bin/fm-secondmate-restart.sh Resolved
Comment on lines +262 to +284
if out=$(run_in_mate_home "$home" fm-captain-hold.sh binding "$id"); then
continue
elif [ -n "$out" ]; then
printf '%s: %s\n' "$id" "$(first_line "$out")"
return 1
fi
guard=()
if ! fm_procevent_source_lock_acquire "$id"; then
printf '%s: cannot lock the source\n' "$id"
return 1
fi
fm_procevent_extension_registration_load_locked "$home/state" "$id"
owner_state=$?
fm_procevent_source_lock_release "$id"
case "$owner_state" in
0) guard=(--if-owner "$FM_PROCEVENT_EXTENSION_REGISTRATION_TOKEN") ;;
1) ;;
*)
printf '%s: cannot safely read its registration owner\n' "$id"
return 1
;;
esac
if ! out=$(run_in_mate_home "$home" fm-procevent.sh retire "$id" "${guard[@]+"${guard[@]}"}"); then

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Held call loses its listener

When a captain-call binding is published after the binding lookup but before source retirement, retire_unbound_listeners retires the source despite the new binding, leaving the held call bound to a missing listener. Its answer is not captured after wake.

Make the binding check and source retirement atomic so a source with a newly published captain-call binding is not retired.

Prompt for AI agents
In `bin/fm-secondmate-sleep.sh` at lines 262-284:

**Held call loses its listener**

When a captain-call binding is published after the binding lookup but before source retirement, `retire_unbound_listeners` retires the source despite the new binding, leaving the held call bound to a missing listener. Its answer is not captured after wake.

Make the binding check and source retirement atomic so a source with a newly published captain-call binding is not retired.

Comment thread bin/fm-teardown.sh Resolved
Comment thread bin/fm-bearings-snapshot.sh Resolved
Comment thread tests/fm-wake-queue.test.sh Resolved
- Sleep re-probes the agent under the per-mate liveness lock every time and
  stops only the incarnation that was asked to persist (its spawn_gen); a
  replaced or returned agent is refused unstopped.
- The second-mate restart runs its relaunch under the same lock and rechecks
  the sleep marker there, so it never leaves a running agent behind a marker.
- Clearing the sleep marker removes a file, symlink, or directory at exactly
  its path and fails unless nothing is left; both teardown paths stop and
  report a marker they could not remove.
- The bearings snapshot header and skill state that the asleep notice is the
  secondmates[] row with state asleep, never a gates[] row.
- The sleep header says a refused sleep rolls nothing back, and that unbound
  board listeners already retired stay retired until re-armed by hand.
- Tests: wake-queue asserts the mate's own queued row survives; new sleep T9,
  restart T4c, and teardown directory and stuck-marker cases.
- CI: the stock-bash job expects 61 Bearings tests, and the gotmp teardown
  fixture stages fm-secondmate-sleep-lib.sh.
@twilwa

twilwa commented Oct 6, 2026

Copy link
Copy Markdown
Owner Author

Review round on the Sourcery findings, applied in 753cfc2e.

Fixed

  • Queue preservation assertion checks parent state (tests/fm-wake-queue.test.sh): the test now also asserts the asleep mate's own $sub/state/.wake-queue still holds its row unchanged after both stall-watch legs; the parent-queue check stays, because it is what proves no stall alarm was queued.
  • Replacement agent stops without persistence (bin/fm-secondmate-sleep.sh): the stop step always re-probes the agent under the per-mate liveness lock, and only the incarnation that was asked to persist (the spawn_gen recorded when the request went out) is stopped; a replaced agent is refused at agent with nothing stopped. New test T9.
  • Restart runs behind sleep marker (bin/fm-secondmate-restart.sh): the relaunch now runs under the same per-mate liveness lock sleep holds while it stops the agent and writes its marker, and rechecks the marker inside it, reporting asleep: <id> instead of relaunching. New test T4c.
  • Stale marker blocks a reprovisioned mate (bin/fm-secondmate-sleep-lib.sh, bin/fm-teardown.sh): clearing removes a file, symlink (never its target), or directory at exactly the marker path and succeeds only when nothing is left, and both teardown paths now stop and report a marker they could not remove. New teardown test covering both.
  • Asleep homes lack a warning row (bin/fm-bearings-snapshot.sh, bearings skill): the contract is now explicit that the asleep notice lives only in the secondmates[] row with state: asleep, never in gates[], and that the Charted Next warning row is composed from that entry.

Not changed, with evidence

  • Sends reach a stopped mate (bin/fm-send.sh): a send that passes the marker check just before the marker lands is still a durable record in the parent's state/<id>.inbox/, which the bin/fm-send.sh header defines as the delivery. The doorbell is best effort by design. While the mate's endpoint is stopped, bin/fm-task-inbox-lib.sh skips typing and escalates the unhandled record to the parent instead of dropping it. After wake the endpoint is available again, so the re-ring ladder delivers it. A marked request also keeps its parent pending-reply expectation, which escalates if it goes unanswered. Nothing accepted in that window is lost or hidden.
  • Held call loses its listener (retire_unbound_listeners): a captain-hold binding is published only by the mate's own agent, through the process-event-sources bind step or bin/fm-bearings-board.sh under /bearings lavish. Nothing on the parent side or in the watcher binds a mate's source. stop_and_mark exits that agent and stops the home's watcher before the listener step runs. So once binding lookups begin, nothing in that home can publish a new binding.
  • Failed sleep leaves listeners missing: no rollback machinery was added. The header now states it. A refusal undoes nothing already done. A refusal after the agent or watcher step leaves no marker, so ordinary liveness recovery relaunches the mate. A refusal at the listeners step may leave unbound board listeners it already retired still retired, and re-arming one is a manual operator step.

CI (run 37537978889)

  • Stock macOS Bash snapshot compatibility: the job asserts an exact Bearings test count, and this PR adds one Bearings test, so .github/workflows/ci.yml now expects 61 instead of 60.
  • tests/fm-gotmp.test.sh: its fake teardown root links a fixed list of bin libraries and lacked fm-secondmate-sleep-lib.sh, which teardown now sources. Both of its teardown fixtures now link it; no other test fixture stages a script that sources the library.
  • Not from this PR, and failing the same way on main at the same commit: the defer that released the captain-held task (portable parallel 2), the Pi calm renderer and lifecycle contract (serial 2 and 4), and the Pi outcome rendering consumers (serial 4 and 7). The "PR must be raised via no-mistakes" check is red by design for this fork-only PR.

@twilwa
twilwa merged commit e2f6671 into main Oct 7, 2026
18 of 23 checks passed
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.

1 participant