Repository navigation
feat(bin): opt-in machine handoff of one home through an S3 lease - #34
Merged
Merged
Conversation
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.
…riprendi pre-check
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 consegnaand 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 prendiat boot (refusal expected when laptop holds the helm),bin/fm-handoff.sh idle --minutes 120thenconsegna. Commit messages carry no agent co-author (repo rule).What Changed
bin/fm-handoff.sh, an opt-in tool that moves one home'sdata/(and nothing else) between machines through a versioned S3 bucket. Only one machine can hold the helm at a time, tracked by aleaseobject plus alast-uploadmarker. It is enabled only whenconfig/handoff-s3exists (off by default). Subcommands:prendi [--force] [--replace-local]takes the lease first, then downloads through a staging dir. It backs up the olddata/understate/handoff-backups/and refuses to replace unuploaded local changes unless--replace-localis passed.--forcerecords the forced takeover and the upload it started from indata/handoff-log.md.consegna [--leave]refuses while tasks are in flight unless--leaveis passed; with--leaveit notes on each backlog item that the task stays on this machine. It then uploads and releases the lease.backupandcheckhandle periodic backup:armregisters 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,diffandinflightreport the lease, the last upload and local state.idle --minutes Nis the EC2 idle probe.riprendiis the laptop-driven return:consegnaon EC2 over SSM, thenprendihere, then stop the instance.fm-handoff.sh gate, a bounded (FM_HANDOFF_TIMEOUT) lease read, and records a refusal instate/.handoff-refused. While that file andconfig/handoff-s3both exist,bin/fm-lock.shrefuses 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.docs/configuration.md("Machine handoff"),docs/scripts.mdandAGENTS.md. Addstests/fm-handoff.test.sh, which uses a stubbedawsCLI backed by a local-directory fake S3, and registers it in thesession-bootstrapfamily inbin/fm-test-run.sh.🤖 Generated with Claude Code
Risk Assessment
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--leaverecording, 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)
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-consegnaandbackuponly check that the lease reads asours, which compares machine and nonce. They never check thatstate/.handoff-heldhas status=held, so a home whereprendiclaimed the lease but its download failed (status=claimed, data/ still stale) can runaws s3 sync --deleteof that stale data/ over the bucket's latest upload. A concrete path: the laptop runs consegna. EC2 boots and runsprendi, 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 runsconsegna. The lease readsours, soupload consegnareplaces the laptop's latest data/ in the bucket with EC2's stale copy. When the laptop next runsprendi, 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: inaction_consegnaandaction_backup, requireheld_field status = heldbefore uploading. For aclaimedhome, consegna should release the lease without uploading, or refuse and point toprendi.bin/fm-session-start.sh:632- The lock stage relies onfm-handoff.sh gatehaving writtenstate/.handoff-refusedbefore it exits non-zero, but some failures exit before any verdict is written. The top-levelpositive_intchecks calldie_usage(exit 2) beforeaction_gateruns, for example when FM_HANDOFF_TIMEOUT=0 or a non-numeric FM_HANDOFF_BACKUP_INTERVAL is set in the environment. A failedwrite_refusedin the final branch also returns 1 with no file. In those cases session-start throws the gate output away (it is only printed on&&), andfm-lock.shfinds 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,gatecan 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- Inaction_check,load_config 2>/dev/null || report_once ...can never reach itsreport_once.load_configreports errors throughdie, which callsexit 1in 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, asaction_gatealready does.bin/fm-handoff.sh:880-idleusesfm_supervision_status, which counts everystate/*.meta, persistentkind=secondmaterecords included.inflight_ids, whichconsegnaandinflightuse, 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 runsconsegnaand 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 withinflight_idsinidle.bin/fm-handoff.sh:689-prendi --forcerecords the forced takeover (FORCED takeover by ... from ...) only on the download path. When the lease is foreign but the bucket has nolast-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: whenprior_holderis set, log the forced line in the seed branch as well.bin/fm-handoff.sh:985-riprendirunsconsegnaon EC2 over SSM before it checks for unuploaded local data/ changes. If the localprendithen 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 locallocal_changescheck before the SSM consegna would avoid the half-done state.bin/fm-handoff.sh:858-checkcaps 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.shrefusal on ec2, consegna refused and then--leave, prendi on ec2, the laptop gate offering riprendi andprendi --force,checkuploading a backlog change,idle --minutes 120, riprendi refused over local changes, thenriprendi --replace-local. It then inspected the lease,data/handoff-log.md,state/handoff-backupsand the recordedec2 stop-instancescall. Transcript saved to the evidence directory.✅ **Document** - passed
✅ No issues found.
✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.