Skip to content

feat(bin): opt-in machine handoff of one home through an S3 lease - #34

Merged
alandomio merged 3 commits into
mainfrom
fm/fm-handoff-s3
Sep 22, 2026
Merged

alandomio merged 3 commits into
mainfrom
fm/fm-handoff-s3

Conversation

@alandomio

Copy link
Copy Markdown
Owner

Intent

Build an OPT-IN firstmate feature: one firstmate home that moves between the captain's laptop and an EC2 machine, sharing data/ through an S3 bucket, never active in two places at once. Spec is the captain's decision record (decisions 8, 9, 10, 15, 16): sync only data/ (never state/, projects/, config/); only one firstmate active at a time via an S3 handover signal; a machine that finds the other's signal starts read-only; handover by explicit "consegna" on the laptop and automatic at EC2 boot/shutdown, no continuous sync; in-flight tasks do not move - they reach a stop point or explicitly stay on the machine and the backlog says where each stays; forced takeover only on the captain's explicit command, working from the last upload and recording the forced takeover and the upload it started from; the returning machine starts read-only, shows its unuploaded changes and the captain decides to merge or discard, never silent overwrite; periodic upload about every 15 minutes and after backlog updates without releasing the signal; return flow driven by the laptop on the captain's yes: consegna on EC2 via SSM, download data/, take the signal, stop EC2, listing EC2 in-flight tasks first; EC2 does consegna and shuts down after 2 hours idle.
Requirements: 1) off by default, enabled only by a config/ file (config/handoff-s3 with bucket and machine name), documented in docs/configuration.md; without the file nothing changes. 2) sync only data/ with aws s3 sync semantics safe for deletions; bucket is versioned. 3) lease S3 object (machine, timestamp) plus last-upload marker; integrated with bin/fm-session-start.sh lock stage and the per-home session lock: if another machine holds the lease the session must start in the EXISTING lock-refused read-only mode (no second read-only mode) and print the last upload time and exact force-takeover command. 4) one script bin/fm-handoff.sh with consegna (refuse in-flight tasks or require --leave and record in the backlog which machine each task stays on; upload; release lease), prendi (download, take lease; refuse if held elsewhere unless --force), --force records a note of the forced takeover and its starting upload in data/, returning machine shows local unuploaded data/ changes and the captain decides. 5) periodic backup every ~15 min and after backlog updates without releasing the lease, via a mechanism that fits supervision. 6) return flow riprendi via SSM (instance id from config), captain-authorized per occasion, listing EC2 in-flight tasks first. 7) idle probe (no active workers, no pending wakes/messages for N minutes) for the EC2 idle-shutdown timer; EC2 side (Terraform/Ansible in aws-goplanner) calls bin/fm-handoff.sh consegna and the idle probe - keep those names or document the interface. Tests colocated with a stubbed aws CLI / local-directory fake S3, no real AWS calls; shellcheck clean; PR against main of alandomio/firstmate.
Implementation decisions: the lease read is the one bounded (FM_HANDOFF_TIMEOUT) network call on the session-start blocking path, only when enabled, because mutation authority cannot be deferred past the lock; the gate records its verdict in state/.handoff-refused and bin/fm-lock.sh refuses locally (no network) while that file exists and config/handoff-s3 is present, so every lock claimant including the Stop auto-arm stale-lock recovery lands in the existing read-only mode. Offline: allowed only for the machine whose own record says it took the lease and never released it (laptop offline work), refused otherwise; an unusable config refuses. A free lease also refuses until prendi, because local data may be stale. prendi takes the lease before downloading; downloads go through a staging dir and always save the previous data/ under state/handoff-backups/; unuploaded local changes (vs a manifest recorded at the last sync) block prendi unless --replace-local; an empty bucket is seeded from the local machine. Handover events are logged in data/handoff-log.md; consegna --leave annotates backlog item bodies through tasks-axi when available. The periodic backup is a registered watcher check (state/handoff-backup.check.sh via fm-check-register.sh, like fm-tool-update-check) rather than an OS timer: runs inside supervision on every platform and turns a lost lease into a wake; accepted tradeoff: it runs only while a watcher runs, documented, with on-demand backup. EC2 interface: bin/fm-handoff.sh prendi at boot (refusal expected when laptop holds the helm), bin/fm-handoff.sh idle --minutes 120 then consegna. Commit messages carry no agent co-author (repo rule).

What Changed

  • Adds bin/fm-handoff.sh, an opt-in tool that moves one home's data/ (and nothing else) between machines through a versioned S3 bucket. Only one machine can hold the helm at a time, tracked by a lease object plus a last-upload marker. It is enabled only when config/handoff-s3 exists (off by default). Subcommands:
    • prendi [--force] [--replace-local] takes the lease first, then downloads through a staging dir. It backs up the old data/ under state/handoff-backups/ and refuses to replace unuploaded local changes unless --replace-local is passed. --force records the forced takeover and the upload it started from in data/handoff-log.md.
    • consegna [--leave] refuses while tasks are in flight unless --leave is passed; with --leave it notes on each backlog item that the task stays on this machine. It then uploads and releases the lease.
    • backup and check handle periodic backup: arm registers a watcher check that uploads about every 15 minutes or after a backlog change, without releasing the lease, and turns a lost lease into a wake.
    • status, diff and inflight report the lease, the last upload and local state. idle --minutes N is the EC2 idle probe. riprendi is the laptop-driven return: consegna on EC2 over SSM, then prendi here, then stop the instance.
  • Integrates the lease with the session lock. At session start the lock stage runs fm-handoff.sh gate, a bounded (FM_HANDOFF_TIMEOUT) lease read, and records a refusal in state/.handoff-refused. While that file and config/handoff-s3 both exist, bin/fm-lock.sh refuses locally with no network call, so the session lands in the existing lock-refused read-only mode and prints the holder, the last upload and the commands to take over. Multi-line lock diagnostics are now prefixed line by line in the read-only banner. When the bucket can't be read (offline), the session is allowed only if this machine's own record says it took the lease and never released it.
  • Documents the feature in docs/configuration.md ("Machine handoff"), docs/scripts.md and AGENTS.md. Adds tests/fm-handoff.test.sh, which uses a stubbed aws CLI backed by a local-directory fake S3, and registers it in the session-bootstrap family in bin/fm-test-run.sh.

🤖 Generated with Claude Code

Risk Assessment

⚠️ Medium: The fix round correctly implements every prescribed remedy: consegna and backup now require status=held, the gate fails closed, the invalid-config check reports through a subshell, the idle probe ignores secondmates, a forced seed is logged, riprendi checks local changes before calling EC2, and the check budget covers the small calls; each has an executable test, but the feature as a whole is a large new lease/sync subsystem guarding against silent data overwrite, so it still deserves careful merge attention.

Testing

I ran the targeted handoff test suite (tests/fm-handoff.test.sh), and all 13 end-to-end cases pass with a stubbed aws CLI. They include the round-1 fixes: unfinished-prendi refusal, the fail-closed session gate, the config-invalid wake, the forced-seed record, secondmate-only idle, and riprendi checking local changes before anything happens on EC2. I also captured a CLI transcript of a full laptop to EC2 to laptop handover across two homes. It shows the read-only refusal with the last upload and the force command, the in-flight --leave recording, periodic backup without releasing the lease, the idle probe, riprendi over SSM with backup of local changes and the EC2 stop, and the handoff log. No failures and no leftover artifacts in the worktree. This is a CLI change with no rendered UI, so a text transcript is the right evidence.

Evidence: End-to-end laptop/EC2 handoff CLI transcript (fake S3, stubbed aws)

Source: End-to-end laptop/EC2 handoff CLI transcript (fake S3, stubbed aws)

# config/handoff-s3 on laptop:
bucket=fm-test-bucket
machine=laptop
ec2_instance_id=i-0demo
ec2_machine=ec2
ec2_home=/tmp/fm-handoff.gBqUaI/ec2
ec2_user=firstmate

$ [laptop] bin/fm-handoff.sh prendi
seeded the empty bucket from this machine (upload 20260919T130851Z-laptop-422bf3).
this machine (laptop) now holds the helm. Rerun bin/fm-session-start.sh to take it in this session.
(exit 0)

$ [laptop] bin/fm-handoff.sh gate
HANDOFF: this machine (laptop) holds the helm since 2026-09-19T13:08:50Z.
(exit 0)

$ [ec2] bin/fm-handoff.sh gate
HANDOFF: the helm is on machine laptop (lease taken 2026-09-19T13:08:50Z) - operate read-only.
HANDOFF: last upload of data/: 2026-09-19T13:08:51Z by laptop (seed, upload 20260919T130851Z-laptop-422bf3).
HANDOFF: to force the takeover without a handover (captain's explicit word only): bin/fm-handoff.sh prendi --force
HANDOFF: after taking the helm, rerun bin/fm-session-start.sh.
(exit 1)

$ [ec2] bin/fm-lock.sh
error: this machine does not hold the machine-handoff lease; operate read-only until resolved
HANDOFF: the helm is on machine laptop (lease taken 2026-09-19T13:08:50Z) - operate read-only.
HANDOFF: last upload of data/: 2026-09-19T13:08:51Z by laptop (seed, upload 20260919T130851Z-laptop-422bf3).
HANDOFF: to force the takeover without a handover (captain's explicit word only): bin/fm-handoff.sh prendi --force
HANDOFF: after taking the helm, rerun bin/fm-session-start.sh.
(exit 1)

$ [laptop] bin/fm-handoff.sh consegna
in-flight tasks on this machine (laptop):
  t1 (ship, proj)
refused: bring them to a stop point first, or rerun with --leave to hand over while they stay on laptop.
(exit 1)

$ [laptop] bin/fm-handoff.sh consegna --leave
in-flight tasks on this machine (laptop):
  t1 (ship, proj)
note: t1 is not a backlog item this script could annotate; recorded in data/handoff-log.md only.
handed over: data/ uploaded (upload 20260919T130851Z-laptop-78424f) and the lease released. This machine is now read-only; a running firstmate session here must stop mutating.
(exit 0)

$ [ec2] bin/fm-handoff.sh prendi
downloaded data/ from upload 2026-09-19T13:08:51Z by laptop (consegna, upload 20260919T130851Z-laptop-78424f).
the previous local data/ is saved at /tmp/fm-handoff.gBqUaI/ec2/state/handoff-backups/20260919T130852Z.
this machine (ec2) now holds the helm. Rerun bin/fm-session-start.sh to take it in this session.
(exit 0)

$ [laptop] bin/fm-handoff.sh gate
HANDOFF: the helm is on machine ec2 (lease taken 2026-09-19T13:08:52Z) - operate read-only.
HANDOFF: last upload of data/: 2026-09-19T13:08:52Z by ec2 (prendi, upload 20260919T130852Z-ec2-632480).
HANDOFF: to take the helm back cleanly (captain's explicit word only): bin/fm-handoff.sh riprendi
HANDOFF: to force the takeover without a handover (captain's explicit word only): bin/fm-handoff.sh prendi --force
HANDOFF: after taking the helm, rerun bin/fm-session-start.sh.
(exit 1)

$ [ec2] bin/fm-handoff.sh check
(exit 0)

$ cat s3://fm-test-bucket/firstmate/data/backlog.md
- item A
- ec2 edit

$ [ec2] bin/fm-handoff.sh idle --minutes 120
busy: activity in the last 120 minute(s) (/tmp/fm-handoff.gBqUaI/ec2/data)
(exit 1)

$ [laptop] bin/fm-handoff.sh riprendi
in-flight tasks on ec2:
  none
refused: this machine has local data/ changes that were never uploaded:
  modified: backlog.md
Nothing changed on EC2. Decide with the captain: bin/fm-handoff.sh diff compares them; bin/fm-handoff.sh riprendi --replace-local saves this copy under state/handoff-backups/ before taking the helm.
(exit 1)

$ [laptop] bin/fm-handoff.sh riprendi --replace-local
in-flight tasks on ec2:
  none
  EC2: handed over: data/ uploaded (upload 20260919T130853Z-ec2-a201eb) and the lease released. This machine is now read-only; a running firstmate session here must stop mutating.
downloaded data/ from upload 2026-09-19T13:08:53Z by ec2 (consegna, upload 20260919T130853Z-ec2-a201eb).
the previous local data/ is saved at /tmp/fm-handoff.gBqUaI/laptop/state/handoff-backups/20260919T130853Z.
this machine (laptop) now holds the helm. Rerun bin/fm-session-start.sh to take it in this session.
stopping the EC2 instance i-0demo.
(exit 0)

$ cat s3://.../lease
fm-handoff-lease-v1
machine=laptop
nonce=07f1fc790d0d804e
taken_at=2026-09-19T13:08:53Z
forced_from=

$ cat laptop data/handoff-log.md
# Machine handoff log

Written by bin/fm-handoff.sh; one line per handoff event.

- 2026-09-19T13:08:51Z laptop took the helm, seeding the empty bucket from its data/.
- 2026-09-19T13:08:51Z laptop handed over with task(s) left in flight on it: t1
- 2026-09-19T13:08:52Z ec2 took the helm, starting from upload 2026-09-19T13:08:51Z by laptop (consegna, upload 20260919T130851Z-laptop-78424f).
- 2026-09-19T13:08:53Z ec2 handed over the helm (no task in flight).
- 2026-09-19T13:08:53Z laptop took the helm, starting from upload 2026-09-19T13:08:53Z by ec2 (consegna, upload 20260919T130853Z-ec2-a201eb).
- 2026-09-19T13:08:53Z laptop set aside its unuploaded local data/ changes in /tmp/fm-handoff.gBqUaI/laptop/state/handoff-backups/20260919T130853Z for merging.

$ ls laptop state/handoff-backups
20260919T130853Z

$ ec2 stop-instances calls
--instance-ids i-0demo

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 7 issues found → auto-fixed ✅
  • 🚨 bin/fm-handoff.sh:766 - consegna and backup only check that the lease reads as ours, which compares machine and nonce. They never check that state/.handoff-held has status=held, so a home where prendi claimed the lease but its download failed (status=claimed, data/ still stale) can run aws s3 sync --delete of that stale data/ over the bucket's latest upload. A concrete path: the laptop runs consegna. EC2 boots and runs prendi, which writes the lease, but the download times out after FM_HANDOFF_SYNC_TIMEOUT, so status stays claimed and data/ is still EC2's copy from its last stint. Two hours later the EC2 idle timer finds the home idle (no tasks, data/ unchanged) and runs consegna. The lease reads ours, so upload consegna replaces the laptop's latest data/ in the bucket with EC2's stale copy. When the laptop next runs prendi, its data/ matches its manifest, so it downloads the stale copy with no warning. That is exactly the silent overwrite the intent forbids, and it can only be recovered by hand from S3 object versions. Fix: in action_consegna and action_backup, require held_field status = held before uploading. For a claimed home, consegna should release the lease without uploading, or refuse and point to prendi.
  • ⚠️ bin/fm-session-start.sh:632 - The lock stage relies on fm-handoff.sh gate having written state/.handoff-refused before it exits non-zero, but some failures exit before any verdict is written. The top-level positive_int checks call die_usage (exit 2) before action_gate runs, for example when FM_HANDOFF_TIMEOUT=0 or a non-numeric FM_HANDOFF_BACKUP_INTERVAL is set in the environment. A failed write_refused in the final branch also returns 1 with no file. In those cases session-start throws the gate output away (it is only printed on &&), and fm-lock.sh finds no refusal file and grants the lock, so the lease is never verified. That breaks the stated rule that an unusable setup refuses. Fix: when the gate exits non-zero and no refusal file exists, session-start should write one from the gate's output. Alternatively, gate can write a 'verdict pending' refusal first and clear it only on an allowed verdict, with the env-var validation moved after that point.
  • ⚠️ bin/fm-handoff.sh:836 - In action_check, load_config 2>/dev/null || report_once ... can never reach its report_once. load_config reports errors through die, which calls exit 1 in the current shell rather than returning. With an invalid config/handoff-s3 the watcher check exits silently: the watcher ignores exit status, reads only stdout, and stderr is sent to /dev/null. So the promised 'config/handoff-s3 is invalid' wake never fires and backups stop without any notice. Fix: validate in a subshell first, e.g. (load_config) >/dev/null 2>&1 || { report_once ...; return 0; }; load_config, as action_gate already does.
  • ⚠️ bin/fm-handoff.sh:880 - idle uses fm_supervision_status, which counts every state/*.meta, persistent kind=secondmate records included. inflight_ids, which consegna and inflight use, excludes secondmates. As a result, an EC2 home with any registered secondmate always reports 'busy: N task(s) in flight', so the idle-shutdown timer never runs consegna and the instance never stops. That contradicts the intent's 'EC2 does consegna and shuts down after 2 hours idle', and the idle check disagrees with what consegna itself treats as in flight. Whether a persistent secondmate should keep EC2 awake is a product decision, so this needs the author's call. The mechanical fix is to count in-flight tasks with inflight_ids in idle.
  • ⚠️ bin/fm-handoff.sh:689 - prendi --force records the forced takeover (FORCED takeover by ... from ...) only on the download path. When the lease is foreign but the bucket has no last-upload (for example, the other machine took the lease and its seed upload failed), the seed branch logs only '<machine> took the helm, seeding the empty bucket'. The forced takeover and the machine it was taken from are never recorded, although the intent requires 'recording the forced takeover'. Fix: when prior_holder is set, log the forced line in the seed branch as well.
  • ℹ️ bin/fm-handoff.sh:985 - riprendi runs consegna on EC2 over SSM before it checks for unuploaded local data/ changes. If the local prendi then refuses (local changes without --replace-local), EC2 has already released the lease and is still running, so neither machine holds the helm until the captain reruns. Recovery works (rerunning takes the lease-free path), but running the local local_changes check before the SSM consegna would avoid the half-done state.
  • ℹ️ bin/fm-handoff.sh:858 - check caps only the sync at FM_CHECK_TIMEOUT-10, but it also makes a lease read and a last-upload write, each up to FM_HANDOFF_TIMEOUT (15s). On a slow network the check can exceed the watcher's 30s bound and be killed after the sync but before the manifest is recorded. It also hashes every data/ file on each check interval before deciding whether a backup is due. Both are self-healing (the next check retries), but the budget arithmetic should include the two small calls.

🔧 Fix: Harden handoff lease checks, fail-closed gate, idle secondmates
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • bash tests/fm-handoff.test.sh: all 13 cases pass. They cover: disabled means no change and no aws calls; seeding an empty bucket; handing data/ over with consegna and prendi; a foreign lease keeping the other machine read-only; consegna refusing in-flight tasks unless --leave; recording forced takeovers, including onto an empty bucket; the backup check uploading and detecting a lost lease; offline and bad-config refusal; an unfinished prendi never uploading stale data/; the idle probe, where a home with only a secondmate counts as idle; riprendi over SSM, refusing local changes before touching EC2; session start landing in the existing read-only banner; session start failing closed when the gate exits without a verdict.
  • Manual end-to-end walkthrough with two homes (laptop and ec2) on the test's fake aws, fake runuser and fake ps. It ran prendi (seed), gate on both machines, fm-lock.sh refusal on ec2, consegna refused and then --leave, prendi on ec2, the laptop gate offering riprendi and prendi --force, check uploading a backlog change, idle --minutes 120, riprendi refused over local changes, then riprendi --replace-local. It then inspected the lease, data/handoff-log.md, state/handoff-backups and the recorded ec2 stop-instances call. Transcript saved to the evidence directory.
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

Alan Domio added 3 commits September 19, 2026 14:56
Add bin/fm-handoff.sh: when config/handoff-s3 exists, one firstmate home
moves between machines by syncing only data/ through a versioned S3
bucket under a single-holder lease. Session start reads the lease before
the lock, and fm-lock.sh refuses while this machine does not hold it, so
the session lands in the existing lock-refused read-only mode.

Commands: prendi (take the lease, download data/, --force records a
forced takeover), consegna (upload, release; refuses in-flight tasks
unless --leave, which records where each stays), riprendi (return flow
from EC2 via SSM, then stop the instance), a registered watcher backup
check, diff, inflight, and the idle probe for the EC2 idle timer.
Unuploaded local data/ changes are never overwritten silently.
@alandomio
alandomio merged commit 43d53eb into main Sep 22, 2026
24 of 25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant