Skip to content

Commit 0869131

Browse files
authored
fix: recover safe fleet sync drift (#111)
* fix(fleet-sync): self-heal safe detached drift, loudly flag stuck clones A pooled clone that drifts off its default branch was silently skipped forever by both the post-merge teardown sync and bootstrap fleet-sync, falling further behind on every merge with only an easy-to-miss skip line. - Auto-recover the one safe case: a clean, detached HEAD that is an ancestor of origin/<default> and whose <default> is free to check out is re-attached and fast-forwarded, reported as 'recovered:'. - Every other off-default state (dirty, non-default named branch, detached with unique commits, diverged) is left untouched and reported as a quantified 'STUCK: ... N commits behind ... - needs attention' warning instead of a quiet drift. Nothing is forced, stashed, or discarded. - Relay the new recovered:/STUCK: outcomes through bootstrap FLEET_SYNC lines; document both in AGENTS.md section 3. - Add tests/fm-fleet-sync.test.sh covering recover, every stuck variant, ordinary fast-forward, already-current, local-only/no-origin skips, the whole-fleet form, and the bootstrap relay. * no-mistakes(review): Guard detached recovery from diverged local defaults * no-mistakes(document): Sync fleet refresh docs * no-mistakes: apply CI fixes
1 parent 13f0d43 commit 0869131

9 files changed

Lines changed: 425 additions & 20 deletions

File tree

‎AGENTS.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,9 @@ Otherwise it prints one line per problem or capability fact; handle each:
124124
- `NEEDS_GH_AUTH` - ask the captain to run `! gh auth login` (interactive; you cannot run it for them).
125125
- `TANGLE: <remediation>` - the firstmate primary checkout (the repo root, `FM_ROOT`) is stranded on a feature branch instead of its default branch: a crewmate working firstmate-on-itself branched/committed in the primary instead of its own isolated worktree (section 8). The work is safe on that branch ref; restore the primary to its default branch with the printed `git -C <root> checkout <default>`, then re-validate that branch in a proper worktree. This is the only sanctioned firstmate-initiated git write to the primary, and it is a non-destructive branch switch that strands nothing.
126126
- `CREW_HARNESS_OVERRIDE: <name>` - record and use the override silently; surface a harness fact only if it actually blocks work or the captain asks.
127-
- `FLEET_SYNC: <repo>: skipped: <reason>` - bootstrap continued; investigate only if the dirty, diverged, or offline clone blocks work.
127+
- `FLEET_SYNC: <repo>: skipped: <reason>` - a benign one-off skip (offline, no origin, local-only); bootstrap continued, investigate only if it blocks work.
128+
- `FLEET_SYNC: <repo>: recovered: <detail>` - the clone had drifted onto a clean detached HEAD holding no unique commits and the sync self-healed it (re-attached the default branch and fast-forwarded); no action needed, it is reported only so the self-heal is visible.
129+
- `FLEET_SYNC: <repo>: STUCK: on <state>, N commits behind <base> - needs attention` - the clone is dirty, on a non-default branch, detached with unique commits, or diverged, so the sync left it untouched (never forcing or discarding); it will keep falling behind until you look. A loud STUCK, especially a growing N across bootstraps, means that clone needs hands-on attention; dispatch a crewmate or resolve it before it strands work.
128130
- `SECONDMATE_SYNC: secondmate <id>: skipped: <reason>` - the local-HEAD secondmate sync left a live secondmate home on its existing checkout because the home was dirty, diverged, unsafe, on the wrong branch, missing the primary target commit, or otherwise not fast-forwardable; bootstrap continued, but inspect the reason because the secondmate may be stale after a primary update.
129131
- `TASKS_AXI: available` - an optional capability fact, not a problem; record it silently and use section 10 for backlog mutations.
130132
It prints only after the `tasks-axi` compatibility probe passes for version 0.1.1 or newer; absence or incompatibility only falls back to hand-editing and never blocks work.
@@ -420,7 +422,8 @@ The script refuses if the worktree holds uncommitted changes or committed work t
420422
This recognizes the common squash-merge-then-delete-branch flow, where the branch's own commits live nowhere on a remote yet the change is fully in `main`; a merged-and-deleted branch now tears down cleanly instead of false-refusing.
421423
Genuinely unlanded work (no matching merged PR head and content not in the default branch) and dirty worktrees still refuse, and a gh lookup error falls back to the content check rather than silently allowing.
422424
Known benign case: after an external-PR task, a squash merge leaves the branch commits reachable only on the contributor's fork; add the fork as a remote and fetch (`git remote add fork <fork url> && git fetch fork`), then retry - never reach for `--force`.
423-
After a successful PR-based teardown, it also runs `bin/fm-fleet-sync.sh` for that project, best-effort, so the clone's local default catches up to the merge and the just-merged branch, now gone on the remote and free of its worktree, is pruned immediately.
425+
After a successful PR-based teardown, it also runs `bin/fm-fleet-sync.sh` for that project, best-effort, so safe clone states catch up to the merge, clean detached ancestor drift self-heals, and the just-merged branch, now gone on the remote and free of its worktree, is pruned immediately.
426+
Unsafe drift is reported as `STUCK:` and left untouched.
424427
Then update the backlog using the teardown reminder: run `tasks-axi done` when the compatible tool is available, otherwise move the task to Done in `data/backlog.md` manually with the full `https://...` PR URL or local merge note and date and keep Done to the 10 most recent.
425428
Re-evaluate the queue and dispatch only queued work whose blockers are gone and whose time/date gate, if any, has arrived.
426429

‎CONTRIBUTING.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ tests/fm-wake-daemon-lifecycle-e2e.test.sh # watcher + daemon lifecycle e2e: res
7070
tests/fm-composer-ghost.test.sh # dim-ghost stripping, ghost-only composer detection, and escape-free peek tests
7171
tests/fm-afk-inject-e2e.test.sh # private-socket end-to-end test of the afk injection path (partial-input deferral, swallowed-Enter retry)
7272
tests/fm-bootstrap.test.sh # bootstrap dependency and feature-probe tests
73+
tests/fm-fleet-sync.test.sh # project clone refresh: safe detached recovery, STUCK drift reports, benign skips, and bootstrap relay
7374
tests/fm-x-mode.test.sh # X-mode poll, inbox context round-trip, reply threading, dry-run preview, and .env-presence activation tests
7475
tests/fm-tangle-guard.test.sh # primary-checkout tangle detection and spawn/brief isolation tests
7576
tests/fm-spawn-batch.test.sh # batch dispatch and FM_HOME project-path scoping tests

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ This is.. a directory that turns any agent into your firstmate, and you the capt
4747
- **Optional secondmates** - opt in to persistent domain supervisors that run from isolated firstmate homes with their own `FM_HOME`, state, projects, and session lock, kept on the primary firstmate version by guarded local fast-forwards.
4848
- **Event-driven, zero-token supervision** - a bash watcher sleeps on the fleet and wakes the first mate only when something needs you.
4949
- **Optional X mode** - opt in with one local `.env` token so firstmate can answer your public `@myfirstmate` mentions, act on normal reversible mention requests through the same lifecycle as chat requests, and report public-safe outcomes without changing non-X behavior; dry-run preview records would-be replies locally before go-live.
50-
- **Guarded by construction** - the first mate is read-only over your projects outside clean default-branch refreshes, safe branch pruning, and approved `local-only` fast-forward merges; crewmates make every project change behind your merge approval.
50+
- **Guarded by construction** - the first mate is read-only over your projects outside guarded clone refreshes, safe branch pruning, and approved `local-only` fast-forward merges; crewmates make every project change behind your merge approval.
5151
- **Restart-proof** - all state lives on disk and in tmux; kill the session anytime and the next one reconciles and carries on.
5252

5353
Full detail on every feature lives in [docs/architecture.md](docs/architecture.md).

‎bin/fm-bootstrap.sh‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44
# Detect: prints one line per problem or capability fact and exits 0.
55
# Silent = all good.
66
# Lines: "MISSING: <tool> (install: <command>)", "NEEDS_GH_AUTH",
7-
# "CREW_HARNESS_OVERRIDE: <name>", "FLEET_SYNC: <repo>: skipped: <reason>",
7+
# "CREW_HARNESS_OVERRIDE: <name>",
8+
# "FLEET_SYNC: <repo>: skipped|recovered|STUCK: <detail>",
89
# "TASKS_AXI: available", "TANGLE: <remediation>",
910
# "SECONDMATE_SYNC: secondmate <id>: skipped: <reason>",
1011
# "NUDGE_SECONDMATES: <window-targets...>",
@@ -29,8 +30,9 @@
2930
# X mode is OPTIONAL and inert unless FM_HOME/.env has a non-empty
3031
# FMX_PAIRING_TOKEN. When opted in, bootstrap requires curl+jq, writes
3132
# the relay poll shim and 30s cadence config, and prints an FMX line.
32-
# Fleet sync fetches, fast-forwards, and prunes gone local branches;
33-
# it is bounded by FM_FLEET_SYNC_BOOTSTRAP_TIMEOUT, default 20s.
33+
# Fleet sync fetches, fast-forwards safe default-branch states, reports
34+
# recovered and STUCK clone drift, and prunes gone local branches; it is
35+
# bounded by FM_FLEET_SYNC_BOOTSTRAP_TIMEOUT, default 20s.
3436
# Set FM_FLEET_PRUNE=0 to skip branch pruning during that refresh.
3537
# fm-bootstrap.sh install <tool>...
3638
# Install the named tools (only ones the captain approved).
@@ -84,6 +86,8 @@ fleet_sync() {
8486
*': skipped: local-only project') ;;
8587
*': skipped: no origin remote') ;;
8688
*': skipped:'*) echo "FLEET_SYNC: $line" ;;
89+
*': STUCK:'*) echo "FLEET_SYNC: $line" ;;
90+
*': recovered:'*) echo "FLEET_SYNC: $line" ;;
8791
esac
8892
done < "$tmp"
8993
rm -f "$tmp"

‎bin/fm-fleet-sync.sh‎

Lines changed: 96 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,16 @@
33
# origin/<default> when safe, and prune local branches whose upstream tracking
44
# branch is gone (the remote branch was deleted, i.e. its PR merged) and that no
55
# worktree still needs.
6-
# Skips local-only/no-origin projects, dirty clones, non-default checkouts,
7-
# diverged branches, and fetch/fast-forward failures without forcing or stashing.
6+
# Self-heals the one unambiguously safe drift: a clean, detached HEAD that holds
7+
# no unique commits (it is an ancestor of origin/<default>) and whose <default>
8+
# branch is free to check out is re-attached and then fast-forwarded ("recovered:").
9+
# Every other off-default state - a non-default named branch, a detached HEAD with
10+
# unique commits, a dirty tree, or a diverged default - may hold real work, so it
11+
# is left untouched and reported as a quantified, loud "STUCK: ... N commits behind
12+
# ... - needs attention" warning rather than a quiet drift. Nothing is ever forced,
13+
# stashed, or discarded.
14+
# Still skips (benignly) local-only/no-origin projects, missing remotes/branches,
15+
# and fetch failures.
816
# Pruning never deletes the checked-out branch or a branch that still has a
917
# worktree, so it cannot discard unlanded work; set FM_FLEET_PRUNE=0 to disable it.
1018
# Usage: fm-fleet-sync.sh [<project-dir>]
@@ -88,6 +96,51 @@ prune_gone_branches() {
8896
--format='%(refname:short) %(upstream:track)' refs/heads 2>/dev/null)
8997
}
9098

99+
# True when some worktree of $PROJ has $DEFAULT checked out (so we cannot attach
100+
# to it here). The current worktree is detached when this is consulted, so any
101+
# match is necessarily another worktree.
102+
default_checked_out_elsewhere() {
103+
git -C "$PROJ" worktree list --porcelain 2>/dev/null \
104+
| sed -n 's#^branch refs/heads/##p' \
105+
| grep -Fxq -- "$DEFAULT"
106+
}
107+
108+
local_default_safe_for_recovery() {
109+
! git -C "$PROJ" rev-parse --verify --quiet "$DEFAULT^{commit}" >/dev/null \
110+
|| git -C "$PROJ" merge-base --is-ancestor "$DEFAULT" "$BASE" 2>/dev/null
111+
}
112+
113+
# Human-readable name for the unsafe state the clone is in, used in the STUCK
114+
# warning. Reads $cur (current branch, empty when detached), $dirty, and the
115+
# HEAD-vs-$BASE ancestry to pick the most informative description.
116+
stuck_state() {
117+
local s
118+
if [ -n "$cur" ]; then
119+
s="branch $cur"
120+
elif [ "$dirty" = yes ]; then
121+
s="detached HEAD"
122+
elif ! git -C "$PROJ" merge-base --is-ancestor HEAD "$BASE" 2>/dev/null; then
123+
s="detached HEAD with unique commits"
124+
elif default_checked_out_elsewhere; then
125+
s="detached HEAD ($DEFAULT checked out in another worktree)"
126+
elif ! local_default_safe_for_recovery; then
127+
s="detached HEAD (local $DEFAULT diverged from $BASE)"
128+
else
129+
s="detached HEAD"
130+
fi
131+
[ "$dirty" = no ] || s="$s with uncommitted changes"
132+
printf '%s\n' "$s"
133+
}
134+
135+
# Loud, quantified report for a clone we deliberately leave untouched. Includes
136+
# how far behind origin/<default> it is, so a chronically-stuck clone is visibly
137+
# distinct from a benign one-off skip.
138+
report_stuck() {
139+
local state=$1 behind
140+
behind=$(git -C "$PROJ" rev-list --count "HEAD..$BASE" 2>/dev/null) || behind="?"
141+
echo "$label: STUCK: on $state, $behind commits behind $BASE - needs attention"
142+
}
143+
91144
sync_project() {
92145
PROJ=$1
93146
label=$(project_label)
@@ -133,15 +186,39 @@ sync_project() {
133186
fi
134187

135188
cur=$(git -C "$PROJ" symbolic-ref --short HEAD 2>/dev/null || echo "")
189+
dirty=no
190+
[ -z "$(git -C "$PROJ" status --porcelain 2>/dev/null | head -1)" ] || dirty=yes
191+
recovered=no
192+
136193
if [ "$cur" != "$DEFAULT" ]; then
137-
[ -n "$cur" ] || cur="detached HEAD"
138-
echo "$label: skipped: on $cur, expected $DEFAULT"
139-
return 0
140-
fi
141-
if [ -n "$(git -C "$PROJ" status --porcelain 2>/dev/null | head -1)" ]; then
142-
echo "$label: skipped: dirty working tree"
194+
# Off the default branch. Auto-recover only the one unambiguously safe drift:
195+
# a clean, detached HEAD that holds no unique commits (it is an ancestor of
196+
# origin/<default>) and whose <default> branch is free to check out here.
197+
# Re-attaching to an already-published commit strands nothing, and the
198+
# fast-forward path below then catches the clone up. Anything else - a
199+
# non-default named branch, a detached HEAD with unique commits, a dirty tree,
200+
# or <default> already checked out elsewhere - may hold real work, so it is
201+
# reported loudly and left untouched.
202+
if [ -z "$cur" ] && [ "$dirty" = no ] \
203+
&& git -C "$PROJ" merge-base --is-ancestor HEAD "$BASE" 2>/dev/null \
204+
&& ! default_checked_out_elsewhere \
205+
&& local_default_safe_for_recovery; then
206+
if ! git -C "$PROJ" checkout --quiet "$DEFAULT" 2>/dev/null; then
207+
report_stuck "$(stuck_state)"
208+
return 0
209+
fi
210+
recovered=yes
211+
cur=$DEFAULT
212+
else
213+
report_stuck "$(stuck_state)"
214+
return 0
215+
fi
216+
elif [ "$dirty" = yes ]; then
217+
# On the default branch but with uncommitted changes we must not disturb.
218+
report_stuck "$(stuck_state)"
143219
return 0
144220
fi
221+
145222
if ! git -C "$PROJ" rev-parse --verify --quiet "$DEFAULT^{commit}" >/dev/null; then
146223
echo "$label: skipped: local $DEFAULT does not exist"
147224
return 0
@@ -156,11 +233,15 @@ sync_project() {
156233
return 0
157234
}
158235
if [ "$local_rev" = "$remote_rev" ]; then
159-
echo "$label: already current"
236+
if [ "$recovered" = yes ]; then
237+
echo "$label: recovered: re-attached $DEFAULT (already current)"
238+
else
239+
echo "$label: already current"
240+
fi
160241
return 0
161242
fi
162243
if ! git -C "$PROJ" merge-base --is-ancestor "$DEFAULT" "$BASE"; then
163-
echo "$label: skipped: local $DEFAULT has diverged from $BASE"
244+
report_stuck "diverged $DEFAULT"
164245
return 0
165246
fi
166247

@@ -180,7 +261,11 @@ sync_project() {
180261
echo "$label: skipped: fast-forward completed but cannot read local $DEFAULT"
181262
return 0
182263
}
183-
echo "$label: synced $before..$after"
264+
if [ "$recovered" = yes ]; then
265+
echo "$label: recovered: re-attached $DEFAULT, synced $before..$after"
266+
else
267+
echo "$label: synced $before..$after"
268+
fi
184269
return 0
185270
}
186271

‎docs/architecture.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,11 @@ The full ownership rule - what is project-intrinsic versus fleet-private, and ho
106106

107107
## Local clones stay fresh
108108

109-
Bootstrap and PR-based teardown refresh remote-backed project clones with clean default-branch fast-forwards when the clone is on the default branch and has no local work, and prune local branches whose remote is gone and that no worktree still needs.
109+
Bootstrap and PR-based teardown refresh remote-backed project clones when the clone is safe to move.
110+
Clean default-branch clones fast-forward to `origin/<default>`, and a clean detached HEAD that holds no unique commits is re-attached to the default branch before the same fast-forward path runs.
111+
Dirty clones, non-default branches, detached HEADs with unique commits, diverged defaults, and default branches checked out in another worktree are reported as `STUCK:` with their behind count and left untouched.
112+
Local-only projects, clones without an origin remote, and fetch failures remain benign skips.
113+
The refresh also prunes local branches whose remote is gone and that no worktree still needs.
110114

111115
## Self-updates stay safe
112116

‎docs/configuration.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ On first launch the first mate detects what its required toolchain is missing or
4949
When X mode is opted in, bootstrap also requires `curl` and `jq` before arming the relay poll shim.
5050
If compatible `tasks-axi` is already on `PATH`, bootstrap records it as an optional capability fact and firstmate uses its verbs for routine backlog mutations; when it is absent or incompatible, firstmate keeps hand-editing `data/backlog.md` exactly as before.
5151
Bootstrap also reports a `TANGLE:` line when `FM_ROOT` is on a named non-default branch; follow the printed checkout remediation rather than treating it as an installable tool problem.
52+
Bootstrap also runs a best-effort project clone refresh through `fm-fleet-sync.sh`.
53+
It emits `FLEET_SYNC:` for skipped refreshes that may matter, recovered self-heals, and `STUCK:` alarms; local-only and no-origin skips stay silent.
5254
Bootstrap also runs the guarded local secondmate sync for recorded live secondmate homes.
5355
It emits `SECONDMATE_SYNC:` only when a home was skipped for an actionable reason, and `NUDGE_SECONDMATES:` only when a running home advanced and its instruction surface changed.
5456

‎docs/scripts.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ Each file also starts with a short header comment.
55

66
| Script | Description |
77
| ------------------------ | ------------------------------------------------------------------------------------------------------------------- |
8-
| `fm-bootstrap.sh` | Detect required toolchain and version problems, optional capability facts, and primary-checkout `TANGLE:` problems; locally sync live secondmate homes; set up opt-in X mode; refresh clones best-effort; install tools only after consent |
9-
| `fm-fleet-sync.sh` | Fetch clones, clean-fast-forward their checked-out default branches, and safely prune branches whose remote is gone |
8+
| `fm-bootstrap.sh` | Detect required toolchain and version problems, optional capability facts, primary-checkout `TANGLE:` problems, and actionable clone refresh outcomes; refresh project clones best-effort; locally sync live secondmate homes; set up opt-in X mode; install tools only after consent |
9+
| `fm-fleet-sync.sh` | Fetch clones, fast-forward safe default-branch states, self-heal clean detached ancestor drift, report unsafe drift as `STUCK:`, and safely prune branches whose remote is gone |
1010
| `fm-update.sh` | Self-update the running firstmate repo and registered secondmate homes with fast-forward-only pulls from origin |
1111
| `fm-backlog-handoff.sh` | Move already-judged in-scope queued backlog items from the main home into a seeded secondmate home |
1212
| `fm-brief.sh` | Scaffold a ship brief with a worktree-isolation assertion, a report-only scout brief with `--scout`, or a secondmate charter with `--secondmate` |

0 commit comments

Comments
 (0)