Skip to content

fix(bin): pin pid-identity time zone so engines in another TZ keep the host's grant - #7265

Merged
kunchenguid merged 4 commits into
kunchenguid:mainfrom
leo1oel:fm/fm-host-ack
Oct 25, 2026
Merged

kunchenguid merged 4 commits into
kunchenguid:mainfrom
leo1oel:fm/fm-host-ack

Conversation

@leo1oel

@leo1oel leo1oel commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Intent

The captain approved (2026-10-14: "好的, 你来提交就行") submitting the real firstmate bugs found by a retro to firstmate's upstream. This task fixes retro candidate #4: the supervision-host engine almost never completes a wake. state/.supervision-host.log over 2026-10-13T05:45Z to 2026-10-14T02:53Z shows 134 start, 109 failed, 110 to-main and 1 handled; each failed line has rc=0 reports=1 unacked=: the engine recorded an outcome but left its granted wake rows queued, so bin/fm-supervision-host.sh labels the turn failed and hands every wake to the main session (two model turns per wake). The engine prompt (bin/fm-supervision-instructions.sh) appears to have no wake-ack step for a Claude engine; that is the leading hypothesis, not yet proven.

What Changed

  • fm_pid_identity in bin/fm-wake-lib.sh now runs ps -o lstart= with TZ=UTC0. Before this, a supervision engine launched with a different TZ than the host's hooks would read the host's grant owner as dead. It then discarded the branch grant, refused its drain, and left every granted wake row queued for main. capturedProcessOutput in bin/fm-extension.mjs (which pidIdentity uses) now pins the same TZ: "UTC0".
  • The code comment and docs/turnend-guard.md record one accepted upgrade-window residual. On a host without /proc and outside UTC, an identity recorded before this change can read as reused until the restart that follows the update.
  • Added test_engine_in_another_time_zone_handles_its_granted_rows to tests/fm-supervision-host.test.sh. It runs the engine stub in another TZ through a new stub-tz fixture and hides /proc so Linux takes the process-table path. It then checks that the turn ends handled without a failed line, that the drain keeps the grant, and that the wake is acknowledged and never reaches main.

🤖 Generated with Claude Code

Risk Assessment

✅ Low: The change is small and well-bounded. It pins TZ=UTC0 on the lstart fallback in fm_pid_identity and on the matching ps call in fm-extension.mjs's pidIdentity, which consumes those identities. The grant-owner check in fm-supervision-engine-lib.sh (lines 196 and 259) goes through fm_pid_identity, so the engine-side drain now reads the same identity as the host. Other callers of capturedProcessOutput (pgid and command) do not depend on TZ. The upgrade-window residual is documented, as the user decided.

Testing

I first ran the new regression test on its own. It passes with the fix and fails with the fix reverted, reproducing the retro's failed rc=0 reports=1 unacked → to-main pattern. I then drove the real supervision host with a real Claude engine launched through the machine's cac wrapper, which exports a different TZ from the host's. With the fix the turn ended handled reports=1, the wake queue was empty and nothing went to main. With the fix reverted the real engine produced the exact retro failure and hand-back to main, and its own summary says the drain refused for lack of a branch-eligible snapshot. A cross-TZ check shows fm_pid_identity and the extension's ps spawn now render the same identity in every zone; before the change the extension's spawn rendered a different one. One setup problem came up: the first real-engine attempt had no bin/ in the fixture home and recorded no report. I symlinked bin and re-ran. Temporary test copies and wrapper dirs were removed and the worktree is clean. The change has no UI, so there are no screenshots.

  • Live validation: ✅ go - 2 of 4 scenarios driven live against the product
Scenario Result Live Evidence
A real Claude engine launched by a wrapper exporting a different TZ from the host drains, reports, acknowledges its granted rows, and the wake is handled without reaching main ✅ pass live live-real-claude-engine-with-fix.txt: handled ... rc=0 reports=1, wake queue empty, host still parked (no host.rc / no to-main)
Adversarial: the same live real-engine run with the TZ pin reverted reproduces the retro failure (rc=0 reports=1 unacked=<rows> then to-main) ✅ pass live live-real-claude-engine-fix-reverted.txt and live-engine-result-fix-reverted.json: failed rc=0 reports=1 unacked=1 2, to-main ... left its granted wake rows 1 2 unacknowledged; engine says the dra…
Regression test: engine in another time zone handles its granted rows; it fails before the fix and passes after ⏸️ untested no The prior payload did not establish a live result: this scenario ran the regression test with a stub engine, not against the live product (regression-test-with-fix.txt ok; regression-test-fix-reverted…
Process identity reads the same from shell callers in any TZ and from the extension's ps spawn ⏸️ untested no The prior payload did not establish a live result. The Pi extension path (bin/fm-extension.mjs) could not be driven inside a real Pi primary because pi is not on PATH. Only the extension's /bin/ps i…
Evidence: Live real Claude engine, host TZ=UTC0 vs cac engine TZ=America/New_York, with fix: turn handled, queue empty, no hand-back to main

Source: Live real Claude engine, host TZ=UTC0 vs cac engine TZ=America/New_York, with fix: turn handled, queue empty, no hand-back to main

home=/private/var/folders/25/sd66pgx930b20ffc13h_jgk00000gn/T/fm-supervision-host.8Z1OED/live-fixed3 host-TZ=UTC0 engine-wrapper-TZ=America/New_York
=== state/.supervision-host.log ===
1792905117	start	gen=host-6597-1792905117	primary=claude
1792905131	handled	turn=host-6597-1792905117.1	posture=attended	rc=0	reports=1	error=0 cost=0.019498 conversation_cost=0.019498 input=8 cache_read=67660 cache_write=2019 output=464 turns=4	signal: /private/var/folders/25/sd66pgx930b20ffc13h_jgk00000gn/T/fm-supervision-host.8Z1OED/live-fixed3/state/demo.status
=== wake queue (state/.wake-queue) ===
=== host.rc ===
(host still parked: no hand-back to main)
=== host.out ===
watcher: started pid=6769 (beacon fresh)
=== branch reports ===
Evidence: Live real Claude engine, same setup with the TZ pin reverted: failed rc=0 reports=1 unacked=1 2, then to-main (retro signature)

Source: Live real Claude engine, same setup with the TZ pin reverted: failed rc=0 reports=1 unacked=1 2, then to-main (retro signature)

home=/private/var/folders/25/sd66pgx930b20ffc13h_jgk00000gn/T/fm-supervision-host.8XMHb9/live-reverted host-TZ=UTC0 engine-wrapper-TZ=America/New_York
=== state/.supervision-host.log ===
1792905143	start	gen=host-19346-1792905143	primary=claude
1792905158	failed	turn=host-19346-1792905143.1	posture=attended	rc=0	reports=1	unacked=1 2	error=0 cost=0.023222 conversation_cost=0.023222 input=8 cache_read=67796 cache_write=2399 output=683 turns=4		signal: /private/var/folders/25/sd66pgx930b20ffc13h_jgk00000gn/T/fm-supervision-host.8XMHb9/live-reverted/state/demo.status
1792905158	to-main	the supervision session could not take this wake: the engine turn left its granted wake rows 1 2 unacknowledged; this wake is yours
=== wake queue (state/.wake-queue) ===
1792905144	1	signal	demo.status	signal: /private/var/folders/25/sd66pgx930b20ffc13h_jgk00000gn/T/fm-supervision-host.8XMHb9/live-reverted/state/demo.status
1792905144	2	signal	demo.status	signal: /private/var/folders/25/sd66pgx930b20ffc13h_jgk00000gn/T/fm-supervision-host.8XMHb9/live-reverted/state/demo.status
=== host.rc ===
0
=== host.out ===
watcher: started pid=19514 (beacon fresh)
signal: /private/var/folders/25/sd66pgx930b20ffc13h_jgk00000gn/T/fm-supervision-host.8XMHb9/live-reverted/state/demo.status
supervision-host: the supervision session could not take this wake: the engine turn left its granted wake rows 1 2 unacknowledged; this wake is yours
=== branch reports ===
Evidence: Real engine JSON result with fix (filed report and ran ack)

Source: Real engine JSON result with fix (filed report and ran ack)

{"duration_api_ms":6971,"stop_reason":"end_turn","session_id":"51d5cdc3-2885-4e80-84cc-e1d687fa6503","total_cost_usd":0.019497999999999998,"usage":{"input_tokens":8,"cache_creation_input_tokens":2019,"cache_read_input_tokens":67660,"output_tokens":464,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":2019,"ephemeral_5m_input_tokens":0},"inference_geo":"global","iterations":[],"speed":"standard","fallback_credit":null},"modelUsage":{"claude-sonnet-5-5":{"inputTokens":8,"outputTokens":464,"cacheReadInputTokens":67660,"cacheCreationInputTokens":2019,"webSearchRequests":0,"costUSD":0.019497999999999998,"contextWindow":1000000,"maxOutputTokens":128000,"thinkingTokens":0,"canonicalModel":"claude-sonnet-5-5","provider":"firstParty","costBasis":"list"}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","fast_mode_disabled_reason":"sdk_opt_in_required","subagent_stats":{"spawned":0,"requested":{"background":0,"foreground":0,"unset":0},"started_in_background":0,"max_depth":0,"spawned_by_subagents":0,"completed":0,"failed":0,"killed":{"parent":0,"user":0,"system":0},"refused":{"depth_limit":0,"concurrency_limit":0,"budget":0},"by_type":{}},"safety_stops":0,"is_error":false,"num_turns":4,"subtype":"success","api_error_status":null,"result":"The demo worker's wake was routine: its status line says it's still working on \"step one\", with nothing new. I took no action.\n\nI filed a silent routine report for `demo`. I also ran the acknowledgement command from the drain, which printed nothing, so I can't confirm from output that it consumed the wake. I claimed no leases because I changed nothing.","ttft_ms":2642,"type":"result","duration_ms":8965,"uuid":"97bdabbe-2918-4947-b855-1371e00e93e5","ttft_stream_ms":1823,"time_to_request_ms":628,"first_content_frame_ms":1823,"queued_turn_count":0,"result_index":0}
Evidence: Real engine JSON result with fix reverted (drain refused: no branch-eligible row snapshot)

Source: Real engine JSON result with fix reverted (drain refused: no branch-eligible row snapshot)

{"duration_api_ms":8358,"stop_reason":"end_turn","session_id":"faab9541-6a00-45c9-b988-dfb59802a040","total_cost_usd":0.023221600000000002,"usage":{"input_tokens":8,"cache_creation_input_tokens":2399,"cache_read_input_tokens":67796,"output_tokens":683,"output_tokens_details":{"thinking_tokens":44},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":2399,"ephemeral_5m_input_tokens":0},"inference_geo":"global","iterations":[],"speed":"standard","fallback_credit":null},"modelUsage":{"claude-sonnet-5-5":{"inputTokens":8,"outputTokens":683,"cacheReadInputTokens":67796,"cacheCreationInputTokens":2399,"webSearchRequests":0,"costUSD":0.023221600000000002,"contextWindow":1000000,"maxOutputTokens":128000,"thinkingTokens":44,"canonicalModel":"claude-sonnet-5-5","provider":"firstParty","costBasis":"list"}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","fast_mode_disabled_reason":"sdk_opt_in_required","subagent_stats":{"spawned":0,"requested":{"background":0,"foreground":0,"unset":0},"started_in_background":0,"max_depth":0,"spawned_by_subagents":0,"completed":0,"failed":0,"killed":{"parent":0,"user":0,"system":0},"refused":{"depth_limit":0,"concurrency_limit":0,"budget":0},"by_type":{}},"safety_stops":0,"is_error":false,"num_turns":4,"subtype":"success","api_error_status":null,"result":"I reported the demo task to MAIN as a silent routine outcome. The worker is still on step one and I took no action.\n\nThe wake drain refused to run. It said there was no branch-eligible row snapshot (`state/.branch-eligible-rows`). I read `state/demo.status` directly instead, which gave the \"working: step one\" line. I didn't run the acknowledgement command because the drain never printed one, so this wake may be presented again.\n\nI didn't check for open decisions, unread status or record divergence, since those come from the drain. If the missing snapshot persists, supervision wakes will keep failing the same way.","ttft_ms":2744,"type":"result","duration_ms":10079,"uuid":"bff04763-106e-417d-82b2-e37c5aa21e53","ttft_stream_ms":1825,"time_to_request_ms":683,"first_content_frame_ms":1825,"queued_turn_count":0,"result_index":0}
Evidence: Live driver script used for the real-engine runs

Source: Live driver script used for the real-engine runs

#!/usr/bin/env bash
# Behavior tests for the supervision host (bin/fm-supervision-host.sh,
# docs/supervision-host.md): its report surface (bin/fm-branch-report.sh), its
# dispatch entry (bin/fm-branch-dispatch.mjs), and the host loop itself.
#
# The loop cases run the real host, arm, watcher, wake grant, drain, outcome
# store, and lease scripts in a fixture home. The host runs as a child of a fake
# harness (a bash symlink named "claude") whose pid is the home's session lock,
# and its engine is a stub named by FM_SUPERVISION_ENGINE_CLAUDE_BIN that does
# what a branch turn does through the same scripts, so the real argument
# construction, bounding, and reaping are exercised without a model. A real
# status append drives each wake through the real watcher.
# shellcheck disable=SC2016 # single-quoted scripts expand inside their own shells
set -u

# shellcheck source=tests/wake-helpers.sh
. "$(dirname "${BASH_SOURCE[0]}")/wake-helpers.sh"

HOST="$ROOT/bin/fm-supervision-host.sh"
REPORT="$ROOT/bin/fm-branch-report.sh"
DISPATCH="$ROOT/bin/fm-branch-dispatch.mjs"
CONTRACT="$ROOT/bin/fm-afk-contract.sh"
LEASE="$ROOT/bin/fm-lease.sh"

command -v node >/dev/null 2>&1 || { printf 'skip: node absent\n'; exit 0; }
command -v perl >/dev/null 2>&1 || { printf 'skip: perl absent\n'; exit 0; }

TMP_ROOT=$(fm_test_tmproot fm-supervision-host)
FAKEBIN=$(fm_fakebin "$TMP_ROOT/fakebin")
ln -s /bin/bash "$FAKEBIN/claude"
FAKE_CLAUDE="$FAKEBIN/claude"

# The stub engine. It records its environment and arguments, then acts like a
# branch turn through the real scripts according to $FM_HOME/stub-mode:
#   handle      drain, claim the task's lease, report, acknowledge, release
#   captain     the same as handle, but report verdict captain naming the rows
#               the drain presented
#   hold-lease  the same, but leave the lease held (the host must release it),
#               logging its check line while held
#   return      handle, but the captain returns (the record is archived) before
#               the turn ends
#   return-silent the same, but the routine outcome is silent
#   return-fail the same, then exit nonzero without a result
#   return-fail-silent the same, but the routine outcome is silent
#   return-many handle, then seed more than 1,000 same-turn receipts after an
#               early visible outcome
#   return-lookup-fail handle, then corrupt the store before the return lookup
#   return-first the captain returns first, then handle, then block until the
#               host is stopped (an owner killing its host at the turn's end)
#   noack       the same as handle, but skip the acknowledgement
#   held        handle, but first block reading the $FM_HOME/stub-release FIFO
#               until the test writes to it, so the test chooses when the turn
#               ends
#   captain-held the same, but record a captain outcome before the turn ends
#   emptyresult the same as handle, but print {} as its result
#   noreport    drain and exit cleanly without a report
#   go-away     the captain goes away (the record is written) mid-turn, then
#               the turn reports verdict captain
#   fail        exit nonzero at once, with no result and no report (an engine
#               error the latch counts)
#   hang        before anything else, start a descendant in a process group of
#               its own, then block
#   hold-marker the same as handle, but before the result a helper takes the
#               recovery-marker lock for a few seconds, so the host's handled-
#               turn settle is still waiting for it (holding the queue lock)
# A $FM_HOME/stub-tz file sets the engine's TZ, as a wrapper launching the
# real engine binary may, independent of the host's own TZ.
STUB="$TMP_ROOT/engine-stub"
cat > "$STUB" <<'SH'
#!/usr/bin/env bash
set -u
STATE=${FM_STATE_OVERRIDE:-$FM_HOME/state}
mode=$(cat "$FM_HOME/stub-mode" 2>/dev/null || echo handle)
[ ! -s "$FM_HOME/stub-tz" ] || { TZ=$(cat "$FM_HOME/stub-tz"); export TZ; }
n=$(( $(ls "$FM_HOME"/engine-call.* 2>/dev/null | wc -l) + 1 ))
{
  printf 'mode=%s\nactor=%s\nholder=%s\nprimary=%s\nturn=%s\n' "$mode" "${FM_SUPERVISION_ACTOR:-}" \
    "${FM_LEASE_HOLDER_PID:-}" "${FM_SUPERVISION_PRIMARY_HARNESS:-}" "${FM_BRANCH_REPORT_TURN:-}"
  for a in "$@"; do printf 'arg=%s\n' "$a"; done
} > "$FM_HOME/engine-call.$n"
case "$mode" in held|captain-held) printf 'ready\n' > "$FM_HOME/stub-ready" ;; esac
# Like Claude, the reported cost is the conversation's running total.
result() {
  printf '{"type":"result","subtype":"success","is_error":false,"num_turns":3,"total_cost_usd":%s,' "$(awk -v n="$n" 'BEGIN { print n * 0.25 }')"
  printf '"usage":{"input_tokens":5,"cache_read_input_tokens":100,"cache_creation_input_tokens":10,"output_tokens":20},"session_id":"stub"}\n'
}
if [ "$mode" = hang ]; then
  perl -e 'setpgrp(0, 0); exec "sleep", $ARGV[0]' "$FM_TEST_STUB_MAX_BLOCK_SECONDS" &
  printf '%s\n' "$!" > "$FM_HOME/orphan-pid"
  sleep "$FM_TEST_STUB_MAX_BLOCK_SECONDS"
  exit 0
fi
drain=$("$FM_REPO/bin/fm-wake-drain.sh" 2>&1)
printf '%s\n' "$drain" > "$FM_HOME/engine-drain.$n"
ack=$(printf '%s\n' "$drain" | sed -n 's/^WAKE_ACK_REQUIRED: after handling completes run bin\/fm-wake-drain.sh //p' | tail -1)
task=$(sed -n 's/^tasks=//p' "$STATE/.supervision-host-turn" | awk '{ print $1 }')
[ -n "$task" ] || task=fleet
verdict=routine
[ "$mode" != go-away ] || verdict=captain
case "$mode" in
  fail) exit 3 ;;
  handle|captain|captain-close-before-return|held|captain-held|hold-lease|hold-marker|return|return-silent|return-fail|return-fail-silent|return-many|return-lookup-fail|return-first|noack|emptyresult|go-away)
    case "$mode" in held|captain-held) read -r _ < "$FM_HOME/stub-release" ;; esac
    [ "$mode" != return-first ] || "$FM_REPO/bin/fm-afk-contract.sh" archive >> "$FM_HOME/engine-return.log" 2>&1
    [ "$mode" != go-away ] || "$FM_REPO/bin/fm-afk-contract.sh" enter --words 'gone mid-turn' >> "$FM_HOME/engine-return.log" 2>&1
    "$FM_REPO/bin/fm-lease.sh" claim "$task" >> "$FM_HOME/engine-lease.log" 2>&1
    [ "$mode" != hold-lease ] || "$FM_REPO/bin/fm-lease.sh" check "$task" >> "$FM_HOME/engine-lease.log" 2>&1
    if [ "$mode" = captain ] || [ "$mode" = captain-held ] \
      || [ "$mode" = captain-close-before-return ]; then
      "$FM_REPO/bin/fm-branch-report.sh" --task "$task" --verdict captain \
        --summary "stub escalated: $(printf '%s\n' "$drain" | grep -v '^WAKE_' | tr '\n' ' ' | cut -c1-400)" \
        >> "$FM_HOME/engine-report.log" 2>&1
    else
      report_args=(--task "$task" --verdict "$verdict" --summary "stub handled $task")
      case "$mode" in
        return-silent|return-fail-silent)
          report_args=(--task "$task" --verdict routine --summary 'still working; nothing new has happened; no action was taken' --silent true)
          ;;
      esac
      "$FM_REPO/bin/fm-branch-report.sh" "${report_args[@]}" >> "$FM_HOME/engine-report.log" 2>&1
    fi
    if [ "$mode" = return-many ]; then
      awk -v task="$task" 'BEGIN { for (seq = 2; seq <= 1001; seq++)
        printf "{\"seq\":%d,\"epoch\":1,\"task\":\"%s\",\"wake\":\"host test\",\"verdict\":\"routine\",\"summary\":\"bulk silent fixture\",\"silent\":true}\n", seq, task
      }' >> "$STATE/branch-outcomes.jsonl"
      awk -v turn="$FM_BRANCH_REPORT_TURN" -v task="$task" 'BEGIN { for (seq = 2; seq <= 1001; seq++)
        printf "%s\t%d\troutine\t%s\n", turn, seq, task
      }' >> "$STATE/.supervision-host-receipts"
    fi
    if [ "$mode" = return-lookup-fail ]; then
      printf 'not-json\n' >> "$STATE/branch-outcomes.jsonl"
    fi
    # shellcheck disable=SC2086 # the printed acknowledgement arguments
    [ -z "$ack" ] || [ "$mode" = noack ] || "$FM_REPO/bin/fm-wake-drain.sh" $ack >> "$FM_HOME/engine-ack.log" 2>&1
    case "$mode" in captain-close-before-return)
      watcher=$(cat "$STATE/.watch.lock/pid" 2>/dev/null || true)
      [ -z "$watcher" ] || kill -TERM "$watcher" 2>/dev/null || true
      i=0
      while [ -n "$watcher" ] && kill -0 "$watcher" 2>/dev/null && [ "$i" -lt 100 ]; do
        sleep 0.05
        i=$((i + 1))
      done
      ;;
    esac
    [ "$mode" = hold-lease ] || "$FM_REPO/bin/fm-l

... [585 bytes truncated] ...

k_acquire_wait "$2" || exit 1
        : > "$3"
        sleep 3
        fm_lock_release "$2"' _ "$FM_REPO/bin/fm-wake-lib.sh" "$STATE/.watcher-down.lock" "$FM_HOME/marker-held" \
        >/dev/null 2>&1 </dev/null &
      i=0
      while [ ! -e "$FM_HOME/marker-held" ] && [ "$i" -lt 100 ]; do
        sleep 0.05
        i=$((i + 1))
      done
    fi
    result
    ;;
  noreport) result ;;
esac
SH
chmod +x "$STUB"

export FM_REPO="$ROOT"
export FM_SUPERVISION_ENGINE_CLAUDE_BIN=${LIVE_ENGINE_BIN:-/Users/leonardo/.cac/bin/claude}
export FM_SUPERVISION_HOST_PRIMARY=claude
export FM_POLL=1 FM_SIGNAL_GRACE=0 FM_CHECK_INTERVAL=999999 FM_HEARTBEAT=999999
# Keep the real engine watchdog/reaping path, but not its production grace in fixtures.
export FM_SUPERVISION_ENGINE_GRACE=1
export FM_ARM_CONFIRM_TIMEOUT=30
unset FM_SUPERVISION_ACTOR FM_BRANCH_REPORT_TURN FM_LEASE_HOLDER_PID PI_CODING_AGENT

# Homes are registered in a file: make_home runs in a command substitution,
# whose variables never reach this shell.
HOMES_FILE="$TMP_ROOT/homes"
# Stop whatever a case left running, by the exact pids its home recorded.
stop_home_processes() {  # <home>
  local home=$1 pid arms='' i=0
  pid=$(cut -f1 "$home/state/.supervision-handoff-owner" 2>/dev/null || true)
  [ -z "$pid" ] || kill -TERM "$pid" 2>/dev/null || true
  if [ -f "$home/state/.supervision-host" ]; then
    arms=$(awk -F '\t' '$1 == "arm" { print $2 }' "$home/state/.supervision-host")
    pid=$(awk -F '\t' '$1 == "host" { print $2; exit }' "$home/state/.supervision-host")
    [ -z "$pid" ] || kill -TERM "$pid" 2>/dev/null || true
    while [ "$i" -lt 50 ] && [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; do
      sleep 0.1
      i=$((i + 1))
    done
  fi
  for pid in $arms; do
    kill -TERM "$pid" 2>/dev/null || true
  done
  pid=$(cat "$home/state/.watch.lock/pid" 2>/dev/null || true)
  [ -z "$pid" ] || kill -TERM "$pid" 2>/dev/null || true
  while IFS= read -r pid; do
    if [ -e "$home/session.stop" ]; then
      wait "$pid" 2>/dev/null || true
    else
      kill -TERM "$pid" 2>/dev/null || true
    fi
  done < <(cat "$home/claude-pids" 2>/dev/null)
  while IFS= read -r pid; do
    kill -TERM "$pid" 2>/dev/null || true
  done < <(cat "$home/orphan-pid" 2>/dev/null)
}
suite_cleanup() {
  local home
  while IFS= read -r home; do
    [ -n "$home" ] && stop_home_processes "$home"
  done < <(cat "$HOMES_FILE" 2>/dev/null)
  fm_test_cleanup
}
trap suite_cleanup EXIT

make_home() {  # <name> <attended|away|quiet> [config line]
  local home="$TMP_ROOT/$1"
  mkdir -p "$home/state" "$home/config" "$home/fakebin"
  # An unreachable backend: the watcher reads no endpoint as dead, so the only
  # wakes are the status appends each case makes.
  printf '#!/usr/bin/env bash\nexit 1\n' > "$home/fakebin/tmux"
  chmod +x "$home/fakebin/tmux"
  make_fake_crew_state "$home/fakebin" >/dev/null
  printf '%s\n' "${3:-}" > "$home/config/supervision-host"
  [ -n "${3:-}" ] || : > "$home/config/supervision-host"
  printf 'project=demo\nwindow=fm-demo\nharness=claude\n' > "$home/state/demo.meta"
  echo handle > "$home/stub-mode"
  # The captain has spoken in this session, so an attended wake has a mirror.
  [ "$2" = away ] \
    || printf '{"hook_event_name":"UserPromptSubmit","prompt_id":"p0","prompt":"watch the fleet for me"}' > "$home/mirror-seed.0"
  if [ "$2" = away ]; then
    FM_HOME="$home" "$CONTRACT" enter --words 'watch the fleet; merge nothing' >/dev/null 2>&1 \
      || fail "fixture: could not record the away posture"
  fi
  # Quiet mode's record with no daemon flag: a quiet entry whose daemon never
  # started or stopped, left beside a present captain.
  if [ "$2" = quiet ]; then
    FM_HOME="$home" FM_AFK_MODE=quiet "$CONTRACT" enter --words 'keep routine wakes off my main' >/dev/null 2>&1 \
      || fail "fixture: could not record quiet mode"
    [ "$(FM_HOME="$home" "$CONTRACT" mode)" = quiet ] || fail "fixture: the record is not quiet mode's"
  fi
  printf '%s\n' "$home" >> "$HOMES_FILE"
  printf '%s\n' "$home"
}

# A git checkout that passes the primary-scope check, so the dialog-mirror
# writer runs from a linked worktree too; its bin is this repo's bin.
MIRROR_ROOT="$TMP_ROOT/mirror-root"
mkdir -p "$MIRROR_ROOT"
git init -q "$MIRROR_ROOT"
: > "$MIRROR_ROOT/AGENTS.md"
ln -s "$ROOT/bin" "$MIRROR_ROOT/bin"

# Run the host under the fake harness that holds the home's session lock.
# Every hook payload in $home/mirror-seed.* is first written to the dialog
# mirror by that same session, as its prompt and Stop hooks would.
start_host() {  # <home> [park options...]
  local home=$1
  shift
  FM_HOME="$home" FM_CREW_STATE_BIN="$home/fakebin/fm-crew-state.sh" PATH="$home/fakebin:$PATH" \
    MIRROR_ROOT="$MIRROR_ROOT" "$FAKE_CLAUDE" -c '
      printf "%s\n" "$$" > "$FM_HOME/state/.lock"
      printf "%s\n" "$$" >> "$FM_HOME/claude-pids"
      rm -f "$FM_HOME/host.rc"
      for seed in "$FM_HOME"/mirror-seed.*; do
        [ -f "$seed" ] || continue
        FM_ROOT_OVERRIDE="$MIRROR_ROOT" "$MIRROR_ROOT/bin/fm-host-mirror.sh" hook claude < "$seed"
      done
      "$0" park "$@" > "$FM_HOME/host.out" 2>&1
      printf "%s\n" "$?" > "$FM_HOME/host.rc"
    ' "$HOST" "$@" 2>> "$home/claude.err" &
}

# Extended-regex twins of tests/lib.sh's fixed-string assert_grep pair.
assert_re() {  # <regex> <file> <msg>
  grep -E -- "$1" "$2" >/dev/null || fail "$3"$'\n'"--- $2 ---"$'\n'"$(cat "$2" 2>/dev/null)"
}
assert_no_re() {  # <regex> <file> <msg>
  ! grep -E -- "$1" "$2" >/dev/null || fail "$3"$'\n'"--- $2 ---"$'\n'"$(cat "$2" 2>/dev/null)"
}

wait_until() {  # <polls of 0.1s> <command...>
  local limit=$1 i=0
  shift
  while [ "$i" -lt "$limit" ]; do
    "$@" && return 0
    sleep 0.1
    i=$((i + 1))
  done
  return 1
}

watcher_live() {  # <home>
  local pid
  pid=$(cat "$1/state/.watch.lock/pid" 2>/dev/null) || return 1
  [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null
}
host_exited() { [ -s "$1/host.rc" ]; }
# The recovery marker's episode kind (downtime or handling), read through its
# owner's parser; the Claude re-arm owner delivers a close only on downtime.
marker_kind() {  # <home>
  FM_HOME="$1" bash -c '
    . "$1"
    fm_recovery_marker_read "$2" || exit 1
    kind=${FM_RECOVERY_MARKER_TOKEN#*:}
    printf "%s\n" "${kind%%:*}"
  ' _ "$ROOT/bin/fm-wake-lib.sh" "$1/state/.watcher-down"
}
engine_calls() { find "$1" -maxdepth 1 -name 'engine-call.*' 2>/dev/null | wc -l | tr -d ' '; }
handled_count() { local n; n=$(grep -c '	handled	' "$1/state/.supervision-host.log" 2>/dev/null); printf '%s\n' "${n:-0}"; }
handled_at_least() { [ "$(handled_count "$1")" -ge "$2" ]; }
append_status() {  # <home> <text>
  printf '%s [at=%s]: %s\n' "${3:-working}" "$(date +%s)" "$2" >> "$1/state/demo.status"
}

# LIVE: the real Claude engine through the cac wrapper (which exports
# TZ=America/New_York from its env's tz file) beside a host running in TZ=UTC0.
export FM_SUPERVISION_ENGINE_CLAUDE_BIN=${LIVE_ENGINE_BIN:-/Users/leonardo/.cac/bin/claude}
export FM_SUPERVISION_ENGINE_GRACE=30
label=${LIVE_LABEL:-live}
home=$(make_home "$label" attended); ln -s "$ROOT/bin" "$home/bin"
echo "home=$home host-TZ=UTC0 engine-wrapper-TZ=$(cat ~/.cac/envs/working/tz)"
TZ=UTC0 start_host "$home"
wait_until 300 watcher_live "$home" || { echo "no watcher"; cat "$home/host.out"; exit 1; }
append_status "$home" 'step one'
i=0
while [ $i -lt 600 ]; do
  grep -qE $'\t(handled|failed|to-main)\t' "$home/state/.supervision-host.log" 2>/dev/null && break
  [ -s "$home/host.rc" ] && break
  sleep 1; i=$((i+1))
done
sleep 3
echo "=== state/.supervision-host.log ==="; cat "$home/state/.supervision-host.log"
echo "=== wake queue (state/.wake-queue) ==="; cat "$home/state/.wake-queue" 2>/dev/null || echo "(absent)"
echo "=== host.rc ==="; cat "$home/host.rc" 2>/dev/null || echo "(host still parked: no hand-back to main)"
echo "=== host.out ==="; cat "$home/host.out"
echo "=== branch reports ==="; ls -R "$home/state" | grep -i report | head; find "$home/state" -path '*report*' -type f -exec sh -c 'echo "-- $1"; head -c 1500 "$1"; echo' _ {} \; 2>/dev/null | head -60
stop_home_processes "$home"; [ -z "${LIVE_KEEP:-}" ] || cp -R "$home" "$LIVE_KEEP"
Evidence: Regression test output with fix

Source: Regression test output with fix

ok - host: an engine in another time zone than the host drains, reports, and acknowledges its granted rows
ok - host: an attended wake the branch may take is handled on the engine, and its routine outcome never wakes main
Evidence: Regression test output with fix reverted (fails as the retro did)

Source: Regression test output with fix reverted (fails as the retro did)

not ok - engine tz: the turn did not end handled: 1792904938	start	gen=host-43027-1792904938	primary=claude
1792904942	failed	turn=host-43027-1792904938.1	posture=attended	rc=0	reports=1	unacked=1 2	error=0 cost=0.25 conversation_cost=0.25 input=5 cache_read=100 cache_write=10 output=20 turns=3		signal: /private/var/folders/25/sd66pgx930b20ffc13h_jgk00000gn/T/fm-supervision-host.n7570i/engine-tz/state/demo.status
1792904942	to-main	the supervision session could not take this wake: the engine turn left its granted wake rows 1 2 unacknowledged; this wake is yours
wake drain: no branch-eligible row snapshot at /private/var/folders/25/sd66pgx930b20ffc13h_jgk00000gn/T/fm-supervision-host.n7570i/engine-tz/state/.branch-eligible-rows; refusing to guess what this actor may consume
Evidence: pid identity rendered identically across TZs (shell and extension-style spawn)

Source: pid identity rendered identically across TZs (shell and extension-style spawn)

target pid=43583 (sleep 300)
fm_pid_identity  TZ=UTC0              Sun Oct 25 05:13:05 2026     sleep 300
fm_pid_identity  TZ=America/New_York  Sun Oct 25 05:13:05 2026     sleep 300
fm_pid_identity  TZ=ENG-9             Sun Oct 25 05:13:05 2026     sleep 300
fm_pid_identity  TZ=Asia/Tokyo        Sun Oct 25 05:13:05 2026     sleep 300
extension-style ps spawn (env PATH/LANG/LC_ALL/TZ=UTC0): Sun Oct 25 05:13:05 2026     sleep 300
pre-change extension spawn (no TZ in env):            Sun Oct 25 13:13:05 2026     sleep 300

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 2 of 4 scenarios driven live against the product
Scenario Result Live Evidence
A real Claude engine launched by a wrapper exporting a different TZ from the host drains, reports, acknowledges its granted rows, and the wake is handled without reaching main ✅ pass live live-real-claude-engine-with-fix.txt: handled ... rc=0 reports=1, wake queue empty, host still parked (no host.rc / no to-main)
Adversarial: the same live real-engine run with the TZ pin reverted reproduces the retro failure (rc=0 reports=1 unacked=<rows> then to-main) ✅ pass live live-real-claude-engine-fix-reverted.txt and live-engine-result-fix-reverted.json: failed rc=0 reports=1 unacked=1 2, to-main ... left its granted wake rows 1 2 unacknowledged; engine says the dra…
Regression test: engine in another time zone handles its granted rows; it fails before the fix and passes after ⏸️ untested no The prior payload did not establish a live result: this scenario ran the regression test with a stub engine, not against the live product (regression-test-with-fix.txt ok; regression-test-fix-reverted…
Process identity reads the same from shell callers in any TZ and from the extension's ps spawn ⏸️ untested no The prior payload did not establish a live result. The Pi extension path (bin/fm-extension.mjs) could not be driven inside a real Pi primary because pi is not on PATH. Only the extension's /bin/ps i…
  • bash tests/zz-tz-only.test.sh (a temporary copy of tests/fm-supervision-host.test.sh, since removed, that runs only test_engine_in_another_time_zone_handles_its_granted_rows plus test_attended_routine_wake_is_handled_on_the_engine_and_stays_off_main) with the fix: both ok
  • The same focused test with the TZ=UTC0 pin reverted in bin/fm-wake-lib.sh: the new test fails with the retro signature failed rc=0 reports=1 unacked=1 2 / to-main, and the drain says no branch-eligible row snapshot; the pin was restored afterwards with git checkout
  • Live run: the real bin/fm-supervision-host.sh, watcher, grant, drain and report scripts in a disposable fixture home, host started with TZ=UTC0. The engine was the real Claude CLI through the machine's cac wrapper ~/.cac/bin/claude (exports TZ=America/New_York), behind a tee wrapper that captures its JSON result. A real status append triggered the wake
  • The same live real-engine run with the fix reverted
  • Cross-TZ check: fm_pid_identity under TZ=UTC0, America/New_York, ENG-9 and Asia/Tokyo, compared with a node spawn of /bin/ps using the extension's new env and its pre-change env
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

fm_pid_identity's ps fallback (macOS, or any host without /proc) renders
lstart in local time. A supervision engine launched through a wrapper that
exports a different TZ than the host's hook environment read the host's
branch-grant owner identity as a different process, so its drain discarded
the grant as stale and refused. The engine reported but could never
acknowledge its granted rows, and the host handed nearly every wake to main.

Pin TZ=UTC0 alongside the existing LC_ALL and COLUMNS pins, and pin the same
zone in fm-extension.mjs's pidIdentity, which compares identities the bash
helper writes. Add a host regression test that runs the engine in another
time zone than the host on the process-table path.
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thank you @leo1oel. This is a really clean find. A real-engine negative control that reproduces the failed rc=0 reports=1 unacked=… → to-main pattern before the fix and passes after it is exactly the evidence I hoped for.

What I checked: the full diff at b416d889 against current main 8c9c67de: bin/fm-wake-lib.sh (fm_pid_identity pinned to TZ=UTC0), bin/fm-extension.mjs (same pin on the ps child), and the new stub-engine host test with /proc hidden. There are no workflow, secret, or network changes. The no-mistakes attestation matches this head.

Fork CI: approved for this head (CI 38515579969, Require no-mistakes 38515579937).

Contract-class (my own verdict): restore. The supervision engine was already specified to drain, report, and acknowledge its granted rows. A time-zone mismatch was breaking that path. After the fix the default run does what it already promised, with no new surface. I accept the bounded upgrade-window residual on /proc-less non-UTC hosts as documented.

VISION: aligns on every rule (fewer duplicate main turns, deterministic script fix, harness-agnostic, guard for report-without-ack kept).

Live validation: 4 of 6 live, including the real-Claude before/after. I accept that.

Optional, your call: the no-mistakes review note about fm_pending_reply_pid_identity having the same unpinned lstart could be a nice follow-up. It doesn't block this PR.

Next step: once CI is green this can merge on its own, so it's waiting on CI, not on you.

@leo1oel leo1oel changed the title fix: pin TZ in process-table pid identity so engine wakes are handled fix(bin): pin pid-identity time zone so engines in another TZ keep the host's grant Oct 25, 2026
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thanks for bringing this up to date, @leo1oel, and for documenting the residual in docs/turnend-guard.md too.

I re-checked new head 28e2d9f1 against main 3c1e4684. The code is the same TZ=UTC0 pin in fm_pid_identity and in the fm-extension.mjs ps child, plus the stub-engine host test with /proc hidden. The new commit only adds the one doc line. It merges cleanly, there's no workflow, secret or network surface, and the no-mistakes attestation binds this head. Because of that, I approved the fork runs (CI 40164884949, Require no-mistakes 40164884959 and 40164930073), and they're running now.

Contract-class (mine): restore, unchanged. The engine was already specified to drain, report and acknowledge its granted rows, and a time-zone mismatch broke that. VISION: aligns on every rule. Your earlier live evidence still covers this.

A heads-up, nothing to do now: #7706 is splitting tests/fm-supervision-host.test.sh into two files. If it lands first, your new test may need a small move.

Next step: nothing is waiting on you. We're waiting on CI, and once it's green this can merge.

@kunchenguid
kunchenguid merged commit 43cd3b7 into kunchenguid:main Oct 25, 2026
37 of 38 checks passed
@kunchenguid

Copy link
Copy Markdown
Owner

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

cursor Bot pushed a commit that referenced this pull request Oct 25, 2026
Port #7265's engine time-zone grant test into the split host suites
and keep the combined host test file deleted.

Co-authored-by: Kun Chen <[email protected]>
vinicius928e8r84 pushed a commit to vinicius928e8r84/firstmate that referenced this pull request Nov 11, 2026
…e host's grant (kunchenguid#7265)

* fix(wake): pin TZ in the process-table pid identity

fm_pid_identity's ps fallback (macOS, or any host without /proc) renders
lstart in local time. A supervision engine launched through a wrapper that
exports a different TZ than the host's hook environment read the host's
branch-grant owner identity as a different process, so its drain discarded
the grant as stale and refused. The engine reported but could never
acknowledge its granted rows, and the host handed nearly every wake to main.

Pin TZ=UTC0 alongside the existing LC_ALL and COLUMNS pins, and pin the same
zone in fm-extension.mjs's pidIdentity, which compares identities the bash
helper writes. Add a host regression test that runs the engine in another
time zone than the host on the process-table path.

* no-mistakes(review): Document TZ-pin identity upgrade-window residual

* no-mistakes(document): Note TZ pid-identity upgrade residual in turnend-guard doc

(cherry picked from commit 43cd3b7)
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