Skip to content

fix(bin): stop secondmate relaunch failing when watcher scratch files vanish - #4900

Merged
kunchenguid merged 2 commits into
kunchenguid:mainfrom
tiago-peixoto:fm/fm4765
Sep 22, 2026
Merged

kunchenguid merged 2 commits into
kunchenguid:mainfrom
tiago-peixoto:fm/fm4765

Conversation

@tiago-peixoto

@tiago-peixoto tiago-peixoto commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Intent

Fixes #4765

Observed: bin/fm-control.sh relaunch for a secondmate runs find "$WT/state" -mindepth 1 -maxdepth 1 -print and refuses if find exits non-zero ("child records cannot be traversed"). On a live home whose watcher continuously writes .hash-*, .count-*, .last-* scratch files, find can exit non-zero when an entry disappears between directory read and processing. The same directory is readable immediately afterwards. Re-running restart alone succeeds with nothing changed. The loop below that probe already opens every *.meta child record and refuses on an unreadable regular file, which is the actual guarantee.

Expected: restart should refuse when child *.meta records cannot be read, not when a watcher scratch file vanishes mid-find.

Consequence: a live second mate keeps running stale instructions after it already persisted open work, and the update reads as mostly successful.

What Changed

  • bin/fm-control.sh: secondmate relaunch no longer runs find over $WT/state and no longer refuses with "child records cannot be traversed". Before this change, a .hash-*, .count-*, or .last-* scratch file that the watcher removed mid-scan made find exit non-zero and blocked the relaunch.
    Now the check only requires state/ to be a directory the relaunch can read and enter (-d, -r, -x). The existing per-*.meta loop still refuses when any child record is not a readable regular file.
  • tests/fm-control-relaunch.test.sh: adds a test with a fake find that fails on the state directory with a vanished .hash-0 error. It checks that relaunch still succeeds and that both child metas are recorded in the journal (children=2).
  • The unreadable-child-state test now checks a mode-000 state directory instead of the removed find failure path. It expects the "no readable state directory" refusal and checks that the secondmate keeps running. This test is skipped when run as root, because mode 000 does not restrict root.

🤖 Generated with Claude Code

Risk Assessment

✅ Low: The change is small: it drops the find(1) probe that could fail when a scratch file vanished mid-scan, replaces it with -d/-r/-x checks on the state directory, and leaves the per-*.meta readability loop that intent names as the real guarantee unchanged; the tests cover both the race regression and the refusal cases.

Testing

I ran the targeted relaunch test file, and all 58 cases passed. I then ran fm-control.sh <id> relaunch on a secondmate home built with the suite's hermetic tmux harness, which stands in for the agent endpoint. Each case ran against both the base commit and the fix. The first case reproduces the reported race by making find fail on state/ while a background loop keeps creating and deleting scratch files. The base script refuses ("child records cannot be traversed"). The fix relaunches and counts both child records (children=2). With the real find and live churn, the fix relaunched 20 out of 20 times. The refusal cases still hold on the fix: an unreadable child .meta, a directory named *.meta, an unlistable state/ and a missing state/ all exit 1 and leave the secondmate running. The real GNU find did not fail under churn on this Linux host (0 of 3000 runs), so the race itself was reproduced by forcing the find error (the error the issue reports) rather than waiting for it to happen naturally. There is no UI change, so there are no screenshots; the evidence is the CLI transcripts.

  • Live validation: ✅ go - 5 of 5 scenarios driven live against the product
Scenario Result Live Evidence
Relaunch a secondmate while a watcher scratch file vanishes mid-find: base refuses, fix relaunches and counts 2 child records ✅ pass live live-vanish.txt: base exit 1 'child records cannot be traversed'; fix exit 0 'relaunched sm9', children=2
Relaunch repeatedly while a background watcher keeps creating and deleting .hash-/.last- files (real find), and every run succeeds ✅ pass live live-churn-20x.txt: 20/20 exit 0, children=2
Adversarial: unreadable child .meta still refuses and leaves the secondmate running ✅ pass live live-unreadable.txt: fix exit 1 'c2.meta is not a readable regular file', agent still claude
Adversarial: a directory named *.meta still refuses ✅ pass live live-metadir.txt: fix exit 1 'bad.meta is not a readable regular file'
Adversarial: unlistable (mode 000) or missing state/ still refuses ✅ pass live live-unlistable.txt and live-nostate.txt: fix exit 1 'no readable state directory'
Evidence: Before/after: find fails on vanished scratch file during relaunch

Source: Before/after: find fails on vanished scratch file during relaunch

######## BASE (1bb72cc) mode=vanish
== control script: /tmp/fm4765.C1XN/bin/fm-control.sh
== state/ before relaunch:
   total 8
   drwxr-xr-x 2 firstmate firstmate 2840 Sep 19  2026 .
   drwxr-xr-x 5 firstmate firstmate  180 Sep 19 04:42 ..
   -rw-r--r-- 1 firstmate firstmate    0 Sep 19 04:42 .count-1
   -rw-r--r-- 1 firstmate firstmate    0 Sep 19 04:42 .count-2
   -rw-r--r-- 1 firstmate firstmate    0 Sep 19 04:42 .count-3
   -rw-r--r-- 1 firstmate firstmate    0 Sep 19 04:42 .count-4
   -rw-r--r-- 1 firstmate firstmate    0 Sep 19 04:42 .count-5
   -rw-r--r-- 1 firstmate firstmate    0 Sep 19 04:42 .count-6
   -rw-r--r-- 1 firstmate firstmate    0 Sep 19 04:42 .count-7
   -rw-r--r-- 1 firstmate firstmate    0 Sep 19 04:42 .count-8
   -rw-r--r-- 1 firstmate firstmate    0 Sep 19 04:42 .hash-1
== $ fm-control.sh sm9 relaunch
   error: secondmate sm9's child records cannot be traversed; refusing to relaunch
== exit code: 1
== secondmate agent command now: claude
== journal children=: 

######## FIX (ef8a25b) mode=vanish
== control script: ~/.no-mistakes/worktrees/42fe67ed39fa/01M2VYARPVCA20CAN8081M3MZS/bin/fm-control.sh
== state/ before relaunch:
   total 8
   drwxr-xr-x 2 firstmate firstmate 1040 Sep 19  2026 .
   drwxr-xr-x 5 firstmate firstmate  180 Sep 19 04:42 ..
   -rw-r--r-- 1 firstmate firstmate    0 Sep 19 04:42 .count-1
   -rw-r--r-- 1 firstmate firstmate    0 Sep 19 04:42 .count-10
   -rw-r--r-- 1 firstmate firstmate    0 Sep 19 04:42 .count-11
   -rw-r--r-- 1 firstmate firstmate    0 Sep 19 04:42 .count-12
   -rw-r--r-- 1 firstmate firstmate    0 Sep 19 04:42 .count-13
   -rw-r--r-- 1 firstmate firstmate    0 Sep 19 04:42 .count-14
   -rw-r--r-- 1 firstmate firstmate    0 Sep 19 04:42 .count-15
   -rw-r--r-- 1 firstmate firstmate    0 Sep 19 04:42 .count-16
   -rw-r--r-- 1 firstmate firstmate    0 Sep 19 04:42 .count-2
== $ fm-control.sh sm9 relaunch
   warning: secondmate sm9 sync skipped before launch: primary default-branch commit cannot be resolved
   relaunched sm9 harness=claude from=claude model=default effort=default backend=tmux endpoint=fmses:fm-sm9 worktree=/tmp/fm-control-relaunch.H23rrk/live4765-12566/smhome
== exit code: 0
== secondmate agent command now: claude
== journal children=: 2
Evidence: Fixed relaunch under real scratch churn, 20 runs

Source: Fixed relaunch under real scratch churn, 20 runs

== exit code: 0
== journal children=: 2
== exit code: 0
== journal children=: 2
== exit code: 0
== journal children=: 2
== exit code: 0
== journal children=: 2
== exit code: 0
== journal children=: 2
== exit code: 0
== journal children=: 2
== exit code: 0
== journal children=: 2
== exit code: 0
== journal children=: 2
== exit code: 0
== journal children=: 2
== exit code: 0
== journal children=: 2
== exit code: 0
== journal children=: 2
== exit code: 0
== journal children=: 2
== exit code: 0
== journal children=: 2
== exit code: 0
== journal children=: 2
== exit code: 0
== journal children=: 2
== exit code: 0
== journal children=: 2
== exit code: 0
== journal children=: 2
== exit code: 0
== journal children=: 2
== exit code: 0
== journal children=: 2
== exit code: 0
== journal children=: 2
Evidence: Refusal: unreadable child meta

Source: Refusal: unreadable child meta

######## BASE (1bb72cc) mode=unreadable
== control script: /tmp/fm4765.C1XN/bin/fm-control.sh
== state/ before relaunch:
   total 8
   drwxr-xr-x 2 firstmate firstmate  80 Sep 19 04:42 .
   drwxr-xr-x 5 firstmate firstmate 180 Sep 19 04:42 ..
   -rw-r--r-- 1 firstmate firstmate  15 Sep 19 04:42 c1.meta
   ---------- 1 firstmate firstmate  15 Sep 19 04:42 c2.meta
== $ fm-control.sh sm9 relaunch
   error: secondmate sm9's child record /tmp/fm-control-relaunch.IkFXXe/live4765-27430/smhome/state/c2.meta is not a readable regular file; refusing to relaunch
== exit code: 1
== secondmate agent command now: claude
== journal children=: 

######## FIX (ef8a25b) mode=unreadable
== control script: ~/.no-mistakes/worktrees/42fe67ed39fa/01M2VYARPVCA20CAN8081M3MZS/bin/fm-control.sh
== state/ before relaunch:
   total 8
   drwxr-xr-x 2 firstmate firstmate  80 Sep 19 04:42 .
   drwxr-xr-x 5 firstmate firstmate 180 Sep 19 04:42 ..
   -rw-r--r-- 1 firstmate firstmate  15 Sep 19 04:42 c1.meta
   ---------- 1 firstmate firstmate  15 Sep 19 04:42 c2.meta
== $ fm-control.sh sm9 relaunch
   error: secondmate sm9's child record /tmp/fm-control-relaunch.Ud1dfp/live4765-3404/smhome/state/c2.meta is not a readable regular file; refusing to relaunch
== exit code: 1
== secondmate agent command now: claude
== journal children=: 
Evidence: Refusal: directory named *.meta

Source: Refusal: directory named *.meta

######## BASE (1bb72cc) mode=metadir
== control script: /tmp/fm4765.C1XN/bin/fm-control.sh
== state/ before relaunch:
   total 8
   drwxr-xr-x 3 firstmate firstmate 100 Sep 19 04:42 .
   drwxr-xr-x 5 firstmate firstmate 180 Sep 19 04:42 ..
   drwxr-xr-x 2 firstmate firstmate  40 Sep 19 04:42 bad.meta
   -rw-r--r-- 1 firstmate firstmate  15 Sep 19 04:42 c1.meta
   -rw-r--r-- 1 firstmate firstmate  15 Sep 19 04:42 c2.meta
== $ fm-control.sh sm9 relaunch
   error: secondmate sm9's child record /tmp/fm-control-relaunch.GwpQ4y/live4765-20793/smhome/state/bad.meta is not a readable regular file; refusing to relaunch
== exit code: 1
== secondmate agent command now: claude
== journal children=: 

######## FIX (ef8a25b) mode=metadir
== control script: ~/.no-mistakes/worktrees/42fe67ed39fa/01M2VYARPVCA20CAN8081M3MZS/bin/fm-control.sh
== state/ before relaunch:
   total 8
   drwxr-xr-x 3 firstmate firstmate 100 Sep 19 04:42 .
   drwxr-xr-x 5 firstmate firstmate 180 Sep 19 04:42 ..
   drwxr-xr-x 2 firstmate firstmate  40 Sep 19 04:42 bad.meta
   -rw-r--r-- 1 firstmate firstmate  15 Sep 19 04:42 c1.meta
   -rw-r--r-- 1 firstmate firstmate  15 Sep 19 04:42 c2.meta
== $ fm-control.sh sm9 relaunch
   error: secondmate sm9's child record /tmp/fm-control-relaunch.okLGLJ/live4765-1071/smhome/state/bad.meta is not a readable regular file; refusing to relaunch
== exit code: 1
== secondmate agent command now: claude
== journal children=: 
Evidence: Refusal: unlistable state dir

Source: Refusal: unlistable state dir

######## BASE (1bb72cc) mode=unlistable
== control script: /tmp/fm4765.C1XN/bin/fm-control.sh
== state/ before relaunch:
   ls: cannot open directory '/tmp/fm-control-relaunch.OEgUHF/live4765-30083/smhome/state': Permission denied
== $ fm-control.sh sm9 relaunch
   error: secondmate sm9's child records cannot be traversed; refusing to relaunch
== exit code: 1
== secondmate agent command now: claude
== journal children=: 

######## FIX (ef8a25b) mode=unlistable
== control script: ~/.no-mistakes/worktrees/42fe67ed39fa/01M2VYARPVCA20CAN8081M3MZS/bin/fm-control.sh
== state/ before relaunch:
   ls: cannot open directory '/tmp/fm-control-relaunch.i3krCW/live4765-29134/smhome/state': Permission denied
== $ fm-control.sh sm9 relaunch
   error: secondmate sm9's home has no readable state directory, so its child work cannot be accounted for; refusing to relaunch
== exit code: 1
== secondmate agent command now: claude
== journal children=: 
Evidence: Refusal: missing state dir

Source: Refusal: missing state dir

######## BASE (1bb72cc) mode=nostate
== control script: /tmp/fm4765.C1XN/bin/fm-control.sh
== state/ before relaunch:
   ls: cannot access '/tmp/fm-control-relaunch.IcVoKH/live4765-32166/smhome/state': No such file or directory
== $ fm-control.sh sm9 relaunch
   error: secondmate sm9's home has no readable state directory, so its child work cannot be accounted for; refusing to relaunch
== exit code: 1
== secondmate agent command now: claude
== journal children=: 

######## FIX (ef8a25b) mode=nostate
== control script: ~/.no-mistakes/worktrees/42fe67ed39fa/01M2VYARPVCA20CAN8081M3MZS/bin/fm-control.sh
== state/ before relaunch:
   ls: cannot access '/tmp/fm-control-relaunch.b5YwxI/live4765-2091/smhome/state': No such file or directory
== $ fm-control.sh sm9 relaunch
   error: secondmate sm9's home has no readable state directory, so its child work cannot be accounted for; refusing to relaunch
== exit code: 1
== secondmate agent command now: claude
== journal children=: 
Evidence: Driver script

Source: Driver script

#!/usr/bin/env bash
# fm-control.sh relaunch: the transactional replace-the-agent verb.
#
# Relaunch is the only control verb that changes durable records, so these
# tests pin the transaction itself, hermetically (stubbed session provider, no
# real agent):
#   1. A same-harness relaunch keeps every identity axis and reuses the SAME
#      endpoint and worktree - it replaces an agent, it never forks a task.
#   2. A harness switch is one ordinary relaunch: the record follows, the
#      previous harness's per-task wiring is cleared, and profile axes chosen
#      for the old harness do not silently carry to the new one.
#   3. The progress note is required where the replacement needs it, lands in
#      the instructions the replacement reads, and never rewrites a charter.
#   4. A refusal before the agent is stopped changes nothing.
#   5. A launch failure after the agent is stopped keeps the prior record,
#      reports the concrete state, and preserves the work.
#   6. fm-spawn --relaunch refuses on its own: a live agent, a contradicting
#      flag, an extra positional, or a backend that cannot prove the previous
#      agent exited.
set -u

# shellcheck source=tests/lib.sh
. "${FM4765_TESTS:?}/lib.sh"
# shellcheck source=/dev/null
. "$ROOT/bin/fm-control-lib.sh"
# shellcheck source=/dev/null
. "$ROOT/bin/fm-trace-context-lib.sh"

CONTROL="$ROOT/bin/fm-control.sh"
SPAWN="$ROOT/bin/fm-spawn.sh"
PROMOTE="$ROOT/bin/fm-promote.sh"
BRIEF="$ROOT/bin/fm-brief.sh"
X_LINK="$ROOT/bin/fm-x-link.sh"
# fm_test_tmproot's own cleanup trap fires when its command substitution exits,
# so recreate the root before resolving it and clean it up from this file's trap.
TMP_ROOT=$(fm_test_tmproot fm-control-relaunch)
mkdir -p "$TMP_ROOT"
TMP_ROOT=$(cd "$TMP_ROOT" && pwd)
TASK_TMPS=()

relaunch_cleanup() {
  local d
  for d in "${TASK_TMPS[@]:-}"; do
    [ -n "$d" ] && rm -rf "$d"
  done
  rm -rf "$TMP_ROOT"
}
trap relaunch_cleanup EXIT

# The same lifecycle-modelling tmux stub as tests/fm-control.test.sh: the
# harness's exit command stops the agent, and a launch-brief literal starts the
# harness named in `becomes`.
make_tmux_stub() {  # <dir>
  local fb="$1/fakebin"
  mkdir -p "$fb"
  cat > "$fb/tmux" <<'SH'
#!/usr/bin/env bash
set -u
D=$FM_FAKE_DIR
case "${1:-}" in
  send-keys)
    shift
    literal=0
    while [ $# -gt 0 ]; do
      case "$1" in
        -t) shift 2 ;;
        -l) literal=1; shift ;;
        *) break ;;
      esac
    done
    payload=${1:-}
    if [ "$literal" = 1 ]; then
      printf '%s\n' "$payload" >> "$D/literal"
      case "$payload" in
        /exit|/quit)
          printf 'zsh' > "$D/command"
          [ -z "${FM_FAKE_EXIT_TRANSPORT_FAIL_AFTER_STOP:-}" ] || exit 1
          ;;
        *'encode launch-brief'*)
          cat "$D/becomes" > "$D/command"
          [ -z "${FM_FAKE_LAUNCH_TRANSPORT_FAIL_AFTER_START:-}" ] || exit 1
          ;;
      esac
    else
      printf '%s\n' "$payload" >> "$D/keys"
      case "$payload" in
        'export GOTMPDIR='*)
          if [ -n "${FM_FAKE_TRACE_PREPARE:-}" ]; then
            : > "$FM_FAKE_TRACE_PREPARE"
            while [ ! -e "$FM_FAKE_TRACE_RELEASE" ]; do /bin/sleep 0.01; done
          fi
          ;;
        'export TRACEPARENT='*)
          [ -z "${FM_FAKE_TRACE_EXPORTED:-}" ] || : > "$FM_FAKE_TRACE_EXPORTED"
          ;;
      esac
    fi
    exit 0 ;;
  display-message)
    for a in "$@"; do
      case "$a" in
        *cursor_y*) printf '1\n'; exit 0 ;;
        *pane_current_command*) cat "$D/command"; printf '\n'; exit 0 ;;
        *pane_current_path*)
          if [ -n "${FM_FAKE_CWD_RACE_READY:-}" ]; then
            : > "$FM_FAKE_CWD_RACE_READY"
            /bin/sleep 1
          fi
          cat "$D/cwd"; printf '\n'; exit 0 ;;
      esac
    done
    printf 'fakepane\n'; exit 0 ;;
  capture-pane)
    [ -z "${FM_FAKE_COMPOSER_READ_FAIL:-}" ] || exit 1
    if [ -s "$D/composer" ]; then
      printf '╭────╮\n│ %s  │\n╰────╯\n' "$(cat "$D/composer")"
    else
      printf '╭────╮\n│    │\n╰────╯\n'
    fi
    exit 0 ;;
  list-windows) [ -f "$D/windows" ] && cat "$D/windows"; exit 0 ;;
esac
exit 0
SH
  chmod +x "$fb/tmux"
  cat > "$fb/sleep" <<'SH'
#!/usr/bin/env bash
[ -z "${FM_FAKE_LOCK_WAITING:-}" ] || : > "$FM_FAKE_LOCK_WAITING"
exit 0
SH
  chmod +x "$fb/sleep"
}

# new_case <name> [id] -> echoes a case dir with a live claude ship task.
new_case() {
  local id=${2:-t1} dir="$TMP_ROOT/$1-$RANDOM"
  mkdir -p "$dir/home/state" "$dir/home/data" "$dir/fake"
  : > "$dir/fake/literal"
  : > "$dir/fake/keys"
  printf 'claude' > "$dir/fake/command"
  printf 'claude' > "$dir/fake/becomes"
  printf '%s\n' "fm-$id" > "$dir/fake/windows"
  make_tmux_stub "$dir"
  printf '%s\n' "$dir"
}

# add_ship_task <case-dir> <id> [harness]
add_ship_task() {
  local dir=$1 id=$2 harness=${3:-claude}
  local home="$dir/home" proj="$dir/proj" wt="$dir/wt"
  fm_git_worktree "$proj" "$wt" "task-$id"
  mkdir -p "$home/data/$id"
  cat > "$home/data/$id/brief.md" <<EOF
# Task
## Captain's intent
Exercise relaunch behavior for $id.

## Firstmate spec
Preserve the task while replacing its agent process.
EOF
  {
    echo "window=fmses:fm-$id"
    echo "endpoint_task_id=$id"
    echo "worktree=$wt"
    echo "project=$proj"
    echo "harness=$harness"
    echo "kind=ship"
    echo "mode=no-mistakes"
    echo "yolo=off"
    echo "tasktmp=/tmp/fm-$id"
    echo "model=default"
    echo "effort=default"
  } > "$home/state/$id.meta"
  printf '%s\n' "fm-$id" > "$dir/fake/windows"
  printf '%s' "$wt" > "$dir/fake/cwd"
  TASK_TMPS+=("/tmp/fm-$id")
}

run_control() {  # <case-dir> <args...>
  local dir=$1; shift
  # A claude spawn pre-registers workspace trust in the launching user's own
  # store (bin/fm-claude-trust.sh), and a relaunch reaches it through fm-control.sh, so this runs against a throwaway HOME;
  # without it this suite would write the developer's real ~/.claude.json.
  mkdir -p "$dir/user-home"
  env PATH="$dir/fakebin:$PATH" FM_HOME="$dir/home" FM_FAKE_DIR="$dir/fake" \
    HOME="$dir/user-home" CLAUDE_CONFIG_DIR='' \
    FM_SPAWN_NO_GUARD=1 GROK_HOME="$dir/grokhome" \
    FM_CONTROL_POLL=0.01 FM_CONTROL_EXIT_WAIT=0.05 FM_CONTROL_LAUNCH_WAIT=0.05 \
    FM_REAL_GIT="${FM_REAL_GIT:-}" FM_FAKE_GIT_FAILURE="${FM_FAKE_GIT_FAILURE:-}" \
    FM_REAL_MV="${FM_REAL_MV:-}" FM_FAKE_COMPLETE_JOURNAL_MV_FAIL="${FM_FAKE_COMPLETE_JOURNAL_MV_FAIL:-}" \
    FM_FAKE_META_PUBLISH_MV_FAIL="${FM_FAKE_META_PUBLISH_MV_FAIL:-}" \
    FM_FAKE_TRACE_PREPARE="${FM_FAKE_TRACE_PREPARE:-}" \
    FM_FAKE_TRACE_RELEASE="${FM_FAKE_TRACE_RELEASE:-}" \
    FM_FAKE_META_WRITER_READY="${FM_FAKE_META_WRITER_READY:-}" \
    FM_FAKE_TRACE_EXPORTED="${FM_FAKE_TRACE_EXPORTED:-}" \
    "$CONTROL" "$@" 2>&1
}

run_spawn() {  # <case-dir> <args...>
  local dir=$1; shift
  # A claude spawn pre-registers workspace trust in the launching user's own
  # store (bin/fm-claude-trust.sh), so it runs against a throwaway HOME;
  # without it this suite would write the developer's real ~/.claude.json.
  mkdir -p "$dir/user-home"
  env PATH="$dir/fakebin:$PATH" FM_HOME="$dir/home" FM_FAKE_DIR="$dir/fake" \
    HOME="$dir/user-home" CLAUDE_CONFIG_DIR='' \
    FM_SPAWN_NO_GUARD=1 GROK_HOME="$dir/grokhome" \
    "$SPAWN" "$@" 2>&1
}

meta_field() {  # <case-dir> <id> <key>
  grep "^$3=" "$1/home/state/$2.meta" | tail -1 | cut -d= -f2-
}

journal_field() {  # <case-dir> <id> <key>
  grep "^$3=" "$1/home/state/$2.control-relaunch" | tail -1 | cut -d= -f2-
}

make_git_failure_stub() {  # <case-dir>
  cat > "$1/fakebin/git" <<'SH'
#!/usr/bin/env bash
case "${FM_FAKE_GIT_FAILURE:-}:$*" in
  head:*' rev-parse --verify HEAD'|head:*' symbolic-ref -q HEAD') exit 128 ;;
  status:*' status --porcelain') exit 128 ;;
esac
exec "$FM_REAL_GIT" "$@"
SH
  chmod +x "$1/fakebin/git"
}

make_mv_failure_stub() {  # <case-dir>
  cat > "$1/fakebin/mv" <<'SH'
#!/usr/bin/env bash
if [ -n "${FM_FAKE_COMPLETE_JOURNAL_MV_FAIL:-}" ]; then
  for path in "$@"; do
    if [ -f "$path" ] && grep -Fqx 'phase=complete' "$path"; then
      exit 1
    fi
  done
fi
if [ -n "${FM_FAKE_META_PUBLISH_MV_FAIL:-}" ]; then
  for path in "$@"; do
   

... [66517 bytes truncated] ...

f [ ! -e "$lock/continuity-sentinel" ]; then
    : > "$dir/meta-lock-was-recreated"
  fi
fi
exec "$dir/fakebin/tmux-real" "\$@"
SH
  chmod +x "$dir/fakebin/tmux"

  out=$(run_spawn "$dir" rl38 --relaunch --harness claude); rc=$?
  expect_code 0 "$rc" "relaunch with one continuous meta lock should succeed"$'\n'"$out"
  assert_present "$dir/lock-observation-started" \
    "test did not observe the relaunch-held meta lock"
  assert_absent "$dir/meta-lock-was-recreated" \
    "relaunch released or recreated its already-held meta lock"
  pass "fm-spawn --relaunch: keeps its early meta lock continuous"
}

test_spawn_relaunch_refuses_a_pending_authoritative_close() {
  local dir meta marker out rc
  dir=$(new_case pending-close rl36)
  add_ship_task "$dir" rl36 claude
  meta="$dir/home/state/rl36.meta"
  printf 'spawn_gen=spawn-pending\n' >> "$meta"
  cp "$meta" "$dir/meta.before"
  mkdir -p "$dir/wt/.claude"
  printf 'prior wiring\n' > "$dir/wt/.claude/settings.local.json"
  marker="$dir/home/state/rl36.backlog-close"
  printf 'id=rl36\ndata=%s\nspawn_gen=spawn-pending\narg=--note\narg=local%%20main\n' \
    "$dir/home/data" > "$marker"
  printf 'zsh' > "$dir/fake/command"

  out=$(run_spawn "$dir" rl36 --relaunch --harness claude); rc=$?
  expect_code 1 "$rc" "relaunching over a pending close should refuse"
  assert_contains "$out" "pending authoritative backlog close" \
    "the refusal should identify the close that still owns the task"
  cmp -s "$dir/meta.before" "$meta" \
    || fail "pending-close refusal replaced the task incarnation"
  assert_grep 'prior wiring' "$dir/wt/.claude/settings.local.json" \
    "pending-close refusal cleared the prior worker wiring"
  assert_present "$marker" "pending-close refusal discarded the authoritative close"
  pass "fm-spawn --relaunch: pending closes refuse before replacement begins"
}

test_spawn_relaunch_refuses_contradicting_flags() {
  local dir out rc
  dir=$(new_case flags rl16)
  add_ship_task "$dir" rl16 claude
  printf 'zsh' > "$dir/fake/command"
  out=$(run_spawn "$dir" rl16 --relaunch --backend herdr); rc=$?
  expect_code 1 "$rc" "--backend should be refused alongside --relaunch"
  assert_contains "$out" "recorded backend" "the refusal should name the recorded backend rule"
  out=$(run_spawn "$dir" rl16 --relaunch --scout); rc=$?
  expect_code 1 "$rc" "--scout should be refused alongside --relaunch"
  assert_contains "$out" "recorded kind" "the refusal should name the recorded kind rule"
  out=$(run_spawn "$dir" rl16 "$dir/proj" --relaunch); rc=$?
  expect_code 1 "$rc" "a project positional should be refused alongside --relaunch"
  assert_contains "$out" "takes the task id only" "the refusal should name the positional rule"
  pass "fm-spawn --relaunch: every identity axis comes from the record, and a contradicting flag refuses"
}

test_spawn_relaunch_refuses_an_unrecorded_task() {
  local dir out rc
  dir=$(new_case norecord rl17)
  add_ship_task "$dir" rl17 claude
  out=$(run_spawn "$dir" nosuchtask --relaunch); rc=$?
  expect_code 1 "$rc" "an unrecorded task should refuse"
  assert_contains "$out" "needs an existing task record" "the refusal should name the missing record"
  pass "fm-spawn --relaunch: an unrecorded task is refused"
}

test_spawn_relaunch_refuses_a_pane_outside_the_worktree() {
  local dir out rc
  dir=$(new_case wrongcwd rl18)
  add_ship_task "$dir" rl18 claude
  printf 'zsh' > "$dir/fake/command"
  printf '%s' "$dir/proj" > "$dir/fake/cwd"
  out=$(run_spawn "$dir" rl18 --relaunch --harness claude); rc=$?
  expect_code 1 "$rc" "a pane outside the worktree should refuse"
  assert_contains "$out" "not its recorded worktree" "the refusal should name the wrong location"
  [ ! -s "$dir/fake/keys" ] || fail "a refused tmux relaunch must send nothing to the pane"
  pass "fm-spawn --relaunch: refuses to start a replacement outside the copy holding its work"
}

test_relaunch_reverifies_an_already_in_flight_item_instead_of_rewriting_it() {
  local dir out rc=0
  command -v tasks-axi >/dev/null 2>&1 || {
    pass "skipped: tasks-axi is not installed, so the backlog transition is inert"
    return 0
  }
  dir=$(new_case reverify rl40)
  add_ship_task "$dir" rl40 claude
  seed_backlog "$dir" rl40 in_flight
  break_tasks_axi_start "$dir"

  out=$(run_control "$dir" rl40 relaunch --note "picking the work back up") || rc=$?
  expect_code 0 "$rc" "a relaunch must not re-run a transition the row already reflects"$'\n'"$out"
  [ "$(backlog_state "$dir" rl40)" = in_flight ] \
    || fail "a relaunch changed an already In-flight item to $(backlog_state "$dir" rl40)"
  pass "relaunch re-reads the backlog item instead of blindly re-running the transition"
}

test_relaunch_moves_a_drifted_item_back_in_flight() {
  local dir out rc=0
  command -v tasks-axi >/dev/null 2>&1 || {
    pass "skipped: tasks-axi is not installed, so the backlog transition is inert"
    return 0
  }
  dir=$(new_case drifted rl41)
  add_ship_task "$dir" rl41 claude
  seed_backlog "$dir" rl41 queued

  out=$(run_control "$dir" rl41 relaunch --note "picking the work back up") || rc=$?
  expect_code 0 "$rc" "a relaunch onto a drifted item should succeed"$'\n'"$out"
  [ "$(backlog_state "$dir" rl41)" = in_flight ] \
    || fail "a relaunch left its item at $(backlog_state "$dir" rl41)"
  pass "relaunch heals an item that drifted out of In flight while the task stayed live"
}


# ---- issue #4765 live driver ----
# CONTROL may point at the base-commit fm-control.sh via FM4765_CONTROL.
[ -n "${FM4765_CONTROL:-}" ] && CONTROL=$FM4765_CONTROL
setup_sm() {  # <dir> <id>
  local dir=$1 id=$2 home="$1/home"
  mkdir -p "$home/config"; printf 'claude\n' > "$home/config/secondmate-harness"
  fm_git_worktree "$dir/proj" "$dir/smhome" sm-branch >/dev/null 2>&1
  mkdir -p "$dir/smhome/state" "$dir/smhome/data" "$dir/smhome/bin"
  printf '%s\n' "$id" > "$dir/smhome/.fm-secondmate-home"
  printf '# charter\n' > "$dir/smhome/data/charter.md"; printf '# agents\n' > "$dir/smhome/AGENTS.md"
  printf 'window=x:fm-c1\n' > "$dir/smhome/state/c1.meta"
  printf 'window=x:fm-c2\n' > "$dir/smhome/state/c2.meta"
  printf 'window=fmses:fm-%s\nendpoint_task_id=%s\nworktree=%s\nproject=%s\nharness=claude\nkind=secondmate\nmode=secondmate\nyolo=off\nmodel=default\neffort=default\nhome=%s\nprojects=\n' \
    "$id" "$id" "$dir/smhome" "$dir/smhome" "$dir/smhome" > "$home/state/$id.meta"
  printf 'fm-%s\n' "$id" > "$dir/fake/windows"; printf '%s' "$dir/smhome" > "$dir/fake/cwd"
}
echo "== control script: $CONTROL"
mode=${1:?}
dir=$(new_case live4765 sm9); setup_sm "$dir" sm9
case "$mode" in
  vanish)  # find hits an entry that vanished between readdir and processing (the reported failure)
    real_find=$(command -v find)
    cat > "$dir/fakebin/find" <<SH
#!/usr/bin/env bash
for a in "\$@"; do [ "\$a" = "$dir/smhome/state" ] && { echo "find: \$a/.hash-7: No such file or directory" >&2; exit 1; }; done
exec "$real_find" "\$@"
SH
    chmod +x "$dir/fakebin/find"
    ( while :; do for i in $(seq 1 50); do : > "$dir/smhome/state/.hash-$i"; : > "$dir/smhome/state/.count-$i"; : > "$dir/smhome/state/.last-$i"; done; rm -f "$dir/smhome/state"/.hash-* "$dir/smhome/state"/.count-* "$dir/smhome/state"/.last-*; done ) & churn=$!
    ;;
  churn) ( while :; do for i in $(seq 1 50); do : > "$dir/smhome/state/.hash-$i"; : > "$dir/smhome/state/.last-$i"; done; rm -f "$dir/smhome/state"/.hash-* "$dir/smhome/state"/.last-*; done ) & churn=$! ;;
  unreadable) chmod 000 "$dir/smhome/state/c2.meta" ;;
  metadir) mkdir "$dir/smhome/state/bad.meta" ;;
  unlistable) chmod 000 "$dir/smhome/state" ;;
  nostate) rm -rf "$dir/smhome/state" ;;
esac
echo "== state/ before relaunch:"; ls -la "$dir/smhome/state" 2>&1 | sed 's/^/   /' | head -12
echo "== \$ fm-control.sh sm9 relaunch"
out=$(run_control "$dir" sm9 relaunch); rc=$?
[ -n "${churn:-}" ] && { kill $churn; wait $churn 2>/dev/null; }
chmod 755 "$dir/smhome/state" 2>/dev/null; chmod 644 "$dir/smhome/state/c2.meta" 2>/dev/null
printf '%s\n' "$out" | sed 's/^/   /'
echo "== exit code: $rc"
echo "== secondmate agent command now: $(cat "$dir/fake/command")"
echo "== journal children=: $(journal_field "$dir" sm9 children 2>/dev/null)"

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 1 issue found → auto-fixed ✅
  • ⚠️ tests/fm-control-relaunch.test.sh:1414 - The new unlistable-state assertion uses chmod 000 &#34;$dir/smhome/state&#34; and expects relaunch to exit 1. If the suite runs as root (UID 0), which is common in containers, [ -r ]/[ -x ] in bin/fm-control.sh:752 return true for a mode-000 directory. Root can also list the directory, so the glob finds c1.meta and relaunch succeeds with rc 0, and expect_code 1 fails. The version this replaces used a fake find and a directory named as a .meta, so it did not depend on the caller's UID. Other suites already guard the same way (for example tests/fm-claude-trust.test.sh:508 and tests/fm-procevent.test.sh:2237 check id -u). Fix: skip or branch this sub-case when $(id -u) is 0, so the test does not fail when run as root.

🔧 Fix applied.
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 5 of 5 scenarios driven live against the product
Scenario Result Live Evidence
Relaunch a secondmate while a watcher scratch file vanishes mid-find: base refuses, fix relaunches and counts 2 child records ✅ pass live live-vanish.txt: base exit 1 'child records cannot be traversed'; fix exit 0 'relaunched sm9', children=2
Relaunch repeatedly while a background watcher keeps creating and deleting .hash-/.last- files (real find), and every run succeeds ✅ pass live live-churn-20x.txt: 20/20 exit 0, children=2
Adversarial: unreadable child .meta still refuses and leaves the secondmate running ✅ pass live live-unreadable.txt: fix exit 1 'c2.meta is not a readable regular file', agent still claude
Adversarial: a directory named *.meta still refuses ✅ pass live live-metadir.txt: fix exit 1 'bad.meta is not a readable regular file'
Adversarial: unlistable (mode 000) or missing state/ still refuses ✅ pass live live-unlistable.txt and live-nostate.txt: fix exit 1 'no readable state directory'
  • bash tests/fm-control-relaunch.test.sh: all 58 cases pass, including the new vanished-scratch test and the unlistable-state test that is skipped as root (run here as a non-root user)
  • live-driver.sh vanish: base 1bb72cc vs fix ef8a25b, with an injected find failure on state/ while a background loop keeps creating and deleting .hash-/.count-/.last-* files
  • live-driver.sh churn x20: fixed fm-control.sh relaunch with the real find while scratch files churn
  • live-driver.sh unreadable|metadir|unlistable|nostate: refusal cases on base and fix
  • Probe: 3000 runs of the real GNU find -mindepth 1 -maxdepth 1 -print under scratch-file churn (0 failures on this Linux host)
✅ **Document** - passed

✅ No issues found.

🔧 **Lint** - 1 issue found → no changes applied (2) ✅
  • ⚠️ linter found issues (exit code 1)

🔧 No changes applied.
1 warning still open:

  • ⚠️ linter found issues (exit code 1)

🔧 No changes applied.
✅ Re-checked - no issues remain.

✅ **Push** - passed

✅ No issues found.

Relaunch refused when find(1) exited non-zero while listing a secondmate
home's state directory. A live watcher can delete scratch files between
readdir and processing, which is not evidence that child *.meta records
are unreadable.

Prove the directory is listable from its mode and keep the existing
readable-meta loop as the child-record guarantee. Fixes kunchenguid#4765.
@kunchenguid
kunchenguid merged commit dd9f2b4 into kunchenguid:main Sep 22, 2026
20 checks passed
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: this is merged. Thank you @tiago-peixoto — really appreciate you taking the time on this.

Contract-class: restore. Tip vs main: removed the find \"$WT/state\" walk that refused relaunch when watcher scratch vanished mid-scan; kept directory readability + per-*.meta checks (#4765). Attestation MATCH. Closes #4765 verified (Fixes #4765).

BohnBawerick added a commit to BohnBawerick/firstmate that referenced this pull request Sep 23, 2026