Skip to content

fix(bin): release a project capacity place when a worker finishes and admit relaunches - #7079

Open
kesslerio wants to merge 17 commits into
kunchenguid:mainfrom
kesslerio:fm/project-capacity-done-frees-slot
Open

kesslerio wants to merge 17 commits into
kunchenguid:mainfrom
kesslerio:fm/project-capacity-done-frees-slot

Conversation

@kesslerio

@kesslerio kesslerio commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

What Changed

  • Project capacity counting now releases the place of a scout or local-only ship whose status history ends in done with no later working, while no-mistakes and direct-PR ships keep their place until their recorded PR handoff or cleanup; bookkeeping, captain-held, needs-decision, paused, or blocked events do not restore occupancy.
  • Relaunches now go through the same project-capacity admission check, excluding the relaunching task's own record, and a relaunch of a completed scout or local-only ship writes state/<task-id>.capacity-reservation (generation plus status offset) that holds the released place until the replacement's log records working or done. An aborted relaunch whose launch was never sent or whose endpoint was closed removes that reservation again.
  • The admission extras — a working: spawn admitted status line and the shared project lock on a relaunch — apply only once some project declares capacity, and docs/configuration.md, AGENTS.md, the spawn/lib header contracts, and the operational-home-layout skill document the completion rule, reservation format, and expiry.

Risk Assessment

✅ Low: The changes are bounded and preserve the approved completion, reservation expiry, and uncertain-delivery rules; no material defects were found.

Testing

Ran the repository's targeted capacity behavior suite, which drives the real bin/fm-spawn.sh through 24 cases and passed in full. Then drove an independent live driver that runs the real spawn executable against disposable Firstmate homes, real git clones with origins, and real meta/status/reservation files, exercising: a done scout freeing its place (with the deferral and the subsequent admitted spawn both observed), the no-mistakes ship guard, an in-flight relaunch reservation that survives bookkeeping and releases on the replacement's working/done, an aborted relaunch releasing its place, and malformed reservations holding a place. All 23 assertions passed on the target commit; running the identical driver against a base-commit copy produced 8 failures on precisely the intent scenarios, confirming the change is what fixes them. Only the tmux/treehouse/gh boundary is shimmed (the mux is not part of this behavior); admission decisions, records, status history, reservations and backlog files are real files. This is agent-tooling/CLI work with no rendered UI, so no screenshots apply.

  • Live validation: ✅ go - 5 of 5 scenarios driven live against the product
Scenario Result Live Evidence
A scout records done and the next queued worker on the capped project is admitted instead of deferred ✅ pass live live-capacity-driver.sh S1 (transcript live-capacity-target.log): working scout -> exit 75 'already hold a place (live-s)' with no task record; after 'done' appended -> exit 0 'spawned task-e' and sta…
A no-mistakes ship keeps its place after done plus captain-held bookkeeping, so the next worker is still deferred ✅ pass live live-capacity-driver.sh S2: exit 75 with 'already hold a place (live-p)' for a ship mode=no-mistakes whose status is working/done/captain-held
Relaunching a completed scout reserves the freed place through the launch window, ignores bookkeeping, keeps holding while the replacement works, and releases when the replacement records done ✅ pass live live-capacity-driver.sh S3: relaunch deferred while another task holds the only place; in-flight relaunch writes state/task-a.capacity-reservation with prior status bytes unchanged; a concurrent spawn…
Adversarial: a relaunch refused before launch (proven non-launch) removes the reservation so the place is usable, while a malformed or unparseable reservation holds a place instead of undercounting ✅ pass live live-capacity-driver.sh S4: relaunch with an invalid backend exits non-zero, no reservation file remains, next spawn admitted (exit 0); a finished scout carrying 'gen=stale/status_offset=not-a-number'…
The repository's capacity admission behavior suite passes end-to-end against the real spawn script ✅ pass live bash tests/fm-project-capacity.test.sh -> 24 ok cases including 'only finished scouts and local-only ships release on done until working resumes', 'relaunch reservations hold unchanged status until…
Evidence: Live capacity driver (real bin/fm-spawn.sh, disposable home + real git clone)

Source: Live capacity driver (real bin/fm-spawn.sh, disposable home + real git clone)

#!/usr/bin/env bash
# Independent live driver for the project-capacity change under validation.
# It drives the REAL bin/fm-spawn.sh executable end-to-end against a disposable
# Firstmate home, a real git project clone with a real origin, and real
# state/<id>.meta + state/<id>.status records. Only the terminal multiplexer,
# the worktree pool, gh and no-mistakes are simple boundary shims (the product
# never exercises mux semantics here; admission decisions, records, status
# history, reservations and backlog files are all real files).
#
# Independent oracle: docs/configuration.md "Project capacity" and
# bin/fm-spawn.sh --help state the contract used for every expectation:
#   - a scout or local-only ship that records `done` frees its place,
#   - a no-mistakes ship keeps its place after `done`,
#   - a relaunch of a completed scout/local-only ship reserves its place until
#     its status log records `working` or `done` after the reservation offset,
#   - bookkeeping alone never expires a reservation,
#   - a proven non-launch removes the reservation; an unreadable reservation
#     holds a place.
# A wrong implementation that still leaves `done` as an occupant, that treats
# any log growth as expiry, or that releases an aborted relaunch would fail
# these assertions.
set -u
REPO=${FM_DRIVER_REPO:-$(git rev-parse --show-toplevel)}
# shellcheck source=/dev/null
. "$REPO/tests/lib.sh"
unset TASKS_AXI_BACKEND || :
SPAWN="$ROOT/bin/fm-spawn.sh"
DEFER_EXIT=75
TMP=$(fm_test_tmproot fm-capacity-live)
FAILS=0

say() { printf '\n== %s\n' "$*"; }
ok() { printf 'PASS - %s\n' "$*"; }
bad() { printf 'FAIL - %s\n' "$*" >&2; FAILS=$((FAILS + 1)); }
expect_rc() { [ "$2" = "$1" ] && ok "$3 (exit $2)" || bad "$3: expected exit $1, got $2: $4"; }
contains() { case "$1" in *"$2"*) ok "$3";; *) bad "$3: output lacks [$2]: $1";; esac; }

brief() {  # <home> <id> [mode]
  mkdir -p "$1/data/$2"
  cat > "$1/data/$2/brief.md" <<EOF
# Task
## Captain's intent
Run the project's heavy suite for $2.

## Firstmate spec
Exercise project capacity admission.

# Definition of done
Delivery contract: mode=${3:-no-mistakes}
EOF
}

home_init() {  # <home> <id...>
  local home=$1 id
  shift
  mkdir -p "$home/state" "$home/config" "$home/data" "$home/projects"
  touch "$home/state/.last-watcher-beat"
  printf '%s\n' codex > "$home/config/crew-harness"
  if command -v tasks-axi >/dev/null 2>&1; then
    printf '%s\n' '# Backlog' '' '## In flight' '' '## Queued' '' '## Done' > "$home/data/backlog.md"
    printf 'backend = "markdown"\n\n[markdown]\npath = "data/backlog.md"\n' > "$home/.tasks.toml"
  fi
  for id in "$@"; do
    brief "$home" "$id"
    if command -v tasks-axi >/dev/null 2>&1; then
      tasks-axi add "$id" "item for $id" --kind ship --file "$home/data/backlog.md" >/dev/null
    fi
  done
}

case_init() {  # <name> [ids...]
  local name=$1 dir fakebin
  shift
  dir="$TMP/$name"
  mkdir -p "$dir"
  fakebin="$dir/fakebin"
  mkdir -p "$fakebin"
  cat > "$fakebin/tmux" <<'SH'
#!/usr/bin/env bash
printf '%s\n' "$*" >> "$FM_FAKE_CALL_LOG"
w="$FM_FAKE_CALL_LOG.window"
case "$*" in
  *'#{pane_current_command}'*) printf 'bash\n'; exit 0 ;;
  *'#{pane_current_path}')
    if [ -n "${FM_FAKE_HOLD:-}" ]; then
      : > "$FM_FAKE_HOLD.reached"
      i=0
      while [ ! -f "$FM_FAKE_HOLD.release" ]; do
        i=$((i + 1)); [ "$i" -lt 600 ] || exit 1; sleep 0.05
      done
    fi
    printf '%s\n' "${FM_FAKE_PANE_PATH:-}"; exit 0 ;;
esac
case "${1:-}" in
  send-keys)
    case "${5:-}" in '. '*) : > "$FM_FAKE_CALL_LOG.launch-text" ;; esac
    if [ -f "$FM_FAKE_CALL_LOG.launch-text" ] && [ -n "${FM_FAKE_SEND_HOLD:-}" ] && [ "${4:-}" = -l ]; then
      : > "$FM_FAKE_SEND_HOLD.reached"
      i=0
      while [ ! -f "$FM_FAKE_SEND_HOLD.release" ]; do
        i=$((i + 1)); [ "$i" -lt 600 ] || exit 1; sleep 0.05
      done
    fi ;;
  display-message) printf 'firstmate\n' ;;
  list-windows) [ ! -s "$w" ] || cat "$w" ;;
  new-window)
    name=; prev=
    for a in "$@"; do [ "$prev" = -n ] && name=$a; prev=$a; done
    grep -Fqx -- "$name" "$w" 2>/dev/null || printf '%s\n' "$name" >> "$w" ;;
  kill-window)
    t=; prev=
    for a in "$@"; do [ "$prev" = -t ] && t=$a; prev=$a; done
    t=${t##*:}; t=${t#=}
    grep -Fvx -- "$t" "$w" 2>/dev/null > "$w.tmp" || true; mv "$w.tmp" "$w" ;;
esac
exit 0
SH
  cat > "$fakebin/treehouse" <<'SH'
#!/usr/bin/env bash
printf 'treehouse %s\n' "$*" >> "$FM_FAKE_CALL_LOG"
exit 0
SH
  chmod +x "$fakebin/tmux" "$fakebin/treehouse"
  fm_fake_exit0 "$fakebin" gh gh-axi no-mistakes
  : > "$dir/calls.log"
  fm_git_init_commit "$dir/project"
  fm_git_add_origin "$dir/project" "$dir/project.origin.git"
  home_init "$dir/home" "$@"
  printf '%s\n' "$dir"
}

declare_capacity() { local h=$1; shift; printf '%s\n' "$@" > "$h/config/project-capacity"; }

live_worker() {  # <dir> <id> [kind] [mode] [status...]
  local dir=$1 id=$2 kind=${3:-ship} mode=${4:-no-mistakes}
  shift 4
  fm_write_meta "$dir/home/state/$id.meta" \
    "window=firstmate:fm-$id" "endpoint_task_id=$id" \
    "worktree=$dir/wt-$id" "project=$dir/project" "harness=codex" \
    "kind=$kind" "mode=$mode" "yolo=off" "spawn_gen=s-$id"
  : > "$dir/home/state/$id.status"
  printf '%s\n' "$@" >> "$dir/home/state/$id.status"
}

worktree_for() {  # <dir> <name>: one isolated worktree per task, created once
  [ -d "$1/wt-$2" ] || git -C "$1/project" worktree add --quiet -b "wt-$2" "$1/wt-$2"
  printf '%s\n' "$1/wt-$2"
}

spawn() {  # <dir> <pane> <args...>
  local dir=$1 pane=$2
  shift 2
  FM_ROOT_OVERRIDE='' FM_HOME="$dir/home" FM_STATE_OVERRIDE='' FM_DATA_OVERRIDE='' \
    FM_PROJECTS_OVERRIDE='' FM_CONFIG_OVERRIDE='' FM_SPAWN_NO_GUARD=1 \
    TMUX="fake,1,0" FM_BACKEND=tmux FM_FAKE_PANE_PATH="$pane" \
    FM_FAKE_CALL_LOG="$dir/calls.log" PATH="$dir/fakebin:$PATH" \
    "$SPAWN" "$@" 2>&1
}

fresh_ship() {  # <dir> <id>
  local dir=$1 id=$2 pane
  pane=$(worktree_for "$dir" "$id")
  spawn "$dir" "$pane" "$id" "$dir/project" --mode no-mistakes --yolo off
}

# --- scenarios --------------------------------------------------------------

say 'S1: a scout that reports done frees its project place for the next worker'
d=$(case_init s1-scout-done task-e)
declare_capacity "$d/home" 'project 1'
live_worker "$d" live-s scout '' 'working [at=1791700000]: scanning'
rc=0; out=$(fresh_ship "$d" task-e "$d/unused") || rc=$?
expect_rc "$DEFER_EXIT" "$rc" 'a working scout holds its place' "$out"
contains "$out" 'already hold a place (live-s)' 'the deferral names the working scout holder'
[ -e "$d/home/state/task-e.meta" ] && bad 'a deferred spawn published a record' || ok 'a deferred spawn left no record'
printf '%s\n' 'done [at=1791700200]: scan finished' >> "$d/home/state/live-s.status"
rc=0; out=$(fresh_ship "$d" task-e) || rc=$?
expect_rc 0 "$rc" 'a done scout releases its place for the next spawn' "$out"
contains "$out" 'spawned task-e' 'the next worker launched after the scout finished'
[ -f "$d/home/state/task-e.meta" ] && ok 'the admitted spawn published its task record' || bad 'the admitted spawn published no record'

say 'S2: a no-mistakes ship keeps its place after done (guard)'
d=$(case_init s2-ship-done task-e)
declare_capacity "$d/home" 'project 1'
live_worker "$d" live-p ship no-mistakes 'working [at=1791700000]: coding' 'done [at=1791700100]: code done' 'captain-held [at=1791700200]: decision transferred'
rc=0; out=$(fresh_ship "$d" task-e "$d/unused") || rc=$?
expect_rc "$DEFER_EXIT" "$rc" 'a shipped-mode worker still holds its place after done' "$out"
contains "$out" 'already hold a place (live-p)' 'the no-mistakes holder is named'

say 'S3: relaunching a finished scout reserves the place until the replacement reports'
d=$(case_init s3-relaunch task-a task-b)
declare_capacity "$d/home" 'project 1'
worktree_for "$d" task-a >/dev/null
live_worker "$d" task-a scout '' 'done [at=1791700000]: finished'
printf 'fm-task-a\n' > "$d/calls.log.window"
printf '%s\n' 'captain-held [at=1791700100]: decision transferred' >> "$d/home/state/task-a.status"
cp "$d/home/state/task-a.status" "$d/prior.status"
live_worker "$d" live-b ship no-mistakes 'working [at=1791700000]: busy'
rc=0; out=$(spawn "$d" "$d/wt-task-a" task-a --relaunch) || rc=$?
expect_rc "$DEFER_EXIT" "$rc" 'a relaunch is deferred while another worker holds the only place' "$out"
[ -e "$d/home/state/task-a.capacity-reservation" ] && bad 'a refused relaunch wrote a reservation' || ok 'a refused relaunch wrote no reservation'
printf 'pr=123\n' >> "$d/home/state/live-b.meta"
hold="$d/send-hold"
FM_FAKE_SEND_HOLD="$hold" spawn "$d" "$d/wt-task-a" task-a --relaunch > "$d/relaunch.out" 2>&1 &
pid=$!
i=0
while [ ! -f "$hold.reached" ]; do i=$((i+1)); [ "$i" -lt 600 ] || { bad 'relaunch never reached delivery'; break; }; sleep 0.05; done
[ -f "$d/home/state/task-a.capacity-reservation" ] && ok 'the in-flight relaunch reserved the released place' || bad 'no reservation during relaunch'
cmp -s "$d/prior.status" "$d/home/state/task-a.status" && ok 'the reservation left prior status history byte-identical' || bad 'the relaunch rewrote status history'
rc=0; out=$(fresh_ship "$d" task-b "$d/unused") || rc=$?
expect_rc "$DEFER_EXIT" "$rc" 'another spawn cannot take the place of the in-flight relaunch' "$out"
printf '%s\n' 'note [at=1791700150]: bookkeeping only' 'captain-held [at=1791700160]: bookkeeping only' >> "$d/home/state/task-a.status"
rc=0; out=$(fresh_ship "$d" task-b "$d/unused") || rc=$?
expect_rc "$DEFER_EXIT" "$rc" 'bookkeeping alone does not expire the reservation' "$out"
: > "$hold.release"
wait "$pid"; rrc=$?
expect_rc 0 "$rrc" 'the relaunch succeeded' "$(cat "$d/relaunch.out")"
[ -f "$d/home/state/task-a.capacity-reservation" ] && ok 'a successful relaunch keeps its reservation' || bad 'a successful relaunch dropped its reservation'
printf '%s\n' 'working [at=1791700300]: replacement active' >> "$d/home/state/task-a.status"
rc=0; out=$(fresh_ship "$d" task-b "$d/unused") || rc=$?
expect_rc "$DEFER_EXIT" "$rc" 'the running replacement still holds its place' "$out"
printf '%s\n' 'done [at=1791700400]: replacement finished' >> "$d/home/state/task-a.status"
rc=0; out=$(fresh_ship "$d" task-b) || rc=$?
expect_rc 0 "$rc" 'the replacement reporting done frees the place again' "$out"

say 'S4: an aborted relaunch releases its reservation'
d=$(case_init s4-abort task-a task-b)
declare_capacity "$d/home" 'project 1'
worktree_for "$d" task-a >/dev/null
live_worker "$d" task-a scout '' 'done [at=1791700000]: finished'
printf 'fm-task-a\n' > "$d/calls.log.window"
rc=0; out=$(spawn "$d" "$d/wt-task-a" task-a --relaunch --backend invalid-backend) || rc=$?
[ "$rc" -ne 0 ] && [ "$rc" -ne "$DEFER_EXIT" ] && ok "a relaunch refused before launch fails (exit $rc)" || bad "refused relaunch exit $rc: $out"
[ -e "$d/home/state/task-a.capacity-reservation" ] && bad 'a proven non-launch kept its reservation' || ok 'a proven non-launch removed the reservation'
rc=0; out=$(fresh_ship "$d" task-b) || rc=$?
expect_rc 0 "$rc" 'the place of an aborted relaunch is free for the next worker' "$out"

d=$(case_init s4-malformed task-c)
declare_capacity "$d/home" 'project 1'
live_worker "$d" task-m scout '' 'done [at=1791700000]: finished'
printf '%s\n' 'gen=stale' 'status_offset=not-a-number' > "$d/home/state/task-m.capacity-reservation"
rc=0; out=$(fresh_ship "$d" task-c "$d/unused") || rc=$?
expect_rc "$DEFER_EXIT" "$rc" 'a malformed reservation holds a place instead of undercounting' "$out"
printf 'garbage\n' > "$d/home/state/task-m.capacity-reservation"
rc=0; out=$(fresh_ship "$d" task-c "$d/unused") || rc=$?
expect_rc "$DEFER_EXIT" "$rc" 'an unparseable reservation holds a place too' "$out"

say "result: $([ "$FAILS" -eq 0 ] && echo PASS || echo "FAIL ($FAILS)")"
exit "$FAILS"
Evidence: Live driver transcript on the change (23/23 assertions pass)

Source: Live driver transcript on the change (23/23 assertions pass)


== S1: a scout that reports done frees its project place for the next worker
PASS - a working scout holds its place (exit 75)
PASS - the deferral names the working scout holder
PASS - a deferred spawn left no record
PASS - a done scout releases its place for the next spawn (exit 0)
PASS - the next worker launched after the scout finished
PASS - the admitted spawn published its task record

== S2: a no-mistakes ship keeps its place after done (guard)
PASS - a shipped-mode worker still holds its place after done (exit 75)
PASS - the no-mistakes holder is named

== S3: relaunching a finished scout reserves the place until the replacement reports
PASS - a relaunch is deferred while another worker holds the only place (exit 75)
PASS - a refused relaunch wrote no reservation
PASS - the in-flight relaunch reserved the released place
PASS - the reservation left prior status history byte-identical
PASS - another spawn cannot take the place of the in-flight relaunch (exit 75)
PASS - bookkeeping alone does not expire the reservation (exit 75)
PASS - the relaunch succeeded (exit 0)
PASS - a successful relaunch keeps its reservation
PASS - the running replacement still holds its place (exit 75)
PASS - the replacement reporting done frees the place again (exit 0)

== S4: an aborted relaunch releases its reservation
PASS - a relaunch refused before launch fails (exit 1)
PASS - a proven non-launch removed the reservation
PASS - the place of an aborted relaunch is free for the next worker (exit 0)
PASS - a malformed reservation holds a place instead of undercounting (exit 75)
PASS - an unparseable reservation holds a place too (exit 75)

== result: PASS
Evidence: Same driver against base commit 913bb7a (8 intent assertions fail: done did not free a place, relaunch wrote no reservation)

Source: Same driver against base commit 913bb7a (8 intent assertions fail: done did not free a place, relaunch wrote no reservation)


== S1: a scout that reports done frees its project place for the next worker
PASS - a working scout holds its place (exit 75)
PASS - the deferral names the working scout holder
PASS - a deferred spawn left no record
FAIL - a done scout releases its place for the next spawn: expected exit 0, got 75: deferred: project project admits 1 worker(s) at once on this machine (/tmp/fm-capacity-live.9JI0Y5/s1-scout-done/home/config/project-capacity) and 1 already hold a place (live-s); task task-e was not launched and its backlog item stays queued - dispatch it again once one of them records its ready PR or is cleaned up
FAIL - the next worker launched after the scout finished: output lacks [spawned task-e]: deferred: project project admits 1 worker(s) at once on this machine (/tmp/fm-capacity-live.9JI0Y5/s1-scout-done/home/config/project-capacity) and 1 already hold a place (live-s); task task-e was not launched and its backlog item stays queued - dispatch it again once one of them records its ready PR or is cleaned up
FAIL - the admitted spawn published no record

== S2: a no-mistakes ship keeps its place after done (guard)
PASS - a shipped-mode worker still holds its place after done (exit 75)
PASS - the no-mistakes holder is named

== S3: relaunching a finished scout reserves the place until the replacement reports
FAIL - a relaunch is deferred while another worker holds the only place: expected exit 75, got 0: spawned task-a harness=codex kind=scout window=firstmate:fm-task-a worktree=/tmp/fm-capacity-live.9JI0Y5/s3-relaunch/wt-task-a
PASS - a refused relaunch wrote no reservation
FAIL - no reservation during relaunch
PASS - the reservation left prior status history byte-identical
PASS - another spawn cannot take the place of the in-flight relaunch (exit 75)
PASS - bookkeeping alone does not expire the reservation (exit 75)
PASS - the relaunch succeeded (exit 0)
FAIL - a successful relaunch dropped its reservation
PASS - the running replacement still holds its place (exit 75)
FAIL - the replacement reporting done frees the place again: expected exit 0, got 75: deferred: project project admits 1 worker(s) at once on this machine (/tmp/fm-capacity-live.9JI0Y5/s3-relaunch/home/config/project-capacity) and 1 already hold a place (task-a); task task-b was not launched and its backlog item stays queued - dispatch it again once one of them records its ready PR or is cleaned up

== S4: an aborted relaunch releases its reservation
PASS - a relaunch refused before launch fails (exit 1)
PASS - a proven non-launch removed the reservation
FAIL - the place of an aborted relaunch is free for the next worker: expected exit 0, got 75: deferred: project project admits 1 worker(s) at once on this machine (/tmp/fm-capacity-live.9JI0Y5/s4-abort/home/config/project-capacity) and 1 already hold a place (task-a); task task-b was not launched and its backlog item stays queued - dispatch it again once one of them records its ready PR or is cleaned up
PASS - a malformed reservation holds a place instead of undercounting (exit 75)
PASS - an unparseable reservation holds a place too (exit 75)

== result: FAIL (8)
Evidence: Target vs base result
target: == result: PASS (23 assertions, 0 failures)
base 913bb7a: == result: FAIL (8) - e.g. 'a done scout releases its place for the next spawn: expected exit 0, got 75 ... 1 already hold a place (live-s)' and 'a successful relaunch dropped its reservation'

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 - 5 of 5 scenarios driven live against the product
Scenario Result Live Evidence
A scout records done and the next queued worker on the capped project is admitted instead of deferred ✅ pass live live-capacity-driver.sh S1 (transcript live-capacity-target.log): working scout -> exit 75 'already hold a place (live-s)' with no task record; after 'done' appended -> exit 0 'spawned task-e' and sta…
A no-mistakes ship keeps its place after done plus captain-held bookkeeping, so the next worker is still deferred ✅ pass live live-capacity-driver.sh S2: exit 75 with 'already hold a place (live-p)' for a ship mode=no-mistakes whose status is working/done/captain-held
Relaunching a completed scout reserves the freed place through the launch window, ignores bookkeeping, keeps holding while the replacement works, and releases when the replacement records done ✅ pass live live-capacity-driver.sh S3: relaunch deferred while another task holds the only place; in-flight relaunch writes state/task-a.capacity-reservation with prior status bytes unchanged; a concurrent spawn…
Adversarial: a relaunch refused before launch (proven non-launch) removes the reservation so the place is usable, while a malformed or unparseable reservation holds a place instead of undercounting ✅ pass live live-capacity-driver.sh S4: relaunch with an invalid backend exits non-zero, no reservation file remains, next spawn admitted (exit 0); a finished scout carrying 'gen=stale/status_offset=not-a-number'…
The repository's capacity admission behavior suite passes end-to-end against the real spawn script ✅ pass live bash tests/fm-project-capacity.test.sh -> 24 ok cases including 'only finished scouts and local-only ships release on done until working resumes', 'relaunch reservations hold unchanged status until…
  • bash tests/fm-project-capacity.test.sh (all 24 behavior cases ok: freeing on done, relaunch reservations, aborted relaunches, default-path opt-in)
  • bash ~/.no-mistakes/evidence/01M71CTZE55KNHYYVDNBA3Z6SH/live-capacity-driver.sh driving the real bin/fm-spawn.sh in a disposable home with a real git clone+origin (23/23 assertions pass)
  • Same driver against a git archive 913bb7a7b6 copy of the base commit as an independent regression oracle (8 assertions fail, confirming the scenarios are meaningful and fixed by the target commit)
  • Manual driving of deferred: exit-75 output, published state/&lt;id&gt;.meta records, state/&lt;id&gt;.status history bytes, and state/&lt;id&gt;.capacity-reservation files across each scenario
⚠️ **Document** - 1 info
  • ℹ️ docs/configuration.md:1894 - This change extended two full restatements of one contract: the operator section "Project capacity" now spells out occupancy, completion, reservation expiry, and resumed-work rules that bin/fm-project-capacity-lib.sh declares itself the single owner of, and the two copies must be kept in step by hand. They currently agree, and the operator section carries load-bearing guidance, so I left both intact rather than re-cut the section here. A follow-up could reduce the operator prose to the consequences a captain needs (a done scout or local-only ship frees its place, a relaunch holds it) and point at the lib header for the record format and expiry mechanism.
✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@kesslerio

Copy link
Copy Markdown
Contributor Author

@kunchenguid could you rerun Behavior portable serial 2 on head d9807273da2ffe8f1222395ba214014e78983f89, or the enclosing CI workflow if GitHub no longer permits that job retry?

The job was cancelled at the 30-minute limit without a test verdict; the other checks passed.
My contributor retry was refused with job 114558896654 cannot be rerun.
I’m keeping the cancellation inconclusive and preserving the code while waiting for a replacement verdict.

@kesslerio
kesslerio force-pushed the fm/project-capacity-done-frees-slot branch from d980727 to 6f6671d Compare October 31, 2026 03:30
@kesslerio kesslerio changed the title fix(bin): release project capacity when scouts and local-only ships finish fix: release capacity when scouts and local-only ships finish Oct 31, 2026
@greptile-apps

greptile-apps Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no new actionable issues were found.

Reviews (5) · Last reviewed commit: "no-mistakes(document): Fix stale fresh-s..." · Reviewed by Greptile

Comment thread bin/fm-project-capacity-lib.sh Resolved
Comment thread tests/fm-project-capacity.test.sh Resolved
Comment thread bin/fm-project-capacity-lib.sh Resolved
@kesslerio

Copy link
Copy Markdown
Contributor Author

Live evidence for the two capacity scenarios, driven against the real product in a disposable live lab home.

Setup

bin/fm-live-lab.sh up --harness claude on this exact pipeline ref (f59a29a4), which is the reviewed head:

tree: f59a29a46f3e721cd2051078fdb51144f67d974d
ok primary: claude pid 3081851 in /tmp/opencode/lab-7079/home
ok probe: the primary answered LABREADY-f93c934c9f89
ready: /tmp/opencode/lab-7079

A real home with a real Claude primary, a real git project at projects/capprobe, and a real declaration:

config/project-capacity:
capprobe 1

Every worker below was launched by bin/fm-spawn.sh itself; nothing was simulated and no fixture stood in for admission.

Scenario: "A finished scout or local-only ship releases capacity, while a no-mistakes or direct-PR ship remains counted until PR handoff." — PASS, live

A scout releases its place when it reports done.

Step Result
fm-spawn.sh cap-a … --scout rc=0, spawned cap-a … kind=scout
fm-spawn.sh cap-b … --scout rc=75 deferred — "admits 1 worker(s) … 1 already hold a place (cap-a)"
cap-a's own worker wrote done done [at=1793419004]: cap-a report written …
fm-spawn.sh cap-b … --scout again rc=0, spawned cap-b

The deferral named the specific holder and the item stayed queued; once the scout finished, the same command was admitted. That is the release the change is for.

A no-mistakes ship keeps its place after done. With the slot free, a --mode no-mistakes ship was spawned, then marked done without a PR handoff:

cap-ship   done [at=1793419102]: ship probe complete
fm-spawn.sh cap-c … --scout   →   rc=75 deferred
deferred: … 1 already hold a place (cap-ship) …

So the scout released and the ship did not, which is the distinction the change promises rather than a blanket release on every done.

Scenario: "A finished scout or local-only ship that is restarted reserves capacity again, including after fresh restart and relaunch." — PASS, live

cap-a was stopped through its own control plane and relaunched:

bin/fm-control.sh cap-a exit   →   stopped cap-a harness=claude endpoint=firstmate:fm-cap-a
fm-spawn.sh cap-a --relaunch   →   rc=0, spawned cap-a
cap-a status tail: working [at=1793419060]: spawn admitted
fm-spawn.sh cap-c … --scout    →   rc=75 deferred
deferred: … 1 already hold a place (cap-a) …

The replacement worker took the place back before the admission lock dropped, so the next spawn was deferred instead of slipping in beside it. This is exactly the hole the earlier round left open, and it is now closed against the real binary.

Fresh restart through the plain spawn path was also attempted first and refused with window firstmate:fm-cap-a already exists, because the previous endpoint was still alive — the correct refusal, not a capacity result. The relaunch path was used after stopping that endpoint, which is the supported order.

Not established

  • Only one project and one declaration were exercised; multi-project and multi-home admission were not re-proven here, they remain covered by the fixture suites.
  • The ship case was proven for no-mistakes only. direct-PR shares the same "counted until PR handoff" rule but was not driven separately.

The lab is torn down; nothing was pushed and no project was modified.

Comment thread bin/fm-spawn.sh Resolved
@kesslerio

Copy link
Copy Markdown
Contributor Author

Status note on 74d19c61, and why I have stopped iterating on it.

What is proven

The release behavior this change is for was driven live in a disposable lab home and posted above: a finished scout frees its place and the next spawn is admitted, a no-mistakes ship keeps its place after done until PR handoff, and a relaunched scout takes its place back so the next spawn defers. That part holds against the real binary.

What is not, and why I am not patching it again

The relaunch and fresh-restart path needs to reserve a place, then keep it only if a replacement actually starts. Four review rounds found four distinct ways that reservation outlives a failure:

  1. --relaunch skipped admission entirely, so a worker whose place had been taken could relaunch alongside its replacement.
  2. A fresh restart kept the stale done event, so the replacement held no place at all.
  3. Appending working happened before metadata publication and launch delivery, and neither spawn_abort_cleanup nor relaunch_rollback restored the completion state.
  4. Even after that fix: SPAWN_LAUNCH_SENT is set before the text is delivered, and fm_backend_tmux_window_inventory returns 2 for confirmed session or server absence while the new condition accepted only 0 — so a proven non-launch still retained the place.

Round 3 did not close round 2's finding, and round 4 opened a sibling. That is not a run of bad luck; it is one invariant with no single owner.

The actual root cause

A capacity or seat reservation has no uniform lifecycle. Each site acquires in its own way and hand-rolls its own unwind, and the unwind has to reason about a dozen distinct failure points — metadata publication, endpoint delivery, Enter delivery, tmux inventory states, rollback paths — each of which can be the one that fails.

The same shape produced the three rounds on #6238, where a seat reservation was counted in two independent places. Both PRs are rediscovering the same missing abstraction from opposite ends.

What I propose instead

Extract one reservation lifecycle helper with a strict contract:

  • acquire persists the claim and the state it displaced,
  • commit is the single point that proves a replacement started, and
  • rollback restores the displaced state, and is reachable from every failure exit including proven non-launch.

Then both this PR and #6238 sit on top of it, rather than each growing its own rollback logic. fm_backend_tmux_window_inventory's exit-2-means-absent semantics belong in that helper's "proven non-launch" predicate, not in each caller.

I am leaving the branch at 74d19c61, the head you last reviewed, with nothing unpublished behind it. Tell me whether you want that helper as its own change with these two rebased on it, or whether you would rather take the release behavior alone and drop the relaunch admission from this PR's scope.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thank you @kesslerio, and thanks for stopping to name the root cause instead of patching a fifth round. I read head 74d19c61 against main 095db3bc, along with your live lab transcripts.

What it does: with config/project-capacity declared, a scout or local-only ship that reports done frees its place until a later working. No-mistakes and direct-PR ships stay counted until PR handoff. Relaunches are now admitted against the same limit, and a restart records new work.

Contract-class (my own read): opt-in. All of it sits behind a config/project-capacity declaration, and an unconfigured home is unchanged. It does change the documented semantics of that opt-in surface ("a local-only ship or a scout holds its place until cleanup").

VISION.md, rule by rule: One captain: aligns (fewer stuck queues). Authority: aligns (only for captains who declared a cap). Scripts/judgment: aligns. Restart is a non-event: cannot tell yet, because a failed relaunch can keep a place (open Greptile P1 "Failed relaunch blocks queued work"). Delegation with a spine: aligns on the release behavior, which you drove live; the relaunch reservation is the open part. Vendor: aligns. Scope: this is the open question. Your proposal adds a shared reservation lifecycle helper that #6238 would also sit on.

Where it stands: the attestation binds this head and the quick checks pass. The open P1 is the failed-relaunch rollback you described. The red Full suite row is our label gate, not your code.

This is now waiting on Kun, not on you. Your question is a scope call: (a) a separate reservation-lifecycle helper with this PR and #6238 rebased on it, or (b) ship the release behavior alone. Note that dropping relaunch admission would reopen the earlier "relaunch exceeds the worker limit" finding. I've put both options to him. Nothing is needed from you until he answers.

@kesslerio
kesslerio force-pushed the fm/project-capacity-done-frees-slot branch from 74d19c6 to 63a30d2 Compare November 2, 2026 22:44
@kesslerio kesslerio changed the title fix: release capacity when scouts and local-only ships finish fix(bin): free project capacity when a finished worker reports done Nov 2, 2026
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thank you @kesslerio for the new round. Moving the relaunch hold into one capacity-reservation record with a single expiry rule (working or done past the recorded offset) is a lot tidier than the earlier status rewriting.

At head 63a30d26 against main 60f95dfa: it merges cleanly, the attestation binds this head with every step completed, the quick checks and Greptile pass, the failed-relaunch P1 thread is resolved, and the live table is 7/7. The red Full suite row is our label gate, not your code.

One small housekeeping note: your two replies on the bin/fm-spawn.sh thread came through as literal file paths (@/tmp/opencode/7079-reply.md, @/tmp/opencode/7079-resolve.md), so the text didn't post. If anything in them matters for review, please paste it in.

Contract-class: I've revised this to new-default, unless two pieces are gated. On 10-31 I read the PR as fully behind config/project-capacity. At this head, two pieces run in every home, with or without a capacity declaration:

  1. Every fresh scout or local-only ship spawn, and every relaunch of an unfinished one, now appends working: spawn admitted to the task's status log (bin/fm-spawn.sh, the new block before the meta publish).
  2. A relaunch on any backend other than Orca now takes the shared Treehouse project lock with fm_lock_try_acquire. If another spawn or cleanup is holding it, the relaunch fails with "another Treehouse slot allocation or return is in progress". On main, a relaunch never takes that lock.

Waiting on you, no rush, for one thing: either gate both behind a capacity declaration for the project, for example only when SPAWN_PROJECT_CAPACITY_ANY is set, which keeps this opt-in, or tell me they're meant for every home. If they are, they become part of the decision Kun is already looking at.

Still with Kun, not you: the scope question from 10-31, (a) a shared reservation-lifecycle helper with this PR and #6238 on top of it, or (b) the release behavior alone. Your reservation record is relevant to that choice, and I'll add it to what he sees.

VISION: One captain aligns. Authority aligns only if the default-path pieces are gated. Scripts own the mechanics aligns. Restart is a non-event aligns (the failed-relaunch hole is closed, and reservations are durable records). Delegation with a spine aligns (live 7/7). Vendor aligns. Scope is Kun's call.

@kesslerio
kesslerio force-pushed the fm/project-capacity-done-frees-slot branch from 63a30d2 to 7b822cd Compare November 4, 2026 07:00
@kesslerio kesslerio changed the title fix(bin): free project capacity when a finished worker reports done fix(bin): free a project capacity place when a worker reports done Nov 4, 2026
@kesslerio

Copy link
Copy Markdown
Contributor Author

@kunchenguid — answering the contract question with option (a) on 7b822cdd: both default-path pieces are now gated behind a capacity declaration.

What changed. bin/fm-spawn.sh runs the two pieces only when the home declares project capacity at all (SPAWN_PROJECT_CAPACITY_ANY): the working [at=…]: spawn admitted status line, and the shared Treehouse project lock on a relaunch. Fresh non-Orca spawns keep main's lock, and a home with no declaration now matches main on both paths. Declared homes keep both pieces, including the capacity-admission lock. tests/fm-project-capacity.test.sh proves both directions with a real spawn and a held project lock: an undeclared relaunch succeeds while the lock is held, a declared relaunch refuses on it with the existing message, and only a declared home records the admitted line. The suite passes (21/21), the coverage guard reports the partition intact, and lint is clean.

One deliberate exception, which the Document step recorded rather than changing: a relaunch of a finished scout or local-only ship still writes state/<id>.capacity-reservation on an undeclared home. That record is defensible because a capped same-origin clone on that home still counts the replacement, so the write stays ungated and the intent wording is about the two named pieces.

The two replies that came through as literal file paths. The substance, for the thread:

  • The failed-relaunch hole was real: after the new working append and the replacement record were published, a relaunch that died during launch delivery left done: finished followed by working [at=…]: spawn admitted, so a finished worker's released place stayed taken until a later done or cleanup, and the next spawn on that project deferred.
  • The fix rolled that back into a durable reservation instead of rewriting status: state/<id>.capacity-reservation (gen=, status_offset=) is written atomically when a finished scout or local-only ship is relaunched, the status log is left untouched, and the capacity reader treats a live reservation as the authority until the log records working or done after its offset. spawn_abort_cleanup removes the reservation only when a non-launch is proven — nothing sent, or the endpoint positively closed — while a failed send that leaves the endpoint open keeps the place, because the replacement may have started. Bookkeeping after a successful relaunch holds the place; a later done releases it. Tests cover the plain and done-then-captain-held tails for both kinds, staging and literal-send failures, and expiry.

Attestation. I re-raised through the gate: intent, rebase, review, test, document, lint, push, pr and ci all completed, so the attestation binds 7b822cdd with every step completed and nothing skipped. The Test step finished inside its budget this round. Greptile's threads are all resolved, and the only red check is Full suite, which is your full-ci label gate.

The scope question from 10-31 stays with Kun: a shared reservation-lifecycle helper with this PR and #6238 on top, or the release behavior alone. With the default path gated again, this PR reads as restore-class, so that choice is about structure rather than a new default.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thank you @kesslerio, this does exactly what I asked on 11-02. At 7b822cdd, the working: spawn admitted line and the relaunch's shared project lock both run only once the home declares project capacity (SPAWN_PROJECT_CAPACITY_ANY). An undeclared home relaunches the way main does, and your live table shows it: 10/10, including byte-identical status logs and no project lock in an undeclared home. The capacity reservation record is the one piece written everywhere, and it only matters to capacity counting. So I'm moving the contract-class back to opt-in.

The attestation binds this head with every step completed. The quick checks and Greptile pass, every thread is resolved, and it merges cleanly. The red Full suite row is our label gate, not your code.

This is now waiting on Kun, not on you. The 10-31 scope question is still his: (a) a shared reservation-lifecycle helper with this PR and #6238 on top of it, or (b) the release behavior on its own. I've added your reservation record and the new gating to what he sees. Nothing is needed from you until he answers.

VISION: One captain aligns. Authority aligns (opt-in behind a declared cap). Scripts own the mechanics aligns. Restart is a non-event aligns. Delegation with a spine aligns (live 10/10). Vendor aligns. Scope is Kun's call.

A finished ship or scout whose newest status event is done no longer uses
local resources, but fm_project_capacity_occupants kept counting it until a
pr= line was recorded or the record was cleaned up. A lane finished and
parked on landing, a captain decision, or an upstream wait could hold its
project's only place for days, quietly deferring every new spawn.

The occupant walk now skips a record whose newest status verb is done, the
same way it already skips a recorded PR handoff. A paused, blocked, or waiting
worker keeps its place because it can resume without a new spawn, and a
finished worker steered back into work counts again once its newest event is
no longer done. The deferral message and docs/configuration.md describe the
new release condition.

Fixes kunchenguid#6979 (project-capacity part).
A finished scout or local-only ship releases its place, so a relaunch no
longer necessarily replaces a worker that holds one. Capacity admission
now runs for relaunches too. The occupant count already excludes this
task's own record, so relaunching a live worker never blocks itself,
while a relaunch whose place was taken by another worker is deferred
like any other spawn.

Admission also resolved every task's project only after reading its
status log, so a capped spawn walked unrelated projects' history while
holding its own project lock. The project and its lock are now resolved
first and unrelated records are skipped before any log read.

The completion fixture used a bare `sed -i`, which stock macOS `sed`
rejects without a backup suffix, so those cases tested nothing there.
It now uses `sed -i.bak` and removes the backup.
A relaunch of a completed scout or local-only ship reserves a place again by
appending a working line before its record is republished and before launch
delivery. When the launch was then refused, neither the abort path nor the
control-plane rollback restored the earlier completion, so the record kept
holding the place although nothing had replaced the worker: queued work on that
project deferred until a later done event or a cleanup.

Record the status file's exact prior size when the reservation replaces a done
line, and put those bytes back in spawn_abort_cleanup when the abort proves no
launch reached the endpoint (SPAWN_LAUNCH_SENT=0). The rollback runs under the
per-id spawn lock and only while this spawn's own line is still the file's
tail, so a concurrent retry of the same id keeps what it wrote. Restoring the
prior bytes rather than appending a synthetic done line avoids closing the
task's open decisions and avoids reporting a second completion.

Regression: tests/fm-project-capacity.test.sh covers an aborted relaunch of a
finished scout and of a finished local-only ship, and fails on the previous
code with the reservation still in the status log.
… declaration

Answering the maintainer's 11-03 contract question with option (a): the two
pieces this change added on the default path now run only once the home
declares project capacity at all. Without a declaration the status log gains no
`working [at=...]: spawn admitted` line and a relaunch does not take the shared
Treehouse project lock, so an undeclared home behaves exactly as main. Fresh
non-Orca spawns keep main's lock, and declared homes keep both pieces.

tests/fm-project-capacity.test.sh proves both directions with a real spawn and a
held project lock: undeclared relaunch succeeds while the lock is held, declared
relaunch refuses on it, and only a declared home records the admitted line.
@kesslerio
kesslerio force-pushed the fm/project-capacity-done-frees-slot branch from 7b822cd to 767984e Compare November 11, 2026 00:52
@kesslerio kesslerio changed the title fix(bin): free a project capacity place when a worker reports done fix(bin): release a project capacity place when a worker finishes and admit relaunches Nov 11, 2026
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thanks @kesslerio for the rebase. I compared head 767984e0 with 7b822cdd. The code is the same. The only differences are comment and header wording that follow main's updated comments. Both default-path pieces still run only when the home declares project capacity (SPAWN_PROJECT_CAPACITY_ANY). The attestation binds this head with no skipped steps, and live is 5/5. Greptile gives 5/5, every thread is resolved, and it merges cleanly with main 1d43f9cb. Contract-class: opt-in, unchanged.

This is still waiting on Kun, not on you. The scope question from 10-31 is his call: a shared reservation-lifecycle helper with this PR and #6238 on top of it, or the release behaviour on its own. You don't need to do anything until he answers.

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